diff --git a/README.md b/README.md index 88cd2d09..95927732 100644 --- a/README.md +++ b/README.md @@ -109,9 +109,9 @@ To build from a worktree instead of `../bitkit-android` / `../bitkit-ios` (dirty --- -### Spark receive on local regtest +### Spark tests on local regtest -The `@spark_1` spec uses the Spark operators and Lightning payer from the repository's `BITKIT_DOCKER_REVISION`. Start the fixture before building either app so both builds embed the fixture's Spark settings. +The Spark spec uses the operators, Lightning node, and Bitcoin miner from `BITKIT_DOCKER_REVISION`. It covers receiving Lightning into Spark (`@spark_1`), sending Lightning from Spark (`@spark_2`), and confirming an on-chain deposit (`@spark_3`). Start the fixture before building either app so both builds embed its Spark settings. ```bash ./scripts/local-backend spark-up @@ -125,10 +125,10 @@ BACKEND=local ./scripts/build-ios-sim.sh ./scripts/run-spark-e2e.sh ios ``` -Use a dedicated emulator and simulator because the test reinstalls Bitkit and creates a new wallet. Set `SIMULATOR_NAME` to the dedicated simulator's unique name and `SIMULATOR_OS_VERSION` to its installed runtime so Appium requests the matching capability. The Docker images build from source on the first start. Run `./scripts/local-backend spark-down` to stop the Spark services when done. +Use a dedicated emulator and simulator because each case reinstalls Bitkit and creates a new wallet. Set `SIMULATOR_NAME` to the dedicated simulator's unique name and `SIMULATOR_OS_VERSION` to its installed runtime so Appium requests the matching capability. The Docker images build from source on the first start. Run `./scripts/local-backend spark-down` to stop the Spark services when done. -The **Local E2E Nightly** workflows run this case on Android and iOS at 05:35 UTC against E2E `main`. To run it on demand, dispatch the workflow in the app repository. Set `e2e_branch` if the spec is on another ref. The job makes up to three attempts and uploads logs and diagnostics by attempt. -CI caches the Spark images by Docker pin and runner architecture. The iOS workflow prepares ARM64 images and wallet settings on hosted Linux, then builds the app on hosted macOS. The self-hosted Mac reuses matching Docker images when available, starts a fresh fixture, and verifies its wallet settings before running the test. +The **Local E2E Nightly** workflows run the Spark spec on Android and iOS at 05:35 UTC against E2E `main`. To run it on demand, dispatch the workflow in the app repository. Set `e2e_branch` if the spec is on another ref. The job makes up to three attempts and uploads logs and diagnostics by attempt. +CI caches the Spark images by Docker pin and runner architecture. The iOS workflow prepares ARM64 images and wallet settings on hosted Linux, then builds the app on hosted macOS. The self-hosted Mac reuses matching Docker images when available, starts a fresh fixture, and verifies its wallet settings before running the tests. ### USDT local execution diff --git a/scripts/local-backend b/scripts/local-backend index a4958648..2bb859be 100755 --- a/scripts/local-backend +++ b/scripts/local-backend @@ -251,6 +251,54 @@ case "${1:-}" in } spark pay "$2" ;; + spark-invoice) + check_revision + [[ "$#" -eq 2 && "${2:-}" =~ ^[1-9][0-9]*$ ]] || { + echo 'Usage: ./scripts/local-backend spark-invoice ' >&2 + exit 2 + } + spark invoice "$2" | jq -e '{invoice, payment_hash}' + ;; + spark-payment-details) + check_revision + [[ "$#" -eq 2 && "${2:-}" =~ ^[a-f0-9]{64}$ ]] || { + echo 'Usage: ./scripts/local-backend spark-payment-details ' >&2 + exit 2 + } + compose --profile spark exec -T spark-ldk-alice ldk-server-cli \ + --config /local/ldk-alice.toml --base-url localhost:3536 get-payment-details "$2" | + jq -e '.payment | {amount_msat, direction, status}' + ;; + spark-fund) + check_revision + [[ "$#" -eq 3 && "${2:-}" =~ ^bcrt1[qp][02-9ac-hj-np-z]+$ && "${3:-}" =~ ^[1-9][0-9]*$ ]] || { + echo 'Usage: ./scripts/local-backend spark-fund ' >&2 + exit 2 + } + funding="$(spark send "$2" "$3" -m 0)" + [[ "$funding" =~ ([a-f0-9]{64})$ ]] || { + echo 'The Spark miner did not report a transaction ID.' >&2 + exit 1 + } + printf '%s\n' "${BASH_REMATCH[1]}" + ;; + spark-tx) + check_revision + [[ "$#" -eq 2 && "${2:-}" =~ ^[a-f0-9]{64}$ ]] || { + echo 'Usage: ./scripts/local-backend spark-tx ' >&2 + exit 2 + } + # The pinned CLI prints the transaction first, followed by its output spend records. + spark tx "$2" | jq -cse '.[0]' + ;; + spark-mine) + check_revision + [[ "$#" -eq 1 ]] || { + echo 'Usage: ./scripts/local-backend spark-mine' >&2 + exit 2 + } + spark mine 1 + ;; spark-down) check_revision spark down @@ -279,7 +327,7 @@ case "${1:-}" in exec "$@" ;; *) - echo 'Usage: ./scripts/local-backend {prepare|path|up|down|ps|logs|github-env|run |spark-pack |spark-up|spark-image-fingerprint|spark-init-env|spark-env|spark-pay |spark-down|spark-logs}' >&2 + echo 'Usage: ./scripts/local-backend {prepare|path|up|down|ps|logs|github-env|run |spark-pack |spark-up|spark-image-fingerprint|spark-init-env|spark-env|spark-pay |spark-invoice |spark-payment-details |spark-fund
|spark-tx |spark-mine|spark-down|spark-logs}' >&2 exit 2 ;; esac diff --git a/scripts/run-spark-e2e.sh b/scripts/run-spark-e2e.sh index 9c00f5b0..5506d1c8 100755 --- a/scripts/run-spark-e2e.sh +++ b/scripts/run-spark-e2e.sh @@ -18,6 +18,6 @@ if [[ "$1" == android ]]; then done fi -# Each dedicated run must execute the payment even on a reused runner. +# Run fresh wallets on every attempt, including on a reused runner. exec ./scripts/local-backend run env -u CI BITKIT_LOCAL_SPARK=1 "./ci_run_$1.sh" \ - --spec ./test/specs/spark.e2e.ts --mochaOpts.grep '@spark_1\b' + --spec ./test/specs/spark.e2e.ts diff --git a/test/specs/spark.e2e.ts b/test/specs/spark.e2e.ts index 67f36a6d..574e7656 100644 --- a/test/specs/spark.e2e.ts +++ b/test/specs/spark.e2e.ts @@ -4,23 +4,43 @@ import { promisify } from 'node:util'; import { acknowledgeReceivedPayment, completeOnboarding, + dragOnElement, elementById, + elementByText, + enterAmount, + expectSavingsBalance, expectSpendingBalance, expectTextWithin, + formatSats, getAddressFromQRCode, getAmountUnder, + getClipboardPlaintext, getReceiveAddress, - multiTap, + getSavingsBalance, + getSpendingBalance, + handleOver50PercentAlert, swipeFullScreen, + tap, + tryDismissQuickPayIntroIfVisible, + waitForWalletHomeCondition, } from '../helpers/actions'; +import { enterGateAddress } from '../helpers/gate-actions'; import { doNavigationClose, openSettings } from '../helpers/navigation'; -import { tapAndExpect } from '../helpers/outcome'; +import { tapAndExpect, waitAndExpect } from '../helpers/outcome'; import { editGateLightningInvoice } from '../helpers/receive-invoice'; -import { reinstallApp } from '../helpers/setup'; +import { launchFreshApp, reinstallApp } from '../helpers/setup'; import { ciIt } from '../helpers/suite'; const runCommand = promisify(execFile); const describeSpark = process.env.BITKIT_LOCAL_SPARK === '1' ? describe : describe.skip; +const lightningFundingSats = 10_000; + +async function sparkFixture(...args: string[]): Promise { + const { stdout } = await runCommand(resolve(__dirname, '../../scripts/local-backend'), args, { + timeout: 120_000, + }); + return stdout.trim(); +} async function openSparkConnection() { await openSettings('advanced'); @@ -29,40 +49,264 @@ async function openSparkConnection() { { id: 'SparkConnection' }, { anyVisible: [{ id: 'SparkBalance' }, { id: 'SparkDepositAddress' }] } ); - if (!(await elementById('SparkBalance').isDisplayed())) { + // Android can expose a clipped balance row before its amount is on screen. + const balance = driver.isAndroid + ? $('//*[@resource-id="SparkBalance"]//*[@resource-id="MoneyText"]') + : elementById('SparkBalance'); + if (!(await balance.isDisplayed())) { await swipeFullScreen('up', { upStartYPercent: 0.68, upEndYPercent: 0.34 }); + await balance.waitForDisplayed(); + } +} + +async function receiveSparkLightning(amount = lightningFundingSats) { + const originalInvoice = await getReceiveAddress('lightning'); + await editGateLightningInvoice(); + await tapAndExpect({ id: 'ReceiveNumberPadTextField' }, { anyVisible: [{ id: 'N1' }] }); + await enterAmount(amount); + await tapAndExpect({ id: 'ReceiveNumberPadSubmit' }, { anyVisible: [{ id: 'ShowQrReceive' }] }); + await tapAndExpect({ id: 'ShowQrReceive' }, { anyVisible: [{ id: 'QRCode' }] }); + const invoice = await getAddressFromQRCode('lightning'); + expect(invoice).not.toBe(originalInvoice); + await swipeFullScreen('down'); + + await sparkFixture('spark-pay', invoice); + await acknowledgeReceivedPayment({ timeout: 90_000 }); + await expectFundedSparkWallet(amount); +} + +async function copySparkDepositAddress() { + const readClipboard = () => + driver.isIOS + ? driver.execute('mobile: getPasteboard', { + encoding: 'utf8', + }) + : getClipboardPlaintext(); + if (driver.isIOS) { + await driver.execute('mobile: setPasteboard', { content: '', encoding: 'utf8' }); + } + const oldClipboard = (await readClipboard()).trim(); + await tap('SparkDepositAddress'); + let address = ''; + await browser.waitUntil( + async () => { + address = (await readClipboard()).trim(); + return address !== oldClipboard && /^bcrt1[qp][02-9ac-hj-np-z]+$/.test(address); + }, + { + timeout: 15_000, + interval: 500, + timeoutMsg: 'Spark did not copy a fresh regtest deposit address', + } + ); + return address; +} + +async function getSparkDepositClaimFee(txid: string) { + const deposit = elementById('SparkDeposit'); + const claimFee = elementByText('Claim fee', 'exact'); + await browser.waitUntil( + async () => { + if ((await deposit.isDisplayed()) && (await claimFee.isDisplayed())) return true; + // On iOS the fixed transfer buttons sit below the details scroll view. + await swipeFullScreen('up', { upStartYPercent: 0.65, upEndYPercent: 0.35 }); + return false; + }, + { timeout: 90_000, interval: 1_500, timeoutMsg: 'Spark did not display the claimed deposit' } + ); + if (driver.isAndroid) { + const elementId = await elementById('SparkScrollView').elementId; + await browser.waitUntil( + async () => + (await driver.execute('mobile: scrollGesture', { + elementId, + direction: 'down', + percent: 1, + })) === false, + { timeout: 15_000, timeoutMsg: 'Could not reach the end of the Spark deposit history' } + ); + // On a fresh wallet the history starts below the balance and ends at the bottom of this view. + // Seeing both boundaries makes the row count include the entire history on Android. + await expect(elementById('SparkBalance')).toBeDisplayed(); + } + const depositRows = $$( + '//*[@resource-id="SparkDeposit"] | //XCUIElementTypeButton[@name="SparkDeposit"]' + ); + expect(await depositRows.length).toBe(1); + await expectTextWithin('SparkDeposit', txid.slice(0, 8)); + + const feeAmount = $( + driver.isIOS + ? '//XCUIElementTypeStaticText[@label="Claim fee"]/following-sibling::XCUIElementTypeStaticText[1]' + : '//*[@text="Claim fee"]/following-sibling::*[@resource-id="MoneyText"][1]' + ); + const digits = (await feeAmount.getText()).replace(/[^\d]/g, ''); + if (!digits) throw new Error('The Spark deposit claim fee was not displayed in sats'); + return Number(digits); +} + +async function waitForSparkDepositTransaction(txid: string, status: RegExp) { + await browser.waitUntil( + async () => { + try { + const transaction = JSON.parse(await sparkFixture('spark-tx', txid)); + return status.test(transaction.status); + } catch (error) { + if (String(error).includes('did not answer')) return false; + throw error; + } + }, + { + timeout: 30_000, + interval: 1_000, + timeoutMsg: `Spark deposit ${txid} did not reach ${status}`, + } + ); +} + +async function waitForSparkWalletHome(condition: () => Promise) { + const backupLater = elementById('BackupIntroViewCancel'); + const quickPay = elementById( + driver.isAndroid ? 'QuickpayIntro-button' : 'QuickpayIntroDescription' + ); + const deadline = Date.now() + 90_000; + while (Date.now() < deadline) { + let backupVisible = false; + let quickPayVisible = false; + let readySince: number | undefined; + await waitForWalletHomeCondition( + async () => { + backupVisible = await backupLater.isDisplayed(); + quickPayVisible = !backupVisible && (await quickPay.isDisplayed()); + if (backupVisible || quickPayVisible) return true; + if (!(await condition())) { + readySince = undefined; + return false; + } + // Funded-wallet reminders can appear two seconds after Home appears. + readySince ??= Date.now(); + return Date.now() - readySince >= 2_500; + }, + { timeout: Math.max(1, deadline - Date.now()) } + ); + if (backupVisible) { + if (await backupLater.isDisplayed()) await backupLater.click(); + } else if (quickPayVisible) { + await tryDismissQuickPayIntroIfVisible(); + } else { + return; + } } + throw new Error('Spark wallet home did not settle'); +} + +async function expectFundedSparkWallet(amount: number) { + await waitForSparkWalletHome(async () => { + return ( + (await elementById('ActivitySpending').isDisplayed()) && + (await elementById('ActivitySavings').isDisplayed()) && + (await getSpendingBalance()) === amount && + (await getSavingsBalance()) === 0 + ); + }); } describeSpark('Spark on local regtest', () => { - ciIt('@spark_1 - Receive a Lightning payment into Spark', async () => { + beforeEach(async () => { await reinstallApp(); await completeOnboarding(); - await openSparkConnection(); expect(await getAmountUnder('SparkBalance')).toBe(0); + }); + + ciIt('@spark_1 - Receive a Lightning payment into Spark', async () => { + await doNavigationClose(); + await receiveSparkLightning(); + await expectTextWithin('ActivityShort-0', '+'); + await expectTextWithin('ActivityShort-0', formatSats(lightningFundingSats)); + + await openSparkConnection(); + expect(await getAmountUnder('SparkBalance')).toBe(lightningFundingSats); + }); + + ciIt('@spark_2 - Send a Lightning payment from Spark', async () => { + const sendSats = 1_000; + // The pinned provider charges 2 sats plus 4,000 ppm and does not support wallet leaf swaps. + // Fund the exact total so paying Alice does not require breaking a leaf to make change. + const expectedFeeSats = 6; + const fundingSats = sendSats + expectedFeeSats; await doNavigationClose(); + await receiveSparkLightning(fundingSats); - const originalInvoice = await getReceiveAddress('lightning'); - await editGateLightningInvoice(); - await tapAndExpect({ id: 'ReceiveNumberPadTextField' }, { anyVisible: [{ id: 'N1' }] }); - await tapAndExpect({ id: 'N1' }, { anyVisible: [{ id: 'N0' }] }); - await multiTap('N0', 4); - await tapAndExpect({ id: 'ReceiveNumberPadSubmit' }, { anyVisible: [{ id: 'ShowQrReceive' }] }); - await tapAndExpect({ id: 'ShowQrReceive' }, { anyVisible: [{ id: 'QRCode' }] }); - const invoice = await getAddressFromQRCode('lightning'); - expect(invoice).not.toBe(originalInvoice); - await swipeFullScreen('down'); - - await runCommand(resolve(__dirname, '../../scripts/local-backend'), ['spark-pay', invoice], { - timeout: 120_000, + const { invoice, payment_hash: paymentHash } = JSON.parse( + await sparkFixture('spark-invoice', String(sendSats)) + ); + await waitForSparkWalletHome(() => elementById('Send').isDisplayed()); + await enterGateAddress(invoice); + await expectTextWithin('ReviewAmount-primary', formatSats(sendSats)); + await dragOnElement('GRAB', 'right', 0.95); + await handleOver50PercentAlert(); + await waitAndExpect({ + anyVisible: [{ id: 'SendSuccess' }, { id: 'SendFailure' }], + timeout: 90_000, }); - await acknowledgeReceivedPayment({ timeout: 90_000 }); - await expectSpendingBalance(10_000); - await expectTextWithin('ActivityShort-0', '+'); - await expectTextWithin('ActivityShort-0', '10 000'); + await expect(elementById('SendSuccess')).toBeDisplayed(); + await tapAndExpect({ id: 'Close' }, { anyVisible: [{ id: 'TotalBalance-primary' }] }); + + await browser.waitUntil( + async () => { + const payment = JSON.parse(await sparkFixture('spark-payment-details', paymentHash)); + return ( + payment.status === 'SUCCEEDED' && + payment.direction === 'INBOUND' && + Number(payment.amount_msat) === sendSats * 1_000 + ); + }, + { + timeout: 60_000, + interval: 2_000, + timeoutMsg: 'The fixture recipient did not settle the Spark payment', + } + ); + + await expectTextWithin('ActivityShort-0', '-'); + await expectTextWithin('ActivityShort-0', 'Sent'); + await expectTextWithin('ActivityShort-1', '+'); + await expectTextWithin('ActivityShort-1', formatSats(fundingSats)); + await expect(elementById('ActivityShort-2')).not.toExist(); + await tapAndExpect({ id: 'ActivityShort-0' }, { anyVisible: [{ id: 'ActivityAmount' }] }); + expect(await getAmountUnder('ActivityAmount')).toBe(sendSats); + expect(await getAmountUnder('ActivityFee')).toBe(expectedFeeSats); + await tapAndExpect({ id: 'NavigationBack' }, { anyVisible: [{ id: 'TotalBalance-primary' }] }); + await expectSpendingBalance(0); + await expectSavingsBalance(0); + await openSparkConnection(); + expect(await getAmountUnder('SparkBalance')).toBe(0); + }); + + ciIt('@spark_3 - Confirm an on-chain deposit into Spark', async () => { + const depositSats = 100_000; + const address = await copySparkDepositAddress(); + const txid = await sparkFixture('spark-fund', address, String(depositSats)); + + await waitForSparkDepositTransaction(txid, /^in the mempool$/); + const pending = JSON.parse(await sparkFixture('spark-tx', txid)); + expect(pending.status).toBe('in the mempool'); + expect(pending.outputs).toContainEqual({ address, value: depositSats }); + + // On the local provider the wallet can claim deposits before their first confirmation. + await sparkFixture('spark-mine'); + await waitForSparkDepositTransaction(txid, /^confirmed at /); + const feeSats = await getSparkDepositClaimFee(txid); + expect(feeSats).toBeLessThan(depositSats); + const creditedSats = depositSats - feeSats; + await doNavigationClose(); + await expectFundedSparkWallet(creditedSats); + await launchFreshApp(); + await expectFundedSparkWallet(creditedSats); await openSparkConnection(); - expect(await getAmountUnder('SparkBalance')).toBe(10_000); + expect(await getAmountUnder('SparkBalance')).toBe(creditedSats); + expect(await getSparkDepositClaimFee(txid)).toBe(feeSats); }); });