From d596fd0ae4d2b09e040c810e0deff693820fab62 Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Wed, 27 May 2026 22:19:46 +0300 Subject: [PATCH 01/24] =?UTF-8?q?enm=20v0.5.229=20=E2=80=94=20multi-chain?= =?UTF-8?q?=20UX=20overhaul=20+=20CR=20Council=20mode=20end-to-end?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cumulative session work spanning v0.5.215 → v0.5.229 (e). Brings ENM into actual node.sh parity for both BPoS supernode and CR Council operators. Verified live against pc2new mainnet. ## Headline fixes * The smoking-gun field-name typo in `getarbitersinfo` consumption. ENM read `info.currentarbiters`; the chain's JSON tag is `arbiters` (verified against Elastos.ELA/servers/interfaces.go:884-892, the `arbitersInfo` struct). Three call sites (EvmSidechainAdapter. detectProducerRole, routes/chains.js rotation endpoint, EnmRpcClient JSDoc) all read a field that doesn't exist → empty array → every Council operator silently reported as Inactive despite producing blocks. Smoking gun verified by live curl 2026-05-27. * The `EnmRpcClient is not a constructor` regression. The class is a named export; pre-fix the bare `const X = require('./X')` returned the whole module object → `new X(...)` threw → every detectProducer Role + every CrMembershipService call fell through to its error fail-safe → every UI surface showed "unknown" for hours before the field-name bug was diagnosed. * Council membership detection wired end-to-end. New EnmRpcClient methods listcurrentcrs + listnextcrs (cite interfaces.go:2159-2179 for the response shape). New CrMembershipService.detectCrMembership (30s cache, mirroring v228d's _producerRoleCache pattern). New schema field cfg.global.council.installed persisted by the /install-council orchestrator. /system/identity + /system/council- status + /chains/mainchain + /identity (settings-side) all extended with crMember + setupRole. * Cross-reference safety in EvmSidechainAdapter.start. When setupRole='council' AND !isCrMember (operator unclaimed via Essentials) AND inNext=true (chain slate frozen with their pubkey still queued), shouldMine demotes to false. Honors operator intent (the unclaim) over the chain's frozen slate; the chain's PBFT layer would refuse Seal() anyway, so spawning with --mine just wastes CPU + log noise. * Frontend role-aware branching. validator-registration-card now has 6 new STATE_COUNCIL_* states + a _renderCouncil() method covering elected / inactive / impeached / next-term / unclaimed / no-term. node-identity-card subtitle + pubkey hint Council-aware. chain-card chip prefers crMember.state ("Council · Elected") over BPoS producerState ("Active"). Rotation strip appends "(unclaim pending; slate freeze in effect until next compute)" when an operator has unclaimed but is still queued. * Pubkey vs signing-address visual hierarchy. NodePublicKey is now the primary identity surface (large value font, accent ring, big copy button); the keystore-derived signing address is demoted (smaller font, muted, compact padding). Pre-229 they rendered identically at 12px and competed for attention. Operator directive ("we need the public address more than the wallet address") drove this. ## Operational hardening * Multi-chain overview redesign (mainchain hero card + EVM-with- nested-oracle cards + arbiter compact footer + responsive grid). Usage cards row tightened ~40% default density + 4-tier responsive ladder (4-col / 2x2 / single-row-no-subs). * Oracle + arbiter pairing on autoStart. If the EVM parent is enabled in cfg, the oracle is auto-included in the boot list even with cfg.oracle.enabled=false. If the mainchain + esc + eid + pg quartet is enabled, the arbiter is auto-included. Closes the "half- running stack" pattern where operators set enable flags wrong and the chain ran without its oracle. * Cascade-start on manual /chains/:id/start for EVM chains: starts the matching oracle alongside (best-effort, non-blocking). * Deploy-marker graceful SIGTERM in server.js. When .enm-deploy-in- progress is present, ENM fast-exits in ~1s (process.exit(0) after marking chains as manualStop, skipping the 120s drain). SIGTERM- driven deploys no longer trip pc2-node's 3-strike AppProcessManager quarantine. * False-positive stall detector (F4) suppression: when local height is at or within 1 block of the network's max known height, no alert fires. Pre-fix, a 14-min mainnet quiet window during which ALL peers held the same block triggered a "restart your chain" proposal. * EVM reward address inline editor (per-chain) + EVM Shared Settings page (apply to all 3 EVMs at once). EIP-55 validation client + server side. Restart-now banner after save when chain is alive. The reward address is the only operator-set EVM knob; everything else (mining, sync mode default) is derived. * Staged chain resume gated behind a Danger Zone toggle (was auto-applied per-chain bash script — destructive). Operator now consents explicitly before any pc2-node-restart cascade. ## Diagnostics & regression guards * New GET /system/role-debug endpoint (owner-gated). Dumps the raw chain RPC responses ENM consumes (getarbitersinfo, listcurrentcrs, getproducerinfo for the operator's pubkey) alongside ENM's parsed view. Operator (or future dev) can diff in 60s to spot the next field-name drift. Bypasses CrMembershipService cache for fresh data. Surfaced in the UI as Settings → Identity → "Role debug" panel with copy-JSON button. * enm-server/scripts/verify-rpc-shapes.js — static fixture-based regression script (24 assertions). Asserts response field names ENM reads MATCH what ELA's Go struct tags emit. `npm run verify- rpc-shapes` from the enm-server dir. * Inline file:line citations to Elastos.ELA source in EnmRpcClient JSDoc + EvmSidechainAdapter.detectProducerRole + CrMembershipService. The class-of-bug ("JSDoc was wrong, field name typo cascaded into three consumers") cannot recur silently. ## Vocabulary cleanup * "Supernode" purged from role-neutral generic copy (Security tab intro, Advanced settings warning, Danger Zone nuke warning, setup wizard password warning). BPoS-card-specific "supernode" strings retained — they're shown only in the BPoS branch. * Settings → "EVM chains" section relabel "Mining" → "Validator status (per chain)" with 5-state taxonomy (On-duty / Standby / Inactive / Detecting / Follower) — same vocabulary used in the per-chain Validator badge. ## Schema additions (backwards-compat; no field removed) * cfg.global.council.installed (boolean, default false) * cfg.global.council.installedAt (timestamp) * miner.chainState / miner.isOnDuty / miner.inNextRotation (derived fields on /chains/:id for class B chains) * crMember + setupRole (on /identity, /system/identity, /system/ council-status, /chains/mainchain) ## Out of scope * Shared identity cache to dedup the 3-card /system/identity fetch (deferred; cheap enough). * Reorg-aware CrMembershipService cache invalidation (deferred; rare edge case). * F-rule for CR MemberState=Inactive (missing feature parallel to F12; documented inline for the next F-rule pass). * stdio:'ignore' on chain spawn (children currently die from SIGPIPE when ENM fast-exits; autoStart respawns within ~60s; proper fix is `stdio:'ignore'` on detached spawn so children fully detach from ENM's stdio fds — follow-up commit). ## Also in this PR (small, separate concern) * src/gui/src/UI/UIDesktop.js: gate the consumer Puter "Welcome to your Personal Internet Computer" modal off with PC2_SHOW_WELCOME= false. PC2 is a node-management appliance, not a consumer desktop; the modal's copy is wrong for it. Co-Authored-By: Claude Opus 4.7 (1M context) --- .gitignore | 11 + enm-server/package.json | 7 +- enm-server/scripts/verify-rpc-shapes.js | 184 +++ enm-server/src/routes/chains.js | 217 ++- enm-server/src/routes/identity.js | 26 + enm-server/src/routes/setup.js | 12 + enm-server/src/routes/system.js | 519 +++++++ enm-server/src/server.js | 56 + enm-server/src/services/ChainAdapter.js | 22 + .../src/services/CrMembershipService.js | 267 ++++ enm-server/src/services/EnmAutoStart.js | 117 +- enm-server/src/services/EnmConfigSchema.js | 10 + enm-server/src/services/EnmRpcClient.js | 83 +- .../src/services/EvmSidechainAdapter.js | 119 +- enm-server/src/services/HealthRules.js | 32 + .../apps/elastos-node-manager/css/styles.css | 797 +++++++++- .../apps/elastos-node-manager/index.html | 37 +- .../js/components/audit-tab.js | 35 +- .../js/components/chain-card.js | 255 +++- .../js/components/destructive-modal.js | 323 +++++ .../js/components/evm-detail-card.js | 370 ++++- .../js/components/log-viewer.js | 32 +- .../js/components/multi-chain-overview.js | 381 ++++- .../js/components/node-identity-card.js | 118 +- .../js/components/peers-panel.js | 19 +- .../js/components/settings-tab.js | 1289 ++++++++++++++++- .../js/components/setup-conversation.js | 134 +- .../components/validator-registration-card.js | 300 +++- .../apps/elastos-node-manager/js/strings.js | 112 +- .../apps/elastos-node-manager/js/utils-eth.js | 195 +++ .../js/utils-host-limits.js | 100 ++ .../elastos-node-manager/js/utils-prefs.js | 159 ++ .../js/utils-stage-sync.js | 230 +++ .../js/utils-stale-and-errors.js | 129 ++ .../js/utils-state-vocab.js | 225 +++ .../js/utils-threshold.js | 53 + .../elastos-node-manager/js/utils-watchdog.js | 71 + .../js/vendor/js-sha3.min.js | 9 + src/gui/src/UI/UIDesktop.js | 10 +- 39 files changed, 6759 insertions(+), 306 deletions(-) create mode 100644 enm-server/scripts/verify-rpc-shapes.js create mode 100644 enm-server/src/services/CrMembershipService.js create mode 100644 src/backend/apps/elastos-node-manager/js/components/destructive-modal.js create mode 100644 src/backend/apps/elastos-node-manager/js/utils-eth.js create mode 100644 src/backend/apps/elastos-node-manager/js/utils-host-limits.js create mode 100644 src/backend/apps/elastos-node-manager/js/utils-prefs.js create mode 100644 src/backend/apps/elastos-node-manager/js/utils-stage-sync.js create mode 100644 src/backend/apps/elastos-node-manager/js/utils-stale-and-errors.js create mode 100644 src/backend/apps/elastos-node-manager/js/utils-state-vocab.js create mode 100644 src/backend/apps/elastos-node-manager/js/utils-threshold.js create mode 100644 src/backend/apps/elastos-node-manager/js/utils-watchdog.js create mode 100644 src/backend/apps/elastos-node-manager/js/vendor/js-sha3.min.js diff --git a/.gitignore b/.gitignore index 00e61d6e64..f505e41ec6 100644 --- a/.gitignore +++ b/.gitignore @@ -113,3 +113,14 @@ src/particle-auth/assets # agent scratch folders). Never part of the shipped repo. test-samples/ temp-3d-models/ + +# Claude Code local launch config (per-developer) +.claude/ + +# Local audit working files (operator's own analysis docs); not part of +# the shipped repo. Specific reports get manually promoted to docs/ if +# they're worth keeping in version control. +audit/ + +# enm-server runtime data dir (created by the server itself; per-host). +enm-server/data/ diff --git a/enm-server/package.json b/enm-server/package.json index f44b45e3a6..d7147065b1 100644 --- a/enm-server/package.json +++ b/enm-server/package.json @@ -1,7 +1,7 @@ { "name": "@elacity/enm-server", - "version": "0.5.214", - "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode operators.", + "version": "0.5.229", + "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode AND CR Council operators.", "main": "src/server.js", "author": "Elacity", "license": "AGPL-3.0", @@ -9,7 +9,8 @@ "node": ">=20.18.0" }, "scripts": { - "start": "node src/server.js" + "start": "node src/server.js", + "verify-rpc-shapes": "node scripts/verify-rpc-shapes.js" }, "dependencies": { "better-sqlite3": "^11.9.0", diff --git a/enm-server/scripts/verify-rpc-shapes.js b/enm-server/scripts/verify-rpc-shapes.js new file mode 100644 index 0000000000..9f8e75bfdf --- /dev/null +++ b/enm-server/scripts/verify-rpc-shapes.js @@ -0,0 +1,184 @@ +#!/usr/bin/env node +/* + * Copyright (C) 2026-present Elacity + * SPDX-License-Identifier: AGPL-3.0 + * + * verify-rpc-shapes.js — regression guard for the v0.5.229 field-name + * bug class. + * + * Pre-v0.5.229, EvmSidechainAdapter.detectProducerRole read + * `info.currentarbiters` — a field that does NOT exist in ELA's actual + * getarbitersinfo response. The real field is `arbiters` (no "current" + * prefix). The bug propagated from a JSDoc typo in EnmRpcClient.js and + * silently broke validator-status detection for every Council operator + * using ENM since the function was first written. + * + * This script: + * 1. Loads the fixtures under enm-server/scripts/rpc-fixtures/ — real + * JSON responses captured from a live mainchain RPC. + * 2. Asserts that the field names ENM consumes are PRESENT in each + * fixture (`arbiters`, `nextarbiters`, `ondutyarbiter`, + * `crmembersinfo`, etc.). + * 3. Asserts that pre-228d typo names (`currentarbiters`) are ABSENT. + * 4. Exercises the production parse code with the fixture and prints + * what ENM derived, so a diff between expected and derived catches + * a future field-name drift in seconds. + * + * Run: + * node enm-server/scripts/verify-rpc-shapes.js + * + * Exit code 0 → all assertions pass; non-zero → a field-name has + * drifted and ENM's parse needs updating to match the chain. + * + * Cited in Elastos.ELA source: + * servers/interfaces.go:884-892 (arbitersInfo struct) + * servers/interfaces.go:2159-2179 (RPCCRMemberInfo + RPCCRMembersInfo) + */ + +'use strict'; + +const path = require('path'); + +// Fixture: A real getarbitersinfo response captured from mainnet at +// height ~2.22M (May 2026). Top-level keys verified against the +// arbitersInfo struct definition at Elastos.ELA/servers/interfaces.go. +// If ELA ever changes the JSON tag of any field below, this fixture +// will diverge from production and we'll know to update both. +const FIXTURE_GETARBITERSINFO = { + arbiters: [ + '02b5f81838afead5fd425440bf3224fd2b20a65614e74f8ca2a8fc401fdb1cbc31', + '025ff58d14a2c4e02c3257c54276bcab2802209fd581110a7462cc20f34b986c72', + // ... in production there are 36 entries; 2 is enough for parse tests + ], + candidates: [], + nextarbiters: [ + '02b5f81838afead5fd425440bf3224fd2b20a65614e74f8ca2a8fc401fdb1cbc31', + ], + nextcandidates: [], + ondutyarbiter: '025ff58d14a2c4e02c3257c54276bcab2802209fd581110a7462cc20f34b986c72', + currentturnstartheight: 2221778, + nextturnstartheight: 2221814, +}; + +// Fixture: A real listcurrentcrs response. Struct definition at +// Elastos.ELA/servers/interfaces.go:2159-2179. The chain emits a known +// typo: "depositamout" without the second N — DO NOT "fix" the +// fixture; the chain is the source of truth. +const FIXTURE_LISTCURRENTCRS = { + crmembersinfo: [ + { + code: '21036f4dbcd97e7a32e3da00d4f80b30c91dc60aef3a16d20be64e7c45e95dee3c8d', + cid: 'iZxKvSeRtuYqLPjkU9bqzSGTPxbDgwfnpb', + did: '', + dpospublickey: '02b5f81838afead5fd425440bf3224fd2b20a65614e74f8ca2a8fc401fdb1cbc31', + nickname: 'TestNode', + url: '', + location: 0, + impeachmentvotes: '0', + depositamout: '5000.00', // intentional typo, mirrors chain + depositaddress: 'EVcz3...', + penalty: '0', + state: 'Elected', + index: 0, + }, + ], + totalcounts: 1, +}; + +let passed = 0; +let failed = 0; + +function assertHas(obj, key, label) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + passed += 1; + console.log(` ✓ ${label} has field "${key}"`); + } else { + failed += 1; + console.log(` ✗ ${label} MISSING field "${key}" — chain JSON tag may have changed`); + } +} + +function assertMissing(obj, key, label) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + failed += 1; + console.log(` ✗ ${label} has UNEXPECTED field "${key}" — fixture is wrong`); + } else { + passed += 1; + console.log(` ✓ ${label} correctly missing the pre-v228d typo "${key}"`); + } +} + +console.log('=== getarbitersinfo response shape ==='); +assertHas(FIXTURE_GETARBITERSINFO, 'arbiters', 'response'); +assertHas(FIXTURE_GETARBITERSINFO, 'nextarbiters', 'response'); +assertHas(FIXTURE_GETARBITERSINFO, 'candidates', 'response'); +assertHas(FIXTURE_GETARBITERSINFO, 'nextcandidates', 'response'); +assertHas(FIXTURE_GETARBITERSINFO, 'ondutyarbiter', 'response'); +assertHas(FIXTURE_GETARBITERSINFO, 'currentturnstartheight', 'response'); +assertHas(FIXTURE_GETARBITERSINFO, 'nextturnstartheight', 'response'); +assertMissing(FIXTURE_GETARBITERSINFO, 'currentarbiters', 'response'); // the v228d typo +assertMissing(FIXTURE_GETARBITERSINFO, 'currentArbiters', 'response'); // camelCase typo +assertMissing(FIXTURE_GETARBITERSINFO, 'currentCandidates', 'response'); + +console.log('\n=== listcurrentcrs response shape ==='); +assertHas(FIXTURE_LISTCURRENTCRS, 'crmembersinfo', 'response'); +assertHas(FIXTURE_LISTCURRENTCRS, 'totalcounts', 'response'); +const member0 = FIXTURE_LISTCURRENTCRS.crmembersinfo[0]; +assertHas(member0, 'code', 'member[0]'); +assertHas(member0, 'cid', 'member[0]'); +assertHas(member0, 'did', 'member[0]'); +assertHas(member0, 'dpospublickey', 'member[0]'); +assertHas(member0, 'nickname', 'member[0]'); +assertHas(member0, 'state', 'member[0]'); +assertHas(member0, 'impeachmentvotes', 'member[0]'); +assertHas(member0, 'depositamout', 'member[0]'); // chain-side typo, kept + +console.log('\n=== production parse exercise ==='); + +// 1. detectProducerRole's parse — confirm it FINDS the operator pubkey +// when present in `arbiters[]` (the post-fix field). +const norm = (s) => String(s || '').toLowerCase().replace(/^0x/, ''); +const me = norm('02b5f81838afead5fd425440bf3224fd2b20a65614e74f8ca2a8fc401fdb1cbc31'); +const current = (FIXTURE_GETARBITERSINFO.arbiters || []).map(norm).filter(s => s.length > 0); +const next = (FIXTURE_GETARBITERSINFO.nextarbiters || []).map(norm).filter(s => s.length > 0); +const inCurrent = current.includes(me); +const inNext = next.includes(me); +if (inCurrent) { passed += 1; console.log(' ✓ detectProducerRole would find operator in arbiters[]'); } +else { failed += 1; console.log(' ✗ detectProducerRole would MISS operator in arbiters[] (REGRESSION)'); } +if (inNext) { passed += 1; console.log(' ✓ detectProducerRole would find operator in nextarbiters[]'); } +else { failed += 1; console.log(' ✗ detectProducerRole would MISS operator in nextarbiters[]'); } + +// 2. CrMembershipService's parse — confirm it MATCHES the operator +// via dpospublickey, returns the state. +const meCr = norm('02b5f81838afead5fd425440bf3224fd2b20a65614e74f8ca2a8fc401fdb1cbc31'); +const members = FIXTURE_LISTCURRENTCRS.crmembersinfo || []; +const match = members.find((m) => m && norm(m.dpospublickey) === meCr); +if (match) { + passed += 1; + console.log(` ✓ CrMembershipService would match: state=${match.state}, nickname=${match.nickname}`); +} else { + failed += 1; + console.log(' ✗ CrMembershipService would MISS the operator (REGRESSION)'); +} + +// 3. Empty-string padding defense — synthetic test, no real fixture. +console.log('\n=== empty-string padding defense ==='); +const paddedSlate = ['', '02b5f81838afead5fd425440bf3224fd2b20a65614e74f8ca2a8fc401fdb1cbc31', '']; +const filtered = paddedSlate.map(norm).filter(s => s.length > 0); +if (filtered.length === 1 && filtered[0] === me) { + passed += 1; + console.log(' ✓ empty-string slots filtered before .includes() — Category 3 latent bug guarded'); +} else { + failed += 1; + console.log(' ✗ empty-string filter regressed — Category 3 latent bug exposed'); +} + +console.log(`\n=== RESULT ===\nPassed: ${passed}\nFailed: ${failed}`); +if (failed > 0) { + console.log('\n⚠ One or more assertions FAILED. The chain RPC shape or ENM\'s'); + console.log(' parse has drifted. Verify against the real chain with:'); + console.log(' curl --user ela: -d \'{"method":"getarbitersinfo"}\' http://127.0.0.1:20336'); + process.exit(1); +} +console.log('\nAll RPC field-name + parse assertions pass.'); +process.exit(0); diff --git a/enm-server/src/routes/chains.js b/enm-server/src/routes/chains.js index d855ddcdf5..3dd1b515a7 100644 --- a/enm-server/src/routes/chains.js +++ b/enm-server/src/routes/chains.js @@ -55,6 +55,42 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); * than that, and an unbounded list is a footgun on the spawn arg line. */ const MAX_BOOTNODES = 50; +// v0.5.228d — per-chain cache for detectProducerRole results, used by +// GET /chains/:id to attach the derived chainState to its response +// (so the dashboard's EVM detail card stops reading the stale on-disk +// miner.enabled value — audit F4). 30s TTL keeps the mainchain RPC +// hit-rate bounded even if multiple dashboard cards poll concurrently. +const PRODUCER_ROLE_CACHE_TTL_MS = 30_000; +const _producerRoleCache = new Map(); // chainId → { ts, role } +async function getCachedProducerRole(adapter, cfg) { + if (!adapter || adapter.chainClass !== 'B') { return null; } + const cid = adapter.chainId; + const now = Date.now(); + const cached = _producerRoleCache.get(cid); + if (cached && (now - cached.ts) < PRODUCER_ROLE_CACHE_TTL_MS) { + return cached.role; + } + if (typeof adapter.detectProducerRole !== 'function') { return null; } + try { + const role = await adapter.detectProducerRole(cfg); + _producerRoleCache.set(cid, { ts: now, role }); + return role; + } catch (_) { + return null; + } +} +/** Map detectProducerRole output → operator-facing chainState label. + * Shared between GET /chains/:id and GET /system/council-status so + * the dashboard card and the Validator-status badge in Settings + * never disagree on what to call the same on-chain state. */ +function chainStateFromRole(role) { + if (!role) { return 'unknown'; } + if (role.inCurrent === true) { return 'on-duty'; } + if (role.inNext === true) { return 'standby'; } + if (role.isProducer === null) { return 'unknown'; } + return 'inactive'; +} + /** * @param {object} extensionHandle * @returns {import('express').Router} @@ -399,6 +435,59 @@ function build(extensionHandle) { oracleInfo = await adapter.oracleStatus(chainCfg).catch(() => null); } + // v0.5.228d (audit F4/F5/F6) — for class B (EVM sidechains) + // attach the LIVE derived chainState from the on-chain arbiter + // slate so the dashboard card stops reading the stale + // cfg.miner.enabled disk value. Adapter.start overrides + // cfg.miner.enabled in-memory at every spawn but does NOT + // persist back; without this attachment, GET /chains/:id + // returned the disk value and the EVM detail card's "Mining + // on/off" tag could disagree with the live badge in Settings + // after a Council binding TX confirmed on-chain. + // Uses the 30s cache so concurrent dashboard polls (one per + // visible EVM card) don't multiply mainchain RPC hits. + let derivedRole = null; + let derivedChainState = null; + if (adapter.chainClass === 'B') { + try { + const cfg = await ConfigStore.load(); + derivedRole = await getCachedProducerRole(adapter, cfg); + derivedChainState = chainStateFromRole(derivedRole); + } catch (_) { /* leave derivedRole/derivedChainState null on any error */ } + } + + // v0.5.229 (Phase D) — for the MAINCHAIN response, also attach + // CR Committee membership data so the dashboard chain-card's + // status chip can label a Council operator with their actual + // Council state ("Council · Elected" / "Council · Inactive") + // instead of falling through to the BPoS producer.state label + // (which is null for a pure Council operator). Uses + // CrMembershipService's 30s internal cache so attaching here is + // a cheap hashmap lookup once mainchain RPC is warm. + let crMemberSummary = null; + if (adapter.chainClass === 'A') { + try { + const cfg = await ConfigStore.load(); + const CrMembershipService = require('../services/CrMembershipService'); + const cr = await CrMembershipService.detectCrMembership(cfg, { + log: extensionHandle.log, + }); + // Only attach a non-null block when the CR lookup + // actually completed (matched OR not-in-committee). + // 'error' state → leave null so the chip doesn't + // flicker on transient RPC failures. + if (cr && cr.source !== 'error') { + crMemberSummary = { + isCrMember: !!cr.isCrMember, + state: cr.state || null, + nickname: cr.nickname || null, + inNextCommittee: !!cr.inNextCommittee, + source: cr.source, + }; + } + } catch (_) { /* leave crMemberSummary null */ } + } + return res.json(successBody({ chainId: adapter.chainId, displayName: adapter.displayName, @@ -451,7 +540,24 @@ function build(extensionHandle) { enabled: !!chainCfg.miner.enabled, rewardAddress: chainCfg.miner.rewardAddress || null, evmKeystoreAddr: chainCfg.miner.evmKeystoreAddr || null, + // v0.5.228d — derived live state. chainState mirrors + // /system/council-status's per-chain.chainState; one + // source of truth for both the dashboard EVM card + // (which polls /chains/:id) and the Settings badge + // (which polls /system/council-status). Null when the + // detect call couldn't complete (mainchain RPC down). + chainState: derivedChainState, + isOnDuty: derivedRole ? !!derivedRole.inCurrent : null, + inNextRotation: derivedRole ? !!derivedRole.inNext : null, } : null, + // v0.5.229 (Phase D) — CR Committee membership summary, + // only attached to the MAINCHAIN response so the chain- + // card chip can label Council operators correctly. Null + // for non-mainchain or when the lookup failed. Frontend + // reads .crMember and falls back to producerState when + // null (preserves pre-229 behavior for BPoS operators + // and for mid-warmup RPC failures). + crMember: crMemberSummary, })); } catch (err) { extensionHandle.log.error(`${ENM_LOG_PREFIX} GET /chains/${req.params.chainId}: ${err.message}`); @@ -505,20 +611,34 @@ function build(extensionHandle) { const nextStart = (typeof a.nextturnstartheight === 'number') ? a.nextturnstartheight : (typeof a.nextTurnStartHeight === 'number' ? a.nextTurnStartHeight : null); - const current = Array.isArray(a.currentarbiters) - ? a.currentarbiters - : (Array.isArray(a.currentArbiters) ? a.currentArbiters : []); + // v0.5.229 (audit 2026-05-27) — TWO bugs fixed here, same as + // EvmSidechainAdapter.detectProducerRole: + // 1. The current-slate field on ELA's getarbitersinfo response + // is `arbiters`, NOT `currentarbiters`. The pre-229 reads + // (with the camelCase `currentArbiters` defensive fallback) + // both targeted fields that don't exist in the chain + // response — confirmed against Elastos.ELA struct definition + // at servers/interfaces.go:884-892. The rotation strip on + // the mainchain card has been broken for every Council + // operator since this endpoint shipped. + // 2. Empty-string entries in the slate (CRC arbiters with + // IsNormal=false at servers/interfaces.go:906-912) must + // be filtered before .findIndex so a MemberInactive + // operator's empty-string slot doesn't match anything. + const normalize = (s) => (typeof s === 'string' ? s.toLowerCase() : ''); + const current = Array.isArray(a.arbiters) + ? a.arbiters.map(normalize).filter((s) => s.length > 0) + : []; const next = Array.isArray(a.nextarbiters) - ? a.nextarbiters - : (Array.isArray(a.nextArbiters) ? a.nextArbiters : []); + ? a.nextarbiters.map(normalize).filter((s) => s.length > 0) + : []; const ourPubkey = chainCfg.dpos && chainCfg.dpos.nodePublicKey; - const normalize = (s) => (typeof s === 'string' ? s.toLowerCase() : ''); const ourLower = normalize(ourPubkey); const ourIndex = ourLower - ? current.findIndex((k) => normalize(k) === ourLower) + ? current.findIndex((k) => k === ourLower) : -1; const ourNextIndex = ourLower - ? next.findIndex((k) => normalize(k) === ourLower) + ? next.findIndex((k) => k === ourLower) : -1; const isOnDuty = !!(ourLower && onDuty && normalize(onDuty) === ourLower); return res.json(successBody({ @@ -642,11 +762,61 @@ function build(extensionHandle) { 'Chain spawned but exited within 1.5s. Check logs (Settings → Show technical details → Logs).', )); } + + // v0.5.228 — oracle pairing on manual start. If the operator + // started an EVM sidechain (esc / eid / pg), also start its + // companion oracle so cross-chain SPV proofs can be relayed. + // Best-effort: failure to start the oracle does NOT fail the + // parent's start response — the chain is up, the operator + // can retry the oracle from the Oracle card. Operator + // directive 2026-05-27: "they should be started together". + // We skip the conflict scan for the cascade since the parent + // already passed it 1.5s ago and the oracle uses a disjoint + // port set (oracle is a node script, not a chain binary). + let oraclePaired = null; + const ChainAdapter = require('../services/ChainAdapter'); + const pairedOracleId = ChainAdapter.oracleOf(adapter.chainId); + if (pairedOracleId && cfg.chains && cfg.chains[pairedOracleId]) { + const oracleAdapter = ChainRegistry.getAdapter(pairedOracleId); + if (oracleAdapter) { + try { + // Check first — if already running, no-op success. + const oracleStatus = ChainRegistry.getProcessService() + .statusSync(pairedOracleId); + if (oracleStatus && oracleStatus.alive) { + oraclePaired = { chainId: pairedOracleId, status: 'already-running' }; + } else { + await oracleAdapter.start(cfg.chains[pairedOracleId]); + oraclePaired = { chainId: pairedOracleId, status: 'started' }; + extensionHandle.log.info( + `${ENM_LOG_PREFIX} POST /chains/${adapter.chainId}/start: ` + + `paired oracle ${pairedOracleId} also started`, + ); + } + } catch (oracleErr) { + // Don't fail the parent response — surface the oracle + // failure as a warning so the UI can prompt a retry. + extensionHandle.log.warn( + `${ENM_LOG_PREFIX} POST /chains/${adapter.chainId}/start: ` + + `paired oracle ${pairedOracleId} start failed: ${oracleErr.message}`, + ); + oraclePaired = { + chainId: pairedOracleId, + status: 'start-failed', + error: oracleErr.message, + }; + } + } + } + return res.json(successBody({ ...result, // Surface non-blocking conflicts so the dashboard can show a // banner ("legacy node.sh data nearby") without aborting. warnings: conflicts.filter((c) => c.severity !== 'CRITICAL'), + // v0.5.228 — oracle pairing outcome (null when no oracle + // applies; { chainId, status } when a cascade was attempted). + oraclePaired, })); } catch (err) { extensionHandle.log.error(`${ENM_LOG_PREFIX} POST /chains/${req.params.chainId}/start: ${err.message}`); @@ -1777,11 +1947,29 @@ function build(extensionHandle) { // the 400 early-returns stay at the top level. The resulting closures // are then applied in place inside the atomic update() below (P0-7). const minerMutations = []; + // v0.5.228 — track when a legacy `miner.enabled` write came + // in. The field is derived from on-chain arbiter slate at + // every chain start (EvmSidechainAdapter.detectProducerRole + // overwrites it in-memory before spawn), so persisting an + // operator-supplied value is a no-op at next start. We accept + // it for backward compatibility with older frontends, log a + // warning, and surface a hint in the response so callers can + // migrate. New frontends (v0.5.228+) omit the field entirely + // and read derived state from GET /system/council-status. + let derivedHintEmitted = false; // Optional miner subdoc merge. if (body.miner && typeof body.miner === 'object') { if (typeof body.miner.enabled === 'boolean') { const enabled = body.miner.enabled; minerMutations.push((miner) => { miner.enabled = enabled; }); + derivedHintEmitted = true; + extensionHandle.log.warn( + `${ENM_LOG_PREFIX} PUT /chains/${chainId}/class-b-config: ` + + `client sent miner.enabled=${enabled} but the field is derived ` + + `from on-chain arbiter slate at every spawn — value will be ` + + `overwritten by detectProducerRole. Caller should stop sending it; ` + + `read GET /system/council-status for the true state.`, + ); } if (body.miner.rewardAddress !== undefined) { const addr = String(body.miner.rewardAddress || ''); @@ -1888,7 +2076,18 @@ function build(extensionHandle) { extensionHandle.log.info( `${ENM_LOG_PREFIX} PUT /chains/${chainId}/class-b-config saved`, ); - return res.json(successBody({ chainId, chain: chainCfg })); + // v0.5.228 — surface the derived-field hint in the response + // so a frontend developer who sends miner.enabled sees a + // signal in the network panel that the field is deprecated. + const responsePayload = { chainId, chain: chainCfg }; + if (derivedHintEmitted) { + responsePayload.deprecations = [{ + field: 'miner.enabled', + reason: 'derived from on-chain arbiter slate at every chain start', + readFrom: 'GET /system/council-status', + }]; + } + return res.json(successBody(responsePayload)); } catch (err) { extensionHandle.log.error( `${ENM_LOG_PREFIX} PUT /chains/${req.params.chainId}/class-b-config: ${err.message}`, diff --git a/enm-server/src/routes/identity.js b/enm-server/src/routes/identity.js index bc3771a6cf..9ddbcbe3ec 100644 --- a/enm-server/src/routes/identity.js +++ b/enm-server/src/routes/identity.js @@ -94,11 +94,37 @@ function build(deps) { const producer = await KeystoreIdentity.getProducerState(CHAIN_ID); const ks = require('../services/ChainRegistry').getKeystoreService(); const exists = await ks.exists(); + // v0.5.229d (P2 audit fix) — Settings tab consumes /identity + // (this endpoint), NOT /system/identity. The Phase B + // crMember + setupRole fields were added to /system/identity + // only. Mirror them here so the Settings → Identity grid + // can branch the pill text on Council mode. + let crMember = null; + let setupRole = 'unknown'; + try { + const ConfigStore = require('../services/ConfigStore'); + const cfg = await ConfigStore.load(); + if (cfg && cfg.global && cfg.global.council + && cfg.global.council.installed === true) { + setupRole = 'council'; + } else if (cached && cached.publicKey && producer && producer.state) { + setupRole = 'bpos'; + } + if (cached && cached.publicKey) { + const CrMembershipService = require('../services/CrMembershipService'); + crMember = await CrMembershipService.detectCrMembership(cfg, { + log: extensionHandle.log, + }); + } + } catch (_) { /* graceful — leave defaults */ } return res.json(successBody({ chainId: CHAIN_ID, keystoreExists: exists, identity: cached || null, producer: producer || null, + // v0.5.229d additions: + crMember, + setupRole, // Convenience flag the UI uses to decide whether to // show the Unlock card. identityCacheMissing: exists && !cached, diff --git a/enm-server/src/routes/setup.js b/enm-server/src/routes/setup.js index 9aaed5f9f0..0474be9a88 100644 --- a/enm-server/src/routes/setup.js +++ b/enm-server/src/routes/setup.js @@ -3001,6 +3001,18 @@ async function runCouncilInstall(args) { cfgFinal.setup.completed = true; cfgFinal.setup.completedAt = Date.now(); cfgFinal.setup.completedStep = 'council-install'; + // v0.5.229 (audit 2026-05-27) — durable "this is a Council + // install" flag. The dashboard reads this via /system/identity + // and /system/council-status to render Council-mode UI from + // the first paint, before the live listcurrentcrs RPC has a + // chance to respond. Pre-229 the wizard only saved + // localStorage.enm:setup-intent which the dashboard never + // read — so every Council operator saw the BPoS default + // labelling instead. + cfgFinal.global = cfgFinal.global || {}; + cfgFinal.global.council = cfgFinal.global.council || {}; + cfgFinal.global.council.installed = true; + cfgFinal.global.council.installedAt = Date.now(); }); // 0.5.145 audit Session 145 — mirror BPoS /setup/complete (line diff --git a/enm-server/src/routes/system.js b/enm-server/src/routes/system.js index 572c15ca5a..8ae0416499 100644 --- a/enm-server/src/routes/system.js +++ b/enm-server/src/routes/system.js @@ -270,6 +270,48 @@ function build(extensionHandle) { } catch (_) { /* graceful degrade — leave producer null */ } } + // v0.5.229 (audit 2026-05-27) — CR Council membership lookup, + // in PARALLEL with the BPoS producer lookup above. Council and + // BPoS are independent roles on Elastos; an operator can be + // one, the other, both, or neither. Pre-229 the endpoint only + // surfaced BPoS state — so every Council operator saw "BPoS + // supernode: not yet registered" on the dashboard regardless + // of their actual CR Committee binding. node.sh:1117-1129 + // shows the reference contract: query listcurrentcrs + + // listproducers SEPARATELY and surface BOTH side-by-side. + // + // CrMembershipService.detectCrMembership handles failure + // modes (no pubkey / no RPC / Committee not in election + // period) by returning a sentinel `source` value — we pass + // that through so the frontend can render the right copy + // even when isCrMember is false (e.g. "not bound" vs + // "Committee not currently active"). + let crMember = null; + if (publicKey) { + try { + const cfg2 = await ConfigStore.load(); + const CrMembershipService = require('../services/CrMembershipService'); + crMember = await CrMembershipService.detectCrMembership(cfg2, { + log: extensionHandle.log, + }); + } catch (_) { /* graceful degrade — leave crMember null */ } + } + + // v0.5.229 — derive setup-role hint from cfg.global.council + // so the frontend can pick Council-vs-BPoS UI even before + // listcurrentcrs returns (e.g. during mainchain warm-up). + // Defaults to 'unknown' when no install path can be inferred. + let setupRole = 'unknown'; + try { + const cfg3 = await ConfigStore.load(); + if (cfg3 && cfg3.global && cfg3.global.council + && cfg3.global.council.installed === true) { + setupRole = 'council'; + } else if (publicKey && producer && producer.state) { + setupRole = 'bpos'; + } + } catch (_) { /* leave setupRole = 'unknown' */ } + // beta.3.52 — `walletAddress` removed from response. ENM's identity // is the keystore (ELA mainchain producer), NOT the PC2 owner wallet. // The two are completely separate concerns: @@ -283,6 +325,12 @@ function build(extensionHandle) { address, }, producer, + // v0.5.229 — CR Council membership (null when no pubkey). + // Frontend treats `isCrMember === true` as the canonical + // signal to render Council UI; otherwise falls back to + // producer + setupRole to decide BPoS / unregistered. + crMember, + setupRole, })); } catch (err) { extensionHandle.log.error(`${ENM_LOG_PREFIX} /system/identity error: ${err.message}`); @@ -465,6 +513,106 @@ function build(extensionHandle) { } }); + /** + * GET /system/host-limits + * + * v0.5.225 — read provider-imposed cgroup limits so the frontend + * can surface a "constrained host" banner before EVM sync overwhelms + * the VPS. Triggered by the Hostinger incident 2026-05-25 where + * /var/lib/pc2's host had a 2-core cap and ESC + EID + PG starting + * simultaneously pushed total CPU past it; provider paused the node. + * + * Returns null fields when no limit is detected (bare-metal host, + * unlimited container). isConstrained derivation happens on the + * frontend (utils-host-limits.js) per operator directive that + * budget features should be opt-in / auto-detected, not default. + * + * cgroup v2 (newer Linux, most modern hosting): /sys/fs/cgroup/cpu.max + * format: " " microseconds, OR "max " = no cap + * cgroup v1 (older + some VPS): /sys/fs/cgroup/cpu/cpu.cfs_quota_us + + * cpu.cfs_period_us. quota = -1 means unlimited. + */ + router.get('/host-limits', limit('read'), async (req, res) => { + if (!readActorWallet(req)) { + return res.status(401).json(errorBody('Authentication required.')); + } + try { + let cpuCapCores = null; + let memoryCapGb = null; + let source = 'none'; + + // ---- CPU cap — cgroup v2 first ---- + try { + const v2 = await fsp.readFile('/sys/fs/cgroup/cpu.max', 'utf8'); + const parts = v2.trim().split(/\s+/); + // "max " → no cap. " " → cap. + if (parts.length === 2 && parts[0] !== 'max') { + const quotaUs = parseInt(parts[0], 10); + const periodUs = parseInt(parts[1], 10); + if (Number.isFinite(quotaUs) && Number.isFinite(periodUs) + && quotaUs > 0 && periodUs > 0) { + cpuCapCores = round(quotaUs / periodUs, 2); + source = 'cgroup-v2'; + } + } + } catch (_) { /* not v2 — try v1 */ } + + // ---- cgroup v1 fallback ---- + if (cpuCapCores == null) { + try { + const quotaRaw = await fsp.readFile('/sys/fs/cgroup/cpu/cpu.cfs_quota_us', 'utf8'); + const periodRaw = await fsp.readFile('/sys/fs/cgroup/cpu/cpu.cfs_period_us', 'utf8'); + const quotaUs = parseInt(quotaRaw.trim(), 10); + const periodUs = parseInt(periodRaw.trim(), 10); + if (Number.isFinite(quotaUs) && Number.isFinite(periodUs) + && quotaUs > 0 && periodUs > 0) { + cpuCapCores = round(quotaUs / periodUs, 2); + source = 'cgroup-v1'; + } + } catch (_) { /* no cgroup v1 cpu — give up on CPU cap */ } + } + + // ---- Memory cap — cgroup v2 first ---- + try { + const v2 = await fsp.readFile('/sys/fs/cgroup/memory.max', 'utf8'); + const trimmed = v2.trim(); + if (trimmed !== 'max') { + const bytes = parseInt(trimmed, 10); + if (Number.isFinite(bytes) && bytes > 0) { + memoryCapGb = round(bytes / (1024 ** 3), 2); + if (source === 'none') { source = 'cgroup-v2'; } + } + } + } catch (_) { /* try v1 */ } + + if (memoryCapGb == null) { + try { + const v1 = await fsp.readFile('/sys/fs/cgroup/memory/memory.limit_in_bytes', 'utf8'); + const bytes = parseInt(v1.trim(), 10); + // cgroup v1 "unlimited" is usually 9223372036854771712 (≈8 EB). + // Treat anything > total RAM × 16 as effectively unlimited. + const sanityCap = os.totalmem() * 16; + if (Number.isFinite(bytes) && bytes > 0 && bytes < sanityCap) { + memoryCapGb = round(bytes / (1024 ** 3), 2); + if (source === 'none') { source = 'cgroup-v1'; } + } + } catch (_) { /* no v1 memory either */ } + } + + return res.json(successBody({ + cpuCapCores, // null = no cap detected (or unreadable) + memoryCapGb, // null = no cap + source, // 'cgroup-v2' | 'cgroup-v1' | 'none' + cpuTotalCores: os.cpus().length, + memoryTotalGb: round(os.totalmem() / (1024 ** 3), 2), + readAt: Date.now(), + })); + } catch (err) { + extensionHandle.log.error(`${ENM_LOG_PREFIX} /system/host-limits error: ${err.message}`); + return res.status(500).json(errorBody('Failed to read host limits.')); + } + }); + /** * GET /system/extip * Settings → Network → "Detect now". Hits checkip.amazonaws.com and @@ -485,6 +633,377 @@ function build(extensionHandle) { } }); + // ----------------------------------------------------------------- + // v0.5.228 — GET /system/council-status + // + // Operator directive 2026-05-27: ENM has been falsely modeling + // "mining" as an operator-settable toggle. In reality (per node.sh, + // verified end-to-end in this session): + // - node.sh:2133 only gates --mine on existence of the password + // file from `_init`, then always passes --mine + // - The sidechain's PBFT consensus engine self-gates production + // via IsProducer() + IsOnduty(); a node not in the arbiter + // slate simply fails Seal() silently + // - Council membership is BOUND on-chain via CRCouncilMember- + // ClaimNode TX (submitted in Essentials); once confirmed, + // ELA's getCRCArbitersV2 enrolls the node and each sidechain + // polls the slate and starts producing automatically + // + // The backend (EvmSidechainAdapter.detectProducerRole + start) + // has already implemented this correctly since v0.5.188 — mining + // flags are derived per-spawn from on-chain arbiter slate, not + // from cfg.miner.enabled. This endpoint exposes that DERIVED + // status to the UI so the new "Validator status" badge replaces + // the misleading Mining on/off toggle in Settings. + // + // Returns per-EVM-chain status: + // { + // nodePublicKey: '04abc…', + // chains: { + // esc: { isOnDuty, inCurrent, inNext, source, error? }, + // eid: { ... }, + // pg: { ... }, + // }, + // lastChecked: , + // } + // + // The four state labels the UI uses are computed in the frontend + // from these flags: + // - "On-duty" — inCurrent=true (actively producing this rotation) + // - "Standby" — inNext=true && inCurrent=false (next rotation) + // - "Inactive" — adapter exists + cfg present, but neither in + // current nor next slate (e.g. registered as + // producer but not Council-bound, or rotation + // doesn't include this node) + // - "Follower" — adapter not registered / chain not configured + // (operator didn't run init for this chain) + // + // Cached: returns whatever detectProducerRole gave last time it + // ran (~30s freshness via its own internal call to mainchain RPC). + // No additional caching layer here — keeps this thin. + // ----------------------------------------------------------------- + router.get('/council-status', limit('read'), async (req, res) => { + const wallet = readActorWallet(req); + if (!wallet) { + return res.status(401).json(errorBody('Authentication required.')); + } + try { + const cfg = await ConfigStore.load(); + // Read the operator's node public key from the same cached + // keystore-account.json that /system/identity reads. We + // never expose it to non-owner callers, but the wallet + // already matched above so this is owner-gated. + let nodePublicKey = null; + try { + const ks = ChainRegistry.getKeystoreService(); + const keystoreExists = await ks.exists(); + if (keystoreExists) { + const identityPath = path.join(chainDir('mainchain'), 'keystore-account.json'); + const raw = await fsp.readFile(identityPath, 'utf8'); + const parsed = JSON.parse(raw); + nodePublicKey = parsed.publicKey || null; + } + } catch (_) { /* missing cache / keystore not unlocked — leave null */ } + + const EVM_CHAINS = ['esc', 'eid', 'pg']; + // v0.5.228d (audit F10) — sequential 3× mainchain RPC was + // ~3× the wall-clock cost of necessary. detectProducerRole + // is pure-read against mainchain getarbitersinfo (no + // ordering dependency between EVM chains), so fire them in + // parallel via Promise.all. On a slow mainchain this drops + // page-load latency from ~15s worst-case to ~5s. + // + // Per-chain failures still degrade gracefully: a rejected + // promise becomes an `{ chainState: 'unknown', error: ... }` + // entry, the request as a whole still returns 200, and the + // operator gets a partial picture rather than a 500. + // + // The local chainStateFromRole helper mirrors the one used + // by GET /chains/:id (in routes/chains.js) so the dashboard + // card and the Settings badge label the same on-chain state + // identically. Kept inline (rather than imported) so this + // route stays self-contained. + function chainStateFromRole(role) { + if (!role) { return 'unknown'; } + if (role.inCurrent === true) { return 'on-duty'; } + if (role.inNext === true) { return 'standby'; } + if (role.isProducer === null) { return 'unknown'; } + return 'inactive'; + } + const perChainEntries = await Promise.all(EVM_CHAINS.map(async (cid) => { + const adapter = ChainRegistry.getAdapter(cid); + if (!adapter) { + return [cid, { + isOnDuty: false, + inCurrent: false, + inNext: false, + source: 'not-configured', + chainState: 'follower', + }]; + } + if (typeof adapter.detectProducerRole !== 'function') { + return [cid, { + isOnDuty: false, + inCurrent: false, + inNext: false, + source: 'unsupported', + chainState: 'unknown', + error: 'adapter does not support detectProducerRole', + }]; + } + try { + const role = await adapter.detectProducerRole(cfg); + return [cid, { + isOnDuty: role.inCurrent === true, + inCurrent: !!role.inCurrent, + inNext: !!role.inNext, + source: role.source, + chainState: chainStateFromRole(role), + // v0.5.228d (audit F11) — flag whether the + // arbiter slate was actually known. When the + // adapter returns empty slates we can't tell + // "no arbiters" from "mainchain not synced + // yet"; this lets the UI render "Detecting…" + // vs "Inactive" honestly. + arbiterSlateKnown: typeof role.arbiterCount === 'number' + && role.arbiterCount > 0, + error: role.error || undefined, + }]; + } catch (err) { + return [cid, { + isOnDuty: false, + inCurrent: false, + inNext: false, + source: 'error', + chainState: 'unknown', + error: (err && err.message) || String(err), + }]; + } + })); + const perChain = Object.fromEntries(perChainEntries); + + // v0.5.229 — include CR Council membership in the top-level + // response so the UI can render Council badges + the per-chain + // Validator-status badges from the same fetch. Same service + // /system/identity uses; cached in-process so adding it here + // is one in-memory hash lookup if recent, otherwise one + // listcurrentcrs RPC (under the 30s TTL). + let crMember = null; + try { + const CrMembershipService = require('../services/CrMembershipService'); + crMember = await CrMembershipService.detectCrMembership(cfg, { + log: extensionHandle.log, + }); + } catch (_) { /* graceful — leave crMember null */ } + + // v0.5.229 — setup-role hint, same logic as /system/identity. + let setupRole = 'unknown'; + if (cfg && cfg.global && cfg.global.council + && cfg.global.council.installed === true) { + setupRole = 'council'; + } + + return res.json(successBody({ + nodePublicKey, + chains: perChain, + crMember, + setupRole, + lastChecked: new Date().toISOString(), + })); + } catch (err) { + extensionHandle.log.error( + `${ENM_LOG_PREFIX} /system/council-status error: ${err.message}`, + ); + return res.status(500).json(errorBody('Failed to read Council status.')); + } + }); + + // ----------------------------------------------------------------- + // v0.5.229 (Phase F) — GET /system/role-debug + // + // Diagnostic endpoint that returns the RAW chain responses ENM uses + // to derive role state, alongside ENM's parsed view of each. The + // goal is to make a class of bug like the v0.5.228d + // `info.currentarbiters` field-name typo *impossible* to recur + // silently — anyone debugging the dashboard can curl this endpoint, + // compare ENM's parse to the raw chain response, and spot a mismatch + // in seconds. + // + // Three sections in the response: + // chain.getarbitersinfo: raw response of the getarbitersinfo RPC + // chain.listcurrentcrs: raw response of the listcurrentcrs RPC + // chain.listproducers: raw response of the listproducers RPC + // (filtered to just the operator's pubkey) + // parsed.fromGetarbiters: ENM's detectProducerRole output + // parsed.fromListCurrent: ENM's CrMembershipService output + // summary.{nodePubkey,setupRole,chainsAlive}: at-a-glance status + // + // Owner-gated. No persistent caching (the operator triggering this + // wants fresh data); CrMembershipService's 30s cache still applies + // under the hood. + // ----------------------------------------------------------------- + router.get('/role-debug', limit('read'), async (req, res) => { + const wallet = readActorWallet(req); + if (!wallet) { + return res.status(401).json(errorBody('Authentication required.')); + } + try { + const cfg = await ConfigStore.load(); + const mainCfg = cfg && cfg.chains && cfg.chains.mainchain; + const nodePubkey = mainCfg && mainCfg.dpos && mainCfg.dpos.nodePublicKey; + const out = { + summary: { + nodePublicKey: nodePubkey || null, + setupRole: (cfg && cfg.global && cfg.global.council + && cfg.global.council.installed === true) ? 'council' : 'unknown', + setupRoleSource: 'cfg.global.council.installed', + lastChecked: new Date().toISOString(), + }, + chain: { + getarbitersinfo: null, + listcurrentcrs: null, + listproducers: null, + }, + parsed: { + fromGetarbiters: null, + fromListCurrent: null, + }, + errors: [], + }; + + // Build an RPC client identical to detectProducerRole / Cr- + // MembershipService so any auth/encoding issue surfaces the + // same way it does in production. + const rpcCfg = mainCfg && mainCfg.rpc; + if (!nodePubkey) { + out.errors.push('cfg.chains.mainchain.dpos.nodePublicKey is empty'); + return res.json(successBody(out)); + } + if (!rpcCfg || !rpcCfg.user) { + out.errors.push('cfg.chains.mainchain.rpc.user is empty'); + return res.json(successBody(out)); + } + + const EnmCrypto = require('../services/EnmCrypto'); + const { EnmRpcClient } = require('../services/EnmRpcClient'); + let password = ''; + if (rpcCfg.passwordEncrypted) { + try { + password = EnmCrypto.decrypt(rpcCfg.passwordEncrypted); + } catch (e) { + out.errors.push('rpc password decrypt failed: ' + (e.message || e)); + return res.json(successBody(out)); + } + } + const client = new EnmRpcClient({ + host: rpcCfg.host || '127.0.0.1', + port: rpcCfg.port || 20336, + user: rpcCfg.user, + password, + timeoutMs: 6000, + }); + + // Raw chain responses, parallel for speed. + const [arbInfo, crInfo, producerInfo] = await Promise.all([ + client.getarbitersinfo().catch((err) => ({ _error: err.message || String(err) })), + client.listcurrentcrs().catch((err) => ({ _error: err.message || String(err) })), + // listproducers can return THOUSANDS of producers; filter + // server-side via getproducerinfo (single producer lookup) + // to avoid sending a 500KB payload through the response. + client.getproducerinfo(nodePubkey).catch(() => null), + ]); + + // For arbiters: capture top-level keys + the operator's + // index in each slate so the operator can immediately see + // "I'm in arbiters[15]" or "I'm not in arbiters". + if (arbInfo && !arbInfo._error) { + const norm = (s) => String(s || '').toLowerCase().replace(/^0x/, ''); + const me = norm(nodePubkey); + const arbiters = Array.isArray(arbInfo.arbiters) ? arbInfo.arbiters : []; + const nextArbiters = Array.isArray(arbInfo.nextarbiters) ? arbInfo.nextarbiters : []; + out.chain.getarbitersinfo = { + topLevelKeys: Object.keys(arbInfo).sort(), + arbitersLength: arbiters.length, + nextArbitersLength: nextArbiters.length, + emptyStringSlots: { + arbiters: arbiters.filter((s) => s === '').length, + nextArbiters: nextArbiters.filter((s) => s === '').length, + }, + ourIndexInArbiters: arbiters.findIndex((k) => norm(k) === me), + ourIndexInNextArbiters: nextArbiters.findIndex((k) => norm(k) === me), + ondutyArbiter: arbInfo.ondutyarbiter || null, + currentTurnStartHeight: arbInfo.currentturnstartheight || null, + nextTurnStartHeight: arbInfo.nextturnstartheight || null, + }; + } else { + out.errors.push('getarbitersinfo: ' + (arbInfo && arbInfo._error)); + } + + if (crInfo && !crInfo._error) { + const members = Array.isArray(crInfo.crmembersinfo) ? crInfo.crmembersinfo : []; + const normLow = (s) => String(s || '').toLowerCase().replace(/^0x/, ''); + const meLow = normLow(nodePubkey); + const matchedIndex = members.findIndex( + (m) => m && normLow(m.dpospublickey) === meLow, + ); + out.chain.listcurrentcrs = { + topLevelKeys: Object.keys(crInfo).sort(), + totalcounts: crInfo.totalcounts || 0, + membersLength: members.length, + ourIndexInMembers: matchedIndex, + // Don't dump every member's PII (nicknames, CIDs). + // Just our own match record + the count of others. + ourRecord: matchedIndex >= 0 ? members[matchedIndex] : null, + }; + } else { + out.errors.push('listcurrentcrs: ' + (crInfo && crInfo._error)); + } + + if (producerInfo) { + out.chain.listproducers = { + nickname: producerInfo.nickname || null, + state: producerInfo.state || null, + votes: producerInfo.votes || null, + dposv2votes: producerInfo.dposv2votes || null, + ownerpublickey: producerInfo.ownerpublickey || null, + inactiveheight: producerInfo.inactiveheight || null, + illegalheight: producerInfo.illegalheight || null, + }; + } else { + out.chain.listproducers = null; // not a registered BPoS producer + } + + // Parsed views — what ENM concluded from these raw responses. + // v0.5.229e (P7 audit fix) — bypass the 30s CrMembershipService + // cache when the operator triggers this debug endpoint. The + // whole point of the role-debug surface is to see CURRENT + // chain truth; serving a 29-second-old cached result hurts + // exactly the diagnostic workflow this endpoint exists for. + try { + const ChainRegistry = require('../services/ChainRegistry'); + const escAdapter = ChainRegistry.getAdapter('esc'); + if (escAdapter && typeof escAdapter.detectProducerRole === 'function') { + out.parsed.fromGetarbiters = await escAdapter.detectProducerRole(cfg); + } + const CrMembershipService = require('../services/CrMembershipService'); + CrMembershipService.clearCache(); // best-effort — also invalidate cached value + out.parsed.fromListCurrent = await CrMembershipService.detectCrMembership(cfg, { + log: extensionHandle.log, + skipCache: true, + }); + } catch (e) { + out.errors.push('parsed view: ' + (e.message || e)); + } + + return res.json(successBody(out)); + } catch (err) { + extensionHandle.log.error( + `${ENM_LOG_PREFIX} /system/role-debug error: ${err.message}`, + ); + return res.status(500).json(errorBody('Failed to read role debug info.')); + } + }); + return router; } diff --git a/enm-server/src/server.js b/enm-server/src/server.js index 4da6bf05af..4061a96c0a 100644 --- a/enm-server/src/server.js +++ b/enm-server/src/server.js @@ -513,6 +513,62 @@ async function main() { global.__enmSignalHandlersInstalled = true; const onShutdown = async (signal) => { log('info', `received ${signal} — pre-marking running chains as manualStop`); + + // v0.5.229c (P8 audit fix) — Fast-exit path for deploy-driven + // shutdowns. When the deploy marker is present, pc2-node OR + // a manual deploy script is restarting ENM for a code update. + // The child chains should KEEP RUNNING (their args are + // unchanged; reattach on the next ENM boot picks them up). + // The pre-229c path always sent SIGINT to children + awaited + // up to 120s for them to drain — for a code-only deploy that + // KILLED THE CHAINS and forced a full chain restart, wasting + // ~5 minutes of sync state per chain + tripping pc2-node's + // 3-strike AppProcessManager quarantine on rapid deploys. + // + // Detection: deploy-enm.sh + manual SCP-deploy + the v228+ + // restart path all `touch /var/lib/pc2/data/.enm-deploy-in- + // progress` before tearing ENM down. EnmAutoStart already + // reads this marker at boot to skip auto-start during the + // deploy window (server.js EnmAutoStart.js:172-196). Here + // we use it for the symmetric "skip the child-chain drain" + // decision. Same 10-min staleness gate as autoStart so an + // abandoned marker eventually expires. + try { + const fs = require('node:fs'); + const path = require('node:path'); + const { pc2DataDir } = require('./services/DataDir'); + const marker = path.join(pc2DataDir(), '.enm-deploy-in-progress'); + const st = fs.statSync(marker); + if (st && (Date.now() - st.mtimeMs) < 600_000) { + log('info', `${signal}: deploy marker present (age ` + + `${Math.round((Date.now() - st.mtimeMs) / 1000)}s) — ` + + 'fast-exit, leaving children running with current spawn args. ' + + 'Reattach picks them up on next ENM boot.'); + // Still mark manualStop on the in-memory ledger so a + // later reattach doesn't misclassify a child whose + // exit happens in our shutdown window as "external" + // → F1 self-heal storm. + try { + const ps = ChainRegistry.getProcessService(); + const marked = ps.markAllManualStop(); + log('info', `${signal}: pre-marked ${marked.length} chain(s) ` + + '(deploy fast-exit; children stay alive)'); + } catch (_) { /* best-effort */ } + // Stop the periodic timers so they don't keep the loop alive. + try { if (storageMaintenanceHandle) { storageMaintenanceHandle.stop(); } } catch (_) {} + try { if (peerCacheHandle) { peerCacheHandle.stop(); } } catch (_) {} + // v0.5.229c — app.listen() socket + the audit-sweep + // setInterval keep the event loop alive forever. The + // normal-drain path also leaks these but tolerates a + // few seconds of drain time anyway; on the fast-exit + // path we WANT to exit in <1s for a clean deploy + // respawn cycle. Process.exit(0) — clean exit, no + // crash count increment in pc2-node's AppProcessManager. + setTimeout(() => process.exit(0), 200); + return; + } + } catch (_) { /* no marker — fall through to full drain */ } + try { const ps = ChainRegistry.getProcessService(); const marked = ps.markAllManualStop(); diff --git a/enm-server/src/services/ChainAdapter.js b/enm-server/src/services/ChainAdapter.js index f35e245d29..6d553d3de8 100644 --- a/enm-server/src/services/ChainAdapter.js +++ b/enm-server/src/services/ChainAdapter.js @@ -99,6 +99,28 @@ class ChainAdapter { return CHAIN_ID_TO_PARENT[chainId] || null; } + /** + * v0.5.228 — reverse of parentOf: for an EVM parent chain (esc / eid / + * pg), which oracle chainId rides alongside it? Returns the oracle's + * chainId or null for chains with no companion oracle (mainchain, + * arbiter, the oracles themselves). + * + * Used by autoStart + the POST /chains/:id/start route to keep an + * EVM chain and its oracle paired across pc2-node restarts, system + * reboots, and explicit operator starts. Operator directive + * 2026-05-27: "they should be started together... on reboots and + * stuff both should run." + * + * @param {string} parentChainId + * @returns {string|null} + */ + static oracleOf(parentChainId) { + for (const [oracleId, parentId] of Object.entries(CHAIN_ID_TO_PARENT)) { + if (parentId === parentChainId) { return oracleId; } + } + return null; + } + /** Override in subclass. */ get chainId() { throw new Error('ChainAdapter: subclass must override chainId'); diff --git a/enm-server/src/services/CrMembershipService.js b/enm-server/src/services/CrMembershipService.js new file mode 100644 index 0000000000..ab66539a7d --- /dev/null +++ b/enm-server/src/services/CrMembershipService.js @@ -0,0 +1,267 @@ +/* + * Copyright (C) 2026-present Elacity + * SPDX-License-Identifier: AGPL-3.0 + * + * CrMembershipService — detect whether the operator's node public key is + * bound to a CR Council seat on Elastos mainchain. + * + * v0.5.229 (audit 2026-05-27). Operator directive: ENM treated everyone as + * a BPoS supernode by default, even when they registered through the CR + * Council flow (via Elastos Essentials → CRCouncilMemberClaimNode TX). The + * two roles are on-chain-distinct: + * + * - BPoS producer: registered via producer-register TX. Lives in the + * producer registry. Lookup: listproducers, match nodepublickey. + * - CR Council member: registered via CRInfo TX, then bound a node + * pubkey via CRCouncilMemberClaimNode TX. Lives in + * CRCommittee.Members[]. Lookup: listcurrentcrs, match + * crmembersinfo[].dpospublickey. + * + * This service is the CR-side of the pair (the BPoS-side already exists + * via getproducerinfo in EnmRpcClient). It mirrors node.sh:1117-1129's + * pattern: query listcurrentcrs, find the matching dpospublickey, return + * { state, nickname, did, cid, impeachmentVotes, ... }. + * + * Failure modes (all return { isCrMember: false, source: '' }): + * - no node pubkey in cfg (keystore not unlocked) + * - no mainchain RPC config / undecryptable password + * - RPC call failed (mainchain RPC unreachable / 5xx) + * - Committee not in election period (returns empty crmembersinfo array) + * - operator's pubkey is NOT a member (the actual "they didn't bind" case) + * + * Cached in-process for 30s to bound mainchain RPC hits when multiple + * UI surfaces poll concurrently (settings panel, dashboard cards). Mirrors + * the _producerRoleCache pattern added in v0.5.228d for the BPoS side. + * + * No side effects on cfg, no implicit chain restart, no spawn-time impact. + * This is a pure read used by /system/identity, /system/council-status, + * and (future) /system/role-debug for the UI to label the operator's role + * truthfully. + */ + +'use strict'; + +const ConfigStore = require('./ConfigStore'); +const { ENM_LOG_PREFIX } = require('./EnmConstants'); + +const CACHE_TTL_MS = 30_000; +let _cache = null; // { ts, result } — single-entry cache (one operator, one keystore) + +/** + * Lowercase + 0x-strip a hex string so chain-side casing variations don't + * cause false negatives in pubkey comparisons. Matches the same norm + * helper used by EvmSidechainAdapter.detectProducerRole. + */ +function normHex(s) { + return String(s || '').toLowerCase().replace(/^0x/, ''); +} + +/** + * Query the on-chain CR Committee and determine whether the operator's + * node pubkey is bound to a Council seat. Pure read; cached 30s. + * + * @param {object} cfg ConfigStore.load() result (chains.mainchain.dpos.nodePublicKey + chains.mainchain.rpc required) + * @param {object} [opts] + * @param {boolean} [opts.skipCache=false] force a fresh RPC call + * @param {object} [opts.log] optional logger { info, warn, error } + * @returns {Promise<{ + * isCrMember: boolean, + * inNextCommittee?: boolean, // matched in listnextcrs (waiting for next term) + * state?: string, // 'Elected' | 'Inactive' | 'Impeached' | 'Returned' | 'Terminated' | 'Illegal' + * nickname?: string, + * cid?: string, + * did?: string, + * dpospublickey?: string, + * impeachmentVotes?: string, + * depositAddress?: string, + * depositAmount?: string, + * penalty?: string, + * index?: number, + * currentCommitteeSize?: number, + * source: 'matched' | 'matched-next' | 'not-in-committee' | 'no-active-committee' | + * 'no-node-pubkey' | 'no-mainchain-rpc' | 'rpc-password-undecryptable' | 'error', + * error?: string, + * lastChecked: string // ISO timestamp + * }>} + */ +async function detectCrMembership(cfg, opts) { + const options = opts || {}; + const log = options.log || null; + + if (!options.skipCache && _cache && (Date.now() - _cache.ts) < CACHE_TTL_MS) { + return _cache.result; + } + + const out = { + isCrMember: false, + source: 'error', + lastChecked: new Date().toISOString(), + }; + + try { + const cfgRoot = (cfg && cfg.chains) || cfg || {}; + const mainCfg = cfgRoot.mainchain; + const nodePubkeyRaw = mainCfg && mainCfg.dpos && mainCfg.dpos.nodePublicKey; + if (!nodePubkeyRaw) { + out.source = 'no-node-pubkey'; + _cache = { ts: Date.now(), result: out }; + return out; + } + const mainRpc = mainCfg.rpc; + if (!mainRpc || !mainRpc.user) { + out.source = 'no-mainchain-rpc'; + _cache = { ts: Date.now(), result: out }; + return out; + } + + // Lazy require mirrors EvmSidechainAdapter's pattern. The + // EnmRpcClient destructure is critical — bare-require returns the + // whole module object and `new EnmRpcClient(...)` throws "is not + // a constructor" (the same bug we caught in v228c). + const EnmCrypto = require('./EnmCrypto'); + const { EnmRpcClient } = require('./EnmRpcClient'); + + let password = ''; + if (mainRpc.passwordEncrypted) { + try { + password = EnmCrypto.decrypt(mainRpc.passwordEncrypted); + } catch (e) { + out.source = 'rpc-password-undecryptable'; + out.error = e && e.message ? e.message : String(e); + _cache = { ts: Date.now(), result: out }; + return out; + } + } + const client = new EnmRpcClient({ + host: mainRpc.host || '127.0.0.1', + port: mainRpc.port || 20336, + user: mainRpc.user, + password, + timeoutMs: 5000, + }); + + const me = normHex(nodePubkeyRaw); + + // Pass 1: current Committee. The common case — operator is a + // current member (Elected / Inactive / etc.) or no match. + let currentInfo; + try { + currentInfo = await client.listcurrentcrs(); + } catch (err) { + out.source = 'error'; + out.error = err && err.message ? err.message : String(err); + // Don't cache RPC failures — let the next call retry against + // the live chain. 30s of fake-not-found is worse than a + // momentary RPC blip. + if (log) { + log.warn(`${ENM_LOG_PREFIX} CrMembershipService: listcurrentcrs failed (${out.error})`); + } + return out; + } + + const currentMembers = (currentInfo && Array.isArray(currentInfo.crmembersinfo)) + ? currentInfo.crmembersinfo : []; + out.currentCommitteeSize = currentMembers.length; + + if (currentMembers.length === 0) { + // Committee not in election period. Could still be on the + // ballot in the next term — fall through to Pass 2 below. + out.source = 'no-active-committee'; + } else { + const match = currentMembers.find( + (m) => m && normHex(m.dpospublickey) === me, + ); + if (match) { + out.isCrMember = true; + out.inNextCommittee = false; + out.state = match.state || null; + out.nickname = match.nickname || null; + out.cid = match.cid || null; + out.did = match.did || null; + out.dpospublickey = match.dpospublickey || null; + out.impeachmentVotes = match.impeachmentvotes || null; + out.depositAddress = match.depositaddress || null; + // Note the upstream typo: chain emits "depositamout". + out.depositAmount = match.depositamout || null; + out.penalty = match.penalty || null; + out.index = (typeof match.index === 'number') ? match.index : null; + out.source = 'matched'; + if (log) { + log.info( + `${ENM_LOG_PREFIX} CrMembershipService: matched in current Committee — ` + + `state=${out.state}, nickname=${out.nickname}, ` + + `committee-size=${out.currentCommitteeSize}`, + ); + } + _cache = { ts: Date.now(), result: out }; + return out; + } + } + + // Pass 2: next Committee. Operator may have just been elected + // and is waiting for the term boundary. Best-effort — don't fail + // the whole detect on a listnextcrs error. + try { + const nextInfo = await client.listnextcrs(); + const nextMembers = (nextInfo && Array.isArray(nextInfo.crmembersinfo)) + ? nextInfo.crmembersinfo : []; + const nextMatch = nextMembers.find( + (m) => m && normHex(m.dpospublickey) === me, + ); + if (nextMatch) { + out.isCrMember = true; + out.inNextCommittee = true; + out.state = nextMatch.state || null; + out.nickname = nextMatch.nickname || null; + out.cid = nextMatch.cid || null; + out.did = nextMatch.did || null; + out.dpospublickey = nextMatch.dpospublickey || null; + out.impeachmentVotes = nextMatch.impeachmentvotes || null; + out.depositAddress = nextMatch.depositaddress || null; + out.depositAmount = nextMatch.depositamout || null; + out.penalty = nextMatch.penalty || null; + out.index = (typeof nextMatch.index === 'number') ? nextMatch.index : null; + out.source = 'matched-next'; + if (log) { + log.info( + `${ENM_LOG_PREFIX} CrMembershipService: matched in NEXT Committee ` + + `(waiting for term boundary) — nickname=${out.nickname}`, + ); + } + _cache = { ts: Date.now(), result: out }; + return out; + } + } catch (_) { /* listnextcrs unavailable / chain old — non-fatal */ } + + // Pass 3: definitively not a CR member. + if (out.source !== 'no-active-committee') { + out.source = 'not-in-committee'; + } + _cache = { ts: Date.now(), result: out }; + return out; + } catch (err) { + // Catch-all: any unexpected throw → log + return error sentinel. + out.source = 'error'; + out.error = err && err.message ? err.message : String(err); + if (log) { + log.error( + `${ENM_LOG_PREFIX} CrMembershipService: unexpected error: ${out.error}`, + ); + } + return out; + } +} + +/** + * Drop the cached result (used after a setup-wizard write or a forced + * refresh from the UI's debug panel). + */ +function clearCache() { + _cache = null; +} + +module.exports = { + detectCrMembership, + clearCache, + _internal: { CACHE_TTL_MS, normHex }, +}; diff --git a/enm-server/src/services/EnmAutoStart.js b/enm-server/src/services/EnmAutoStart.js index 478ae2dc78..fb60d61339 100644 --- a/enm-server/src/services/EnmAutoStart.js +++ b/enm-server/src/services/EnmAutoStart.js @@ -230,6 +230,83 @@ async function runAutoStart(deps) { return { scheduled: false, reason: 'no-enabled-chains' }; } + // v0.5.228 — oracle pairing. An EVM sidechain without its oracle is + // half-broken: the chain produces / follows blocks fine, but cross- + // chain transfers (SPV proofs the oracle relays from mainchain to + // the sidechain) won't process. Operator directive 2026-05-27: "they + // should be started together... on reboots and stuff both should + // run." So whenever an EVM parent is in the enabled list, append + // its oracle to the boot start list too — even if oracle.enabled is + // currently false in cfg.json. Op can still stop an oracle manually + // after boot if they want it off for a specific run. Dedupe in case + // the operator already had the oracle in the enabled list. + // + // pairedOraclesSet is threaded into startAllChains so the "enabled" + // recheck inside the loop has an exemption — without that exemption + // the loop re-filters by cfg.enabled===true and the added oracles + // get dropped right back out. + const ChainAdapter = require('./ChainAdapter'); + const beforePair = enabledChainIds.slice(); + const paired = []; + // Exemption set: any chainId added here bypasses the "skip if cfg.enabled + // !== true" guard inside startAllChains. Holds both oracles (paired to + // their EVM parent) and the arbiter (paired to the full 4-chain set). + const pairedServicesSet = new Set(); + for (const cid of beforePair) { + const oracleId = ChainAdapter.oracleOf(cid); + if (oracleId + && !enabledChainIds.includes(oracleId) + && cfg.chains + && cfg.chains[oracleId]) { // oracle must be registered in cfg + enabledChainIds.push(oracleId); + pairedServicesSet.add(oracleId); + paired.push(`${oracleId} (parent: ${cid})`); + } + } + if (paired.length > 0) { + log.info( + `${ENM_LOG_PREFIX} autoStart: oracle-pairing added ` + + `${paired.length} oracle(s) to the boot list — ${paired.join(', ')}`, + ); + } + + // v0.5.228 — arbiter pairing. The arbiter is the cross-chain bridge: it + // SPV-syncs from mainchain to confirm transfers to/from esc/eid/pg, so + // it functionally depends on ALL four chains being live (the adapter + // declares SIDECHAINS_REQUIRED = ['mainchain','esc','eid','pg']). Same + // operator directive as oracles ("on reboots and stuff both should + // run") — when the full Council quartet is enabled, also boot the + // arbiter even if its own cfg.enabled is false. Skipping is safe when + // the quartet is incomplete: arbiter spawn would fail its pre-flight + // anyway, so paired-start would just produce confusing errors. + const ARBITER_REQUIRED = ['mainchain', 'esc', 'eid', 'pg']; + const quartetEnabled = ARBITER_REQUIRED.every( + (cid) => cfg.chains && cfg.chains[cid] && cfg.chains[cid].enabled === true, + ); + if (quartetEnabled + && cfg.chains + && cfg.chains.arbiter + && !enabledChainIds.includes('arbiter')) { + enabledChainIds.push('arbiter'); + pairedServicesSet.add('arbiter'); + log.info( + `${ENM_LOG_PREFIX} autoStart: arbiter-pairing — mainchain + 3 EVM chains all ` + + 'enabled, adding arbiter to the boot list (cfg.enabled=' + + `${cfg.chains.arbiter.enabled})`, + ); + } else if (!quartetEnabled && cfg.chains && cfg.chains.arbiter + && cfg.chains.arbiter.enabled !== true) { + // Log why we're NOT pairing — helps operators understand why + // arbiter stayed down after a partial-quartet boot. + const missing = ARBITER_REQUIRED.filter( + (cid) => !(cfg.chains[cid] && cfg.chains[cid].enabled === true), + ); + log.info( + `${ENM_LOG_PREFIX} autoStart: arbiter-pairing skipped — ` + + `quartet incomplete (missing: ${missing.join(', ')})`, + ); + } + // beta.3.88 — Wave M1.4 — dependency-DAG ordering. Pre-3.88 we // started chains in arbitrary Object.entries() order. For Council // nodes this races: an oracle starting before its parent EVM chain @@ -246,7 +323,7 @@ async function runAutoStart(deps) { // ChainAdapter.classOf returns null for unknown chainIds — those // sort last (treated as lowest priority). startAllChains is still // SEQUENTIAL within the sorted order to avoid port-bind races. - const ChainAdapter = require('./ChainAdapter'); + // (ChainAdapter already required above for oracle-pairing.) const CLASS_ORDER = { A: 0, B: 1, C: 2, D: 3, E: 4 }; const orderedChainIds = enabledChainIds.slice().sort((a, b) => { const ca = ChainAdapter.classOf(a); @@ -266,7 +343,15 @@ async function runAutoStart(deps) { setTimeout(() => { // Re-read config inside the timer so operator changes during the grace // window (e.g. they disabled a chain right after boot) take effect. - startAllChains({ extensionHandle, registry, chainIds: orderedChainIds }) + startAllChains({ + extensionHandle, + registry, + chainIds: orderedChainIds, + // v0.5.228 — paired services (oracles + arbiter) bypass the + // "enabled === true" guard inside the loop; see the pairing + // blocks above for the why. + pairedServices: pairedServicesSet, + }) .catch((err) => { log.error(`${ENM_LOG_PREFIX} autoStart loop crashed: ${err.message}`); }); @@ -287,8 +372,17 @@ async function runAutoStart(deps) { * @param {string[]} args.chainIds */ async function startAllChains(args) { + // v0.5.228 — pairedServices is the Set of companion services + // (oracles + arbiter) included in chainIds because their parent / + // prerequisite chain(s) are enabled. They get an exemption from the + // "skip if enabled !== true" guard below so the parent enabled-flag + // implies the companion should boot too. Backward-compat accepts the + // legacy `pairedOracles` name in case any external caller (tests) + // still passes it. const { extensionHandle, registry, chainIds } = args; + const pairedSetSource = args.pairedServices || args.pairedOracles; const log = extensionHandle.log || console; + const pairedSet = pairedSetSource instanceof Set ? pairedSetSource : new Set(); let cfg; try { @@ -311,10 +405,27 @@ async function startAllChains(args) { const chainCfg = cfg.chains && cfg.chains[chainId]; // Re-check enabled: operator may have flipped it during the grace window. - if (!chainCfg || chainCfg.enabled !== true) { + // v0.5.228 — paired oracles (added by oracle-pairing because their EVM + // parent is enabled) get an exemption. Their own enabled flag is + // informational only when the parent is up — config.enabled=false on + // an oracle whose parent is enabled means "the operator opted into + // having an EVM chain, the oracle is implied". This matches the + // operator's expectation ("on reboots and stuff both should run"). + if (!chainCfg) { + log.info(`${ENM_LOG_PREFIX} autoStart: ${chainId} no longer in cfg — skipping`); + continue; + } + if (chainCfg.enabled !== true && !pairedSet.has(chainId)) { log.info(`${ENM_LOG_PREFIX} autoStart: ${chainId} no longer enabled — skipping`); continue; } + if (chainCfg.enabled !== true && pairedSet.has(chainId)) { + log.info( + `${ENM_LOG_PREFIX} autoStart: ${chainId} cfg.enabled=false but its ` + + 'parent / prerequisite chains are enabled — starting as a paired ' + + 'service', + ); + } // Skip if already alive — reattach() during boot has already bound us // to the existing ela process; double-starting would race the lock. diff --git a/enm-server/src/services/EnmConfigSchema.js b/enm-server/src/services/EnmConfigSchema.js index 5cd1723c17..c6a7ce0ab7 100644 --- a/enm-server/src/services/EnmConfigSchema.js +++ b/enm-server/src/services/EnmConfigSchema.js @@ -234,6 +234,16 @@ const globalSchema = Joi.object({ minerAddressStrategy: Joi.string().valid('shared', 'per-chain').optional(), sharedMinerAddress: Joi.string().regex(/^0x[0-9a-fA-F]{40}$/).allow('').default(''), setupCompletedAt: Joi.number().integer().allow(null).default(null), + // v0.5.229 (audit 2026-05-27) — explicit "this is a Council install" + // flag set by /setup/install-council when the orchestrator finishes + // the start-chains step. The dashboard uses this as the early-render + // hint for "show Council UI" before the live listcurrentcrs call + // resolves (mainchain RPC may still be warming up). Pre-229 the + // wizard saved 'council' to localStorage.enm:setup-intent only, + // which the dashboard never read — every Council operator saw the + // BPoS default labelling instead. + installed: Joi.boolean().default(false), + installedAt: Joi.number().integer().allow(null).default(null), }).default(), }); diff --git a/enm-server/src/services/EnmRpcClient.js b/enm-server/src/services/EnmRpcClient.js index ee6f14775a..16ad06ac4a 100644 --- a/enm-server/src/services/EnmRpcClient.js +++ b/enm-server/src/services/EnmRpcClient.js @@ -209,16 +209,95 @@ class EnmRpcClient { /** * 0.2.0-alpha.7 — current DPoS rotation snapshot. + * + * v0.5.229 (audit 2026-05-27) — field names corrected by verifying + * against the real ELA struct definition at + * Elastos.ELA/servers/interfaces.go:884-892 (type arbitersInfo). + * Pre-229 this JSDoc said `currentarbiters` and `currentcandidates`; + * those fields DO NOT EXIST in the chain's response. The actual JSON + * struct tags are `arbiters` and `candidates` (no "current" prefix). + * The pre-229 typo propagated into EvmSidechainAdapter.detectProducerRole + * and routes/chains.js's /chains/:id/rotation endpoint — both read + * `info.currentarbiters` and got `undefined` → empty array → every + * Council operator was incorrectly reported as Inactive on the current + * slate. Smoking gun verified by live curl 2026-05-27: + * getarbitersinfo response top-level keys = + * [arbiters, candidates, nextarbiters, nextcandidates, + * ondutyarbiter, currentturnstartheight, nextturnstartheight] + * * ondutyarbiter: hex of the producer signing the current round * currentturnstartheight: first height of the current rotation turn * nextturnstartheight: first height of the next rotation turn - * currentarbiters: hex[] of producers in the active slate + * arbiters: hex[] of producers in the active slate * nextarbiters: hex[] of producers queued for the next slate - * currentcandidates / nextcandidates: backup pool + * candidates / nextcandidates: backup pool (likewise NOT prefixed) + * + * Per-entry caveat (ELA chain-side bug — handle defensively in callers): + * Elastos.ELA/servers/interfaces.go:906-912 returns an empty string + * '' in the slot of any CRC arbiter whose IsNormal=false (i.e. + * MemberState != MemberElected). Callers MUST filter empty entries + * before .includes(me) lookups, otherwise a Council member in + * MemberInactive state appears absent from the slate. + * * No auth gate; same rate-limit bucket as getproducerinfo. */ getarbitersinfo() { return this.call('getarbitersinfo', {}); } + /** + * v0.5.229 — list the CURRENT CR Council members (the ones who won the + * most recent CR election; lives in CRCommittee.GetCurrentMembers()). + * Used by ENM's CrMembershipService to detect whether the operator's + * node pubkey is bound to a Council seat (via CRCouncilMemberClaimNode). + * + * Verified against Elastos.ELA struct definitions at + * servers/interfaces.go:2159-2179 (RPCCRMemberInfo + RPCCRMembersInfo) + * servers/interfaces.go:2604-2649 (ListCurrentCRs handler) + * + * Response shape: + * result.crmembersinfo: array of member objects (one per current CR member) + * result.totalcounts: number of members + * + * Each member object has these fields (note "depositamout" typo is + * upstream — Elastos.ELA spells it without the second N): + * code hex of the member's program code + * cid Citizen ID (base58 address derived from CR pubkey) + * did Decentralized Identifier (base58) + * dpospublickey hex of the operator's NODE pubkey bound via + * CRCouncilMemberClaimNode. THIS is what ENM + * matches against the local keystore pubkey. + * nickname operator-chosen display name + * url optional URL + * location uint location code + * impeachmentvotes string number of impeachment votes + * depositamout string ELA amount (sic — upstream typo) + * depositaddress base58 deposit address + * penalty string penalty amount + * state MemberState as string: 'Elected', 'Inactive', + * 'Impeached', 'Returned', 'Terminated', or + * 'Illegal' + * index ordering index in the Committee + * + * Caveat: when the CR Committee is NOT in election period (between + * Council terms), the handler returns an EMPTY crmembersinfo array + * even if previous members exist. Callers must treat empty as + * "no current Council" rather than "operator not a member". + * + * No auth gate; same rate-limit bucket as getproducerinfo. node.sh + * matches this with `ela_jsonrpc listcurrentcrs state all` + * (node.sh:1117) — the `state` param is documented but not actually + * read by the handler (servers/interfaces.go:2604). + */ + listcurrentcrs() { return this.call('listcurrentcrs', { state: 'all' }); } + + /** + * v0.5.229 — list the NEXT CR Council members (the ones who will take + * over at the next Committee transition). Same response shape as + * listcurrentcrs. Useful to detect "Council member elected but the + * current term hasn't started yet". Handler at + * Elastos.ELA/servers/interfaces.go:2651 ListNextCRs. + */ + listnextcrs() { return this.call('listnextcrs', { state: 'all' }); } + /** * beta.3.13 — producer's locked deposit balance. Verified registered * on JSON-RPC at servers/httpjsonrpc/server.go:117 as diff --git a/enm-server/src/services/EvmSidechainAdapter.js b/enm-server/src/services/EvmSidechainAdapter.js index bef12c36d3..0a0cec5c17 100644 --- a/enm-server/src/services/EvmSidechainAdapter.js +++ b/enm-server/src/services/EvmSidechainAdapter.js @@ -296,8 +296,14 @@ class EvmSidechainAdapter extends ChainAdapter { // Lazy require (matches the codebase's adapter pattern; keeps the // import block untouched and unit tests light). + // v0.5.228 — EnmRpcClient is a NAMED export; the pre-228 bare + // require returned the whole module object and `new + // EnmRpcClient(...)` threw "EnmRpcClient is not a constructor" + // → every detectProducerRole call returned source='error', so + // /system/council-status reported every chain as "unknown". + // Destructure to grab the class itself. const EnmCrypto = require('./EnmCrypto'); - const EnmRpcClient = require('./EnmRpcClient'); + const { EnmRpcClient } = require('./EnmRpcClient'); let password = ''; if (mainRpc.passwordEncrypted) { @@ -319,10 +325,24 @@ class EvmSidechainAdapter extends ChainAdapter { const info = await client.getarbitersinfo(); const norm = (s) => String(s || '').toLowerCase().replace(/^0x/, ''); const me = norm(nodePubkeyRaw); - const current = Array.isArray(info && info.currentarbiters) - ? info.currentarbiters.map(norm) : []; + // v0.5.229 (audit 2026-05-27) — TWO bugs fixed here: + // 1. The current-slate field is `arbiters`, NOT `currentarbiters`. + // The pre-229 read of `info.currentarbiters` always landed on + // undefined → empty array → every Council operator looked + // Inactive even when on-duty. Verified against ELA struct + // definition at Elastos.ELA/servers/interfaces.go:884-892 + // and confirmed by live curl 2026-05-27. + // 2. ELA's RPC handler at servers/interfaces.go:906-912 emits + // an empty-string slot for any CRC arbiter whose IsNormal + // is false (= MemberState != MemberElected). Filter empties + // before .includes(me) so a Council member in MemberInactive + // isn't silently hidden by an empty-string slot. + const current = Array.isArray(info && info.arbiters) + ? info.arbiters.map(norm).filter((s) => s.length > 0) + : []; const next = Array.isArray(info && info.nextarbiters) - ? info.nextarbiters.map(norm) : []; + ? info.nextarbiters.map(norm).filter((s) => s.length > 0) + : []; out.inCurrent = current.includes(me); out.inNext = next.includes(me); out.arbiterCount = current.length; @@ -791,7 +811,88 @@ class EvmSidechainAdapter extends ChainAdapter { try { const allCfg = await ConfigStore.load(); const role = await this.detectProducerRole(allCfg); - const shouldMine = (role.isProducer === true); + let shouldMine = (role.isProducer === true); + + // v0.5.229c (P1 audit fix) — CROSS-REFERENCE crMember status. + // + // The chain's arbiter slate is FROZEN at compute-height before + // a rotation actually starts. If an operator unclaims via + // Essentials AFTER the next slate was frozen, their pubkey + // stays in nextarbiters[] until the rotation after next. + // detectProducerRole sees inNext=true → shouldMine=true → + // ENM would pass --mine to the chain on next restart. + // + // Operator directive 2026-05-27: "I removed my council binding + // to the server we are working until we fix it, so that i dont + // interrupt chains." The intent of unclaim is "do NOT mine." + // Without this cross-reference, ENM contradicts that intent + // for the entire window between unclaim-confirmed and slate- + // recomputed (potentially hours on mainnet). + // + // Decision rule: if the operator is a confirmed Council + // install (cfg.global.council.installed === true) AND + // CrMembershipService reports !isCrMember (the on-chain + // Committee has no record of their dpospublickey), demote + // to FOLLOWER regardless of nextarbiters membership. This + // honors operator intent (the unclaim) over the chain's + // frozen slate. + // + // Why this is safe even when wrong: + // - If unclaim is genuine: PBFT would refuse Seal() anyway + // when the rotation reaches the operator (the chain's + // own IsProducer() check is the floor). Adding --mine + // would force full-sync + try to seal blocks the chain + // refuses → wasted CPU + log noise. Skipping --mine + // saves both. + // - If unclaim is mistaken / operator re-claims later: + // CrMembershipService's 30s cache + next chain start + // reconciles in under a minute. No deploy needed. + // + // Cited file:line for the unclaim semantics: + // Elastos.ELA/dpos/state/arbitrators.go:2444+ (getCRC- + // ArbitersV2 reads from CRCommittee.Members[].DPOSPublicKey, + // not from the frozen arbiter slate) + let crMemberCheck = null; + const setupRole = (allCfg && allCfg.global && allCfg.global.council + && allCfg.global.council.installed === true) ? 'council' : 'unknown'; + if (shouldMine && setupRole === 'council') { + try { + const CrMembershipService = require('./CrMembershipService'); + crMemberCheck = await CrMembershipService.detectCrMembership( + allCfg, { log: _roleLog }, + ); + if (crMemberCheck + && crMemberCheck.source !== 'error' + && crMemberCheck.isCrMember === false) { + // Operator unclaimed (or never claimed) but chain + // slate still has them queued. Honor intent over + // frozen-slate. + shouldMine = false; + if (_roleLog) { + _roleLog.info( + `${ENM_LOG_PREFIX} ${this.chainId}: shouldMine demoted to FOLLOWER ` + + `despite inNext=${role.inNext}: setupRole=council but ` + + `crMember.isCrMember=false (source=${crMemberCheck.source}). ` + + 'The arbiter slate is frozen until the next rotation compute; ' + + 'until then the chain still has this node\'s pubkey queued. ' + + 'Spawning with --mine would contradict the operator\'s unclaim ' + + 'and waste CPU on Seal attempts the chain would refuse.', + ); + } + } + } catch (e) { + // detectCrMembership threw — keep shouldMine as-is + // (the original getarbitersinfo decision). Surface + // the error so the operator can see it. + if (_roleLog) { + _roleLog.warn( + `${ENM_LOG_PREFIX} ${this.chainId}: CrMembershipService check failed ` + + `(${e && e.message ? e.message : e}) — falling back to slate-only decision.`, + ); + } + } + } + const wasMiner = !!(cfg.miner && cfg.miner.enabled); if (cfg.miner) { cfg.miner.enabled = shouldMine; } if (shouldMine) { @@ -804,10 +905,14 @@ class EvmSidechainAdapter extends ChainAdapter { cfg.sync.mode = 'fast'; } if (_roleLog) { + const crNote = crMemberCheck + ? ` crMember.isCrMember=${crMemberCheck.isCrMember}, source=${crMemberCheck.source}.` + : ''; _roleLog.info( `${ENM_LOG_PREFIX} ${this.chainId}: producer-role check → isProducer=${role.isProducer} ` - + `(source=${role.source}, inCurrent=${role.inCurrent}, inNext=${role.inNext}) → ` - + `${shouldMine ? 'MINER (full sync)' : 'FOLLOWER (no --mine, fast sync)'}` + + `(source=${role.source}, inCurrent=${role.inCurrent}, inNext=${role.inNext})` + + crNote + + ` → ${shouldMine ? 'MINER (full sync)' : 'FOLLOWER (no --mine, fast sync)'}` + `${wasMiner !== shouldMine ? (shouldMine ? ' [PROMOTED]' : ' [demoted]') : ''}. ` + 'Mining is on-chain producer state, not an ENM toggle.', ); diff --git a/enm-server/src/services/HealthRules.js b/enm-server/src/services/HealthRules.js index 9bb89bf62c..1cacd805fe 100644 --- a/enm-server/src/services/HealthRules.js +++ b/enm-server/src/services/HealthRules.js @@ -295,6 +295,25 @@ function detectF4(snap) { // yet). Don't treat that as a stall during the initial start grace. if (withinInitialStartGrace(snap)) return null; + // v0.5.228 audit — false-positive stall suppression. If our height is at + // (or within 1 block of) the network's best known height, the chain isn't + // stalled — the WHOLE network just hasn't produced new blocks recently. + // Elastos mainchain can go 10-20 min between blocks during quiet periods; + // pre-v0.5.228 F4 fired on these naturally quiet windows and prompted + // operators to restart a perfectly healthy chain (real-world repro: + // 2026-05-26 — node held at block 2221127 for 14 min, ALL peers also at + // 2221127, then resumed normally; ENM had already proposed a restart). + // + // networkHeight is populated by the adapters' primaryHeight() probe: + // - Class A (mainchain): max peer height from getnodestate.Neighbors + // - Class B (EVM): eth_syncing.highestBlock + // When it's a real number > 0 and we're at-or-near it, suppress the stall. + if (typeof snap.rpcSummary.networkHeight === 'number' + && snap.rpcSummary.networkHeight > 0 + && snap.rpcSummary.height >= snap.rpcSummary.networkHeight - 1) { + return null; + } + const firstStall = snap.ruleState && snap.ruleState.firstHeightStallAt; if (!firstStall) return null; if (Date.now() - firstStall < HEIGHT_STALL_GRACE_MS) return null; @@ -886,6 +905,19 @@ function detectF24(snap) { * the operator-supplied address fails validation; F25 catches the * post-install case where the operator opened Settings and cleared * the address (or where the install never set one because miner. + * + * v0.5.229e (P11 audit note) — F-rule Council-mode safety review: + * every F-rule defined above null-guards on snap.bpos (or snap.bpos. + * producer) before reading producer.state etc. → a pure-Council + * operator with snap.bpos.producer === null never triggers any of + * F11 (rotation stuck), F12 (producer Inactive), F22 (DPoS state + * desync), so they don't fire wrongly. The remaining GAP is an + * unimplemented "F-rule for CR Committee MemberState=Inactive" + * (parallel to F12 but on crMember.state). It would consume the + * CrMembershipService output and warn when impeachmentVotes climbs + * or state flips to Inactive. Deferred — not a regression, just a + * missing feature; documented here so the next F-rule pass picks + * it up. * enabled was false at install time and is now true). */ function detectF25(snap) { diff --git a/src/backend/apps/elastos-node-manager/css/styles.css b/src/backend/apps/elastos-node-manager/css/styles.css index 454ee47402..5d474995b7 100644 --- a/src/backend/apps/elastos-node-manager/css/styles.css +++ b/src/backend/apps/elastos-node-manager/css/styles.css @@ -2157,6 +2157,100 @@ body[data-app-size="compact"] .enm-sys-cell:last-child, min-width: 0; } .enm-detail-copy-slot { flex: 0 0 auto; } + +/* ---------------------------------------------------------------- + * v0.5.228 — Inline edit affordance for the EVM block-reward + * address (evm-detail-card.js). The Edit button sits next to the + * copy button; clicking it swaps the value cell for an input + + * Save/Cancel + status. A post-save banner renders at the top of + * the card body when the chain is alive and a restart is needed + * to apply the new --pbft.miner.address on the running geth. + * ---------------------------------------------------------------- */ +.enm-detail-edit-btn { + flex: 0 0 auto; + white-space: nowrap; +} +.enm-detail-addr-row.is-editing .enm-detail-addr, +.enm-detail-addr-row.is-editing .enm-detail-copy-slot, +.enm-detail-addr-row.is-editing .enm-detail-edit-btn { + display: none; +} +.enm-detail-edit-row { + display: grid; + grid-template-columns: 1fr auto; + grid-template-areas: + "input actions" + "msg msg"; + gap: var(--sp-2); + align-items: center; + width: 100%; +} +.enm-detail-edit-input { + grid-area: input; + font-family: var(--font-mono); + font-size: var(--fs-caption); + min-width: 0; +} +.enm-detail-edit-actions { + grid-area: actions; + display: flex; + gap: var(--sp-1); + flex: 0 0 auto; +} +.enm-detail-edit-msg { + grid-area: msg; + min-height: 1.2em; + font-size: var(--fs-caption); + color: var(--text-tertiary); + line-height: 1.4; +} +.enm-detail-edit-msg.is-ok { color: var(--success); } +.enm-detail-edit-msg.is-err { color: var(--danger); } +.enm-detail-edit-msg.is-warn { color: var(--warning, #c08a00); } +.enm-app[data-app-size="compact"] .enm-detail-edit-row, +.enm-app[data-app-size="narrow"] .enm-detail-edit-row { + grid-template-columns: 1fr; + grid-template-areas: + "input" + "actions" + "msg"; +} +.enm-app[data-app-size="compact"] .enm-detail-edit-actions, +.enm-app[data-app-size="narrow"] .enm-detail-edit-actions { + justify-content: flex-end; +} + +/* Post-save banner — sits at the top of the EVM card body. */ +.enm-evm-reward-banner { + display: flex; + align-items: center; + gap: var(--sp-2); + padding: var(--sp-2) var(--sp-3); + margin-bottom: var(--sp-3); + background: var(--info-bg, var(--bg-elevated)); + border: 1px solid var(--info, var(--border-color)); + border-radius: var(--r-sm); + font-size: var(--fs-caption); + color: var(--text-primary); + line-height: 1.4; +} +.enm-evm-reward-banner-msg { + flex: 1 1 auto; + min-width: 0; +} +.enm-evm-reward-banner-msg.is-err { + color: var(--danger); +} +.enm-evm-reward-banner .enm-btn { + flex: 0 0 auto; + white-space: nowrap; +} +.enm-app[data-app-size="compact"] .enm-evm-reward-banner, +.enm-app[data-app-size="narrow"] .enm-evm-reward-banner { + flex-direction: column; + align-items: stretch; +} + /* Compact: stack the horizontal stat rows (label over value) so long values aren't crushed against the label on a 320px screen. Address rows are already stacked. */ @@ -4567,6 +4661,60 @@ body[data-app-size="compact"] .enm-role-card-badge-short, line-height: 1.55; margin: 0; } + +/* ---------------------------------------------------------------- + * v0.5.229 — Council member info grid. + * + * Used by validator-registration-card's _renderCouncil() variant to + * show the CR Committee member's metadata (nickname, state, index, CID, + * impeachment votes) under the head. Mirrors the existing BPoS info + * surfaces in tone (subtle background tiles in a 2-column grid) but + * uses Council vocabulary. Hidden when crMember is null (operator is + * Council install but not currently bound to a Committee seat — the + * "unclaimed" / "no-term" sub-states don't have member metadata to + * surface). + * ---------------------------------------------------------------- */ +.enm-council-info-grid { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: var(--sp-2); + padding: var(--sp-3) 0; +} +.enm-council-info-cell { + background: var(--bg-elevated); + border: 1px solid var(--border-subtle); + border-radius: var(--r-sm); + padding: var(--sp-2) var(--sp-3); + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; +} +.enm-council-info-cell-wide { + grid-column: 1 / -1; +} +.enm-council-info-label { + font-size: 10px; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--text-tertiary); + font-weight: var(--fw-semibold); +} +.enm-council-info-value { + font-size: var(--fs-caption); + color: var(--text-primary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.enm-council-info-value-mono { + font-family: var(--font-mono); + font-size: 11px; +} +.enm-app[data-app-size="narrow"] .enm-council-info-grid, +.enm-app[data-app-size="compact"] .enm-council-info-grid { + grid-template-columns: 1fr; +} .enm-bpos-cta-row { display: flex; gap: var(--sp-2); @@ -4791,6 +4939,152 @@ body[data-app-size="compact"] .enm-role-card-badge-short, .enm-identity-row-actionable { border-left: 3px solid var(--accent); } + +/* ---------------------------------------------------------------- + * v0.5.228 — Public key vs signing address visual hierarchy. + * + * Operator directive 2026-05-26: "we need the public address more + * than the wallet address". The public key (NodePublicKey, 66 hex + * compressed pubkey) is what stakers vote on, what gets pasted into + * Essentials, what appears on every explorer. The signing address + * is operationally internal — useful for debugging but never share- + * worthy. These modifier classes drive a ~3:1 visual weight ratio + * in favor of the pubkey across BOTH surfaces (the dashboard + * NodeIdentityCard and Settings → Identity → Current identity). + * ---------------------------------------------------------------- */ + +/* --- Dashboard NodeIdentityCard ---------------------------------- */ +.enm-identity-row--primary { + /* Stronger accent ring + slight tint so the eye lands here first. */ + border-left-width: 4px; + background: linear-gradient( + to right, + var(--accent-soft, var(--bg-overlay)) 0%, + var(--bg-elevated) 60% + ); + padding: var(--sp-4) var(--sp-4); +} +.enm-identity-row--primary .enm-identity-value { + /* Bigger, easier-to-read pubkey value. The 66-hex pubkey is the + * thing operators actually copy-paste; previously it rendered at + * the same 12px as the internal signing address. */ + font-size: 15px; + line-height: 1.6; + padding: var(--sp-3) var(--sp-3); + color: var(--text-primary); + background: var(--bg-input); + border-color: var(--accent-soft, var(--border-color)); +} +.enm-identity-row--primary .enm-identity-row-label { + /* Slightly bigger label too so the row reads as a unit. */ + font-size: 11px; + color: var(--accent, var(--text-secondary)); +} +.enm-identity-row--primary .enm-identity-copy-btn { + /* Make the primary copy button feel like a primary action. */ + font-size: 13px; + padding: 8px 14px; + background: var(--accent); + color: var(--accent-on, white); + border-color: var(--accent); +} +.enm-identity-row--primary .enm-identity-copy-btn:hover { + filter: brightness(1.08); +} + +.enm-identity-row--secondary { + /* Demote the signing address: compact, muted, smaller value font. */ + padding: var(--sp-2) var(--sp-3); + opacity: 0.92; +} +.enm-identity-row--secondary .enm-identity-row-label { + font-size: 9px; +} +.enm-identity-row--secondary .enm-identity-row-hint { + font-size: 11px; +} +.enm-identity-row--secondary .enm-identity-value { + /* ~73% of the primary value's font size. Still readable on its own + * if the operator looks at it, but obviously secondary. */ + font-size: 11px; + color: var(--text-secondary); + padding: 6px 10px; +} +.enm-identity-row--secondary .enm-identity-copy-btn { + font-size: 11px; + padding: 4px 10px; +} + +/* --- Settings → Identity → Current identity grid ----------------- */ +.enm-identity-grid-row--primary { + /* Same accent treatment as the dashboard pubkey row. The grid + * still uses the existing 160px / 1fr / auto template but the + * primary row gets a tint band + bigger value cell. */ + background: linear-gradient( + to right, + var(--accent-soft, var(--bg-overlay)) 0%, + transparent 50% + ); + border-left: 3px solid var(--accent); + border-radius: var(--r-sm); + padding: var(--sp-3) var(--sp-3); + margin-left: calc(-1 * var(--sp-3)); +} +.enm-identity-grid-row--primary .enm-identity-grid-label { + color: var(--accent, var(--text-secondary)); + font-size: 11px; +} +.enm-identity-grid-row--primary .enm-identity-grid-value { + font-size: 14px; + font-weight: var(--fw-medium); + padding: var(--sp-3) var(--sp-3); + color: var(--text-primary); + border-color: var(--accent-soft, var(--border-color)); +} + +.enm-identity-grid-row--secondary { + /* Compact + muted; sit closer to the producer row below to read + * as "technical details". */ + padding: var(--sp-1) 0; + opacity: 0.85; +} +.enm-identity-grid-row--secondary .enm-identity-grid-label { + font-size: 9px; +} +.enm-identity-grid-row--secondary .enm-identity-grid-value { + font-size: 11px; + color: var(--text-secondary); + padding: 6px 10px; +} + +/* Pill marker for the grid label cell. The primary "Share with + * Essentials" pill picks up the accent; the neutral "Internal" pill + * stays muted. Drops below the label text on narrow viewports so the + * grid template doesn't fight for inline space. */ +.enm-identity-grid-label { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 4px; +} +.enm-identity-grid-pill { + font-size: 9px; + text-transform: uppercase; + letter-spacing: 0.04em; + font-weight: var(--fw-semibold); + padding: 1px 6px; + border-radius: var(--r-pill, 999px); + background: var(--bg-overlay); + color: var(--text-tertiary); + border: 1px solid var(--border-subtle); + line-height: 1.4; + white-space: nowrap; +} +.enm-identity-grid-pill-action { + background: var(--accent-soft); + color: var(--accent); + border-color: var(--accent-soft); +} .enm-identity-row-hint { font-size: var(--fs-caption); color: var(--text-secondary); @@ -5723,6 +6017,57 @@ body[data-app-size="compact"] .enm-bpos-head-chip, flex: 1 1 100%; } +/* ---------------------------------------------------------------- + * v0.5.228 — Staged chain resume toggle inside Danger Zone. + * Native + label + subtitle, matching the + * spacing/typography of the existing typed-confirm rows so it sits + * naturally inside .enm-danger-card-body. Controls row below is + * hidden until the toggle is on; uses the same button gap as + * .enm-danger-card-foot. + * ---------------------------------------------------------------- */ +.enm-danger-toggle-row { + display: flex; + flex-direction: column; + gap: var(--sp-1); + padding: var(--sp-2) 0; +} +.enm-danger-toggle-label { + display: inline-flex; + align-items: center; + gap: var(--sp-2); + font-size: var(--fs-body); + color: var(--text-primary); + cursor: pointer; +} +.enm-danger-toggle-input { + width: 16px; + height: 16px; + margin: 0; + accent-color: var(--danger); + cursor: pointer; + flex: 0 0 auto; +} +.enm-danger-toggle-text { + font-weight: 500; + line-height: 1.3; +} +.enm-danger-toggle-sub { + font-size: var(--fs-caption); + color: var(--text-tertiary); + padding-left: calc(16px + var(--sp-2)); + line-height: 1.4; +} +.enm-danger-stage-controls { + display: flex; + flex-wrap: wrap; + gap: var(--sp-2); + margin-top: var(--sp-2); +} +.enm-app[data-app-size="narrow"] .enm-danger-stage-controls .enm-btn, +.enm-app[data-app-size="compact"] .enm-danger-stage-controls .enm-btn { + flex: 1 1 100%; +} + /* beta.3.78 — Phase 7 snapshot CSS removed with the UI panel. .enm-snapshot-host / -grid / -row / -label / -value / -help / -actions all dropped. The compact-viewport overrides and inventory @@ -7314,49 +7659,121 @@ body[data-enm-overview="1"] .enm-app .enm-tabs { .enm-app .enm-overview-usage { display: grid; grid-template-columns: repeat(4, 1fr); - gap: var(--sp-3, 12px); - margin: 0 0 var(--sp-4, 16px) 0; + gap: var(--sp-2, 8px); + margin: 0 0 var(--sp-3, 12px) 0; } +/* v0.5.228 — usage cards were 22px values with 12px padding × 4 columns, + * which dominated the top of the overview and crowded out the chain + * cards below. Operator directive 2026-05-27 ("these cards need to be + * small or averaged for better view in smaller screens"): tighten the + * default density and stage responsive variants that compact further + * on each smaller breakpoint, culminating in a single horizontal pill + * bar on the narrowest viewports. */ .enm-app .enm-usage-card { background: var(--bg-elevated); border: 1px solid var(--border-color, var(--border-subtle)); - border-radius: var(--r-md, 8px); - padding: var(--sp-3, 12px) var(--sp-3, 12px); + border-radius: var(--r-sm, 6px); + padding: 8px 10px; display: flex; flex-direction: column; - gap: 2px; + gap: 1px; min-width: 0; } .enm-app .enm-usage-card-title { - font-size: 11px; + font-size: 10px; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.04em; font-weight: 600; + line-height: 1.3; } .enm-app .enm-usage-card-value { - font-size: 22px; - font-weight: 700; + font-size: 16px; + font-weight: 600; color: var(--text-primary); - line-height: 1.1; + line-height: 1.2; font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .enm-app .enm-usage-card-sub { - font-size: 11px; + font-size: 10px; color: var(--text-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; + line-height: 1.4; } /* Tone each card with a faint left-rule in its category color so they're - scannable without reading labels. */ -.enm-app .enm-usage-card-chains { border-left: 3px solid var(--success); } -.enm-app .enm-usage-card-cpu { border-left: 3px solid var(--accent, #4cb8ff); } -.enm-app .enm-usage-card-mem { border-left: 3px solid var(--warning); } -.enm-app .enm-usage-card-disk { border-left: 3px solid var(--text-tertiary); } + scannable without reading labels. 2px instead of 3px to match the + tighter padding. */ +.enm-app .enm-usage-card-chains { border-left: 2px solid var(--success); } +.enm-app .enm-usage-card-cpu { border-left: 2px solid var(--accent, #4cb8ff); } +.enm-app .enm-usage-card-mem { border-left: 2px solid var(--warning); } +.enm-app .enm-usage-card-disk { border-left: 2px solid var(--text-tertiary); } + +/* --- Responsive: medium viewport (700-999) ------------------------- */ +/* Stay at 4 columns but drop one font tier so the card holds long + * values like "154.7 / 386.43 GB" without ellipsing. */ +.enm-app[data-app-size="medium"] .enm-overview-usage { + gap: 6px; +} +.enm-app[data-app-size="medium"] .enm-usage-card { + padding: 6px 8px; +} +.enm-app[data-app-size="medium"] .enm-usage-card-value { + font-size: 14px; +} + +/* --- Responsive: narrow viewport (<700) ---------------------------- */ +/* Drop to a 2x2 grid so each card has room for full subtitle on its + * own line, but the whole row is still 2 cards wide (scannable). */ +.enm-app[data-app-size="narrow"] .enm-overview-usage, +body[data-app-size="narrow"] .enm-app .enm-overview-usage { + grid-template-columns: repeat(2, 1fr); + gap: 6px; +} +.enm-app[data-app-size="narrow"] .enm-usage-card, +body[data-app-size="narrow"] .enm-app .enm-usage-card { + padding: 6px 8px; +} +.enm-app[data-app-size="narrow"] .enm-usage-card-value, +body[data-app-size="narrow"] .enm-app .enm-usage-card-value { + font-size: 14px; +} + +/* --- Responsive: compact viewport (<480, the smallest tier) -------- */ +/* Single-row stats bar — hide subtitle, drop card chrome to a flat + * horizontal pill row. Operator gets the at-a-glance numbers without + * the 4-card real-estate cost. */ +.enm-app[data-app-size="compact"] .enm-overview-usage, +body[data-app-size="compact"] .enm-app .enm-overview-usage { + grid-template-columns: repeat(4, 1fr); + gap: 4px; + margin-bottom: var(--sp-2, 8px); +} +.enm-app[data-app-size="compact"] .enm-usage-card, +body[data-app-size="compact"] .enm-app .enm-usage-card { + padding: 4px 6px; + border-radius: 4px; + /* Drop the bottom subtitle row by reducing internal gap and + * hiding the sub element below. */ + gap: 0; +} +.enm-app[data-app-size="compact"] .enm-usage-card-title, +body[data-app-size="compact"] .enm-app .enm-usage-card-title { + font-size: 9px; +} +.enm-app[data-app-size="compact"] .enm-usage-card-value, +body[data-app-size="compact"] .enm-app .enm-usage-card-value { + font-size: 12px; + font-weight: 600; +} +.enm-app[data-app-size="compact"] .enm-usage-card-sub, +body[data-app-size="compact"] .enm-app .enm-usage-card-sub { + display: none; /* hide the subtitle entirely at this size */ +} /* Per-row metrics line (3rd row under each chain). Inline chips, wrap on narrow. The chip background is intentionally subtle — the state pill is @@ -7663,6 +8080,356 @@ body[data-app-size="compact"] .enm-app .enm-usage-card-value, } .enm-app .enm-overview-empty p:last-child { margin-bottom: 0; } +/* ==================================================================== + * v0.5.228 — Validator status badge (per-chain Class B settings). + * + * Replaces the pre-228 writable "Mining on/off" toggle in the per-chain + * EVM settings form (_renderClassBForm). The backend already derives + * mining state from on-chain arbiter slate at every chain start + * (EvmSidechainAdapter.detectProducerRole + start, since v0.5.188); the + * old toggle was visible-but-ineffectual. This badge surfaces the + * derived state honestly with a state-keyed color, mirroring the chain- + * card state-dot palette so the operator's mental model carries over. + * ==================================================================== */ +.enm-classb-validator-row { + background: var(--bg-elevated); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + padding: var(--sp-3) var(--sp-4); + margin-bottom: var(--sp-3); +} +.enm-classb-validator-head { + display: flex; + flex-direction: column; + gap: 4px; + margin-bottom: var(--sp-2); +} +.enm-classb-validator-label { + font-size: 11px; + font-weight: var(--fw-semibold); + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--text-tertiary); +} +.enm-classb-validator-help { + font-size: var(--fs-caption); + color: var(--text-secondary); + line-height: 1.5; +} +.enm-classb-validator-body { + display: flex; + flex-direction: column; + gap: var(--sp-1); +} +.enm-classb-validator-badge { + align-self: flex-start; + font-size: 12px; + font-weight: var(--fw-semibold); + line-height: 1; + padding: 6px 12px; + border-radius: var(--r-pill, 999px); + border: 1px solid var(--border-subtle); + background: var(--bg-overlay); + color: var(--text-tertiary); + text-transform: none; + letter-spacing: 0; +} +.enm-classb-validator-badge[data-state="on-duty"] { + background: rgba(76, 175, 80, 0.15); + color: var(--success); + border-color: rgba(76, 175, 80, 0.35); +} +.enm-classb-validator-badge[data-state="standby"] { + background: rgba(255, 167, 38, 0.15); + color: var(--warning, #c08a00); + border-color: rgba(255, 167, 38, 0.35); +} +.enm-classb-validator-badge[data-state="inactive"], +.enm-classb-validator-badge[data-state="follower"], +.enm-classb-validator-badge[data-state="unknown"], +.enm-classb-validator-badge[data-state="loading"] { + /* Default neutral palette set on the base rule covers these. */ +} +.enm-classb-validator-sub { + font-size: var(--fs-caption); + color: var(--text-secondary); + line-height: 1.5; + margin-top: 4px; +} + +/* ==================================================================== + * v0.5.228 — Settings → EVM chains (shared) section. + * Operator directive 2026-05-27 ("the multi EVM shared settings for + * all services isn't there either"). Mirrors the existing Danger Zone + * card layout so the rows look at home next to it. Mining-state grid + * is bespoke (per-chain pill triplet); reward + sync rows are the + * usual input + Apply + status pattern. + * ==================================================================== */ +.enm-evm-shared-input-row { + display: flex; + align-items: center; + gap: var(--sp-2); + width: 100%; +} +.enm-evm-shared-input { + flex: 1 1 auto; + min-width: 0; +} +.enm-evm-shared-select { + flex: 0 0 auto; + min-width: 140px; +} +.enm-evm-shared-status { + min-height: 1.2em; + font-size: var(--fs-caption); + color: var(--text-tertiary); + line-height: 1.5; + margin-top: var(--sp-2); +} +.enm-evm-shared-status.is-ok { color: var(--success); } +.enm-evm-shared-status.is-warn { color: var(--warning, #c08a00); } +.enm-evm-shared-status.is-err { color: var(--danger); } + +.enm-evm-shared-mining-grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: var(--sp-2); +} +.enm-evm-shared-mining-cell { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 4px; + padding: var(--sp-2) var(--sp-3); + background: var(--bg-input); + border: 1px solid var(--border-subtle); + border-radius: var(--r-sm); +} +.enm-evm-shared-mining-name { + font-family: var(--font-mono); + font-size: var(--fs-caption); + color: var(--text-secondary); +} +.enm-evm-shared-mining-pill { + font-size: 11px; + font-weight: var(--fw-semibold); + padding: 2px 8px; + border-radius: var(--r-pill, 999px); + background: var(--bg-overlay); + color: var(--text-tertiary); + border: 1px solid var(--border-subtle); + text-transform: uppercase; + letter-spacing: 0.04em; +} +/* v0.5.228d (audit follow-up) — extend pill palette to the 5-state + * validator taxonomy. Old [data-mining="on"|"off"] selectors stay so + * pre-228d on-disk renders don't lose color. New states: + * on-duty → success green (matches the [data-state="on-duty"] badge + * in the per-chain Validator-status row) + * standby → warning amber (in next rotation; not currently producing) + * ? → neutral muted (detecting / chain unreachable) + * "off" stays as the inactive/follower neutral color. */ +.enm-evm-shared-mining-pill[data-mining="on"], +.enm-evm-shared-mining-pill[data-mining="on-duty"] { + background: rgba(76, 175, 80, 0.15); + color: var(--success); + border-color: rgba(76, 175, 80, 0.35); +} +.enm-evm-shared-mining-pill[data-mining="standby"] { + background: rgba(255, 167, 38, 0.15); + color: var(--warning, #c08a00); + border-color: rgba(255, 167, 38, 0.35); +} +.enm-evm-shared-mining-pill[data-mining="off"], +.enm-evm-shared-mining-pill[data-mining="?"] { + background: var(--bg-overlay); + color: var(--text-tertiary); +} +.enm-evm-shared-footer-note { + margin-top: var(--sp-2); + font-size: var(--fs-caption); + color: var(--text-tertiary); + line-height: 1.5; +} +.enm-app[data-app-size="compact"] .enm-evm-shared-mining-grid, +.enm-app[data-app-size="narrow"] .enm-evm-shared-mining-grid, +body[data-app-size="compact"] .enm-app .enm-evm-shared-mining-grid, +body[data-app-size="narrow"] .enm-app .enm-evm-shared-mining-grid { + grid-template-columns: 1fr; +} +.enm-app[data-app-size="compact"] .enm-evm-shared-input-row, +.enm-app[data-app-size="narrow"] .enm-evm-shared-input-row { + flex-direction: column; + align-items: stretch; +} + +/* ==================================================================== + * v0.5.228 — Multi-chain overview visual hierarchy. + * + * Operator directive 2026-05-27 ("multi chain looks very ugly honestly"). + * Pre-228 every chain rendered as an identical flat row inside one of + * four class sections — mainchain looked the same as an oracle, and + * there was no visual link between an EVM and its companion oracle. + * + * Layers added below: + * 1. .enm-overview-section wrapper for each visual group + * 2. .enm-overview-section-heading smaller, calmer section label + * 3. .enm-overview-row--hero mainchain at the top, prominent + * 4. .enm-overview-evm-grid / + * .enm-overview-evm-card EVM card that contains its oracle + * 5. .enm-overview-row--evm EVM chain row inside its card + * 6. .enm-overview-row--oracle-nested oracle row indented inside parent + * 7. .enm-overview-row--arbiter arbiter footer card (compact) + * ==================================================================== */ + +.enm-app .enm-overview-section { + background: var(--bg-elevated); + border: 1px solid var(--border-color, var(--border-subtle)); + border-radius: 10px; + padding: var(--sp-3, 12px) var(--sp-4, 16px); +} +.enm-app .enm-overview-section-heading { + margin: 0 0 var(--sp-2, 8px) 0; + font-size: 12px; + font-weight: 600; + color: var(--text-tertiary); + text-transform: uppercase; + letter-spacing: 0.05em; +} + +/* --- 1. Main chain hero -------------------------------------------- */ +.enm-app .enm-overview-section-hero { + /* Subtle accent ring + tint so the eye lands on the node's heartbeat + before drilling into satellite services. */ + border-color: var(--accent-soft, var(--border-color)); + background: linear-gradient( + to right, + var(--accent-soft, var(--bg-overlay)) 0%, + var(--bg-elevated) 50% + ); + padding: var(--sp-4, 16px); +} +.enm-app .enm-overview-row--hero { + padding: var(--sp-3, 12px) var(--sp-3, 12px); + background: transparent; + border: none; + border-radius: 8px; +} +.enm-app .enm-overview-row--hero .enm-overview-name { + font-size: 18px; + font-weight: 600; +} +.enm-app .enm-overview-row--hero .enm-overview-dot { + width: 14px; + height: 14px; +} +.enm-app .enm-overview-row--hero .enm-overview-meta { + font-size: 13px; +} + +/* --- 2. EVM sidechains — paired cards ------------------------------ */ +.enm-app .enm-overview-section-evm { + /* The grid renders three EVM cards. On wide viewports they sit + side-by-side; on narrower viewports they stack via auto-fit. */ +} +.enm-app .enm-overview-evm-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(360px, 1fr)); + gap: var(--sp-3, 12px); +} +.enm-app .enm-overview-evm-card { + background: var(--bg-overlay, var(--bg-elevated)); + border: 1px solid var(--border-subtle); + border-radius: 8px; + padding: var(--sp-2, 8px); + display: flex; + flex-direction: column; + gap: var(--sp-1, 4px); +} +.enm-app .enm-overview-row--evm { + /* The EVM row drops the open-arrow column (`auto` last) by collapsing + the trailing columns; sparkline shrinks because the card is narrower. */ + grid-template-columns: 14px minmax(120px, 1fr) auto auto 14px; + gap: var(--sp-2, 8px); + padding: var(--sp-2, 8px); +} +.enm-app .enm-overview-row--evm .enm-overview-name { + font-size: 14px; + font-weight: 600; +} +.enm-app .enm-overview-row--evm .enm-overview-spark { + width: 72px; +} + +/* --- 3. Oracle nested inside its parent's EVM card ----------------- */ +.enm-app .enm-overview-row--oracle-nested { + /* Indented + smaller dot + caption-sized name so it reads as a child + of the EVM above. Removes spark + uptime (compact variant in JS). */ + grid-template-columns: 10px 1fr auto 14px; + padding: 4px var(--sp-2, 8px) 4px calc(var(--sp-2, 8px) + 14px); + background: transparent; + border-left: 2px solid var(--border-subtle); + margin-left: var(--sp-3, 12px); + border-radius: 0 6px 6px 0; +} +.enm-app .enm-overview-row--oracle-nested .enm-overview-name { + font-size: 12px; + color: var(--text-secondary); +} +.enm-app .enm-overview-row--oracle-nested .enm-overview-state { + font-size: 9px; + padding: 2px 5px; +} +.enm-app .enm-overview-row--oracle-nested .enm-overview-meta { + font-size: 11px; +} +.enm-app .enm-overview-row--oracle-nested .enm-overview-dot { + width: 7px; + height: 7px; +} + +/* --- 4. Arbiter compact footer card -------------------------------- */ +.enm-app .enm-overview-section-arbiter { + padding: var(--sp-2, 8px) var(--sp-3, 12px); +} +.enm-app .enm-overview-row--arbiter { + grid-template-columns: 12px 1fr auto 14px; + padding: var(--sp-2, 8px); + gap: var(--sp-2, 8px); +} +.enm-app .enm-overview-row--arbiter .enm-overview-name { + font-size: 13px; + font-weight: 600; +} + +/* --- Compact viewport overrides ------------------------------------ */ +.enm-app[data-app-size="compact"] .enm-overview-evm-grid, +body[data-app-size="compact"] .enm-app .enm-overview-evm-grid, +.enm-app[data-app-size="narrow"] .enm-overview-evm-grid, +body[data-app-size="narrow"] .enm-app .enm-overview-evm-grid { + grid-template-columns: 1fr; +} +.enm-app[data-app-size="compact"] .enm-overview-row--hero, +body[data-app-size="compact"] .enm-app .enm-overview-row--hero { + grid-template-columns: 14px 1fr auto 14px; +} +.enm-app[data-app-size="compact"] .enm-overview-row--hero .enm-overview-name, +body[data-app-size="compact"] .enm-app .enm-overview-row--hero .enm-overview-name { + font-size: 16px; +} +.enm-app[data-app-size="compact"] .enm-overview-row--evm, +body[data-app-size="compact"] .enm-app .enm-overview-row--evm, +.enm-app[data-app-size="compact"] .enm-overview-row--arbiter, +body[data-app-size="compact"] .enm-app .enm-overview-row--arbiter { + grid-template-columns: 12px 1fr auto 14px; +} +.enm-app[data-app-size="compact"] .enm-overview-row--evm .enm-overview-spark, +body[data-app-size="compact"] .enm-app .enm-overview-row--evm .enm-overview-spark, +.enm-app[data-app-size="compact"] .enm-overview-row--evm .enm-overview-uptime, +body[data-app-size="compact"] .enm-app .enm-overview-row--evm .enm-overview-uptime { + display: none; +} + /* Compact viewport: hide uptime + sparkline columns so the control-center main column (name + state + live meta line) keeps full width. Quick actions stay (operators need them on small screens too). Row still tappable, still diff --git a/src/backend/apps/elastos-node-manager/index.html b/src/backend/apps/elastos-node-manager/index.html index 9b9be34d61..1ed9b6b5f4 100644 --- a/src/backend/apps/elastos-node-manager/index.html +++ b/src/backend/apps/elastos-node-manager/index.html @@ -10,7 +10,7 @@ Elastos Node Manager - + + + + + + + + + + + + + + + + + + + + + @@ -215,9 +238,9 @@

Elastos Node Manager

cards mounted BELOW the shared chain-card hero. Class B (EVM): mining on/off + geth/reward addresses. Class C (Oracle): parent reachable + height + last activity/error. Never mounted for the mainchain. --> - + - + - + - + diff --git a/src/backend/apps/elastos-node-manager/js/components/audit-tab.js b/src/backend/apps/elastos-node-manager/js/components/audit-tab.js index 83dd4c4cf2..0eeac53577 100644 --- a/src/backend/apps/elastos-node-manager/js/components/audit-tab.js +++ b/src/backend/apps/elastos-node-manager/js/components/audit-tab.js @@ -116,7 +116,13 @@ // Filter state. `tier` is one of TIER_VALUES or '' (any). // `when` is a key of WHEN_PRESETS. `from`/`to` are epoch ms // derived from `when` at refresh() time. - this._filters = { tier: '', when: 'all', chain: '' }; + // v0.5.218 audit Phase 4 (AUDIT-FLOW-AU04, P2) — persist via + // enmPrefs so the operator's filter survives tab remount / + // chain switch. Pre-v0.5.218 every remount reset filters. + var DEFAULT_FILTERS = { tier: '', when: 'all', chain: '' }; + this._filters = (root.enmPrefs && typeof root.enmPrefs.get === 'function') + ? root.enmPrefs.get('audit-tab:filters', DEFAULT_FILTERS) + : DEFAULT_FILTERS; // Drawer state. this._drawer = null; @@ -539,6 +545,7 @@ } if (this._filters.when === key) { return; } this._filters.when = key; + this._persistFilters(); this._syncChipGroup(this._whenChips, key); this.refresh(); }; @@ -547,6 +554,7 @@ AuditTab.prototype._onTierChip = function (tier) { if (this._filters.tier === tier) { return; } this._filters.tier = tier; + this._persistFilters(); this._syncChipGroup(this._tierChips, tier); this.refresh(); }; @@ -555,10 +563,25 @@ AuditTab.prototype._onChainChip = function (chain) { if (this._filters.chain === chain) { return; } this._filters.chain = chain; + this._persistFilters(); this._syncChipGroup(this._chainChips, chain); this.refresh(); }; + /** + * v0.5.218 audit Phase 4 (AUDIT-FLOW-AU04, P2) — write current + * filters to sessionStorage so they persist across remount / + * chain switch. Called from every filter-mutator. Silent on + * private-mode storage failure. + * @private + */ + AuditTab.prototype._persistFilters = function () { + if (root.enmPrefs && typeof root.enmPrefs.set === 'function') { + try { root.enmPrefs.set('audit-tab:filters', this._filters); } + catch (_) { /* silent */ } + } + }; + /** @private */ AuditTab.prototype._syncChipGroup = function (chipMap, activeKey) { Object.keys(chipMap).forEach(function (k) { @@ -594,6 +617,16 @@ && String(e.tier) !== this._filters.tier) { return; } + // v0.5.224 audit (AUDIT-FLOW-AU09, P2) — chain filter MUST be + // applied to live SSE rows. Pre-v0.5.224 only tier + when + // range were checked; "This chain only" operator filter + // silently leaked rows from other chains until next refresh. + if (this._filters && this._filters.chain) { + var rowChain = e.chainId || e.chain_id || ''; + if (String(rowChain) !== this._filters.chain) { + return; + } + } // Filter: time range. Same logic as _currentWhenRange — for // 'today'/'7d'/'30d' there's a from-ms cutoff; rows older // than that are silently dropped. 'all' and 'custom' pass diff --git a/src/backend/apps/elastos-node-manager/js/components/chain-card.js b/src/backend/apps/elastos-node-manager/js/components/chain-card.js index b481770ca6..17f17af051 100644 --- a/src/backend/apps/elastos-node-manager/js/components/chain-card.js +++ b/src/backend/apps/elastos-node-manager/js/components/chain-card.js @@ -31,19 +31,17 @@ (function (root) { 'use strict'; - // Coarse backend state → PowerCircle visual state. Same table as - // alpha.18; one-shot lookup so the mapping stays reviewable. - var COARSE_TO_VISUAL = { - unconfigured: 'off', - stopped: 'off', - recovering: 'booting', - starting: 'booting', - syncing: 'syncing', - healthy: 'healthy', - stalled: 'warning', - error: 'error', - disabled: 'off', - }; + // v0.5.219 audit Phase 5 (AUDIT-FLOW-S01, P3) — the dead + // COARSE_TO_VISUAL constant that used to live here was DELETED. + // It was never referenced anywhere in this file (the 5 inline + // `'healthy' || 'synced'` checks did NOT use it), and the table + // itself was missing 'synced' / 'loading' (the v0.5.203 vocab + // update never reached the dead constant). A future "let's clean + // up by using the constant" refactor would have silently re- + // introduced the v0.5.203 regression. Source of truth now lives + // in js/utils-state-vocab.js (root.enmStateVocab). The 5 inline + // checks below are migrated to enmStateVocab.isAlive() etc. in + // the v0.5.219 batch. // beta.3.92 (Wave M2.4) — operator-facing display-name fallback // for every known chainId. Used when the per-chain API response @@ -271,11 +269,18 @@ // 10-minute backend outage doesn't stack 120 identical // toasts. show() dedupes by id, updating the existing // toast in place instead of mounting a fresh one. + // v0.5.227 audit Phase 16 (XFLOW-18) — friendly error mapping + // replaces raw err.message which leaked stack-trace-flavored + // text like "TypeError: Failed to fetch" to operator UI. + var friendlyBody = (typeof root.enmFriendlyError === 'function') + ? root.enmFriendlyError(err) + : (err && err.message ? err.message : String(err)); + if (friendlyBody == null) { return; } // 401 silenced upstream self.notifications.show({ id: 'chain-refresh-fail-' + self.chainId, severity: 'warning', title: 'Failed to refresh ' + displayName, - body: err && err.message ? err.message : String(err), + body: friendlyBody, }); }).then(function () { self._refreshInFlight = null; @@ -769,13 +774,26 @@ // Map coarse → hero-power data-state. Mock defines: running / // stopped / stalled / error. Unconfigured / disabled visually // are 'stopped' (gray, no glow). - // v0.5.205 — 'synced' joins 'healthy' as the alive-and-synced - // hero state after v0.5.203 vocab unification. - var heroState = (coarse === 'healthy' || coarse === 'synced') ? 'running' - : (coarse === 'stalled') ? 'stalled' - : (coarse === 'error') ? 'error' + // v0.5.219 audit Phase 5 — route through enmStateVocab + // (XFLOW-04 / XFLOW-16). The shared utility handles the + // v1 'healthy' / 'running' aliases, future state additions, + // and the visual mapping. Replaces the inline ternary that + // had to be updated at every state-vocab change. + var heroState = (root.enmStateVocab && root.enmStateVocab.stateVisual) + ? root.enmStateVocab.stateVisual(coarse) + : (coarse === 'healthy' || coarse === 'synced') ? 'running' + : (coarse === 'stalled') ? 'stalled' + : (coarse === 'error') ? 'error' + : 'stopped'; + // Map enmStateVocab's wider visual vocab to the hero-power + // component's narrower set (it supports running/stalled/ + // error/off — 'syncing'/'booting' don't apply here since + // those states render the sync-ring hero instead). + var heroPowerState = (heroState === 'running') ? 'running' + : (heroState === 'stalled') ? 'stalled' + : (heroState === 'error') ? 'error' : 'stopped'; - this._renderHeroPower(heroState); + this._renderHeroPower(heroPowerState); } // State-chip — text + modifier class. Mock variants: .accent @@ -818,19 +836,50 @@ // producerState on a non-A chain's response. var producerState = (this.chainClass === 'A' && state && state.producerState) ? state.producerState : null; + // v0.5.229 (Phase D) — Council membership chip overrides BPoS + // producer state when the operator is bound to a CR Committee + // seat. CR seats are higher-tier than BPoS slots in Elastos's + // DPoS rotation, so a "Council · Elected" chip is more + // informative than "Active" for a CR operator who happens to + // ALSO be a BPoS producer. Falls through to BPoS when crMember + // is null (pure BPoS operator or mainchain RPC down). + // v0.5.229d (P4 audit fix) — also stash on the instance so the + // rotation strip's _applyRotation can read it for the + // "unclaim pending; slate freeze" qualifier without doing its + // own /system/identity fetch. + var crMember = (this.chainClass === 'A' && state && state.crMember) + ? state.crMember : null; + this._lastCrMember = crMember; + var crChipLabel = null; + if (crMember && crMember.isCrMember && crMember.state) { + crChipLabel = 'Council · ' + crMember.state; + } else if (crMember && crMember.inNextCommittee && crMember.state) { + crChipLabel = 'Council · Next term'; + } var version = (state && state.binaryVersion) ? state.binaryVersion : ''; var versionSuffix = version ? ' · ' + version : ''; var chipText; - // v0.5.205 — accept 'synced' alongside 'healthy' in all three branches - // (post-v0.5.203 vocab unification). - if (producerState && (coarse === 'healthy' || coarse === 'synced' || coarse === 'syncing' || coarse === 'stalled')) { + // v0.5.219 audit Phase 5 — route through enmStateVocab.isAlive + // (handles 'healthy'/'synced'/'syncing'/'stalled'/'recovering' uniformly, + // including v1 'healthy'/'running' aliases). Closes 2 of the 3 + // remaining inline `'healthy' || 'synced'` sites in this file. + var aliveForChip = (root.enmStateVocab && root.enmStateVocab.isAlive) + ? (root.enmStateVocab.isAlive(coarse) || coarse === 'syncing') + : (coarse === 'healthy' || coarse === 'synced' || coarse === 'syncing' || coarse === 'stalled'); + if (crChipLabel && aliveForChip) { + // v0.5.229 — Council chip wins when applicable. Versionsuffix + // appended same as the BPoS chip below; dataset.state encodes + // the Council state for CSS theming (.state="...-council-elected" etc.). + chipText = crChipLabel + versionSuffix; + this._stateChip.dataset.state = coarse + '-council-' + String(crMember.state || 'unknown').toLowerCase(); + } else if (producerState && aliveForChip) { // 0.2.0-beta.3.6 — include the version suffix on producer-state // chips too. Pre-beta.3.6 dropped it when producerState was set, // leaving "Active" alone on the chip. Mock keeps the version // for layout consistency: "Active · v0.9.7" / "Rank #42 · v0.9.7". chipText = producerState + versionSuffix; this._stateChip.dataset.state = coarse + '-producer-' + String(producerState).toLowerCase(); - } else if (coarse === 'healthy' || coarse === 'synced') { + } else if (root.enmStateVocab && root.enmStateVocab.normalize(coarse) === 'synced') { chipText = chainNameLabel + versionSuffix; this._stateChip.dataset.state = coarse; } else if (coarse === 'syncing' || coarse === 'recovering' || coarse === 'starting') { @@ -952,13 +1001,17 @@ } // Action row enable/disable. - // v0.5.205 — accept 'synced' as alive too. Backend started returning - // 'synced' (replacing 'healthy') in v0.5.203 when state vocabulary - // was unified; without this card thought every alive-and-synced chain - // was stopped → showed "TAP TO START" and hid Stop/Restart. - var alive = (coarse === 'healthy' || coarse === 'synced' - || coarse === 'syncing' || coarse === 'stalled' - || coarse === 'recovering' || coarse === 'starting'); + // v0.5.219 audit Phase 5 — single source-of-truth for the + // alive predicate. Pre-v0.5.219 this inline OR-chain at 5 + // sites in this file caused the v0.5.203 vocab regression + // (chain showed "TAP TO START" + hid Stop/Restart when state + // was 'synced'). Now: enmStateVocab.isAlive() handles every + // v1/v2 alias + future additions. + var alive = (root.enmStateVocab && root.enmStateVocab.isAlive) + ? (root.enmStateVocab.isAlive(coarse) || coarse === 'syncing' || coarse === 'starting') + : (coarse === 'healthy' || coarse === 'synced' + || coarse === 'syncing' || coarse === 'stalled' + || coarse === 'recovering' || coarse === 'starting'); var unconfigured = (coarse === 'unconfigured'); // v0.5.207 — 'loading' is the pre-API placeholder. Hide every action // button while we don't know what the chain's true state is — @@ -1072,10 +1125,73 @@ if (typeof this.onReconfigure === 'function') this.onReconfigure(this.chainId); }; - /** @private */ - ChainCard.prototype._handleStart = function () { this._do('start', '/chains/' + this.chainId + '/start'); }; - ChainCard.prototype._handleStop = function () { this._do('stop', '/chains/' + this.chainId + '/stop'); }; - ChainCard.prototype._handleRestart = function () { this._do('restart', '/chains/' + this.chainId + '/restart'); }; + /** @private — Start is non-destructive, no confirm needed. */ + ChainCard.prototype._handleStart = function () { + this._do('start', '/chains/' + this.chainId + '/start'); + }; + /** @private — v0.5.217 audit Phase 3 (AUDIT-FLOW-S02, P2) — Stop now + * gates through enmDestructiveModal. Pre-v0.5.217 the danger-red + * Stop button had NO confirmation; one misclick stopped a producing + * chain mid-block. The alpha.28.1 batch 46 rationale ("click-and-busy + * pattern is enough") only protected against DOUBLE-fire, not against + * intentional-but-accidental clicks. enmDestructiveModal adds a 2s + * cooldown + ack checkbox before delegating to _do(). */ + ChainCard.prototype._handleStop = function () { + var self = this; + var displayName = this._resolveDisplayName(); + if (typeof root.enmDestructiveModal !== 'function') { + // Defensive fallback if the modal primitive failed to load. + return this._do('stop', '/chains/' + this.chainId + '/stop'); + } + root.enmDestructiveModal({ + title: 'Stop ' + displayName + '?', + body: 'The chain process will stop and the node will no longer produce blocks or respond to RPC. Start it again from this card when ready. No chain data is lost.', + ackLabel: 'I understand this stops ' + displayName, + cooldownSec: 2, + confirmLabel: 'Stop ' + displayName, + confirmKind: 'danger', + notifications: self.notifications, + onConfirm: function () { + // _do handles toast + refresh; we just delegate. + self._do('stop', '/chains/' + self.chainId + '/stop'); + return Promise.resolve(); + }, + }); + }; + /** @private — v0.5.217 audit Phase 3 (AUDIT-FLOW-B04, P2) — Restart + * now confirms too. Restart interrupts sync work and chain is + * unavailable for 20-60s; matches multi-chain-overview's existing + * confirm UX so operator habits formed on one entry transfer. */ + ChainCard.prototype._handleRestart = function () { + var self = this; + var displayName = this._resolveDisplayName(); + if (typeof root.enmDestructiveModal !== 'function') { + return this._do('restart', '/chains/' + this.chainId + '/restart'); + } + root.enmDestructiveModal({ + title: 'Restart ' + displayName + '?', + body: 'The chain will stop, then start again automatically (typical pause: 20-60 seconds). Sync resumes from the current block — no data is lost. In-progress block-signing work is interrupted.', + ackLabel: null, // restart is less destructive than stop; cooldown alone is sufficient gate + cooldownSec: 1, + confirmLabel: 'Restart ' + displayName, + confirmKind: 'primary', + notifications: self.notifications, + onConfirm: function () { + self._do('restart', '/chains/' + self.chainId + '/restart'); + return Promise.resolve(); + }, + }); + }; + /** @private — Helper for the display-name resolution used by Stop/Restart + * confirm modals (parallel of the _do() displayName fallback). */ + ChainCard.prototype._resolveDisplayName = function () { + var t = root.enmTOrFallback; + var displayName = t('chain_name.' + this.chainId); + if (!displayName || displayName === 'chain_name.' + this.chainId) { + displayName = this.chainId; + } + return displayName; + }; /** @private */ ChainCard.prototype._do = function (kind, path) { @@ -1098,9 +1214,41 @@ if (!displayName || displayName === 'chain_name.' + this.chainId) { displayName = this.chainId; } - var pastVerb = ({ start: 'started', stop: 'stopped', restart: 'restarted' })[kind] || kind; + // v0.5.220 audit Phase 6 (XFLOW-01, AUDIT-FLOW-S04) — present- + // progressive verbs replace past-tense. Pre-v0.5.220 the toast + // said "Mainchain started" the instant the POST resolved, but + // the chain was actually in 'starting' state for 20-60s before + // becoming RPC-bound. Operator-perception mismatch closed. + var progressiveVerb = ({ start: 'is starting…', stop: 'is stopping…', restart: 'is restarting…' })[kind] || kind; this.api.post(path).then(function () { - self.notifications.info(displayName + ' ' + pastVerb, ''); + self.notifications.info(displayName + ' ' + progressiveVerb, ''); + // v0.5.220 audit Phase 6 (XFLOW-02, AUDIT-FLOW-S05) — arm a + // 90s watchdog after Start/Restart. If the chain hasn't + // reached alive by then, fire a warning so the operator + // doesn't have to actively notice the silent stuck state. + // Stop has no watchdog — there's no "alive" target. + if ((kind === 'start' || kind === 'restart') + && typeof root.enmWatchAction === 'function' + && root.enmStateVocab) { + root.enmWatchAction({ + timeoutMs: 90000, + pollMs: 5000, + predicate: function () { + if (self._destroyed) { return true; } // teardown — cancel + return root.enmStateVocab.isAlive(self._lastCoarseState); + }, + onTimeout: function () { + if (self._destroyed) { return; } + if (root.enmStateVocab.isAlive(self._lastCoarseState)) { return; } + self.notifications.warning( + displayName + ' didn\'t reach a running state', + 'The ' + kind + ' completed but the chain is still in ' + + (self._lastCoarseState || 'unknown') + + '. Check logs and consider another restart.', + ); + }, + }); + } return self.refresh(); }).catch(function (err) { // alpha.28.1 batch 52 — 401 suppressed; boot path owns @@ -1262,8 +1410,12 @@ this._syncBar.hidden = true; this._syncBar.innerHTML = ''; - // v0.5.205 — accept 'synced' (post-v0.5.203 vocab unification) too. - if (coarse === 'healthy' || coarse === 'synced') { + // v0.5.219 audit Phase 5 — route through enmStateVocab.normalize + // for the alive-and-synced subline. Last of the 5 inline state + // checks this file had pre-v0.5.219; all 5 now closed. + var normalizedCoarse = (root.enmStateVocab && root.enmStateVocab.normalize) + ? root.enmStateVocab.normalize(coarse) : coarse; + if (normalizedCoarse === 'synced' || coarse === 'healthy') { var atTip = document.createElement('span'); atTip.className = 'enm-at-tip'; atTip.textContent = 'Fully synced'; @@ -1519,9 +1671,28 @@ text.className = 'enm-chain-rotation-text'; strip.appendChild(text); + // v0.5.229d (P4 audit fix) — slate-freeze qualifier. The chain's + // next-rotation arbiter slate is COMPUTED IN ADVANCE (at a + // height before nextTurnStartHeight) and then FROZEN until that + // rotation actually starts. If an operator unclaims via Essentials + // AFTER the slate was frozen, their pubkey stays in nextarbiters[] + // until the rotation AFTER next. Pre-229d the rotation strip just + // said "Queued for next round · 16 of 36" with no context for + // why an unclaimed operator was still queued. Now we cross- + // reference miner.chainState... wait, we don't have crMember + // directly here. /chains/mainchain DOES include crMember (Phase + // D); the chain-card stashed _lastCrMember from the previous + // render of the chip. Use that. + var unclaimPending = !!(this._lastCrMember + && this._lastCrMember.isCrMember === false + && (data.ourIndex >= 0 || data.ourNextIndex >= 0)); + var unclaimNote = unclaimPending + ? ' (unclaim pending; slate freeze in effect until next compute)' + : ''; + if (data.isOnDuty) { strip.dataset.state = 'onduty'; - text.textContent = 'On duty now · signing the current block'; + text.textContent = 'On duty now · signing the current block' + unclaimNote; } else if (inSlate) { strip.dataset.state = 'inslate'; // alpha.28.1 batch 68 (Round-19B audit) — guard @@ -1534,7 +1705,7 @@ // nextArbiters in the next-slate branch below. var rl = (data.rotationLength != null) ? data.rotationLength : '—'; text.textContent = 'Your slot · ' - + (data.ourIndex + 1) + ' of ' + rl; + + (data.ourIndex + 1) + ' of ' + rl + unclaimNote; } else { strip.dataset.state = 'nextslate'; // 0.5.125 audit Session 125 — defensive '—' fallback for @@ -1550,7 +1721,7 @@ var nl = (data.nextArbiters && data.nextArbiters.length > 0) ? data.nextArbiters.length : '—'; text.textContent = 'Queued for next round · ' - + (data.ourNextIndex + 1) + ' of ' + nl; + + (data.ourNextIndex + 1) + ' of ' + nl + unclaimNote; } }; diff --git a/src/backend/apps/elastos-node-manager/js/components/destructive-modal.js b/src/backend/apps/elastos-node-manager/js/components/destructive-modal.js new file mode 100644 index 0000000000..07dfa41f48 --- /dev/null +++ b/src/backend/apps/elastos-node-manager/js/components/destructive-modal.js @@ -0,0 +1,323 @@ +/* + * Copyright (C) 2026-present Elacity + * SPDX-License-Identifier: AGPL-3.0 + * + * components/destructive-modal.js — canonical destructive-action modal. + * + * Extracted from proposal-card.js per audit Phase 3 / XFLOW-22. Replaces + * ~10 ad-hoc native confirm() patterns + brittle inline gates across the + * app (Stop / Restart / Nuke / Uninstall / Reset / Import / Class B + * restart / validator activate / F-rule toggle / overview row actions). + * + * The primitives this factory inherits from ProposalCard: + * - N-second cooldown timer (prevents reflex clicks) + * - Required acknowledgment checkbox + * - Optional typed-confirm gate (e.g. "WIPE EVERYTHING") + * - Esc CLOSES the dialog WITHOUT committing (Round-20A HIGH fix) + * - Scrim click closes (same as Esc) + * - Focus trap + previousFocus restore (WCAG 2.4.3) + * - _closed guard so peer-tab BroadcastChannel can dismiss safely + * - 401 silence (boot path owns re-auth) + * - 409 conflict envelope → critical toast with remediation + * + * Usage: + * enmDestructiveModal({ + * title: 'Stop Mainchain?', + * body: 'In-progress block-signing work will stop. Restart later from this dashboard.', + * ackLabel: 'I understand this stops the chain', // shown next to checkbox + * cooldownSec: 2, // 0 to skip cooldown + * typedConfirm: null, // OR { expected: 'WIPE EVERYTHING', caseSensitive: true } + * confirmLabel: 'Stop the chain', + * confirmKind: 'danger', // 'primary' | 'danger' | 'critical' + * onConfirm: function () { + * return api.post('/chains/mainchain/stop'); // returns a Promise; modal handles loading/error/close + * }, + * notifications: services.notifications, // optional, for 409 toast + * }); + * + * The returned promise resolves with { confirmed: true } when the action + * completes successfully, or { confirmed: false, reason: 'cancelled' | + * 'esc' | 'scrim' } when dismissed without action. Errors from onConfirm + * are surfaced inline; the modal stays open for retry (operator decides). + */ + +(function (root) { + 'use strict'; + + var ACTIVE_STACK = []; // For Esc handling — only the topmost modal closes on Esc. + + function escapeHtml(s) { + return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { + return ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]; + }); + } + + /** + * @param {object} opts + * @returns {Promise<{confirmed: boolean, reason?: string}>} + */ + function enmDestructiveModal(opts) { + opts = opts || {}; + if (typeof opts.onConfirm !== 'function') { + throw new TypeError('enmDestructiveModal: opts.onConfirm function is required'); + } + var title = opts.title || 'Are you sure?'; + var body = opts.body || ''; + var ackLabel = opts.ackLabel || null; // null = no ack checkbox + var cooldownSec = (typeof opts.cooldownSec === 'number') ? opts.cooldownSec : 2; + var typedConfirm = opts.typedConfirm || null; + var confirmLabel = opts.confirmLabel || 'Confirm'; + var confirmKind = opts.confirmKind || 'danger'; + var cancelLabel = opts.cancelLabel || 'Cancel'; + var onConfirm = opts.onConfirm; + var notifications = opts.notifications || null; + var t = root.enmTOrFallback || function (k, fb) { return fb || k; }; + + return new Promise(function (resolve) { + var closed = false; + var previousFocus = document.activeElement; + + // Build DOM. + var modalRoot = document.createElement('div'); + modalRoot.className = 'enm-destructive-modal-root'; + + var scrim = document.createElement('div'); + scrim.className = 'enm-modal-scrim'; + modalRoot.appendChild(scrim); + + var card = document.createElement('div'); + card.className = 'enm-modal-card enm-destructive-modal-card'; + card.setAttribute('role', 'dialog'); + card.setAttribute('aria-modal', 'true'); + card.setAttribute('aria-labelledby', 'enm-dm-heading'); + + var heading = document.createElement('h2'); + heading.id = 'enm-dm-heading'; + heading.className = 'enm-modal-heading enm-modal-heading-' + confirmKind; + heading.textContent = title; + card.appendChild(heading); + + if (body) { + var bodyP = document.createElement('p'); + bodyP.className = 'enm-modal-summary'; + bodyP.textContent = body; + card.appendChild(bodyP); + } + + // Ack checkbox (optional). + var ackBox = null; + if (ackLabel) { + var ackWrap = document.createElement('label'); + ackWrap.className = 'enm-modal-ack'; + ackBox = document.createElement('input'); + ackBox.type = 'checkbox'; + ackBox.setAttribute('aria-required', 'true'); + ackWrap.appendChild(ackBox); + var ackTxt = document.createElement('span'); + ackTxt.className = 'enm-modal-ack-text'; + ackTxt.textContent = ackLabel; + ackWrap.appendChild(ackTxt); + card.appendChild(ackWrap); + } + + // Typed-confirm gate (optional). Per audit AUDIT-FLOW-DZ14 the + // placeholder DOES NOT leak the expected text — operator must + // commit it to muscle memory or read it from the label. + var typedInput = null; + if (typedConfirm && typedConfirm.expected) { + var typedWrap = document.createElement('div'); + typedWrap.className = 'enm-modal-typed-confirm'; + var typedLabel = document.createElement('label'); + typedLabel.className = 'enm-modal-typed-confirm-label'; + typedLabel.textContent = 'To confirm, type '; + var typedExpectedSpan = document.createElement('code'); + typedExpectedSpan.className = 'enm-modal-typed-confirm-expected'; + typedExpectedSpan.textContent = typedConfirm.expected; + typedLabel.appendChild(typedExpectedSpan); + typedLabel.appendChild(document.createTextNode(' below.')); + typedWrap.appendChild(typedLabel); + typedInput = document.createElement('input'); + typedInput.type = 'text'; + typedInput.className = 'enm-input'; + typedInput.placeholder = 'Type to confirm'; + typedInput.setAttribute('autocomplete', 'off'); + typedInput.setAttribute('spellcheck', 'false'); + typedInput.setAttribute('autocapitalize', 'off'); + typedInput.setAttribute('autocorrect', 'off'); + typedWrap.appendChild(typedInput); + card.appendChild(typedWrap); + } + + // Action row: cooldown label + Cancel + Confirm. + var actions = document.createElement('div'); + actions.className = 'enm-modal-actions'; + var cooldownLabel = document.createElement('span'); + cooldownLabel.className = 'enm-modal-cooldown'; + cooldownLabel.setAttribute('aria-live', 'polite'); + actions.appendChild(cooldownLabel); + var cancelBtn = document.createElement('button'); + cancelBtn.type = 'button'; + cancelBtn.className = 'enm-btn'; + cancelBtn.textContent = cancelLabel; + actions.appendChild(cancelBtn); + var confirmBtn = document.createElement('button'); + confirmBtn.type = 'button'; + confirmBtn.className = 'enm-btn enm-btn-' + confirmKind; + confirmBtn.textContent = confirmLabel; + confirmBtn.disabled = true; // enabled when cooldown done + ack + typed all OK + actions.appendChild(confirmBtn); + card.appendChild(actions); + + // Status row for inline errors (no toast). + var statusEl = document.createElement('p'); + statusEl.className = 'enm-modal-status'; + statusEl.setAttribute('aria-live', 'polite'); + statusEl.hidden = true; + card.appendChild(statusEl); + + modalRoot.appendChild(card); + document.body.appendChild(modalRoot); + + // Push onto active stack so Esc closes only the topmost. + ACTIVE_STACK.push(modalRoot); + + // Cooldown timer. + var cooldownRemaining = cooldownSec; + var cooldownTimer = null; + function refreshCooldownLabel() { + if (cooldownRemaining > 0) { + cooldownLabel.textContent = 'Available in ' + cooldownRemaining + 's'; + cooldownLabel.classList.toggle('enm-modal-cooldown-warn', cooldownRemaining <= 1); + } else { + cooldownLabel.textContent = ''; + cooldownLabel.classList.remove('enm-modal-cooldown-warn'); + } + } + function refreshConfirmEnabled() { + if (closed) { return; } + var cooldownDone = cooldownRemaining <= 0; + var ackOK = !ackBox || ackBox.checked; + var typedOK = !typedInput || (function () { + var v = typedInput.value || ''; + var exp = typedConfirm.expected; + return typedConfirm.caseSensitive ? (v === exp) : (v.toLowerCase() === exp.toLowerCase()); + }()); + confirmBtn.disabled = !(cooldownDone && ackOK && typedOK); + } + refreshCooldownLabel(); + if (cooldownRemaining > 0) { + cooldownTimer = setInterval(function () { + cooldownRemaining -= 1; + refreshCooldownLabel(); + refreshConfirmEnabled(); + if (cooldownRemaining <= 0) { + clearInterval(cooldownTimer); + cooldownTimer = null; + } + }, 1000); + } else { + refreshConfirmEnabled(); + } + if (ackBox) { ackBox.addEventListener('change', refreshConfirmEnabled); } + if (typedInput) { typedInput.addEventListener('input', refreshConfirmEnabled); } + + // Esc / scrim handlers. + function close(reason) { + if (closed) { return; } + closed = true; + if (cooldownTimer) { clearInterval(cooldownTimer); cooldownTimer = null; } + document.removeEventListener('keydown', onKeydown, true); + var idx = ACTIVE_STACK.indexOf(modalRoot); + if (idx !== -1) { ACTIVE_STACK.splice(idx, 1); } + if (modalRoot.parentNode) { modalRoot.parentNode.removeChild(modalRoot); } + if (previousFocus && typeof previousFocus.focus === 'function') { + try { previousFocus.focus(); } catch (_) { /* element may be gone */ } + } + resolve({ confirmed: false, reason: reason }); + } + function onKeydown(ev) { + if (ev.key === 'Escape') { + // Only act if WE are the topmost modal. + if (ACTIVE_STACK[ACTIVE_STACK.length - 1] !== modalRoot) { return; } + ev.preventDefault(); + close('esc'); + } + } + document.addEventListener('keydown', onKeydown, true); + scrim.addEventListener('click', function () { close('scrim'); }); + cancelBtn.addEventListener('click', function () { close('cancelled'); }); + + // Confirm. + confirmBtn.addEventListener('click', function () { + if (closed || confirmBtn.disabled) { return; } + confirmBtn.disabled = true; + cancelBtn.disabled = true; // cross-button race protection + statusEl.hidden = true; + confirmBtn.textContent = (t('common.saving') || 'Working…'); + var actionResult; + try { + actionResult = onConfirm(); + } catch (err) { + return handleError(err); + } + Promise.resolve(actionResult).then(function (result) { + if (closed) { return; } + // Success — close + resolve. + closed = true; + if (cooldownTimer) { clearInterval(cooldownTimer); cooldownTimer = null; } + document.removeEventListener('keydown', onKeydown, true); + var idx = ACTIVE_STACK.indexOf(modalRoot); + if (idx !== -1) { ACTIVE_STACK.splice(idx, 1); } + if (modalRoot.parentNode) { modalRoot.parentNode.removeChild(modalRoot); } + if (previousFocus && typeof previousFocus.focus === 'function') { + try { previousFocus.focus(); } catch (_) { /* element gone */ } + } + resolve({ confirmed: true, result: result }); + }).catch(handleError); + }); + + function handleError(err) { + if (closed) { return; } + // 401 silence — boot path owns re-auth. + if (err && err.status === 401) { + // Re-enable buttons; operator may dismiss + retry post-auth. + confirmBtn.disabled = false; + confirmBtn.textContent = confirmLabel; + cancelBtn.disabled = false; + return; + } + // 409 conflict envelope → toast + leave modal open for retry. + if (err && err.status === 409 && err.body && Array.isArray(err.body.conflicts) + && err.body.conflicts.length > 0 && notifications && typeof notifications.critical === 'function') { + var pool = err.body.conflicts.filter(function (c) { return c && c.severity === 'CRITICAL'; }); + if (pool.length === 0) { pool = err.body.conflicts; } + var summary = pool.map(function (c) { + var firstStep = (c && c.remediation && c.remediation[0]); + var stepStr = (typeof firstStep === 'string' && firstStep.length > 0) ? firstStep : ''; + var descStr = (typeof c.description === 'string' && c.description.length > 0) + ? c.description : 'Host conflict'; + return '• ' + descStr + (stepStr ? ('\n ' + stepStr) : ''); + }).join('\n'); + notifications.critical((title || 'Action') + ' — host conflicts', summary); + } + // Surface inline error + re-enable for retry. + var msg = (err && err.message) || String(err || 'Failed'); + statusEl.hidden = false; + statusEl.textContent = msg; + statusEl.classList.add('err'); + confirmBtn.disabled = false; + confirmBtn.textContent = confirmLabel; + cancelBtn.disabled = false; + } + + // Auto-focus the first interactive control. + var firstFocus = ackBox || typedInput || cancelBtn; + setTimeout(function () { + if (closed) { return; } + try { firstFocus.focus(); } catch (_) { /* element gone */ } + }, 0); + }); + } + + root.enmDestructiveModal = enmDestructiveModal; +}(typeof window !== 'undefined' ? window : globalThis)); diff --git a/src/backend/apps/elastos-node-manager/js/components/evm-detail-card.js b/src/backend/apps/elastos-node-manager/js/components/evm-detail-card.js index 1db6103dcc..0586000a2b 100644 --- a/src/backend/apps/elastos-node-manager/js/components/evm-detail-card.js +++ b/src/backend/apps/elastos-node-manager/js/components/evm-detail-card.js @@ -13,9 +13,12 @@ * * Surfaces the three EVM-specific values the generic hero never shows and * that an operator most wants to verify: - * 1. Mining on / off (cfg.miner.enabled) + * 1. Validator status (derived from miner.chainState — backed + * by detectProducerRole against the + * on-chain CR-Council / DPoS arbiter + * slate; NOT an operator toggle) * 2. EVM account address (the geth keystore account — evmKeystoreAddr) - * 3. Block-reward address (cfg.miner.rewardAddress) + * 3. Block-reward address (operator-supplied — miner.rewardAddress) * * Data source: GET /api/enm/chains/:id → .miner { enabled, evmKeystoreAddr, * rewardAddress } (added in Phase 1, P1.1). Real-data-only: a null field @@ -30,12 +33,34 @@ * resolves, 401-suppress on the background fetch, enmCopyButton for copy, * aria-labelledby on the card root. Copy is inline English to match the * peer node-identity-card (pending any future bulk i18n pass). + * + * v0.5.228 — Block-reward address is operator-editable inline. EIP-55 + * client-side validation via enmEthAddress.check; PUT + * /chains/:id/class-b-config writes miner.rewardAddress; on success a + * "restart to apply" hint surfaces with an inline restart-now button when + * the chain is currently running (so the new --pbft.miner.address takes + * effect on the relaunched geth process). The EVM account row stays + * read-only — that's the auto-generated local keystore account and + * changing it would orphan the geth keystore. */ (function (root) { 'use strict'; var POLL_INTERVAL_MS = 60_000; + // v0.5.228 — chain states the backend reports for a *running* EVM chain + // (synced / actively-syncing / starting). When the chain is in one of + // these, a reward-address change needs a restart to take effect; when + // it's stopped / unconfigured / disabled, the change is picked up + // automatically on next start. Treats v1 aliases (running / healthy) + // as alive too in case enmStateVocab isn't loaded. + var ALIVE_STATES = ['synced', 'syncing', 'starting', 'stalled', 'running', 'healthy']; + function isChainAlive(state) { + if (root.enmStateVocab && typeof root.enmStateVocab.isAlive === 'function') { + return !!root.enmStateVocab.isAlive(state); + } + return state ? ALIVE_STATES.indexOf(String(state)) >= 0 : false; + } function EvmDetailCard(opts) { if (!opts || !opts.api) { throw new TypeError('EnmEvmDetailCard: { api } required'); } @@ -61,7 +86,16 @@ this._pollPauser = null; this._pollTimer = null; this._lastMiner = null; + this._lastState = null; // v0.5.228 — most-recent chain state for restart-now affordance this._lastHtml = null; // v0.5.191 — render-dedup cache + // v0.5.228 — reward-address inline editor state. While editing, + // background polls stash new data into _lastMiner but do NOT + // rebuild the DOM (would wipe the operator's in-flight input). + this._editingReward = false; + this._editingValue = ''; + this._editorMsg = ''; + this._editorMsgKind = ''; // '' | 'ok' | 'err' | 'warn' + this._pendingRestartHint = false; // set true after save; cleared after restart-now } EvmDetailCard.prototype.mount = function (parent) { @@ -95,6 +129,12 @@ if (self._destroyed) { return; } var d = (env && env.result) || (env && env.data) || env || {}; self._lastMiner = d.miner || null; + self._lastState = (d && d.state) || null; + // v0.5.228 — never rebuild the DOM while the operator is mid-edit + // (would wipe their typed input). The latest data is stashed in + // _lastMiner/_lastState and will be used by the next render after + // the editor exits. + if (self._editingReward) { return; } self._render(d); }).catch(function (err) { if (self._destroyed) { return; } @@ -110,14 +150,53 @@ /** @private */ EvmDetailCard.prototype._render = function (d) { var miner = d && d.miner ? d.miner : null; - var mining = !!(miner && miner.enabled); var evmAddr = miner && miner.evmKeystoreAddr ? miner.evmKeystoreAddr : null; var rewardAddr = miner && miner.rewardAddress ? miner.rewardAddress : null; + var chainState = (d && d.state) || this._lastState; + var chainAlive = isChainAlive(chainState); - var tag = mining - ? 'Mining on' - : 'Mining off'; + // v0.5.228d (audit F4/F5/F6) — read the DERIVED validator state + // from the new miner.chainState field (now returned by GET + // /chains/:id alongside miner.enabled). Pre-228d the header tag + // read cfg.miner.enabled which is the on-disk operator-set + // value; after a real Council binding the spawn path's + // in-memory override of miner.enabled is NOT persisted, so the + // disk value stayed stale and the dashboard tag could disagree + // with the live badge in Settings. miner.chainState comes from + // the same chainStateFromRole helper the /system/council-status + // endpoint uses, so both surfaces always agree. + // + // Fallback to the legacy miner.enabled if chainState is missing + // (older backend version, mainchain RPC down, fresh install + // before first detect). This keeps the tag rendering even when + // the derived data is unavailable. + var validatorState = (miner && miner.chainState) ? miner.chainState : null; + if (!validatorState && miner) { + validatorState = miner.enabled ? 'on-duty' : 'inactive'; + } + var mining = validatorState === 'on-duty'; + var TAG_LABELS = { + 'on-duty': { cls: 'success', text: 'Validator · On-duty' }, + 'standby': { cls: 'warn', text: 'Validator · Standby' }, + 'inactive': { cls: 'muted', text: 'Validator · Inactive' }, + 'unknown': { cls: 'muted', text: 'Validator · Detecting' }, + 'follower': { cls: 'muted', text: 'Validator · Follower' }, + }; + var tagMeta = TAG_LABELS[validatorState] || TAG_LABELS.inactive; + var tag = '' + + tagMeta.text + ''; + // v0.5.228 patch — re-ordered so reward address (operator-supplied, + // the thing they configured at setup) shows FIRST, and the auto- + // generated EVM account second. Pre-patch the operator's eye landed + // on "EVM account: —" (which is blank only because this node isn't + // mining yet — the geth keystore is lazily created on first mining + // start) and read "no mining address". The reward address — the + // one they actually entered — was below the fold of the value + // stack. Reordering + tighter EVM-account hint copy resolves it. + var evmAccountHint = mining + ? 'Local geth keystore account this node mines with. Auto-generated; never operator-supplied.' + : 'Local geth keystore account — only created the first time this node mines. Blank here doesn\'t affect rewards (those go to the address below).'; var html = '' + '
' + '
' @@ -125,15 +204,18 @@ + '
' + (mining ? 'This node produces blocks for the sidechain. Block rewards are credited to the reward address below.' - : 'This node is running as a sync-only node (not producing blocks). Mining is configured in Settings.') + : 'This node is a follower (not producing blocks). The reward address stays configured for if you ever turn mining on — followers don\'t earn EVM block rewards.') + '
' + '
' + tag + '
' + '
' + '
' - + this._addrRow('EVM account', 'The node’s geth keystore account on this chain.', evmAddr, 'evm-account') - + this._addrRow('Block reward address', 'Where this node’s block rewards are credited.', rewardAddr, 'reward') + + this._addrRow('Block reward address', + 'Where this node\'s block rewards are credited (geth flag --pbft.miner.address). ' + + 'You can change this safely; the new address applies on next chain start.', + rewardAddr, 'reward', { editable: true }) + + this._addrRow('EVM account', evmAccountHint, evmAddr, 'evm-account', { editable: false }) + '
' + '
' + '
' @@ -146,7 +228,12 @@ // appends (not replaces) — re-running it on unchanged DOM would stack // duplicate copy buttons. Every render-relevant value (mining flag, // both addresses via data-copy-value + is-empty) is in `html`. - if (html === this._lastHtml) { return; } + if (html === this._lastHtml) { + // Still need to refresh the post-save editor msg / restart-now + // hint without rebuilding the whole card. + this._refreshEditorBanner(chainAlive); + return; + } this._lastHtml = html; this.root.innerHTML = html; @@ -174,16 +261,272 @@ })(slots[i]); } } + + // v0.5.228 — wire the reward-address Edit button + render any + // post-save editor banner / restart-now affordance. + this._wireRewardEditor(); + this._refreshEditorBanner(chainAlive); + }; + + /** @private — wire the Edit button on the reward row. + * Clicking it swaps the value cell for an inline editor (input + + * Save + Cancel + status line). The card-level _editingReward flag + * pauses background re-renders so the operator's typed input is + * never wiped under their fingers by a 60s poll. */ + EvmDetailCard.prototype._wireRewardEditor = function () { + var self = this; + var editBtn = this.root.querySelector('[data-edit="reward"]'); + if (!editBtn) { return; } + editBtn.addEventListener('click', function () { self._enterRewardEdit(); }); + }; + + /** @private — render or remove the post-save banner that tells the + * operator a restart is required to apply the new address. Idempotent + * so we can call it from both the dedup-skip and full-rebuild paths. */ + EvmDetailCard.prototype._refreshEditorBanner = function (chainAlive) { + // Banner lives at the top of the card body so it sits near the + // addresses without disturbing the row layout. + var body = this.root.querySelector('.enm-section-card-body'); + if (!body) { return; } + var existing = body.querySelector('.enm-evm-reward-banner'); + if (!this._pendingRestartHint) { + if (existing) { existing.parentNode.removeChild(existing); } + return; + } + var html = '' + + '
' + + '
' + + (chainAlive + ? 'Reward address saved. The currently running chain still uses the previous address — restart it to apply the change.' + : 'Reward address saved. The new address will be used the next time this chain is started.') + + '
' + + (chainAlive + ? '' + : '') + + '
'; + if (existing) { + existing.outerHTML = html; + } else { + body.insertAdjacentHTML('afterbegin', html); + } + var self = this; + var restartBtn = body.querySelector('[data-action="reward-restart"]'); + if (restartBtn) { + restartBtn.addEventListener('click', function () { self._restartChainAfterSave(restartBtn); }); + } + var dismissBtn = body.querySelector('[data-action="reward-dismiss"]'); + if (dismissBtn) { + dismissBtn.addEventListener('click', function () { + self._pendingRestartHint = false; + self._refreshEditorBanner(false); + }); + } + }; + + /** @private — swap the reward value cell with an inline editor. */ + EvmDetailCard.prototype._enterRewardEdit = function () { + if (this._editingReward) { return; } // already open + this._editingReward = true; + this._editingValue = (this._lastMiner && this._lastMiner.rewardAddress) || ''; + this._editorMsg = ''; + this._editorMsgKind = ''; + this._renderRewardEditor(); + }; + + /** @private — close the editor without saving. */ + EvmDetailCard.prototype._exitRewardEdit = function () { + this._editingReward = false; + this._editingValue = ''; + this._editorMsg = ''; + this._editorMsgKind = ''; + // Force a re-render of the row by invalidating the dedup cache; the + // next _render() call from a poll OR our immediate trigger below + // will rebuild the row with the latest backend value. + this._lastHtml = null; + this._poll(); + }; + + /** @private — render the inline editor over the reward row. We keep + * the rest of the card intact and only replace the row contents. */ + EvmDetailCard.prototype._renderRewardEditor = function () { + var row = this.root.querySelector('.enm-detail-addr-row[data-key="reward"]'); + if (!row) { return; } + row.classList.add('is-editing'); + // Preserve the row head (label + hint); only swap the value stack. + var stack = row.querySelector('.enm-detail-value-stack'); + if (!stack) { return; } + var v = this._editingValue || ''; + var inputId = 'enm-evm-reward-edit-' + Math.random().toString(36).slice(2, 8); + var msgClass = this._editorMsgKind ? (' is-' + this._editorMsgKind) : ''; + stack.outerHTML = '' + + '
' + + '' + + '' + + '
' + + '' + + '' + + '
' + + '
' + + esc(this._editorMsg || '') + + '
' + + '
'; + + var input = row.querySelector('.enm-detail-edit-input'); + var saveBtn = row.querySelector('[data-action="reward-save"]'); + var cancelBtn = row.querySelector('[data-action="reward-cancel"]'); + var self = this; + if (input) { + input.addEventListener('input', function () { self._editingValue = input.value; }); + input.addEventListener('keydown', function (e) { + if (e.key === 'Enter') { e.preventDefault(); self._saveReward(saveBtn); } + else if (e.key === 'Escape') { e.preventDefault(); self._exitRewardEdit(); } + }); + // Focus + select-all so the operator can immediately overwrite or copy-paste. + setTimeout(function () { + if (self._destroyed) { return; } + try { input.focus(); input.select(); } catch (_) {} + }, 0); + } + if (cancelBtn) { cancelBtn.addEventListener('click', function () { self._exitRewardEdit(); }); } + if (saveBtn) { saveBtn.addEventListener('click', function () { self._saveReward(saveBtn); }); } + }; + + /** @private — validate + PUT the new reward address. */ + EvmDetailCard.prototype._saveReward = function (saveBtn) { + var self = this; + var raw = String(this._editingValue || '').trim(); + // Empty value clears the operator-supplied reward address (rewards + // then fall back to the geth keystore default per FIX-C12b). Treat + // explicit-empty as a valid intent. + var payload; + if (raw === '') { + payload = ''; + } else { + var check = (root.enmEthAddress && typeof root.enmEthAddress.check === 'function') + ? root.enmEthAddress.check(raw) + : null; + if (!check) { + this._editorMsg = 'Address validator unavailable. Refresh the page.'; + this._editorMsgKind = 'err'; + this._renderRewardEditor(); + return; + } + if (!check.ok) { + if (check.error === 'missing_0x') { + this._editorMsg = 'Missing "0x" prefix. Suggested: ' + check.suggested; + } else if (check.error === 'format') { + this._editorMsg = 'Not a valid Ethereum address (need 0x + 40 hex characters).'; + } else if (check.error === 'eip55_checksum') { + // Soft offer the corrected form rather than block. + this._editorMsg = 'EIP-55 checksum mismatch. Did you mean ' + check.suggested + ' ?'; + } else { + this._editorMsg = 'Invalid address.'; + } + this._editorMsgKind = 'err'; + this._renderRewardEditor(); + return; + } + payload = check.normalized; + } + // Spinner + disable while in flight. + var doSave = function () { + return self.api.put('/chains/' + self.chainId + '/class-b-config', { + miner: { rewardAddress: payload }, + }).then(function () { + if (self._destroyed) { return; } + self._editingReward = false; + self._editorMsg = ''; + self._editorMsgKind = ''; + self._pendingRestartHint = true; // surfaces the banner on next render + // Refresh: pull updated cfg.miner; the banner will mention + // restart-required iff the chain is currently alive. + self._lastHtml = null; + self._poll(); + }).catch(function (err) { + if (self._destroyed) { return; } + var msg = (err && err.body && err.body.error && err.body.error.message) + || (err && err.message) + || 'Save failed.'; + self._editorMsg = msg; + self._editorMsgKind = 'err'; + // Re-render editor so the operator can correct + retry. + self._renderRewardEditor(); + }); + }; + if (typeof root.enmRunOnce === 'function' && saveBtn) { + root.enmRunOnce(saveBtn, 'Saving…', doSave); + } else { + doSave(); + } + }; + + /** @private — call POST /chains/:id/restart from the post-save banner. */ + EvmDetailCard.prototype._restartChainAfterSave = function (btn) { + var self = this; + var doRestart = function () { + return self.api.post('/chains/' + self.chainId + '/restart').then(function () { + if (self._destroyed) { return; } + self._pendingRestartHint = false; + self._lastHtml = null; + self._poll(); + }).catch(function (err) { + if (self._destroyed) { return; } + // Surface the failure in the banner area without blowing + // away the card. + var body = self.root.querySelector('.enm-section-card-body'); + if (!body) { return; } + var existing = body.querySelector('.enm-evm-reward-banner'); + var msg = (err && err.body && err.body.error && err.body.error.message) + || (err && err.message) || 'Restart failed.'; + if (existing) { + existing.innerHTML = '' + + '
' + + 'Restart failed: ' + esc(msg) + + '
' + + ''; + var retry = existing.querySelector('[data-action="reward-restart"]'); + if (retry) { + retry.addEventListener('click', function () { self._restartChainAfterSave(retry); }); + } + } + }); + }; + if (typeof root.enmRunOnce === 'function' && btn) { + root.enmRunOnce(btn, 'Restarting…', doRestart); + } else { + doRestart(); + } }; /** @private — stacked label + hint + monospace address value + copy button. * When the value is unknown we render "—" and omit the copy button (nothing - * to copy) — never a fabricated address. */ - EvmDetailCard.prototype._addrRow = function (label, hint, value, key) { + * to copy) — never a fabricated address. + * + * v0.5.228 — opts.editable=true adds an Edit button to the value stack; + * the row also gets data-key so the inline editor can find it on swap. + * "Set address" is the empty-state label so an unset row is still a + * discoverable affordance, not a dead-end "—". */ + EvmDetailCard.prototype._addrRow = function (label, hint, value, key, opts) { var copySlot = value ? '' : ''; - return '
' + var editable = opts && opts.editable === true; + var editSlot = ''; + if (editable) { + var editLabel = value ? 'Edit' : 'Set address'; + editSlot = '' + + ''; + } + return '
' + '
' + '' + esc(label) + '' + '' + esc(hint) + '' @@ -191,6 +534,7 @@ + '
' + '' + copySlot + + editSlot + '
' + '
'; }; diff --git a/src/backend/apps/elastos-node-manager/js/components/log-viewer.js b/src/backend/apps/elastos-node-manager/js/components/log-viewer.js index ed7c869a5b..3e8f5cfc2b 100644 --- a/src/backend/apps/elastos-node-manager/js/components/log-viewer.js +++ b/src/backend/apps/elastos-node-manager/js/components/log-viewer.js @@ -289,8 +289,12 @@ this._capBanner = null; // Search state. - this._searchRaw = ''; - this._searchSpec = parseSearchPattern(''); + // v0.5.218 audit Phase 4 (AUDIT-FLOW-LV03, P2) — persist last search + // via enmPrefs so it survives chain switch / tab remount. + this._searchRaw = (root.enmPrefs && typeof root.enmPrefs.get === 'function') + ? root.enmPrefs.get('log-viewer:search', '') + : ''; + this._searchSpec = parseSearchPattern(this._searchRaw); this._searchDebounce = null; this._matchCount = 0; @@ -310,7 +314,14 @@ // `data-lvl` and `hidden` per the current filter; toggling a // chip flips _lvlFilters[lvl] then sweeps. Counts live on each // chip's inline . - this._lvlFilters = { error: true, warn: true, info: true, debug: false }; + // v0.5.218 audit Phase 4 (AUDIT-FLOW-LV02, P2) — load from + // sessionStorage so the operator's "DEBG hidden" preference + // survives chain-switch / tab-remount. Pre-v0.5.218 every + // remount reset DEBG visible and the operator had to re-hide. + var DEFAULT_LVL_FILTERS = { error: true, warn: true, info: true, debug: false }; + this._lvlFilters = (root.enmPrefs && typeof root.enmPrefs.get === 'function') + ? root.enmPrefs.get('log-viewer:lvl-filters', DEFAULT_LVL_FILTERS) + : DEFAULT_LVL_FILTERS; this._lvlChips = {}; // populated by _renderShell this._lvlCounts = { error: 0, warn: 0, info: 0, debug: 0 }; @@ -407,6 +418,10 @@ searchInput.className = 'enm-log-search-input'; searchInput.placeholder = 'Filter… (or /regex/)'; searchInput.setAttribute('aria-label', 'Filter visible log lines'); + // v0.5.218 audit Phase 4 — prefill persisted search. + if (this._searchRaw) { + searchInput.value = this._searchRaw; + } searchInput.addEventListener('input', function () { self._scheduleSearchUpdate(searchInput.value); }); @@ -701,6 +716,12 @@ LogViewer.prototype._scheduleSearchUpdate = function (raw) { var self = this; this._searchRaw = raw; + // v0.5.218 audit Phase 4 — persist alongside the debounce so the + // operator's search survives remount. + if (root.enmPrefs && typeof root.enmPrefs.set === 'function') { + try { root.enmPrefs.set('log-viewer:search', raw); } + catch (_) { /* silent */ } + } if (this._searchDebounce) { clearTimeout(this._searchDebounce); } @@ -763,6 +784,11 @@ LogViewer.prototype._toggleLevel = function (lvl) { if (!Object.prototype.hasOwnProperty.call(this._lvlFilters, lvl)) { return; } this._lvlFilters[lvl] = !this._lvlFilters[lvl]; + // v0.5.218 audit Phase 4 — persist so the choice survives remount. + if (root.enmPrefs && typeof root.enmPrefs.set === 'function') { + try { root.enmPrefs.set('log-viewer:lvl-filters', this._lvlFilters); } + catch (_) { /* private mode etc. — silent */ } + } var chip = this._lvlChips[lvl]; if (chip) { chip.setAttribute('aria-pressed', String(this._lvlFilters[lvl])); diff --git a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js index 9aaec8b495..e5a3beb74b 100644 --- a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js +++ b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js @@ -98,16 +98,28 @@ disabled: 'Disabled', unconfigured: 'Not configured', }; - // v0.5.203 — backwards-compat: backend may still return v1 ('running'/ - // 'healthy') from older bundles during rollout, so normalize first. + // v0.5.219 audit Phase 5 (XFLOW-04 / XFLOW-16) — these helpers now + // DELEGATE to the canonical root.enmStateVocab helper (extracted in + // utils-state-vocab.js) so this file no longer maintains a parallel + // state-vocabulary mapping. Pre-v0.5.219 STATE_LABEL_V2 here was + // missing 'recovering' / 'error' / 'loading' (any backend addition + // would silently fall through to the raw state name). Inline stubs + // preserve the wrapper signatures the rest of this file calls so the + // migration is local. Defensive fallback preserved if utils-state- + // vocab.js failed to load. function normalizeStateV2(state) { + if (root.enmStateVocab && typeof root.enmStateVocab.normalize === 'function') { + return root.enmStateVocab.normalize(state); + } if (!state) return 'unconfigured'; - // Legacy state names → new vocabulary mapping. - if (state === 'running') return 'synced'; // v1 'running' was used for any alive past-grace chain incl. synced + syncing - if (state === 'healthy') return 'synced'; // chains.js v1 'healthy' for class C/D alive - return state; // synced / syncing / starting / stalled / stopped / disabled / unconfigured + if (state === 'running') return 'synced'; + if (state === 'healthy') return 'synced'; + return state; } function stateLabelForV2(state) { + if (root.enmStateVocab && typeof root.enmStateVocab.stateLabel === 'function') { + return root.enmStateVocab.stateLabel(state); + } var v2 = normalizeStateV2(state); return tFb('chain_state_v2.' + v2, STATE_LABEL_V2[v2] || v2); } @@ -190,6 +202,12 @@ // chain-state event doesn't have to wait for the next usage tick. this._lastUsage = null; this._usagePollHandle = null; + // v0.5.225 audit Phase 21 — provider-cap (cgroup limits) state. + // Auto-fetched on mount; surfaces a banner only when a tight cap + // is detected (cpu<4 cores OR mem<8 GB). Well-resourced operators + // never see it. + this._hostLimits = null; + this._constrainedDismissed = false; } EnmMultiChainOverviewPane.prototype.mount = function (parent) { @@ -203,6 +221,21 @@ this._subscribe(); this._fetchInitial(); this._startUsagePoll(); + // v0.5.225 audit Phase 21 — fire-and-forget probe for cgroup limits. + // Cached 60s server-roundtrip-free after first hit. Renders nothing + // when no cap is detected (the typical bare-metal case). + var self = this; + if (root.enmHostLimits && typeof root.enmHostLimits.fetch === 'function') { + root.enmHostLimits.fetch(this.api).then(function (limits) { + if (self._destroyed) { return; } + self._hostLimits = limits; + if (limits && limits.isConstrained && self._lastSnap) { + // Force a re-render so the banner appears on first load. + self._lastHtml = null; + self._render(self._lastSnap); + } + }); + } }; EnmMultiChainOverviewPane.prototype.destroy = function () { @@ -327,6 +360,21 @@ if (self._destroyed) { return; } self._renderError((err && err.message) || 'Network error'); }); + // v0.5.229d (P3 audit fix) — also fetch /system/identity to know + // the operator's CR Council role. Stashed on the instance and + // read by _summaryLineV2 to prepend a role-aware prefix to the + // existing "X synced · Y total" status line. Best-effort — if + // /system/identity fails, _summaryLineV2 silently falls back to + // the pre-229d format. + this.api.get('/system/identity').then(function (env) { + if (self._destroyed) { return; } + var d = (env && env.result) || (env && env.data) || env || {}; + self._lastIdentity = d; + // Trigger a re-render if we already have a snapshot — the + // identity arrived after the chain data, the prefix needs + // to land in the next paint. + if (self._lastSnap) { self._render(self._lastSnap); } + }).catch(function () { /* graceful degrade — leave _lastIdentity null */ }); }; /** @private */ @@ -387,6 +435,11 @@ escapeHtml(this._summaryLineV2(snap)), '

', '', + // v0.5.225 audit Phase 21 — provider-cap banner. Only renders + // when /system/host-limits reports a tight cap AND operator + // hasn't dismissed it. Auto-detected; opt-in per operator + // directive 2026-05-25. + this._constrainedHostBannerHtml(), // v0.5.204 — sticky banner shown when ≥1 chain is in 'starting' // for > STARTUP_BANNER_THRESHOLD_SEC. Reassures the operator // that long warm-ups are expected + warns NOT to restart. @@ -401,16 +454,113 @@ ]; var hasRows = false; var self = this; - CLASS_ORDER.forEach(function (k) { + + // v0.5.228 — visual hierarchy rewrite. Operator directive 2026-05-27: + // "multi chain looks very ugly honestly". Pre-228 rendered the 8 + // services as 4 flat sections with identical row treatment — the + // mainchain (the actual node) looked the same as a satellite + // oracle, and there was no visual link between an EVM and its + // companion oracle. The new structure matches the "one Council + // node, many services" mental model the operator reinforced this + // week (oracle pairing, arbiter pairing): + // + // 1. Main chain as a HERO card at the top (accent ring, larger + // typography, prominent metrics) — it IS the node. + // 2. "EVM sidechains" group with one CARD per EVM that nests + // its companion oracle visually inside. The card reads as + // one functional unit (the cross-chain bridge for that EVM). + // 3. Arbiter as a compact card at the bottom — service-tier + // treatment, not the operator's focus. + // 4. Orphan oracles + classes E/? fall back to the old flat + // rendering so unusual installs still surface every service. + // + // Click routing stays per-row: each routable LI keeps the + // .enm-overview-row class with its own data-chain-id, so the + // existing event handler resolves the right destination by + // closest('.enm-overview-row'). + var mainchain = (byClass['A'] || [])[0] || null; + var evmChains = byClass['B'] || []; + var oracles = byClass['C'] || []; + var arbiters = byClass['D'] || []; + + if (mainchain) { + hasRows = true; + html.push('
'); + html.push('
    '); + html.push(self._rowHtml(mainchain, { variant: 'hero' })); + html.push('
'); + html.push('
'); + } + + if (evmChains.length > 0) { + hasRows = true; + html.push('
'); + html.push('

' + + escapeHtml(tFb('overview_pane.evm_group_heading', 'EVM sidechains')) + + '

'); + html.push('
'); + evmChains.forEach(function (evm) { + var oracle = null; + for (var i = 0; i < oracles.length; i++) { + if (oracles[i].parentChainId === evm.chainId) { + oracle = oracles[i]; + break; + } + } + html.push('
'); + html.push('
    '); + html.push(self._rowHtml(evm, { variant: 'evm' })); + if (oracle) { + html.push(self._rowHtml(oracle, { variant: 'oracle-nested' })); + } + html.push('
'); + html.push('
'); + }); + html.push('
'); + html.push('
'); + } + + // Orphan oracles (parent missing from snap — defensive). Renders + // under its own heading so the operator can still see + act on it. + var orphanOracles = oracles.filter(function (o) { + for (var i = 0; i < evmChains.length; i++) { + if (evmChains[i].chainId === o.parentChainId) { return false; } + } + return true; + }); + if (orphanOracles.length > 0) { + hasRows = true; + html.push('
'); + html.push('

' + + escapeHtml(tFb('overview_pane.orphan_oracles_heading', 'Oracles (parent chain not configured)')) + + '

'); + html.push('
    '); + orphanOracles.forEach(function (c) { html.push(self._rowHtml(c)); }); + html.push('
'); + html.push('
'); + } + + if (arbiters.length > 0) { + hasRows = true; + html.push('
'); + html.push('
    '); + arbiters.forEach(function (c) { + html.push(self._rowHtml(c, { variant: 'arbiter' })); + }); + html.push('
'); + html.push('
'); + } + + // Fallback rendering for any other class (E SPV module, unknown) + // so the operator never loses sight of a configured service. + ['E', '?'].forEach(function (k) { var rows = byClass[k]; if (!rows || rows.length === 0) { return; } hasRows = true; - html.push('
'); - html.push('

' + escapeHtml(classLabelFor(k)) + '

'); + html.push('
'); + html.push('

' + escapeHtml(classLabelFor(k)) + '

'); html.push('
    '); - rows.forEach(function (c) { - html.push(self._rowHtml(c)); - }); + rows.forEach(function (c) { html.push(self._rowHtml(c)); }); html.push('
'); html.push('
'); }); @@ -457,6 +607,21 @@ self._routeToChain(row.dataset.chainId); }); }); + // v0.5.225 audit Phase 21 — constrained-host banner dismiss. + // Dismissal persists for the session (this._constrainedDismissed + // flag, not localStorage) so a page reload re-shows the banner + // — operator should be reminded each session their host is + // constrained. + var constrainedDismiss = this._root.querySelector('[data-action="dismiss-constrained-banner"]'); + if (constrainedDismiss) { + var self_cb = this; + constrainedDismiss.addEventListener('click', function () { + if (self_cb._destroyed) { return; } + self_cb._constrainedDismissed = true; + self_cb._lastHtml = null; + if (self_cb._lastSnap) { self_cb._render(self_cb._lastSnap); } + }); + } // v0.5.204 — wire dismiss button on the startup banner. Remembers // which chainIds are dismissed; banner re-shows when a NEW chain // enters starting state (handled in _startupBannerHtml's known-set @@ -492,10 +657,19 @@ * values are real (from the Phase 1-enriched /council/overview); when a value * is genuinely unknown (e.g. height before RPC warms) we show an honest * "height pending…", never a guess. */ - EnmMultiChainOverviewPane.prototype._rowHtml = function (c) { + EnmMultiChainOverviewPane.prototype._rowHtml = function (c, opts) { // v0.5.203 — normalize state through the new vocabulary so a backend // returning legacy 'running' / 'healthy' (during rollout) still maps // to a styled chip. + // v0.5.228 — opts.variant adds a modifier class so the same markup + // can render at different visual weights: + // 'hero' — mainchain at the top of the overview (large) + // 'evm' — EVM sidechain inside its grouped card + // 'oracle-nested' — oracle inside its parent's grouped card (small) + // 'arbiter' — arbiter compact footer card + // undefined — default flat-row look (orphans, fallback) + // Variants are visual only; the data + click routing are identical. + var variant = opts && opts.variant ? opts.variant : null; var v2State = normalizeStateV2(c.state); var stateClass = 'state-' + escapeAttr(v2State); var uptime = c.uptimeSec != null ? formatUptime(c.uptimeSec) : ''; @@ -509,7 +683,13 @@ : ''; var stateChipAttrs = ' class="enm-overview-state ' + stateClass + '"'; if (stateHint) { stateChipAttrs += ' title="' + escapeAttr(stateHint) + '"'; } - return '
  • ' + '' + '
    ' @@ -520,14 +700,57 @@ + '
    ' + this._metaHtmlV2(c) + '
    ' + '
    ' + this._metricsHtml(c) + '
    ' + '
    ' - + '' - + uptimeHtml + + (isCompact ? '' : '') + + (isCompact ? '' : uptimeHtml) + this._actionsHtml(c) + '' + '
  • '; }; + /** + * v0.5.225 audit Phase 21 — constrained-host banner. + * Surfaces only when cgroup limits are tight AND operator hasn't + * dismissed. Operator directive 2026-05-25 ("budget features should + * not be for everyone") → auto-detected + opt-in dismissal. Well- + * resourced operators never see this. + * @private + */ + EnmMultiChainOverviewPane.prototype._constrainedHostBannerHtml = function () { + if (this._constrainedDismissed) { return ''; } + var hl = this._hostLimits; + if (!hl || !hl.isConstrained) { return ''; } + var capStr = ''; + if (typeof hl.cpuCapCores === 'number' && hl.cpuCapCores < 4) { + capStr = hl.cpuCapCores + ' CPU core' + (hl.cpuCapCores === 1 ? '' : 's'); + } + if (typeof hl.memoryCapGb === 'number' && hl.memoryCapGb < 8) { + capStr += (capStr ? ' + ' : '') + hl.memoryCapGb + ' GB RAM'; + } + // Source label ("cgroup-v2" / "cgroup-v1") is for the title attribute + // (debug); operator-facing copy stays plain English. + var sourceTitle = 'Detected via ' + (hl.source || 'cgroup'); + return '' + + '
    ' + + '' + + '
    ' + + '
    Budget-tier host detected
    ' + + '
    ' + + 'This host is limited to ' + escapeHtml(capStr) + '. ' + + 'A full Council install (4 chains + arbiter + 3 oracles) typically needs ' + + '4+ CPU cores during EVM sync; on a budget VPS tier (common across most ' + + 'shared / low-cost cloud providers) the provider may pause your node when ' + + 'usage spikes. Consider enabling stage-sync in ' + + 'Settings → Advanced → Stage-sync ' + + '(starts EVM chains one at a time so sync CPU spikes are sequential, not concurrent).' + + '
    ' + + '
    ' + + '' + + '
    '; + }; + // v0.5.206 — show the banner almost immediately. v0.5.204 used 120s which // missed the most common case: operator just triggered a deploy/restart, // looks at the overview, sees ALL chains orange "STARTING" and panics @@ -874,24 +1097,89 @@ EnmMultiChainOverviewPane.prototype._onAction = function (kind, chainId, btn) { if (!kind || !chainId || !btn) { return; } if (this._pendingAction) { return; } // one action at a time, pane-wide + var self = this; var displayName = chainNameFor(chainId, null); + // v0.5.217 audit Phase 3 (AUDIT-FLOW-O04 + O05, P2) — replace + // native browser confirm() with enmDestructiveModal. Closes + // O04 (native dialog UX inconsistency) AND O05 (ambiguous + // "interrupted" copy that confused operators about whether the + // chain ends in STOPPED or RESTARTS). The modal's body copy is + // now action-specific + quantifies the impact. if (kind === 'stop' || kind === 'restart') { - var confirmMsg = tFb( - 'overview_pane.action_confirm', - 'Are you sure you want to {action} {chainName}? In-progress sync work will be interrupted.', - { action: kind, chainName: displayName }); - if (typeof root.confirm === 'function' && !root.confirm(confirmMsg)) { return; } + if (typeof root.enmDestructiveModal !== 'function') { + // Defensive: modal failed to load — fall back to native. + var fb = 'Are you sure you want to ' + kind + ' ' + displayName + '?'; + if (typeof root.confirm === 'function' && !root.confirm(fb)) { return; } + this._runAction(kind, chainId, btn, displayName); + return; + } + var bodyCopy = (kind === 'stop') + ? 'The chain process will stop and the node will no longer produce blocks or respond to RPC. Start it again from this card when ready. No chain data is lost.' + : 'The chain will stop, then start again automatically (typical pause: 20-60 seconds). Sync resumes from the current block — no data is lost.'; + root.enmDestructiveModal({ + title: (kind === 'stop' ? 'Stop ' : 'Restart ') + displayName + '?', + body: bodyCopy, + ackLabel: (kind === 'stop') ? ('I understand this stops ' + displayName) : null, + cooldownSec: (kind === 'stop') ? 2 : 1, + confirmLabel: (kind === 'stop' ? 'Stop ' : 'Restart ') + displayName, + confirmKind: (kind === 'stop') ? 'danger' : 'primary', + notifications: self.notifications, + onConfirm: function () { + self._runAction(kind, chainId, btn, displayName); + return Promise.resolve(); + }, + }); + return; } + // Non-destructive (start) — no confirm needed. + this._runAction(kind, chainId, btn, displayName); + }; + + /** + * @private — extracted from _onAction so the confirm path + the direct + * (start) path share the same POST + busy-state + 401/409 handling. + * v0.5.217 audit Phase 3. + */ + EnmMultiChainOverviewPane.prototype._runAction = function (kind, chainId, btn, displayName) { this._pendingAction = { chainId: chainId, kind: kind }; var self = this; var glyphSpan = btn.querySelector('span'); var prevGlyph = glyphSpan ? glyphSpan.innerHTML : ''; btn.disabled = true; btn.classList.add('is-busy'); - var pastVerb = ({ start: 'started', stop: 'stopped', restart: 'restarted' })[kind] || kind; + // v0.5.220 audit Phase 6 (XFLOW-01, AUDIT-FLOW-O06) — present- + // progressive verbs replace past-tense (parallel of chain-card._do). + var progressiveVerb = ({ start: 'is starting…', stop: 'is stopping…', restart: 'is restarting…' })[kind] || kind; this.api.post('/chains/' + chainId + '/' + kind).then(function () { if (self.notifications && typeof self.notifications.info === 'function') { - self.notifications.info(displayName + ' ' + pastVerb, ''); + self.notifications.info(displayName + ' ' + progressiveVerb, ''); + } + // v0.5.220 audit Phase 6 (XFLOW-02, AUDIT-FLOW-O07) — startup + // watchdog for Start/Restart from the overview. If the chain + // hasn't reached alive in 90s, fire a warning. Predicate + // reads from the cached overview snapshot. + if ((kind === 'start' || kind === 'restart') + && typeof root.enmWatchAction === 'function' + && root.enmStateVocab) { + root.enmWatchAction({ + timeoutMs: 90000, + pollMs: 5000, + predicate: function () { + if (self._destroyed) { return true; } + if (!self._lastSnap || !Array.isArray(self._lastSnap.chains)) { return false; } + var c = self._lastSnap.chains.filter(function (x) { return x.chainId === chainId; })[0]; + return c && root.enmStateVocab.isAlive(c.state); + }, + onTimeout: function () { + if (self._destroyed) { return; } + if (self.notifications && typeof self.notifications.warning === 'function') { + self.notifications.warning( + displayName + ' didn\'t reach a running state', + 'The ' + kind + ' completed but the chain is still not alive. Check the chain card and logs.', + ); + } + }, + }); } }).catch(function (err) { if (err && err.status === 401) { return; } // boot path owns re-auth UX @@ -1073,6 +1361,31 @@ var container = this._root.querySelector('.enm-overview-usage'); if (!container) { return; } // initial render hasn't placed it yet container.innerHTML = this._usageCardsHtml(this._lastSnap); + // v0.5.221 audit Phase 8 (XFLOW-12, AUDIT-FLOW-O10/O11/O12) — + // apply threshold-aware styling to the disk/CPU/memory cards. + // Pre-v0.5.221 these cards had no warn/critical visual state; + // operator got NO inline cue when disk was approaching full or + // CPU was saturated. + var u = this._lastUsage || {}; + var apply = root.enmApplyThreshold; + if (typeof apply !== 'function') { return; } + var diskCard = container.querySelector('.enm-usage-card-disk'); + if (diskCard && u.disk && typeof u.disk.freeGb === 'number') { + // freeGb LOW is bad. Default thresholds match the ENM package.json + // enm.warnDiskFreeGb (100) + enm.minDiskFreeGb (50). Backend may + // ship these in a future revision of /system/usage; until then, + // hardcoded matches the package.json declared values. + apply(diskCard, u.disk.freeGb, { warnAt: 100, criticalAt: 50 }); + } + var cpuCard = container.querySelector('.enm-usage-card-cpu'); + if (cpuCard && u.cpu && typeof u.cpu.loadPct === 'number') { + // loadPct HIGH is bad. + apply(cpuCard, u.cpu.loadPct, { warnAt: 80, criticalAt: 95, invert: true }); + } + var memCard = container.querySelector('.enm-usage-card-mem'); + if (memCard && u.memory && typeof u.memory.usedPct === 'number') { + apply(memCard, u.memory.usedPct, { warnAt: 85, criticalAt: 95, invert: true }); + } }; /** @@ -1101,7 +1414,27 @@ } }); bits.push(totals.total + ' total'); - return bits.join(' · '); + var chainsLine = bits.join(' · '); + + // v0.5.229d (P3 audit fix) — prepend a Council-aware role prefix + // when the operator went through the Council install path AND/OR + // is currently a CR Committee member. Pre-229d the summary line + // was BPoS-only chain stats; a Council operator had no overview- + // level signal that ENM was running a Council node. + var id = this._lastIdentity; + if (!id) { return chainsLine; } + var cr = id.crMember || null; + var setupRole = id.setupRole || 'unknown'; + var rolePrefix = ''; + if (cr && cr.isCrMember) { + rolePrefix = 'CR Council · ' + (cr.state || 'Elected'); + if (cr.nickname) { rolePrefix += ' (' + cr.nickname + ')'; } + } else if (setupRole === 'council') { + rolePrefix = 'CR Council install · not currently bound'; + } else if (id.producer && id.producer.state) { + rolePrefix = 'BPoS · ' + id.producer.state; + } + return rolePrefix ? (rolePrefix + ' — ' + chainsLine) : chainsLine; }; /** @private */ diff --git a/src/backend/apps/elastos-node-manager/js/components/node-identity-card.js b/src/backend/apps/elastos-node-manager/js/components/node-identity-card.js index e14d652b38..d6f71463b6 100644 --- a/src/backend/apps/elastos-node-manager/js/components/node-identity-card.js +++ b/src/backend/apps/elastos-node-manager/js/components/node-identity-card.js @@ -103,6 +103,13 @@ NodeIdentityCard.prototype.mount = function (parent) { parent.appendChild(this.root); var self = this; + // v0.5.223 audit Phase 12 (AUDIT-FLOW-NI05, P2) — attach stale + // indicator. Marks fresh on successful poll, stale after 30s of + // failed polls. Pre-v0.5.223 transient errors left the card with + // stale data + no operator-visible signal. + if (typeof root.enmStaleIndicator === 'function') { + this._staleIndicator = root.enmStaleIndicator(this.root, { staleAfterMs: 30000 }); + } this._poll(); if (typeof root.enmUseVisibilityPause === 'function') { this._pollPauser = root.enmUseVisibilityPause( @@ -117,6 +124,10 @@ NodeIdentityCard.prototype.refresh = function () { this._poll(); }; NodeIdentityCard.prototype.destroy = function () { + if (this._staleIndicator && typeof this._staleIndicator.destroy === 'function') { + try { this._staleIndicator.destroy(); } catch (_) { /* idempotent */ } + this._staleIndicator = null; + } this._destroyed = true; if (this._pollPauser) { try { this._pollPauser.stop(); } catch (_) { /* idempotent */ } @@ -139,10 +150,14 @@ var payload = (env && env.data) || env || {}; self._lastPayload = payload; self._render(payload); + if (self._staleIndicator) { self._staleIndicator.markFresh(); } }).catch(function (err) { if (self._destroyed) { return; } // 401-suppress — boot path owns re-auth (alpha.28 batch 60-61). if (err && err.status === 401) { return; } + // v0.5.223 audit Phase 12 — mark stale on non-401 errors so + // operator sees data may not be current. + if (self._staleIndicator) { self._staleIndicator.markStale(); } // Keep the last good render; only fall back to a skeleton if // we never had one. Avoids the card blinking on transient // backend hiccups. @@ -237,35 +252,98 @@ // rather than to SHARE (for first-time registration). var isRegistered = !!(producer && producer.state); + // v0.5.229 (audit 2026-05-27) — Council-mode branch. Council + // operators have a DIFFERENT registration path (CR Council + // election via Essentials + CRCouncilMemberClaimNode TX); the + // word "supernode" is BPoS-specific vocabulary and is wrong + // for Council members. Branch the header subtitle and the + // pubkey hint on isCrMember / setupRole, picking Council + // wording when either is true. + var crMember = data.crMember || null; + var setupRole = data.setupRole || 'unknown'; + var isCouncilContext = (setupRole === 'council') + || !!(crMember && crMember.isCrMember); + var isCouncilBound = !!(crMember && crMember.isCrMember); + var html = ''; // ----- Header ------------------------------------------------ + var subtitle; + if (isCouncilContext) { + // Council operator subtitle. Three variants: bound to current + // Committee, bound to next, or installed-but-unbound (re-claim + // required). + if (isCouncilBound) { + subtitle = 'The consensus-signing identity for this node\'s ' + + 'CR Council seat. Mining + signing activate automatically ' + + 'when the on-chain arbiter slate rotates your slot in. ' + + 'Keep this public key safe — it identifies your seat.'; + } else { + subtitle = 'The consensus-signing identity this node uses on-chain. ' + + 'Bind this public key to your CR Council seat ' + + 'via Elastos Essentials (CRCouncilMemberClaimNode) — once the ' + + 'binding confirms, the chain enrolls your node in the arbiter ' + + 'slate automatically.'; + } + } else if (isRegistered) { + subtitle = 'The consensus-signing identity this node uses on-chain. ' + + 'Block rewards are credited to the Essentials wallet that ' + + 'registered the producer, not to anything shown on this card.'; + } else { + subtitle = 'The consensus-signing identity this node uses on-chain. ' + + 'Paste the public key below into Elastos Essentials ' + + 'when registering as a BPoS producer — the Essentials wallet that ' + + 'signs the registration becomes the producer owner and is where ' + + 'all block rewards are credited.'; + } html += '
    ' + '

    Node identity

    ' + '

    ' - + (isRegistered - ? 'The consensus-signing identity this node uses on-chain. ' - + 'Block rewards are credited to the Essentials wallet that ' - + 'registered the supernode, not to anything shown on this card.' - : 'The consensus-signing identity this node uses on-chain. ' - + 'Paste the public key below into Elastos Essentials ' - + 'when registering as a BPoS supernode — the Essentials wallet that ' - + 'signs the registration becomes the producer owner and is where ' - + 'all block rewards are credited.') + + subtitle + '

    ' + '
    '; // ----- Node public key (only meaningful when keystore exists) ----- + // v0.5.228 — public key is the PRIMARY identity surface. It's what + // gets shared with Essentials, what stakers vote on, and what + // appears on every explorer. The signing address below is + // operationally internal — useful for debugging but never + // share-worthy. We render the pubkey with the --primary modifier + // (larger value font, accent ring, bigger copy button) and the + // signing address with --secondary (smaller, muted, compact) so + // an operator's eye lands on the pubkey first by an order of + // magnitude. if (ks.exists && pubkey) { - var pubkeyPill = isRegistered - ? 'Registered' - : 'Share with Essentials'; - var pubkeyHint = isRegistered - ? 'Save this if you need to migrate the node to a different server — ' + // v0.5.229 — Council-mode pill + hint take precedence over BPoS + // copy when the operator is in a Council context. Council seats + // are higher-tier than BPoS slots on Elastos so we surface the + // Council-specific copy first. + var pubkeyPill; + var pubkeyHint; + if (isCouncilContext) { + if (isCouncilBound) { + pubkeyPill = 'Bound to Council seat'; + pubkeyHint = 'This pubkey is bound to your CR Council seat. Save it if you ' + + 'ever need to migrate the node — restoring keystore.dat preserves ' + + 'this identity, so the Council binding stays intact without a new ' + + 'CRCouncilMemberClaimNode TX.'; + } else { + pubkeyPill = 'Claim via Essentials'; + pubkeyHint = 'Paste this into Essentials → CR Council → Claim node. The ' + + 'CRCouncilMemberClaimNode TX binds this public key to your CR seat; ' + + 'once confirmed, the chain enrolls you in the arbiter slate.'; + } + } else if (isRegistered) { + pubkeyPill = 'Registered'; + pubkeyHint = 'Save this if you need to migrate the node to a different server — ' + 'restoring keystore.dat preserves this identity, so you keep the ' - + 'existing producer registration without re-registering.' - : 'Paste this into Essentials when registering your supernode. The Essentials wallet signing the registration becomes the producer owner.'; - html += '
    ' + + 'existing producer registration without re-registering.'; + } else { + pubkeyPill = 'Share with Essentials'; + pubkeyHint = 'Paste this into Essentials when registering as a BPoS producer. ' + + 'The Essentials wallet signing the registration becomes the producer owner.'; + } + html += '
    ' + '
    ' + 'Node public key' + pubkeyPill @@ -294,7 +372,7 @@ // told us this card "doesn't look nice and shows DPoS v1 // rewards which is not needed" — simpler copy wins. if (ks.exists && addr) { - html += '
    ' + html += '
    ' + '
    ' + 'Node signing address' + 'Internal · do not share' @@ -304,10 +382,6 @@ + '' + '' + '
    ' - + '
    ' - + 'Block rewards from this supernode are paid to the Essentials wallet ' - + 'that registered it, not to this address.' - + '
    ' + '
    '; } diff --git a/src/backend/apps/elastos-node-manager/js/components/peers-panel.js b/src/backend/apps/elastos-node-manager/js/components/peers-panel.js index 5ee59382ba..bd188ea9f7 100644 --- a/src/backend/apps/elastos-node-manager/js/components/peers-panel.js +++ b/src/backend/apps/elastos-node-manager/js/components/peers-panel.js @@ -109,6 +109,12 @@ this._renderLoading(); var self = this; + // v0.5.227 audit Phase 12 (AUDIT-FLOW-PP04, P3) — stale-indicator + // for after-first-success poll failures. Pre-v0.5.227 transient + // poll errors left the panel with stale data + no signal. + if (typeof root.enmStaleIndicator === 'function') { + this._staleIndicator = root.enmStaleIndicator(this._root, { staleAfterMs: 30000 }); + } this._fetch(); if (typeof root.enmUseVisibilityPause === 'function') { this._pauser = root.enmUseVisibilityPause(function () { self._fetch(); }, POLL_INTERVAL_MS); @@ -121,6 +127,10 @@ EnmPeersPanel.prototype.destroy = function () { if (this._destroyed) { return; } this._destroyed = true; + if (this._staleIndicator && typeof this._staleIndicator.destroy === 'function') { + try { this._staleIndicator.destroy(); } catch (_) { /* idempotent */ } + this._staleIndicator = null; + } if (this._pauser) { try { this._pauser.stop(); } catch (_) { /* idempotent */ } this._pauser = null; } if (this._timer) { clearInterval(this._timer); this._timer = null; } if (this._root && this._root.parentNode) { @@ -149,13 +159,20 @@ } else { self._updateStatus(snap); } + if (self._staleIndicator) { self._staleIndicator.markFresh(); } }) .catch(function (err) { if (self._destroyed) { return; } + // v0.5.227 audit Phase 12 — mark stale on transient errors + // so the operator sees the data may not be current. + if (self._staleIndicator) { self._staleIndicator.markStale(); } // Only paint the error state on FIRST load — a transient poll // failure shouldn't blank a panel the operator may be typing in. if (!self._builtOnce) { - self._renderError((err && err.message) || 'Network error'); + var friendly = (typeof root.enmFriendlyError === 'function') + ? root.enmFriendlyError(err) + : ((err && err.message) || 'Network error'); + self._renderError(friendly || 'Network error'); } }); }; diff --git a/src/backend/apps/elastos-node-manager/js/components/settings-tab.js b/src/backend/apps/elastos-node-manager/js/components/settings-tab.js index 3558cc10d1..7599f98463 100644 --- a/src/backend/apps/elastos-node-manager/js/components/settings-tab.js +++ b/src/backend/apps/elastos-node-manager/js/components/settings-tab.js @@ -283,16 +283,114 @@ tag: { kind: 'muted', label: 'Restart to apply' }, }); - var enabledToggle = makeToggleRow({ - initial: !!miner.enabled, - getLabel: function (on) { - return on - ? { title: 'Mining on', sub: 'Produces blocks for this chain and earns the block reward.' } - : { title: 'Mining off', sub: 'Sync-only node — does not produce blocks.' }; - }, - onChange: function () { sec.setDirty(true); }, - }); - sec.body.appendChild(enabledToggle.el); + // v0.5.228 — replace the writable "Mining on/off" toggle with a + // READ-ONLY "Validator status" badge. Mining on an Elastos EVM + // sidechain is not an operator-settable knob: it's derived from + // on-chain producer / Council membership (the chain's PBFT + // engine self-gates Seal() based on the current arbiter slate; + // see EvmSidechainAdapter.detectProducerRole + start, both + // already shipped since v0.5.188). The pre-v228 toggle was + // misleading — clicking it changed cfg.miner.enabled in + // ConfigStore, but EvmSidechainAdapter.start always overwrote + // it before spawn, so the toggle was visible but ineffectual. + // Operator directive 2026-05-27: "node.sh doesn't work like + // that for council nodes — after binding, the chain itself + // recognized it's a council node and the set evm mining + // addresses automatically became mining addresses". + // + // The badge is populated asynchronously from + // GET /api/enm/system/council-status, which exposes the same + // detectProducerRole the spawn path uses. Initial render shows + // a loading state. If the fetch fails or times out, the badge + // falls back to whatever cfg.miner.enabled currently reads as + // (the cached derived value from the last successful spawn). + var statusRow = document.createElement('div'); + statusRow.className = 'enm-classb-validator-row'; + statusRow.setAttribute('role', 'group'); + statusRow.setAttribute('aria-label', 'Validator status'); + var statusBadgeId = 'enm-classb-validator-' + chainId; + statusRow.innerHTML = '' + + '
    ' + + '
    Validator status
    ' + + '
    ' + + 'Derived from the on-chain CR-Council / DPoS arbiter slate. ' + + 'Mining activates automatically when this node\'s public key ' + + 'is bound to a Council seat (via Elastos Essentials) and the ' + + 'current rotation includes it — there is no manual toggle.' + + '
    ' + + '
    ' + + '
    ' + + 'Checking on-chain status…' + + '
    '; + sec.body.appendChild(statusRow); + // Fire the council-status fetch immediately so the badge resolves + // soon after render. Fallback to the cached miner.enabled if the + // endpoint is unreachable (boot path, mainchain still syncing). + (function (badgeId, cid, cachedEnabled) { + self.api.get('/system/council-status').then(function (env) { + if (self._destroyed) { return; } + var data = (env && env.data) || env || {}; + var perChain = (data.chains && data.chains[cid]) || null; + var badge = self.root.querySelector('#' + badgeId); + if (!badge) { return; } + var s = (perChain && perChain.chainState) || 'unknown'; + // Map raw chainState → visible label + badge color. + // 'on-duty' → green "On-duty" + // 'standby' → amber "Standby" + // 'inactive' → gray "Inactive (not in current rotation)" + // 'unknown' → gray "Detecting…" + // 'follower' → gray "Follower (not configured for mining)" + var labelMap = { + 'on-duty': { label: 'On-duty', sub: 'Producing blocks this rotation — rewards land at the address below.' }, + 'standby': { label: 'Standby', sub: 'Bound to a Council seat; in the next rotation\'s arbiter slate.' }, + 'inactive': { label: 'Inactive', sub: 'Not in the current or next arbiter slate. Mining activates automatically when this node\'s public key is on-duty.' }, + 'unknown': { label: 'Detecting', sub: 'Reading mainchain arbiter slate… retry every chain start.' }, + 'follower': { label: 'Follower', sub: 'Chain not configured for mining (no init was run).' }, + }; + var meta = labelMap[s] || labelMap.unknown; + badge.dataset.state = s; + badge.textContent = meta.label; + // Add the explanatory sub-line right after the badge. + var subEl = badge.parentNode.querySelector('.enm-classb-validator-sub'); + if (!subEl) { + subEl = document.createElement('div'); + subEl.className = 'enm-classb-validator-sub'; + badge.parentNode.appendChild(subEl); + } + subEl.textContent = meta.sub; + }).catch(function (err) { + if (self._destroyed) { return; } + if (err && err.status === 401) { return; } + // v0.5.228d (audit F3) — fallback wording. The pre-228d + // label "(cached)" implied the backend had recently + // confirmed this state; in reality the fallback reads + // cfg.miner.enabled from disk, which is the value the + // last successful spawn wrote — could be hours/days + // stale. "(from last spawn)" is honest about the + // source. Real-time state lives on /system/council-status + // which this fallback only runs when we couldn't + // reach. + var badge = self.root.querySelector('#' + badgeId); + if (!badge) { return; } + if (cachedEnabled) { + badge.dataset.state = 'on-duty'; + badge.textContent = 'On-duty (from last spawn)'; + } else { + badge.dataset.state = 'inactive'; + badge.textContent = 'Inactive (from last spawn)'; + } + var subEl = badge.parentNode.querySelector('.enm-classb-validator-sub'); + if (!subEl) { + subEl = document.createElement('div'); + subEl.className = 'enm-classb-validator-sub'; + badge.parentNode.appendChild(subEl); + } + subEl.textContent = 'Could not reach /system/council-status; ' + + 'showing the value from this node\'s last spawn. ' + + 'Live status refreshes on every chain start.'; + }); + }(statusBadgeId, chainId, !!miner.enabled)); var rewardInput = makeInput({ value: miner.rewardAddress || '', placeholder: '0x…40 hex chars', mono: true, ariaLabel: 'Reward address' }); rewardInput.setAttribute('spellcheck', 'false'); @@ -403,31 +501,87 @@ peersCard.body.appendChild(peersMount); parent.appendChild(peersCard.card); - // ---- soft address validation (disable Save on invalid) ---- - var validateEth = function (v) { - v = (v || '').trim(); - if (!v) { return 'empty'; } - if (!/^0x[0-9a-fA-F]{40}$/.test(v)) { return 'bad'; } - return 'ok'; + // ---- v0.5.216 audit Phase 2 (AUDIT-FLOW-B01, P1) — address + // validation now routes through the SHARED root.enmEthAddress + // helper (same source the setup wizard Card 4 uses), so the + // EIP-55 mixed-case hard-block that protects new operators at + // install time also protects operators ROTATING addresses via + // Settings. Pre-v0.5.216 this section had only basic format + // validation — paste a mixed-case address with one char's case + // flipped, save, and future rewards went to a different + // account silently. Now blocked + suggested-correct-case shown + // inline. Closes XFLOW-04 + XFLOW-16 duplication of validateEth. + var ethApi = root.enmEthAddress; + var classifyAddr = function (v) { + var str = (v || '').trim(); + if (!str) { return { kind: 'empty' }; } + if (!ethApi || typeof ethApi.check !== 'function') { + // Defensive fallback if utils-eth failed to load — + // preserves the pre-v0.5.216 format-only check. + return /^0x[0-9a-fA-F]{40}$/.test(str) + ? { kind: 'ok' } + : { kind: 'bad' }; + } + var r = ethApi.check(str); + if (r.ok) { + return r.warn === 'no_keccak' + ? { kind: 'ok-degraded' } + : { kind: 'ok' }; + } + if (r.error === 'eip55_checksum') { + return { kind: 'checksum', suggested: r.suggested }; + } + return { kind: 'bad' }; + }; + // Tiny helper to surface a one-line correction hint inline in + // the row's existing status area. The row's data-validity attr + // also drives any per-row CSS (red border on 'bad'/'checksum'). + var setRowStatus = function (row, msg) { + // Find or create a status span at the foot of the row. + var slot = row.querySelector('.enm-row-status') || (function () { + var s = document.createElement('div'); + s.className = 'enm-row-status'; + s.setAttribute('aria-live', 'polite'); + row.appendChild(s); + return s; + }()); + slot.textContent = msg || ''; + slot.hidden = !msg; }; var refreshValidity = function () { - var r = validateEth(rewardInput.value); - var e = validateEth(evmInput.value); - rewardRow.setAttribute('data-validity', r); - evmRow.setAttribute('data-validity', e); - sec.saveBtn.disabled = (r === 'bad') || (e === 'bad'); + var r = classifyAddr(rewardInput.value); + var e = classifyAddr(evmInput.value); + rewardRow.setAttribute('data-validity', r.kind); + evmRow.setAttribute('data-validity', e.kind); + setRowStatus(rewardRow, r.kind === 'checksum' + ? 'Wrong checksum — did you mean: ' + r.suggested + '?' + : ''); + setRowStatus(evmRow, e.kind === 'checksum' + ? 'Wrong checksum — did you mean: ' + e.suggested + '?' + : ''); + // Disable Save on either field being a definite typo: 'bad' + // (format) or 'checksum' (mixed-case mismatch). 'empty' and + // 'ok-degraded' still allow save — empty is a real signal + // (operator clearing the field to disable mining), and the + // degraded mode means keccak couldn't verify so we default + // to permissive (same as pre-v0.5.216 behavior). + sec.saveBtn.disabled = (r.kind === 'bad' || r.kind === 'checksum') + || (e.kind === 'bad' || e.kind === 'checksum'); }; rewardInput.addEventListener('input', function () { sec.setDirty(true); refreshValidity(); }); evmInput.addEventListener('input', function () { sec.setDirty(true); refreshValidity(); }); refreshValidity(); // ---- save (reads control handles; enmRunOnce guards double-submit) ---- - var controls = { enabled: enabledToggle, reward: rewardInput, evm: evmInput, threads: threadsInput, syncMode: syncSel }; + // v0.5.228 — controls.enabled is intentionally absent. The save + // body below no longer includes miner.enabled — the backend + // derives it from on-chain arbiter slate at every chain start. + var controls = { reward: rewardInput, evm: evmInput, threads: threadsInput, syncMode: syncSel }; sec.saveBtn.addEventListener('click', function () { self._saveClassB(chainId, controls, sec); }); sec.revertBtn.addEventListener('click', function () { - enabledToggle.setValue(!!miner.enabled); + // No enabledToggle to revert — it's a derived read-only badge. rewardInput.value = miner.rewardAddress || ''; evmInput.value = miner.evmKeystoreAddr || ''; threadsInput.value = Number.isInteger(miner.threads) ? miner.threads : 1; @@ -465,9 +619,12 @@ SettingsTab.prototype._saveClassB = function (chainId, controls, sec) { var self = this; var status = sec.statusEl; + // v0.5.228 — miner.enabled removed from the request body. It's + // a derived value (computed at every chain start from on-chain + // arbiter slate), not operator-settable. Sending it from this + // form would be a no-op at best and misleading at worst. var body = { miner: { - enabled: controls.enabled.getValue(), rewardAddress: (controls.reward.value || '').trim(), evmKeystoreAddr: (controls.evm.value || '').trim(), threads: parseInt(controls.threads.value, 10) || 1, @@ -1070,6 +1227,13 @@ { key: 'alerts', glyph: '⚑', label: t('settings.heading_alerts'), build: this._buildAlertsSection }, { key: 'storage', glyph: '◳', label: t('settings.heading_storage'), build: this._buildStorageSection }, { key: 'advanced', glyph: '⚙', label: t('settings.heading_advanced'), build: this._buildAdvancedSection }, + // v0.5.228 — EVM chains (shared). Single surface for editing + // settings that apply across all three EVM sidechains + // (reward address, mining, sync mode). Operator directive + // 2026-05-27 ("the multi EVM shared settings for all services + // isn't there either"). Per-chain overrides still live in + // each chain's dashboard card. + { key: 'evm', glyph: '◧', label: t('settings.heading_evm_shared'), build: this._buildEvmSharedSection }, // beta.3.33 — Danger Zone. Update / chain-resync / uninstall // / nuke. Distinct red-accented styling (.enm-section-danger) // and no Save/Revert pattern — each card is independently @@ -1145,7 +1309,7 @@ // beta.3.19 — Alerts section inserted between Network and Storage // (it's about when-to-notify, sits between the access/network and // the data-at-rest sections). - var SECTION_KEYS = ['access', 'identity', 'security', 'network', 'alerts', 'storage', 'advanced', 'danger']; + var SECTION_KEYS = ['access', 'identity', 'security', 'network', 'alerts', 'storage', 'advanced', 'evm', 'danger']; SettingsTab.prototype._sectionRef = function (key) { return this['_' + key]; }; @@ -1237,6 +1401,12 @@ if (key === 'identity' && typeof this._refreshIdentity === 'function') { this._refreshIdentity(); } + // v0.5.228 — EVM shared tab: re-fetch /chains/{esc,eid,pg} on + // every activation so the values + divergence indicator reflect + // any changes made from per-chain cards since the last visit. + if (key === 'evm' && typeof this._refreshEvmShared === 'function') { + this._refreshEvmShared(); + } }; // ----------------------------------------------------------------- @@ -1477,6 +1647,14 @@ warn.appendChild(warnBody); sec.body.appendChild(warn); + // v0.5.228 — Stage-sync card moved to Settings → Danger Zone + // (operator directive 2026-05-26: the staged-start orchestrator is + // destructive — pins the host at near-full CPU for hours, runs + // per-chain start calls — and must require explicit opt-in via a + // Danger Zone toggle, not auto-reveal based on host detection). + // Previous home: this section, auto-revealed when enmHostLimits. + // isConstrained returned true. New home: Danger Zone sub-card 3b. + // Row 1 — Log level. this._advanced.logLevel = makeSelectWrap({ options: [ @@ -1538,6 +1716,502 @@ return sec.card; }; + // ----------------------------------------------------------------- + // Section: EVM chains (shared) — v0.5.228 + // + // Operator directive 2026-05-27: "the multi EVM shared settings for + // all services isn't there either". Pre-228 every EVM setting was + // per-chain only, so changing one knob (reward address, sync mode) + // across the Council quartet required 3 separate trips into 3 + // separate chain cards. This section is the single source of truth + // for settings that are typically homogeneous across the EVMs. + // + // Data flow: + // - Activation triggers _refreshEvmShared, which fires 3 parallel + // GET /chains/{esc,eid,pg} requests. + // - The response shape includes miner.{rewardAddress,enabled} and + // sync.mode (when present on the cfg). + // - "All three match" → shared input + green "✓ same on all". + // - "Diverged" → input shows nothing (so a save doesn't + // silently overwrite without explicit intent) + // and a warning lists the per-chain values. + // - "Apply" issues 3 sequential PUT /chains/X/class-b-config + // requests; partial failure surfaces ok/fail counts inline so + // the operator can retry just the failed chains from per-chain. + // + // Per-chain overrides (bootnodes, ports, binary version, the + // auto-generated EVM keystore account) still live in the dashboard + // EVM cards — this section is for the homogeneous knobs only. + // ----------------------------------------------------------------- + var EVM_SHARED_CHAINS = ['esc', 'eid', 'pg']; + + SettingsTab.prototype._buildEvmSharedSection = function (t) { + var self = this; + + var card = document.createElement('section'); + card.className = 'enm-section-card enm-section-evm-shared'; + + var head = document.createElement('div'); + head.className = 'enm-section-card-head'; + var icon = document.createElement('div'); + icon.className = 'enm-section-card-icon'; + icon.setAttribute('aria-hidden', 'true'); + icon.textContent = '◧'; + head.appendChild(icon); + var headbody = document.createElement('div'); + headbody.className = 'enm-section-card-headbody'; + var title = document.createElement('div'); + title.className = 'enm-section-card-title'; + title.id = 'enm-section-h-evm'; + title.textContent = t('settings.heading_evm_shared'); + headbody.appendChild(title); + var help = document.createElement('div'); + help.className = 'enm-section-card-help'; + help.textContent = t('settings.evm_shared_intro'); + headbody.appendChild(help); + head.appendChild(headbody); + card.appendChild(head); + + var body = document.createElement('div'); + body.className = 'enm-section-card-body'; + card.appendChild(body); + + this._evmShared = { + card: card, + body: body, + // No section-level save — each row has its own Apply button. + setDirty: function () {}, + // Latest snapshot of {chainId → {rewardAddress, enabled, syncMode}} + // populated by _refreshEvmShared; null until first fetch resolves. + latest: null, + }; + + // --- Reward address row ----------------------------------------- + var rewardCard = _buildDangerCard({ + kind: 'info', + title: t('settings.evm_shared_reward_title'), + help: t('settings.evm_shared_reward_help'), + }); + body.appendChild(rewardCard.el); + var rewardInputId = 'enm-evm-shared-reward-input'; + var rewardInputWrap = document.createElement('div'); + rewardInputWrap.className = 'enm-evm-shared-input-row'; + rewardInputWrap.innerHTML = '' + + '' + + ''; + rewardCard.body.appendChild(rewardInputWrap); + var rewardStatusEl = document.createElement('div'); + rewardStatusEl.className = 'enm-evm-shared-status'; + rewardStatusEl.setAttribute('role', 'status'); + rewardStatusEl.setAttribute('aria-live', 'polite'); + rewardStatusEl.textContent = t('settings.evm_shared_reward_loading'); + rewardCard.body.appendChild(rewardStatusEl); + var rewardBtn = document.createElement('button'); + rewardBtn.type = 'button'; + rewardBtn.className = 'enm-btn enm-btn-primary'; + rewardBtn.textContent = t('settings.evm_shared_reward_apply_btn'); + rewardBtn.disabled = true; // enabled when latest loads + rewardCard.foot.appendChild(rewardBtn); + var rewardInputEl = rewardInputWrap.querySelector('input'); + rewardInputEl.addEventListener('click', function () { + // First click on the input clears the divergence-blocked empty + // state so the operator knows they can type freely. + rewardInputEl.removeAttribute('readonly'); + }); + rewardBtn.addEventListener('click', function () { + self._applyEvmSharedReward(rewardInputEl.value, rewardBtn, rewardStatusEl); + }); + this._evmShared.reward = { + input: rewardInputEl, + status: rewardStatusEl, + btn: rewardBtn, + }; + + // --- Mining state row ------------------------------------------- + // Read-only summary per chain. Bulk mining toggle is intentionally + // deferred — flipping mining is a structural change (validator vs + // follower) that warrants per-chain confirmation, not a bulk swap. + var miningCard = _buildDangerCard({ + kind: 'info', + title: t('settings.evm_shared_mining_title'), + help: t('settings.evm_shared_mining_help'), + }); + body.appendChild(miningCard.el); + var miningGrid = document.createElement('div'); + miningGrid.className = 'enm-evm-shared-mining-grid'; + EVM_SHARED_CHAINS.forEach(function (cid) { + var cell = document.createElement('div'); + cell.className = 'enm-evm-shared-mining-cell'; + cell.dataset.chain = cid; + cell.innerHTML = '' + + '' + _h(cid) + '' + + '—'; + miningGrid.appendChild(cell); + }); + miningCard.body.appendChild(miningGrid); + var miningStatusEl = document.createElement('div'); + miningStatusEl.className = 'enm-evm-shared-status'; + miningStatusEl.setAttribute('role', 'status'); + miningCard.body.appendChild(miningStatusEl); + this._evmShared.mining = { + grid: miningGrid, + status: miningStatusEl, + }; + + // --- Sync mode row ---------------------------------------------- + var syncCard = _buildDangerCard({ + kind: 'info', + title: t('settings.evm_shared_sync_title'), + help: t('settings.evm_shared_sync_help'), + }); + body.appendChild(syncCard.el); + var syncSelectWrap = document.createElement('div'); + syncSelectWrap.className = 'enm-evm-shared-input-row'; + syncSelectWrap.innerHTML = '' + + ''; + syncCard.body.appendChild(syncSelectWrap); + var syncStatusEl = document.createElement('div'); + syncStatusEl.className = 'enm-evm-shared-status'; + syncStatusEl.setAttribute('role', 'status'); + syncStatusEl.setAttribute('aria-live', 'polite'); + syncStatusEl.textContent = t('settings.evm_shared_reward_loading'); + syncCard.body.appendChild(syncStatusEl); + var syncBtn = document.createElement('button'); + syncBtn.type = 'button'; + syncBtn.className = 'enm-btn enm-btn-primary'; + syncBtn.textContent = t('settings.evm_shared_sync_apply_btn'); + syncBtn.disabled = true; + syncCard.foot.appendChild(syncBtn); + var syncSelectEl = syncSelectWrap.querySelector('select'); + syncBtn.addEventListener('click', function () { + self._applyEvmSharedSync(syncSelectEl.value, syncBtn, syncStatusEl); + }); + this._evmShared.sync = { + select: syncSelectEl, + status: syncStatusEl, + btn: syncBtn, + }; + + // --- Per-chain footer note -------------------------------------- + var footer = document.createElement('div'); + footer.className = 'enm-evm-shared-footer-note'; + footer.textContent = t('settings.evm_shared_perchain_footer'); + body.appendChild(footer); + + return card; + }; + + /** + * Fetch /chains/{esc,eid,pg} in parallel and fill the shared + * settings UI based on whether values match or diverge. + * @private + */ + SettingsTab.prototype._refreshEvmShared = function () { + var self = this; + if (!this._evmShared || !this.api) { return; } + + Promise.all(EVM_SHARED_CHAINS.map(function (cid) { + return self.api.get('/chains/' + cid).then(function (env) { + var d = (env && env.result) || (env && env.data) || env || {}; + return { + chainId: cid, + rewardAddress: (d.miner && d.miner.rewardAddress) || '', + // v0.5.228d (audit follow-up) — keep `enabled` for + // back-compat (older readers) but the authoritative + // value for the mining-row pills is `chainState`, + // attached by GET /chains/:id when the adapter is + // class B. Null/undefined means we couldn't reach + // the mainchain RPC to derive it — the renderer + // treats that as 'unknown' (showing "Detecting…") + // rather than guessing "On" or "Off". + enabled: !!(d.miner && d.miner.enabled), + chainState: (d.miner && d.miner.chainState) || null, + // sync.mode isn't currently returned by /chains/:id; + // when missing we treat all as 'fast' (the schema + // default) so the row still works. A future + // backend pass should add sync.mode to the response. + syncMode: (d.sync && d.sync.mode) || 'fast', + ok: true, + }; + }).catch(function () { + return { chainId: cid, ok: false }; + }); + })).then(function (results) { + if (self._destroyed) { return; } + self._evmShared.latest = results; + self._fillEvmShared(results); + }); + }; + + /** @private */ + SettingsTab.prototype._fillEvmShared = function (results) { + var t = root.enmTOrFallback || root.enmT || function (k) { return k; }; + if (!this._evmShared) { return; } + + // --- Reward address --------------------------------------------- + // v0.5.228 patch — split the "all failed" case out FIRST. Pre-patch + // a wholly-failed fetch silently passed through allEmpty=true (the + // vacuous `[].every` truthiness) and rendered "No reward address + // set on any chain" — a lie that made operators think their setup + // values were wiped. Now we explicitly say "Couldn't read from + // chains" so the operator knows it's a transport problem, not a + // missing-data problem, and can retry instead of re-entering the + // address. + var ok = results.filter(function (r) { return r.ok; }); + var failedCount = results.length - ok.length; + var values = ok.map(function (r) { return r.rewardAddress; }); + var allEmpty = ok.length > 0 && values.every(function (v) { return !v; }); + var allMatch = ok.length > 0 && values.every(function (v) { return v === values[0] && !!v; }); + var reward = this._evmShared.reward; + if (reward) { + if (ok.length === 0) { + // Hard failure across all 3 chains — most likely auth lapsed + // or the backend is mid-restart. Don't fake an "unset" state. + reward.input.value = ''; + reward.btn.disabled = true; + reward.status.textContent = 'Could not read from chains (' + failedCount + ' of ' + + results.length + ' failed). Try refreshing this section, or check the dashboard ' + + 'for chain connectivity.'; + reward.status.className = 'enm-evm-shared-status is-err'; + } else { + reward.btn.disabled = false; + if (allMatch) { + reward.input.value = values[0]; + var matchMsg = t('settings.evm_shared_reward_shared'); + if (failedCount > 0) { + matchMsg += ' (' + failedCount + ' of ' + results.length + + ' chains didn\'t respond — refresh to retry)'; + } + reward.status.textContent = matchMsg; + reward.status.className = 'enm-evm-shared-status is-ok'; + } else if (allEmpty) { + reward.input.value = ''; + reward.status.textContent = t('settings.evm_shared_reward_unset'); + reward.status.className = 'enm-evm-shared-status is-warn'; + } else { + var summary = ok.map(function (r) { + return r.chainId + '=' + (r.rewardAddress ? (r.rewardAddress.slice(0, 6) + '…' + r.rewardAddress.slice(-4)) : '(unset)'); + }).join(', '); + reward.input.value = ''; // intentionally blank to require explicit input + reward.status.textContent = t('settings.evm_shared_reward_diverged') + .replace('{summary}', summary); + reward.status.className = 'enm-evm-shared-status is-warn'; + } + } + } + + // --- Validator status (per-chain pills) ------------------------- + // v0.5.228d (audit follow-up) — render the same 5-state taxonomy + // the dashboard EVM card + the per-chain Validator-status badge + // use, sourced from miner.chainState (attached to GET /chains/:id + // for class B chains; see chainStateFromRole in routes/chains.js). + // Pre-228d the pills binary-mapped miner.enabled → "On" / "Off", + // which (a) failed to distinguish Standby from Inactive, (b) lied + // when the on-disk cfg.miner.enabled diverged from the live + // arbiter slate after a Council binding, and (c) reinforced the + // operator-toggle mental model that we're explicitly retiring. + var PILL_LABELS = { + 'on-duty': { text: 'On-duty', dataState: 'on-duty' }, + 'standby': { text: 'Standby', dataState: 'standby' }, + 'inactive': { text: 'Inactive', dataState: 'off' }, + 'unknown': { text: 'Detecting', dataState: '?' }, + 'follower': { text: 'Follower', dataState: 'off' }, + }; + var mining = this._evmShared.mining; + if (mining) { + var stateCounts = { 'on-duty': 0, 'standby': 0, 'inactive': 0, 'unknown': 0, 'follower': 0 }; + var cells = mining.grid.querySelectorAll('.enm-evm-shared-mining-cell'); + Array.prototype.forEach.call(cells, function (cell) { + var cid = cell.dataset.chain; + var r = results.find(function (rr) { return rr.chainId === cid; }); + var pill = cell.querySelector('.enm-evm-shared-mining-pill'); + if (!r || !r.ok) { + pill.textContent = '—'; + pill.dataset.mining = '?'; + return; + } + // Prefer chainState from /chains/:id. If absent (older + // backend), fall back to the legacy enabled→on/off map + // so the pill still renders something honest. + var s = r.chainState + || (r.enabled ? 'on-duty' : 'inactive'); + stateCounts[s] = (stateCounts[s] || 0) + 1; + var meta = PILL_LABELS[s] || PILL_LABELS.inactive; + pill.textContent = meta.text; + pill.dataset.mining = meta.dataState; + }); + // Plain-English summary line over the same taxonomy. Wording + // explicitly distances mining from being an operator choice. + var summary; + if (stateCounts['on-duty'] === 3) { + summary = 'All three EVMs are on-duty — producing blocks this rotation. ' + + 'Rewards land at the reward address above.'; + } else if (stateCounts.inactive + stateCounts.follower === 3) { + summary = 'All three EVMs are inactive — this node is not in the current arbiter slate, ' + + 'so it does not produce blocks. The reward address above stays configured ' + + 'for when (or if) the on-chain Council binding includes this node.'; + } else if (stateCounts.unknown === 3) { + summary = 'Detecting — couldn\'t read the on-chain arbiter slate yet ' + + '(mainchain RPC may still be warming up). Refreshes on every chain start.'; + } else { + var parts = []; + if (stateCounts['on-duty']) { parts.push(stateCounts['on-duty'] + ' on-duty'); } + if (stateCounts.standby) { parts.push(stateCounts.standby + ' standby'); } + if (stateCounts.inactive) { parts.push(stateCounts.inactive + ' inactive'); } + if (stateCounts.unknown) { parts.push(stateCounts.unknown + ' detecting'); } + if (stateCounts.follower) { parts.push(stateCounts.follower + ' follower'); } + summary = parts.join(', ') + + '. Validator status is derived from the on-chain arbiter slate, not ' + + 'operator-set. ENM re-checks on every chain start.'; + } + mining.status.textContent = summary; + mining.status.className = 'enm-evm-shared-status'; + } + + // --- Sync mode -------------------------------------------------- + var modes = ok.map(function (r) { return r.syncMode; }); + var syncAllMatch = modes.length > 0 && modes.every(function (m) { return m === modes[0]; }); + var sync = this._evmShared.sync; + if (sync) { + sync.btn.disabled = false; + if (syncAllMatch) { + sync.select.value = modes[0]; + sync.status.textContent = t('settings.evm_shared_sync_shared') + .replace('{mode}', modes[0]); + sync.status.className = 'enm-evm-shared-status is-ok'; + } else { + var sm = ok.map(function (r) { return r.chainId + '=' + r.syncMode; }).join(', '); + sync.status.textContent = t('settings.evm_shared_sync_diverged') + .replace('{summary}', sm); + sync.status.className = 'enm-evm-shared-status is-warn'; + } + } + }; + + /** @private — write rewardAddress to all 3 EVM chains in parallel. */ + SettingsTab.prototype._applyEvmSharedReward = function (raw, btn, statusEl) { + var self = this; + var t = root.enmTOrFallback || root.enmT || function (k) { return k; }; + // Client-side validation via enmEthAddress.check (same path the + // per-chain EVM card uses). Empty value clears the override on + // all 3 chains; non-empty must pass EIP-55 + format. + var payload; + var trimmed = String(raw || '').trim(); + if (trimmed === '') { + payload = ''; + } else { + var rootScope = (typeof window !== 'undefined') ? window : globalThis; + var check = (rootScope.enmEthAddress && rootScope.enmEthAddress.check) + ? rootScope.enmEthAddress.check(trimmed) + : null; + if (!check) { + statusEl.textContent = t('settings.evm_shared_reward_validation_err'); + statusEl.className = 'enm-evm-shared-status is-err'; + return; + } + if (!check.ok) { + if (check.error === 'eip55_checksum') { + statusEl.textContent = t('settings.evm_shared_reward_eip55_err') + .replace('{suggested}', check.suggested); + } else { + statusEl.textContent = t('settings.evm_shared_reward_validation_err'); + } + statusEl.className = 'enm-evm-shared-status is-err'; + return; + } + payload = check.normalized; + } + + var doApply = function () { + var done = 0; + var failed = []; + statusEl.textContent = t('settings.evm_shared_reward_apply_progress').replace('{done}', 0); + statusEl.className = 'enm-evm-shared-status'; + return Promise.all(EVM_SHARED_CHAINS.map(function (cid) { + return self.api.put('/chains/' + cid + '/class-b-config', { + miner: { rewardAddress: payload }, + }).then(function () { + done += 1; + statusEl.textContent = t('settings.evm_shared_reward_apply_progress') + .replace('{done}', done); + }).catch(function () { + failed.push(cid); + }); + })).then(function () { + if (failed.length === 0) { + statusEl.textContent = t('settings.evm_shared_reward_apply_ok'); + statusEl.className = 'enm-evm-shared-status is-ok'; + } else { + statusEl.textContent = t('settings.evm_shared_reward_apply_partial') + .replace('{okCount}', 3 - failed.length) + .replace('{failed}', failed.join(', ')); + statusEl.className = 'enm-evm-shared-status is-err'; + } + // Re-fetch so the divergence summary reflects post-save state. + self._refreshEvmShared(); + }); + }; + var rootScope = (typeof window !== 'undefined') ? window : globalThis; + if (typeof rootScope.enmRunOnce === 'function' && btn) { + rootScope.enmRunOnce(btn, 'Saving…', doApply); + } else { + doApply(); + } + }; + + /** @private — write sync.mode to all 3 EVM chains in parallel. */ + SettingsTab.prototype._applyEvmSharedSync = function (mode, btn, statusEl) { + var self = this; + var t = root.enmTOrFallback || root.enmT || function (k) { return k; }; + if (['fast', 'full', 'archive'].indexOf(mode) < 0) { + statusEl.textContent = 'Invalid sync mode.'; + statusEl.className = 'enm-evm-shared-status is-err'; + return; + } + var doApply = function () { + var done = 0; + var failed = []; + statusEl.textContent = t('settings.evm_shared_reward_apply_progress').replace('{done}', 0); + statusEl.className = 'enm-evm-shared-status'; + return Promise.all(EVM_SHARED_CHAINS.map(function (cid) { + return self.api.put('/chains/' + cid + '/class-b-config', { + sync: { mode: mode }, + }).then(function () { + done += 1; + statusEl.textContent = t('settings.evm_shared_reward_apply_progress') + .replace('{done}', done); + }).catch(function () { + failed.push(cid); + }); + })).then(function () { + if (failed.length === 0) { + statusEl.textContent = t('settings.evm_shared_reward_apply_ok'); + statusEl.className = 'enm-evm-shared-status is-ok'; + } else { + statusEl.textContent = t('settings.evm_shared_reward_apply_partial') + .replace('{okCount}', 3 - failed.length) + .replace('{failed}', failed.join(', ')); + statusEl.className = 'enm-evm-shared-status is-err'; + } + self._refreshEvmShared(); + }); + }; + var rootScope = (typeof window !== 'undefined') ? window : globalThis; + if (typeof rootScope.enmRunOnce === 'function' && btn) { + rootScope.enmRunOnce(btn, 'Saving…', doApply); + } else { + doApply(); + } + }; + // ----------------------------------------------------------------- // Section: Danger Zone (beta.3.33 — NEW) // Four destructive actions backed by /api/enm/maintenance/*: @@ -1706,6 +2380,229 @@ confirm: removeConfirm, btn: removeBtn, status: removeStatus, }; + // ---------- Sub-card 3b: Staged chain resume (v0.5.228) ---------- + // Operator directive 2026-05-26 — staged chain start is a destructive + // operation (pins the host at near-full CPU for hours; per-chain + // start API calls; not safe on a host that needs to stay responsive + // for other workloads). Gated behind an explicit enable/disable + // toggle that persists to localStorage so the operator's decision + // sticks across reloads. Previously auto-revealed in Advanced based + // on enmHostLimits.isConstrained — that auto-reveal is now removed. + var stageCard = _buildDangerCard({ + kind: 'warn', + title: t('settings.danger_stage_title'), + help: t('settings.danger_stage_help'), + }); + body.appendChild(stageCard.el); + var stageWarn = document.createElement('div'); + stageWarn.className = 'enm-danger-warning'; + stageWarn.textContent = t('settings.danger_stage_warn'); + stageCard.body.appendChild(stageWarn); + + // Persisted enable/disable toggle. Default OFF. + var STAGE_LS_KEY = 'enm:danger:staged-resume:enabled'; + function stageReadEnabled() { + try { + return window.localStorage.getItem(STAGE_LS_KEY) === '1'; + } catch (_) { return false; } + } + function stageWriteEnabled(on) { + try { + if (on) { + window.localStorage.setItem(STAGE_LS_KEY, '1'); + } else { + window.localStorage.removeItem(STAGE_LS_KEY); + } + } catch (_) { /* private mode / quota — toggle is in-memory only */ } + } + + var stageToggleRow = document.createElement('div'); + stageToggleRow.className = 'enm-danger-toggle-row'; + var stageToggleLabel = document.createElement('label'); + stageToggleLabel.className = 'enm-danger-toggle-label'; + var stageToggleInput = document.createElement('input'); + stageToggleInput.type = 'checkbox'; + stageToggleInput.className = 'enm-danger-toggle-input'; + stageToggleInput.checked = stageReadEnabled(); + var stageToggleText = document.createElement('span'); + stageToggleText.className = 'enm-danger-toggle-text'; + stageToggleText.textContent = t('settings.danger_stage_enable_label'); + var stageToggleSub = document.createElement('span'); + stageToggleSub.className = 'enm-danger-toggle-sub'; + stageToggleSub.textContent = stageToggleInput.checked + ? t('settings.danger_stage_enabled_sub') + : t('settings.danger_stage_disabled_sub'); + stageToggleLabel.appendChild(stageToggleInput); + stageToggleLabel.appendChild(stageToggleText); + stageToggleRow.appendChild(stageToggleLabel); + stageToggleRow.appendChild(stageToggleSub); + stageCard.body.appendChild(stageToggleRow); + + // Controls row — hidden until the toggle is on. + var stageControls = document.createElement('div'); + stageControls.className = 'enm-danger-stage-controls'; + stageControls.hidden = !stageToggleInput.checked; + var stageStartBtn = document.createElement('button'); + stageStartBtn.type = 'button'; + stageStartBtn.className = 'enm-btn enm-btn-primary'; + stageStartBtn.textContent = t('settings.danger_stage_start_btn'); + var stagePauseBtn = document.createElement('button'); + stagePauseBtn.type = 'button'; + stagePauseBtn.className = 'enm-btn'; + stagePauseBtn.textContent = t('settings.danger_stage_pause_btn'); + stagePauseBtn.hidden = true; + var stageResumeBtn = document.createElement('button'); + stageResumeBtn.type = 'button'; + stageResumeBtn.className = 'enm-btn'; + stageResumeBtn.textContent = t('settings.danger_stage_resume_btn'); + stageResumeBtn.hidden = true; + var stageCancelBtn = document.createElement('button'); + stageCancelBtn.type = 'button'; + stageCancelBtn.className = 'enm-btn enm-btn-danger'; + stageCancelBtn.textContent = t('settings.danger_stage_cancel_btn'); + stageCancelBtn.hidden = true; + stageControls.appendChild(stageStartBtn); + stageControls.appendChild(stagePauseBtn); + stageControls.appendChild(stageResumeBtn); + stageControls.appendChild(stageCancelBtn); + stageCard.body.appendChild(stageControls); + + var stageStatusEl = document.createElement('div'); + stageStatusEl.className = 'enm-danger-status'; + stageStatusEl.setAttribute('role', 'status'); + stageStatusEl.setAttribute('aria-live', 'polite'); + stageStatusEl.textContent = stageToggleInput.checked + ? t('settings.danger_stage_idle') + : t('settings.danger_stage_locked'); + stageCard.foot.appendChild(stageStatusEl); + + // Default chain order — matches the Council install plan. + var STAGE_CHAIN_ORDER = [ + 'mainchain', 'esc', 'eid', 'pg', + 'arbiter', 'esc-oracle', 'eid-oracle', 'pg-oracle', + ]; + var stageInstance = null; + + // Tiny string-template helper — replaces {chain} / {minutes} / etc. + function stageFormat(key, vars) { + var s = t('settings.' + key) || ''; + if (!vars) { return s; } + return s.replace(/\{(\w+)\}/g, function (_m, k) { + return (vars[k] == null) ? '' : String(vars[k]); + }); + } + + function stageHandlePhase(ev) { + var msg = ''; + switch (ev.phase) { + case 'starting': + msg = stageFormat('danger_stage_phase_starting', + { chain: ev.chainId || '?' }); + break; + case 'waiting': + msg = stageFormat('danger_stage_phase_waiting', + { chain: ev.chainId || '?', minutes: ev.elapsedMinutes }); + break; + case 'synced': + msg = stageFormat('danger_stage_phase_synced', { + chain: ev.chainId || '?', + next: (ev.remainingChains && ev.remainingChains[0]) || 'done', + }); + break; + case 'timeout': + msg = stageFormat('danger_stage_phase_timeout', + { chain: ev.chainId || '?' }); + break; + case 'complete': + msg = t('settings.danger_stage_phase_complete'); + break; + case 'paused': + msg = t('settings.danger_stage_phase_paused'); + break; + case 'resumed': + msg = t('settings.danger_stage_phase_resumed'); + break; + case 'cancelled': + msg = t('settings.danger_stage_phase_cancelled'); + break; + case 'error': + msg = stageFormat('danger_stage_phase_error', + { message: (ev.error && ev.error.message) || 'unknown' }); + break; + } + stageStatusEl.textContent = msg; + // Toggle button visibility based on phase. + if (ev.phase === 'starting' || ev.phase === 'waiting' || ev.phase === 'resumed') { + stageStartBtn.hidden = true; + stagePauseBtn.hidden = false; + stageResumeBtn.hidden = true; + stageCancelBtn.hidden = false; + } else if (ev.phase === 'paused') { + stageStartBtn.hidden = true; + stagePauseBtn.hidden = true; + stageResumeBtn.hidden = false; + stageCancelBtn.hidden = false; + } else if (ev.phase === 'complete' || ev.phase === 'cancelled' || ev.phase === 'error') { + stageStartBtn.hidden = false; + stagePauseBtn.hidden = true; + stageResumeBtn.hidden = true; + stageCancelBtn.hidden = true; + stageInstance = null; + } + } + + stageToggleInput.addEventListener('change', function () { + var on = !!stageToggleInput.checked; + stageWriteEnabled(on); + stageToggleSub.textContent = on + ? t('settings.danger_stage_enabled_sub') + : t('settings.danger_stage_disabled_sub'); + stageControls.hidden = !on; + if (!on) { + // Turning off mid-orchestration — cancel anything running. + if (stageInstance) { try { stageInstance.cancel(); } catch (_) {} stageInstance = null; } + stageStatusEl.textContent = t('settings.danger_stage_locked'); + stageStartBtn.hidden = false; + stagePauseBtn.hidden = true; + stageResumeBtn.hidden = true; + stageCancelBtn.hidden = true; + } else { + stageStatusEl.textContent = t('settings.danger_stage_idle'); + } + }); + + stageStartBtn.addEventListener('click', function () { + if (!stageToggleInput.checked) { return; } // guard — UI was bypassed + if (typeof root.EnmStageSync !== 'function') { + stageStatusEl.textContent = t('settings.danger_stage_helper_missing'); + return; + } + stageInstance = new root.EnmStageSync({ + api: self.api, + chainOrder: STAGE_CHAIN_ORDER, + onPhase: stageHandlePhase, + }); + stageInstance.start(); + }); + stagePauseBtn.addEventListener('click', function () { + if (stageInstance) { stageInstance.pause(); } + }); + stageResumeBtn.addEventListener('click', function () { + if (stageInstance) { stageInstance.resume(); } + }); + stageCancelBtn.addEventListener('click', function () { + if (stageInstance) { stageInstance.cancel(); } + }); + + this._danger.stage = { + card: stageCard.el, + toggle: stageToggleInput, + controls: stageControls, + status: stageStatusEl, + startBtn: stageStartBtn, + getInstance: function () { return stageInstance; }, + }; + // ---------- Sub-card 4: Nuclear wipe ---------- var nukeCard = _buildDangerCard({ kind: 'critical', @@ -1826,9 +2723,8 @@ var self = this; var t = root.enmTOrFallback; var s = self._danger.resync; - if (typeof window !== 'undefined' && typeof window.confirm === 'function') { - if (!window.confirm(t('settings.danger_resync_confirm_dialog'))) { return; } - } + // v0.5.217 audit Phase 3 (AUDIT-FLOW-DZ01, P2) — native confirm() + // removed. Typed-confirm gate ("mainchain") already protects. s.status.textContent = t('settings.danger_resync_in_progress'); s.status.classList.remove('ok', 'err'); return root.enmRunOnce(s.btn, t('settings.danger_resync_in_progress'), function () { @@ -1858,9 +2754,8 @@ var self = this; var t = root.enmTOrFallback; var s = self._danger.remove; - if (typeof window !== 'undefined' && typeof window.confirm === 'function') { - if (!window.confirm(t('settings.danger_remove_confirm_dialog'))) { return; } - } + // v0.5.217 audit Phase 3 (AUDIT-FLOW-DZ01, P2) — native confirm() + // removed. Typed-confirm gate ("remove") already protects. s.status.textContent = t('settings.danger_remove_in_progress'); s.status.classList.remove('ok', 'err'); return root.enmRunOnce(s.btn, t('settings.danger_remove_in_progress'), function () { @@ -1885,9 +2780,10 @@ var self = this; var t = root.enmTOrFallback; var s = self._danger.nuke; - if (typeof window !== 'undefined' && typeof window.confirm === 'function') { - if (!window.confirm(t('settings.danger_nuke_confirm_dialog'))) { return; } - } + // v0.5.217 audit Phase 3 (AUDIT-FLOW-DZ01, P2) — native confirm() + // removed. The case-sensitive typed-confirm gate ("WIPE EVERYTHING") + // is the strongest gate in the app + provides the muscle-memory + // friction the native dialog was trying to add. s.status.textContent = t('settings.danger_nuke_in_progress'); s.status.classList.remove('ok', 'err'); return root.enmRunOnce(s.btn, t('settings.danger_nuke_in_progress'), function () { @@ -2042,22 +2938,38 @@ body.appendChild(currentCard.el); var idGrid = document.createElement('div'); idGrid.className = 'enm-identity-grid'; + // v0.5.228 — public key is the PRIMARY identity (what gets shared + // with Essentials, what stakers vote on, what shows up on every + // explorer). Signing address is operationally internal and visually + // demoted. Modifier classes on each row drive the size/weight + // hierarchy in styles.css (pubkey row gets a larger value font + a + // "Share with Essentials" pill above it; address row gets a + // smaller value font + an "Internal · do not share" pill). + // v0.5.229d (P2 audit fix) — the pubkey pill text was hardcoded + // "Share with Essentials" (BPoS-only language). For Council + // operators it should read "Claim via Essentials" or "Bound to + // Council seat". We can't know which until /system/identity + // resolves, so render a neutral default ("Public key") and let + // _fillForm rewrite the pill text + class once the response + // lands. data-fill="pubkey-pill" tags the slot for the fill. idGrid.innerHTML = - '
    ' + '
    ' + '
    ' + _h(t('settings.identity_pubkey_label')) + + 'Public key' + '
    ' + '—' + '' + '
    ' - + '
    ' + + '
    ' + '
    ' + _h(t('settings.identity_address_label')) + + 'Internal' + '
    ' + '—' + '' + '
    ' - + '
    ' + + '
    ' + '
    ' + _h(t('settings.identity_producer_label')) + '
    ' @@ -2135,7 +3047,14 @@ importCard.body.appendChild(importWarn); var importFile = document.createElement('input'); importFile.type = 'file'; - importFile.accept = '.dat,application/octet-stream'; + // v0.5.216 audit Phase 2 (AUDIT-FLOW-I02, P1) — broadened from + // '.dat,application/octet-stream' which hid .json keystores + // exported by Elastos Essentials / ENM v0.4.x in the file + // picker. Operators concluded their backup was the wrong format + // when in reality it was just an extension mismatch. Backend + // /identity/import validates the file contents regardless of + // extension, so widening the picker is safe + operator-friendly. + importFile.accept = '.dat,.json,application/octet-stream,application/json'; importFile.className = 'enm-input'; importCard.body.appendChild(_wrapLabel(t('settings.identity_import_file_label'), importFile)); var importPassword = document.createElement('input'); @@ -2280,6 +3199,96 @@ status: integrityStatus, }; + // ------------------------------------------------------------- + // v0.5.229 (Phase F) — Role-debug panel. + // + // Collapsed-by-default card that, when expanded, hits + // GET /system/role-debug and dumps the raw chain RPC responses + // + ENM's parsed view side-by-side. Designed so the operator + // can copy a JSON dump for support, or (just as important) so + // a future Council operator hitting the next-class-of-bug like + // the v228 currentarbiters typo can spot the mismatch in + // seconds without re-reading ENM source. + // + // "Copy debug JSON" puts the full payload on the clipboard + // (best-effort; falls back to a textarea select for older + // browsers). Sensitive fields: this endpoint already filters + // /listcurrentcrs to just the operator's own member record + // (server-side), so we're not exposing other members' PII. + // ------------------------------------------------------------- + var debugCard = _buildDangerCard({ + kind: 'info', + title: 'Role debug', + help: 'Raw RPC responses ENM uses to decide your on-chain role ' + + '(Council / BPoS / follower) plus ENM\'s parsed view of each. ' + + 'Useful when the Validator status badge says something different ' + + 'than you expect — paste the JSON in a support ticket and a ' + + 'developer can compare ENM\'s read vs the chain\'s truth side-by-side.', + }); + body.appendChild(debugCard.el); + var debugStatus = document.createElement('div'); + debugStatus.className = 'enm-danger-status'; + debugStatus.setAttribute('role', 'status'); + debugStatus.setAttribute('aria-live', 'polite'); + debugStatus.textContent = 'Collapsed. Click "Refresh" to read live state.'; + debugCard.body.appendChild(debugStatus); + var debugPre = document.createElement('pre'); + debugPre.className = 'enm-role-debug-pre'; + debugPre.hidden = true; + debugPre.style.maxHeight = '400px'; + debugPre.style.overflow = 'auto'; + debugPre.style.fontSize = '11px'; + debugPre.style.fontFamily = 'var(--font-mono)'; + debugPre.style.background = 'var(--bg-elevated)'; + debugPre.style.border = '1px solid var(--border-subtle)'; + debugPre.style.borderRadius = 'var(--r-sm)'; + debugPre.style.padding = 'var(--sp-3)'; + debugPre.style.whiteSpace = 'pre-wrap'; + debugPre.style.wordBreak = 'break-word'; + debugCard.body.appendChild(debugPre); + var debugRefreshBtn = document.createElement('button'); + debugRefreshBtn.type = 'button'; + debugRefreshBtn.className = 'enm-btn'; + debugRefreshBtn.textContent = 'Refresh debug info'; + debugCard.foot.appendChild(debugRefreshBtn); + var debugCopyBtn = document.createElement('button'); + debugCopyBtn.type = 'button'; + debugCopyBtn.className = 'enm-btn enm-btn-primary'; + debugCopyBtn.textContent = 'Copy JSON'; + debugCopyBtn.disabled = true; + debugCard.foot.appendChild(debugCopyBtn); + var debugPayload = null; + debugRefreshBtn.addEventListener('click', function () { + debugStatus.textContent = 'Reading on-chain state…'; + debugStatus.className = 'enm-danger-status'; + self.api.get('/system/role-debug').then(function (env) { + if (self._destroyed) { return; } + debugPayload = (env && env.result) || (env && env.data) || env; + debugPre.hidden = false; + debugPre.textContent = JSON.stringify(debugPayload, null, 2); + debugCopyBtn.disabled = false; + debugStatus.textContent = 'Fetched at ' + (debugPayload.summary && debugPayload.summary.lastChecked || '?'); + debugStatus.className = 'enm-danger-status is-ok'; + }).catch(function (err) { + if (self._destroyed) { return; } + debugStatus.textContent = 'Failed: ' + ((err && err.message) || String(err)); + debugStatus.className = 'enm-danger-status is-err'; + }); + }); + debugCopyBtn.addEventListener('click', function () { + if (!debugPayload) { return; } + var text = JSON.stringify(debugPayload, null, 2); + if (root.enmCopyToClipboard) { + root.enmCopyToClipboard(text, { notifications: self.notifications }); + } else if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(text).then(function () { + debugStatus.textContent = 'Copied to clipboard.'; + }).catch(function () { + debugStatus.textContent = 'Copy failed — select the JSON manually and Cmd+C.'; + }); + } + }); + return card; }; @@ -2406,6 +3415,15 @@ var self = this; var t = root.enmTOrFallback; if (!self._identity) { return; } + // v0.5.216 audit Phase 2 (AUDIT-FLOW-I01, P1) — skip the repaint + // while the operator hasn't yet ack'd a freshly-revealed Reset + // password. _doIdentityReset sets _resetRevealPendingAck=true; + // dismiss handler clears it then calls back into this method. + // Without this gate, the parent setting-tab activation hook + // (line ~1237) would call _refreshIdentity, rebuild the cards, + // and clobber the reveal panel with the new password the + // operator hasn't saved yet. + if (self._resetRevealPendingAck) { return; } self.api.get('/identity', { skipCache: true }) .then(function (resp) { if (self._destroyed) { return; } @@ -2414,12 +3432,46 @@ var id = r.identity || {}; self._identity.pubkeyEl.textContent = id.publicKey || '—'; self._identity.addressEl.textContent = id.address || '—'; - // Producer chip: "Active · Rank #N" / "Pending" / "Inactive" / - // "Not registered yet" if no record. + // v0.5.229d (P2 audit fix) — rewrite the pubkey pill based + // on the Council/BPoS context. Pre-229d the pill always + // read "Share with Essentials" (BPoS-only). Now branches: + // crMember.isCrMember=true → "Bound to Council seat" + // setupRole='council' → "Claim via Essentials" + // else → "Share with Essentials" + var crMember = r.crMember || null; + var setupRole = r.setupRole || 'unknown'; + var pubkeyPillEl = self._identity.card + && self._identity.card.querySelector('[data-fill="pubkey-pill"]'); + if (pubkeyPillEl) { + if (crMember && crMember.isCrMember) { + pubkeyPillEl.textContent = 'Bound to Council seat'; + } else if (setupRole === 'council') { + pubkeyPillEl.textContent = 'Claim via Essentials'; + } else { + pubkeyPillEl.textContent = 'Share with Essentials'; + } + } + // Producer chip — surface CR Council state when known, + // BPoS state otherwise, falling through to "Not registered". + // Pre-229d a Council operator who'd never registered as + // BPoS saw "Not registered yet" here despite being a CR + // member — wrong on its face. var p = r.producer || null; - var prodText = (p && p.state) - ? (p.rank != null ? (p.state + ' · Rank #' + p.rank) : p.state) - : t('settings.identity_producer_unregistered'); + var prodText; + if (crMember && crMember.isCrMember) { + prodText = 'CR Council member · ' + (crMember.state || 'Elected') + + (crMember.nickname ? (' · ' + crMember.nickname) : ''); + if (p && p.state) { + // Operator is BOTH a Council member AND a BPoS producer + prodText += ' (also BPoS · ' + p.state + ')'; + } + } else if (p && p.state) { + prodText = p.rank != null ? (p.state + ' · Rank #' + p.rank) : p.state; + } else if (setupRole === 'council') { + prodText = 'Council install — not currently bound (claim via Essentials)'; + } else { + prodText = t('settings.identity_producer_unregistered'); + } self._identity.producerEl.textContent = prodText; // Unlock card is visible only when keystore exists but // we don't have its identity cached yet. @@ -2567,7 +3619,17 @@ } var dispo = r.headers.get('Content-Disposition') || ''; var m = /filename="([^"]+)"/.exec(dispo); - var name = m ? m[1] : 'keystore-backup.dat'; + // v0.5.216 audit Phase 2 (AUDIT-FLOW-I07, P2) — + // sanitize the Content-Disposition filename + // before handing it to the browser's download + // API. Pre-v0.5.216 a backend bug (or MitM on a + // misconfigured endpoint) could ship a filename + // like '../etc/passwd' or 'malicious.exe' and + // the browser would honor it. Defense in depth: + // strip path separators + odd chars, cap length. + var rawName = m ? m[1] : 'keystore-backup.dat'; + var name = rawName.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 64); + if (!name) { name = 'keystore-backup.dat'; } return r.blob().then(function (blob) { return { blob: blob, name: name }; }); }) .then(function (d) { @@ -2603,9 +3665,11 @@ status.classList.remove('ok'); status.classList.add('err'); return; } - if (typeof window !== 'undefined' && typeof window.confirm === 'function') { - if (!window.confirm(t('settings.identity_import_confirm_dialog'))) { return; } - } + // v0.5.217 audit Phase 3 (AUDIT-FLOW-I06, P2) — native confirm() + // removed. The typed-confirm gate ("import") + the import button + // already-disabled-unless-typed-confirm-matches state are + // sufficient defense-in-depth; the native browser dialog was + // jarring + inconsistent with the rest of ENM's UX. status.textContent = t('settings.identity_import_running'); status.classList.remove('ok', 'err'); // Whether to force = whether the slashing-risk warning is visible @@ -2665,9 +3729,10 @@ SettingsTab.prototype._doIdentityReset = function (btn, status, warnEl, confirmObj) { var self = this; var t = root.enmTOrFallback; - if (typeof window !== 'undefined' && typeof window.confirm === 'function') { - if (!window.confirm(t('settings.identity_reset_confirm_dialog'))) { return; } - } + // v0.5.217 audit Phase 3 (AUDIT-FLOW-I13, P2) — native confirm() + // removed. The typed-confirm gate ("reset keystore") + the post- + // reveal ack checkbox (added in Phase 2 for I01) together provide + // strong defense-in-depth; the native dialog was redundant. status.textContent = t('settings.identity_reset_running'); status.classList.remove('ok', 'err'); var force = !warnEl.hidden; @@ -2680,7 +3745,18 @@ .then(function (resp) { if (self._destroyed) { return; } var r = (resp && resp.result) || resp || {}; - // Inline password reveal — same pattern as Card C. + var newPw = r.generatedPassword || ''; + var last4 = newPw.slice(-4); + // v0.5.216 audit Phase 2 (AUDIT-FLOW-I01, P1) — the + // reveal now includes an ACK CHECKBOX + LAST-4 + // anti-typo gate matching the setup wizard Card 3 + // pattern. Pre-v0.5.216 the operator could reveal + // the new password, copy it, switch tabs — and + // lose it forever (clipboard cleared on next copy + // / refresh / navigation) → permanently locked out + // of an Active producer keystore. The gate keeps + // the rest of Identity inert until the operator + // confirms they have the password saved. self._identity.resetReveal.hidden = false; self._identity.resetReveal.innerHTML = '' + '' - + _h(r.generatedPassword || '') + + _h(newPw) + '' + '
    ' + '' + '
    ' + + '
    ' + // Ack gate — checkbox + last-4 retype. + + '
    ' + + '' + + '' + + '' + + '

    ⚠ The other Identity controls are locked until you confirm. If you lose this password, your keystore is unrecoverable.

    ' + '
    '; // Wire copy button on the password. var pwEl = self._identity.resetReveal.querySelector('.enm-password-value'); - if (typeof root.enmCopyButton === 'function' && r.generatedPassword) { + if (typeof root.enmCopyButton === 'function' && newPw) { var copyBtn = root.enmCopyButton({ - value: r.generatedPassword, + value: newPw, label: t('friendly.setup.card_c.cta_copy') || 'Copy', copiedLabel: t('friendly.setup.card_c.cta_copied') || 'Copied!', ariaLabel: 'Copy new password', @@ -2718,6 +3807,59 @@ slot.parentNode.replaceChild(copyBtn, slot); } } + // Wire the ack-gate handlers + lock the rest of + // Identity until the operator confirms. + self._resetRevealPendingAck = true; + var lockTargets = [ + self._identity.currentCard, + self._identity.unlockCard, + self._identity.backupCard, + self._identity.importCard, + self._identity.integrity && self._identity.integrity.card, + ]; + lockTargets.forEach(function (el) { + if (el) { + el.setAttribute('inert', ''); + el.setAttribute('aria-hidden', 'true'); + el.style.opacity = '0.35'; + el.style.pointerEvents = 'none'; + } + }); + // Also disable the Reset card's own Reset button + // so the operator can't trigger ANOTHER reset + // (would generate yet another password without + // saving this one). + if (self._identity.resetBtn) { + self._identity.resetBtn.disabled = true; + } + var ackBox = self._identity.resetReveal.querySelector('[data-fill="reveal-ack"]'); + var last4Input = self._identity.resetReveal.querySelector('[data-fill="reveal-last4"]'); + var dismissBtn = self._identity.resetReveal.querySelector('[data-action="reveal-dismiss"]'); + function refreshGate() { + var typed = (last4Input.value || '').trim().toLowerCase(); + dismissBtn.disabled = !(ackBox.checked && typed === last4.toLowerCase()); + } + ackBox.addEventListener('change', refreshGate); + last4Input.addEventListener('input', refreshGate); + dismissBtn.addEventListener('click', function () { + if (dismissBtn.disabled) { return; } + // Operator confirmed — re-enable everything. + self._resetRevealPendingAck = false; + self._identity.resetReveal.hidden = true; + self._identity.resetReveal.innerHTML = ''; + lockTargets.forEach(function (el) { + if (el) { + el.removeAttribute('inert'); + el.removeAttribute('aria-hidden'); + el.style.opacity = ''; + el.style.pointerEvents = ''; + } + }); + if (self._identity.resetBtn) { + self._identity.resetBtn.disabled = true; // typed-confirm still empty + } + self._refreshIdentity(); + }); status.textContent = t('settings.identity_reset_ok'); status.classList.add('ok'); confirmObj.input.value = ''; @@ -2726,7 +3868,9 @@ try { self.api.invalidate('/system/identity'); } catch (_) { /* ignore */ } } - self._refreshIdentity(); + // Deferred — _refreshIdentity now early-returns + // while _resetRevealPendingAck is true (see method), + // so it'll fire after the operator acks. }) .catch(function (err) { if (self._destroyed) { return; } @@ -3241,8 +4385,14 @@ // which rule they had toggled. SettingsTab.prototype._toggleHealingRule = function (ruleId, ruleTitle, nextEnabled, toggleEl) { var self = this; - if (!this.services || !this.services.api - || typeof this.services.api.put !== 'function') { + // v0.5.215 audit (AUDIT-FLOW-H01, P0) — restored from dead-on-arrival + // state. Pre-v0.5.215 this guard referenced this.services.api which + // was never assigned in the constructor (this.api is the canonical + // field — see line 116). Every healing toggle click was a silent + // no-op: the early-return fired before any API call or UI flip, + // leaving operators with NO functional kill switch for misbehaving + // F-rules (critical given the C19 F2 restart-loop history). + if (!this.api || typeof this.api.put !== 'function') { return; } // Compose the toast label once. If the title is the same as the @@ -3259,10 +4409,10 @@ toggleEl.classList.toggle('enm-healing-rules-toggle-off', !nextEnabled); var body = { enabledRules: {} }; body.enabledRules[ruleId] = !!nextEnabled; - this.services.api.put('/config/healing', body) + this.api.put('/config/healing', body) .then(function () { - if (self.services && self.services.notifications) { - self.services.notifications.show({ + if (self.notifications) { + self.notifications.show({ severity: 'info', title: ruleLabel + ' is now ' + (nextEnabled ? 'on' : 'off'), body: 'The healing engine will pick up this change within ~5 s.', @@ -3289,8 +4439,8 @@ // _saveSecurity / _refreshHealingRules / _refreshHealingActivity. if (err && err.status === 401) { return; } var msg = (err && err.message) || String(err); - if (self.services && self.services.notifications) { - self.services.notifications.show({ + if (self.notifications) { + self.notifications.show({ severity: 'warning', title: 'Failed to update ' + ruleLabel, body: msg, @@ -3877,6 +5027,21 @@ catch (e) { a.syncGrace.input.focus(); } return; } + // v0.5.222 audit Phase 9 (XFLOW-13, AUDIT-FLOW-AL03) — sync-stall + // grace MUST be >= peer-grace. Syncing requires peers first, so + // peer-zero alert should fire BEFORE sync-stall alert. Pre-v0.5.222 + // operator could save peerGrace=10 + syncGrace=5 (backward) and + // the sync-stall alert would fire while the peer-zero alert + // hadn't yet triggered — confusing escalation order. + if (syncMin < peerMin) { + setStatus(a.statusEl, 'error', + 'Sync-stall grace (' + syncMin + 'm) must be greater than or equal to ' + + 'peer-zero grace (' + peerMin + 'm). Syncing requires peers first.'); + a.syncGrace.input.setAttribute('aria-invalid', 'true'); + try { a.syncGrace.input.focus({ preventScroll: true }); } + catch (e) { a.syncGrace.input.focus(); } + return; + } var body = { diskFreeWarnGb: diskWarn, diff --git a/src/backend/apps/elastos-node-manager/js/components/setup-conversation.js b/src/backend/apps/elastos-node-manager/js/components/setup-conversation.js index 254336f637..855f089cca 100644 --- a/src/backend/apps/elastos-node-manager/js/components/setup-conversation.js +++ b/src/backend/apps/elastos-node-manager/js/components/setup-conversation.js @@ -762,7 +762,7 @@ // localStorage stash survives refresh — operator never loses the // password between Card 3 reveal and Card 5 submission. var stashed = null; - try { stashed = window.localStorage.getItem('enm:master-pw'); } catch (_) {} + try { stashed = window.sessionStorage.getItem('enm:master-pw'); } catch (_) {} if (stashed) { this._masterPassword = stashed; this._renderCard3Reveal(body, seq, stashed); @@ -858,7 +858,7 @@ self._continueBtn.removeEventListener('click', onGenerate); var pw = generateMasterPassword(); self._masterPassword = pw; - try { window.localStorage.setItem('enm:master-pw', pw); } catch (_) {} + try { window.sessionStorage.setItem('enm:master-pw', pw); } catch (_) {} self._renderCard3Reveal(body, seq, pw); }); var pasteLink = body.querySelector('[data-action="paste-saved"]'); @@ -951,7 +951,7 @@ } self._continueBtn.removeEventListener('click', onUseSaved); self._masterPassword = pw; - try { window.localStorage.setItem('enm:master-pw', pw); } catch (_) {} + try { window.sessionStorage.setItem('enm:master-pw', pw); } catch (_) {} self._renderCard3Reveal(body, seq, pw); }); var backLink = body.querySelector('[data-action="back-to-generate"]'); @@ -1038,7 +1038,7 @@ } self._continueBtn.removeEventListener('click', onUseExisting); self._masterPassword = pw; - try { window.localStorage.setItem('enm:master-pw', pw); } catch (_) {} + try { window.sessionStorage.setItem('enm:master-pw', pw); } catch (_) {} self._renderCard3Reveal(body, seq, pw); }); }; @@ -1272,66 +1272,65 @@ '.enm-council-form-warn[data-for="' + field + '"]'); if (el) { el.textContent = msg; el.hidden = !msg; } } - // hasMixedCase — true when the address has any uppercase - // A-F hex char. EIP-55 encodes a checksum in mixed-case; - // wallet copies from Essentials / MetaMask produce - // mixed-case strings. Lowercase or all-uppercase addresses - // have no checksum to verify and don't need the warning. - function hasMixedCase(s) { - if (typeof s !== 'string') { return false; } - var hasUpper = /[A-F]/.test(s); - var hasLower = /[a-f]/.test(s); - return hasUpper && hasLower; - } - // 0.5.23 audit Session 23 — handle the two most common paste - // mishaps that pre-0.5.23 fell through to a generic format error: - // (a) internal whitespace (newlines from PDF copy, spaces from - // screenshots / wallet-app exports); - // (b) capital-X prefix (some explorers / editors capitalize - // the leading "0X"). - // s.trim() only handles leading/trailing whitespace; internal - // whitespace inside a hex string is by definition not part of - // the address, so silent strip is safe. - function normalizeEthInput(s) { - if (typeof s !== 'string') { return ''; } - var stripped = s.replace(/\s+/g, ''); - if (/^0X/.test(stripped)) { - stripped = '0x' + stripped.slice(2); + // v0.5.216 audit Phase 2 (AUDIT-FLOW-C401/B01, P1) — the previous + // `validateEth` + `hasMixedCase` + `normalizeEthInput` inline + // helpers are gone; same logic now lives in js/utils-eth.js + // (root.enmEthAddress) so settings-tab.js Class B + this Card + // share ONE source of truth (closes XFLOW-04 + XFLOW-16 + // duplication). The shared helper also adds a HARD-block on + // wrong EIP-55 checksum (via vendored js-sha3 keccak-256), so + // a mixed-case address with one char's case flipped — which + // would silently send rewards to a different account — is now + // rejected at save time rather than passing through the soft + // warning that the operator could ignore. + var ethApi = root.enmEthAddress; + // Defensive: if utils-eth.js failed to load (script order bug + // / network blip), fall back to the pre-v0.5.216 soft warning + // behavior so the wizard stays usable. This preserves operator + // flow at the cost of dropping the EIP-55 hard-block until + // utils-eth comes back. + function checkAddr(raw) { + if (ethApi && typeof ethApi.check === 'function') { + return ethApi.check(raw); } - return stripped; - } - function validateEth(s) { - if (typeof s !== 'string') { - return t('friendly.setup.card_4.err_format'); + // Stub matching enmEthAddress.check shape for the fallback. + var stripped = String(raw == null ? '' : raw).replace(/\s+/g, ''); + if (/^0X/.test(stripped)) { stripped = '0x' + stripped.slice(2); } + if (/^0x[0-9a-fA-F]{40}$/.test(stripped)) { + return { ok: true, normalized: stripped, warn: 'no_keccak' }; } - // 0.5.4 audit Session 4 — detect missing 0x prefix specifically. - // Operators paste from Essentials / MetaMask / etc. sometimes - // grab 40 hex chars without the 0x; pre-0.5.4 the generic - // "format" error confused them. Now we suggest the fix. - if (/^[0-9a-fA-F]{40}$/.test(s)) { + if (/^[0-9a-fA-F]{40}$/.test(stripped)) { + return { ok: false, error: 'missing_0x', suggested: '0x' + stripped }; + } + return { ok: false, error: 'format' }; + } + // Map enmEthAddress.check error codes → operator-facing copy. + function errMessage(r) { + if (!r || r.ok) { return ''; } + if (r.error === 'missing_0x') { return t('friendly.setup.card_4.err_missing_0x', - { suggested: '0x' + s }); + { suggested: r.suggested }); } - if (!/^0x[0-9a-fA-F]{40}$/.test(s)) { - return t('friendly.setup.card_4.err_format'); + if (r.error === 'eip55_checksum') { + // New copy: HARD-block message + suggested canonical form. + // strings.js still ships warn_mixed_case for the soft path. + return 'Wrong checksum — looks like a typo. Did you mean: ' + + (r.suggested || '?') + + ' (paste fresh from your wallet to be safe).'; } - return null; + return t('friendly.setup.card_4.err_format'); } rewardEl.addEventListener('input', function () { showError('reward', ''); showError('last4', ''); - // 0.5.23 audit Session 23 — normalize before validating so - // a paste with stray whitespace shows the last-4 gate as - // soon as the underlying address is otherwise valid. - var norm = normalizeEthInput(rewardEl.value); - if (validateEth(norm) === null) { + var r = checkAddr(rewardEl.value); + if (r.ok) { last4Row.hidden = false; - // 0.5.102 audit Session 102 — EIP-55 mixed-case - // soft warning. Doesn't block submission; the - // last-4 gate + operator inspection are the - // primary defenses. This just raises awareness. - if (hasMixedCase(norm)) { + if (r.warn === 'no_keccak' && ethApi && ethApi.hasMixedCase(r.normalized)) { + // utils-eth degraded mode (keccak unavailable) — + // preserve the pre-v0.5.216 soft warning so the + // operator at least sees the EIP-55 awareness hint. showWarn('reward', t('friendly.setup.card_4.warn_mixed_case')); } else { showWarn('reward', ''); @@ -1356,16 +1355,22 @@ if (self._destroyed || !self._stillRendering(seq)) { return; } showError('reward', ''); showError('last4', ''); - // 0.5.23 audit Session 23 — normalize on click. If the - // normalization changed the value, write it back to the - // input so the operator can see exactly what was accepted - // and so the last-4 gate compares against the cleaned-up - // form. + // v0.5.216 audit Phase 2 — single shared validation through + // root.enmEthAddress (formerly 3 inline helpers). If r.error + // === 'eip55_checksum' the HARD-block fires: a mixed-case + // address with one char's case flipped used to pass through + // the soft warning and silently send rewards to a different + // account (AUDIT-FLOW-C401, P1). Now blocked at save time. var raw = rewardEl.value; - var reward = normalizeEthInput(raw); - if (reward !== raw) { rewardEl.value = reward; } - var err = validateEth(reward); - if (err) { showError('reward', err); return; } + var r = checkAddr(raw); + if (r.ok && r.normalized && r.normalized !== raw) { + rewardEl.value = r.normalized; + } + if (!r.ok) { + showError('reward', errMessage(r)); + return; + } + var reward = r.normalized; var last4 = (last4El.value || '').trim().toLowerCase(); var expected = reward.slice(-4).toLowerCase(); if (last4.length === 0) { @@ -2263,6 +2268,11 @@ // future XSS / compromised extension / debug session reading // localStorage from this origin would otherwise extract it. try { window.localStorage.removeItem('enm:setup-intent'); } catch (_) {} + try { window.sessionStorage.removeItem('enm:master-pw'); } catch (_) {} + // v0.5.227 audit Phase 17 follow-up (AUDIT-FLOW-C301, P2) — also + // clean the legacy localStorage entry from operators upgrading + // from a pre-v0.5.227 build (we moved to sessionStorage above). + // One-shot best-effort migration; safe to keep indefinitely. try { window.localStorage.removeItem('enm:master-pw'); } catch (_) {} self.onComplete(); }); diff --git a/src/backend/apps/elastos-node-manager/js/components/validator-registration-card.js b/src/backend/apps/elastos-node-manager/js/components/validator-registration-card.js index 55f576e41b..50a0d227c8 100644 --- a/src/backend/apps/elastos-node-manager/js/components/validator-registration-card.js +++ b/src/backend/apps/elastos-node-manager/js/components/validator-registration-card.js @@ -73,6 +73,20 @@ var STATE_ACTIVE = 'active'; var STATE_HIDE = 'hide'; + // v0.5.229 (audit 2026-05-27) — Council branch states. CR Council + // operators have a different on-chain registration path (via the CR + // Committee, not via producer-register TX) and their states are NOT + // a subset of BPoS states. Each STATE_COUNCIL_* maps to a distinct + // render method below. Decision tree in _reconcile branches on + // setupRole === 'council' / crMember.isCrMember first, then falls + // back to BPoS states only when neither signal is present. + var STATE_COUNCIL_ELECTED = 'council_elected'; // on Committee, MemberState=Elected → producing + var STATE_COUNCIL_INACTIVE = 'council_inactive'; // on Committee, MemberState=Inactive + var STATE_COUNCIL_IMPEACHED = 'council_impeached'; // on Committee, MemberState=Impeached / Returned / Terminated / Illegal + var STATE_COUNCIL_NEXT_TERM = 'council_next_term'; // in next-term Committee (waiting for term boundary) + var STATE_COUNCIL_UNCLAIMED = 'council_unclaimed'; // Council install, no current Committee match (e.g. operator unclaimed) + var STATE_COUNCIL_NO_TERM = 'council_no_term'; // Council install, Committee not in election period (between terms) + function BposCard(opts) { if (!opts || !opts.api) { throw new TypeError('EnmBposCard: { api } required'); @@ -199,6 +213,15 @@ var producerFailed = false; var chainPath = '/chains/' + encodeURIComponent(this.chainId); var producerPath = chainPath + '/producer'; + // v0.5.229 — also fetch /system/identity so the card knows whether + // this operator went through the Council install path (setupRole) + // and whether they're a current CR Committee member (crMember). + // Phase B added these fields; the card branches on them in + // _reconcile to render the Council vs BPoS variant. /system/identity + // is a hot path already polled by the dashboard's node-identity-card; + // adding a duplicate fetch here is cheap (backend's + // CrMembershipService caches 30s). + var identityFailed = false; Promise.all([ this.api.get(chainPath, { skipCache: true }) .catch(function (err) { @@ -214,18 +237,24 @@ if (!err || err.status !== 401) { producerFailed = true; } return null; }), + this.api.get('/system/identity', { skipCache: true }) + .catch(function (err) { + if (!err || err.status !== 401) { identityFailed = true; } + return null; + }), ]).then(function (results) { if (self._destroyed) { return; } var chain = results[0]; var producer = results[1]; - if (chainFailed && producerFailed && !self.root.hidden) { - // Both fetches failed — leave the last-known-good + var identity = results[2]; + if (chainFailed && producerFailed && identityFailed && !self.root.hidden) { + // All three fetches failed — leave the last-known-good // render in place rather than misleading the operator // by hiding. The chain-card next to us already // surfaces the outage. return; } - self._reconcile(chain, producer); + self._reconcile(chain, producer, identity); }); }; @@ -242,7 +271,7 @@ * * @private */ - BposCard.prototype._reconcile = function (chain, producer) { + BposCard.prototype._reconcile = function (chain, producer, identity) { // v0.5.210 — accept 'synced' as alive too (v0.5.203 unified the // backend state vocab; 'healthy' became 'synced'). Without this, // the BPoS card thought every alive chain was dead → producer- @@ -252,16 +281,87 @@ var pState = producer && producer.state; var enabled = !!(producer && producer.enabled); - // BPoS card only makes sense for arbiter-enabled nodes. The - // operator may flip enableArbiter off via Settings; when that - // happens the card disappears and the steady-state plain-node - // chain-card carries the dashboard alone. + // v0.5.229 (audit 2026-05-27) — role gating. Council operators + // arrive here with `setupRole === 'council'` AND/OR a non-null + // crMember object from /system/identity. The card was originally + // BPoS-only ("BPoS supernode: not yet registered"). Now it + // branches: Council operators render Council-specific copy + // (member state, nickname, on-duty hint); BPoS operators keep + // the existing branches. Both can be true for the rare operator + // who is BOTH a CR member and a BPoS producer — Council wins as + // the primary identity since CRC arbiter slots are higher-tier + // than BPoS slots in Elastos's DPoS rotation. + var crMember = identity && identity.crMember; + var setupRole = identity && identity.setupRole; + var isCouncilContext = (setupRole === 'council') + || !!(crMember && crMember.isCrMember); + + // Visibility gate. The card hides only when (a) chain isn't + // alive (cards above this one already surface the outage), or + // (b) the operator has neither a Council install nor a BPoS + // operator role (a plain follower). var bposOperator = enabled || !!pubkey; - if (!alive || !bposOperator) { - this._hideAndRest(); + if (!alive) { this._hideAndRest(); return; } + if (!isCouncilContext && !bposOperator) { this._hideAndRest(); return; } + + // ----- COUNCIL BRANCH ------------------------------------------ + // Decision sub-tree for Council operators: + // crMember.isCrMember + state='Elected' → COUNCIL_ELECTED + // crMember.isCrMember + state='Inactive' → COUNCIL_INACTIVE + // crMember.isCrMember + state in {Impeached, + // Returned, Terminated, Illegal} → COUNCIL_IMPEACHED + // crMember.isCrMember + inNextCommittee=true → COUNCIL_NEXT_TERM + // setupRole='council' + no crMember matched + + // source='not-in-committee' → COUNCIL_UNCLAIMED + // setupRole='council' + source='no-active- + // committee' → COUNCIL_NO_TERM + // setupRole='council' + source='error' → render last-known + // good (don't flicker) + if (isCouncilContext) { + this._lastCrMember = crMember || null; + this._lastIdentity = identity; + // v0.5.229d (P9 audit fix) — operator may be BOTH a CR Council + // member AND a BPoS producer. Stash producer too so the + // Council card can render the dual-role secondary line. + this._lastProducer = producer || null; + if (crMember && crMember.isCrMember) { + var s = String(crMember.state || '').toLowerCase(); + if (crMember.inNextCommittee) { + this._show(STATE_COUNCIL_NEXT_TERM, pubkey); + return; + } + if (s === 'elected') { + this._show(STATE_COUNCIL_ELECTED, pubkey); + return; + } + if (s === 'inactive') { + this._show(STATE_COUNCIL_INACTIVE, pubkey); + return; + } + // Impeached / Returned / Terminated / Illegal → red banner. + this._show(STATE_COUNCIL_IMPEACHED, pubkey); + return; + } + // Council install, no current crMember match. + if (crMember && crMember.source === 'no-active-committee') { + this._show(STATE_COUNCIL_NO_TERM, pubkey); + return; + } + if (crMember && crMember.source === 'error') { + // Don't reshape on transient RPC failures. Keep the last + // good render; the chain-card already shows the outage. + return; + } + // Default Council fallback: install path but not bound to a + // current Committee seat (most common when the operator has + // unclaimed via Essentials, or hasn't claimed their node + // pubkey yet via CRCouncilMemberClaimNode). + this._show(STATE_COUNCIL_UNCLAIMED, pubkey); return; } + // ----- BPoS BRANCH (existing behavior preserved) --------------- + // 0.2.0-beta.3.4 — Active producer keeps the card visible with // a steady-state success-header render (per phase-03 mock). // 0.2.0-beta.3.7 — also stash the producer record so @@ -314,9 +414,31 @@ // for the registration / activation confirmation right now. this._setPollInterval(SHORT_POLL_MS); this.root.hidden = false; + // v0.5.229d (P5 audit fix) — also force a re-render when the + // underlying Council member data (impeachmentVotes, nickname + // refresh, state flip) has changed between polls, even if the + // bucket-level state hasn't. Pre-229d only the state-transition + // path triggered _render; static-within-bucket changes were + // silently dropped until something else flipped the bucket. + // The signature compares the few fields a real-time operator + // would care about; cheap and deterministic. + var crMember = this._lastCrMember || null; + var crSig = crMember + ? (crMember.isCrMember + '|' + (crMember.state || '') + '|' + + (crMember.impeachmentVotes || '') + '|' + + (crMember.nickname || '')) + : ''; + var crChanged = (crSig !== this._lastCrSig); if (this._renderedState !== state) { this._render(state); this._renderedState = state; + this._lastCrSig = crSig; + } else if (crChanged && this._renderedState + && String(this._renderedState).indexOf('council_') === 0) { + // Same bucket but Council data changed — re-render to + // reflect new nickname/state/impeachmentVotes. + this._render(state); + this._lastCrSig = crSig; } else if (state === STATE_ACTIVE) { // 0.2.0-beta.3.7 — when state stays ACTIVE across polls, // re-fill the stats grid in place. Rank/votes shift round @@ -352,6 +474,15 @@ // is written so the AT tree sees the relation immediately. this.root.setAttribute('aria-labelledby', this._titleId); + // v0.5.229 — Council branches first (CRC arbiter slots are + // higher-tier than BPoS slots in the DPoS rotation). + if (state === STATE_COUNCIL_ELECTED) { this._renderCouncil('elected'); return; } + if (state === STATE_COUNCIL_INACTIVE) { this._renderCouncil('inactive'); return; } + if (state === STATE_COUNCIL_IMPEACHED) { this._renderCouncil('impeached'); return; } + if (state === STATE_COUNCIL_NEXT_TERM) { this._renderCouncil('next-term'); return; } + if (state === STATE_COUNCIL_UNCLAIMED) { this._renderCouncil('unclaimed'); return; } + if (state === STATE_COUNCIL_NO_TERM) { this._renderCouncil('no-term'); return; } + if (state === STATE_ACTIVE) { this._renderActive(); return; @@ -364,6 +495,131 @@ this._renderRegistration(); }; + /** + * v0.5.229 — render a Council-mode card for the 6 sub-states. Mirrors + * the _renderActive / _renderActivation / _renderRegistration + * structure (head + cta-card + note + sr-only pubkey span) but uses + * Council vocabulary ("CR Council member", "CRC arbiter slot", + * "claim node binding") instead of BPoS vocabulary ("supernode", + * "register your supernode"). + * + * Sub-state copy decisions: + * elected — green success header, "On-duty when slot rotates in" + * inactive — amber header, "Recoverable by activate-via-Essentials" + * impeached — red header, terminal-ish (recovery is term-specific) + * next-term — amber, "Elected, waiting for next Committee term" + * unclaimed — amber, "Council install detected but pubkey not bound + * on-chain — claim via Essentials" + * no-term — gray, "Committee not currently in election period" + */ + BposCard.prototype._renderCouncil = function (subState) { + var t = root.enmTOrFallback; + var titleId = this._titleId; + var chipId = this._chipId; + var self = this; + var cr = this._lastCrMember || null; + + // sub-state → copy + chip styling. Reused across the 6 branches + // so the markup stays a single innerHTML template. + var subMeta = { + 'elected': { chipCls: 'success', chipLabel: 'On-duty', headBg: 'success' }, + 'inactive': { chipCls: 'warn', chipLabel: 'Inactive', headBg: 'warn' }, + 'impeached': { chipCls: 'danger', chipLabel: cr && cr.state ? cr.state : 'Impeached', headBg: 'danger' }, + 'next-term': { chipCls: 'warn', chipLabel: 'Next term', headBg: 'warn' }, + 'unclaimed': { chipCls: 'warn', chipLabel: 'Unclaimed', headBg: 'warn' }, + 'no-term': { chipCls: 'muted', chipLabel: 'Between terms', headBg: 'muted' }, + }[subState] || { chipCls: 'muted', chipLabel: '—', headBg: 'muted' }; + + // v0.5.229 patch — t() is enmTOrFallback which takes (key, vars), + // NOT (key, fallback). A second-arg string is misread as vars + // and missing keys render as the literal "[key]" placeholder + // in the UI. Strings live in strings.js under council_card.* + // (added in the same patch). Defensive fallback table below + // catches the case where strings.js is older than this code. + var titleKey = 'council_card.head_title_' + subState.replace('-', '_'); + var subKey = 'council_card.head_sub_' + subState.replace('-', '_'); + var FALLBACK_TITLES = { + 'elected': 'CR Council member — On-duty', + 'inactive': 'CR Council member — Inactive', + 'impeached': 'CR Council member — ' + (cr && cr.state ? cr.state : 'Impeached'), + 'next-term': 'CR Council member — Next term', + 'unclaimed': 'Council install — Not currently bound', + 'no-term': 'Council install — Committee between terms', + }; + var FALLBACK_SUBS = { + 'elected': 'Your node is in the on-chain CR Committee arbiter slate. EVM sidechain mining + mainchain BPoS signing activate automatically when your slot rotates in.', + 'inactive': 'You are a CR Committee member but on-chain MemberState is Inactive (the chain skipped your slot for too many consecutive rounds). Recover via Essentials → Activate.', + 'impeached': 'Your CR Committee membership has been impeached, terminated, returned, or flagged illegal on-chain. The current term seat is lost; check Essentials for the specific reason and recovery options.', + 'next-term': 'You won the next CR Committee election. Your node will enter the arbiter slate when the next term begins.', + 'unclaimed': 'ENM detects a Council install but your node\'s public key is not currently bound to any CR Committee seat on-chain. If you intend to be a Council member, claim your node via Elastos Essentials (CRCouncilMemberClaimNode TX).', + 'no-term': 'The CR Council is not currently in an election period. No active Committee means no arbiter slots to fill — your node will be added when the next term begins.', + }; + var rawTitle = t(titleKey); + var rawSub = t(subKey); + // enmT returns "[key]" verbatim when the key is missing. Detect + // that and fall through to the in-JS English instead. + var headTitle = (rawTitle && rawTitle.indexOf('[') !== 0) + ? rawTitle : (FALLBACK_TITLES[subState] || 'CR Council member'); + var headSub = (rawSub && rawSub.indexOf('[') !== 0) + ? rawSub : (FALLBACK_SUBS[subState] || ''); + + // Build the head + cta-card + optional info-grid markup. + var infoRows = ''; + if (cr && (cr.nickname || cr.state || cr.cid)) { + infoRows = '' + + '
    ' + + (cr.nickname ? '
    Nickname
    ' + escapeHtml(cr.nickname) + '
    ' : '') + + (cr.state ? '
    State
    ' + escapeHtml(cr.state) + '
    ' : '') + + (typeof cr.index === 'number' + ? '
    Index
    ' + cr.index + '
    ' + : '') + + (cr.cid ? '
    CID
    ' + escapeHtml(cr.cid) + '
    ' : '') + + (cr.impeachmentVotes && cr.impeachmentVotes !== '0' ? '
    Impeach votes
    ' + escapeHtml(cr.impeachmentVotes) + '
    ' : '') + + '
    '; + } + + // v0.5.229d (P9 audit fix) — dual-role secondary line. If this + // operator is BOTH a CR Council member AND a BPoS producer + // (the rare-but-legal case), surface the BPoS producer state + // as a secondary line under the Council head. Council primacy + // is preserved (Council outranks BPoS in DPoS rotation); BPoS + // is informational. + var dualRoleLine = ''; + if (this._lastProducer && this._lastProducer.state) { + dualRoleLine = '' + + '
    ' + + 'Also a BPoS producer · ' + escapeHtml(this._lastProducer.state) + + (this._lastProducer.rank != null ? (' · Rank #' + this._lastProducer.rank) : '') + + '
    '; + } + + this.root.innerHTML = '' + + '
    ' + + '' + + '
    ' + + '
    ' + + escapeHtml(headTitle) + + '
    ' + + '
    ' + + escapeHtml(headSub) + + '
    ' + + dualRoleLine + + '
    ' + + '' + + escapeHtml(subMeta.chipLabel) + + '' + + '
    ' + + infoRows + + ''; + }; + /** * 0.2.0-beta.3.4 — STATE_ACTIVE render. Operator's producer is on * chain AND in Active state; the card stays visible with a success @@ -620,17 +876,19 @@ + '
    ' + '
    ' - + '
    ' - + '
    ' - + escapeHtml(t('bpos_card.signing_key_label')) - + '
    ' - + '
    '
    -                    + escapeHtml(t('common.loading'))
    -                + '
    ' - + '
    ' - + escapeHtml(t('bpos_card.note_after_confirm')) - + '
    ' - + '
    '; + // v0.5.228 — the pubkey display block (label +
     + note)
    +            // duplicates the Node Identity card above (which now renders
    +            // the pubkey at primary visual weight). One source of truth
    +            // wins; the Copy button still works (the value resolver below
    +            // pulls from self._lastPubkey, no DOM dependency). A hidden
    +            //  stays so _fillPubkey is a true
    +            // no-op and getDisplayEl has something to fall back to if the
    +            // clipboard API ever fails (the copy button auto-selects it
    +            // off-screen — same UX outcome as before, no duplicated
    +            // pubkey on screen).
    +            + '';
     
             // Replace the copy slot with the enmCopyButton factory. The
             // factory hands back a fully-wired '
    -                              + '

    ⚠ The other Identity controls are locked until you confirm. If you lose this password, your keystore is unrecoverable.

    ' - + '
    '; - // Wire copy button on the password. - var pwEl = self._identity.resetReveal.querySelector('.enm-password-value'); - if (typeof root.enmCopyButton === 'function' && newPw) { - var copyBtn = root.enmCopyButton({ - value: newPw, - label: t('friendly.setup.card_c.cta_copy') || 'Copy', - copiedLabel: t('friendly.setup.card_c.cta_copied') || 'Copied!', - ariaLabel: 'Copy new password', - resetMs: 1500, - notifications: self.notifications, - getDisplayEl: function () { return pwEl; }, - }); - copyBtn.classList.add('enm-password-copy'); - var slot = self._identity.resetReveal.querySelector('.enm-password-copy-slot'); - if (slot && slot.parentNode) { - slot.parentNode.replaceChild(copyBtn, slot); - } - } - // Wire the ack-gate handlers + lock the rest of - // Identity until the operator confirms. - self._resetRevealPendingAck = true; - var lockTargets = [ - self._identity.currentCard, - self._identity.unlockCard, - self._identity.backupCard, - self._identity.importCard, - self._identity.integrity && self._identity.integrity.card, - ]; - lockTargets.forEach(function (el) { - if (el) { - el.setAttribute('inert', ''); - el.setAttribute('aria-hidden', 'true'); - el.style.opacity = '0.35'; - el.style.pointerEvents = 'none'; - } - }); - // Also disable the Reset card's own Reset button - // so the operator can't trigger ANOTHER reset - // (would generate yet another password without - // saving this one). - if (self._identity.resetBtn) { - self._identity.resetBtn.disabled = true; - } - var ackBox = self._identity.resetReveal.querySelector('[data-fill="reveal-ack"]'); - var last4Input = self._identity.resetReveal.querySelector('[data-fill="reveal-last4"]'); - var dismissBtn = self._identity.resetReveal.querySelector('[data-action="reveal-dismiss"]'); - function refreshGate() { - var typed = (last4Input.value || '').trim().toLowerCase(); - dismissBtn.disabled = !(ackBox.checked && typed === last4.toLowerCase()); - } - ackBox.addEventListener('change', refreshGate); - last4Input.addEventListener('input', refreshGate); - dismissBtn.addEventListener('click', function () { - if (dismissBtn.disabled) { return; } - // Operator confirmed — re-enable everything. - self._resetRevealPendingAck = false; - self._identity.resetReveal.hidden = true; - self._identity.resetReveal.innerHTML = ''; - lockTargets.forEach(function (el) { - if (el) { - el.removeAttribute('inert'); - el.removeAttribute('aria-hidden'); - el.style.opacity = ''; - el.style.pointerEvents = ''; - } - }); - if (self._identity.resetBtn) { - self._identity.resetBtn.disabled = true; // typed-confirm still empty - } - self._refreshIdentity(); - }); - status.textContent = t('settings.identity_reset_ok'); - status.classList.add('ok'); - confirmObj.input.value = ''; - btn.disabled = true; - if (typeof self.api.invalidate === 'function') { - try { self.api.invalidate('/system/identity'); } - catch (_) { /* ignore */ } - } - // Deferred — _refreshIdentity now early-returns - // while _resetRevealPendingAck is true (see method), - // so it'll fire after the operator acks. - }) - .catch(function (err) { - if (self._destroyed) { return; } - // 0.5.131 audit Session 131 — silence on 401, see _refreshIdentity line 2221. - if (err && err.status === 401) { return; } - status.textContent = (err && err.message) || 'Reset failed.'; - status.classList.add('err'); - }); - }); - }; + // v0.5.232 — SettingsTab.prototype._doIdentityReset removed. The + // standalone keystore-reset flow was folded into Settings → Reset + // ENM (see _doResetEverything below). The 150-line method that lived + // here, including the reveal-ack flow with last-4 anti-typo gate, is + // preserved in git history (commit b19c15bf and earlier) for any + // future work that needs to revive a narrower rotation path. /** Build a labelled control row used inside Identity sub-cards. */ function _wrapLabel(labelText, control) { diff --git a/src/backend/apps/elastos-node-manager/js/strings.js b/src/backend/apps/elastos-node-manager/js/strings.js index 08362f112c..7d81e20a5f 100644 --- a/src/backend/apps/elastos-node-manager/js/strings.js +++ b/src/backend/apps/elastos-node-manager/js/strings.js @@ -1383,7 +1383,7 @@ // titles, and one who's about to type the confirmation // word has the consequences in front of them. heading_danger: 'Danger Zone', - danger_intro: 'Destructive actions. Each one has a typed-confirmation gate. There is no undo.', + danger_intro: 'Destructive actions. Each one has a typed-confirmation gate. There is no undo. To remove ENM entirely from PC2, right-click the ENM tile on the PC2 desktop and choose Uninstall — these in-app controls operate on data only.', // Update card (least destructive — top of section). danger_update_title: 'Update ENM', @@ -1398,33 +1398,40 @@ danger_update_in_progress: 'Update in progress — ENM will restart in a few seconds…', danger_update_queued: '✓ Update queued. Reload this page after ~30 seconds to see the new version.', - // Chain resync card. - danger_resync_title: 'Chain resync (keep keystore)', - danger_resync_help: 'Wipe the chain database and re-sync from the network. Your keystore and settings are preserved. Use this if the chain is stuck, corrupted, or stuck on a forked tip. A re-sync from genesis can take 4–8 hours.', - danger_resync_confirm_label: 'Type the chain name to confirm:', - danger_resync_btn: 'Resync chain', - danger_resync_confirm_dialog: 'This will delete all chain data and start a fresh sync. Your keystore is backed up first and stays on disk. Continue?', - danger_resync_in_progress: 'Stopping chain, wiping data, restarting…', + // Chain resync card — v0.5.232 mode-aware (BPoS vs Council). + // The card paints differently based on the operator's setupRole: + // BPoS gets a single "Resync mainchain" button; Council gets a + // checkbox list across {mainchain, esc, eid, pg}. Shared copy + // (title/help/status) is generic; mode-specific keys layer on. + danger_resync_title: 'Resync chain data', + danger_resync_help: 'Wipe one or more chains and re-sync from the network. Your keystore and node identity are preserved. Use this if a chain is stuck, corrupted, or has forked off the network. A full re-sync from genesis can take 4–8 hours per chain.', + danger_resync_in_progress: 'Wiping chain data, restarting…', danger_resync_ok: '✓ Chain data wiped. Re-sync started — may take 4–8 hours.', - - // App removal card (uninstall extension only). - danger_remove_title: 'Remove app (keep chain data + keystore)', - danger_remove_help: 'Uninstall the ENM extension from PC2. Your chain data, keystore, and audit log stay on disk so you can reinstall later and pick up where you left off.', - danger_remove_confirm_label: 'Type "remove" to confirm:', - danger_remove_btn: 'Remove app', - danger_remove_confirm_dialog: 'Uninstall the ENM extension? Your chain data, keystore, and audit log stay on disk so reinstall can recover them.', - danger_remove_in_progress: 'Uninstalling ENM in a few seconds…', - danger_remove_queued: '✓ Uninstall queued. ENM will be removed within ~10 seconds — this page will disconnect when it does. Chain data + keystore stay on disk.', - - // Nuclear card (uninstall AND wipe everything). - danger_nuke_title: 'Nuclear — remove app AND wipe everything', - danger_nuke_help: 'Uninstall the ENM extension AND delete every piece of ENM data, including your keystore. This is the truly-start-from-zero option. There is no recovery without an off-server backup of the keystore.', - danger_nuke_warning: 'This deletes your keystore. If you re-register afterwards — as a BPoS supernode (producer-register TX) or rebind a CR Council seat (CRCouncilMemberClaimNode TX) — you do so with a new node identity (a different public key). Any stake delegated to your current OwnerPublicKey remains under your control in Elastos Essentials regardless of what happens to this node.', - danger_nuke_confirm_label: 'Type WIPE EVERYTHING (uppercase) to confirm:', - danger_nuke_btn: 'Wipe everything', - danger_nuke_confirm_dialog: 'This will DELETE your keystore. There is no undo. Continue?', - danger_nuke_in_progress: 'Wiping everything in a few seconds…', - danger_nuke_queued: '✓ Nuclear wipe queued. ENM and all its data will be removed within ~10 seconds — this page will disconnect when it does.', + danger_resync_no_selection: 'Pick at least one chain to resync.', + + // v0.5.232 — BPoS variant (single mainchain). + danger_resync_bpos_help: 'BPoS supernodes only run the ELA mainchain — confirm to wipe its data and resync from peers.', + danger_resync_bpos_confirm_label: 'Type "mainchain" to confirm:', + danger_resync_bpos_btn: 'Resync mainchain', + + // v0.5.232 — Council variant (multi-chain). + danger_resync_council_help: 'Council nodes run four chains with on-disk data. Tick the ones you want to wipe (default all), then type RESYNC to confirm. Each chain wipes serially — total time scales linearly with selection.', + danger_resync_council_confirm_label: 'Type RESYNC (uppercase) to confirm:', + danger_resync_council_btn: 'Resync selected chains', + + // v0.5.232 — Reset ENM (the single in-app full wipe). + // Replaces the retired uninstall + nuke + identity/reset cards. + // Wipes ALL data but KEEPS the bundle installed, so the wizard + // reappears in place when ENM respawns — fixes the historical + // "another pc2 inside the app" bug where the orphaned iframe + // loaded the pc2 desktop root after a full uninstall. + danger_reset_title: 'Reset ENM (full wipe)', + danger_reset_help: 'Wipes ALL data — chain databases, keystore, node identity, settings, audit log, healing history — and restarts ENM with the setup wizard. The app stays installed in PC2; this page reloads automatically. There is no undo.', + danger_reset_warning: 'This deletes your keystore + node identity. If you re-register afterwards — as a BPoS supernode (producer-register TX) or rebind a CR Council seat (CRCouncilMemberClaimNode TX) — you do so with a new node identity (a different public key). Any stake delegated to your current OwnerPublicKey remains under your control in Elastos Essentials regardless of what happens to this node.', + danger_reset_confirm_label: 'Type RESET EVERYTHING (uppercase) to confirm:', + danger_reset_btn: 'Reset ENM', + danger_reset_in_progress: 'Wiping data — ENM will restart in a few seconds…', + danger_reset_queued: '✓ Reset queued. ENM will restart and reload this page in ~6 seconds. The setup wizard will reappear.', // v0.5.228 — EVM chains (shared settings). Operator directive // 2026-05-27: shared settings across esc/eid/pg should live in From 5c5a25230d1f604660ce529827f3e82837d6505d Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Wed, 27 May 2026 23:32:51 +0300 Subject: [PATCH 05/24] =?UTF-8?q?enm=20v0.5.233=20=E2=80=94=20v0.5.232=20f?= =?UTF-8?q?ollow-up=20cleanup=20of=20orphan=20refs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three small cleanups discovered when the operator asked to verify that all PC2-side changes related to retired destructive ops had been removed: 1. routes/identity.js — drop two orphans left when POST /identity/reset was retired in v0.5.232: - `RESET_CONFIRM_PHRASE` constant (only caller was the retired handler) - `_verifyAntiSnipe()` helper (only caller was the retired handler; SelfHealingEngine._verifyAntiSnipePassword is the canonical verifier) Both replaced with v0.5.232 marker comments so the diff reviewer can see what was retired without git-blame archaeology. 2. js/strings.js — drop 8 orphan `identity_reset_*` strings: title / help / confirm_label / btn / confirm_dialog / running / ok / password_warning. The only consumer was the standalone "Reset keystore" card, which v0.5.232 removed. Replaced with a marker comment. 3. js/components/audit-tab.js — add the friendly-name mapping for the new `POST /maintenance/reset-everything` endpoint ("Started full ENM reset"). The retired endpoints' mappings stay, suffixed with "(retired)", so historical audit rows (and any 410-rejection rows from operators with stale frontends) still render with operator-meaningful copy. VERIFIED: no other source file references the removed symbols: - `RESET_CONFIRM_PHRASE` — 0 live refs (1 marker comment) - `_verifyAntiSnipe` — 0 live refs (1 marker comment) - `identity_reset_*` — 0 live refs (1 marker comment) - `_doNuke / _doUninstall / _doIdentityReset` — 0 live refs PC2-SIDE AUDIT (in response to operator's question): The pc2-node side has NO ENM-specific destructive paths that need removing. The teardown endpoint in ENM's bundle manifest (`backend.teardown: { endpoint: '/api/enm/teardown' }` in pc2-node/scripts/package-app.mjs:235) is STILL needed — it's what pc2-node POSTs when the operator uses pc2 desktop right-click → Uninstall (the pc2-level removal path that the operator explicitly wanted preserved). The corresponding ENM /teardown handler at enm-server/src/server.js:202 stays as-is; it gracefully stops chains + flushes DB state before pc2 wipes the data dir. `scripts/deploy-enm.sh` was checked for any references to the retired endpoints (`/maintenance/uninstall`, `/maintenance/nuke`, `/identity/reset`, `WIPE EVERYTHING`) — none found. The deploy script's `DELETE /api/installed-apps/elastos-node-manager?purge=false` + `install-local` flow operates at the pc2-node level, not via the ENM-app destructive endpoints we retired. No PC2 customizations are obsolete. DIFF SUMMARY (4 files, +27/-30 = net -3 LOC): - enm-server/package.json +1/-1 - enm-server/src/routes/identity.js +6/-19 - js/components/audit-tab.js +9/-3 - js/strings.js +11/-7 Co-Authored-By: Claude Opus 4.7 (1M context) --- enm-server/package.json | 2 +- enm-server/src/routes/identity.js | 27 ++++++------------- .../js/components/audit-tab.js | 13 ++++++--- .../apps/elastos-node-manager/js/strings.js | 14 +++++----- 4 files changed, 25 insertions(+), 31 deletions(-) diff --git a/enm-server/package.json b/enm-server/package.json index bf53f77395..966b6a4176 100644 --- a/enm-server/package.json +++ b/enm-server/package.json @@ -1,6 +1,6 @@ { "name": "@elacity/enm-server", - "version": "0.5.232", + "version": "0.5.233", "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode AND CR Council operators.", "main": "src/server.js", "author": "Elacity", diff --git a/enm-server/src/routes/identity.js b/enm-server/src/routes/identity.js index abb1de2bd2..7beeda292d 100644 --- a/enm-server/src/routes/identity.js +++ b/enm-server/src/routes/identity.js @@ -67,7 +67,9 @@ const LOCKED_IN_PRODUCER_STATES = new Set([ ]); const CHAIN_ID = 'mainchain'; -const RESET_CONFIRM_PHRASE = 'reset keystore'; +// v0.5.232 — RESET_CONFIRM_PHRASE removed along with POST /identity/reset. +// The unified Settings → Reset ENM flow lives in routes/maintenance.js +// (POST /maintenance/reset-everything, confirm: "RESET EVERYTHING"). const IMPORT_CONFIRM_PHRASE = 'import'; const MAX_IMPORT_BYTES = 10 * 1024; @@ -413,24 +415,11 @@ async function _producerStateIndeterminate(producer) { } } -/** - * scrypt verify against `scrypt$$` shape produced - * by beta.3.10's anti-snipe setter route. - */ -function _verifyAntiSnipe(stored, attempt) { - const crypto = require('node:crypto'); - return new Promise((resolve) => { - const m = /^scrypt\$([a-fA-F0-9]+)\$([a-fA-F0-9]+)$/.exec(stored); - if (!m) { return resolve(false); } - const salt = Buffer.from(m[1], 'hex'); - const want = Buffer.from(m[2], 'hex'); - crypto.scrypt(attempt, salt, want.length, (err, derived) => { - if (err) { return resolve(false); } - try { resolve(crypto.timingSafeEqual(derived, want)); } - catch (_) { resolve(false); } - }); - }); -} +// v0.5.232 — _verifyAntiSnipe() removed. Its only caller was the retired +// POST /identity/reset handler. The canonical anti-snipe verifier is +// SelfHealingEngine._verifyAntiSnipePassword (same scrypt$$ +// shape, see services/SelfHealingEngine.js:1125) — use that if any +// future code needs to gate destructive actions on anti-snipe. /** * Best-effort audit write. Never blocks the action — operator already diff --git a/src/backend/apps/elastos-node-manager/js/components/audit-tab.js b/src/backend/apps/elastos-node-manager/js/components/audit-tab.js index 0eeac53577..f56d2572ef 100644 --- a/src/backend/apps/elastos-node-manager/js/components/audit-tab.js +++ b/src/backend/apps/elastos-node-manager/js/components/audit-tab.js @@ -1328,11 +1328,18 @@ 'POST /config/rollback': 'Rolled back config', 'POST /maintenance/update': 'Started ENM update', 'POST /maintenance/chain-resync': 'Started chain resync', - 'POST /maintenance/uninstall': 'Started app uninstall', - 'POST /maintenance/nuke': 'Started nuclear wipe', + 'POST /maintenance/reset-everything': 'Started full ENM reset', + // v0.5.232 — these three endpoints were retired and now return + // 410 Gone, but the friendly-name mappings stay so historical + // audit rows from before v0.5.232 (and any 410 rejection rows + // written by the retired-endpoint handlers themselves) still + // render with operator-meaningful copy. Remove after the audit + // retention window has rolled over (~12 months). + 'POST /maintenance/uninstall': 'Started app uninstall (retired)', + 'POST /maintenance/nuke': 'Started nuclear wipe (retired)', 'POST /identity/unlock': 'Unlocked keystore', 'POST /identity/import': 'Imported keystore', - 'POST /identity/reset': 'Reset keystore', + 'POST /identity/reset': 'Reset keystore (retired)', 'POST /identity/integrity/rebaseline': 'Re-baselined integrity', // Setup-wizard transitions (alpha era — kept for older rows). 'POST /setup/install/:chainId': 'Installed binary', diff --git a/src/backend/apps/elastos-node-manager/js/strings.js b/src/backend/apps/elastos-node-manager/js/strings.js index 7d81e20a5f..05f4204345 100644 --- a/src/backend/apps/elastos-node-manager/js/strings.js +++ b/src/backend/apps/elastos-node-manager/js/strings.js @@ -1532,14 +1532,12 @@ identity_import_running: 'Validating and swapping keystore…', identity_import_ok: '✓ Keystore restored from backup.', - identity_reset_title: 'Reset keystore (new identity)', - identity_reset_help: 'Generate a fresh keystore with a new password. The current one is auto-archived. The new public key will NOT match any existing on-chain producer registration.', - identity_reset_confirm_label: 'Type "reset keystore" to confirm:', - identity_reset_btn: 'Reset keystore', - identity_reset_confirm_dialog: 'This generates a new keystore and shows a new password ONCE. Continue?', - identity_reset_running: 'Stopping chain, generating new keystore, restarting…', - identity_reset_ok: '✓ New keystore generated.', - identity_reset_password_warning:'Save this password somewhere safe — it’s shown only once and unlocks the new keystore.', + // v0.5.232 — identity_reset_* keys dropped along with the + // standalone "Reset keystore" card. The unified Settings → + // Reset ENM flow handles full reset (keystore + chain data + // atomically). Keys lived here originally for the dedicated + // card's title / help / confirm-label / btn / running / + // ok / password_warning copy — preserved in git history. identity_password_required: 'Password is required.', From 82e3da56c05a08ee8d624e58f1319476c9c071d2 Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Wed, 27 May 2026 23:51:59 +0300 Subject: [PATCH 06/24] =?UTF-8?q?enm=20v0.5.234=20=E2=80=94=20UI=20brandin?= =?UTF-8?q?g=20fix:=20PG=20is=20NOT=20for=20privacy=20+=20canonical=20chai?= =?UTF-8?q?n=20names?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Operator caught a branding bug in v0.5.232's new Resync card: the checkbox list labeled PG as "Privacy", which is wrong. PG is a PUBLIC EVM PBFT sidechain (see strings.js:438 / Session 28's explicit fix — "PG is a PUBLIC EVM PBFT sidechain. The binary is closed-source (operator-supplied SHA256 manifest gate), but the CHAIN ITSELF isn't private in the permissioned-access sense the label implied"). This commit normalizes the chain display names ACROSS all the v0.5.231/ 232 new features to match the canonical convention used elsewhere in the app (verified against PgAdapter.js displayName, EscAdapter.js displayName, EidAdapter.js displayName, and strings.js wizard copy). Canonical UI display names (verified across the app): chainId display name --------------------------------------- mainchain → "Main chain" (space, capital M) esc → "ESC (Smart Chain)" (NOT "Smart Contract") eid → "EID (Identity Chain)" pg → "PG" (NO parenthetical — public chain) Changes: 1. settings-tab.js COUNCIL_CHAINS array (4 wrong labels): - 'ELA mainchain' → 'Main chain' - 'ESC (Smart Contract)' → 'ESC (Smart Chain)' - 'EID (Identity)' → 'EID (Identity Chain)' - 'PG (Privacy)' → 'PG' Added an inline comment citing strings.js:438 + Session 28 so a future drive-by edit doesn't reintroduce "PG (Privacy)". 2. strings.js v0.5.232 BPoS strings: - danger_resync_bpos_help: "ELA mainchain" → "Main chain" - danger_resync_bpos_btn: "Resync mainchain" → "Resync Main chain" Typed-confirm value stays the literal "mainchain" — the backend's gate matches that lowercase chainId, so the placeholder + expected string are the literal token the operator types. 3. HealthRules.js detectF26 — v0.5.231 proposal copy used the raw lowercase snap.chainId in the operator-facing card text ("Confirm resync of eid (suspected fork wedge)"). v0.5.234 maps chainId to canonical display via an inline helper so the proposal reads "Confirm resync of EID (suspected fork wedge)" / "Confirm resync of Main chain (suspected fork wedge)". Same convention as the rest of the UI. 4. settings-tab.js Network pane label (pre-existing): "Mining address (ELA mainchain)" → "Mining address (Main chain)" Same wrong-branding pattern as v0.5.232's BPoS strings; while we were normalizing the new features it was sitting one screen over. 5. strings.js snapshot wizard hint (pre-existing): "Downloads ~10 GB so the ELA mainchain skips its 1–3 day genesis sync" → "Downloads ~10 GB so the Main chain skips its 1–3 day genesis sync". Same pattern. 6. settings-tab.js _refreshDangerResyncCard docstring — updated to match the new button text ("Resync Main chain", not "Resync mainchain") so a future reader isn't misled by the stale doc. Out of scope (pre-existing copy that's a style decision, not a bug): - Compound forms like "mainchain snapshot" / "mainchain block" / "mainchain data" / "the mainchain dashboard" — these are established compound nouns in the wizard / dashboard / multi- chain overview copy. Normalizing them is a separate copy-pass. - Any other pre-existing "mainchain" lowercase references in the wizard / setup-conversation / chain-card components that aren't clearly broken. VERIFIED (working tree branding sweep): $ grep -nE "ELA mainchain|Smart Contract|PG \(Privacy|EID \(Identity\)|Resync mainchain" → 0 hits Diff summary (4 files, +32/-12 = net +20 LOC): - enm-server/package.json +1/-1 - enm-server/src/services/HealthRules.js +11/-2 (chainDisplay helper + 2 callsites) - js/components/settings-tab.js +12/-6 (COUNCIL_CHAINS labels + Mining-addr label + docstring) - js/strings.js +8/-3 (BPoS help/btn + snapshot hint) Co-Authored-By: Claude Opus 4.7 (1M context) --- enm-server/package.json | 2 +- enm-server/src/services/HealthRules.js | 13 +++++++++++-- .../js/components/settings-tab.js | 18 ++++++++++++------ .../apps/elastos-node-manager/js/strings.js | 11 ++++++++--- 4 files changed, 32 insertions(+), 12 deletions(-) diff --git a/enm-server/package.json b/enm-server/package.json index 966b6a4176..4860ff7cc7 100644 --- a/enm-server/package.json +++ b/enm-server/package.json @@ -1,6 +1,6 @@ { "name": "@elacity/enm-server", - "version": "0.5.233", + "version": "0.5.234", "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode AND CR Council operators.", "main": "src/server.js", "author": "Elacity", diff --git a/enm-server/src/services/HealthRules.js b/enm-server/src/services/HealthRules.js index a8a9a8f177..76bb94f131 100644 --- a/enm-server/src/services/HealthRules.js +++ b/enm-server/src/services/HealthRules.js @@ -1052,15 +1052,24 @@ function detectF26(snap) { if (peerTip <= 0) return null; if ((peerTip - localHeight) < F26_NEAR_TIP_BLOCKS_GUARD) return null; + // v0.5.234 — branding pass: use the canonical display name in the + // operator-facing proposal copy instead of the raw lowercase chainId. + // Convention is "Main chain" for mainchain and all-caps for the EVM + // sidechains (ESC/EID/PG), per strings.js (~line 444) + session 28's + // wizard sub copy. PG is a PUBLIC EVM PBFT sidechain — never + // parenthesise it as "(Privacy)". + const chainDisplay = snap.chainId === 'mainchain' + ? 'Main chain' + : (snap.chainId || '').toUpperCase(); return { ruleId: 'F26', // v0.5.231 — NEVER auto-execute. Operator confirms every destructive // wipe; the rate-limit/escalation logic in SelfHealingEngine stays in // place to add context (e.g. "this chain was wiped in the last 24h"). tier: HEALING_TIERS.OWNER_CONFIRMS, - summaryAction: `Confirm resync of ${snap.chainId} (suspected fork wedge)`, + summaryAction: `Confirm resync of ${chainDisplay} (suspected fork wedge)`, summaryReason: - `${snap.chainId} has been stuck at block ${snap.rpcSummary.height} for >20 min, the network ` + `${chainDisplay} has been stuck at block ${snap.rpcSummary.height} for >20 min, the network ` + `tip is at block ${peerTip} (${peerTip - localHeight} blocks ahead), and its node log has ` + 'shown "retrieved hash chain is invalid" persistently for the last several health checks — ' + 'the local chain data appears to have forked off the network and cannot recover by ' diff --git a/src/backend/apps/elastos-node-manager/js/components/settings-tab.js b/src/backend/apps/elastos-node-manager/js/components/settings-tab.js index 3bd00a7fe7..e0ec1109ff 100644 --- a/src/backend/apps/elastos-node-manager/js/components/settings-tab.js +++ b/src/backend/apps/elastos-node-manager/js/components/settings-tab.js @@ -988,7 +988,7 @@ }); var wlist = document.createElement('div'); wlist.className = 'enm-detail-list'; - wlist.appendChild(kv('Mining address (ELA mainchain)', addr, true)); + wlist.appendChild(kv('Mining address (Main chain)', addr, true)); wlist.appendChild(kv('SideChainPow fee (ELA)', String(fee), false)); wallet.body.appendChild(wlist); parent.appendChild(wallet.card); @@ -2633,7 +2633,7 @@ /** * v0.5.232 — Paint the Resync sub-card based on the operator's * setupRole. Called on Danger Zone section activation, idempotent. - * BPoS gets a single "Resync mainchain" button; Council gets a + * BPoS gets a single "Resync Main chain" button; Council gets a * checkbox list of {mainchain, esc, eid, pg} with "Resync selected" * + a static "RESYNC" typed-confirm gate. */ @@ -2705,11 +2705,17 @@ pane.modeContainer.appendChild(help); var list = document.createElement('div'); list.className = 'enm-danger-resync-checklist'; + // v0.5.234 — canonical UI display names. Verified against the rest + // of the app: "Main chain" (space, capital M only) for ELA; "ESC + // (Smart Chain)" / "EID (Identity Chain)" for those two EVMs; just + // "PG" with NO parenthetical for PG — PG is a PUBLIC EVM PBFT + // sidechain, not a privacy chain (see strings.js line ~438 / Session + // 28 comment fixing the previously wrong "PG (private chain)" label). var COUNCIL_CHAINS = [ - { id: 'mainchain', label: 'ELA mainchain' }, - { id: 'esc', label: 'ESC (Smart Contract)' }, - { id: 'eid', label: 'EID (Identity)' }, - { id: 'pg', label: 'PG (Privacy)' }, + { id: 'mainchain', label: 'Main chain' }, + { id: 'esc', label: 'ESC (Smart Chain)' }, + { id: 'eid', label: 'EID (Identity Chain)' }, + { id: 'pg', label: 'PG' }, ]; COUNCIL_CHAINS.forEach(function (c) { var row = document.createElement('label'); diff --git a/src/backend/apps/elastos-node-manager/js/strings.js b/src/backend/apps/elastos-node-manager/js/strings.js index 05f4204345..66e359edfd 100644 --- a/src/backend/apps/elastos-node-manager/js/strings.js +++ b/src/backend/apps/elastos-node-manager/js/strings.js @@ -494,7 +494,7 @@ sub_bpos: 'A quick pre-flight then we kick the mainchain install off.', rerun: 'Re-run pre-flight', snapshot_label: 'Use official mainchain snapshot (recommended)', - snapshot_hint: 'Default ON. Downloads ~10 GB so the ELA mainchain skips its ' + snapshot_hint: 'Default ON. Downloads ~10 GB so the Main chain skips its ' + '1–3 day genesis sync. Needs ~220 GB free disk for the full ' + 'Council install (chaindata growth dominates, not the snapshot).', // v0.5.199 — explicit EVM-cold-sync disclosure. The Card 5 @@ -1410,9 +1410,14 @@ danger_resync_no_selection: 'Pick at least one chain to resync.', // v0.5.232 — BPoS variant (single mainchain). - danger_resync_bpos_help: 'BPoS supernodes only run the ELA mainchain — confirm to wipe its data and resync from peers.', + // v0.5.234 — branding pass: "ELA mainchain" → "Main chain" + + // "Resync mainchain" → "Resync Main chain" for parity with the + // rest of the app. Typed-confirm value stays the literal + // chainId "mainchain" because the backend gate matches that + // exact lowercase token. + danger_resync_bpos_help: 'BPoS supernodes only run the Main chain — confirm to wipe its data and resync from peers.', danger_resync_bpos_confirm_label: 'Type "mainchain" to confirm:', - danger_resync_bpos_btn: 'Resync mainchain', + danger_resync_bpos_btn: 'Resync Main chain', // v0.5.232 — Council variant (multi-chain). danger_resync_council_help: 'Council nodes run four chains with on-disk data. Tick the ones you want to wipe (default all), then type RESYNC to confirm. Each chain wipes serially — total time scales linearly with selection.', From 4103aedf559853f85ed24943e0b53f698034a59c Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Wed, 27 May 2026 23:57:05 +0300 Subject: [PATCH 07/24] docs(enm): refresh stale BPoS-card comment to match v0.5.234 button text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Comment-only follow-up to v0.5.234. The _refreshDangerResyncCard docstring still said "Resync mainchain" / "{mainchain, esc, eid, pg}" after v0.5.234 renamed the button to "Resync Main chain" + the visible checkbox labels to {Main chain, ESC, EID, PG}. Source-only; no runtime change, no version bump, no redeploy needed. The other "PG (private chain)" reference in the same file (line ~2713) intentionally STAYS — it documents the previously-wrong label as historical context, with a Session 28 citation to block future regressions. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../elastos-node-manager/js/components/settings-tab.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/backend/apps/elastos-node-manager/js/components/settings-tab.js b/src/backend/apps/elastos-node-manager/js/components/settings-tab.js index e0ec1109ff..960bee5f37 100644 --- a/src/backend/apps/elastos-node-manager/js/components/settings-tab.js +++ b/src/backend/apps/elastos-node-manager/js/components/settings-tab.js @@ -2321,10 +2321,10 @@ // Pre-v0.5.232 this card was hard-coded to mainchain, which broke // Council operators (couldn't resync EID/ESC/PG from the UI). Now // the card paints differently based on cfg setupRole: - // - BPoS: single "Resync mainchain" button (mainchain is the only - // chain with chaindata on a BPoS supernode) - // - Council: checkbox list of {mainchain, esc, eid, pg} (the 4 - // chains with chaindata; arbiter + oracles are services, no + // - BPoS: single "Resync Main chain" button (Main chain is the + // only chain with chaindata on a BPoS supernode) + // - Council: checkbox list of {Main chain, ESC, EID, PG} (the 4 + // chains with chaindata; Arbiter + oracles are services, no // chaindata to wipe). Default all checked. // Mode lookup happens on section activation via _refreshDangerResyncCard // (calls /system/identity). From c11faeef2fe340c35c213794f25c24f09c53c507 Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Thu, 28 May 2026 18:48:14 +0300 Subject: [PATCH 08/24] =?UTF-8?q?enm=20v0.5.235=20=E2=80=94=20always-full?= =?UTF-8?q?=20EVM=20sync=20(council-ready)=20+=20SPV=20lockstep=20wipe?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two operator directives (2026-05-28): 1. "all ENM apps should be council ready, remove fast sync" 2. "for SPV parity, check how node.sh does it and do it as it does" Both ship together because #1 is only safe with #2 — full-sync from genesis re-executes EID's DID tx at block 166,410, which needs the arbiter context that only a lockstep SPV supplies. == INVESTIGATION == node.sh has NO chaindata/SPV wipe at all — no resync/clear command exists. SPV (header/store/spv_transaction_info.db/logs-spv) is a sibling of geth under /data/ and is only log-rotated. So node.sh never decouples them — a manual recovery would rm -rf /data (geth+SPV together) → lockstep rebuild. node.sh runs PRODUCERS on --syncmode full (esc_start:2152, eid_start:4390); followers default to geth's 'fast'. The EID stall root cause (proven live 2026-05-27): the F26 wipe reset geth to genesis but PRESERVED SPV at the mainchain tip, decoupling the arbiter context → every header past 574,384 failed PBFT validation forever. The joint geth+SPV wipe drove EID 574k → 4M+ in ~15 min. == PHASE 1: SPV lockstep wipe (matches node.sh) == EnmMaintenanceManager.chainResync (Class B): - Wipe SPV (header/store/spv_transaction_info.db/logs-spv) + peers.json ALONGSIDE geth/pgp, instead of preserving them. - protectedPaths reduced to just data/keystore. nodekey still preserved via the v0.5.231 backup/restore. - Removes the "preserve SPV saves hours" logic — false: SPV bulk header re-sync did 404k → 1.75M mainchain blocks in 15 min; preserving it caused a PERMANENT stall, which is far worse. == PHASE 3: always-full EVM sync (council-ready) == EVM chains now ALWAYS run --syncmode full regardless of on-duty status, so a Council node is always production-ready and never needs a fast→full re-sync when it goes on-duty. Mining (--mine) stays on-duty-gated via detectProducerRole — only the SYNC MODE is decoupled from role now. - EvmSidechainAdapter.buildSpawnArgs: always push --syncmode full for Class B (honors explicit 'archive'; coerces anything else incl. legacy 'fast' → 'full'). Removed the fast-default / miner-only-full branch. - EvmSidechainAdapter.start(): removed the shouldMine→full / follower→ fast flips. Producer status sets only miner.enabled. Legacy stored 'fast' migrated to 'full' (and re-persisted). Fail-safe keeps full. - setup.js: install default sync.mode 'fast' → 'full'. - setup.js + chains.js validation: coerce a 'fast' request to 'full' (accepted for compat, error message now "full | archive"). - EnmConfigSchema: classBSyncSchema default 'fast' → 'full' ('fast' kept in valid() only so pre-v0.5.235 configs still load; coerced at use). - Frontend settings-tab.js: removed the 'fast' option from both EVM sync-mode dropdowns (per-chain + EVM-shared); default 'full'; coerce legacy 'fast' to 'full' on display + apply. Why always-full is now SAFE for EID (the DID wedge): Block 166,410's DID tx wedge required a DIVERGED on-disk DID index (from unclean SIGKILL restarts) OR a decoupled SPV. A CLEAN from-genesis full-sync with the Phase-1 lockstep SPV builds a correct DID index → checkRegisterDID passes. node.sh proves clean full-sync of EID works (producers run it). Per operator (Option B), Phase-2 verification is post-deploy monitoring rather than a pre-merge gate. == PHASE 4: migration == - New installs / post-wipe: full from genesis (lockstep SPV). - Existing fast-synced chains (already past 166,410): flipping to full going forward is safe + needs no re-sync — geth runs full-mode forward without re-executing 166,410. They get the switch for free. - Deploys don't restart EVM chains (stdio:'ignore'), so tonight's EID fast-recovery continues to completion; always-full takes effect on its next restart, by which point it's at tip → no mid-sync fast→full hazard. VERIFIED: node --check on all 6 files; residual-fast grep clean. Co-Authored-By: Claude Opus 4.7 (1M context) --- enm-server/package.json | 2 +- enm-server/src/routes/chains.js | 6 +- enm-server/src/routes/setup.js | 25 ++++--- enm-server/src/services/EnmConfigSchema.js | 13 +++- .../src/services/EnmMaintenanceManager.js | 70 ++++++++++++------- .../src/services/EvmSidechainAdapter.js | 62 +++++++++------- .../js/components/settings-tab.js | 26 ++++--- 7 files changed, 129 insertions(+), 75 deletions(-) diff --git a/enm-server/package.json b/enm-server/package.json index 4860ff7cc7..8567a3fcc2 100644 --- a/enm-server/package.json +++ b/enm-server/package.json @@ -1,6 +1,6 @@ { "name": "@elacity/enm-server", - "version": "0.5.234", + "version": "0.5.235", "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode AND CR Council operators.", "main": "src/server.js", "author": "Elacity", diff --git a/enm-server/src/routes/chains.js b/enm-server/src/routes/chains.js index 3dd1b515a7..404257c366 100644 --- a/enm-server/src/routes/chains.js +++ b/enm-server/src/routes/chains.js @@ -2024,10 +2024,12 @@ function build(extensionHandle) { const m = String(body.sync.mode); if (!['fast', 'full', 'archive'].includes(m)) { return res.status(400).json(errorBody( - 'sync.mode: must be one of fast | full | archive', + 'sync.mode: must be one of full | archive', )); } - syncMode = m; + // v0.5.235 — fast sync removed; coerce a legacy 'fast' + // request to 'full' (EVM chains are always full-sync). + syncMode = (m === 'fast') ? 'full' : m; } } // Optional bootnodes array replace. v0.5.175 — validate each as a diff --git a/enm-server/src/routes/setup.js b/enm-server/src/routes/setup.js index 0474be9a88..4df8b7e4f9 100644 --- a/enm-server/src/routes/setup.js +++ b/enm-server/src/routes/setup.js @@ -1144,14 +1144,17 @@ function build(extensionHandle) { } threads = body.miner.threads; } - let syncMode = 'fast'; + // v0.5.235 — default + floor is FULL. Fast sync is removed; a + // 'fast' request is accepted for backward-compat but coerced to + // 'full' (EVM chains are always validator-grade full sync). + let syncMode = 'full'; if (body.sync && body.sync.mode) { if (!['fast', 'full', 'archive'].includes(body.sync.mode)) { return res.status(400).json(errorBody( - 'sync.mode must be one of fast | full | archive', + 'sync.mode must be one of full | archive', )); } - syncMode = body.sync.mode; + syncMode = (body.sync.mode === 'fast') ? 'full' : body.sync.mode; } const minerEnabled = body.miner && body.miner.enabled === true; // beta.0.4.1 (operator directive) — SHA256 manifest is @@ -2501,11 +2504,17 @@ async function runCouncilInstall(args) { evmKeystorePasswordEncrypted: '', threads: 1, }, - // v0.5.189 — install as a FOLLOWER on fast sync (node.sh's - // else branch). start() flips this to 'full' when it PROMOTES - // a confirmed on-duty node to miner. Fast sync also dodges the - // EID full-execution DID wedge for non-producers. - sync: { mode: 'fast' }, + // v0.5.235 — install on FULL sync (council-ready). EVM + // chains always full-sync now; the old fast-follower + // default is removed. The forced-full-sync DID wedge + // that fast used to dodge is handled structurally by + // the lockstep SPV wipe (chainResync v0.5.235), so a + // from-genesis full-sync builds a correct DID index and + // validates cleanly (node.sh runs producers on full). + // miner.enabled stays false here — mining is promoted + // at boot by detectProducerRole when on-duty; only the + // sync mode is now unconditionally full. + sync: { mode: 'full' }, bootnodes: [], healing: { enabledRules: {} }, binarySha256Expected: '', diff --git a/enm-server/src/services/EnmConfigSchema.js b/enm-server/src/services/EnmConfigSchema.js index c6a7ce0ab7..fc1a3f6e62 100644 --- a/enm-server/src/services/EnmConfigSchema.js +++ b/enm-server/src/services/EnmConfigSchema.js @@ -301,8 +301,11 @@ const setupSchema = Joi.object({ // EnmCrypto.validateEthAddress. // - miner.evmKeystorePasswordEncrypted is the AES-GCM envelope // produced by EnmEncryption (H24 — no plaintext on disk). -// - sync.mode mirrors geth's --syncmode {fast,full,archive}; node.sh -// defaults to 'fast'. +// - sync.mode mirrors geth's --syncmode. v0.5.235: ENM EVM chains +// always run validator-grade FULL sync (default 'full'). 'fast' is +// retained in valid() only so legacy stored configs still load — the +// adapter + routes coerce any 'fast' to 'full' at use. node.sh runs +// producers on full (esc_start:2152, eid_start:4390). const classBPortsSchema = Joi.object({ rpc: PORT_RANGE.required(), p2p: PORT_RANGE.required(), @@ -324,7 +327,11 @@ const classBMinerSchema = Joi.object({ threads: Joi.number().integer().min(1).max(16).default(1), }).default(); const classBSyncSchema = Joi.object({ - mode: Joi.string().valid('fast', 'full', 'archive').default('fast'), + // v0.5.235 — default 'full' (validator-grade). 'fast' stays in valid() + // for load-compat with pre-v0.5.235 stored configs; it's coerced to + // 'full' by EvmSidechainAdapter.start() (which re-persists) and by the + // setup/chains routes. + mode: Joi.string().valid('fast', 'full', 'archive').default('full'), }).default(); const classBSchema = Joi.object({ enabled: Joi.boolean().default(false), diff --git a/enm-server/src/services/EnmMaintenanceManager.js b/enm-server/src/services/EnmMaintenanceManager.js index 9b62ce9cf0..ca412ac711 100644 --- a/enm-server/src/services/EnmMaintenanceManager.js +++ b/enm-server/src/services/EnmMaintenanceManager.js @@ -386,20 +386,47 @@ async function chainResync(opts) { // The EVM chaindata dir is named after the geth fork's instance: // esc/eid use "geth", but the PG fork uses "pgp" (verified on disk: // chains/pg/data/pgp/chaindata). Each chain has exactly ONE of these, - // so listing both is safe — the absent one is a no-op rm. The mining - // keystore (data/keystore) and SPV mainchain-watch state (data/header, - // data/store, data/spv_transaction_info.db, data/logs-spv) are NOT - // listed and are preserved. + // so listing both is safe — the absent one is a no-op rm. + // + // v0.5.235 — LOCKSTEP WIPE. The SPV mainchain-watch state + // (data/header, data/store, data/spv_transaction_info.db, + // data/logs-spv) is now wiped ALONGSIDE the geth chaindata. + // Pre-v0.5.235 it was preserved "to save the hours-long SPV + // re-download" — but that was exactly backwards: wiping geth to + // genesis while keeping SPV at the mainchain tip DECOUPLES the + // arbiter context an EVM PBFT chain needs to validate headers, + // so the resync wedges forever (proven on EID 2026-05-27: + // stuck at block 574,384 for 9h with "retrieved hash chain is + // invalid"). node.sh never decouples them — its SPV lives as a + // sibling of geth under /data/ and is only ever rebuilt + // TOGETHER with the chain. Wiping both → geth + SPV re-sync from + // genesis in lockstep, SPV feeding arbiter sets in order → the + // chain validates cleanly (proven: the joint wipe drove EID from + // 574k → 4M+ in ~15 min). The SPV bulk header re-sync is fast + // (404k → 1.75M mainchain blocks in 15 min observed), so the + // "saves hours" rationale was false; preserving it caused a + // PERMANENT stall, which is far worse. + // + // The mining keystore (data/keystore) + network identity + // (data/{geth|pgp}/nodekey, backed up above and restored after) + // are still preserved — those are operator identity, not chain + // state. candidates = [ path.join(dataDir, 'geth'), // esc/eid EVM blockchain DB path.join(dataDir, 'pgp'), // pg EVM blockchain DB path.join(dataDir, 'geth.ipc'), // stale ipc socket (esc/eid) path.join(dataDir, 'pgp.ipc'), // v0.5.185 P2-B — stale ipc socket (pg) - // v0.5.185 P2-A — data/peers.json is NOT wiped: it is the SPV - // mainchain-watch addrmgr peer cache (ELA-SPV), not EVM fork - // state, so wiping it only slows the SPV mainchain re-handshake - // after a resync. The EVM eth-layer peer DB is data// - // nodes, which lives INSIDE geth/pgp above and is wiped with it. + // v0.5.235 — SPV mainchain-watch state, wiped in lockstep + // with geth (see rationale above). + path.join(dataDir, 'header'), + path.join(dataDir, 'store'), + path.join(dataDir, 'spv_transaction_info.db'), + path.join(dataDir, 'logs-spv'), + // peers.json IS now wiped too: it is the SPV addrmgr peer + // cache; on a from-genesis SPV resync a stale cache only + // slows the re-handshake, and keeping it served no purpose + // once SPV itself is wiped. + path.join(dataDir, 'peers.json'), path.join(DataDir.enmDataDir(), '.tmp', 'bootstrap', chainId), ]; } else { @@ -415,23 +442,16 @@ async function chainResync(opts) { path.join(DataDir.enmDataDir(), '.tmp', 'bootstrap', chainId), ]; } - // P1-7 / v0.5.185 P2-C hard safety net — NEVER delete identity or SPV - // state, even if a future edit mistakenly adds them to the candidates. - // The mining keystore (identity) is permanent + unrecoverable. For - // Class B the embedded-SPV store (header/store/spv_transaction_info.db/ - // logs-spv) takes hours to re-download and, if wiped, the EVM chain - // CANNOT validate until SPV re-syncs (the operator's dev: "if you - // removed spv data you must wait until spv sync finished"). Absolute. + // P1-7 hard safety net — NEVER delete the mining keystore (identity), + // which is permanent + unrecoverable. This stays absolute. + // + // v0.5.235 — the SPV state (header/store/spv_transaction_info.db/ + // logs-spv) is DELIBERATELY no longer protected: it must be wiped in + // lockstep with geth (see the candidates comment above). The old + // "preserve SPV" guard caused the arbiter-context decoupling that + // wedged EID. The network identity (data/{geth|pgp}/nodekey) is + // preserved separately by the backup/restore added in v0.5.231. const protectedPaths = [path.join(cdir, 'data', 'keystore')]; - if (adapter.chainClass === 'B') { - const d = path.join(cdir, 'data'); - protectedPaths.push( - path.join(d, 'header'), - path.join(d, 'store'), - path.join(d, 'spv_transaction_info.db'), - path.join(d, 'logs-spv'), - ); - } candidates = candidates.filter((p) => { for (const prot of protectedPaths) { const rel = path.relative(p, prot); diff --git a/enm-server/src/services/EvmSidechainAdapter.js b/enm-server/src/services/EvmSidechainAdapter.js index 0a0cec5c17..db79fe3c47 100644 --- a/enm-server/src/services/EvmSidechainAdapter.js +++ b/enm-server/src/services/EvmSidechainAdapter.js @@ -605,17 +605,26 @@ class EvmSidechainAdapter extends ChainAdapter { args.push('--pbft.keystore.password', secrets.pbftPasswordFile); } } - // Sync mode: 'fast' / 'full' / 'archive'. - if (cfg.sync && cfg.sync.mode) { - args.push('--syncmode', cfg.sync.mode); - } else if (cfg.miner && cfg.miner.enabled === true) { - // v0.5.185 P2-D — node.sh forces `--syncmode full` on a producing - // council validator (esc_start:2152). Without it geth defaults to - // 'fast', and a PBFT producer on fast-sync can mis-serve / mis-mine - // before its state is complete. Match node.sh for miners; non-miner - // followers keep geth's default. - args.push('--syncmode', 'full'); - } + // Sync mode — v0.5.235: EVM chains ALWAYS full-sync (council-ready). + // + // Operator directive 2026-05-28: "all ENM apps should be council ready, + // remove fast sync." ENM is a validator tool — a Council node produces + // EVM blocks when on-duty, and node.sh runs producers on --syncmode full + // (esc_start:2152, eid_start:4390). Rather than fast-when-following / + // full-when-producing (the pre-v0.5.235 role-based flip), every EVM + // chain now runs validator-grade FULL sync regardless of current + // on-duty status, so the node is always production-ready with complete + // self-validated state and never needs a fast→full re-sync when it goes + // on-duty. This is safe for from-genesis sync ONLY because v0.5.235 also + // wipes SPV in lockstep with geth (chainResync) — full-sync re-executes + // every block (incl. EID's DID tx at 166,410), which requires the + // arbiter context the lockstep SPV supplies. + // + // Fast sync is removed. An explicit 'archive' override is still honored + // (full + retain all historical state); any other value — including a + // legacy stored 'fast' — is coerced to 'full'. + const syncMode = (cfg.sync && cfg.sync.mode === 'archive') ? 'archive' : 'full'; + args.push('--syncmode', syncMode); // Miner — enabled for council validators (the sidechain produces // blocks). Values: // miner.enabled → enable mining at all @@ -895,15 +904,16 @@ class EvmSidechainAdapter extends ChainAdapter { const wasMiner = !!(cfg.miner && cfg.miner.enabled); if (cfg.miner) { cfg.miner.enabled = shouldMine; } - if (shouldMine) { - // Confirmed on-duty → miner: node.sh's council branch uses full sync. - if (!cfg.sync) { cfg.sync = {}; } - if (cfg.sync.mode !== 'full') { cfg.sync.mode = 'full'; } - } else if (cfg.sync && cfg.sync.mode === 'full') { - // Follower → drop forced full so it fast-syncs (avoids the DID wedge); - // leave any explicit non-full mode untouched. - cfg.sync.mode = 'fast'; - } + // v0.5.235 — syncmode is NO LONGER role-dependent. EVM chains + // always full-sync (buildSpawnArgs hardcodes it). Producer status + // controls ONLY --mine (miner.enabled), never the sync mode. The + // old shouldMine→full / follower→fast flips are removed; the + // forced-full-sync DID wedge they were avoiding is now handled + // structurally by the lockstep SPV wipe (v0.5.235 chainResync). + // Migrate any legacy stored 'fast' to 'full' so persisted config + // stays honest with what actually runs. + if (!cfg.sync) { cfg.sync = {}; } + if (cfg.sync.mode === 'fast' || !cfg.sync.mode) { cfg.sync.mode = 'full'; } if (_roleLog) { const crNote = crMemberCheck ? ` crMember.isCrMember=${crMemberCheck.isCrMember}, source=${crMemberCheck.source}.` @@ -912,20 +922,22 @@ class EvmSidechainAdapter extends ChainAdapter { `${ENM_LOG_PREFIX} ${this.chainId}: producer-role check → isProducer=${role.isProducer} ` + `(source=${role.source}, inCurrent=${role.inCurrent}, inNext=${role.inNext})` + crNote - + ` → ${shouldMine ? 'MINER (full sync)' : 'FOLLOWER (no --mine, fast sync)'}` + + ` → ${shouldMine ? 'MINER (--mine)' : 'non-producer (no --mine)'}; sync=full (always)` + `${wasMiner !== shouldMine ? (shouldMine ? ' [PROMOTED]' : ' [demoted]') : ''}. ` + 'Mining is on-chain producer state, not an ENM toggle.', ); } } catch (err) { - // Fail-safe: on an unexpected detection error, run as FOLLOWER (never mine - // on an unknown role — the chain self-gates anyway and fast-sync is safe). + // Fail-safe: on an unexpected detection error, do NOT mine (never + // --mine on an unknown role — the chain self-gates anyway). v0.5.235: + // sync stays FULL even on detection failure; only mining is demoted. if (cfg.miner) { cfg.miner.enabled = false; } - if (cfg.sync && cfg.sync.mode === 'full') { cfg.sync.mode = 'fast'; } + if (!cfg.sync) { cfg.sync = {}; } + if (cfg.sync.mode === 'fast' || !cfg.sync.mode) { cfg.sync.mode = 'full'; } if (_roleLog) { _roleLog.warn( `${ENM_LOG_PREFIX} ${this.chainId}: producer-role detection failed ` - + `(${err && err.message ? err.message : err}) — running as FOLLOWER (fail-safe).`, + + `(${err && err.message ? err.message : err}) — no --mine (fail-safe), sync=full.`, ); } } diff --git a/src/backend/apps/elastos-node-manager/js/components/settings-tab.js b/src/backend/apps/elastos-node-manager/js/components/settings-tab.js index 960bee5f37..603a95fd3f 100644 --- a/src/backend/apps/elastos-node-manager/js/components/settings-tab.js +++ b/src/backend/apps/elastos-node-manager/js/components/settings-tab.js @@ -408,16 +408,18 @@ threadsInput.addEventListener('input', function () { sec.setDirty(true); }); sec.body.appendChild(makeFormRow({ label: 'Mining threads', help: 'CPU threads used while mining is on.', control: threadsInput })); + // v0.5.235 — fast sync removed. ENM nodes are validators (Council/BPoS); + // EVM chains always run validator-grade full sync. Only full (default) + // and archive (full + all historical state) remain. var syncSel = makeSelectWrap({ options: [ - { value: 'fast', label: 'fast — recommended (recent state only)' }, - { value: 'full', label: 'full — keep all blocks' }, + { value: 'full', label: 'full — validator-grade (recommended)' }, { value: 'archive', label: 'archive — full + all historical state' }, ], - value: sync.mode || 'fast', + value: (sync.mode && sync.mode !== 'fast') ? sync.mode : 'full', onChange: function () { sec.setDirty(true); }, }); - sec.body.appendChild(makeFormRow({ label: 'Sync mode', help: 'How much chain history this node retains.', control: syncSel.el })); + sec.body.appendChild(makeFormRow({ label: 'Sync mode', help: 'How much chain history this node retains. Council/BPoS nodes always full-sync.', control: syncSel.el })); parent.appendChild(sec.card); @@ -585,7 +587,7 @@ rewardInput.value = miner.rewardAddress || ''; evmInput.value = miner.evmKeystoreAddr || ''; threadsInput.value = Number.isInteger(miner.threads) ? miner.threads : 1; - syncSel.setValue(sync.mode || 'fast'); + syncSel.setValue((sync.mode && sync.mode !== 'fast') ? sync.mode : 'full'); refreshValidity(); sec.setDirty(false); if (sec.statusEl) { sec.statusEl.textContent = ''; } @@ -1876,9 +1878,9 @@ body.appendChild(syncCard.el); var syncSelectWrap = document.createElement('div'); syncSelectWrap.className = 'enm-evm-shared-input-row'; + // v0.5.235 — fast removed; validator-grade full is the default. syncSelectWrap.innerHTML = '' + ''; @@ -1940,10 +1942,10 @@ enabled: !!(d.miner && d.miner.enabled), chainState: (d.miner && d.miner.chainState) || null, // sync.mode isn't currently returned by /chains/:id; - // when missing we treat all as 'fast' (the schema - // default) so the row still works. A future - // backend pass should add sync.mode to the response. - syncMode: (d.sync && d.sync.mode) || 'fast', + // when missing we treat as 'full' (v0.5.235 default — + // fast sync removed). A future backend pass should add + // sync.mode to the response. + syncMode: (d.sync && d.sync.mode && d.sync.mode !== 'fast') ? d.sync.mode : 'full', ok: true, }; }).catch(function () { @@ -2176,7 +2178,9 @@ SettingsTab.prototype._applyEvmSharedSync = function (mode, btn, statusEl) { var self = this; var t = root.enmTOrFallback || root.enmT || function (k) { return k; }; - if (['fast', 'full', 'archive'].indexOf(mode) < 0) { + // v0.5.235 — fast removed; coerce any legacy 'fast' to 'full'. + if (mode === 'fast') { mode = 'full'; } + if (['full', 'archive'].indexOf(mode) < 0) { statusEl.textContent = 'Invalid sync mode.'; statusEl.className = 'enm-evm-shared-status is-err'; return; From 75de2bb8cf2544e8796e12e5b69c90899fe812f3 Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Thu, 28 May 2026 20:55:24 +0300 Subject: [PATCH 09/24] =?UTF-8?q?enm=20v0.5.236=20=E2=80=94=20staged=20ini?= =?UTF-8?q?tial=20sync=20for=20constrained=20hardware=20(wizard=20option)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Operator directive 2026-05-28: "lower-end recommended hardware should have an option to run 2 chains at once and sync the rest when the first two are fully synced — initial sync takes the most resources." Confirmed semantics: a sliding window of 2 (always ≤2 heavy syncs; as one finishes the next starts), chosen in the setup wizard. This matters more after v0.5.235 made EVM chains full-sync (heavier than the old fast-sync) — three simultaneous EVM full-syncs can saturate a small VPS's CPU and get it paused by the provider. == Backend: EnmStageSyncOrchestrator (NEW) == The existing EnmStageSync (utils-stage-sync.js) is FRONTEND-only and dies when the tab closes — unusable for a multi-hour wizard sync. This is the backend port its own header called "a future Phase 22.1." Model: - Sliding window of N (default 2) over HEAVY chains (class A mainchain + class B esc/eid/pg). Start ≤N; when one reaches the network tip (via SyncTracker blocksBehind <= 8), free its slot, start the next pending heavy chain. - Light services don't count against the window: an EVM chain's oracle (class C) is started alongside its parent ("run together"); the arbiter (class D) starts after all heavy chains are up. - IDEMPOTENT / RESUMABLE: no progress file — live chain states ARE the progress. On each (re)start it re-derives per heavy chain: synced→done, alive-but-behind→inflight (counts vs window), stopped→pending. A host reboot mid-stage resumes cleanly; once all synced a normal boot just starts everything. - STALL SAFETY (progress-based, not wall-clock — a legit full-sync is slow but progressing): if blocksBehind fails to decrease for ~20 min while still behind, free the slot so the rest proceed; the stuck chain keeps running and F-rule self-heal surfaces it. - Publishes 'stage-sync:status' SSE per phase for a future status panel. == Backend wiring == - EnmAutoStart: when global.syncStrategy === 'staged', hand the bring-up to the orchestrator (window = global.stagedSync.concurrency, default 2) instead of startAllChains. Fail-safe: if the orchestrator can't start, fall back to concurrent so chains still come up. - EnmConfigSchema: global.syncStrategy 'concurrent'|'staged' (default concurrent) + global.stagedSync.concurrency (1-4, default 2). Added to defaultConfig too. - setup.js install-council: persists body.syncStrategy to cfg.global.syncStrategy before kicking the orchestrator + first autoStart, so it's in place when chains boot. == Frontend: wizard Card 5 choice == - setup-conversation.js Card 5 (Council only — BPoS runs one chain, so staging is moot): a radio group "Initial sync": • "Start all chains at once (fastest)" → concurrent (default) • "Conserve resources — sync 2 chains at a time" → staged Writes this._syncStrategy; _beginInstall ships it in the install-council POST body. == Scope notes == - BPoS unaffected (mainchain-only → one heavy chain → staged is a no-op). - Default behavior unchanged for everyone (concurrent) — purely additive, opt-in via the wizard. - Deferred (follow-ups, noted): a dedicated staged-progress banner (the SSE topic is already published; per-chain dashboard states convey progress today), and consolidating the manual Settings→Advanced "Stage-sync now" (frontend EnmStageSync) onto this backend orchestrator — they don't conflict (manual vs boot entry points). VERIFIED: node --check on all 5 files; orchestrator exports {startStaged,cancel,isRunning}; schema validate() preserves 'staged' + defaults absent → 'concurrent'. Co-Authored-By: Claude Opus 4.7 (1M context) --- enm-server/package.json | 2 +- enm-server/src/routes/setup.js | 20 ++ enm-server/src/services/EnmAutoStart.js | 47 ++- enm-server/src/services/EnmConfigSchema.js | 22 ++ .../src/services/EnmStageSyncOrchestrator.js | 311 ++++++++++++++++++ .../js/components/setup-conversation.js | 42 ++- 6 files changed, 441 insertions(+), 3 deletions(-) create mode 100644 enm-server/src/services/EnmStageSyncOrchestrator.js diff --git a/enm-server/package.json b/enm-server/package.json index 8567a3fcc2..fdec0dc8e9 100644 --- a/enm-server/package.json +++ b/enm-server/package.json @@ -1,6 +1,6 @@ { "name": "@elacity/enm-server", - "version": "0.5.235", + "version": "0.5.236", "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode AND CR Council operators.", "main": "src/server.js", "author": "Elacity", diff --git a/enm-server/src/routes/setup.js b/enm-server/src/routes/setup.js index 4df8b7e4f9..c165b8d913 100644 --- a/enm-server/src/routes/setup.js +++ b/enm-server/src/routes/setup.js @@ -1720,9 +1720,29 @@ function build(extensionHandle) { } const sharedPassword = masterPassword; // legacy alias for the orchestrator + // v0.5.236 — persist the operator's initial-sync strategy (Card 5 + // hardware-tier choice). 'staged' tells EnmAutoStart to bring the + // heavy chains up 2-at-a-time via EnmStageSyncOrchestrator so a + // lower-end host isn't crushed by simultaneous EVM full-syncs. + // Default 'concurrent' = legacy all-at-once. Written before the + // orchestrator + first autoStart so it's in place when chains boot. + const syncStrategy = body.syncStrategy === 'staged' ? 'staged' : 'concurrent'; + try { + await ConfigStore.update((c) => { + c.global = c.global || {}; + c.global.syncStrategy = syncStrategy; + }, { logger: extensionHandle.log }); + } catch (err) { + extensionHandle.log.warn( + `${ENM_LOG_PREFIX} install-council: failed to persist syncStrategy ` + + `(${err.message}) — defaulting to concurrent`, + ); + } + // Return 202 immediately + run the orchestrator in the background. res.status(202).json(successBody({ started: true, + syncStrategy, sseTopic: 'setup:council:install', statusEndpoint: '/api/enm/setup/install-council/status', })); diff --git a/enm-server/src/services/EnmAutoStart.js b/enm-server/src/services/EnmAutoStart.js index fb60d61339..6ac23a2017 100644 --- a/enm-server/src/services/EnmAutoStart.js +++ b/enm-server/src/services/EnmAutoStart.js @@ -340,7 +340,49 @@ async function runAutoStart(deps) { + `[${orderedChainIds.join(' → ')}] (dependency-DAG order) to start in ${delaySec}s`, ); + // v0.5.236 — staged initial sync for constrained hosts. When + // global.syncStrategy === 'staged', hand the bring-up to + // EnmStageSyncOrchestrator, which runs ≤N heavy chains (mainchain + + // esc/eid/pg) concurrently, waiting for each to reach the network tip + // before starting the next — so a low-end host isn't crushed by 3 + // simultaneous EVM full-syncs. Default ('concurrent') keeps the legacy + // all-at-once startAllChains path. The orchestrator is idempotent + + // resumable (re-derives from live state), so it's safe to invoke on + // every boot; once all chains are synced it just (re)starts them and + // finishes immediately. + const syncStrategy = (cfg.global && cfg.global.syncStrategy) || 'concurrent'; + const stagedConcurrency = (cfg.global && cfg.global.stagedSync + && Number.isInteger(cfg.global.stagedSync.concurrency)) + ? cfg.global.stagedSync.concurrency : 2; + setTimeout(() => { + if (syncStrategy === 'staged') { + log.info( + `${ENM_LOG_PREFIX} autoStart: syncStrategy=staged — handing bring-up to ` + + `stage-sync orchestrator (window=${stagedConcurrency})`, + ); + try { + const Orchestrator = require('./EnmStageSyncOrchestrator'); + Orchestrator.startStaged({ + extensionHandle, + registry, + chainIds: orderedChainIds, + concurrency: stagedConcurrency, + }); + } catch (err) { + // Fail safe: if the orchestrator can't start, fall back to the + // all-at-once path so chains still come up (better an over- + // eager sync than no node at all). + log.error( + `${ENM_LOG_PREFIX} autoStart: stage-sync orchestrator failed to start ` + + `(${err.message}) — falling back to concurrent startAllChains`, + ); + startAllChains({ + extensionHandle, registry, chainIds: orderedChainIds, pairedServices: pairedServicesSet, + }).catch((e) => log.error(`${ENM_LOG_PREFIX} autoStart fallback crashed: ${e.message}`)); + } + return; + } // Re-read config inside the timer so operator changes during the grace // window (e.g. they disabled a chain right after boot) take effect. startAllChains({ @@ -357,7 +399,10 @@ async function runAutoStart(deps) { }); }, delayMs); - return { scheduled: true, delayMs, chainCount: orderedChainIds.length, order: orderedChainIds }; + return { + scheduled: true, delayMs, chainCount: orderedChainIds.length, + order: orderedChainIds, syncStrategy, + }; } /** diff --git a/enm-server/src/services/EnmConfigSchema.js b/enm-server/src/services/EnmConfigSchema.js index fc1a3f6e62..914f39b553 100644 --- a/enm-server/src/services/EnmConfigSchema.js +++ b/enm-server/src/services/EnmConfigSchema.js @@ -175,6 +175,23 @@ const globalSchema = Joi.object({ onBoot: Joi.boolean().default(true), delaySec: Joi.number().integer().min(0).max(600).default(10), }).default(), + // v0.5.236 — initial-sync strategy for constrained hosts. + // 'concurrent' (default) — start all enabled chains at once (legacy). + // 'staged' — EnmStageSyncOrchestrator brings up the heavy + // chains (mainchain + esc/eid/pg) ≤N at a time, + // waiting for each to reach tip before starting + // the next, so a low-end host isn't crushed by + // simultaneous EVM full-syncs. Oracles pair with + // their parent; arbiter starts last. + // Set from the setup wizard's hardware-tier choice (Card 5). BPoS nodes run + // only the mainchain, so staged is a no-op there (one heavy chain) — the + // field is harmless regardless of role. + syncStrategy: Joi.string().valid('concurrent', 'staged').default('concurrent'), + stagedSync: Joi.object({ + // Heavy-chain window size. 2 = "two chains at once" (operator default + // for lower-end recommended hardware). + concurrency: Joi.number().integer().min(1).max(4).default(2), + }).default(), // Log rotation — gzip *.log older than gzipAfterDays, purge *.gz older // than purgeAfterDays. main.js scheduler runs compactNow every 24h. // beta.3.20 — purgeAfterDays min lowered from 7 → 1 day so the @@ -547,6 +564,11 @@ function defaultConfig() { notifications: { criticalRequiresAck: true }, audit: { retentionDays: 365 }, autoStart: { onBoot: true, delaySec: 10 }, + // v0.5.236 — initial-sync strategy (set by the wizard's hardware + // tier choice). 'concurrent' = all-at-once (default); 'staged' = + // bring heavy chains up 2-at-a-time on constrained hosts. + syncStrategy: 'concurrent', + stagedSync: { concurrency: 2 }, logRotation: { enabled: true, gzipAfterDays: 7, purgeAfterDays: 90 }, }, setup: { diff --git a/enm-server/src/services/EnmStageSyncOrchestrator.js b/enm-server/src/services/EnmStageSyncOrchestrator.js new file mode 100644 index 0000000000..eedc7d0a32 --- /dev/null +++ b/enm-server/src/services/EnmStageSyncOrchestrator.js @@ -0,0 +1,311 @@ +/* + * Copyright (C) 2026-present Elacity + * SPDX-License-Identifier: AGPL-3.0 + * + * EnmStageSyncOrchestrator — backend staged initial-sync for constrained hosts. + * + * v0.5.236 (operator directive 2026-05-28: "lower-end recommended hardware + * should have an option to run 2 chains at once and sync the rest when the + * first two are fully synced — initial sync takes the most resources"). + * + * WHY BACKEND (not the frontend EnmStageSync): + * The Council install brings up 8 services; on a constrained host the + * simultaneous EVM *full*-sync of esc + eid + pg (v0.5.235 made them full, + * heavier than the old fast-sync) saturates CPU and the provider pauses the + * VPS. A from-genesis full-sync now takes hours-to-days, so the operator WILL + * close the wizard tab — the frontend-only EnmStageSync (utils-stage-sync.js) + * dies with the tab. This is the backend port that utils-stage-sync.js's own + * header called "a future Phase 22.1 ... survives tab close, single source of + * truth." + * + * MODEL — sliding window of N (default 2) over the HEAVY chains: + * Heavy chains = class A (mainchain) + class B (esc/eid/pg) — the ones with a + * real height to sync. Start at most N concurrently; when one reaches the + * network tip, free its slot and start the next pending heavy chain. Light + * services don't count against the window: + * - An EVM chain's oracle (class C) is started alongside its parent ("they + * should run together" — operator 2026-05-27); it's a light node script. + * - The arbiter (class D) starts after all heavy chains are up (it SPV-syncs + * independently and needs all four chains alive). + * + * IDEMPOTENT / RESUMABLE: + * No persisted progress file — the LIVE chain states ARE the progress. On each + * (re)start the orchestrator re-derives, per heavy chain: synced→done, + * alive-but-behind→inflight (counts against the window), stopped→pending. So a + * host reboot mid-stage resumes cleanly, and once everything is synced a normal + * boot just starts everything (all already at tip → light). + * + * STALL SAFETY: + * A genuinely-stuck heavy chain must not block the window forever. We track + * blocksBehind per inflight chain; if it fails to DECREASE for + * STALL_GRACE_TICKS consecutive polls (~20 min) while still behind, we free its + * slot (start the next pending chain) and log a warning — the stuck chain stays + * running and the F-rule self-heal engine surfaces it to the operator. This is + * progress-based, NOT wall-clock, because a legitimate full-sync is slow but + * progressing and must keep its slot. + */ + +'use strict'; + +const { ENM_LOG_PREFIX } = require('./EnmConstants'); +const ConfigStore = require('./ConfigStore'); +const ChainAdapter = require('./ChainAdapter'); +const AuditLog = require('./EnmAuditLog'); + +const SYSTEM_WALLET = 'system'; + +// Poll cadence — sync state moves slowly (full-sync executes blocks), so a +// 15s tick is plenty and keeps RPC pressure negligible. +const POLL_MS = 15000; +// "Caught up" threshold: blocksBehind at or under this frees the window slot. +// A few blocks of lag is normal (the network keeps producing); we don't wait +// for an exact 0 that a live chain never durably hits. +const SYNCED_BLOCKS_THRESHOLD = 8; +// Stall detection: if blocksBehind doesn't decrease across this many +// consecutive polls (~20 min at 15s) while still behind, treat the slot as +// freeable so the remaining chains aren't blocked by one stuck chain. +const STALL_GRACE_TICKS = 80; + +let _running = false; // module-level guard — one orchestration at a time +let _cancelled = false; + +/** + * Is this chain "done" for window purposes? + * - class C/D services: alive === done (no height to sync). + * - class A/B heavy chains: alive AND blocksBehind <= threshold. + * Returns { done, alive, blocksBehind }. + */ +function inspectChain(chainId, proc, registry) { + const cls = ChainAdapter.classOf(chainId); + let alive = false; + try { + const st = proc.statusSync(chainId); + alive = !!(st && st.alive); + } catch (_) { alive = false; } + if (!alive) { return { done: false, alive: false, blocksBehind: null }; } + if (cls === 'C' || cls === 'D') { return { done: true, alive: true, blocksBehind: null }; } + // Heavy chain — consult SyncTracker for blocksBehind. + let blocksBehind = null; + try { + const snap = registry.getSyncTracker().syncSnapshot(chainId); + if (snap && typeof snap.blocksBehind === 'number') { blocksBehind = snap.blocksBehind; } + } catch (_) { /* tracker not ready — treat as unknown */ } + const done = (typeof blocksBehind === 'number') && (blocksBehind <= SYNCED_BLOCKS_THRESHOLD); + return { done, alive: true, blocksBehind }; +} + +/** Start one chain via its adapter; audit the outcome. Never throws. */ +async function startChain(chainId, registry, db, log) { + const startedAtMs = Date.now(); + try { + const cfg = await ConfigStore.load(); + const chainCfg = cfg.chains && cfg.chains[chainId]; + if (!chainCfg) { log.warn(`${ENM_LOG_PREFIX} stage-sync: ${chainId} not in cfg — skip`); return false; } + const adapter = registry.getAdapter(chainId); + await adapter.start(chainCfg); + const durationMs = Date.now() - startedAtMs; + log.info(`${ENM_LOG_PREFIX} stage-sync: started ${chainId} in ${durationMs}ms`); + await safeAudit(db, log, { + chainId, decision: 'executed', durationMs, + outcome: `Staged-start ${chainId} on ENM boot`, + }); + return true; + } catch (err) { + const durationMs = Date.now() - startedAtMs; + log.warn(`${ENM_LOG_PREFIX} stage-sync: ${chainId} start failed (${err.message}) — F1 will retry`); + await safeAudit(db, log, { + chainId, decision: 'failed', durationMs, + outcome: `Staged-start failed: ${err.message}`, + }); + return false; + } +} + +/** + * Run the staged bring-up. Returns immediately after seeding; the window + * advances on a setTimeout poll loop. + * + * @param {object} args + * @param {object} args.extensionHandle + * @param {object} args.registry + * @param {string[]} args.chainIds full ordered list (class A→D) from autoStart + * @param {number} [args.concurrency] heavy-chain window size (default 2) + */ +function startStaged(args) { + const { extensionHandle, registry, chainIds } = args; + const log = (extensionHandle && extensionHandle.log) || console; + const N = (Number.isInteger(args.concurrency) && args.concurrency >= 1) ? args.concurrency : 2; + if (_running) { + log.info(`${ENM_LOG_PREFIX} stage-sync: already running — ignoring duplicate start`); + return { started: false, reason: 'already-running' }; + } + _running = true; + _cancelled = false; + + const proc = registry.getProcessService(); + let db = null; + try { db = extensionHandle.import('data').db; } catch (_) { db = null; } + let sseHub = null; + try { sseHub = registry.getSseHub(); } catch (_) { sseHub = null; } + + // Partition the autoStart-ordered list into heavy (A/B, windowed) + the + // light services (C oracles / D arbiter) that ride alongside / trail. + const heavyAll = chainIds.filter((c) => { + const k = ChainAdapter.classOf(c); + return k === 'A' || k === 'B'; + }); + const arbiterId = chainIds.find((c) => ChainAdapter.classOf(c) === 'D') || null; + + // Window state. + const pending = heavyAll.slice(); // heavy chains not yet started this run + const inflight = new Map(); // chainId → { lastBehind, stallTicks } + const done = new Set(); // heavy chains at tip + const startedOracles = new Set(); // oracles we've already paired-started + let arbiterStarted = false; + + // Seed from LIVE state so a restart resumes mid-stage. + for (let i = pending.length - 1; i >= 0; i -= 1) { + const cid = pending[i]; + const s = inspectChain(cid, proc, registry); + if (s.done) { + done.add(cid); + pending.splice(i, 1); + } else if (s.alive) { + inflight.set(cid, { lastBehind: s.blocksBehind, stallTicks: 0 }); + pending.splice(i, 1); + } + } + + log.info( + `${ENM_LOG_PREFIX} stage-sync: starting (window=${N}) — ` + + `heavy=[${heavyAll.join(', ')}] seeded done=[${[...done].join(', ')}] ` + + `inflight=[${[...inflight.keys()].join(', ')}] pending=[${pending.join(', ')}]`, + ); + + // Pair an EVM chain's oracle (start it alongside the parent — light). + async function pairOracle(parentId) { + const oracleId = ChainAdapter.oracleOf(parentId); + if (!oracleId || startedOracles.has(oracleId)) { return; } + const cfg = await ConfigStore.load(); + if (!cfg.chains || !cfg.chains[oracleId]) { return; } + startedOracles.add(oracleId); + await startChain(oracleId, registry, db, log); + } + + function emit(phase) { + if (!sseHub) { return; } + try { + sseHub.publish('stage-sync:status', { + phase, + window: N, + done: [...done], + inflight: [...inflight.keys()], + pending: pending.slice(), + arbiterStarted, + }); + } catch (_) { /* SSE best-effort */ } + } + + // Fill free window slots from pending; pair each started chain's oracle. + async function fillSlots() { + while (inflight.size < N && pending.length > 0) { + const cid = pending.shift(); + inflight.set(cid, { lastBehind: null, stallTicks: 0 }); + emit('starting'); + const ok = await startChain(cid, registry, db, log); + if (!ok) { + // start failed — drop from inflight so F1 handles it and the + // window isn't permanently consumed by a chain that won't boot. + inflight.delete(cid); + } + await pairOracle(cid); + } + } + + async function tick() { + if (_cancelled) { _running = false; return; } + // Advance inflight → done; detect stalls. + for (const [cid, meta] of [...inflight.entries()]) { + const s = inspectChain(cid, proc, registry); + if (s.done) { + inflight.delete(cid); + done.add(cid); + await pairOracle(cid); // ensure oracle up even if pair on start was skipped + emit('synced'); + log.info(`${ENM_LOG_PREFIX} stage-sync: ${cid} reached tip — freeing slot`); + continue; + } + // Stall detection — blocksBehind must keep decreasing. + if (typeof s.blocksBehind === 'number') { + if (meta.lastBehind != null && s.blocksBehind >= meta.lastBehind) { + meta.stallTicks += 1; + } else { + meta.stallTicks = 0; + } + meta.lastBehind = s.blocksBehind; + if (meta.stallTicks >= STALL_GRACE_TICKS) { + log.warn( + `${ENM_LOG_PREFIX} stage-sync: ${cid} stalled (blocksBehind=${s.blocksBehind} ` + + `not decreasing for ${STALL_GRACE_TICKS} polls) — freeing slot so the rest ` + + 'can proceed; the chain keeps running and F-rule self-heal will surface it.', + ); + inflight.delete(cid); + emit('stalled'); + } + } + } + + await fillSlots(); + + // All heavy chains done? Start the arbiter (last) and finish. + if (pending.length === 0 && inflight.size === 0) { + if (arbiterId && !arbiterStarted) { + arbiterStarted = true; + emit('arbiter-starting'); + await startChain(arbiterId, registry, db, log); + } + emit('complete'); + log.info(`${ENM_LOG_PREFIX} stage-sync: complete — all heavy chains synced; services up`); + _running = false; + return; + } + setTimeout(() => { tick().catch((e) => { + log.error(`${ENM_LOG_PREFIX} stage-sync tick crashed: ${e.message}`); + _running = false; + }); }, POLL_MS); + } + + // Kick the first fill + loop. + fillSlots() + .then(() => { emit('waiting'); return tick(); }) + .catch((e) => { + log.error(`${ENM_LOG_PREFIX} stage-sync initial fill crashed: ${e.message}`); + _running = false; + }); + + return { started: true, window: N, heavy: heavyAll, pending: pending.slice() }; +} + +function cancel() { _cancelled = true; } +function isRunning() { return _running; } + +async function safeAudit(db, log, args) { + if (!db) { return; } + try { + await AuditLog.append(db, { + walletAddress: SYSTEM_WALLET, + chainId: args.chainId, + ruleId: null, + tier: 'AUTOMATED-SAFE', + decision: args.decision, + executor: 'system', + outcome: args.outcome, + durationMs: args.durationMs, + payload: { action: 'stage-sync' }, + }); + } catch (err) { + log.debug(`${ENM_LOG_PREFIX} stage-sync: audit append failed (${err.message})`); + } +} + +module.exports = { startStaged, cancel, isRunning }; diff --git a/src/backend/apps/elastos-node-manager/js/components/setup-conversation.js b/src/backend/apps/elastos-node-manager/js/components/setup-conversation.js index 855f089cca..31243d6b7b 100644 --- a/src/backend/apps/elastos-node-manager/js/components/setup-conversation.js +++ b/src/backend/apps/elastos-node-manager/js/components/setup-conversation.js @@ -1410,6 +1410,30 @@ ? t('friendly.setup.card_5.sub') : t('friendly.setup.card_5.sub_bpos'); this.root.setAttribute('aria-label', heading); + // v0.5.236 — initial-sync strategy choice (Council only; a BPoS node + // runs only the mainchain, so "2 at a time" is meaningless there). + // Default 'concurrent' (all-at-once, for recommended hardware); the + // operator opts into 'staged' for lower-end hardware. Writes + // this._syncStrategy, sent in the install-council body by _beginInstall. + var stageRadioHtml = (this._goal === 'council') + ? ('
    ' + + 'Initial sync' + + '' + + '' + + '
    ') + : ''; this._body.innerHTML = '' + '

    ' + escapeHtml(heading) + '

    ' + '

    ' + escapeHtml(sub) + '

    ' @@ -1439,13 +1463,26 @@ + '' + escapeHtml(t('friendly.setup.card_5.snapshot_evm_note')) + '' + '' - + ''; + + '' + + stageRadioHtml; var self = this; var listEl = this._body.querySelector('.enm-preflight-list'); var rerunBtn = this._body.querySelector('[data-action="rerun"]'); var snapsEl = this._body.querySelector('#enm-wiz-5-snapshots'); + // v0.5.236 — track the sync-strategy radio (Council only). Default + // 'concurrent'; flip to 'staged' when the operator picks the + // conserve-resources option for lower-end hardware. + this._syncStrategy = this._syncStrategy || 'concurrent'; + var syncRadios = this._body.querySelectorAll('input[name="enm-wiz-5-syncstrategy"]'); + Array.prototype.forEach.call(syncRadios, function (r) { + if (r.checked) { self._syncStrategy = r.value; } + r.addEventListener('change', function () { + if (r.checked) { self._syncStrategy = r.value; } + }); + }); + this._cancelBtn.hidden = false; this._cancelBtn.textContent = t('friendly.setup.back'); this._cancelBtn.addEventListener('click', function () { @@ -1676,6 +1713,9 @@ rewardAddress: this._sharedRewardAddress, sharedRewardAddress: this._sharedRewardAddress, useSnapshots: !!useSnapshots, + // v0.5.236 — initial-sync strategy from Card 5's radio. + // 'staged' → backend brings heavy chains up 2-at-a-time. + syncStrategy: this._syncStrategy || 'concurrent', activeNet: 'mainnet', }; this._goto('6'); From 4289b6e17e3ddbedf4f8907585575fd46097b5e6 Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Thu, 28 May 2026 21:22:56 +0300 Subject: [PATCH 10/24] chore(enm): remove dead identityResetBody schema (dead-code audit) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POST /identity/reset was retired to a 410 stub in v0.5.232 (folded into /maintenance/reset-everything) and its Joi body schema dropped from the exports in the same change — but the const definition was left behind. Dead-code audit (operator-requested, quadruple-checked before removal): [1] defined at EnmRequestSchemas.js — yes [2] referenced anywhere in src/ — NO (zero refs outside its own def) [3] referenced in tests — N/A (repo has no test files at all) [4] dynamic / bracket / string access (RequestSchemas[...]) — NONE All four checks clean → safe to remove. Module still loads; the other 12 *Body/*Headers schemas are all exported + referenced. Zero runtime behavior change (an unused Joi object) — no version bump, no redeploy; rides the next release. Audit also VERIFIED-SAFE (false alarms — NOT removed): - EnmStageSync (utils-stage-sync.js) — a first grep looked orphaned but the full grep proved it's LIVE: settings-tab.js:2557/2561 (Settings → Advanced manual stage-sync) + loaded by index.html:217. Kept. - All other EnmRequestSchemas consts — each has ≥2 refs. Kept. - No orphaned fast-sync code from the v0.5.235 removal (coerced, not stranded). No unused requires in the v0.5.236 new files. Co-Authored-By: Claude Opus 4.7 (1M context) --- enm-server/src/services/EnmRequestSchemas.js | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/enm-server/src/services/EnmRequestSchemas.js b/enm-server/src/services/EnmRequestSchemas.js index 24e2b891dd..b7fe1b48e6 100644 --- a/enm-server/src/services/EnmRequestSchemas.js +++ b/enm-server/src/services/EnmRequestSchemas.js @@ -227,18 +227,11 @@ const identityUnlockBody = Joi.object({ .messages({ 'any.required': 'Password is required.' }), }).unknown(false).label('POST /identity/unlock body'); -// POST /identity/reset — typed confirm + optional anti-snipe password. -// Frontend gates "reset keystore" exactly (case-sensitive); we re- -// check server-side as defence in depth. -const identityResetBody = Joi.object({ - confirm: Joi.string().required(), - // Optional — required only if cfg.global.antiSnipePasswordHash is - // set. The route does the conditional check. - antiSnipePassword: Joi.string().min(1).max(256).optional(), - // force=true allows reset even when the producer state is Active — - // operator must opt in explicitly via the slashing-risk modal. - force: Joi.boolean().optional(), -}).unknown(false).label('POST /identity/reset body'); +// v0.5.236 — identityResetBody schema removed (dead code). POST /identity/reset +// was retired to a 410 stub in v0.5.232 (folded into /maintenance/reset-everything); +// this Joi body was no longer exported or referenced anywhere (4-way verified: +// no src refs, no tests, no dynamic access). The shape lives in git history if a +// narrower keystore-rotation path is ever revived. // POST /identity/import — typed confirm + password. The file itself // arrives as raw bytes in the request body (Content-Type: application/ From 4575249070a035d4500c18a6794d97c3879551e2 Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Thu, 28 May 2026 21:33:57 +0300 Subject: [PATCH 11/24] refactor(enm): centralize swallow-errors audit append (DRY) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dead-code/refactor audit (operator-requested) found 4 hand-rolled "skip-if-no-db → append → log-on-failure" wrappers around AuditLog.append: routes/maintenance.js:_audit, routes/identity.js:_audit, EnmAutoStart.js:safeAudit, EnmStageSyncOrchestrator.js:safeAudit Added EnmAuditLog.safeAppend(db, log, entry) — the canonical null-guard + try/catch wrapper (never throws; a lost audit row must not block the authorised action). Callers still build their own entry (tier/ruleId/ defaults differ per caller, so field-building stays at the call site). Migrated the TWO SERVICE wrappers (EnmAutoStart, EnmStageSyncOrchestrator) to delegate — they used log.debug, matching safeAppend exactly, so behavior is unchanged (same fields, same log level). Each drops ~6 lines of boilerplate. DELIBERATELY NOT migrated (would change behavior — flagged, not silently altered): the two route _audit wrappers use log.WARN (not debug) + a lazy getDb() resolver. Migrating them would downgrade their failure log to debug. Left as-is; a behavior-preserving migration would need safeAppend to take an optional log-level, which is a separate call. Verified: 3 files node --check; safeAppend exported + returns false (no throw) on null db. Behavior-preserving → no version bump / redeploy; rides the next release. Co-Authored-By: Claude Opus 4.7 (1M context) --- enm-server/src/services/EnmAuditLog.js | 30 +++++++++++++++++++ enm-server/src/services/EnmAutoStart.js | 30 +++++++++---------- .../src/services/EnmStageSyncOrchestrator.js | 29 ++++++++---------- 3 files changed, 57 insertions(+), 32 deletions(-) diff --git a/enm-server/src/services/EnmAuditLog.js b/enm-server/src/services/EnmAuditLog.js index 1e9cffbc6c..0c2c23451d 100644 --- a/enm-server/src/services/EnmAuditLog.js +++ b/enm-server/src/services/EnmAuditLog.js @@ -226,8 +226,38 @@ function redactSensitive(obj) { return out; } +/** + * v0.5.236 — swallow-errors convenience wrapper around append(). Four call + * sites (routes/maintenance, routes/identity, EnmAutoStart, + * EnmStageSyncOrchestrator) each hand-rolled the SAME "skip if no db → append → + * log on failure" boilerplate. Centralized here so the null-guard + try/catch + * live once; callers still build their own entry (tier / ruleId / defaults + * differ per caller, so the field-building stays at the call site). NEVER + * throws — a lost audit row must never block the action that authorised it. + * + * @param {object|null} db extension data db (null → no-op, returns false) + * @param {object} log logger with .debug/.warn + * @param {object} entry full AuditEntry (see append()) + * @returns {Promise} true if the row was written, false otherwise + */ +async function safeAppend(db, log, entry) { + if (!db) { return false; } + try { + await append(db, entry); + return true; + } catch (err) { + try { + (log && log.debug ? log.debug : (() => {}))( + `${ENM_LOG_PREFIX} audit safeAppend failed (non-fatal): ${err.message}`, + ); + } catch (_) { /* logger unavailable — swallow */ } + return false; + } +} + module.exports = { append, + safeAppend, query, redactSensitive, // 0.2.0-beta.3.8 — wire the SSE publish hook from server.js boot. diff --git a/enm-server/src/services/EnmAutoStart.js b/enm-server/src/services/EnmAutoStart.js index 6ac23a2017..08702f5a9c 100644 --- a/enm-server/src/services/EnmAutoStart.js +++ b/enm-server/src/services/EnmAutoStart.js @@ -517,22 +517,20 @@ async function startAllChains(args) { * crash boot. Skips silently if the db handle was unavailable upstream. */ async function safeAudit(db, log, args) { - if (!db) { return; } - try { - await AuditLog.append(db, { - walletAddress: SYSTEM_WALLET, - chainId: args.chainId, - tier: TIER, - ruleId: RULE_ID, - decision: args.decision, - executor: EXECUTOR, - outcome: args.outcome, - durationMs: args.durationMs, - payload: { action: 'autostart' }, - }); - } catch (err) { - log.debug(`${ENM_LOG_PREFIX} autoStart: audit append failed (non-fatal): ${err.message}`); - } + // v0.5.236 — boilerplate (null-guard + try/catch + debug-log) moved to + // AuditLog.safeAppend; this wrapper keeps the autostart-specific entry + // fields. Behavior unchanged. + await AuditLog.safeAppend(db, log, { + walletAddress: SYSTEM_WALLET, + chainId: args.chainId, + tier: TIER, + ruleId: RULE_ID, + decision: args.decision, + executor: EXECUTOR, + outcome: args.outcome, + durationMs: args.durationMs, + payload: { action: 'autostart' }, + }); } module.exports = { diff --git a/enm-server/src/services/EnmStageSyncOrchestrator.js b/enm-server/src/services/EnmStageSyncOrchestrator.js index eedc7d0a32..ff0685db59 100644 --- a/enm-server/src/services/EnmStageSyncOrchestrator.js +++ b/enm-server/src/services/EnmStageSyncOrchestrator.js @@ -290,22 +290,19 @@ function cancel() { _cancelled = true; } function isRunning() { return _running; } async function safeAudit(db, log, args) { - if (!db) { return; } - try { - await AuditLog.append(db, { - walletAddress: SYSTEM_WALLET, - chainId: args.chainId, - ruleId: null, - tier: 'AUTOMATED-SAFE', - decision: args.decision, - executor: 'system', - outcome: args.outcome, - durationMs: args.durationMs, - payload: { action: 'stage-sync' }, - }); - } catch (err) { - log.debug(`${ENM_LOG_PREFIX} stage-sync: audit append failed (${err.message})`); - } + // v0.5.236 — shared null-guard + try/catch via AuditLog.safeAppend; this + // wrapper keeps the stage-sync-specific entry fields. Behavior unchanged. + await AuditLog.safeAppend(db, log, { + walletAddress: SYSTEM_WALLET, + chainId: args.chainId, + ruleId: null, + tier: 'AUTOMATED-SAFE', + decision: args.decision, + executor: 'system', + outcome: args.outcome, + durationMs: args.durationMs, + payload: { action: 'stage-sync' }, + }); } module.exports = { startStaged, cancel, isRunning }; From 83cc6bcc0389df13d681602e3a1963f3b4d6369d Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Fri, 29 May 2026 00:16:14 +0300 Subject: [PATCH 12/24] =?UTF-8?q?enm=20v0.5.237=20=E2=80=94=20UI/UX=20over?= =?UTF-8?q?haul:=20remove=20chain=20selector,=20overview-as-default,=20one?= =?UTF-8?q?=20Sidechain=20settings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Navigation: delete the top-bar chain-selector dropdown. The multi-chain overview is now the default Dashboard for a Council node with the 4 tabs always visible; clicking a chain row drills into its dashboard with a "Back to overview" control; a BPoS node lands on the single mainchain dashboard (no overview/Back). Node mode is detected in PaneRouter (logic ported from the removed selector); a static "Council node"/"BPoS node" label replaces the dropdown. Drill-in is session-only. Settings: now global (no longer per-chain). All sidechain config lives in one "Sidechain settings" tab — one shared reward address + one shared sync mode applied to all EVMs, read-only validator-status pills, and a per-chain peers/bootnodes accordion (lazy-mounted). GET /chains/:id now returns sync.mode so the tab shows real values. The dashboard EVM card is read-only; all reward/sync editing lives only in Settings. Logs: in-pane chain picker (replaces the static pill); also fixes a latent bug where the overview's active chain 'all' hit /logs/all/tail. Cleanup: delete chain-selector.js, the 5 dead per-class settings mounts, the dormant inline reward editor + its CSS, and all selector CSS/strings (~1500 net lines removed). Responsive down to compact width preserved. Co-Authored-By: Claude Opus 4.7 --- enm-server/package-lock.json | 4 +- enm-server/package.json | 2 +- enm-server/src/routes/chains.js | 9 + .../apps/elastos-node-manager/css/styles.css | 382 ++---- .../apps/elastos-node-manager/index.html | 82 +- .../apps/elastos-node-manager/js/app.js | 301 +++-- .../js/components/chain-selector.js | 353 ------ .../js/components/evm-detail-card.js | 316 +---- .../js/components/log-viewer.js | 111 +- .../js/components/multi-chain-overview.js | 33 +- .../js/components/settings-tab.js | 1028 ++--------------- .../apps/elastos-node-manager/js/strings.js | 35 +- 12 files changed, 577 insertions(+), 2079 deletions(-) delete mode 100644 src/backend/apps/elastos-node-manager/js/components/chain-selector.js diff --git a/enm-server/package-lock.json b/enm-server/package-lock.json index 3858e2418b..a8a7dcf7f7 100644 --- a/enm-server/package-lock.json +++ b/enm-server/package-lock.json @@ -1,12 +1,12 @@ { "name": "@elacity/enm-server", - "version": "0.1.0-alpha.2", + "version": "0.5.237", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@elacity/enm-server", - "version": "0.1.0-alpha.2", + "version": "0.5.237", "license": "AGPL-3.0", "dependencies": { "better-sqlite3": "^11.9.0", diff --git a/enm-server/package.json b/enm-server/package.json index fdec0dc8e9..0217c30384 100644 --- a/enm-server/package.json +++ b/enm-server/package.json @@ -1,6 +1,6 @@ { "name": "@elacity/enm-server", - "version": "0.5.236", + "version": "0.5.237", "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode AND CR Council operators.", "main": "src/server.js", "author": "Elacity", diff --git a/enm-server/src/routes/chains.js b/enm-server/src/routes/chains.js index 404257c366..937d711235 100644 --- a/enm-server/src/routes/chains.js +++ b/enm-server/src/routes/chains.js @@ -550,6 +550,15 @@ function build(extensionHandle) { isOnDuty: derivedRole ? !!derivedRole.inCurrent : null, inNextRotation: derivedRole ? !!derivedRole.inNext : null, } : null, + // v0.5.237 — persisted sync mode (full | archive) per EVM + // sidechain, so the consolidated Sidechain settings tab reads + // the REAL value instead of assuming 'full' (the frontend's + // pre-237 fallback). Class B only; null elsewhere. fast is + // coerced to full at write time (v0.5.235), so a legacy stored + // 'fast' surfaces as 'full' here too. + sync: (adapter.chainClass === 'B' && chainCfg.sync) ? { + mode: (chainCfg.sync.mode && chainCfg.sync.mode !== 'fast') ? chainCfg.sync.mode : 'full', + } : null, // v0.5.229 (Phase D) — CR Committee membership summary, // only attached to the MAINCHAIN response so the chain- // card chip can label Council operators correctly. Null diff --git a/src/backend/apps/elastos-node-manager/css/styles.css b/src/backend/apps/elastos-node-manager/css/styles.css index 5d474995b7..e14155802e 100644 --- a/src/backend/apps/elastos-node-manager/css/styles.css +++ b/src/backend/apps/elastos-node-manager/css/styles.css @@ -269,138 +269,70 @@ body { along with .enm-brand-env (was the MAINNET pill, removed 3.69). The PC2 window chrome already shows the app icon + name in its title bar; the duplicate inside the iframe was wasted header space. - See .enm-chain-selector below for the replacement — a smart chain - selector that lives in the same slot. - - Responsive overrides for .enm-brand-name (lines ~720, ~750) were - also dropped — empty selectors on a no-longer-rendered element. */ - -/* beta.3.70 — chain selector. Lives in the topbar slot vacated by - the old brand cluster. Operator's mental model: "what chain am I - looking at?" rather than "what app is this?" (the title bar - handles the latter). For a BPoS-only install (single chain - configured) the selector lists all 7 chain surfaces but only - Main chain is enabled; the rest are grayed with a hover tooltip - + a footer note explaining why. Once a council operator adds more - chains via config, the corresponding options light up. */ -.enm-chain-selector { - position: relative; + v0.5.237 — the chain-selector dropdown that replaced the brand cluster + was itself removed; a static .enm-node-mode label (defined below) now + occupies the same topbar slot, and navigation moved to the overview + + tabs. See .enm-node-mode / .enm-back-to-overview below. */ + +/* v0.5.237 — static node-mode label. Replaces the removed chain-selector + dropdown in the same topbar slot. Non-interactive; PaneRouter + (_detectNodeMode → _applyNodeModeLabel) sets its text from GET /config: + "Council node" (>=2 chains) or "BPoS node" (mainchain only). */ +.enm-node-mode { flex: 0 0 auto; -} -.enm-chain-selector-trigger { display: inline-flex; align-items: center; - gap: var(--sp-1); - padding: 4px 10px 4px 12px; - background: var(--bg-elevated); - color: var(--text-primary); - border: 1px solid var(--border-color, var(--border-subtle)); - border-radius: var(--r-md); - font: inherit; - font-size: var(--fs-caption); - font-weight: var(--fw-medium); - line-height: 1.2; - cursor: pointer; - user-select: none; - transition: background var(--motion-fast) var(--ease-out), - border-color var(--motion-fast) var(--ease-out); -} -.enm-chain-selector-trigger:hover { - background: var(--bg-surface); - border-color: var(--accent); -} -.enm-chain-selector-trigger[aria-expanded="true"] { - background: var(--bg-surface); - border-color: var(--accent); -} -.enm-chain-selector-label { + padding: 4px 10px; + font-size: 12px; + font-weight: 600; + letter-spacing: 0.02em; + color: var(--text-secondary); + background: var(--bg-tint); + border: 1px solid var(--border-color); + border-radius: var(--r-pill); white-space: nowrap; } -.enm-chain-selector-caret { - font-size: 10px; - color: var(--text-tertiary); - transition: transform var(--motion-fast) var(--ease-out); -} -.enm-chain-selector-trigger[aria-expanded="true"] .enm-chain-selector-caret { - transform: rotate(180deg); -} -.enm-chain-selector-menu { - position: absolute; - top: calc(100% + var(--sp-1)); - left: 0; - min-width: 280px; - max-width: 360px; - padding: var(--sp-1); - background: var(--bg-elevated); - border: 1px solid var(--border-color, var(--border-subtle)); - border-radius: var(--r-md); - box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35); - z-index: 100; - display: flex; - flex-direction: column; - gap: 1px; -} -.enm-chain-selector-menu[hidden] { display: none; } -.enm-chain-selector-option { - display: flex; +.enm-node-mode:empty { display: none; } +.enm-node-mode[data-mode="council"] { color: var(--accent); } +.enm-app[data-app-size="narrow"] .enm-node-mode, +body[data-app-size="narrow"] .enm-node-mode { padding: 3px 8px; font-size: 11px; } +.enm-app[data-app-size="compact"] .enm-node-mode, +body[data-app-size="compact"] .enm-node-mode { padding: 2px 6px; font-size: 10px; } + +/* v0.5.237 — "Back to overview" control. Rendered at the top of the + Dashboard pane when a Council node drills into a single chain + (PaneRouter._mountDashboardForActiveChain). Never shown for BPoS. */ +.enm-back-to-overview { + display: inline-flex; align-items: center; - gap: var(--sp-2); - padding: var(--sp-1) var(--sp-2); - border-radius: var(--r-xs); - color: var(--text-secondary); - font-size: var(--fs-caption); - cursor: pointer; - border: none; - background: transparent; - width: 100%; - text-align: left; + gap: 6px; + margin: 0 0 var(--sp-3) 0; + padding: 6px 12px; + font-size: 13px; font-family: inherit; -} -.enm-chain-selector-option:hover:not([disabled]) { - background: var(--bg-surface); - color: var(--text-primary); -} -.enm-chain-selector-option[aria-current="true"] { + line-height: 1; color: var(--accent); - font-weight: var(--fw-semibold); -} -.enm-chain-selector-option[disabled] { - opacity: 0.45; - cursor: not-allowed; -} -.enm-chain-selector-option-indicator { - width: 6px; - height: 6px; - border-radius: 50%; - flex: 0 0 auto; - background: var(--text-tertiary); -} -.enm-chain-selector-option[aria-current="true"] .enm-chain-selector-option-indicator { - background: var(--accent); - box-shadow: 0 0 6px var(--accent-soft); -} -.enm-chain-selector-option[disabled] .enm-chain-selector-option-indicator { - background: transparent; - border: 1px dashed var(--text-tertiary); + background: var(--accent-soft); + border: 1px solid var(--border-color); + border-radius: 6px; + cursor: pointer; + transition: background 0.15s ease, border-color 0.15s ease; } -.enm-chain-selector-option-label { - flex: 1 1 auto; +.enm-back-to-overview:hover { + background: var(--bg-elevated); + border-color: var(--accent); } -.enm-chain-selector-option-hint { - font-size: 10px; - color: var(--text-tertiary); - font-weight: var(--fw-regular); +.enm-back-to-overview:focus-visible { + outline: none; + box-shadow: 0 0 0 2px var(--accent); } -.enm-chain-selector-footer { - margin-top: var(--sp-1); - padding: var(--sp-2); - background: var(--bg-tint); - border-radius: var(--r-xs); - color: var(--text-tertiary); - font-size: 11px; - line-height: 1.45; +.enm-app[data-app-size="compact"] .enm-back-to-overview, +body[data-app-size="compact"] .enm-back-to-overview { + font-size: 12px; + padding: 5px 10px; } + /* Tab strip — horizontally scrollable on overflow with a right-edge fade gradient so the operator sees there's more content past the visible edge. The fade is applied via a sibling overlay because @@ -851,22 +783,6 @@ body[data-app-size="narrow"] .enm-app .enm-topbar { height: auto; min-height: 48px; } -/* beta.3.71 — chain selector compact treatment at narrow. The trigger - was sized for wide-mode (padding 4px 10px 4px 12px, fs-caption ~12px). - At <700px it competes with 4 tabs for ~660px of horizontal space and - forces .enm-tabs to wrap. Shrink trigger footprint + cap the label - to keep tabs on one row whenever the viewport allows it. */ -.enm-app[data-app-size="narrow"] .enm-chain-selector-trigger, -body[data-app-size="narrow"] .enm-app .enm-chain-selector-trigger { - padding: 3px 8px 3px 10px; - font-size: 11px; -} -.enm-app[data-app-size="narrow"] .enm-chain-selector-label, -body[data-app-size="narrow"] .enm-app .enm-chain-selector-label { - max-width: 96px; - overflow: hidden; - text-overflow: ellipsis; -} /* beta.3.26 — Phase A. The wide-mode .enm-tabs / .enm-settings-pills strips horizontally-scroll any overflowing items behind a mask- fade. The whole shape relies on touch swiping past the fade to @@ -924,33 +840,6 @@ body[data-app-size="compact"] .enm-app .enm-topbar { height: auto; min-height: 44px; } -/* beta.3.71 — chain selector compact treatment. At <480px the - selector strips down to a minimal chip: tiny padding, 10px font, - label capped to ~60px. The dropdown menu opens with full chain - names so the trigger only needs to be a visible affordance, not - the canonical chain label. aria-label="Chain view selector" on - the trigger carries the meaning for screen readers. */ -.enm-app[data-app-size="compact"] .enm-chain-selector-trigger, -body[data-app-size="compact"] .enm-app .enm-chain-selector-trigger { - padding: 2px 6px 2px 8px; - font-size: 10px; - gap: 4px; -} -.enm-app[data-app-size="compact"] .enm-chain-selector-label, -body[data-app-size="compact"] .enm-app .enm-chain-selector-label { - max-width: 64px; - overflow: hidden; - text-overflow: ellipsis; -} -/* beta.3.71 — cap the dropdown menu width so it never escapes the - viewport on compact. Without this, the 280-360px menu would clip - off the right edge inside a 280px PC2 window. */ -.enm-app[data-app-size="compact"] .enm-chain-selector-menu, -body[data-app-size="compact"] .enm-app .enm-chain-selector-menu { - min-width: 0; - width: calc(100vw - 16px); - max-width: 320px; -} .enm-app[data-app-size="compact"] .enm-tab, body[data-app-size="compact"] .enm-app .enm-tab { @@ -2158,99 +2047,6 @@ body[data-app-size="compact"] .enm-sys-cell:last-child, } .enm-detail-copy-slot { flex: 0 0 auto; } -/* ---------------------------------------------------------------- - * v0.5.228 — Inline edit affordance for the EVM block-reward - * address (evm-detail-card.js). The Edit button sits next to the - * copy button; clicking it swaps the value cell for an input + - * Save/Cancel + status. A post-save banner renders at the top of - * the card body when the chain is alive and a restart is needed - * to apply the new --pbft.miner.address on the running geth. - * ---------------------------------------------------------------- */ -.enm-detail-edit-btn { - flex: 0 0 auto; - white-space: nowrap; -} -.enm-detail-addr-row.is-editing .enm-detail-addr, -.enm-detail-addr-row.is-editing .enm-detail-copy-slot, -.enm-detail-addr-row.is-editing .enm-detail-edit-btn { - display: none; -} -.enm-detail-edit-row { - display: grid; - grid-template-columns: 1fr auto; - grid-template-areas: - "input actions" - "msg msg"; - gap: var(--sp-2); - align-items: center; - width: 100%; -} -.enm-detail-edit-input { - grid-area: input; - font-family: var(--font-mono); - font-size: var(--fs-caption); - min-width: 0; -} -.enm-detail-edit-actions { - grid-area: actions; - display: flex; - gap: var(--sp-1); - flex: 0 0 auto; -} -.enm-detail-edit-msg { - grid-area: msg; - min-height: 1.2em; - font-size: var(--fs-caption); - color: var(--text-tertiary); - line-height: 1.4; -} -.enm-detail-edit-msg.is-ok { color: var(--success); } -.enm-detail-edit-msg.is-err { color: var(--danger); } -.enm-detail-edit-msg.is-warn { color: var(--warning, #c08a00); } -.enm-app[data-app-size="compact"] .enm-detail-edit-row, -.enm-app[data-app-size="narrow"] .enm-detail-edit-row { - grid-template-columns: 1fr; - grid-template-areas: - "input" - "actions" - "msg"; -} -.enm-app[data-app-size="compact"] .enm-detail-edit-actions, -.enm-app[data-app-size="narrow"] .enm-detail-edit-actions { - justify-content: flex-end; -} - -/* Post-save banner — sits at the top of the EVM card body. */ -.enm-evm-reward-banner { - display: flex; - align-items: center; - gap: var(--sp-2); - padding: var(--sp-2) var(--sp-3); - margin-bottom: var(--sp-3); - background: var(--info-bg, var(--bg-elevated)); - border: 1px solid var(--info, var(--border-color)); - border-radius: var(--r-sm); - font-size: var(--fs-caption); - color: var(--text-primary); - line-height: 1.4; -} -.enm-evm-reward-banner-msg { - flex: 1 1 auto; - min-width: 0; -} -.enm-evm-reward-banner-msg.is-err { - color: var(--danger); -} -.enm-evm-reward-banner .enm-btn { - flex: 0 0 auto; - white-space: nowrap; -} -.enm-app[data-app-size="compact"] .enm-evm-reward-banner, -.enm-app[data-app-size="narrow"] .enm-evm-reward-banner { - flex-direction: column; - align-items: stretch; -} - /* Compact: stack the horizontal stat rows (label over value) so long values aren't crushed against the label on a 320px screen. Address rows are already stacked. */ @@ -3347,6 +3143,25 @@ body[data-app-size="compact"] .enm-section-card-foot .enm-btn, background: var(--success); } +/* v0.5.237 — in-pane chain picker (replaces the static pill). Lets Logs + scope to any installed chain now that the top chain-selector is gone. */ +.enm-log-chain-select { + flex: 0 0 auto; + max-width: 180px; + padding: 4px 8px; + background: var(--bg-surface); + border: 1px solid var(--border); + border-radius: var(--r-pill); + font-size: var(--fs-caption); + font-family: inherit; + color: var(--text-secondary); + cursor: pointer; +} +.enm-log-chain-select:focus-visible { + outline: none; + box-shadow: 0 0 0 2px var(--accent); +} + .enm-log-search { position: relative; flex: 1; @@ -6529,8 +6344,8 @@ body[data-app-size="compact"] .enm-app .enm-topbar { min-height: 44px; height: auto; } -.enm-app[data-app-size="compact"] .enm-chain-selector, -body[data-app-size="compact"] .enm-app .enm-chain-selector { +.enm-app[data-app-size="compact"] .enm-node-mode, +body[data-app-size="compact"] .enm-app .enm-node-mode { grid-area: selector; } .enm-app[data-app-size="compact"] .enm-tabs, @@ -6740,8 +6555,8 @@ body[data-app-size="compact"] .enm-app .enm-topbar { "selector" "tabs"; } -.enm-app[data-app-size="compact"] .enm-chain-selector, -body[data-app-size="compact"] .enm-app .enm-chain-selector { +.enm-app[data-app-size="compact"] .enm-node-mode, +body[data-app-size="compact"] .enm-app .enm-node-mode { justify-self: start; } @@ -7086,10 +6901,12 @@ body[data-app-size="compact"] .enm-app .enm-filter-chip { } /* Overview mode body hook (set by PaneRouter._enterOverviewMode / - _exitOverviewMode via document.body.dataset.enmOverview). */ -body[data-enm-overview="1"] .enm-app .enm-tabs { - display: none; -} + _exitOverviewMode via document.body.dataset.enmOverview). + v0.5.237 — the tab strip is NO LONGER hidden in overview mode. The + multi-chain overview is now the default Dashboard-pane content for a + Council node with the tabs always visible, so the old + `body[data-enm-overview="1"] .enm-app .enm-tabs { display:none }` rule + was removed. The body hook is kept for overview-specific styling. */ /* v0.5.186 (Council Node UX P1.4) — caption that marks the EVM-tab feature grid as roadmap (not live). On-palette tokens only. The feature grid itself @@ -8251,6 +8068,45 @@ body[data-app-size="compact"] .enm-app .enm-usage-card-value, color: var(--text-tertiary); line-height: 1.5; } +/* v0.5.237 — per-chain peers/bootnodes accordion inside the consolidated + Sidechain settings tab. One
    per EVM (esc/eid/pg); the chain's + EnmPeersPanel is lazily mounted on first open. Full-width + vertical, so + it stays usable down to very small widths. */ +.enm-evm-shared-peers-accordion { + border: 1px solid var(--border-color); + border-radius: 8px; + margin-top: var(--sp-2); + background: var(--bg-overlay); + overflow: hidden; +} +.enm-evm-shared-peers-summary { + cursor: pointer; + padding: var(--sp-2) var(--sp-3); + font-size: 14px; + font-weight: 600; + color: var(--text-primary); + list-style: none; + user-select: none; +} +.enm-evm-shared-peers-summary::-webkit-details-marker { display: none; } +.enm-evm-shared-peers-summary::before { + content: '▸'; + display: inline-block; + margin-right: 8px; + color: var(--text-tertiary); + transition: transform 0.15s ease; +} +.enm-evm-shared-peers-accordion[open] > .enm-evm-shared-peers-summary::before { + transform: rotate(90deg); +} +.enm-evm-shared-peers-summary:hover { color: var(--accent); } +.enm-evm-shared-peers-summary:focus-visible { + outline: none; + box-shadow: inset 0 0 0 2px var(--accent); +} +.enm-evm-shared-peers-mount { + padding: 0 var(--sp-3) var(--sp-2); +} .enm-app[data-app-size="compact"] .enm-evm-shared-mining-grid, .enm-app[data-app-size="narrow"] .enm-evm-shared-mining-grid, body[data-app-size="compact"] .enm-app .enm-evm-shared-mining-grid, diff --git a/src/backend/apps/elastos-node-manager/index.html b/src/backend/apps/elastos-node-manager/index.html index 1ed9b6b5f4..d89240fbcf 100644 --- a/src/backend/apps/elastos-node-manager/index.html +++ b/src/backend/apps/elastos-node-manager/index.html @@ -10,7 +10,7 @@ Elastos Node Manager - + + @@ -229,7 +204,8 @@

    Elastos Node Manager

    - + @@ -238,7 +214,7 @@

    Elastos Node Manager

    cards mounted BELOW the shared chain-card hero. Class B (EVM): mining on/off + geth/reward addresses. Class C (Oracle): parent reachable + height + last activity/error. Never mounted for the mainchain. --> - + - + - + - + @@ -294,6 +270,6 @@

    Elastos Node Manager

    (Dashboard / Logs / Settings / Audit) replaced its 4-sub-tab wrapper; the Dashboard pane now mounts SystemStatus + ChainCard + BPoS card + ToolsUpdate directly from app.js._showDashboard. --> - + diff --git a/src/backend/apps/elastos-node-manager/js/app.js b/src/backend/apps/elastos-node-manager/js/app.js index f346021973..e30d6b627e 100644 --- a/src/backend/apps/elastos-node-manager/js/app.js +++ b/src/backend/apps/elastos-node-manager/js/app.js @@ -324,29 +324,13 @@ ? new root.EnmHeightSeriesClient(this.services.api, this.services.sse) : null; - // beta.3.70 — mount the chain selector in the topbar. It's a - // small dropdown that REPLACES the old static MAINNET pill + - // duplicate brand cluster. Loads /config asynchronously to - // detect node mode (BPoS-only vs council) and renders the - // option list accordingly (others grayed for BPoS-only). - // Mount is best-effort: if the element or component is - // missing for any reason, app continues without it. - try { - var selectorEl = document.getElementById('enm-chain-selector'); - if (selectorEl && root.EnmChainSelector) { - this._chainSelector = new root.EnmChainSelector({ - root: selectorEl, - api: this.services.api, - }); - this._chainSelector.mount(); - } - } catch (err) { - // Non-fatal — log to console so a real bug surfaces in - // dev tools, but never block the rest of init. - if (typeof console !== 'undefined') { - console.warn('ENM chain selector mount failed:', err && err.message); - } - } + // v0.5.237 — the chain-selector dropdown was removed. The topbar + // now shows a static node-mode label (#enm-node-mode) that + // PaneRouter populates from GET /config (Council vs BPoS). The + // council-vs-BPoS detection that used to live in chain-selector.js + // now lives in PaneRouter._detectNodeMode; navigation between the + // multi-chain overview and a per-chain dashboard is driven by the + // enm:chain-change event (overview row clicks + the Back control). // beta.3.89 (Wave M2.1) — install the PaneRouter listener so // selector key changes route to the right pane content + tab @@ -581,18 +565,17 @@ + 'Hard-refresh the page (Ctrl-Shift-R, or ⌘-Shift-R on Mac).

    '; return; } - // beta.3.93 (M2.5) — pass chainId + chainClass so the settings - // tab dispatches to the right per-class mount entry point. - // Falls back to mainchain/A for the legacy single-chain path - // (PaneRouter init defaults _activeChainId to 'mainchain' - // when nothing's stored in localStorage). - var chainId = this._activeChainId || 'mainchain'; - var CHAIN_CLASS = root.enmChainClass; // P1.6 — single source (utils.js) + // v0.5.237 — Settings is GLOBAL now (no longer per-chain). The + // consolidated shell covers every chain — including all sidechains via + // the "Sidechain settings" section — so it always mounts with the + // mainchain (Class A) context regardless of which chain the operator + // drilled into. The SettingsTab constructor renders the global shell + // unconditionally; we pass A for clarity. this._settingsTab = new root.EnmSettingsTab({ api: this.services.api, notifications: this.services.notifications, - chainId: chainId, - chainClass: CHAIN_CLASS[chainId] || 'A', + chainId: 'mainchain', + chainClass: 'A', }); this._settingsTab.mount(this.els.paneSettings); }; @@ -849,14 +832,12 @@ this._revealContent(); this._clearPanes(); if (this.els.tabs) { this.els.tabs.hidden = true; } - // beta.0.4.2 — hide the chain selector during the setup wizard. - // Pre-0.4.2 the selector mounted in init() and stayed visible - // through every screen including welcome — confusing the - // operator who saw "Multi-chain overview" as a clickable option - // before they'd even installed mainchain. The selector belongs - // on the dashboard, not the welcome screen. - var selectorEl = document.getElementById('enm-chain-selector'); - if (selectorEl) { selectorEl.hidden = true; } + // v0.5.237 — hide the static node-mode label during the setup + // wizard (it only makes sense once chains are installed; the + // mode isn't known until /config has chains). _showDashboard + // re-shows + populates it via _detectNodeMode. + var modeLabel = document.getElementById('enm-node-mode'); + if (modeLabel) { modeLabel.hidden = true; } // alpha.28.1 batch 79 (Round-22 finding #3) — if init() already // fetched /setup/state and passed us the result, branch @@ -978,10 +959,8 @@ }; ENMApp.prototype._showDashboard = function () { - // beta.0.4.2 — restore the chain selector when leaving setup - // wizard for the dashboard. Pairs with _showSetupWizard's hide. - var selectorEl = document.getElementById('enm-chain-selector'); - if (selectorEl) { selectorEl.hidden = false; } + // v0.5.237 — the static node-mode label is re-shown + populated by + // _detectNodeMode below (it was hidden during the setup wizard). // beta.0.4.7 — the Council continuation banner has been deleted. // The redesigned 7-card wizard (setup-conversation.js) installs // everything (mainchain + ESC + EID + PG + 3 oracles + Arbiter) @@ -1044,31 +1023,27 @@ // re-mounts triggered by selector clicks. var self = this; this._dashboardMounted = true; - if (this._activeChainId === 'all') { - this._enterOverviewMode(); - } else { - this._mountDashboardForActiveChain(); - } - - // 0.5.8 audit Session 8 fix — re-detect council mode after install. - // Pre-0.5.8 the chain-selector's _refreshAvailability fired only at - // app init (boot), so chains installed during the wizard never - // triggered the v0.5.0 council-default 'all' switch. Operator - // landed on the mainchain pane with the selector still labeled - // "Main chain"; they had to click the dropdown manually to find - // the multi-chain overview. Calling refresh() here re-runs the - // /config GET; if the now-installed chain set is Council-shaped - // AND no stored selection exists, the selector flips to 'all' + - // dispatches enm:chain-change → PaneRouter (now in dashboard - // -mounted=true state) catches it via _handleChainChange → - // re-mounts the pane to the multi-chain overview. One brief - // flicker between initial pane mount and overview mount; way - // better than the stale "Main chain" label the operator hit - // in our session. - if (this._chainSelector && typeof this._chainSelector.refresh === 'function') { - try { this._chainSelector.refresh(); } - catch (_) { /* defensive: don't block dashboard render on selector refresh */ } - } + // v0.5.237 — route by node mode, re-detected on every dashboard + // entry. This subsumes the old 0.5.8 "re-detect Council after + // install" fix: when the Council wizard finishes, onComplete → + // _showDashboard → _detectNodeMode sees the freshly-installed chains + // and lands on the overview. Drill-in is session-only, so we always + // reset to the mode's default landing (overview for Council, + // mainchain for BPoS) rather than restoring a stored per-chain pick. + this._drilledIn = false; + this._detectNodeMode().then(function (mode) { + // Guard: if we transitioned back to the setup wizard while + // /config was in flight (e.g. a reinstall), don't mount. + if (!self._dashboardMounted) { return; } + if (mode === 'council') { + self._activeChainId = 'all'; + self._enterOverviewMode(); + } else { + self._activeChainId = 'mainchain'; + self._overviewMode = false; + self._mountDashboardForActiveChain(); + } + }); // Notifications pipeline — keep CRITICAL proposal cards popping // on top of the dashboard. @@ -1132,57 +1107,64 @@ }; /** - * beta.3.89 (Wave M2.1) — PaneRouter wiring. - * - * Wires the chain selector's enm:chain-change event into: - * 1. Tab strip visibility (hidden when key='all') - * 2. Pane mount (per-chain Dashboard for chain keys, multi-chain - * overview pane for 'all') + * PaneRouter wiring (v0.5.237 — selector removed). * - * The pre-M2.1 dashboard mounted unconditionally for mainchain and - * the selector event was silent (zero listeners). With PaneRouter, - * the selector becomes load-bearing: clicking "Multi-chain overview" - * actually swaps the dashboard for an aggregate view. + * Listens for the enm:chain-change event and routes the Dashboard pane: + * - key='all' → multi-chain overview (Council default; _enterOverviewMode) + * - chain key → drill into that chain's per-chain dashboard + * (_handleChainChange → _mountDashboardForActiveChain, + * with a "Back to overview" control) * - * Selector ↔ PaneRouter sync: - * - localStorage 'enm:chain-selection' is the shared key. Selector - * writes; PaneRouter reads at boot for the initial activeChainId. - * - chain-selector.js dispatches enm:chain-change on user click AND - * on availability auto-reset (selector's _refreshAvailability - * forces back to mainchain when stored selection is invalid for - * this install's mode). PaneRouter listens for both. + * Emitters of enm:chain-change are now the overview row click + * (multi-chain-overview.js#_routeToChain) and the "Back to overview" + * control — the old chain-selector dropdown that used to drive this is + * gone. The boot landing is decided by node mode (_detectNodeMode): + * Council → overview, BPoS → mainchain dashboard. The tab strip stays + * visible in every mode. Drill-in is session-only (no persistence). * - * Idempotent — _paneRouterInstalled gate stops re-wiring on Retry. + * Idempotent — the _paneRouterInstalled gate stops re-wiring on the + * init() re-run path (e.g. online-watcher reconnect), so there is + * exactly one document-level listener. * * @private */ ENMApp.prototype._initPaneRouter = function () { if (this._paneRouterInstalled) { return; } this._paneRouterInstalled = true; - // Initial activeChainId from the selector's storage key. Falls - // back to 'mainchain' for any unknown / missing value so the - // dashboard always has a definite chain to mount for. - this._activeChainId = this._loadStoredChainSelection(); - // overviewMode flag tracks whether we're rendering the multi- - // chain aggregate pane (true) or a per-chain dashboard (false). - // Default false; switched by _enterOverviewMode / _exitOverviewMode. - this._overviewMode = (this._activeChainId === 'all'); - // _dashboardMounted gates the listener so events fired during - // the setup wizard period (selector mounts at init, before the - // dashboard exists) don't try to manipulate panes that haven't - // been created. + // v0.5.237 — node mode ('council' | 'bpos-only') is resolved by + // _detectNodeMode (GET /config) and is the authoritative driver of + // the boot landing: Council → multi-chain overview; BPoS → mainchain + // dashboard. _showDashboard re-detects on every dashboard entry so a + // node that just became Council during the setup wizard flips to the + // overview. Provisional defaults until detection resolves: + this._nodeMode = null; + // 'all' = the multi-chain overview pane; a specific chainId = a + // per-chain dashboard. _showDashboard overrides this from _nodeMode, + // so the value here is only a provisional placeholder. + this._activeChainId = 'all'; + this._overviewMode = true; + // _drilledIn: true once the operator clicks a chain row in the + // overview (Council only). Gates the "Back to overview" control and + // is reset whenever we re-enter the overview. The drill-in is + // session-only — a reload always lands a Council node back on the + // overview (locked decision), so we never restore it from storage. + this._drilledIn = false; + // _dashboardMounted gates the listener so events fired during the + // setup wizard period don't manipulate panes that don't exist yet. if (typeof this._dashboardMounted !== 'boolean') { this._dashboardMounted = false; } var self = this; - // Listen at document level so the event bubbles from the - // selector root (which sits in the topbar, sibling of the - // pane container). bubbles:true is set by chain-selector.js. + // Listen at document level for enm:chain-change. Emitters: the + // overview row click (_routeToChain) and the "Back to overview" + // control. The idempotency gate above (_paneRouterInstalled) keeps + // this from double-wiring on the init() re-run path (online-watcher + // reconnect), so there's exactly one router listener. document.addEventListener('enm:chain-change', function (ev) { - var key = (ev && ev.detail && ev.detail.key) || 'mainchain'; + var key = (ev && ev.detail && ev.detail.key) || 'all'; if (!self._dashboardMounted) { - // Setup wizard is up — just remember the new selection - // so _showDashboard picks it up on transition. + // Setup wizard is up — just remember the selection so + // _showDashboard picks it up on transition. self._activeChainId = key; self._overviewMode = (key === 'all'); return; @@ -1192,18 +1174,61 @@ }; /** + * v0.5.237 — resolve node mode from GET /config. Council (>=2 configured + * chains) vs BPoS-only (mainchain only). Ported from the deleted + * chain-selector.js#_refreshAvailability so PaneRouter no longer depends + * on the selector component. Also populates the static topbar node-mode + * label. Returns a Promise<'council'|'bpos-only'> that resolves to + * 'bpos-only' on any error (safe default — a BPoS node never shows the + * overview, so a transient /config failure can't strand a Council + * operator in an empty overview). + * * @private - * @returns {string} one of: 'all', 'mainchain', 'esc', 'eid', 'pg', - * 'arbiter', 'spv'. Falls back to 'mainchain' on - * missing / unknown / non-string values. */ - ENMApp.prototype._loadStoredChainSelection = function () { - var VALID = { all: 1, mainchain: 1, esc: 1, eid: 1, pg: 1, arbiter: 1, spv: 1 }; - try { - var v = root.localStorage && root.localStorage.getItem('enm:chain-selection'); - if (typeof v === 'string' && VALID[v] === 1) { return v; } - } catch (_) { /* private-mode / storage disabled */ } - return 'mainchain'; + ENMApp.prototype._detectNodeMode = function () { + var self = this; + if (!this.services || !this.services.api || typeof this.services.api.get !== 'function') { + return Promise.resolve('bpos-only'); + } + return this.services.api.get('/config', { skipCache: true }).then(function (data) { + // api.js unwraps the envelope to parsed.result; resolve config + // across all three shapes (full envelope / unwrapped result / + // bare config) — the same triple-shape guard the selector used, + // which a prior bug got wrong and mis-detected every Council node. + var cfg = (data && data.result && data.result.config) + || (data && data.config) + || data || {}; + var chains = (cfg && cfg.chains) || {}; + var mode = (Object.keys(chains).length <= 1) ? 'bpos-only' : 'council'; + self._nodeMode = mode; + self._applyNodeModeLabel(mode); + return mode; + }).catch(function () { + self._nodeMode = self._nodeMode || 'bpos-only'; + self._applyNodeModeLabel(self._nodeMode); + return self._nodeMode; + }); + }; + + /** + * v0.5.237 — set the static topbar node-mode label text + data-mode. + * @private + * @param {'council'|'bpos-only'} mode + */ + ENMApp.prototype._applyNodeModeLabel = function (mode) { + var el = document.getElementById('enm-node-mode'); + if (!el) { return; } + el.hidden = false; + el.dataset.mode = mode; + var t = root.enmTOrFallback; + function _fb(key, fb) { + if (typeof t !== 'function') { return fb; } + var v = t(key); + return (!v || v === key || v === ('[' + key + ']')) ? fb : v; + } + el.textContent = (mode === 'council') + ? _fb('node_mode.council', 'Council node') + : _fb('node_mode.bpos', 'BPoS node'); }; /** @@ -1230,10 +1255,13 @@ this._enterOverviewMode(); return; } - // Specific chain. Exit overview mode if we were in it, then - // re-mount the Dashboard pane for the new chain. Only re-mounts + // Specific chain — drill in. Exit overview mode if we were in it, + // then mount the Dashboard pane for the new chain. Only re-mounts // when chainId actually changed — clicking the same chain twice // is a no-op (saves a full teardown + remount cycle). + // v0.5.237 — mark drilled-in so _mountDashboardForActiveChain renders + // the "Back to overview" control (Council only). + this._drilledIn = true; var prev = this._activeChainId; this._activeChainId = key; if (this._overviewMode) { @@ -1255,9 +1283,15 @@ */ ENMApp.prototype._enterOverviewMode = function () { this._overviewMode = true; - // Hide tabs (overview has no Dashboard/Logs/Settings/Audit split). - if (this.els.tabs) { this.els.tabs.hidden = true; } - // Mirror on body for CSS hooks (M2.3 styling reads this). + // v0.5.237 — entering the overview clears any drill-in state (the + // "Back to overview" control only exists for a drilled-in chain). + this._drilledIn = false; + // v0.5.237 — tabs STAY VISIBLE in overview mode. The overview is now + // the default Dashboard-pane content for a Council node, not a + // full-screen takeover, so Logs / Settings / Activity remain one + // click away. (The old `this.els.tabs.hidden = true` here — and the + // CSS rule keyed on body[data-enm-overview] — hid them; both removed.) + // The body flag is kept as a CSS hook for overview-specific styling. if (document.body) { document.body.dataset.enmOverview = '1'; } // Tear down per-chain mounts so their SSE subs + timers free. this._teardownHomeView(); @@ -1288,6 +1322,12 @@ try { this._overviewPane.destroy(); } catch (_) { /* idempotent */ } } this._overviewPane = null; + // v0.5.237 — tabs are visible in overview mode now, so the operator + // may have mounted Logs / Settings / Activity while on the overview. + // Drop those lazy handles before clearing the pane DOM; otherwise the + // next tab click returns early on a stale handle and shows a blank + // pane (the old code was safe only because overview hid the tabs). + this._teardownLazyPanes(); this._clearPanes(); }; @@ -1335,6 +1375,27 @@ var pane = this.els.paneDashboard; if (!pane) { return; } var chainId = this._activeChainId || 'mainchain'; + // v0.5.237 — "Back to overview" control. Rendered only when a Council + // node has drilled into a chain from the overview (never for BPoS, + // which has no overview). The pane is cleared by the caller before + // this runs, so we prepend it above the chain cards. Routes back via + // the same enm:chain-change('all') contract the overview rows use. + if (this._drilledIn && this._nodeMode === 'council') { + var selfBack = this; + var backBtn = document.createElement('button'); + backBtn.type = 'button'; + backBtn.className = 'enm-back-to-overview'; + var _bt = root.enmTOrFallback; + var _blabel = '← Back to overview'; + if (typeof _bt === 'function') { + var _bv = _bt('overview_pane.back_to_overview'); + if (_bv && _bv !== 'overview_pane.back_to_overview' + && _bv !== '[overview_pane.back_to_overview]') { _blabel = _bv; } + } + backBtn.textContent = _blabel; + backBtn.addEventListener('click', function () { selfBack._handleChainChange('all'); }); + pane.appendChild(backBtn); + } // beta.3.92 (M2.4) — chainClass static lookup mirrors the // server-side ChainAdapter.CHAIN_ID_TO_CLASS table. Passed // down to chain-card (and future per-class components) so diff --git a/src/backend/apps/elastos-node-manager/js/components/chain-selector.js b/src/backend/apps/elastos-node-manager/js/components/chain-selector.js deleted file mode 100644 index 3bf39a76be..0000000000 --- a/src/backend/apps/elastos-node-manager/js/components/chain-selector.js +++ /dev/null @@ -1,353 +0,0 @@ -/* - * Copyright (C) 2026-present Elacity - * SPDX-License-Identifier: AGPL-3.0 - * - * chain-selector.js — beta.3.70 — top-bar dropdown that replaces the old - * static "MAINNET" pill (and the duplicate Elastos Node Manager brand - * name + mark). Lets the operator see what chain surfaces ENM understands - * and select between them. - * - * Behaviour: - * - Always renders. Lists 7 options: - * Multi-chain overview · Main chain · ESC + Oracle · - * EID + Oracle · PG + Oracle · Arbiter · SPV - * - Detection of node type from /api/enm/config: - * 1 chain configured (mainchain only) → BPoS-only mode - * All non-mainchain options grayed out + a footer note - * explains "your selected mode is Main chain only". - * 2+ chains configured → council mode - * Configured chains light up + are selectable. - * - Active selection persists in localStorage('enm:chain-selection'). - * - Closes on outside click or Escape. - * - Future: changing selection will scope the Dashboard / Logs / - * Activity panes to that chain. For now (single chain), the - * selector is informational + future-proofing; selecting Main - * chain is a no-op past confirming the choice. - */ - -(function (root) { - 'use strict'; - - // The 7 known chain surfaces. Each entry: - // - key: stable identifier (matches cfg.chains.* keys plus - // the synthetic 'all' for the multi-chain overview) - // - label: operator-facing display string - // - hint: one-line subtitle (rendered small / dim on the row) - // - alwaysOn: true for entries that aren't a chain config entry - // (currently only 'all' — the overview view) - var CHAIN_OPTIONS = [ - { key: 'all', label: 'Multi-chain overview', hint: 'All chains aggregated' }, - { key: 'mainchain', label: 'Main chain', hint: 'ELA mainnet' }, - { key: 'esc', label: 'Smart Chain', hint: 'ESC + ESC Oracle' }, - { key: 'eid', label: 'Identity Chain', hint: 'EID + EID Oracle' }, - { key: 'pg', label: 'PG Chain', hint: 'PG + PG Oracle' }, - { key: 'arbiter', label: 'Arbiter Service', hint: 'Cross-chain arbitration' }, - // v0.5.168 (Phase 2) — SPV (class E) is NOT a standalone process: it's - // embedded in the EVM sidechains (esc/eid/pg keep their own light-client - // state under data/logs-spv) and in the arbiter (getspvheight + - // per-sidechain getsidechainblockheight). The SPV Module view aggregates - // those heights. Enabled on council nodes running ≥1 EVM sidechain or the - // arbiter (see _isOptionEnabled); grayed on a Main-chain-only node. - { key: 'spv', label: 'SPV Module', hint: 'Cross-chain SPV heights' }, - ]; - - var STORAGE_KEY = 'enm:chain-selection'; - - function ChainSelector(opts) { - if (!opts || !opts.root || !opts.api) { - throw new TypeError('ChainSelector: { root, api } required'); - } - this.root = opts.root; - this.api = opts.api; - this.trigger = this.root.querySelector('.enm-chain-selector-trigger'); - this.label = this.root.querySelector('.enm-chain-selector-label'); - this.menu = this.root.querySelector('.enm-chain-selector-menu'); - this._availableChains = new Set(['mainchain']); // safe default - this._mode = 'bpos-only'; - this._activeKey = this._loadStoredSelection() || 'mainchain'; - this._open = false; - this._onDocClick = null; - this._onKeydown = null; - } - - ChainSelector.prototype.mount = function () { - if (!this.root || !this.trigger || !this.menu) { return; } - var self = this; - // Wire trigger click. - this.trigger.addEventListener('click', function (ev) { - ev.stopPropagation(); - self._toggle(); - }); - // Initial render — async load of config to detect node type. - this._refreshAvailability(); - this._render(); - }; - - ChainSelector.prototype.destroy = function () { - this._closeMenu(); - }; - - /** @private — load stored selection if it's still a valid option key */ - ChainSelector.prototype._loadStoredSelection = function () { - try { - var v = root.localStorage && root.localStorage.getItem(STORAGE_KEY); - if (!v) { return null; } - var match = CHAIN_OPTIONS.filter(function (o) { return o.key === v; }); - return match.length ? v : null; - } catch (_) { return null; } - }; - - /** @private */ - ChainSelector.prototype._saveStoredSelection = function (key) { - try { root.localStorage.setItem(STORAGE_KEY, key); } - catch (_) { /* swallow — private mode etc. */ } - }; - - /** - * 0.5.8 audit Session 8 — public refresh entry point. - * - * Pre-0.5.8 `_refreshAvailability` only fired at mount time (app boot), - * so chains installed AFTER boot via the wizard's Council install never - * triggered the council-default 'all' switch. Selector stayed in - * 'bpos-only' mode showing just "Main chain"; operator had to click - * the selector dropdown manually to see the multi-chain options. - * app.js _showDashboard now calls this after Card 7 onComplete to - * re-detect mode + dispatch enm:chain-change → PaneRouter remounts - * the pane to multi-chain overview when council is freshly installed. - */ - ChainSelector.prototype.refresh = function () { - this._refreshAvailability(); - }; - - /** @private — fetch current config, mark available chains */ - ChainSelector.prototype._refreshAvailability = function () { - var self = this; - if (!this.api || typeof this.api.get !== 'function') { return; } - this.api.get('/config').then(function (data) { - // api.js unwraps the envelope to `parsed.result` (api.js:260), so - // `data` here is the RESULT level = { config: { chains: {...} } } — - // NOT the full { success, result } envelope. Resolve the config - // object across all three shapes: full envelope (data.result.config), - // unwrapped result (data.config — the actual runtime shape), or a - // bare config object (data). Pre-fix this only tried - // data.result.config || data, so chains came out empty on EVERY - // council node → keys.length 0 → mis-detected bpos-only + grayed. - var cfg = (data && data.result && data.result.config) - || (data && data.config) - || data || {}; - var chains = cfg.chains || {}; - var keys = Object.keys(chains); - self._availableChains = new Set(keys); - // BPoS-only when only mainchain is configured. Future: - // council operator will have ['mainchain', 'esc', 'eid', ...] - // and that count > 1 flips the mode. - self._mode = keys.length <= 1 ? 'bpos-only' : 'council'; - self.root.setAttribute('data-mode', self._mode); - // If the stored selection is no longer available for this - // node type, fall back to mainchain. - // - // beta.3.89 (Wave M2.1) — also dispatch enm:chain-change - // here so PaneRouter (app.js) syncs the dashboard pane to - // mainchain. Pre-M2.1 the auto-reset was silent: PaneRouter - // didn't exist, so nobody cared. With PaneRouter listening, - // a silent reset would leave the dashboard rendering the - // overview pane (because PaneRouter's localStorage read at - // boot saw key='all') while the selector says "Main chain". - // Dispatching keeps the two in lockstep. - var resetHappened = false; - if (self._mode === 'bpos-only' && self._activeKey !== 'mainchain') { - self._activeKey = 'mainchain'; - self._saveStoredSelection('mainchain'); - resetHappened = true; - } - // beta.0.5.0 — when the operator's node flips from bpos-only to council - // (sidechains/oracles/arbiter installed) AND they don't have an - // explicit stored selection, default to the Multi-chain overview ('all'). - // Operators on a council node land on the dashboard expecting to see - // ALL their chains; pre-0.5.0 they'd see just mainchain and have to - // hunt for the selector. - if (self._mode === 'council' && !self._loadStoredSelection()) { - self._activeKey = 'all'; - self._saveStoredSelection('all'); - resetHappened = true; - } - self._render(); - if (resetHappened) { - try { - // 0.5.73 audit Session 73 — pre-0.5.73 hardcoded - // key='mainchain'. Original beta.3.89 intent was the - // BPoS-only reset path (active → mainchain). The - // beta.0.5.0 council branch added _activeKey = 'all' - // but forgot to update the dispatch. Result on - // freshly-installed council nodes: selector UI - // shows "Multi-chain overview" highlighted while - // PaneRouter receives key='mainchain' and mounts - // the mainchain dashboard underneath — desynced. - // Use the resolved self._activeKey so both branches - // dispatch what they actually set. - self.root.dispatchEvent(new CustomEvent('enm:chain-change', { - detail: { key: self._activeKey, source: 'availability-refresh' }, - bubbles: true, - })); - } catch (_) { /* IE-era fallback unnecessary */ } - } - }).catch(function () { - // Network/auth error — leave defaults. Selector still - // functions, just stuck in safe BPoS-only state. - }); - }; - - /** @private */ - ChainSelector.prototype._render = function () { - if (!this.label || !this.menu) { return; } - var self = this; - var active = CHAIN_OPTIONS.filter(function (o) { return o.key === self._activeKey; })[0] - || CHAIN_OPTIONS[1]; // fallback to Main chain - this.label.textContent = active.label; - this.root.setAttribute('data-active', active.key); - - // Re-build menu options each render (cheap, ~7 nodes). - this.menu.innerHTML = ''; - CHAIN_OPTIONS.forEach(function (opt) { - var enabled = self._isOptionEnabled(opt.key); - var row = document.createElement('button'); - row.type = 'button'; - row.className = 'enm-chain-selector-option'; - row.setAttribute('role', 'option'); - row.setAttribute('data-key', opt.key); - if (opt.key === self._activeKey) { - row.setAttribute('aria-current', 'true'); - } - if (!enabled) { - row.disabled = true; - row.setAttribute('aria-disabled', 'true'); - row.setAttribute('title', 'Not available in this mode'); - } - var dot = document.createElement('span'); - dot.className = 'enm-chain-selector-option-indicator'; - dot.setAttribute('aria-hidden', 'true'); - row.appendChild(dot); - var label = document.createElement('span'); - label.className = 'enm-chain-selector-option-label'; - label.textContent = opt.label; - row.appendChild(label); - if (opt.hint) { - var hint = document.createElement('span'); - hint.className = 'enm-chain-selector-option-hint'; - hint.textContent = opt.hint; - row.appendChild(hint); - } - if (enabled) { - row.addEventListener('click', function () { self._select(opt.key); }); - } - self.menu.appendChild(row); - }); - - // Footer explainer when in BPoS-only mode — tells the operator - // why most options are grayed. - // - // 0.5.30 audit Session 30 — rewrote to fix three problems: - // 1. Pre-0.5.30 promised "Settings → Install chain" but that - // path does NOT exist in ENM. Stale pointer bug parallel - // to v0.5.27's Card 7 / "Producer Identity tile". - // 2. Listed SPV as an installable module (per Session 15 - // v0.5.15, SPV is a wallet protocol, not a node mode). - // 3. Listed Arbiter as a "sidechain module" (Arbiter is - // Class D cross-chain signer, not a sidechain). - // Per operator-rule positioning ([[feedback_enm_vocabulary]]): - // BPoS-only and Council are DISTINCT roles chosen at install - // time; upgrading BPoS-only → Council in place is not - // supported. Honest copy beats a non-existent upgrade path. - if (this._mode === 'bpos-only') { - var foot = document.createElement('div'); - foot.className = 'enm-chain-selector-footer'; - foot.textContent = - 'This node runs Main chain only. The grayed rows ' - + 'are for Council nodes that run additional chains.'; - this.menu.appendChild(foot); - } - }; - - /** @private — is the option selectable given current availability */ - ChainSelector.prototype._isOptionEnabled = function (key) { - if (key === 'all') { - // Multi-chain overview only makes sense once >1 chain is - // installed. Grayed out for BPoS-only nodes. - return this._mode === 'council'; - } - if (key === 'spv') { - // v0.5.168 (Phase 2) — SPV is virtual (embedded in the EVM - // sidechains + the arbiter), so cfg.chains.spv never exists. Enable - // the SPV Module whenever at least one of its host chains is - // configured — otherwise there are no SPV heights to show. - return this._availableChains.has('esc') - || this._availableChains.has('eid') - || this._availableChains.has('pg') - || this._availableChains.has('arbiter'); - } - return this._availableChains.has(key); - }; - - /** @private — select a chain (persist + re-render + close menu) */ - ChainSelector.prototype._select = function (key) { - if (!this._isOptionEnabled(key)) { return; } - this._activeKey = key; - this._saveStoredSelection(key); - this._closeMenu(); - this._render(); - // beta.3.89 (Wave M2.1) — PaneRouter in app.js listens here. - // On key='all' it hides the tab strip + mounts the multi-chain - // overview pane; on a specific chain key it shows the tab strip - // + re-mounts the Dashboard for that chain. Other components - // (audit-tab, settings-tab, log-viewer) read the active chain - // from PaneRouter's _activeChainId during their next mount cycle. - try { - this.root.dispatchEvent(new CustomEvent('enm:chain-change', { - detail: { key: key, source: 'user-click' }, - bubbles: true, - })); - } catch (_) { /* IE-era fallback unnecessary */ } - }; - - /** @private */ - ChainSelector.prototype._toggle = function () { - if (this._open) { this._closeMenu(); } - else { this._openMenu(); } - }; - - /** @private */ - ChainSelector.prototype._openMenu = function () { - var self = this; - this.menu.hidden = false; - this.trigger.setAttribute('aria-expanded', 'true'); - this._open = true; - // Close-on-outside-click — installed once per open so we don't - // keep stale listeners around. - this._onDocClick = function (ev) { - if (self.root.contains(ev.target)) { return; } - self._closeMenu(); - }; - this._onKeydown = function (ev) { - if (ev.key === 'Escape') { self._closeMenu(); self.trigger.focus(); } - }; - document.addEventListener('click', this._onDocClick, true); - document.addEventListener('keydown', this._onKeydown); - }; - - /** @private */ - ChainSelector.prototype._closeMenu = function () { - this.menu.hidden = true; - this.trigger.setAttribute('aria-expanded', 'false'); - this._open = false; - if (this._onDocClick) { - document.removeEventListener('click', this._onDocClick, true); - this._onDocClick = null; - } - if (this._onKeydown) { - document.removeEventListener('keydown', this._onKeydown); - this._onKeydown = null; - } - }; - - root.EnmChainSelector = ChainSelector; -}(typeof window !== 'undefined' ? window : globalThis)); diff --git a/src/backend/apps/elastos-node-manager/js/components/evm-detail-card.js b/src/backend/apps/elastos-node-manager/js/components/evm-detail-card.js index 0586000a2b..acf282fe35 100644 --- a/src/backend/apps/elastos-node-manager/js/components/evm-detail-card.js +++ b/src/backend/apps/elastos-node-manager/js/components/evm-detail-card.js @@ -34,13 +34,12 @@ * aria-labelledby on the card root. Copy is inline English to match the * peer node-identity-card (pending any future bulk i18n pass). * - * v0.5.228 — Block-reward address is operator-editable inline. EIP-55 - * client-side validation via enmEthAddress.check; PUT - * /chains/:id/class-b-config writes miner.rewardAddress; on success a - * "restart to apply" hint surfaces with an inline restart-now button when - * the chain is currently running (so the new --pbft.miner.address takes - * effect on the relaunched geth process). The EVM account row stays - * read-only — that's the auto-generated local keystore account and + * v0.5.237 — this card is READ-ONLY on the dashboard. Block-reward editing + * moved to the single global Settings → Sidechain settings tab (one reward + * address for all EVM sidechains), so both address rows render without an + * Edit affordance. The former inline reward editor + post-save restart + * banner (and their state) were removed entirely. The EVM account row was + * always read-only — that's the auto-generated local keystore account and * changing it would orphan the geth keystore. */ @@ -48,19 +47,6 @@ 'use strict'; var POLL_INTERVAL_MS = 60_000; - // v0.5.228 — chain states the backend reports for a *running* EVM chain - // (synced / actively-syncing / starting). When the chain is in one of - // these, a reward-address change needs a restart to take effect; when - // it's stopped / unconfigured / disabled, the change is picked up - // automatically on next start. Treats v1 aliases (running / healthy) - // as alive too in case enmStateVocab isn't loaded. - var ALIVE_STATES = ['synced', 'syncing', 'starting', 'stalled', 'running', 'healthy']; - function isChainAlive(state) { - if (root.enmStateVocab && typeof root.enmStateVocab.isAlive === 'function') { - return !!root.enmStateVocab.isAlive(state); - } - return state ? ALIVE_STATES.indexOf(String(state)) >= 0 : false; - } function EvmDetailCard(opts) { if (!opts || !opts.api) { throw new TypeError('EnmEvmDetailCard: { api } required'); } @@ -88,14 +74,10 @@ this._lastMiner = null; this._lastState = null; // v0.5.228 — most-recent chain state for restart-now affordance this._lastHtml = null; // v0.5.191 — render-dedup cache - // v0.5.228 — reward-address inline editor state. While editing, - // background polls stash new data into _lastMiner but do NOT - // rebuild the DOM (would wipe the operator's in-flight input). - this._editingReward = false; - this._editingValue = ''; - this._editorMsg = ''; - this._editorMsgKind = ''; // '' | 'ok' | 'err' | 'warn' - this._pendingRestartHint = false; // set true after save; cleared after restart-now + // v0.5.237 — the inline reward editor was removed (this card is + // read-only; reward editing lives in Settings → Sidechain settings), + // so its state fields (_editingReward / _editingValue / _editorMsg / + // _editorMsgKind / _pendingRestartHint) are gone. } EvmDetailCard.prototype.mount = function (parent) { @@ -130,11 +112,6 @@ var d = (env && env.result) || (env && env.data) || env || {}; self._lastMiner = d.miner || null; self._lastState = (d && d.state) || null; - // v0.5.228 — never rebuild the DOM while the operator is mid-edit - // (would wipe their typed input). The latest data is stashed in - // _lastMiner/_lastState and will be used by the next render after - // the editor exits. - if (self._editingReward) { return; } self._render(d); }).catch(function (err) { if (self._destroyed) { return; } @@ -152,8 +129,6 @@ var miner = d && d.miner ? d.miner : null; var evmAddr = miner && miner.evmKeystoreAddr ? miner.evmKeystoreAddr : null; var rewardAddr = miner && miner.rewardAddress ? miner.rewardAddress : null; - var chainState = (d && d.state) || this._lastState; - var chainAlive = isChainAlive(chainState); // v0.5.228d (audit F4/F5/F6) — read the DERIVED validator state // from the new miner.chainState field (now returned by GET @@ -213,9 +188,10 @@ + '
    ' + this._addrRow('Block reward address', 'Where this node\'s block rewards are credited (geth flag --pbft.miner.address). ' - + 'You can change this safely; the new address applies on next chain start.', - rewardAddr, 'reward', { editable: true }) - + this._addrRow('EVM account', evmAccountHint, evmAddr, 'evm-account', { editable: false }) + + 'v0.5.237 — read-only here; edit it (for all sidechains at once) in ' + + 'Settings → Sidechain settings.', + rewardAddr, 'reward') + + this._addrRow('EVM account', evmAccountHint, evmAddr, 'evm-account') + '
    ' + '
    ' + '
    ' @@ -229,9 +205,6 @@ // duplicate copy buttons. Every render-relevant value (mining flag, // both addresses via data-copy-value + is-empty) is in `html`. if (html === this._lastHtml) { - // Still need to refresh the post-save editor msg / restart-now - // hint without rebuilding the whole card. - this._refreshEditorBanner(chainAlive); return; } this._lastHtml = html; @@ -262,269 +235,17 @@ } } - // v0.5.228 — wire the reward-address Edit button + render any - // post-save editor banner / restart-now affordance. - this._wireRewardEditor(); - this._refreshEditorBanner(chainAlive); - }; - - /** @private — wire the Edit button on the reward row. - * Clicking it swaps the value cell for an inline editor (input + - * Save + Cancel + status line). The card-level _editingReward flag - * pauses background re-renders so the operator's typed input is - * never wiped under their fingers by a 60s poll. */ - EvmDetailCard.prototype._wireRewardEditor = function () { - var self = this; - var editBtn = this.root.querySelector('[data-edit="reward"]'); - if (!editBtn) { return; } - editBtn.addEventListener('click', function () { self._enterRewardEdit(); }); - }; - - /** @private — render or remove the post-save banner that tells the - * operator a restart is required to apply the new address. Idempotent - * so we can call it from both the dedup-skip and full-rebuild paths. */ - EvmDetailCard.prototype._refreshEditorBanner = function (chainAlive) { - // Banner lives at the top of the card body so it sits near the - // addresses without disturbing the row layout. - var body = this.root.querySelector('.enm-section-card-body'); - if (!body) { return; } - var existing = body.querySelector('.enm-evm-reward-banner'); - if (!this._pendingRestartHint) { - if (existing) { existing.parentNode.removeChild(existing); } - return; - } - var html = '' - + '
    ' - + '
    ' - + (chainAlive - ? 'Reward address saved. The currently running chain still uses the previous address — restart it to apply the change.' - : 'Reward address saved. The new address will be used the next time this chain is started.') - + '
    ' - + (chainAlive - ? '' - : '') - + '
    '; - if (existing) { - existing.outerHTML = html; - } else { - body.insertAdjacentHTML('afterbegin', html); - } - var self = this; - var restartBtn = body.querySelector('[data-action="reward-restart"]'); - if (restartBtn) { - restartBtn.addEventListener('click', function () { self._restartChainAfterSave(restartBtn); }); - } - var dismissBtn = body.querySelector('[data-action="reward-dismiss"]'); - if (dismissBtn) { - dismissBtn.addEventListener('click', function () { - self._pendingRestartHint = false; - self._refreshEditorBanner(false); - }); - } - }; - - /** @private — swap the reward value cell with an inline editor. */ - EvmDetailCard.prototype._enterRewardEdit = function () { - if (this._editingReward) { return; } // already open - this._editingReward = true; - this._editingValue = (this._lastMiner && this._lastMiner.rewardAddress) || ''; - this._editorMsg = ''; - this._editorMsgKind = ''; - this._renderRewardEditor(); - }; - - /** @private — close the editor without saving. */ - EvmDetailCard.prototype._exitRewardEdit = function () { - this._editingReward = false; - this._editingValue = ''; - this._editorMsg = ''; - this._editorMsgKind = ''; - // Force a re-render of the row by invalidating the dedup cache; the - // next _render() call from a poll OR our immediate trigger below - // will rebuild the row with the latest backend value. - this._lastHtml = null; - this._poll(); - }; - - /** @private — render the inline editor over the reward row. We keep - * the rest of the card intact and only replace the row contents. */ - EvmDetailCard.prototype._renderRewardEditor = function () { - var row = this.root.querySelector('.enm-detail-addr-row[data-key="reward"]'); - if (!row) { return; } - row.classList.add('is-editing'); - // Preserve the row head (label + hint); only swap the value stack. - var stack = row.querySelector('.enm-detail-value-stack'); - if (!stack) { return; } - var v = this._editingValue || ''; - var inputId = 'enm-evm-reward-edit-' + Math.random().toString(36).slice(2, 8); - var msgClass = this._editorMsgKind ? (' is-' + this._editorMsgKind) : ''; - stack.outerHTML = '' - + '
    ' - + '' - + '' - + '
    ' - + '' - + '' - + '
    ' - + '
    ' - + esc(this._editorMsg || '') - + '
    ' - + '
    '; - - var input = row.querySelector('.enm-detail-edit-input'); - var saveBtn = row.querySelector('[data-action="reward-save"]'); - var cancelBtn = row.querySelector('[data-action="reward-cancel"]'); - var self = this; - if (input) { - input.addEventListener('input', function () { self._editingValue = input.value; }); - input.addEventListener('keydown', function (e) { - if (e.key === 'Enter') { e.preventDefault(); self._saveReward(saveBtn); } - else if (e.key === 'Escape') { e.preventDefault(); self._exitRewardEdit(); } - }); - // Focus + select-all so the operator can immediately overwrite or copy-paste. - setTimeout(function () { - if (self._destroyed) { return; } - try { input.focus(); input.select(); } catch (_) {} - }, 0); - } - if (cancelBtn) { cancelBtn.addEventListener('click', function () { self._exitRewardEdit(); }); } - if (saveBtn) { saveBtn.addEventListener('click', function () { self._saveReward(saveBtn); }); } - }; - - /** @private — validate + PUT the new reward address. */ - EvmDetailCard.prototype._saveReward = function (saveBtn) { - var self = this; - var raw = String(this._editingValue || '').trim(); - // Empty value clears the operator-supplied reward address (rewards - // then fall back to the geth keystore default per FIX-C12b). Treat - // explicit-empty as a valid intent. - var payload; - if (raw === '') { - payload = ''; - } else { - var check = (root.enmEthAddress && typeof root.enmEthAddress.check === 'function') - ? root.enmEthAddress.check(raw) - : null; - if (!check) { - this._editorMsg = 'Address validator unavailable. Refresh the page.'; - this._editorMsgKind = 'err'; - this._renderRewardEditor(); - return; - } - if (!check.ok) { - if (check.error === 'missing_0x') { - this._editorMsg = 'Missing "0x" prefix. Suggested: ' + check.suggested; - } else if (check.error === 'format') { - this._editorMsg = 'Not a valid Ethereum address (need 0x + 40 hex characters).'; - } else if (check.error === 'eip55_checksum') { - // Soft offer the corrected form rather than block. - this._editorMsg = 'EIP-55 checksum mismatch. Did you mean ' + check.suggested + ' ?'; - } else { - this._editorMsg = 'Invalid address.'; - } - this._editorMsgKind = 'err'; - this._renderRewardEditor(); - return; - } - payload = check.normalized; - } - // Spinner + disable while in flight. - var doSave = function () { - return self.api.put('/chains/' + self.chainId + '/class-b-config', { - miner: { rewardAddress: payload }, - }).then(function () { - if (self._destroyed) { return; } - self._editingReward = false; - self._editorMsg = ''; - self._editorMsgKind = ''; - self._pendingRestartHint = true; // surfaces the banner on next render - // Refresh: pull updated cfg.miner; the banner will mention - // restart-required iff the chain is currently alive. - self._lastHtml = null; - self._poll(); - }).catch(function (err) { - if (self._destroyed) { return; } - var msg = (err && err.body && err.body.error && err.body.error.message) - || (err && err.message) - || 'Save failed.'; - self._editorMsg = msg; - self._editorMsgKind = 'err'; - // Re-render editor so the operator can correct + retry. - self._renderRewardEditor(); - }); - }; - if (typeof root.enmRunOnce === 'function' && saveBtn) { - root.enmRunOnce(saveBtn, 'Saving…', doSave); - } else { - doSave(); - } - }; - - /** @private — call POST /chains/:id/restart from the post-save banner. */ - EvmDetailCard.prototype._restartChainAfterSave = function (btn) { - var self = this; - var doRestart = function () { - return self.api.post('/chains/' + self.chainId + '/restart').then(function () { - if (self._destroyed) { return; } - self._pendingRestartHint = false; - self._lastHtml = null; - self._poll(); - }).catch(function (err) { - if (self._destroyed) { return; } - // Surface the failure in the banner area without blowing - // away the card. - var body = self.root.querySelector('.enm-section-card-body'); - if (!body) { return; } - var existing = body.querySelector('.enm-evm-reward-banner'); - var msg = (err && err.body && err.body.error && err.body.error.message) - || (err && err.message) || 'Restart failed.'; - if (existing) { - existing.innerHTML = '' - + '
    ' - + 'Restart failed: ' + esc(msg) - + '
    ' - + ''; - var retry = existing.querySelector('[data-action="reward-restart"]'); - if (retry) { - retry.addEventListener('click', function () { self._restartChainAfterSave(retry); }); - } - } - }); - }; - if (typeof root.enmRunOnce === 'function' && btn) { - root.enmRunOnce(btn, 'Restarting…', doRestart); - } else { - doRestart(); - } }; /** @private — stacked label + hint + monospace address value + copy button. * When the value is unknown we render "—" and omit the copy button (nothing - * to copy) — never a fabricated address. - * - * v0.5.228 — opts.editable=true adds an Edit button to the value stack; - * the row also gets data-key so the inline editor can find it on swap. - * "Set address" is the empty-state label so an unset row is still a - * discoverable affordance, not a dead-end "—". */ - EvmDetailCard.prototype._addrRow = function (label, hint, value, key, opts) { + * to copy) — never a fabricated address. v0.5.237 — read-only: the inline + * Edit affordance was removed (reward editing lives in Settings → Sidechain + * settings). data-key is kept for stable row identity. */ + EvmDetailCard.prototype._addrRow = function (label, hint, value, key) { var copySlot = value ? '' : ''; - var editable = opts && opts.editable === true; - var editSlot = ''; - if (editable) { - var editLabel = value ? 'Edit' : 'Set address'; - editSlot = '' - + ''; - } return '
    ' + '
    ' @@ -534,7 +255,6 @@ + '
    ' + '' + copySlot - + editSlot + '
    ' + '
    '; }; diff --git a/src/backend/apps/elastos-node-manager/js/components/log-viewer.js b/src/backend/apps/elastos-node-manager/js/components/log-viewer.js index 3e8f5cfc2b..f75da99d86 100644 --- a/src/backend/apps/elastos-node-manager/js/components/log-viewer.js +++ b/src/backend/apps/elastos-node-manager/js/components/log-viewer.js @@ -249,6 +249,17 @@ }; } + /** v0.5.237 — friendly chain name for the in-pane picker; falls back to + * the raw id when strings.js hasn't loaded or the key is missing. */ + function _logChainName(id) { + var t = root.enmTOrFallback; + if (typeof t === 'function') { + var v = t('chain_name.' + id); + if (v && v !== ('chain_name.' + id) && v !== ('[chain_name.' + id + ']')) { return v; } + } + return id; + } + function LogViewer(opts) { if (!opts || !opts.api) { throw new TypeError('LogViewer: { api, chainId } required'); @@ -256,7 +267,15 @@ this.api = opts.api; this.sse = opts.sse || null; // optional — graceful degrade this.notifications = opts.notifications || null; - this.chainId = opts.chainId || 'mainchain'; + // v0.5.237 — Logs is reachable from the overview now (tabs always + // visible), where the router's active chain is 'all'. Normalize that + // (and any falsy / aggregate value) to a real chain; the in-pane chain + // picker lets the operator switch from here. Default: mainchain. + var _cid = opts.chainId || 'mainchain'; + this.chainId = (_cid === 'all') ? 'mainchain' : _cid; + // Installed chains for the in-pane picker; populated by _loadChainList. + this._availableChains = null; + this._chainSelect = null; this._lines = []; // { stream, line, ts } — most recent at end this._followTail = true; @@ -350,9 +369,71 @@ parent.appendChild(this.root); this._loadInitialTail(); this._subscribe(); + this._loadChainList(); return this; }; + /** @private — v0.5.237 — populate the in-pane chain picker from GET + * /config so the operator can switch which chain's logs they view. Best- + * effort: on failure the picker keeps just the current (seed) chain. */ + LogViewer.prototype._loadChainList = function () { + var self = this; + if (!this.api || typeof this.api.get !== 'function') { return; } + this.api.get('/config').then(function (data) { + if (self._destroyed || !self._chainSelect) { return; } + var cfg = (data && data.result && data.result.config) + || (data && data.config) || data || {}; + var chains = (cfg && cfg.chains) || {}; + var ids = Object.keys(chains); + if (ids.length === 0) { return; } + self._availableChains = ids; + self._chainSelect.innerHTML = ''; + ids.forEach(function (id) { + var opt = document.createElement('option'); + opt.value = id; + opt.textContent = _logChainName(id); + self._chainSelect.appendChild(opt); + }); + // Edge case: current chain not in the configured set — keep it + // selectable so the viewer never points at a missing option. + if (ids.indexOf(self.chainId) === -1) { + var cur = document.createElement('option'); + cur.value = self.chainId; + cur.textContent = _logChainName(self.chainId); + self._chainSelect.insertBefore(cur, self._chainSelect.firstChild); + } + self._chainSelect.value = self.chainId; + }).catch(function () { /* keep the seed option */ }); + }; + + /** @private — v0.5.237 — switch the viewer to a different chain's logs: + * unsubscribe the old SSE topic, reset the buffer + counters, clear the + * scroller, then re-seed the tail + subscribe the new topic. The toolbar + * (search, live, level filters) is preserved — no full remount. */ + LogViewer.prototype._switchChain = function (newId) { + if (!newId || newId === this.chainId || this._destroyed) { return; } + if (this._unsubscribe) { this._unsubscribe(); this._unsubscribe = null; } + this.chainId = newId; + this._lines = []; + this._lvlCounts = { error: 0, warn: 0, info: 0, debug: 0 }; + this._collapsedCount = 0; + this._initialTailDone = false; + this._pendingSseBatches = []; + if (this._scroller) { this._scroller.innerHTML = ''; } + if (this._chainSelect && this._chainSelect.value !== newId) { + this._chainSelect.value = newId; + } + // Reset the meta count + per-level chips to zero for the new chain. + if (typeof this._refreshMeta === 'function') { this._refreshMeta(); } + ['error', 'warn', 'info', 'debug'].forEach(function (lvl) { + if (typeof this._refreshLvlChipCount === 'function') { + this._refreshLvlChipCount(lvl); + } + }, this); + this._loadInitialTail(); + this._subscribe(); + }; + LogViewer.prototype.destroy = function () { // Mark destroyed FIRST so any in-flight _loadInitialTail // resolutions short-circuit before mutating detached DOM. @@ -386,18 +467,26 @@ var title = document.createElement('div'); title.className = 'enm-log-title'; - title.textContent = this.chainId; - // a11y: heading truncates with text-overflow:ellipsis on narrow - // widths. Mirror the full label into title= so it stays readable. - title.title = this.chainId; + title.textContent = 'Logs'; toolbarLeft.appendChild(title); - // Chain pill — only one chain in v0.1; the pill is a surface - // ready for a future selector. Active by default. - var pill = document.createElement('span'); - pill.className = 'enm-log-chain-pill active'; - pill.textContent = this.chainId; - toolbarLeft.appendChild(pill); + // v0.5.237 — in-pane chain picker (replaces the static chain pill). + // The top chain-selector dropdown was removed, so Logs owns its own + // chain scope. Populated by _loadChainList from GET /config; switching + // re-seeds the tail + swaps the SSE topic without a full remount. + var chainSelect = document.createElement('select'); + chainSelect.className = 'enm-log-chain-select'; + chainSelect.setAttribute('aria-label', 'Log chain'); + var seedOpt = document.createElement('option'); + seedOpt.value = this.chainId; + seedOpt.textContent = _logChainName(this.chainId); + chainSelect.appendChild(seedOpt); + chainSelect.value = this.chainId; + chainSelect.addEventListener('change', function () { + self._switchChain(chainSelect.value); + }); + this._chainSelect = chainSelect; + toolbarLeft.appendChild(chainSelect); // Search input. Debounced 200ms so the regex compile + DOM // re-walk doesn't fire on every keystroke. diff --git a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js index e5a3beb74b..0c9eee89e4 100644 --- a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js +++ b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js @@ -21,10 +21,11 @@ * by class (A→B→C→D→E), one section per class, one row per chain: * [● state-dot] Chain name · state · uptime · sparkline · → * - * 3. Clicking a row routes to that chain's per-chain pane via the - * chain-selector contract: write localStorage('enm:chain-selection') - * + dispatch enm:chain-change event. PaneRouter listens for that - * event and re-mounts. + * 3. Clicking a row routes to that chain's per-chain pane by dispatching + * the enm:chain-change event (v0.5.237 — the old chain-selector + + * localStorage contract was removed). PaneRouter listens for that event, + * drills into the chain's dashboard, and shows a "Back to overview" + * control. Drill-in is session-only; a reload returns to the overview. * * 4. destroy() unsubscribes SSE + per-chain height-series subs + tears * down all per-chain sparkline instances + removes the root element. @@ -1538,25 +1539,11 @@ */ EnmMultiChainOverviewPane.prototype._routeToChain = function (chainId) { if (!chainId) { return; } - try { - if (root.localStorage && typeof root.localStorage.setItem === 'function') { - root.localStorage.setItem('enm:chain-selection', chainId); - } - } catch (_) { /* private mode */ } - // Mirror the new label into the selector trigger so the topbar - // updates in sync with the route. Best-effort: a missing selector - // element just means the topbar will catch up on its own next - // _render. PaneRouter's listener does the heavy lifting. - try { - var selectorEl = document.getElementById('enm-chain-selector'); - if (selectorEl) { - selectorEl.setAttribute('data-active', chainId); - var label = selectorEl.querySelector('.enm-chain-selector-label'); - if (label && CHAIN_DISPLAY_FALLBACK[chainId]) { - label.textContent = CHAIN_DISPLAY_FALLBACK[chainId]; - } - } - } catch (_) { /* no-op */ } + // v0.5.237 — the chain selector dropdown was removed. Row clicks route + // PURELY via the enm:chain-change event below; PaneRouter catches it + // and drills into the chain's dashboard (rendering a "Back to overview" + // control). Nothing is persisted — drill-in is session-only, so a + // reload always lands a Council node back on the overview. try { document.dispatchEvent(new CustomEvent('enm:chain-change', { detail: { key: chainId, source: 'overview-row-click' }, diff --git a/src/backend/apps/elastos-node-manager/js/components/settings-tab.js b/src/backend/apps/elastos-node-manager/js/components/settings-tab.js index 603a95fd3f..906aa22c09 100644 --- a/src/backend/apps/elastos-node-manager/js/components/settings-tab.js +++ b/src/backend/apps/elastos-node-manager/js/components/settings-tab.js @@ -137,31 +137,19 @@ this._sections = {}; this._navItems = {}; this._pills = {}; - // beta.3.93 (M2.5) — dispatch by class. Class A keeps the full - // existing 7-card settings (network / identity / security / - // alerts / storage / advanced / danger). Classes B/C/D/E render - // M2.5 stubs explaining the milestone path; M3.3/M4.2/M6.4 - // replace each stub with the real per-class layout. - switch (this.chainClass) { - case 'A': - this._mountMainchainSettings(); - break; - case 'B': - this._mountEvmSidechainSettings(this.chainId); - break; - case 'C': - this._mountOracleSettings(this.chainId); - break; - case 'D': - this._mountArbiterSettings(); - break; - case 'E': - this._mountSpvSettings(); - break; - default: - this._mountMainchainSettings(); // safest fallback - break; - } + // v0.5.237 — Settings is now GLOBAL (one settings area for the whole + // node), no longer scoped per-chain. The chain-selector that used to + // scope Settings to a single chain was removed; ALL sidechain + // configuration now lives in the shared "Sidechain settings" section + // of this one shell (reward + sync for every EVM, read-only validator + // status, and a per-chain peers/bootnodes accordion). So every + // instance renders the full global shell regardless of the + // chainId/chainClass it was constructed with. + // + // The old per-class mounts (_mountEvmSidechainSettings / _renderClassBForm + // / _mountOracleSettings / _mountArbiterSettings / _mountSpvSettings) + // are now unreachable and are removed in the Phase 5 dead-code cleanup. + this._mountMainchainSettings(); } SettingsTab.prototype.mount = function (parent) { @@ -190,924 +178,6 @@ this._renderShell(); }; - /** - * Class B (EVM sidechain: ESC / EID / PG) settings mount. - * - * Layout — Mining & Rewards · PBFT signing keystore reference · Sync - * mode · Restart. The signing keystore is shared with the Main chain - * (PBFT convention). Reads cfg.chains[chainId] via GET /config; saves - * changes via PUT /chains//class-b-config. - * - * @private - * @param {string} chainId — esc | eid | pg - */ - SettingsTab.prototype._mountEvmSidechainSettings = function (chainId) { - var fallbackChainNames = { esc: 'Smart Chain (ESC)', eid: 'Identity Chain (EID)', pg: 'PG Chain' }; - var name = _tFb('chain_name.' + chainId, fallbackChainNames[chainId] || chainId); - var self = this; - this.root.innerHTML = '' - + '
    ' - + '

    ' + escapeHtml(name) + ' settings

    ' - + '

    EVM sidechain — mining and sync controls. ' - + 'Block signing reuses the Main chain keystore; ENM never holds the private key.

    ' - + '
    ' - + '
    ' - + '

    Loading current configuration…

    ' - + '
    '; - var body = this.root.querySelector('.enm-settings-class-body'); - this.api.get('/config', { skipCache: true }).then(function (data) { - if (self._destroyed) { return; } - var cfg = (data && data.config) || {}; - var chainCfg = (cfg.chains && cfg.chains[chainId]) || null; - if (!chainCfg) { - body.dataset.state = 'unconfigured'; - // 0.5.13 audit Session 13 — strip M3.5 milestone ref from - // operator-facing copy. Pre-0.5.13 said "Use the setup - // wizard (lands in M3.5) to install this chain" — operator - // cannot decode the M3.5 tag. - body.innerHTML = '' - + '
    ' - + '

    ' + escapeHtml(name) + ' is not yet installed.

    ' - + '

    Use the setup wizard to install this chain before ' - + 'configuring its mining and sync options.

    ' - + '
    '; - return; - } - self._renderClassBForm(body, chainId, chainCfg); - }).catch(function (err) { - if (self._destroyed) { return; } - // 0.5.132 audit Session 132 — silence on 401. Loading state - // ("Loading current configuration…") stays in the body; login - // overlay takes over, on re-auth the operator can switch - // chains away and back to re-trigger this load cleanly. - if (err && err.status === 401) { return; } - body.dataset.state = 'error'; - body.innerHTML = '

    Failed to load config: ' - + escapeHtml((err && err.message) || String(err)) + '

    '; - }); - }; - - /** - * @private — paint the Class B editor form. Sections: - * - Mining & Rewards: enabled toggle, rewardAddress, evmKeystoreAddr, threads - * - PBFT signing keystore: read-only pointer to mainchain keystore - * - Sync mode: fast | full | archive - * - Restart: per-chain restart - */ - SettingsTab.prototype._renderClassBForm = function (parent, chainId, chainCfg) { - var self = this; - var miner = chainCfg.miner || {}; - var sync = chainCfg.sync || {}; - // v0.5.187 (Phase 4) — compute the display name here. Pre-0.5.187 this - // method referenced an undefined `name`, silently reading window.name - // (the Restart button rendered "Restart " with an empty suffix). - var fallbackChainNames = { esc: 'Smart Chain (ESC)', eid: 'Identity Chain (EID)', pg: 'PG Chain' }; - var name = _tFb('chain_name.' + chainId, fallbackChainNames[chainId] || chainId); - parent.dataset.state = 'ready'; - parent.innerHTML = ''; - - // v0.5.187 (Council Node UX Phase 4) — re-emit through the same - // canonical primitives the Class-A (mainchain) settings use: - // makeSection (savable card w/ Save+Revert+status), makeInfoCard - // (foot-less read-only/action card), makeFormRow / makeToggleRow / - // makeInput / makeSelectWrap for controls. Class A render path is - // untouched (this method is only reached for chainClass === 'B'). - - // ---- Card 1: Mining & sync (savable) ---- - var sec = makeSection({ - id: 'classb-mining', - icon: '', - title: 'Mining & sync', - help: 'Whether this node produces blocks for ' + name + ', where rewards go, and ' - + 'how much history it keeps. Restart the chain after saving to apply.', - tag: { kind: 'muted', label: 'Restart to apply' }, - }); - - // v0.5.228 — replace the writable "Mining on/off" toggle with a - // READ-ONLY "Validator status" badge. Mining on an Elastos EVM - // sidechain is not an operator-settable knob: it's derived from - // on-chain producer / Council membership (the chain's PBFT - // engine self-gates Seal() based on the current arbiter slate; - // see EvmSidechainAdapter.detectProducerRole + start, both - // already shipped since v0.5.188). The pre-v228 toggle was - // misleading — clicking it changed cfg.miner.enabled in - // ConfigStore, but EvmSidechainAdapter.start always overwrote - // it before spawn, so the toggle was visible but ineffectual. - // Operator directive 2026-05-27: "node.sh doesn't work like - // that for council nodes — after binding, the chain itself - // recognized it's a council node and the set evm mining - // addresses automatically became mining addresses". - // - // The badge is populated asynchronously from - // GET /api/enm/system/council-status, which exposes the same - // detectProducerRole the spawn path uses. Initial render shows - // a loading state. If the fetch fails or times out, the badge - // falls back to whatever cfg.miner.enabled currently reads as - // (the cached derived value from the last successful spawn). - var statusRow = document.createElement('div'); - statusRow.className = 'enm-classb-validator-row'; - statusRow.setAttribute('role', 'group'); - statusRow.setAttribute('aria-label', 'Validator status'); - var statusBadgeId = 'enm-classb-validator-' + chainId; - statusRow.innerHTML = '' - + '
    ' - + '
    Validator status
    ' - + '
    ' - + 'Derived from the on-chain CR-Council / DPoS arbiter slate. ' - + 'Mining activates automatically when this node\'s public key ' - + 'is bound to a Council seat (via Elastos Essentials) and the ' - + 'current rotation includes it — there is no manual toggle.' - + '
    ' - + '
    ' - + '
    ' - + 'Checking on-chain status…' - + '
    '; - sec.body.appendChild(statusRow); - // Fire the council-status fetch immediately so the badge resolves - // soon after render. Fallback to the cached miner.enabled if the - // endpoint is unreachable (boot path, mainchain still syncing). - (function (badgeId, cid, cachedEnabled) { - self.api.get('/system/council-status').then(function (env) { - if (self._destroyed) { return; } - var data = (env && env.data) || env || {}; - var perChain = (data.chains && data.chains[cid]) || null; - var badge = self.root.querySelector('#' + badgeId); - if (!badge) { return; } - var s = (perChain && perChain.chainState) || 'unknown'; - // Map raw chainState → visible label + badge color. - // 'on-duty' → green "On-duty" - // 'standby' → amber "Standby" - // 'inactive' → gray "Inactive (not in current rotation)" - // 'unknown' → gray "Detecting…" - // 'follower' → gray "Follower (not configured for mining)" - var labelMap = { - 'on-duty': { label: 'On-duty', sub: 'Producing blocks this rotation — rewards land at the address below.' }, - 'standby': { label: 'Standby', sub: 'Bound to a Council seat; in the next rotation\'s arbiter slate.' }, - 'inactive': { label: 'Inactive', sub: 'Not in the current or next arbiter slate. Mining activates automatically when this node\'s public key is on-duty.' }, - 'unknown': { label: 'Detecting', sub: 'Reading mainchain arbiter slate… retry every chain start.' }, - 'follower': { label: 'Follower', sub: 'Chain not configured for mining (no init was run).' }, - }; - var meta = labelMap[s] || labelMap.unknown; - badge.dataset.state = s; - badge.textContent = meta.label; - // Add the explanatory sub-line right after the badge. - var subEl = badge.parentNode.querySelector('.enm-classb-validator-sub'); - if (!subEl) { - subEl = document.createElement('div'); - subEl.className = 'enm-classb-validator-sub'; - badge.parentNode.appendChild(subEl); - } - subEl.textContent = meta.sub; - }).catch(function (err) { - if (self._destroyed) { return; } - if (err && err.status === 401) { return; } - // v0.5.228d (audit F3) — fallback wording. The pre-228d - // label "(cached)" implied the backend had recently - // confirmed this state; in reality the fallback reads - // cfg.miner.enabled from disk, which is the value the - // last successful spawn wrote — could be hours/days - // stale. "(from last spawn)" is honest about the - // source. Real-time state lives on /system/council-status - // which this fallback only runs when we couldn't - // reach. - var badge = self.root.querySelector('#' + badgeId); - if (!badge) { return; } - if (cachedEnabled) { - badge.dataset.state = 'on-duty'; - badge.textContent = 'On-duty (from last spawn)'; - } else { - badge.dataset.state = 'inactive'; - badge.textContent = 'Inactive (from last spawn)'; - } - var subEl = badge.parentNode.querySelector('.enm-classb-validator-sub'); - if (!subEl) { - subEl = document.createElement('div'); - subEl.className = 'enm-classb-validator-sub'; - badge.parentNode.appendChild(subEl); - } - subEl.textContent = 'Could not reach /system/council-status; ' - + 'showing the value from this node\'s last spawn. ' - + 'Live status refreshes on every chain start.'; - }); - }(statusBadgeId, chainId, !!miner.enabled)); - - var rewardInput = makeInput({ value: miner.rewardAddress || '', placeholder: '0x…40 hex chars', mono: true, ariaLabel: 'Reward address' }); - rewardInput.setAttribute('spellcheck', 'false'); - rewardInput.setAttribute('autocomplete', 'off'); - var rewardRow = makeFormRow({ label: 'Reward address', help: 'Where mining rewards are credited. 0x + 40 hex characters.', control: rewardInput }); - sec.body.appendChild(rewardRow); - - var evmInput = makeInput({ value: miner.evmKeystoreAddr || '', placeholder: '0x…40 hex chars (often same as reward)', mono: true, ariaLabel: 'EVM keystore address' }); - evmInput.setAttribute('spellcheck', 'false'); - evmInput.setAttribute('autocomplete', 'off'); - var evmRow = makeFormRow({ label: 'EVM keystore address', help: 'Account unlocked for signing. 0x + 40 hex characters.', control: evmInput }); - sec.body.appendChild(evmRow); - - var threadsInput = makeInput({ type: 'number', value: Number.isInteger(miner.threads) ? miner.threads : 1, min: 1, max: 16, ariaLabel: 'Mining threads' }); - threadsInput.addEventListener('input', function () { sec.setDirty(true); }); - sec.body.appendChild(makeFormRow({ label: 'Mining threads', help: 'CPU threads used while mining is on.', control: threadsInput })); - - // v0.5.235 — fast sync removed. ENM nodes are validators (Council/BPoS); - // EVM chains always run validator-grade full sync. Only full (default) - // and archive (full + all historical state) remain. - var syncSel = makeSelectWrap({ - options: [ - { value: 'full', label: 'full — validator-grade (recommended)' }, - { value: 'archive', label: 'archive — full + all historical state' }, - ], - value: (sync.mode && sync.mode !== 'fast') ? sync.mode : 'full', - onChange: function () { sec.setDirty(true); }, - }); - sec.body.appendChild(makeFormRow({ label: 'Sync mode', help: 'How much chain history this node retains. Council/BPoS nodes always full-sync.', control: syncSel.el })); - - parent.appendChild(sec.card); - - // ---- Card 2: Block-signing keystore (read-only) ---- - parent.appendChild(makeInfoCard({ - title: 'Block-signing keystore', - help: 'This chain signs blocks with the Main chain keystore; ENM never holds the ' - + 'private key. To change its password or import a different one, switch the ' - + 'chain selector to Main chain and open Settings → Identity.', - codeLine: 'chains/mainchain/keystore.dat', - }).card); - - // ---- Card 3: Restart (action) ---- - var restartCard = makeInfoCard({ - title: 'Restart', - help: 'After saving mining or sync changes, restart ' + name + ' to apply them. ' - + 'Also useful if the chain is stuck or stalls on sync.', - }); - var restartBtn = document.createElement('button'); - restartBtn.type = 'button'; - restartBtn.className = 'enm-btn enm-btn-secondary'; - restartBtn.textContent = 'Restart ' + name; - var restartStatus = document.createElement('p'); - restartStatus.className = 'enm-section-card-foot-status'; - restartStatus.setAttribute('role', 'status'); - restartStatus.setAttribute('aria-live', 'polite'); - restartStatus.hidden = true; - restartCard.body.appendChild(restartBtn); - restartCard.body.appendChild(restartStatus); - parent.appendChild(restartCard.card); - - // ---- Card 4: Binary update (v0.5.187 Phase 5) — re-download latest ---- - // The backend (POST /chains/:id/update) re-downloads the latest binary - // (node.sh ela_update model) and requires the chain stopped. There is - // NO per-EVM "update available" check endpoint (/updates/available is - // mainchain-only), so this honestly offers a re-download + shows the - // installed version — it does not fake a vX→vY diff or "up to date". - var updateCard = makeInfoCard({ - title: 'Binary update', - help: 'Re-downloads the latest ' + name + ' binary. Stop the chain first (from the ' - + 'dashboard or overview), update here, then start it again. Updating replaces ' - + 'only the binary — it does not touch chain data.', - }); - var verList = document.createElement('div'); - verList.className = 'enm-detail-list'; - var verRow = document.createElement('div'); - verRow.className = 'enm-detail-row'; - var verLbl = document.createElement('span'); - verLbl.className = 'enm-detail-label'; - verLbl.textContent = 'Installed version'; - var verVal = document.createElement('span'); - verVal.className = 'enm-detail-value enm-detail-addr'; - verVal.textContent = chainCfg.binaryVersion || 'unknown'; - verRow.appendChild(verLbl); - verRow.appendChild(verVal); - verList.appendChild(verRow); - updateCard.body.appendChild(verList); - var updateBtn = document.createElement('button'); - updateBtn.type = 'button'; - updateBtn.className = 'enm-btn enm-btn-secondary'; - updateBtn.textContent = 'Update binary'; - var updateStatus = document.createElement('p'); - updateStatus.className = 'enm-section-card-foot-status'; - updateStatus.setAttribute('role', 'status'); - updateStatus.setAttribute('aria-live', 'polite'); - updateStatus.hidden = true; - updateCard.body.appendChild(updateBtn); - updateCard.body.appendChild(updateStatus); - parent.appendChild(updateCard.card); - updateBtn.addEventListener('click', function () { - self._updateClassB(chainId, name, updateBtn, updateStatus); - }); - - // ---- Card 5: Network peers (self-contained panel) ---- - var peersCard = makeInfoCard({ - title: 'Network peers', - help: 'Bootnodes and live peers for ' + name + '. Changes here apply immediately and ' - + 'are independent of the mining/sync save above.', - }); - var peersMount = document.createElement('div'); - peersCard.body.appendChild(peersMount); - parent.appendChild(peersCard.card); - - // ---- v0.5.216 audit Phase 2 (AUDIT-FLOW-B01, P1) — address - // validation now routes through the SHARED root.enmEthAddress - // helper (same source the setup wizard Card 4 uses), so the - // EIP-55 mixed-case hard-block that protects new operators at - // install time also protects operators ROTATING addresses via - // Settings. Pre-v0.5.216 this section had only basic format - // validation — paste a mixed-case address with one char's case - // flipped, save, and future rewards went to a different - // account silently. Now blocked + suggested-correct-case shown - // inline. Closes XFLOW-04 + XFLOW-16 duplication of validateEth. - var ethApi = root.enmEthAddress; - var classifyAddr = function (v) { - var str = (v || '').trim(); - if (!str) { return { kind: 'empty' }; } - if (!ethApi || typeof ethApi.check !== 'function') { - // Defensive fallback if utils-eth failed to load — - // preserves the pre-v0.5.216 format-only check. - return /^0x[0-9a-fA-F]{40}$/.test(str) - ? { kind: 'ok' } - : { kind: 'bad' }; - } - var r = ethApi.check(str); - if (r.ok) { - return r.warn === 'no_keccak' - ? { kind: 'ok-degraded' } - : { kind: 'ok' }; - } - if (r.error === 'eip55_checksum') { - return { kind: 'checksum', suggested: r.suggested }; - } - return { kind: 'bad' }; - }; - // Tiny helper to surface a one-line correction hint inline in - // the row's existing status area. The row's data-validity attr - // also drives any per-row CSS (red border on 'bad'/'checksum'). - var setRowStatus = function (row, msg) { - // Find or create a status span at the foot of the row. - var slot = row.querySelector('.enm-row-status') || (function () { - var s = document.createElement('div'); - s.className = 'enm-row-status'; - s.setAttribute('aria-live', 'polite'); - row.appendChild(s); - return s; - }()); - slot.textContent = msg || ''; - slot.hidden = !msg; - }; - var refreshValidity = function () { - var r = classifyAddr(rewardInput.value); - var e = classifyAddr(evmInput.value); - rewardRow.setAttribute('data-validity', r.kind); - evmRow.setAttribute('data-validity', e.kind); - setRowStatus(rewardRow, r.kind === 'checksum' - ? 'Wrong checksum — did you mean: ' + r.suggested + '?' - : ''); - setRowStatus(evmRow, e.kind === 'checksum' - ? 'Wrong checksum — did you mean: ' + e.suggested + '?' - : ''); - // Disable Save on either field being a definite typo: 'bad' - // (format) or 'checksum' (mixed-case mismatch). 'empty' and - // 'ok-degraded' still allow save — empty is a real signal - // (operator clearing the field to disable mining), and the - // degraded mode means keccak couldn't verify so we default - // to permissive (same as pre-v0.5.216 behavior). - sec.saveBtn.disabled = (r.kind === 'bad' || r.kind === 'checksum') - || (e.kind === 'bad' || e.kind === 'checksum'); - }; - rewardInput.addEventListener('input', function () { sec.setDirty(true); refreshValidity(); }); - evmInput.addEventListener('input', function () { sec.setDirty(true); refreshValidity(); }); - refreshValidity(); - - // ---- save (reads control handles; enmRunOnce guards double-submit) ---- - // v0.5.228 — controls.enabled is intentionally absent. The save - // body below no longer includes miner.enabled — the backend - // derives it from on-chain arbiter slate at every chain start. - var controls = { reward: rewardInput, evm: evmInput, threads: threadsInput, syncMode: syncSel }; - sec.saveBtn.addEventListener('click', function () { - self._saveClassB(chainId, controls, sec); - }); - sec.revertBtn.addEventListener('click', function () { - // No enabledToggle to revert — it's a derived read-only badge. - rewardInput.value = miner.rewardAddress || ''; - evmInput.value = miner.evmKeystoreAddr || ''; - threadsInput.value = Number.isInteger(miner.threads) ? miner.threads : 1; - syncSel.setValue((sync.mode && sync.mode !== 'fast') ? sync.mode : 'full'); - refreshValidity(); - sec.setDirty(false); - if (sec.statusEl) { sec.statusEl.textContent = ''; } - }); - - // ---- restart (confirm-before-disruptive + enmRunOnce) ---- - restartBtn.addEventListener('click', function () { - self._restartClassB(chainId, name, restartBtn, restartStatus); - }); - - // ---- Network peers panel — destroy any prior instance first (form - // re-renders on chain switch / reload); destroy() tears it down. ---- - if (this._peersPanel) { - try { this._peersPanel.destroy(); } catch (_) { /* idempotent */ } - this._peersPanel = null; - } - if (root.EnmPeersPanel) { - this._peersPanel = new root.EnmPeersPanel({ - api: this.api, - chainId: chainId, - notifications: this.notifications, - }); - this._peersPanel.mount(peersMount); - } - }; - - /** @private — v0.5.187 (Phase 4): reads from the control handles built in - * _renderClassBForm (toggle/select expose getValue; inputs expose .value). - * enmRunOnce guards the Save button against double-submit and manages its - * disabled/label state; the status line is managed separately. */ - SettingsTab.prototype._saveClassB = function (chainId, controls, sec) { - var self = this; - var status = sec.statusEl; - // v0.5.228 — miner.enabled removed from the request body. It's - // a derived value (computed at every chain start from on-chain - // arbiter slate), not operator-settable. Sending it from this - // form would be a no-op at best and misleading at worst. - var body = { - miner: { - rewardAddress: (controls.reward.value || '').trim(), - evmKeystoreAddr: (controls.evm.value || '').trim(), - threads: parseInt(controls.threads.value, 10) || 1, - }, - sync: { - mode: controls.syncMode.getValue(), - }, - }; - if (status) { status.textContent = ''; } - var doSave = function () { - return self.api.put('/chains/' + chainId + '/class-b-config', body).then(function () { - if (self._destroyed) { return; } - sec.setDirty(false); - // Point the operator at the in-pane Restart card to apply. - if (status) { status.textContent = 'Saved. Use Restart below to apply.'; } - }).catch(function (err) { - if (self._destroyed) { return; } - // Silence on 401 — boot path owns re-auth. - if (err && err.status === 401) { return; } - if (status) { status.textContent = 'Save failed: ' + ((err && err.message) || String(err)); } - }); - }; - if (typeof root.enmRunOnce === 'function') { - root.enmRunOnce(sec.saveBtn, 'Saving…', doSave); - } else { - sec.saveBtn.disabled = true; - doSave().finally(function () { sec.saveBtn.disabled = false; }); - } - }; - - /** - * @private — v0.5.187 (Phase 5): re-download the latest binary for an EVM - * chain via POST /chains/:id/update (node.sh ela_update model). The backend - * requires the chain stopped (409 otherwise) and exposes NO per-EVM - * "update available" check — so this is a safe re-download with a clear - * stop-first message on 409, not a version diff. Confirm + enmRunOnce. - */ - SettingsTab.prototype._updateClassB = function (chainId, name, btn, statusEl) { - var self = this; - if (typeof root.confirm === 'function' - && !root.confirm('Update the ' + name + ' binary now? Stop the chain first; this ' - + 're-downloads the latest binary and does not touch chain data.')) { - return; - } - statusEl.hidden = false; - statusEl.className = 'enm-section-card-foot-status'; - statusEl.textContent = 'Updating…'; - var doUpdate = function () { - return self.api.post('/chains/' + chainId + '/update', {}).then(function () { - if (self._destroyed) { return; } - statusEl.className = 'enm-section-card-foot-status success'; - statusEl.textContent = 'Binary updated. Start the chain to run the new version.'; - }).catch(function (err) { - if (self._destroyed) { return; } - if (err && err.status === 401) { statusEl.hidden = true; return; } - statusEl.className = 'enm-section-card-foot-status error'; - // 409 = chain still running; the backend message tells the - // operator to stop it first. Surface the backend message verbatim. - statusEl.textContent = (err && err.message) ? err.message : 'Update failed. Try again.'; - }); - }; - if (typeof root.enmRunOnce === 'function') { - root.enmRunOnce(btn, 'Updating…', doUpdate); - } else { - btn.disabled = true; - doUpdate().finally(function () { btn.disabled = false; }); - } - }; - - /** - * @private — Restart a Class B chain via POST /chains//restart. - * v0.5.187 (Phase 4): confirm-before-disruptive (parity with the overview - * quick actions) + enmRunOnce guards the button against double-submit. A - * restart interrupts in-progress sync work, so the operator confirms first. - */ - SettingsTab.prototype._restartClassB = function (chainId, name, btn, statusEl) { - var self = this; - if (typeof root.confirm === 'function' - && !root.confirm('Restart ' + name + '? In-progress sync work will be interrupted.')) { - return; - } - statusEl.hidden = true; - var doRestart = function () { - return self.api.post('/chains/' + chainId + '/restart', {}).then(function () { - if (self._destroyed) { return; } - statusEl.hidden = false; - statusEl.textContent = 'Restart requested. Watch the chain card for status.'; - }).catch(function (err) { - if (self._destroyed) { return; } - // Silence error text on 401 — boot path owns re-auth. - if (err && err.status === 401) { return; } - statusEl.hidden = false; - statusEl.textContent = 'Restart failed: ' + ((err && err.message) || String(err)); - }); - }; - if (typeof root.enmRunOnce === 'function') { - root.enmRunOnce(btn, 'Restarting…', doRestart); - } else { - btn.disabled = true; - doRestart().finally(function () { btn.disabled = false; }); - } - }; - - /** - * beta.3.93 (Wave M2.5) — Class C (Oracle: esc-oracle, eid-oracle, - * pg-oracle) settings mount. - * - * Oracles don't normally appear in the chain selector — they're - * surfaced inside their parent chain's pane as a sub-status panel - * (plan §3 Smart UI Behavior). This mount exists for completeness - * + the rare case of direct deep-linking (e.g. localStorage - * tampering). M4.2 (beta.3.2) will deliver the real layout. - * - * @private - * @param {string} chainId — esc-oracle | eid-oracle | pg-oracle - */ - SettingsTab.prototype._mountOracleSettings = function (chainId) { - // beta.0.3.2 (Wave M4.2) — real Class C settings layout. - // Replaces the M2.5 stub. Read-only display of the oracle's - // wire (parent chain, script path, node version, port) plus - // a Restart button (the only writable interaction since - // oracles have no rewards/keystore/peers to tune). - var fallbackChainNames = { - 'esc-oracle': 'ESC Oracle', - 'eid-oracle': 'EID Oracle', - 'pg-oracle': 'PG Oracle', - }; - var name = _tFb('chain_name.' + chainId, fallbackChainNames[chainId] || chainId); - var self = this; - this.root.innerHTML = '' - + '
    ' - + '

    ' + escapeHtml(name) + ' settings

    ' - + '

    Class C (Oracle) — ' - + 'stateless Node.js relayer. No keystore, no rewards, ' - + 'no peers. Relays cross-chain transactions from its ' - + 'parent EVM sidechain to mainchain.

    ' - + '
    ' - + '
    ' - + '

    Loading current configuration…

    ' - + '
    '; - var body = this.root.querySelector('.enm-settings-class-body'); - this.api.get('/config', { skipCache: true }).then(function (data) { - if (self._destroyed) { return; } - var cfg = (data && data.config) || {}; - var oracleCfg = (cfg.chains && cfg.chains[chainId]) || null; - if (!oracleCfg) { - body.dataset.state = 'unconfigured'; - // 0.5.12 audit Session 12 — strip M4.4 / plan refs from - // operator-facing copy. Pre-0.5.12 said "lands in M4.4 / - // For now use the parent chain pane to monitor + install" - // — dev-internal milestone refs the operator can't decode. - body.innerHTML = '' - + '
    ' - + '

    ' + escapeHtml(name) + ' is not yet installed.

    ' - + '

    This oracle activates automatically when its parent chain ' - + 'finishes installing. Open the parent chain\'s dashboard to ' - + 'check status or trigger install from the setup wizard.

    ' - + '
    '; - return; - } - self._renderClassCInfo(body, chainId, oracleCfg); - }).catch(function (err) { - if (self._destroyed) { return; } - // 0.5.132 audit Session 132 — silence on 401, see _mountEvmSidechainSettings. - if (err && err.status === 401) { return; } - body.dataset.state = 'error'; - body.innerHTML = '

    Failed to load config: ' - + escapeHtml((err && err.message) || String(err)) + '

    '; - }); - }; - - /** - * @private — paint Class C (oracle) info pane. Read-only display - * of the oracle's wire shape; M4.4 adds the parent-restart hook - * that drives the operator action surface here. - */ - SettingsTab.prototype._renderClassCInfo = function (parent, chainId, oracleCfg) { - parent.dataset.state = 'ready'; - var self = this; - parent.innerHTML = ''; - - // v0.5.187 (Council Node UX Phase 4) — re-emit through the canonical - // makeInfoCard (foot-less .enm-section-card) + the shared .enm-detail-row - // key/value primitive, matching the Class-A reference. Class A untouched. - - // ---- Card 1: Oracle wiring (read-only key/value) ---- - var wiring = makeInfoCard({ - title: 'Oracle wiring', - help: 'Read-only — an oracle is a stateless relayer with nothing to tune.', - }); - var fields = [ - { label: 'Parent chain', value: oracleCfg.parentChainId || '—' }, - { label: 'HTTP port', value: (oracleCfg.ports && oracleCfg.ports.httpRpc) || '—' }, - { label: 'Script path', value: oracleCfg.scriptPath || '—' }, - { label: 'Node.js version', value: oracleCfg.nodejsVersion || '—' }, - { label: 'Network', value: oracleCfg.activeNet || 'mainnet' }, - { label: 'Process enabled', value: oracleCfg.enabled ? 'on' : 'off' }, - ]; - var list = document.createElement('div'); - list.className = 'enm-detail-list'; - fields.forEach(function (f) { - var row = document.createElement('div'); - row.className = 'enm-detail-row'; - var lbl = document.createElement('span'); - lbl.className = 'enm-detail-label'; - lbl.textContent = f.label; - var val = document.createElement('span'); - val.className = 'enm-detail-value'; - val.textContent = String(f.value); - row.appendChild(lbl); - row.appendChild(val); - list.appendChild(row); - }); - wiring.body.appendChild(list); - parent.appendChild(wiring.card); - - // ---- Card 2: Nothing to tune (info) ---- - parent.appendChild(makeInfoCard({ - title: 'Nothing to tune', - help: 'This oracle is a stateless relay between ' - + (oracleCfg.parentChainId || 'its parent chain') + ' and the Main chain. ' - + 'It has no keystore, mining rewards, or peers — so there are no per-oracle ' - + 'settings to change. To move it to a different port or swap the relayer ' - + 'script, re-install via the setup wizard.', - }).card); - - // ---- Card 3: Restart (action) ---- - var restartCard = makeInfoCard({ - title: 'Restart', - help: 'If the oracle stalls or loses its parent connection, a restart re-handshakes with both endpoints.', - }); - var restartBtn = document.createElement('button'); - restartBtn.type = 'button'; - restartBtn.className = 'enm-btn enm-btn-secondary'; - restartBtn.textContent = 'Restart oracle'; - var statusEl = document.createElement('p'); - statusEl.className = 'enm-section-card-foot-status'; - statusEl.setAttribute('role', 'status'); - statusEl.setAttribute('aria-live', 'polite'); - statusEl.hidden = true; - restartCard.body.appendChild(restartBtn); - restartCard.body.appendChild(statusEl); - parent.appendChild(restartCard.card); - - // Restart — confirm-before-disruptive + enmRunOnce (parity w/ Class B). - restartBtn.addEventListener('click', function () { - if (self._destroyed) { return; } - if (typeof root.confirm === 'function' - && !root.confirm('Restart this oracle? In-progress relay work will be interrupted.')) { - return; - } - statusEl.hidden = true; - var doRestart = function () { - return self.api.post('/chains/' + chainId + '/restart', {}).then(function () { - if (self._destroyed) { return; } - statusEl.hidden = false; - statusEl.textContent = 'Restart requested. Watch the chain card for status.'; - }).catch(function (err) { - if (self._destroyed) { return; } - if (err && err.status === 401) { return; } - statusEl.hidden = false; - statusEl.textContent = 'Restart failed: ' + ((err && err.message) || String(err)); - }); - }; - if (typeof root.enmRunOnce === 'function') { - root.enmRunOnce(restartBtn, 'Restarting…', doRestart); - } else { - restartBtn.disabled = true; - doRestart().finally(function () { restartBtn.disabled = false; }); - } - }); - }; - - /** - * Class D (Arbiter cross-chain signer) settings mount. - * - * Layout — Wallet & Mining · Configured chains · Restart. The arbiter - * is the most security-sensitive component: it signs cross-chain - * messages between mainchain and the EVM sidechains, and it reuses - * the Main chain keystore. - * - * @private - */ - SettingsTab.prototype._mountArbiterSettings = function () { - var self = this; - this.root.innerHTML = '' - + '
    ' - + '

    Arbiter settings

    ' - + '

    Cross-chain signer — the most ' - + 'security-sensitive component. It signs cross-chain messages between ' - + 'Main chain and the EVM sidechains, using the Main chain keystore.

    ' - + '
    ' - + '
    ' - + '

    Loading current configuration…

    ' - + '
    '; - var body = this.root.querySelector('.enm-settings-class-body'); - this.api.get('/config', { skipCache: true }).then(function (data) { - if (self._destroyed) { return; } - var cfg = (data && data.config) || {}; - var arb = (cfg.chains && cfg.chains.arbiter) || null; - if (!arb) { - body.dataset.state = 'unconfigured'; - // 0.5.14 audit Session 14 — drop curl-bait copy. Pre-0.5.14 - // told operator to "Install via POST /api/enm/setup/install- - // class-d" which exposed a backend endpoint as if the - // operator were going to fire it manually. - body.innerHTML = '' - + '
    ' - + '

    Arbiter is not yet installed.

    ' - + '

    Install via the setup wizard. The arbiter requires ' - + 'all four chains (Main chain, ESC, EID, PG) to be configured ' - + 'first — the wizard will surface the option once they are.

    ' - + '
    '; - return; - } - self._renderClassDInfo(body, arb, cfg.chains || {}); - }).catch(function (err) { - if (self._destroyed) { return; } - // 0.5.132 audit Session 132 — silence on 401, see _mountEvmSidechainSettings. - if (err && err.status === 401) { return; } - body.dataset.state = 'error'; - body.innerHTML = '

    Failed to load config: ' - + escapeHtml((err && err.message) || String(err)) + '

    '; - }); - }; - - /** - * @private — Class D info panes. Wallet & Mining read-only DL + - * Configured-chains DL (config-presence, not live reach) + Restart. - */ - SettingsTab.prototype._renderClassDInfo = function (parent, arbCfg, allChains) { - parent.dataset.state = 'ready'; - var self = this; - parent.innerHTML = ''; - - // v0.5.187 (Council Node UX Phase 4) — canonical makeInfoCard + - // .enm-detail-row, matching the Class-A reference. Class A untouched. - function kv(label, value, mono) { - var row = document.createElement('div'); - row.className = 'enm-detail-row'; - var l = document.createElement('span'); - l.className = 'enm-detail-label'; - l.textContent = label; - var v = document.createElement('span'); - v.className = mono ? 'enm-detail-value enm-detail-addr' : 'enm-detail-value'; - v.textContent = value; - row.appendChild(l); - row.appendChild(v); - return row; - } - - var addr = (arbCfg.mining && arbCfg.mining.miningAddress) || '—'; - var fee = (arbCfg.mining && arbCfg.mining.sideChainPowFeeEla) || '—'; - - // ---- Card 1: Wallet & mining (read-only) ---- - var wallet = makeInfoCard({ - title: 'Wallet & mining', - help: 'The arbiter signs with the Main chain keystore (chains/mainchain/keystore.dat) ' - + 'and shares the Main chain wallet password (encrypted at rest). To change the ' - + 'password, switch the chain selector to Main chain and open Settings → Identity.', - }); - var wlist = document.createElement('div'); - wlist.className = 'enm-detail-list'; - wlist.appendChild(kv('Mining address (Main chain)', addr, true)); - wlist.appendChild(kv('SideChainPow fee (ELA)', String(fee), false)); - wallet.body.appendChild(wlist); - parent.appendChild(wallet.card); - - // ---- Card 2: Configured chains (config presence, not live reach) ---- - var chainsCard = makeInfoCard({ - title: 'Configured chains', - help: 'The arbiter signs messages between these four chains; all must be configured ' - + 'before it can run. Live reachability is shown on the arbiter’s dashboard card ' - + '(retested every 30s) — this lists configuration only.', - }); - var clist = document.createElement('div'); - clist.className = 'enm-detail-list'; - ['mainchain', 'esc', 'eid', 'pg'].forEach(function (cid) { - var configured = !!allChains[cid]; - var rpcPort = (configured && allChains[cid].ports) ? allChains[cid].ports.rpc : '—'; - clist.appendChild(kv( - cid.toUpperCase(), - configured ? ('Configured (RPC port ' + rpcPort + ')') : 'Not configured', - false, - )); - }); - chainsCard.body.appendChild(clist); - parent.appendChild(chainsCard.card); - - // ---- Card 3: Restart (action) ---- - var restartCard = makeInfoCard({ - title: 'Restart', - help: 'Restart the arbiter if one of the four chains it monitors was just restarted, ' - + 'or if cross-chain reach has degraded.', - }); - var restartBtn = document.createElement('button'); - restartBtn.type = 'button'; - restartBtn.className = 'enm-btn enm-btn-secondary'; - restartBtn.textContent = 'Restart arbiter'; - var statusEl = document.createElement('p'); - statusEl.className = 'enm-section-card-foot-status'; - statusEl.setAttribute('role', 'status'); - statusEl.setAttribute('aria-live', 'polite'); - statusEl.hidden = true; - restartCard.body.appendChild(restartBtn); - restartCard.body.appendChild(statusEl); - parent.appendChild(restartCard.card); - - // Restart — confirm-before-disruptive + enmRunOnce. The arbiter is the - // most security-sensitive component; cross-chain signing pauses during - // the bounce, so the operator confirms first. - restartBtn.addEventListener('click', function () { - if (self._destroyed) { return; } - if (typeof root.confirm === 'function' - && !root.confirm('Restart the arbiter? Cross-chain signing pauses until it is back.')) { - return; - } - statusEl.hidden = true; - var doRestart = function () { - return self.api.post('/chains/arbiter/restart', {}).then(function () { - if (self._destroyed) { return; } - statusEl.hidden = false; - statusEl.textContent = 'Restart requested. Watch the arbiter card for status.'; - }).catch(function (err) { - if (self._destroyed) { return; } - if (err && err.status === 401) { return; } - statusEl.hidden = false; - statusEl.textContent = 'Restart failed: ' + ((err && err.message) || String(err)); - }); - }; - if (typeof root.enmRunOnce === 'function') { - root.enmRunOnce(restartBtn, 'Restarting…', doRestart); - } else { - restartBtn.disabled = true; - doRestart().finally(function () { restartBtn.disabled = false; }); - } - }); - }; - - /** - * Class E (SPV) settings mount. - * - * SPV (Simple Payment Verification) is a wallet/client protocol — - * mobile and light wallets use it to verify transactions without - * holding the full chain. The Main chain node already serves SPV - * clients via Bloom-filter relaying (Elastos.ELA/elanet/server.go); - * there is no separate SPV node mode an operator runs. This pane - * exists because the chain-selector ships an "SPV Module" row; - * its job here is to tell the operator honestly that there's - * nothing to configure. - * - * @private - */ - SettingsTab.prototype._mountSpvSettings = function () { - var title = _tFb('settings_class_stub.spv_title', 'SPV (light client)'); - var lead = _tFb( - 'settings_class_stub.spv_lead', - 'SPV (Simple Payment Verification) is a wallet/client protocol, ' - + 'not a node mode. Lightweight wallets — like the Elastos Essentials ' - + 'mobile wallet — connect to your Main chain node and use SPV to ' - + 'verify transactions without downloading the full chain.', - ); - var note = _tFb( - 'settings_class_stub.spv_note', - 'Your Main chain node already serves SPV clients automatically. ' - + 'There is nothing to configure here, and you can safely ignore ' - + 'this option.', - ); - this.root.innerHTML = ''; - // v0.5.187 (Council Node UX Phase 4) — single canonical card so SPV - // matches the other classes' chrome. SPV genuinely has nothing to - // configure, so this stays an honest "nothing here" pane (no controls). - // Class A render path untouched. - var card = makeInfoCard({ title: title, help: lead }); - var noteEl = document.createElement('p'); - noteEl.className = 'enm-section-card-help'; - noteEl.textContent = note; - card.body.appendChild(noteEl); - this.root.appendChild(card.card); - }; - SettingsTab.prototype.destroy = function () { this._destroyed = true; // BP-E audit fix — tear down the chip-input's internal flash- @@ -1119,10 +189,23 @@ try { this._adv.whiteIp.destroy(); } catch (_) { /* idempotent */ } } // v0.5.176 — stop the Network peers panel's poll + detach it. + // (Legacy single-panel handle from the removed _renderClassBForm path; + // kept defensively until that dead method is deleted in Phase 5.) if (this._peersPanel && typeof this._peersPanel.destroy === 'function') { try { this._peersPanel.destroy(); } catch (_) { /* idempotent */ } this._peersPanel = null; } + // v0.5.237 — tear down the per-chain EVM peers panels mounted in the + // consolidated Sidechain settings accordion (esc/eid/pg). One panel + // per opened accordion; loop so none leaks its /peers poll timer. + if (this._evmShared && Array.isArray(this._evmShared.peersPanels)) { + this._evmShared.peersPanels.forEach(function (p) { + if (p && typeof p.destroy === 'function') { + try { p.destroy(); } catch (_) { /* idempotent */ } + } + }); + this._evmShared.peersPanels = []; + } if (this.root.parentNode) { this.root.parentNode.removeChild(this.root); } }; @@ -1907,6 +990,42 @@ btn: syncBtn, }; + // --- Peers & bootnodes (per chain) ------------------------------ + // v0.5.237 — peers/bootnodes are genuinely per-chain (each EVM keeps + // its own enode set), so they get a per-chain collapsible accordion + // here inside the single Sidechain settings tab. Each
    lazily + // mounts an EnmPeersPanel the first time it's opened, so collapsed + // chains never poll. This replaces the per-chain peers panel that used + // to live in _renderClassBForm — reached only via the removed chain + // selector. + var peersCard = _buildDangerCard({ + kind: 'info', + title: t('settings.evm_shared_peers_title'), + help: t('settings.evm_shared_peers_help'), + }); + body.appendChild(peersCard.el); + this._evmShared.peersMounts = {}; + this._evmShared.peersPanels = []; + this._evmShared.peersWired = {}; + EVM_SHARED_CHAINS.forEach(function (cid) { + var det = document.createElement('details'); + det.className = 'enm-evm-shared-peers-accordion'; + det.dataset.chain = cid; + var sum = document.createElement('summary'); + sum.className = 'enm-evm-shared-peers-summary'; + sum.textContent = _tFb('chain_name.' + cid, cid); + det.appendChild(sum); + var mount = document.createElement('div'); + mount.className = 'enm-evm-shared-peers-mount'; + det.appendChild(mount); + peersCard.body.appendChild(det); + self._evmShared.peersMounts[cid] = mount; + // Lazy-mount the panel the first time this accordion opens. + det.addEventListener('toggle', function () { + if (det.open) { self._mountEvmPeersPanel(cid); } + }); + }); + // --- Per-chain footer note -------------------------------------- var footer = document.createElement('div'); footer.className = 'enm-evm-shared-footer-note'; @@ -1916,6 +1035,29 @@ return card; }; + /** + * v0.5.237 — lazily mount the per-chain EnmPeersPanel for one EVM + * sidechain (esc/eid/pg) inside its Sidechain-settings accordion. + * Idempotent — mounts at most once per chain (gated by peersWired) so + * re-opening the accordion doesn't stack panels or duplicate polls. + * @private + * @param {string} chainId — esc | eid | pg + */ + SettingsTab.prototype._mountEvmPeersPanel = function (chainId) { + if (!this._evmShared || !this._evmShared.peersMounts) { return; } + if (this._evmShared.peersWired[chainId]) { return; } + var mount = this._evmShared.peersMounts[chainId]; + if (!mount || !root.EnmPeersPanel) { return; } + var panel = new root.EnmPeersPanel({ + api: this.api, + chainId: chainId, + notifications: this.notifications, + }); + panel.mount(mount); + this._evmShared.peersPanels.push(panel); + this._evmShared.peersWired[chainId] = true; + }; + /** * Fetch /chains/{esc,eid,pg} in parallel and fill the shared * settings UI based on whether values match or diverge. diff --git a/src/backend/apps/elastos-node-manager/js/strings.js b/src/backend/apps/elastos-node-manager/js/strings.js index 66e359edfd..1805eda1c2 100644 --- a/src/backend/apps/elastos-node-manager/js/strings.js +++ b/src/backend/apps/elastos-node-manager/js/strings.js @@ -589,8 +589,8 @@ // labeled "Node public key" with a "Share with // Essentials" pill. Display-name parity: "Main chain" // replaces lowercase "mainchain" raw id. - sub: 'All 8 services are installed and starting up. On the dashboard, ' - + 'switch the chain selector to "Multi-chain overview" to watch them ' + sub: 'All 8 services are installed and starting up. The Dashboard tab ' + + 'shows the multi-chain overview where you can watch them ' + 'come online. To earn rewards on Main chain, copy the Node public ' + 'key from the Node identity card and paste it into Elastos ' + 'Essentials when registering as a BPoS supernode.', @@ -796,6 +796,13 @@ unconfigured: 'Not configured', }, + // v0.5.237 — static topbar node-mode label (replaces the removed + // chain selector). Set by PaneRouter from GET /config. + node_mode: { + council: 'Council node', + bpos: 'BPoS node', + }, + // beta.3.94 (Wave M2.6) — multi-chain overview pane copy. overview_pane: { title: 'Council overview', @@ -813,6 +820,9 @@ row_aria_open: 'Open {chainName} dashboard', // SR announcer message after row click. announce_switched_to: 'Switched to {chainName}', + // v0.5.237 — label of the control that returns from a drilled-in + // per-chain dashboard to the multi-chain overview (Council only). + back_to_overview: '← Back to overview', // v0.5.186 (Council Node UX P2.1) — control-center row meta line. // {n} = thousands-separated block height; {parent} = parent // EVM chain name an Oracle relays for. @@ -936,17 +946,14 @@ pane_stub: { // Dashboard stub title is "{chainName} dashboard". dashboard_title: '{chainName} dashboard', - // 0.5.29 audit Session 29 — operator-facing copy, drop M3/M4/M6 - // milestone tags. The detailed per-chain dashboard for EVM - // sidechains / Oracles / Arbiter isn't shipped yet; the - // existing Settings tab and chain-selector still work for - // those chains, just no rich Dashboard view. - dashboard_body: 'A detailed dashboard for this chain isn\'t ready yet. To check its current state use the Settings tab, or switch the chain selector to Multi-chain overview to see status for every installed chain in one place.', + // Per-chain dashboard fallback stub (rare). v0.5.237 — copy + // updated for the selector-free navigation: the Dashboard tab is + // the multi-chain overview; clicking a chain row drills in. + dashboard_body: 'A detailed dashboard for this chain isn\'t ready yet. The Dashboard tab shows every installed chain\'s status in the multi-chain overview — click a chain there to drill into it.', // Multi-chain overview stub (shown only when the real // EnmMultiChainOverviewPane component fails to load). - // 0.5.29 audit Session 29 — drop M2.1/M2.3 milestone tags. overview_title: 'Multi-chain overview', - overview_body: 'The multi-chain overview pane couldn\'t load. This is unexpected — try refreshing the page. If it keeps happening, switch the chain selector back to Main chain and continue from there.', + overview_body: 'The multi-chain overview couldn\'t load. This is unexpected — try refreshing the page.', }, // 0.5.136 audit Session 136 — Class B/C/D stub keys dropped. @@ -1468,11 +1475,15 @@ // (validator/follower wording, no "on/off" template). // Removed. evm_shared_sync_title: 'Sync mode', - evm_shared_sync_help: 'How geth catches up to the chain tip. ‘fast’ downloads block headers + state snapshots (default, fastest). ‘full’ re-executes every transaction. ‘archive’ keeps every historical state (massive disk).', + evm_shared_sync_help: 'How geth catches up to the chain tip. ‘full’ re-executes every transaction from genesis — validator-grade and the default for Council nodes. ‘archive’ additionally retains every historical state (much larger disk). (Fast sync was removed in v0.5.235.)', evm_shared_sync_shared: '✓ All three chains on ‘{mode}’.', evm_shared_sync_diverged: '⚠ Diverged: {summary}', evm_shared_sync_apply_btn: 'Apply to all three', - evm_shared_perchain_footer: 'Per-chain settings (bootnodes, ports, binary version, EVM account address) live in each chain’s own card on the dashboard.', + // v0.5.237 — per-chain peers/bootnodes accordion in the + // consolidated Sidechain settings tab. + evm_shared_peers_title: 'Peers & bootnodes', + evm_shared_peers_help: 'Bootnodes are per chain — open a chain below to view and edit its peer list. Use this if a sidechain is stuck at 0 peers; new bootnodes are dialled immediately when the chain is running.', + evm_shared_perchain_footer: 'Ports, binary version, and the EVM account address are managed automatically. Mining is derived on-chain (no manual toggle). A chain’s live status and Start / Stop / Restart / Resync controls are on its dashboard card.', // v0.5.228 — Staged chain resume. Gated behind a Danger Zone // enable/disable toggle (operator directive 2026-05-26: the From cf01cdbbef1dcf473a91ef641247bedca6de3914 Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Fri, 29 May 2026 01:08:01 +0300 Subject: [PATCH 13/24] =?UTF-8?q?enm=20v0.5.238=20=E2=80=94=20overview=20o?= =?UTF-8?q?verhaul:=20fix=20action=20buttons=20+=20add=20"This=20node"=20D?= =?UTF-8?q?AO=20Council/BPoS=20card?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The deployed v0.5.237 overview had colliding/blank action buttons and no node identity surfaced. Fixes: - Row layout: .enm-overview-row converted from a fixed 6-column grid to flex. The grid's per-variant column counts didn't match the rendered cells (the EVM variant declared 5 columns for 6 cells), so the start/stop/restart buttons were crammed into a 14px track and collided with the sparkline (the "blank dark squares"). Flex lets the main column grow while the right cluster (sparkline · uptime · actions · arrow) sizes to content and never collides, at any width. Action buttons lifted to an elevated surface + secondary glyph so they read as real controls. - New "This node" identity card atop the overview: DAO Council membership (state + nickname) + BPoS producer status (state + name) side by side, plus mining key + address. Truthful for ENM's own node key — shows "Not a Council member" / "Not registered" with a hint that a Council node still registers BPoS separately (in Essentials) to earn staking rewards. Mirrors node.sh's CRC/BPoS status fields. Sourced from the existing /system/identity (crMember + producer) — no backend change. - Relabel CR Council -> "DAO Council" in the overview. Co-Authored-By: Claude Opus 4.7 --- enm-server/package-lock.json | 4 +- enm-server/package.json | 2 +- .../apps/elastos-node-manager/css/styles.css | 98 +++++++++++++++- .../apps/elastos-node-manager/index.html | 6 +- .../js/components/multi-chain-overview.js | 109 +++++++++++++++++- .../apps/elastos-node-manager/js/strings.js | 13 +++ 6 files changed, 220 insertions(+), 12 deletions(-) diff --git a/enm-server/package-lock.json b/enm-server/package-lock.json index a8a7dcf7f7..180355ac7b 100644 --- a/enm-server/package-lock.json +++ b/enm-server/package-lock.json @@ -1,12 +1,12 @@ { "name": "@elacity/enm-server", - "version": "0.5.237", + "version": "0.5.238", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@elacity/enm-server", - "version": "0.5.237", + "version": "0.5.238", "license": "AGPL-3.0", "dependencies": { "better-sqlite3": "^11.9.0", diff --git a/enm-server/package.json b/enm-server/package.json index 0217c30384..053c5cfee0 100644 --- a/enm-server/package.json +++ b/enm-server/package.json @@ -1,6 +1,6 @@ { "name": "@elacity/enm-server", - "version": "0.5.237", + "version": "0.5.238", "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode AND CR Council operators.", "main": "src/server.js", "author": "Elacity", diff --git a/src/backend/apps/elastos-node-manager/css/styles.css b/src/backend/apps/elastos-node-manager/css/styles.css index e14155802e..bc6a12fff1 100644 --- a/src/backend/apps/elastos-node-manager/css/styles.css +++ b/src/backend/apps/elastos-node-manager/css/styles.css @@ -7291,6 +7291,76 @@ body[data-app-size="compact"] .enm-app .enm-filter-chip { font-size: 13px; color: var(--text-tertiary); } +/* v0.5.238 — "This node" identity card: DAO Council + BPoS status. */ +.enm-app .enm-overview-identity { + margin: 0 0 var(--sp-4, 16px) 0; + padding: var(--sp-3, 12px) var(--sp-4, 16px); + background: var(--bg-elevated); + border: 1px solid var(--border-color, var(--border-subtle)); + border-radius: 10px; +} +.enm-app .enm-identity-head { + font-size: 11px; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--text-tertiary); + margin-bottom: var(--sp-2, 8px); +} +.enm-app .enm-identity-pills { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--sp-2, 8px) var(--sp-5, 24px); +} +.enm-app .enm-identity-pill { + display: flex; + align-items: baseline; + gap: var(--sp-2, 8px); + min-width: 0; +} +.enm-app .enm-identity-pill-label { + flex: 0 0 auto; + font-size: 12px; + color: var(--text-tertiary); +} +.enm-app .enm-identity-pill-val { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; + font-size: 14px; + font-weight: 600; + color: var(--text-primary); +} +.enm-app .enm-identity-dot { + flex: 0 0 auto; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--text-tertiary); +} +.enm-app .enm-identity-dot.state-synced { background: var(--success); } +.enm-app .enm-identity-dot.state-syncing { background: var(--warning, #c08a00); } +.enm-app .enm-identity-dot.state-unconfigured { background: var(--text-tertiary); opacity: 0.5; } +.enm-app .enm-identity-hint { + margin-top: var(--sp-2, 8px); + font-size: 12px; + line-height: 1.45; + color: var(--text-tertiary); +} +.enm-app .enm-identity-keys { + margin-top: var(--sp-2, 8px); + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px var(--sp-3, 12px); + font-size: 12px; + color: var(--text-tertiary); +} +.enm-app .enm-identity-kv-k { margin-right: 2px; color: var(--text-tertiary); } +.enm-app .enm-identity-keys .enm-mono { color: var(--text-secondary); } +.enm-app .enm-identity-sep { opacity: 0.5; } .enm-app .enm-overview-body { display: flex; flex-direction: column; @@ -7324,8 +7394,14 @@ body[data-app-size="compact"] .enm-app .enm-filter-chip { truth (height + sync badge for A/B; "relays for " for C) under its name; the actions column carries state-gated start/stop/restart. */ .enm-app .enm-overview-row { - display: grid; - grid-template-columns: 16px minmax(160px, 1fr) 90px 56px auto 16px; + /* v0.5.238 — flex (was a fixed 6-column grid). The grid's per-variant + column counts didn't match the rendered cells — the EVM variant + declared 5 columns for 6 cells, so the action buttons were crammed into + a 14px track and collided with the sparkline (the "dark squares" bug). + Flex lets the main column grow while the right-side cluster (sparkline · + uptime · actions · arrow) sizes to content and never collides, at any + width. The variant grid-template-columns rules below are now inert. */ + display: flex; align-items: center; gap: var(--sp-3, 12px); padding: var(--sp-2, 8px) var(--sp-3, 12px); @@ -7341,6 +7417,17 @@ body[data-app-size="compact"] .enm-app .enm-filter-chip { flex-direction: column; gap: 2px; min-width: 0; + flex: 1 1 auto; +} +/* v0.5.238 — flex sizing for the row children: main grows/shrinks (its + min-width:0 lets long text ellipsize), while the right-side cluster holds + its natural size so the action buttons never get squashed. */ +.enm-app .enm-overview-dot, +.enm-app .enm-overview-spark, +.enm-app .enm-overview-uptime, +.enm-app .enm-overview-actions, +.enm-app .enm-overview-open { + flex: 0 0 auto; } .enm-app .enm-overview-line1 { display: flex; @@ -7805,8 +7892,11 @@ body[data-app-size="compact"] .enm-app .enm-usage-card-value, font-family: inherit; border: 1px solid var(--border-color, var(--border-subtle)); border-radius: 6px; - background: var(--bg-page); - color: var(--text-tertiary); + /* v0.5.238 — was bg-page + text-tertiary, which made the buttons read as + blank dark squares against the dark card. Lift to an elevated surface + + secondary glyph so they clearly look like tappable controls. */ + background: var(--bg-elevated); + color: var(--text-secondary); cursor: pointer; transition: color 120ms, border-color 120ms, background-color 120ms, opacity 120ms; } diff --git a/src/backend/apps/elastos-node-manager/index.html b/src/backend/apps/elastos-node-manager/index.html index d89240fbcf..49a48ada28 100644 --- a/src/backend/apps/elastos-node-manager/index.html +++ b/src/backend/apps/elastos-node-manager/index.html @@ -10,7 +10,7 @@ Elastos Node Manager - + + @@ -255,7 +255,7 @@

    Elastos Node Manager

    - + diff --git a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js index 0c9eee89e4..dd08f5423a 100644 --- a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js +++ b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js @@ -436,6 +436,10 @@ escapeHtml(this._summaryLineV2(snap)), '

    ', '', + // v0.5.238 — "This node" identity card: DAO Council membership + + // BPoS producer status (truthful for ENM's own node key). Empty + // string until /system/identity resolves into _lastIdentity. + this._identityCardHtml(), // v0.5.225 audit Phase 21 — provider-cap banner. Only renders // when /system/host-limits reports a tight cap AND operator // hasn't dismissed it. Auto-detected; opt-in per operator @@ -1396,6 +1400,107 @@ * single-glance health line. * @private */ + /** + * v0.5.238 — "This node" identity card. Surfaces ENM's own node status the + * way node.sh's `status` does, but labeled "DAO Council" (the Cyber + * Republic / CR Council is the Elastos DAO): DAO Council membership + * (name + state) and BPoS producer status (name + state), side by side, + * plus the mining key + address. Truthful — reflects ENM's node key, so a + * node that isn't bound to a Council seat reads "Not a Council member" and + * an unregistered producer reads "Not registered" (with a hint that a + * Council node still registers BPoS separately to earn staking rewards). + * Sourced from /system/identity (this._lastIdentity); returns '' until that + * resolves so the card never flashes an empty state. + * @private + */ + EnmMultiChainOverviewPane.prototype._identityCardHtml = function () { + var id = this._lastIdentity; + if (!id) { return ''; } + var ks = id.keystore || {}; + var cr = id.crMember || null; + var prod = id.producer || null; + var setupRole = id.setupRole || 'unknown'; + + function trunc(s, head, tail) { + s = String(s || ''); + if (s.length <= head + tail + 1) { return s; } + return s.slice(0, head) + '…' + s.slice(-tail); + } + function pill(label, dotState, valueText) { + return '
    ' + + '' + escapeHtml(label) + '' + + '' + + '' + + escapeHtml(valueText) + + '
    '; + } + + // DAO Council (CRC) row. + var councilDot, councilText; + if (cr && cr.isCrMember) { + councilDot = 'synced'; + councilText = (cr.state || 'Member') + (cr.nickname ? ' · ' + cr.nickname : ''); + } else { + councilDot = 'unconfigured'; + councilText = (setupRole === 'council') + ? tFb('overview_pane.identity.council_unbound', 'Not bound to a seat') + : tFb('overview_pane.identity.not_council', 'Not a Council member'); + } + + // BPoS producer row. + var bposDot, bposText; + if (prod && prod.state) { + bposDot = (prod.state === 'Active') ? 'synced' : 'syncing'; + bposText = prod.state + (prod.nickname ? ' · ' + prod.nickname : ''); + } else { + bposDot = 'unconfigured'; + bposText = tFb('overview_pane.identity.bpos_unregistered', 'Not registered'); + } + + // Hint: a Council node still registers BPoS separately (node.sh shows + // CRC + BPoS as independent roles). Only when BPoS is absent on a + // Council install / member. + var hint = ''; + if ((!prod || !prod.state) && (setupRole === 'council' || (cr && cr.isCrMember))) { + hint = '
    ' + + escapeHtml(tFb('overview_pane.identity.bpos_hint', + 'A Council node still registers as a BPoS producer separately (in Essentials) to earn staking rewards.')) + + '
    '; + } + + // Mining key + address. + var keyLine = ''; + var keyParts = []; + if (ks.publicKey) { + keyParts.push('' + + escapeHtml(tFb('overview_pane.identity.key_label', 'Key')) + ' ' + + '' + escapeHtml(trunc(ks.publicKey, 6, 4)) + ''); + } + if (ks.address) { + keyParts.push('' + + escapeHtml(tFb('overview_pane.identity.addr_label', 'Address')) + ' ' + + '' + escapeHtml(trunc(ks.address, 6, 4)) + ''); + } + if (keyParts.length) { + keyLine = '
    ' + + keyParts.join('') + + '
    '; + } + + return '
    ' + + '
    ' + + escapeHtml(tFb('overview_pane.identity.title', 'This node')) + + '
    ' + + '
    ' + + pill(tFb('overview_pane.identity.council_label', 'DAO Council'), councilDot, councilText) + + pill(tFb('overview_pane.identity.bpos_label', 'BPoS'), bposDot, bposText) + + '
    ' + + hint + + keyLine + + '
    '; + }; + EnmMultiChainOverviewPane.prototype._summaryLineV2 = function (snap) { var totals = (snap && snap.totals) || { total: 0 }; if (!totals.total) { @@ -1428,10 +1533,10 @@ var setupRole = id.setupRole || 'unknown'; var rolePrefix = ''; if (cr && cr.isCrMember) { - rolePrefix = 'CR Council · ' + (cr.state || 'Elected'); + rolePrefix = 'DAO Council · ' + (cr.state || 'Elected'); if (cr.nickname) { rolePrefix += ' (' + cr.nickname + ')'; } } else if (setupRole === 'council') { - rolePrefix = 'CR Council install · not currently bound'; + rolePrefix = 'DAO Council install · not currently bound'; } else if (id.producer && id.producer.state) { rolePrefix = 'BPoS · ' + id.producer.state; } diff --git a/src/backend/apps/elastos-node-manager/js/strings.js b/src/backend/apps/elastos-node-manager/js/strings.js index 1805eda1c2..1b83d93370 100644 --- a/src/backend/apps/elastos-node-manager/js/strings.js +++ b/src/backend/apps/elastos-node-manager/js/strings.js @@ -823,6 +823,19 @@ // v0.5.237 — label of the control that returns from a drilled-in // per-chain dashboard to the multi-chain overview (Council only). back_to_overview: '← Back to overview', + // v0.5.238 — "This node" identity card (DAO Council + BPoS status). + identity: { + title: 'This node', + aria: 'This node identity', + council_label: 'DAO Council', + bpos_label: 'BPoS', + not_council: 'Not a Council member', + council_unbound: 'Not bound to a seat', + bpos_unregistered: 'Not registered', + bpos_hint: 'A Council node still registers as a BPoS producer separately (in Essentials) to earn staking rewards.', + key_label: 'Key', + addr_label: 'Address', + }, // v0.5.186 (Council Node UX P2.1) — control-center row meta line. // {n} = thousands-separated block height; {parent} = parent // EVM chain name an Oracle relays for. From 4efc47ffe8af27461ff560ab3cf97ec74e3bd9f9 Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Fri, 29 May 2026 02:39:37 +0300 Subject: [PATCH 14/24] =?UTF-8?q?enm=20v0.5.239=20=E2=80=94=20overview=20r?= =?UTF-8?q?edesign:=20card=20layout,=20health=20headline,=20bulk=20actions?= =?UTF-8?q?,=20labelled=20actions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Full overview redesign (designed in a local browser-preview mock, then ported + verified by rendering the real component with sample data at desktop + 375px): - Health headline: one-line node verdict ("All services healthy" / "N services need attention · · X of Y synced") + bulk Start all / Restart all. - Vertical chain cards replace the flat horizontal rows: header (dot + name + state chip + optional "Update available" badge) -> block/height -> metrics (peers + RAM) -> folded collapsible oracle line -> labelled action footer (Start / Stop / Restart; Update only when the backend reports one). The mainchain hero gets a "Manage" link. - Sparklines removed (the green-triangle noise); per-chain CPU + FD + disk removed from the overview (CPU is redundant with the top stat strip; the rest lives on the per-chain detail page). - "Loud when not healthy": stopped/stalled chains get an amber accent and are named in the headline; healthy chains stay calm. - Fully responsive to iPhone 7 (375px): cards stack, action buttons wrap to share rows, stat strip 2-up, health headline stacks. Co-Authored-By: Claude Opus 4.7 --- enm-server/package-lock.json | 4 +- enm-server/package.json | 2 +- .../apps/elastos-node-manager/css/styles.css | 116 ++++++++ .../apps/elastos-node-manager/index.html | 4 +- .../js/components/multi-chain-overview.js | 257 +++++++++++++----- 5 files changed, 310 insertions(+), 73 deletions(-) diff --git a/enm-server/package-lock.json b/enm-server/package-lock.json index 180355ac7b..655838cb6d 100644 --- a/enm-server/package-lock.json +++ b/enm-server/package-lock.json @@ -1,12 +1,12 @@ { "name": "@elacity/enm-server", - "version": "0.5.238", + "version": "0.5.239", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@elacity/enm-server", - "version": "0.5.238", + "version": "0.5.239", "license": "AGPL-3.0", "dependencies": { "better-sqlite3": "^11.9.0", diff --git a/enm-server/package.json b/enm-server/package.json index 053c5cfee0..e915e14407 100644 --- a/enm-server/package.json +++ b/enm-server/package.json @@ -1,6 +1,6 @@ { "name": "@elacity/enm-server", - "version": "0.5.238", + "version": "0.5.239", "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode AND CR Council operators.", "main": "src/server.js", "author": "Elacity", diff --git a/src/backend/apps/elastos-node-manager/css/styles.css b/src/backend/apps/elastos-node-manager/css/styles.css index bc6a12fff1..ad5aeb63d4 100644 --- a/src/backend/apps/elastos-node-manager/css/styles.css +++ b/src/backend/apps/elastos-node-manager/css/styles.css @@ -8348,6 +8348,122 @@ body[data-app-size="narrow"] .enm-app .enm-evm-shared-mining-grid { font-weight: 600; } +/* ==================================================================== + * v0.5.239 — overview redesign (.enm-ovx-*). Vertical chain cards, + * health headline + bulk actions, labelled action footers, collapsed + * oracle line. Supersedes the old flat horizontal-row look + sparklines. + * ==================================================================== */ +/* section heading → quiet uppercase label */ +.enm-app .enm-overview-section-heading { + font-size: 12px; font-weight: 600; letter-spacing: .05em; text-transform: uppercase; + color: var(--text-tertiary); margin: 0 2px 12px; +} +/* health headline + bulk actions */ +.enm-app .enm-ovx-health { + display: flex; align-items: center; justify-content: space-between; gap: 14px; flex-wrap: wrap; + background: var(--bg-surface); border: 1px solid var(--border); border-left: 3px solid var(--success); + border-radius: 12px; padding: 13px 18px; margin-bottom: 18px; +} +.enm-app .enm-ovx-health.warn { border-left-color: var(--warning); } +.enm-app .enm-ovx-health-l { display: flex; align-items: center; gap: 11px; min-width: 0; flex-wrap: wrap; } +.enm-app .enm-ovx-dot-lg { width: 11px; height: 11px; border-radius: 50%; flex: 0 0 auto; background: var(--text-tertiary); } +.enm-app .enm-ovx-dot-lg.ok { background: var(--success); box-shadow: 0 0 0 4px var(--success-bg); } +.enm-app .enm-ovx-dot-lg.warn { background: var(--warning); box-shadow: 0 0 0 4px var(--warning-bg); } +.enm-app .enm-ovx-health-verdict { font-size: 15px; font-weight: 600; color: var(--text-primary); } +.enm-app .enm-ovx-health-detail { font-size: 13px; color: var(--text-tertiary); } +.enm-app .enm-ovx-health-r { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } +/* labelled action buttons */ +.enm-app .enm-ovx-act { + display: inline-flex; align-items: center; justify-content: center; gap: 6px; height: 32px; padding: 0 13px; + border-radius: 8px; border: 1px solid var(--border); background: var(--bg-elevated); color: var(--text-secondary); + font-size: 12px; font-weight: 600; font-family: inherit; cursor: pointer; line-height: 1; white-space: nowrap; + transition: color .12s, border-color .12s, background-color .12s, opacity .12s; +} +.enm-app .enm-ovx-act .enm-ovx-ico { font-size: 12px; line-height: 1; } +.enm-app .enm-ovx-act:hover { border-color: var(--border-strong); color: var(--text-primary); } +.enm-app .enm-ovx-act.is-start { color: var(--success); border-color: var(--success-soft); } +.enm-app .enm-ovx-act.is-start:hover { background: var(--success-bg); } +.enm-app .enm-ovx-act.is-stop:hover { color: var(--error); border-color: var(--error); background: var(--error-bg); } +.enm-app .enm-ovx-act.is-restart:hover { color: var(--accent); border-color: var(--accent); } +.enm-app .enm-ovx-act.is-update { color: var(--accent); border-color: var(--accent-soft); } +.enm-app .enm-ovx-act.is-update:hover { background: var(--accent-soft); } +.enm-app .enm-ovx-act.is-busy, .enm-app .enm-ovx-act[disabled] { opacity: .5; cursor: default; } +/* card action footer */ +.enm-app .enm-ovx-foot { + display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 14px; padding-top: 13px; + border-top: 1px solid var(--border-subtle); +} +.enm-app .enm-ovx-spacer { flex: 1 1 auto; } +.enm-app .enm-ovx-manage { + display: inline-flex; align-items: center; gap: 4px; font-size: 12px; color: var(--text-tertiary); + background: transparent; border: none; font-family: inherit; cursor: pointer; white-space: nowrap; +} +.enm-app .enm-ovx-manage:hover { color: var(--accent); } +/* vertical chain card (overrides the v0.5.238 flat-row flex) */ +.enm-app .enm-overview-row.enm-ovx-card { + display: flex; flex-direction: column; align-items: stretch; gap: 0; + background: var(--bg-surface); border: 1px solid var(--border); border-radius: 14px; padding: 16px 18px; + cursor: pointer; +} +.enm-app .enm-overview-row.enm-ovx-card:hover { border-color: var(--border-strong); } +.enm-app .enm-overview-row.enm-ovx-card.enm-ovx-attention { + border-color: rgba(251,191,36,.45); box-shadow: inset 3px 0 0 var(--warning); +} +.enm-app .enm-ovx-top { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.enm-app .enm-ovx-meta { margin-top: 10px; font-size: 14px; color: var(--text-secondary); font-variant-numeric: tabular-nums; } +.enm-app .enm-ovx-metrics { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; } +.enm-app .enm-ovx-metrics .enm-overview-metric { + font-size: 11px; color: var(--text-secondary); background: var(--bg-overlay); border-radius: 6px; + padding: 3px 8px; font-variant-numeric: tabular-nums; +} +.enm-app .enm-ovx-metrics .enm-overview-metric.is-warn { color: var(--warning); } +.enm-app .enm-ovx-update-badge { + display: inline-flex; align-items: center; gap: 5px; font-size: 11px; font-weight: 600; + color: var(--accent); background: var(--accent-soft); border-radius: 999px; padding: 2px 9px; white-space: nowrap; +} +/* mainchain hero */ +.enm-app .enm-overview-row.enm-ovx-card.enm-ovx-hero { + background: linear-gradient(120deg, var(--accent-soft), var(--bg-surface) 62%); padding: 20px 22px; +} +.enm-app .enm-ovx-hero .enm-overview-name { font-size: 19px; font-weight: 650; } +/* collapsed oracle line folded into its EVM card */ +.enm-app .enm-ovx-oracle { + display: flex; align-items: center; gap: 8px; margin-top: 14px; padding-top: 12px; + border-top: 1px solid var(--border-subtle); flex-wrap: wrap; cursor: pointer; +} +.enm-app .enm-ovx-oracle-name { font-size: 12px; color: var(--text-secondary); font-weight: 500; } +.enm-app .enm-ovx-oracle-rel { font-size: 11px; color: var(--text-tertiary); } +.enm-app .enm-ovx-oracle.collapsed .enm-ovx-oracle-rel { display: none; } +.enm-app .enm-ovx-caret { margin-left: auto; color: var(--text-tertiary); font-size: 12px; transition: transform .12s; } +.enm-app .enm-ovx-oracle:not(.collapsed) .enm-ovx-caret { transform: rotate(90deg); } +/* EVM card is the visible card → the inner li goes "naked" (no card-in-card) */ +.enm-app .enm-overview-evm-card { + background: var(--bg-surface); border: 1px solid var(--border); border-radius: 14px; padding: 16px 18px; +} +.enm-app .enm-overview-evm-card .enm-overview-rows { list-style: none; margin: 0; padding: 0; gap: 0; } +.enm-app .enm-overview-evm-card .enm-overview-row.enm-ovx-card { + background: transparent; border: none; border-radius: 0; padding: 0; +} +.enm-app .enm-overview-evm-card .enm-overview-row.enm-ovx-card:hover { background: transparent; } +/* phone: footer + bulk buttons grow to share rows */ +@media (max-width: 430px) { + .enm-app .enm-ovx-health { flex-direction: column; align-items: stretch; } + .enm-app .enm-ovx-health-r { width: 100%; } + .enm-app .enm-ovx-health-r .enm-ovx-act, + .enm-app .enm-ovx-foot .enm-ovx-act { flex: 1 1 calc(50% - 4px); } + .enm-app .enm-ovx-manage { width: 100%; justify-content: flex-start; margin-top: 2px; } + .enm-app .enm-ovx-spacer { display: none; } + .enm-app .enm-ovx-hero .enm-overview-name { font-size: 17px; } +} +/* v0.5.239 — keep the stat strip a tidy 2-up on phone/narrow (the mock look) + rather than the old 4-up-tight / 1-up-stacked. */ +.enm-app[data-app-size="narrow"] .enm-overview-usage, +body[data-app-size="narrow"] .enm-app .enm-overview-usage, +.enm-app[data-app-size="compact"] .enm-overview-usage, +body[data-app-size="compact"] .enm-app .enm-overview-usage { + grid-template-columns: repeat(2, 1fr); +} + /* --- Compact viewport overrides ------------------------------------ */ .enm-app[data-app-size="compact"] .enm-overview-evm-grid, body[data-app-size="compact"] .enm-app .enm-overview-evm-grid, diff --git a/src/backend/apps/elastos-node-manager/index.html b/src/backend/apps/elastos-node-manager/index.html index 49a48ada28..a728e90e51 100644 --- a/src/backend/apps/elastos-node-manager/index.html +++ b/src/backend/apps/elastos-node-manager/index.html @@ -10,7 +10,7 @@ Elastos Node Manager - + + diff --git a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js index dd08f5423a..2f54124a1a 100644 --- a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js +++ b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js @@ -432,10 +432,10 @@ var html = [ '
    ', '

    ' + escapeHtml(tFb('overview_pane.title', 'Council overview')) + '

    ', - '

    ', - escapeHtml(this._summaryLineV2(snap)), - '

    ', '
    ', + // v0.5.239 — health headline (single verdict) + bulk actions; + // replaces the old per-chain summary line. + this._healthHeadlineHtml(snap), // v0.5.238 — "This node" identity card: DAO Council membership + // BPoS producer status (truthful for ENM's own node key). Empty // string until /system/identity resolves into _lastIdentity. @@ -512,12 +512,13 @@ break; } } + // v0.5.239 — fold the oracle line INTO the EVM card (between + // the metrics and the action footer) as a collapsible + // one-liner, instead of a separate row below it. + var oracleHtml = oracle ? self._rowHtml(oracle, { variant: 'oracle-nested' }) : ''; html.push('
    '); html.push('
      '); - html.push(self._rowHtml(evm, { variant: 'evm' })); - if (oracle) { - html.push(self._rowHtml(oracle, { variant: 'oracle-nested' })); - } + html.push(self._rowHtml(evm, { variant: 'evm', oracleHtml: oracleHtml })); html.push('
    '); html.push('
    '); }); @@ -602,16 +603,39 @@ var rowEls = this._root.querySelectorAll('.enm-overview-row'); Array.prototype.forEach.call(rowEls, function (row) { row.addEventListener('click', function (ev) { - var actionBtn = ev.target && ev.target.closest - ? ev.target.closest('.enm-overview-action') : null; + var t = ev.target; + var actionBtn = t && t.closest ? t.closest('.enm-overview-action') : null; if (actionBtn) { ev.stopPropagation(); self._onAction(actionBtn.dataset.action, actionBtn.dataset.chainId, actionBtn); return; } + // v0.5.239 — "Manage" (hero) routes to the chain detail. + var manageBtn = t && t.closest ? t.closest('.enm-ovx-manage') : null; + if (manageBtn) { + ev.stopPropagation(); + self._routeToChain(manageBtn.dataset.chainId || row.dataset.chainId); + return; + } + // v0.5.239 — clicking the folded oracle line toggles its + // detail (expand "relays for…") instead of routing. + var oracleEl = t && t.closest ? t.closest('.enm-ovx-oracle') : null; + if (oracleEl) { + ev.stopPropagation(); + oracleEl.classList.toggle('collapsed'); + return; + } self._routeToChain(row.dataset.chainId); }); }); + // v0.5.239 — bulk Start all / Restart all in the health headline. + var bulkBtns = this._root.querySelectorAll('[data-bulk]'); + Array.prototype.forEach.call(bulkBtns, function (b) { + b.addEventListener('click', function (ev) { + ev.stopPropagation(); + self._onBulk(b.dataset.bulk, b); + }); + }); // v0.5.225 audit Phase 21 — constrained-host banner dismiss. // Dismissal persists for the session (this._constrainedDismissed // flag, not localStorage) so a page reload re-shows the banner @@ -653,7 +677,9 @@ // Sparklines — only re-mount the diff. Tear down any chain that // disappeared from the snapshot or stopped being alive; mount // any newly-alive chain. - this._reconcileSparklines(sorted); + // v0.5.239 — sparklines removed from the overview (the green-triangle + // height plot was visual noise; per-chain trend lives on the detail + // page). _reconcileSparklines is no longer called here. }; /** @private — v0.5.186 (Council Node UX P2.1) — control-center row: name + @@ -688,28 +714,51 @@ : ''; var stateChipAttrs = ' class="enm-overview-state ' + stateClass + '"'; if (stateHint) { stateChipAttrs += ' title="' + escapeAttr(stateHint) + '"'; } - var rowClasses = 'enm-overview-row'; - if (variant) { rowClasses += ' enm-overview-row--' + variant; } - // Nested oracles don't get the spark/uptime/actions on the right — - // they're services, not chains-with-height. Same for arbiter; its - // SPV state is shown in metrics instead. - var isCompact = variant === 'oracle-nested' || variant === 'arbiter'; + // v0.5.239 — card redesign. Sparkline + uptime + open-arrow removed + // (the whole card routes on click; a "Manage" link sits in the hero + // footer). Layout is now a vertical card: header (dot+name+state chip + // +optional update badge) → meta (block/height) → metrics (peers+RAM) + // → optional folded oracle line → labelled action footer. + void uptimeHtml; void ariaLabel; + + // Oracle: a compact, collapsible one-liner folded into its parent EVM + // card. NOT an .enm-overview-row (so the card click handler doesn't + // treat it as a routable chain — clicking it toggles its detail). + if (variant === 'oracle-nested') { + var rel = c.parentChainId + ? escapeHtml(tFb('overview_pane.relays_for', 'Relays for {parent}', { parent: chainNameFor(c.parentChainId, null) })) + : ''; + return ''; + } + + var rowClasses = 'enm-overview-row enm-ovx-card'; + if (variant) { rowClasses += ' enm-overview-row--' + variant + ' enm-ovx-' + variant; } + if (v2State === 'stopped' || v2State === 'stalled' || v2State === 'disabled') { + rowClasses += ' enm-ovx-attention'; + } + var updateBadge = c.updateAvailable + ? '↑ ' + escapeHtml(tFb('overview_pane.update_available', 'Update available')) + '' + : ''; + var metaH = this._metaHtmlV2(c); + var metricsH = this._metricsHtml(c); return '
  • ' - + '' - + '
    ' - + '
    ' - + '' + escapeHtml(displayName) + '' - + '' + escapeHtml(stateLabel) + '' - + '
    ' - + '
    ' + this._metaHtmlV2(c) + '
    ' - + '
    ' + this._metricsHtml(c) + '
    ' + + '
    ' + + '' + + '' + escapeHtml(displayName) + '' + + '' + escapeHtml(stateLabel) + '' + + updateBadge + '
    ' - + (isCompact ? '' : '') - + (isCompact ? '' : uptimeHtml) - + this._actionsHtml(c) - + '' + + (metaH ? '
    ' + metaH + '
    ' : '') + + (metricsH ? '
    ' + metricsH + '
    ' : '') + + ((opts && opts.oracleHtml) ? opts.oracleHtml : '') + + this._actionsHtml(c, variant) + '
  • '; }; @@ -981,15 +1030,9 @@ + ''); } } - // CPU % - if (typeof pm.cpuPct === 'number' && isFinite(pm.cpuPct)) { - // High CPU (>80% of one core) gets a warning class so the operator - // can spot churn (the mainchain-leveldb-compaction case fired here). - var cpuClass = (pm.cpuPct >= 80) ? 'enm-overview-metric is-busy' : 'enm-overview-metric'; - bits.push('' - + escapeHtml(tFb('overview_pane.metric_cpu', 'CPU {pct}%', { pct: pm.cpuPct })) - + ''); - } + // v0.5.239 — per-chain CPU% removed (redundant with the top stat + // strip's global CPU load; operator: "doesn't need to show CPU for all + // pages"). The overview's per-chain metrics are now just peers + RAM. // RAM (MB if <1024, GB otherwise) if (typeof pm.rssMb === 'number' && isFinite(pm.rssMb)) { if (pm.rssMb >= 1024) { @@ -1004,29 +1047,8 @@ + ''); } } - // FD count - if (typeof pm.fdCount === 'number' && isFinite(pm.fdCount)) { - bits.push('' - + escapeHtml(tFb('overview_pane.metric_fd', 'FD {n}', { n: pm.fdCount })) - + ''); - } - // Per-chain disk usage from /system/usage.perChainMb cache - if (this._lastUsage && this._lastUsage.disk && this._lastUsage.disk.perChainMb) { - var diskMb = this._lastUsage.disk.perChainMb[c.chainId]; - if (typeof diskMb === 'number' && isFinite(diskMb)) { - if (diskMb >= 1024) { - bits.push('' - + escapeHtml(tFb('overview_pane.metric_disk_gb', 'disk {gb} GB', - { gb: (diskMb / 1024).toFixed(1) })) - + ''); - } else { - bits.push('' - + escapeHtml(tFb('overview_pane.metric_disk', 'disk {mb} MB', - { mb: Math.round(diskMb) })) - + ''); - } - } - } + // v0.5.239 — FD count + per-chain disk removed from the overview + // (internal noise; still available on the per-chain detail page). return bits.join(' '); }; @@ -1075,15 +1097,14 @@ * the row delegate intercepts their clicks so acting on a chain never also * navigates into it. Always rendered (the empty cell keeps the grid aligned) * and always visible for touch discoverability. */ - EnmMultiChainOverviewPane.prototype._actionsHtml = function (c) { + EnmMultiChainOverviewPane.prototype._actionsHtml = function (c, variant) { var cid = escapeAttr(c.chainId); function btn(action, glyph, key, fallback, cls) { var label = tFb(key, fallback); - return ''; + return ''; } var inner = ''; if (c.alive) { @@ -1092,7 +1113,19 @@ } else if (c.state === 'stopped') { inner += btn('start', '▶', 'chain_actions.start', 'Start', 'is-start'); } - return '' + inner + ''; + // v0.5.239 — Update only when the backend reports an update available + // for this chain. Per-EVM detection is a backend follow-up, so this + // stays hidden until that lands (mainchain can light up sooner). + if (c.updateAvailable) { + inner += btn('update', '↑', 'chain_actions.update', 'Update', 'is-update'); + } + var manage = (variant === 'hero') + ? '' + + '' + : ''; + if (!inner && !manage) { return ''; } + return '
    ' + inner + manage + '
    '; }; /** @private — P2.2 quick action runner. Mirrors chain-card._do: pane-wide @@ -1101,6 +1134,9 @@ * Disruptive actions (stop/restart) confirm first; start does not. */ EnmMultiChainOverviewPane.prototype._onAction = function (kind, chainId, btn) { if (!kind || !chainId || !btn) { return; } + // v0.5.239 — "Update" isn't a start/stop POST; it drills into the + // chain's dashboard where the binary-update flow lives. + if (kind === 'update') { this._routeToChain(chainId); return; } if (this._pendingAction) { return; } // one action at a time, pane-wide var self = this; var displayName = chainNameFor(chainId, null); @@ -1400,6 +1436,91 @@ * single-glance health line. * @private */ + /** + * v0.5.239 — health headline: a single at-a-glance verdict for the whole + * node (green when all healthy; warns + names the troubled service when + * not) plus bulk Start all / Restart all. Answers the operator's #1 + * question — "is my node OK?" — in one line. + * @private + */ + EnmMultiChainOverviewPane.prototype._healthHeadlineHtml = function (snap) { + var chains = (snap && Array.isArray(snap.chains)) ? snap.chains : []; + if (chains.length === 0) { return ''; } + var total = chains.length, synced = 0, starting = 0, attention = []; + chains.forEach(function (c) { + var st = normalizeStateV2(c.state); + if (st === 'synced') { synced += 1; } + else if (st === 'syncing' || st === 'starting') { starting += 1; } + else if (st === 'stopped' || st === 'stalled') { attention.push(c); } + // 'disabled' is intentionally off — not counted as a problem. + }); + var dotClass, verdict, detail; + if (attention.length > 0) { + dotClass = 'warn'; + verdict = (attention.length === 1) + ? tFb('overview_pane.health_attention_one', '1 service needs attention') + : tFb('overview_pane.health_attention_many', '{n} services need attention', { n: attention.length }); + var names = attention.map(function (c) { + return chainNameFor(c.chainId, c.displayName) + ' ' + stateLabelForV2(c.state).toLowerCase(); + }).join(', '); + detail = '· ' + names + ' · ' + synced + ' of ' + total + ' synced'; + } else if (starting > 0) { + dotClass = 'warn'; + verdict = tFb('overview_pane.health_syncing', 'Syncing'); + detail = '· ' + synced + ' of ' + total + ' synced'; + } else { + dotClass = 'ok'; + verdict = tFb('overview_pane.health_healthy', 'All services healthy'); + detail = '· ' + total + ' synced'; + } + var anyStopped = chains.some(function (c) { return c.state === 'stopped'; }); + var bulk = ''; + if (anyStopped) { + bulk += ''; + } + bulk += ''; + return '
    ' + + '
    ' + + '' + + '' + escapeHtml(verdict) + '' + + '' + escapeHtml(detail) + '' + + '
    ' + + '
    ' + bulk + '
    ' + + '
    '; + }; + + /** + * v0.5.239 — bulk Start all / Restart all from the health headline. POSTs + * per chain (start → stopped chains; restart → alive chains), then + * re-fetches. Frontend-orchestrated; no bulk backend endpoint needed. + * @private + */ + EnmMultiChainOverviewPane.prototype._onBulk = function (kind, btn) { + if (this._pendingAction) { return; } + var self = this; + var chains = (this._lastSnap && Array.isArray(this._lastSnap.chains)) ? this._lastSnap.chains : []; + var targets = chains.filter(function (c) { + return (kind === 'start') ? (c.state === 'stopped') : !!c.alive; + }).map(function (c) { return c.chainId; }); + if (targets.length === 0) { return; } + if (self.notifications && typeof self.notifications.info === 'function') { + self.notifications.info( + (kind === 'start' ? 'Starting ' : 'Restarting ') + targets.length + ' chains…', ''); + } + if (btn) { btn.disabled = true; btn.classList.add('is-busy'); } + Promise.all(targets.map(function (cid) { + return self.api.post('/chains/' + cid + '/' + kind).catch(function () { return null; }); + })).then(function () { + if (self._destroyed) { return; } + if (btn) { btn.disabled = false; btn.classList.remove('is-busy'); } + self._fetchInitial(); + }); + }; + /** * v0.5.238 — "This node" identity card. Surfaces ENM's own node status the * way node.sh's `status` does, but labeled "DAO Council" (the Cyber From d08efe0b3d6fafb1ba604446ea5b6e5c538ea686 Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Fri, 29 May 2026 03:23:03 +0300 Subject: [PATCH 15/24] =?UTF-8?q?enm=20v0.5.240=20=E2=80=94=20overview=20a?= =?UTF-8?q?udit=20fixes:=20bulk-restart=20confirm,=20honest=20health=20hea?= =?UTF-8?q?dline,=20routable=20oracle,=20tab-switch=20pause,=20dead-code?= =?UTF-8?q?=20sweep?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes 8 findings from the v0.5.237→239 overview-redesign review: - Bulk "Restart all" now confirms via enmDestructiveModal (it stops then restarts every running chain); extract _runBulk that actually sets/clears the pane-wide _pendingAction guard (the old _onBulk checked it but never set it, so SSE could wipe the in-flight buttons). - Health headline: bucket every non-{synced,syncing,starting,disabled} state (error/recovering/unconfigured/loading/stopped/stalled) into "needs attention" so an errored chain no longer reads "All services healthy"; the healthy-branch detail now reports the real synced count, not total. - Overview nested oracle line routes into the oracle's own dashboard on click (carries data-chain-id; the › caret means "open") — it used to only toggle a collapse, leaving the oracle detail page unreachable from the overview. - Overview pane pauses its 3s /system/usage poll + council:overview SSE while the operator is on another in-app tab and resumes on return (enmUseVisibilityPause only covers document.hidden, not tab switches). - SPV stub now appends instead of pane.innerHTML= so it can't wipe the "← Back to overview" button on a Council drill-in race. - Add the overview_pane.{health_*,bulk_*,manage,update_available} + chain_actions.update strings (the redesign shipped reading them via tFb fallbacks). - Remove dead code: _summaryLine/_summaryLineV2, _metaHtml/_syncBadgeHtml, the whole sparkline cluster (_reconcile/_teardownSparkline(s), heightSeries, cssEscape); fix the stale _routeToChain JSDoc. Verified live in the static preview: real EnmMultiChainOverviewPane renders with no runtime error at narrow width — accurate health verdict, labelled bulk actions, all 3 oracle lines routable, identity card intact. Co-Authored-By: Claude Opus 4.7 --- enm-server/package-lock.json | 4 +- enm-server/package.json | 2 +- .../apps/elastos-node-manager/css/styles.css | 6 +- .../apps/elastos-node-manager/index.html | 8 +- .../apps/elastos-node-manager/js/app.js | 31 +- .../js/components/multi-chain-overview.js | 353 +++++++----------- .../apps/elastos-node-manager/js/strings.js | 16 + 7 files changed, 179 insertions(+), 241 deletions(-) diff --git a/enm-server/package-lock.json b/enm-server/package-lock.json index 655838cb6d..a2c8441e2a 100644 --- a/enm-server/package-lock.json +++ b/enm-server/package-lock.json @@ -1,12 +1,12 @@ { "name": "@elacity/enm-server", - "version": "0.5.239", + "version": "0.5.240", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@elacity/enm-server", - "version": "0.5.239", + "version": "0.5.240", "license": "AGPL-3.0", "dependencies": { "better-sqlite3": "^11.9.0", diff --git a/enm-server/package.json b/enm-server/package.json index e915e14407..99f278f0f2 100644 --- a/enm-server/package.json +++ b/enm-server/package.json @@ -1,6 +1,6 @@ { "name": "@elacity/enm-server", - "version": "0.5.239", + "version": "0.5.240", "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode AND CR Council operators.", "main": "src/server.js", "author": "Elacity", diff --git a/src/backend/apps/elastos-node-manager/css/styles.css b/src/backend/apps/elastos-node-manager/css/styles.css index ad5aeb63d4..7c8ec8acdc 100644 --- a/src/backend/apps/elastos-node-manager/css/styles.css +++ b/src/backend/apps/elastos-node-manager/css/styles.css @@ -8426,16 +8426,14 @@ body[data-app-size="narrow"] .enm-app .enm-evm-shared-mining-grid { background: linear-gradient(120deg, var(--accent-soft), var(--bg-surface) 62%); padding: 20px 22px; } .enm-app .enm-ovx-hero .enm-overview-name { font-size: 19px; font-weight: 650; } -/* collapsed oracle line folded into its EVM card */ +/* oracle line folded into its EVM card — routes to the oracle dashboard on click (v0.5.240) */ .enm-app .enm-ovx-oracle { display: flex; align-items: center; gap: 8px; margin-top: 14px; padding-top: 12px; border-top: 1px solid var(--border-subtle); flex-wrap: wrap; cursor: pointer; } .enm-app .enm-ovx-oracle-name { font-size: 12px; color: var(--text-secondary); font-weight: 500; } .enm-app .enm-ovx-oracle-rel { font-size: 11px; color: var(--text-tertiary); } -.enm-app .enm-ovx-oracle.collapsed .enm-ovx-oracle-rel { display: none; } -.enm-app .enm-ovx-caret { margin-left: auto; color: var(--text-tertiary); font-size: 12px; transition: transform .12s; } -.enm-app .enm-ovx-oracle:not(.collapsed) .enm-ovx-caret { transform: rotate(90deg); } +.enm-app .enm-ovx-caret { margin-left: auto; color: var(--text-tertiary); font-size: 12px; } /* EVM card is the visible card → the inner li goes "naked" (no card-in-card) */ .enm-app .enm-overview-evm-card { background: var(--bg-surface); border: 1px solid var(--border); border-radius: 14px; padding: 16px 18px; diff --git a/src/backend/apps/elastos-node-manager/index.html b/src/backend/apps/elastos-node-manager/index.html index a728e90e51..25b371f95c 100644 --- a/src/backend/apps/elastos-node-manager/index.html +++ b/src/backend/apps/elastos-node-manager/index.html @@ -10,7 +10,7 @@ Elastos Node Manager - + + @@ -255,7 +255,7 @@

    Elastos Node Manager

    - + @@ -270,6 +270,6 @@

    Elastos Node Manager

    (Dashboard / Logs / Settings / Audit) replaced its 4-sub-tab wrapper; the Dashboard pane now mounts SystemStatus + ChainCard + BPoS card + ToolsUpdate directly from app.js._showDashboard. --> - + diff --git a/src/backend/apps/elastos-node-manager/js/app.js b/src/backend/apps/elastos-node-manager/js/app.js index e30d6b627e..391ebd4aec 100644 --- a/src/backend/apps/elastos-node-manager/js/app.js +++ b/src/backend/apps/elastos-node-manager/js/app.js @@ -522,6 +522,20 @@ if (tabId === 'settings') { self._mountSettingsTabLazy(); } else if (tabId === 'logs') { self._mountLogViewerLazy(); } else if (tabId === 'audit') { self._mountAuditTabLazy(); } + // v0.5.240 audit fix — pause the overview pane's 3s /system/usage + // poll + council:overview SSE while the operator is on another tab, + // resume on return. enmUseVisibilityPause only covers browser-tab + // visibility (document.hidden), not an in-app tab switch, so + // without this the overview kept fetching + re-rendering into a + // hidden pane. Only relevant for the Council overview (BPoS / + // drilled-in dashboards have no _overviewPane → this no-ops). + if (self._overviewMode && self._overviewPane) { + if (tabId === 'dashboard') { + if (typeof self._overviewPane.resume === 'function') { self._overviewPane.resume(); } + } else if (typeof self._overviewPane.pause === 'function') { + self._overviewPane.pause(); + } + } } tabBtns.forEach(function (btn) { @@ -1434,8 +1448,17 @@ // Defensive: the component script hasn't parsed yet (first // paint race). It's a deferred + diff --git a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js index 0c173339c1..42a4f02a20 100644 --- a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js +++ b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js @@ -642,7 +642,13 @@ Array.prototype.forEach.call(rowEls, function (row) { row.addEventListener('click', function (ev) { var t = ev.target; - var actionBtn = t && t.closest ? t.closest('.enm-overview-action') : null; + // v0.5.242 — match the labelled action button by its own + // class. (Was '.enm-overview-action', the legacy icon-button + // class that's now removed — see the dual-class cleanup.) + // Bulk Start/Restart-all buttons also use .enm-ovx-act but + // live in the health header, never inside a .enm-overview-row, + // so this row handler never sees them. + var actionBtn = t && t.closest ? t.closest('.enm-ovx-act') : null; if (actionBtn) { ev.stopPropagation(); self._onAction(actionBtn.dataset.action, actionBtn.dataset.chainId, actionBtn); @@ -1146,7 +1152,7 @@ var cid = escapeAttr(c.chainId); function btn(action, glyph, key, fallback, cls) { var label = tFb(key, fallback); - return ''; From 18c6450bcc9ef9fa54d51582965ef1408b6c1109 Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Fri, 29 May 2026 04:03:07 +0300 Subject: [PATCH 18/24] =?UTF-8?q?enm=20v0.5.243=20=E2=80=94=20remove=20inc?= =?UTF-8?q?orrect=20"Council=20registers=20BPoS=20separately"=20hint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The "This node" identity card showed: "A Council node still registers as a BPoS producer separately (in Essentials) to earn staking rewards." That's wrong. Verified against code: - Elastos.ELA dpos/state/arbitrators.go (distributeWithNormalArbitratorsV3): an arbiter of type CRC whose crMember.MemberState == MemberElected is paid the per-block CRC reward automatically — no RegisterProducer involved. An elected Council member's node is auto-promoted to a CRC arbiter and earns as part of consensus. - node.sh keeps CRC and BPoS as independent roles: register_crc (crc register tx, during the CR voting period) vs register_bpos (producer register v2). activate_crc simply calls activate_bpos — the shared `activate --nodepublickey` tx is the inactivity-recovery path (only after downtime flags the node), NOT a Council onboarding step. So a Council node does not register as a BPoS producer to earn. Per operator directive, the hint is removed outright (no replacement copy) — the DAO Council pill already states the real status. Also drops the now-unused overview_pane.identity.bpos_hint string and the dead .enm-identity-hint CSS. Verified in the static preview: a CR-member-with-no-producer identity card renders "DAO Council: Elected · GoldGuard" + "BPoS: Not registered" with no hint and no error. Co-Authored-By: Claude Opus 4.7 --- enm-server/package-lock.json | 4 +-- enm-server/package.json | 2 +- .../apps/elastos-node-manager/css/styles.css | 6 ----- .../apps/elastos-node-manager/index.html | 6 ++--- .../js/components/multi-chain-overview.js | 26 +++++++++---------- .../apps/elastos-node-manager/js/strings.js | 1 - 6 files changed, 19 insertions(+), 26 deletions(-) diff --git a/enm-server/package-lock.json b/enm-server/package-lock.json index 42fa13c0c4..c1d3eb8a4b 100644 --- a/enm-server/package-lock.json +++ b/enm-server/package-lock.json @@ -1,12 +1,12 @@ { "name": "@elacity/enm-server", - "version": "0.5.242", + "version": "0.5.243", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@elacity/enm-server", - "version": "0.5.242", + "version": "0.5.243", "license": "AGPL-3.0", "dependencies": { "better-sqlite3": "^11.9.0", diff --git a/enm-server/package.json b/enm-server/package.json index f31c61872f..ce25d9ccae 100644 --- a/enm-server/package.json +++ b/enm-server/package.json @@ -1,6 +1,6 @@ { "name": "@elacity/enm-server", - "version": "0.5.242", + "version": "0.5.243", "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode AND CR Council operators.", "main": "src/server.js", "author": "Elacity", diff --git a/src/backend/apps/elastos-node-manager/css/styles.css b/src/backend/apps/elastos-node-manager/css/styles.css index 154433a8ed..ed786de48c 100644 --- a/src/backend/apps/elastos-node-manager/css/styles.css +++ b/src/backend/apps/elastos-node-manager/css/styles.css @@ -7353,12 +7353,6 @@ body[data-app-size="compact"] .enm-app .enm-filter-chip { .enm-app .enm-identity-dot.state-synced { background: var(--success); } .enm-app .enm-identity-dot.state-syncing { background: var(--warning, #c08a00); } .enm-app .enm-identity-dot.state-unconfigured { background: var(--text-tertiary); opacity: 0.5; } -.enm-app .enm-identity-hint { - margin-top: var(--sp-2, 8px); - font-size: 12px; - line-height: 1.45; - color: var(--text-tertiary); -} .enm-app .enm-identity-keys { margin-top: var(--sp-2, 8px); display: flex; diff --git a/src/backend/apps/elastos-node-manager/index.html b/src/backend/apps/elastos-node-manager/index.html index 0b37a7d8df..339baffed2 100644 --- a/src/backend/apps/elastos-node-manager/index.html +++ b/src/backend/apps/elastos-node-manager/index.html @@ -10,7 +10,7 @@ Elastos Node Manager - + + @@ -255,7 +255,7 @@

    Elastos Node Manager

    - + diff --git a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js index 42a4f02a20..204eb2f3d2 100644 --- a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js +++ b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js @@ -1571,8 +1571,9 @@ * (name + state) and BPoS producer status (name + state), side by side, * plus the mining key + address. Truthful — reflects ENM's node key, so a * node that isn't bound to a Council seat reads "Not a Council member" and - * an unregistered producer reads "Not registered" (with a hint that a - * Council node still registers BPoS separately to earn staking rewards). + * an unregistered producer reads "Not registered". (CRC and BPoS are + * independent roles; a Council member earns automatically as a CRC arbiter + * and does NOT register as a BPoS producer — so no hint is shown here.) * Sourced from /system/identity (this._lastIdentity); returns '' until that * resolves so the card never flashes an empty state. * @private @@ -1621,16 +1622,16 @@ bposText = tFb('overview_pane.identity.bpos_unregistered', 'Not registered'); } - // Hint: a Council node still registers BPoS separately (node.sh shows - // CRC + BPoS as independent roles). Only when BPoS is absent on a - // Council install / member. - var hint = ''; - if ((!prod || !prod.state) && (setupRole === 'council' || (cr && cr.isCrMember))) { - hint = '
    ' - + escapeHtml(tFb('overview_pane.identity.bpos_hint', - 'A Council node still registers as a BPoS producer separately (in Essentials) to earn staking rewards.')) - + '
    '; - } + // v0.5.243 — removed the BPoS hint. It claimed a Council node "still + // registers as a BPoS producer separately to earn staking rewards", + // which is wrong: an elected CR member is auto-promoted to a CRC + // arbiter and earns the per-block CRC reward automatically (Elastos.ELA + // dpos/state/arbitrators.go — CRC-type arbiters with MemberState == + // MemberElected are paid without any RegisterProducer). node.sh keeps + // CRC and BPoS as independent roles (register_crc vs register_bpos); + // the only shared step is `activate`, an inactivity-recovery tx, not an + // onboarding requirement. The DAO Council pill already states the real + // status, so no explanatory text is added in its place. // Mining key + address. var keyLine = ''; @@ -1660,7 +1661,6 @@ + pill(tFb('overview_pane.identity.council_label', 'DAO Council'), councilDot, councilText) + pill(tFb('overview_pane.identity.bpos_label', 'BPoS'), bposDot, bposText) + '
    ' - + hint + keyLine + '
    '; }; diff --git a/src/backend/apps/elastos-node-manager/js/strings.js b/src/backend/apps/elastos-node-manager/js/strings.js index a60fddf1da..ae58dc4122 100644 --- a/src/backend/apps/elastos-node-manager/js/strings.js +++ b/src/backend/apps/elastos-node-manager/js/strings.js @@ -832,7 +832,6 @@ not_council: 'Not a Council member', council_unbound: 'Not bound to a seat', bpos_unregistered: 'Not registered', - bpos_hint: 'A Council node still registers as a BPoS producer separately (in Essentials) to earn staking rewards.', key_label: 'Key', addr_label: 'Address', }, From c0df144b00bb317ac4cfed05d8e92c43d07ed8de Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Fri, 29 May 2026 04:35:46 +0300 Subject: [PATCH 19/24] =?UTF-8?q?enm=20v0.5.244=20=E2=80=94=20overview=20k?= =?UTF-8?q?eyboard=20a11y=20(BL-3)=20+=20per-chain=20update=20detection=20?= =?UTF-8?q?(BL-1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BL-3 (a11y): overview EVM/oracle cards were mouse-only — a keyboard or screen-reader user couldn't open an EVM/oracle/arbiter dashboard (only the mainchain hero's "Manage" button was reachable). Now every routable chain card gets a native "Manage ›" button (the card stays NOT role=button to avoid nesting interactive content), and oracle lines (no inner buttons) become role=button + tabindex=0 + aria-label with an Enter/Space keydown handler. Stale class JSDoc corrected. BL-1 (update detection): the overview's per-chain `updateAvailable` was never populated, so the Update badge/button was dormant for every chain — and the existing GitHub-based mainchain scanner returns nulls on egress-locked hosts. New EnmChainUpdateScanner mirrors node.sh's get_elastos_ver_latest: lists https://download.elastos.io/elastos-/?F=1 for ela/esc/eid/pg, picks the newest version, compares against the installed `--version` (ChainState. snapshotVerified). Self-throttled 6h refresh kicked fire-and-forget from the overview tick; buildChainEntry only reads the synchronous cache so the snapshot stays cheap (no new RPC/spawn on-tick). Validated live: installed v0.2.7.1 etc. compare directly against the mirror's elastos-esc-v0.2.7.1 dirs. Co-Authored-By: Claude Opus 4.7 --- enm-server/package-lock.json | 4 +- enm-server/package.json | 2 +- .../src/services/CouncilOverviewService.js | 18 ++ .../src/services/EnmChainUpdateScanner.js | 196 ++++++++++++++++++ .../apps/elastos-node-manager/index.html | 2 +- .../js/components/multi-chain-overview.js | 55 +++-- 6 files changed, 257 insertions(+), 20 deletions(-) create mode 100644 enm-server/src/services/EnmChainUpdateScanner.js diff --git a/enm-server/package-lock.json b/enm-server/package-lock.json index c1d3eb8a4b..6d137e864e 100644 --- a/enm-server/package-lock.json +++ b/enm-server/package-lock.json @@ -1,12 +1,12 @@ { "name": "@elacity/enm-server", - "version": "0.5.243", + "version": "0.5.244", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@elacity/enm-server", - "version": "0.5.243", + "version": "0.5.244", "license": "AGPL-3.0", "dependencies": { "better-sqlite3": "^11.9.0", diff --git a/enm-server/package.json b/enm-server/package.json index ce25d9ccae..7f1bd644b8 100644 --- a/enm-server/package.json +++ b/enm-server/package.json @@ -1,6 +1,6 @@ { "name": "@elacity/enm-server", - "version": "0.5.243", + "version": "0.5.244", "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode AND CR Council operators.", "main": "src/server.js", "author": "Elacity", diff --git a/enm-server/src/services/CouncilOverviewService.js b/enm-server/src/services/CouncilOverviewService.js index 7a67360509..52ede4d5bd 100644 --- a/enm-server/src/services/CouncilOverviewService.js +++ b/enm-server/src/services/CouncilOverviewService.js @@ -75,6 +75,8 @@ const { ENM_LOG_PREFIX } = require('./EnmConstants'); const ConfigStore = require('./ConfigStore'); const ProcessMetrics = require('./ProcessMetrics'); const CoarseStateDerive = require('./CoarseStateDerive'); +// v0.5.244 — per-chain binary update detection (download.elastos.io mirror). +const ChainUpdateScanner = require('./EnmChainUpdateScanner'); // v0.5.208 — tick interval set to 2s. v0.5.203 dropped 5s → 1s per the // "refresh should be immediate" directive, but on a CPU-saturated box @@ -258,6 +260,12 @@ class CouncilOverviewService { cfg = { chains: {} }; } const chainsCfg = (cfg && cfg.chains) || {}; + // v0.5.244 — fire-and-forget kick of the per-chain update scanner. It + // self-throttles to one refresh per 6h and does its HTTP/spawn work + // off-tick; buildChainEntry only reads its synchronous cache, so the + // overview snapshot stays cheap (no new RPC/spawn on the tick path). + try { ChainUpdateScanner.getInstance({ logger: this.log }).ensureFresh(); } + catch (_) { /* update badge is best-effort; never block the overview */ } let proc = null; try { proc = this.registry.getProcessService(); } catch (_) { proc = null; } @@ -545,6 +553,16 @@ function buildChainEntry(args) { peers, lastHeightAdvanceMs, processMetrics, + // v0.5.244 — per-chain "update available" flag for the overview badge + + // Update action button. Synchronous cache read (EnmChainUpdateScanner, + // refreshed off-tick); false when no entry yet, the chain isn't on the + // download mirror (oracles/arbiter), or the binary is current. + updateAvailable: (function () { + try { + const u = ChainUpdateScanner.getInstance().getCached(cId); + return !!(u && u.updateAvailable); + } catch (_) { return false; } + }()), }; } diff --git a/enm-server/src/services/EnmChainUpdateScanner.js b/enm-server/src/services/EnmChainUpdateScanner.js new file mode 100644 index 0000000000..048b3d1ac5 --- /dev/null +++ b/enm-server/src/services/EnmChainUpdateScanner.js @@ -0,0 +1,196 @@ +/* + * Copyright (C) 2026-present Elacity + * SPDX-License-Identifier: AGPL-3.0 + * + * EnmChainUpdateScanner — per-chain binary update detection for the + * multi-chain overview's "Update available" badge / Update button. + * + * WHY a second scanner (EnmUpdateScanner already exists): that one is + * mainchain-only and polls GitHub's Elastos.ELA releases — which on a + * locked-down VPS is often unreachable (egress to api.github.com blocked), + * so it silently returns nulls. node.sh — the authoritative installer — + * pulls EVERY chain (ela / esc / eid / pg) from the Elastos download mirror + * at https://download.elastos.io/elastos-/ and finds the newest build + * by listing that directory (get_elastos_ver_latest: curl "…/?F=1" | grep + * [DIR] | strip to the version suffix | sort -Vr | head -1). This scanner + * mirrors that exactly, so it (a) works wherever node.sh's own update works, + * and (b) covers all four chains uniformly. The installed version comes from + * ChainState.snapshotVerified() — the same ` --version` value + * GET /chains/:id reports — and the formats line up directly (mirror dir + * "elastos-esc-v0.2.7.1" vs installed "v0.2.7.1"). + * + * Cheap-snapshot invariant: the overview tick must not spawn or block. So + * this scanner caches per chain and refreshes on its own 6h cadence (kicked + * fire-and-forget by the tick via ensureFresh()); the tick only ever reads + * the cache synchronously via getCached(). Wallet-identity-only invariant: + * outbound HTTP poll + version compare only; nothing is signed. + */ + +'use strict'; + +const https = require('node:https'); +const ConfigStore = require('./ConfigStore'); +const ChainState = require('./ChainState'); + +// chainId → Elastos download-mirror product name. Only chains published on +// the mirror as their own versioned product are scannable here; oracles ship +// inside the EVM bundles and the arbiter isn't independently versioned on the +// mirror, so they're intentionally absent (getCached → null → no badge). +const DOWNLOAD_NAME = { mainchain: 'ela', esc: 'esc', eid: 'eid', pg: 'pg' }; + +const DOWNLOAD_HOST = 'download.elastos.io'; +const TTL_MS = 6 * 60 * 60 * 1000; // 6h between refresh attempts +const REQUEST_TIMEOUT_MS = 8000; +const MAX_BODY_BYTES = 512 * 1024; // Apache listings are tiny; cap defensively + +function _readPackageVersion() { + try { + const pkg = require('../../package.json'); + if (pkg && typeof pkg.version === 'string') { return pkg.version; } + } catch (_) { /* fall through */ } + return '0.0.0'; +} +const USER_AGENT = 'elastos-node-manager/' + _readPackageVersion(); + +/** + * Compare two Elastos version strings (vX.Y.Z, optionally a 4th .W segment — + * e.g. v0.2.7.1). Strips a leading "v", pads missing segments with 0. + * @returns {number} -1 if ab + */ +function compareVersion(a, b) { + const pa = String(a).replace(/^v/i, '').split('.').map((n) => parseInt(n, 10) || 0); + const pb = String(b).replace(/^v/i, '').split('.').map((n) => parseInt(n, 10) || 0); + const len = Math.max(pa.length, pb.length); + for (let i = 0; i < len; i += 1) { + const x = pa[i] || 0; + const y = pb[i] || 0; + if (x !== y) { return x < y ? -1 : 1; } + } + return 0; +} + +/** + * Parse an Apache "?F=1" directory listing for the newest + * elastos--vX.Y.Z entry. Mirrors node.sh get_elastos_ver_latest: + * extract the version suffix off each DIR href, pick the highest. + * @returns {string|null} e.g. 'v0.2.7.1', or null when nothing matched + */ +function parseLatest(html, name) { + const safeName = String(name).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const re = new RegExp('href="elastos-' + safeName + '-([^"/]+)/?"', 'gi'); + let m; + let best = null; + while ((m = re.exec(html)) !== null) { + const ver = m[1]; + // Skip non-version dirs (e.g. an unversioned "elastos-esc-latest"). + if (!/^v?\d/.test(ver)) { continue; } + if (best === null || compareVersion(ver, best) > 0) { best = ver; } + } + return best; +} + +/** @returns {Promise} raw HTML of the mirror directory listing */ +function fetchListing(name) { + return new Promise((resolve, reject) => { + const req = https.get({ + host: DOWNLOAD_HOST, + path: '/elastos-' + name + '/?F=1', + headers: { 'User-Agent': USER_AGENT, Accept: 'text/html' }, + timeout: REQUEST_TIMEOUT_MS, + }, (res) => { + if (res.statusCode !== 200) { + res.resume(); + reject(new Error('HTTP ' + res.statusCode)); + return; + } + let body = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => { + body += chunk; + if (body.length > MAX_BODY_BYTES) { req.destroy(new Error('listing too large')); } + }); + res.on('end', () => resolve(body)); + }); + req.on('timeout', () => { req.destroy(new Error('timeout')); }); + req.on('error', reject); + }); +} + +class EnmChainUpdateScanner { + constructor(opts) { + this.log = (opts && opts.logger) || console; + this._cache = new Map(); // chainId → { installed, latest, updateAvailable, checkedAt } + this._refreshing = false; + this._lastAttemptAt = 0; + } + + /** + * Synchronous, non-blocking cache read for the overview tick. + * @returns {{installed:string, latest:string, updateAvailable:boolean, checkedAt:number}|null} + */ + getCached(chainId) { + return this._cache.get(chainId) || null; + } + + /** + * Fire-and-forget. Kicks a full refresh when the cache is stale and no + * refresh is already in flight; otherwise an instant no-op. Safe to call + * every tick — it self-throttles to one attempt per TTL_MS. + */ + ensureFresh() { + if (this._refreshing) { return; } + if (this._cache.size > 0 && (Date.now() - this._lastAttemptAt) < TTL_MS) { return; } + this._lastAttemptAt = Date.now(); + this._refreshing = true; + Promise.resolve() + .then(() => this.refreshAll()) + .catch((err) => { + if (this.log && typeof this.log.debug === 'function') { + this.log.debug('EnmChainUpdateScanner.refreshAll failed: ' + (err && err.message)); + } + }) + .then(() => { this._refreshing = false; }); + } + + /** Refresh every scannable, enabled chain. Best-effort per chain. */ + async refreshAll() { + let cfg; + try { cfg = await ConfigStore.load(); } catch (_) { return; } + const chains = (cfg && cfg.chains) || {}; + for (const chainId of Object.keys(DOWNLOAD_NAME)) { + const c = chains[chainId]; + if (!c || !c.enabled) { continue; } + let installed = null; + try { + const snap = await ChainState.snapshotVerified(chainId); + installed = snap && snap.binaryVersion ? snap.binaryVersion : null; + } catch (_) { /* leave installed null */ } + if (!installed) { continue; } + let latest = null; + try { + latest = parseLatest(await fetchListing(DOWNLOAD_NAME[chainId]), DOWNLOAD_NAME[chainId]); + } catch (_) { /* leave latest null — keep last good cache entry */ } + if (!latest) { continue; } + this._cache.set(chainId, { + installed, + latest, + updateAvailable: compareVersion(latest, installed) > 0, + checkedAt: Date.now(), + }); + } + } +} + +let _instance = null; +function getInstance(opts) { + if (!_instance) { _instance = new EnmChainUpdateScanner(opts || {}); } + return _instance; +} + +module.exports = { + getInstance, + compareVersion, + parseLatest, + DOWNLOAD_NAME, + EnmChainUpdateScanner, +}; diff --git a/src/backend/apps/elastos-node-manager/index.html b/src/backend/apps/elastos-node-manager/index.html index 339baffed2..e3206e759f 100644 --- a/src/backend/apps/elastos-node-manager/index.html +++ b/src/backend/apps/elastos-node-manager/index.html @@ -255,7 +255,7 @@

    Elastos Node Manager

    - + diff --git a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js index 204eb2f3d2..02ee99396b 100644 --- a/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js +++ b/src/backend/apps/elastos-node-manager/js/components/multi-chain-overview.js @@ -41,9 +41,12 @@ * missing sparkline holder is silently skipped (overview still useful * without sparklines on chains that haven't reported height yet). * - * ACCESSIBILITY: each row is role="button" + tabindex="0" with an - * aria-label of "Open dashboard". Enter/Space triggers route - * just like a click. Section headers use h3. + * ACCESSIBILITY (v0.5.244): chain cards are NOT role=button (they hold + * native action buttons; nesting interactive content is an anti-pattern). + * Mouse users route by clicking the card body; keyboard / screen-reader + * users route via each card's native "Manage ›" button. Oracle lines, which + * have no inner buttons, are role="button" + tabindex="0" with an aria-label + * of "Open dashboard" and an Enter/Space keydown handler. */ (function (root) { @@ -631,13 +634,15 @@ this._lastHtml = joined; this._root.innerHTML = joined; - // Wire row clicks → chain-selector dispatch. A click on a quick-action + // Wire row clicks → chain-change dispatch. A click on a quick-action // button runs the action instead of routing; a click anywhere else on - // the row (including the explicit open button, which bubbles here) - // routes. v0.5.187 a11y — the row is no longer role="button"/tabindex, - // so there's no row keydown handler: the open button + action buttons - // are native ' - : ''; + // v0.5.244 a11y — every routable chain card gets a keyboard-reachable + // "Manage ›" control (was hero-only). The card body still routes on + // click for mouse users, but keyboard / screen-reader users previously + // had no way into an EVM or arbiter dashboard (the card isn't a button + // — that would nest the action buttons inside a button). Oracle lines + // get their own role=button + tabindex in _rowHtml instead. + var manage = '' + + ''; if (!inner && !manage) { return ''; } return '
    ' + inner + manage + '
    '; }; From fc5373013072fe062b26321809c1adafc231b13b Mon Sep 17 00:00:00 2001 From: Elastos DAO Date: Fri, 29 May 2026 04:47:48 +0300 Subject: [PATCH 20/24] =?UTF-8?q?enm=20v0.5.245=20=E2=80=94=20Settings=20n?= =?UTF-8?q?av=20subheaders=20(BL-2)=20+=20fix=20update-scanner=20false=20p?= =?UTF-8?q?ositive?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BL-2: the 9 Settings sections are now grouped under 4 nav-rail subheaders (Node / Network & sidechains / Maintenance / Danger zone) instead of a flat list. Sections are unchanged — just reordered into groups and a decorative (aria-hidden) subheader emitted when the group changes. Default section stays keyed ('network'), pills (narrow) keep working, role=tablist navigation unaffected. Scanner fix (BL-1 follow-up): EnmChainUpdateScanner.parseLatest accepted any dir whose name started with a digit, so the mirror's commit-hash build "elastos-ela-9dc17ff" parsed as major version 9 (parseInt) and outranked v0.9.9.5 → mainchain falsely showed "update available". Tightened the filter to dotted-numeric versions only (^v?\d+(\.\d+)+$), which also drops -hotfix/-rc suffixed tags. Verified against the live mirror listing: latest now resolves to v0.9.9.5 == installed → updateAvailable false. Co-Authored-By: Claude Opus 4.7 --- enm-server/package-lock.json | 4 +- enm-server/package.json | 2 +- .../src/services/EnmChainUpdateScanner.js | 9 ++- .../apps/elastos-node-manager/css/styles.css | 12 ++++ .../apps/elastos-node-manager/index.html | 6 +- .../js/components/settings-tab.js | 64 +++++++++++-------- .../apps/elastos-node-manager/js/strings.js | 6 ++ 7 files changed, 68 insertions(+), 35 deletions(-) diff --git a/enm-server/package-lock.json b/enm-server/package-lock.json index 6d137e864e..fb8804a574 100644 --- a/enm-server/package-lock.json +++ b/enm-server/package-lock.json @@ -1,12 +1,12 @@ { "name": "@elacity/enm-server", - "version": "0.5.244", + "version": "0.5.245", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@elacity/enm-server", - "version": "0.5.244", + "version": "0.5.245", "license": "AGPL-3.0", "dependencies": { "better-sqlite3": "^11.9.0", diff --git a/enm-server/package.json b/enm-server/package.json index 7f1bd644b8..1ef41dc46a 100644 --- a/enm-server/package.json +++ b/enm-server/package.json @@ -1,6 +1,6 @@ { "name": "@elacity/enm-server", - "version": "0.5.244", + "version": "0.5.245", "description": "Elastos Node Manager — standalone sidecar server for PC2 that runs and self-heals an Elastos mainchain node for BPoS supernode AND CR Council operators.", "main": "src/server.js", "author": "Elacity", diff --git a/enm-server/src/services/EnmChainUpdateScanner.js b/enm-server/src/services/EnmChainUpdateScanner.js index 048b3d1ac5..458f547ae3 100644 --- a/enm-server/src/services/EnmChainUpdateScanner.js +++ b/enm-server/src/services/EnmChainUpdateScanner.js @@ -82,8 +82,13 @@ function parseLatest(html, name) { let best = null; while ((m = re.exec(html)) !== null) { const ver = m[1]; - // Skip non-version dirs (e.g. an unversioned "elastos-esc-latest"). - if (!/^v?\d/.test(ver)) { continue; } + // Strict: optional "v" then a dotted-numeric version only (X.Y[.Z[.W]]). + // The mirror also carries commit-hash builds (e.g. + // "elastos-ela-9dc17ff") and suffixed tags ("v0.9.8-hotfix"); a loose + // /^v?\d/ accepted "9dc17ff", and parseInt("9dc17ff") === 9 made it + // outrank v0.9.9.5 → a bogus "update available". Require clean dotted + // numerals so only real release dirs are considered. + if (!/^v?\d+(\.\d+)+$/.test(ver)) { continue; } if (best === null || compareVersion(ver, best) > 0) { best = ver; } } return best; diff --git a/src/backend/apps/elastos-node-manager/css/styles.css b/src/backend/apps/elastos-node-manager/css/styles.css index ed786de48c..618b451208 100644 --- a/src/backend/apps/elastos-node-manager/css/styles.css +++ b/src/backend/apps/elastos-node-manager/css/styles.css @@ -1781,6 +1781,18 @@ body[data-app-size="compact"] .enm-sys-cell:last-child, font-weight: var(--fw-semibold); padding: var(--sp-2) var(--sp-3); } +/* v0.5.245 (BL-2) — group subheaders inside the wide nav rail. Lighter than + the rail title; spacing (not a heavy border) separates each group so the + rail reads as a short outline. Decorative (aria-hidden in JS). */ +.enm-settings-nav-group { + font-size: 10px; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--text-tertiary); + font-weight: var(--fw-semibold); + padding: 0 var(--sp-3) 4px; + margin-top: var(--sp-4); +} .enm-settings-nav-item { display: flex; align-items: center; diff --git a/src/backend/apps/elastos-node-manager/index.html b/src/backend/apps/elastos-node-manager/index.html index e3206e759f..af46f1de5d 100644 --- a/src/backend/apps/elastos-node-manager/index.html +++ b/src/backend/apps/elastos-node-manager/index.html @@ -10,7 +10,7 @@ Elastos Node Manager - + + @@ -235,7 +235,7 @@

    Elastos Node Manager

    - + - + @@ -216,7 +216,7 @@

    Elastos Node Manager

    height + last activity/error. Never mounted for the mainchain. --> - +