From 4eef13b151ddbee48fef4f83c354d823f9e2dfe1 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 18:13:19 -0500 Subject: [PATCH 01/15] feat(testnet): read InstantSend locks from the DAPI bloom stream trpc.digitalcash.dev is stuck on Core v23 and stops serving IS locks after the testnet V24 fork (block 1,578,000), so the bridge hung waiting for the lock. Testnet now uses the existing DAPI subscription path with an explicit snapshot of healthy evonodes, which skips dapi-client's seed/SML discovery (broken on V24 CbTx v4 coinbases). - TESTNET: drop rpcUrl, add 15 explicit https://:1443 dapiAddresses - dapi.ts: remove the implicit testnet JSON-RPC default so hasRpcUrl is false and no request goes to any digitalcash.dev host - tests: pin testnet to the subscription path; JSON-RPC deadline tests now use mainnet Co-Authored-By: Claude Sonnet 5.5 --- src/api/dapi.ts | 3 ++- src/api/islock.test.ts | 22 +++++++++++++++++++++- src/api/islock.ts | 13 +++++++------ src/api/network-status.ts | 4 ++-- src/api/request-deadlines.test.ts | 6 +++--- src/config.ts | 24 +++++++++++++++++++++++- 6 files changed, 58 insertions(+), 14 deletions(-) diff --git a/src/api/dapi.ts b/src/api/dapi.ts index 3b72a7c..c16ccac 100644 --- a/src/api/dapi.ts +++ b/src/api/dapi.ts @@ -7,8 +7,9 @@ import { describeIslock } from '../utils/islock-debug.js'; import { abortableSleep } from '../utils/sleep.js'; import { fetchJson } from '../utils/fetch-json.js'; +// Testnet has no default: it reads IS locks from the DAPI bloom stream (see +// TESTNET.dapiAddresses) because trpc.digitalcash.dev never upgraded to V24. const API_URLS: Record = { - testnet: 'https://trpc.digitalcash.dev', mainnet: 'https://rpc.digitalcash.dev', }; diff --git a/src/api/islock.test.ts b/src/api/islock.test.ts index 302fe15..47c9359 100644 --- a/src/api/islock.test.ts +++ b/src/api/islock.test.ts @@ -14,7 +14,7 @@ vi.mock('./dapi.js', () => ({ DAPIClient: vi.fn().mockImplementation((config: { network: string; rpcUrl?: string }) => ({ network: config.network, get hasRpcUrl() { - return !!config.rpcUrl || config.network === 'mainnet' || config.network === 'testnet'; + return !!config.rpcUrl || config.network === 'mainnet'; }, waitForInstantSendLock: mocks.waitForInstantSendLock, getBestChainLock: mocks.getBestChainLock, @@ -63,6 +63,26 @@ describe('IslockService', () => { await expect(handle.wait()).resolves.toBe(bytes); }); + it('uses the DAPI subscription on testnet (no JSON-RPC since V24)', async () => { + const { TESTNET } = await import('../config.js'); + const bytes = new Uint8Array([5, 6]); + mocks.subscribeForInstantSendLock.mockResolvedValue({ wait: vi.fn().mockResolvedValue(bytes) }); + const service = new IslockService({ + network: 'testnet', + rpcUrl: TESTNET.rpcUrl, + dapiAddresses: TESTNET.dapiAddresses, + }); + + expect(TESTNET.rpcUrl).toBeUndefined(); + expect(TESTNET.dapiAddresses?.length).toBeGreaterThan(0); + expect(service.supportsJsonRpc).toBe(false); + const handle = await service.subscribeForInstantSendLock('txid', new Uint8Array([4]), { txid: 'prevout', vout: 0 }); + + expect(mocks.waitForInstantSendLock).not.toHaveBeenCalled(); + expect(mocks.subscribeForInstantSendLock).toHaveBeenCalledOnce(); + await expect(handle.wait()).resolves.toBe(bytes); + }); + it('keeps the pre-broadcast DAPI subscription path for devnets without RPC', async () => { const bytes = new Uint8Array([9, 8, 7]); const subHandle = { wait: vi.fn().mockResolvedValue(bytes) }; diff --git a/src/api/islock.ts b/src/api/islock.ts index 01bb31e..91e54ea 100644 --- a/src/api/islock.ts +++ b/src/api/islock.ts @@ -66,11 +66,12 @@ export class IslockService { /** * Open the IS lock source before broadcasting and return a handle whose - * `.wait()` resolves with the IS lock bytes once available. Devnets without - * RPC use the DAPI bloom subscription, which must be established before - * broadcast because subscriptions don't replay historical IS locks. - * Mainnet/testnet use JSON-RPC polling, which can recover by txid and avoids - * browser-hostile dapi-client stream discovery. + * `.wait()` resolves with the IS lock bytes once available. Networks without + * RPC (testnet, devnets) use the DAPI bloom subscription over their explicit + * dapiAddresses, which must be established before broadcast because + * subscriptions don't replay historical IS locks. Mainnet uses JSON-RPC + * polling, which can recover by txid and avoids browser-hostile dapi-client + * stream discovery. */ async subscribeForInstantSendLock( txid: string, @@ -102,7 +103,7 @@ export class IslockService { }; } - // JSON-RPC backed networks (mainnet/testnet) should not touch dapi-client + // JSON-RPC backed networks (mainnet) should not touch dapi-client // stream setup here. Browser seed/SML discovery can fail on TLS-hostname // validation and report "No available addresses", which would block the // broadcast even though the RPC islock endpoint is sufficient. diff --git a/src/api/network-status.ts b/src/api/network-status.ts index e342099..258e4f6 100644 --- a/src/api/network-status.ts +++ b/src/api/network-status.ts @@ -34,11 +34,11 @@ export async function fetchNetworkStatus( const checkedAtMs = Date.now(); // Route the chain-lock source the same way the islock flow is routed: - // - mainnet/testnet (JSON-RPC available): read Core's best chain-lock over + // - mainnet (JSON-RPC available): read Core's best chain-lock over // JSON-RPC. The dapi-client DAPI path can't resolve a masternode address // in a browser there (seed/SML resolution fails on bad certs + CORS), so // we deliberately avoid it. - // - devnets (no JSON-RPC, explicit dapiAddresses): read full Platform + // - testnet/devnets (no JSON-RPC, explicit dapiAddresses): read full Platform // status over DAPI, which also yields Tenderdash block height + age. const useDapiPlatformStatus = !islock.supportsJsonRpc; diff --git a/src/api/request-deadlines.test.ts b/src/api/request-deadlines.test.ts index 31d3a38..5edfabd 100644 --- a/src/api/request-deadlines.test.ts +++ b/src/api/request-deadlines.test.ts @@ -124,7 +124,7 @@ describe('per-request deadlines', () => { it('JSON-RPC IS-lock wait rejects at its deadline when the response body stalls', async () => { vi.stubGlobal('fetch', stalledBody()); - const client = new DAPIClient({ network: 'testnet' }); + const client = new DAPIClient({ network: 'mainnet' }); const wait = track(client.waitForInstantSendLock('txid', 30_000)); await vi.advanceTimersByTimeAsync(29_999); @@ -135,7 +135,7 @@ describe('per-request deadlines', () => { it('JSON-RPC IS-lock wait rejects at its deadline even mid retry backoff', async () => { vi.stubGlobal('fetch', stalledHeaders()); - const client = new DAPIClient({ network: 'testnet' }); + const client = new DAPIClient({ network: 'mainnet' }); // First request times out at 8s, then withRetry backs off 1s: 8.5s lands in the backoff. const wait = track(client.waitForInstantSendLock('txid', 8500)); @@ -149,7 +149,7 @@ describe('per-request deadlines', () => { const fetchMock = stalledHeaders(); vi.stubGlobal('fetch', fetchMock); const controller = new AbortController(); - const client = new DAPIClient({ network: 'testnet' }); + const client = new DAPIClient({ network: 'mainnet' }); const wait = track(client.waitForInstantSendLock('txid', 60_000, undefined, controller.signal)); await vi.advanceTimersByTimeAsync(10); diff --git a/src/config.ts b/src/config.ts index a763a57..cc8568a 100644 --- a/src/config.ts +++ b/src/config.ts @@ -44,7 +44,29 @@ export const TESTNET: NetworkConfig = { dustThreshold: 546, platformHrp: 'tdash', faucetBaseUrl: 'https://faucet.thepasta.org', - rpcUrl: 'https://trpc.digitalcash.dev', + // No rpcUrl: trpc.digitalcash.dev is stuck on Core v23 and has no IS locks + // past the V24 fork (block 1,578,000). IS locks come from the DAPI bloom + // stream instead. Explicit addresses skip dapi-client's seed/SML discovery, + // which can't parse V24 CbTx v4 coinbases. Snapshot (2026-10-23) of ENABLED + // evonodes whose DAPI version check passed, with an IP-valid TLS cert and a + // CORS preflight that reflects the request origin. + dapiAddresses: [ + 'https://68.67.122.1:1443', + 'https://68.67.122.2:1443', + 'https://68.67.122.3:1443', + 'https://68.67.122.4:1443', + 'https://68.67.122.5:1443', + 'https://68.67.122.6:1443', + 'https://68.67.122.7:1443', + 'https://68.67.122.8:1443', + 'https://68.67.122.9:1443', + 'https://68.67.122.10:1443', + 'https://68.67.122.11:1443', + 'https://68.67.122.12:1443', + 'https://85.209.243.1:1443', + 'https://85.209.243.2:1443', + 'https://87.229.22.126:1443', + ], }; export const MAINNET: NetworkConfig = { From 64d09b0058e1a625701c4a4ec84746fb3b654ce0 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 18:28:30 -0500 Subject: [PATCH 02/15] feat(islock): subscribe on several evonodes at once and take the first lock The bloom-filter IS lock stream used one dapi-client instance that picks a random node per call. subscribeToTransactionsWithProofs returns before any connection exists, so a dead node only surfaced ~12 s later as 'Response closed without headers', after the asset-lock tx was already broadcast, with no retry. A single live node can also silently drop a lock. With two or more configured addresses, open streams on up to 3 distinct nodes at once, each through its own one-address DAPIClient so nodes cannot repeat. The first matching lock wins and the other streams and clients are torn down; late locks and errors from losers are ignored. A stream that errors or ends is replaced from the untried shuffled list (9 attempts max), and when every node has failed the error names the nodes tried and the last cause. Timeout and abort messages are unchanged. The function returns after the first stream message or a 3 s readiness cap, so the broadcast is not held up by slow nodes. disconnect() now also stops in-flight subscriptions, since DAPIClient.disconnect() does not cancel streams. Fewer than two distinct addresses keep the single-client path. Co-Authored-By: Claude Sonnet 5.5 --- src/api/dapi-subscription-multi.test.ts | 438 ++++++++++++++++++++++++ src/api/dapi-subscription.ts | 257 ++++++++++++-- 2 files changed, 668 insertions(+), 27 deletions(-) create mode 100644 src/api/dapi-subscription-multi.test.ts diff --git a/src/api/dapi-subscription-multi.test.ts b/src/api/dapi-subscription-multi.test.ts new file mode 100644 index 0000000..771bdec --- /dev/null +++ b/src/api/dapi-subscription-multi.test.ts @@ -0,0 +1,438 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { EventEmitter } from 'node:events'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const state = vi.hoisted(() => ({ + clients: [] as any[], + deadHosts: new Set(), + // Hosts whose subscribe call stays pending until releaseSlow() is called. + slowHosts: new Set(), + slowWaiters: [] as Array<() => void>, + releaseSlow(): void { + state.slowWaiters.splice(0).forEach((release) => release()); + }, + height: 100, +})); + +vi.mock('@dashevo/dapi-client', () => { + class FakeClient { + options: any; + streams: any[] = []; + disconnect = vi.fn(async () => {}); + core: any; + platform = {}; + + constructor(options: any) { + this.options = options; + state.clients.push(this); + this.core = { + getBestBlockHeight: vi.fn(async () => state.height), + subscribeToTransactionsWithProofs: vi.fn(async (_filter: unknown, _opts: unknown) => { + if (options.dapiAddresses?.length === 1 && state.deadHosts.has(options.dapiAddresses[0].host)) { + throw new Error('GrpcError: Response closed without headers'); + } + if (options.dapiAddresses?.length === 1 && state.slowHosts.has(options.dapiAddresses[0].host)) { + await new Promise((resolve) => state.slowWaiters.push(resolve)); + } + const stream: any = new EventEmitter(); + stream.cancel = vi.fn(); + this.streams.push(stream); + return stream; + }), + }; + } + } + return { default: FakeClient }; +}); + +vi.mock('@dashevo/dashcore-lib', () => ({ + default: { + BloomFilter: Object.assign( + { + create: () => ({ + vData: [1, 2, 3], + nHashFuncs: 2, + nTweak: 7, + nFlags: 1, + insert: () => {}, + }), + }, + { BLOOM_UPDATE_ALL: 1 } + ), + // Test "IS locks" are just the txid as UTF-8 bytes. + InstantLock: { + fromBuffer: (buf: Buffer) => ({ txid: buf.toString('utf8') }), + }, + }, +})); + +vi.mock('../utils/islock-debug.js', () => ({ describeIslock: () => ({}) })); + +import { + DAPISubscriptionClient, + ISLOCK_CONCURRENT_NODES, + ISLOCK_MAX_NODE_ATTEMPTS, + ISLOCK_READINESS_CAP_MS, +} from './dapi-subscription.js'; + +const TXID = 'aa'.repeat(32); +const OTHER_TXID = 'bb'.repeat(32); +const PUBKEY = new Uint8Array(33).fill(2); +const UTXO = { txid: 'cc'.repeat(32), vout: 0 }; +const TIMEOUT = 60000; + +const addresses = (n: number): string[] => + Array.from({ length: n }, (_, i) => `https://node${i}.test:1443`); + +const lockMessage = (txid: string) => ({ + getInstantSendLockMessages: () => ({ getMessagesList_asU8: () => [new TextEncoder().encode(txid)] }), +}); +const blockMessage = { getRawMerkleBlock: () => new Uint8Array([1]) }; + +/** The one-address clients, in creation order. */ +const nodeClients = (): any[] => state.clients.filter((c) => c.options.dapiAddresses?.length === 1); +const liveStreams = (): any[] => nodeClients().flatMap((c) => c.streams); +const flush = async (): Promise => { await vi.advanceTimersByTimeAsync(0); }; + +/** Start a subscription and let the first stream deliver a message so it returns. */ +async function startReady( + client: DAPISubscriptionClient, + opts: { timeoutMs?: number; signal?: AbortSignal } = {} +) { + const pending = client.subscribeForInstantSendLock( + TXID, PUBKEY, UTXO, opts.timeoutMs ?? TIMEOUT, undefined, opts.signal + ); + await flush(); + liveStreams()[0]?.emit('data', blockMessage); + return pending; +} + +describe('DAPISubscriptionClient multi-node IS lock subscription', () => { + beforeEach(() => { + vi.useFakeTimers(); + state.clients.length = 0; + state.deadHosts.clear(); + state.slowHosts.clear(); + state.slowWaiters.length = 0; + state.height = 100; + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('opens one stream per distinct node, each on a client with exactly one address', async () => { + const all = addresses(5); + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: all }); + const sub = await startReady(client); + + const nodes = nodeClients(); + expect(nodes).toHaveLength(ISLOCK_CONCURRENT_NODES); + const hosts = nodes.map((c) => c.options.dapiAddresses[0].host); + expect(new Set(hosts).size).toBe(ISLOCK_CONCURRENT_NODES); + for (const host of hosts) expect(all.map((a) => new URL(a).hostname)).toContain(host); + expect(nodes[0].options.dapiAddresses[0]).toMatchObject({ protocol: 'https', port: 1443 }); + + // Height comes from the shared failover client, once, and every stream starts from height - 10. + const shared = state.clients.find((c) => c.options.dapiAddresses?.length === 5); + expect(shared.core.getBestBlockHeight).toHaveBeenCalledTimes(1); + for (const node of nodes) { + expect(node.core.getBestBlockHeight).not.toHaveBeenCalled(); + expect(node.core.subscribeToTransactionsWithProofs).toHaveBeenCalledTimes(1); + expect(node.core.subscribeToTransactionsWithProofs.mock.calls[0][1]).toEqual({ + fromBlockHeight: 90, + count: 0, + }); + } + const filters = nodes.map((c) => c.core.subscribeToTransactionsWithProofs.mock.calls[0][0]); + expect(filters[1]).toBe(filters[0]); + expect(filters[2]).toBe(filters[0]); + + liveStreams()[0].emit('data', lockMessage(TXID)); + await sub.wait(); + }); + + it('uses fewer streams when fewer than three nodes are configured', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(2) }); + const sub = await startReady(client); + expect(nodeClients()).toHaveLength(2); + liveStreams()[0].emit('data', lockMessage(TXID)); + await sub.wait(); + }); + + it('resolves with the first matching lock and tears down every other stream and client', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(4) }); + const sub = await startReady(client); + const streams = liveStreams(); + expect(streams).toHaveLength(3); + + streams[1].emit('data', lockMessage(OTHER_TXID)); // not ours + streams[1].emit('data', lockMessage(TXID)); + + const bytes = await sub.wait(); + expect(new TextDecoder().decode(bytes)).toBe(TXID); + for (const stream of streams) expect(stream.cancel).toHaveBeenCalled(); + for (const node of nodeClients()) expect(node.disconnect).toHaveBeenCalledTimes(1); + }); + + it('replaces a failed stream with an untried node and still gets the lock', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(5) }); + const sub = await startReady(client); + const firstHosts = nodeClients().map((c) => c.options.dapiAddresses[0].host); + + const failing = liveStreams()[0]; + failing.emit('error', new Error('GrpcError: Response closed without headers')); + await flush(); + + const nodes = nodeClients(); + expect(nodes).toHaveLength(4); + const replacementHost = nodes[3].options.dapiAddresses[0].host; + expect(firstHosts).not.toContain(replacementHost); + expect(nodes[0].disconnect).toHaveBeenCalledTimes(1); + expect(failing.cancel).toHaveBeenCalled(); + + nodes[3].streams[0].emit('data', lockMessage(TXID)); + const bytes = await sub.wait(); + expect(new TextDecoder().decode(bytes)).toBe(TXID); + for (const node of nodes) expect(node.disconnect).toHaveBeenCalled(); + }); + + it('treats a stream ending before a lock as a failure and replaces it', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(4) }); + const sub = await startReady(client); + + liveStreams()[2].emit('end'); + await flush(); + expect(nodeClients()).toHaveLength(4); + + nodeClients()[3].streams[0].emit('data', lockMessage(TXID)); + await sub.wait(); + }); + + it('still resolves when one node is dead from the start', async () => { + const all = addresses(3); + state.deadHosts.add('node0.test'); + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: all }); + const sub = await startReady(client); + + // The dead node rejects its subscribe call, so only two streams exist. + expect(liveStreams()).toHaveLength(2); + liveStreams()[1].emit('data', lockMessage(TXID)); + const bytes = await sub.wait(); + expect(new TextDecoder().decode(bytes)).toBe(TXID); + }); + + it('rejects naming the nodes tried and the last error when every node fails', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const sub = await startReady(client); + const outcome = expect(sub.wait()).rejects.toThrow(/3 nodes tried.*last error: boom 2/); + + liveStreams().forEach((stream, i) => stream.emit('error', new Error(`boom ${i}`))); + await outcome; + for (const node of nodeClients()) expect(node.disconnect).toHaveBeenCalled(); + }); + + it('rejects immediately without waiting for the readiness cap when all nodes fail on connect', async () => { + for (const host of addresses(3).map((a) => new URL(a).hostname)) state.deadHosts.add(host); + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const pending = client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT); + await flush(); + const sub = await pending; + await expect(sub.wait()).rejects.toThrow(/3 nodes tried.*Response closed without headers/); + }); + + it('caps total attempts when replacements keep failing', async () => { + const many = addresses(20); + for (const a of many) state.deadHosts.add(new URL(a).hostname); + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: many }); + const pending = client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT); + await flush(); + const sub = await pending; + await expect(sub.wait()).rejects.toThrow(new RegExp(`${ISLOCK_MAX_NODE_ATTEMPTS} nodes tried`)); + expect(nodeClients()).toHaveLength(ISLOCK_MAX_NODE_ATTEMPTS); + }); + + it('keeps the timeout message and cleans up when no lock arrives', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const sub = await startReady(client, { timeoutMs: 10000 }); + const outcome = expect(sub.wait()).rejects.toThrow( + `Timeout waiting for InstantSend lock for ${TXID} after 10000ms` + ); + await vi.advanceTimersByTimeAsync(10000); + await outcome; + for (const stream of liveStreams()) expect(stream.cancel).toHaveBeenCalled(); + for (const node of nodeClients()) expect(node.disconnect).toHaveBeenCalled(); + }); + + it('keeps the abort message, both before and during the subscription', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const preAborted = new AbortController(); + preAborted.abort(); + await expect( + client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT, undefined, preAborted.signal) + ).rejects.toThrow(`InstantSend lock subscription aborted for ${TXID}`); + expect(state.clients).toHaveLength(1); // only the shared client from the constructor + + const controller = new AbortController(); + const sub = await startReady(client, { signal: controller.signal }); + const outcome = expect(sub.wait()).rejects.toThrow(`InstantSend lock subscription aborted for ${TXID}`); + controller.abort(); + await outcome; + for (const stream of liveStreams()) expect(stream.cancel).toHaveBeenCalled(); + }); + + it('ignores late locks and errors after the winner', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(5) }); + const sub = await startReady(client); + const streams = liveStreams(); + streams[0].emit('data', lockMessage(TXID)); + const bytes = await sub.wait(); + + const clientCount = state.clients.length; + expect(() => { + streams[1].emit('data', lockMessage(TXID)); + streams[0].emit('data', lockMessage(TXID)); + streams[1].emit('error', new Error('Cancelled on client')); + streams[2].emit('error', new Error('late')); + streams[2].emit('end'); + }).not.toThrow(); + await flush(); + + expect(state.clients).toHaveLength(clientCount); // no replacements after the win + for (const node of nodeClients()) expect(node.disconnect).toHaveBeenCalledTimes(1); + await expect(sub.wait()).resolves.toBe(bytes); + }); + + it('aborting during the readiness window rejects wait() and closes every stream', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const controller = new AbortController(); + const pending = client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT, undefined, controller.signal); + const outcome = pending.then((sub) => expect(sub.wait()).rejects.toThrow(/aborted/)); + await flush(); + controller.abort(); + await flush(); + await outcome; + for (const stream of liveStreams()) expect(stream.cancel).toHaveBeenCalled(); + }); + + it('cancels a stream whose subscribe call resolves only after the winner is decided', async () => { + state.slowHosts.add('node2.test'); + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const sub = await startReady(client); + expect(liveStreams()).toHaveLength(2); + liveStreams()[0].emit('data', lockMessage(TXID)); + await sub.wait(); + + state.releaseSlow(); + await flush(); + const late = nodeClients().find((c) => c.options.dapiAddresses[0].host === 'node2.test').streams[0]; + expect(late.cancel).toHaveBeenCalled(); + expect(late.listenerCount('data')).toBe(0); + }); + + it('returns after the readiness cap when no stream emits data', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + let returned = false; + const pending = client + .subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT) + .then((sub) => { returned = true; return sub; }); + + await vi.advanceTimersByTimeAsync(ISLOCK_READINESS_CAP_MS - 1); + expect(returned).toBe(false); + await vi.advanceTimersByTimeAsync(1); + const sub = await pending; + expect(returned).toBe(true); + + // Streams are still connecting in the background and can still win. + liveStreams()[2].emit('data', lockMessage(TXID)); + await sub.wait(); + }); + + it('returns as soon as the first stream emits data, not after all of them', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + let returned = false; + const pending = client + .subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT) + .then((sub) => { returned = true; return sub; }); + await flush(); + expect(returned).toBe(false); + + liveStreams()[1].emit('data', blockMessage); + const sub = await pending; + expect(returned).toBe(true); + liveStreams()[0].emit('data', lockMessage(TXID)); + await sub.wait(); + }); + + it('uses the single shared client with fewer than two addresses', async () => { + for (const dapiAddresses of [undefined, [] as string[], addresses(1)]) { + state.clients.length = 0; + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses }); + expect(state.clients).toHaveLength(1); + + const pending = client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT); + await flush(); + const sub = await pending; // returns without waiting for data, as before + + expect(state.clients).toHaveLength(1); + const shared = state.clients[0]; + expect(shared.core.subscribeToTransactionsWithProofs).toHaveBeenCalledTimes(1); + expect(shared.streams).toHaveLength(1); + shared.streams[0].emit('data', lockMessage(TXID)); + await sub.wait(); + expect(shared.streams[0].cancel).toHaveBeenCalled(); + } + }); + + it('disconnect() stops in-flight subscriptions and closes their per-node clients', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const sub = await startReady(client); + const outcome = expect(sub.wait()).rejects.toThrow(`InstantSend lock subscription aborted for ${TXID}`); + + await client.disconnect(); + await outcome; + const shared = state.clients.find((c) => c.options.dapiAddresses?.length === 3); + expect(shared.disconnect).toHaveBeenCalledTimes(1); + for (const stream of liveStreams()) expect(stream.cancel).toHaveBeenCalled(); + for (const node of nodeClients()) expect(node.disconnect).toHaveBeenCalledTimes(1); + expect(nodeClients()).toHaveLength(3); // no replacements opened after disconnect + }); + + it('disconnect() after a finished subscription does not touch per-node clients again', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const sub = await startReady(client); + liveStreams()[0].emit('data', lockMessage(TXID)); + await sub.wait(); + + await client.disconnect(); + for (const node of nodeClients()) expect(node.disconnect).toHaveBeenCalledTimes(1); + }); + + it('counts one failure once when a stream reports both error and end', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(5) }); + const sub = await startReady(client); + + const failing = liveStreams()[0]; + failing.emit('error', new Error('boom')); + failing.emit('end'); + await flush(); + + expect(nodeClients()).toHaveLength(4); // one replacement, not two + nodeClients()[3].streams[0].emit('data', lockMessage(TXID)); + await sub.wait(); + }); + + it('never puts two streams on a repeated address', async () => { + const dup = ['https://a.test:1443', 'https://a.test:1443', 'https://b.test:1443']; + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: dup }); + const sub = await startReady(client); + + expect(nodeClients().map((c) => c.options.dapiAddresses[0].host).sort()).toEqual(['a.test', 'b.test']); + liveStreams()[0].emit('data', lockMessage(TXID)); + await sub.wait(); + }); +}); diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index 156720e..98ebb4c 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -29,18 +29,53 @@ export interface DAPISubscriptionConfig { dapiAddresses?: string[]; } +/** Distinct evonodes the IS lock stream is opened on at once. */ +export const ISLOCK_CONCURRENT_NODES = 3; +/** Total streams opened per subscription, initial ones plus replacements for failed ones. */ +export const ISLOCK_MAX_NODE_ATTEMPTS = ISLOCK_CONCURRENT_NODES + 6; +/** Longest subscribeForInstantSendLock waits for a first stream message before returning. */ +export const ISLOCK_READINESS_CAP_MS = 3000; + +const CLIENT_OPTIONS = { timeout: 30000, retries: 3 }; + +interface DapiAddress { + protocol: string; + host: string; + port: number; +} + +interface NodeSlot { + client?: any; + stream?: any; + failed: boolean; +} + +function shuffled(items: readonly T[]): T[] { + const copy = [...items]; + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [copy[i], copy[j]] = [copy[j], copy[i]]; + } + return copy; +} + export class DAPISubscriptionClient { readonly network: string; private readonly dapiClient: any; + private readonly nodeAddresses: DapiAddress[]; + // Aborts of in-flight multi-node subscriptions. DAPIClient.disconnect() does + // not cancel streams, so disconnect() must stop these to close the per-node clients. + private readonly activeSubscriptions = new Set<() => void>(); constructor(config: DAPISubscriptionConfig) { this.network = config.network; - const options: any = { timeout: 30000, retries: 3 }; + const options: any = { ...CLIENT_OPTIONS }; + this.nodeAddresses = []; if (config.dapiAddresses?.length) { // DAPIClient expects address objects { host, port, protocol }, not URL strings. // Our configs store URLs (https://host:port) for EvoSDK compatibility, so // parse them here. - options.dapiAddresses = config.dapiAddresses.map((addr) => { + const parsed: DapiAddress[] = config.dapiAddresses.map((addr) => { const url = new URL(addr); return { protocol: url.protocol.replace(':', ''), @@ -48,6 +83,9 @@ export class DAPISubscriptionClient { port: url.port ? parseInt(url.port, 10) : 443, }; }); + options.dapiAddresses = parsed; + // A repeated address would put two "distinct" streams on one node. + this.nodeAddresses = [...new Map(parsed.map((a) => [`${a.host}:${a.port}`, a])).values()]; } else { options.network = config.network === 'mainnet' ? 'mainnet' : 'testnet'; } @@ -119,6 +157,12 @@ export class DAPISubscriptionClient { console.log('[islock-sub] Current block height:', currentHeight); const fromBlockHeight = Math.max(1, currentHeight - 10); + if (this.nodeAddresses.length >= 2) { + return this.subscribeOnMultipleNodes( + txid, bloomFilter, fromBlockHeight, timeoutMs, onProgress, signal + ); + } + onProgress?.(`Subscribing from block ${fromBlockHeight}...`); const stream = await this.dapiClient.core.subscribeToTransactionsWithProofs( bloomFilter, @@ -153,31 +197,8 @@ export class DAPISubscriptionClient { } stream.on('data', (response: unknown) => { - try { - const islockMessages = (response as any).getInstantSendLockMessages?.(); - const hasIslocks = !!islockMessages; - const hasMerkleBlock = !!(response as any).getRawMerkleBlock?.()?.length; - const hasRawTxs = !!(response as any).getRawTransactions?.()?.getTransactionsList?.()?.length; - console.log(`[islock-sub] stream data: islocks=${hasIslocks} merkleBlock=${hasMerkleBlock} rawTxs=${hasRawTxs}`); - if (!islockMessages) return; - const messages = islockMessages.getMessagesList_asU8?.() || islockMessages.getMessagesList?.(); - if (!messages || messages.length === 0) return; - console.log(`[islock-sub] received ${messages.length} IS lock(s) in stream message`); - for (const msgBytes of messages) { - const bytes = msgBytes instanceof Uint8Array ? msgBytes : new Uint8Array(msgBytes); - const lockTxid = this.parseInstantLockTxid(bytes); - console.log(`[islock-sub] IS lock txid=${lockTxid} (want ${txid})`); - if (lockTxid === txid) { - onProgress?.('InstantSend lock received!'); - const debug = describeIslock(bytes, 'dapi-subscription'); - console.log('[islock-debug] IS lock received via gRPC subscription:', debug); - finish(() => resolve(bytes)); - return; - } - } - } catch (error) { - console.warn('Error processing stream data:', error); - } + const bytes = this.findMatchingLock(response, txid, onProgress); + if (bytes) finish(() => resolve(bytes)); }); stream.on('error', (error: Error) => { @@ -196,6 +217,187 @@ export class DAPISubscriptionClient { return { wait: () => lockPromise }; } + /** Returns the bytes of the IS lock for `txid` carried by a stream message, if any. */ + private findMatchingLock( + response: unknown, + txid: string, + onProgress?: (message: string) => void + ): Uint8Array | null { + try { + const islockMessages = (response as any).getInstantSendLockMessages?.(); + const hasIslocks = !!islockMessages; + const hasMerkleBlock = !!(response as any).getRawMerkleBlock?.()?.length; + const hasRawTxs = !!(response as any).getRawTransactions?.()?.getTransactionsList?.()?.length; + console.log(`[islock-sub] stream data: islocks=${hasIslocks} merkleBlock=${hasMerkleBlock} rawTxs=${hasRawTxs}`); + if (!islockMessages) return null; + const messages = islockMessages.getMessagesList_asU8?.() || islockMessages.getMessagesList?.(); + if (!messages || messages.length === 0) return null; + console.log(`[islock-sub] received ${messages.length} IS lock(s) in stream message`); + for (const msgBytes of messages) { + const bytes = msgBytes instanceof Uint8Array ? msgBytes : new Uint8Array(msgBytes); + const lockTxid = this.parseInstantLockTxid(bytes); + console.log(`[islock-sub] IS lock txid=${lockTxid} (want ${txid})`); + if (lockTxid === txid) { + onProgress?.('InstantSend lock received!'); + const debug = describeIslock(bytes, 'dapi-subscription'); + console.log('[islock-debug] IS lock received via gRPC subscription:', debug); + return bytes; + } + } + } catch (error) { + console.warn('Error processing stream data:', error); + } + return null; + } + + /** + * Subscribe on several distinct evonodes at once and take the first matching + * IS lock. A single random node can be dead (the stream then errors ~12 s + * after connecting, long after the tx was broadcast) or can silently drop the + * lock, so each node gets its own one-address client: a shared client would + * pick nodes at random and could land on the same one twice. + * + * subscribeToTransactionsWithProofs resolves before any connection exists, so + * readiness is approximated: return once any stream delivers a message (the + * server replays recent blocks, usually within ~1 s) or after the readiness + * cap, whichever comes first. The remaining streams keep connecting. + */ + private async subscribeOnMultipleNodes( + txid: string, + bloomFilter: ReturnType, + fromBlockHeight: number, + timeoutMs: number, + onProgress?: (message: string) => void, + signal?: AbortSignal + ): Promise<{ wait: () => Promise }> { + const nodes = shuffled(this.nodeAddresses); + const initialCount = Math.min(ISLOCK_CONCURRENT_NODES, nodes.length); + onProgress?.(`Subscribing from block ${fromBlockHeight} on ${initialCount} nodes...`); + + let markReady!: () => void; + const ready = new Promise((resolve) => { markReady = resolve; }); + const readyTimerId = setTimeout(markReady, ISLOCK_READINESS_CAP_MS); + + const lockPromise = new Promise((resolve, reject) => { + const slots = new Set(); + let settled = false; + let nextNode = 0; + let attempts = 0; + let running = 0; + + const cancelStream = (stream: any): void => { + try { stream?.cancel(); } catch { /* ignore */ } + }; + + const release = (slot: NodeSlot): void => { + slots.delete(slot); + cancelStream(slot.stream); + const client = slot.client; + if (!client) return; + try { + Promise.resolve(client.disconnect()).catch(() => {}); + } catch { /* ignore */ } + }; + + const finish = (fn: () => void): void => { + if (settled) return; + settled = true; + clearTimeout(timeoutId); + clearTimeout(readyTimerId); + this.activeSubscriptions.delete(onAbort); + signal?.removeEventListener('abort', onAbort); + for (const slot of [...slots]) release(slot); + markReady(); + fn(); + }; + + const onAbort = (): void => { + finish(() => reject(new Error(`InstantSend lock subscription aborted for ${txid}`))); + }; + + const timeoutId = setTimeout(() => { + finish(() => reject(new Error(`Timeout waiting for InstantSend lock for ${txid} after ${timeoutMs}ms`))); + }, timeoutMs); + + const openNode = (): void => { + const address = nodes[nextNode++]; + if (!address) return; + const slot: NodeSlot = { failed: false }; + slots.add(slot); + attempts++; + running++; + + const fail = (error: unknown): void => { + if (settled || slot.failed) return; + slot.failed = true; + running--; + release(slot); + if (nextNode < nodes.length && attempts < ISLOCK_MAX_NODE_ATTEMPTS) { + openNode(); + } else if (running === 0) { + const reason = error instanceof Error ? error.message : String(error); + finish(() => reject(new Error( + `InstantSend lock subscription failed for ${txid}: ${attempts} nodes tried, last error: ${reason}` + ))); + } + }; + + console.log(`[islock-sub] opening stream on ${address.host}:${address.port} (attempt ${attempts})`); + try { + slot.client = new DAPIClientClass({ ...CLIENT_OPTIONS, dapiAddresses: [address] }); + Promise.resolve( + slot.client.core.subscribeToTransactionsWithProofs(bloomFilter, { fromBlockHeight, count: 0 }) + ).then((stream: any) => { + if (settled || slot.failed) { + cancelStream(stream); + return; + } + slot.stream = stream; + stream.on('data', (response: unknown) => { + if (settled) return; + markReady(); + const bytes = this.findMatchingLock(response, txid, onProgress); + if (bytes) finish(() => resolve(bytes)); + }); + // Listeners stay attached after cancel(): Node gRPC streams emit + // 'error' on cancel, which would throw if nothing were listening. + // The browser build reports one failure through both 'error' and + // 'end'; slot.failed makes the second a no-op. + stream.on('error', (error: Error) => { + if (settled || slot.failed) return; + console.error(`[islock-sub] stream error on ${address.host}:${address.port}:`, error); + fail(error); + }); + stream.on('end', () => { + if (settled || slot.failed) return; + console.warn(`[islock-sub] stream ended on ${address.host}:${address.port}`); + fail(new Error(`Stream ended before receiving InstantSend lock for ${txid}`)); + }); + }).catch(fail); + } catch (error) { + fail(error); + } + }; + + if (signal) { + if (signal.aborted) { + onAbort(); + return; + } + signal.addEventListener('abort', onAbort, { once: true }); + } + this.activeSubscriptions.add(onAbort); + + for (let i = 0; i < initialCount && !settled; i++) openNode(); + }); + + // Avoid unhandled-rejection warnings if the caller never awaits .wait() + lockPromise.catch(() => {}); + + await ready; + return { wait: () => lockPromise }; + } + async waitForInstantSendLock( txid: string, publicKey: Uint8Array, @@ -209,6 +411,7 @@ export class DAPISubscriptionClient { } async disconnect(): Promise { + for (const abort of [...this.activeSubscriptions]) abort(); try { await this.dapiClient.disconnect(); } catch { /* ignore */ } } From 45d40b0bb885c36149e43fd1a07cf8c586f6fb5d Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 18:29:16 -0500 Subject: [PATCH 03/15] refactor(islock): drop redundant node counters in multi-node subscribe attempts already indexes the next untried node and slots.size is the number of live streams, so nextNode and running were duplicates. Co-Authored-By: Claude Sonnet 5.5 --- src/api/dapi-subscription.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index 98ebb4c..16a1c5e 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -281,9 +281,8 @@ export class DAPISubscriptionClient { const lockPromise = new Promise((resolve, reject) => { const slots = new Set(); let settled = false; - let nextNode = 0; + // Streams opened so far; also the index of the next untried node. let attempts = 0; - let running = 0; const cancelStream = (stream: any): void => { try { stream?.cancel(); } catch { /* ignore */ } @@ -320,21 +319,18 @@ export class DAPISubscriptionClient { }, timeoutMs); const openNode = (): void => { - const address = nodes[nextNode++]; + const address = nodes[attempts++]; if (!address) return; const slot: NodeSlot = { failed: false }; slots.add(slot); - attempts++; - running++; const fail = (error: unknown): void => { if (settled || slot.failed) return; slot.failed = true; - running--; release(slot); - if (nextNode < nodes.length && attempts < ISLOCK_MAX_NODE_ATTEMPTS) { + if (attempts < nodes.length && attempts < ISLOCK_MAX_NODE_ATTEMPTS) { openNode(); - } else if (running === 0) { + } else if (slots.size === 0) { const reason = error instanceof Error ? error.message : String(error); finish(() => reject(new Error( `InstantSend lock subscription failed for ${txid}: ${attempts} nodes tried, last error: ${reason}` From a057e8472690a58b82edea47a72eb12e28f87baa Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 18:59:56 -0500 Subject: [PATCH 04/15] fix(testnet): read Platform status through the EvoSDK Every testnet node omits the optional state_sync message from platform getStatus, and @dashevo/dapi-client 3.1.0-dev.7 dereferences it unconditionally, so the network-health indicator reported "degraded" and the chain-lock fallback never got a height. Testnet now reads chain-locked height, Platform block height and block time via sdk.system.status(); devnets and mainnet keep their existing paths. Co-Authored-By: Claude Sonnet 5.5 --- src/api/dapi-subscription.ts | 39 +++--- src/api/islock.ts | 18 ++- src/api/network-status.ts | 6 +- src/api/platform-status-routing.test.ts | 168 ++++++++++++++++++++++++ src/main.ts | 18 +-- src/platform/status.test.ts | 133 +++++++++++++++++++ src/platform/status.ts | 56 ++++++++ 7 files changed, 402 insertions(+), 36 deletions(-) create mode 100644 src/api/platform-status-routing.test.ts create mode 100644 src/platform/status.test.ts create mode 100644 src/platform/status.ts diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index 16a1c5e..1f10f89 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -4,6 +4,7 @@ import DAPIClientModule from '@dashevo/dapi-client'; import dashcoreLib from '@dashevo/dashcore-lib'; import { hash160 } from '../crypto/hash.js'; import { describeIslock } from '../utils/islock-debug.js'; +import { fetchPlatformStatus, type PlatformStatus } from '../platform/status.js'; interface BloomFilterStatic { create(elements: number, falsePositiveRate: number, nTweak: number, nFlags: number): { @@ -412,13 +413,14 @@ export class DAPISubscriptionClient { } /** - * Read the chain-locked Dash Core block height directly from Platform via - * gRPC (`platform.getStatus()` → `chain.coreChainLockedHeight`). + * Read the chain-locked Dash Core block height directly from Platform + * (`chain.coreChainLockedHeight` of the Platform status). * - * We go straight to dapi-client rather than `sdk.system.status()` because - * the wasm SDK in trusted mode returns testnet-cached values for this - * field on devnets, while this path is authoritative for whatever - * masternode the dapiAddresses point at. + * Devnets go straight to dapi-client (`platform.getStatus()`) rather than + * `sdk.system.status()` because the wasm SDK in trusted mode can return + * testnet-cached values there, while this path is authoritative for + * whatever masternode the dapiAddresses point at. Testnet uses the SDK; + * see {@link getPlatformStatus}. * * @returns the chain-locked height, or `undefined` if the masternode * reports no chain-lock yet. @@ -429,17 +431,22 @@ export class DAPISubscriptionClient { } /** - * Read Platform/Tenderdash status via gRPC `platform.getStatus()`. Surfaces - * the chain-locked Core height plus the latest Platform block height and its - * timestamp, which together let callers detect a stalled Platform consensus - * (Core advancing while Tenderdash is stuck). Fields are `undefined` when the - * masternode doesn't report them. + * Read Platform/Tenderdash status. Surfaces the chain-locked Core height + * plus the latest Platform block height and its timestamp, which together + * let callers detect a stalled Platform consensus (Core advancing while + * Tenderdash is stuck). Fields are `undefined` when the masternode doesn't + * report them. + * + * Testnet reads through the EvoSDK: every testnet node omits the optional + * `state_sync` message that dapi-client's `platform.getStatus()` decoder + * dereferences unconditionally, so that call always throws there. Devnets + * keep the dapi-client gRPC call (see getCoreChainLockedHeight). */ - async getPlatformStatus(): Promise<{ - coreChainLockedHeight?: number; - latestBlockHeight?: number; - latestBlockTimeMs?: number; - }> { + async getPlatformStatus(): Promise { + if (this.network === 'testnet') { + return fetchPlatformStatus(this.network); + } + const status = await this.dapiClient.platform.getStatus(); const chain = status.getChainStatus?.() ?? status.chain; diff --git a/src/api/islock.ts b/src/api/islock.ts index 91e54ea..58af0cd 100644 --- a/src/api/islock.ts +++ b/src/api/islock.ts @@ -1,5 +1,6 @@ import { DAPIClient, type DAPIConfig } from './dapi.js'; import { DAPISubscriptionClient, type DAPISubscriptionConfig } from './dapi-subscription.js'; +import type { PlatformStatus } from '../platform/status.js'; import type { RetryOptions } from '../utils/retry.js'; import { abortableSleep } from '../utils/sleep.js'; @@ -148,9 +149,9 @@ export class IslockService { } /** - * Direct gRPC read of the Platform chain-locked Dash Core height. - * Used by the chainlock fallback — see DAPISubscriptionClient - * for why this bypasses `sdk.system.status()`. + * Read of the Platform chain-locked Dash Core height. Used by the + * chainlock fallback; testnet reads it through the EvoSDK and devnets over + * direct gRPC — see DAPISubscriptionClient for why. */ async getCoreChainLockedHeight(): Promise { return this.subscriptionClient.getCoreChainLockedHeight(); @@ -177,14 +178,11 @@ export class IslockService { /** * Read Platform/Tenderdash status (chain-locked Core height, latest Platform - * block height + timestamp) over DAPI. Used by the network-health indicator - * on devnets (which have explicit dapiAddresses). + * block height + timestamp). Used by the network-health indicator on + * testnet (via the EvoSDK) and devnets (via DAPI over their explicit + * dapiAddresses). */ - async getPlatformStatus(): Promise<{ - coreChainLockedHeight?: number; - latestBlockHeight?: number; - latestBlockTimeMs?: number; - }> { + async getPlatformStatus(): Promise { return this.subscriptionClient.getPlatformStatus(); } diff --git a/src/api/network-status.ts b/src/api/network-status.ts index 258e4f6..6556a77 100644 --- a/src/api/network-status.ts +++ b/src/api/network-status.ts @@ -38,8 +38,10 @@ export async function fetchNetworkStatus( // JSON-RPC. The dapi-client DAPI path can't resolve a masternode address // in a browser there (seed/SML resolution fails on bad certs + CORS), so // we deliberately avoid it. - // - testnet/devnets (no JSON-RPC, explicit dapiAddresses): read full Platform - // status over DAPI, which also yields Tenderdash block height + age. + // - testnet/devnets (no JSON-RPC): read full Platform status, which also + // yields Tenderdash block height + age. Testnet goes through the EvoSDK + // (dapi-client's status decoder throws on testnet nodes); devnets use + // DAPI over their explicit dapiAddresses. IslockService picks the path. const useDapiPlatformStatus = !islock.supportsJsonRpc; // Bound the Insight retry so a flaky endpoint can't stretch one poll past the diff --git a/src/api/platform-status-routing.test.ts b/src/api/platform-status-routing.test.ts new file mode 100644 index 0000000..a61f008 --- /dev/null +++ b/src/api/platform-status-routing.test.ts @@ -0,0 +1,168 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + fetchPlatformStatus: vi.fn(), + dapiGetStatus: vi.fn(), +})); + +vi.mock('../platform/status.js', () => ({ fetchPlatformStatus: mocks.fetchPlatformStatus })); + +vi.mock('@dashevo/dapi-client', () => { + class FakeClient { + platform = { getStatus: mocks.dapiGetStatus }; + core = {}; + disconnect = vi.fn(async () => {}); + } + return { default: FakeClient }; +}); + +vi.mock('@dashevo/dashcore-lib', () => ({ default: {} })); + +import { DAPISubscriptionClient } from './dapi-subscription.js'; +import { IslockService } from './islock.js'; +import { fetchNetworkStatus } from './network-status.js'; +import { TESTNET } from '../config.js'; +import type { InsightClient } from './insight.js'; + +const insightAt = (height: number | Error): InsightClient => + ({ + getBlockHeight: async () => { + if (height instanceof Error) throw height; + return height; + }, + }) as unknown as InsightClient; + +const freshStatus = (overrides: Record = {}) => ({ + coreChainLockedHeight: 1_578_100, + latestBlockHeight: 80_000, + latestBlockTimeMs: Date.now() - 4_000, + ...overrides, +}); + +describe('Platform status routing', () => { + const fetchSpy = vi.fn(); + + beforeEach(() => { + vi.clearAllMocks(); + fetchSpy.mockRejectedValue(new Error('no network access expected')); + vi.stubGlobal('fetch', fetchSpy); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + describe('DAPISubscriptionClient', () => { + it('reads testnet status through the SDK, never dapi-client', async () => { + // dapi-client's decoder throws on testnet nodes (no state_sync). + mocks.dapiGetStatus.mockRejectedValue( + new TypeError("Cannot read properties of undefined (reading 'getTotalSyncedTime')") + ); + mocks.fetchPlatformStatus.mockResolvedValue(freshStatus()); + const client = new DAPISubscriptionClient({ + network: 'testnet', + dapiAddresses: TESTNET.dapiAddresses, + }); + + await expect(client.getPlatformStatus()).resolves.toMatchObject({ + coreChainLockedHeight: 1_578_100, + latestBlockHeight: 80_000, + }); + await expect(client.getCoreChainLockedHeight()).resolves.toBe(1_578_100); + expect(mocks.fetchPlatformStatus).toHaveBeenCalledWith('testnet'); + expect(mocks.dapiGetStatus).not.toHaveBeenCalled(); + }); + + it('returns undefined chain-locked height when testnet reports none', async () => { + mocks.fetchPlatformStatus.mockResolvedValue(freshStatus({ coreChainLockedHeight: undefined })); + const client = new DAPISubscriptionClient({ network: 'testnet' }); + + await expect(client.getCoreChainLockedHeight()).resolves.toBeUndefined(); + }); + + it('keeps the dapi-client call on devnets', async () => { + mocks.dapiGetStatus.mockResolvedValue({ + chain: { coreChainLockedHeight: 4321, latestBlockHeight: 99n }, + time: { block: 1_700_000_000_000n }, + }); + const client = new DAPISubscriptionClient({ + network: 'devnet-moutai', + dapiAddresses: ['https://68.67.122.254:1443'], + }); + + await expect(client.getPlatformStatus()).resolves.toEqual({ + coreChainLockedHeight: 4321, + latestBlockHeight: 99, + latestBlockTimeMs: 1_700_000_000_000, + }); + expect(mocks.fetchPlatformStatus).not.toHaveBeenCalled(); + }); + + it('keeps the dapi-client call on mainnet', async () => { + mocks.dapiGetStatus.mockResolvedValue({ chain: { coreChainLockedHeight: 5 } }); + const client = new DAPISubscriptionClient({ network: 'mainnet' }); + + await expect(client.getCoreChainLockedHeight()).resolves.toBe(5); + expect(mocks.fetchPlatformStatus).not.toHaveBeenCalled(); + }); + }); + + describe('network status on testnet', () => { + const testnetIslock = () => + new IslockService({ network: 'testnet', dapiAddresses: TESTNET.dapiAddresses }); + + it('uses the DAPI/SDK path, not JSON-RPC', () => { + expect(testnetIslock().supportsJsonRpc).toBe(false); + }); + + it('reports healthy when the SDK call succeeds', async () => { + mocks.fetchPlatformStatus.mockResolvedValue(freshStatus()); + + const status = await fetchNetworkStatus(insightAt(1_578_102), testnetIslock()); + + expect(status.health).toBe('healthy'); + expect(status.reasons).toEqual([]); + expect(status.coreChainLockedHeight).toBe(1_578_100); + expect(status.platformBlockHeight).toBe(80_000); + expect(status.platformBlockAgeMs).toBeLessThan(60_000); + expect(mocks.fetchPlatformStatus).toHaveBeenCalledWith('testnet'); + expect(mocks.dapiGetStatus).not.toHaveBeenCalled(); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('stays healthy when the node omits optional fields', async () => { + mocks.fetchPlatformStatus.mockResolvedValue({}); + + const status = await fetchNetworkStatus(insightAt(1_578_102), testnetIslock()); + + expect(status.health).toBe('healthy'); + expect(status.coreChainLockedHeight).toBeUndefined(); + }); + + it('reports degraded only when the SDK call fails', async () => { + mocks.fetchPlatformStatus.mockRejectedValue(new Error('Timed out while reading Platform status')); + + const status = await fetchNetworkStatus(insightAt(1_578_102), testnetIslock()); + + expect(status.health).toBe('degraded'); + expect(status.reasons).toEqual(['Platform (DAPI) status unreachable']); + }); + + it('reports unknown when both Insight and the SDK call fail', async () => { + mocks.fetchPlatformStatus.mockRejectedValue(new Error('down')); + + const status = await fetchNetworkStatus(insightAt(new Error('down')), testnetIslock()); + + expect(status.health).toBe('unknown'); + }); + + it('still flags a genuinely stalled chain-lock', async () => { + mocks.fetchPlatformStatus.mockResolvedValue(freshStatus({ coreChainLockedHeight: 1_577_000 })); + + const status = await fetchNetworkStatus(insightAt(1_578_102), testnetIslock()); + + expect(status.health).toBe('stalled'); + }); + }); +}); diff --git a/src/main.ts b/src/main.ts index f149d5e..e87117b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -3362,14 +3362,16 @@ async function startChainlockFallback(): Promise { } ); - // Poll #2: chain-locked Dash Core height. DAPI JSON-RPC - // `getbestchainlock` first (when an rpcUrl is configured), then direct - // gRPC `platform.getStatus()` via @dashevo/dapi-client. We intentionally - // do NOT use `sdk.system.status()`: in pre-dev.7 builds the testnet - // trusted context returned testnet-cached values on devnets. SDK - // 3.1.0-dev.7 fixes this with per-devnet trusted contexts, but the - // direct dapi-client call works uniformly across trusted and - // non-trusted devnets, so we keep it. + // Poll #2: chain-locked Dash Core height. JSON-RPC `getbestchainlock` + // first (mainnet only; it returns nothing without an rpcUrl), then the + // Platform status via IslockService. On testnet that is + // `sdk.system.status()` (dapi-client's decoder throws on every testnet + // node, which omit `state_sync`). On devnets it is direct gRPC + // `platform.getStatus()` via @dashevo/dapi-client: in pre-dev.7 builds the + // SDK's testnet trusted context returned testnet-cached values on devnets. + // SDK 3.1.0-dev.7 fixes this with per-devnet trusted contexts, but the + // direct dapi-client call works uniformly across trusted and non-trusted + // devnets, so we keep it there. const chainLockPoll = (async (): Promise => { while (!signal.aborted) { let height: number | undefined; diff --git a/src/platform/status.test.ts b/src/platform/status.test.ts new file mode 100644 index 0000000..19ca0a4 --- /dev/null +++ b/src/platform/status.test.ts @@ -0,0 +1,133 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const sdkState = vi.hoisted(() => ({ + status: vi.fn(), + connect: vi.fn(async () => {}), + created: 0, +})); + +// Exercise the real client helpers (connect, timeout) against a fake SDK. +vi.mock('./sdkModule.js', () => ({ + loadSdkModule: async () => ({ + EvoSDK: { + testnetTrusted: () => { + sdkState.created++; + return { + isConnected: false, + connect: sdkState.connect, + system: { status: sdkState.status }, + }; + }, + }, + }), +})); + +import { fetchPlatformStatus } from './status.js'; +import { PlatformOperationTimeoutError } from './client.js'; + +function status(overrides: { + chain?: Record; + time?: Record; +} = {}) { + return { + chain: { + core_chain_locked_height: 1_578_123, + latest_block_height: '77001', + ...overrides.chain, + }, + time: { block: '1792000000000', local: '1792000000', ...overrides.time }, + }; +} + +describe('fetchPlatformStatus', () => { + beforeEach(() => { + sdkState.status.mockReset(); + sdkState.connect.mockClear(); + sdkState.created = 0; + vi.spyOn(console, 'log').mockImplementation(() => {}); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('maps the snake_case SDK fields', async () => { + sdkState.status.mockResolvedValue(status()); + + await expect(fetchPlatformStatus('testnet')).resolves.toEqual({ + coreChainLockedHeight: 1_578_123, + latestBlockHeight: 77001, + latestBlockTimeMs: 1_792_000_000_000, + }); + expect(sdkState.connect).toHaveBeenCalledOnce(); + }); + + it('accepts bigint values', async () => { + sdkState.status.mockResolvedValue( + status({ + chain: { core_chain_locked_height: 1_578_124n, latest_block_height: 77002n }, + time: { block: 1_792_000_001_000n }, + }) + ); + + await expect(fetchPlatformStatus('testnet')).resolves.toEqual({ + coreChainLockedHeight: 1_578_124, + latestBlockHeight: 77002, + latestBlockTimeMs: 1_792_000_001_000, + }); + }); + + it('reports missing, zero and malformed values as undefined', async () => { + sdkState.status.mockResolvedValue( + status({ + chain: { core_chain_locked_height: undefined, latest_block_height: '0' }, + time: { block: '' }, + }) + ); + await expect(fetchPlatformStatus('testnet')).resolves.toEqual({ + coreChainLockedHeight: undefined, + latestBlockHeight: undefined, + latestBlockTimeMs: undefined, + }); + + sdkState.status.mockResolvedValue( + status({ + chain: { core_chain_locked_height: 0, latest_block_height: 'abc' }, + time: { block: null }, + }) + ); + await expect(fetchPlatformStatus('testnet')).resolves.toEqual({ + coreChainLockedHeight: undefined, + latestBlockHeight: undefined, + latestBlockTimeMs: undefined, + }); + }); + + it('tolerates a status without chain or time sections', async () => { + sdkState.status.mockResolvedValue({}); + + await expect(fetchPlatformStatus('testnet')).resolves.toEqual({ + coreChainLockedHeight: undefined, + latestBlockHeight: undefined, + latestBlockTimeMs: undefined, + }); + }); + + it('propagates SDK failures', async () => { + sdkState.status.mockRejectedValue(new Error('boom')); + + await expect(fetchPlatformStatus('testnet')).rejects.toThrow('boom'); + }); + + it('times out when the SDK call never settles', async () => { + vi.useFakeTimers(); + sdkState.status.mockReturnValue(new Promise(() => {})); + + const result = fetchPlatformStatus('testnet'); + const assertion = expect(result).rejects.toBeInstanceOf(PlatformOperationTimeoutError); + await vi.advanceTimersByTimeAsync(20_000); + await assertion; + }); +}); diff --git a/src/platform/status.ts b/src/platform/status.ts new file mode 100644 index 0000000..e8b720a --- /dev/null +++ b/src/platform/status.ts @@ -0,0 +1,56 @@ +import { withConnectedPlatformSdk, withPlatformOperationTimeout } from './client.js'; + +export interface PlatformStatus { + coreChainLockedHeight?: number; + latestBlockHeight?: number; + /** Latest Platform block time, Unix milliseconds. */ + latestBlockTimeMs?: number; +} + +const PLATFORM_STATUS_TIMEOUT_MS = 20000; + +/** + * The SDK types these as number/string, but wasm bindings can surface u64 + * fields as bigint and proto3 omits zero values, so accept number, bigint and + * numeric strings and treat anything that is not a positive safe integer as + * "not reported". + */ +function positiveInteger(value: unknown): number | undefined { + if (typeof value !== 'number' && typeof value !== 'bigint' && typeof value !== 'string') { + return undefined; + } + if (value === '') return undefined; + const number = Number(value); + return Number.isSafeInteger(number) && number > 0 ? number : undefined; +} + +/** + * Read Platform status through the EvoSDK (`sdk.system.status()`). + * + * Used instead of `@dashevo/dapi-client`'s `platform.getStatus()` on testnet: + * testnet evonodes omit the optional `state_sync` message (and occasionally + * a version sub-field), and dapi-client 3.1.0-dev.7's + * `GetStatusResponse.createFromProto` dereferences them unconditionally, so + * the whole call throws even though the chain/time data is present. The SDK + * decodes the same response tolerantly. + * + * Fields the node does not report are `undefined`. + */ +export async function fetchPlatformStatus(network: string): Promise { + return withPlatformOperationTimeout( + withConnectedPlatformSdk( + network, + async (sdk) => { + const status = await sdk.system.status(); + return { + coreChainLockedHeight: positiveInteger(status?.chain?.core_chain_locked_height), + latestBlockHeight: positiveInteger(status?.chain?.latest_block_height), + latestBlockTimeMs: positiveInteger(status?.time?.block), + }; + }, + { maxAttempts: 1 } + ), + 'reading Platform status', + PLATFORM_STATUS_TIMEOUT_MS + ); +} From c0d9e8585e89f30a918011e1075ac12726a05a00 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 19:02:01 -0500 Subject: [PATCH 05/15] feat(testnet): fetch the live evonode list at client init Testnet certificates rotate in 2-6 days and nodes come and go, so the static dapiAddresses snapshot goes stale. At client init, testnet now fetches the quorum service /masternodes list (CORS-enabled for browsers; 5 s, one attempt), keeps ENABLED nodes with a successful version check and dials them on :1443. The static list is the fallback when the fetch fails and tops up the result when fewer than 3 nodes come back. The static list is refreshed to a current 20-node snapshot with regeneration notes. Co-Authored-By: Claude Sonnet 5.5 --- src/api/evonodes.test.ts | 194 +++++++++++++++++++++++++++++++++++++++ src/api/evonodes.ts | 82 +++++++++++++++++ src/config.ts | 19 +++- src/main.ts | 10 +- 4 files changed, 299 insertions(+), 6 deletions(-) create mode 100644 src/api/evonodes.test.ts create mode 100644 src/api/evonodes.ts diff --git a/src/api/evonodes.test.ts b/src/api/evonodes.test.ts new file mode 100644 index 0000000..fb77d1a --- /dev/null +++ b/src/api/evonodes.test.ts @@ -0,0 +1,194 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { + MIN_DYNAMIC_EVONODES, + TESTNET_MASTERNODES_URL, + parseEvonodeAddresses, + resolveDapiAddresses, + resolveTestnetDapiAddresses, +} from './evonodes.js'; + +const node = (host: string, overrides: Record = {}) => ({ + proTxHash: 'aa', + address: `${host}:19999`, + addresses: { platform_https: [`${host}:1443`] }, + status: 'ENABLED', + platformHTTPPort: 1443, + versionCheck: 'success', + ...overrides, +}); + +const payload = (...nodes: unknown[]) => ({ success: true, data: nodes }); + +const FALLBACK = ['https://1.1.1.1:1443', 'https://1.1.1.2:1443', 'https://1.1.1.3:1443']; + +describe('parseEvonodeAddresses', () => { + it('keeps ENABLED nodes with a successful version check and maps them to :1443', () => { + const result = parseEvonodeAddresses( + payload( + node('68.67.122.1'), + node('68.67.122.2', { status: 'POSE_BANNED' }), + node('68.67.122.3', { versionCheck: 'fail' }), + node('68.67.122.4', { versionCheck: undefined }), + node('85.209.243.1') + ) + ); + + expect(result).toEqual(['https://68.67.122.1:1443', 'https://85.209.243.1:1443']); + }); + + it('ignores the Core P2P port and de-duplicates by host', () => { + const result = parseEvonodeAddresses( + payload(node('68.67.122.1'), node('68.67.122.1', { address: '68.67.122.1:12345' })) + ); + + expect(result).toEqual(['https://68.67.122.1:1443']); + }); + + it('accepts DNS names but drops unsafe or malformed hosts', () => { + const result = parseEvonodeAddresses( + payload( + node('evo1.example.org'), + node('x', { address: 'user@evil.example:19999' }), + node('x', { address: 'host/path:19999' }), + node('x', { address: '[::1]:19999' }), + node('x', { address: '' }), + node('x', { address: 42 }), + null, + 'junk' + ) + ); + + expect(result).toEqual(['https://evo1.example.org:1443']); + }); + + it.each([undefined, null, 'x', {}, { data: {} }, { success: false }])( + 'returns nothing for malformed payload %j', + (bad) => { + expect(parseEvonodeAddresses(bad)).toEqual([]); + } + ); +}); + +describe('resolveTestnetDapiAddresses', () => { + const fetchMock = vi.fn(); + + beforeEach(() => { + fetchMock.mockReset(); + vi.stubGlobal('fetch', fetchMock); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + const respond = (body: unknown, ok = true) => + fetchMock.mockResolvedValue({ + ok, + status: ok ? 200 : 503, + statusText: ok ? 'OK' : 'Service Unavailable', + json: async () => body, + }); + + it('uses only the live list when it has enough nodes', async () => { + respond(payload(node('10.0.0.1'), node('10.0.0.2'), node('10.0.0.3'), node('10.0.0.4'))); + + const result = await resolveTestnetDapiAddresses(FALLBACK); + + expect(result).toEqual([ + 'https://10.0.0.1:1443', + 'https://10.0.0.2:1443', + 'https://10.0.0.3:1443', + 'https://10.0.0.4:1443', + ]); + expect(fetchMock).toHaveBeenCalledOnce(); + expect(fetchMock.mock.calls[0][0]).toBe(TESTNET_MASTERNODES_URL); + }); + + it(`tops up with the static list below ${MIN_DYNAMIC_EVONODES} live nodes, without duplicates`, async () => { + respond(payload(node('10.0.0.1'), node('1.1.1.2'))); + + const result = await resolveTestnetDapiAddresses(FALLBACK); + + expect(result).toEqual([ + 'https://10.0.0.1:1443', + 'https://1.1.1.2:1443', + 'https://1.1.1.1:1443', + 'https://1.1.1.3:1443', + ]); + }); + + it('falls back to the static list when no node is healthy', async () => { + respond(payload(node('10.0.0.1', { status: 'POSE_BANNED' }))); + + await expect(resolveTestnetDapiAddresses(FALLBACK)).resolves.toEqual(FALLBACK); + }); + + it('falls back to the static list on a network error, without retrying', async () => { + fetchMock.mockRejectedValue(new TypeError('Failed to fetch')); + + await expect(resolveTestnetDapiAddresses(FALLBACK)).resolves.toEqual(FALLBACK); + expect(fetchMock).toHaveBeenCalledOnce(); + }); + + it('falls back to the static list on an HTTP error', async () => { + respond({}, false); + + await expect(resolveTestnetDapiAddresses(FALLBACK)).resolves.toEqual(FALLBACK); + expect(fetchMock).toHaveBeenCalledOnce(); + }); + + it('falls back to the static list on invalid JSON', async () => { + fetchMock.mockResolvedValue({ + ok: true, + status: 200, + statusText: 'OK', + json: async () => { + throw new SyntaxError('Unexpected token'); + }, + }); + + await expect(resolveTestnetDapiAddresses(FALLBACK)).resolves.toEqual(FALLBACK); + }); + + describe('resolveDapiAddresses', () => { + it('resolves the live list for testnet', async () => { + respond(payload(node('10.0.0.1'), node('10.0.0.2'), node('10.0.0.3'))); + + const result = await resolveDapiAddresses({ type: 'testnet', dapiAddresses: FALLBACK }); + + expect(result).toHaveLength(3); + expect(result?.[0]).toBe('https://10.0.0.1:1443'); + }); + + it('makes no request for devnets, mainnet or networks without addresses', async () => { + const devnet = ['https://68.67.122.254:1443']; + + await expect(resolveDapiAddresses({ type: 'devnet', dapiAddresses: devnet })).resolves.toBe(devnet); + await expect(resolveDapiAddresses({ type: 'mainnet' })).resolves.toBeUndefined(); + await expect(resolveDapiAddresses({ type: 'testnet' })).resolves.toBeUndefined(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + }); + + it('gives up after the timeout and uses the static list', async () => { + vi.useFakeTimers(); + fetchMock.mockImplementation( + (_url: string, init?: RequestInit) => + new Promise((_, reject) => { + init?.signal?.addEventListener('abort', () => + reject(Object.assign(new Error('aborted'), { name: 'AbortError' })) + ); + }) + ); + + const result = resolveTestnetDapiAddresses(FALLBACK, 5000); + await vi.advanceTimersByTimeAsync(5000); + + await expect(result).resolves.toEqual(FALLBACK); + expect(fetchMock).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/api/evonodes.ts b/src/api/evonodes.ts new file mode 100644 index 0000000..21efc7e --- /dev/null +++ b/src/api/evonodes.ts @@ -0,0 +1,82 @@ +import type { NetworkConfig } from '../config.js'; +import { fetchJson } from '../utils/fetch-json.js'; + +/** + * Quorum service lists every testnet masternode with its PoSe status and the + * result of its DAPI version check. It answers CORS requests from any origin + * (`access-control-allow-origin: *`, including preflights), so browsers can + * read it directly. + */ +export const TESTNET_MASTERNODES_URL = 'https://quorums.testnet.networks.dash.org/masternodes'; + +export const EVONODE_FETCH_TIMEOUT_MS = 5000; + +/** Below this many live nodes the fetched list is not trusted on its own. */ +export const MIN_DYNAMIC_EVONODES = 3; + +const DAPI_HTTPS_PORT = 1443; + +// Plain IPv4 / DNS hostnames only: the result is turned into a URL and handed +// to dapi-client, so anything exotic (IPv6 literals, userinfo, paths) is dropped. +const HOST_PATTERN = /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$/; + +/** + * Extract DAPI endpoints (`https://:1443`) of healthy evonodes from the + * quorum service payload. Healthy means PoSe status ENABLED and a successful + * DAPI version check. Order is preserved; duplicates are dropped. + */ +export function parseEvonodeAddresses(payload: unknown): string[] { + const data = (payload as { data?: unknown } | null | undefined)?.data; + if (!Array.isArray(data)) return []; + + const endpoints = new Set(); + for (const node of data) { + if (!node || typeof node !== 'object') continue; + const { address, status, versionCheck } = node as Record; + if (status !== 'ENABLED' || versionCheck !== 'success' || typeof address !== 'string') continue; + // `address` is the Core P2P endpoint (host:19999); only the host is reused. + const host = address.replace(/:\d+$/, ''); + if (!HOST_PATTERN.test(host)) continue; + endpoints.add(`https://${host}:${DAPI_HTTPS_PORT}`); + } + return [...endpoints]; +} + +/** + * Testnet DAPI endpoints for this session. Fetches the live evonode list + * (one attempt, 5 s) because certificates rotate every few days and nodes come + * and go, which makes a static list go stale. Falls back to `staticAddresses` + * when the fetch fails and tops the live list up with them when it yields + * fewer than {@link MIN_DYNAMIC_EVONODES} nodes. + */ +export async function resolveTestnetDapiAddresses( + staticAddresses: readonly string[], + timeoutMs: number = EVONODE_FETCH_TIMEOUT_MS +): Promise { + let live: string[] = []; + try { + live = parseEvonodeAddresses(await fetchJson(TESTNET_MASTERNODES_URL, {}, timeoutMs)); + } catch (error) { + console.warn('Could not fetch the testnet evonode list; using the built-in list:', error); + } + + if (live.length >= MIN_DYNAMIC_EVONODES) return live; + if (live.length > 0) { + console.warn(`Only ${live.length} live testnet evonodes found; adding the built-in list`); + } + return [...new Set([...live, ...staticAddresses])]; +} + +/** + * DAPI endpoints to dial for a network: testnet resolves the live evonode + * list (see {@link resolveTestnetDapiAddresses}); mainnet and devnets use + * their configured addresses unchanged and make no request. + */ +export async function resolveDapiAddresses( + config: Pick +): Promise { + if (config.type === 'testnet' && config.dapiAddresses) { + return resolveTestnetDapiAddresses(config.dapiAddresses); + } + return config.dapiAddresses; +} diff --git a/src/config.ts b/src/config.ts index cc8568a..3ac3655 100644 --- a/src/config.ts +++ b/src/config.ts @@ -47,9 +47,15 @@ export const TESTNET: NetworkConfig = { // No rpcUrl: trpc.digitalcash.dev is stuck on Core v23 and has no IS locks // past the V24 fork (block 1,578,000). IS locks come from the DAPI bloom // stream instead. Explicit addresses skip dapi-client's seed/SML discovery, - // which can't parse V24 CbTx v4 coinbases. Snapshot (2026-10-23) of ENABLED - // evonodes whose DAPI version check passed, with an IP-valid TLS cert and a - // CORS preflight that reflects the request origin. + // which can't parse V24 CbTx v4 coinbases. + // + // This list is only the FALLBACK: at client init the app fetches the live + // evonode list from the quorum service (see api/evonodes.ts) because nodes + // and their certificates rotate within days. Snapshot (2026-10-23) of + // ENABLED evonodes whose DAPI version check passed, each with an IP-valid + // TLS cert and a CORS preflight that reflects the request origin. To + // regenerate (candidates still need the cert/CORS check above): + // curl -s https://quorums.testnet.networks.dash.org/masternodes | jq -r '.data | map(select(.status=="ENABLED" and .versionCheck=="success") | .address | sub(":[0-9]+$"; "")) | .[]' dapiAddresses: [ 'https://68.67.122.1:1443', 'https://68.67.122.2:1443', @@ -65,7 +71,12 @@ export const TESTNET: NetworkConfig = { 'https://68.67.122.12:1443', 'https://85.209.243.1:1443', 'https://85.209.243.2:1443', - 'https://87.229.22.126:1443', + 'https://85.209.243.3:1443', + 'https://85.209.243.4:1443', + 'https://85.209.243.5:1443', + 'https://85.209.243.6:1443', + 'https://85.209.243.7:1443', + 'https://206.245.167.63:1443', ], }; diff --git a/src/main.ts b/src/main.ts index e87117b..1686c3b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -14,6 +14,7 @@ import { InsightClient, isAmbiguousBroadcastError } from './api/insight.js'; import type { IslockService } from './api/islock.js'; import { fetchNetworkStatus } from './api/network-status.js'; import { DAPIClient } from './api/dapi.js'; +import { resolveDapiAddresses } from './api/evonodes.js'; import { buildInstantAssetLockProof, buildChainAssetLockProof } from './proof/index.js'; import { bech32m } from '@scure/base'; import { privateKeyToWif, bytesToHex, abortableSleep } from './utils/index.js'; @@ -286,11 +287,16 @@ let warmupStarted = false; async function initClients(network: string): Promise { const config = getNetwork(network); insightClient = new InsightClient(config); - const { IslockService } = await loadIslockModule(); + // Testnet evonodes (and their certificates) rotate within days, so use the + // live list; the static one in config.ts is the fallback. + const [{ IslockService }, dapiAddresses] = await Promise.all([ + loadIslockModule(), + resolveDapiAddresses(config), + ]); islockService = new IslockService({ network, rpcUrl: config.rpcUrl, - dapiAddresses: config.dapiAddresses, + dapiAddresses, }); startNetworkStatusPolling(); } From 7b453e3f35dd9c003b0b8c6e426796e1ef84afe5 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 19:03:43 -0500 Subject: [PATCH 06/15] docs(testnet): align comments, docs and e2e with the DAPI stream model Testnet no longer uses JSON-RPC, so fix the stale mainnet/testnet wording in islock.ts, main.ts and the network-status tests, document the per-network InstantSend source in CLAUDE.md, and add a mock-mode e2e test asserting that testnet discovers evonodes from the quorum service and sends no request to any digitalcash.dev host. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 11 ++++++++++- e2e/deterministic.spec.ts | 35 ++++++++++++++++++++++++++++++++++ src/api/islock.ts | 9 +++++---- src/api/network-status.test.ts | 6 +++--- src/main.ts | 4 ++-- 5 files changed, 55 insertions(+), 10 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b26f79a..bffdac3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -41,7 +41,10 @@ src/ │ └── builder.ts # InstantSend lock proof building ├── api/ # Network communication │ ├── insight.ts # Insight API client (UTXO fetching, broadcast) -│ └── dapi.ts # DAPI client (Platform operations, InstantSend) +│ ├── dapi.ts # JSON-RPC client (mainnet InstantSend locks, best chain lock) +│ ├── dapi-subscription.ts # DAPI bloom-filter stream (testnet/devnet InstantSend locks) +│ ├── islock.ts # IslockService: picks the InstantSend lock source per network +│ └── evonodes.ts # Live testnet evonode list (static list in config.ts is the fallback) ├── platform/ # Dash Platform operations │ ├── identity.ts # Identity registration and top-up │ └── login.ts # Sign in with Dash: key checks and signing @@ -81,6 +84,12 @@ Uses random one-time keypair (not HD-derived) to add credits to an existing iden Network is determined by URL parameter: `?network=mainnet` (defaults to testnet). +InstantSend lock source and Platform status per network: + +- **mainnet**: JSON-RPC at `rpc.digitalcash.dev` (`rpcUrl` in `config.ts`). +- **testnet**: no JSON-RPC service (trpc.digitalcash.dev never upgraded to Core V24). The lock comes from the DAPI bloom-filter stream on evonodes, discovered from the quorum service at init with the static `dapiAddresses` as fallback. Platform status is read through the EvoSDK (`platform/status.ts`) because dapi-client's `platform.getStatus()` throws on testnet nodes. +- **devnets**: their configured `rpcUrl` if any, otherwise the DAPI stream over their `dapiAddresses`; Platform status through dapi-client. + ## Dependencies Core dependencies: `@dashevo/evo-sdk`, `@noble/hashes`, `@noble/secp256k1`, `@scure/bip32`, `@scure/bip39`, `bs58check`, `qrcode` diff --git a/e2e/deterministic.spec.ts b/e2e/deterministic.spec.ts index 7a787ae..af9fcdb 100644 --- a/e2e/deterministic.spec.ts +++ b/e2e/deterministic.spec.ts @@ -13,6 +13,41 @@ import { const MOCK_QUERY = '/?network=testnet&e2e=mock'; test.describe('Deterministic UI E2E (mock mode)', () => { + test('testnet discovers evonodes from the quorum service and never calls a digitalcash.dev host', async ({ page }) => { + const digitalcashRequests: string[] = []; + page.on('request', (request) => { + if (/(^|\.)digitalcash\.dev$/.test(new URL(request.url()).hostname)) { + digitalcashRequests.push(request.url()); + } + }); + await page.route('https://quorums.testnet.networks.dash.org/masternodes', (route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + headers: { 'access-control-allow-origin': '*' }, + body: JSON.stringify({ + success: true, + data: [1, 2, 3].map((n) => ({ + address: `203.0.113.${n}:19999`, + status: 'ENABLED', + versionCheck: 'success', + })), + }), + }) + ); + + // Client init (warmup) fetches the evonode list and starts network-status polling. + const evonodeRequest = page.waitForRequest('https://quorums.testnet.networks.dash.org/masternodes', { + timeout: 15000, + }); + await page.goto(MOCK_QUERY); + await evonodeRequest; + // Let the first network-status poll (Insight + Platform status) go out. + await page.waitForTimeout(2000); + + expect(digitalcashRequests).toEqual([]); + }); + test('create identity flow transitions to completion and DPNS registration', async ({ page }) => { await page.goto(MOCK_QUERY); diff --git a/src/api/islock.ts b/src/api/islock.ts index 58af0cd..ebc6fef 100644 --- a/src/api/islock.ts +++ b/src/api/islock.ts @@ -158,10 +158,11 @@ export class IslockService { } /** - * Whether a JSON-RPC endpoint is configured (mainnet/testnet). Devnets have - * none and must read Platform status over DAPI instead. The network-status - * poller uses this to avoid the dapi-client seed/SML address resolution, - * which can't complete in a browser on mainnet/testnet. + * Whether a JSON-RPC endpoint is configured (mainnet, or a devnet with an + * rpcUrl). Testnet and other devnets have none and read Platform status + * instead. The network-status poller uses this to avoid the dapi-client + * seed/SML address resolution, which can't complete in a browser on + * mainnet. */ get supportsJsonRpc(): boolean { return this.hasJsonRpc; diff --git a/src/api/network-status.test.ts b/src/api/network-status.test.ts index 2ef5046..245854c 100644 --- a/src/api/network-status.test.ts +++ b/src/api/network-status.test.ts @@ -9,8 +9,8 @@ type ChainLock = Awaited>; /** * Build stub clients. `platform` selects the DAPI path (devnet: - * supportsJsonRpc=false); `chainLock` selects the JSON-RPC path - * (mainnet/testnet: supportsJsonRpc=true). + * supportsJsonRpc=false; testnet also takes it, via the SDK); `chainLock` + * selects the JSON-RPC path (mainnet: supportsJsonRpc=true). */ function makeClients(opts: { coreHeight?: number | Error; @@ -121,7 +121,7 @@ describe('fetchNetworkStatus (DAPI / devnet path)', () => { }); }); -describe('fetchNetworkStatus (JSON-RPC / mainnet-testnet path)', () => { +describe('fetchNetworkStatus (JSON-RPC / mainnet path)', () => { it('reports healthy when Core chain-lock tracks the tip', async () => { const { insight, islock } = makeClients({ coreHeight: 10_700, diff --git a/src/main.ts b/src/main.ts index 1686c3b..77bdc91 100644 --- a/src/main.ts +++ b/src/main.ts @@ -3332,8 +3332,8 @@ function cancelChainlockFallback(): void { /** * Begin the chainlock fallback flow: poll Insight for the asset-lock tx's - * confirming block, poll Platform (with DAPI JSON-RPC as backup) for the - * chain-locked tip, and once `coreChainLockedHeight >= blockHeight` build a + * confirming block, poll for the chain-locked tip (JSON-RPC on mainnet, + * Platform status elsewhere), and once `coreChainLockedHeight >= blockHeight` build a * chain asset lock proof and resubmit the original Platform operation. */ async function startChainlockFallback(): Promise { From 49b2094967facb0c5624a82ab0d739ed685a6dbe Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 19:14:29 -0500 Subject: [PATCH 07/15] fix(testnet): harden client init, status routing and evonode parsing Review follow-ups: - initClients no longer installs a stale islock service when the user switched networks while the evonode list was loading. - evonode hosts that pass the character check but are not valid URLs (999.1.1.1) are dropped instead of making the DAPI client constructor throw for the whole list. - Platform status routes on the network config type rather than its name, so an unknown name that falls back to the testnet config still uses the SDK path. - connectPlatformSdk shares one in-flight connect between concurrent callers (status polls and write paths) instead of orphaning SDKs. - Trim duplicated comments and redundant tests. Co-Authored-By: Claude Sonnet 5.5 --- src/api/dapi-subscription.ts | 10 ++-- src/api/evonodes.test.ts | 4 +- src/api/evonodes.ts | 19 +++++-- src/api/islock.ts | 8 +-- src/api/network-status.ts | 5 +- src/api/platform-status-routing.test.ts | 44 ++++---------- src/main.ts | 17 +++--- src/platform/client.test.ts | 76 +++++++++++++++++++++++++ src/platform/client.ts | 29 ++++++++-- src/platform/status.ts | 7 ++- 10 files changed, 150 insertions(+), 69 deletions(-) create mode 100644 src/platform/client.test.ts diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index 1f10f89..2e88cfe 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -2,6 +2,7 @@ import DAPIClientModule from '@dashevo/dapi-client'; import dashcoreLib from '@dashevo/dashcore-lib'; +import { getNetwork } from '../config.js'; import { hash160 } from '../crypto/hash.js'; import { describeIslock } from '../utils/islock-debug.js'; import { fetchPlatformStatus, type PlatformStatus } from '../platform/status.js'; @@ -437,13 +438,12 @@ export class DAPISubscriptionClient { * Tenderdash is stuck). Fields are `undefined` when the masternode doesn't * report them. * - * Testnet reads through the EvoSDK: every testnet node omits the optional - * `state_sync` message that dapi-client's `platform.getStatus()` decoder - * dereferences unconditionally, so that call always throws there. Devnets - * keep the dapi-client gRPC call (see getCoreChainLockedHeight). + * Testnet reads through the EvoSDK (see `fetchPlatformStatus` for why); + * every other network keeps the dapi-client gRPC call. */ async getPlatformStatus(): Promise { - if (this.network === 'testnet') { + // By config type, not name: an unknown name falls back to the testnet config. + if (getNetwork(this.network).type === 'testnet') { return fetchPlatformStatus(this.network); } diff --git a/src/api/evonodes.test.ts b/src/api/evonodes.test.ts index fb77d1a..de4f0f2 100644 --- a/src/api/evonodes.test.ts +++ b/src/api/evonodes.test.ts @@ -52,6 +52,8 @@ describe('parseEvonodeAddresses', () => { node('x', { address: 'user@evil.example:19999' }), node('x', { address: 'host/path:19999' }), node('x', { address: '[::1]:19999' }), + node('999.1.1.1'), + node('1.2.3.4.5'), node('x', { address: '' }), node('x', { address: 42 }), null, @@ -185,7 +187,7 @@ describe('resolveTestnetDapiAddresses', () => { }) ); - const result = resolveTestnetDapiAddresses(FALLBACK, 5000); + const result = resolveTestnetDapiAddresses(FALLBACK); await vi.advanceTimersByTimeAsync(5000); await expect(result).resolves.toEqual(FALLBACK); diff --git a/src/api/evonodes.ts b/src/api/evonodes.ts index 21efc7e..aa10209 100644 --- a/src/api/evonodes.ts +++ b/src/api/evonodes.ts @@ -9,7 +9,7 @@ import { fetchJson } from '../utils/fetch-json.js'; */ export const TESTNET_MASTERNODES_URL = 'https://quorums.testnet.networks.dash.org/masternodes'; -export const EVONODE_FETCH_TIMEOUT_MS = 5000; +const EVONODE_FETCH_TIMEOUT_MS = 5000; /** Below this many live nodes the fetched list is not trusted on its own. */ export const MIN_DYNAMIC_EVONODES = 3; @@ -37,7 +37,15 @@ export function parseEvonodeAddresses(payload: unknown): string[] { // `address` is the Core P2P endpoint (host:19999); only the host is reused. const host = address.replace(/:\d+$/, ''); if (!HOST_PATTERN.test(host)) continue; - endpoints.add(`https://${host}:${DAPI_HTTPS_PORT}`); + const endpoint = `https://${host}:${DAPI_HTTPS_PORT}`; + // The regex alone admits non-URLs such as 999.1.1.1, and one of those + // would make the DAPI client constructor throw for the whole list. + try { + new URL(endpoint); + } catch { + continue; + } + endpoints.add(endpoint); } return [...endpoints]; } @@ -50,12 +58,13 @@ export function parseEvonodeAddresses(payload: unknown): string[] { * fewer than {@link MIN_DYNAMIC_EVONODES} nodes. */ export async function resolveTestnetDapiAddresses( - staticAddresses: readonly string[], - timeoutMs: number = EVONODE_FETCH_TIMEOUT_MS + staticAddresses: readonly string[] ): Promise { let live: string[] = []; try { - live = parseEvonodeAddresses(await fetchJson(TESTNET_MASTERNODES_URL, {}, timeoutMs)); + live = parseEvonodeAddresses( + await fetchJson(TESTNET_MASTERNODES_URL, {}, EVONODE_FETCH_TIMEOUT_MS) + ); } catch (error) { console.warn('Could not fetch the testnet evonode list; using the built-in list:', error); } diff --git a/src/api/islock.ts b/src/api/islock.ts index ebc6fef..eb07377 100644 --- a/src/api/islock.ts +++ b/src/api/islock.ts @@ -149,9 +149,8 @@ export class IslockService { } /** - * Read of the Platform chain-locked Dash Core height. Used by the - * chainlock fallback; testnet reads it through the EvoSDK and devnets over - * direct gRPC — see DAPISubscriptionClient for why. + * Platform's chain-locked Dash Core height, for the chainlock fallback. + * See DAPISubscriptionClient.getCoreChainLockedHeight for how it is read. */ async getCoreChainLockedHeight(): Promise { return this.subscriptionClient.getCoreChainLockedHeight(); @@ -180,8 +179,7 @@ export class IslockService { /** * Read Platform/Tenderdash status (chain-locked Core height, latest Platform * block height + timestamp). Used by the network-health indicator on - * testnet (via the EvoSDK) and devnets (via DAPI over their explicit - * dapiAddresses). + * testnet and devnets; see DAPISubscriptionClient.getPlatformStatus. */ async getPlatformStatus(): Promise { return this.subscriptionClient.getPlatformStatus(); diff --git a/src/api/network-status.ts b/src/api/network-status.ts index 6556a77..5fa7bde 100644 --- a/src/api/network-status.ts +++ b/src/api/network-status.ts @@ -39,9 +39,8 @@ export async function fetchNetworkStatus( // in a browser there (seed/SML resolution fails on bad certs + CORS), so // we deliberately avoid it. // - testnet/devnets (no JSON-RPC): read full Platform status, which also - // yields Tenderdash block height + age. Testnet goes through the EvoSDK - // (dapi-client's status decoder throws on testnet nodes); devnets use - // DAPI over their explicit dapiAddresses. IslockService picks the path. + // yields Tenderdash block height + age. IslockService picks the path + // (EvoSDK on testnet, DAPI over explicit dapiAddresses on devnets). const useDapiPlatformStatus = !islock.supportsJsonRpc; // Bound the Insight retry so a flaky endpoint can't stretch one poll past the diff --git a/src/api/platform-status-routing.test.ts b/src/api/platform-status-routing.test.ts index a61f008..3b9da63 100644 --- a/src/api/platform-status-routing.test.ts +++ b/src/api/platform-status-routing.test.ts @@ -25,13 +25,8 @@ import { fetchNetworkStatus } from './network-status.js'; import { TESTNET } from '../config.js'; import type { InsightClient } from './insight.js'; -const insightAt = (height: number | Error): InsightClient => - ({ - getBlockHeight: async () => { - if (height instanceof Error) throw height; - return height; - }, - }) as unknown as InsightClient; +const insightAt = (height: number): InsightClient => + ({ getBlockHeight: async () => height }) as unknown as InsightClient; const freshStatus = (overrides: Record = {}) => ({ coreChainLockedHeight: 1_578_100, @@ -51,6 +46,7 @@ describe('Platform status routing', () => { afterEach(() => { vi.unstubAllGlobals(); + vi.restoreAllMocks(); }); describe('DAPISubscriptionClient', () => { @@ -81,6 +77,15 @@ describe('Platform status routing', () => { await expect(client.getCoreChainLockedHeight()).resolves.toBeUndefined(); }); + it('routes by config type, so an unknown name that falls back to testnet uses the SDK', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + mocks.fetchPlatformStatus.mockResolvedValue(freshStatus()); + const client = new DAPISubscriptionClient({ network: 'Testnet' }); + + await expect(client.getCoreChainLockedHeight()).resolves.toBe(1_578_100); + expect(mocks.dapiGetStatus).not.toHaveBeenCalled(); + }); + it('keeps the dapi-client call on devnets', async () => { mocks.dapiGetStatus.mockResolvedValue({ chain: { coreChainLockedHeight: 4321, latestBlockHeight: 99n }, @@ -131,15 +136,6 @@ describe('Platform status routing', () => { expect(fetchSpy).not.toHaveBeenCalled(); }); - it('stays healthy when the node omits optional fields', async () => { - mocks.fetchPlatformStatus.mockResolvedValue({}); - - const status = await fetchNetworkStatus(insightAt(1_578_102), testnetIslock()); - - expect(status.health).toBe('healthy'); - expect(status.coreChainLockedHeight).toBeUndefined(); - }); - it('reports degraded only when the SDK call fails', async () => { mocks.fetchPlatformStatus.mockRejectedValue(new Error('Timed out while reading Platform status')); @@ -148,21 +144,5 @@ describe('Platform status routing', () => { expect(status.health).toBe('degraded'); expect(status.reasons).toEqual(['Platform (DAPI) status unreachable']); }); - - it('reports unknown when both Insight and the SDK call fail', async () => { - mocks.fetchPlatformStatus.mockRejectedValue(new Error('down')); - - const status = await fetchNetworkStatus(insightAt(new Error('down')), testnetIslock()); - - expect(status.health).toBe('unknown'); - }); - - it('still flags a genuinely stalled chain-lock', async () => { - mocks.fetchPlatformStatus.mockResolvedValue(freshStatus({ coreChainLockedHeight: 1_577_000 })); - - const status = await fetchNetworkStatus(insightAt(1_578_102), testnetIslock()); - - expect(status.health).toBe('stalled'); - }); }); }); diff --git a/src/main.ts b/src/main.ts index 77bdc91..429228b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -293,6 +293,10 @@ async function initClients(network: string): Promise { loadIslockModule(), resolveDapiAddresses(config), ]); + // The evonode fetch can take seconds. If the user switched networks meanwhile, + // the newer init owns the clients; installing these would pair this network's + // IS-lock service with the other network's Insight client. + if (state.network !== network) return; islockService = new IslockService({ network, rpcUrl: config.rpcUrl, @@ -3369,15 +3373,10 @@ async function startChainlockFallback(): Promise { ); // Poll #2: chain-locked Dash Core height. JSON-RPC `getbestchainlock` - // first (mainnet only; it returns nothing without an rpcUrl), then the - // Platform status via IslockService. On testnet that is - // `sdk.system.status()` (dapi-client's decoder throws on every testnet - // node, which omit `state_sync`). On devnets it is direct gRPC - // `platform.getStatus()` via @dashevo/dapi-client: in pre-dev.7 builds the - // SDK's testnet trusted context returned testnet-cached values on devnets. - // SDK 3.1.0-dev.7 fixes this with per-devnet trusted contexts, but the - // direct dapi-client call works uniformly across trusted and non-trusted - // devnets, so we keep it there. + // first (it returns nothing without an rpcUrl, e.g. on testnet), then the + // Platform status via IslockService: the EvoSDK on testnet, direct gRPC via + // @dashevo/dapi-client elsewhere (it works uniformly across trusted and + // non-trusted devnets; see DAPISubscriptionClient.getCoreChainLockedHeight). const chainLockPoll = (async (): Promise => { while (!signal.aborted) { let height: number | undefined; diff --git a/src/platform/client.test.ts b/src/platform/client.test.ts new file mode 100644 index 0000000..de282b0 --- /dev/null +++ b/src/platform/client.test.ts @@ -0,0 +1,76 @@ +import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'; + +const sdkState = vi.hoisted(() => ({ + created: 0, + connect: vi.fn(), +})); + +vi.mock('./sdkModule.js', () => ({ + loadSdkModule: async () => ({ + EvoSDK: { + testnetTrusted: () => { + sdkState.created++; + const sdk = { + isConnected: false, + connect: async () => { + await sdkState.connect(); + sdk.isConnected = true; + }, + }; + return sdk; + }, + }, + }), +})); + +describe('connectPlatformSdk', () => { + let connectPlatformSdk: typeof import('./client.js').connectPlatformSdk; + + beforeEach(async () => { + // The SDK cache is module state; start each test from an empty one. + vi.resetModules(); + ({ connectPlatformSdk } = await import('./client.js')); + sdkState.created = 0; + sdkState.connect.mockReset(); + sdkState.connect.mockResolvedValue(undefined); + vi.spyOn(console, 'log').mockImplementation(() => {}); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('shares one SDK between concurrent callers', async () => { + const [a, b, c] = await Promise.all([ + connectPlatformSdk('testnet', { maxAttempts: 1 }), + connectPlatformSdk('testnet', { maxAttempts: 1 }), + connectPlatformSdk('testnet', { maxAttempts: 1 }), + ]); + + expect(a).toBe(b); + expect(b).toBe(c); + expect(sdkState.created).toBe(1); + expect(sdkState.connect).toHaveBeenCalledOnce(); + }); + + it('reuses the connected SDK on later calls', async () => { + const first = await connectPlatformSdk('testnet', { maxAttempts: 1 }); + const second = await connectPlatformSdk('testnet', { maxAttempts: 1 }); + + expect(second).toBe(first); + expect(sdkState.created).toBe(1); + }); + + it('lets the next caller retry after a failed connect', async () => { + sdkState.connect.mockRejectedValueOnce(new Error('connect failed')); + + const failed = await Promise.allSettled([ + connectPlatformSdk('testnet', { maxAttempts: 1 }), + connectPlatformSdk('testnet', { maxAttempts: 1 }), + ]); + expect(failed.map((r) => r.status)).toEqual(['rejected', 'rejected']); + + await expect(connectPlatformSdk('testnet', { maxAttempts: 1 })).resolves.toBeDefined(); + expect(sdkState.created).toBe(2); + }); +}); diff --git a/src/platform/client.ts b/src/platform/client.ts index bb56084..ecf839a 100644 --- a/src/platform/client.ts +++ b/src/platform/client.ts @@ -78,15 +78,15 @@ async function createPlatformSdk(network: PlatformNetwork): Promise { return EvoSDK.testnetTrusted(options); } -export async function connectPlatformSdk( +// In-flight connects, so concurrent callers (background status polls, write +// paths) share one SDK instead of each opening a connection and orphaning all +// but the last. +const pendingConnects = new Map>(); + +async function openPlatformSdk( network: PlatformNetwork, retryOptions?: RetryOptions ): Promise { - const cached = sdkCache.get(network); - if (cached && cached.isConnected) { - return cached; - } - const sdk = await createPlatformSdk(network); console.log(`Connecting to ${network}...`); @@ -97,6 +97,23 @@ export async function connectPlatformSdk( return sdk; } +export async function connectPlatformSdk( + network: PlatformNetwork, + retryOptions?: RetryOptions +): Promise { + const cached = sdkCache.get(network); + if (cached && cached.isConnected) { + return cached; + } + + let pending = pendingConnects.get(network); + if (!pending) { + pending = openPlatformSdk(network, retryOptions).finally(() => pendingConnects.delete(network)); + pendingConnects.set(network, pending); + } + return pending; +} + export function disconnectPlatformSdk(network: PlatformNetwork): void { sdkCache.delete(network); } diff --git a/src/platform/status.ts b/src/platform/status.ts index e8b720a..89037bc 100644 --- a/src/platform/status.ts +++ b/src/platform/status.ts @@ -19,7 +19,6 @@ function positiveInteger(value: unknown): number | undefined { if (typeof value !== 'number' && typeof value !== 'bigint' && typeof value !== 'string') { return undefined; } - if (value === '') return undefined; const number = Number(value); return Number.isSafeInteger(number) && number > 0 ? number : undefined; } @@ -42,9 +41,11 @@ export async function fetchPlatformStatus(network: string): Promise { const status = await sdk.system.status(); + // wasm getters build a new object per access, so read `chain` once. + const chain = status?.chain; return { - coreChainLockedHeight: positiveInteger(status?.chain?.core_chain_locked_height), - latestBlockHeight: positiveInteger(status?.chain?.latest_block_height), + coreChainLockedHeight: positiveInteger(chain?.core_chain_locked_height), + latestBlockHeight: positiveInteger(chain?.latest_block_height), latestBlockTimeMs: positiveInteger(status?.time?.block), }; }, From d4733900631a71a5a3957f0671bb4fbecbc7b702 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 19:17:04 -0500 Subject: [PATCH 08/15] fix(islock): fail the subscription before broadcast when every node fails The caller broadcasts the asset-lock tx as soon as subscribeForInstantSendLock returns. When every node attempt had already failed inside the readiness window or initial open loop, it used to return a handle whose wait() rejected later, so funds were committed with no listener. It now rejects itself with the same "N nodes tried, last error" message; main.ts's existing catch turns that into the retryable ISLOCK error with nothing broadcast. Failures after subscribe has returned still surface through wait(). Co-Authored-By: Claude Sonnet 5.5 --- src/api/dapi-subscription-multi.test.ts | 40 ++++++++++++++++++++----- src/api/dapi-subscription.ts | 17 +++++++++-- src/api/islock.test.ts | 13 ++++++++ 3 files changed, 59 insertions(+), 11 deletions(-) diff --git a/src/api/dapi-subscription-multi.test.ts b/src/api/dapi-subscription-multi.test.ts index 771bdec..601cc14 100644 --- a/src/api/dapi-subscription-multi.test.ts +++ b/src/api/dapi-subscription-multi.test.ts @@ -226,7 +226,7 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { expect(new TextDecoder().decode(bytes)).toBe(TXID); }); - it('rejects naming the nodes tried and the last error when every node fails', async () => { + it('rejects wait() naming the nodes tried and the last error when every node fails after readiness', async () => { const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); const sub = await startReady(client); const outcome = expect(sub.wait()).rejects.toThrow(/3 nodes tried.*last error: boom 2/); @@ -236,23 +236,47 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { for (const node of nodeClients()) expect(node.disconnect).toHaveBeenCalled(); }); - it('rejects immediately without waiting for the readiness cap when all nodes fail on connect', async () => { + it('still returns a handle when readiness comes from the cap, and a later total failure surfaces via wait()', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const pending = client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT); + await vi.advanceTimersByTimeAsync(ISLOCK_READINESS_CAP_MS); + const sub = await pending; // streams are open but silent: returns at the cap + + const outcome = expect(sub.wait()).rejects.toThrow(/3 nodes tried.*last error: late boom 2/); + liveStreams().forEach((stream, i) => stream.emit('error', new Error(`late boom ${i}`))); + await outcome; + }); + + it('rejects subscribe itself, before returning, when every stream fails inside the readiness window', async () => { + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const pending = client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT); + const outcome = expect(pending).rejects.toThrow( + new RegExp(`InstantSend lock subscription failed for ${TXID}: 3 nodes tried, last error: boom 2`) + ); + await flush(); // streams opened, nothing delivered yet + + liveStreams().forEach((stream, i) => stream.emit('error', new Error(`boom ${i}`))); + await outcome; + for (const node of nodeClients()) expect(node.disconnect).toHaveBeenCalled(); + }); + + it('rejects subscribe immediately, without the readiness cap, when all nodes fail on connect', async () => { for (const host of addresses(3).map((a) => new URL(a).hostname)) state.deadHosts.add(host); const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); const pending = client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT); - await flush(); - const sub = await pending; - await expect(sub.wait()).rejects.toThrow(/3 nodes tried.*Response closed without headers/); + const outcome = expect(pending).rejects.toThrow(/3 nodes tried.*Response closed without headers/); + await flush(); // far less than ISLOCK_READINESS_CAP_MS + await outcome; }); - it('caps total attempts when replacements keep failing', async () => { + it('rejects subscribe after the attempt cap when replacements keep failing', async () => { const many = addresses(20); for (const a of many) state.deadHosts.add(new URL(a).hostname); const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: many }); const pending = client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT); + const outcome = expect(pending).rejects.toThrow(new RegExp(`${ISLOCK_MAX_NODE_ATTEMPTS} nodes tried`)); await flush(); - const sub = await pending; - await expect(sub.wait()).rejects.toThrow(new RegExp(`${ISLOCK_MAX_NODE_ATTEMPTS} nodes tried`)); + await outcome; expect(nodeClients()).toHaveLength(ISLOCK_MAX_NODE_ATTEMPTS); }); diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index 2e88cfe..d973077 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -262,7 +262,9 @@ export class DAPISubscriptionClient { * subscribeToTransactionsWithProofs resolves before any connection exists, so * readiness is approximated: return once any stream delivers a message (the * server replays recent blocks, usually within ~1 s) or after the readiness - * cap, whichever comes first. The remaining streams keep connecting. + * cap, whichever comes first. The remaining streams keep connecting. If every + * node attempt has already failed by then, this rejects instead of returning + * a handle, so nothing is broadcast without a listener. */ private async subscribeOnMultipleNodes( txid: string, @@ -279,6 +281,9 @@ export class DAPISubscriptionClient { let markReady!: () => void; const ready = new Promise((resolve) => { markReady = resolve; }); const readyTimerId = setTimeout(markReady, ISLOCK_READINESS_CAP_MS); + // Set when every node attempt failed. Only read once, right after the + // readiness wait, to fail before the caller broadcasts. + let allFailed: Error | undefined; const lockPromise = new Promise((resolve, reject) => { const slots = new Set(); @@ -334,9 +339,11 @@ export class DAPISubscriptionClient { openNode(); } else if (slots.size === 0) { const reason = error instanceof Error ? error.message : String(error); - finish(() => reject(new Error( + const exhausted = new Error( `InstantSend lock subscription failed for ${txid}: ${attempts} nodes tried, last error: ${reason}` - ))); + ); + allFailed = exhausted; + finish(() => reject(exhausted)); } }; @@ -393,6 +400,10 @@ export class DAPISubscriptionClient { lockPromise.catch(() => {}); await ready; + // The caller broadcasts the asset lock as soon as this returns, so a + // subscription with no live stream must stop the flow before funds are + // committed. Failures after this point surface through wait(). + if (allFailed) throw allFailed; return { wait: () => lockPromise }; } diff --git a/src/api/islock.test.ts b/src/api/islock.test.ts index 47c9359..9405120 100644 --- a/src/api/islock.test.ts +++ b/src/api/islock.test.ts @@ -83,6 +83,19 @@ describe('IslockService', () => { await expect(handle.wait()).resolves.toBe(bytes); }); + it('propagates a failed subscription so the caller stops before broadcasting', async () => { + mocks.subscribeForInstantSendLock.mockRejectedValue( + new Error('InstantSend lock subscription failed for txid: 3 nodes tried, last error: boom') + ); + const service = new IslockService({ network: 'testnet', dapiAddresses: ['https://127.0.0.1:1443'] }); + + await expect( + service.subscribeForInstantSendLock('txid', new Uint8Array([4]), { txid: 'prevout', vout: 0 }) + ).rejects.toThrow(/3 nodes tried/); + // No tripwire poller is left running for a subscription that never existed. + expect(mocks.getTransactionLockStatus).not.toHaveBeenCalled(); + }); + it('keeps the pre-broadcast DAPI subscription path for devnets without RPC', async () => { const bytes = new Uint8Array([9, 8, 7]); const subHandle = { wait: vi.fn().mockResolvedValue(bytes) }; From e7e981c10219b05b2ea3a88e9f3076130840e759 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 19:38:29 -0500 Subject: [PATCH 09/15] fix(islock): race the start height across nodes instead of one random pick The one-off getBestBlockHeight before opening streams went through the shared random-pick client. When it picked an unreachable node the browser's TCP connect hung ~75 s before failover, with nothing broadcast meanwhile (measured: 75 s from subscribe to broadcast in the funded browser test). The multi-node path now asks the first three nodes of the shuffled list at once, each through the single-address client its stream will reuse, with an 8 s per-request deadline. The first valid height wins; it fails only when all of them fail or time out, with the usual "N nodes tried, last error" message and the probe clients disconnected, before anything is broadcast. Caller aborts also stop the wait. The single-node path is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- src/api/dapi-subscription-multi.test.ts | 95 +++++++++++++++- src/api/dapi-subscription.ts | 142 +++++++++++++++++++++--- 2 files changed, 220 insertions(+), 17 deletions(-) diff --git a/src/api/dapi-subscription-multi.test.ts b/src/api/dapi-subscription-multi.test.ts index 601cc14..616d461 100644 --- a/src/api/dapi-subscription-multi.test.ts +++ b/src/api/dapi-subscription-multi.test.ts @@ -5,6 +5,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; const state = vi.hoisted(() => ({ clients: [] as any[], deadHosts: new Set(), + // Hosts whose best-block-height call hangs forever / rejects. + hungHeightHosts: new Set(), + failedHeightHosts: new Set(), // Hosts whose subscribe call stays pending until releaseSlow() is called. slowHosts: new Set(), slowWaiters: [] as Array<() => void>, @@ -26,7 +29,13 @@ vi.mock('@dashevo/dapi-client', () => { this.options = options; state.clients.push(this); this.core = { - getBestBlockHeight: vi.fn(async () => state.height), + getBestBlockHeight: vi.fn(async () => { + const only = options.dapiAddresses?.length === 1 ? options.dapiAddresses[0].host : undefined; + // A blackholed node never answers (the real transport gives up after ~75 s). + if (only && state.hungHeightHosts.has(only)) return new Promise(() => {}); + if (only && state.failedHeightHosts.has(only)) throw new Error('GrpcError: height refused'); + return state.height; + }), subscribeToTransactionsWithProofs: vi.fn(async (_filter: unknown, _opts: unknown) => { if (options.dapiAddresses?.length === 1 && state.deadHosts.has(options.dapiAddresses[0].host)) { throw new Error('GrpcError: Response closed without headers'); @@ -72,6 +81,7 @@ import { DAPISubscriptionClient, ISLOCK_CONCURRENT_NODES, ISLOCK_MAX_NODE_ATTEMPTS, + ISLOCK_HEIGHT_TIMEOUT_MS, ISLOCK_READINESS_CAP_MS, } from './dapi-subscription.js'; @@ -112,6 +122,8 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { vi.useFakeTimers(); state.clients.length = 0; state.deadHosts.clear(); + state.hungHeightHosts.clear(); + state.failedHeightHosts.clear(); state.slowHosts.clear(); state.slowWaiters.length = 0; state.height = 100; @@ -137,11 +149,12 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { for (const host of hosts) expect(all.map((a) => new URL(a).hostname)).toContain(host); expect(nodes[0].options.dapiAddresses[0]).toMatchObject({ protocol: 'https', port: 1443 }); - // Height comes from the shared failover client, once, and every stream starts from height - 10. + // Height is asked of the same per-node clients (not the shared random-pick + // client), once each, and every stream starts from height - 10. const shared = state.clients.find((c) => c.options.dapiAddresses?.length === 5); - expect(shared.core.getBestBlockHeight).toHaveBeenCalledTimes(1); + expect(shared.core.getBestBlockHeight).not.toHaveBeenCalled(); for (const node of nodes) { - expect(node.core.getBestBlockHeight).not.toHaveBeenCalled(); + expect(node.core.getBestBlockHeight).toHaveBeenCalledTimes(1); expect(node.core.subscribeToTransactionsWithProofs).toHaveBeenCalledTimes(1); expect(node.core.subscribeToTransactionsWithProofs.mock.calls[0][1]).toEqual({ fromBlockHeight: 90, @@ -226,6 +239,80 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { expect(new TextDecoder().decode(bytes)).toBe(TXID); }); + describe('block height race', () => { + it('is not delayed by a node whose height request hangs', async () => { + state.hungHeightHosts.add('node0.test'); + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const sub = await startReady(client); // no timers advanced: far below the 8 s deadline + + expect(liveStreams()).toHaveLength(3); + for (const node of nodeClients()) { + expect(node.core.subscribeToTransactionsWithProofs.mock.calls[0][1]).toEqual({ + fromBlockHeight: 90, + count: 0, + }); + } + liveStreams()[1].emit('data', lockMessage(TXID)); + await sub.wait(); + }); + + it('survives nodes whose height request fails as long as one answers', async () => { + state.failedHeightHosts.add('node0.test'); + state.hungHeightHosts.add('node1.test'); + state.height = 500; // only node2 answers + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const sub = await startReady(client); + + for (const node of nodeClients()) { + expect(node.core.subscribeToTransactionsWithProofs.mock.calls[0][1].fromBlockHeight).toBe(490); + } + liveStreams()[0].emit('data', lockMessage(TXID)); + await sub.wait(); + }); + + it('rejects within the per-request deadline, naming the nodes tried, when every node hangs', async () => { + for (const host of ['node0.test', 'node1.test', 'node2.test']) state.hungHeightHosts.add(host); + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const pending = client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT); + const outcome = expect(pending).rejects.toThrow( + new RegExp(`failed for ${TXID}: 3 nodes tried, last error: getBestBlockHeight timed out after ${ISLOCK_HEIGHT_TIMEOUT_MS}ms`) + ); + + await vi.advanceTimersByTimeAsync(ISLOCK_HEIGHT_TIMEOUT_MS - 1); + expect(nodeClients().flatMap((c) => c.streams)).toHaveLength(0); + await vi.advanceTimersByTimeAsync(1); + await outcome; + + // Nothing was opened and every probe client was cleaned up. + expect(liveStreams()).toHaveLength(0); + for (const node of nodeClients()) { + expect(node.core.subscribeToTransactionsWithProofs).not.toHaveBeenCalled(); + expect(node.disconnect).toHaveBeenCalled(); + } + }); + + it('rejects at once when every node fails its height request', async () => { + for (const host of ['node0.test', 'node1.test', 'node2.test']) state.failedHeightHosts.add(host); + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const pending = client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT); + const outcome = expect(pending).rejects.toThrow(/3 nodes tried.*height refused/); + await flush(); + await outcome; + }); + + it('stops waiting for heights when the caller aborts', async () => { + for (const host of ['node0.test', 'node1.test', 'node2.test']) state.hungHeightHosts.add(host); + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const controller = new AbortController(); + const pending = client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT, undefined, controller.signal); + const outcome = expect(pending).rejects.toThrow(`InstantSend lock subscription aborted for ${TXID}`); + await flush(); + controller.abort(); + await outcome; + for (const node of nodeClients()) expect(node.disconnect).toHaveBeenCalled(); + }); + }); + it('rejects wait() naming the nodes tried and the last error when every node fails after readiness', async () => { const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); const sub = await startReady(client); diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index d973077..cdf3b92 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -35,6 +35,8 @@ export interface DAPISubscriptionConfig { export const ISLOCK_CONCURRENT_NODES = 3; /** Total streams opened per subscription, initial ones plus replacements for failed ones. */ export const ISLOCK_MAX_NODE_ATTEMPTS = ISLOCK_CONCURRENT_NODES + 6; +/** Deadline for each node's best-block-height answer before the stream starts. */ +export const ISLOCK_HEIGHT_TIMEOUT_MS = 8000; /** Longest subscribeForInstantSendLock waits for a first stream message before returning. */ export const ISLOCK_READINESS_CAP_MS = 3000; @@ -94,6 +96,101 @@ export class DAPISubscriptionClient { this.dapiClient = new DAPIClientClass(options); } + /** A client pinned to one node, so streams and height probes can't land on the same node twice. */ + private createNodeClient(address: DapiAddress): any { + return new DAPIClientClass({ ...CLIENT_OPTIONS, dapiAddresses: [address] }); + } + + private tryCreateNodeClient(address: DapiAddress): any | undefined { + try { + return this.createNodeClient(address); + } catch (error) { + console.warn(`[islock-sub] could not create client for ${address.host}:${address.port}:`, error); + return undefined; + } + } + + private disconnectQuietly(client: any | undefined): void { + if (!client) return; + try { + Promise.resolve(client.disconnect()).catch(() => {}); + } catch { /* ignore */ } + } + + /** + * Ask every client for the best block height at once and take the first + * success. Each request has its own deadline because a blackholed node never + * answers and the transport only gives up after ~75 s. Rejects only when + * every node failed (same message shape as a failed stream subscription), or + * when `signal` aborts. + */ + private raceBestBlockHeight( + txid: string, + clients: Array, + signal?: AbortSignal + ): Promise { + return new Promise((resolve, reject) => { + let done = false; + let failures = 0; + const timers = new Set>(); + + const settle = (fn: () => void): void => { + if (done) return; + done = true; + for (const timer of timers) clearTimeout(timer); + signal?.removeEventListener('abort', onAbort); + fn(); + }; + const onAbort = (): void => { + settle(() => reject(new Error(`InstantSend lock subscription aborted for ${txid}`))); + }; + const failOne = (error: unknown): void => { + if (done) return; + console.warn('[islock-sub] block height request failed:', error); + if (++failures < clients.length) return; + const reason = error instanceof Error ? error.message : String(error); + settle(() => reject(new Error( + `InstantSend lock subscription failed for ${txid}: ${clients.length} nodes tried, last error: ${reason}` + ))); + }; + + if (signal?.aborted) { + onAbort(); + return; + } + signal?.addEventListener('abort', onAbort, { once: true }); + + for (const client of clients) { + if (!client) { + failOne(new Error('Could not create a client for the node')); + continue; + } + let answered = false; + const timer = setTimeout(() => { + if (answered) return; + answered = true; + failOne(new Error(`getBestBlockHeight timed out after ${ISLOCK_HEIGHT_TIMEOUT_MS}ms`)); + }, ISLOCK_HEIGHT_TIMEOUT_MS); + timers.add(timer); + Promise.resolve() + .then(() => client.core.getBestBlockHeight()) + .then((height: unknown) => { + if (answered) return; + answered = true; + if (typeof height !== 'number' || !Number.isFinite(height) || height <= 0) { + failOne(new Error(`Invalid block height ${String(height)}`)); + return; + } + settle(() => resolve(height)); + }, (error: unknown) => { + if (answered) return; + answered = true; + failOne(error); + }); + } + }); + } + private createBloomFilter( pubKeyHash: Uint8Array, outpoint: { txid: string; vout: number } @@ -155,16 +252,31 @@ export class DAPISubscriptionClient { const bloomFilter = this.createBloomFilter(hash160(publicKey), utxo); onProgress?.('Getting current block height...'); - const currentHeight: number = await this.dapiClient.core.getBestBlockHeight(); - console.log('[islock-sub] Current block height:', currentHeight); - const fromBlockHeight = Math.max(1, currentHeight - 10); - if (this.nodeAddresses.length >= 2) { + // The shared client picks one random node and waits out its full connect + // timeout (~75 s in browsers) when that node is unreachable, with nothing + // broadcast meanwhile. Ask the nodes the streams will use, all at once. + const nodes = shuffled(this.nodeAddresses); + const clients = nodes + .slice(0, ISLOCK_CONCURRENT_NODES) + .map((address) => this.tryCreateNodeClient(address)); + let currentHeight: number; + try { + currentHeight = await this.raceBestBlockHeight(txid, clients, signal); + } catch (error) { + for (const client of clients) this.disconnectQuietly(client); + throw error; + } + console.log('[islock-sub] Current block height:', currentHeight); return this.subscribeOnMultipleNodes( - txid, bloomFilter, fromBlockHeight, timeoutMs, onProgress, signal + txid, bloomFilter, Math.max(1, currentHeight - 10), timeoutMs, nodes, clients, onProgress, signal ); } + const currentHeight: number = await this.dapiClient.core.getBestBlockHeight(); + console.log('[islock-sub] Current block height:', currentHeight); + const fromBlockHeight = Math.max(1, currentHeight - 10); + onProgress?.(`Subscribing from block ${fromBlockHeight}...`); const stream = await this.dapiClient.core.subscribeToTransactionsWithProofs( bloomFilter, @@ -271,11 +383,15 @@ export class DAPISubscriptionClient { bloomFilter: ReturnType, fromBlockHeight: number, timeoutMs: number, + nodes: DapiAddress[], + // Clients already created for nodes[0..n) while fetching the height; the + // streams reuse them. Entries are undefined where creation threw. + initialClients: Array, onProgress?: (message: string) => void, signal?: AbortSignal ): Promise<{ wait: () => Promise }> { - const nodes = shuffled(this.nodeAddresses); - const initialCount = Math.min(ISLOCK_CONCURRENT_NODES, nodes.length); + const initialCount = initialClients.length; + const unadopted = new Set(initialClients.filter(Boolean)); onProgress?.(`Subscribing from block ${fromBlockHeight} on ${initialCount} nodes...`); let markReady!: () => void; @@ -298,11 +414,7 @@ export class DAPISubscriptionClient { const release = (slot: NodeSlot): void => { slots.delete(slot); cancelStream(slot.stream); - const client = slot.client; - if (!client) return; - try { - Promise.resolve(client.disconnect()).catch(() => {}); - } catch { /* ignore */ } + this.disconnectQuietly(slot.client); }; const finish = (fn: () => void): void => { @@ -313,6 +425,9 @@ export class DAPISubscriptionClient { this.activeSubscriptions.delete(onAbort); signal?.removeEventListener('abort', onAbort); for (const slot of [...slots]) release(slot); + // Height-probe clients that never got a stream (aborted before opening). + for (const client of unadopted) this.disconnectQuietly(client); + unadopted.clear(); markReady(); fn(); }; @@ -349,7 +464,8 @@ export class DAPISubscriptionClient { console.log(`[islock-sub] opening stream on ${address.host}:${address.port} (attempt ${attempts})`); try { - slot.client = new DAPIClientClass({ ...CLIENT_OPTIONS, dapiAddresses: [address] }); + slot.client = initialClients[attempts - 1] ?? this.createNodeClient(address); + unadopted.delete(slot.client); Promise.resolve( slot.client.core.subscribeToTransactionsWithProofs(bloomFilter, { fromBlockHeight, count: 0 }) ).then((stream: any) => { From 35eddc7d89d6468e453bd9f87cc5aa2042e14e0d Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 19:40:48 -0500 Subject: [PATCH 10/15] fix(testnet): don't download the EvoSDK just for the health indicator Since a057e84 the testnet health poll read Platform status through sdk.system.status(), which loads and connects the whole EvoSDK (~7 MB gz) on every testnet page load. Testnet is the default network, so that undid the load-time work from PR #28. What loads when now: - Page load (idle warmup): the JS modules and the IslockService, the evonode list fetch, and the Core height poll via Insight. The EvoSDK chunk and wasm are NOT requested. - Health polls (every 30 s) call IslockService.peekPlatformStatus(). On testnet that resolves undefined while no SDK is connected, without touching the loader. The verdict then rests on Core alone: healthy with only the Core height in the tooltip, no reasons, never "degraded"; if Insight also fails it is "unknown" ("Could not reach Insight"). - The SDK is loaded by the flows that need it (creating an identity, top-up, DPNS, ...). The first poll after connectPlatformSdk has cached a connected SDK reads Platform status through it and shows chain-lock lag and block age as before. A failure of that real read still degrades. - The chain-lock fallback keeps using the loading getPlatformStatus path, since the user is mid-flow and needs the height. - Devnets are unchanged: dapi-client needs no SDK. Mainnet is unchanged (JSON-RPC). The mock-mode e2e test now also asserts no evo-sdk request on page load; it fails if the poll uses the loading path. Co-Authored-By: Claude Sonnet 5.5 --- e2e/deterministic.spec.ts | 11 ++++-- src/api/dapi-subscription.ts | 30 +++++++++++++-- src/api/islock.ts | 9 +++++ src/api/network-status.test.ts | 40 ++++++++++++++++++- src/api/network-status.ts | 22 ++++++++--- src/api/platform-status-routing.test.ts | 47 +++++++++++++++++++++-- src/platform/client.test.ts | 15 ++++++++ src/platform/client.ts | 10 +++++ src/platform/status.passive.test.ts | 51 +++++++++++++++++++++++++ src/platform/status.ts | 18 ++++++++- 10 files changed, 233 insertions(+), 20 deletions(-) create mode 100644 src/platform/status.passive.test.ts diff --git a/e2e/deterministic.spec.ts b/e2e/deterministic.spec.ts index af9fcdb..0e241f1 100644 --- a/e2e/deterministic.spec.ts +++ b/e2e/deterministic.spec.ts @@ -13,12 +13,14 @@ import { const MOCK_QUERY = '/?network=testnet&e2e=mock'; test.describe('Deterministic UI E2E (mock mode)', () => { - test('testnet discovers evonodes from the quorum service and never calls a digitalcash.dev host', async ({ page }) => { + test('testnet discovers evonodes from the quorum service, never calls digitalcash.dev and does not load the SDK for the health poll', async ({ page }) => { const digitalcashRequests: string[] = []; + const sdkRequests: string[] = []; page.on('request', (request) => { - if (/(^|\.)digitalcash\.dev$/.test(new URL(request.url()).hostname)) { - digitalcashRequests.push(request.url()); - } + const url = new URL(request.url()); + if (/(^|\.)digitalcash\.dev$/.test(url.hostname)) digitalcashRequests.push(request.url()); + // The EvoSDK bundle/wasm must not be fetched just to draw the health indicator. + if (/evo-sdk|wasm[-_]sdk/i.test(url.pathname)) sdkRequests.push(request.url()); }); await page.route('https://quorums.testnet.networks.dash.org/masternodes', (route) => route.fulfill({ @@ -46,6 +48,7 @@ test.describe('Deterministic UI E2E (mock mode)', () => { await page.waitForTimeout(2000); expect(digitalcashRequests).toEqual([]); + expect(sdkRequests).toEqual([]); }); test('create identity flow transitions to completion and DPNS registration', async ({ page }) => { diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index cdf3b92..e130301 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -5,7 +5,11 @@ import dashcoreLib from '@dashevo/dashcore-lib'; import { getNetwork } from '../config.js'; import { hash160 } from '../crypto/hash.js'; import { describeIslock } from '../utils/islock-debug.js'; -import { fetchPlatformStatus, type PlatformStatus } from '../platform/status.js'; +import { + fetchPlatformStatus, + fetchPlatformStatusIfSdkReady, + type PlatformStatus, +} from '../platform/status.js'; interface BloomFilterStatic { create(elements: number, falsePositiveRate: number, nTweak: number, nFlags: number): { @@ -569,11 +573,31 @@ export class DAPISubscriptionClient { * every other network keeps the dapi-client gRPC call. */ async getPlatformStatus(): Promise { - // By config type, not name: an unknown name falls back to the testnet config. - if (getNetwork(this.network).type === 'testnet') { + if (this.readsStatusViaSdk()) { return fetchPlatformStatus(this.network); } + return this.fetchStatusViaDapiClient(); + } + + /** + * Passive variant of {@link getPlatformStatus} for background health polling. + * On testnet it resolves `undefined`, without loading the EvoSDK, until the + * SDK is already connected for another reason; other networks read exactly + * as getPlatformStatus does (dapi-client needs no SDK download). + */ + async peekPlatformStatus(): Promise { + if (this.readsStatusViaSdk()) { + return fetchPlatformStatusIfSdkReady(this.network); + } + return this.fetchStatusViaDapiClient(); + } + + /** By config type, not name: an unknown name falls back to the testnet config. */ + private readsStatusViaSdk(): boolean { + return getNetwork(this.network).type === 'testnet'; + } + private async fetchStatusViaDapiClient(): Promise { const status = await this.dapiClient.platform.getStatus(); const chain = status.getChainStatus?.() ?? status.chain; diff --git a/src/api/islock.ts b/src/api/islock.ts index eb07377..3eb78d9 100644 --- a/src/api/islock.ts +++ b/src/api/islock.ts @@ -185,6 +185,15 @@ export class IslockService { return this.subscriptionClient.getPlatformStatus(); } + /** + * Platform status for background polling: `undefined` means "not available + * without loading the EvoSDK" (testnet before something else connected it), + * which is not a failure. See DAPISubscriptionClient.peekPlatformStatus. + */ + async peekPlatformStatus(): Promise { + return this.subscriptionClient.peekPlatformStatus(); + } + /** * Diagnostic helper: ask DAPI directly whether `txid` is currently * IS-locked or chain-locked. Returns null if the tx isn't known. diff --git a/src/api/network-status.test.ts b/src/api/network-status.test.ts index 245854c..fb752c9 100644 --- a/src/api/network-status.test.ts +++ b/src/api/network-status.test.ts @@ -4,7 +4,7 @@ import { fetchNetworkStatus, formatAge } from './network-status.js'; import type { InsightClient } from './insight.js'; import type { IslockService } from './islock.js'; -type PlatformStatus = Awaited>; +type PlatformStatus = NonNullable>>; type ChainLock = Awaited>; /** @@ -15,6 +15,8 @@ type ChainLock = Awaited>; function makeClients(opts: { coreHeight?: number | Error; platform?: PlatformStatus | Error; + /** Platform status deliberately not read (testnet, SDK not loaded): peek resolves undefined. */ + platformSkipped?: boolean; chainLock?: ChainLock | Error; }): { insight: InsightClient; islock: IslockService } { const insight = { @@ -33,7 +35,8 @@ function makeClients(opts: { if (opts.chainLock instanceof Error) throw opts.chainLock; return opts.chainLock ?? null; }, - getPlatformStatus: async () => { + peekPlatformStatus: async () => { + if (opts.platformSkipped) return undefined; if (opts.platform instanceof Error) throw opts.platform; if (opts.platform === undefined) throw new Error('no platform status'); return opts.platform; @@ -121,6 +124,39 @@ describe('fetchNetworkStatus (DAPI / devnet path)', () => { }); }); +describe('fetchNetworkStatus (Platform status not read yet)', () => { + it('judges Core alone and raises no Platform alarm', async () => { + const { insight, islock } = makeClients({ coreHeight: 10_700, platformSkipped: true }); + + const status = await fetchNetworkStatus(insight, islock); + + expect(status.health).toBe('healthy'); + expect(status.reasons).toEqual([]); + expect(status.coreHeight).toBe(10_700); + expect(status.coreChainLockedHeight).toBeUndefined(); + expect(status.platformBlockHeight).toBeUndefined(); + expect(status.chainLockLag).toBeUndefined(); + }); + + it('is unknown, not degraded, when Insight fails too', async () => { + const { insight, islock } = makeClients({ coreHeight: new Error('down'), platformSkipped: true }); + + const status = await fetchNetworkStatus(insight, islock); + + expect(status.health).toBe('unknown'); + expect(status.reasons).toEqual(['Could not reach Insight']); + }); + + it('still degrades when a real Platform read fails', async () => { + const { insight, islock } = makeClients({ coreHeight: 10_700, platform: new Error('timeout') }); + + const status = await fetchNetworkStatus(insight, islock); + + expect(status.health).toBe('degraded'); + expect(status.reasons).toEqual(['Platform (DAPI) status unreachable']); + }); +}); + describe('fetchNetworkStatus (JSON-RPC / mainnet path)', () => { it('reports healthy when Core chain-lock tracks the tip', async () => { const { insight, islock } = makeClients({ diff --git a/src/api/network-status.ts b/src/api/network-status.ts index 5fa7bde..9e17578 100644 --- a/src/api/network-status.ts +++ b/src/api/network-status.ts @@ -40,14 +40,16 @@ export async function fetchNetworkStatus( // we deliberately avoid it. // - testnet/devnets (no JSON-RPC): read full Platform status, which also // yields Tenderdash block height + age. IslockService picks the path - // (EvoSDK on testnet, DAPI over explicit dapiAddresses on devnets). + // (EvoSDK on testnet, DAPI over explicit dapiAddresses on devnets). On + // testnet this is passive: Platform is only read once the SDK is already + // connected for another reason, so the poll never downloads it. const useDapiPlatformStatus = !islock.supportsJsonRpc; // Bound the Insight retry so a flaky endpoint can't stretch one poll past the // 30s interval (the dapi-client / JSON-RPC calls have their own timeouts). const [coreResult, secondaryResult] = await Promise.allSettled([ insight.getBlockHeight({ maxAttempts: 1 }), - useDapiPlatformStatus ? islock.getPlatformStatus() : islock.getBestChainLock(), + useDapiPlatformStatus ? islock.peekPlatformStatus() : islock.getBestChainLock(), ]); const coreHeight = coreResult.status === 'fulfilled' ? coreResult.value : undefined; @@ -56,13 +58,17 @@ export async function fetchNetworkStatus( let platformBlockHeight: number | undefined; let platformBlockTimeMs: number | undefined; let secondaryReachable: boolean; + // Platform status was deliberately not read (see peekPlatformStatus). Not a + // failure: the verdict then rests on Core alone and carries no Platform alarm. + let platformNotChecked = false; if (useDapiPlatformStatus) { - // Settled value is the getPlatformStatus() shape on this branch. + // Settled value is the peekPlatformStatus() shape on this branch. const platform = secondaryResult.status === 'fulfilled' - ? (secondaryResult.value as Awaited>) + ? (secondaryResult.value as Awaited>) : undefined; + platformNotChecked = secondaryResult.status === 'fulfilled' && platform === undefined; secondaryReachable = platform !== undefined; coreChainLockedHeight = platform?.coreChainLockedHeight; platformBlockHeight = platform?.latestBlockHeight; @@ -107,7 +113,11 @@ export async function fetchNetworkStatus( if (!coreReachable && !secondaryReachable) { return { health: 'unknown', - reasons: ['Could not reach Insight or the chain-lock source'], + reasons: [ + platformNotChecked + ? 'Could not reach Insight' + : 'Could not reach Insight or the chain-lock source', + ], checkedAtMs, }; } @@ -116,7 +126,7 @@ export async function fetchNetworkStatus( escalate('degraded'); reasons.push('Insight (Core) unreachable'); } - if (!secondaryReachable) { + if (!secondaryReachable && !platformNotChecked) { // "Unreachable" is a transport failure, not an observed consensus stall — // flag it as degraded so a transient error doesn't fire a false red // "stalled" alarm. A genuine stall shows up via the lag/age checks below. diff --git a/src/api/platform-status-routing.test.ts b/src/api/platform-status-routing.test.ts index 3b9da63..5eb26ee 100644 --- a/src/api/platform-status-routing.test.ts +++ b/src/api/platform-status-routing.test.ts @@ -3,10 +3,14 @@ import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'; const mocks = vi.hoisted(() => ({ fetchPlatformStatus: vi.fn(), + fetchPlatformStatusIfSdkReady: vi.fn(), dapiGetStatus: vi.fn(), })); -vi.mock('../platform/status.js', () => ({ fetchPlatformStatus: mocks.fetchPlatformStatus })); +vi.mock('../platform/status.js', () => ({ + fetchPlatformStatus: mocks.fetchPlatformStatus, + fetchPlatformStatusIfSdkReady: mocks.fetchPlatformStatusIfSdkReady, +})); vi.mock('@dashevo/dapi-client', () => { class FakeClient { @@ -122,7 +126,7 @@ describe('Platform status routing', () => { }); it('reports healthy when the SDK call succeeds', async () => { - mocks.fetchPlatformStatus.mockResolvedValue(freshStatus()); + mocks.fetchPlatformStatusIfSdkReady.mockResolvedValue(freshStatus()); const status = await fetchNetworkStatus(insightAt(1_578_102), testnetIslock()); @@ -131,18 +135,53 @@ describe('Platform status routing', () => { expect(status.coreChainLockedHeight).toBe(1_578_100); expect(status.platformBlockHeight).toBe(80_000); expect(status.platformBlockAgeMs).toBeLessThan(60_000); - expect(mocks.fetchPlatformStatus).toHaveBeenCalledWith('testnet'); + expect(mocks.fetchPlatformStatusIfSdkReady).toHaveBeenCalledWith('testnet'); expect(mocks.dapiGetStatus).not.toHaveBeenCalled(); expect(fetchSpy).not.toHaveBeenCalled(); }); + it('never triggers the SDK download: without a connected SDK it judges Core alone', async () => { + mocks.fetchPlatformStatusIfSdkReady.mockResolvedValue(undefined); + + const status = await fetchNetworkStatus(insightAt(1_578_102), testnetIslock()); + + expect(status.health).toBe('healthy'); + expect(status.reasons).toEqual([]); + expect(status.coreHeight).toBe(1_578_102); + expect(status.platformBlockHeight).toBeUndefined(); + // The loading variant is what would pull the SDK in; the poll must not use it. + expect(mocks.fetchPlatformStatus).not.toHaveBeenCalled(); + expect(mocks.dapiGetStatus).not.toHaveBeenCalled(); + }); + it('reports degraded only when the SDK call fails', async () => { - mocks.fetchPlatformStatus.mockRejectedValue(new Error('Timed out while reading Platform status')); + mocks.fetchPlatformStatusIfSdkReady.mockRejectedValue( + new Error('Timed out while reading Platform status') + ); const status = await fetchNetworkStatus(insightAt(1_578_102), testnetIslock()); expect(status.health).toBe('degraded'); expect(status.reasons).toEqual(['Platform (DAPI) status unreachable']); }); + + it('lets the chain-lock fallback load the SDK, since the user is mid-flow', async () => { + mocks.fetchPlatformStatus.mockResolvedValue(freshStatus()); + + await expect(testnetIslock().getCoreChainLockedHeight()).resolves.toBe(1_578_100); + expect(mocks.fetchPlatformStatus).toHaveBeenCalledWith('testnet'); + }); + }); + + it('peeks devnet status through dapi-client with no SDK involved', async () => { + mocks.dapiGetStatus.mockResolvedValue({ chain: { coreChainLockedHeight: 7 } }); + const client = new DAPISubscriptionClient({ + network: 'devnet-moutai', + dapiAddresses: ['https://68.67.122.254:1443'], + }); + + await expect(client.peekPlatformStatus()).resolves.toMatchObject({ coreChainLockedHeight: 7 }); + expect(mocks.fetchPlatformStatus).not.toHaveBeenCalled(); + expect(mocks.fetchPlatformStatusIfSdkReady).not.toHaveBeenCalled(); }); }); diff --git a/src/platform/client.test.ts b/src/platform/client.test.ts index de282b0..ee59174 100644 --- a/src/platform/client.test.ts +++ b/src/platform/client.test.ts @@ -53,6 +53,21 @@ describe('connectPlatformSdk', () => { expect(sdkState.connect).toHaveBeenCalledOnce(); }); + it('reports whether an SDK is connected without loading or connecting one', async () => { + const { hasConnectedPlatformSdk, disconnectPlatformSdk } = await import('./client.js'); + + expect(hasConnectedPlatformSdk('testnet')).toBe(false); + expect(sdkState.created).toBe(0); + + await connectPlatformSdk('testnet', { maxAttempts: 1 }); + expect(hasConnectedPlatformSdk('testnet')).toBe(true); + expect(hasConnectedPlatformSdk('mainnet')).toBe(false); + expect(sdkState.created).toBe(1); + + disconnectPlatformSdk('testnet'); + expect(hasConnectedPlatformSdk('testnet')).toBe(false); + }); + it('reuses the connected SDK on later calls', async () => { const first = await connectPlatformSdk('testnet', { maxAttempts: 1 }); const second = await connectPlatformSdk('testnet', { maxAttempts: 1 }); diff --git a/src/platform/client.ts b/src/platform/client.ts index ecf839a..8d5de5b 100644 --- a/src/platform/client.ts +++ b/src/platform/client.ts @@ -114,6 +114,16 @@ export async function connectPlatformSdk( return pending; } +/** + * Whether the SDK for `network` is already loaded and connected. Never loads + * or connects anything, so passive readers (the health poll) can use an SDK + * that something else brought up without triggering the multi-megabyte + * download themselves. + */ +export function hasConnectedPlatformSdk(network: PlatformNetwork): boolean { + return sdkCache.get(network)?.isConnected === true; +} + export function disconnectPlatformSdk(network: PlatformNetwork): void { sdkCache.delete(network); } diff --git a/src/platform/status.passive.test.ts b/src/platform/status.passive.test.ts new file mode 100644 index 0000000..99da8cf --- /dev/null +++ b/src/platform/status.passive.test.ts @@ -0,0 +1,51 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + hasConnectedPlatformSdk: vi.fn(), + loadSdk: vi.fn(), + status: vi.fn(), +})); + +// Fake the client module wholesale: what matters here is that the passive +// reader never calls into anything that would load or connect the SDK. +vi.mock('./client.js', () => ({ + hasConnectedPlatformSdk: mocks.hasConnectedPlatformSdk, + withConnectedPlatformSdk: async (_network: string, callback: (sdk: unknown) => Promise) => { + mocks.loadSdk(); + return callback({ system: { status: mocks.status } }); + }, + withPlatformOperationTimeout: (promise: Promise) => promise, +})); + +import { fetchPlatformStatusIfSdkReady } from './status.js'; + +describe('fetchPlatformStatusIfSdkReady', () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.status.mockResolvedValue({ + chain: { core_chain_locked_height: 1_578_300, latest_block_height: '642000' }, + time: { block: '1792000000000' }, + }); + }); + + it('resolves undefined without touching the SDK while it is not connected', async () => { + mocks.hasConnectedPlatformSdk.mockReturnValue(false); + + await expect(fetchPlatformStatusIfSdkReady('testnet')).resolves.toBeUndefined(); + + expect(mocks.hasConnectedPlatformSdk).toHaveBeenCalledWith('testnet'); + expect(mocks.loadSdk).not.toHaveBeenCalled(); + expect(mocks.status).not.toHaveBeenCalled(); + }); + + it('reads the status once the SDK is already connected', async () => { + mocks.hasConnectedPlatformSdk.mockReturnValue(true); + + await expect(fetchPlatformStatusIfSdkReady('testnet')).resolves.toEqual({ + coreChainLockedHeight: 1_578_300, + latestBlockHeight: 642000, + latestBlockTimeMs: 1_792_000_000_000, + }); + expect(mocks.status).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/platform/status.ts b/src/platform/status.ts index 89037bc..cef8888 100644 --- a/src/platform/status.ts +++ b/src/platform/status.ts @@ -1,4 +1,8 @@ -import { withConnectedPlatformSdk, withPlatformOperationTimeout } from './client.js'; +import { + hasConnectedPlatformSdk, + withConnectedPlatformSdk, + withPlatformOperationTimeout, +} from './client.js'; export interface PlatformStatus { coreChainLockedHeight?: number; @@ -23,6 +27,18 @@ function positiveInteger(value: unknown): number | undefined { return Number.isSafeInteger(number) && number > 0 ? number : undefined; } +/** + * Like {@link fetchPlatformStatus}, but only when the SDK is already loaded + * and connected; otherwise resolves `undefined` without loading it. For + * background health polling, which must not pull the ~7 MB (gzip) SDK onto + * every page load just to draw an indicator. + */ +export async function fetchPlatformStatusIfSdkReady( + network: string +): Promise { + return hasConnectedPlatformSdk(network) ? fetchPlatformStatus(network) : undefined; +} + /** * Read Platform status through the EvoSDK (`sdk.system.status()`). * From abb4ec815519a47f4efd4fd81133c935f30d2b0d Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 19:42:36 -0500 Subject: [PATCH 11/15] fix(ui): keep the health indicator fresh and visible across resets Two bugs, both from the poller skipping any result whose verdict matched the previous one: - A flow reset (Try Again, Contract -> Back) builds a fresh state without networkStatus, and the poller then skipped the unchanged verdict, so the indicator stayed hidden until it changed (75+ s observed). - The tooltip numbers (heights, block age) never refreshed while the verdict was unchanged (stuck over 8 polls). Poll results are now always written to the state. A full re-render still happens only when the verdict or its reasons change, which is all the label and banner show; otherwise only the tooltip is patched in place, so focus isn't disturbed every 30 s. updateState re-attaches the last known status of the same network to any state that lacks one, and a poll that finds the state without a status renders it. Logic lives in ui/network-status-sync.ts so it can be tested. Co-Authored-By: Claude Sonnet 5.5 --- src/main.ts | 23 ++-- src/ui/components.network-status.test.ts | 69 ++++++++++ src/ui/components.ts | 36 ++++-- src/ui/index.ts | 1 + src/ui/network-status-sync.test.ts | 156 +++++++++++++++++++++++ src/ui/network-status-sync.ts | 69 ++++++++++ 6 files changed, 334 insertions(+), 20 deletions(-) create mode 100644 src/ui/components.network-status.test.ts create mode 100644 src/ui/network-status-sync.test.ts create mode 100644 src/ui/network-status-sync.ts diff --git a/src/main.ts b/src/main.ts index 429228b..5b74a40 100644 --- a/src/main.ts +++ b/src/main.ts @@ -47,11 +47,11 @@ import { setDepositTimedOut, setDepositVerificationFailed, setNetwork, - setNetworkStatus, updateIdentityKey, addIdentityKey, removeIdentityKey, render, + refreshNetworkStatusTooltip, renderEmbedNotice, downloadKeyBackup, // DPNS state functions @@ -190,6 +190,7 @@ import { type NearQuoteRequest, } from './api/near-intents.js'; import { pollNearSwap } from './ui/near-swap-poll.js'; +import { createNetworkStatusSync } from './ui/network-status-sync.js'; import { isContestedUsername } from './platform/dpns.js'; import { findMatchingKeyIndex, @@ -346,7 +347,14 @@ function preloadDashWarmup(): void { const NETWORK_STATUS_POLL_MS = 30_000; let networkStatusTimer: ReturnType | undefined; let networkStatusGeneration = 0; -let lastNetworkStatusKey: string | undefined; +const networkStatusSync = createNetworkStatusSync({ + getState: () => state, + setStateQuietly: (next) => { + state = next; + }, + updateState: (next) => updateState(next), + refreshTooltip: (status) => refreshNetworkStatusTooltip(document, status), +}); function stopNetworkStatusPolling(): void { if (networkStatusTimer !== undefined) { @@ -355,7 +363,7 @@ function stopNetworkStatusPolling(): void { } // Bump the generation so any in-flight fetch result is ignored. networkStatusGeneration += 1; - lastNetworkStatusKey = undefined; + networkStatusSync.reset(); } function startNetworkStatusPolling(): void { @@ -364,6 +372,7 @@ function startNetworkStatusPolling(): void { const generation = networkStatusGeneration; const insight = insightClient; const islock = islockService; + const network = state.network; const poll = async (): Promise => { try { @@ -371,10 +380,7 @@ function startNetworkStatusPolling(): void { // Ignore results from a superseded network/client. if (generation !== networkStatusGeneration) return; - const key = `${status.health}|${status.reasons.join('|')}`; - if (key === lastNetworkStatusKey) return; - lastNetworkStatusKey = key; - updateState(setNetworkStatus(state, status)); + networkStatusSync.apply(network, status); } catch (err) { console.warn('Network status poll failed:', err); } @@ -719,7 +725,8 @@ async function parseAndEstimateContract(json: unknown) { function updateState(newState: BridgeState) { const prevState = state; const previousStep = prevState?.step; - state = applyEmbed(newState); + // A flow reset builds a fresh state without the health snapshot; keep the last one. + state = applyEmbed(networkStatusSync.carryOver(newState)); const container = document.getElementById('app'); // Embed request cancelled or expired: the flow UI stays replaced. if (embedSession?.notice) { diff --git a/src/ui/components.network-status.test.ts b/src/ui/components.network-status.test.ts new file mode 100644 index 0000000..0c308b6 --- /dev/null +++ b/src/ui/components.network-status.test.ts @@ -0,0 +1,69 @@ +// @vitest-environment happy-dom +import { describe, expect, it, vi } from 'vitest'; + +// QR rendering needs a canvas, which happy-dom does not provide. +vi.mock('./qrcode.js', () => ({ + generateQRCodeDataUrl: () => new Promise(() => {}), +})); + +import { refreshNetworkStatusTooltip, render } from './components.js'; +import { createInitialState } from './state.js'; +import type { NetworkStatus } from '../types.js'; + +const status = (overrides: Partial = {}): NetworkStatus => ({ + health: 'healthy', + coreHeight: 1_578_205, + coreChainLockedHeight: 1_578_204, + platformBlockHeight: 641_243, + platformBlockAgeMs: 60_000, + reasons: [], + checkedAtMs: 1, + ...overrides, +}); + +function renderWith(networkStatus?: NetworkStatus): HTMLElement { + const container = document.createElement('div'); + render({ ...createInitialState('testnet'), networkStatus }, container); + return container; +} + +describe('network status indicator', () => { + it('is hidden until a status exists', () => { + expect(renderWith().querySelector('.net-status')).toBeNull(); + expect(renderWith(status()).querySelector('.net-status')).not.toBeNull(); + }); + + it('shows only the Core height when Platform was not read', () => { + const container = renderWith( + status({ coreChainLockedHeight: undefined, platformBlockHeight: undefined, platformBlockAgeMs: undefined }) + ); + + const indicator = container.querySelector('.net-status')!; + expect(indicator.getAttribute('title')).toBe('Core height: 1578205'); + expect(indicator.textContent).toContain('Network healthy'); + expect(container.querySelector('.net-status-banner')).toBeNull(); + }); + + it('refreshNetworkStatusTooltip updates the numbers in place, leaving the element and label alone', () => { + const container = renderWith(status()); + const indicator = container.querySelector('.net-status')!; + expect(indicator.getAttribute('title')).toContain('Core height: 1578205'); + + refreshNetworkStatusTooltip( + container, + status({ coreHeight: 1_578_213, platformBlockHeight: 641_290, platformBlockAgeMs: 180_000 }) + ); + + expect(container.querySelector('.net-status')).toBe(indicator); + expect(indicator.getAttribute('title')).toBe( + ['Core height: 1578213', 'Platform chain-locked: 1578204', 'Platform block: 641290', 'Platform block age: 3m'].join('\n') + ); + expect(indicator.textContent).toContain('Network healthy'); + }); + + it('refreshNetworkStatusTooltip is a no-op when no indicator is on screen', () => { + const container = renderWith(); + expect(() => refreshNetworkStatusTooltip(container, status())).not.toThrow(); + expect(container.querySelector('.net-status')).toBeNull(); + }); +}); diff --git a/src/ui/components.ts b/src/ui/components.ts index 00b6184..894e4a3 100644 --- a/src/ui/components.ts +++ b/src/ui/components.ts @@ -1,4 +1,4 @@ -import type { BridgeState, KeyType, KeyPurpose, SecurityLevel, NetworkHealth, EmbedNotice, NearIntentsState, NearIntentsSwap } from '../types.js'; +import type { BridgeState, KeyType, KeyPurpose, SecurityLevel, NetworkHealth, NetworkStatus, EmbedNotice, NearIntentsState, NearIntentsSwap } from '../types.js'; import { canCancel } from '../embed/bridge.js'; import { getStepProgress, getStepDescription, ErrorCodes, ErrorCodeLabels } from './state.js'; import { @@ -43,16 +43,8 @@ const NETWORK_HEALTH_META: Record< unknown: { label: 'Status unknown', dotClass: 'unknown' }, }; -/** - * Compact header indicator: a colored dot + short label reflecting overall - * network health. Hidden until the first status snapshot arrives. The full - * `title` tooltip carries the underlying numbers. - */ -function renderNetworkStatusIndicator(state: BridgeState): string { - const status = state.networkStatus; - if (!status) return ''; - const meta = NETWORK_HEALTH_META[status.health]; - +/** The indicator's `title` tooltip: the numbers behind the verdict. */ +function networkStatusTooltip(status: NetworkStatus): string { const tip: string[] = []; if (status.coreHeight !== undefined) tip.push(`Core height: ${status.coreHeight}`); if (status.coreChainLockedHeight !== undefined) @@ -62,8 +54,28 @@ function renderNetworkStatusIndicator(state: BridgeState): string { if (status.platformBlockAgeMs !== undefined) tip.push(`Platform block age: ${formatAge(status.platformBlockAgeMs)}`); if (status.reasons.length) tip.push('', ...status.reasons); + return tip.join('\n'); +} + +/** + * Update the indicator's tooltip numbers without re-rendering the page. Only + * valid while the verdict (dot color, label) is unchanged. + */ +export function refreshNetworkStatusTooltip(root: ParentNode, status: NetworkStatus): void { + root.querySelector('.net-status')?.setAttribute('title', networkStatusTooltip(status)); +} + +/** + * Compact header indicator: a colored dot + short label reflecting overall + * network health. Hidden until the first status snapshot arrives. The full + * `title` tooltip carries the underlying numbers. + */ +function renderNetworkStatusIndicator(state: BridgeState): string { + const status = state.networkStatus; + if (!status) return ''; + const meta = NETWORK_HEALTH_META[status.health]; - return ` + return ` ${escapeHtml(meta.label)} `; } diff --git a/src/ui/index.ts b/src/ui/index.ts index 6a822d5..6eb7f77 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -164,6 +164,7 @@ export { generateQRCodeDataUrl, createQRCodeElement, renderQRCodeToCanvas } from export { render, + refreshNetworkStatusTooltip, renderEmbedNotice, nearChainName, createKeyBackup, diff --git a/src/ui/network-status-sync.test.ts b/src/ui/network-status-sync.test.ts new file mode 100644 index 0000000..65d013c --- /dev/null +++ b/src/ui/network-status-sync.test.ts @@ -0,0 +1,156 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { createNetworkStatusSync } from './network-status-sync.js'; +import { createInitialState } from './state.js'; +import type { BridgeState, NetworkStatus } from '../types.js'; + +const status = (overrides: Partial = {}): NetworkStatus => ({ + health: 'healthy', + coreHeight: 1_578_205, + coreChainLockedHeight: 1_578_204, + platformBlockHeight: 641_243, + platformBlockAgeMs: 60_000, + reasons: [], + checkedAtMs: 1, + ...overrides, +}); + +function setup(network = 'testnet') { + let state: BridgeState = createInitialState(network); + const updateState = vi.fn((next: BridgeState) => { + state = next; + }); + const refreshTooltip = vi.fn(); + const sync = createNetworkStatusSync({ + getState: () => state, + setStateQuietly: (next) => { + state = next; + }, + updateState, + refreshTooltip, + }); + return { + sync, + updateState, + refreshTooltip, + get state() { + return state; + }, + set state(next: BridgeState) { + state = next; + }, + }; +} + +describe('createNetworkStatusSync', () => { + let ctx: ReturnType; + + beforeEach(() => { + ctx = setup(); + }); + + it('renders the first status', () => { + const first = status(); + ctx.sync.apply('testnet', first); + + expect(ctx.updateState).toHaveBeenCalledOnce(); + expect(ctx.state.networkStatus).toBe(first); + expect(ctx.refreshTooltip).not.toHaveBeenCalled(); + }); + + it('keeps the state fresh and patches only the tooltip while the verdict is unchanged', () => { + ctx.sync.apply('testnet', status()); + ctx.updateState.mockClear(); + + // 8 polls with moving numbers and the same verdict (the case that stayed stuck). + for (let i = 1; i <= 8; i++) { + const fresh = status({ + coreHeight: 1_578_205 + i, + platformBlockHeight: 641_243 + i * 5, + platformBlockAgeMs: 60_000 + i * 1000, + }); + ctx.sync.apply('testnet', fresh); + expect(ctx.state.networkStatus).toBe(fresh); + expect(ctx.refreshTooltip).toHaveBeenLastCalledWith(fresh); + } + + expect(ctx.refreshTooltip).toHaveBeenCalledTimes(8); + expect(ctx.updateState).not.toHaveBeenCalled(); // no needless re-render + }); + + it('re-renders when the verdict or its reasons change', () => { + ctx.sync.apply('testnet', status()); + ctx.updateState.mockClear(); + + ctx.sync.apply('testnet', status({ health: 'degraded', reasons: ['Insight (Core) unreachable'] })); + expect(ctx.updateState).toHaveBeenCalledTimes(1); + + ctx.sync.apply('testnet', status({ health: 'degraded', reasons: ['Platform (DAPI) status unreachable'] })); + expect(ctx.updateState).toHaveBeenCalledTimes(2); + + ctx.sync.apply('testnet', status()); + expect(ctx.updateState).toHaveBeenCalledTimes(3); + expect(ctx.refreshTooltip).not.toHaveBeenCalled(); + }); + + it('renders again when an unchanged verdict arrives but the state lost its status', () => { + ctx.sync.apply('testnet', status()); + ctx.updateState.mockClear(); + ctx.state = createInitialState('testnet'); // a reset that bypassed carryOver + + const fresh = status({ coreHeight: 1_578_300 }); + ctx.sync.apply('testnet', fresh); + + expect(ctx.updateState).toHaveBeenCalledOnce(); + expect(ctx.state.networkStatus).toBe(fresh); + expect(ctx.refreshTooltip).not.toHaveBeenCalled(); + }); + + describe('carryOver', () => { + it('restores the last known status after a state reset', () => { + const last = status({ coreHeight: 1_578_400 }); + ctx.sync.apply('testnet', status()); + ctx.sync.apply('testnet', last); + + const reset = createInitialState('testnet'); // Try Again / Contract -> Back + expect(reset.networkStatus).toBeUndefined(); + expect(ctx.sync.carryOver(reset).networkStatus).toBe(last); + }); + + it('leaves a state that already has a status alone', () => { + ctx.sync.apply('testnet', status()); + const own = status({ coreHeight: 1 }); + const state = { ...createInitialState('testnet'), networkStatus: own }; + + expect(ctx.sync.carryOver(state)).toBe(state); + }); + + it('does nothing before the first poll', () => { + const state = createInitialState('testnet'); + expect(ctx.sync.carryOver(state)).toBe(state); + }); + + it('never carries a status across networks', () => { + ctx.sync.apply('testnet', status()); + const mainnet = createInitialState('mainnet'); + + expect(ctx.sync.carryOver(mainnet).networkStatus).toBeUndefined(); + }); + + it('forgets the status on reset()', () => { + ctx.sync.apply('testnet', status()); + ctx.sync.reset(); + + expect(ctx.sync.carryOver(createInitialState('testnet')).networkStatus).toBeUndefined(); + }); + }); + + it('after reset(), the next poll renders even with an unchanged verdict', () => { + ctx.sync.apply('testnet', status()); + ctx.sync.reset(); + ctx.updateState.mockClear(); + + ctx.sync.apply('testnet', status()); + expect(ctx.updateState).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/ui/network-status-sync.ts b/src/ui/network-status-sync.ts new file mode 100644 index 0000000..fba0838 --- /dev/null +++ b/src/ui/network-status-sync.ts @@ -0,0 +1,69 @@ +import type { BridgeState, NetworkStatus } from '../types.js'; + +export interface NetworkStatusSyncDeps { + getState(): BridgeState; + /** Replace the app state without re-rendering. */ + setStateQuietly(state: BridgeState): void; + /** Replace the app state and re-render. */ + updateState(state: BridgeState): void; + /** Patch the visible indicator's tooltip in place. */ + refreshTooltip(status: NetworkStatus): void; +} + +export interface NetworkStatusSync { + /** Take a fresh poll result. */ + apply(network: string, status: NetworkStatus): void; + /** + * Re-attach the last known status to a state that lacks one (a flow reset + * builds a fresh state), so the indicator doesn't vanish until a poll's + * verdict happens to change. Never carries a status across networks. + */ + carryOver(state: BridgeState): BridgeState; + /** Forget everything, e.g. when polling restarts for another network. */ + reset(): void; +} + +/** What the banner and the indicator label depend on; the numbers are not part of it. */ +function verdictKey(status: NetworkStatus): string { + return `${status.health}|${status.reasons.join('|')}`; +} + +/** + * Keeps `state.networkStatus` current. Every poll result is stored, so reads of + * the state (and the next render) always see fresh numbers. A full re-render + * happens only when the verdict or its reasons change, because that is all the + * banner and the indicator label show; otherwise just the tooltip is patched in + * place, which avoids re-rendering (and disturbing focus) every 30 seconds. + */ +export function createNetworkStatusSync(deps: NetworkStatusSyncDeps): NetworkStatusSync { + let last: { network: string; status: NetworkStatus } | undefined; + let lastKey: string | undefined; + + return { + apply(network, status) { + last = { network, status }; + const key = verdictKey(status); + const verdictChanged = key !== lastKey; + lastKey = key; + + const state = deps.getState(); + // Also render when the state has no status at all: nothing is on screen to patch. + if (verdictChanged || !state.networkStatus) { + deps.updateState({ ...state, networkStatus: status }); + return; + } + deps.setStateQuietly({ ...state, networkStatus: status }); + deps.refreshTooltip(status); + }, + + carryOver(state) { + if (state.networkStatus || !last || last.network !== state.network) return state; + return { ...state, networkStatus: last.status }; + }, + + reset() { + last = undefined; + lastKey = undefined; + }, + }; +} From 30fe215b41908d8e85e0a13fb661db8190eaaf98 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 19:43:04 -0500 Subject: [PATCH 12/15] feat(islock): log which node delivered the InstantSend lock Log "[islock-sub] IS lock for from : after ms since subscribe" on the winning stream (node address and elapsed time only), so a slow or failing lock can be traced to a node. Co-Authored-By: Claude Sonnet 5.5 --- src/api/dapi-subscription-multi.test.ts | 17 +++++++++++++++++ src/api/dapi-subscription.ts | 7 ++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/api/dapi-subscription-multi.test.ts b/src/api/dapi-subscription-multi.test.ts index 616d461..8acfbd6 100644 --- a/src/api/dapi-subscription-multi.test.ts +++ b/src/api/dapi-subscription-multi.test.ts @@ -214,6 +214,23 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { for (const node of nodes) expect(node.disconnect).toHaveBeenCalled(); }); + it('logs which node delivered the lock and how long it took', async () => { + const log = vi.spyOn(console, 'log'); + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const sub = await startReady(client); + await vi.advanceTimersByTimeAsync(250); + + const winner = nodeClients()[1]; + winner.streams[0].emit('data', lockMessage(TXID)); + await sub.wait(); + + const host = winner.options.dapiAddresses[0].host; + const lines = log.mock.calls.map((call) => String(call[0])); + expect(lines.filter((line) => line.startsWith('[islock-sub] IS lock for'))).toEqual([ + `[islock-sub] IS lock for ${TXID} from ${host}:1443 after 250 ms since subscribe`, + ]); + }); + it('treats a stream ending before a lock as a failure and replaces it', async () => { const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(4) }); const sub = await startReady(client); diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index e130301..d855c67 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -395,6 +395,7 @@ export class DAPISubscriptionClient { signal?: AbortSignal ): Promise<{ wait: () => Promise }> { const initialCount = initialClients.length; + const subscribedAt = Date.now(); const unadopted = new Set(initialClients.filter(Boolean)); onProgress?.(`Subscribing from block ${fromBlockHeight} on ${initialCount} nodes...`); @@ -482,7 +483,11 @@ export class DAPISubscriptionClient { if (settled) return; markReady(); const bytes = this.findMatchingLock(response, txid, onProgress); - if (bytes) finish(() => resolve(bytes)); + if (!bytes) return; + console.log( + `[islock-sub] IS lock for ${txid} from ${address.host}:${address.port} after ${Date.now() - subscribedAt} ms since subscribe` + ); + finish(() => resolve(bytes)); }); // Listeners stay attached after cancel(): Node gRPC streams emit // 'error' on cancel, which would throw if nothing were listening. From afc6dc8ad8e0d05d2586a7d24ededad24b7ddca7 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 19:51:14 -0500 Subject: [PATCH 13/15] fix(testnet): address review of the height race and health indicator - The indicator says so when Platform was not read yet (tooltip line "Platform status: not read yet", NetworkStatus.platformChecked), so the Core-only "healthy" is not mistaken for a Platform check. - A poll result for a network the user already left is ignored, and switching networks clears the old network's status instead of showing it under the new badge. - Re-render decisions compare with the verdict actually on screen rather than with the previous poll. - The height probes use retries 0 and a gRPC deadline, so no hidden background retries outlive the 8 s deadline. - disconnect() (network switch) now also stops a pending height race, so no streams open on the network being left. Co-Authored-By: Claude Sonnet 5.5 --- src/api/dapi-subscription-multi.test.ts | 17 +++++++++++++++++ src/api/dapi-subscription.ts | 18 ++++++++++++++++-- src/api/network-status.test.ts | 2 ++ src/api/network-status.ts | 1 + src/main.ts | 5 ++++- src/types.ts | 5 +++++ src/ui/components.network-status.test.ts | 20 ++++++++++++++++++-- src/ui/components.ts | 1 + src/ui/network-status-sync.test.ts | 22 +++++++++++++++++++--- src/ui/network-status-sync.ts | 15 +++++++-------- 10 files changed, 90 insertions(+), 16 deletions(-) diff --git a/src/api/dapi-subscription-multi.test.ts b/src/api/dapi-subscription-multi.test.ts index 8acfbd6..bc89145 100644 --- a/src/api/dapi-subscription-multi.test.ts +++ b/src/api/dapi-subscription-multi.test.ts @@ -155,6 +155,10 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { expect(shared.core.getBestBlockHeight).not.toHaveBeenCalled(); for (const node of nodes) { expect(node.core.getBestBlockHeight).toHaveBeenCalledTimes(1); + expect(node.core.getBestBlockHeight).toHaveBeenCalledWith({ + retries: 0, + timeout: ISLOCK_HEIGHT_TIMEOUT_MS, + }); expect(node.core.subscribeToTransactionsWithProofs).toHaveBeenCalledTimes(1); expect(node.core.subscribeToTransactionsWithProofs.mock.calls[0][1]).toEqual({ fromBlockHeight: 90, @@ -317,6 +321,19 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { await outcome; }); + it('stops waiting for heights when the client is disconnected', async () => { + for (const host of ['node0.test', 'node1.test', 'node2.test']) state.hungHeightHosts.add(host); + const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); + const pending = client.subscribeForInstantSendLock(TXID, PUBKEY, UTXO, TIMEOUT); + const outcome = expect(pending).rejects.toThrow(`InstantSend lock subscription aborted for ${TXID}`); + await flush(); + + await client.disconnect(); // e.g. switchNetwork while the height is still pending + await outcome; + expect(liveStreams()).toHaveLength(0); // no stream opened on the network being left + for (const node of nodeClients()) expect(node.disconnect).toHaveBeenCalled(); + }); + it('stops waiting for heights when the caller aborts', async () => { for (const host of ['node0.test', 'node1.test', 'node2.test']) state.hungHeightHosts.add(host); const client = new DAPISubscriptionClient({ network: 'testnet', dapiAddresses: addresses(3) }); diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index d855c67..60788c5 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -177,7 +177,11 @@ export class DAPISubscriptionClient { }, ISLOCK_HEIGHT_TIMEOUT_MS); timers.add(timer); Promise.resolve() - .then(() => client.core.getBestBlockHeight()) + .then(() => + // retries 0 + a gRPC deadline: no hidden background retries after our own + // deadline has already counted this node as failed. + client.core.getBestBlockHeight({ retries: 0, timeout: ISLOCK_HEIGHT_TIMEOUT_MS }) + ) .then((height: unknown) => { if (answered) return; answered = true; @@ -264,12 +268,22 @@ export class DAPISubscriptionClient { const clients = nodes .slice(0, ISLOCK_CONCURRENT_NODES) .map((address) => this.tryCreateNodeClient(address)); + // disconnect() (e.g. a network switch) must also stop this wait, or the + // streams below would open on the network being left. + const raceAbort = new AbortController(); + const abortRace = (): void => raceAbort.abort(); + if (signal?.aborted) abortRace(); + signal?.addEventListener('abort', abortRace, { once: true }); + this.activeSubscriptions.add(abortRace); let currentHeight: number; try { - currentHeight = await this.raceBestBlockHeight(txid, clients, signal); + currentHeight = await this.raceBestBlockHeight(txid, clients, raceAbort.signal); } catch (error) { for (const client of clients) this.disconnectQuietly(client); throw error; + } finally { + this.activeSubscriptions.delete(abortRace); + signal?.removeEventListener('abort', abortRace); } console.log('[islock-sub] Current block height:', currentHeight); return this.subscribeOnMultipleNodes( diff --git a/src/api/network-status.test.ts b/src/api/network-status.test.ts index fb752c9..12dca6f 100644 --- a/src/api/network-status.test.ts +++ b/src/api/network-status.test.ts @@ -63,6 +63,7 @@ describe('fetchNetworkStatus (DAPI / devnet path)', () => { expect(status.health).toBe('healthy'); expect(status.chainLockLag).toBe(2); expect(status.reasons).toHaveLength(0); + expect(status.platformChecked).toBeUndefined(); }); it('flags stalled when chain-lock lags Core far behind', async () => { @@ -136,6 +137,7 @@ describe('fetchNetworkStatus (Platform status not read yet)', () => { expect(status.coreChainLockedHeight).toBeUndefined(); expect(status.platformBlockHeight).toBeUndefined(); expect(status.chainLockLag).toBeUndefined(); + expect(status.platformChecked).toBe(false); }); it('is unknown, not degraded, when Insight fails too', async () => { diff --git a/src/api/network-status.ts b/src/api/network-status.ts index 9e17578..dc91ae6 100644 --- a/src/api/network-status.ts +++ b/src/api/network-status.ts @@ -171,6 +171,7 @@ export async function fetchNetworkStatus( platformBlockTimeMs, chainLockLag, platformBlockAgeMs, + ...(platformNotChecked ? { platformChecked: false as const } : {}), reasons, checkedAtMs, }; diff --git a/src/main.ts b/src/main.ts index 5b74a40..5abc286 100644 --- a/src/main.ts +++ b/src/main.ts @@ -395,7 +395,10 @@ function switchNetwork(network: string): void { if (islockService) { islockService.disconnect().catch((err) => console.warn('Error disconnecting IslockService:', err)); } - updateState(setNetwork(state, network)); + // The previous network's health snapshot must not sit under the new network's + // badge until the next poll; the old poller's late results are ignored (see + // createNetworkStatusSync.apply). + updateState({ ...setNetwork(state, network), networkStatus: undefined }); syncSmartAppBanner(document, network); clientInitPromise = undefined; warmupScheduled = false; diff --git a/src/types.ts b/src/types.ts index 8d857cf..24c05b6 100644 --- a/src/types.ts +++ b/src/types.ts @@ -322,6 +322,11 @@ export interface NetworkStatus { chainLockLag?: number; /** now − platformBlockTimeMs, when known. */ platformBlockAgeMs?: number; + /** + * `false` when Platform status was deliberately not read (testnet, EvoSDK not + * loaded yet), so the verdict covers Core only. Absent when it was read. + */ + platformChecked?: false; /** Human-readable explanations for a degraded/stalled verdict. */ reasons: string[]; /** When this snapshot was taken, ms since epoch. */ diff --git a/src/ui/components.network-status.test.ts b/src/ui/components.network-status.test.ts index 0c308b6..d1f18d2 100644 --- a/src/ui/components.network-status.test.ts +++ b/src/ui/components.network-status.test.ts @@ -35,15 +35,31 @@ describe('network status indicator', () => { it('shows only the Core height when Platform was not read', () => { const container = renderWith( - status({ coreChainLockedHeight: undefined, platformBlockHeight: undefined, platformBlockAgeMs: undefined }) + status({ + coreChainLockedHeight: undefined, + platformBlockHeight: undefined, + platformBlockAgeMs: undefined, + platformChecked: false, + }) ); const indicator = container.querySelector('.net-status')!; - expect(indicator.getAttribute('title')).toBe('Core height: 1578205'); + expect(indicator.getAttribute('title')).toBe( + 'Core height: 1578205\nPlatform status: not read yet' + ); expect(indicator.textContent).toContain('Network healthy'); expect(container.querySelector('.net-status-banner')).toBeNull(); }); + it('drops the "not read yet" line once Platform has been read', () => { + const container = renderWith(status({ platformChecked: false })); + expect(container.querySelector('.net-status')!.getAttribute('title')).toContain('not read yet'); + + refreshNetworkStatusTooltip(container, status()); + + expect(container.querySelector('.net-status')!.getAttribute('title')).not.toContain('not read yet'); + }); + it('refreshNetworkStatusTooltip updates the numbers in place, leaving the element and label alone', () => { const container = renderWith(status()); const indicator = container.querySelector('.net-status')!; diff --git a/src/ui/components.ts b/src/ui/components.ts index 894e4a3..28db465 100644 --- a/src/ui/components.ts +++ b/src/ui/components.ts @@ -53,6 +53,7 @@ function networkStatusTooltip(status: NetworkStatus): string { tip.push(`Platform block: ${status.platformBlockHeight}`); if (status.platformBlockAgeMs !== undefined) tip.push(`Platform block age: ${formatAge(status.platformBlockAgeMs)}`); + if (status.platformChecked === false) tip.push('Platform status: not read yet'); if (status.reasons.length) tip.push('', ...status.reasons); return tip.join('\n'); } diff --git a/src/ui/network-status-sync.test.ts b/src/ui/network-status-sync.test.ts index 65d013c..ea373cf 100644 --- a/src/ui/network-status-sync.test.ts +++ b/src/ui/network-status-sync.test.ts @@ -145,12 +145,28 @@ describe('createNetworkStatusSync', () => { }); }); - it('after reset(), the next poll renders even with an unchanged verdict', () => { + it('ignores a poll result for a network the user already left', () => { + ctx.state = { ...createInitialState('mainnet'), networkStatus: undefined }; + + ctx.sync.apply('testnet', status({ health: 'stalled', reasons: ['Latest Platform block is 20m old'] })); + + expect(ctx.updateState).not.toHaveBeenCalled(); + expect(ctx.refreshTooltip).not.toHaveBeenCalled(); + expect(ctx.state.networkStatus).toBeUndefined(); + expect(ctx.sync.carryOver(createInitialState('mainnet')).networkStatus).toBeUndefined(); + }); + + it('compares with the verdict on screen, so a state replaced with a stale status gets corrected', () => { ctx.sync.apply('testnet', status()); - ctx.sync.reset(); + const degraded = status({ health: 'degraded', reasons: ['Insight (Core) unreachable'] }); + ctx.sync.apply('testnet', degraded); ctx.updateState.mockClear(); + // A flow captured the state before the verdict changed and writes it back. + ctx.state = { ...ctx.state, networkStatus: status() }; + + ctx.sync.apply('testnet', degraded); - ctx.sync.apply('testnet', status()); expect(ctx.updateState).toHaveBeenCalledOnce(); + expect(ctx.state.networkStatus).toBe(degraded); }); }); diff --git a/src/ui/network-status-sync.ts b/src/ui/network-status-sync.ts index fba0838..d204d68 100644 --- a/src/ui/network-status-sync.ts +++ b/src/ui/network-status-sync.ts @@ -37,18 +37,18 @@ function verdictKey(status: NetworkStatus): string { */ export function createNetworkStatusSync(deps: NetworkStatusSyncDeps): NetworkStatusSync { let last: { network: string; status: NetworkStatus } | undefined; - let lastKey: string | undefined; return { apply(network, status) { + const state = deps.getState(); + // A poller of a network the user already left must not write into the new one. + if (network !== state.network) return; last = { network, status }; - const key = verdictKey(status); - const verdictChanged = key !== lastKey; - lastKey = key; - const state = deps.getState(); - // Also render when the state has no status at all: nothing is on screen to patch. - if (verdictChanged || !state.networkStatus) { + // Compare with what is on screen (the state), not with the previous poll: + // the state may have been replaced in between. + const shown = state.networkStatus; + if (!shown || verdictKey(shown) !== verdictKey(status)) { deps.updateState({ ...state, networkStatus: status }); return; } @@ -63,7 +63,6 @@ export function createNetworkStatusSync(deps: NetworkStatusSyncDeps): NetworkSta reset() { last = undefined; - lastKey = undefined; }, }; } From 55801a29bbd5931762a254bb40447add794c9d1e Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 19:55:01 -0500 Subject: [PATCH 14/15] feat(testnet): connect the EvoSDK when a funding flow starts The health poll no longer downloads the SDK on page load (35eddc7), which left testnet showing a Core-only "healthy" until registration, i.e. after the asset lock was broadcast. Now, on testnet only, create / top-up / send-to-address start connecting the EvoSDK as soon as their clients are ready (before the deposit address is shown and before any funds can be committed) via warmPlatformSdkForFunding in the existing loaders, and poll the network status right after the connect settles. Registration needs the SDK anyway, so funding users download nothing extra; idle visitors still never do. Nothing blocks funding; mainnet and devnets are untouched. Indicator behaviour: - Before any funding flow, and while the first connect is in flight: Core only, tooltip "Platform status: not read yet", not degraded. - Once a connect has been attempted (connected, failed, or evicted after a connection error), the poll always reads Platform through the SDK, so a failing read is "degraded" and no longer reverts to the Core-only healthy when withConnectedPlatformSdk evicts the SDK. The next poll reconnects (module already loaded); success shows healthy again. This replaces hasConnectedPlatformSdk with isPlatformSdkSettled (attempted and not currently connecting). Co-Authored-By: Claude Sonnet 5.5 --- src/api/dapi-subscription.ts | 7 +- src/api/islock.ts | 7 +- src/api/network-status.ts | 4 +- src/main.ts | 16 +++ src/platform/client.test.ts | 47 +++++-- src/platform/client.ts | 19 ++- src/platform/loaders.ts | 24 ++++ src/platform/status.passive.test.ts | 14 +-- src/platform/status.session.test.ts | 186 ++++++++++++++++++++++++++++ src/platform/status.ts | 15 ++- 10 files changed, 304 insertions(+), 35 deletions(-) create mode 100644 src/platform/status.session.test.ts diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index 60788c5..5173a14 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -600,9 +600,10 @@ export class DAPISubscriptionClient { /** * Passive variant of {@link getPlatformStatus} for background health polling. - * On testnet it resolves `undefined`, without loading the EvoSDK, until the - * SDK is already connected for another reason; other networks read exactly - * as getPlatformStatus does (dapi-client needs no SDK download). + * On testnet it resolves `undefined`, without loading the EvoSDK, until a + * funding flow has started connecting it (and while that connect is in + * flight); from then on it reads, and failures reject. Other networks read + * exactly as getPlatformStatus does (dapi-client needs no SDK download). */ async peekPlatformStatus(): Promise { if (this.readsStatusViaSdk()) { diff --git a/src/api/islock.ts b/src/api/islock.ts index 3eb78d9..a040ca4 100644 --- a/src/api/islock.ts +++ b/src/api/islock.ts @@ -186,9 +186,10 @@ export class IslockService { } /** - * Platform status for background polling: `undefined` means "not available - * without loading the EvoSDK" (testnet before something else connected it), - * which is not a failure. See DAPISubscriptionClient.peekPlatformStatus. + * Platform status for background polling: `undefined` means "not read yet" + * (testnet, before any funding flow started connecting the EvoSDK, or while + * that connect is in flight), which is not a failure. A failing read after + * that rejects. See DAPISubscriptionClient.peekPlatformStatus. */ async peekPlatformStatus(): Promise { return this.subscriptionClient.peekPlatformStatus(); diff --git a/src/api/network-status.ts b/src/api/network-status.ts index dc91ae6..99edc25 100644 --- a/src/api/network-status.ts +++ b/src/api/network-status.ts @@ -41,8 +41,8 @@ export async function fetchNetworkStatus( // - testnet/devnets (no JSON-RPC): read full Platform status, which also // yields Tenderdash block height + age. IslockService picks the path // (EvoSDK on testnet, DAPI over explicit dapiAddresses on devnets). On - // testnet this is passive: Platform is only read once the SDK is already - // connected for another reason, so the poll never downloads it. + // testnet this is passive: Platform is only read once a funding flow has + // started connecting the SDK, so an idle page never downloads it. const useDapiPlatformStatus = !islock.supportsJsonRpc; // Bound the Insight retry so a flaky endpoint can't stretch one poll past the diff --git a/src/main.ts b/src/main.ts index 5abc286..be5329c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -209,6 +209,7 @@ import { loadPlatformModule, loadUsernameTransferModule, warmDashModules, + warmPlatformSdkForFunding, } from './platform/loaders.js'; import { deriveCandidateKeys, @@ -339,6 +340,15 @@ function preloadDashWarmup(): void { void ensureClients().catch((err) => console.warn('Dash warmup failed:', err)); } +/** + * Funding is about to start: begin connecting the SDK (testnet only), so the + * health indicator reads Platform before the asset lock is broadcast. Polls + * right after the connect settles instead of waiting for the next 30 s tick. + */ +function startPlatformSdkForFunding(): void { + void warmPlatformSdkForFunding(state.network).then(() => pollNetworkStatusNow?.()); +} + // ── Network-status polling ────────────────────────────────────────────────── // Periodically compares Core (Insight) height against Platform (DAPI) status // so the header can warn when Platform consensus stalls while Core keeps @@ -347,6 +357,7 @@ function preloadDashWarmup(): void { const NETWORK_STATUS_POLL_MS = 30_000; let networkStatusTimer: ReturnType | undefined; let networkStatusGeneration = 0; +let pollNetworkStatusNow: (() => void) | undefined; const networkStatusSync = createNetworkStatusSync({ getState: () => state, setStateQuietly: (next) => { @@ -363,6 +374,7 @@ function stopNetworkStatusPolling(): void { } // Bump the generation so any in-flight fetch result is ignored. networkStatusGeneration += 1; + pollNetworkStatusNow = undefined; networkStatusSync.reset(); } @@ -387,6 +399,7 @@ function startNetworkStatusPolling(): void { }; void poll(); + pollNetworkStatusNow = () => void poll(); networkStatusTimer = setInterval(() => void poll(), NETWORK_STATUS_POLL_MS); } @@ -2713,6 +2726,7 @@ async function startTopUp() { updateState(setStep(state, 'generating_keys')); await ensureClients(); + startPlatformSdkForFunding(); const islock = islockService!; const network = getNetwork(state.network); @@ -2837,6 +2851,7 @@ async function startSendToAddress() { try { updateState(setStep(state, 'generating_keys')); await ensureClients(); + startPlatformSdkForFunding(); const islock = islockService!; const network = getNetwork(state.network); @@ -3008,6 +3023,7 @@ async function startBridge() { // Step 1: Derive asset lock key from mnemonic (identity keys are pre-configured in state) updateState(setStep(state, 'generating_keys')); await ensureClients(); + startPlatformSdkForFunding(); const islock = islockService!; const { privateKey, publicKey } = deriveAssetLockKeyPair(state.mnemonic, state.network); diff --git a/src/platform/client.test.ts b/src/platform/client.test.ts index ee59174..51b79f7 100644 --- a/src/platform/client.test.ts +++ b/src/platform/client.test.ts @@ -53,19 +53,46 @@ describe('connectPlatformSdk', () => { expect(sdkState.connect).toHaveBeenCalledOnce(); }); - it('reports whether an SDK is connected without loading or connecting one', async () => { - const { hasConnectedPlatformSdk, disconnectPlatformSdk } = await import('./client.js'); + describe('isPlatformSdkSettled', () => { + it('is false while nobody has asked for the SDK, and asking about it loads nothing', async () => { + const { isPlatformSdkSettled } = await import('./client.js'); - expect(hasConnectedPlatformSdk('testnet')).toBe(false); - expect(sdkState.created).toBe(0); + expect(isPlatformSdkSettled('testnet')).toBe(false); + expect(sdkState.created).toBe(0); + }); - await connectPlatformSdk('testnet', { maxAttempts: 1 }); - expect(hasConnectedPlatformSdk('testnet')).toBe(true); - expect(hasConnectedPlatformSdk('mainnet')).toBe(false); - expect(sdkState.created).toBe(1); + it('is false while the first connect is in flight and true once it settles', async () => { + const { isPlatformSdkSettled } = await import('./client.js'); + let finishConnect!: () => void; + sdkState.connect.mockReturnValue(new Promise((resolve) => (finishConnect = resolve))); + + const connecting = connectPlatformSdk('testnet', { maxAttempts: 1 }); + await Promise.resolve(); + expect(isPlatformSdkSettled('testnet')).toBe(false); + + finishConnect(); + await connecting; + expect(isPlatformSdkSettled('testnet')).toBe(true); + expect(isPlatformSdkSettled('mainnet')).toBe(false); + }); + + it('stays true after the SDK is evicted, so a later failure is not hidden', async () => { + const { isPlatformSdkSettled, disconnectPlatformSdk } = await import('./client.js'); + await connectPlatformSdk('testnet', { maxAttempts: 1 }); + + disconnectPlatformSdk('testnet'); + + expect(isPlatformSdkSettled('testnet')).toBe(true); + }); + + it('is true after a failed connect', async () => { + const { isPlatformSdkSettled } = await import('./client.js'); + sdkState.connect.mockRejectedValue(new Error('quorums unreachable')); + + await expect(connectPlatformSdk('testnet', { maxAttempts: 1 })).rejects.toThrow('quorums'); - disconnectPlatformSdk('testnet'); - expect(hasConnectedPlatformSdk('testnet')).toBe(false); + expect(isPlatformSdkSettled('testnet')).toBe(true); + }); }); it('reuses the connected SDK on later calls', async () => { diff --git a/src/platform/client.ts b/src/platform/client.ts index 8d5de5b..60662ff 100644 --- a/src/platform/client.ts +++ b/src/platform/client.ts @@ -82,11 +82,16 @@ async function createPlatformSdk(network: PlatformNetwork): Promise { // paths) share one SDK instead of each opening a connection and orphaning all // but the last. const pendingConnects = new Map>(); +// Networks where something has ever started connecting the SDK. Never cleared: +// it separates "nobody wanted the SDK" (idle visitor) from "wanted it, and it is +// connected, was evicted after a connection error, or failed to connect". +const attemptedConnects = new Set(); async function openPlatformSdk( network: PlatformNetwork, retryOptions?: RetryOptions ): Promise { + attemptedConnects.add(network); const sdk = await createPlatformSdk(network); console.log(`Connecting to ${network}...`); @@ -115,13 +120,15 @@ export async function connectPlatformSdk( } /** - * Whether the SDK for `network` is already loaded and connected. Never loads - * or connects anything, so passive readers (the health poll) can use an SDK - * that something else brought up without triggering the multi-megabyte - * download themselves. + * Whether something has already started connecting the SDK for `network` and no + * connect is still in flight, so reading through it costs no new download. Never + * loads or connects anything. The health poll uses it so idle visitors never + * fetch the multi-megabyte SDK, while an SDK that was brought up (or tried and + * failed, or was evicted after a connection error) keeps being read, and a + * failing read stays visible as degraded instead of silently disappearing. */ -export function hasConnectedPlatformSdk(network: PlatformNetwork): boolean { - return sdkCache.get(network)?.isConnected === true; +export function isPlatformSdkSettled(network: PlatformNetwork): boolean { + return attemptedConnects.has(network) && !pendingConnects.has(network); } export function disconnectPlatformSdk(network: PlatformNetwork): void { diff --git a/src/platform/loaders.ts b/src/platform/loaders.ts index 31871f8..d7226f0 100644 --- a/src/platform/loaders.ts +++ b/src/platform/loaders.ts @@ -1,3 +1,5 @@ +import { getNetwork } from '../config.js'; + export function createCachedLoader(load: () => Promise): () => Promise { let promise: Promise | null = null; return () => { @@ -30,3 +32,25 @@ export function warmDashModules(): Promise[]> { loadIslockModule(), ]); } + +/** + * Start connecting the EvoSDK when the user enters a funding flow (create, + * top-up, send-to-address), before any funds can be committed. Registration + * needs the SDK anyway; connecting early means the health indicator can read + * real Platform status before the asset lock is broadcast. Idle visitors never + * reach a funding flow, so they still never download it. + * + * Testnet only: other networks keep their existing status sources (JSON-RPC on + * mainnet, dapi-client on devnets) and are not touched. Fire and forget: a + * failed connect is logged and later shows up as a degraded health verdict; it + * never blocks funding. Concurrent and repeated calls share one connect. + */ +export function warmPlatformSdkForFunding(network: string): Promise { + if (getNetwork(network).type !== 'testnet') return Promise.resolve(); + return loadPlatformClientModule() + .then(({ connectPlatformSdk }) => connectPlatformSdk(network)) + .then( + () => undefined, + (error) => console.warn('Platform SDK warmup failed:', error) + ); +} diff --git a/src/platform/status.passive.test.ts b/src/platform/status.passive.test.ts index 99da8cf..b1f938e 100644 --- a/src/platform/status.passive.test.ts +++ b/src/platform/status.passive.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; const mocks = vi.hoisted(() => ({ - hasConnectedPlatformSdk: vi.fn(), + isPlatformSdkSettled: vi.fn(), loadSdk: vi.fn(), status: vi.fn(), })); @@ -9,7 +9,7 @@ const mocks = vi.hoisted(() => ({ // Fake the client module wholesale: what matters here is that the passive // reader never calls into anything that would load or connect the SDK. vi.mock('./client.js', () => ({ - hasConnectedPlatformSdk: mocks.hasConnectedPlatformSdk, + isPlatformSdkSettled: mocks.isPlatformSdkSettled, withConnectedPlatformSdk: async (_network: string, callback: (sdk: unknown) => Promise) => { mocks.loadSdk(); return callback({ system: { status: mocks.status } }); @@ -28,18 +28,18 @@ describe('fetchPlatformStatusIfSdkReady', () => { }); }); - it('resolves undefined without touching the SDK while it is not connected', async () => { - mocks.hasConnectedPlatformSdk.mockReturnValue(false); + it('resolves undefined without touching the SDK while nothing has started connecting it or the first connect is in flight', async () => { + mocks.isPlatformSdkSettled.mockReturnValue(false); await expect(fetchPlatformStatusIfSdkReady('testnet')).resolves.toBeUndefined(); - expect(mocks.hasConnectedPlatformSdk).toHaveBeenCalledWith('testnet'); + expect(mocks.isPlatformSdkSettled).toHaveBeenCalledWith('testnet'); expect(mocks.loadSdk).not.toHaveBeenCalled(); expect(mocks.status).not.toHaveBeenCalled(); }); - it('reads the status once the SDK is already connected', async () => { - mocks.hasConnectedPlatformSdk.mockReturnValue(true); + it('reads the status once a connect has settled', async () => { + mocks.isPlatformSdkSettled.mockReturnValue(true); await expect(fetchPlatformStatusIfSdkReady('testnet')).resolves.toEqual({ coreChainLockedHeight: 1_578_300, diff --git a/src/platform/status.session.test.ts b/src/platform/status.session.test.ts new file mode 100644 index 0000000..d4ba2b1 --- /dev/null +++ b/src/platform/status.session.test.ts @@ -0,0 +1,186 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const sdk = vi.hoisted(() => ({ + created: [] as string[], + connect: vi.fn(), + status: vi.fn(), +})); + +// Real client/status/loaders modules against a fake SDK, so the eviction path +// in withConnectedPlatformSdk is exercised for real. +vi.mock('./sdkModule.js', () => { + const make = (kind: string) => () => { + sdk.created.push(kind); + const instance = { + isConnected: false, + connect: async () => { + await sdk.connect(); + instance.isConnected = true; + }, + system: { status: () => sdk.status() }, + }; + return instance; + }; + return { + loadSdkModule: async () => ({ + EvoSDK: { + testnetTrusted: make('testnet'), + mainnetTrusted: make('mainnet'), + devnetTrusted: make('devnet-trusted'), + devnet: make('devnet'), + }, + }), + }; +}); + +const goodStatus = (overrides: { clh?: number } = {}) => ({ + chain: { core_chain_locked_height: overrides.clh ?? 1_578_100, latest_block_height: '80000' }, + time: { block: String(Date.now() - 4_000) }, +}); + +const insight = (height: number) => ({ getBlockHeight: async () => height }) as never; + +describe('Platform status across an SDK session', () => { + let fetchPlatformStatusIfSdkReady: typeof import('./status.js').fetchPlatformStatusIfSdkReady; + let warmPlatformSdkForFunding: typeof import('./loaders.js').warmPlatformSdkForFunding; + let fetchNetworkStatus: typeof import('../api/network-status.js').fetchNetworkStatus; + + const testnetStatus = () => + fetchNetworkStatus(insight(1_578_102), { + supportsJsonRpc: false, + peekPlatformStatus: () => fetchPlatformStatusIfSdkReady('testnet'), + } as never); + + beforeEach(async () => { + vi.resetModules(); // fresh SDK cache and loader cache per test + ({ fetchPlatformStatusIfSdkReady } = await import('./status.js')); + ({ warmPlatformSdkForFunding } = await import('./loaders.js')); + ({ fetchNetworkStatus } = await import('../api/network-status.js')); + sdk.created.length = 0; + sdk.connect.mockReset(); + sdk.connect.mockResolvedValue(undefined); + sdk.status.mockReset(); + sdk.status.mockResolvedValue(goodStatus()); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('loads no SDK on an idle page: the poll reports Core only and never connects', async () => { + const result = await testnetStatus(); + await testnetStatus(); + + expect(result.health).toBe('healthy'); + expect(result.platformChecked).toBe(false); + expect(result.reasons).toEqual([]); + expect(sdk.created).toEqual([]); + expect(sdk.status).not.toHaveBeenCalled(); + }); + + describe('warmPlatformSdkForFunding', () => { + it('connects the testnet SDK when a funding flow starts', async () => { + await warmPlatformSdkForFunding('testnet'); + + expect(sdk.created).toEqual(['testnet']); + expect(sdk.connect).toHaveBeenCalledOnce(); + }); + + it.each(['mainnet', 'devnet-moutai'])('does nothing on %s', async (network) => { + await warmPlatformSdkForFunding(network); + + expect(sdk.created).toEqual([]); + expect(sdk.connect).not.toHaveBeenCalled(); + }); + + it('shares one connect between repeated and concurrent funding starts', async () => { + await Promise.all([ + warmPlatformSdkForFunding('testnet'), + warmPlatformSdkForFunding('testnet'), + ]); + await warmPlatformSdkForFunding('testnet'); + + expect(sdk.created).toEqual(['testnet']); + }); + + it('never rejects when the connect fails, and the failure then shows as degraded', async () => { + sdk.connect.mockRejectedValue(new Error('quorums unreachable')); + + await expect(warmPlatformSdkForFunding('testnet')).resolves.toBeUndefined(); + + const result = await testnetStatus(); // retries the connect, which still fails + expect(result.health).toBe('degraded'); + expect(result.reasons).toEqual(['Platform (DAPI) status unreachable']); + }); + }); + + it('keeps the Core-only wording while the SDK is still connecting, then reads Platform', async () => { + let finishConnect!: () => void; + sdk.connect.mockReturnValue(new Promise((resolve) => (finishConnect = resolve))); + + const warming = warmPlatformSdkForFunding('testnet'); + await vi.waitFor(() => expect(sdk.connect).toHaveBeenCalled()); + + const connecting = await testnetStatus(); + expect(connecting.health).toBe('healthy'); + expect(connecting.platformChecked).toBe(false); + expect(sdk.status).not.toHaveBeenCalled(); + + finishConnect(); + await warming; + + const connected = await testnetStatus(); + expect(connected.health).toBe('healthy'); + expect(connected.platformChecked).toBeUndefined(); + expect(connected.platformBlockHeight).toBe(80_000); + expect(connected.coreChainLockedHeight).toBe(1_578_100); + }); + + it('turns degraded when a connected SDK stops answering, and recovers when it answers again', async () => { + await warmPlatformSdkForFunding('testnet'); + expect((await testnetStatus()).platformChecked).toBeUndefined(); + + // A connection error evicts the cached SDK (withConnectedPlatformSdk). The + // next poll must not fall back to Core-only "healthy" because of that. + sdk.status.mockRejectedValueOnce(new Error('transport error: connection refused')); + const failing = await testnetStatus(); + expect(failing.health).toBe('degraded'); + expect(failing.reasons).toEqual(['Platform (DAPI) status unreachable']); + + sdk.status.mockRejectedValueOnce(new Error('transport error: connection refused')); + const stillFailing = await testnetStatus(); + expect(stillFailing.health).toBe('degraded'); + expect(stillFailing.platformChecked).toBeUndefined(); + + // Platform is back: the poll reconnects through the already loaded module. + const recovered = await testnetStatus(); + expect(recovered.health).toBe('healthy'); + expect(recovered.reasons).toEqual([]); + expect(recovered.platformBlockHeight).toBe(80_000); + expect(sdk.created.every((kind) => kind === 'testnet')).toBe(true); + // The connection errors really evicted the cached SDK: each recovery reconnected. + expect(sdk.created.length).toBeGreaterThan(1); + }); + + it('also degrades on a timeout-style failure of a connected SDK (no eviction)', async () => { + await warmPlatformSdkForFunding('testnet'); + sdk.status.mockRejectedValueOnce(new Error('Timed out while reading Platform status')); + + const failing = await testnetStatus(); + + expect(failing.health).toBe('degraded'); + expect((await testnetStatus()).health).toBe('healthy'); + }); + + it('still flags a genuinely stalled Platform once connected', async () => { + await warmPlatformSdkForFunding('testnet'); + sdk.status.mockResolvedValue(goodStatus({ clh: 1_577_000 })); + + const result = await testnetStatus(); + + expect(result.health).toBe('stalled'); + }); +}); diff --git a/src/platform/status.ts b/src/platform/status.ts index cef8888..359a047 100644 --- a/src/platform/status.ts +++ b/src/platform/status.ts @@ -1,5 +1,5 @@ import { - hasConnectedPlatformSdk, + isPlatformSdkSettled, withConnectedPlatformSdk, withPlatformOperationTimeout, } from './client.js'; @@ -28,15 +28,22 @@ function positiveInteger(value: unknown): number | undefined { } /** - * Like {@link fetchPlatformStatus}, but only when the SDK is already loaded - * and connected; otherwise resolves `undefined` without loading it. For + * Like {@link fetchPlatformStatus}, but never starts the SDK download: resolves + * `undefined` ("not read yet", not a failure) while nothing has started + * connecting the SDK, or while that first connect is still in flight. For * background health polling, which must not pull the ~7 MB (gzip) SDK onto * every page load just to draw an indicator. + * + * Once a connect has been attempted, reads always go through it, and a failing + * read rejects: after a connection error the SDK is evicted from the cache, and + * the next poll reconnects (the module is already loaded) rather than falling + * back to "not read yet", so a Platform outage shows as degraded and a recovery + * shows as healthy again. */ export async function fetchPlatformStatusIfSdkReady( network: string ): Promise { - return hasConnectedPlatformSdk(network) ? fetchPlatformStatus(network) : undefined; + return isPlatformSdkSettled(network) ? fetchPlatformStatus(network) : undefined; } /** From 794571857ef2b1e4d50f24ed90a2243220bf7ef9 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 23 Oct 2026 20:01:10 -0500 Subject: [PATCH 15/15] fix(testnet): keep the degraded verdict stable and polls from racing Review follow-ups to the funding-flow SDK warmup: - A reconnect in flight after an outage no longer reads as "not read yet" (which flipped the badge between degraded and healthy every poll): only the very first connect is shown that way, and only for a 60 s grace period, so a hung first connect cannot read as healthy forever. Later reads join the pending connect and are bounded by their own 20 s timeout. isPlatformSdkSettled becomes isPlatformSdkReadable. - The status poll no longer passes maxAttempts 1 to the shared connect, so a write path that joins a poll-started connect keeps its normal retries. - Overlapping polls (the extra one after the SDK connects) apply in order; a slower older poll cannot overwrite a newer result. - The funding warmup is skipped in e2e mock mode, and the extra poll only runs when a connect was actually attempted (testnet), not on mainnet or devnets. - Note: the warmup starts when a funding flow starts, which can be before the 7 MB download finishes; until it connects the indicator shows the Core-only "Platform status: not read yet". Co-Authored-By: Claude Sonnet 5.5 --- src/main.ts | 14 +++++++- src/platform/client.test.ts | 45 +++++++++++++++++------- src/platform/client.ts | 52 +++++++++++++++++++--------- src/platform/loaders.ts | 13 ++++--- src/platform/status.passive.test.ts | 14 ++++---- src/platform/status.session.test.ts | 53 +++++++++++++++++++++++++++-- src/platform/status.ts | 26 +++++++------- 7 files changed, 161 insertions(+), 56 deletions(-) diff --git a/src/main.ts b/src/main.ts index be5329c..0aca256 100644 --- a/src/main.ts +++ b/src/main.ts @@ -346,7 +346,11 @@ function preloadDashWarmup(): void { * right after the connect settles instead of waiting for the next 30 s tick. */ function startPlatformSdkForFunding(): void { - void warmPlatformSdkForFunding(state.network).then(() => pollNetworkStatusNow?.()); + // Mock-mode flows must not touch the network. + if (isE2EMockMode()) return; + void warmPlatformSdkForFunding(state.network).then((attempted) => { + if (attempted) pollNetworkStatusNow?.(); + }); } // ── Network-status polling ────────────────────────────────────────────────── @@ -386,11 +390,19 @@ function startNetworkStatusPolling(): void { const islock = islockService; const network = state.network; + // Polls can overlap (the extra poll after the SDK connects); a slower, older + // one must not overwrite the result of a newer one. + let issued = 0; + let applied = 0; + const poll = async (): Promise => { + const sequence = ++issued; try { const status = await fetchNetworkStatus(insight, islock); // Ignore results from a superseded network/client. if (generation !== networkStatusGeneration) return; + if (sequence < applied) return; + applied = sequence; networkStatusSync.apply(network, status); } catch (err) { diff --git a/src/platform/client.test.ts b/src/platform/client.test.ts index 51b79f7..6e27900 100644 --- a/src/platform/client.test.ts +++ b/src/platform/client.test.ts @@ -53,45 +53,66 @@ describe('connectPlatformSdk', () => { expect(sdkState.connect).toHaveBeenCalledOnce(); }); - describe('isPlatformSdkSettled', () => { + describe('isPlatformSdkReadable', () => { it('is false while nobody has asked for the SDK, and asking about it loads nothing', async () => { - const { isPlatformSdkSettled } = await import('./client.js'); + const { isPlatformSdkReadable } = await import('./client.js'); - expect(isPlatformSdkSettled('testnet')).toBe(false); + expect(isPlatformSdkReadable('testnet')).toBe(false); expect(sdkState.created).toBe(0); }); it('is false while the first connect is in flight and true once it settles', async () => { - const { isPlatformSdkSettled } = await import('./client.js'); + const { isPlatformSdkReadable } = await import('./client.js'); let finishConnect!: () => void; sdkState.connect.mockReturnValue(new Promise((resolve) => (finishConnect = resolve))); const connecting = connectPlatformSdk('testnet', { maxAttempts: 1 }); await Promise.resolve(); - expect(isPlatformSdkSettled('testnet')).toBe(false); + expect(isPlatformSdkReadable('testnet')).toBe(false); finishConnect(); await connecting; - expect(isPlatformSdkSettled('testnet')).toBe(true); - expect(isPlatformSdkSettled('mainnet')).toBe(false); + expect(isPlatformSdkReadable('testnet')).toBe(true); + expect(isPlatformSdkReadable('mainnet')).toBe(false); }); - it('stays true after the SDK is evicted, so a later failure is not hidden', async () => { - const { isPlatformSdkSettled, disconnectPlatformSdk } = await import('./client.js'); + it('turns true when the first connect hangs past the grace period', async () => { + vi.useFakeTimers(); + try { + const { isPlatformSdkReadable } = await import('./client.js'); + sdkState.connect.mockReturnValue(new Promise(() => {})); + + void connectPlatformSdk('testnet', { maxAttempts: 1 }).catch(() => {}); + await vi.advanceTimersByTimeAsync(59_000); + expect(isPlatformSdkReadable('testnet')).toBe(false); + + await vi.advanceTimersByTimeAsync(2_000); + expect(isPlatformSdkReadable('testnet')).toBe(true); + } finally { + vi.useRealTimers(); + } + }); + + it('stays true after eviction, including while a reconnect is in flight', async () => { + const { isPlatformSdkReadable, disconnectPlatformSdk } = await import('./client.js'); await connectPlatformSdk('testnet', { maxAttempts: 1 }); disconnectPlatformSdk('testnet'); + expect(isPlatformSdkReadable('testnet')).toBe(true); - expect(isPlatformSdkSettled('testnet')).toBe(true); + sdkState.connect.mockReturnValue(new Promise(() => {})); + void connectPlatformSdk('testnet', { maxAttempts: 1 }).catch(() => {}); + await Promise.resolve(); + expect(isPlatformSdkReadable('testnet')).toBe(true); }); it('is true after a failed connect', async () => { - const { isPlatformSdkSettled } = await import('./client.js'); + const { isPlatformSdkReadable } = await import('./client.js'); sdkState.connect.mockRejectedValue(new Error('quorums unreachable')); await expect(connectPlatformSdk('testnet', { maxAttempts: 1 })).rejects.toThrow('quorums'); - expect(isPlatformSdkSettled('testnet')).toBe(true); + expect(isPlatformSdkReadable('testnet')).toBe(true); }); }); diff --git a/src/platform/client.ts b/src/platform/client.ts index 60662ff..b3fe62a 100644 --- a/src/platform/client.ts +++ b/src/platform/client.ts @@ -82,24 +82,33 @@ async function createPlatformSdk(network: PlatformNetwork): Promise { // paths) share one SDK instead of each opening a connection and orphaning all // but the last. const pendingConnects = new Map>(); -// Networks where something has ever started connecting the SDK. Never cleared: +// When something first started connecting the SDK, per network. Never cleared: // it separates "nobody wanted the SDK" (idle visitor) from "wanted it, and it is // connected, was evicted after a connection error, or failed to connect". -const attemptedConnects = new Set(); +const firstConnectStartedAt = new Map(); +// Networks whose first connect has settled (success or failure). +const firstConnectSettled = new Set(); +// How long the very first connect (which includes the ~7 MB download) may be +// shown as "not read yet" before a hung connect counts as a failure. +const FIRST_CONNECT_GRACE_MS = 60_000; async function openPlatformSdk( network: PlatformNetwork, retryOptions?: RetryOptions ): Promise { - attemptedConnects.add(network); - const sdk = await createPlatformSdk(network); + if (!firstConnectStartedAt.has(network)) firstConnectStartedAt.set(network, Date.now()); + try { + const sdk = await createPlatformSdk(network); - console.log(`Connecting to ${network}...`); - await withRetry(() => sdk.connect(), retryOptions); - console.log('Connected to Platform'); + console.log(`Connecting to ${network}...`); + await withRetry(() => sdk.connect(), retryOptions); + console.log('Connected to Platform'); - sdkCache.set(network, sdk); - return sdk; + sdkCache.set(network, sdk); + return sdk; + } finally { + firstConnectSettled.add(network); + } } export async function connectPlatformSdk( @@ -120,15 +129,24 @@ export async function connectPlatformSdk( } /** - * Whether something has already started connecting the SDK for `network` and no - * connect is still in flight, so reading through it costs no new download. Never - * loads or connects anything. The health poll uses it so idle visitors never - * fetch the multi-megabyte SDK, while an SDK that was brought up (or tried and - * failed, or was evicted after a connection error) keeps being read, and a - * failing read stays visible as degraded instead of silently disappearing. + * Whether reading Platform status through the SDK for `network` is appropriate: + * something has already asked for the SDK (so reading costs no new download), + * and it is not merely the first connect still within its grace period. Never + * loads or connects anything. + * + * The health poll uses it so idle visitors never fetch the multi-megabyte SDK + * and a first connect in progress reads as "not read yet". After that the poll + * always reads, and a failing read stays visible as degraded rather than + * disappearing: an SDK that was connected, failed, was evicted after a + * connection error, or is reconnecting (a read joins that connect and is + * bounded by its own timeout) all count. A first connect that hangs past the + * grace period counts too, so it cannot read as healthy indefinitely. */ -export function isPlatformSdkSettled(network: PlatformNetwork): boolean { - return attemptedConnects.has(network) && !pendingConnects.has(network); +export function isPlatformSdkReadable(network: PlatformNetwork): boolean { + const startedAt = firstConnectStartedAt.get(network); + if (startedAt === undefined) return false; + const firstConnectInFlight = !firstConnectSettled.has(network) && pendingConnects.has(network); + return !(firstConnectInFlight && Date.now() - startedAt < FIRST_CONNECT_GRACE_MS); } export function disconnectPlatformSdk(network: PlatformNetwork): void { diff --git a/src/platform/loaders.ts b/src/platform/loaders.ts index d7226f0..09a9123 100644 --- a/src/platform/loaders.ts +++ b/src/platform/loaders.ts @@ -44,13 +44,18 @@ export function warmDashModules(): Promise[]> { * mainnet, dapi-client on devnets) and are not touched. Fire and forget: a * failed connect is logged and later shows up as a degraded health verdict; it * never blocks funding. Concurrent and repeated calls share one connect. + * Resolves true once a connect was attempted (settled either way), false when + * the network is not testnet and nothing was started. */ -export function warmPlatformSdkForFunding(network: string): Promise { - if (getNetwork(network).type !== 'testnet') return Promise.resolve(); +export function warmPlatformSdkForFunding(network: string): Promise { + if (getNetwork(network).type !== 'testnet') return Promise.resolve(false); return loadPlatformClientModule() .then(({ connectPlatformSdk }) => connectPlatformSdk(network)) .then( - () => undefined, - (error) => console.warn('Platform SDK warmup failed:', error) + () => true, + (error) => { + console.warn('Platform SDK warmup failed:', error); + return true; + } ); } diff --git a/src/platform/status.passive.test.ts b/src/platform/status.passive.test.ts index b1f938e..b0bac1b 100644 --- a/src/platform/status.passive.test.ts +++ b/src/platform/status.passive.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; const mocks = vi.hoisted(() => ({ - isPlatformSdkSettled: vi.fn(), + isPlatformSdkReadable: vi.fn(), loadSdk: vi.fn(), status: vi.fn(), })); @@ -9,7 +9,7 @@ const mocks = vi.hoisted(() => ({ // Fake the client module wholesale: what matters here is that the passive // reader never calls into anything that would load or connect the SDK. vi.mock('./client.js', () => ({ - isPlatformSdkSettled: mocks.isPlatformSdkSettled, + isPlatformSdkReadable: mocks.isPlatformSdkReadable, withConnectedPlatformSdk: async (_network: string, callback: (sdk: unknown) => Promise) => { mocks.loadSdk(); return callback({ system: { status: mocks.status } }); @@ -28,18 +28,18 @@ describe('fetchPlatformStatusIfSdkReady', () => { }); }); - it('resolves undefined without touching the SDK while nothing has started connecting it or the first connect is in flight', async () => { - mocks.isPlatformSdkSettled.mockReturnValue(false); + it('resolves undefined without touching the SDK while nothing has started connecting it or the first connect is still within its grace period', async () => { + mocks.isPlatformSdkReadable.mockReturnValue(false); await expect(fetchPlatformStatusIfSdkReady('testnet')).resolves.toBeUndefined(); - expect(mocks.isPlatformSdkSettled).toHaveBeenCalledWith('testnet'); + expect(mocks.isPlatformSdkReadable).toHaveBeenCalledWith('testnet'); expect(mocks.loadSdk).not.toHaveBeenCalled(); expect(mocks.status).not.toHaveBeenCalled(); }); - it('reads the status once a connect has settled', async () => { - mocks.isPlatformSdkSettled.mockReturnValue(true); + it('reads the status once the SDK is readable', async () => { + mocks.isPlatformSdkReadable.mockReturnValue(true); await expect(fetchPlatformStatusIfSdkReady('testnet')).resolves.toEqual({ coreChainLockedHeight: 1_578_300, diff --git a/src/platform/status.session.test.ts b/src/platform/status.session.test.ts index d4ba2b1..b3e16f2 100644 --- a/src/platform/status.session.test.ts +++ b/src/platform/status.session.test.ts @@ -83,14 +83,14 @@ describe('Platform status across an SDK session', () => { describe('warmPlatformSdkForFunding', () => { it('connects the testnet SDK when a funding flow starts', async () => { - await warmPlatformSdkForFunding('testnet'); + await expect(warmPlatformSdkForFunding('testnet')).resolves.toBe(true); expect(sdk.created).toEqual(['testnet']); expect(sdk.connect).toHaveBeenCalledOnce(); }); it.each(['mainnet', 'devnet-moutai'])('does nothing on %s', async (network) => { - await warmPlatformSdkForFunding(network); + await expect(warmPlatformSdkForFunding(network)).resolves.toBe(false); expect(sdk.created).toEqual([]); expect(sdk.connect).not.toHaveBeenCalled(); @@ -109,7 +109,7 @@ describe('Platform status across an SDK session', () => { it('never rejects when the connect fails, and the failure then shows as degraded', async () => { sdk.connect.mockRejectedValue(new Error('quorums unreachable')); - await expect(warmPlatformSdkForFunding('testnet')).resolves.toBeUndefined(); + await expect(warmPlatformSdkForFunding('testnet')).resolves.toBe(true); const result = await testnetStatus(); // retries the connect, which still fails expect(result.health).toBe('degraded'); @@ -173,6 +173,53 @@ describe('Platform status across an SDK session', () => { expect(failing.health).toBe('degraded'); expect((await testnetStatus()).health).toBe('healthy'); + expect(sdk.created).toEqual(['testnet']); // a timeout does not evict the SDK + }); + + it('does not flap back to healthy while a reconnect after an outage is still pending', async () => { + vi.useFakeTimers(); + try { + await warmPlatformSdkForFunding('testnet'); + sdk.status.mockRejectedValueOnce(new Error('transport error: connection refused')); + expect((await testnetStatus()).health).toBe('degraded'); // evicts the SDK + + // The reconnect started by the next poll never finishes. + sdk.connect.mockReturnValue(new Promise(() => {})); + const second = testnetStatus(); + await vi.advanceTimersByTimeAsync(20_000); // the poll's own timeout + const secondResult = await second; + expect(secondResult.health).toBe('degraded'); + + // The next poll joins that same pending connect: still degraded, not "not read yet". + const third = testnetStatus(); + await vi.advanceTimersByTimeAsync(20_000); + const thirdResult = await third; + expect(thirdResult.health).toBe('degraded'); + expect(thirdResult.platformChecked).toBeUndefined(); + expect(sdk.created.length).toBe(2); // one reconnect, shared + } finally { + vi.useRealTimers(); + } + }); + + it('turns a hung first connect into degraded once the grace period has passed', async () => { + vi.useFakeTimers(); + try { + sdk.connect.mockReturnValue(new Promise(() => {})); + void warmPlatformSdkForFunding('testnet'); + await vi.advanceTimersByTimeAsync(0); + + const early = await testnetStatus(); + expect(early.health).toBe('healthy'); + expect(early.platformChecked).toBe(false); + + await vi.advanceTimersByTimeAsync(60_000); + const late = testnetStatus(); + await vi.advanceTimersByTimeAsync(20_000); + expect((await late).health).toBe('degraded'); + } finally { + vi.useRealTimers(); + } }); it('still flags a genuinely stalled Platform once connected', async () => { diff --git a/src/platform/status.ts b/src/platform/status.ts index 359a047..2efff6d 100644 --- a/src/platform/status.ts +++ b/src/platform/status.ts @@ -1,5 +1,5 @@ import { - isPlatformSdkSettled, + isPlatformSdkReadable, withConnectedPlatformSdk, withPlatformOperationTimeout, } from './client.js'; @@ -30,20 +30,20 @@ function positiveInteger(value: unknown): number | undefined { /** * Like {@link fetchPlatformStatus}, but never starts the SDK download: resolves * `undefined` ("not read yet", not a failure) while nothing has started - * connecting the SDK, or while that first connect is still in flight. For - * background health polling, which must not pull the ~7 MB (gzip) SDK onto - * every page load just to draw an indicator. + * connecting the SDK, or while that first connect is still within its grace + * period. For background health polling, which must not pull the ~7 MB (gzip) + * SDK onto every page load just to draw an indicator. * - * Once a connect has been attempted, reads always go through it, and a failing - * read rejects: after a connection error the SDK is evicted from the cache, and - * the next poll reconnects (the module is already loaded) rather than falling - * back to "not read yet", so a Platform outage shows as degraded and a recovery - * shows as healthy again. + * Afterwards reads always go through the SDK and a failing read rejects: after + * a connection error the SDK is evicted from the cache, and the next poll + * reconnects (the module is already loaded) rather than falling back to "not + * read yet", so a Platform outage shows as degraded and a recovery shows as + * healthy again. See {@link isPlatformSdkReadable}. */ export async function fetchPlatformStatusIfSdkReady( network: string ): Promise { - return isPlatformSdkSettled(network) ? fetchPlatformStatus(network) : undefined; + return isPlatformSdkReadable(network) ? fetchPlatformStatus(network) : undefined; } /** @@ -71,8 +71,10 @@ export async function fetchPlatformStatus(network: string): Promise