From 819706b97132adb9e22c82d5c9ea2637b00d3444 Mon Sep 17 00:00:00 2001 From: pasta Date: Mon, 2 Nov 2026 13:57:03 -0600 Subject: [PATCH 1/3] fix(mainnet): get IS locks and chain-lock heights from DAPI, drop digitalcash.dev Mainnet still depended on rpc.digitalcash.dev for InstantSend locks and chain-lock heights. It now resets connections, so production mainnet showed "Chain-lock RPC unreachable" and could not get a lock. - Mainnet uses the testnet path from #55: evonodes discovered from the masternode list on dapi-client's mainnet seeds (health-checked by quorums.mainnet), 3 concurrent DAPI streams, Platform status and the ChainLock fallback's height through the EvoSDK, which a funding flow now connects on mainnet too. The mainnet list is ~1.2 MB, so mainnet waits 8 s before asking a second seed and 25 s before giving up. - No built-in JSON-RPC service anywhere: MAINNET.rpcUrl and the default mainnet endpoint are gone. JSON-RPC remains only for a custom devnet that configures its own rpcUrl. - The build check fails if "digitalcash" appears in any built file; an e2e test checks an idle mainnet page contacts neither digitalcash.dev nor the seeds. - The faucet button no longer sends `amount` (the faucet only takes one with an API key, which broke the button). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 3 +- e2e/deterministic.spec.ts | 17 +++++++++ scripts/check-build-artifacts.mjs | 15 ++++++++ src/api/dapi-subscription-multi.test.ts | 20 ++++++++-- src/api/dapi-subscription.ts | 51 ++++++++++++++----------- src/api/dapi.ts | 18 ++++----- src/api/evonode-discovery.ts | 44 ++++++++++++++------- src/api/evonodes.test.ts | 19 ++++----- src/api/evonodes.ts | 22 ++++++----- src/api/faucet.test.ts | 11 ++++++ src/api/faucet.ts | 9 ++--- src/api/islock.test.ts | 29 ++++++++++---- src/api/islock.ts | 25 +++++------- src/api/network-status.ts | 17 ++++----- src/api/platform-status-routing.test.ts | 7 ++-- src/api/request-deadlines.test.ts | 8 ++-- src/config.ts | 14 +++---- src/main.ts | 15 +++----- src/platform/loaders.ts | 13 +++---- src/platform/status.session.test.ts | 8 +++- src/types/external.d.ts | 1 + 21 files changed, 227 insertions(+), 139 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 6abc002..1f700f1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -87,8 +87,7 @@ 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 3 evonodes at once. They are discovered when a funding flow starts, from the masternode list served by `@dashevo/dapi-client`'s testnet seeds, with the quorum service list as fallback; the subscription rejects before broadcast if both fail. There is no built-in node list. Platform status is read through the EvoSDK (`platform/status.ts`) because dapi-client's `platform.getStatus()` throws on testnet nodes. +- **testnet and mainnet**: no JSON-RPC service, and no digitalcash.dev anywhere (the build check fails if it reappears). The lock comes from the DAPI bloom-filter stream on 3 evonodes at once. They are discovered when a funding flow starts, from the masternode list served by `@dashevo/dapi-client`'s seeds for that network, preferring nodes the quorum service health-checks and falling back to its list; the subscription rejects before broadcast if both fail. There is no built-in node list. Platform status is read through the EvoSDK (`platform/status.ts`) (it tolerates sections nodes leave out). - **devnets**: their configured `rpcUrl` if any, otherwise the DAPI stream over their `dapiAddresses`; Platform status through dapi-client. ## Dependencies diff --git a/e2e/deterministic.spec.ts b/e2e/deterministic.spec.ts index 2745642..bffcf77 100644 --- a/e2e/deterministic.spec.ts +++ b/e2e/deterministic.spec.ts @@ -58,6 +58,23 @@ test.describe('Deterministic UI E2E (mock mode)', () => { expect(discoveryRequests).toEqual([]); }); + test('an idle mainnet page never calls digitalcash.dev and starts no evonode discovery', async ({ page }) => { + const forbidden: string[] = []; + page.on('request', (request) => { + const url = new URL(request.url()); + if (/(^|\.)digitalcash\.dev$/.test(url.hostname) || /^seed-\d+\./.test(url.hostname)) forbidden.push(request.url()); + }); + const islockChunk = page.waitForRequest((request) => /\/islock(-[^/]*\.js|\.ts)$/.test(new URL(request.url()).pathname), { + timeout: 15000, + }); + await page.goto('/?network=mainnet&e2e=mock'); + await islockChunk; + // Let the first network-status poll go out. + await page.waitForTimeout(2000); + + expect(forbidden).toEqual([]); + }); + test('create identity flow transitions to completion and DPNS registration', async ({ page }) => { await page.goto(MOCK_QUERY); diff --git a/scripts/check-build-artifacts.mjs b/scripts/check-build-artifacts.mjs index 240dcf7..f3482be 100644 --- a/scripts/check-build-artifacts.mjs +++ b/scripts/check-build-artifacts.mjs @@ -128,4 +128,19 @@ if (typeof verifyLogin !== 'function' || bogus?.ok !== false) { fail('dist/widget-verify.mjs does not export a working verifyLogin'); } +// No Digital Cash service anywhere: IS locks and chain-lock heights come from +// DAPI (evonode streams, the EvoSDK). Guard against one creeping back in. +function builtFiles(dir) { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const path = join(dir, entry.name); + return entry.isDirectory() ? builtFiles(path) : [path]; + }); +} +const digitalcashFiles = builtFiles(distDir.pathname).filter((path) => + /\.(?:js|mjs|html|json|css)$/.test(path) && readFileSync(path, 'utf8').includes('digitalcash') +); +if (digitalcashFiles.length > 0) { + fail(`build references digitalcash: ${digitalcashFiles.join(', ')}`); +} + console.log('Build artifact smoke check passed'); diff --git a/src/api/dapi-subscription-multi.test.ts b/src/api/dapi-subscription-multi.test.ts index 1eb6d3e..2713c67 100644 --- a/src/api/dapi-subscription-multi.test.ts +++ b/src/api/dapi-subscription-multi.test.ts @@ -114,7 +114,7 @@ vi.mock('cbor', () => ({ default: { decodeFirstSync: (bytes: Buffer) => JSON.par const fallbackMock = vi.hoisted(() => vi.fn<[], Promise>()); vi.mock('./evonodes.js', async (importOriginal) => ({ ...(await importOriginal()), - fetchTestnetEvonodeAddresses: fallbackMock, + fetchHealthyEvonodeAddresses: fallbackMock, })); import { @@ -603,8 +603,8 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { await sub.wait(); }); - it('uses the single shared client with fewer than two configured addresses', async () => { - for (const dapiAddresses of [undefined, [] as string[], addresses(1)]) { + it('uses the single shared client for a devnet with one configured address', async () => { + for (const dapiAddresses of [addresses(1)]) { state.clients.length = 0; const client = new DAPISubscriptionClient({ network: 'devnet-moutai', dapiAddresses }); expect(state.clients).toHaveLength(1); @@ -798,6 +798,20 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { expect(nodeClients()).toHaveLength(3); }); + it('mainnet discovers its evonodes from the mainnet seeds the same way', async () => { + state.smlHosts = hosts(4); + const client = new DAPISubscriptionClient({ network: 'mainnet' }); + + const sub = await startDiscovered(client); + + expect(seedClients()).toHaveLength(1); + const seed = seedClients()[0].options.dapiAddresses[0]; + expect(seed.host).toMatch(/\.mainnet\.networks\.dash\.org$|pshenmic/); + expect(nodeClients()).toHaveLength(ISLOCK_CONCURRENT_NODES); + liveStreams()[0].emit('data', lockMessage(TXID)); + await expect(sub.wait()).resolves.toBeInstanceOf(Uint8Array); + }); + it('configured addresses (devnets) never start discovery', async () => { const client = new DAPISubscriptionClient({ network: 'devnet-moutai', dapiAddresses: addresses(3) }); diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index 730637d..2bf40ea 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -8,6 +8,7 @@ import { hash160 } from '../crypto/hash.js'; import { describeIslock } from '../utils/islock-debug.js'; import { EvonodeDiscovery, + type DiscoveryNetwork, parseDapiAddress, seedAddresses, shuffled, @@ -60,11 +61,19 @@ interface NodeSlot { failed: boolean; } +/** + * The public network a config belongs to (by type, so an unknown name that + * falls back to the testnet config counts as testnet); undefined for devnets. + */ +function publicNetwork(network: string): DiscoveryNetwork | undefined { + const { type } = getNetwork(network); + return type === 'testnet' || type === 'mainnet' ? type : undefined; +} + export class DAPISubscriptionClient { readonly network: string; - // Exactly one of these is set: testnet discovers its evonodes, every other - // network uses one client over its configured addresses (or, on mainnet, - // dapi-client's default seeds). + // Exactly one of these is set: testnet and mainnet discover their evonodes, + // devnets use one client over their configured addresses. private readonly discovery?: EvonodeDiscovery; private readonly fixedClient?: any; private readonly nodeAddresses: DapiAddress[]; @@ -83,25 +92,23 @@ export class DAPISubscriptionClient { // A repeated address would put two "distinct" streams on one node. this.nodeAddresses = [...new Map(parsed.map((a) => [`${a.host}:${a.port}`, a])).values()]; this.fixedClient = new DAPIClientClass({ ...CLIENT_OPTIONS, dapiAddresses: parsed }); - } else if (getNetwork(config.network).type === 'testnet') { + } else { // Seeds come from the published dapi-client, so they follow its releases. + // A devnet without addresses can't be reached; it discovers testnet's, + // as dapi-client's default would have. + const network = publicNetwork(config.network) ?? 'testnet'; this.discovery = new EvonodeDiscovery({ - network: 'testnet', - seeds: seedAddresses(dapiNetworkConfigs.testnet.seeds), + network, + seeds: seedAddresses(dapiNetworkConfigs[network].seeds), createClient: (dapiAddresses) => new DAPIClientClass({ ...CLIENT_OPTIONS, dapiAddresses }), }); - } else { - this.fixedClient = new DAPIClientClass({ - ...CLIENT_OPTIONS, - network: config.network === 'mainnet' ? 'mainnet' : 'testnet', - }); } } /** - * Client for calls that may go to any node. On testnet it covers the - * evonodes found by the last discovery, so it is undefined before the - * first subscription. + * Client for calls that may go to any node. On testnet and mainnet it + * covers the evonodes found by the last discovery, so it is undefined + * before the first subscription. */ private get dapiClient(): any { return this.discovery ? this.discovery.sharedClient : this.fixedClient; @@ -640,8 +647,8 @@ export class DAPISubscriptionClient { * 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. + * Testnet and mainnet read through the EvoSDK (see `fetchPlatformStatus` + * for why); devnets keep the dapi-client gRPC call. */ async getPlatformStatus(): Promise { if (this.readsStatusViaSdk()) { @@ -652,10 +659,11 @@ export class DAPISubscriptionClient { /** * 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). + * On testnet and mainnet 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. + * Devnets read exactly as getPlatformStatus does (dapi-client needs no SDK + * download). */ async peekPlatformStatus(): Promise { if (this.readsStatusViaSdk()) { @@ -664,9 +672,8 @@ export class DAPISubscriptionClient { 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'; + return publicNetwork(this.network) !== undefined; } private async fetchStatusViaDapiClient(): Promise { diff --git a/src/api/dapi.ts b/src/api/dapi.ts index 33d9e25..9d4e29c 100644 --- a/src/api/dapi.ts +++ b/src/api/dapi.ts @@ -1,5 +1,9 @@ /** - * Client for InstantSend lock retrieval via JSON-RPC API + * JSON-RPC client for InstantSend locks and the best chain lock, used only + * for a custom devnet that configures its own `rpcUrl`. Testnet and mainnet + * use no JSON-RPC service: their IS locks come from DAPI streams on + * discovered evonodes (api/evonode-discovery.ts) and their chain-locked + * height from the EvoSDK. */ import { withRetry, isRetryableError, type RetryOptions } from '../utils/retry.js'; @@ -7,12 +11,6 @@ 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 on -// evonodes it discovers (see api/evonode-discovery.ts) because -// trpc.digitalcash.dev never upgraded to V24. -const API_URLS: Record = { - mainnet: 'https://rpc.digitalcash.dev', -}; export interface DAPIConfig { network: string; @@ -57,7 +55,7 @@ export class DAPIClient { } get hasRpcUrl(): boolean { - return !!(this.rpcUrl || API_URLS[this.network]); + return !!this.rpcUrl; } /** @@ -149,7 +147,7 @@ export class DAPIClient { } return withRetry(async () => { - const baseUrl = this.rpcUrl ?? API_URLS[this.network]; + const baseUrl = this.rpcUrl; if (!baseUrl) { return null; } @@ -175,7 +173,7 @@ export class DAPIClient { signal?: AbortSignal ): Promise { return withRetry(async () => { - const baseUrl = this.rpcUrl ?? API_URLS[this.network]; + const baseUrl = this.rpcUrl; if (!baseUrl) { throw new Error(`No RPC URL configured for network ${this.network}`); } diff --git a/src/api/evonode-discovery.ts b/src/api/evonode-discovery.ts index 2dbbf91..bb9d7b6 100644 --- a/src/api/evonode-discovery.ts +++ b/src/api/evonode-discovery.ts @@ -2,7 +2,7 @@ import dashcoreLib from '@dashevo/dashcore-lib'; import cbor from 'cbor'; -import { fetchTestnetEvonodeAddresses, toDapiEndpoint } from './evonodes.js'; +import { fetchHealthyEvonodeAddresses, toDapiEndpoint } from './evonodes.js'; /** A DAPI endpoint in the shape dapi-client's `dapiAddresses` option takes. */ export interface DapiAddress { @@ -14,10 +14,27 @@ export interface DapiAddress { /** A dapi-client pinned to the given addresses. */ export type CreateDapiClient = (addresses: DapiAddress[]) => any; -/** Longest one masternode list fetch may take, across all seeds tried. */ +export type DiscoveryNetwork = 'testnet' | 'mainnet'; + +/** Longest one testnet masternode list fetch may take, across all seeds tried. */ export const MASTERNODE_LIST_TIMEOUT_MS = 10000; -/** A seed that hasn't answered by then gets company: the next seed is asked too. */ +/** A testnet seed that hasn't answered by then gets company: the next seed is asked too. */ export const SEED_HEDGE_DELAY_MS = 3000; + +export interface ListFetchTiming { + timeoutMs: number; + hedgeDelayMs: number; +} + +/** + * The full mainnet list is about 1.2 MB (vs 270 kB on testnet) and took + * 4.6–7.6 s from a healthy seed, so mainnet waits longer before asking a + * second seed and before giving up. + */ +export const LIST_FETCH_TIMING: Record = { + testnet: { timeoutMs: MASTERNODE_LIST_TIMEOUT_MS, hedgeDelayMs: SEED_HEDGE_DELAY_MS }, + mainnet: { timeoutMs: 25000, hedgeDelayMs: 8000 }, +}; /** A list older than this is fetched again before use. */ export const EVONODE_LIST_MAX_AGE_MS = 10 * 60_000; /** @@ -80,8 +97,9 @@ function cancelQuietly(stream: any): void { export function fetchEvonodesFromSeeds( seeds: readonly DapiAddress[], createClient: CreateDapiClient, - network: string, - signal?: AbortSignal + network: DiscoveryNetwork, + signal?: AbortSignal, + timing: ListFetchTiming = LIST_FETCH_TIMING[network] ): Promise { return new Promise((resolve, reject) => { // Attempts still in play; leaving this set is what retires an attempt. @@ -107,15 +125,15 @@ export function fetchEvonodesFromSeeds( }; const onAbort = (): void => finish(() => reject(new Error('Masternode list fetch aborted'))); const deadlineTimer = setTimeout( - () => finish(() => reject(new Error(`Masternode list fetch timed out after ${MASTERNODE_LIST_TIMEOUT_MS}ms`))), - MASTERNODE_LIST_TIMEOUT_MS + () => finish(() => reject(new Error(`Masternode list fetch timed out after ${timing.timeoutMs}ms`))), + timing.timeoutMs ); const tryNextSeed = (): void => { clearTimeout(hedgeTimer); const seed = seeds[next++]; if (!seed) return; - hedgeTimer = setTimeout(tryNextSeed, SEED_HEDGE_DELAY_MS); + hedgeTimer = setTimeout(tryNextSeed, timing.hedgeDelayMs); const attempt: { client?: any; stream?: any } = {}; open.add(attempt); @@ -185,7 +203,7 @@ export function fetchEvonodesFromSeeds( } export interface EvonodeDiscoveryOptions { - network: string; + network: DiscoveryNetwork; seeds: readonly DapiAddress[]; createClient: CreateDapiClient; /** Quorum-service list of evonodes that pass its health check. */ @@ -194,7 +212,7 @@ export interface EvonodeDiscoveryOptions { } /** - * Finds the testnet evonodes to open IS lock streams on. The source is the + * Finds the evonodes (testnet or mainnet) to open IS lock streams on. The source is the * simplified masternode list served by the network seeds (dapi-client's * discovery source), read with {@link fetchEvonodesFromSeeds}. The quorum * service's list of nodes passing its DAPI health check is read alongside: @@ -212,7 +230,7 @@ export interface EvonodeDiscoveryOptions { * before broadcasting. */ export class EvonodeDiscovery { - private readonly network: string; + private readonly network: DiscoveryNetwork; private readonly seeds: readonly DapiAddress[]; private readonly createClient: CreateDapiClient; private readonly fetchHealthy: () => Promise; @@ -226,7 +244,7 @@ export class EvonodeDiscovery { this.network = options.network; this.seeds = options.seeds; this.createClient = options.createClient; - this.fetchHealthy = options.fetchHealthy ?? fetchTestnetEvonodeAddresses; + this.fetchHealthy = options.fetchHealthy ?? (() => fetchHealthyEvonodeAddresses(options.network)); this.now = options.now ?? Date.now; } @@ -246,7 +264,7 @@ export class EvonodeDiscovery { async getNodes(signal?: AbortSignal): Promise { const endpoints = await whenNotAborted(this.readList(), signal); if (endpoints.length === 0) { - throw new Error('No testnet evonodes found: the masternode list and the quorum service both failed'); + throw new Error(`No ${this.network} evonodes found: the masternode list and the quorum service both failed`); } const nodes = endpoints.map(parseDapiAddress); this.updateSharedClient(endpoints, nodes); diff --git a/src/api/evonodes.test.ts b/src/api/evonodes.test.ts index ef3bb24..aede37d 100644 --- a/src/api/evonodes.test.ts +++ b/src/api/evonodes.test.ts @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { - TESTNET_MASTERNODES_URL, - fetchTestnetEvonodeAddresses, + fetchHealthyEvonodeAddresses, + quorumMasternodesUrl, parseEvonodeAddresses, toDapiEndpoint, } from './evonodes.js'; @@ -104,7 +104,7 @@ describe('toDapiEndpoint', () => { }); }); -describe('fetchTestnetEvonodeAddresses', () => { +describe('fetchHealthyEvonodeAddresses', () => { const fetchMock = vi.fn(); beforeEach(() => { @@ -130,25 +130,26 @@ describe('fetchTestnetEvonodeAddresses', () => { it('returns the healthy nodes from the quorum service', async () => { respond(payload(node('10.0.0.1'), node('10.0.0.2', { status: 'POSE_BANNED' }), node('10.0.0.3'))); - await expect(fetchTestnetEvonodeAddresses()).resolves.toEqual([ + await expect(fetchHealthyEvonodeAddresses('testnet')).resolves.toEqual([ 'https://10.0.0.1:1443', 'https://10.0.0.3:1443', ]); expect(fetchMock).toHaveBeenCalledOnce(); - expect(fetchMock.mock.calls[0][0]).toBe(TESTNET_MASTERNODES_URL); + expect(fetchMock.mock.calls[0][0]).toBe('https://quorums.testnet.networks.dash.org/masternodes'); + expect(quorumMasternodesUrl('mainnet')).toBe('https://quorums.mainnet.networks.dash.org/masternodes'); }); it('returns nothing on a network error, without retrying', async () => { fetchMock.mockRejectedValue(new TypeError('Failed to fetch')); - await expect(fetchTestnetEvonodeAddresses()).resolves.toEqual([]); + await expect(fetchHealthyEvonodeAddresses('testnet')).resolves.toEqual([]); expect(fetchMock).toHaveBeenCalledOnce(); }); it('returns nothing on an HTTP error', async () => { respond({}, false); - await expect(fetchTestnetEvonodeAddresses()).resolves.toEqual([]); + await expect(fetchHealthyEvonodeAddresses('testnet')).resolves.toEqual([]); }); it('returns nothing on invalid JSON', async () => { @@ -161,7 +162,7 @@ describe('fetchTestnetEvonodeAddresses', () => { }, }); - await expect(fetchTestnetEvonodeAddresses()).resolves.toEqual([]); + await expect(fetchHealthyEvonodeAddresses('testnet')).resolves.toEqual([]); }); it('gives up after the 5 s timeout', async () => { @@ -175,7 +176,7 @@ describe('fetchTestnetEvonodeAddresses', () => { }) ); - const result = fetchTestnetEvonodeAddresses(); + const result = fetchHealthyEvonodeAddresses('testnet'); await vi.advanceTimersByTimeAsync(5000); await expect(result).resolves.toEqual([]); diff --git a/src/api/evonodes.ts b/src/api/evonodes.ts index f8ce714..9c768e6 100644 --- a/src/api/evonodes.ts +++ b/src/api/evonodes.ts @@ -1,13 +1,15 @@ 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. Used only as the fallback when dapi-client's masternode - * list discovery fails (see evonode-discovery.ts). + * The quorum service lists every masternode of a network 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. Discovery uses it as a health hint and as the fallback + * when the masternode list can't be read (see evonode-discovery.ts). */ -export const TESTNET_MASTERNODES_URL = 'https://quorums.testnet.networks.dash.org/masternodes'; +export function quorumMasternodesUrl(network: 'testnet' | 'mainnet'): string { + return `https://quorums.${network}.networks.dash.org/masternodes`; +} const EVONODE_FETCH_TIMEOUT_MS = 5000; @@ -72,16 +74,16 @@ function coreHostEndpoint(address: unknown): string | undefined { } /** - * Healthy testnet evonode endpoints from the quorum service (one attempt, + * Healthy evonode endpoints from the network's quorum service (one attempt, * 5 s). Resolves an empty list, after logging why, when the service fails. */ -export async function fetchTestnetEvonodeAddresses(): Promise { +export async function fetchHealthyEvonodeAddresses(network: 'testnet' | 'mainnet'): Promise { try { return parseEvonodeAddresses( - await fetchJson(TESTNET_MASTERNODES_URL, {}, EVONODE_FETCH_TIMEOUT_MS) + await fetchJson(quorumMasternodesUrl(network), {}, EVONODE_FETCH_TIMEOUT_MS) ); } catch (error) { - console.warn('Could not fetch the testnet evonode list from the quorum service:', error); + console.warn(`Could not fetch the ${network} evonode list from the quorum service:`, error); return []; } } diff --git a/src/api/faucet.test.ts b/src/api/faucet.test.ts index 2edc07b..37f3994 100644 --- a/src/api/faucet.test.ts +++ b/src/api/faucet.test.ts @@ -120,6 +120,17 @@ describe('requestTestnetFunds', () => { vi.unstubAllGlobals(); }); + it('asks for the standard payout without an amount (the faucet rejects an unkeyed amount)', async () => { + stubFaucetResponse({ txid: VALID_TXID, amount: 1, address: 'yAddr' }); + const { requestTestnetFunds } = await import('./faucet.js'); + + await requestTestnetFunds('https://faucet.example', 'yAddr', 'cap-token'); + + const [url, init] = (fetch as unknown as { mock: { calls: [string, RequestInit][] } }).mock.calls[0]; + expect(url).toBe('https://faucet.example/api/core-faucet'); + expect(JSON.parse(init.body as string)).toEqual({ address: 'yAddr', capToken: 'cap-token' }); + }); + it('returns a response with a hex txid', async () => { stubFaucetResponse({ txid: VALID_TXID, amount: 1, address: 'yAddr' }); const { requestTestnetFunds } = await import('./faucet.js'); diff --git a/src/api/faucet.ts b/src/api/faucet.ts index 9d49257..9557743 100644 --- a/src/api/faucet.ts +++ b/src/api/faucet.ts @@ -186,18 +186,15 @@ function loadCapWidget(): Promise { } /** - * Request testnet funds from the faucet + * Request the faucet's standard payout. No `amount` is sent: the faucet only + * accepts one with an API key. */ export async function requestTestnetFunds( baseUrl: string, address: string, - amount: number = 1.0, capToken?: string ): Promise { - const body: Record = { - address, - amount, - }; + const body: Record = { address }; if (capToken) { body.capToken = capToken; diff --git a/src/api/islock.test.ts b/src/api/islock.test.ts index 28eb2a7..67b0fbb 100644 --- a/src/api/islock.test.ts +++ b/src/api/islock.test.ts @@ -15,7 +15,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'; + return !!config.rpcUrl; }, waitForInstantSendLock: mocks.waitForInstantSendLock, getBestChainLock: mocks.getBestChainLock, @@ -41,10 +41,10 @@ describe('IslockService', () => { mocks.getTransactionLockStatus.mockResolvedValue(null); }); - it('uses JSON-RPC only on mainnet to avoid browser DAPI stream discovery', async () => { + it('uses JSON-RPC only for a devnet that configures its own rpcUrl', async () => { const bytes = new Uint8Array([1, 2, 3]); mocks.waitForInstantSendLock.mockResolvedValue(bytes); - const service = new IslockService({ network: 'mainnet' }); + const service = new IslockService({ network: 'devnet-moutai', rpcUrl: 'https://rpc.devnet.test' }); const progress: string[] = []; const handle = await service.subscribeForInstantSendLock( @@ -115,13 +115,28 @@ describe('IslockService', () => { await expect(handle.wait()).resolves.toBe(bytes); }); - it('warms evonode discovery on testnet but not on JSON-RPC networks', async () => { + it('uses the DAPI subscription on mainnet too: no JSON-RPC service anywhere by default', async () => { + const { MAINNET } = await import('../config.js'); + const bytes = new Uint8Array([7]); + mocks.subscribeForInstantSendLock.mockResolvedValue({ wait: vi.fn().mockResolvedValue(bytes) }); + const service = new IslockService({ network: 'mainnet', rpcUrl: MAINNET.rpcUrl }); + + expect(MAINNET.rpcUrl).toBeUndefined(); + expect(service.supportsJsonRpc).toBe(false); + const handle = await service.subscribeForInstantSendLock('txid', new Uint8Array([4]), { txid: 'prevout', vout: 0 }); + + expect(mocks.waitForInstantSendLock).not.toHaveBeenCalled(); + await expect(handle.wait()).resolves.toBe(bytes); + }); + + it('warms evonode discovery on testnet and mainnet but not on JSON-RPC networks', async () => { mocks.warmEvonodeDiscovery.mockResolvedValue(undefined); await new IslockService({ network: 'testnet' }).warmEvonodeDiscovery(); - expect(mocks.warmEvonodeDiscovery).toHaveBeenCalledOnce(); - await new IslockService({ network: 'mainnet' }).warmEvonodeDiscovery(); - expect(mocks.warmEvonodeDiscovery).toHaveBeenCalledOnce(); + expect(mocks.warmEvonodeDiscovery).toHaveBeenCalledTimes(2); + + await new IslockService({ network: 'devnet-moutai', rpcUrl: 'https://rpc.devnet.test' }).warmEvonodeDiscovery(); + expect(mocks.warmEvonodeDiscovery).toHaveBeenCalledTimes(2); }); }); diff --git a/src/api/islock.ts b/src/api/islock.ts index 4c12975..1d1c4e3 100644 --- a/src/api/islock.ts +++ b/src/api/islock.ts @@ -67,13 +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. Networks without - * RPC (testnet, devnets) use the DAPI bloom subscription (testnet over the - * evonodes it discovers, devnets over their configured 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. + * `.wait()` resolves with the IS lock bytes once available. Testnet, mainnet + * and devnets use the DAPI bloom subscription (testnet and mainnet over the + * evonodes they discover, devnets over their configured dapiAddresses), + * which must be established before broadcast because subscriptions don't + * replay historical IS locks. Only a custom devnet that configures its own + * rpcUrl polls JSON-RPC instead. */ async subscribeForInstantSendLock( txid: string, @@ -105,10 +104,7 @@ export class IslockService { }; } - // 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. + // A devnet with its own rpcUrl polls it by txid and opens no stream. const jsonRpcController = new AbortController(); onProgress?.('Polling InstantSend lock...'); @@ -158,11 +154,8 @@ export class IslockService { } /** - * 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. + * Whether a JSON-RPC endpoint is configured: only a custom devnet with its + * own rpcUrl. Every other network reads Platform status instead. */ get supportsJsonRpc(): boolean { return this.hasJsonRpc; diff --git a/src/api/network-status.ts b/src/api/network-status.ts index 99edc25..74cfe7a 100644 --- a/src/api/network-status.ts +++ b/src/api/network-status.ts @@ -34,15 +34,14 @@ export async function fetchNetworkStatus( const checkedAtMs = Date.now(); // Route the chain-lock source the same way the islock flow is routed: - // - 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. - // - 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. + // - a custom devnet with its own rpcUrl: read Core's best chain-lock over + // JSON-RPC. + // - everything else: read full Platform status, which also yields + // Tenderdash block height + age. IslockService picks the path (EvoSDK on + // testnet and mainnet, DAPI over explicit dapiAddresses on devnets). On + // testnet and mainnet this is passive: Platform is only read once a + // funding flow has started connecting the SDK, so an idle page never + // downloads it. const useDapiPlatformStatus = !islock.supportsJsonRpc; // Bound the Insight retry so a flaky endpoint can't stretch one poll past the diff --git a/src/api/platform-status-routing.test.ts b/src/api/platform-status-routing.test.ts index 593178d..0380a8d 100644 --- a/src/api/platform-status-routing.test.ts +++ b/src/api/platform-status-routing.test.ts @@ -104,12 +104,13 @@ describe('Platform status routing', () => { expect(mocks.fetchPlatformStatus).not.toHaveBeenCalled(); }); - it('keeps the dapi-client call on mainnet', async () => { - mocks.dapiGetStatus.mockResolvedValue({ chain: { coreChainLockedHeight: 5 } }); + it('reads mainnet status through the SDK too (no JSON-RPC or dapi-client status there)', async () => { + mocks.fetchPlatformStatus.mockResolvedValue({ coreChainLockedHeight: 5 }); const client = new DAPISubscriptionClient({ network: 'mainnet' }); await expect(client.getCoreChainLockedHeight()).resolves.toBe(5); - expect(mocks.fetchPlatformStatus).not.toHaveBeenCalled(); + expect(mocks.fetchPlatformStatus).toHaveBeenCalledWith('mainnet'); + expect(mocks.dapiGetStatus).not.toHaveBeenCalled(); }); }); diff --git a/src/api/request-deadlines.test.ts b/src/api/request-deadlines.test.ts index 5edfabd..66679ec 100644 --- a/src/api/request-deadlines.test.ts +++ b/src/api/request-deadlines.test.ts @@ -100,7 +100,7 @@ describe('per-request deadlines', () => { const fetchMock = stalledHeaders(); vi.stubGlobal('fetch', fetchMock); const onRetry = vi.fn(); - const service = new IslockService({ network: 'mainnet' }); + const service = new IslockService({ network: 'devnet-moutai', rpcUrl: 'https://rpc.devnet.test' }); const handle = await service.subscribeForInstantSendLock( 'txid', new Uint8Array([1]), @@ -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: 'mainnet' }); + const client = new DAPIClient({ network: 'devnet-moutai', rpcUrl: 'https://rpc.devnet.test' }); 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: 'mainnet' }); + const client = new DAPIClient({ network: 'devnet-moutai', rpcUrl: 'https://rpc.devnet.test' }); // 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: 'mainnet' }); + const client = new DAPIClient({ network: 'devnet-moutai', rpcUrl: 'https://rpc.devnet.test' }); 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 6f482c7..7007f9b 100644 --- a/src/config.ts +++ b/src/config.ts @@ -44,12 +44,11 @@ export const TESTNET: NetworkConfig = { dustThreshold: 546, platformHrp: 'tdash', faucetBaseUrl: 'https://faucet.thepasta.org', - // 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, on evonodes found through dapi-client's masternode list - // discovery (falling back to the quorum service's list); see - // api/evonode-discovery.ts. No dapiAddresses: evonodes and their - // certificates rotate within days, so any built-in list goes stale. + // No rpcUrl: IS locks come from the DAPI bloom stream on evonodes found + // through dapi-client's masternode list discovery (with the quorum + // service's list as health hint and fallback); see api/evonode-discovery.ts. + // No dapiAddresses: evonodes and their certificates rotate within days, so + // any built-in list goes stale. }; export const MAINNET: NetworkConfig = { @@ -62,7 +61,8 @@ export const MAINNET: NetworkConfig = { minFee: 1000, dustThreshold: 546, platformHrp: 'dash', - rpcUrl: 'https://rpc.digitalcash.dev', + // No rpcUrl: like testnet, IS locks come from DAPI streams on discovered + // evonodes and Platform status from the EvoSDK (api/evonode-discovery.ts). }; export const DEVNET_MOUTAI: NetworkConfig = { diff --git a/src/main.ts b/src/main.ts index 2982313..1465ae1 100644 --- a/src/main.ts +++ b/src/main.ts @@ -3517,10 +3517,10 @@ async function startChainlockFallback(): Promise { ); // 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). + // first (only a custom devnet with its own rpcUrl has one; it returns + // nothing elsewhere), then the Platform status via IslockService: the EvoSDK + // on testnet and mainnet, direct gRPC via @dashevo/dapi-client on devnets + // (see DAPISubscriptionClient.getCoreChainLockedHeight). const chainLockPoll = (async (): Promise => { while (!signal.aborted) { let height: number | undefined; @@ -4512,12 +4512,7 @@ async function requestFaucetFunds() { // Step 3: Request funds updateState(setFaucetRequesting(state)); - const result = await requestTestnetFunds( - network.faucetBaseUrl, - state.depositAddress, - 1.0, // 1 DASH - capToken - ); + const result = await requestTestnetFunds(network.faucetBaseUrl, state.depositAddress, capToken); updateState(setFaucetSuccess(state, result.txid)); diff --git a/src/platform/loaders.ts b/src/platform/loaders.ts index 8099b6c..7680f71 100644 --- a/src/platform/loaders.ts +++ b/src/platform/loaders.ts @@ -59,15 +59,14 @@ export async function loadPlatformForFunding(timeoutMs = 5 * 60_000): Promise { - if (getNetwork(network).type !== 'testnet') return Promise.resolve(false); + if (getNetwork(network).type === 'devnet') return Promise.resolve(false); return loadPlatformClientModule() .then(({ connectPlatformSdk }) => connectPlatformSdk(network)) .then( diff --git a/src/platform/status.session.test.ts b/src/platform/status.session.test.ts index b3e16f2..0163e93 100644 --- a/src/platform/status.session.test.ts +++ b/src/platform/status.session.test.ts @@ -89,7 +89,13 @@ describe('Platform status across an SDK session', () => { expect(sdk.connect).toHaveBeenCalledOnce(); }); - it.each(['mainnet', 'devnet-moutai'])('does nothing on %s', async (network) => { + it('connects the mainnet SDK when a funding flow starts', async () => { + await expect(warmPlatformSdkForFunding('mainnet')).resolves.toBe(true); + + expect(sdk.created).toEqual(['mainnet']); + }); + + it.each(['devnet-moutai'])('does nothing on %s', async (network) => { await expect(warmPlatformSdkForFunding(network)).resolves.toBe(false); expect(sdk.created).toEqual([]); diff --git a/src/types/external.d.ts b/src/types/external.d.ts index f6e1aa6..e2a21be 100644 --- a/src/types/external.d.ts +++ b/src/types/external.d.ts @@ -50,6 +50,7 @@ declare module '@dashevo/dapi-client' { declare module '@dashevo/dapi-client/lib/networkConfigs.js' { const networkConfigs: { testnet: { seeds: string[] }; + mainnet: { seeds: string[] }; }; export default networkConfigs; } From 138bcaabf9e669a78a14abffb207dbc474d74bf9 Mon Sep 17 00:00:00 2001 From: pasta Date: Mon, 2 Nov 2026 14:16:06 -0600 Subject: [PATCH 2/3] fix(dapi): never broadcast before a stream has delivered data; retry before broadcast Review follow-ups for mainnet on DAPI, where these now guard real funds. - Readiness means a stream delivered data: subscribe waits up to 15 s for the first message (streams replay the last 10 blocks first, so a live one answers in about a second) and otherwise rejects before broadcast. The old 3 s cap could broadcast with no stream known to be listening and miss a fast IS lock. - A subscription that fails before broadcast is retried twice (after 5 s and 15 s; disconnect stops the wait). The final error says nothing was broadcast and the deposit is unspent and recoverable from the key backup. - A list past its 10-minute age is served while it is read again (up to an hour), so a subscription after a long deposit wait doesn't wait up to 25 s for a full mainnet list before broadcasting. - Quorum records without platform_https use their platformHTTPPort (443 on mainnet) instead of 1443. - Tests: mainnet health hint uses the mainnet quorum service, mainnet list timing, readiness timeout, retry/abort, stale-while-revalidate; the mainnet idle e2e also forbids SDK and /masternodes requests. Stale testnet-only and JSON-RPC comments fixed. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 6 +- e2e/deterministic.spec.ts | 11 +++- src/api/dapi-subscription-multi.test.ts | 25 ++++---- src/api/dapi-subscription.ts | 34 +++++++--- src/api/evonode-discovery.test.ts | 38 ++++++++++- src/api/evonode-discovery.ts | 23 ++++++- src/api/evonodes.test.ts | 6 +- src/api/evonodes.ts | 15 +++-- src/api/islock.test.ts | 83 ++++++++++++++++++++----- src/api/islock.ts | 56 ++++++++++++++--- src/main.ts | 20 +++--- src/platform/status.ts | 6 +- 12 files changed, 247 insertions(+), 76 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 1f700f1..1205804 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -41,10 +41,10 @@ src/ │ └── builder.ts # InstantSend lock proof building ├── api/ # Network communication │ ├── insight.ts # Insight API client (UTXO fetching, broadcast) -│ ├── dapi.ts # JSON-RPC client (mainnet InstantSend locks, best chain lock) -│ ├── dapi-subscription.ts # DAPI bloom-filter stream (testnet/devnet InstantSend locks) +│ ├── dapi.ts # JSON-RPC client (only for a custom devnet with its own rpcUrl) +│ ├── dapi-subscription.ts # DAPI bloom-filter streams (InstantSend locks on every network) │ ├── islock.ts # IslockService: picks the InstantSend lock source per network -│ ├── evonode-discovery.ts # Testnet evonodes from the masternode list the seeds serve +│ ├── evonode-discovery.ts # Testnet/mainnet evonodes from the masternode list the seeds serve │ └── evonodes.ts # Quorum-service evonode list (discovery fallback) ├── platform/ # Dash Platform operations │ ├── identity.ts # Identity registration and top-up diff --git a/e2e/deterministic.spec.ts b/e2e/deterministic.spec.ts index bffcf77..bfab7eb 100644 --- a/e2e/deterministic.spec.ts +++ b/e2e/deterministic.spec.ts @@ -58,11 +58,18 @@ test.describe('Deterministic UI E2E (mock mode)', () => { expect(discoveryRequests).toEqual([]); }); - test('an idle mainnet page never calls digitalcash.dev and starts no evonode discovery', async ({ page }) => { + test('an idle mainnet page never calls digitalcash.dev, starts no evonode discovery and does not load the SDK', async ({ page }) => { const forbidden: string[] = []; page.on('request', (request) => { const url = new URL(request.url()); - if (/(^|\.)digitalcash\.dev$/.test(url.hostname) || /^seed-\d+\./.test(url.hostname)) forbidden.push(request.url()); + if ( + /(^|\.)digitalcash\.dev$/.test(url.hostname) || + /^seed-\d+\./.test(url.hostname) || + url.pathname === '/masternodes' || + /evo-sdk|wasm[-_]sdk/i.test(url.pathname) + ) { + forbidden.push(request.url()); + } }); const islockChunk = page.waitForRequest((request) => /\/islock(-[^/]*\.js|\.ts)$/.test(new URL(request.url()).pathname), { timeout: 15000, diff --git a/src/api/dapi-subscription-multi.test.ts b/src/api/dapi-subscription-multi.test.ts index 2713c67..9c9b95b 100644 --- a/src/api/dapi-subscription-multi.test.ts +++ b/src/api/dapi-subscription-multi.test.ts @@ -122,7 +122,7 @@ import { ISLOCK_CONCURRENT_NODES, ISLOCK_MAX_NODE_ATTEMPTS, ISLOCK_HEIGHT_TIMEOUT_MS, - ISLOCK_READINESS_CAP_MS, + ISLOCK_READINESS_TIMEOUT_MS, } from './dapi-subscription.js'; const TXID = 'aa'.repeat(32); @@ -447,15 +447,17 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { 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 () => { + it('rejects subscribe before returning when no stream delivers data within the readiness timeout', 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}`))); + const outcome = expect(pending).rejects.toThrow( + new RegExp(`no evonode stream delivered data within ${ISLOCK_READINESS_TIMEOUT_MS}ms`) + ); + // Streams are open but silent: none is known to be listening. + await vi.advanceTimersByTimeAsync(ISLOCK_READINESS_TIMEOUT_MS); await outcome; + for (const stream of liveStreams()) expect(stream.cancel).toHaveBeenCalled(); + for (const node of nodeClients()) expect(node.disconnect).toHaveBeenCalled(); }); it('rejects subscribe itself, before returning, when every stream fails inside the readiness window', async () => { @@ -569,20 +571,19 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { expect(late.listenerCount('data')).toBe(0); }); - it('returns after the readiness cap when no stream emits data', async () => { + it('waits for the first stream data, however late within the readiness timeout, before returning', 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); + await vi.advanceTimersByTimeAsync(ISLOCK_READINESS_TIMEOUT_MS - 1); expect(returned).toBe(false); - await vi.advanceTimersByTimeAsync(1); + liveStreams()[2].emit('data', blockMessage); 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(); }); @@ -807,6 +808,8 @@ describe('DAPISubscriptionClient multi-node IS lock subscription', () => { expect(seedClients()).toHaveLength(1); const seed = seedClients()[0].options.dapiAddresses[0]; expect(seed.host).toMatch(/\.mainnet\.networks\.dash\.org$|pshenmic/); + // The health hint comes from the mainnet quorum service, never testnet's. + expect(fallbackMock).toHaveBeenCalledWith('mainnet'); expect(nodeClients()).toHaveLength(ISLOCK_CONCURRENT_NODES); liveStreams()[0].emit('data', lockMessage(TXID)); await expect(sub.wait()).resolves.toBeInstanceOf(Uint8Array); diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index 2bf40ea..bbffd4c 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -50,8 +50,14 @@ export const ISLOCK_CONCURRENT_NODES = 3; 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; +/** + * Longest subscribeForInstantSendLock waits for a first stream message. With + * no message by then it rejects (nothing has been broadcast yet): a stream + * that has not delivered anything is not known to be listening, and an IS + * lock arriving before it is would be lost. Streams replay the last 10 blocks + * first, so a live one answers within about a second. + */ +export const ISLOCK_READINESS_TIMEOUT_MS = 15000; const CLIENT_OPTIONS = { timeout: 30000, retries: 3 }; @@ -115,7 +121,7 @@ export class DAPISubscriptionClient { } /** - * Start syncing the testnet masternode list so the first IS lock + * Start reading the testnet or mainnet masternode list so the first IS lock * subscription doesn't wait for it. Never rejects; resolves at once on * networks with configured addresses. */ @@ -445,11 +451,11 @@ export class DAPISubscriptionClient { * 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. + * readiness means a stream has delivered a message (the server replays + * recent blocks first, usually within ~1 s). Return then; the remaining + * streams keep connecting. If every node attempt fails first, or no stream + * delivers anything within {@link ISLOCK_READINESS_TIMEOUT_MS}, this rejects + * instead of returning a handle, so nothing is broadcast without a listener. */ private async subscribeOnMultipleNodes( txid: string, @@ -470,7 +476,7 @@ export class DAPISubscriptionClient { let markReady!: () => void; const ready = new Promise((resolve) => { markReady = resolve; }); - const readyTimerId = setTimeout(markReady, ISLOCK_READINESS_CAP_MS); + let readyTimerId: ReturnType | undefined; // Set when every node attempt failed. Only read once, right after the // readiness wait, to fail before the caller broadcasts. let allFailed: Error | undefined; @@ -514,6 +520,14 @@ export class DAPISubscriptionClient { finish(() => reject(new Error(`Timeout waiting for InstantSend lock for ${txid} after ${timeoutMs}ms`))); }, timeoutMs); + readyTimerId = setTimeout(() => { + const silent = new Error( + `InstantSend lock subscription failed for ${txid}: no evonode stream delivered data within ${ISLOCK_READINESS_TIMEOUT_MS}ms` + ); + allFailed = silent; + finish(() => reject(silent)); + }, ISLOCK_READINESS_TIMEOUT_MS); + const openNode = (): void => { const address = nodes[attempts++]; if (!address) return; @@ -629,7 +643,7 @@ export class DAPISubscriptionClient { * 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; + * whatever masternode the dapiAddresses point at. Testnet and mainnet use the SDK; * see {@link getPlatformStatus}. * * @returns the chain-locked height, or `undefined` if the masternode diff --git a/src/api/evonode-discovery.test.ts b/src/api/evonode-discovery.test.ts index d7cdde3..0ff47f3 100644 --- a/src/api/evonode-discovery.test.ts +++ b/src/api/evonode-discovery.test.ts @@ -24,7 +24,9 @@ vi.mock('@dashevo/dashcore-lib', () => { import { EVONODE_LIST_MAX_AGE_MS, + EVONODE_LIST_STALE_LIMIT_MS, EvonodeDiscovery, + LIST_FETCH_TIMING, MASTERNODE_LIST_TIMEOUT_MS, MIN_HEALTHY_EVONODES, SEED_HEDGE_DELAY_MS, @@ -244,6 +246,22 @@ describe('fetchEvonodesFromSeeds', () => { expect(net.streams[0].cancel).toHaveBeenCalled(); }); + it('gives the bigger mainnet list longer: hedge at 8 s, give up at 25 s', async () => { + const net = fakeNetwork({}); + const mainnetSeeds = seedAddresses(['seed-1.mainnet.test', 'seed-2.mainnet.test', 'seed-3.mainnet.test', 'seed-4.mainnet.test']); + + const result = fetchEvonodesFromSeeds(mainnetSeeds, net.createClient, 'mainnet'); + const assertion = expect(result).rejects.toThrow(`timed out after ${LIST_FETCH_TIMING.mainnet.timeoutMs}ms`); + await vi.advanceTimersByTimeAsync(SEED_HEDGE_DELAY_MS); + expect(net.clients).toHaveLength(1); + await vi.advanceTimersByTimeAsync(LIST_FETCH_TIMING.mainnet.hedgeDelayMs - SEED_HEDGE_DELAY_MS); + expect(net.clients).toHaveLength(2); + await vi.advanceTimersByTimeAsync(MASTERNODE_LIST_TIMEOUT_MS); + expect(mainnetSeeds[0].port).toBe(443); + await vi.advanceTimersByTimeAsync(LIST_FETCH_TIMING.mainnet.timeoutMs); + await assertion; + }); + it('rejects without contacting a seed when the signal is already aborted or there are no seeds', async () => { const net = fakeNetwork({}); const controller = new AbortController(); @@ -322,9 +340,12 @@ describe('EvonodeDiscovery', () => { expect(hostsOf(await discovery.getNodes())).toEqual(['10.0.0.1']); expect(seedClients()).toHaveLength(1); + // Past the max age the old list is served at once while a new one is read. now = EVONODE_LIST_MAX_AGE_MS; - expect(hostsOf(await settle(discovery.getNodes()))).toEqual(['10.0.0.9']); + expect(hostsOf(await discovery.getNodes())).toEqual(['10.0.0.1']); expect(seedClients()).toHaveLength(2); + await vi.advanceTimersByTimeAsync(100); + expect(hostsOf(await discovery.getNodes())).toEqual(['10.0.0.9']); // The shared client follows the new list; the old one is closed. expect(discovery.sharedClient).not.toBe(firstShared); await vi.advanceTimersByTimeAsync(0); @@ -336,11 +357,22 @@ describe('EvonodeDiscovery', () => { const { discovery } = discover(behaviour); await settle(discovery.getNodes()); - now = EVONODE_LIST_MAX_AGE_MS; + // Even past the stale limit, where the read is awaited. + now = EVONODE_LIST_STALE_LIMIT_MS; behaviour['seed-1.test'] = { kind: 'reject' }; expect(hostsOf(await settle(discovery.getNodes()))).toEqual(['10.0.0.1']); }); + it(`awaits a new read once the list is older than ${EVONODE_LIST_STALE_LIMIT_MS / 60000} minutes`, async () => { + const behaviour: Record = { 'seed-1.test': { kind: 'list', hosts: ['10.0.0.1'] } }; + const { discovery } = discover(behaviour); + await settle(discovery.getNodes()); + + now = EVONODE_LIST_STALE_LIMIT_MS; + behaviour['seed-1.test'] = { kind: 'list', hosts: ['10.0.0.9'] }; + expect(hostsOf(await settle(discovery.getNodes()))).toEqual(['10.0.0.9']); + }); + it('shares one read between concurrent callers', async () => { const { discovery, seedClients } = discover({ 'seed-1.test': { kind: 'list', hosts: ['10.0.0.1'] } }); @@ -366,7 +398,7 @@ describe('EvonodeDiscovery', () => { expect(hostsOf(await discovery.getNodes())).toEqual(['10.0.0.9']); expect(seedClients()).toHaveLength(1); - now = EVONODE_LIST_MAX_AGE_MS; + now = EVONODE_LIST_STALE_LIMIT_MS; behaviour['seed-1.test'] = { kind: 'list', hosts: ['10.0.0.1'] }; expect(hostsOf(await settle(discovery.getNodes()))).toEqual(['10.0.0.1']); }); diff --git a/src/api/evonode-discovery.ts b/src/api/evonode-discovery.ts index bb9d7b6..0c532bd 100644 --- a/src/api/evonode-discovery.ts +++ b/src/api/evonode-discovery.ts @@ -35,8 +35,10 @@ export const LIST_FETCH_TIMING: Record = { testnet: { timeoutMs: MASTERNODE_LIST_TIMEOUT_MS, hedgeDelayMs: SEED_HEDGE_DELAY_MS }, mainnet: { timeoutMs: 25000, hedgeDelayMs: 8000 }, }; -/** A list older than this is fetched again before use. */ +/** A list older than this is read again (in the background while it is still usable). */ export const EVONODE_LIST_MAX_AGE_MS = 10 * 60_000; +/** A list older than this is not used while a new one is read; the read is awaited. */ +export const EVONODE_LIST_STALE_LIMIT_MS = 60 * 60_000; /** * Fewest evonodes that both the masternode list and the quorum service's * health check vouch for before discovery narrows to them (one per IS lock @@ -286,11 +288,26 @@ export class EvonodeDiscovery { if (shared) disconnectQuietly(shared.client); } - /** Endpoints of a fresh enough list, read again when stale; [] when none was ever found. */ + /** + * Endpoints of the current list; [] when none was ever found. A list past + * its max age is still served (and read again in the background) up to the + * stale limit, so a subscription after a long deposit wait doesn't wait for + * a full read before broadcasting. + */ private readList(): Promise { - if (this.list && this.now() - this.list.fetchedAt < EVONODE_LIST_MAX_AGE_MS) { + const age = this.list ? this.now() - this.list.fetchedAt : Infinity; + if (this.list && age < EVONODE_LIST_MAX_AGE_MS) { + return Promise.resolve(this.list.endpoints); + } + const read = this.startRead(); + if (this.list && age < EVONODE_LIST_STALE_LIMIT_MS) { + read.catch(() => {}); return Promise.resolve(this.list.endpoints); } + return read; + } + + private startRead(): Promise { if (!this.pending) { const controller = new AbortController(); const pending = { diff --git a/src/api/evonodes.test.ts b/src/api/evonodes.test.ts index aede37d..5093f2f 100644 --- a/src/api/evonodes.test.ts +++ b/src/api/evonodes.test.ts @@ -69,11 +69,13 @@ describe('parseEvonodeAddresses', () => { const result = parseEvonodeAddresses( payload( node('68.67.122.3', { addresses: { core_p2p: ['68.67.122.3:19999'], platform_https: ['evo3.example.org:443'] } }), - node('68.67.122.4', { addresses: undefined }) + node('68.67.122.4', { addresses: undefined }), + // Without platform_https, the record's platformHTTPPort (mainnet: 443). + node('89.35.131.219', { addresses: undefined, address: '89.35.131.219:9999', platformHTTPPort: 443 }) ) ); - expect(result).toEqual(['https://evo3.example.org:443', 'https://68.67.122.4:1443']); + expect(result).toEqual(['https://evo3.example.org:443', 'https://68.67.122.4:1443', 'https://89.35.131.219:443']); }); it.each([undefined, null, 'x', {}, { data: {} }, { success: false }])( diff --git a/src/api/evonodes.ts b/src/api/evonodes.ts index 9c768e6..c212bb5 100644 --- a/src/api/evonodes.ts +++ b/src/api/evonodes.ts @@ -50,9 +50,9 @@ export function parseEvonodeAddresses(payload: unknown): string[] { const endpoints = new Set(); for (const node of data) { if (!node || typeof node !== 'object') continue; - const { address, addresses, status, versionCheck } = node as Record; + const { address, addresses, platformHTTPPort, status, versionCheck } = node as Record; if (status !== 'ENABLED' || versionCheck !== 'success') continue; - const endpoint = platformEndpoint(addresses) ?? coreHostEndpoint(address); + const endpoint = platformEndpoint(addresses) ?? coreHostEndpoint(address, platformHTTPPort); if (endpoint) endpoints.add(endpoint); } return [...endpoints]; @@ -68,9 +68,14 @@ function platformEndpoint(addresses: unknown): string | undefined { return toDapiEndpoint(first.slice(0, separator), Number(first.slice(separator + 1))); } -/** Older records: `address` is the Core P2P endpoint (host:19999); only its host is reused, on port 1443. */ -function coreHostEndpoint(address: unknown): string | undefined { - return typeof address === 'string' ? toDapiEndpoint(address.replace(/:\d+$/, '')) : undefined; +/** + * Older records: `address` is the Core P2P endpoint (host:19999); its host is + * reused with the record's platformHTTPPort (1443 when absent). + */ +function coreHostEndpoint(address: unknown, platformHTTPPort: unknown): string | undefined { + if (typeof address !== 'string') return undefined; + const port = typeof platformHTTPPort === 'number' ? platformHTTPPort : DAPI_HTTPS_PORT; + return toDapiEndpoint(address.replace(/:\d+$/, ''), port); } /** diff --git a/src/api/islock.test.ts b/src/api/islock.test.ts index 67b0fbb..770bf23 100644 --- a/src/api/islock.test.ts +++ b/src/api/islock.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; const mocks = vi.hoisted(() => ({ waitForInstantSendLock: vi.fn(), @@ -33,7 +33,7 @@ vi.mock('./dapi-subscription.js', () => ({ })), })); -import { IslockService } from './islock.js'; +import { IslockService, PRE_BROADCAST_RETRY_DELAYS_MS } from './islock.js'; describe('IslockService', () => { beforeEach(() => { @@ -85,19 +85,6 @@ describe('IslockService', () => { await expect(handle.wait()).resolves.toBe(bytes); }); - it('propagates a failed subscription so the caller stops before broadcasting', async () => { - mocks.subscribeForInstantSendLock.mockRejectedValue( - new Error('InstantSend lock subscription failed for txid: 3 nodes tried, last error: boom') - ); - const service = new IslockService({ network: 'testnet', dapiAddresses: ['https://127.0.0.1:1443'] }); - - await expect( - service.subscribeForInstantSendLock('txid', new Uint8Array([4]), { txid: 'prevout', vout: 0 }) - ).rejects.toThrow(/3 nodes tried/); - // No tripwire poller is left running for a subscription that never existed. - expect(mocks.getTransactionLockStatus).not.toHaveBeenCalled(); - }); - it('keeps the pre-broadcast DAPI subscription path for devnets without RPC', async () => { const bytes = new Uint8Array([9, 8, 7]); const subHandle = { wait: vi.fn().mockResolvedValue(bytes) }; @@ -139,4 +126,70 @@ describe('IslockService', () => { await new IslockService({ network: 'devnet-moutai', rpcUrl: 'https://rpc.devnet.test' }).warmEvonodeDiscovery(); expect(mocks.warmEvonodeDiscovery).toHaveBeenCalledTimes(2); }); + + describe('before broadcast', () => { + const subscribe = (service: IslockService) => + service.subscribeForInstantSendLock('txid', new Uint8Array([4]), { txid: 'prevout', vout: 0 }); + + let warn: { mockRestore: () => void }; + beforeEach(() => { + vi.useFakeTimers(); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => { + vi.useRealTimers(); + warn.mockRestore(); + }); + + it('retries a failed subscription, since nothing has been broadcast yet', async () => { + const bytes = new Uint8Array([9]); + mocks.subscribeForInstantSendLock + .mockRejectedValueOnce(new Error('No mainnet evonodes found')) + .mockRejectedValueOnce(new Error('3 nodes tried')) + .mockResolvedValueOnce({ wait: vi.fn().mockResolvedValue(bytes) }); + const progress: string[] = []; + const service = new IslockService({ network: 'mainnet' }); + + const pending = service.subscribeForInstantSendLock( + 'txid', new Uint8Array([4]), { txid: 'prevout', vout: 0 }, 60000, undefined, (m) => progress.push(m) + ); + await vi.advanceTimersByTimeAsync(PRE_BROADCAST_RETRY_DELAYS_MS[0] + PRE_BROADCAST_RETRY_DELAYS_MS[1]); + const handle = await pending; + + expect(mocks.subscribeForInstantSendLock).toHaveBeenCalledTimes(3); + expect(progress).toContain('Could not reach Dash evonodes, retrying...'); + await expect(handle.wait()).resolves.toBe(bytes); + }); + + it('says the deposit is unspent when every attempt fails', async () => { + mocks.subscribeForInstantSendLock.mockRejectedValue(new Error('No mainnet evonodes found')); + const pending = subscribe(new IslockService({ network: 'mainnet' })); + const outcome = expect(pending).rejects.toThrow(/No mainnet evonodes found\. Nothing was broadcast, so your deposit has not been spent/); + + await vi.advanceTimersByTimeAsync(PRE_BROADCAST_RETRY_DELAYS_MS.reduce((a, b) => a + b, 0)); + await outcome; + expect(mocks.subscribeForInstantSendLock).toHaveBeenCalledTimes(PRE_BROADCAST_RETRY_DELAYS_MS.length + 1); + // No tripwire poller is left running for a subscription that never existed. + expect(mocks.getTransactionLockStatus).not.toHaveBeenCalled(); + }); + + it('does not retry an aborted subscription', async () => { + mocks.subscribeForInstantSendLock.mockRejectedValue(new Error('InstantSend lock subscription aborted for txid')); + + await expect(subscribe(new IslockService({ network: 'testnet' }))).rejects.toThrow(/aborted/); + expect(mocks.subscribeForInstantSendLock).toHaveBeenCalledOnce(); + }); + + it('stops waiting to retry when disconnected', async () => { + mocks.subscribeForInstantSendLock.mockRejectedValue(new Error('3 nodes tried')); + const service = new IslockService({ network: 'testnet' }); + const pending = subscribe(service); + const outcome = expect(pending).rejects.toThrow('InstantSend lock subscription aborted for txid'); + + await vi.advanceTimersByTimeAsync(100); + await service.disconnect(); + await outcome; + expect(mocks.subscribeForInstantSendLock).toHaveBeenCalledOnce(); + }); + }); }); diff --git a/src/api/islock.ts b/src/api/islock.ts index 1d1c4e3..493b5da 100644 --- a/src/api/islock.ts +++ b/src/api/islock.ts @@ -10,10 +10,15 @@ export interface IslockServiceConfig { dapiAddresses?: string[]; } +/** Subscription attempts before broadcast, and the waits between them. */ +export const PRE_BROADCAST_RETRY_DELAYS_MS = [5000, 15000]; + export class IslockService { private readonly jsonRpcClient: DAPIClient; private readonly subscriptionClient: DAPISubscriptionClient; private readonly hasJsonRpc: boolean; + // Aborted by disconnect(), so a pre-broadcast retry wait stops with it. + private readonly lifetime = new AbortController(); constructor(config: IslockServiceConfig) { const jsonRpcConfig: DAPIConfig = { network: config.network, rpcUrl: config.rpcUrl }; @@ -84,13 +89,7 @@ export class IslockService { ): Promise<{ wait: () => Promise }> { if (!this.hasJsonRpc) { // DAPI subscription only — establish the stream, then return. - const sub = await this.subscriptionClient.subscribeForInstantSendLock( - txid, - publicKey, - utxo, - timeoutMs, - onProgress - ); + const sub = await this.subscribeBeforeBroadcast(txid, publicKey, utxo, timeoutMs, onProgress); const tripwireController = new AbortController(); this.startLockStatusTripwire(txid, tripwireController.signal); return { @@ -181,7 +180,7 @@ export class IslockService { /** * Platform status for background polling: `undefined` means "not read yet" - * (testnet, before any funding flow started connecting the EvoSDK, or while + * (testnet and mainnet, before a 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. */ @@ -206,7 +205,7 @@ export class IslockService { } /** - * Start finding testnet evonodes for the IS lock subscription. Never + * Start finding testnet or mainnet evonodes for the IS lock subscription. Never * rejects; a no-op on networks with configured addresses or JSON-RPC. */ warmEvonodeDiscovery(): Promise { @@ -214,7 +213,46 @@ export class IslockService { return this.subscriptionClient.warmEvonodeDiscovery(); } + /** + * Open the DAPI subscription, retrying while nothing has been broadcast: + * evonodes can be briefly unreachable, and failing here would leave the + * user with an unspent deposit and no in-app way back to it. The final + * failure says so. + */ + private async subscribeBeforeBroadcast( + txid: string, + publicKey: Uint8Array, + utxo: { txid: string; vout: number }, + timeoutMs: number, + onProgress?: (message: string) => void + ): Promise<{ wait: () => Promise }> { + for (let attempt = 0; ; attempt++) { + try { + return await this.subscriptionClient.subscribeForInstantSendLock( + txid, publicKey, utxo, timeoutMs, onProgress + ); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (this.lifetime.signal.aborted || /aborted/i.test(message)) throw error; + const delay = PRE_BROADCAST_RETRY_DELAYS_MS[attempt]; + if (delay === undefined) { + throw new Error( + `${message}. Nothing was broadcast, so your deposit has not been spent; ` + + 'it can be recovered with the key backup that was downloaded.' + ); + } + console.warn(`[islock] subscription failed before broadcast, retrying in ${delay} ms:`, error); + onProgress?.('Could not reach Dash evonodes, retrying...'); + await abortableSleep(delay, this.lifetime.signal); + if (this.lifetime.signal.aborted) { + throw new Error(`InstantSend lock subscription aborted for ${txid}`); + } + } + } + } + async disconnect(): Promise { + this.lifetime.abort(); await this.subscriptionClient.disconnect(); } } diff --git a/src/main.ts b/src/main.ts index 1465ae1..c0b02ea 100644 --- a/src/main.ts +++ b/src/main.ts @@ -295,8 +295,8 @@ async function initClients(network: string): Promise { // 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; - // Testnet has no dapiAddresses: the service discovers its evonodes when a - // funding flow starts (see warmFundingConnect). + // Testnet and mainnet have no dapiAddresses: the service discovers their + // evonodes when a funding flow starts (see warmFundingConnect). islockService = new IslockService({ network, rpcUrl: config.rpcUrl, @@ -362,10 +362,10 @@ function downloadFundingKeyBackup(backupState: BridgeState): void { } /** - * Testnet: connect the SDK (shared with any connect in flight) and poll the - * health indicator as soon as it settles, and sync the masternode list the IS - * lock subscription picks its evonodes from. Other networks: nothing. - * Never rejects. + * Testnet and mainnet: connect the SDK (shared with any connect in flight) + * and poll the health indicator as soon as it settles, and read the + * masternode list the IS lock subscription picks its evonodes from. Devnets: + * nothing. Never rejects. */ function warmFundingConnect(network: string): Promise { const sdk = warmPlatformSdkForFunding(network).then((attempted) => { @@ -374,7 +374,7 @@ function warmFundingConnect(network: string): Promise { return Promise.all([sdk, islockService?.warmEvonodeDiscovery()]).then(() => {}); } -/** How long a funding flow waits for the testnet SDK connect before showing its deposit address anyway. */ +/** How long a funding flow waits for the SDK connect (testnet, mainnet) before showing its deposit address anyway. */ const FUNDING_SDK_CONNECT_WAIT_MS = 5000; /** @@ -384,7 +384,7 @@ const FUNDING_SDK_CONNECT_WAIT_MS = 5000; * when they still fail (or stall for 5 min) this throws a ChunkLoadError * while nothing is at risk (error screen with Reload). * - * Testnet also starts connecting the SDK, so the health indicator reads + * Testnet and mainnet also start connecting the SDK, 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). The flow waits for that * connect at most FUNDING_SDK_CONNECT_WAIT_MS; it continues in the background @@ -3480,8 +3480,8 @@ function cancelChainlockFallback(): void { /** * Begin the chainlock fallback flow: poll Insight for the asset-lock tx's - * confirming block, poll for the chain-locked tip (JSON-RPC on mainnet, - * Platform status elsewhere), and once `coreChainLockedHeight >= blockHeight` build a + * confirming block, poll for the chain-locked tip (Platform status; JSON-RPC + * only for a devnet with its own rpcUrl), and once `coreChainLockedHeight >= blockHeight` build a * chain asset lock proof and resubmit the original Platform operation. */ async function startChainlockFallback(): Promise { diff --git a/src/platform/status.ts b/src/platform/status.ts index 2efff6d..70bb068 100644 --- a/src/platform/status.ts +++ b/src/platform/status.ts @@ -49,9 +49,9 @@ export async function fetchPlatformStatusIfSdkReady( /** * 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 + * Used instead of `@dashevo/dapi-client`'s `platform.getStatus()` on testnet + * and mainnet: 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. From c4fdb2a4c5a0befc6879420a91f633fc12fbe726 Mon Sep 17 00:00:00 2001 From: pasta Date: Mon, 2 Nov 2026 14:30:48 -0600 Subject: [PATCH 3/3] test: case-insensitive digitalcash guard; mainnet lists are parsed as mainnet Co-Authored-By: Claude Opus 5.5 --- scripts/check-build-artifacts.mjs | 2 +- src/api/evonode-discovery.test.ts | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/scripts/check-build-artifacts.mjs b/scripts/check-build-artifacts.mjs index f3482be..0c3da73 100644 --- a/scripts/check-build-artifacts.mjs +++ b/scripts/check-build-artifacts.mjs @@ -137,7 +137,7 @@ function builtFiles(dir) { }); } const digitalcashFiles = builtFiles(distDir.pathname).filter((path) => - /\.(?:js|mjs|html|json|css)$/.test(path) && readFileSync(path, 'utf8').includes('digitalcash') + /\.(?:js|mjs|html|json|css)$/.test(path) && readFileSync(path, 'utf8').toLowerCase().includes('digitalcash') ); if (digitalcashFiles.length > 0) { fail(`build references digitalcash: ${digitalcashFiles.join(', ')}`); diff --git a/src/api/evonode-discovery.test.ts b/src/api/evonode-discovery.test.ts index 0ff47f3..a291bfa 100644 --- a/src/api/evonode-discovery.test.ts +++ b/src/api/evonode-discovery.test.ts @@ -5,10 +5,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; // A "masternode list" here is CBOR of { hosts: [...] }; the fake parser turns // each host into a valid evonode on port 1443 ('bad' hosts make it throw). +// Networks the list parser was given, so tests can check mainnet lists are parsed as mainnet. +const parsedNetworks = vi.hoisted(() => [] as string[]); + vi.mock('@dashevo/dashcore-lib', () => { class SimplifiedMNListDiff { hosts: string[]; constructor(obj: { hosts: string[] }, public network: string) { + parsedNetworks.push(network); if (obj.hosts.includes('bad')) throw new Error('Failed to parse payload'); this.hosts = obj.hosts; } @@ -246,6 +250,17 @@ describe('fetchEvonodesFromSeeds', () => { expect(net.streams[0].cancel).toHaveBeenCalled(); }); + it('parses a mainnet list as mainnet', async () => { + parsedNetworks.length = 0; + const net = fakeNetwork({ 'seed-1.mainnet.test': { kind: 'list', hosts: ['10.0.0.1'] } }); + + const result = fetchEvonodesFromSeeds(seedAddresses(['seed-1.mainnet.test']), net.createClient, 'mainnet'); + await vi.advanceTimersByTimeAsync(100); + + await expect(result).resolves.toEqual([endpoint('10.0.0.1')]); + expect(parsedNetworks).toEqual(['mainnet']); + }); + it('gives the bigger mainnet list longer: hedge at 8 s, give up at 25 s', async () => { const net = fakeNetwork({}); const mainnetSeeds = seedAddresses(['seed-1.mainnet.test', 'seed-2.mainnet.test', 'seed-3.mainnet.test', 'seed-4.mainnet.test']);