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..0e241f1 100644 --- a/e2e/deterministic.spec.ts +++ b/e2e/deterministic.spec.ts @@ -13,6 +13,44 @@ import { const MOCK_QUERY = '/?network=testnet&e2e=mock'; test.describe('Deterministic UI E2E (mock mode)', () => { + 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) => { + 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({ + 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([]); + expect(sdkRequests).toEqual([]); + }); + test('create identity flow transitions to completion and DPNS registration', async ({ page }) => { await page.goto(MOCK_QUERY); diff --git a/src/api/dapi-subscription-multi.test.ts b/src/api/dapi-subscription-multi.test.ts new file mode 100644 index 0000000..bc89145 --- /dev/null +++ b/src/api/dapi-subscription-multi.test.ts @@ -0,0 +1,583 @@ +/* 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 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>, + 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 () => { + 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'); + } + 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_HEIGHT_TIMEOUT_MS, + 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.hungHeightHosts.clear(); + state.failedHeightHosts.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 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).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, + 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('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); + + 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); + }); + + 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 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) }); + 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); + 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('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); + 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('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(); + await outcome; + 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..5173a14 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -2,8 +2,14 @@ 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, + fetchPlatformStatusIfSdkReady, + type PlatformStatus, +} from '../platform/status.js'; interface BloomFilterStatic { create(elements: number, falsePositiveRate: number, nTweak: number, nFlags: number): { @@ -29,18 +35,55 @@ 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; +/** 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; + +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,12 +91,114 @@ 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'; } 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(() => + // 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; + 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 } @@ -115,6 +260,37 @@ export class DAPISubscriptionClient { const bloomFilter = this.createBloomFilter(hash160(publicKey), utxo); onProgress?.('Getting current block height...'); + 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)); + // 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, 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( + 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); @@ -153,31 +329,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 +349,203 @@ 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. 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, + 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 initialCount = initialClients.length; + const subscribedAt = Date.now(); + const unadopted = new Set(initialClients.filter(Boolean)); + 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); + // 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(); + let settled = false; + // Streams opened so far; also the index of the next untried node. + let attempts = 0; + + const cancelStream = (stream: any): void => { + try { stream?.cancel(); } catch { /* ignore */ } + }; + + const release = (slot: NodeSlot): void => { + slots.delete(slot); + cancelStream(slot.stream); + this.disconnectQuietly(slot.client); + }; + + 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); + // Height-probe clients that never got a stream (aborted before opening). + for (const client of unadopted) this.disconnectQuietly(client); + unadopted.clear(); + 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[attempts++]; + if (!address) return; + const slot: NodeSlot = { failed: false }; + slots.add(slot); + + const fail = (error: unknown): void => { + if (settled || slot.failed) return; + slot.failed = true; + release(slot); + if (attempts < nodes.length && attempts < ISLOCK_MAX_NODE_ATTEMPTS) { + openNode(); + } else if (slots.size === 0) { + const reason = error instanceof Error ? error.message : String(error); + const exhausted = new Error( + `InstantSend lock subscription failed for ${txid}: ${attempts} nodes tried, last error: ${reason}` + ); + allFailed = exhausted; + finish(() => reject(exhausted)); + } + }; + + console.log(`[islock-sub] opening stream on ${address.host}:${address.port} (attempt ${attempts})`); + try { + 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) => { + 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) 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. + // 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; + // 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 }; + } + async waitForInstantSendLock( txid: string, publicKey: Uint8Array, @@ -209,17 +559,19 @@ export class DAPISubscriptionClient { } async disconnect(): Promise { + for (const abort of [...this.activeSubscriptions]) abort(); try { await this.dapiClient.disconnect(); } catch { /* ignore */ } } /** - * 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. @@ -230,17 +582,42 @@ 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 (see `fetchPlatformStatus` for why); + * every other network keeps the dapi-client gRPC call. + */ + async getPlatformStatus(): Promise { + 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 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 getPlatformStatus(): Promise<{ - coreChainLockedHeight?: number; - latestBlockHeight?: number; - latestBlockTimeMs?: number; - }> { + 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/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/evonodes.test.ts b/src/api/evonodes.test.ts new file mode 100644 index 0000000..de4f0f2 --- /dev/null +++ b/src/api/evonodes.test.ts @@ -0,0 +1,196 @@ +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('999.1.1.1'), + node('1.2.3.4.5'), + 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); + 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..aa10209 --- /dev/null +++ b/src/api/evonodes.ts @@ -0,0 +1,91 @@ +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'; + +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; + 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]; +} + +/** + * 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[] +): Promise { + let live: string[] = []; + try { + 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); + } + + 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/api/islock.test.ts b/src/api/islock.test.ts index 302fe15..9405120 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,39 @@ 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('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) }; diff --git a/src/api/islock.ts b/src/api/islock.ts index 01bb31e..a040ca4 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'; @@ -66,11 +67,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 +104,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. @@ -147,19 +149,19 @@ 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()`. + * 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(); } /** - * 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; @@ -176,17 +178,23 @@ 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 and devnets; see DAPISubscriptionClient.getPlatformStatus. */ - async getPlatformStatus(): Promise<{ - coreChainLockedHeight?: number; - latestBlockHeight?: number; - latestBlockTimeMs?: number; - }> { + async getPlatformStatus(): Promise { return this.subscriptionClient.getPlatformStatus(); } + /** + * 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(); + } + /** * 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 2ef5046..12dca6f 100644 --- a/src/api/network-status.test.ts +++ b/src/api/network-status.test.ts @@ -4,17 +4,19 @@ 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>; /** * 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; 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; @@ -60,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 () => { @@ -121,7 +125,41 @@ describe('fetchNetworkStatus (DAPI / devnet path)', () => { }); }); -describe('fetchNetworkStatus (JSON-RPC / mainnet-testnet 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(); + expect(status.platformChecked).toBe(false); + }); + + 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({ coreHeight: 10_700, diff --git a/src/api/network-status.ts b/src/api/network-status.ts index e342099..99edc25 100644 --- a/src/api/network-status.ts +++ b/src/api/network-status.ts @@ -34,19 +34,22 @@ 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 - // 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. IslockService picks the path + // (EvoSDK on testnet, DAPI over explicit dapiAddresses on devnets). On + // 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 // 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; @@ -55,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; @@ -106,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, }; } @@ -115,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. @@ -160,6 +171,7 @@ export async function fetchNetworkStatus( platformBlockTimeMs, chainLockLag, platformBlockAgeMs, + ...(platformNotChecked ? { platformChecked: false as const } : {}), reasons, checkedAtMs, }; diff --git a/src/api/platform-status-routing.test.ts b/src/api/platform-status-routing.test.ts new file mode 100644 index 0000000..5eb26ee --- /dev/null +++ b/src/api/platform-status-routing.test.ts @@ -0,0 +1,187 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +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, + fetchPlatformStatusIfSdkReady: mocks.fetchPlatformStatusIfSdkReady, +})); + +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): InsightClient => + ({ getBlockHeight: async () => 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(); + vi.restoreAllMocks(); + }); + + 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('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 }, + 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.fetchPlatformStatusIfSdkReady.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.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.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/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..3ac3655 100644 --- a/src/config.ts +++ b/src/config.ts @@ -44,7 +44,40 @@ 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. + // + // 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', + '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://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', + ], }; export const MAINNET: NetworkConfig = { diff --git a/src/main.ts b/src/main.ts index f149d5e..0aca256 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'; @@ -46,11 +47,11 @@ import { setDepositTimedOut, setDepositVerificationFailed, setNetwork, - setNetworkStatus, updateIdentityKey, addIdentityKey, removeIdentityKey, render, + refreshNetworkStatusTooltip, renderEmbedNotice, downloadKeyBackup, // DPNS state functions @@ -189,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, @@ -207,6 +209,7 @@ import { loadPlatformModule, loadUsernameTransferModule, warmDashModules, + warmPlatformSdkForFunding, } from './platform/loaders.js'; import { deriveCandidateKeys, @@ -286,11 +289,20 @@ 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), + ]); + // 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, - dapiAddresses: config.dapiAddresses, + dapiAddresses, }); startNetworkStatusPolling(); } @@ -328,6 +340,19 @@ 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 { + // Mock-mode flows must not touch the network. + if (isE2EMockMode()) return; + void warmPlatformSdkForFunding(state.network).then((attempted) => { + if (attempted) 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 @@ -336,7 +361,15 @@ function preloadDashWarmup(): void { const NETWORK_STATUS_POLL_MS = 30_000; let networkStatusTimer: ReturnType | undefined; let networkStatusGeneration = 0; -let lastNetworkStatusKey: string | undefined; +let pollNetworkStatusNow: (() => void) | 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) { @@ -345,7 +378,8 @@ function stopNetworkStatusPolling(): void { } // Bump the generation so any in-flight fetch result is ignored. networkStatusGeneration += 1; - lastNetworkStatusKey = undefined; + pollNetworkStatusNow = undefined; + networkStatusSync.reset(); } function startNetworkStatusPolling(): void { @@ -354,23 +388,30 @@ function startNetworkStatusPolling(): void { const generation = networkStatusGeneration; const insight = insightClient; 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; - 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); } }; void poll(); + pollNetworkStatusNow = () => void poll(); networkStatusTimer = setInterval(() => void poll(), NETWORK_STATUS_POLL_MS); } @@ -379,7 +420,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; @@ -709,7 +753,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) { @@ -2693,6 +2738,7 @@ async function startTopUp() { updateState(setStep(state, 'generating_keys')); await ensureClients(); + startPlatformSdkForFunding(); const islock = islockService!; const network = getNetwork(state.network); @@ -2817,6 +2863,7 @@ async function startSendToAddress() { try { updateState(setStep(state, 'generating_keys')); await ensureClients(); + startPlatformSdkForFunding(); const islock = islockService!; const network = getNetwork(state.network); @@ -2988,6 +3035,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); @@ -3326,8 +3374,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 { @@ -3362,14 +3410,11 @@ 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 (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..6e27900 --- /dev/null +++ b/src/platform/client.test.ts @@ -0,0 +1,139 @@ +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(); + }); + + describe('isPlatformSdkReadable', () => { + it('is false while nobody has asked for the SDK, and asking about it loads nothing', async () => { + const { isPlatformSdkReadable } = await import('./client.js'); + + 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 { 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(isPlatformSdkReadable('testnet')).toBe(false); + + finishConnect(); + await connecting; + expect(isPlatformSdkReadable('testnet')).toBe(true); + expect(isPlatformSdkReadable('mainnet')).toBe(false); + }); + + 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); + + 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 { isPlatformSdkReadable } = await import('./client.js'); + sdkState.connect.mockRejectedValue(new Error('quorums unreachable')); + + await expect(connectPlatformSdk('testnet', { maxAttempts: 1 })).rejects.toThrow('quorums'); + + expect(isPlatformSdkReadable('testnet')).toBe(true); + }); + }); + + 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..b3fe62a 100644 --- a/src/platform/client.ts +++ b/src/platform/client.ts @@ -78,6 +78,39 @@ async function createPlatformSdk(network: PlatformNetwork): Promise { return EvoSDK.testnetTrusted(options); } +// 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>(); +// 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 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 { + 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'); + + sdkCache.set(network, sdk); + return sdk; + } finally { + firstConnectSettled.add(network); + } +} + export async function connectPlatformSdk( network: PlatformNetwork, retryOptions?: RetryOptions @@ -87,14 +120,33 @@ export async function connectPlatformSdk( return cached; } - const sdk = await createPlatformSdk(network); - - console.log(`Connecting to ${network}...`); - await withRetry(() => sdk.connect(), retryOptions); - console.log('Connected to Platform'); + let pending = pendingConnects.get(network); + if (!pending) { + pending = openPlatformSdk(network, retryOptions).finally(() => pendingConnects.delete(network)); + pendingConnects.set(network, pending); + } + return pending; +} - sdkCache.set(network, sdk); - return sdk; +/** + * 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 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 31871f8..09a9123 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,30 @@ 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. + * 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(false); + return loadPlatformClientModule() + .then(({ connectPlatformSdk }) => connectPlatformSdk(network)) + .then( + () => 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 new file mode 100644 index 0000000..b0bac1b --- /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(() => ({ + isPlatformSdkReadable: 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', () => ({ + isPlatformSdkReadable: mocks.isPlatformSdkReadable, + 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 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.isPlatformSdkReadable).toHaveBeenCalledWith('testnet'); + expect(mocks.loadSdk).not.toHaveBeenCalled(); + expect(mocks.status).not.toHaveBeenCalled(); + }); + + it('reads the status once the SDK is readable', async () => { + mocks.isPlatformSdkReadable.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.session.test.ts b/src/platform/status.session.test.ts new file mode 100644 index 0000000..b3e16f2 --- /dev/null +++ b/src/platform/status.session.test.ts @@ -0,0 +1,233 @@ +// @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 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 expect(warmPlatformSdkForFunding(network)).resolves.toBe(false); + + 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.toBe(true); + + 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'); + 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 () => { + 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.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..2efff6d --- /dev/null +++ b/src/platform/status.ts @@ -0,0 +1,82 @@ +import { + isPlatformSdkReadable, + 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; + } + const number = Number(value); + return Number.isSafeInteger(number) && number > 0 ? 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 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. + * + * 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 isPlatformSdkReadable(network) ? fetchPlatformStatus(network) : 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(); + // wasm getters build a new object per access, so read `chain` once. + const chain = status?.chain; + return { + coreChainLockedHeight: positiveInteger(chain?.core_chain_locked_height), + latestBlockHeight: positiveInteger(chain?.latest_block_height), + latestBlockTimeMs: positiveInteger(status?.time?.block), + }; + } + // Default retry options: when a poll's reconnect is joined by a write path + // (connects are shared), that path keeps its normal resilience. The 20 s + // timeout below bounds the poll itself. + ), + 'reading Platform status', + PLATFORM_STATUS_TIMEOUT_MS + ); +} 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 new file mode 100644 index 0000000..d1f18d2 --- /dev/null +++ b/src/ui/components.network-status.test.ts @@ -0,0 +1,85 @@ +// @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, + platformChecked: false, + }) + ); + + const indicator = container.querySelector('.net-status')!; + 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')!; + 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..28db465 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) @@ -61,9 +53,30 @@ function renderNetworkStatusIndicator(state: BridgeState): 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'); +} + +/** + * 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..ea373cf --- /dev/null +++ b/src/ui/network-status-sync.test.ts @@ -0,0 +1,172 @@ +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('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()); + 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); + + 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 new file mode 100644 index 0000000..d204d68 --- /dev/null +++ b/src/ui/network-status-sync.ts @@ -0,0 +1,68 @@ +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; + + 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 }; + + // 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; + } + 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; + }, + }; +}