From 4396ef0faa2cb484315e49b23c71b2c6acd0a330 Mon Sep 17 00:00:00 2001 From: minuszka <101508242+minuszka@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:45:36 +0100 Subject: [PATCH] Add a page for each masternode and let visitors star their own nodes There was no single place to see everything about one masternode, and no way to keep track of your own nodes. - Each masternode now has its own page: status, identifiers, payout, owner and voting addresses, hosting, wallet version and its recent PoSe history (bans, recoveries and status changes from the last 90 days). Events from an earlier registration of the same collateral are left out and counted, not shown as this node's history. - A star on the page and in the masternode table adds a node to "My nodes", saved in the browser (up to 50). The table can show only starred nodes, and starred nodes that are no longer active are linked separately. - Addresses in the masternode table and node hashes in PoSe Watch now open the new page. - An unknown or mistyped hash shows a clear "not found" message, and the page keeps working when the browser does not allow saving. - Browser tests cover the page, the stars and these error cases on desktop and mobile; breaking any of these rules on purpose makes them fail. --- client/e2e/ban-detection.spec.ts | 12 + client/e2e/masternode-detail.spec.ts | 245 +++++++++++++++ client/e2e/masternode-table.spec.ts | 98 ++++++ client/src/App.tsx | 2 + client/src/components/ui/FavoriteButton.css | 71 +++++ client/src/components/ui/FavoriteButton.tsx | 44 +++ client/src/pages/BanDetectionPage.tsx | 5 +- client/src/pages/MasternodeDetailPage.css | 208 ++++++++++++ client/src/pages/MasternodeDetailPage.tsx | 297 ++++++++++++++++++ client/src/pages/MasternodesPage.tsx | 8 + .../src/pages/masternodes/MasternodeTable.css | 67 ++-- .../src/pages/masternodes/MasternodeTable.tsx | 104 +++++- .../pages/masternodes/masternodeBadges.css | 27 ++ .../src/pages/masternodes/masternodeRows.ts | 11 +- client/src/pages/masternodes/nodeEvents.ts | 53 ++++ client/src/services/api.ts | 45 ++- client/src/types/api.ts | 6 + client/src/utils/favoriteMasternodes.ts | 122 +++++++ client/src/utils/routes.ts | 9 + server/test/masternodes.v1.routes.test.ts | 151 +++++++++ server/test/routeSeo.test.ts | 2 + shared/src/contracts/masternodes.ts | 39 +++ shared/src/index.ts | 3 + shared/src/routeSeo.ts | 9 + 24 files changed, 1600 insertions(+), 38 deletions(-) create mode 100644 client/e2e/masternode-detail.spec.ts create mode 100644 client/src/components/ui/FavoriteButton.css create mode 100644 client/src/components/ui/FavoriteButton.tsx create mode 100644 client/src/pages/MasternodeDetailPage.css create mode 100644 client/src/pages/MasternodeDetailPage.tsx create mode 100644 client/src/pages/masternodes/masternodeBadges.css create mode 100644 client/src/pages/masternodes/nodeEvents.ts create mode 100644 client/src/utils/favoriteMasternodes.ts diff --git a/client/e2e/ban-detection.spec.ts b/client/e2e/ban-detection.spec.ts index f40e72a..86f07b0 100644 --- a/client/e2e/ban-detection.spec.ts +++ b/client/e2e/ban-detection.spec.ts @@ -71,3 +71,15 @@ test('failed refresh removes previous current counts @smoke', async ({ page }) = await expect(page.getByText('Ban analysis unavailable.', { exact: false })).toBeVisible({ timeout: 20_000 }); await expect(page.locator('.bd-current-stats')).not.toContainText('217'); }); + +test('a node with a proTxHash links to its masternode page; the service still filters this page @smoke', async ({ page }) => { + const data = fixture(); + data.trackedNodes[0].proTxHash = 'a'.repeat(64); + await stubApi(page, { [path]: { success: true, data } }); + await page.goto('/ban-detection'); + const panel = page.locator('.bd-node-panel tbody'); + await expect(panel.getByRole('link', { name: 'aaaaaaaa...aaaaaaaa' })).toHaveAttribute('href', `/masternode/${'a'.repeat(64)}`); + await expect(panel.getByRole('link', { name: '198.51.100.1:8192' })).toHaveAttribute('href', `/ban-detection?node=${'a'.repeat(64)}`); + // "protx-b" is not a proTxHash: its line stays plain text. + await expect(panel.locator('tr').nth(1).locator('.mnh-meta-line a')).toHaveCount(0); +}); diff --git a/client/e2e/masternode-detail.spec.ts b/client/e2e/masternode-detail.spec.ts new file mode 100644 index 0000000..1fffce0 --- /dev/null +++ b/client/e2e/masternode-detail.spec.ts @@ -0,0 +1,245 @@ +import { expect, test, type Page } from '@playwright/test'; +import { stubApi } from './apiStub'; + +// One masternode's page: identity, addresses, placement, version and the PoSe history of this +// registration (not of earlier registrations of the same collateral), plus the "My nodes" star. + +const proTx = 'ab'.repeat(32); +const otherProTx = 'ef'.repeat(32); +const nodeId = `${'cd'.repeat(32)}-1`; +const service = '203.0.113.50:9999'; +const registeredAt = Date.UTC(2026, 0, 15) / 1000; +const FAVORITES_KEY = 'deftrack-fav-masternodes'; + +const detail = { + id: nodeId, service, ip: '203.0.113.50', port: 9999, status: 'POSE_PENALTY', protocol: 70242, lastSeen: null, + activeSeconds: 3_600, isTor: false, countryCode: 'DE', countryName: 'Germany', proTxHash: proTx, + ownerAddress: 'DOwnerAddress000000000000000000000', payoutAddress: 'DPayoutAddress00000000000000000000', + collateralAddress: 'DCollateralAddress0000000000000000', registeredHeight: 120_000, registeredAt, + poseBanHeight: null, poseBanAt: null, poseRevivedHeight: 125_000, posePenalty: 33, operatorPubkey: 'op'.repeat(24), + votingAddress: 'DVotingAddress00000000000000000000', collateralAmount: 10_000, provider: 'Hetzner', + providerSource: 'tag', providerTagCidr: '203.0.113.0/24', providerTagSource: 'manual', providerConfidence: 1, + providerEvidenceUrl: null, asn: 24_940, asnOrg: 'Hetzner Online GmbH', uptime: 3_600, queuePosition: 5, nextPayoutEta: 600, +}; + +const events = [ + // Newest first, as the endpoint answers. A plain status change after this registration: shown. + { _id: 'e1', nodeId, service, previousStatus: 'ENABLED', currentStatus: 'POSE_PENALTY', detectedAt: '2026-11-10T08:00:00.000Z', eventType: 'status', eventStatus: 'observed', proTxHash: null }, + // A ban of this registration that later recovered: shown. + { _id: 'e2', nodeId, service, previousStatus: 'POSE_BAN_HEIGHT', currentStatus: 'POSE_BANNED', detectedAt: '2026-11-01T08:00:00.000Z', eventType: 'ban', eventStatus: 'recovered', proTxHash: proTx, poseBanHeight: 124_000, detectedHeight: 124_000, recoveredAt: '2026-11-02T08:00:00.000Z', recoveredHeight: 125_000 }, + // A ban of an earlier registration of the same collateral: not shown. + { _id: 'e3', nodeId, service, previousStatus: 'POSE_BAN_HEIGHT', currentStatus: 'POSE_BANNED', detectedAt: '2026-10-01T08:00:00.000Z', eventType: 'ban', eventStatus: 'banned', proTxHash: otherProTx, poseBanHeight: 110_000 }, + // A plain status change from before this registration: cannot be tied to it, not shown. + { _id: 'e4', nodeId, service, previousStatus: 'NEW', currentStatus: 'ENABLED', detectedAt: '2025-12-01T08:00:00.000Z', eventType: 'status', eventStatus: 'observed', proTxHash: null }, +]; + +const versions = { nodes: [{ id: proTx, ip: '203.0.113.50', port: 9999, status: 'POSE_PENALTY', walletVersion: '23.0.0', versionState: 'fresh', lastVersionObservedAt: null, lastInventoryObservedAt: null, sources: [], isDeprecated: false }] }; + +function api(overrides: Record> = {}) { + return { + [`/api/v1/masternodes/${proTx}`]: { success: true, data: detail }, + [`/api/v1/masternodes/${nodeId}/events`]: { success: true, data: events }, + '/api/v1/node-inventory/active-versions': { success: true, data: versions }, + ...overrides, + }; +} + +const row = (page: Page, label: string) => + page.locator('.mnd-row').filter({ has: page.locator('dt', { hasText: new RegExp(`^${label}$`) }) }).locator('dd'); +const star = (page: Page) => page.getByRole('button', { name: `Star ${service}` }); +const pageFits = (page: Page) => + page.evaluate(() => { + const root = document.querySelector('.mnd-page')!; + return root.scrollWidth <= root.clientWidth && document.documentElement.scrollWidth <= window.innerWidth; + }); + +test('the masternode page shows the node and the PoSe history of this registration only @smoke', async ({ page }, testInfo) => { + await stubApi(page, api()); + await page.goto(`/masternode/${proTx}`); + + await expect(page.getByRole('heading', { level: 1 })).toHaveText(service); + await expect(row(page, 'Status')).toContainText('PoSe Penalty'); + await expect(row(page, 'proTxHash')).toContainText(proTx); + await expect(row(page, 'proTxHash').getByRole('button', { name: 'Copy proTxHash' })).toBeVisible(); + await expect(row(page, 'Collateral').first()).toContainText(nodeId); + await expect(row(page, 'Version')).toHaveText('23.0.0'); + await expect(row(page, 'Registered').getByRole('link')).toHaveAttribute('href', '/block/120000'); + await expect(row(page, 'PoSe penalty')).toHaveText('33'); + await expect(row(page, 'PoSe ban block')).toHaveText('Not banned'); + await expect(row(page, 'Last revived').getByRole('link')).toHaveAttribute('href', '/block/125000'); + await expect(row(page, 'Payout').getByRole('link')).toHaveAttribute('href', `/address/${detail.payoutAddress}`); + await expect(row(page, 'Owner').getByRole('link')).toHaveAttribute('href', `/address/${detail.ownerAddress}`); + await expect(row(page, 'Voting').getByRole('link')).toHaveAttribute('href', `/address/${detail.votingAddress}`); + await expect(row(page, 'Operator key')).toContainText(detail.operatorPubkey); + await expect(row(page, 'Country')).toContainText('Germany'); + await expect(row(page, 'Provider')).toContainText('Hetzner'); + await expect(row(page, 'Provider')).toContainText('Tagged'); + await expect(row(page, 'Network')).toContainText('AS24940'); + await expect(page.getByRole('link', { name: 'Open in PoSe Watch' })).toHaveAttribute('href', `/ban-detection?node=${proTx}`); + // The payout estimate of the endpoint is a guess from registration order: not shown. + await expect(page.locator('.mnd-page')).not.toContainText(/queue|next payout/i); + + const history = page.locator('.mnd-events tbody tr'); + await expect(history).toHaveCount(2); + await expect(history.nth(0)).toContainText('Enabled → PoSe Penalty'); + await expect(history.nth(1)).toContainText('PoSe ban, later recovered'); + await expect(history.nth(1).getByRole('link', { name: '124,000' })).toHaveAttribute('href', '/block/124000'); + await expect(history.nth(1).getByRole('link', { name: '125,000' })).toHaveAttribute('href', '/block/125000'); + await expect(page.locator('.mnd-page')).not.toContainText('110,000'); + await expect(page.getByText('2 stored events of this collateral are not shown')).toBeVisible(); + expect(await pageFits(page)).toBe(true); + if (testInfo.project.name.includes('mobile')) { + // Touch targets of at least 40 px on a phone. + const copy = await row(page, 'proTxHash').getByRole('button', { name: 'Copy proTxHash' }).boundingBox(); + const watch = await page.getByRole('link', { name: 'Open in PoSe Watch' }).boundingBox(); + expect(copy!.height).toBeGreaterThanOrEqual(40); + expect(watch!.height).toBeGreaterThanOrEqual(40); + } +}); + +test('without a registration time no plain status change is counted for this registration @smoke', async ({ page }) => { + await stubApi(page, api({ [`/api/v1/masternodes/${proTx}`]: { success: true, data: { ...detail, registeredAt: null } } })); + await page.goto(`/masternode/${proTx}`); + const history = page.locator('.mnd-events tbody tr'); + await expect(history).toHaveCount(1); + await expect(history.first()).toContainText('PoSe ban, later recovered'); + await expect(page.getByText('3 stored events of this collateral are not shown')).toBeVisible(); +}); + +test('an unknown proTxHash shows "not found", an invalid one sends no request, upper case is redirected @smoke', async ({ page }) => { + const unknown = '12'.repeat(32); + const detailRequests: string[] = []; + page.on('request', (request) => { if (request.url().includes('/api/v1/masternodes/')) detailRequests.push(request.url()); }); + await stubApi(page, api()); + await page.route(`**/api/v1/masternodes/${unknown}`, (route) => + route.fulfill({ status: 404, contentType: 'application/json', body: JSON.stringify({ success: false, error: { code: 'NOT_FOUND', message: 'Masternode not found' } }) })); + + await page.goto(`/masternode/${unknown}`); + await expect(page.getByText('Masternode not found')).toBeVisible(); + await expect(page.getByText('The current masternode list has no registration with this proTxHash')).toBeVisible(); + await expect(page.getByRole('link', { name: 'Open the Masternodes table' })).toHaveAttribute('href', '/masternodes'); + expect(detailRequests.filter((url) => url.includes('/events'))).toHaveLength(0); + + detailRequests.length = 0; + await page.goto('/masternode/not-a-hash'); + await expect(page.getByText('"not-a-hash" is not a proTxHash')).toBeVisible(); + expect(detailRequests).toHaveLength(0); + + // A pasted collateral outpoint is long and unbroken: it wraps inside the panel. + const outpoint = `${'9'.repeat(64)}-1`; + await page.goto(`/masternode/${outpoint}`); + await expect(page.getByText(`"${outpoint}" is not a proTxHash`)).toBeVisible(); + expect(await page.locator('.state-panel').evaluate((panel) => panel.scrollWidth <= panel.clientWidth)).toBe(true); + + await page.goto(`/masternode/${proTx.toUpperCase()}`); + await expect(page).toHaveURL(new RegExp(`/masternode/${proTx}$`)); + await expect(page.getByRole('heading', { level: 1 })).toHaveText(service); +}); + +test('a failed node request and a failed history request each say so; versions fall back to unavailable @smoke', async ({ page }) => { + // Only the node itself answers: the history and the versions get the stub's 503. + await stubApi(page, { [`/api/v1/masternodes/${proTx}`]: { success: true, data: detail } }); + await page.goto(`/masternode/${proTx}`); + await expect(page.getByRole('heading', { level: 1 })).toHaveText(service); + await expect(page.getByText('PoSe history could not be loaded')).toBeVisible(); + await expect(row(page, 'Version')).toHaveText('Unavailable right now'); + + await stubApi(page, {}); + await page.goto(`/masternode/${'34'.repeat(32)}`); + await expect(page.getByText('Masternode could not be loaded')).toBeVisible(); +}); + +test('a node naming another registration, or an unreadable answer, is refused rather than shown @smoke', async ({ page }) => { + await stubApi(page, api({ [`/api/v1/masternodes/${proTx}`]: { success: true, data: { ...detail, proTxHash: otherProTx } } })); + await page.goto(`/masternode/${proTx}`); + await expect(page.getByText('Masternode could not be loaded')).toBeVisible(); + await expect(page.getByText('Masternode identity mismatch')).toBeVisible(); + + const { status: _status, ...withoutStatus } = detail; + await stubApi(page, api({ [`/api/v1/masternodes/${proTx}`]: { success: true, data: withoutStatus } })); + await page.goto(`/masternode/${proTx}`); + await expect(page.getByText('The masternode answer could not be read')).toBeVisible(); +}); + +test('a star keeps the node in My nodes after a reload @smoke', async ({ page }) => { + await stubApi(page, api()); + await page.goto(`/masternode/${proTx}`); + await expect(star(page)).toHaveAttribute('aria-pressed', 'false'); + await star(page).click(); + await expect(star(page)).toHaveAttribute('aria-pressed', 'true'); + expect(await page.evaluate((key) => window.localStorage.getItem(key), FAVORITES_KEY)).toBe(JSON.stringify([proTx])); + + await page.reload(); + await expect(star(page)).toHaveAttribute('aria-pressed', 'true'); + await star(page).click(); + await expect(star(page)).toHaveAttribute('aria-pressed', 'false'); + expect(await page.evaluate((key) => window.localStorage.getItem(key), FAVORITES_KEY)).toBe('[]'); +}); + +test('with storage blocked the page works and the star lasts until a reload @smoke', async ({ page }) => { + const errors: string[] = []; + page.on('pageerror', (error) => errors.push(error.message)); + await page.addInitScript(() => { + Object.defineProperty(window, 'localStorage', { get() { throw new Error('storage blocked'); } }); + }); + await stubApi(page, api()); + await page.goto(`/masternode/${proTx}`); + await expect(page.getByRole('heading', { level: 1 })).toHaveText(service); + await star(page).click(); + await expect(star(page)).toHaveAttribute('aria-pressed', 'true'); + await expect(page.getByText('This browser does not allow saving here, so your stars are kept only until the page is reloaded or closed.')).toBeVisible(); + expect(errors).toEqual([]); +}); + +test('when saving is refused the star still works until a reload @smoke', async ({ page }) => { + const errors: string[] = []; + page.on('pageerror', (error) => errors.push(error.message)); + // Reading works (nothing saved yet); every write is refused, as with a full or locked storage. + await page.addInitScript(() => { + Storage.prototype.setItem = () => { throw new DOMException('refused', 'QuotaExceededError'); }; + }); + await stubApi(page, api()); + await page.goto(`/masternode/${proTx}`); + await star(page).click(); + await expect(star(page)).toHaveAttribute('aria-pressed', 'true'); + await expect(page.getByText('This browser does not allow saving here, so your stars are kept only until the page is reloaded or closed.')).toBeVisible(); + await page.reload(); + await expect(star(page)).toHaveAttribute('aria-pressed', 'false'); + expect(errors).toEqual([]); +}); + +test('a star given in one tab shows in another tab of the same site @smoke', async ({ page }) => { + await stubApi(page, api()); + const other = await page.context().newPage(); + await stubApi(other, api()); + await page.goto(`/masternode/${proTx}`); + await other.goto(`/masternode/${proTx}`); + await expect(star(other)).toHaveAttribute('aria-pressed', 'false'); + await star(page).click(); + await expect(star(other)).toHaveAttribute('aria-pressed', 'true'); +}); + +test('history events of another node id are refused rather than shown @smoke', async ({ page }) => { + await stubApi(page, api({ [`/api/v1/masternodes/${nodeId}/events`]: { success: true, data: [{ ...events[0], nodeId: 'another-node' }] } })); + await page.goto(`/masternode/${proTx}`); + await expect(page.getByRole('heading', { level: 1 })).toHaveText(service); + await expect(page.getByText('PoSe history could not be loaded')).toBeVisible(); +}); + +test('a damaged saved list counts as empty, and a full list refuses a new star @smoke', async ({ page }) => { + await page.addInitScript((key) => window.localStorage.setItem(key, '{not json'), FAVORITES_KEY); + await stubApi(page, api()); + await page.goto(`/masternode/${proTx}`); + await expect(star(page)).toHaveAttribute('aria-pressed', 'false'); + + const full = Array.from({ length: 50 }, (_, index) => index.toString(16).padStart(64, '0')); + await page.evaluate(([key, list]) => window.localStorage.setItem(key as string, JSON.stringify(list)), [FAVORITES_KEY, full] as const); + // The init script would put the damaged value back on reload; open a fresh page in the same context. + const fresh = await page.context().newPage(); + await stubApi(fresh, api()); + await fresh.goto(`/masternode/${proTx}`); + await star(fresh).click(); + await expect(star(fresh)).toHaveAttribute('aria-pressed', 'false'); + await expect(fresh.getByText('My nodes is full (50). Remove a star first.')).toBeVisible(); + expect(JSON.parse((await fresh.evaluate((key) => window.localStorage.getItem(key), FAVORITES_KEY))!)).toHaveLength(50); +}); diff --git a/client/e2e/masternode-table.spec.ts b/client/e2e/masternode-table.spec.ts index 1a583ca..bd4c071 100644 --- a/client/e2e/masternode-table.spec.ts +++ b/client/e2e/masternode-table.spec.ts @@ -218,3 +218,101 @@ test('without a version snapshot every version is unknown and the page says why await expect(page.getByText('Versions are unavailable right now')).toBeVisible(); await expect(rows(page).locator('.mn-col-version').filter({ hasNotText: 'unknown' })).toHaveCount(0); }); + +test('a star marks a node, My nodes shows only starred ones after a reload, and the address opens its page @smoke', async ({ page }, testInfo) => { + await stubApi(page, api()); + // Node 121 is banned, so it is starred but not in the active table. + await page.addInitScript(([key, value]) => { + if (!window.sessionStorage.getItem('seeded')) { + window.localStorage.setItem(key, value); + window.sessionStorage.setItem('seeded', '1'); + } + }, ['deftrack-fav-masternodes', JSON.stringify([proTx(121)])]); + await page.goto('/masternodes'); + await expect(rows(page)).toHaveCount(50); + + const starButton = (i: number) => rowFor(page, i).getByRole('button', { name: `Star ${ip(i)}:9999` }); + await expect(rowFor(page, 1).locator('.mn-col-service a')).toHaveAttribute('href', `/masternode/${proTx(1)}`); + // Node 7 has no proTxHash: no star and no page link. + await expect(rowFor(page, 7).getByRole('button', { name: /^Star / })).toHaveCount(0); + await expect(rowFor(page, 7).locator('.mn-col-service a')).toHaveCount(0); + if (testInfo.project.name.includes('mobile')) { + // In the card view the star ends the first line inside the card, even beside the widest badge. + const [card, starBox, serviceBox] = await Promise.all([ + rowFor(page, 10).boundingBox(), + starButton(10).boundingBox(), + rowFor(page, 10).locator('.mn-col-service').boundingBox(), + ]); + expect(starBox!.x + starBox!.width).toBeLessThanOrEqual(card!.x + card!.width); + expect(starBox!.y).toBeLessThan(serviceBox!.y + serviceBox!.height); + } + + await starButton(1).click(); + await starButton(3).click(); + await expect(starButton(1)).toHaveAttribute('aria-pressed', 'true'); + const mine = page.getByRole('button', { name: /My nodes/ }); + await expect(mine).toContainText('3'); + await mine.click(); + await expect(page).toHaveURL(/[?&]mine=1(&|$)/); + await expect(rows(page)).toHaveCount(2); + await expect(page.locator('.mn-starred-elsewhere a')).toHaveAttribute('href', `/masternode/${proTx(121)}`); + + await page.reload(); + await expect(mine).toHaveAttribute('aria-pressed', 'true'); + await expect(rows(page)).toHaveCount(2); + await expect(starButton(3)).toHaveAttribute('aria-pressed', 'true'); + expect(await fitsWindow(page)).toBe(true); + + await rowFor(page, 1).locator('.mn-col-service a').click(); + await expect(page).toHaveURL(new RegExp(`/masternode/${proTx(1)}$`)); +}); + +test('a starred node hidden by the country filter is not called inactive; a banned one still is @smoke', async ({ page }) => { + // Node 2 is in the United States and active; the Germany filter hides it. Node 121 is banned. + await stubApi(page, { + ...api(), + '/api/masternodes/distribution': { success: true, data: { total: 120, countries: [ + { countryCode: 'DE', countryName: 'Germany', count: 61 }, { countryCode: 'US', countryName: 'United States', count: 60 }, + ], providers: [] } }, + }); + await page.addInitScript(([key, value]) => window.localStorage.setItem(key, value), ['deftrack-fav-masternodes', JSON.stringify([proTx(2), proTx(121)])]); + await page.goto('/masternodes?mine=1'); + await expect(rows(page)).toHaveCount(1); + const elsewhere = page.locator('.mn-starred-elsewhere a'); + await expect(elsewhere).toHaveCount(1); + await expect(elsewhere).toHaveAttribute('href', `/masternode/${proTx(121)}`); + await page.getByRole('list', { name: 'Masternodes by country' }).getByRole('button', { name: /Germany/ }).click(); + await expect(page.getByText('No starred masternode matches the chosen country or provider')).toBeVisible(); + await expect(page.getByText('None of your starred masternodes is active')).toHaveCount(0); + // Still only the banned node is listed as not active: node 2 is merely filtered out. + await expect(elsewhere).toHaveCount(1); + await expect(elsewhere).toHaveAttribute('href', `/masternode/${proTx(121)}`); +}); + +test('My nodes with only a banned star says none of them is active and links to it @smoke', async ({ page }) => { + await stubApi(page, api()); + await page.addInitScript(([key, value]) => window.localStorage.setItem(key, value), ['deftrack-fav-masternodes', JSON.stringify([proTx(121)])]); + await page.goto('/masternodes?mine=1'); + await expect(page.getByText('None of your starred masternodes is active')).toBeVisible(); + await expect(page.locator('.mn-starred-elsewhere a')).toHaveAttribute('href', `/masternode/${proTx(121)}`); + await expect(rows(page)).toHaveCount(0); +}); + +test('with storage blocked the table says the stars are not kept @smoke', async ({ page }) => { + await page.addInitScript(() => { + Object.defineProperty(window, 'localStorage', { get() { throw new Error('storage blocked'); } }); + }); + await stubApi(page, api()); + await page.goto('/masternodes'); + await rowFor(page, 1).getByRole('button', { name: `Star ${ip(1)}:9999` }).click(); + await expect(page.getByText('This browser does not allow saving here, so your stars are kept only until the page is reloaded or closed.')).toBeVisible(); +}); + +test('My nodes without any star explains how to add one @smoke', async ({ page }) => { + await stubApi(page, api()); + await page.goto('/masternodes?mine=1'); + await expect(page.getByText('No starred masternodes yet')).toBeVisible(); + await page.getByRole('button', { name: 'Show all masternodes' }).click(); + await expect(page).not.toHaveURL(/mine=/); + await expect(rows(page)).toHaveCount(50); +}); diff --git a/client/src/App.tsx b/client/src/App.tsx index 1b4b0ee..06f8599 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -18,6 +18,7 @@ const BubblemapsPage = lazy(() => import('./pages/BubblemapsPage')); const NetworkPage = lazy(() => import('./pages/NetworkPage')); const NetworkHealthPage = lazy(() => import('./pages/NetworkHealthPage')); const MasternodesPage = lazy(() => import('./pages/MasternodesPage')); +const MasternodeDetailPage = lazy(() => import('./pages/MasternodeDetailPage')); const ProviderTagsPage = lazy(() => import('./pages/ProviderTagsPage')); const MasternodeHealthPage = lazy(() => import('./pages/MasternodeHealthPage')); const BanDetectionPage = lazy(() => import('./pages/BanDetectionPage')); @@ -87,6 +88,7 @@ export default function App() { )} /> } /> )} /> + )} /> )} /> } /> )} /> diff --git a/client/src/components/ui/FavoriteButton.css b/client/src/components/ui/FavoriteButton.css new file mode 100644 index 0000000..66a4a6f --- /dev/null +++ b/client/src/components/ui/FavoriteButton.css @@ -0,0 +1,71 @@ +.favorite-button-wrap { + position: relative; + display: inline-flex; + align-items: center; + flex-shrink: 0; + vertical-align: middle; +} + +.favorite-button { + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + border: 1px solid var(--border); + border-radius: 7px; + background: var(--surface-muted); + color: var(--text-muted); + font: inherit; + cursor: pointer; + transition: border-color 0.18s ease, color 0.18s ease; +} + +.favorite-button:hover { + border-color: var(--accent); + color: var(--accent); +} + +/* Starred is the visitor's own choice, not a node state, so it uses the accent colour. */ +.favorite-button.starred { + border-color: var(--accent); + color: var(--accent); +} + +.favorite-button svg { + width: 17px; + height: 17px; +} + +/* A small note above the button, like the copy button's, so nothing beside it reflows. */ +.favorite-button-status { + position: absolute; + left: 0; + bottom: calc(100% + 6px); + z-index: 2; + padding: 0.15rem 0.45rem; + border: 1px solid var(--border); + border-radius: 6px; + background: var(--surface); + color: var(--text); + font-family: var(--font-sans); + font-size: 0.72rem; + font-weight: 600; + line-height: 1.4; + white-space: nowrap; + pointer-events: none; +} + +.favorite-button-status:empty { + padding: 0; + border: 0; + background: transparent; +} + +@media (max-width: 768px) { + .favorite-button { + width: 40px; + height: 40px; + } +} diff --git a/client/src/components/ui/FavoriteButton.tsx b/client/src/components/ui/FavoriteButton.tsx new file mode 100644 index 0000000..051cf32 --- /dev/null +++ b/client/src/components/ui/FavoriteButton.tsx @@ -0,0 +1,44 @@ +import { useEffect, useRef, useState } from 'react'; +import { HiOutlineStar, HiStar } from 'react-icons/hi2'; +import { MAX_FAVORITES, useFavoriteMasternodes } from '../../utils/favoriteMasternodes'; +import './FavoriteButton.css'; + +const NOTICE_MS = 3000; + +/** + * A star that adds a masternode to "My nodes" or removes it. `label` names the node for screen + * readers ("Star 203.0.113.5:9999"); the pressed state says whether it is starred. A full list + * refuses the star and says so next to the button. + */ +export default function FavoriteButton({ proTxHash, label }: { proTxHash: string; label: string }) { + const { isFavorite, toggle } = useFavoriteMasternodes(); + const [notice, setNotice] = useState(''); + const timer = useRef(undefined); + useEffect(() => () => window.clearTimeout(timer.current), []); + + const starred = isFavorite(proTxHash); + const onClick = () => { + const result = toggle(proTxHash); + window.clearTimeout(timer.current); + setNotice(result === 'full' ? `My nodes is full (${MAX_FAVORITES}). Remove a star first.` : ''); + if (result === 'full') timer.current = window.setTimeout(() => setNotice(''), NOTICE_MS); + }; + + return ( + + + + {notice} + + + ); +} diff --git a/client/src/pages/BanDetectionPage.tsx b/client/src/pages/BanDetectionPage.tsx index d845509..089aa6c 100644 --- a/client/src/pages/BanDetectionPage.tsx +++ b/client/src/pages/BanDetectionPage.tsx @@ -3,6 +3,7 @@ import { Link, useSearchParams } from 'react-router-dom'; import { OperatorDiagnosisPanel, nodePermalink } from '../components/OperatorDiagnosisPanel'; import { BannedByPanel } from '../components/BannedByPanel'; import TimeText from '../components/ui/TimeText'; +import { isProTxHash, masternodePath } from '../utils/routes'; import { HiOutlineFire, HiOutlineBolt, @@ -554,7 +555,9 @@ export function BanDetectionPage() { {visibleNodes.map((node) => - + diff --git a/client/src/pages/MasternodeDetailPage.css b/client/src/pages/MasternodeDetailPage.css new file mode 100644 index 0000000..6a007e8 --- /dev/null +++ b/client/src/pages/MasternodeDetailPage.css @@ -0,0 +1,208 @@ +/* One masternode: identity, addresses and placement cards, then its PoSe history. */ + +.mnd-header-meta { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem 0.9rem; + margin-top: 0.5rem; +} + +.mnd-header-link { + font-size: 0.85rem; +} + +.mnd-note { + margin: 0.6rem 0 0; + color: var(--text-muted); + font-size: 0.82rem; +} + +/* Two cards side by side where both fit with room for an address, otherwise one under the other. */ +.mnd-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 440px), 1fr)); + gap: 1rem; + margin-bottom: 1rem; +} + +.mnd-card { + min-width: 0; +} + +.mnd-card .card-header { + margin-bottom: 0.5rem; +} + +.mnd-card-subtitle { + margin: 0.25rem 0 0; + color: var(--text-muted); + font-size: 0.82rem; +} + +.mnd-list { + margin: 0; +} + +.mnd-row { + display: grid; + grid-template-columns: 8.5rem minmax(0, 1fr); + gap: 0.75rem; + align-items: baseline; + padding: 0.6rem 0; + border-bottom: 1px solid var(--border-soft); +} + +.mnd-row:last-child { + border-bottom: 0; +} + +.mnd-row dt { + color: var(--text-muted); + font-size: 0.82rem; + font-weight: 600; +} + +.mnd-row dd { + min-width: 0; + margin: 0; + font-variant-numeric: tabular-nums; + overflow-wrap: anywhere; +} + +/* An identifier in full, wrapped where needed, with its copy button beside it. */ +.mnd-id { + display: inline-flex; + align-items: center; + gap: 0.5rem; + max-width: 100%; +} + +.mnd-id .mono { + min-width: 0; + overflow-wrap: anywhere; + word-break: break-all; +} + +.mnd-code { + margin-left: 0.45rem; + font-size: 0.76rem; +} + +/* A pasted value that is not a proTxHash can be long and unbroken: let it wrap. */ +.mnd-state .state-panel-description { + overflow-wrap: anywhere; +} + +.mnd-state-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 0.75rem; + margin-top: 0.75rem; +} + +.mnd-state-star { + display: inline-flex; + align-items: center; + gap: 0.5rem; + color: var(--text-muted); + font-size: 0.85rem; +} + +.mnd-events-wrap { + border: 1px solid var(--border); + border-radius: 12px; + background: var(--surface); +} + +.mnd-events { + width: 100%; +} + +.mnd-events thead th { + background: var(--surface-muted); +} + +.mnd-events thead th:first-child { + border-top-left-radius: 12px; +} + +.mnd-events thead th:last-child { + border-top-right-radius: 12px; +} + +.mnd-events tbody tr:last-child td { + border-bottom: 0; +} + +.mnd-events td { + font-variant-numeric: tabular-nums; + overflow-wrap: anywhere; +} + +@media (max-width: 768px) { + /* Touch targets of at least 40 px on phones. */ + .mnd-page .copy-button { + width: 40px; + height: 40px; + } + + .mnd-header-link { + display: inline-flex; + align-items: center; + min-height: 40px; + } + + /* Each event is a small card with labelled values. */ + .mnd-events-wrap { + border: 0; + background: transparent; + } + + .mnd-events, + .mnd-events tbody { + display: flex; + flex-direction: column; + gap: 0.55rem; + } + + .mnd-events thead { + display: none; + } + + .mnd-events tbody tr { + display: flex; + flex-direction: column; + gap: 0.25rem; + padding: 0.7rem 0.8rem; + border: 1px solid var(--border); + border-radius: 12px; + background: var(--surface); + } + + .mnd-events td { + display: block; + padding: 0; + border: 0; + font-size: 0.85rem; + } + + .mnd-events td[data-label]::before { + content: attr(data-label) ' '; + margin-right: 0.35rem; + color: var(--text-muted); + font-size: 0.68rem; + font-weight: 700; + letter-spacing: 0.04em; + text-transform: uppercase; + } +} + +@media (max-width: 520px) { + .mnd-row { + grid-template-columns: minmax(0, 1fr); + gap: 0.2rem; + } +} diff --git a/client/src/pages/MasternodeDetailPage.tsx b/client/src/pages/MasternodeDetailPage.tsx new file mode 100644 index 0000000..f89900e --- /dev/null +++ b/client/src/pages/MasternodeDetailPage.tsx @@ -0,0 +1,297 @@ +import type { ReactNode } from 'react'; +import { Link, Navigate, useParams } from 'react-router-dom'; +import { useQuery } from '@tanstack/react-query'; +import { HiOutlineServerStack } from 'react-icons/hi2'; +import { fetchActiveMasternodeVersions, fetchMasternodeDetail, fetchMasternodeNodeEvents } from '../services/api'; +import type { MasternodeDetailView } from '../types/api'; +import CopyButton from '../components/ui/CopyButton'; +import FavoriteButton from '../components/ui/FavoriteButton'; +import StatePanel from '../components/ui/StatePanel'; +import TimeText from '../components/ui/TimeText'; +import { formatNumber } from '../utils/formatters'; +import { addressPath, blockPath, isProTxHash, masternodePath } from '../utils/routes'; +import { useFavoriteMasternodes } from '../utils/favoriteMasternodes'; +import { registrationKey } from './masternodes/masternodeRows'; +import { describeEvent, eventsOfRegistration, statusName } from './masternodes/nodeEvents'; +import './PageStyles.css'; +import './masternodes/masternodeBadges.css'; +import './MasternodeDetailPage.css'; + +const EVENT_LIMIT = 50; + +export default function MasternodeDetailPage() { + const param = useParams().proTxHash ?? ''; + if (isProTxHash(param) && param !== param.toLowerCase()) return ; + // A new node gets a fresh view, so the previous node's details never show under the new address. + return ; +} + +function statusBadge(status: string) { + const key = status.toUpperCase(); + const tone = key === 'ENABLED' ? 'success' : key === 'POSE_PENALTY' ? 'warning' : key === 'POSE_BANNED' ? 'error' : ''; + return {statusName(status)}; +} + +function Row({ label, children }: { label: string; children: ReactNode }) { + return ( +
+
{label}
+
{children}
+
+ ); +} + +const muted = (text: string) => {text}; + +function Identifier({ value, label, to }: { value: string | null | undefined; label: string; to?: string }) { + if (!value) return muted('Unknown'); + return ( + + {to ? ( + {value} + ) : ( + {value} + )} + + + ); +} + +function Height({ height, none }: { height: number | null | undefined; none: string }) { + if (height == null || height <= 0) return muted(none); + return {formatNumber(height)}; +} + +function NotFound({ proTxHash, invalid }: { proTxHash: string; invalid: boolean }) { + const { isFavorite } = useFavoriteMasternodes(); + return ( +
+ + Open the Masternodes table + {!invalid && isFavorite(proTxHash) && ( + + In My nodes + + )} +
+ } + /> + + ); +} + +function VersionValue({ node }: { node: MasternodeDetailView }) { + const versionsQuery = useQuery({ + queryKey: ['masternodes', 'active-versions'], + queryFn: fetchActiveMasternodeVersions, + staleTime: 60_000, + }); + if (versionsQuery.isPending) return …; + if (!versionsQuery.data) return muted('Unavailable right now'); + // Matched by registration (proTxHash, else id) as in the table; never by IP. + const row = versionsQuery.data.nodes.find((entry) => entry.id === registrationKey(node)); + if (!row?.walletVersion) return muted('unknown'); + return ( + <> + {row.walletVersion} + {row.versionState === 'stale' && ( + stale + )} + + ); +} + +function PoseHistory({ node }: { node: MasternodeDetailView }) { + const eventsQuery = useQuery({ + queryKey: ['masternode', node.proTxHash, 'events', node.id], + queryFn: () => fetchMasternodeNodeEvents(node.id, EVENT_LIMIT), + staleTime: 60_000, + placeholderData: undefined, + }); + + let body: ReactNode; + if (eventsQuery.isPending) { + body = ; + } else if (eventsQuery.isError) { + body = ; + } else { + const { shown, hidden } = eventsOfRegistration(eventsQuery.data, node); + body = ( + <> + {shown.length === 0 ? ( + + ) : ( +
+
Node / ServiceBan eventsLast ban blockLast eventRecorded recoveryCurrent statePenaltyBan cause
{node.service || 'Unknown service'}
{truncateHash(node.proTxHash || node.nodeId, 8)}
{node.service || 'Unknown service'}{isProTxHash(node.proTxHash) + ?
{truncateHash(node.proTxHash, 8)}
+ :
{truncateHash(node.proTxHash || node.nodeId, 8)}
}
{node.banCount} {node.lastBanHeight != null ? {formatNumber(node.lastBanHeight)} : 'Unknown'}
+ + + + + + + + + + {shown.map((event, index) => ( + + + + + + + ))} + +
TimeEventBan blockRecovered
{describeEvent(event)} + {event.recoveredAt ? ( + <> + + {event.recoveredHeight != null && event.recoveredHeight > 0 && ( + <> · {formatNumber(event.recoveredHeight)} + )} + + ) : ( + muted('—') + )} +
+ + )} + {hidden > 0 && ( +

+ {hidden === 1 ? '1 stored event' : `${formatNumber(hidden)} stored events`} of this collateral{' '} + {hidden === 1 ? 'is' : 'are'} not shown: {hidden === 1 ? 'it belongs' : 'they belong'} to an earlier + registration or cannot be tied to this one. +

+ )} + + ); + } + + return ( +
+
+
+

PoSe history

+

+ Status changes, bans and recoveries recorded by the explorer. A ban shows the time of its ban block; other + changes show when the explorer recorded them. Block numbers come from the chain. Events are kept for 90 days; + the latest {EVENT_LIMIT} are shown. +

+
+
+ {body} +
+ ); +} + +function MasternodeDetailView({ proTxHash }: { proTxHash: string }) { + const valid = isProTxHash(proTxHash); + const { favorites, persistent } = useFavoriteMasternodes(); + const detailQuery = useQuery({ + queryKey: ['masternode', proTxHash], + queryFn: () => fetchMasternodeDetail(proTxHash), + enabled: valid, + staleTime: 60_000, + placeholderData: undefined, + }); + + if (!valid) return ; + if (detailQuery.isPending) return ; + if (detailQuery.isError) { + return ( + + ); + } + const node = detailQuery.data; + if (!node) return ; + + const service = node.service || node.ip || 'Unknown service'; + const tagged = node.providerSource === 'tag'; + + return ( +
+
+

+

+
+

{service}

+ +
+
+ {statusBadge(node.status)} + Open in PoSe Watch +
+ {!persistent && favorites.length > 0 && ( +

This browser does not allow saving here, so your stars are kept only until the page is reloaded or closed.

+ )} +
+ +
+
+

Identity

+
+ {service} + {statusBadge(node.status)} + + + + + + {node.registeredAt != null && node.registeredAt > 0 && ( + <> · + )} + + {node.posePenalty != null ? formatNumber(node.posePenalty) : muted('Unknown')} + + +
+
+ +
+

Addresses

+
+ + + + + +
+
+ +
+

Placement

+
+ + {node.countryName || muted('Unknown')} + {node.countryCode && {node.countryCode}} + + + {node.provider || muted('Unknown')} + {tagged ? 'Tagged' : 'Auto'} + {tagged && node.providerTagCidr && {node.providerTagCidr}} + + + {node.asn != null ? `AS${node.asn}` : muted('Unknown')} + {node.asnOrg && {node.asnOrg}} + +
+
+
+ + +
+ ); +} diff --git a/client/src/pages/MasternodesPage.tsx b/client/src/pages/MasternodesPage.tsx index 018bbf8..56c8d4f 100644 --- a/client/src/pages/MasternodesPage.tsx +++ b/client/src/pages/MasternodesPage.tsx @@ -102,6 +102,13 @@ export default function MasternodesPage() { [nodes], ); + // Every active registration, before the country or provider filter: the table uses it to tell a + // starred node hidden by that filter from one that is no longer active. + const activeRegistrations = useMemo( + () => new Set(activeNodes.flatMap((node) => (node.proTxHash ? [node.proTxHash.toLowerCase()] : []))), + [activeNodes], + ); + const visibleNodes = useMemo(() => { if (!activeFilter) return activeNodes; if (activeFilter.type === 'country') { @@ -271,6 +278,7 @@ export default function MasternodesPage() { error={nodesError} versionsLoading={versionsQuery.isPending} versionsUnavailable={versionsQuery.isError && !versionsQuery.data} + activeRegistrations={activeRegistrations} pageFilter={ activeFilter && ( <> diff --git a/client/src/pages/masternodes/MasternodeTable.css b/client/src/pages/masternodes/MasternodeTable.css index 407fd7e..8ec09d6 100644 --- a/client/src/pages/masternodes/MasternodeTable.css +++ b/client/src/pages/masternodes/MasternodeTable.css @@ -28,6 +28,25 @@ font-size: 0.82rem; } +/* The status chips and the "My nodes" toggle share one wrapping row. */ +.mn-filter-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; +} + +.mn-mine-toggle svg { + width: 14px; + height: 14px; +} + +.mn-table th.mn-col-star, +.mn-table td.mn-col-star { + width: 1%; + padding-right: 0; +} + .mn-table-wrap { border: 1px solid var(--border); border-radius: 12px; @@ -72,32 +91,6 @@ font-size: 0.76rem; } -.mn-source-tag { - display: inline-flex; - margin-left: 0.45rem; - padding: 0.05rem 0.4rem; - border: 1px solid var(--border); - border-radius: 999px; - color: var(--text-muted); - font-size: 0.66rem; - font-weight: 700; - letter-spacing: 0.04em; - text-transform: uppercase; - vertical-align: middle; -} - -.mn-source-tag.tagged { - border-color: rgba(43, 196, 138, 0.42); - color: var(--success); -} - -.mn-version-stale { - margin-left: 0.4rem; - color: var(--warning, var(--text-muted)); - font-size: 0.72rem; - font-weight: 600; -} - /* * Phones and narrow tablets: each row is a card; the header becomes a wrapping row of sort buttons. * The six columns need about 730 px, and the card is about 90 px narrower than the window, so the @@ -165,9 +158,10 @@ font-size: 0.82rem; } + /* The address takes what the status and the star leave on the first line. */ .mn-table td.mn-col-service { - flex: 1 1 60%; - min-width: 0; + flex: 1 1 0%; + min-width: 8rem; } .mn-table .mn-col-service .mono { @@ -201,6 +195,23 @@ order: 0; } + /* The star needs no sort button in the header row of the card view. */ + .mn-table thead th.mn-col-star { + display: none; + } + + /* The star ends the first line, after the status, so the address keeps the card's left edge. */ + .mn-table td.mn-col-star { + order: 2; + flex: 0 0 auto; + width: auto; + padding: 0; + } + + .mn-table td.mn-col-star:empty { + display: none; + } + .mn-table td.mn-col-status { order: 1; } diff --git a/client/src/pages/masternodes/MasternodeTable.tsx b/client/src/pages/masternodes/MasternodeTable.tsx index 258ef1e..cc52ad4 100644 --- a/client/src/pages/masternodes/MasternodeTable.tsx +++ b/client/src/pages/masternodes/MasternodeTable.tsx @@ -1,15 +1,19 @@ import { useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'; import { Link, useSearchParams } from 'react-router-dom'; +import { HiStar } from 'react-icons/hi2'; +import FavoriteButton from '../../components/ui/FavoriteButton'; import FilterChips from '../../components/ui/FilterChips'; import Pager from '../../components/ui/Pager'; import SearchField from '../../components/ui/SearchField'; import SortHeader from '../../components/ui/SortHeader'; import StatePanel from '../../components/ui/StatePanel'; import { formatNumber, truncateHash } from '../../utils/formatters'; -import { addressPath } from '../../utils/routes'; +import { addressPath, masternodePath } from '../../utils/routes'; +import { useFavoriteMasternodes } from '../../utils/favoriteMasternodes'; import { PAGE_SIZE, filterRows, + isStarred, pageCount, readTableState, sortRows, @@ -20,6 +24,7 @@ import { type TableState, UNKNOWN_VERSION, } from './masternodeRows'; +import './masternodeBadges.css'; import './MasternodeTable.css'; interface MasternodeTableProps { @@ -32,6 +37,11 @@ interface MasternodeTableProps { versionsUnavailable: boolean; /** A country or provider filter chosen on the page (a ranking row), shown with a way to clear it. */ pageFilter?: ReactNode; + /** + * Lower-case proTxHashes of every active node, before the page's country or provider filter. + * Tells a starred node hidden by that filter from one that is not active at all. + */ + activeRegistrations?: ReadonlySet; } const COLUMNS: Array<{ key: SortKey; label: string }> = [ @@ -82,7 +92,7 @@ function VersionCell({ row, pending }: { row: MasternodeRow; pending: boolean }) /** * Active masternodes with search, status filter, sortable columns and 50-row pages. The search, * filter, sort and page live in the URL (`?q=&status=&sort=&page=`), so a view can be shared and - * survives a reload. + * survives a reload. A star marks a node as the visitor's own; "My nodes" (`?mine=1`) shows only those. */ export default function MasternodeTable({ rows, @@ -91,9 +101,12 @@ export default function MasternodeTable({ versionsLoading, versionsUnavailable, pageFilter, + activeRegistrations, }: MasternodeTableProps) { const [params, setParams] = useSearchParams(); const state = readTableState(params); + const { favorites, persistent } = useFavoriteMasternodes(); + const favoriteSet = useMemo(() => new Set(favorites), [favorites]); const cardRef = useRef(null); const headerHeight = useSiteHeaderHeight(); @@ -141,11 +154,22 @@ export default function MasternodeTable({ window.scrollTo({ top: card.getBoundingClientRect().top + window.scrollY - siteHeader }); }, [showingRows]); + // "My nodes" narrows the table to the starred registrations before any search or filter. + const starredRows = useMemo(() => rows.filter((row) => isStarred(row, favoriteSet)), [rows, favoriteSet]); + const scope = state.mine ? starredRows : rows; // While waiting for the versions nothing is matched yet, so the status counts claim nothing either. const searched = useMemo( - () => (waitingForVersions ? [] : filterRows(rows, state.q, 'all', state.version)), - [rows, state.q, state.version, waitingForVersions], + () => (waitingForVersions ? [] : filterRows(scope, state.q, 'all', state.version)), + [scope, state.q, state.version, waitingForVersions], ); + // Starred registrations that are not in the active list at all (banned, removed or registered + // again); a node hidden only by the page's country or provider filter is still active. + const activeKeys = useMemo( + () => activeRegistrations ?? new Set(rows.flatMap((row) => (row.proTxHash ? [row.proTxHash.toLowerCase()] : []))), + [activeRegistrations, rows], + ); + const starredElsewhere = useMemo(() => favorites.filter((id) => !activeKeys.has(id)), [favorites, activeKeys]); + const starredHiddenByPageFilter = starredRows.length === 0 && favorites.some((id) => activeKeys.has(id)); const matched = useMemo(() => filterRows(searched, '', state.status), [searched, state.status]); const sorted = useMemo(() => sortRows(matched, state.sort, state.dir), [matched, state.sort, state.dir]); const pages = pageCount(sorted.length); @@ -183,6 +207,37 @@ export default function MasternodeTable({ description={pageFilter ? 'No active masternode matches the chosen country or provider.' : 'The current snapshot lists no active masternode.'} /> ); + } else if (state.mine && favorites.length === 0) { + body = ( + update({ mine: false, page: 1 })}> + Show all masternodes + + } + /> + ); + } else if (state.mine && starredHiddenByPageFilter) { + body = ( + + ); + } else if (state.mine && starredRows.length === 0) { + body = ( + update({ mine: false, page: 1 })}> + Show all masternodes + + } + /> + ); } else if (matched.length === 0) { body = ( { window.clearTimeout(pendingSearch.current); - update({ q: '', status: 'all', version: '', page: 1 }); + update({ q: '', status: 'all', version: '', mine: false, page: 1 }); }} > Clear search and filter @@ -209,6 +264,9 @@ export default function MasternodeTable({ + {COLUMNS.map((column) => ( {visible.map((row) => ( +
+ Star +
+ {row.proTxHash && } + - {row.service} + {row.proTxHash ? ( + {row.service} + ) : ( + {row.service} + )} @@ -298,8 +363,33 @@ export default function MasternodeTable({ value={draft} onChange={onSearch} /> - update({ status, page: 1 })} /> +
+ update({ status, page: 1 })} /> + +
+ {state.mine && showingRows && starredElsewhere.length > 0 && ( +

+ Starred but not in the active list:{' '} + {starredElsewhere.map((id, index) => ( + + {index > 0 && ', '} + {truncateHash(id, 6)} + + ))} +

+ )} + {!persistent && favorites.length > 0 && ( +

This browser does not allow saving here, so your stars are kept only until the page is reloaded or closed.

+ )} {versionsUnavailable && !loading && !error && (

Versions are unavailable right now, so every version shows as unknown.

)} diff --git a/client/src/pages/masternodes/masternodeBadges.css b/client/src/pages/masternodes/masternodeBadges.css new file mode 100644 index 0000000..b2bac09 --- /dev/null +++ b/client/src/pages/masternodes/masternodeBadges.css @@ -0,0 +1,27 @@ +/* Small labels shared by the masternode table and the masternode page. */ + +.mn-source-tag { + display: inline-flex; + margin-left: 0.45rem; + padding: 0.05rem 0.4rem; + border: 1px solid var(--border); + border-radius: 999px; + color: var(--text-muted); + font-size: 0.66rem; + font-weight: 700; + letter-spacing: 0.04em; + text-transform: uppercase; + vertical-align: middle; +} + +.mn-source-tag.tagged { + border-color: color-mix(in oklab, var(--success) 42%, transparent); + color: var(--success); +} + +.mn-version-stale { + margin-left: 0.4rem; + color: var(--warning, var(--text-muted)); + font-size: 0.72rem; + font-weight: 600; +} diff --git a/client/src/pages/masternodes/masternodeRows.ts b/client/src/pages/masternodes/masternodeRows.ts index 00df46b..11133ee 100644 --- a/client/src/pages/masternodes/masternodeRows.ts +++ b/client/src/pages/masternodes/masternodeRows.ts @@ -16,6 +16,8 @@ export interface TableState { sort: SortKey; dir: SortDirection; page: number; + /** Only the visitor's starred masternodes ("My nodes"). */ + mine: boolean; } export interface MasternodeRow { @@ -38,7 +40,7 @@ export interface MasternodeRow { export const PAGE_SIZE = 50; const SORT_KEYS: SortKey[] = ['service', 'status', 'version', 'country', 'provider', 'payout']; const STATUS_FILTERS: StatusFilter[] = ['all', 'enabled', 'pose_penalty']; -export const DEFAULT_STATE: TableState = { q: '', status: 'all', version: '', sort: 'service', dir: 'asc', page: 1 }; +export const DEFAULT_STATE: TableState = { q: '', status: 'all', version: '', sort: 'service', dir: 'asc', page: 1, mine: false }; export const UNKNOWN_VERSION = 'unknown'; /** @@ -109,6 +111,7 @@ export function readTableState(params: URLSearchParams): TableState { sort: SORT_KEYS.includes(sort) ? sort : DEFAULT_STATE.sort, dir: SORT_KEYS.includes(sort) ? dir : DEFAULT_STATE.dir, page: Number.isSafeInteger(page) && page >= 1 ? page : DEFAULT_STATE.page, + mine: params.get('mine') === '1', }; } @@ -121,6 +124,7 @@ export function writeTableState(params: URLSearchParams, state: TableState): URL set('version', state.version, DEFAULT_STATE.version); set('sort', `${state.dir === 'desc' ? '-' : ''}${state.sort}`, DEFAULT_STATE.sort); set('page', String(state.page), String(DEFAULT_STATE.page)); + set('mine', state.mine ? '1' : '', ''); return next; } @@ -141,6 +145,11 @@ export function filterRows(rows: MasternodeRow[], q: string, status: StatusFilte }); } +/** Whether the row's registration is starred; a row without a proTxHash cannot be starred. */ +export function isStarred(row: Pick, favorites: ReadonlySet): boolean { + return row.proTxHash != null && favorites.has(row.proTxHash.toLowerCase()); +} + function compareNumbers(a: number[], b: number[]): number { for (let index = 0; index < Math.max(a.length, b.length); index += 1) { const diff = (a[index] ?? 0) - (b[index] ?? 0); diff --git a/client/src/pages/masternodes/nodeEvents.ts b/client/src/pages/masternodes/nodeEvents.ts new file mode 100644 index 0000000..33ad775 --- /dev/null +++ b/client/src/pages/masternodes/nodeEvents.ts @@ -0,0 +1,53 @@ +import type { MasternodeDetailView, MasternodeNodeEventView } from '../../types/api'; + +/** + * The events endpoint answers by node id, which is the collateral outpoint. A collateral can be + * registered again under a new proTxHash, so its stored events may belong to an earlier + * registration. Ban and recovery records name their proTxHash; plain status changes do not, so + * those count only from this registration's own registration time. Anything that cannot be tied + * to this registration is left out and counted, never shown as its history. + * `registeredAt` is the registering block's time, or an estimate from its height when that block + * is not indexed, and the poller stamps `detectedAt` with its own clock: near the boundary a + * status change can fall on the wrong side by minutes. Without a registration time none counts. + */ +export function eventsOfRegistration( + events: MasternodeNodeEventView[], + node: Pick, +): { shown: MasternodeNodeEventView[]; hidden: number } { + const proTxHash = (node.proTxHash ?? '').toLowerCase(); + const registeredMs = node.registeredAt != null && node.registeredAt > 0 ? node.registeredAt * 1000 : null; + const shown: MasternodeNodeEventView[] = []; + let hidden = 0; + for (const event of events) { + const eventProTx = event.proTxHash ? event.proTxHash.toLowerCase() : null; + if (eventProTx) { + if (eventProTx === proTxHash) shown.push(event); + else hidden += 1; + continue; + } + const detectedMs = Date.parse(event.detectedAt); + if (registeredMs != null && Number.isFinite(detectedMs) && detectedMs >= registeredMs) shown.push(event); + else hidden += 1; + } + return { shown, hidden }; +} + +const STATUS_NAMES: Record = { + ENABLED: 'Enabled', + POSE_PENALTY: 'PoSe Penalty', + POSE_BANNED: 'PoSe Banned', + NEW: 'First seen', + REMOVED: 'Removed', +}; + +export function statusName(status: string | null | undefined): string { + const key = String(status ?? '').trim().toUpperCase(); + return STATUS_NAMES[key] ?? (key || 'Unknown'); +} + +/** What the stored event records, in words; it adds no cause or diagnosis. */ +export function describeEvent(event: MasternodeNodeEventView): string { + if (event.eventType === 'ban') return event.eventStatus === 'recovered' ? 'PoSe ban, later recovered' : 'PoSe ban'; + if (event.eventType === 'recovery') return 'Recovery'; + return `${statusName(event.previousStatus)} → ${statusName(event.currentStatus)}`; +} diff --git a/client/src/services/api.ts b/client/src/services/api.ts index 6da0aa2..7f5a60d 100644 --- a/client/src/services/api.ts +++ b/client/src/services/api.ts @@ -1,6 +1,12 @@ import axios from 'axios'; import type { OperatorDiagnosisData } from '@defcon/shared/dist/contracts'; -import { banAttributionApiResponseSchema, poseObservedEventsApiResponseSchema, dnsSeederNodesApiResponseSchema } from '@defcon/shared'; +import { + banAttributionApiResponseSchema, + poseObservedEventsApiResponseSchema, + dnsSeederNodesApiResponseSchema, + masternodeDetailApiResponseSchema, + masternodeNodeEventsApiResponseSchema, +} from '@defcon/shared'; import type { BanAttributionQuery, BanAttributionProof } from '@defcon/shared/dist/contracts'; import type { ActiveMasternodeVersionsView, @@ -75,6 +81,43 @@ export async function fetchPoseChainSummary(params: { hours: number; since?: str return data.data; } +/** The request reached the API and it answered that the item does not exist. */ +export function isNotFoundError(error: unknown): boolean { + return axios.isAxiosError(error) && error.response?.status === 404; +} + +/** + * One masternode registration by proTxHash, or null when the snapshot does not list it (404). + * The answer must name the same registration. + */ +export async function fetchMasternodeDetail(proTxHash: string) { + const wanted = proTxHash.toLowerCase(); + try { + const { data } = await api.get(`/v1/masternodes/${encodeURIComponent(wanted)}`); + const parsed = masternodeDetailApiResponseSchema.safeParse(data); + if (!parsed.success) throw new Error('The masternode answer could not be read'); + const node = parsed.data.data; + if ((node.proTxHash ?? '').toLowerCase() !== wanted) throw new Error('Masternode identity mismatch'); + return node; + } catch (error) { + if (isNotFoundError(error)) return null; + throw error; + } +} + +/** + * The stored events of one node id (its collateral outpoint), newest first. Every event must + * belong to that node id; which of them belong to one registration is decided by the caller. + */ +export async function fetchMasternodeNodeEvents(nodeId: string, limit = 50) { + const { data } = await api.get(`/v1/masternodes/${encodeURIComponent(nodeId)}/events`, { params: { limit } }); + const parsed = masternodeNodeEventsApiResponseSchema.safeParse(data); + if (!parsed.success) throw new Error('The masternode events could not be read'); + const events = parsed.data.data; + if (events.some((event) => event.nodeId !== nodeId)) throw new Error('Masternode event identity mismatch'); + return events; +} + export async function fetchActiveMasternodeVersions() { const { data } = await api.get>('/v1/node-inventory/active-versions'); return data.data; diff --git a/client/src/types/api.ts b/client/src/types/api.ts index ce49160..90476b7 100644 --- a/client/src/types/api.ts +++ b/client/src/types/api.ts @@ -20,6 +20,8 @@ import type { MasternodeHealthTimelinePointContract, MasternodeListItemContract, MasternodeNodeContract, + MasternodeDetailContract, + MasternodeNodeEventContract, MasternodeNodesContract, MasternodeOffenderContract, MasternodePayloadContract, @@ -438,6 +440,10 @@ export interface PreReleaseNodeView { export type MasternodeCountryView = MasternodeCountryContract; export type MasternodeProviderView = MasternodeProviderContract; export type MasternodeView = MasternodeNodeContract; +/** One node from `/v1/masternodes/:id`, with its PoSe and key fields. */ +export type MasternodeDetailView = MasternodeDetailContract; +/** One stored event from `/v1/masternodes/:id/events`. */ +export type MasternodeNodeEventView = MasternodeNodeEventContract; export type MasternodeAnalyticsView = MasternodeAnalyticsContract; export type MasternodesView = MasternodePayloadContract; export type MasternodeListItemView = MasternodeListItemContract; diff --git a/client/src/utils/favoriteMasternodes.ts b/client/src/utils/favoriteMasternodes.ts new file mode 100644 index 0000000..6c64f34 --- /dev/null +++ b/client/src/utils/favoriteMasternodes.ts @@ -0,0 +1,122 @@ +import { useSyncExternalStore } from 'react'; + +/** + * The visitor's starred masternodes ("My nodes"): a list of proTxHashes kept in this browser. + * Every storage access is guarded: when the browser refuses storage, the stars still work until + * the page is reloaded and `persistent` is false, so the page can say they will not be kept. + */ +export const FAVORITES_KEY = 'deftrack-fav-masternodes'; +export const MAX_FAVORITES = 50; + +const PRO_TX = /^[0-9a-f]{64}$/; + +interface FavoritesSnapshot { + list: readonly string[]; + /** False when the list lives only in this tab because the browser storage cannot be used. */ + persistent: boolean; +} + +/** Set once storage fails; from then on this tab keeps the list in memory. */ +let memory: string[] | null = null; +let snapshot: FavoritesSnapshot | null = null; +const listeners = new Set<() => void>(); +let watchingOtherTabs = false; + +/** Lower-case proTxHashes, without duplicates, at most MAX_FAVORITES; anything else is dropped. */ +function clean(value: unknown): string[] { + const list: string[] = []; + if (!Array.isArray(value)) return list; + for (const item of value) { + const id = typeof item === 'string' ? item.toLowerCase() : ''; + if (PRO_TX.test(id) && !list.includes(id)) list.push(id); + if (list.length === MAX_FAVORITES) break; + } + return list; +} + +function load(): FavoritesSnapshot { + if (memory) return { list: memory, persistent: false }; + let raw: string | null; + try { + raw = window.localStorage.getItem(FAVORITES_KEY); + } catch { + memory = []; + return { list: memory, persistent: false }; + } + try { + // A damaged value counts as an empty list; it is replaced on the next change. + return { list: clean(raw ? JSON.parse(raw) : []), persistent: true }; + } catch { + return { list: [], persistent: true }; + } +} + +function current(): FavoritesSnapshot { + if (!snapshot) snapshot = load(); + return snapshot; +} + +function emit() { + for (const listener of listeners) listener(); +} + +function onOtherTab(event: StorageEvent) { + if (event.key !== null && event.key !== FAVORITES_KEY) return; + if (memory) return; + snapshot = null; + emit(); +} + +function subscribe(listener: () => void) { + listeners.add(listener); + if (!watchingOtherTabs) { + watchingOtherTabs = true; + window.addEventListener('storage', onOtherTab); + } + return () => { + listeners.delete(listener); + }; +} + +export type FavoriteToggle = 'added' | 'removed' | 'full' | 'invalid'; + +/** Stars or unstars a proTxHash. A full list (MAX_FAVORITES) refuses a new star rather than dropping one. */ +export function toggleFavorite(proTxHash: string): FavoriteToggle { + const id = proTxHash.toLowerCase(); + if (!PRO_TX.test(id)) return 'invalid'; + const { list } = current(); + let next: string[]; + let result: FavoriteToggle; + if (list.includes(id)) { + next = list.filter((item) => item !== id); + result = 'removed'; + } else if (list.length >= MAX_FAVORITES) { + return 'full'; + } else { + next = [...list, id]; + result = 'added'; + } + let persistent = false; + if (!memory) { + try { + window.localStorage.setItem(FAVORITES_KEY, JSON.stringify(next)); + persistent = true; + } catch { + persistent = false; + } + } + if (!persistent) memory = next; + snapshot = { list: next, persistent }; + emit(); + return result; +} + +export function useFavoriteMasternodes() { + const { list, persistent } = useSyncExternalStore(subscribe, current, current); + return { + favorites: list, + persistent, + isFavorite: (proTxHash: string | null | undefined) => Boolean(proTxHash) && list.includes(proTxHash!.toLowerCase()), + toggle: toggleFavorite, + }; +} diff --git a/client/src/utils/routes.ts b/client/src/utils/routes.ts index 8c4744d..75d5d41 100644 --- a/client/src/utils/routes.ts +++ b/client/src/utils/routes.ts @@ -11,6 +11,15 @@ export function addressPath(address: string): string { return `/address/${encodeURIComponent(address)}`; } +/** A masternode registration is named by its proTxHash (64 hex characters). */ +export function isProTxHash(value: string | null | undefined): value is string { + return /^[0-9a-fA-F]{64}$/.test(value ?? ''); +} + +export function masternodePath(proTxHash: string): string { + return `/masternode/${encodeURIComponent(proTxHash.toLowerCase())}`; +} + /** The search page resolves a free-text query and moves on to one of the paths above. */ export function searchPath(query: string): string { return `/search?q=${encodeURIComponent(query)}`; diff --git a/server/test/masternodes.v1.routes.test.ts b/server/test/masternodes.v1.routes.test.ts index 13d299c..d27a2ca 100644 --- a/server/test/masternodes.v1.routes.test.ts +++ b/server/test/masternodes.v1.routes.test.ts @@ -1,8 +1,11 @@ import express from 'express'; import request from 'supertest'; +import { Types } from 'mongoose'; import { banWaveAnalysisApiResponseSchema, + masternodeDetailApiResponseSchema, masternodeEventsApiResponseSchema, + masternodeNodeEventsApiResponseSchema, } from '@defcon/shared/dist/contracts'; import masternodesV1Routes from '../src/routes/v1/masternodes.v1.routes'; import { getEnrichedNodes } from '../src/services/masternode.service'; @@ -270,3 +273,151 @@ describe('masternodes v1 ban wave history', () => { }); }); }); + +describe('masternodes v1 per-node routes', () => { + const app = express(); + app.use('/api/v1/masternodes', masternodesV1Routes); + const proTxHash = 'b'.repeat(64); + const node = { + id: `${'c'.repeat(64)}-1`, + service: '203.0.113.20:8192', + ip: '203.0.113.20', + port: 8192, + status: 'ENABLED', + protocol: 70242, + lastSeen: null, + activeSeconds: 3_600, + isTor: false, + countryCode: 'DE', + countryName: 'Germany', + proTxHash, + ownerAddress: 'DownerAddress', + payoutAddress: 'DpayoutAddress', + collateralAddress: 'DcollateralAddress', + registeredHeight: 120_000, + registeredAt: 1_725_000_000, + poseBanHeight: null, + poseBanAt: null, + poseRevivedHeight: 125_000, + posePenalty: 12, + operatorPubkey: 'operator-key', + votingAddress: 'DvotingAddress', + collateralAmount: 10_000, + provider: 'Example Host', + providerSource: 'mmdb' as const, + asn: 64_500, + asnOrg: 'Example Host AS', + providerTagCidr: null, + providerTagSource: null, + providerConfidence: null, + providerEvidenceUrl: null, + }; + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('returns one node by proTxHash in the shared detail contract, and 404 for an unknown one', async () => { + vi.mocked(getEnrichedNodes).mockResolvedValue([node] as never); + + const res = await request(app).get(`/api/v1/masternodes/${proTxHash}`); + expect(res.status).toBe(200); + const parsed = masternodeDetailApiResponseSchema.safeParse(res.body); + expect(parsed.success).toBe(true); + expect(res.body.data).toMatchObject({ id: node.id, proTxHash, posePenalty: 12, poseRevivedHeight: 125_000 }); + + const missing = await request(app).get(`/api/v1/masternodes/${'d'.repeat(64)}`); + expect(missing.status).toBe(404); + }); + + it('keeps serving /events when a stored ban has recovered, whose recoveredAt is still a Date', async () => { + const detectedAt = new Date(Date.now() - 30 * 60 * 1000); + const recoveredAt = new Date(Date.now() - 10 * 60 * 1000); + const query = { + sort: vi.fn().mockReturnThis(), + limit: vi.fn().mockReturnThis(), + lean: vi.fn().mockResolvedValue([ + { + _id: new Types.ObjectId(), + nodeId: node.id, + service: node.service, + previousStatus: 'POSE_BAN_HEIGHT', + currentStatus: 'ENABLED', + detectedAt, + eventType: 'ban', + eventStatus: 'recovered', + proTxHash, + poseBanHeight: 124_000, + detectedHeight: 124_000, + recoveredAt, + recoveredHeight: 125_000, + recoveryTransition: 'POSE_BANNED -> ENABLED', + updatedAt: recoveredAt, + }, + ]), + }; + vi.spyOn(MasternodeEvent, 'find').mockReturnValue(query as never); + + // A query of its own, so the route's short cache cannot answer from another test. + const res = await request(app).get('/api/v1/masternodes/events').query({ hours: 2, limit: 20 }); + expect(res.status).toBe(200); + expect(masternodeEventsApiResponseSchema.safeParse(res.body).success).toBe(true); + expect(res.body.data.events[0]).toMatchObject({ recoveredAt: recoveredAt.toISOString(), poseBanHeight: 124_000 }); + }); + + it('returns the stored events of the node id in the shared event contract', async () => { + vi.mocked(getEnrichedNodes).mockResolvedValue([node] as never); + const detectedAt = new Date('2026-11-01T10:00:00.000Z'); + const recoveredAt = new Date('2026-11-02T10:00:00.000Z'); + const query = { + sort: vi.fn().mockReturnThis(), + limit: vi.fn().mockReturnThis(), + lean: vi.fn().mockResolvedValue([ + { + _id: new Types.ObjectId(), + __v: 0, + nodeId: node.id, + service: node.service, + previousStatus: 'POSE_BAN_HEIGHT', + currentStatus: 'POSE_BANNED', + detectedAt, + eventKey: `ban:${proTxHash}:124000`, + eventType: 'ban', + eventStatus: 'recovered', + proTxHash, + poseBanHeight: 124_000, + detectedHeight: 124_000, + recoveredAt, + recoveredHeight: 125_000, + recoveryTransition: 'POSE_BANNED->ENABLED', + updatedAt: recoveredAt, + }, + { + _id: new Types.ObjectId(), + nodeId: node.id, + service: '', + previousStatus: 'ENABLED', + currentStatus: 'POSE_PENALTY', + detectedAt, + eventType: 'status', + eventStatus: 'observed', + proTxHash: null, + }, + ]), + }; + const find = vi.spyOn(MasternodeEvent, 'find').mockReturnValue(query as never); + + const res = await request(app).get(`/api/v1/masternodes/${encodeURIComponent(node.id)}/events`).query({ limit: 50 }); + expect(res.status).toBe(200); + expect(find).toHaveBeenCalledWith({ nodeId: node.id }); + expect(masternodeNodeEventsApiResponseSchema.safeParse(res.body).success).toBe(true); + expect(res.body.data[0]).toMatchObject({ + proTxHash, + eventType: 'ban', + poseBanHeight: 124_000, + recoveredAt: recoveredAt.toISOString(), + detectedAt: detectedAt.toISOString(), + }); + expect(typeof res.body.data[0]._id).toBe('string'); + }); +}); diff --git a/server/test/routeSeo.test.ts b/server/test/routeSeo.test.ts index 94de556..bc2a77f 100644 --- a/server/test/routeSeo.test.ts +++ b/server/test/routeSeo.test.ts @@ -21,6 +21,8 @@ describe('shared route SEO metadata', () => { expect(resolveRouteSeo('/block/108705').title).toContain('Block Details'); expect(resolveRouteSeo('/tx/example').title).toContain('Transaction Details'); expect(resolveRouteSeo('/address/example').title).toContain('Address Details'); + expect(resolveRouteSeo(`/masternode/${'a'.repeat(64)}`).title).toContain('Masternode Details'); + expect(resolveRouteSeo('/masternodes').title).not.toContain('Masternode Details'); }); it('uses the redirect target as the canonical URL', () => { diff --git a/shared/src/contracts/masternodes.ts b/shared/src/contracts/masternodes.ts index 97fec3f..235971c 100644 --- a/shared/src/contracts/masternodes.ts +++ b/shared/src/contracts/masternodes.ts @@ -1,10 +1,13 @@ import { z } from 'zod'; import { apiSuccessSchema } from './api'; +import { masternodeEventSchema } from './pose'; const finiteNumber = z.number().finite(); const integer = z.number().int(); const nullableInteger = integer.nullable(); const providerSourceSchema = z.enum(['tor', 'cache', 'ptr', 'mmdb', 'ipapi', 'tag', 'unknown']); +const nullableText = z.string().nullable(); +const isoDateTime = z.string().datetime({ offset: true }); export const masternodeCountrySchema = z.object({ countryCode: z.string(), @@ -149,7 +152,41 @@ export const masternodeNodesSchema = masternodeSnapshotMetaSchema.extend({ nodes: z.array(masternodeListItemSchema), }); +/** + * `GET /api/v1/masternodes/:id`: one node of the snapshot, found by id (collateral outpoint) or + * proTxHash, with the PoSe and key fields the snapshot node also carries. + */ +export const masternodeDetailSchema = masternodeNodeSchema + .extend({ + posePenalty: finiteNumber.optional(), + poseRevivedHeight: nullableInteger.optional(), + operatorPubkey: z.string().nullable().optional(), + votingAddress: z.string().nullable().optional(), + }) + .passthrough(); + export const masternodeApiResponseSchema = apiSuccessSchema(masternodePayloadSchema); +export const masternodeDetailApiResponseSchema = apiSuccessSchema(masternodeDetailSchema); +/** + * One event as `GET /api/v1/masternodes/:id/events` sends it: the stored document as JSON, so every + * date is ISO text. Ban and recovery records name their registration (proTxHash); plain status + * changes carry null there. Kept apart from the shared event schema, which `/events` validates + * before its dates are turned into text. + */ +export const masternodeNodeEventSchema = masternodeEventSchema + .extend({ + proTxHash: nullableText.optional(), + eventType: nullableText.optional(), + eventStatus: nullableText.optional(), + poseBanHeight: nullableInteger.optional(), + detectedHeight: nullableInteger.optional(), + recoveredAt: isoDateTime.nullable().optional(), + recoveredHeight: nullableInteger.optional(), + }) + .passthrough(); + +/** `GET /api/v1/masternodes/:id/events`: the stored events of one node id, newest first. */ +export const masternodeNodeEventsApiResponseSchema = apiSuccessSchema(z.array(masternodeNodeEventSchema)); export const masternodeSummaryApiResponseSchema = apiSuccessSchema(masternodeSummarySchema); export const masternodeDistributionApiResponseSchema = apiSuccessSchema(masternodeDistributionSchema); export const masternodeNodesApiResponseSchema = apiSuccessSchema(masternodeNodesSchema); @@ -157,6 +194,8 @@ export const masternodeNodesApiResponseSchema = apiSuccessSchema(masternodeNodes export type MasternodeCountryContract = z.infer; export type MasternodeProviderContract = z.infer; export type MasternodeNodeContract = z.infer; +export type MasternodeDetailContract = z.infer; +export type MasternodeNodeEventContract = z.infer; export type MasternodeAnalyticsContract = z.infer; export type MasternodePayloadContract = z.infer; export type MasternodeSummaryContract = z.infer; diff --git a/shared/src/index.ts b/shared/src/index.ts index 88e91fc..87c9221 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -3,6 +3,7 @@ export * from './constants'; export { banAttributionApiResponseSchema } from './contracts/banAttribution'; export { poseObservedEventsApiResponseSchema } from './contracts/poseTelemetry'; export { dnsSeederNodesApiResponseSchema } from './contracts/dnsSeeder'; +export { masternodeDetailApiResponseSchema, masternodeNodeEventsApiResponseSchema } from './contracts/masternodes'; export type { DnsSeederNodeContract, DnsSeederNodesApiResponse } from './contracts/dnsSeeder'; export type { ActiveMasternodeVersionsContract, @@ -13,6 +14,8 @@ export type { MasternodeAnalyticsContract, MasternodeApiResponse, MasternodeCountryContract, + MasternodeDetailContract, + MasternodeNodeEventContract, MasternodeDistributionApiResponse, MasternodeDistributionContract, MasternodeListItemContract, diff --git a/shared/src/routeSeo.ts b/shared/src/routeSeo.ts index e1e2681..7628f11 100644 --- a/shared/src/routeSeo.ts +++ b/shared/src/routeSeo.ts @@ -171,6 +171,15 @@ const prefixRoutes: Array<{ prefix: string; seo: RouteSeo }> = [ robots: DEFAULT_ROBOTS, }, }, + { + prefix: '/masternode/', + seo: { + title: 'Masternode Details | DefTrack DeFCoN Explorer', + description: 'Inspect one DeFCoN masternode: status, payout and owner addresses, hosting, version and PoSe history.', + keywords: 'DeFCoN masternode, DFCN masternode details, proTxHash, PoSe history', + robots: DEFAULT_ROBOTS, + }, + }, { prefix: '/address/', seo: {