diff --git a/.github/workflows/e2e-local-nightly.yml b/.github/workflows/e2e-local-nightly.yml new file mode 100644 index 000000000..c6bb7e443 --- /dev/null +++ b/.github/workflows/e2e-local-nightly.yml @@ -0,0 +1,323 @@ +name: Local E2E Nightly (iOS) + +on: + schedule: + - cron: "35 5 * * *" + workflow_dispatch: + inputs: + e2e_branch: + description: "Ref in synonymdev/bitkit-e2e-tests" + type: string + default: main + post_to_slack: + description: "Post Local E2E Nightly summary to Slack (#bitkit-staging-nightly)" + type: boolean + default: false + +permissions: + contents: read + +env: + TERM: xterm-256color + FORCE_COLOR: 1 + GIT_LFS_SKIP_SMUDGE: "1" + +concurrency: + group: bitkit-local-e2e-nightly-ios + cancel-in-progress: false + +jobs: + spark-images: + runs-on: ubuntu-24.04-arm + timeout-minutes: 80 + outputs: + e2e-sha: ${{ steps.e2e.outputs.sha }} + spark-config: ${{ steps.settings.outputs.SPARK_LOCAL_CONFIG_B64 }} + spark-chain-url: ${{ steps.settings.outputs.SPARK_LOCAL_CHAIN_URL }} + image-fingerprint: ${{ steps.settings.outputs.image-fingerprint }} + steps: + - uses: actions/checkout@v7 + with: + repository: synonymdev/bitkit-e2e-tests + ref: ${{ inputs.e2e_branch || 'main' }} + persist-credentials: false + + - name: Record shared E2E revision + id: e2e + run: | + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + if [[ "$(git symbolic-ref --quiet HEAD)" == refs/heads/main ]]; then + echo 'save-cache=true' >> "$GITHUB_OUTPUT" + fi + + - name: Restore pinned Spark fixture images + id: images + uses: actions/cache/restore@v6 + with: + path: ${{ runner.temp }}/spark-images.tar + key: spark-fixture-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('BITKIT_DOCKER_REVISION') }} + + - name: Package pinned Spark fixture images + if: steps.images.outputs.cache-hit != 'true' + run: ./scripts/local-backend spark-pack "$RUNNER_TEMP/spark-images.tar" + + - name: Generate pinned Spark app settings + id: settings + run: | + docker image load --quiet --input "$RUNNER_TEMP/spark-images.tar" + ./scripts/local-backend spark-init-env >> "$GITHUB_OUTPUT" + fingerprint="$(./scripts/local-backend spark-image-fingerprint)" + echo "image-fingerprint=$fingerprint" >> "$GITHUB_OUTPUT" + + - name: Save pinned Spark fixture images + if: steps.images.outputs.cache-hit != 'true' && steps.e2e.outputs.save-cache == 'true' + continue-on-error: true + uses: actions/cache/save@v6 + with: + path: ${{ runner.temp }}/spark-images.tar + key: ${{ steps.images.outputs.cache-primary-key }} + + - name: Compress the fixture archive for transfer + run: gzip -1 -c "$RUNNER_TEMP/spark-images.tar" > "$RUNNER_TEMP/spark-images.tar.gz" + + - uses: actions/upload-artifact@v7 + with: + name: spark-fixture-images + path: ${{ runner.temp }}/spark-images.tar.gz + if-no-files-found: error + compression-level: 0 + retention-days: 3 + + build-spark-ios: + needs: spark-images + runs-on: macos-26 + timeout-minutes: 45 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: actions/checkout@v7 + with: + repository: synonymdev/bitkit-e2e-tests + ref: ${{ needs.spark-images.outputs.e2e-sha }} + path: bitkit-e2e-tests + persist-credentials: false + + - name: Set up Xcode + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: "26.6" + + - name: Install xcbeautify + run: brew install xcbeautify + + - name: Swift packages + uses: ./.github/actions/swift-packages + + - name: Build iOS Spark app + working-directory: bitkit-e2e-tests + env: + IOS_ROOT: ${{ github.workspace }} + IOS_SIMULATOR_ARCH: arm64 + SPARK_LOCAL_CONFIG_B64: ${{ needs.spark-images.outputs.spark-config }} + SPARK_LOCAL_CHAIN_URL: ${{ needs.spark-images.outputs.spark-chain-url }} + run: | + test -n "$SPARK_LOCAL_CONFIG_B64" + test -n "$SPARK_LOCAL_CHAIN_URL" + ./scripts/build-ios-sim.sh + tar -C aut -czf "$RUNNER_TEMP/spark-ios-app.tar.gz" Bitkit.app + + - uses: actions/upload-artifact@v7 + with: + name: spark-ios-app + path: ${{ runner.temp }}/spark-ios-app.tar.gz + if-no-files-found: error + compression-level: 0 + retention-days: 3 + + e2e-spark: + needs: [spark-images, build-spark-ios] + runs-on: [self-hosted, macOS] + timeout-minutes: 120 + env: + SIMULATOR_NAME: "iPhone 17" + SIMULATOR_OS_VERSION: "27.2" + # The PR suite uses the same fixed Bitcoin and Electrum ports on this Mac. + COMPOSE_PROJECT_NAME: docker + steps: + - uses: actions/checkout@v7 + with: + repository: synonymdev/bitkit-e2e-tests + ref: ${{ needs.spark-images.outputs.e2e-sha }} + path: bitkit-e2e-tests + persist-credentials: false + + - uses: actions/setup-node@v7 + with: + node-version: 22 + cache: npm + cache-dependency-path: bitkit-e2e-tests/package-lock.json + + - name: Install Appium dependencies + working-directory: bitkit-e2e-tests + run: npm ci + + - name: Check the local Spark images + id: local-images + working-directory: bitkit-e2e-tests + env: + SPARK_IMAGE_FINGERPRINT: ${{ needs.spark-images.outputs.image-fingerprint }} + run: | + if [[ "$RUNNER_ARCH" != ARM64 ]]; then + echo "::error::The Spark fixture archive requires an ARM64 Mac runner." + exit 1 + fi + test -n "$SPARK_IMAGE_FINGERPRINT" + ./scripts/local-backend prepare + if actual="$(./scripts/local-backend spark-image-fingerprint 2>/dev/null)" && + [[ "$actual" == "$SPARK_IMAGE_FINGERPRINT" ]]; then + echo 'Reusing the exact pinned Spark images on this runner.' + echo 'match=true' >> "$GITHUB_OUTPUT" + fi + + - uses: actions/download-artifact@v8 + if: steps.local-images.outputs.match != 'true' + with: + name: spark-fixture-images + path: ${{ runner.temp }} + + - name: Load the pinned Spark images + if: steps.local-images.outputs.match != 'true' + run: | + docker image load --input "$RUNNER_TEMP/spark-images.tar.gz" + rm -f "$RUNNER_TEMP/spark-images.tar.gz" + + - uses: actions/download-artifact@v8 + with: + name: spark-ios-app + path: ${{ runner.temp }} + + - name: Unpack the hosted simulator build + working-directory: bitkit-e2e-tests + run: | + mkdir -p aut + tar -C aut -xzf "$RUNNER_TEMP/spark-ios-app.tar.gz" + rm -f "$RUNNER_TEMP/spark-ios-app.tar.gz" + + - name: Start pinned Spark fixture + id: spark + working-directory: bitkit-e2e-tests + env: + SPARK_IMAGE_FINGERPRINT: ${{ needs.spark-images.outputs.image-fingerprint }} + SPARK_LOCAL_CONFIG_B64: ${{ needs.spark-images.outputs.spark-config }} + SPARK_LOCAL_CHAIN_URL: ${{ needs.spark-images.outputs.spark-chain-url }} + run: | + (cd "$(./scripts/local-backend path)" && docker compose --profile spark down --remove-orphans -v) + ./scripts/local-backend spark-up + expected="$(printf 'SPARK_LOCAL_CONFIG_B64=%s\nSPARK_LOCAL_CHAIN_URL=%s' "$SPARK_LOCAL_CONFIG_B64" "$SPARK_LOCAL_CHAIN_URL")" + if [[ "$(./scripts/local-backend spark-env)" != "$expected" ]]; then + echo "::error::The running Spark fixture differs from the simulator build settings." + exit 1 + fi + + - name: Run E2E tests (attempt 1) + continue-on-error: true + id: test1 + working-directory: bitkit-e2e-tests + run: ./scripts/run-spark-e2e.sh ios + env: + RECORD_VIDEO: true + ATTEMPT: 1 + + - name: Collect Spark logs after attempt 1 + if: steps.test1.outcome == 'failure' + continue-on-error: true + working-directory: bitkit-e2e-tests + run: | + mkdir -p artifacts/attempt-1 + ./scripts/local-backend spark-logs --tail 200 > artifacts/attempt-1/spark-docker.log 2>&1 + + - name: Run E2E tests (attempt 2) + continue-on-error: true + if: steps.test1.outcome != 'success' + id: test2 + working-directory: bitkit-e2e-tests + run: ./scripts/run-spark-e2e.sh ios + env: + RECORD_VIDEO: true + ATTEMPT: 2 + + - name: Collect Spark logs after attempt 2 + if: steps.test2.outcome == 'failure' + continue-on-error: true + working-directory: bitkit-e2e-tests + run: | + mkdir -p artifacts/attempt-2 + ./scripts/local-backend spark-logs --tail 200 > artifacts/attempt-2/spark-docker.log 2>&1 + + - name: Run E2E tests (attempt 3) + if: steps.test1.outcome != 'success' && steps.test2.outcome != 'success' + id: test3 + working-directory: bitkit-e2e-tests + run: ./scripts/run-spark-e2e.sh ios + env: + RECORD_VIDEO: true + ATTEMPT: 3 + + - name: Collect Spark logs + if: failure() + working-directory: bitkit-e2e-tests + run: | + mkdir -p artifacts + ./scripts/local-backend spark-logs --tail 200 > artifacts/spark-docker.log 2>&1 || true + + - name: Stop Spark fixture + if: always() && steps.spark.outcome != 'skipped' + working-directory: bitkit-e2e-tests + run: cd "$(./scripts/local-backend path)" && docker compose --profile spark down --remove-orphans -v + + - name: Remove the imported archives + if: always() + run: rm -f "$RUNNER_TEMP/spark-images.tar.gz" "$RUNNER_TEMP/spark-ios-app.tar.gz" + + # Preserve logs and recordings from failed attempts even when a retry passes. + - uses: actions/upload-artifact@v7 + if: always() + with: + name: spark-ios-${{ github.run_number }} + path: bitkit-e2e-tests/artifacts/ + retention-days: 7 + + slack-report: + if: >- + always() && + (github.event_name == 'schedule' || + (github.event_name == 'workflow_dispatch' && inputs.post_to_slack == true)) + needs: [spark-images, build-spark-ios, e2e-spark] + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + steps: + - name: Checkout shared Slack reporter + uses: actions/checkout@v7 + with: + repository: synonymdev/bitkit-e2e-tests + ref: main + persist-credentials: false + + - name: Post Slack summary + run: python3 scripts/slack_summary.py e2e-local-nightly + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL_STAGING }} + PLATFORM: ios + LOCAL_NIGHTLY_RESULT: >- + ${{ contains(needs.*.result, 'failure') && 'failure' || + contains(needs.*.result, 'cancelled') && 'cancelled' || needs.e2e-spark.result }} + SPARK_IMAGES_RESULT: ${{ needs.spark-images.result }} + BUILD_RESULT: ${{ needs.build-spark-ios.result }} + E2E_TESTS_REF: ${{ needs.spark-images.outputs.e2e-sha || inputs.e2e_branch || 'main' }} + E2E_TESTS_RESULT: ${{ needs.e2e-spark.result }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} diff --git a/.github/workflows/e2e-tests.yml b/.github/workflows/e2e-tests.yml index 6f7e32974..4ba1b1182 100644 --- a/.github/workflows/e2e-tests.yml +++ b/.github/workflows/e2e-tests.yml @@ -231,6 +231,8 @@ jobs: runs-on: [self-hosted, macOS] needs: [detect-changes, build-local, e2e-branch] env: + SIMULATOR_NAME: "iPhone 17" + SIMULATOR_OS_VERSION: "27.2" # Reuse the legacy project so reset also clears containers left after a ref switch. COMPOSE_PROJECT_NAME: docker # Match the legacy fixture for the iOS manual channel funding Max case. @@ -323,7 +325,8 @@ jobs: run: | if [ -x ./scripts/local-backend ]; then ./scripts/local-backend prepare - ./scripts/local-backend down --remove-orphans -v -t 300 + # Include services left by an interrupted Spark nightly on this Mac. + COMPOSE_PROFILES=spark ./scripts/local-backend down --remove-orphans -v -t 300 ./scripts/local-backend up ./scripts/local-backend github-env >> "$GITHUB_ENV" else @@ -351,7 +354,7 @@ jobs: - name: Clear iOS Simulator environment run: | xcrun simctl shutdown all || true - xcrun simctl erase "iPhone 17" || true + xcrun simctl erase "$SIMULATOR_NAME" || true defaults write com.apple.iphonesimulator DisableAllNotifications -bool true - name: Run E2E Tests 1 (${{ matrix.shard.name }}) @@ -396,7 +399,7 @@ jobs: working-directory: bitkit-e2e-tests run: | if [ -x ./scripts/local-backend ]; then - ./scripts/local-backend down --remove-orphans -v || true + COMPOSE_PROFILES=spark ./scripts/local-backend down --remove-orphans -v || true else (cd docker && docker compose --profile trezor down --remove-orphans -v) || true fi diff --git a/Bitkit/Constants/Env.swift b/Bitkit/Constants/Env.swift index f0507dcf7..3b848e994 100644 --- a/Bitkit/Constants/Env.swift +++ b/Bitkit/Constants/Env.swift @@ -109,6 +109,11 @@ enum Env { isE2E && e2eBackend == "local" } + static var localSparkSettings: (configBase64: String?, chainURL: String?) { + guard isDebug, isLocalE2EBackend, network == .regtest else { return (nil, nil) } + return (infoPlistValue("SPARK_LOCAL_CONFIG_B64"), infoPlistValue("SPARK_LOCAL_CHAIN_URL")) + } + private static var e2eLocalHost: String { configValue("E2E_LOCAL_HOST") ?? "127.0.0.1" } @@ -222,22 +227,42 @@ enum Env { } /// Esplora REST API Spark reads the chain from and broadcasts through, in place of the SDK's default - /// (mempool.space with blockstream as fallback on mainnet); nil keeps the default. On regtest a debug or E2E build - /// can point Spark at Bitkit's own chain with `SPARK_CHAIN_SERVICE_URL`, so a Savings deposit reaches it. - static func sparkChainServiceUrl(for network: LDKNode.Network) -> String? { + /// (mempool.space with blockstream as fallback on mainnet); nil keeps the default. A local E2E build uses its + /// pinned regtest fixture for both deposits and exits. + static func sparkChainServiceUrl( + for network: LDKNode.Network, + localRegtestURL: String? = localSparkSettings.chainURL, + configuredURL: String? = configValue("SPARK_CHAIN_SERVICE_URL") + ) -> String? { switch network { case .bitcoin: "https://bitkit.to/electrs" - default: configValue("SPARK_CHAIN_SERVICE_URL") + case .regtest: localRegtestURL ?? configuredURL + default: configuredURL } } static var electrumServerUrl: String { if isE2E, e2eBackend == "local" { - return "tcp://\(e2eLocalHost):60001" + return localElectrumServerUrl(host: e2eLocalHost) } return electrumServerUrl(for: network) } + /// The pinned fixture's Spark REST and Savings Electrum endpoints serve the same regtest. + static func sharesLocalSparkChain( + sparkURL: String, + nodeElectrumURL: String?, + hardwareElectrumURL: String, + fixtureHost: String = e2eLocalHost + ) -> Bool { + let electrumURL = localElectrumServerUrl(host: fixtureHost) + return sparkURL == "http://\(fixtureHost):23090/api" && nodeElectrumURL == electrumURL && hardwareElectrumURL == electrumURL + } + + private static func localElectrumServerUrl(host: String) -> String { + "tcp://\(host):60001" + } + /// Whether a Paykit payment may route through a Pubky Swaps provider when no balance reaches the contact's /// endpoints. Regtest debug builds with `PUBKY_SWAPS_ROUTES=true` only. static var isPubkySwapsRouteEnabled: Bool { diff --git a/Bitkit/Info.plist b/Bitkit/Info.plist index a33a05f78..ccc26042b 100644 --- a/Bitkit/Info.plist +++ b/Bitkit/Info.plist @@ -55,6 +55,10 @@ $(E2E_LOCAL_HOST) E2E_NETWORK $(E2E_NETWORK) + SPARK_LOCAL_CONFIG_B64 + $(SPARK_LOCAL_CONFIG_B64) + SPARK_LOCAL_CHAIN_URL + $(SPARK_LOCAL_CHAIN_URL) TREZOR_BRIDGE $(TREZOR_BRIDGE) TREZOR_BRIDGE_URL diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 0a02b6497..a147eb664 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -143,7 +143,18 @@ final class SparkManager: ChannelFreeLightningRail { /// Whether savings or a hardware wallet can fund Spark: its deposit goes out on Bitkit's chain, which Spark must read. var canFundFromChain: Bool { - isReady && Self.readsBitkitChain(network: Env.network, chainServiceUrl: Env.sparkChainServiceUrl(for: Env.network)) + isReady && readsSavingsChain + } + + var readsSavingsChain: Bool { + if let fixtureURL = Env.localSparkSettings.chainURL { + return Env.sharesLocalSparkChain( + sparkURL: fixtureURL, + nodeElectrumURL: LightningService.shared.activeElectrumServerUrl, + hardwareElectrumURL: OnChainHwService.getElectrumUrl() + ) + } + return Self.readsBitkitChain(network: Env.network, chainServiceUrl: Env.sparkChainServiceUrl(for: Env.network)) } /// On mainnet both read Bitcoin; Spark's default regtest is its own chain, so a regtest deposit reaches Spark only @@ -451,14 +462,15 @@ final class SparkManager: ChannelFreeLightningRail { throw CustomServiceError.mnemonicNotFound } let passphrase = try Keychain.loadString(key: .bip39Passphrase(index: walletIndex)) - let config = Self.sdkConfig(network: network, apiKey: Env.breezApiKey, isExiting: isExiting) + var config = Self.sdkConfig(network: network, apiKey: Env.breezApiKey, isExiting: isExiting) + let chainAPI = try Self.configureLocalSpark(&config) let storageDir = Env.sparkStorage(walletIndex: walletIndex) try FileManager.default.createDirectory(at: storageDir, withIntermediateDirectories: true) // What `BreezSdkSpark.connect` builds, plus our own chain service where Env names one. let builder = SdkBuilder(config: config, seed: .mnemonic(mnemonic: mnemonic, passphrase: passphrase)) await builder.withDefaultStorage(storageDir: storageDir.path) if let chainServiceUrl = Env.sparkChainServiceUrl(for: Env.network) { - await builder.withRestChainService(url: chainServiceUrl, apiType: .esplora, credentials: nil) + await builder.withRestChainService(url: chainServiceUrl, apiType: chainAPI, credentials: nil) } syncedThisRun = false let connected = try await builder.build() @@ -475,6 +487,26 @@ final class SparkManager: ChannelFreeLightningRail { Self.notifyExitStateChanged() } + private nonisolated static func configureLocalSpark(_ config: inout BreezSdkSpark.Config) throws -> ChainApiType { + let settings = Env.localSparkSettings + if settings.configBase64 == nil, settings.chainURL == nil { + return .esplora + } + guard let encoded = settings.configBase64, + let data = Data(base64Encoded: encoded), + let json = String(data: data, encoding: .utf8), + settings.chainURL != nil + else { + throw NSError(domain: "LocalSparkConfiguration", code: 1, userInfo: [ + NSLocalizedDescriptionKey: "Local Spark requires a valid SPARK_LOCAL_CONFIG_B64 and SPARK_LOCAL_CHAIN_URL", + ]) + } + config.sparkConfig = try parseSparkConfig(json: json) + // The pinned regtest operators require anchored refunds. + config.watchtowerFeeLadderEnabled = false + return .mempoolSpace + } + /// The SDK config Bitkit connects with. nonisolated static func sdkConfig(network: BreezSdkSpark.Network, apiKey: String?, isExiting: Bool) -> BreezSdkSpark.Config { var config = defaultConfig(network: network) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 95f2b79ef..ef5e1e1c4 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -106,7 +106,19 @@ protocol NodeLifecycleService: AnyObject { class LightningService: NodeLifecycleService { private static let watchOnlyAccountHighestPreRevealedAddressIndex: UInt32 = 999 - private var node: Node? + private var configuredNode: (node: Node, electrumServerUrl: String)? + private var node: Node? { + setupLock.withLock { configuredNode?.node } + } + + var activeElectrumServerUrl: String? { + setupLock.withLock { configuredNode?.electrumServerUrl } + } + + private func releaseNode() { + setupLock.withLock { configuredNode = nil } + } + private let beforeNodeStopLock = NSLock() private var beforeNodeStopAction: (() async -> Void)? /// Runs before the node stops, while its wallet can still release what was prepared on it. @@ -207,7 +219,7 @@ class LightningService: NodeLifecycleService { ) async throws { // Guard against concurrent setup calls let shouldProceed: Bool = setupLock.withLock { - guard !isSettingUp && node == nil else { + guard !isSettingUp && configuredNode == nil else { Logger.debug("Node already setting up or already set up, skipping") return false } @@ -295,12 +307,13 @@ class LightningService: NodeLifecycleService { } try await ServiceQueue.background(.ldk) { - self.node = try builder.buildWithVssStore( + let node = try builder.buildWithVssStore( vssUrl: vssUrl, storeId: storeId, lnurlAuthServerUrl: lnurlAuthServerUrl, fixedHeaders: [:] ) + self.setupLock.withLock { self.configuredNode = (node, resolvedElectrumServerUrl) } } shouldReleaseLightningLock = false @@ -321,7 +334,7 @@ class LightningService: NodeLifecycleService { } catch { Logger.debug("Node was already stopped or failed to stop: \(error)") // Clear the node reference anyway - node = nil + releaseNode() try? StateLocker.unlock(.lightning) } } @@ -356,7 +369,7 @@ class LightningService: NodeLifecycleService { try await stop() } catch { Logger.error("Failed to stop node during recovery: \(error)") - node = nil + releaseNode() try? StateLocker.unlock(.lightning) } } @@ -438,7 +451,7 @@ class LightningService: NodeLifecycleService { try await ServiceQueue.background(.ldk) { try Self.stopReleasingFinishedNode(node.stop) } - self.node = nil + releaseNode() if clearEventCallback { self.clearEventCallback() diff --git a/Bitkit/Services/SparkExit/SparkExitBroadcaster.swift b/Bitkit/Services/SparkExit/SparkExitBroadcaster.swift index bc5ae86b6..57951f18b 100644 --- a/Bitkit/Services/SparkExit/SparkExitBroadcaster.swift +++ b/Bitkit/Services/SparkExit/SparkExitBroadcaster.swift @@ -149,7 +149,7 @@ struct EsploraSparkExitChain: SparkExitChain { /// On mainnet the chain service Spark connects with (`Env.sparkChainServiceUrl`) answers every read and takes /// broadcasts first, on its `/txs/package` (no `/v1`); the SDK's default hosts stay as broadcast fallbacks. On - /// regtest the chain service Spark connects with, `regtestChainServiceUrl` (`SPARK_CHAIN_SERVICE_URL`), does both, + /// regtest the configured chain service (including the local E2E fixture) does both, /// else the SDK's default host (breez spark-sdk `default_rest_chain_services`). static func network( _ network: BreezSdkSpark.Network, diff --git a/Bitkit/ViewModels/TransferViewModel.swift b/Bitkit/ViewModels/TransferViewModel.swift index bfef8b1a5..f9cbffd00 100644 --- a/Bitkit/ViewModels/TransferViewModel.swift +++ b/Bitkit/ViewModels/TransferViewModel.swift @@ -56,9 +56,7 @@ class TransferViewModel: ObservableObject { /// Sends Spark's balance to the address, refusing above the shown fee; tests replace it. var withdrawSpark: @MainActor (String, UInt64) async throws -> Void = { try await SparkManager.shared.withdrawAll(to: $0, maxFeeSats: $1) } /// Whether Spark reads Savings' chain, so its withdrawal reaches Savings; tests replace it. - var sparkReadsSavingsChain: @MainActor () -> Bool = { - SparkManager.readsBitkitChain(network: Env.network, chainServiceUrl: Env.sparkChainServiceUrl(for: Env.network)) - } + var sparkReadsSavingsChain: @MainActor () -> Bool = { SparkManager.shared.readsSavingsChain } /// How long the confirm screen waits for Spark's withdrawal fee before offering to retry; a full-balance quote can /// take minutes. diff --git a/Bitkit/Views/Settings/Advanced/SparkConnectionViews.swift b/Bitkit/Views/Settings/Advanced/SparkConnectionViews.swift index 726a1bd2e..e2b395ebb 100644 --- a/Bitkit/Views/Settings/Advanced/SparkConnectionViews.swift +++ b/Bitkit/Views/Settings/Advanced/SparkConnectionViews.swift @@ -172,6 +172,8 @@ struct SparkConnectionDetailView: View { detailRow(label: t("lightning__receiving_label"), value: t("lightning__spark_receiving_unlimited")) } amountRow(label: t("lightning__spending_label"), amount: spark.shownBalanceSats) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("SparkBalance") } if !spark.deposits.isEmpty { diff --git a/BitkitTests/SparkConfigTests.swift b/BitkitTests/SparkConfigTests.swift index d153d0ac6..d8b4f62fd 100644 --- a/BitkitTests/SparkConfigTests.swift +++ b/BitkitTests/SparkConfigTests.swift @@ -24,6 +24,29 @@ final class SparkConfigTests: XCTestCase { func testChainServiceIsBitkitElectrsOnMainnetOnly() { XCTAssertEqual(Env.sparkChainServiceUrl(for: .bitcoin), "https://bitkit.to/electrs") - XCTAssertNil(Env.sparkChainServiceUrl(for: .regtest)) + XCTAssertNil(Env.sparkChainServiceUrl(for: .regtest, localRegtestURL: nil, configuredURL: nil)) + } + + func testLocalChainServiceTakesPrecedenceOnlyOnRegtest() { + let local = "http://127.0.0.1:23090/api" + let configured = "https://example.com/electrs" + XCTAssertEqual(Env.sparkChainServiceUrl(for: .regtest, localRegtestURL: local, configuredURL: configured), local) + XCTAssertEqual(Env.sparkChainServiceUrl(for: .regtest, localRegtestURL: nil, configuredURL: configured), configured) + XCTAssertEqual(Env.sparkChainServiceUrl(for: .bitcoin, localRegtestURL: local, configuredURL: configured), "https://bitkit.to/electrs") + XCTAssertEqual(Env.sparkChainServiceUrl(for: .signet, localRegtestURL: local, configuredURL: configured), configured) + } + + func testLocalSparkSharesSavingsOnlyOnTheFixtureElectrumEndpoint() { + let spark = "http://127.0.0.1:23090/api" + let electrum = "tcp://127.0.0.1:60001" + func shares(_ sparkURL: String, _ node: String?, _ hardware: String) -> Bool { + Env.sharesLocalSparkChain(sparkURL: sparkURL, nodeElectrumURL: node, hardwareElectrumURL: hardware, fixtureHost: "127.0.0.1") + } + XCTAssertTrue(shares(spark, electrum, electrum)) + XCTAssertFalse(shares(spark, nil, electrum)) + XCTAssertFalse(shares(spark, "tcp://regtest.example:60001", electrum)) + XCTAssertFalse(shares(spark, electrum, "tcp://regtest.example:60001")) + XCTAssertFalse(shares(spark, "tcp://127.0.0.1:60002", electrum)) + XCTAssertFalse(shares("http://127.0.0.1:23091/api", electrum, electrum)) } } diff --git a/BitkitTests/SparkExitSweepTests.swift b/BitkitTests/SparkExitSweepTests.swift index 1664ec2cd..a74aa3bf1 100644 --- a/BitkitTests/SparkExitSweepTests.swift +++ b/BitkitTests/SparkExitSweepTests.swift @@ -931,9 +931,17 @@ final class SparkExitSweepTests: XCTestCase { offset += 34 XCTAssertEqual(signature.last, 0x01, "SIGHASH_ALL") - let preimage = le32(2) + dsha(outpoints.flatMap { $0 }) + dsha(Array(repeating: sequence, count: utxos.count).flatMap { $0 }) - + outpoints[i] + [0x19, 0x76, 0xA9, 0x14] + pubkeyHash + [0x88, 0xAC] + le64(utxo.value) + sequence - + dsha(outputs) + le32(0) + le32(1) + let scriptCode: [UInt8] = [0x19, 0x76, 0xA9, 0x14] + pubkeyHash + [0x88, 0xAC] + var preimage = le32(2) + preimage.append(contentsOf: dsha(outpoints.flatMap { $0 })) + preimage.append(contentsOf: dsha(Array(repeating: sequence, count: utxos.count).flatMap { $0 })) + preimage.append(contentsOf: outpoints[i]) + preimage.append(contentsOf: scriptCode) + preimage.append(contentsOf: le64(utxo.value)) + preimage.append(contentsOf: sequence) + preimage.append(contentsOf: dsha(outputs)) + preimage.append(contentsOf: le32(0)) + preimage.append(contentsOf: le32(1)) let digest = dsha(preimage) var parsed = secp256k1_ecdsa_signature() let der = Array(signature.dropLast())