diff --git a/README.md b/README.md index 0146d0a..3759726 100644 --- a/README.md +++ b/README.md @@ -92,3 +92,15 @@ This project automatically deploys to GitHub Pages on push to `main` via GitHub ## License MIT + +## Service resilience + +Mainnet and testnet work without Digital Cash RPC. After broadcasting an asset +lock, the bridge waits for mining and a Platform-observed chain lock, then +continues with a chain proof. This can take several minutes. The wait can be +cancelled and resumed without another broadcast. Devnets retain their existing +InstantSend subscription or explicitly configured RPC, with chain recovery if +the lock cannot be retrieved after broadcast. + +See [the dependency review](docs/rpc-dependency-review.md) for the deployed +baseline, remaining bridge dependencies, and outage-test coverage. diff --git a/docs/rpc-dependency-review.md b/docs/rpc-dependency-review.md new file mode 100644 index 0000000..55105af --- /dev/null +++ b/docs/rpc-dependency-review.md @@ -0,0 +1,104 @@ +# RPC dependency review — 2026-09-17 + +## Deployed baseline + +The review and implementation start from `dashpay/dash-bridge` commit +`ab04c2f3316f573131673bf66fd682cf3ecc22a0`, the latest `origin/main` and latest +successful GitHub Pages deployment at the time of review. + +- [Successful deployment run](https://github.com/dashpay/dash-bridge/actions/runs/33567685502), completed September 1, 2026, 22:45 UTC. +- GitHub Pages config names `bridge.thepasta.org`; the public host resolves to + Cloudflare, and its response has GitHub Pages origin headers. +- The live HTML references `/assets/index-CoHZD5JG.js`, which contains both RPC + hostnames and the deployed network configuration. Its Last-Modified header is + September 1, 2026, 22:44:59 GMT. +- Both RPC hosts returned HTTP 200 to `getbestchainlock` and allowed the bridge + origin in CORS preflight and POST responses during this review. The final + implementation removes both hosts from the built-in mainnet/testnet config; + the public networks use chain proofs directly. This establishes availability from the review environment, not universal + reachability. + +`trpc.digitalcash.dev` is testnet; `rpc.digitalcash.dev` is mainnet. They are +**not interchangeable fallbacks**. They also share an operator/domain failure +boundary. The bridge uses HTTPS, not WebSockets. Mainnet/testnet no longer +configure a Digital Cash RPC URL. + +## What the bridge uses RPC for + +| Operation | Deployed behavior | Behavior with this change | +| --- | --- | --- | +| Get an InstantSend lock (`getislocks`) | Single RPC provider; unbounded individual fetches could outlive the nominal 60-second poll timeout | No built-in provider. Explicit custom URLs have an 8-second request/body deadline and a 60-second overall deadline; three consecutive failures yield to chain recovery | +| Create identity, top up, send Core funds to a Platform address, recheck a deposit | Need an InstantSend proof, otherwise show an error requiring a manual recovery choice | Use a chain proof for the same broadcast asset-lock transaction | +| Create an identity while registering DPNS or a contract | Shares the identity-creation funding flow | Shares the same automatic recovery | +| Network-health indicator | Mainnet/testnet read `getbestchainlock` from the single RPC host, without observing Platform block age | Read Platform status through EvoSDK; only explicitly configured RPC URLs can act as a degraded health backup | +| Chain-proof recovery | Try RPC first; then legacy dapi-client seed/SML discovery, which had browser certificate/CORS failures | Read Platform's chain-lock height through EvoSDK on public networks; retain explicit DAPI addresses on devnets | +| Existing-identity DPNS, key management, username transfers, withdrawals | Platform SDK operations; no direct RPC requirement for their operation | Unchanged operation dependency; header health no longer normally calls RPC | + +The deployed DAPI InstantSend stream is used only for devnets without an RPC +URL. It must be open before broadcast and does not replay historical locks. +Public networks use chain-proof recovery when no optional RPC URL is supplied; +legacy browser discovery is never required for recovery. + +## Recovery guarantees and limits + +Recovery polls the transaction and Platform in parallel. It submits only after +Insight reports a positive, integral confirming block height and Platform +reports a chain-locked height at least that high. Confirmation count alone is +insufficient. Each poll uses fresh transaction information, avoiding reuse of +an earlier block height after a reorg or failed read. Platform still validates +the submitted proof and asset lock. + +Cancellation preserves the transaction and keys in the existing in-memory +state and allows the same chain-lock wait to resume. Recovery neither builds +nor broadcasts a second asset lock. Transaction data and keys are not persisted +by this change; closing/reloading the page still requires the existing key +backup/recovery process. + +Recovery can take minutes while the transaction is mined and Platform observes +its chain lock. It cannot complete if Platform consensus stalls or the remaining +required services are unreachable. The wait is cancellable. Individual public +Platform status reads have a 20-second wall-clock guard; SDK requests retain +normal node rotation/retry behavior. Cancellation releases the recovery wait +immediately. It does not cancel an underlying WASM request, but a late result +cannot submit a proof after cancellation. + +## Remaining bridge dependencies + +| Dependency | Purpose | Existing fallback / limitation | +| --- | --- | --- | +| Insight (`insight.testnet.networks.dash.org`, `insight.dash.org`, configured devnet Insight) | Deposit UTXOs, transaction broadcast, confirming block height, Core health | Retries on the same provider; no independent explorer failover. Blocking Insight still prevents the relevant funding/recovery steps. | +| `@dashevo/evo-sdk` trusted quorum service (`quorums..networks.dash.org`) | Quorum context and Platform node discovery on public/trusted networks | SDK caches context and rotates discovered Platform nodes; no independently configured quorum-context provider for mainnet/testnet. A cold connection needs this service. | +| Platform evonodes | Status and identity/credit/DPNS/contract operations | SDK retries/rotates nodes; a network-wide outage has no application substitute. | +| Configured DAPI nodes on devnets | Pre-broadcast InstantSend stream and Platform status | Multiple explicit addresses; stream failure can use chain recovery after broadcast. Subscription setup failure still stops before broadcast. | +| `faucet.thepasta.org` and CAPTCHA services | Optional testnet funding button | Users can fund the deposit address themselves. This is not required to bridge their own funds. | +| Platform Explorer links | External transaction/identity viewing | Display/navigation only; not part of proof creation or submission. | +| Cloudflare + GitHub Pages | Deliver the app | No alternate app origin is configured in this repository. | + +Devnet subscription setup still relies on the existing DAPI timeouts/retries. +Caller cancellation while obtaining the initial height or opening the stream +is a separate follow-up; public-network funding does not use this setup path. + +## Validation + +- Production TypeScript/Vite build and build-artifact smoke check passed; + the artifact check rejects any bundled `digitalcash.dev` endpoint. +- Unit coverage for blocked/invalid RPC responses, matching lock parsing, + polling deadlines, request cancellation, mining/chain-lock readiness, + reorg/read-failure handling, and late responses after cancellation. +- Deterministic Chromium outage tests execute the real signing and bridge + orchestration with every external request intercepted. They verify one + broadcast, no premature submission, a chain proof for the same transaction, + and cancellation/resume on both mainnet and testnet, across create, top-up, + send-to-address, and deposit recheck. Every test blocks the domain with a DNS + error and asserts zero requests to it. Broadcast and Platform submission are fixtures; + these tests do not spend funds. +- Regression cases verify prompt cancellation with a pending Platform read and + recovery using the locally calculated transaction ID when Insight returns a + mismatched ID after accepting a broadcast. +- A separate live, read-only Chromium check blocked both Digital Cash RPC + hosts and exercised the new `IslockService`/`fetchNetworkStatus` code. Testnet + reported Core 1,555,588 / Platform chain-lock 1,555,586; mainnet reported + 2,540,454 / 2,540,454. Both health results were healthy and no RPC request was + attempted. These heights are a dated observation, not a future health claim. +- No funded live end-to-end transaction or production deployment was performed + during this review. diff --git a/e2e/rpc-outage.spec.ts b/e2e/rpc-outage.spec.ts new file mode 100644 index 0000000..c28a90d --- /dev/null +++ b/e2e/rpc-outage.spec.ts @@ -0,0 +1,104 @@ +import { createHash } from 'node:crypto'; +import { bech32m } from '@scure/base'; +import { expect, test } from '@playwright/test'; +import { E2E_MOCK_IDENTITY_ID } from '../src/e2e-mock-constants'; + +// Exercise real signing/orchestration, intercepting every external request. +// No fixture can fund, broadcast, or submit a real transaction. +for (const network of ['mainnet', 'testnet']) { + for (const flow of ['create', 'topup', 'send', 'recheck', 'cancel', 'mismatch'] as const) { + test(`${network} ${flow} works without Digital Cash RPC`, async ({ page }) => { + test.setTimeout(60000); + let txid = ''; + let broadcasts = 0; + let rpcRequests = 0; + let depositReady = flow !== 'recheck'; + const json = (value: unknown) => ({ contentType: 'application/json', body: JSON.stringify(value) }); + await page.route('**/*', async (route) => { + const url = new URL(route.request().url()); + if (url.hostname === '127.0.0.1' || url.hostname === 'localhost') { + if (url.pathname === '/src/platform/status.ts') { + await route.fulfill({ contentType: 'application/javascript', body: ` + export async function fetchPlatformStatus() { + return { coreChainLockedHeight: window.__testChainHeight ?? 99, + latestBlockHeight: 10, latestBlockTimeMs: Date.now() }; + } + ` }); + } else if (url.pathname === '/src/platform/index.ts') { + await route.fulfill({ contentType: 'application/javascript', body: ` + const record = (operation, proof) => (window.__testProofs ??= []).push({ operation, proof }); + export async function registerIdentity(proof) { + record('create', proof); + return { identityId: '${E2E_MOCK_IDENTITY_ID}', balance: 1, revision: 0 }; + } + export async function topUpIdentity(id, proof) { record('topup', proof); } + export async function sendToPlatformAddress(address, proof) { record('send', proof); } + ` }); + } else await route.continue(); + return; + } + if (url.hostname === 'digitalcash.dev' || url.hostname.endsWith('.digitalcash.dev')) { + rpcRequests++; + await route.abort('namenotresolved'); + } else if (['insight.testnet.networks.dash.org', 'insight.dash.org'].includes(url.hostname)) { + if (url.pathname.endsWith('/utxo')) { + await route.fulfill(json(depositReady ? [{ txid: 'a'.repeat(64), vout: 0, satoshis: 300000, + scriptPubKey: `76a914${'11'.repeat(20)}88ac`, confirmations: 1 }] : [])); + } else if (url.pathname.endsWith('/tx/send')) { + broadcasts++; + const raw = Buffer.from(route.request().postDataJSON().rawtx, 'hex'); + const hash = createHash('sha256').update(createHash('sha256').update(raw).digest()).digest(); + txid = hash.reverse().toString('hex'); + await route.fulfill(json({ txid: flow === 'mismatch' ? 'b'.repeat(64) : txid })); + } else if (url.pathname.includes('/tx/')) { + await route.fulfill(json({ txid, blockheight: 100, confirmations: 1 })); + } else await route.fulfill(json({ info: { blocks: 100 } })); + } else await route.abort(); + }); + if (flow === 'recheck') await page.clock.install(); + await page.goto(`/?network=${network}`); + if (flow === 'topup') { + await page.click('#mode-manage-btn'); + await page.click('#manage-action-topup-btn'); + await page.fill('#identity-id-input', E2E_MOCK_IDENTITY_ID); + await page.click('#continue-topup-btn'); + } else if (flow === 'send') { + await page.click('#mode-send-to-address-btn'); + const address = bech32m.encode(network === 'mainnet' ? 'dash' : 'tdash', bech32m.toWords(new Uint8Array(21).fill(1))); + await page.fill('#recipient-address-input', address); + await page.click('#continue-send-to-address-btn'); + } else { + await page.click('#mode-create-btn'); + await page.click('#continue-btn'); + } + if (flow === 'recheck') { + await expect(page.locator('.deposit-headline')).toBeVisible(); + await page.clock.fastForward(125000); + await expect(page.locator('#recheck-deposit-btn')).toBeVisible(); + depositReady = true; + await page.click('#recheck-deposit-btn'); + } + if (flow === 'mismatch') { + await expect(page.getByText('Broadcast returned a different transaction ID', { exact: true })).toBeVisible({ timeout: 40000 }); + await expect(page.locator('.error-code-badge')).toHaveText('ERR-1005'); + await page.click('#chainlock-fallback-btn'); + } + await expect(page.getByRole('heading', { name: 'Waiting for chain lock', exact: true })).toBeVisible({ timeout: 40000 }); + expect(broadcasts).toBe(1); + expect(await page.evaluate(() => (window as any).__testProofs)).toBeUndefined(); + if (flow === 'cancel') { + await page.click('#chainlock-cancel-btn'); + await expect(page.locator('.error-code-badge')).toHaveText('ERR-1014'); + await page.click('#chainlock-fallback-btn'); + } + await page.evaluate(() => { (window as any).__testChainHeight = 100; }); + const completion = flow === 'topup' ? 'Top-up complete!' : flow === 'send' ? 'Send complete!' : 'Save your keys'; + await expect(page.getByText(completion, { exact: true })).toBeVisible({ timeout: 15000 }); + const proofs = await page.evaluate(() => (window as any).__testProofs); + const operation = flow === 'send' || flow === 'topup' ? flow : 'create'; + expect(proofs).toEqual([{ operation, proof: { type: 'chain', txid, vout: 0, coreChainLockedHeight: 100 } }]); + expect(broadcasts).toBe(1); + expect(rpcRequests).toBe(0); + }); + } +} diff --git a/package.json b/package.json index 83c8fde..74ec719 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "test": "vitest run", "test:watch": "vitest", "test:build-artifacts": "npm run build && node scripts/check-build-artifacts.mjs", - "test:e2e": "playwright test e2e/deterministic.spec.ts", + "test:e2e": "playwright test e2e/deterministic.spec.ts e2e/rpc-outage.spec.ts", "test:e2e:headed": "playwright test e2e/deterministic.spec.ts --headed", "test:e2e:live": "PW_E2E_LIVE=1 playwright test e2e/live.testnet.spec.ts", "test:e2e:live:transfer": "PW_LIVE_XFER=1 playwright test e2e/live.transfer.spec.ts", diff --git a/scripts/check-build-artifacts.mjs b/scripts/check-build-artifacts.mjs index 98fada8..5c9570d 100644 --- a/scripts/check-build-artifacts.mjs +++ b/scripts/check-build-artifacts.mjs @@ -1,4 +1,4 @@ -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync, readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; // Guard the Lighthouse fix: the initial page must not preload or statically @@ -62,4 +62,13 @@ if (staticImportPattern.test(entryChunk)) { fail('entry chunk statically imports a heavy Dash chunk'); } +// The production bundle must not silently reintroduce a Digital Cash endpoint +// through either application config or a transitive dependency. +for (const name of readdirSync(new URL('assets/', distDir))) { + if (!name.endsWith('.js')) continue; + if (readBuiltFile(new URL(`assets/${name}`, distDir)).includes('digitalcash.dev')) { + fail(`Digital Cash endpoint found in ${name}`); + } +} + console.log('Build artifact smoke check passed'); diff --git a/src/api/chainlock.test.ts b/src/api/chainlock.test.ts new file mode 100644 index 0000000..c1e0eea --- /dev/null +++ b/src/api/chainlock.test.ts @@ -0,0 +1,80 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { waitForChainLock } from './chainlock.js'; +import type { InsightClient } from './insight.js'; +import type { IslockService } from './islock.js'; + +const getTransaction = vi.fn(); +const getCoreChainLockedHeight = vi.fn(); +const insight = { getTransaction } as unknown as InsightClient; +const islock = { getCoreChainLockedHeight } as unknown as IslockService; + +beforeEach(() => { vi.useFakeTimers(); vi.resetAllMocks(); }); +afterEach(() => { vi.useRealTimers(); }); + +describe('chain proof readiness', () => { + it('waits for mining and Platform catching up, without an RPC provider', async () => { + getTransaction.mockResolvedValueOnce({ confirmations: 0 }).mockResolvedValue({ blockheight: 100 }); + getCoreChainLockedHeight.mockResolvedValueOnce(99).mockResolvedValueOnce(99).mockResolvedValue(100); + const progress = vi.fn(); + const ready = vi.fn(); + const result = waitForChainLock('tx', insight, islock, new AbortController().signal, progress).then(ready); + await vi.advanceTimersByTimeAsync(5000); + expect(ready).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(5000); + await result; + expect(ready).toHaveBeenCalledWith(100); + expect(progress).toHaveBeenLastCalledWith({ blockHeight: 100, chainLockedHeight: 100 }); + }); + + it('does not reuse a previous transaction height after a reorg or failed read', async () => { + getTransaction.mockResolvedValueOnce({ blockheight: 100 }).mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce({ blockheight: 102 }); + getCoreChainLockedHeight.mockResolvedValueOnce(99).mockResolvedValueOnce(100).mockResolvedValue(102); + const ready = vi.fn(); + const result = waitForChainLock('tx', insight, islock, new AbortController().signal, vi.fn()).then(ready); + await vi.advanceTimersByTimeAsync(5000); + expect(ready).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(5000); + await result; + expect(ready).toHaveBeenCalledWith(102); + }); + + it.each([undefined, NaN, Infinity, -1, 99.5])('never treats %s as a chain lock', async (height) => { + getTransaction.mockResolvedValue({ blockheight: 90, confirmations: 100 }); + getCoreChainLockedHeight.mockResolvedValue(height); + const controller = new AbortController(); + const progress = vi.fn(); + const result = waitForChainLock('tx', insight, islock, controller.signal, progress); + const assertion = expect(result).rejects.toThrow('cancelled'); + await vi.advanceTimersByTimeAsync(10000); + controller.abort(); + await assertion; + expect(progress).toHaveBeenCalled(); + }); + + it('ignores late responses after cancellation', async () => { + let resolve!: (value: { blockheight: number }) => void; + getTransaction.mockReturnValue(new Promise((r) => { resolve = r; })); + getCoreChainLockedHeight.mockResolvedValue(100); + const controller = new AbortController(); + const progress = vi.fn(); + const result = waitForChainLock('tx', insight, islock, controller.signal, progress); + const assertion = expect(result).rejects.toThrow('cancelled'); + controller.abort(); + resolve({ blockheight: 100 }); + await assertion; + expect(progress).not.toHaveBeenCalled(); + }); + + it('settles cancellation while Platform status is still pending', async () => { + getTransaction.mockResolvedValue({ blockheight: 100 }); + getCoreChainLockedHeight.mockReturnValue(new Promise(() => {})); + const controller = new AbortController(); + const progress = vi.fn(); + const rejected = vi.fn(); + void waitForChainLock('tx', insight, islock, controller.signal, progress).catch(rejected); + controller.abort(); + await vi.advanceTimersByTimeAsync(0); + expect(rejected).toHaveBeenCalledWith(new Error('Chain-lock wait cancelled')); + expect(progress).not.toHaveBeenCalled(); + }); +}); diff --git a/src/api/chainlock.ts b/src/api/chainlock.ts new file mode 100644 index 0000000..b8045fb --- /dev/null +++ b/src/api/chainlock.ts @@ -0,0 +1,46 @@ +import type { InsightClient } from './insight.js'; +import type { IslockService } from './islock.js'; +import { abortableSleep } from '../utils/sleep.js'; + +/** Wait for a mined transaction AND a real Platform-observed chain lock. */ +export async function waitForChainLock( + txid: string, + insight: InsightClient, + islock: IslockService, + signal: AbortSignal, + onProgress: (progress: { blockHeight?: number; chainLockedHeight?: number }) => void +): Promise { + while (!signal.aborted) { + // Platform reads cannot be aborted inside the SDK. Release this wait + // promptly and ignore their eventual results when the user cancels. + let onAbort = (): void => {}; + const cancelled = new Promise((resolve) => { + onAbort = () => resolve(null); + signal.addEventListener('abort', onAbort, { once: true }); + }); + let results; + try { + results = await Promise.race([ + Promise.allSettled([ + insight.getTransaction(txid, { maxAttempts: 1 }, signal), + islock.getCoreChainLockedHeight(), + ]), + cancelled, + ]); + } finally { + signal.removeEventListener('abort', onAbort); + } + if (!results || signal.aborted) break; + const [tx, chain] = results; + const blockHeight = tx.status === 'fulfilled' ? tx.value.blockheight : undefined; + const chainLockedHeight = chain.status === 'fulfilled' ? chain.value : undefined; + onProgress({ blockHeight, chainLockedHeight }); + // Never infer a chain lock from confirmation count or an old UI snapshot. + if (blockHeight !== undefined && Number.isSafeInteger(blockHeight) && blockHeight > 0 && + chainLockedHeight !== undefined && Number.isSafeInteger(chainLockedHeight) && chainLockedHeight >= blockHeight) { + return blockHeight; + } + await abortableSleep(5000, signal); + } + throw new Error('Chain-lock wait cancelled'); +} diff --git a/src/api/dapi-subscription.ts b/src/api/dapi-subscription.ts index 156720e..9879e63 100644 --- a/src/api/dapi-subscription.ts +++ b/src/api/dapi-subscription.ts @@ -129,11 +129,14 @@ export class DAPISubscriptionClient { onProgress?.('Listening for InstantSend lock...'); const lockPromise = new Promise((resolve, reject) => { + let settled = false; const onAbort = (): void => { finish(() => reject(new Error(`InstantSend lock subscription aborted for ${txid}`))); }; const finish = (fn: () => void): void => { + if (settled) return; + settled = true; clearTimeout(timeoutId); signal?.removeEventListener('abort', onAbort); try { stream.cancel(); } catch { /* ignore */ } diff --git a/src/api/dapi.test.ts b/src/api/dapi.test.ts new file mode 100644 index 0000000..bad6c7c --- /dev/null +++ b/src/api/dapi.test.ts @@ -0,0 +1,77 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { DAPIClient } from './dapi.js'; + +// A structurally valid deterministic InstantSend lock (signature is a fixture). +const txid = '22'.repeat(32); +const lockHex = '0101' + '11'.repeat(32) + '00000000' + txid + '33'.repeat(32) + '44'.repeat(96); +const fetchMock = vi.fn(); +const client = new DAPIClient({ network: 'testnet', rpcUrl: 'https://rpc.example.invalid' }); +const reply = (result: unknown) => ({ ok: true, json: async () => ({ result }) }); + +beforeEach(() => { vi.useFakeTimers(); vi.stubGlobal('fetch', fetchMock); fetchMock.mockReset(); }); +afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); }); + +describe('optional InstantSend RPC', () => { + it('has no provider when no URL is configured', () => { + expect(new DAPIClient({ network: 'testnet' }).hasRpcUrl).toBe(false); + expect(new DAPIClient({ network: 'mainnet' }).hasRpcUrl).toBe(false); + }); + + it('polls empty results and returns a valid matching lock', async () => { + fetchMock.mockResolvedValueOnce(reply([])).mockResolvedValue(reply([{ txid, hex: lockHex }])); + const result = client.waitForInstantSendLock(txid); + await vi.advanceTimersByTimeAsync(2000); + await expect(result).resolves.toEqual(new Uint8Array(Buffer.from(lockHex, 'hex'))); + expect(fetchMock.mock.calls[0][0]).toBe('https://rpc.example.invalid'); + }); + + it('yields after three blocked requests instead of polling forever', async () => { + fetchMock.mockRejectedValue(new TypeError('Failed to fetch')); + const result = expect(client.waitForInstantSendLock(txid)).rejects.toThrow('Failed to fetch'); + await vi.advanceTimersByTimeAsync(12000); + await result; + expect(fetchMock).toHaveBeenCalledTimes(3); + }); + + it('aborts a stalled request at the overall polling deadline', async () => { + let requestSignal: AbortSignal | undefined; + fetchMock.mockImplementation((_url, init) => new Promise((_resolve, reject) => { + requestSignal = init.signal; + init.signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError'))); + })); + const result = expect(client.waitForInstantSendLock(txid, 1000)).rejects.toThrow('Timeout'); + await vi.advanceTimersByTimeAsync(1000); + await result; + expect(requestSignal?.aborted).toBe(true); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('cancels an in-flight request when a broadcast fails', async () => { + const controller = new AbortController(); + fetchMock.mockImplementation((_url, init) => new Promise((_resolve, reject) => { + init.signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError'))); + })); + const result = expect(client.waitForInstantSendLock(txid, 60000, undefined, controller.signal)).rejects.toThrow('aborted'); + controller.abort(); + await result; + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it.each([ + { error: { code: -32601, message: 'Method not found' } }, + { result: [{ txid, hex: 'abz' }] }, + { result: [{ txid, hex: lockHex.replace(txid, '55'.repeat(32)) }] }, + { result: {} }, + ])('surfaces provider errors/malformed locks for recovery', async (body) => { + fetchMock.mockResolvedValue({ ok: true, json: async () => body }); + const result = expect(client.waitForInstantSendLock(txid)).rejects.toThrow(); + await vi.advanceTimersByTimeAsync(12000); + await result; + expect(fetchMock).toHaveBeenCalledTimes(3); + }); + + it('rejects invalid heights instead of claiming a healthy RPC', async () => { + fetchMock.mockResolvedValue(reply({ height: -1 })); + await expect(client.getBestChainLock()).rejects.toThrow('Invalid chain-lock height'); + }); +}); diff --git a/src/api/dapi.ts b/src/api/dapi.ts index 0ec275e..07b23ee 100644 --- a/src/api/dapi.ts +++ b/src/api/dapi.ts @@ -1,49 +1,16 @@ -/** - * Client for InstantSend lock retrieval via JSON-RPC API - */ - -import { withRetry, type RetryOptions } from '../utils/retry.js'; +/** Optional JSON-RPC fast path for retrieving InstantSend locks by txid. */ +import { fetchJson } from '../utils/fetch-json.js'; +import type { RetryOptions } from '../utils/retry.js'; import { describeIslock } from '../utils/islock-debug.js'; import { abortableSleep } from '../utils/sleep.js'; -const API_URLS: Record = { - testnet: 'https://trpc.digitalcash.dev', - mainnet: 'https://rpc.digitalcash.dev', -}; - export interface DAPIConfig { network: string; rpcUrl?: string; } -/** - * Response from the getislocks JSON-RPC endpoint - */ -interface IslockResponse { - result?: Array<{ - txid: string; - hex: string; // hex-encoded islock bytes - signature?: string; - cycleHash?: string; - }>; - error?: unknown; - id?: unknown; -} - -interface BestChainLockResponse { - result?: { - height?: number; - blockhash?: string; - signature?: string; - known_block?: boolean; - }; - error?: unknown; - id?: unknown; -} +const REQUEST_TIMEOUT_MS = 8000; -/** - * Client for InstantSend lock retrieval - */ export class DAPIClient { readonly network: string; private readonly rpcUrl?: string; @@ -54,147 +21,76 @@ export class DAPIClient { } get hasRpcUrl(): boolean { - return !!(this.rpcUrl || API_URLS[this.network]); + return !!this.rpcUrl; } - /** - * Broadcast a transaction via DAPI - * - * Note: This is a placeholder. Use InsightClient.broadcastTransaction instead. - */ - async broadcastTransaction(_txBytes: Uint8Array): Promise { - throw new Error( - 'DAPI broadcastTransaction not implemented. Use InsightClient.broadcastTransaction instead.' - ); + private async request( + method: string, + params: unknown[], + timeoutMs = REQUEST_TIMEOUT_MS, + signal?: AbortSignal + ): Promise { + if (!this.rpcUrl) throw new Error(`No RPC URL configured for network ${this.network}`); + const data = await fetchJson(this.rpcUrl, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ method, params }), + signal, + }, timeoutMs); + if (!data || typeof data !== 'object') throw new Error(`Invalid RPC ${method} response`); + if (data.error) throw new Error(`RPC ${method} failed: ${JSON.stringify(data.error)}`); + if (!('result' in data)) throw new Error(`RPC ${method} response missing result`); + return data.result; } - /** - * Get InstantSend lock from tRPC API - * Polls the API until the islock is available or timeout is reached - * @param onRetry - Optional callback when a network error causes a retry - * @param signal - Optional AbortSignal to cancel polling early - */ async waitForInstantSendLock( txid: string, - timeoutMs: number = 60000, - onRetry?: (attempt: number, maxAttempts: number, error: unknown) => void, + timeoutMs = 60000, + onRetry?: RetryOptions['onRetry'], signal?: AbortSignal ): Promise { - const startTime = Date.now(); - const pollInterval = 2000; // Poll every 2 seconds - - while (Date.now() - startTime < timeoutMs) { - if (signal?.aborted) { - throw new Error(`InstantSend lock polling aborted for ${txid}`); - } + const deadline = Date.now() + timeoutMs; + let failures = 0; + while (Date.now() < deadline && !signal?.aborted) { try { - const islock = await this.getIslock(txid, { onRetry }); - if (islock) { - return islock; + const result = await this.request('getislocks', [[txid]], Math.min(REQUEST_TIMEOUT_MS, deadline - Date.now()), signal); + if (!Array.isArray(result)) throw new Error('Invalid getislocks response'); + const lock = result.find((item) => item?.txid === txid); + if (lock) { + if (typeof lock.hex !== 'string' || !/^(?:[0-9a-fA-F]{2})+$/.test(lock.hex)) { + throw new Error('Invalid InstantSend lock hex'); + } + const bytes = Uint8Array.from(lock.hex.match(/../g)!, (pair: string) => parseInt(pair, 16)); + const debug = describeIslock(bytes, 'json-rpc'); + if (debug.parsed?.txid !== txid) throw new Error('Invalid or mismatched InstantSend lock'); + return bytes; } + failures = 0; } catch (error) { - console.warn('Error polling for islock:', error); + if (signal?.aborted) break; + failures++; + onRetry?.(failures, 3, error); + // An unreachable/blocked provider should yield to the chain-proof path + // promptly. Empty results still poll until the normal IS lock deadline. + if (failures >= 3) throw error; } - - // Wait before next poll, but bail out immediately if aborted - await abortableSleep(pollInterval, signal); + if (Date.now() >= deadline) break; + await abortableSleep(Math.min(2000 * 2 ** failures, 10000, Math.max(0, deadline - Date.now())), signal); } - - throw new Error( - `Timeout waiting for InstantSend lock for ${txid} after ${timeoutMs}ms` - ); + throw new Error(signal?.aborted + ? `InstantSend lock polling aborted for ${txid}` + : `Timeout waiting for InstantSend lock for ${txid} after ${timeoutMs}ms`); } - /** - * Fetch the current best chain-locked height via JSON-RPC. - * Returns null if no chain lock has been observed yet. - */ - async getBestChainLock(retryOptions?: RetryOptions): Promise<{ height: number; blockhash?: string } | null> { - if (!this.hasRpcUrl) { - return null; + /** Core-only health backup; this does not establish Platform readiness. */ + async getBestChainLock(): Promise<{ height: number; blockhash?: string } | null> { + if (!this.hasRpcUrl) return null; + const result = await this.request('getbestchainlock', []); + if (result === null) return null; + const lock = result as { height?: number; blockhash?: string }; + if (typeof lock?.height !== 'number' || !Number.isSafeInteger(lock.height) || lock.height < 0) { + throw new Error('Invalid chain-lock height'); } - - return withRetry(async () => { - const baseUrl = this.rpcUrl ?? API_URLS[this.network]; - if (!baseUrl) { - return null; - } - - const response = await fetch(baseUrl, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ method: 'getbestchainlock', params: [] }), - }); - - if (!response.ok) { - throw new Error(`RPC API error: ${response.status} ${response.statusText}`); - } - - const data: BestChainLockResponse = await response.json(); - if (!data.result || typeof data.result.height !== 'number') { - return null; - } - return { height: data.result.height, blockhash: data.result.blockhash }; - }, retryOptions); - } - - /** - * Fetch islock from JSON-RPC API - */ - private async getIslock(txid: string, retryOptions?: RetryOptions): Promise { - return withRetry(async () => { - const baseUrl = this.rpcUrl ?? API_URLS[this.network]; - if (!baseUrl) { - throw new Error(`No RPC URL configured for network ${this.network}`); - } - - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - method: 'getislocks', - params: [[txid]], - }), - }); - - if (!response.ok) { - throw new Error(`RPC API error: ${response.status} ${response.statusText}`); - } - - const data: IslockResponse = await response.json(); - - // Check if we got a result - if (data.result && data.result.length > 0) { - const islockData = data.result.find((item) => item.txid === txid); - if (islockData?.hex) { - const bytes = hexToBytes(islockData.hex); - const debug = describeIslock(bytes, `json-rpc:${baseUrl}`); - console.log('[islock-debug] IS lock received via JSON-RPC:', debug); - if (islockData.signature || islockData.cycleHash) { - console.log('[islock-debug] JSON-RPC reported fields:', { - signature: islockData.signature, - cycleHash: islockData.cycleHash, - }); - } - return bytes; - } - } - - return null; - }, retryOptions); + return { height: lock.height, blockhash: lock.blockhash }; } } - -/** - * Convert hex string to Uint8Array - */ -function hexToBytes(hex: string): Uint8Array { - const bytes = new Uint8Array(hex.length / 2); - for (let i = 0; i < bytes.length; i++) { - bytes[i] = parseInt(hex.substr(i * 2, 2), 16); - } - return bytes; -} - diff --git a/src/api/insight.ts b/src/api/insight.ts index 33e75d2..62485ed 100644 --- a/src/api/insight.ts +++ b/src/api/insight.ts @@ -2,6 +2,7 @@ import type { UTXO, TxInfo } from '../types.js'; import type { NetworkConfig } from '../config.js'; import { withRetry, type RetryOptions } from '../utils/retry.js'; import { abortableSleep } from '../utils/sleep.js'; +import { fetchJson } from '../utils/fetch-json.js'; export interface InsightApiResponse { success: boolean; @@ -50,13 +51,7 @@ export class InsightClient { */ async getBlockHeight(retryOptions?: RetryOptions): Promise { return withRetry(async () => { - const response = await fetch(`${this.baseUrl}/status?q=getInfo`); - - if (!response.ok) { - throw new Error(`Insight API error: ${response.status} ${response.statusText}`); - } - - const data = await response.json(); + const data = await fetchJson(`${this.baseUrl}/status?q=getInfo`); const blocks = data?.info?.blocks; if (typeof blocks !== 'number') { throw new Error('Insight getInfo response missing info.blocks'); @@ -91,15 +86,10 @@ export class InsightClient { /** * Get transaction details */ - async getTransaction(txid: string, retryOptions?: RetryOptions): Promise { + async getTransaction(txid: string, retryOptions?: RetryOptions, signal?: AbortSignal): Promise { return withRetry(async () => { - const response = await fetch(`${this.baseUrl}/tx/${txid}`); - - if (!response.ok) { - throw new Error(`Failed to get transaction: ${response.status}`); - } - - const data = await response.json(); + const data = await fetchJson(`${this.baseUrl}/tx/${txid}`, { signal }); + if (data.txid !== txid) throw new Error('Insight returned a different transaction'); // Insight returns blockheight: -1 while the tx is unconfirmed. const rawHeight = diff --git a/src/api/islock.test.ts b/src/api/islock.test.ts index 302fe15..b73009f 100644 --- a/src/api/islock.test.ts +++ b/src/api/islock.test.ts @@ -8,13 +8,14 @@ const mocks = vi.hoisted(() => ({ getCoreChainLockedHeight: vi.fn(), getPlatformStatus: vi.fn(), disconnect: vi.fn(), + fetchPlatformStatus: vi.fn(), })); 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; }, waitForInstantSendLock: mocks.waitForInstantSendLock, getBestChainLock: mocks.getBestChainLock, @@ -31,6 +32,8 @@ vi.mock('./dapi-subscription.js', () => ({ })), })); +vi.mock('../platform/status.js', () => ({ fetchPlatformStatus: mocks.fetchPlatformStatus })); + import { IslockService } from './islock.js'; describe('IslockService', () => { @@ -39,10 +42,10 @@ describe('IslockService', () => { mocks.getTransactionLockStatus.mockResolvedValue(null); }); - it('uses JSON-RPC only on mainnet to avoid browser DAPI stream discovery', async () => { + it('uses explicitly configured RPC without browser DAPI stream discovery', async () => { const bytes = new Uint8Array([1, 2, 3]); mocks.waitForInstantSendLock.mockResolvedValue(bytes); - const service = new IslockService({ network: 'mainnet' }); + const service = new IslockService({ network: 'mainnet', rpcUrl: 'https://rpc.example.invalid' }); const progress: string[] = []; const handle = await service.subscribeForInstantSendLock( @@ -63,6 +66,14 @@ describe('IslockService', () => { await expect(handle.wait()).resolves.toBe(bytes); }); + it.each(['mainnet', 'testnet'])('uses chain proofs on %s without legacy seed discovery', async (network) => { + const service = new IslockService({ network }); + const handle = await service.subscribeForInstantSendLock('txid', new Uint8Array([4]), { txid: 'prevout', vout: 0 }); + await expect(handle.wait()).rejects.toThrow('disabled'); + expect(mocks.waitForInstantSendLock).not.toHaveBeenCalled(); + expect(mocks.subscribeForInstantSendLock).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) }; @@ -80,3 +91,15 @@ describe('IslockService', () => { await expect(handle.wait()).resolves.toBe(bytes); }); }); + +for (const network of ['mainnet', 'testnet']) { + it(`reads ${network} chain-lock progress independently of RPC and legacy DAPI discovery`, async () => { + vi.clearAllMocks(); + mocks.fetchPlatformStatus.mockResolvedValue({ coreChainLockedHeight: 100 }); + const service = new IslockService({ network }); + await expect(service.getCoreChainLockedHeight()).resolves.toBe(100); + expect(mocks.fetchPlatformStatus).toHaveBeenCalledWith(network); + expect(mocks.getBestChainLock).not.toHaveBeenCalled(); + expect(mocks.getPlatformStatus).not.toHaveBeenCalled(); + }); +} diff --git a/src/api/islock.ts b/src/api/islock.ts index 01bb31e..bd829c5 100644 --- a/src/api/islock.ts +++ b/src/api/islock.ts @@ -2,6 +2,7 @@ import { DAPIClient, type DAPIConfig } from './dapi.js'; import { DAPISubscriptionClient, type DAPISubscriptionConfig } from './dapi-subscription.js'; import type { RetryOptions } from '../utils/retry.js'; import { abortableSleep } from '../utils/sleep.js'; +import { fetchPlatformStatus, type PlatformStatus } from '../platform/status.js'; export interface IslockServiceConfig { network: string; @@ -14,7 +15,7 @@ export class IslockService { private readonly subscriptionClient: DAPISubscriptionClient; private readonly hasJsonRpc: boolean; - constructor(config: IslockServiceConfig) { + constructor(private readonly config: IslockServiceConfig) { const jsonRpcConfig: DAPIConfig = { network: config.network, rpcUrl: config.rpcUrl }; this.jsonRpcClient = new DAPIClient(jsonRpcConfig); this.hasJsonRpc = this.jsonRpcClient.hasRpcUrl; @@ -69,8 +70,8 @@ export class IslockService { * `.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. + * Public networks without a configured RPC provider request chain recovery. + * Explicit RPC URLs enable polling by txid without legacy seed discovery. */ async subscribeForInstantSendLock( txid: string, @@ -79,19 +80,29 @@ export class IslockService { timeoutMs: number = 60000, onRetry?: RetryOptions['onRetry'], onProgress?: (message: string) => void - ): Promise<{ wait: () => Promise }> { + ): Promise<{ wait: () => Promise; cancel: () => void }> { + if (!this.hasJsonRpc && (this.config.network === 'mainnet' || this.config.network === 'testnet')) { + // Public networks can operate entirely through chain proofs when the + // optional RPC URL is omitted/disabled. Never start legacy seed discovery. + return { + wait: async () => { throw new Error('InstantSend RPC is disabled; use a chain proof'); }, + cancel: () => {}, + }; + } if (!this.hasJsonRpc) { // DAPI subscription only — establish the stream, then return. + const tripwireController = new AbortController(); const sub = await this.subscriptionClient.subscribeForInstantSendLock( txid, publicKey, utxo, timeoutMs, - onProgress + onProgress, + tripwireController.signal ); - const tripwireController = new AbortController(); this.startLockStatusTripwire(txid, tripwireController.signal); return { + cancel: () => tripwireController.abort(), wait: async () => { try { return await sub.wait(); @@ -102,7 +113,7 @@ export class IslockService { }; } - // JSON-RPC backed networks (mainnet/testnet) should not touch dapi-client + // Networks with an explicit RPC URL 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. @@ -131,7 +142,7 @@ export class IslockService { })(); waitPromise.catch(() => {}); - return { wait: () => waitPromise }; + return { wait: () => waitPromise, cancel: () => jsonRpcController.abort() }; } async waitForInstantSendLock( @@ -146,21 +157,12 @@ export class IslockService { return sub.wait(); } - /** - * 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-observed chain lock, independent of the optional RPC host. */ async getCoreChainLockedHeight(): Promise { - return this.subscriptionClient.getCoreChainLockedHeight(); + return (await this.getPlatformStatus()).coreChainLockedHeight; } - /** - * 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 an optional Core JSON-RPC fast path is configured. */ get supportsJsonRpc(): boolean { return this.hasJsonRpc; } @@ -174,16 +176,11 @@ export class IslockService { return this.jsonRpcClient.getBestChainLock(); } - /** - * 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). - */ - async getPlatformStatus(): Promise<{ - coreChainLockedHeight?: number; - latestBlockHeight?: number; - latestBlockTimeMs?: number; - }> { + /** Public networks use EvoSDK discovery; devnets keep explicit DAPI nodes. */ + async getPlatformStatus(): Promise { + if (this.config.network === 'mainnet' || this.config.network === 'testnet') { + return fetchPlatformStatus(this.config.network); + } return this.subscriptionClient.getPlatformStatus(); } diff --git a/src/api/network-status.test.ts b/src/api/network-status.test.ts index 2ef5046..b90f812 100644 --- a/src/api/network-status.test.ts +++ b/src/api/network-status.test.ts @@ -8,9 +8,8 @@ type PlatformStatus = Awaited>; type ChainLock = Awaited>; /** - * Build stub clients. `platform` selects the DAPI path (devnet: - * supportsJsonRpc=false); `chainLock` selects the JSON-RPC path - * (mainnet/testnet: supportsJsonRpc=true). + * Platform is preferred on all networks; chainLock supplies an optional + * Core-only RPC backup when Platform status is unavailable. */ function makeClients(opts: { coreHeight?: number | Error; @@ -121,15 +120,15 @@ describe('fetchNetworkStatus (DAPI / devnet path)', () => { }); }); -describe('fetchNetworkStatus (JSON-RPC / mainnet-testnet path)', () => { - it('reports healthy when Core chain-lock tracks the tip', async () => { +describe('fetchNetworkStatus (Core RPC health backup)', () => { + it('reports degraded when only Core chain-lock is reachable', async () => { const { insight, islock } = makeClients({ coreHeight: 10_700, chainLock: { height: 10_699 }, }); const status = await fetchNetworkStatus(insight, islock); - expect(status.health).toBe('healthy'); + expect(status.health).toBe('degraded'); expect(status.coreChainLockedHeight).toBe(10_699); expect(status.chainLockLag).toBe(1); // No Tenderdash block age signal on this path. @@ -147,19 +146,19 @@ describe('fetchNetworkStatus (JSON-RPC / mainnet-testnet path)', () => { expect(status.chainLockLag).toBe(50); }); - it('stays healthy (no lag signal) when no chain lock observed yet', async () => { + it('stays degraded when only RPC answers with no chain lock', async () => { const { insight, islock } = makeClients({ coreHeight: 10_700, chainLock: null, }); const status = await fetchNetworkStatus(insight, islock); - expect(status.health).toBe('healthy'); + expect(status.health).toBe('degraded'); expect(status.coreChainLockedHeight).toBeUndefined(); expect(status.chainLockLag).toBeUndefined(); }); - it('reports the RPC source (not Platform) when the chain-lock RPC fails', async () => { + it('reports unavailable Platform status when both secondary sources fail', async () => { const { insight, islock } = makeClients({ coreHeight: 10_700, chainLock: new Error('rpc down'), @@ -167,8 +166,7 @@ describe('fetchNetworkStatus (JSON-RPC / mainnet-testnet path)', () => { const status = await fetchNetworkStatus(insight, islock); expect(status.health).toBe('degraded'); - expect(status.reasons.join(' ')).toMatch(/RPC/i); - expect(status.reasons.join(' ')).not.toMatch(/Platform/i); + expect(status.reasons.join(' ')).toMatch(/Platform/i); }); }); diff --git a/src/api/network-status.ts b/src/api/network-status.ts index e342099..e85d940 100644 --- a/src/api/network-status.ts +++ b/src/api/network-status.ts @@ -33,49 +33,26 @@ export async function fetchNetworkStatus( ): Promise { 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 - // 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. - 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([ + // Platform status uses EvoSDK on public networks and explicit DAPI nodes on + // devnets. The optional Core RPC is only a degraded health backup. + const [coreResult, platformResult] = await Promise.allSettled([ insight.getBlockHeight({ maxAttempts: 1 }), - useDapiPlatformStatus ? islock.getPlatformStatus() : islock.getBestChainLock(), + islock.getPlatformStatus(), ]); - const coreHeight = coreResult.status === 'fulfilled' ? coreResult.value : undefined; - - let coreChainLockedHeight: number | undefined; - let platformBlockHeight: number | undefined; - let platformBlockTimeMs: number | undefined; - let secondaryReachable: boolean; - - if (useDapiPlatformStatus) { - // Settled value is the getPlatformStatus() shape on this branch. - const platform = - secondaryResult.status === 'fulfilled' - ? (secondaryResult.value as Awaited>) - : undefined; - secondaryReachable = platform !== undefined; - coreChainLockedHeight = platform?.coreChainLockedHeight; - platformBlockHeight = platform?.latestBlockHeight; - platformBlockTimeMs = platform?.latestBlockTimeMs; - } else { - // A null result (no chain lock observed yet) still means the endpoint - // answered — only a rejection counts as unreachable. - secondaryReachable = secondaryResult.status === 'fulfilled'; - const chainLock = - secondaryResult.status === 'fulfilled' - ? (secondaryResult.value as Awaited>) - : undefined; - coreChainLockedHeight = chainLock?.height; + const platform = platformResult.status === 'fulfilled' ? platformResult.value : undefined; + let coreChainLockedHeight = platform?.coreChainLockedHeight; + const platformBlockHeight = platform?.latestBlockHeight; + const platformBlockTimeMs = platform?.latestBlockTimeMs; + let rpcReachable = false; + if (!platform && islock.supportsJsonRpc) { + try { + const lock = await islock.getBestChainLock(); + coreChainLockedHeight = lock?.height; + rpcReachable = true; + } catch { /* Both providers may be blocked; report unavailable below. */ } } + const secondaryReachable = platform !== undefined || rpcReachable; const reasons: string[] = []; let health: Exclude = 'healthy'; @@ -115,13 +92,13 @@ export async function fetchNetworkStatus( escalate('degraded'); reasons.push('Insight (Core) unreachable'); } - if (!secondaryReachable) { + if (!platform) { // "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. escalate('degraded'); reasons.push( - useDapiPlatformStatus ? 'Platform (DAPI) status unreachable' : 'Chain-lock RPC unreachable' + rpcReachable ? 'Platform status unreachable; using Core RPC chain-lock only' : 'Platform status unreachable' ); } diff --git a/src/config.ts b/src/config.ts index a763a57..b5995a5 100644 --- a/src/config.ts +++ b/src/config.ts @@ -11,6 +11,7 @@ export interface NetworkConfig { platformHrp: string; faucetBaseUrl?: string; dapiAddresses?: string[]; + /** Optional InstantSend fast path; chain-proof recovery uses Platform directly. */ rpcUrl?: string; /** * Devnet-only: opt in to the SDK's trusted-context mode. When true, the @@ -44,7 +45,6 @@ export const TESTNET: NetworkConfig = { dustThreshold: 546, platformHrp: 'tdash', faucetBaseUrl: 'https://faucet.thepasta.org', - rpcUrl: 'https://trpc.digitalcash.dev', }; export const MAINNET: NetworkConfig = { @@ -57,7 +57,6 @@ export const MAINNET: NetworkConfig = { minFee: 1000, dustThreshold: 546, platformHrp: 'dash', - rpcUrl: 'https://rpc.digitalcash.dev', }; export const DEVNET_MOUTAI: NetworkConfig = { diff --git a/src/main.ts b/src/main.ts index b90469e..c00958a 100644 --- a/src/main.ts +++ b/src/main.ts @@ -12,10 +12,10 @@ import { createAssetLockTransaction, serializeTransaction, calculateTxId } from import { InsightClient } 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 { waitForChainLock } from './api/chainlock.js'; import { buildInstantAssetLockProof, buildChainAssetLockProof } from './proof/index.js'; import { bech32m } from '@scure/base'; -import { privateKeyToWif, bytesToHex, abortableSleep } from './utils/index.js'; +import { privateKeyToWif, bytesToHex } from './utils/index.js'; import { createInitialState, setStep, @@ -2416,28 +2416,8 @@ async function startTopUp() { updateState(setTransactionSigned(state, signedTxHex, signedTxBytes)); - // Step 5: Open IS lock subscription BEFORE broadcasting — dashd does not - // replay historical IS locks, so we must be listening before the lock - // is signed (which can happen within milliseconds of broadcast). - updateState(setStep(state, 'waiting_islock')); - console.log('Opening IS lock subscription before broadcast...'); - const islockSub = await islock.subscribeForInstantSendLock( - txid, - assetLockKeyPair.publicKey, - utxo - ); - - // Step 6: Broadcast transaction - const broadcastedTxid = await insightClient.broadcastTransaction(signedTxHex); - if (broadcastedTxid !== txid) { - console.warn(`Broadcast txid ${broadcastedTxid} differs from local ${txid}`); - } - - updateState(setTransactionBroadcast(state, txid)); - - console.log('Waiting for InstantSend lock...'); - const islockBytes = await islockSub.wait(); - console.log('InstantSend lock received:', islockBytes.length, 'bytes'); + const islockBytes = await broadcastAndWaitForLock(islock, txid, signedTxHex, assetLockKeyPair.publicKey, utxo); + if (!islockBytes) return; // Chain-proof recovery completed or was cancelled. const assetLockProof = buildInstantAssetLockProof( signedTxBytes, @@ -2539,22 +2519,8 @@ async function startSendToAddress() { updateState(setTransactionSigned(state, signedTxHex, signedTxBytes)); - // Step 5: Subscribe for IS lock BEFORE broadcasting (see flow #1 for why). - updateState(setStep(state, 'waiting_islock')); - const islockSub = await islock.subscribeForInstantSendLock( - txid, - assetLockKeyPair.publicKey, - utxo - ); - - // Step 6: Broadcast transaction - const broadcastedTxid = await insightClient.broadcastTransaction(signedTxHex); - if (broadcastedTxid !== txid) { - console.warn(`Broadcast txid ${broadcastedTxid} differs from local ${txid}`); - } - updateState(setTransactionBroadcast(state, txid)); - - const islockBytes = await islockSub.wait(); + const islockBytes = await broadcastAndWaitForLock(islock, txid, signedTxHex, assetLockKeyPair.publicKey, utxo); + if (!islockBytes) return; // Chain-proof recovery completed or was cancelled. const assetLockProof = buildInstantAssetLockProof( signedTxBytes, @@ -2755,25 +2721,8 @@ async function startBridge() { updateState(setTransactionSigned(state, signedTxHex, signedTxBytes)); - // Step 5: Subscribe for IS lock BEFORE broadcasting (see flow #1 for why). - updateState(setStep(state, 'waiting_islock')); - console.log('Opening IS lock subscription before broadcast...'); - const islockSub = await islock.subscribeForInstantSendLock( - txid, - assetLockKeyPair.publicKey, - utxo - ); - - // Step 6: Broadcast transaction - const broadcastedTxid = await insightClient.broadcastTransaction(signedTxHex); - if (broadcastedTxid !== txid) { - console.warn(`Broadcast txid ${broadcastedTxid} differs from local ${txid}`); - } - updateState(setTransactionBroadcast(state, txid)); - - console.log('Waiting for InstantSend lock...'); - const islockBytes = await islockSub.wait(); - console.log('InstantSend lock received:', islockBytes.length, 'bytes'); + const islockBytes = await broadcastAndWaitForLock(islock, txid, signedTxHex, assetLockKeyPair.publicKey, utxo); + if (!islockBytes) return; // Chain-proof recovery completed or was cancelled. const assetLockProof = buildInstantAssetLockProof( signedTxBytes, @@ -2879,25 +2828,8 @@ async function recheckDeposit() { updateState(setTransactionSigned(state, signedTxHex, signedTxBytes)); - // Step 5: Subscribe for IS lock BEFORE broadcasting (see flow #1 for why). - updateState(setStep(state, 'waiting_islock')); - console.log('Opening IS lock subscription before broadcast...'); - const islockSub = await islock.subscribeForInstantSendLock( - txid, - assetLockKeyPair.publicKey, - utxo - ); - - // Step 6: Broadcast transaction - const broadcastedTxid = await insightClient.broadcastTransaction(signedTxHex); - if (broadcastedTxid !== txid) { - console.warn(`Broadcast txid ${broadcastedTxid} differs from local ${txid}`); - } - updateState(setTransactionBroadcast(state, txid)); - - console.log('Waiting for InstantSend lock...'); - const islockBytes = await islockSub.wait(); - console.log('InstantSend lock received:', islockBytes.length, 'bytes'); + const islockBytes = await broadcastAndWaitForLock(islock, txid, signedTxHex, assetLockKeyPair.publicKey, utxo); + if (!islockBytes) return; // Chain-proof recovery completed or was cancelled. const assetLockProof = buildInstantAssetLockProof( signedTxBytes, @@ -2958,6 +2890,33 @@ async function recheckDeposit() { } } +/** Subscribe before broadcast, then recover the same transaction if IS fails. */ +async function broadcastAndWaitForLock( + islock: IslockService, + txid: string, + signedTxHex: string, + publicKey: Uint8Array, + utxo: { txid: string; vout: number } +): Promise { + updateState(setStep(state, 'waiting_islock')); + const subscription = await islock.subscribeForInstantSendLock(txid, publicKey, utxo); + try { + updateState(setStep(state, 'broadcasting')); + const broadcastedTxid = await insightClient.broadcastTransaction(signedTxHex); + updateState(setTransactionBroadcast(state, txid)); + if (broadcastedTxid !== txid) throw new Error('Broadcast returned a different transaction ID'); + try { + return await subscription.wait(); + } catch (error) { + console.warn('InstantSend unavailable; waiting for a chain proof:', error); + await startChainlockFallback(); + return null; + } + } finally { + subscription.cancel(); + } +} + // ============================================================================ // ChainLock Fallback // ============================================================================ @@ -3048,7 +3007,7 @@ 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 + * confirming block, poll Platform independently of JSON-RPC for the * chain-locked tip, and once `coreChainLockedHeight >= blockHeight` build a * chain asset lock proof and resubmit the original Platform operation. */ @@ -3065,99 +3024,23 @@ async function startChainlockFallback(): Promise { const signal = chainlockController.signal; updateState(setChainlockFallbackStarted(state)); - await ensureClients(); - const islock = islockService!; - - const network = getNetwork(state.network); - const txid = state.txid; - const dapiClient = new DAPIClient({ network: state.network, rpcUrl: network.rpcUrl }); - - // Poll #1: asset lock tx block height via Insight. - const blockHeightPromise = insightClient.waitForBlockHeight( - txid, - 5000, - signal, - (info) => { - if (info.blockheight !== undefined) { - updateState(setChainlockProgress(state, { blockHeight: info.blockheight })); - } - } - ); - - // 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. - const chainLockPoll = (async (): Promise => { - while (!signal.aborted) { - let height: number | undefined; - try { - const observed = await dapiClient.getBestChainLock(); - if (observed) height = observed.height; - } catch (error) { - console.warn('getBestChainLock failed:', error); - } - if (height === undefined) { - try { - height = await islock.getCoreChainLockedHeight(); - } catch (error) { - console.warn('platform.getStatus core chain locked height failed:', error); - } - } - if (height !== undefined) { - updateState(setChainlockProgress(state, { chainLockedHeight: height })); - } - await abortableSleep(5000, signal); - } - })(); - chainLockPoll.catch(() => {}); - - // Tracks whether we've already handed off to the Platform submission. Once - // true, errors should use the step's natural error code (REGISTER / TOPUP / - // SEND_ADDRESS), NOT ErrorCodes.CHAINLOCK — so the user sees the actual - // submission failure rather than a generic chainlock label. let submissionStarted = false; - try { - console.log('[chainlock-fallback] waiting for asset lock tx to be mined…'); - const blockHeight = await blockHeightPromise; - console.log(`[chainlock-fallback] asset lock tx confirmed at block ${blockHeight}`); - - // Wait for an actual chain-lock observation that buries the tx's block. - // No confirmations-based fallback — submitting a chain proof without - // having seen a real chain-locked tip would just be guessing, and - // Platform would reject it anyway. - while (!signal.aborted) { - const chainLockedHeight = state.coreChainLockedHeight; - if (chainLockedHeight !== undefined && chainLockedHeight >= blockHeight) { - break; - } - await abortableSleep(2000, signal); - } - - if (signal.aborted) { - return; - } - - const chainLockedHeight = state.coreChainLockedHeight!; - // Use the tx's confirming block height as the proof value (the minimum - // valid value, and the one Platform can unambiguously correlate back to - // the asset lock tx). The observed chain-lock tip just tells us Platform - // has caught up far enough to verify. - console.log( - `[chainlock-fallback] chain locked through block ${chainLockedHeight} (>= ${blockHeight}); ` + - `building chain asset lock proof for ${txid}:0 with coreChainLockedHeight=${blockHeight}` + await ensureClients(); + const network = getNetwork(state.network); + const txid = state.txid; + const blockHeight = await waitForChainLock( + txid, + insightClient, + islockService!, + signal, + (progress) => updateState(setChainlockProgress(state, progress)) ); + if (signal.aborted) return; const proof = buildChainAssetLockProof(txid, 0, blockHeight); updateState(setChainlockProofReady(state, proof)); - - // Stop the chain-locked-height poller now that we've armed the proof. - // The blockHeightPromise has already resolved. - chainlockController.abort(); + // There are no outstanding pollers now. Cancellation is no longer offered + // once the Platform submission begins. chainlockController = null; const assetLockPrivateKeyWif = privateKeyToWif( @@ -3181,6 +3064,7 @@ async function startChainlockFallback(): Promise { updateState(setError(state, toError(error), errorCode)); } finally { if (chainlockController?.signal === signal) { + chainlockController.abort(); chainlockController = null; } } diff --git a/src/platform/status.ts b/src/platform/status.ts new file mode 100644 index 0000000..0c8cced --- /dev/null +++ b/src/platform/status.ts @@ -0,0 +1,28 @@ +import { withConnectedPlatformSdk, withPlatformOperationTimeout } from './client.js'; + +export interface PlatformStatus { + coreChainLockedHeight?: number; + latestBlockHeight?: number; + latestBlockTimeMs?: number; +} + +function positiveInteger(value: unknown): number | undefined { + const number = Number(value); + return Number.isSafeInteger(number) && number > 0 ? number : undefined; +} + +/** Public networks use the same quorum discovery and node rotation as writes. */ +export async function fetchPlatformStatus(network: string): Promise { + return withPlatformOperationTimeout( + withConnectedPlatformSdk(network, async (sdk) => { + const status = await sdk.system.status(); + return { + coreChainLockedHeight: positiveInteger(status.chain.core_chain_locked_height), + latestBlockHeight: positiveInteger(status.chain.latest_block_height), + latestBlockTimeMs: positiveInteger(status.time.block), + }; + }, { maxAttempts: 1 }), + 'reading Platform status', + 20000 + ); +} diff --git a/src/ui/components.ts b/src/ui/components.ts index 8a79add..4a993b6 100644 --- a/src/ui/components.ts +++ b/src/ui/components.ts @@ -910,7 +910,7 @@ function renderProcessingStep(state: BridgeState): HTMLElement { const subtitle = document.createElement('p'); subtitle.className = 'processing-subtitle'; subtitle.textContent = isChainlock - ? 'Falling back from InstantSend. Polling for confirmation and chain lock — this can take a few minutes on mainnet/testnet.' + ? 'Waiting for your deposit transaction to be mined and chain-locked. This can take a few minutes.' : isSendToAddress ? 'Sending credits to the platform address.' : isTopUp diff --git a/src/ui/state.ts b/src/ui/state.ts index 91d2193..e7da496 100644 --- a/src/ui/state.ts +++ b/src/ui/state.ts @@ -512,6 +512,7 @@ export function setIdentityRegistered( * Determine whether the chainlock fallback can be offered for the given * error code. Available when: * - islock retrieval failed outright (ERR-1005), OR + * - A chain-lock wait was cancelled/failed and the same tx can be resumed. * - Platform rejected a submission that already had a typed asset lock * proof in hand (REGISTER / TOPUP / SEND_ADDRESS), AND we still hold * the broadcast txid + signed tx bytes needed to rebuild the proof. @@ -520,7 +521,7 @@ function computeChainlockFallbackAvailable( state: BridgeState, errorCode: string ): boolean { - if (errorCode === ErrorCodes.ISLOCK) { + if (errorCode === ErrorCodes.ISLOCK || errorCode === ErrorCodes.CHAINLOCK) { return !!state.txid; } if ( @@ -572,8 +573,8 @@ export function setChainlockProgress( ): BridgeState { return { ...state, - assetLockTxBlockHeight: progress.blockHeight ?? state.assetLockTxBlockHeight, - coreChainLockedHeight: progress.chainLockedHeight ?? state.coreChainLockedHeight, + assetLockTxBlockHeight: progress.blockHeight, + coreChainLockedHeight: progress.chainLockedHeight, }; } diff --git a/src/utils/fetch-json.ts b/src/utils/fetch-json.ts new file mode 100644 index 0000000..721d7c4 --- /dev/null +++ b/src/utils/fetch-json.ts @@ -0,0 +1,21 @@ +/** Bound both response headers and body; forward cancellation to fetch. */ +export async function fetchJson( + url: string, + init: RequestInit = {}, + timeoutMs = 8000 +): Promise { + const controller = new AbortController(); + const abort = () => controller.abort(); + const signal = init.signal; + if (signal?.aborted) abort(); + signal?.addEventListener('abort', abort, { once: true }); + const timer = setTimeout(abort, timeoutMs); + try { + const response = await fetch(url, { ...init, signal: controller.signal }); + if (!response.ok) throw new Error(`API error: ${response.status} ${response.statusText}`); + return await response.json(); + } finally { + clearTimeout(timer); + signal?.removeEventListener('abort', abort); + } +} diff --git a/src/utils/sleep.ts b/src/utils/sleep.ts index 4ee010d..647a722 100644 --- a/src/utils/sleep.ts +++ b/src/utils/sleep.ts @@ -10,14 +10,12 @@ export function abortableSleep(ms: number, signal?: AbortSignal): Promise resolve(); return; } - const timer = setTimeout(resolve, ms); - signal?.addEventListener( - 'abort', - () => { - clearTimeout(timer); - resolve(); - }, - { once: true } - ); + const finish = (): void => { + clearTimeout(timer); + signal?.removeEventListener('abort', finish); + resolve(); + }; + const timer = setTimeout(finish, ms); + signal?.addEventListener('abort', finish, { once: true }); }); }