Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
104 changes: 104 additions & 0 deletions docs/rpc-dependency-review.md
Original file line number Diff line number Diff line change
@@ -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.<network>.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.
104 changes: 104 additions & 0 deletions e2e/rpc-outage.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
11 changes: 10 additions & 1 deletion scripts/check-build-artifacts.mjs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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');
80 changes: 80 additions & 0 deletions src/api/chainlock.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
Loading
Loading