diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj index ae80d4f6bf..929566e384 100644 --- a/Bitkit.xcodeproj/project.pbxproj +++ b/Bitkit.xcodeproj/project.pbxproj @@ -602,7 +602,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "if [ \"$CONFIGURATION\" = \"Release\" ] && [ -z \"$(echo \"${BREEZ_API_KEY}\" | tr -d ' ')\" ] && ! /usr/bin/security find-generic-password -a \"$USER\" -s BREEZ_API_KEY >/dev/null 2>&1; then\n echo \"error: BREEZ_API_KEY is empty. Store it in the keychain item BREEZ_API_KEY or set it in Secrets.xcconfig before a Release build or archive (Docs/RELEASE.md).\"\n exit 1\nfi\n"; + shellScript = "# Reads the keychain value only to test it for blank, so a missing, blank or unreadable (locked) item fails here,\n# before the target compiles. The value is never printed.\nif [ \"$CONFIGURATION\" = \"Release\" ] && [ -z \"$(echo \"${BREEZ_API_KEY}\" | tr -d ' ')\" ] \\\n && [ -z \"$(/usr/bin/security find-generic-password -a \"$USER\" -s BREEZ_API_KEY -w 2>/dev/null | tr -d '[:space:]')\" ]; then\n echo \"error: BREEZ_API_KEY is empty. Store it in the keychain item BREEZ_API_KEY (unlocked, not blank) or set it in Secrets.xcconfig before a Release build or archive (Docs/RELEASE.md).\"\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; B17C0F1A2EAE000000000003 /* Breez API Key From Keychain */ = { diff --git a/Bitkit/Managers/MoveToSparkManager.swift b/Bitkit/Managers/MoveToSparkManager.swift index ca27187549..f99199ca75 100644 --- a/Bitkit/Managers/MoveToSparkManager.swift +++ b/Bitkit/Managers/MoveToSparkManager.swift @@ -1,8 +1,12 @@ +import BitkitCore +import Combine import Foundation import LDKNode /// The amounts behind moving the channels' balance to Spark, kept apart so they can be tested without a node. enum MoveToSparkMath { + /// The move invoice's description. + static let invoiceDescription = "Move to Spark" /// Below this a move is not offered: what is left is about the routing fee. static let minMoveSats: UInt64 = 1000 /// The fee guessed for the first quote of a full move, as a share of the amount in parts per million. @@ -72,6 +76,15 @@ struct MoveToSparkQuote: Equatable { let feeSats: UInt64 } +@MainActor +extension LightningActivity { + /// The channel send of a move to Spark, which Activity shows as a transfer rather than a payment. Known by its payment + /// hash, so a paid outside invoice that happens to carry the move's description stays a payment. + var isMoveToSpark: Bool { + txType == .sent && MoveToSparkPayments.contains(id) + } +} + enum MoveToSparkError: Error { case nothingToMove case sparkUnavailable @@ -80,20 +93,91 @@ enum MoveToSparkError: Error { } /// The payments that move a channel balance to Spark, whose send and receive the app does not announce as payments. +/// Kept on disk until a wipe and in the metadata backup, so a move that settles after a relaunch, and its Activity row after +/// a restore, stay known as one. @MainActor enum MoveToSparkPayments { - private static var paymentHashes = Set() + private static let storageKey = "moveToSparkPaymentHashes" + static var defaults: UserDefaults = .standard { + didSet { cached = nil } + } + + /// Read once, as Activity asks for every row it draws. + private static var cached: [String: Double]? + /// Outside the main actor, so the backup observers can subscribe from anywhere. + nonisolated static var savedPublisher: AnyPublisher { + MoveToSparkPaymentsSaved.subject.eraseToAnyPublisher() + } + + static func insert(_ paymentHash: String, now: Date = Date()) { + var hashes = stored + hashes[paymentHash.lowercased()] = now.timeIntervalSince1970 + save(hashes) + MoveToSparkPaymentsSaved.subject.send() + } + + /// Sorted, so an unchanged store backs up byte for byte the same. + static func backupSnapshot() -> [String] { + stored.keys.sorted() + } - static func insert(_ paymentHash: String) { - paymentHashes.insert(paymentHash.lowercased()) + /// Adds the restored hashes to any already known. + static func restore(_ paymentHashes: [String]?, now: Date = Date()) { + guard let paymentHashes, !paymentHashes.isEmpty else { return } + var hashes = stored + for hash in paymentHashes where hashes[hash.lowercased()] == nil { + hashes[hash.lowercased()] = now.timeIntervalSince1970 + } + save(hashes) } static func contains(_ paymentHash: String?) -> Bool { - paymentHash.map { paymentHashes.contains($0.lowercased()) } ?? false + paymentHash.map { stored[$0.lowercased()] != nil } ?? false + } + + private static func save(_ hashes: [String: Double]) { + defaults.set(hashes, forKey: storageKey) + cached = hashes } static func removeAll() { - paymentHashes.removeAll() + defaults.removeObject(forKey: storageKey) + cached = nil + } + + private static var stored: [String: Double] { + if let cached { + return cached + } + let hashes = defaults.dictionary(forKey: storageKey) as? [String: Double] ?? [:] + cached = hashes + return hashes + } +} + +private enum MoveToSparkPaymentsSaved { + static let subject = PassthroughSubject() +} + +/// What a move quote needs from Spark and the channels, apart so the quote can be tested without either. +protocol MoveToSparkServices { + @MainActor var isSparkUsable: Bool { get } + func receiveInvoice(description: String, expirySecs: UInt32) async throws -> String + /// The routing fee LDK estimates for paying `bolt11` with `amountSats` over the channels only. + func estimateChannelFee(bolt11: String, amountSats: UInt64) async throws -> UInt64 +} + +struct LiveMoveToSparkServices: MoveToSparkServices { + @MainActor var isSparkUsable: Bool { + MoveToSparkMath.isSparkUsable(SparkManager.shared) + } + + func receiveInvoice(description: String, expirySecs: UInt32) async throws -> String { + try await SparkManager.shared.receive(amountSats: nil, description: description, expirySecs: expirySecs) + } + + func estimateChannelFee(bolt11: String, amountSats: UInt64) async throws -> UInt64 { + try await LightningService.shared.estimateRoutingFees(bolt11: bolt11, amountSats: amountSats, channelsOnly: true) } } @@ -134,7 +218,6 @@ final class MoveToSparkManager { /// Shared so a move and its outcome outlive the screen, which is rebuilt when the app is unlocked. static let shared = MoveToSparkManager() - private static let invoiceDescription = "Move to Spark" private static let invoiceExpirySecs: UInt32 = 3600 private static let maxQuoteRounds = 4 @@ -147,12 +230,15 @@ final class MoveToSparkManager { /// A swiped payment that has not settled yet; leaving the screen keeps it, so it is never quoted over. private var isMoveInFlight = false - private let lightningService: LightningService - private let spark: SparkManager + /// A move is kept for its result, so its screen stays reachable while the channels have nothing left to move. + var keepsMoveForItsResult: Bool { + keepsOutcome || isMoveInFlight + } + + private let services: any MoveToSparkServices - init() { - lightningService = .shared - spark = .shared + init(services: any MoveToSparkServices = LiveMoveToSparkServices()) { + self.services = services } /// Opens the screen: quotes a new move, unless a quote is still running or a move started earlier is still running @@ -266,20 +352,16 @@ final class MoveToSparkManager { guard wantedSats >= MoveToSparkMath.minMoveSats, MoveToSparkMath.hasMovableBalance(limitSats: limitSats) else { throw MoveToSparkError.nothingToMove } - guard MoveToSparkMath.isSparkUsable(spark) else { throw MoveToSparkError.sparkUnavailable } + guard services.isSparkUsable else { throw MoveToSparkError.sparkUnavailable } - let invoice = try await spark.receive( - amountSats: nil, - description: Self.invoiceDescription, - expirySecs: Self.invoiceExpirySecs - ) + let invoice = try await services.receiveInvoice(description: MoveToSparkMath.invoiceDescription, expirySecs: Self.invoiceExpirySecs) var amountSats = MoveToSparkMath.firstCandidate(wantedSats: wantedSats, limitSats: limitSats) var fitting: MoveToSparkQuote? // The first amount leaves room for a guessed fee; once the real fee is known, the amount grows to fit it. for _ in 0 ..< Self.maxQuoteRounds where amountSats >= MoveToSparkMath.minMoveSats { let estimateSats: UInt64 do { - estimateSats = try await lightningService.estimateRoutingFees(bolt11: invoice, amountSats: amountSats, channelsOnly: true) + estimateSats = try await services.estimateChannelFee(bolt11: invoice, amountSats: amountSats) } catch { if let fitting { return fitting diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index a147eb664d..17f5189371 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -383,6 +383,11 @@ final class SparkManager: ChannelFreeLightningRail { .bolt11Invoice(preferSpark: prefersSpark, completionTimeoutSecs: nil) } + /// The network name an exit backup carries: Spark's, which names Bitcoin's main network `mainnet`. + nonisolated static func exitBackupNetworkName(_ network: LDKNode.Network) -> String { + network == .bitcoin ? "\(BreezSdkSpark.Network.mainnet)" : "\(network)" + } + private static var sparkNetwork: BreezSdkSpark.Network? { switch Env.network { case .bitcoin: Env.breezApiKey == nil ? nil : .mainnet @@ -415,6 +420,7 @@ final class SparkManager: ChannelFreeLightningRail { // Registered before the first refresh marks Spark ready, so Lightning calls never see it ready while they // still go to LDK, even when that refresh or the activity sync fails. An emergency exit keeps it out. LightningService.shared.channelFreePaymentHistory = self + LightningService.shared.railSendExpired = { [weak self] hash in await self?.recordExpiredSend(paymentHash: hash) ?? false } if !isExiting { LightningService.shared.channelFreeRail = self } @@ -766,17 +772,19 @@ final class SparkManager: ChannelFreeLightningRail { nonisolated func lightningPayments() async throws -> [ChannelFreeRailPayment] { let payments = try await requireSdk().listPayments(request: ListPaymentsRequest(sortAscending: false)).payments - return payments.compactMap { payment in - guard case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { return nil } - return ChannelFreeRailPayment( - paymentHash: htlcDetails.paymentHash, - direction: payment.paymentType == .send ? .outbound : .inbound, - status: Self.ldkStatus(payment.status), - preimage: htlcDetails.preimage, - timestamp: payment.timestamp, - feeSats: Self.sats(payment.fees) - ) - } + return payments.compactMap(Self.railPayment) + } + + nonisolated static func railPayment(_ payment: Payment) -> ChannelFreeRailPayment? { + guard case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { return nil } + return ChannelFreeRailPayment( + paymentHash: htlcDetails.paymentHash, + direction: payment.paymentType == .send ? .outbound : .inbound, + status: ldkStatus(payment.status), + preimage: htlcDetails.preimage, + timestamp: payment.timestamp, + feeSats: sats(payment.fees) + ) } nonisolated func estimateRoutingFees(bolt11: String, amountSats: UInt64?) async throws -> UInt64 { @@ -830,6 +838,12 @@ final class SparkManager: ChannelFreeLightningRail { return SparkClaimOffer(txid: deposit.txid, vout: deposit.vout, quote: quote) } + /// Whether Spark still lists the deposit in `txid` as unclaimed. Asks no provider for a quote. + func isDepositUnclaimed(txid: String) async throws -> Bool { + let unclaimed = try await requireSdk().listUnclaimedDeposits(request: ListUnclaimedDepositsRequest()).deposits + return unclaimed.contains { $0.txid.caseInsensitiveCompare(txid) == .orderedSame } + } + /// Clears the fee cap an early claim of `offer` left on its deposit, back to the configured one, which never claims /// early (`sdkConfig`): a claim that names no cap clears the stored one before it is attempted. False when the cap /// may still be there: the call failed, or another claim of the deposit held it, which leaves the cap unchanged. @@ -843,14 +857,14 @@ final class SparkManager: ChannelFreeLightningRail { } } - /// Accepts the early claim of `offer` at its quoted fee. The fee ceiling stays on the deposit, so an early claim - /// not offered at this depth is still made once the provider offers it. - func claimEarly(_ offer: SparkClaimOffer) async throws -> SparkEarlyClaim { + /// Accepts the early claim of `offer`, capped at `ceilingSats`, the fee the user approved. The cap stays on the + /// deposit, so an early claim not offered at this depth is still made once the provider offers it within the cap. + func claimEarly(_ offer: SparkClaimOffer, ceilingSats: UInt64) async throws -> SparkEarlyClaim { guard case let .choice(earlyFeeSats, _, _, _) = offer.kind else { return .claimed } let request = ClaimDepositRequest( txid: offer.txid, vout: offer.vout, - maxFee: MaxFee(onchain: .fixed(amount: earlyFeeSats), proportionalPpm: nil) + maxFee: MaxFee(onchain: .fixed(amount: max(earlyFeeSats, ceilingSats)), proportionalPpm: nil) ) let claim: SparkEarlyClaim do { @@ -1477,15 +1491,31 @@ final class SparkManager: ChannelFreeLightningRail { } } - /// Whether restored exit data is still waiting for its import, after trying that again while connected. - func hasStagedExitState(walletIndex: Int) async -> Bool { + /// Tries the import of restored exit data again while connected, and says what became of it. + func importStagedExitState(walletIndex: Int) async -> SparkStagedExitImport { await importRestoredExitState(walletIndex: walletIndex) - return FileManager.default.fileExists(atPath: Env.sparkExitRestore(walletIndex: walletIndex).path) } - private func importRestoredExitState(walletIndex: Int) async { + /// The restored exit data waiting for Spark to import it, if any. Throws when a staged file can't be read. + func stagedExitState(walletIndex: Int) throws -> String? { let file = Env.sparkExitRestore(walletIndex: walletIndex) - guard let sdk, let data = FileManager.default.contents(atPath: file.path) else { return } + guard FileManager.default.fileExists(atPath: file.path) else { return nil } + return try String(decoding: Data(contentsOf: file), as: UTF8.self) + } + + /// Drops restored exit data Spark rejected, once the backup set a copy of it aside, unless newer data was staged + /// meanwhile. Read and delete run on the main actor with no suspension between them, as staging does. + func discardStagedExitState(_ exitState: String, walletIndex: Int) { + guard (try? stagedExitState(walletIndex: walletIndex)) == exitState else { return } + try? FileManager.default.removeItem(at: Env.sparkExitRestore(walletIndex: walletIndex)) + } + + @discardableResult + private func importRestoredExitState(walletIndex: Int) async -> SparkStagedExitImport { + let file = Env.sparkExitRestore(walletIndex: walletIndex) + guard FileManager.default.fileExists(atPath: file.path) else { return .nothingStaged } + // A staged file that can't be read now isn't absent: nothing may replace the remote copy until it is imported. + guard let data = FileManager.default.contents(atPath: file.path), let sdk else { return .pending } do { let imported = try await sdk.importUnilateralExitState( request: ImportUnilateralExitStateRequest(exitState: String(decoding: data, as: UTF8.self)) @@ -1496,8 +1526,10 @@ final class SparkManager: ChannelFreeLightningRail { + "'\(imported.skippedConflictingLeaves)' conflicting, '\(imported.skippedChains)' already held", context: "SparkManager" ) + return .imported } catch { Logger.error("Failed to import Spark exit data: \(error)", context: "SparkManager") + return SparkStagedExitImport(importError: error) } } @@ -1822,13 +1854,42 @@ final class SparkManager: ChannelFreeLightningRail { return result } - /// Payment hashes whose every Lightning send failed, so a hold on a channel retry can be released. - nonisolated static func failedSendHashes(_ payments: [Payment]) -> [String] { + /// Writes the Activity row of a send Spark never settled once its invoice expired: Spark's own attempt of it, not one + /// listed before it went out, or a failure of the stored pending send when Spark lists none. Returns whether it was saved. + private func recordExpiredSend(paymentHash: String) async -> Bool { + guard let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest()).payments else { return false } + let isEarlierAttempt = { LightningService.shared.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } + if let own = Self.expiredSendAttempt(payments, paymentHash: paymentHash, isEarlierAttempt: isEarlierAttempt) { + return await recordActivity(own) + } + return await (try? CoreService.shared.activity.failPendingLightningSend(id: paymentHash)) != nil + } + + /// The latest of Spark's attempts of a send whose invoice expired, none when Spark lists only attempts before it. + nonisolated static func expiredSendAttempt( + _ payments: [Payment], + paymentHash: String, + isEarlierAttempt: (_ hash: String, _ createdAt: UInt64) -> Bool + ) -> Payment? { + payments.filter { payment in + guard payment.paymentType == .send, case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details, + htlcDetails.paymentHash.caseInsensitiveCompare(paymentHash) == .orderedSame else { return false } + return !isEarlierAttempt(paymentHash, payment.timestamp) + }.max { $0.timestamp < $1.timestamp } + } + + /// Payment hashes whose every Lightning send failed, so a hold on a channel retry can be released. A failure of an + /// attempt before a send Spark hasn't settled yet doesn't count: that send may still pay the invoice. + nonisolated static func failedSendHashes( + _ payments: [Payment], + isEarlierAttempt: (_ hash: String, _ createdAt: UInt64) -> Bool = { _, _ in false } + ) -> [String] { var failed: [String] = [] var live: Set = [] for payment in payments where payment.paymentType == .send { guard case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { continue } if payment.status == .failed { + guard !isEarlierAttempt(htlcDetails.paymentHash, payment.timestamp) else { continue } failed.append(htlcDetails.paymentHash) } else { live.insert(htlcDetails.paymentHash) @@ -1847,17 +1908,22 @@ final class SparkManager: ChannelFreeLightningRail { } // A send that failed while the app was closed released no hold on a channel retry. await Self.releaseFailedSendHolds { try await self.requireSdk().listPayments(request: ListPaymentsRequest()).payments } + await LightningService.shared.endExpiredRailSendUncertainties() if let recordError { throw recordError } } - /// Releases the holds of the sends Spark's list shows failed. The list is read after the activities were recorded, - /// so a retry the user started meanwhile keeps its hold, as does one recorded or ending while the list is read. + /// Releases the holds of the sends Spark's list shows failed, first ending those it shows settled, so a later read + /// of Spark's history that fails doesn't hold them again. The list is read after the activities were recorded, so a + /// retry the user started meanwhile keeps its hold, as does one recorded or ending while the list is read. static func releaseFailedSendHolds(listPayments: () async throws -> [Payment]) async { let mark = LightningService.shared.attemptMark + let heldBefore = LightningService.shared.railSendHolds guard let latest = try? await listPayments() else { return } - for paymentHash in failedSendHashes(latest) { + LightningService.shared.settleListedRailSends(latest.compactMap(railPayment), heldBefore: heldBefore) + let isEarlierAttempt = { LightningService.shared.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } + for paymentHash in failedSendHashes(latest, isEarlierAttempt: isEarlierAttempt) { LightningService.shared.releaseRailAttempt(paymentHash: paymentHash, since: mark) } } @@ -1889,6 +1955,7 @@ final class SparkManager: ChannelFreeLightningRail { syncedThisRun = true await LightningService.shared.listRailSendsIfUnseeded() await refreshState() + await LightningService.shared.endExpiredRailSendUncertainties() await Self.settleAfterSync( since: Self.pendingContactWithdrawal?.startedAt ?? 0, hasSynced: { await self.hasSynced(after: $0) }, @@ -1902,7 +1969,7 @@ final class SparkManager: ChannelFreeLightningRail { await Self.handleSettledPayment( payment, record: { await self.recordActivity($0) }, - emit: { LightningService.shared.emitChannelFreeRailEvent($0) }, + emit: { LightningService.shared.emitChannelFreeRailEvent($0, paymentCreatedAt: payment.timestamp) }, refresh: { try await self.refresh() } ) case let .paymentPending(payment): @@ -1939,6 +2006,12 @@ final class SparkManager: ChannelFreeLightningRail { @discardableResult private func recordActivity(_ payment: Payment) async -> Bool { guard case let .lightning(description, invoice, _, htlcDetails, _, _, _, _) = payment.details else { return true } + // A failure of an attempt before a send Spark hasn't settled yet leaves that send's row pending. + if payment.paymentType == .send, payment.status == .failed, + LightningService.shared.isEarlierRailAttempt(paymentHash: htlcDetails.paymentHash, createdAt: payment.timestamp) + { + return true + } let details = PaymentDetails( id: htlcDetails.paymentHash, kind: .bolt11( @@ -2080,6 +2153,25 @@ struct SparkClaimFees: Equatable { let laterSats: UInt64 } +/// What became of restored exit data staged for import. +enum SparkStagedExitImport: Equatable { + case nothingStaged + case imported + /// Spark can never import it: an exit state version this SDK doesn't support, or a payload it can't parse. + case rejected + /// Not imported yet, as while Spark is not connected or the import failed for a reason that may pass. + case pending + + /// Spark runs the import without its operators, so only invalid input fails it every time. + init(importError: Error) { + if case SdkError.InvalidInput = importError { + self = .rejected + } else { + self = .pending + } + } +} + /// What accepting an early claim did. enum SparkEarlyClaim: Equatable { /// The claim settled, so the deposit is in the balance. diff --git a/Bitkit/Managers/TimedSheets/TimedSheetManager.swift b/Bitkit/Managers/TimedSheets/TimedSheetManager.swift index bc9cf01de0..de31396124 100644 --- a/Bitkit/Managers/TimedSheets/TimedSheetManager.swift +++ b/Bitkit/Managers/TimedSheets/TimedSheetManager.swift @@ -152,23 +152,28 @@ class TimedSheetManager: ObservableObject { currentSheet.onDismissed() currentlyShowingSheet = nil } + // A sheet shown at cold start, before channels and Spark load, kept the Move to Spark intro from being checked. + // A check already pending covers it. + if isOnPrimaryScreen, settleTimer?.isValid != true, queuedSheets.contains(where: { $0.id == .moveToSpark }) { + scheduleSettleCheck(only: .moveToSpark) + } } - /// (Re)start the settle timer that runs the queue check after a short delay. - private func scheduleSettleCheck() { + /// (Re)start the settle timer that runs the queue check after a short delay, for every queued sheet or only `id`. + private func scheduleSettleCheck(only id: SheetID? = nil) { // Cancel any existing timer settleTimer?.invalidate() // Start timer to check for sheets after delay settleTimer = Timer.scheduledTimer(withTimeInterval: checkDelay, repeats: false) { [weak self] _ in Task { @MainActor in - await self?.checkAndShowNextSheet() + await self?.checkAndShowNextSheet(only: id) } } } /// Check the queue and show the highest priority sheet that should be shown - private func checkAndShowNextSheet() async { + private func checkAndShowNextSheet(only id: SheetID? = nil) async { guard let sheetViewModel else { Logger.error("SheetViewModel not configured for TimedSheetManager") return @@ -187,7 +192,7 @@ class TimedSheetManager: ObservableObject { } // Find the highest priority sheet that should be shown - for sheet in queuedSheets { + for sheet in queuedSheets where id == nil || sheet.id == id { if await sheet.shouldShow() { Logger.debug("Showing timed sheet: \(sheet.id.rawValue) with priority: \(sheet.priority.rawValue)") diff --git a/Bitkit/Models/BackupPayloads.swift b/Bitkit/Models/BackupPayloads.swift index 628345dcd7..da908490d7 100644 --- a/Bitkit/Models/BackupPayloads.swift +++ b/Bitkit/Models/BackupPayloads.swift @@ -30,6 +30,9 @@ struct MetadataBackupV1: Codable { /// The earlier Spark exit addresses each wallet watches, keyed `/wallet` as bitkit-android keys them. /// Nil in envelopes written before this field. var sparkExitEarlierAddresses: [String: [SparkExitEarlierAddressBackupV1]]? + /// The payment hashes of moves to Spark, lowercase hex, which Activity shows as transfers. Nil in envelopes written + /// before this field. + var moveToSparkPaymentHashes: [String]? init( version: Int, @@ -39,7 +42,8 @@ struct MetadataBackupV1: Codable { pubkySession: PubkySessionBackupV1?, pubkyContactProfileOverrides: [String: PubkyProfileData]?, hwWalletNames: [String: String]? = nil, - sparkExitEarlierAddresses: [String: [SparkExitEarlierAddressBackupV1]]? = nil + sparkExitEarlierAddresses: [String: [SparkExitEarlierAddressBackupV1]]? = nil, + moveToSparkPaymentHashes: [String]? = nil ) { self.version = version self.createdAt = createdAt @@ -49,6 +53,7 @@ struct MetadataBackupV1: Codable { self.pubkyContactProfileOverrides = pubkyContactProfileOverrides self.hwWalletNames = hwWalletNames self.sparkExitEarlierAddresses = sparkExitEarlierAddresses + self.moveToSparkPaymentHashes = moveToSparkPaymentHashes } } @@ -67,6 +72,7 @@ extension MetadataBackupV1 { [String: [SparkExitEarlierAddressBackupV1]].self, forKey: .sparkExitEarlierAddresses ) + moveToSparkPaymentHashes = try? c.decodeIfPresent([String].self, forKey: .moveToSparkPaymentHashes) } } diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index 21e322b2a8..e93f8bcd7e 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -200,6 +200,7 @@ "lightning__spending_intro__text" = "حوّل الأموال إلى رصيد إنفاقك للاستمتاع بمعاملات فورية ورخيصة مع الأصدقاء والعائلة والتجار."; "lightning__spending_intro__button" = "ابدأ"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "الحد الأدنى لرصيد المدخرات"; "lightning__spending_amount__error_max__title" = "الحد الأقصى لرصيد الإنفاق"; "lightning__spending_amount__error_max__description" = "المبلغ الذي يمكنك تحويله إلى رصيد الإنفاق محدود حاليًا بـ ₿ {amount}."; "lightning__spending_amount__error_fee" = "تعذّر الحصول على رسوم الشبكة. انقر للمحاولة مرة أخرى."; @@ -305,6 +306,29 @@ "lightning__transaction" = "المعاملة"; "lightning__order_fee" = "رسوم الطلب"; "lightning__balance" = "الرصيد"; +"lightning__move_to_spark__amount" = "المبلغ"; +"lightning__move_to_spark__confirm_text" = "يُنقل رصيدك إلى Spark عبر Lightning، وهي الطريقة الأقل رسومًا لإبقائه في الإنفاق. رسوم التوجيه أدناه هي الحد الأقصى الذي تدفعه."; +"lightning__move_to_spark__confirm_title" = "النقل إلى\nSpark"; +"lightning__move_to_spark__done_rest_text" = "أصبح جزء من رصيدك على Spark الآن. انقل الباقي بالطريقة نفسها، ثم أغلق الاتصال الذي أُفرغ."; +"lightning__move_to_spark__done_text" = "أصبح رصيدك على Spark الآن. أغلق الاتصال الذي أُفرغ لإعادة احتياطيه إلى المدخرات."; +"lightning__move_to_spark__done_title" = "تم النقل إلى\nSpark"; +"lightning__move_to_spark__failed_nothing" = "لم يتبقَّ في اتصالات Lightning الخاصة بك أي رصيد لنقله."; +"lightning__move_to_spark__failed_spark" = "Spark غير جاهز للاستلام بعد. حاول مرة أخرى بعد لحظات."; +"lightning__move_to_spark__failed_title" = "تعذّر\nالنقل"; +"lightning__move_to_spark__failed_unknown" = "حدث خطأ أثناء التحضير للنقل. حاول مرة أخرى."; +"lightning__move_to_spark__fee" = "رسوم التوجيه"; +"lightning__move_to_spark__intro_text" = "تُغلق Blocktank اتصالات Lightning الخاصة بها. انقل رصيدك إلى Spark الآن: إنه الخيار الأقل رسومًا، ويبقى في الإنفاق."; +"lightning__move_to_spark__intro_title" = "اتصالك\nقيد الإغلاق"; +"lightning__move_to_spark__move_half" = "انقل النصف"; +"lightning__move_to_spark__move_now" = "انقل الآن"; +"lightning__move_to_spark__move_rest" = "انقل الباقي"; +"lightning__move_to_spark__nav_title" = "النقل إلى Spark"; +"lightning__move_to_spark__quoting" = "جارٍ البحث عن مسار ورسومه…"; +"lightning__move_to_spark__swipe" = "اسحب للنقل"; +"lightning__move_to_spark__too_large_none" = "أغلق الاتصال بدلاً من ذلك لإعادة الرصيد إلى المدخرات."; +"lightning__move_to_spark__too_large_smaller" = "يمكنك نقله على دفعات أصغر."; +"lightning__move_to_spark__too_large_text" = "المبلغ {amount} كبير جدًا لتوجيهه إلى Spark في دفعة واحدة."; +"lightning__move_to_spark__too_large_title" = "المبلغ\nكبير جدًا"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "رسوم المطالبة"; "lightning__spark_confirmations" = "{count}/3 تأكيدات"; @@ -358,6 +382,7 @@ "lightning__spark_exit__leftover_swept" = "أُرسل {amount} من رسوم الطوارئ غير المستخدمة إلى المدخرات."; "lightning__spark_exit__leftover_sending" = "جارٍ إرسال {amount} من رسوم الطوارئ غير المستخدمة إلى المدخرات."; "lightning__spark_exit__leftover_dust" = "{amount} من رسوم الطوارئ غير المستخدمة أصغر من أن يُرسل ويبقى في {address}، مسار الاشتقاق {path}."; +"lightning__spark_exit__earlier_path" = "مسار الاشتقاق"; "lightning__spark_exit__lost_leaves" = "طالب مالك سابق لهذه الأموال بمبلغ {amount} على السلسلة ولا يمكن استرداده."; "lightning__spark_exit__notification_lost" = "لا يمكن استرداد {amount} من تحويلك القسري. افتح Bitkit لمعرفة السبب."; "lightning__spark_exit__notification_failed" = "توقف التحويل القسري. افتح Bitkit لمعرفة السبب."; @@ -863,6 +888,7 @@ "wallet__payment_recipient_rejected" = "رفض المستلم دفعة Lightning هذه. تحقق من الفاتورة وحاول مرة أخرى."; "wallet__payment_abandoned" = "تم إيقاف دفعة Lightning قبل اكتمالها."; "wallet__payment_expired" = "انتهت صلاحية دفعة Lightning هذه. اطلب فاتورة جديدة."; +"wallet__payment_restored_invoice" = "لا يستطيع Bitkit التأكد من أن هذه الفاتورة لم تُدفع قبل استعادة محفظتك. يرجى طلب فاتورة جديدة."; "wallet__payment_timeout" = "انتهت مهلة الدفع. حاول مرة أخرى."; "wallet__payment_route_not_found" = "لم يتمكن Bitkit من العثور على مسار Lightning لهذه الدفعة."; "wallet__payment_retries_exhausted" = "جرّب Bitkit عدة مسارات Lightning، لكن تعذر إكمال الدفعة."; @@ -889,7 +915,7 @@ "wallet__receive_note_placeholder" = "ملاحظة اختيارية للدافع"; "wallet__receive_show_qr" = "عرض رمز QR"; "wallet__receive_spending" = "استلام أموال Lightning"; -"wallet__receive_spending_text" = "استمتع بمدفوعات Bitcoin فورية ورخيصة على شبكة Lightning."; +"wallet__receive_spending_text" = "استمتع بمعاملات فورية ورخيصة مع الأصدقاء والعائلة والتجار."; "wallet__receive_spending_title" = "استلم على رصيد الإنفاق"; "settings__backup__category_contacts" = "جهات الاتصال"; "settings__support__title" = "الدعم"; @@ -1183,6 +1209,7 @@ "wallet__swap_route_restored_title" = "أُعيدت الدفعة إلى المدخرات"; "wallet__send_paykit_no_route__title" = "تعذّر الدفع لجهة الاتصال هذه"; "wallet__send_paykit_no_route__description" = "ليس لدى جهة الاتصال هذه طريقة دفع يمكن لـ Bitkit استخدامها حاليًا."; +"wallet__send_paykit_withdrawal_settling__description" = "لا تزال عملية سحب سابقة من رصيد الإنفاق قيد التسوية. حاول مرة أخرى بعد اكتمالها."; "wallet__recipient_contact" = "جهة الاتصال"; "wallet__recipient_invoice" = "لصق فاتورة"; "wallet__recipient_manual" = "إدخال يدوي"; @@ -1688,6 +1715,7 @@ "wallet__activity_failed" = "فشلت"; "wallet__activity_transfer" = "تحويل"; "wallet__activity_transferring" = "جارٍ التحويل"; +"wallet__activity_move_to_spark" = "النقل إلى Spark"; "wallet__activity_transfer_savings_pending" = "من الإنفاق ({duration})"; "wallet__activity_transfer_savings_done" = "من الإنفاق"; "wallet__activity_transfer_spending_pending" = "من المدخرات ({duration})"; @@ -1768,5 +1796,7 @@ "subscriptions__allowance_auto_paid" = "مدفوع تلقائيًا"; "wallet__balance_updating" = "جارٍ تحديث الرصيد…"; +"lightning__move_to_spark__in_flight_text" = "الدفعة في طريقها وستظهر في Spark بمجرد تسويتها. إذا فشلت، يبقى المبلغ في اتصالك."; +"lightning__move_to_spark__in_flight_title" = "جارٍ النقل إلى\nSpark"; "other__error_keychain" = "مشكلة في الاتصال بالبيانات"; "other__error_keychain_msg" = "تعذر تحميل المفتاح الأساسي من سلسلة المفاتيح."; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index 3f31c49312..6a20f58a6c 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -201,7 +201,7 @@ "lightning__funding__nav_title" = "Saldo de despesa"; "lightning__funding__text" = "La forma més fàcil és utilitzar els teus estalvis de Bitkit o enviar bitcoin des d\'una altra cartera."; "lightning__funding__title" = "Finança el teu saldo de despesa"; -"lightning__funding__button1" = "Transferir des d\'estalvis"; +"lightning__funding__button1" = "Transferir des d'estalvis"; "lightning__funding__button2" = "Utilitza un altre moneder"; "lightning__funding__button3" = "Configuració manual"; "lightning__funding_advanced__button_short" = "Configuració avançada"; @@ -227,6 +227,7 @@ "lightning__spending_intro__button" = "Començar"; "lightning__transfer_failed__continue" = "Torna a intentar"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "Mínim del saldo d'estalvis"; "lightning__spending_amount__error_max__title" = "Màxim del saldo de despesa"; "lightning__spending_amount__error_max__description" = "L'import que pots transferir al teu saldo de despesa està limitat a ₿ {amount}."; "lightning__spending_amount__error_fee" = "No s'ha pogut obtenir la comissió de xarxa. Toca per tornar-ho a provar."; @@ -342,6 +343,29 @@ "lightning__transaction" = "Transacció"; "lightning__order_fee" = "Comissió de comanda"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Import"; +"lightning__move_to_spark__confirm_text" = "El teu saldo es mou a Spark a través de Lightning, la manera amb menys comissions de mantenir-lo a Despesa. La comissió d'encaminament de sota és el màxim que pagues."; +"lightning__move_to_spark__confirm_title" = "Moure a\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Part del teu saldo ja és a Spark. Mou la resta de la mateixa manera i després tanca la connexió buidada."; +"lightning__move_to_spark__done_text" = "El teu saldo ja és a Spark. Tanca la connexió buidada per retornar-ne la reserva a Estalvis."; +"lightning__move_to_spark__done_title" = "Mogut a\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Les teves connexions Lightning no tenen saldo per moure."; +"lightning__move_to_spark__failed_spark" = "Spark encara no està preparat per rebre. Torna-ho a provar d'aquí a un moment."; +"lightning__move_to_spark__failed_title" = "No s'ha pogut\nmoure"; +"lightning__move_to_spark__failed_unknown" = "Alguna cosa ha fallat en preparar el moviment. Torna-ho a provar."; +"lightning__move_to_spark__fee" = "Comissió d'encaminament"; +"lightning__move_to_spark__intro_text" = "Blocktank està tancant les seves connexions Lightning. Mou ara el teu saldo a Spark: és l'opció amb menys comissions i es queda a Despesa."; +"lightning__move_to_spark__intro_title" = "La teva connexió\nes tanca"; +"lightning__move_to_spark__move_half" = "Mou la meitat"; +"lightning__move_to_spark__move_now" = "Mou ara"; +"lightning__move_to_spark__move_rest" = "Mou la resta"; +"lightning__move_to_spark__nav_title" = "Moure a Spark"; +"lightning__move_to_spark__quoting" = "Cercant una ruta i la seva comissió…"; +"lightning__move_to_spark__swipe" = "Llisca per moure"; +"lightning__move_to_spark__too_large_none" = "Tanca la connexió en lloc d'això per retornar el saldo a Estalvis."; +"lightning__move_to_spark__too_large_smaller" = "El pots moure en parts més petites."; +"lightning__move_to_spark__too_large_text" = "{amount} és massa per encaminar-lo a Spark en un sol pagament."; +"lightning__move_to_spark__too_large_title" = "Import\nmassa gran"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Comissió de reclamació"; "lightning__spark_confirmations" = "{count}/3 confirmacions"; @@ -395,6 +419,7 @@ "lightning__spark_exit__leftover_swept" = "{amount} de comissions d'emergència no utilitzades s'han enviat als estalvis."; "lightning__spark_exit__leftover_sending" = "S'estan enviant {amount} de comissions d'emergència no utilitzades als estalvis."; "lightning__spark_exit__leftover_dust" = "{amount} de comissions d'emergència no utilitzades són massa petits per enviar-se i es queden a {address}, camí de derivació {path}."; +"lightning__spark_exit__earlier_path" = "Camí de derivació"; "lightning__spark_exit__lost_leaves" = "Un propietari anterior d'aquests fons ha reclamat {amount} on-chain i no es pot recuperar."; "lightning__spark_exit__notification_lost" = "{amount} de la teva transferència forçosa no es pot recuperar. Obre Bitkit per veure'n el motiu."; "lightning__spark_exit__notification_failed" = "La teva transferència forçosa s'ha aturat. Obre Bitkit per veure'n el motiu."; @@ -1302,6 +1327,7 @@ "wallet__swap_route_restored_title" = "Pagament retornat a Estalvis"; "wallet__send_paykit_no_route__title" = "No es pot pagar aquest contacte"; "wallet__send_paykit_no_route__description" = "Aquest contacte no té cap mètode de pagament que Bitkit pugui fer servir ara mateix."; +"wallet__send_paykit_withdrawal_settling__description" = "Una retirada anterior del teu saldo de despesa encara s'està liquidant. Torna-ho a provar quan s'hagi completat."; "wallet__recipient_contact" = "Contacte"; "wallet__recipient_invoice" = "Enganxa factura"; "wallet__recipient_manual" = "Introdueix manualment"; @@ -1386,6 +1412,7 @@ "wallet__payment_recipient_rejected" = "El destinatari ha rebutjat aquest pagament Lightning. Comprova la factura i torna-ho a provar."; "wallet__payment_abandoned" = "El pagament Lightning s'ha aturat abans de completar-se."; "wallet__payment_expired" = "Aquest pagament Lightning ha caducat. Demana una factura nova."; +"wallet__payment_restored_invoice" = "Bitkit no pot confirmar que aquesta factura no s'hagués pagat abans que restauressis la teva cartera. Demana una factura nova."; "wallet__payment_timeout" = "El pagament ha esgotat el temps d'espera. Torna-ho a provar."; "wallet__payment_route_not_found" = "Bitkit no ha pogut trobar cap ruta Lightning per a aquest pagament."; "wallet__payment_retries_exhausted" = "Bitkit ha provat diverses rutes Lightning, però el pagament no s'ha pogut completar."; @@ -1414,7 +1441,7 @@ "wallet__receive_note_placeholder" = "Nota opcional per al pagador"; "wallet__receive_show_qr" = "Mostra el codi QR"; "wallet__receive_spending" = "Rebre fons Lightning"; -"wallet__receive_spending_text" = "Gaudeix de pagaments de bitcoin instantanis i barats a la xarxa Lightning."; +"wallet__receive_spending_text" = "Gaudeix de transaccions instantànies i barates amb amics, família i comerços."; "wallet__receive_spending_title" = "Rebre al saldo de despesa"; "wallet__receive_cjit_error" = "Transacció fallida"; "wallet__minimum" = "MÍNIM"; @@ -1429,6 +1456,7 @@ "wallet__activity_failed" = "Fallit"; "wallet__activity_transfer" = "Transferència"; "wallet__activity_transferring" = "Transferint"; +"wallet__activity_move_to_spark" = "Moure a Spark"; "wallet__activity_transfer_savings_pending" = "Des de despesa ({duration})"; "wallet__activity_transfer_savings_done" = "Des de despesa"; "wallet__activity_transfer_spending_pending" = "Des d\'estalvis ({duration})"; @@ -1952,5 +1980,7 @@ "subscriptions__allowance_auto_paid" = "Pagat automàticament"; "wallet__balance_updating" = "S’està actualitzant el saldo…"; +"lightning__move_to_spark__in_flight_text" = "El pagament està en camí i apareixerà a Spark quan es liquidi. Si falla, l'import es queda a la teva connexió."; +"lightning__move_to_spark__in_flight_title" = "Movent a\nSpark"; "other__error_keychain" = "Problema de connexió de dades"; "other__error_keychain_msg" = "No s'ha pogut carregar la clau principal del clauer."; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index dc4f89b280..1df2176300 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -358,6 +358,29 @@ "lightning__transaction" = "Transakce"; "lightning__order_fee" = "Poplatek za objednávku"; "lightning__balance" = "Zůstatek"; +"lightning__move_to_spark__amount" = "Částka"; +"lightning__move_to_spark__confirm_text" = "Váš zůstatek se přesune na Spark přes Lightning, což je nejlevnější způsob, jak ho ponechat v útratách. Poplatek za směrování níže je maximum, které zaplatíte."; +"lightning__move_to_spark__confirm_title" = "Přesunout na\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Část vašeho zůstatku je nyní na Sparku. Přesuňte zbytek stejným způsobem a pak uzavřete vyprázdněné spojení."; +"lightning__move_to_spark__done_text" = "Váš zůstatek je nyní na Sparku. Uzavřete vyprázdněné spojení, aby se jeho rezerva vrátila do úspor."; +"lightning__move_to_spark__done_title" = "Přesunuto na\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Vaše Lightning spojení už nemají žádný zůstatek k přesunu."; +"lightning__move_to_spark__failed_spark" = "Spark zatím není připraven přijímat. Zkuste to za chvíli znovu."; +"lightning__move_to_spark__failed_title" = "Přesun se\nnezdařil"; +"lightning__move_to_spark__failed_unknown" = "Při přípravě přesunu se něco pokazilo. Zkuste to znovu."; +"lightning__move_to_spark__fee" = "Poplatek za směrování"; +"lightning__move_to_spark__intro_text" = "Blocktank uzavírá svá Lightning spojení. Přesuňte nyní svůj zůstatek na Spark: je to nejlevnější možnost a zůstatek zůstane v útratách."; +"lightning__move_to_spark__intro_title" = "Vaše spojení\nse uzavírá"; +"lightning__move_to_spark__move_half" = "Přesunout polovinu"; +"lightning__move_to_spark__move_now" = "Přesunout nyní"; +"lightning__move_to_spark__move_rest" = "Přesunout zbytek"; +"lightning__move_to_spark__nav_title" = "Přesun na Spark"; +"lightning__move_to_spark__quoting" = "Hledání trasy a jejího poplatku…"; +"lightning__move_to_spark__swipe" = "Přejeďte pro přesun"; +"lightning__move_to_spark__too_large_none" = "Místo toho uzavřete spojení, aby se zůstatek vrátil do úspor."; +"lightning__move_to_spark__too_large_smaller" = "Můžete ji přesunout po menších částech."; +"lightning__move_to_spark__too_large_text" = "Částka {amount} je příliš velká na to, aby se dala na Spark směrovat jednou platbou."; +"lightning__move_to_spark__too_large_title" = "Částka je\npříliš velká"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Poplatek za připsání"; "lightning__spark_confirmations" = "{count}/3 potvrzení"; @@ -411,6 +434,7 @@ "lightning__spark_exit__leftover_swept" = "{amount} nepoužitých nouzových poplatků bylo odesláno do úspor."; "lightning__spark_exit__leftover_sending" = "Odesílání {amount} nepoužitých nouzových poplatků do úspor."; "lightning__spark_exit__leftover_dust" = "{amount} nepoužitých nouzových poplatků je příliš málo na odeslání a zůstává na adrese {address}, derivační cesta {path}."; +"lightning__spark_exit__earlier_path" = "Derivační cesta"; "lightning__spark_exit__lost_leaves" = "{amount} si on-chain nárokoval dřívější vlastník těchto prostředků a nelze to získat zpět."; "lightning__spark_exit__notification_lost" = "{amount} z vašeho vynuceného převodu nelze obnovit. Otevřete Bitkit a zjistěte proč."; "lightning__spark_exit__notification_failed" = "Váš vynucený převod se zastavil. Otevřete Bitkit a zjistěte proč."; @@ -1409,6 +1433,7 @@ "wallet__swap_route_restored_title" = "Platba vrácena do Úspor"; "wallet__send_paykit_no_route__title" = "Tomuto kontaktu nelze zaplatit"; "wallet__send_paykit_no_route__description" = "Tento kontakt teď nemá žádný platební způsob, který by Bitkit mohl použít."; +"wallet__send_paykit_withdrawal_settling__description" = "Dřívější výběr z vašeho zůstatku na útratu se stále vypořádává. Zkuste to znovu, až bude dokončen."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Vložit fakturu"; "wallet__recipient_manual" = "Zadat ručně"; @@ -1499,6 +1524,7 @@ "wallet__payment_recipient_rejected" = "Příjemce tuto Lightning platbu odmítl. Zkontrolujte fakturu a zkuste to znovu."; "wallet__payment_abandoned" = "Lightning platba byla zastavena před dokončením."; "wallet__payment_expired" = "Platnost této Lightning platby vypršela. Vyžádejte si novou fakturu."; +"wallet__payment_restored_invoice" = "Bitkit nemůže potvrdit, že tato faktura nebyla zaplacena před obnovením vaší peněženky. Vyžádejte si prosím novou fakturu."; "wallet__payment_timeout" = "Časový limit platby vypršel. Zkuste to znovu."; "wallet__payment_route_not_found" = "Bitkit nenašel pro tuto platbu žádnou Lightning trasu."; "wallet__payment_retries_exhausted" = "Bitkit vyzkoušel několik Lightning tras, ale platbu se nepodařilo dokončit."; @@ -1528,7 +1554,7 @@ "wallet__receive_show_qr" = "Zobrazit QR kód"; "wallet__receive_text_lnfunds" = "Chcete obdržet prostředky lightning?"; "wallet__receive_spending" = "Přijmout Lightning prostředky"; -"wallet__receive_spending_text" = "Užívejte si okamžité a levné bitcoinové platby v síti Lightning."; +"wallet__receive_spending_text" = "Užívejte si okamžité a levné transakce s přáteli, rodinou a obchodníky."; "wallet__receive_spending_title" = "Přijmout na disponibilní zůstatek"; "wallet__receive_cjit_error" = "Transakce selhala"; "wallet__receive_cjit_error_msg" = "Nepodařilo se odeslat prostředky na váš disponibilní účet."; @@ -1545,6 +1571,7 @@ "wallet__activity_failed" = "Selhání"; "wallet__activity_transfer" = "Převod"; "wallet__activity_transferring" = "Probíhá převod"; +"wallet__activity_move_to_spark" = "Přesun na Spark"; "wallet__activity_transfer_savings_pending" = "Z disponibilního zůstatku ({duration})"; "wallet__activity_transfer_savings_done" = "Z útraty"; "wallet__activity_transfer_spending_pending" = "Z úspor ({duration})"; @@ -2091,3 +2118,5 @@ "subscriptions__allowance_auto_paid" = "Zaplaceno automaticky"; "wallet__balance_updating" = "Aktualizace zůstatku…"; +"lightning__move_to_spark__in_flight_text" = "Platba je na cestě a po vypořádání se zobrazí ve Sparku. Pokud selže, částka zůstane ve vašem spojení."; +"lightning__move_to_spark__in_flight_title" = "Přesouvání na\nSpark"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 00a1a46df2..2a86b8eec5 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -201,7 +201,7 @@ "lightning__funding__nav_title" = "Spending Balance"; "lightning__funding__text" = "Am einfachsten ist es, deine Bitkit-Ersparnisse zu verwenden oder Bitcoin von einer anderen Wallet zu senden."; "lightning__funding__title" = "Fund your spending balance"; -"lightning__funding__button1" = "Von Sparkonto übertragen"; +"lightning__funding__button1" = "Vom Sparkonto übertragen"; "lightning__funding__button2" = "Anderes Wallet verwenden"; "lightning__funding__button3" = "Manuelle Einrichtung"; "lightning__funding_advanced__button_short" = "Fortgeschrittenes Setup"; @@ -356,6 +356,29 @@ "lightning__transaction" = "Transaktion"; "lightning__order_fee" = "Auftragsgebühr"; "lightning__balance" = "Guthaben"; +"lightning__move_to_spark__amount" = "Betrag"; +"lightning__move_to_spark__confirm_text" = "Dein Guthaben wird über Lightning zu Spark verschoben, der günstigste Weg, es im Ausgabenkonto zu behalten. Die Routing-Gebühr unten ist das Maximum, das du zahlst."; +"lightning__move_to_spark__confirm_title" = "Zu Spark\nverschieben"; +"lightning__move_to_spark__done_rest_text" = "Ein Teil deines Guthabens ist jetzt auf Spark. Verschiebe den Rest auf dieselbe Weise und schließe dann die geleerte Verbindung."; +"lightning__move_to_spark__done_text" = "Dein Guthaben ist jetzt auf Spark. Schließe die geleerte Verbindung, um ihre Reserve ins Sparkonto zurückzuholen."; +"lightning__move_to_spark__done_title" = "Zu Spark\nverschoben"; +"lightning__move_to_spark__failed_nothing" = "Deine Lightning-Verbindungen haben kein Guthaben mehr, das verschoben werden kann."; +"lightning__move_to_spark__failed_spark" = "Spark ist noch nicht bereit zu empfangen. Versuche es gleich noch einmal."; +"lightning__move_to_spark__failed_title" = "Verschieben\nfehlgeschlagen"; +"lightning__move_to_spark__failed_unknown" = "Beim Vorbereiten der Verschiebung ist etwas schiefgelaufen. Versuche es erneut."; +"lightning__move_to_spark__fee" = "Routing-Gebühr"; +"lightning__move_to_spark__intro_text" = "Blocktank schließt seine Lightning-Verbindungen. Verschiebe dein Guthaben jetzt zu Spark: Das ist die günstigste Option, und es bleibt im Ausgabenkonto."; +"lightning__move_to_spark__intro_title" = "Deine Verbindung\nwird geschlossen"; +"lightning__move_to_spark__move_half" = "Hälfte verschieben"; +"lightning__move_to_spark__move_now" = "Jetzt verschieben"; +"lightning__move_to_spark__move_rest" = "Rest verschieben"; +"lightning__move_to_spark__nav_title" = "Verschiebung zu Spark"; +"lightning__move_to_spark__quoting" = "Route und Gebühr werden gesucht…"; +"lightning__move_to_spark__swipe" = "Swipe zum Verschieben"; +"lightning__move_to_spark__too_large_none" = "Schließe stattdessen die Verbindung, um das Guthaben ins Sparkonto zurückzuholen."; +"lightning__move_to_spark__too_large_smaller" = "Du kannst ihn in kleineren Teilen verschieben."; +"lightning__move_to_spark__too_large_text" = "{amount} ist zu groß, um in einer Zahlung zu Spark geroutet zu werden."; +"lightning__move_to_spark__too_large_title" = "Betrag\nzu groß"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Einlösegebühr"; "lightning__spark_confirmations" = "{count}/3 Bestätigungen"; @@ -409,6 +432,7 @@ "lightning__spark_exit__leftover_swept" = "{amount} nicht verbrauchte Notfallgebühren wurden an dein Sparkonto gesendet."; "lightning__spark_exit__leftover_sending" = "{amount} nicht verbrauchte Notfallgebühren werden an dein Sparkonto gesendet."; "lightning__spark_exit__leftover_dust" = "{amount} nicht verbrauchte Notfallgebühren sind zu klein zum Senden und bleiben bei {address}, Ableitungspfad {path}."; +"lightning__spark_exit__earlier_path" = "Ableitungspfad"; "lightning__spark_exit__lost_leaves" = "{amount} wurden von einem früheren Besitzer dieser Mittel on-chain beansprucht und können nicht wiederhergestellt werden."; "lightning__spark_exit__notification_lost" = "{amount} deiner forcierten Übertragung können nicht zurückgeholt werden. Öffne Bitkit, um den Grund zu sehen."; "lightning__spark_exit__notification_failed" = "Deine forcierte Übertragung wurde gestoppt. Öffne Bitkit, um den Grund zu sehen."; @@ -1407,6 +1431,7 @@ "wallet__swap_route_restored_title" = "Zahlung an Ersparnisse zurückgegeben"; "wallet__send_paykit_no_route__title" = "Zahlung an diesen Kontakt nicht möglich"; "wallet__send_paykit_no_route__description" = "Dieser Kontakt hat derzeit keine Zahlungsmethode, die Bitkit nutzen kann."; +"wallet__send_paykit_withdrawal_settling__description" = "Eine frühere Abhebung von deinem Ausgabenguthaben wird noch abgewickelt. Versuche es erneut, sobald sie abgeschlossen ist."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Rechnung einfügen"; "wallet__recipient_manual" = "Manuell eingeben"; @@ -1497,6 +1522,7 @@ "wallet__payment_recipient_rejected" = "Der Empfänger hat diese Lightning-Zahlung abgelehnt. Bitte prüfe die Rechnung und versuche es erneut."; "wallet__payment_abandoned" = "Die Lightning-Zahlung wurde gestoppt, bevor sie abgeschlossen wurde."; "wallet__payment_expired" = "Diese Lightning-Zahlung ist abgelaufen. Bitte fordere eine neue Rechnung an."; +"wallet__payment_restored_invoice" = "Bitkit kann nicht bestätigen, dass diese Rechnung nicht bezahlt wurde, bevor du deine Wallet wiederhergestellt hast. Bitte fordere eine neue Rechnung an."; "wallet__payment_timeout" = "Zeitüberschreitung bei der Zahlung. Bitte versuche es erneut."; "wallet__payment_route_not_found" = "Bitkit konnte keine Lightning-Route für diese Zahlung finden."; "wallet__payment_retries_exhausted" = "Bitkit hat mehrere Lightning-Routen ausprobiert, aber die Zahlung konnte nicht abgeschlossen werden."; @@ -1526,7 +1552,7 @@ "wallet__receive_show_qr" = "QR-Code anzeigen"; "wallet__receive_text_lnfunds" = "Möchtest du Lightning-Gelder empfangen?"; "wallet__receive_spending" = "Auf Ausgabenkonto empfangen"; -"wallet__receive_spending_text" = "Genieße sofortige und günstige Bitcoin-Zahlungen im Lightning-Netzwerk."; +"wallet__receive_spending_text" = "Genieße sofortige und günstige Transaktionen mit Freunden, Familie und Händlern."; "wallet__receive_spending_title" = "Auf Ausgabenguthaben empfangen"; "wallet__receive_cjit_error" = "Transaktion fehlgeschlagen"; "wallet__receive_cjit_error_msg" = "Fehler beim Senden der Gelder auf dein Ausgabenkonto."; @@ -1543,6 +1569,7 @@ "wallet__activity_failed" = "Fehlgeschlagen"; "wallet__activity_transfer" = "Übertragung"; "wallet__activity_transferring" = "Wird übertragen"; +"wallet__activity_move_to_spark" = "Verschiebung zu Spark"; "wallet__activity_transfer_savings_pending" = "Von Ausgabenkonto ({duration})"; "wallet__activity_transfer_savings_done" = "Von Ausgabenkonto"; "wallet__activity_transfer_spending_pending" = "Von Sparkonto ({duration})"; @@ -2088,3 +2115,5 @@ "subscriptions__allowance_auto_paid" = "Automatisch bezahlt"; "wallet__balance_updating" = "Kontostand wird aktualisiert…"; +"lightning__move_to_spark__in_flight_text" = "Die Zahlung ist unterwegs und erscheint in Spark, sobald sie abgewickelt ist. Schlägt sie fehl, bleibt der Betrag in deiner Verbindung."; +"lightning__move_to_spark__in_flight_title" = "Unterwegs zu\nSpark"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 798ae2fc22..ef4a376a81 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -223,6 +223,7 @@ "lightning__spending_intro__button" = "Ξεκινήστε"; "lightning__transfer_failed__continue" = "Προσπαθείστε Ξανά"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "Ελάχιστο υπόλοιπο αποταμιεύσεων"; "lightning__spending_amount__error_max__title" = "Μέγιστο υπόλοιπο δαπανών"; "lightning__spending_amount__error_max__description" = "Το ποσό που μπορείς να μεταφέρεις στο υπόλοιπο δαπανών περιορίζεται προς το παρόν σε ₿ {amount}."; "lightning__spending_amount__error_fee" = "Δεν ήταν δυνατή η λήψη των τελών δικτύου. Πατήστε για νέα προσπάθεια."; @@ -329,6 +330,29 @@ "lightning__transaction" = "Συναλλαγή"; "lightning__order_fee" = "Τέλος παραγγελίας"; "lightning__balance" = "Υπόλοιπο"; +"lightning__move_to_spark__amount" = "Ποσό"; +"lightning__move_to_spark__confirm_text" = "Το υπόλοιπό σας μετακινείται στο Spark μέσω Lightning, ο τρόπος με τα χαμηλότερα τέλη για να παραμείνει στις Δαπάνες. Το τέλος δρομολόγησης παρακάτω είναι το μέγιστο που πληρώνετε."; +"lightning__move_to_spark__confirm_title" = "Μετακίνηση στο\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Μέρος του υπολοίπου σας βρίσκεται τώρα στο Spark. Μετακινήστε το υπόλοιπο ποσό με τον ίδιο τρόπο και μετά κλείστε την άδεια σύνδεση."; +"lightning__move_to_spark__done_text" = "Το υπόλοιπό σας βρίσκεται τώρα στο Spark. Κλείστε την άδεια σύνδεση για να επιστρέψει το αποθεματικό της στις Αποταμιεύσεις."; +"lightning__move_to_spark__done_title" = "Μετακινήθηκε στο\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Οι συνδέσεις Lightning σας δεν έχουν πλέον υπόλοιπο για μετακίνηση."; +"lightning__move_to_spark__failed_spark" = "Το Spark δεν είναι ακόμα έτοιμο να λάβει. Δοκιμάστε ξανά σε λίγο."; +"lightning__move_to_spark__failed_title" = "Η μετακίνηση\nαπέτυχε"; +"lightning__move_to_spark__failed_unknown" = "Κάτι πήγε στραβά κατά την προετοιμασία της μετακίνησης. Δοκιμάστε ξανά."; +"lightning__move_to_spark__fee" = "Τέλος δρομολόγησης"; +"lightning__move_to_spark__intro_text" = "Το Blocktank κλείνει τις συνδέσεις Lightning του. Μετακινήστε τώρα το υπόλοιπό σας στο Spark: είναι η επιλογή με τα χαμηλότερα τέλη και παραμένει στις Δαπάνες."; +"lightning__move_to_spark__intro_title" = "Η σύνδεσή σας\nκλείνει"; +"lightning__move_to_spark__move_half" = "Μετακίνηση Μισού"; +"lightning__move_to_spark__move_now" = "Μετακίνηση Τώρα"; +"lightning__move_to_spark__move_rest" = "Μετακίνηση Υπολοίπου"; +"lightning__move_to_spark__nav_title" = "Μετακίνηση στο Spark"; +"lightning__move_to_spark__quoting" = "Αναζήτηση διαδρομής και τέλους…"; +"lightning__move_to_spark__swipe" = "Σύρετε για Μετακίνηση"; +"lightning__move_to_spark__too_large_none" = "Κλείστε αντί γι' αυτό τη σύνδεση για να επιστρέψει το υπόλοιπο στις Αποταμιεύσεις."; +"lightning__move_to_spark__too_large_smaller" = "Μπορείτε να το μετακινήσετε σε μικρότερα τμήματα."; +"lightning__move_to_spark__too_large_text" = "Το ποσό {amount} είναι πολύ μεγάλο για δρομολόγηση στο Spark με μία πληρωμή."; +"lightning__move_to_spark__too_large_title" = "Ποσό\nπολύ μεγάλο"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Χρέωση εξαργύρωσης"; "lightning__spark_confirmations" = "{count}/3 επιβεβαιώσεις"; @@ -382,6 +406,7 @@ "lightning__spark_exit__leftover_swept" = "Τα {amount} αχρησιμοποίητων έκτακτων τελών στάλθηκαν στις αποταμιεύσεις."; "lightning__spark_exit__leftover_sending" = "Αποστολή {amount} αχρησιμοποίητων έκτακτων τελών στις αποταμιεύσεις."; "lightning__spark_exit__leftover_dust" = "Τα {amount} αχρησιμοποίητων έκτακτων τελών είναι πολύ μικρά για αποστολή και παραμένουν στη διεύθυνση {address}, διαδρομή παραγωγής {path}."; +"lightning__spark_exit__earlier_path" = "Διαδρομή παραγωγής"; "lightning__spark_exit__lost_leaves" = "{amount} διεκδικήθηκε on-chain από προηγούμενο κάτοχο αυτών των κεφαλαίων και δεν μπορεί να ανακτηθεί."; "lightning__spark_exit__notification_lost" = "Τα {amount} της αναγκαστικής μεταφοράς σας δεν μπορούν να ανακτηθούν. Ανοίξτε το Bitkit για να δείτε γιατί."; "lightning__spark_exit__notification_failed" = "Η αναγκαστική μεταφορά σας σταμάτησε. Ανοίξτε το Bitkit για να δείτε γιατί."; @@ -1201,6 +1226,7 @@ "wallet__swap_route_restored_title" = "Η πληρωμή επέστρεψε στις Αποταμιεύσεις"; "wallet__send_paykit_no_route__title" = "Δεν είναι δυνατή η πληρωμή αυτής της επαφής"; "wallet__send_paykit_no_route__description" = "Αυτή η επαφή δεν έχει αυτή τη στιγμή κάποια μέθοδο πληρωμής που μπορεί να χρησιμοποιήσει το Bitkit."; +"wallet__send_paykit_withdrawal_settling__description" = "Μια προηγούμενη ανάληψη από το υπόλοιπο δαπανών σας εκκαθαρίζεται ακόμα. Δοκιμάστε ξανά μόλις ολοκληρωθεί."; "wallet__recipient_contact" = "Επαφή"; "wallet__recipient_invoice" = "Επικόλληση Τιμολογίου"; "wallet__recipient_manual" = "Χειροκίνητη Εισαγωγή"; @@ -1267,6 +1293,7 @@ "wallet__payment_recipient_rejected" = "Ο παραλήπτης απέρριψε αυτήν την πληρωμή Lightning. Ελέγξτε το τιμολόγιο και δοκιμάστε ξανά."; "wallet__payment_abandoned" = "Η πληρωμή Lightning σταμάτησε πριν ολοκληρωθεί."; "wallet__payment_expired" = "Αυτή η πληρωμή Lightning έληξε. Ζητήστε νέο τιμολόγιο."; +"wallet__payment_restored_invoice" = "Το Bitkit δεν μπορεί να επιβεβαιώσει ότι αυτό το τιμολόγιο δεν πληρώθηκε πριν από την επαναφορά του πορτοφολιού σας. Ζητήστε νέο τιμολόγιο."; "wallet__payment_timeout" = "Το χρονικό όριο πληρωμής έληξε. Δοκιμάστε ξανά."; "wallet__payment_route_not_found" = "Το Bitkit δεν μπόρεσε να βρει διαδρομή Lightning για αυτήν την πληρωμή."; "wallet__payment_retries_exhausted" = "Το Bitkit δοκίμασε αρκετές διαδρομές Lightning, αλλά η πληρωμή δεν μπόρεσε να ολοκληρωθεί."; @@ -1293,7 +1320,7 @@ "wallet__receive_note_placeholder" = "Προαιρετική σημείωση στον πληρωτή"; "wallet__receive_show_qr" = "Εμφάνιση Κωδικού QR"; "wallet__receive_spending" = "Λήψη κεφαλαίων Lightning"; -"wallet__receive_spending_text" = "Απολαύστε άμεσες και φθηνές πληρωμές bitcoin στο Lightning Network."; +"wallet__receive_spending_text" = "Απολαύστε άμεσες και φθηνές συναλλαγές με φίλους, οικογένεια και εμπόρους."; "wallet__receive_spending_title" = "Λήψη στο υπόλοιπο δαπανών"; "wallet__receive_cjit_error" = "Η Συναλλαγή Απέτυχε"; "wallet__activity" = "Δραστηριότητα"; @@ -1306,6 +1333,7 @@ "wallet__activity_failed" = "Απέτυχε"; "wallet__activity_transfer" = "Μεταφορά"; "wallet__activity_transferring" = "Μεταφορά σε εξέλιξη"; +"wallet__activity_move_to_spark" = "Μετακίνηση στο Spark"; "wallet__activity_transfer_savings_pending" = "Από Δαπάνες ({duration})"; "wallet__activity_transfer_savings_done" = "Από Δαπάνες"; "wallet__activity_transfer_spending_pending" = "Από Αποταμιεύσεις ({duration})"; @@ -1823,5 +1851,7 @@ "subscriptions__allowance_auto_paid" = "Πληρώθηκε αυτόματα"; "wallet__balance_updating" = "Ενημέρωση υπολοίπου…"; +"lightning__move_to_spark__in_flight_text" = "Η πληρωμή βρίσκεται καθ' οδόν και εμφανίζεται στο Spark μόλις διακανονιστεί. Αν αποτύχει, το ποσό παραμένει στη σύνδεσή σας."; +"lightning__move_to_spark__in_flight_title" = "Μετακινείται στο\nSpark"; "other__error_keychain" = "Πρόβλημα Σύνδεσης Δεδομένων"; "other__error_keychain_msg" = "Δεν ήταν δυνατή η φόρτωση του κύριου κλειδιού από την κλειδοθήκη."; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index ec5b29cc79..7f80844018 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1584,6 +1584,7 @@ "wallet__activity_failed" = "Failed"; "wallet__activity_transfer" = "Transfer"; "wallet__activity_transferring" = "Transferring"; +"wallet__activity_move_to_spark" = "Move to Spark"; "wallet__activity_transfer_savings_pending" = "From Spending ({duration})"; "wallet__activity_transfer_savings_done" = "From Spending"; "wallet__activity_transfer_spending_pending" = "From Savings ({duration})"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 5c98969e10..ca649c6214 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -359,6 +359,29 @@ "lightning__transaction" = "Transacción"; "lightning__order_fee" = "Tarifa de pedido"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Cantidad"; +"lightning__move_to_spark__confirm_text" = "Tu saldo se mueve a Spark a través de Lightning, la forma con menos comisiones de mantenerlo en Gastos. La comisión de enrutamiento de abajo es lo máximo que pagas."; +"lightning__move_to_spark__confirm_title" = "Mover a\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Parte de tu saldo ya está en Spark. Mueve el resto de la misma manera y después cierra la conexión vaciada."; +"lightning__move_to_spark__done_text" = "Tu saldo ya está en Spark. Cierra la conexión vaciada para devolver su reserva a Ahorros."; +"lightning__move_to_spark__done_title" = "Movido a\nSpark"; +"lightning__move_to_spark__failed_nothing" = "A tus conexiones Lightning no les queda saldo que mover."; +"lightning__move_to_spark__failed_spark" = "Spark todavía no está listo para recibir. Vuelve a intentarlo en un momento."; +"lightning__move_to_spark__failed_title" = "No se pudo\nmover"; +"lightning__move_to_spark__failed_unknown" = "Algo salió mal al preparar el movimiento. Vuelve a intentarlo."; +"lightning__move_to_spark__fee" = "Comisión de enrutamiento"; +"lightning__move_to_spark__intro_text" = "Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción con menos comisiones y se queda en Gastos."; +"lightning__move_to_spark__intro_title" = "Tu conexión\nse está cerrando"; +"lightning__move_to_spark__move_half" = "Mover la mitad"; +"lightning__move_to_spark__move_now" = "Mover ahora"; +"lightning__move_to_spark__move_rest" = "Mover el resto"; +"lightning__move_to_spark__nav_title" = "Mover a Spark"; +"lightning__move_to_spark__quoting" = "Buscando una ruta y su comisión…"; +"lightning__move_to_spark__swipe" = "Deslizar para mover"; +"lightning__move_to_spark__too_large_none" = "En su lugar, cierra la conexión para devolver el saldo a Ahorros."; +"lightning__move_to_spark__too_large_smaller" = "Puedes moverla en partes más pequeñas."; +"lightning__move_to_spark__too_large_text" = "{amount} es demasiado para enrutarlo a Spark en un solo pago."; +"lightning__move_to_spark__too_large_title" = "Cantidad\ndemasiado alta"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Comisión de reclamo"; "lightning__spark_confirmations" = "{count}/3 confirmaciones"; @@ -412,6 +435,7 @@ "lightning__spark_exit__leftover_swept" = "{amount} de comisiones de emergencia sin usar se envió a tus ahorros."; "lightning__spark_exit__leftover_sending" = "Enviando {amount} de comisiones de emergencia sin usar a tus ahorros."; "lightning__spark_exit__leftover_dust" = "{amount} de comisiones de emergencia sin usar es demasiado pequeño para enviarse y se queda en {address}, ruta de derivación {path}."; +"lightning__spark_exit__earlier_path" = "Ruta de derivación"; "lightning__spark_exit__lost_leaves" = "Un propietario anterior de estos fondos reclamó {amount} on-chain y no se puede recuperar."; "lightning__spark_exit__notification_lost" = "{amount} de tu transferencia forzada no se puede recuperar. Abre Bitkit para ver por qué."; "lightning__spark_exit__notification_failed" = "Tu transferencia forzada se detuvo. Abre Bitkit para ver por qué."; @@ -1412,6 +1436,7 @@ "wallet__swap_route_restored_title" = "Pago devuelto a Ahorros"; "wallet__send_paykit_no_route__title" = "No se puede pagar a este contacto"; "wallet__send_paykit_no_route__description" = "Este contacto no tiene ningún método de pago que Bitkit pueda usar en este momento."; +"wallet__send_paykit_withdrawal_settling__description" = "Un retiro anterior de tu saldo para gastos todavía se está liquidando. Vuelve a intentarlo cuando se complete."; "wallet__recipient_contact" = "Contacto"; "wallet__recipient_invoice" = "Pegar factura"; "wallet__recipient_manual" = "Introducir manualmente"; @@ -1502,6 +1527,7 @@ "wallet__payment_recipient_rejected" = "El destinatario rechazó este pago Lightning. Revise la factura e inténtelo de nuevo."; "wallet__payment_abandoned" = "El pago Lightning se detuvo antes de completarse."; "wallet__payment_expired" = "Este pago Lightning venció. Solicite una factura nueva."; +"wallet__payment_restored_invoice" = "Bitkit no puede confirmar que esta factura no se haya pagado antes de que restaurara su cartera. Solicite una factura nueva."; "wallet__payment_timeout" = "El pago agotó el tiempo de espera. Inténtelo de nuevo."; "wallet__payment_route_not_found" = "Bitkit no pudo encontrar una ruta Lightning para este pago."; "wallet__payment_retries_exhausted" = "Bitkit probó varias rutas Lightning, pero el pago no se pudo completar."; @@ -1531,7 +1557,7 @@ "wallet__receive_show_qr" = "Mostrar código QR"; "wallet__receive_text_lnfunds" = "Quiero recibir"; "wallet__receive_spending" = "Recibir en Saldo de Gastos"; -"wallet__receive_spending_text" = "Disfrute de pagos de bitcoin instantáneos y baratos en la red Lightning."; +"wallet__receive_spending_text" = "Disfruta de transacciones instantáneas y baratas con amigos, familia y comercios."; "wallet__receive_spending_title" = "Recibir en saldo de gastos"; "wallet__receive_cjit_error" = "Transacción fallida"; "wallet__receive_cjit_error_msg" = "No se han podido enviar fondos a su cuenta de gastos."; @@ -1548,6 +1574,7 @@ "wallet__activity_failed" = "Fallido"; "wallet__activity_transfer" = "Transferir"; "wallet__activity_transferring" = "Transfiriendo"; +"wallet__activity_move_to_spark" = "Mover a Spark"; "wallet__activity_transfer_savings_pending" = "Del Gastos ({duration})"; "wallet__activity_transfer_savings_done" = "De Gastos"; "wallet__activity_transfer_spending_pending" = "De Ahorros ({duration})"; @@ -2094,3 +2121,5 @@ "subscriptions__allowance_auto_paid" = "Pagado automáticamente"; "wallet__balance_updating" = "Actualizando saldo…"; +"lightning__move_to_spark__in_flight_text" = "El pago está en camino y aparecerá en Spark cuando se liquide. Si falla, la cantidad se queda en tu conexión."; +"lightning__move_to_spark__in_flight_title" = "Moviendo a\nSpark"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index 29ddb78c27..6f3a20cf9f 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -225,6 +225,7 @@ "lightning__spending_intro__button" = "Empezar"; "lightning__transfer_failed__continue" = "Inténtelo de nuevo"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "Mínimo del Saldo de Ahorros"; "lightning__spending_amount__error_max__title" = "Máximo del Saldo de Gastos"; "lightning__spending_amount__error_max__description" = "La cantidad que puedes transferir a tu saldo de gastos está actualmente limitada a ₿ {amount}."; "lightning__spending_amount__error_fee" = "No se pudo obtener la comisión de red. Toque para reintentar."; @@ -343,6 +344,29 @@ "lightning__transaction" = "Transacción"; "lightning__order_fee" = "Tarifa de pedido"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Cantidad"; +"lightning__move_to_spark__confirm_text" = "Tu saldo se mueve a Spark a través de Lightning, la forma con menos comisiones de mantenerlo en Gasto. La comisión de enrutamiento de abajo es lo máximo que pagas."; +"lightning__move_to_spark__confirm_title" = "Mover a\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Parte de tu saldo ya está en Spark. Mueve el resto de la misma manera y después cierra la conexión vaciada."; +"lightning__move_to_spark__done_text" = "Tu saldo ya está en Spark. Cierra la conexión vaciada para devolver su reserva a Ahorro."; +"lightning__move_to_spark__done_title" = "Movido a\nSpark"; +"lightning__move_to_spark__failed_nothing" = "A tus conexiones Lightning no les queda saldo que mover."; +"lightning__move_to_spark__failed_spark" = "Spark aún no está listo para recibir. Inténtalo de nuevo en un momento."; +"lightning__move_to_spark__failed_title" = "No se pudo\nmover"; +"lightning__move_to_spark__failed_unknown" = "Algo salió mal al preparar el movimiento. Inténtalo de nuevo."; +"lightning__move_to_spark__fee" = "Comisión de enrutamiento"; +"lightning__move_to_spark__intro_text" = "Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción con menos comisiones y se queda en Gasto."; +"lightning__move_to_spark__intro_title" = "Tu conexión\nse está cerrando"; +"lightning__move_to_spark__move_half" = "Mover la mitad"; +"lightning__move_to_spark__move_now" = "Mover ahora"; +"lightning__move_to_spark__move_rest" = "Mover el resto"; +"lightning__move_to_spark__nav_title" = "Mover a Spark"; +"lightning__move_to_spark__quoting" = "Buscando una ruta y su comisión…"; +"lightning__move_to_spark__swipe" = "Deslizar para mover"; +"lightning__move_to_spark__too_large_none" = "En su lugar, cierra la conexión para devolver el saldo a Ahorro."; +"lightning__move_to_spark__too_large_smaller" = "Puedes moverla en partes más pequeñas."; +"lightning__move_to_spark__too_large_text" = "{amount} es demasiado para enrutarlo a Spark en un solo pago."; +"lightning__move_to_spark__too_large_title" = "Cantidad\ndemasiado alta"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Comisión de reclamo"; "lightning__spark_confirmations" = "{count}/3 confirmaciones"; @@ -396,6 +420,7 @@ "lightning__spark_exit__leftover_swept" = "Se han enviado a tus ahorros {amount} de comisiones de emergencia sin usar."; "lightning__spark_exit__leftover_sending" = "Enviando {amount} de comisiones de emergencia sin usar a tus ahorros."; "lightning__spark_exit__leftover_dust" = "{amount} de comisiones de emergencia sin usar es demasiado poco para enviarse y se queda en {address}, ruta de derivación {path}."; +"lightning__spark_exit__earlier_path" = "Ruta de derivación"; "lightning__spark_exit__lost_leaves" = "Un propietario anterior de estos fondos reclamó {amount} on-chain y no se puede recuperar."; "lightning__spark_exit__notification_lost" = "{amount} de tu transferencia forzada no se puede recuperar. Abre Bitkit para ver el motivo."; "lightning__spark_exit__notification_failed" = "Tu transferencia forzada se detuvo. Abre Bitkit para ver el motivo."; @@ -1320,6 +1345,7 @@ "wallet__swap_route_restored_title" = "Pago devuelto a Ahorros"; "wallet__send_paykit_no_route__title" = "No se puede pagar a este contacto"; "wallet__send_paykit_no_route__description" = "Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora mismo."; +"wallet__send_paykit_withdrawal_settling__description" = "Una retirada anterior de tu saldo de gastos aún se está liquidando. Inténtalo de nuevo cuando se complete."; "wallet__recipient_contact" = "Contactar"; "wallet__recipient_invoice" = "Pegar factura"; "wallet__recipient_manual" = "Introducir manualmente"; @@ -1401,6 +1427,7 @@ "wallet__payment_recipient_rejected" = "El destinatario ha rechazado este pago Lightning. Comprueba la factura e inténtalo de nuevo."; "wallet__payment_abandoned" = "El pago Lightning se detuvo antes de completarse."; "wallet__payment_expired" = "Este pago Lightning ha caducado. Solicita una factura nueva."; +"wallet__payment_restored_invoice" = "Bitkit no puede confirmar que esta factura no se pagara antes de que restauraras tu cartera. Solicita una factura nueva."; "wallet__payment_timeout" = "El pago agotó el tiempo de espera. Inténtalo de nuevo."; "wallet__payment_route_not_found" = "Bitkit no ha podido encontrar una ruta Lightning para este pago."; "wallet__payment_retries_exhausted" = "Bitkit ha probado varias rutas Lightning, pero el pago no se ha podido completar."; @@ -1429,7 +1456,7 @@ "wallet__receive_note_placeholder" = "Nota opcional para el pagador"; "wallet__receive_show_qr" = "Mostrar código QR"; "wallet__receive_spending" = "Recibir Fondos Lightning"; -"wallet__receive_spending_text" = "Disfrute de pagos de bitcoin instantáneos y baratos en la red Lightning."; +"wallet__receive_spending_text" = "Disfruta de transacciones instantáneas y baratas con amigos, familia y comercios."; "wallet__receive_spending_title" = "Recibir en saldo de gasto"; "wallet__receive_cjit_error" = "Transacción ha fallado"; "wallet__receive_cjit_error_msg" = "Fallo al enviar fondos a la cuenta de gastos."; @@ -1445,6 +1472,7 @@ "wallet__activity_failed" = "Fallido"; "wallet__activity_transfer" = "Transferir"; "wallet__activity_transferring" = "Transfiriendo"; +"wallet__activity_move_to_spark" = "Mover a Spark"; "wallet__activity_transfer_savings_pending" = "Desde Gasto ({duration})"; "wallet__activity_transfer_savings_done" = "Desde Gasto"; "wallet__activity_transfer_spending_pending" = "Desde Ahorros ({duration})"; @@ -1973,3 +2001,5 @@ "subscriptions__allowance_auto_paid" = "Pagado automáticamente"; "wallet__balance_updating" = "Actualizando saldo…"; +"lightning__move_to_spark__in_flight_text" = "El pago está en camino y aparecerá en Spark cuando se liquide. Si falla, la cantidad se queda en tu conexión."; +"lightning__move_to_spark__in_flight_title" = "Moviendo a\nSpark"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index 3a655506e1..6c2f99f64e 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -202,7 +202,7 @@ "lightning__funding__nav_title" = "Solde Dépenses"; "lightning__funding__text" = "Le plus simple est d\'utiliser vos économies Bitkit ou d\'envoyer des bitcoins depuis un autre portefeuille."; "lightning__funding__title" = "Financez votre solde Dépenses"; -"lightning__funding__button1" = "Transfert depuis l\'épargne"; +"lightning__funding__button1" = "Transférer depuis l'Épargne"; "lightning__funding__button2" = "Utiliser un autre portefeuille"; "lightning__funding__button3" = "Configuration manuelle"; "lightning__funding_advanced__button_short" = "Configuration avancée"; @@ -359,6 +359,29 @@ "lightning__transaction" = "Transaction"; "lightning__order_fee" = "Frais"; "lightning__balance" = "Solde"; +"lightning__move_to_spark__amount" = "Montant"; +"lightning__move_to_spark__confirm_text" = "Votre solde est déplacé vers Spark via Lightning, le moyen le moins cher de le garder dans Dépenses. Les frais de routage ci-dessous sont le maximum que vous payez."; +"lightning__move_to_spark__confirm_title" = "Déplacer vers\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Une partie de votre solde est maintenant sur Spark. Déplacez le reste de la même façon, puis fermez la connexion vidée."; +"lightning__move_to_spark__done_text" = "Votre solde est maintenant sur Spark. Fermez la connexion vidée pour renvoyer sa réserve vers l'Épargne."; +"lightning__move_to_spark__done_title" = "Déplacé vers\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Vos connexions Lightning n'ont plus de solde à déplacer."; +"lightning__move_to_spark__failed_spark" = "Spark n'est pas encore prêt à recevoir. Réessayez dans un instant."; +"lightning__move_to_spark__failed_title" = "Déplacement\nimpossible"; +"lightning__move_to_spark__failed_unknown" = "Une erreur s'est produite lors de la préparation du déplacement. Réessayez."; +"lightning__move_to_spark__fee" = "Frais de routage"; +"lightning__move_to_spark__intro_text" = "Blocktank ferme ses connexions Lightning. Déplacez votre solde vers Spark maintenant : c'est l'option la moins chère, et il reste dans Dépenses."; +"lightning__move_to_spark__intro_title" = "Votre connexion\nva être fermée"; +"lightning__move_to_spark__move_half" = "Déplacer la moitié"; +"lightning__move_to_spark__move_now" = "Déplacer maintenant"; +"lightning__move_to_spark__move_rest" = "Déplacer le reste"; +"lightning__move_to_spark__nav_title" = "Déplacement vers Spark"; +"lightning__move_to_spark__quoting" = "Recherche d'une route et de ses frais…"; +"lightning__move_to_spark__swipe" = "Glissez pour déplacer"; +"lightning__move_to_spark__too_large_none" = "Fermez plutôt la connexion pour renvoyer le solde vers l'Épargne."; +"lightning__move_to_spark__too_large_smaller" = "Vous pouvez le déplacer en plusieurs parties plus petites."; +"lightning__move_to_spark__too_large_text" = "{amount} est trop élevé pour être routé vers Spark en un seul paiement."; +"lightning__move_to_spark__too_large_title" = "Montant\ntrop élevé"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Frais de réclamation"; "lightning__spark_confirmations" = "{count}/3 confirmations"; @@ -412,6 +435,7 @@ "lightning__spark_exit__leftover_swept" = "{amount} de frais d'urgence inutilisés ont été envoyés vers l'épargne."; "lightning__spark_exit__leftover_sending" = "Envoi de {amount} de frais d'urgence inutilisés vers l'épargne."; "lightning__spark_exit__leftover_dust" = "{amount} de frais d'urgence inutilisés est trop faible pour être envoyé et reste à {address}, chemin de dérivation {path}."; +"lightning__spark_exit__earlier_path" = "Chemin de dérivation"; "lightning__spark_exit__lost_leaves" = "{amount} a été réclamé on-chain par un ancien propriétaire de ces fonds et ne peut pas être récupéré."; "lightning__spark_exit__notification_lost" = "{amount} de votre transfert forcé ne peut pas être récupéré. Ouvrez Bitkit pour savoir pourquoi."; "lightning__spark_exit__notification_failed" = "Votre transfert forcé s'est arrêté. Ouvrez Bitkit pour savoir pourquoi."; @@ -1420,6 +1444,7 @@ "wallet__swap_route_restored_title" = "Paiement renvoyé vers l'Épargne"; "wallet__send_paykit_no_route__title" = "Impossible de payer ce contact"; "wallet__send_paykit_no_route__description" = "Ce contact n’a actuellement aucun moyen de paiement que Bitkit peut utiliser."; +"wallet__send_paykit_withdrawal_settling__description" = "Un retrait précédent depuis votre solde Dépenses est toujours en cours de règlement. Réessayez une fois qu'il est terminé."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Coller la facture"; "wallet__recipient_manual" = "Entrer manuellement"; @@ -1510,6 +1535,7 @@ "wallet__payment_recipient_rejected" = "Le destinataire a rejeté ce paiement Lightning. Vérifiez la facture et réessayez."; "wallet__payment_abandoned" = "Le paiement Lightning a été arrêté avant d'être terminé."; "wallet__payment_expired" = "Ce paiement Lightning a expiré. Demandez une nouvelle facture."; +"wallet__payment_restored_invoice" = "Bitkit ne peut pas confirmer que cette facture n'a pas été payée avant la restauration de votre portefeuille. Veuillez demander une nouvelle facture."; "wallet__payment_timeout" = "Le paiement a expiré. Veuillez réessayer."; "wallet__payment_route_not_found" = "Bitkit n'a pas trouvé de route Lightning pour ce paiement."; "wallet__payment_retries_exhausted" = "Bitkit a essayé plusieurs routes Lightning, mais le paiement n'a pas pu être terminé."; @@ -1539,7 +1565,7 @@ "wallet__receive_show_qr" = "Afficher le QR code"; "wallet__receive_text_lnfunds" = "Vous souhaitez recevoir des fonds Lightning?"; "wallet__receive_spending" = "Recevoir sur le compte de dépenses"; -"wallet__receive_spending_text" = "Profitez de paiements en bitcoins instantanés et bon marché sur le Lightning Network."; +"wallet__receive_spending_text" = "Profitez de transactions instantanées et bon marché avec vos amis, votre famille et les commerçants."; "wallet__receive_spending_title" = "Recevoir sur le solde de dépenses"; "wallet__receive_cjit_error" = "Échec de la transaction"; "wallet__receive_cjit_error_msg" = "Échec de l’envoi vers Dépenses."; @@ -1556,6 +1582,7 @@ "wallet__activity_failed" = "Échec"; "wallet__activity_transfer" = "Transfert"; "wallet__activity_transferring" = "Transfert en cours"; +"wallet__activity_move_to_spark" = "Déplacement vers Spark"; "wallet__activity_transfer_savings_pending" = "Depuis le compte Dépenses ({duration})"; "wallet__activity_transfer_savings_done" = "Depuis le compte Dépenses"; "wallet__activity_transfer_spending_pending" = "Depuis l\'Épargne ({duration})"; @@ -2102,3 +2129,5 @@ "subscriptions__allowance_auto_paid" = "Payé automatiquement"; "wallet__balance_updating" = "Mise à jour du solde…"; +"lightning__move_to_spark__in_flight_text" = "Le paiement est en route et apparaîtra dans Spark une fois réglé. En cas d'échec, le montant reste dans votre connexion."; +"lightning__move_to_spark__in_flight_title" = "Déplacement vers\nSpark"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index 11e23d4451..554de26e65 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -200,7 +200,7 @@ "lightning__funding__nav_title" = "Conto di Spesa"; "lightning__funding__text" = "Il modo più semplice è usare i tuoi risparmi Bitkit o inviare bitcoin da un portafoglio diverso."; "lightning__funding__title" = "Manda fondi al tuo conto di spesa"; -"lightning__funding__button1" = "Trasferimento da risparmio"; +"lightning__funding__button1" = "Trasferisci dai risparmi"; "lightning__funding__button2" = "Usa un altro portafoglio"; "lightning__funding__button3" = "Configurazione manuale"; "lightning__funding_advanced__button_short" = "Configurazione Avanzata"; @@ -230,6 +230,7 @@ "lightning__transfer_failed__cancel" = "Ispeziona errore"; "lightning__transfer_failed__continue" = "Riprova"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "Saldo Minimo dei Risparmi"; "lightning__spending_amount__error_max__title" = "Massimo Conto di Spesa"; "lightning__spending_amount__error_max__description" = "L'importo che puoi trasferire al tuo conto di spesa e' attualmente limitato a ₿ {amount}."; "lightning__spending_amount__error_fee" = "Impossibile ottenere la commissione di rete. Tocca per riprovare."; @@ -352,6 +353,29 @@ "lightning__transaction" = "Transazione"; "lightning__order_fee" = "Fee Ordine"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Importo"; +"lightning__move_to_spark__confirm_text" = "Il tuo saldo si sposta su Spark tramite Lightning, il modo più economico per mantenerlo nella Spesa. La commissione di routing qui sotto è il massimo che paghi."; +"lightning__move_to_spark__confirm_title" = "Sposta su\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Parte del tuo saldo ora è su Spark. Sposta il resto allo stesso modo, poi chiudi la connessione svuotata."; +"lightning__move_to_spark__done_text" = "Il tuo saldo ora è su Spark. Chiudi la connessione svuotata per riportare la sua riserva nei Risparmi."; +"lightning__move_to_spark__done_title" = "Spostato su\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Le tue connessioni Lightning non hanno più saldo da spostare."; +"lightning__move_to_spark__failed_spark" = "Spark non è ancora pronto a ricevere. Riprova tra un momento."; +"lightning__move_to_spark__failed_title" = "Impossibile\nspostare"; +"lightning__move_to_spark__failed_unknown" = "Qualcosa è andato storto durante la preparazione dello spostamento. Riprova."; +"lightning__move_to_spark__fee" = "Commissione di routing"; +"lightning__move_to_spark__intro_text" = "Blocktank sta chiudendo le sue connessioni Lightning. Sposta ora il tuo saldo su Spark: è l'opzione più economica e resta nella Spesa."; +"lightning__move_to_spark__intro_title" = "La tua connessione\nsta per chiudersi"; +"lightning__move_to_spark__move_half" = "Sposta Metà"; +"lightning__move_to_spark__move_now" = "Sposta Ora"; +"lightning__move_to_spark__move_rest" = "Sposta il Resto"; +"lightning__move_to_spark__nav_title" = "Sposta su Spark"; +"lightning__move_to_spark__quoting" = "Ricerca di un percorso e della sua commissione…"; +"lightning__move_to_spark__swipe" = "Scorri Per Spostare"; +"lightning__move_to_spark__too_large_none" = "Chiudi invece la connessione per riportare il saldo nei Risparmi."; +"lightning__move_to_spark__too_large_smaller" = "Puoi spostarlo in parti più piccole."; +"lightning__move_to_spark__too_large_text" = "{amount} è troppo grande per essere instradato su Spark in un unico pagamento."; +"lightning__move_to_spark__too_large_title" = "Importo\ntroppo grande"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Commissione di riscatto"; "lightning__spark_confirmations" = "{count}/3 conferme"; @@ -405,6 +429,7 @@ "lightning__spark_exit__leftover_swept" = "{amount} di commissioni di emergenza non utilizzate è stato inviato ai risparmi."; "lightning__spark_exit__leftover_sending" = "Invio di {amount} di commissioni di emergenza non utilizzate ai risparmi."; "lightning__spark_exit__leftover_dust" = "{amount} di commissioni di emergenza non utilizzate è troppo poco per essere inviato e resta su {address}, percorso di derivazione {path}."; +"lightning__spark_exit__earlier_path" = "Percorso di derivazione"; "lightning__spark_exit__lost_leaves" = "{amount} è stato riscattato on-chain da un precedente proprietario di questi fondi e non può essere recuperato."; "lightning__spark_exit__notification_lost" = "{amount} del tuo trasferimento forzato non può essere recuperato. Apri Bitkit per scoprire perché."; "lightning__spark_exit__notification_failed" = "Il tuo trasferimento forzato si è interrotto. Apri Bitkit per scoprire perché."; @@ -1385,6 +1410,7 @@ "wallet__swap_route_restored_title" = "Pagamento restituito ai Risparmi"; "wallet__send_paykit_no_route__title" = "Impossibile pagare questo contatto"; "wallet__send_paykit_no_route__description" = "Al momento questo contatto non ha un metodo di pagamento che Bitkit possa usare."; +"wallet__send_paykit_withdrawal_settling__description" = "Un prelievo precedente dal tuo saldo di spesa è ancora in fase di regolamento. Riprova quando sarà completato."; "wallet__recipient_contact" = "Contatto"; "wallet__recipient_invoice" = "Incolla fattura"; "wallet__recipient_manual" = "Inserisci Manualmente"; @@ -1474,6 +1500,7 @@ "wallet__payment_recipient_rejected" = "Il destinatario ha rifiutato questo pagamento Lightning. Controlla la fattura e riprova."; "wallet__payment_abandoned" = "Il pagamento Lightning è stato interrotto prima del completamento."; "wallet__payment_expired" = "Questo pagamento Lightning è scaduto. Richiedi una nuova fattura."; +"wallet__payment_restored_invoice" = "Bitkit non può confermare che questa fattura non sia stata pagata prima del ripristino del tuo wallet. Richiedi una nuova fattura."; "wallet__payment_timeout" = "Il pagamento è scaduto. Riprova."; "wallet__payment_route_not_found" = "Bitkit non ha trovato una rotta Lightning per questo pagamento."; "wallet__payment_retries_exhausted" = "Bitkit ha provato diverse rotte Lightning, ma il pagamento non è stato completato."; @@ -1503,7 +1530,7 @@ "wallet__receive_show_qr" = "Visualizza QR Code"; "wallet__receive_text_lnfunds" = "Vuoi ricevere fondi Lightning?"; "wallet__receive_spending" = "Ricevi fondi Lightning"; -"wallet__receive_spending_text" = "Goditi pagamenti bitcoin istantanei ed economici sulla Lightning Network."; +"wallet__receive_spending_text" = "Goditi transazioni istantanee ed economiche con amici, familiari e commercianti."; "wallet__receive_spending_title" = "Ricevi su saldo di spesa"; "wallet__receive_cjit_error" = "Transazione Fallita"; "wallet__receive_cjit_error_msg" = "Impossibile inviare fondi al tuo conto di spesa."; @@ -1519,6 +1546,7 @@ "wallet__activity_failed" = "Fallito"; "wallet__activity_transfer" = "Trasferisci"; "wallet__activity_transferring" = "Trasferimento in corso"; +"wallet__activity_move_to_spark" = "Sposta su Spark"; "wallet__activity_transfer_savings_pending" = "Da Saldo Spendibile ({duration})"; "wallet__activity_transfer_savings_done" = "Da Saldo Spendibile"; "wallet__activity_transfer_spending_pending" = "Dai risparmi ({duration})"; @@ -2061,3 +2089,5 @@ "subscriptions__allowance_auto_paid" = "Pagato automaticamente"; "wallet__balance_updating" = "Aggiornamento del saldo…"; +"lightning__move_to_spark__in_flight_text" = "Il pagamento è in corso e apparirà in Spark una volta regolato. Se non va a buon fine, l'importo resta nella tua connessione."; +"lightning__move_to_spark__in_flight_title" = "Spostamento su\nSpark"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index c0fc50cb1f..63964e4301 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -356,6 +356,29 @@ "lightning__transaction" = "Transactie"; "lightning__order_fee" = "Order kosten"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Bedrag"; +"lightning__move_to_spark__confirm_text" = "Je saldo gaat via Lightning naar Spark, de goedkoopste manier om het in je bestedingssaldo te houden. De routeringsvergoeding hieronder is het maximum dat je betaalt."; +"lightning__move_to_spark__confirm_title" = "Verplaatsen naar\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Een deel van je saldo staat nu op Spark. Verplaats de rest op dezelfde manier en sluit daarna de leeggemaakte verbinding."; +"lightning__move_to_spark__done_text" = "Je saldo staat nu op Spark. Sluit de leeggemaakte verbinding om de reserve ervan terug te zetten naar je spaargeld."; +"lightning__move_to_spark__done_title" = "Verplaatst naar\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Je Lightning-verbindingen hebben geen saldo meer om te verplaatsen."; +"lightning__move_to_spark__failed_spark" = "Spark is nog niet klaar om te ontvangen. Probeer het zo opnieuw."; +"lightning__move_to_spark__failed_title" = "Verplaatsen\nmislukt"; +"lightning__move_to_spark__failed_unknown" = "Er ging iets mis bij het voorbereiden van de verplaatsing. Probeer het opnieuw."; +"lightning__move_to_spark__fee" = "Routeringsvergoeding"; +"lightning__move_to_spark__intro_text" = "Blocktank sluit zijn Lightning-verbindingen. Verplaats je saldo nu naar Spark: dat is de goedkoopste optie, en het blijft in je bestedingssaldo."; +"lightning__move_to_spark__intro_title" = "Je verbinding\nwordt gesloten"; +"lightning__move_to_spark__move_half" = "Helft Verplaatsen"; +"lightning__move_to_spark__move_now" = "Nu Verplaatsen"; +"lightning__move_to_spark__move_rest" = "Rest Verplaatsen"; +"lightning__move_to_spark__nav_title" = "Verplaatsen Naar Spark"; +"lightning__move_to_spark__quoting" = "Route en vergoeding zoeken…"; +"lightning__move_to_spark__swipe" = "Veeg Om Te Verplaatsen"; +"lightning__move_to_spark__too_large_none" = "Sluit in plaats daarvan de verbinding om het saldo terug te zetten naar je spaargeld."; +"lightning__move_to_spark__too_large_smaller" = "Je kunt het in kleinere delen verplaatsen."; +"lightning__move_to_spark__too_large_text" = "{amount} is te groot om in één betaling naar Spark te routeren."; +"lightning__move_to_spark__too_large_title" = "Bedrag\nte groot"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Claimkosten"; "lightning__spark_confirmations" = "{count}/3 bevestigingen"; @@ -409,6 +432,7 @@ "lightning__spark_exit__leftover_swept" = "{amount} aan ongebruikte noodkosten is naar spaargeld gestuurd."; "lightning__spark_exit__leftover_sending" = "{amount} aan ongebruikte noodkosten wordt naar spaargeld gestuurd."; "lightning__spark_exit__leftover_dust" = "{amount} aan ongebruikte noodkosten is te klein om te versturen en blijft op {address}, afleidingspad {path}."; +"lightning__spark_exit__earlier_path" = "Afleidingspad"; "lightning__spark_exit__lost_leaves" = "{amount} is on-chain geclaimd door een eerdere eigenaar van dit geld en kan niet worden teruggehaald."; "lightning__spark_exit__notification_lost" = "{amount} van uw geforceerde overboeking kan niet worden hersteld. Open Bitkit om te zien waarom."; "lightning__spark_exit__notification_failed" = "Uw geforceerde overboeking is gestopt. Open Bitkit om te zien waarom."; @@ -1415,6 +1439,7 @@ "wallet__swap_route_restored_title" = "Betaling teruggestort naar Spaargeld"; "wallet__send_paykit_no_route__title" = "Kan dit contact niet betalen"; "wallet__send_paykit_no_route__description" = "Dit contact heeft op dit moment geen betaalmethode die Bitkit kan gebruiken."; +"wallet__send_paykit_withdrawal_settling__description" = "Een eerdere opname van je bestedingssaldo wordt nog verwerkt. Probeer het opnieuw zodra die is voltooid."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Factuur Plakken"; "wallet__recipient_manual" = "Handmatig Invoeren"; @@ -1505,6 +1530,7 @@ "wallet__payment_recipient_rejected" = "De ontvanger heeft deze Lightning-betaling geweigerd. Controleer de factuur en probeer het opnieuw."; "wallet__payment_abandoned" = "De Lightning-betaling is gestopt voordat deze was voltooid."; "wallet__payment_expired" = "Deze Lightning-betaling is verlopen. Vraag een nieuwe factuur aan."; +"wallet__payment_restored_invoice" = "Bitkit kan niet bevestigen dat deze factuur niet is betaald voordat je je wallet herstelde. Vraag een nieuwe factuur aan."; "wallet__payment_timeout" = "Time-out voor betaling. Probeer het opnieuw."; "wallet__payment_route_not_found" = "Bitkit kon geen Lightning-route voor deze betaling vinden."; "wallet__payment_retries_exhausted" = "Bitkit heeft meerdere Lightning-routes geprobeerd, maar de betaling kon niet worden voltooid."; @@ -1534,7 +1560,7 @@ "wallet__receive_show_qr" = "Toon QR Code"; "wallet__receive_text_lnfunds" = "Wilt u Lightning ₿ ontvangen?"; "wallet__receive_spending" = "Ontvang Lightning-geld"; -"wallet__receive_spending_text" = "Geniet van directe en goedkope bitcoin-betalingen op het Lightning Network."; +"wallet__receive_spending_text" = "Geniet van directe en goedkope transacties met vrienden, familie en winkeliers."; "wallet__receive_spending_title" = "Ontvang op bestedingssaldo"; "wallet__receive_cjit_error" = "Transactie Mislukt"; "wallet__receive_cjit_error_msg" = "Fehler beim Senden der Gelder auf dein Ausgabenkonto."; @@ -1551,6 +1577,7 @@ "wallet__activity_failed" = "Mislukt"; "wallet__activity_transfer" = "Overboeken"; "wallet__activity_transferring" = "Overboeken"; +"wallet__activity_move_to_spark" = "Verplaatsen naar Spark"; "wallet__activity_transfer_savings_pending" = "Van Bestedingssaldo ({duration})"; "wallet__activity_transfer_savings_done" = "Van Bestedingssaldo"; "wallet__activity_transfer_spending_pending" = "Van Spaargeld ({duration})"; @@ -2096,3 +2123,5 @@ "subscriptions__allowance_auto_paid" = "Automatisch betaald"; "wallet__balance_updating" = "Saldo bijwerken…"; +"lightning__move_to_spark__in_flight_text" = "De betaling is onderweg en verschijnt in Spark zodra die is afgerond. Als die mislukt, blijft het bedrag in je verbinding."; +"lightning__move_to_spark__in_flight_title" = "Onderweg naar\nSpark"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index 39ecbfd344..a20787f268 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -358,6 +358,29 @@ "lightning__transaction" = "Transakcja"; "lightning__order_fee" = "Opłata za zamówienie"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Kwota"; +"lightning__move_to_spark__confirm_text" = "Twoje saldo zostanie przeniesione do Spark przez Lightning, najtańszym sposobem na zachowanie go w Wydatkach. Opłata za routing poniżej to maksimum, jakie zapłacisz."; +"lightning__move_to_spark__confirm_title" = "Przenieś do\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Część Twojego salda jest już w Spark. Przenieś resztę w ten sam sposób, a potem zamknij opróżnione połączenie."; +"lightning__move_to_spark__done_text" = "Twoje saldo jest już w Spark. Zamknij opróżnione połączenie, aby zwrócić jego rezerwę do Oszczędności."; +"lightning__move_to_spark__done_title" = "Przeniesiono do\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Na Twoich połączeniach Lightning nie zostało saldo do przeniesienia."; +"lightning__move_to_spark__failed_spark" = "Spark nie jest jeszcze gotowy do odbioru. Spróbuj ponownie za chwilę."; +"lightning__move_to_spark__failed_title" = "Nie udało się\nprzenieść"; +"lightning__move_to_spark__failed_unknown" = "Coś poszło nie tak podczas przygotowywania przeniesienia. Spróbuj ponownie."; +"lightning__move_to_spark__fee" = "Opłata za routing"; +"lightning__move_to_spark__intro_text" = "Blocktank zamyka swoje połączenia Lightning. Przenieś teraz saldo do Spark: to najtańsza opcja, a saldo pozostaje w Wydatkach."; +"lightning__move_to_spark__intro_title" = "Twoje połączenie\nzostanie zamknięte"; +"lightning__move_to_spark__move_half" = "Przenieś połowę"; +"lightning__move_to_spark__move_now" = "Przenieś teraz"; +"lightning__move_to_spark__move_rest" = "Przenieś resztę"; +"lightning__move_to_spark__nav_title" = "Przeniesienie do Spark"; +"lightning__move_to_spark__quoting" = "Szukanie trasy i jej opłaty…"; +"lightning__move_to_spark__swipe" = "Przesuń, aby przenieść"; +"lightning__move_to_spark__too_large_none" = "Zamiast tego zamknij połączenie, aby zwrócić saldo do Oszczędności."; +"lightning__move_to_spark__too_large_smaller" = "Możesz ją przenieść w mniejszych częściach."; +"lightning__move_to_spark__too_large_text" = "Kwota {amount} jest zbyt duża, aby przesłać ją do Spark jedną płatnością."; +"lightning__move_to_spark__too_large_title" = "Kwota\nzbyt duża"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Opłata za odbiór"; "lightning__spark_confirmations" = "{count}/3 potwierdzeń"; @@ -411,6 +434,7 @@ "lightning__spark_exit__leftover_swept" = "{amount} niewykorzystanych opłat awaryjnych zostało wysłane do oszczędności."; "lightning__spark_exit__leftover_sending" = "Wysyłanie {amount} niewykorzystanych opłat awaryjnych do oszczędności."; "lightning__spark_exit__leftover_dust" = "{amount} niewykorzystanych opłat awaryjnych to za mało, by je wysłać, i pozostaje pod adresem {address}, ścieżka derywacji {path}."; +"lightning__spark_exit__earlier_path" = "Ścieżka derywacji"; "lightning__spark_exit__lost_leaves" = "{amount} zostało przejęte on-chain przez poprzedniego właściciela tych środków i nie można go odzyskać."; "lightning__spark_exit__notification_lost" = "{amount} z Twojego wymuszonego transferu nie można odzyskać. Otwórz Bitkit, aby zobaczyć powód."; "lightning__spark_exit__notification_failed" = "Twój wymuszony transfer został zatrzymany. Otwórz Bitkit, aby zobaczyć powód."; @@ -1419,6 +1443,7 @@ "wallet__swap_route_restored_title" = "Płatność zwrócona do Oszczędności"; "wallet__send_paykit_no_route__title" = "Nie można zapłacić temu kontaktowi"; "wallet__send_paykit_no_route__description" = "Ten kontakt nie ma obecnie żadnej metody płatności, której Bitkit może użyć."; +"wallet__send_paykit_withdrawal_settling__description" = "Wcześniejsza wypłata z Twojego salda wydatków jest wciąż rozliczana. Spróbuj ponownie, gdy się zakończy."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Wklej fakturę"; "wallet__recipient_manual" = "Wprowadź ręcznie"; @@ -1509,6 +1534,7 @@ "wallet__payment_recipient_rejected" = "Odbiorca odrzucił tę płatność Lightning. Sprawdź fakturę i spróbuj ponownie."; "wallet__payment_abandoned" = "Płatność Lightning została zatrzymana przed zakończeniem."; "wallet__payment_expired" = "Ta płatność Lightning wygasła. Poproś o nową fakturę."; +"wallet__payment_restored_invoice" = "Bitkit nie może potwierdzić, że ta faktura nie została opłacona przed przywróceniem Twojego portfela. Poproś o nową fakturę."; "wallet__payment_timeout" = "Przekroczono limit czasu płatności. Spróbuj ponownie."; "wallet__payment_route_not_found" = "Bitkit nie znalazł trasy Lightning dla tej płatności."; "wallet__payment_retries_exhausted" = "Bitkit wypróbował kilka tras Lightning, ale płatności nie udało się ukończyć."; @@ -1538,7 +1564,7 @@ "wallet__receive_show_qr" = "Skanuj kod QR"; "wallet__receive_text_lnfunds" = "Chcesz otrzymać fundusze Lightning?"; "wallet__receive_spending" = "Odbierz środki Lightning"; -"wallet__receive_spending_text" = "Korzystaj z natychmiastowych i tanich płatności bitcoin w sieci Lightning."; +"wallet__receive_spending_text" = "Korzystaj z natychmiastowych i tanich transakcji ze znajomymi, rodziną i sprzedawcami."; "wallet__receive_spending_title" = "Odbierz na saldo wydatków"; "wallet__receive_cjit_error" = "Transakcja nie powiodła się"; "wallet__receive_cjit_error_msg" = "Nie udało się wysłać środków na Twoje saldo wydatków."; @@ -1555,6 +1581,7 @@ "wallet__activity_failed" = "Niepowodzenie"; "wallet__activity_transfer" = "Transfery"; "wallet__activity_transferring" = "Przesyłanie"; +"wallet__activity_move_to_spark" = "Przeniesienie do Spark"; "wallet__activity_transfer_savings_pending" = "Z salda wydatków ({duration})"; "wallet__activity_transfer_savings_done" = "Z salda wydatków"; "wallet__activity_transfer_spending_pending" = "Z oszczędności ({duration})"; @@ -2101,3 +2128,5 @@ "subscriptions__allowance_auto_paid" = "Opłacono automatycznie"; "wallet__balance_updating" = "Aktualizowanie salda…"; +"lightning__move_to_spark__in_flight_text" = "Płatność jest w drodze i pojawi się w Spark po rozliczeniu. Jeśli się nie powiedzie, kwota pozostanie w Twoim połączeniu."; +"lightning__move_to_spark__in_flight_title" = "Przenoszenie do\nSpark"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index bc0ba75a69..2bab732b1f 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -358,6 +358,29 @@ "lightning__transaction" = "Transação"; "lightning__order_fee" = "Taxa de pedido"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Valor"; +"lightning__move_to_spark__confirm_text" = "Seu saldo vai para a Spark pela Lightning, a forma de menor taxa de mantê-lo em Gastos. A taxa de roteamento abaixo é o máximo que você paga."; +"lightning__move_to_spark__confirm_title" = "Mover para a\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Parte do seu saldo já está na Spark. Mova o restante da mesma forma e depois feche a conexão esvaziada."; +"lightning__move_to_spark__done_text" = "Seu saldo já está na Spark. Feche a conexão esvaziada para devolver a reserva dela à Poupança."; +"lightning__move_to_spark__done_title" = "Movido para a\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Suas conexões Lightning não têm mais saldo para mover."; +"lightning__move_to_spark__failed_spark" = "A Spark ainda não está pronta para receber. Tente novamente em instantes."; +"lightning__move_to_spark__failed_title" = "Não foi possível\nmover"; +"lightning__move_to_spark__failed_unknown" = "Algo deu errado ao preparar a movimentação. Tente novamente."; +"lightning__move_to_spark__fee" = "Taxa de roteamento"; +"lightning__move_to_spark__intro_text" = "A Blocktank está fechando suas conexões Lightning. Mova seu saldo para a Spark agora: é a opção de menor taxa, e ele continua em Gastos."; +"lightning__move_to_spark__intro_title" = "Sua conexão\nvai ser fechada"; +"lightning__move_to_spark__move_half" = "Mover Metade"; +"lightning__move_to_spark__move_now" = "Mover Agora"; +"lightning__move_to_spark__move_rest" = "Mover o Restante"; +"lightning__move_to_spark__nav_title" = "Mover Para a Spark"; +"lightning__move_to_spark__quoting" = "Buscando uma rota e sua taxa…"; +"lightning__move_to_spark__swipe" = "Deslizar Para Mover"; +"lightning__move_to_spark__too_large_none" = "Em vez disso, feche a conexão para devolver o saldo à Poupança."; +"lightning__move_to_spark__too_large_smaller" = "Você pode movê-lo em partes menores."; +"lightning__move_to_spark__too_large_text" = "{amount} é grande demais para ser roteado para a Spark em um único pagamento."; +"lightning__move_to_spark__too_large_title" = "Valor\ngrande demais"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Taxa de resgate"; "lightning__spark_confirmations" = "{count}/3 confirmações"; @@ -411,6 +434,7 @@ "lightning__spark_exit__leftover_swept" = "{amount} de taxas de emergência não utilizadas foi enviado para a poupança."; "lightning__spark_exit__leftover_sending" = "Enviando {amount} de taxas de emergência não utilizadas para a poupança."; "lightning__spark_exit__leftover_dust" = "{amount} de taxas de emergência não utilizadas é pequeno demais para enviar e fica em {address}, caminho de derivação {path}."; +"lightning__spark_exit__earlier_path" = "Caminho de derivação"; "lightning__spark_exit__lost_leaves" = "{amount} foi resgatado on-chain por um antigo dono desses fundos e não pode ser recuperado."; "lightning__spark_exit__notification_lost" = "{amount} da sua transferência forçada não pode ser recuperado. Abra a Bitkit para ver o motivo."; "lightning__spark_exit__notification_failed" = "Sua transferência forçada parou. Abra a Bitkit para ver o motivo."; @@ -1420,6 +1444,7 @@ "wallet__swap_route_restored_title" = "Pagamento devolvido à Poupança"; "wallet__send_paykit_no_route__title" = "Não é possível pagar este contato"; "wallet__send_paykit_no_route__description" = "Este contato não tem nenhum método de pagamento que o Bitkit possa usar agora."; +"wallet__send_paykit_withdrawal_settling__description" = "Um saque anterior do seu saldo de gastos ainda está sendo liquidado. Tente novamente quando ele for concluído."; "wallet__recipient_contact" = "Contato"; "wallet__recipient_invoice" = "Colar Invoice"; "wallet__recipient_manual" = "Inserir Manualmente"; @@ -1510,6 +1535,7 @@ "wallet__payment_recipient_rejected" = "O destinatário rejeitou este pagamento Lightning. Verifique a fatura e tente novamente."; "wallet__payment_abandoned" = "O pagamento Lightning foi interrompido antes de ser concluído."; "wallet__payment_expired" = "Este pagamento Lightning expirou. Solicite uma nova fatura."; +"wallet__payment_restored_invoice" = "A Bitkit não consegue confirmar que esta fatura não foi paga antes de você restaurar sua carteira. Solicite uma nova fatura."; "wallet__payment_timeout" = "O pagamento expirou. Tente novamente."; "wallet__payment_route_not_found" = "O Bitkit não conseguiu encontrar uma rota Lightning para este pagamento."; "wallet__payment_retries_exhausted" = "O Bitkit tentou várias rotas Lightning, mas o pagamento não pôde ser concluído."; @@ -1539,7 +1565,7 @@ "wallet__receive_show_qr" = "Mostrar código QR"; "wallet__receive_text_lnfunds" = "Deseja receber via Lightning?"; "wallet__receive_spending" = "Receber no Saldo de Gastos"; -"wallet__receive_spending_text" = "Aproveite pagamentos em bitcoin instantâneos e baratos na Lightning Network."; +"wallet__receive_spending_text" = "Aproveite transações instantâneas e baratas com amigos, família e comerciantes."; "wallet__receive_spending_title" = "Receber no saldo de gastos"; "wallet__receive_cjit_error" = "Falha na Transação"; "wallet__receive_cjit_error_msg" = "Falha ao enviar fundos para sua conta de gastos."; @@ -1556,6 +1582,7 @@ "wallet__activity_failed" = "Falha"; "wallet__activity_transfer" = "Transferência"; "wallet__activity_transferring" = "Transferindo"; +"wallet__activity_move_to_spark" = "Mover para a Spark"; "wallet__activity_transfer_savings_pending" = "Do Saldo de Gastos ({duration})"; "wallet__activity_transfer_savings_done" = "Do Saldo de Gastos"; "wallet__activity_transfer_spending_pending" = "Da Poupança ({duration})"; @@ -2102,3 +2129,5 @@ "subscriptions__allowance_auto_paid" = "Pago automaticamente"; "wallet__balance_updating" = "Atualizando saldo…"; +"lightning__move_to_spark__in_flight_text" = "O pagamento está a caminho e aparece na Spark quando for liquidado. Se falhar, o valor continua na sua conexão."; +"lightning__move_to_spark__in_flight_title" = "Movendo para a\nSpark"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index f48c7b66d8..eaff83932f 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -5,6 +5,7 @@ "wallet__payment_recipient_rejected" = "O destinatário rejeitou este pagamento Lightning. Verifique a fatura e tente novamente."; "wallet__payment_abandoned" = "O pagamento Lightning foi interrompido antes de ser concluído."; "wallet__payment_expired" = "Este pagamento Lightning expirou. Peça uma nova fatura."; +"wallet__payment_restored_invoice" = "A Bitkit não consegue confirmar que esta fatura não foi paga antes de restaurar a sua carteira. Peça uma nova fatura."; "wallet__payment_timeout" = "O pagamento expirou. Tente novamente."; "wallet__send_error_support" = "Suporte"; "wallet__payment_route_not_found" = "O Bitkit não conseguiu encontrar uma rota Lightning para este pagamento."; @@ -251,6 +252,7 @@ "lightning__spending_intro__text" = "Transfira fundos para seu saldo de gastos para desfrutar de transações instantâneas e baratas com amigos, familiares e comerciantes."; "lightning__spending_intro__button" = "Começar"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "Mínimo do saldo de poupança"; "lightning__spending_amount__error_max__title" = "Saldo de gastos Máximo"; "lightning__spending_amount__error_max__description" = "O valor que você pode transferir para seu saldo de gastos está atualmente limitado a ₿ {amount}."; "lightning__spending_amount__error_fee" = "Não foi possível obter a taxa de rede. Toque para tentar novamente."; @@ -356,6 +358,29 @@ "lightning__transaction" = "Transação"; "lightning__order_fee" = "Taxa de pedido"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Montante"; +"lightning__move_to_spark__confirm_text" = "O seu saldo é movido para a Spark através da Lightning, a forma com as taxas mais baixas de o manter em Gastos. A taxa de encaminhamento abaixo é o máximo que paga."; +"lightning__move_to_spark__confirm_title" = "Mover para a\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Parte do seu saldo já está na Spark. Mova o resto da mesma forma e depois feche a conexão esvaziada."; +"lightning__move_to_spark__done_text" = "O seu saldo já está na Spark. Feche a conexão esvaziada para devolver a respetiva reserva à Poupança."; +"lightning__move_to_spark__done_title" = "Movido para a\nSpark"; +"lightning__move_to_spark__failed_nothing" = "As suas conexões Lightning não têm saldo para mover."; +"lightning__move_to_spark__failed_spark" = "A Spark ainda não está pronta para receber. Tente novamente daqui a pouco."; +"lightning__move_to_spark__failed_title" = "Não foi possível\nmover"; +"lightning__move_to_spark__failed_unknown" = "Algo correu mal ao preparar o movimento. Tente novamente."; +"lightning__move_to_spark__fee" = "Taxa de encaminhamento"; +"lightning__move_to_spark__intro_text" = "A Blocktank está a fechar as suas conexões Lightning. Mova agora o seu saldo para a Spark: é a opção com as taxas mais baixas e continua em Gastos."; +"lightning__move_to_spark__intro_title" = "A sua conexão\nvai ser fechada"; +"lightning__move_to_spark__move_half" = "Mover Metade"; +"lightning__move_to_spark__move_now" = "Mover Agora"; +"lightning__move_to_spark__move_rest" = "Mover o Resto"; +"lightning__move_to_spark__nav_title" = "Mover Para a Spark"; +"lightning__move_to_spark__quoting" = "A procurar uma rota e a respetiva taxa…"; +"lightning__move_to_spark__swipe" = "Deslizar Para Mover"; +"lightning__move_to_spark__too_large_none" = "Em vez disso, feche a conexão para devolver o saldo à Poupança."; +"lightning__move_to_spark__too_large_smaller" = "Pode movê-lo em partes mais pequenas."; +"lightning__move_to_spark__too_large_text" = "{amount} é demasiado elevado para encaminhar para a Spark num só pagamento."; +"lightning__move_to_spark__too_large_title" = "Montante\ndemasiado elevado"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Taxa de resgate"; "lightning__spark_confirmations" = "{count}/3 confirmações"; @@ -409,6 +434,7 @@ "lightning__spark_exit__leftover_swept" = "{amount} de taxas de emergência não utilizadas foi enviado para a poupança."; "lightning__spark_exit__leftover_sending" = "A enviar {amount} de taxas de emergência não utilizadas para a poupança."; "lightning__spark_exit__leftover_dust" = "{amount} de taxas de emergência não utilizadas é demasiado pequeno para enviar e fica em {address}, caminho de derivação {path}."; +"lightning__spark_exit__earlier_path" = "Caminho de derivação"; "lightning__spark_exit__lost_leaves" = "{amount} foi reclamado on-chain por um antigo dono destes fundos e não pode ser recuperado."; "lightning__spark_exit__notification_lost" = "{amount} da sua transferência forçada não pode ser recuperado. Abra a Bitkit para ver porquê."; "lightning__spark_exit__notification_failed" = "A sua transferência forçada parou. Abra a Bitkit para ver porquê."; @@ -1174,6 +1200,7 @@ "wallet__swap_route_restored_title" = "Pagamento devolvido às Poupanças"; "wallet__send_paykit_no_route__title" = "Não é possível pagar a este contacto"; "wallet__send_paykit_no_route__description" = "Este contacto não tem neste momento nenhum método de pagamento que a Bitkit possa usar."; +"wallet__send_paykit_withdrawal_settling__description" = "Um saque anterior do seu saldo de gastos ainda está a ser liquidado. Tente novamente quando estiver concluído."; "wallet__recipient_contact" = "Contato"; "wallet__recipient_invoice" = "Colar Invoice"; "wallet__recipient_manual" = "Inserir Manualmente"; @@ -1256,7 +1283,7 @@ "wallet__receive_note_placeholder" = "Comentário opcional para o pagador"; "wallet__receive_show_qr" = "Mostrar código QR"; "wallet__receive_spending" = "Receber fundos Lightning"; -"wallet__receive_spending_text" = "Desfrute de pagamentos em bitcoin instantâneos e baratos na rede Lightning."; +"wallet__receive_spending_text" = "Desfrute de transações instantâneas e baratas com amigos, família e comerciantes."; "wallet__receive_spending_title" = "Receba no saldo de gastos"; "wallet__activity" = "Atividade"; "wallet__activity_no" = "Nenhuma atividade ainda"; @@ -1267,6 +1294,7 @@ "wallet__activity_failed" = "Falha"; "wallet__activity_transfer" = "Transferência"; "wallet__activity_transferring" = "Em transferência"; +"wallet__activity_move_to_spark" = "Mover para a Spark"; "wallet__activity_transfer_savings_pending" = "Do Saldo de Gastos (±{duration})"; "wallet__activity_transfer_savings_done" = "Do Saldo de Gastos"; "wallet__activity_transfer_spending_pending" = "Da Poupança (±{duration})"; @@ -1748,5 +1776,7 @@ "subscriptions__allowance_auto_paid" = "Pago automaticamente"; "wallet__balance_updating" = "A atualizar o saldo…"; +"lightning__move_to_spark__in_flight_text" = "O pagamento está a caminho e aparece na Spark quando for liquidado. Se falhar, o montante fica na sua conexão."; +"lightning__move_to_spark__in_flight_title" = "A mover para a\nSpark"; "other__error_keychain" = "Problema de Ligação de Dados"; "other__error_keychain_msg" = "Não foi possível carregar a chave principal do porta-chaves."; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index f339835a0c..5ba62a1073 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -231,6 +231,7 @@ "lightning__transfer_failed__cancel" = "Проверить Ошибку"; "lightning__transfer_failed__continue" = "Попробовать Снова"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "Минимум Баланса Сбережений"; "lightning__spending_amount__error_max__title" = "Максимум Баланса Расходов"; "lightning__spending_amount__error_max__description" = "Сумма, которую вы можете перевести на баланс расходов, в настоящее время ограничена ₿ {amount}."; "lightning__spending_amount__error_fee" = "Не удалось получить сетевую комиссию. Нажмите, чтобы повторить."; @@ -353,6 +354,29 @@ "lightning__transaction" = "Транзакция"; "lightning__order_fee" = "Комиссия Ордера"; "lightning__balance" = "Баланс"; +"lightning__move_to_spark__amount" = "Сумма"; +"lightning__move_to_spark__confirm_text" = "Ваш баланс переносится в Spark через Lightning — это самый дешёвый способ сохранить его в Расходах. Комиссия за маршрутизацию ниже — максимум, который вы заплатите."; +"lightning__move_to_spark__confirm_title" = "Перенос в\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Часть вашего баланса уже в Spark. Перенесите остаток так же, а затем закройте опустевшее соединение."; +"lightning__move_to_spark__done_text" = "Ваш баланс уже в Spark. Закройте опустевшее соединение, чтобы вернуть его резерв в Сбережения."; +"lightning__move_to_spark__done_title" = "Перенесено в\nSpark"; +"lightning__move_to_spark__failed_nothing" = "На ваших Lightning соединениях не осталось баланса для переноса."; +"lightning__move_to_spark__failed_spark" = "Spark пока не готов принимать платежи. Попробуйте ещё раз чуть позже."; +"lightning__move_to_spark__failed_title" = "Не удалось\nперенести"; +"lightning__move_to_spark__failed_unknown" = "Что-то пошло не так при подготовке переноса. Попробуйте снова."; +"lightning__move_to_spark__fee" = "Комиссия за маршрутизацию"; +"lightning__move_to_spark__intro_text" = "Blocktank закрывает свои Lightning соединения. Перенесите баланс в Spark сейчас: это самый дешёвый вариант, и баланс останется в Расходах."; +"lightning__move_to_spark__intro_title" = "Ваше соединение\nзакрывается"; +"lightning__move_to_spark__move_half" = "Перенести Половину"; +"lightning__move_to_spark__move_now" = "Перенести Сейчас"; +"lightning__move_to_spark__move_rest" = "Перенести Остаток"; +"lightning__move_to_spark__nav_title" = "Перенос в Spark"; +"lightning__move_to_spark__quoting" = "Поиск маршрута и комиссии…"; +"lightning__move_to_spark__swipe" = "Проведите для Переноса"; +"lightning__move_to_spark__too_large_none" = "Вместо этого закройте соединение, чтобы вернуть баланс в Сбережения."; +"lightning__move_to_spark__too_large_smaller" = "Вы можете перенести её несколькими частями поменьше."; +"lightning__move_to_spark__too_large_text" = "Сумма {amount} слишком велика, чтобы направить её в Spark одним платежом."; +"lightning__move_to_spark__too_large_title" = "Сумма\nслишком велика"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Комиссия за зачисление"; "lightning__spark_confirmations" = "{count}/3 подтверждений"; @@ -406,6 +430,7 @@ "lightning__spark_exit__leftover_swept" = "Неиспользованные экстренные комиссии ({amount}) отправлены в сбережения."; "lightning__spark_exit__leftover_sending" = "Отправка неиспользованных экстренных комиссий ({amount}) в сбережения."; "lightning__spark_exit__leftover_dust" = "Неиспользованные экстренные комиссии в размере {amount} слишком малы для отправки и остаются на {address}, путь деривации {path}."; +"lightning__spark_exit__earlier_path" = "Путь деривации"; "lightning__spark_exit__lost_leaves" = "{amount} забрал ончейн один из прежних владельцев этих средств, их нельзя вернуть."; "lightning__spark_exit__notification_lost" = "{amount} из вашего принудительного перевода нельзя вернуть. Откройте Bitkit, чтобы узнать причину."; "lightning__spark_exit__notification_failed" = "Ваш принудительный перевод остановлен. Откройте Bitkit, чтобы узнать причину."; @@ -1404,6 +1429,7 @@ "wallet__swap_route_restored_title" = "Платёж возвращён в Сбережения"; "wallet__send_paykit_no_route__title" = "Не удаётся оплатить этому контакту"; "wallet__send_paykit_no_route__description" = "У этого контакта сейчас нет способа оплаты, который может использовать Bitkit."; +"wallet__send_paykit_withdrawal_settling__description" = "Предыдущий вывод с баланса расходов ещё не завершён. Попробуйте снова, когда он завершится."; "wallet__recipient_contact" = "Контакт"; "wallet__recipient_invoice" = "Вставить Инвойс"; "wallet__recipient_manual" = "Ввести Вручную"; @@ -1493,6 +1519,7 @@ "wallet__payment_recipient_rejected" = "Получатель отклонил этот платеж Lightning. Проверьте счет и попробуйте снова."; "wallet__payment_abandoned" = "Платеж Lightning был остановлен до завершения."; "wallet__payment_expired" = "Срок действия этого платежа Lightning истек. Запросите новый счет."; +"wallet__payment_restored_invoice" = "Bitkit не может подтвердить, что этот счёт не был оплачен до восстановления вашего кошелька. Запросите новый счёт."; "wallet__payment_timeout" = "Время ожидания платежа истекло. Попробуйте еще раз."; "wallet__payment_route_not_found" = "Bitkit не смог найти маршрут Lightning для этого платежа."; "wallet__payment_retries_exhausted" = "Bitkit попробовал несколько маршрутов Lightning, но платеж не удалось завершить."; @@ -1522,7 +1549,7 @@ "wallet__receive_show_qr" = "Показать QR-код"; "wallet__receive_text_lnfunds" = "Хотите получить Лайтнинг средства?"; "wallet__receive_spending" = "Получить Lightning средства"; -"wallet__receive_spending_text" = "Наслаждайтесь мгновенными и дешёвыми биткоин-платежами в сети Lightning."; +"wallet__receive_spending_text" = "Наслаждайтесь мгновенными и дешёвыми транзакциями с друзьями, семьёй и продавцами."; "wallet__receive_spending_title" = "Получить на баланс расходов"; "wallet__receive_cjit_error" = "Транзакция не удалась"; "wallet__receive_cjit_error_msg" = "Не удалось отправить средства на ваш Баланс Расходов."; @@ -1539,6 +1566,7 @@ "wallet__activity_failed" = "Не удалось"; "wallet__activity_transfer" = "Перенос"; "wallet__activity_transferring" = "Перевод"; +"wallet__activity_move_to_spark" = "Перенос в Spark"; "wallet__activity_transfer_savings_pending" = "От Расходов ({duration}м)"; "wallet__activity_transfer_savings_done" = "От Расходов"; "wallet__activity_transfer_spending_pending" = "От Сбережений ({duration}м)"; @@ -2082,3 +2110,5 @@ "subscriptions__allowance_auto_paid" = "Оплачено автоматически"; "wallet__balance_updating" = "Обновление баланса…"; +"lightning__move_to_spark__in_flight_text" = "Платёж в пути и появится в Spark после завершения. Если он не пройдёт, сумма останется в вашем соединении."; +"lightning__move_to_spark__in_flight_title" = "Идёт перенос\nв Spark"; diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 95a0cb040b..d200a87a02 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -1,5 +1,6 @@ import BitkitCore import Combine +import CryptoKit import Foundation import Paykit import VssRustClientFfi @@ -134,7 +135,14 @@ class BackupService { /// Set while the Spark exit data restore hasn't succeeded or found no older backup, kept across launches, so a fresh /// export never replaces the remote backup it couldn't read yet. private static let sparkExitRestorePendingKey = "sparkExitRestorePending" + /// The prefix of the remote keys of exit data Spark rejected for good: each copy goes under this plus `_` and the first + /// 16 hex digits of its SHA-256. + static let sparkExitRejectedKey = "SPARK_EXIT_REJECTED" private let backupData: ((BackupCategory) async throws -> Data)? + private let importStagedSparkExit: () async -> SparkStagedExitImport + private let discardStagedSparkExit: (String) async -> Void + private let stagedSparkExitState: () async throws -> String? + private let restoreExitBackup: (SparkExitBackupV1) async throws -> Void private let isSparkExitActive: () async -> Bool private let uploadBackup: (String, Data) async throws -> Void private let waitForBackupDelay: () async throws -> Void @@ -182,9 +190,25 @@ class BackupService { }, fetchBackup: @escaping (String) async throws -> Data? = { key in try await VssBackupClient.shared.getObject(key: key)?.value + }, + importStagedSparkExit: @escaping () async -> SparkStagedExitImport = { @MainActor in + await SparkManager.shared.importStagedExitState(walletIndex: LightningService.shared.currentWalletIndex) + }, + discardStagedSparkExit: @escaping (String) async -> Void = { @MainActor exitState in + SparkManager.shared.discardStagedExitState(exitState, walletIndex: LightningService.shared.currentWalletIndex) + }, + stagedSparkExitState: @escaping () async throws -> String? = { @MainActor in + try SparkManager.shared.stagedExitState(walletIndex: LightningService.shared.currentWalletIndex) + }, + restoreExitBackup: @escaping (SparkExitBackupV1) async throws -> Void = { @MainActor backup in + try await SparkManager.shared.restoreExitBackup(backup, walletIndex: LightningService.shared.currentWalletIndex) } ) { self.defaults = defaults + self.importStagedSparkExit = importStagedSparkExit + self.discardStagedSparkExit = discardStagedSparkExit + self.stagedSparkExitState = stagedSparkExitState + self.restoreExitBackup = restoreExitBackup self.isSparkExitActive = isSparkExitActive self.fetchBackup = fetchBackup self.backupData = backupData @@ -434,9 +458,33 @@ class BackupService { await restoreSparkExit() } guard !defaults.bool(forKey: Self.sparkExitRestorePendingKey) else { throw SparkExitBackupError.restorePending } - // Restored exit data Spark couldn't import yet lives only in the remote backup, so nothing replaces it. - guard await !SparkManager.shared.hasStagedExitState(walletIndex: LightningService.shared.currentWalletIndex) else { + // Restored exit data Spark couldn't import yet lives only in the remote backup, so nothing replaces it, unless + // Spark can never import it: then a copy of it is set aside and fresh exports go up again. + switch await importStagedSparkExit() { + case .pending: throw SparkExitBackupError.restorePending + case .rejected: + var isReplacedRemotely = false + let staged = try await stagedSparkExitState() + if let staged { + let copy = try await rejectedSparkExitCopy(staged: staged) + try await setAsideRejectedSparkExit(copy.data) + isReplacedRemotely = copy.isReplacedRemotely + } + // Another device replaced the backup with exit data this one never read, so it is restored before + // anything replaces it; noted before the staged copy goes, so a stop in between still restores it. + if isReplacedRemotely { + defaults.set(true, forKey: Self.sparkExitRestorePendingKey) + } + if let staged { + await discardStagedSparkExit(staged) + } + if isReplacedRemotely { + await restoreSparkExit() + throw SparkExitBackupError.restorePending + } + case .nothingStaged, .imported: + break } // Nothing to back up until Spark connects, which marks this category required again. if let data = try await sparkExitBackupData() { @@ -795,6 +843,7 @@ class BackupService { SparkExitEarlierAddressBackup.restore(payload.sparkExitEarlierAddresses, network: "\(Env.network)") { SparkExitEarlierAddressStore(walletIndex: $0) } + await MoveToSparkPayments.restore(payload.moveToSparkPaymentHashes) // Force address rotation by clearing onchain address UserDefaults.standard.set("", forKey: "onchainAddress") @@ -968,6 +1017,15 @@ class BackupService { } .store(in: cancellables) + // METADATA (moves to Spark). Marked as the hash is saved, so a stop right after can't leave a later Activity backup + // holding the move without the metadata that names it one. + MoveToSparkPayments.savedPublisher + .sink { @Sendable [weak self] _ in + guard let self, !self.shouldSkipBackup() else { return } + markBackupRequired(category: .metadata) + } + .store(in: cancellables) + // APP STATE (UserDefaults changes, etc.) SettingsViewModel.shared.appStatePublisher .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) @@ -1397,6 +1455,7 @@ class BackupService { // case to guard against. Nil rather than an empty map when nothing is named, so an // envelope this app writes stays byte-comparable with one bitkit-android writes. let hwWalletNames = HwKnownDeviceStorage.backupSnapshot() + let moveToSparkPaymentHashes = await MoveToSparkPayments.backupSnapshot() let payload = MetadataBackupV1( version: 1, @@ -1409,7 +1468,8 @@ class BackupService { sparkExitEarlierAddresses: SparkExitEarlierAddressBackup.backup( SparkExitEarlierAddressStore(walletIndex: LightningService.shared.currentWalletIndex), walletKey: SparkExitFundingIndexes.walletKey(network: "\(Env.network)", walletIndex: LightningService.shared.currentWalletIndex) - ) + ), + moveToSparkPaymentHashes: moveToSparkPaymentHashes.isEmpty ? nil : moveToSparkPaymentHashes ) return try JSONEncoder().encode(payload) @@ -1468,9 +1528,21 @@ class BackupService { defaults.set(true, forKey: Self.sparkExitRestorePendingKey) do { if let data = try await fetchBackup(BackupCategory.sparkExit.rawValue) { - let backup = try JSONDecoder().decode(SparkExitBackupV1.self, from: data) - try await SparkManager.shared.restoreExitBackup(backup, walletIndex: LightningService.shared.currentWalletIndex) - Logger.info("Restore success for: '\(BackupCategory.sparkExit.rawValue)'", context: "BackupService") + let backup: SparkExitBackupV1 + do { + backup = try JSONDecoder().decode(SparkExitBackupV1.self, from: data) + } catch let error as Swift.DecodingError { + // A layout this app can't read never becomes readable here, so it is kept apart for an app that can. + Logger.warn("Unreadable '\(BackupCategory.sparkExit.rawValue)' backup: \(error)", context: "BackupService") + try await setAsideRejectedSparkExit(data) + // Another device may have written a backup meanwhile; it is read before anything replaces it. + guard try await fetchBackup(BackupCategory.sparkExit.rawValue) == data else { return } + defaults.removeObject(forKey: Self.sparkExitRestorePendingKey) + return + } + try await restoreExitBackup(backup) + // Spark imports it only once connected, and may still reject it then. + Logger.info("Staged '\(BackupCategory.sparkExit.rawValue)' for Spark's import", context: "BackupService") } else { Logger.warn("Restore null for: '\(BackupCategory.sparkExit.rawValue)'", context: "BackupService") } @@ -1480,6 +1552,38 @@ class BackupService { } } + /// The remote exit backup when it still holds the staged data, byte for byte as it came; otherwise, as another device + /// may have replaced it since, the staged data in a backup of its own, and whether the remote holds other data. + private func rejectedSparkExitCopy(staged: String) async throws -> (data: Data, isReplacedRemotely: Bool) { + let remote = try await fetchBackup(BackupCategory.sparkExit.rawValue) + let remoteBackup = remote.flatMap { try? JSONDecoder().decode(SparkExitBackupV1.self, from: $0) } + if let remote, remoteBackup?.exitState == staged { + return (remote, false) + } + let copy = try JSONEncoder().encode(SparkExitBackupV1( + version: 1, + createdAt: UInt64(Date().timeIntervalSince1970 * 1000), + network: remoteBackup?.network ?? SparkManager.exitBackupNetworkName(Env.network), + exitState: staged + )) + return (copy, remote != nil) + } + + /// Keeps exit data Spark can never import under a key of its own, so a fresh export doesn't replace it and it stays + /// recoverable. The key is derived from the data, so devices setting different copies aside at once never overwrite + /// each other's. Nothing reads them back yet. + private func setAsideRejectedSparkExit(_ data: Data) async throws { + let key = Self.rejectedSparkExitKey(for: data) + guard try await fetchBackup(key) == nil else { return } + try await uploadBackup(key, data) + Logger.warn("Set Spark exit data Spark can't import aside as '\(key)'", context: "BackupService") + } + + static func rejectedSparkExitKey(for data: Data) -> String { + let digest = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + return sparkExitRejectedKey + "_" + digest.prefix(16) + } + /// Nothing while an exit runs: the operators may stop reporting a leaf once it is being exited, so a fresh export /// could drop the very leaf a restored wallet needs. The backup from before the exit stays. private func sparkExitBackupData() async throws -> Data? { diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 595383b893..0129fa61f2 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1015,8 +1015,14 @@ class ActivityService { // The Spark receive of a move can settle the send before the node's routing fee is recorded. let feeChanging = payment.feePaidMsat.map { $0 / 1000 != existing.fee } ?? false let needsPrivateContactAttribution = existing.contact == nil && payment.direction == .inbound + // Spark dates each attempt at its start: of two failed attempts, the later one's amount, fee and time stay. + let isRailFailureOverFailure = rail == .channelFree && state == .failed && existing.status == .failed + if isRailFailureOverFailure, existing.timestamp > paymentTimestamp { + return + } + let isLaterRailFailure = isRailFailureOverFailure && paymentTimestamp > existing.timestamp if existingUpdatedAt > paymentTimestamp && !statusChanging && !feeChanging && !needsPrivateContactAttribution - && !replacesSelfReceive + && !replacesSelfReceive && !isLaterRailFailure { return } @@ -1400,6 +1406,20 @@ class ActivityService { return !onchain.doesExist && onchain.txType == .sent && txIdsInBoostTxIds.contains(onchain.txId) } + /// Marks the stored Lightning send `id` failed while it is still pending, read, checked and written in one core-queue + /// operation, so a change saved meanwhile isn't overwritten. + func failPendingLightningSend(id: String) async throws { + try await ServiceQueue.background(.core) { + guard case let .lightning(activity) = try getActivityById(walletId: WalletScope.default, activityId: id), + activity.txType == .sent, activity.status == .pending + else { return } + var failed = activity + failed.status = .failed + try updateActivity(activityId: id, activity: .lightning(failed)) + self.activitiesChangedSubject.send() + } + } + func update(id: String, activity: Activity) async throws { try await ServiceQueue.background(.core) { try updateActivity(activityId: id, activity: activity) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 8c0664faf0..03976e1237 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -164,6 +164,9 @@ class LightningService: NodeLifecycleService { private var attemptRails: [String: LightningPaymentRail] = [:] /// Payment hashes inside a rail send, which Spark lists only once it returns. private var railSendsInFlight: Set = [] + /// Per payment hash, the latest time Spark dated a failed attempt of it, from its list or its events, so a send's + /// start is saved after it and that failure never reads as the send's own. + private var railFailureCreatedAt: [String: UInt64] = [:] /// Counts attempts recorded in this run, so a listing drops a hash just when the hash was recorded before the /// listing was read, never a retry recorded while it was read. private var attemptRecords = 0 @@ -175,6 +178,9 @@ class LightningService: NodeLifecycleService { /// The rail whose payments the duplicate-payment check reads, kept while an emergency exit takes Spark off /// Lightning: an invoice Spark paid or is paying is never paid again over a channel. weak var channelFreePaymentHistory: ChannelFreeLightningRail? + /// Writes the Activity row of a rail send Spark never settled once its invoice expired: from Spark's own attempt of it + /// when listed, otherwise by failing the stored pending row. Returns whether the row was saved. + var railSendExpired: ((String) async -> Bool)? var onchainTransactionConfirmed: (@Sendable (String) async -> Void)? var onchainTransactionReceived: (@Sendable (String) async -> Void)? typealias OnchainActivityCompletion = @MainActor () async -> Void @@ -1096,7 +1102,8 @@ class LightningService: NodeLifecycleService { bolt11: bolt11, sats: sats, invoiceCreatedAt: invoice?.secondsSinceEpoch(), - invoiceExpiresAt: expiresAt + invoiceExpiresAt: expiresAt, + sendsOverRail: true ) { return paid } @@ -1126,7 +1133,7 @@ class LightningService: NodeLifecycleService { } var isRefusedAtAdmission = false do { - let sent = try await rail.send( + return try await rail.send( bolt11: bolt11, sats: sats, maxFeeSats: params?.maxTotalRoutingFeeMsat.map { $0 / 1000 } @@ -1142,16 +1149,13 @@ class LightningService: NodeLifecycleService { // Noted once admitted, so a refused attempt never takes the place of the one that went out. self?.noteAttempt(on: .channelFree, bolt11: bolt11) self?.recordRailAttempt(paymentHash: paymentHash, expiresAt: expiresAt) - // Kept until the call returns, so a send cut off by process death stays held after a relaunch. + // Kept until Spark settles the attempt, so no retry of the invoice starts meanwhile, also after a + // relaunch. if let paymentHash { self?.markRailSendUncertain(paymentHash: paymentHash, since: mark) } } ) - if let paymentHash { - endRailSendUncertainty(paymentHash: paymentHash) - } - return sent } catch let refusal as ChannelFreeRailSendRefused { // Nothing left the wallet, and the checks above leave no earlier live attempt under this hash. if let paymentHash { @@ -1231,9 +1235,9 @@ class LightningService: NodeLifecycleService { /// The clock a trim checks invoice expiries against; tests set it. var now: () -> Date = Date.init private static let railAttemptsKey = "channelFreeRailAttemptedPaymentHashes" - /// Rail sends submitted but not returned, or that failed after they were submitted, by hash, with the time they - /// were submitted or failed in seconds since 1970. Kept across launches, as Spark may still resume one after a - /// relaunch while its list shows an earlier failed attempt. + /// Rail sends Spark hasn't settled yet, from submission until Spark reports or lists their attempt succeeded or failed, + /// or their invoice expired, by hash, with the time they were submitted in seconds since 1970. No other + /// send of the invoice starts meanwhile. Kept across launches, as Spark may still resume one after a relaunch. private static let uncertainRailSendsKey = "channelFreeRailUncertainSendFailedAt" /// A listing drops the hashes it shows failed only, or paid once the invoice has expired, so the other rail can't /// pay it again, and ones it doesn't show once the invoice expired `unlistedAttemptSettleSeconds` ago. Paid or @@ -1429,6 +1433,7 @@ class LightningService: NodeLifecycleService { railAttemptsStore.removeObject(forKey: Self.railAttemptsKey) railAttemptsStore.removeObject(forKey: Self.expiriesKey(Self.railAttemptsKey)) attemptRecordedAt[Self.railAttemptsKey] = nil + railFailureCreatedAt = [:] } } @@ -1484,7 +1489,9 @@ class LightningService: NodeLifecycleService { let outbound = payments.filter { $0.direction == .outbound } let hashes = { (status: PaymentStatus) in Set(outbound.filter { $0.status == status }.map { $0.paymentHash.lowercased() }) } return eventCallbackLock.withLock { + // A send Spark hasn't settled keeps its record and expiry, whatever its earlier attempts show. let live = hashes(.pending).union(attemptsLive(since: mark, key: Self.railAttemptsKey)) + .union(uncertainRailSendFailedAt().keys) let paid = hashes(.succeeded).subtracting(live) let listed = Set(outbound.map { $0.paymentHash.lowercased() }) trimSettledAttempts( @@ -1510,7 +1517,8 @@ class LightningService: NodeLifecycleService { bolt11: String, sats: UInt64?, invoiceCreatedAt: UInt64?, - invoiceExpiresAt: Int? + invoiceExpiresAt: Int?, + sendsOverRail: Bool = false ) async throws -> PaymentHash? { guard let paymentHash else { return nil } var statuses: [PaymentStatus] = rails.contains(.channelFree) && isRailSendInFlight(paymentHash: paymentHash) ? [.pending] : [] @@ -1573,10 +1581,18 @@ class LightningService: NodeLifecycleService { } else if isPaidOverTheNode { Logger.info("Skipped Spark's restore checks of '\(paymentHash)', the node already paid it", context: "LightningService") } else { - try await refuseUnverifiedRestoredInvoice( + let restoredSends = try await refuseUnverifiedRestoredInvoice( paymentHash: paymentHash, bolt11: bolt11, sats: sats, invoiceCreatedAt: invoiceCreatedAt, invoiceExpiresAt: invoiceExpiresAt ) + // A Spark send's start must come after every failure Spark dated for the invoice, which only its list + // shows after a relaunch, so it doesn't go out unlisted, unless Spark's operators show no send of it. + if sendsOverRail, restoredSends != .noSend { + Logger.warn("Refused paying '\(paymentHash)' over Spark, Spark can't list its payments now", context: "LightningService") + throw restoredSends == .allFailed + ? ChannelFreeRailSendRefused.restoredInvoiceUnverified() + : ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description")) + } } } if statuses.contains(.succeeded) { @@ -1593,26 +1609,29 @@ class LightningService: NodeLifecycleService { /// After a restore, refuses a still-valid invoice created before it, as Spark's list can lack a send it made then, /// unless Spark's operators show no live or paid Lightning send of it and it can't have been paid by a direct Spark /// transfer, which they can't see. A send they show sent or pending, or no answer, refuses it until it expires. A - /// failed one counts as unsent, as they show it failed only once every attempt at the hash was returned. + /// failed one counts as unsent, as they show it failed only once every attempt at the hash was returned. Returns + /// what they show of a pre-restore invoice's sends, nil for any other invoice. + @discardableResult private func refuseUnverifiedRestoredInvoice( paymentHash: String, bolt11: String, sats: UInt64?, invoiceCreatedAt: UInt64?, invoiceExpiresAt: Int? - ) async throws { + ) async throws -> RestoredInvoiceSends? { guard let restoredAt = sparkRestoredAt, Self.holdsRestoredInvoice( restoredAt: restoredAt, invoiceCreatedAt: invoiceCreatedAt, invoiceExpiresAt: invoiceExpiresAt, now: Int(now().timeIntervalSince1970) - ) else { return } + ) else { return nil } let rail = channelFreeRail ?? channelFreePaymentHistory let sparkRuns = rail != nil ? true : await channelFreeRailSupported() - guard sparkRuns else { return } + guard sparkRuns else { return nil } do { guard let rail else { throw ChannelFreeRailUnavailable() } - if let status = try await rail.lightningSendStatus(bolt11: bolt11), status != .failed { + let status = try await rail.lightningSendStatus(bolt11: bolt11) + if let status, status != .failed { Logger.warn("Refused paying '\(paymentHash)', a pre-restore invoice Spark shows as '\(status)'", context: "LightningService") throw ChannelFreeRailSendRefused.restoredInvoiceUnverified() } @@ -1621,6 +1640,7 @@ class LightningService: NodeLifecycleService { throw ChannelFreeRailSendRefused.restoredInvoiceUnverified() } Logger.info("Found no live or paid Spark operator send of pre-restore invoice '\(paymentHash)'", context: "LightningService") + return status == nil ? .noSend : .allFailed } catch let refusal as ChannelFreeRailSendRefused { throw refusal } catch { @@ -1632,6 +1652,14 @@ class LightningService: NodeLifecycleService { } } + /// What Spark's operators show of a pre-restore invoice's sends that leaves it payable. + enum RestoredInvoiceSends { + /// No send of it. + case noSend + /// Sends that all failed. + case allFailed + } + /// An unknown time counts as before the restore and never expiring. static func holdsRestoredInvoice(restoredAt: Int, invoiceCreatedAt: UInt64?, invoiceExpiresAt: Int?, now: Int) -> Bool { Int(clamping: invoiceCreatedAt ?? 0) < restoredAt && invoiceExpiresAt.map { now < $0 } ?? true @@ -1647,19 +1675,79 @@ class LightningService: NodeLifecycleService { railAttemptsStore.dictionary(forKey: Self.uncertainRailSendsKey) as? [String: Int] ?? [:] } - /// A rail send about to be submitted, or that failed after it was, until a sync after it and its invoice's expiry - /// settle it. The expiry is the one kept beside the hash. + /// A rail send about to be submitted, or that failed after it was, until Spark settles its attempt or a sync after its + /// invoice's expiry settles it. The expiry is the one kept beside the hash, and the time the one it was submitted at, + /// which a later failure of its call leaves as it is. That time is past the clock margin after any failed attempt + /// Spark dated for the hash so far, so that failure reads as an earlier attempt's, also after a relaunch. private func markRailSendUncertain(paymentHash: String, since mark: AttemptMark) { let hash = paymentHash.lowercased() - let failedAt = Int(max(0, now().timeIntervalSince1970)) + let now = Int64(max(0, now().timeIntervalSince1970)) eventCallbackLock.withLock { guard attemptsRecorded(since: mark.records, key: Self.railAttemptsKey).contains(hash) else { return } var uncertain = uncertainRailSendFailedAt() - uncertain[hash] = failedAt + guard uncertain[hash] == nil else { return } + let afterKnownFailure = railFailureCreatedAt[hash].map { Int64(clamping: $0) + Self.railClockSkewSeconds + 1 } ?? 0 + uncertain[hash] = Int(clamping: max(now, afterKnownFailure)) railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) } } + /// How far before a send's start, by this device's clock, Spark may date the send's own attempt. + static let railClockSkewSeconds: Int64 = 10 + + /// Whether a Spark attempt of `paymentHash` created at `createdAt`, in seconds since 1970, came before the send of it + /// Spark hasn't settled yet: Spark dates an attempt at its start, and a retry starts only once the attempts before it + /// failed. Its failure settles nothing of that send, so it is ignored. + func isEarlierRailAttempt(paymentHash: String, createdAt: UInt64?) -> Bool { + guard let createdAt else { return false } + return eventCallbackLock.withLock { + uncertainRailSendFailedAt()[paymentHash.lowercased()].map { !Self.isOwnRailAttempt(createdAt: createdAt, startedAt: $0) } ?? false + } + } + + /// Whether Spark dated an attempt at or after a send's start, less the clock margin: that send's own. + private static func isOwnRailAttempt(createdAt: UInt64, startedAt: Int) -> Bool { + Int64(clamping: createdAt) >= Int64(startedAt) - railClockSkewSeconds + } + + private static func listsResult(_ payments: [ChannelFreeRailPayment], paymentHash: String, startedAt: Int?) -> Bool { + payments.contains { payment in + guard payment.direction == .outbound, payment.paymentHash.lowercased() == paymentHash.lowercased() else { return false } + if payment.status == .succeeded { + return true + } + guard payment.status == .failed, let startedAt else { return false } + return isOwnRailAttempt(createdAt: payment.timestamp, startedAt: startedAt) + } + } + + /// The held rail sends and when each started, read before a listing so it settles only those. + var railSendHolds: [String: Int] { + eventCallbackLock.withLock { uncertainRailSendFailedAt() } + } + + /// Ends the sends Spark lists a settled attempt of: a success, or a failure of the send's own attempt. Only the holds + /// in `heldBefore`, read before the listing, as one taken since started after Spark's list was read. + func settleListedRailSends(_ payments: [ChannelFreeRailPayment], heldBefore: [String: Int]) { + let settled = eventCallbackLock.withLock { + for payment in payments where payment.direction == .outbound && payment.status == .failed { + noteRailFailure(paymentHash: payment.paymentHash, createdAt: payment.timestamp) + } + let uncertain = uncertainRailSendFailedAt() + return payments.reduce(into: [String: Int]()) { settled, payment in + let hash = payment.paymentHash.lowercased() + guard payment.direction == .outbound, payment.status != .pending, let startedAt = uncertain[hash], + heldBefore[hash] == startedAt, + payment.status == .succeeded || Self.isOwnRailAttempt(createdAt: payment.timestamp, startedAt: startedAt) + else { return } + settled[hash] = startedAt + } + } + for (hash, startedAt) in settled { + endRailSendUncertainty(paymentHash: hash, startedAt: startedAt) + } + } + /// Rail sends whose outcome stayed unknown, listed as pending until a sync after them reaches the rail: Spark may /// still finish one, while its own list shows only an earlier attempt, or nothing. private func unsettledUncertainRailSends() async -> [ChannelFreeRailPayment] { @@ -1685,10 +1773,49 @@ class LightningService: NodeLifecycleService { } private func endRailSendUncertainty(paymentHash: String) { + endRailSendUncertainty(paymentHash: paymentHash) { _ in true } + } + + /// Ends the send held since `startedAt` only: once it ended, a retry may hold the invoice again, and that retry stays + /// held. + private func endRailSendUncertainty(paymentHash: String, startedAt: Int) { + endRailSendUncertainty(paymentHash: paymentHash) { $0 == startedAt } + } + + private func endRailSendUncertainty(paymentHash: String, where isEnded: (Int) -> Bool) { + let hash = paymentHash.lowercased() eventCallbackLock.withLock { var uncertain = uncertainRailSendFailedAt() - guard uncertain.removeValue(forKey: paymentHash.lowercased()) != nil else { return } + guard let startedAt = uncertain[hash], isEnded(startedAt) else { return } + uncertain.removeValue(forKey: hash) + railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) + } + } + + /// Callers hold `eventCallbackLock`. + private func noteRailFailure(paymentHash: String, createdAt: UInt64) { + let hash = paymentHash.lowercased() + railFailureCreatedAt[hash] = max(railFailureCreatedAt[hash] ?? 0, createdAt) + } + + /// Whether a Spark failure, of an attempt created at `createdAt`, is the failure of the invoice's send, ending its hold + /// if it has one, in one step, so a retry that holds the invoice meanwhile is judged by its own hold. Not when Spark + /// dated it before the send Spark hasn't settled yet, or while a send in Spark's send call wasn't submitted yet, as + /// nothing of it reached Spark: an earlier attempt's, while that send may still pay. + private func endRailSendByFailure(paymentHash: String, createdAt: UInt64?) -> Bool { + let hash = paymentHash.lowercased() + return eventCallbackLock.withLock { + if let createdAt { + noteRailFailure(paymentHash: hash, createdAt: createdAt) + } + var uncertain = uncertainRailSendFailedAt() + guard let startedAt = uncertain[hash] else { return !railSendsInFlight.contains(hash) } + if let createdAt, !Self.isOwnRailAttempt(createdAt: createdAt, startedAt: startedAt) { + return false + } + uncertain.removeValue(forKey: hash) railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) + return true } } @@ -1697,17 +1824,32 @@ class LightningService: NodeLifecycleService { private func railSyncedSinceUncertainSend(paymentHash: String) async -> Bool { let hash = paymentHash.lowercased() let uncertain = eventCallbackLock.withLock { - uncertainRailSendFailedAt()[hash].map { (failedAt: UInt64($0), expiresAt: attemptExpiries(key: Self.railAttemptsKey)[hash]) } + uncertainRailSendFailedAt()[hash].map { (startedAt: $0, expiresAt: attemptExpiries(key: Self.railAttemptsKey)[hash]) } } guard let uncertain else { return true } - guard let rail = channelFreeRail, await rail.hasSynced(after: uncertain.failedAt) else { return false } // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark // can still fail to resume it, so only an expired invoice shows a missing send will never go out. guard let expiresAt = uncertain.expiresAt, Int(now().timeIntervalSince1970) >= expiresAt else { return false } - endRailSendUncertainty(paymentHash: hash) + // During an exit Spark no longer sends but still syncs its history, which settles the send the same way. + guard let rail = channelFreeRail ?? channelFreePaymentHistory, await rail.hasSynced(after: UInt64(uncertain.startedAt)) else { + return false + } + // Its Activity row is written first, so a stop in between finds the send held and writes it again. + if let record = railSendExpired, await !record(hash) { + return false + } + endRailSendUncertainty(paymentHash: hash, startedAt: uncertain.startedAt) return true } + /// Ends the sends Spark never settled whose invoice expired since, once a sync after the grace reached Spark. + func endExpiredRailSendUncertainties() async { + let hashes = eventCallbackLock.withLock { Array(uncertainRailSendFailedAt().keys) } + for hash in hashes { + _ = await railSyncedSinceUncertainSend(paymentHash: hash) + } + } + private static func pendingDuplicate(paymentHash: String?) -> NodeError { .DuplicatePayment(message: "An earlier attempt to pay '\(paymentHash ?? "")' is still pending") } @@ -2331,11 +2473,16 @@ extension LightningService { } /// Spark runs before the node starts, so its events wait until the node's event callback is set rather than being lost. - func emitChannelFreeRailEvent(_ event: Event) { + /// `paymentCreatedAt` is when Spark created the payment the event is about, in seconds since 1970. + func emitChannelFreeRailEvent(_ event: Event, paymentCreatedAt: UInt64? = nil) { switch event { case let .paymentFailed(_, paymentHash?, _): - // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. - endRailSendUncertainty(paymentHash: paymentHash) + // An attempt before the send Spark hasn't settled yet ended: that send may still pay, so nothing changes. + // Otherwise the event settles a send whose outcome was unknown, so retries of its invoice are no longer held. + guard endRailSendByFailure(paymentHash: paymentHash, createdAt: paymentCreatedAt) else { + Logger.info("Ignored a Spark failure of an attempt before an unsettled send: \(event)", context: "LightningService") + return + } // The failure of the send itself, which may arrive while its send call is still returning. releaseRailAttempt(paymentHash: paymentHash, unlessInFlight: false) case let .paymentSuccessful(_, paymentHash, _, _): @@ -2392,9 +2539,19 @@ extension LightningService { // nothing. guard await rail.hasSynced(after: nil) else { throw ChannelFreeRailUnavailable() } // Read before the listing, so a sync that ends while it is read can't settle a send the listing predates. - let unsettled = await unsettledUncertainRailSends() + let unsettledBefore = await unsettledUncertainRailSends() let kept = unexpiredRailAttempts() + let heldBefore = railSendHolds let payments = try await rail.lightningPayments() + // A send Spark lists a settled attempt of is no longer held; the others read pending until then. + settleListedRailSends(payments, heldBefore: heldBefore) + let stillUnsettled = eventCallbackLock.withLock { Set(uncertainRailSendFailedAt().keys) } + // A hold that ended during the read without its result in the list (a success Spark lists later) stays + // pending, so it never reads as an earlier attempt's failure. + let unsettled = unsettledBefore.filter { + stillUnsettled.contains($0.paymentHash) + || !Self.listsResult(payments, paymentHash: $0.paymentHash, startedAt: heldBefore[$0.paymentHash]) + } if let since = sparkHistoryUnseededSince, await rail.hasSynced(after: UInt64(clamping: since)) { // Kept, so after a relaunch the sends Spark listed hold the node until Spark syncs again. let seeded = payments.filter { $0.direction == .outbound && $0.status != .failed }.map { $0.paymentHash.lowercased() } diff --git a/Bitkit/Utilities/AppStatusHelper.swift b/Bitkit/Utilities/AppStatusHelper.swift index 4e8c35a7ed..e9ce2aefb5 100644 --- a/Bitkit/Utilities/AppStatusHelper.swift +++ b/Bitkit/Utilities/AppStatusHelper.swift @@ -117,6 +117,11 @@ struct AppStatusHelper { ) } + /// Spark's detail shows a zero balance until Spark has read its state; once it has, the detail opens offline too. + nonisolated static func opensSparkDetail(status: HealthStatus, isReady: Bool) -> Bool { + status == .ready || isReady + } + /// Spark carries Lightning when no channel can, so the connection is ready through it; red only when neither can pay. nonisolated static func channelsStatus( isOnline: Bool, diff --git a/Bitkit/ViewModels/ActivityListViewModel.swift b/Bitkit/ViewModels/ActivityListViewModel.swift index 1a303bb6c3..827b05baab 100644 --- a/Bitkit/ViewModels/ActivityListViewModel.swift +++ b/Bitkit/ViewModels/ActivityListViewModel.swift @@ -494,7 +494,7 @@ extension ActivityListViewModel { return activities.filter { activity in switch activity { case let .lightning(ln): - return ln.txType == .sent + return ln.txType == .sent && !ln.isMoveToSpark case let .onchain(on): return on.txType == .sent && !on.isTransfer } @@ -511,8 +511,8 @@ extension ActivityListViewModel { case .other: return activities.filter { activity in switch activity { - case .lightning: - return false // Lightning activities are never transfers + case let .lightning(ln): + return ln.isMoveToSpark case let .onchain(on): return on.isTransfer } diff --git a/Bitkit/ViewModels/SparkTransferFlow.swift b/Bitkit/ViewModels/SparkTransferFlow.swift index ed8a6f19bd..ac94a64906 100644 --- a/Bitkit/ViewModels/SparkTransferFlow.swift +++ b/Bitkit/ViewModels/SparkTransferFlow.swift @@ -132,7 +132,10 @@ enum SparkClaimDecision { /// The Spark calls the deposit claim makes, injectable so the polling can be tested without the SDK. struct SparkClaimOperations { var offer: (String) async throws -> SparkClaimOffer? - var claimEarly: (SparkClaimOffer) async throws -> SparkEarlyClaim + /// Accepts the early claim of an offer, capped at the fee the user approved. + var claimEarly: (SparkClaimOffer, _ ceilingSats: UInt64) async throws -> SparkEarlyClaim + /// Whether Spark still lists the deposit as unclaimed, without asking the provider for a quote. + var isUnclaimed: (String) async throws -> Bool var refresh: () async -> Void var sleep: (Duration) async -> Void /// Clears the early-claim fee cap `claimEarly` left on the deposit, so only the claim at maturity is made. False when @@ -142,7 +145,8 @@ struct SparkClaimOperations { static var live: SparkClaimOperations { SparkClaimOperations( offer: { try await SparkManager.shared.depositClaimOffer(txid: $0) }, - claimEarly: { try await SparkManager.shared.claimEarly($0) }, + claimEarly: { try await SparkManager.shared.claimEarly($0, ceilingSats: $1) }, + isUnclaimed: { try await SparkManager.shared.isDepositUnclaimed(txid: $0) }, refresh: { await SparkManager.shared.refreshState() }, sleep: { try? await Task.sleep(for: $0) }, releaseEarlyClaim: { await SparkManager.shared.releaseEarlyClaim($0) } @@ -345,9 +349,14 @@ final class SparkTransferFlow { } /// Records the early-claim ceiling and speed the user swiped, as the confirm screen keeps requoting while a payment - /// whose outcome is unknown waits on the pending screen. - func approveSwipe() { - approved = (ceilingSats: quote?.claimFees.instantMaxSats ?? 0, speed: speed) + /// whose outcome is unknown waits on the pending screen. The ceiling is never above `shownCeilingSats`, the one the + /// swiped quote showed, as the requote before sending can raise it. Returns the approved ceiling. + @discardableResult + func approveSwipe(shownCeilingSats: UInt64? = nil) -> UInt64 { + let current = quote?.claimFees.instantMaxSats ?? 0 + let ceilingSats = shownCeilingSats.map { min($0, current) } ?? current + approved = (ceilingSats: ceilingSats, speed: speed) + return ceilingSats } /// Ties the last swipe's approval to the funding it left unresolved. A later swipe rejected while that funding is @@ -435,25 +444,29 @@ final class SparkTransferFlow { if let txid { watchTasks[txid]?.cancel() watchTasks[txid] = nil - if let offer = claimedOffers.removeValue(forKey: txid) { - let operations = operations - let attempts = max(pollAttempts, 1) - // Not awaited: the SDK call ignores cancellation and can take a while. Tried again while another claim of - // the deposit, such as Spark's own sync, leaves the cap in place. - Task { - for attempt in 1 ... attempts { - if await operations.releaseEarlyClaim(offer) { - return - } - if attempt < attempts { - await operations.sleep(Self.pollInterval) - } - } - Logger.warn("Gave up clearing the early claim cap of Spark deposit \(offer.txid)", context: "SparkTransferFlow") + releaseEarlyClaimCap(txid: txid) + } + claimState = .later + } + + /// Clears the fee cap an early claim attempt left on the deposit, so Spark no longer claims it early. + private func releaseEarlyClaimCap(txid: String) { + guard let offer = claimedOffers.removeValue(forKey: txid) else { return } + let operations = operations + let attempts = max(pollAttempts, 1) + // Not awaited: the SDK call ignores cancellation and can take a while. Tried again while another claim of the + // deposit, such as Spark's own sync, leaves the cap in place. + Task { + for attempt in 1 ... attempts { + if await operations.releaseEarlyClaim(offer) { + return + } + if attempt < attempts { + await operations.sleep(Self.pollInterval) } } + Logger.warn("Gave up clearing the early claim cap of Spark deposit \(offer.txid)", context: "SparkTransferFlow") } - claimState = .later } /// Waits for the current transfer's claim to settle; for tests. @@ -486,11 +499,25 @@ final class SparkTransferFlow { } private func pollDeposit(txid: String) async { + // After a waiting claim the fee ceiling stays on the deposit and Spark claims it early by itself once the provider + // offers it, so the poll only watches for the claim instead of quoting again. + var isClaimLeftToSpark = false for _ in 0 ..< pollAttempts { if Task.isCancelled { return } do { + if isClaimLeftToSpark { + let isUnclaimed = try await operations.isUnclaimed(txid) + guard !Task.isCancelled else { return } + if !isUnclaimed { + setClaimState(.added, for: txid) + return + } + await operations.refresh() + await operations.sleep(Self.pollInterval) + continue + } let found = try await operations.offer(txid) guard !Task.isCancelled else { return } if found == nil, offers[txid] != nil { @@ -507,12 +534,13 @@ final class SparkTransferFlow { } setClaimState(.claiming, for: txid) claimedOffers[txid] = found - let claim = try await operations.claimEarly(found) + let claim = try await operations.claimEarly(found, ceilings[txid] ?? 0) guard !Task.isCancelled else { return } if let state = SparkClaimDecision.onClaim(claim) { setClaimState(state, for: txid) return } + isClaimLeftToSpark = true } } catch { Logger.warn("Failed to claim Spark deposit \(txid) early: \(error)", context: "SparkTransferFlow") @@ -524,6 +552,8 @@ final class SparkTransferFlow { // A deposit Spark listed whose early claim never came is waiting for its confirmations, not unseen. guard offers[txid] == nil else { Logger.info("No early claim for Spark deposit \(txid) within the polling window", context: "SparkTransferFlow") + // Shown at the normal speed, so Spark no longer claims it early at the approved fee. + releaseEarlyClaimCap(txid: txid) setClaimState(.unavailable, for: txid) return } diff --git a/Bitkit/Views/Settings/Advanced/LightningConnectionsView.swift b/Bitkit/Views/Settings/Advanced/LightningConnectionsView.swift index eb0efa83ae..3ccd657da4 100644 --- a/Bitkit/Views/Settings/Advanced/LightningConnectionsView.swift +++ b/Bitkit/Views/Settings/Advanced/LightningConnectionsView.swift @@ -156,7 +156,7 @@ struct LightningConnectionsView: View { } } - if MoveToSparkMath.canMove( + if MoveToSparkManager.shared.keepsMoveForItsResult || MoveToSparkMath.canMove( channels: wallet.channels, isSparkUsable: MoveToSparkMath.isSparkUsable(SparkManager.shared) ) { diff --git a/Bitkit/Views/Settings/AppStatusView.swift b/Bitkit/Views/Settings/AppStatusView.swift index 3c70e5108d..e73063b594 100644 --- a/Bitkit/Views/Settings/AppStatusView.swift +++ b/Bitkit/Views/Settings/AppStatusView.swift @@ -173,8 +173,8 @@ struct AppStatusView: View { title: t("settings__status__spark__title"), description: t("settings__status__spark__\(status.rawValue)"), status: status, - // Spark's detail shows a zero balance until Spark has read its state. - onTap: status == .ready ? { navigation.navigate(.sparkConnectionDetail) } : nil + onTap: AppStatusHelper.opensSparkDetail(status: status, isReady: SparkManager.shared.isReady) + ? { navigation.navigate(.sparkConnectionDetail) } : nil ) .accessibilityElement(children: .contain) .accessibilityIdentifier("Status-spark") diff --git a/Bitkit/Views/Transfer/SpendingConfirm.swift b/Bitkit/Views/Transfer/SpendingConfirm.swift index f338dffcb8..560078afc2 100644 --- a/Bitkit/Views/Transfer/SpendingConfirm.swift +++ b/Bitkit/Views/Transfer/SpendingConfirm.swift @@ -141,7 +141,7 @@ struct SpendingConfirm: View { throw SpendingFeesIncreasedError() } - flow.approveSwipe() + let ceilingSats = flow.approveSwipe(shownCeilingSats: shown.claimFees.instantMaxSats) do { let txid = try await transfer.fundSpark( address: fresh.address, @@ -150,7 +150,7 @@ struct SpendingConfirm: View { txFee: fresh.networkFeeSats, isMaxAmount: flow.isMaxAmount ) - flow.onBroadcast(txid: txid) + flow.onBroadcast(txid: txid, ceilingSats: ceilingSats) await wallet.updateBalanceState() navigation.navigate(.settingUp) DispatchQueue.main.asyncAfter(deadline: .now() + 1) { diff --git a/Bitkit/Views/Wallets/Activity/ActivityIcon.swift b/Bitkit/Views/Wallets/Activity/ActivityIcon.swift index c905a757c7..d8d501f337 100644 --- a/Bitkit/Views/Wallets/Activity/ActivityIcon.swift +++ b/Bitkit/Views/Wallets/Activity/ActivityIcon.swift @@ -32,7 +32,7 @@ struct ActivityIcon: View { confirmed = nil txType = ln.txType isBoosted = false - isTransfer = false + isTransfer = ln.isMoveToSpark doesExist = true case let .onchain(onchain): isLightning = false @@ -100,7 +100,7 @@ struct ActivityIcon: View { CircularIcon(icon: "hourglass-simple", iconColor: .purpleAccent, backgroundColor: .purple16, size: size) } else { CircularIcon( - icon: txType == .sent ? "arrow-up" : "arrow-down", + icon: isTransfer ? "arrow-up-down" : txType == .sent ? "arrow-up" : "arrow-down", iconColor: .purpleAccent, backgroundColor: .purple16, size: size diff --git a/Bitkit/Views/Wallets/Activity/ActivityItemView.swift b/Bitkit/Views/Wallets/Activity/ActivityItemView.swift index 821dd7d425..e1c48dc1bd 100644 --- a/Bitkit/Views/Wallets/Activity/ActivityItemView.swift +++ b/Bitkit/Views/Wallets/Activity/ActivityItemView.swift @@ -124,6 +124,10 @@ struct ActivityItemView: View { return t("wallet__activity_boost_fee") } + if case let .lightning(activity) = viewModel.activity, activity.isMoveToSpark { + return t("wallet__activity_move_to_spark") + } + if case let .lightning(activity) = viewModel.activity, activity.status == .pending { return t("wallet__activity_pending_nav_title") } diff --git a/Bitkit/Views/Wallets/Activity/ActivityRowLightning.swift b/Bitkit/Views/Wallets/Activity/ActivityRowLightning.swift index f031ef41eb..5810cb61e8 100644 --- a/Bitkit/Views/Wallets/Activity/ActivityRowLightning.swift +++ b/Bitkit/Views/Wallets/Activity/ActivityRowLightning.swift @@ -33,6 +33,10 @@ struct ActivityRowLightning: View { return titleOverride } + if item.isMoveToSpark { + return t("wallet__activity_move_to_spark") + } + switch item.status { case .failed: return t("wallet__activity_failed") @@ -44,6 +48,13 @@ struct ActivityRowLightning: View { } private var description: String { + if item.isMoveToSpark { + switch item.status { + case .failed: return t("wallet__activity_failed") + case .pending: return t("wallet__activity_pending") + case .succeeded: return formattedTime + } + } return item.message.isEmpty ? formattedTime : item.message } diff --git a/Bitkit/Views/Wallets/SpendingWalletScreen.swift b/Bitkit/Views/Wallets/SpendingWalletScreen.swift index 7228112b6b..229ece9a0c 100644 --- a/Bitkit/Views/Wallets/SpendingWalletScreen.swift +++ b/Bitkit/Views/Wallets/SpendingWalletScreen.swift @@ -9,7 +9,8 @@ struct SpendingWalletScreen: View { @EnvironmentObject var wallet: WalletViewModel private var canMoveToSpark: Bool { - MoveToSparkMath.canMove(channels: wallet.channels, isSparkUsable: MoveToSparkMath.isSparkUsable(SparkManager.shared)) + MoveToSparkManager.shared.keepsMoveForItsResult + || MoveToSparkMath.canMove(channels: wallet.channels, isSparkUsable: MoveToSparkMath.isSparkUsable(SparkManager.shared)) } private var shouldShowOnboarding: Bool { diff --git a/BitkitTests/AppStatusHelperTests.swift b/BitkitTests/AppStatusHelperTests.swift index dcd0a874cc..2749f1bab6 100644 --- a/BitkitTests/AppStatusHelperTests.swift +++ b/BitkitTests/AppStatusHelperTests.swift @@ -16,6 +16,15 @@ final class AppStatusHelperTests: XCTestCase { XCTAssertEqual(AppStatusHelper.sparkStatus(isOnline: true, isSupported: true, isReady: false, hasStartFailed: true), .error) } + func testSparkDetailOpensOfflineOnceSparkHasReadItsState() { + let offline = AppStatusHelper.sparkStatus(isOnline: false, isSupported: true, isReady: true, hasStartFailed: false) + XCTAssertEqual(offline, .error) + XCTAssertTrue(AppStatusHelper.opensSparkDetail(status: .error, isReady: true)) + XCTAssertTrue(AppStatusHelper.opensSparkDetail(status: .ready, isReady: true)) + XCTAssertFalse(AppStatusHelper.opensSparkDetail(status: .pending, isReady: false)) + XCTAssertFalse(AppStatusHelper.opensSparkDetail(status: .error, isReady: false)) + } + func testChannelsStatusIsReadyThroughSparkWhenNoChannelIsUsable() { let status = AppStatusHelper.channelsStatus(isOnline: true, hasUsableChannels: false, hasChannels: true, isSparkUsable: true) XCTAssertEqual(status, .ready) diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 56f222a972..8496709b42 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -834,13 +834,31 @@ extension ChannelFreeRailTests { await assertRefusedAsDuplicate() } + func testALaunchThatReadsASparkSendsOwnFailureLetsTheNodeRetryWhileSparkCantList() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + rail.balanceSats = 100_000 + rail.errorAfterSubmission = NSError(domain: "spark", code: 2) + _ = try? await service.send(bolt11: Self.invoice) + rail.errorAfterSubmission = nil + try simulateRelaunch() + + // The launch's sync reads the send's own failure, then Spark's history can't be read. + await SparkManager.releaseFailedSendHolds { [Self.sparkPayment(hash: hash, status: .failed, timestamp: 1000)] } + rail.listError = NSError(domain: "spark", code: 3) + rail.balanceSats = 0 + + await assertReachesTheNode() + } + func testASparkSendThatReturnedLetsTheNodeRetryOnceSparkListsItFailed() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: 1000) } rail.balanceSats = 100_000 _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) // Spark returned the send, then reports that it failed. - rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil)] + rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: 1000)] rail.balanceSats = 0 await assertReachesTheNode() @@ -855,14 +873,14 @@ extension ChannelFreeRailTests { kept.forEach { service.railAttemptsStore.set($0.value, forKey: $0.key) } } - private static func sparkPayment(hash: String, status: BreezSdkSpark.PaymentStatus) -> Payment { + private static func sparkPayment(hash: String, status: BreezSdkSpark.PaymentStatus, timestamp: UInt64 = 1) -> Payment { Payment( id: hash, paymentType: .send, status: status, amount: 20000, fees: 0, - timestamp: 1, + timestamp: timestamp, method: .lightning, details: .lightning( description: nil, @@ -880,6 +898,7 @@ extension ChannelFreeRailTests { private static let ldkAttemptsKey = "ldkAttemptedPaymentHashes" private static let railAttemptsKey = "channelFreeRailAttemptedPaymentHashes" + private static let uncertainRailSendsKey = "channelFreeRailUncertainSendFailedAt" private static func nodePayment(_ hash: String, status: LDKNode.PaymentStatus) -> LDKNode.PaymentDetails { LDKNode.PaymentDetails( @@ -1423,10 +1442,18 @@ extension ChannelFreeRailTests { try await sendOverSpark() // The send failed, for example with no route: Spark lists it failed, and the operators show it failed once // every attempt at its hash was returned. - rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil)] + rail.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: Self.sparkNow()), + ] rail.sendStatus = .success(.failed) + let retriedAt = Bitkit.LightningService.shared.now().addingTimeInterval(20) + Bitkit.LightningService.shared.now = { retriedAt } try await sendOverSpark() + // The retry failed too, so neither rail has a send of the invoice left that may pay. + rail.payments.append( + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: Self.sparkNow()) + ) rail.balanceSats = 0 await assertReachesTheNode() } @@ -1474,6 +1501,17 @@ extension ChannelFreeRailTests { XCTAssertEqual(rail.sendStatusFetches, 1) } + func testAPreRestoreInvoiceTheOperatorsShowFailedIsRefusedOverAnUnsyncedSpark() async throws { + try restore(secondsAfterTheInvoice: 60) + try pinTheClockWhileTheInvoiceIsValid() + leaveSparkUnsyncedAndEmpty() + rail.balanceSats = 100_000 + // Earlier attempts exist, and Spark can't list them yet to date the send after them. + rail.sendStatus = .success(.failed) + + await assertRefusedAsUnverifiedPreRestoreInvoice() + } + func testAPreRestoreInvoiceSparkMayHavePaidByTransferIsRefusedOnBothRails() async throws { for sparkFunded in [false, true] { try await holdForTheOperators(sparkFunded: sparkFunded) @@ -1530,7 +1568,9 @@ extension ChannelFreeRailTests { rail.sendStatus = .success(nil) rail.onSendStatus = { [rail] in _ = try? await service.send(bolt11: Self.invoice) - rail?.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: status, preimage: nil)] + rail?.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: status, preimage: nil, timestamp: Self.sparkNow()), + ] afterCompeting() } return try await service.send(bolt11: Self.invoice) @@ -1598,6 +1638,241 @@ extension ChannelFreeRailTests { XCTAssertFalse(Bitkit.SparkManager.paysBySparkTransfer(prefersSpark: false, sparkTransferFeeSats: nil)) } + /// Now on the service's clock, as Spark dates an attempt at its start. + private static func sparkNow() -> UInt64 { + UInt64(Bitkit.LightningService.shared.now().timeIntervalSince1970) + } + + /// Sends the fixture invoice over Spark while Spark lists an earlier attempt of it that failed, `first`. + private func sendARetryAfterAFailedAttempt() async throws -> String { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(invoice.secondsSinceEpoch() + 60)) } + rail.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: 100), + ] + try await sendOverSpark() + rail.balanceSats = 0 + return hash + } + + func testASentRetryStaysHeldWhileSparkListsOnlyAnEarlierFailure() async throws { + let hash = try await sendARetryAfterAFailedAttempt() + + // Spark took the retry but lists only the attempt before it. + await assertRefusedAsDuplicate() + let status = await PaykitLightningPaymentProofLookup.railStatus(paymentHash: hash) + XCTAssertEqual(status, .pending, "the retry read as failed by the earlier attempt's failure") + + rail.payments.append( + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: Self.sparkNow()) + ) + await assertReachesTheNode() + } + + func testALateFailureOfAnEarlierAttemptKeepsARetryHeld() async throws { + let hash = try await sendARetryAfterAFailedAttempt() + + // A failure Spark dates before the send is an earlier attempt's; one dated at the send is its own and ends it. + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: 100 + ) + await assertRefusedAsDuplicate() + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: Self.sparkNow() + ) + await assertReachesTheNode() + } + + func testASentRetrySparkNeverListsEndsPastItsInvoicesExpiry() async throws { + _ = try await sendARetryAfterAFailedAttempt() + await assertRefusedAsDuplicate() + + let expiresAt = try Self.invoiceExpiresAt() + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt - 1) } + await assertRefusedAsDuplicate() + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt) } + await assertReachesTheNode() + } + + func testARetryThatHoldsTheInvoiceWhileAnExpiredSendSettlesStaysHeld() async throws { + let hash = try await sendARetryAfterAFailedAttempt() + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + defer { service.railSendExpired = previousRecord } + let expiresAt = try Self.invoiceExpiresAt() + service.now = { Date(timeIntervalSince1970: expiresAt) } + // Spark's last sync came before the retry, so only a lost hold lets the invoice go out again. + rail.syncedAfter = { seconds in seconds.map { $0 < UInt64(expiresAt) } ?? true } + // While the expired send's row is written, its own failure ends it and a retry of the invoice goes to Spark. + service.railSendExpired = { [self] _ in + service.railSendExpired = nil + service.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: Self.sparkNow()) + try? await sendOverSpark() + return true + } + + await service.endExpiredRailSendUncertainties() + + rail.balanceSats = 0 + await assertRefusedAsDuplicate() + } + + /// Attempt A starts at 995 and fails; Spark lists its failure before retry B starts at 1000, inside the clock margin. + private func sendARetryFiveSecondsAfterAFailedAttempt() async throws -> (hash: String, startedAt: UInt64) { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + let startedAt = invoice.secondsSinceEpoch() + 60 + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(startedAt)) } + rail.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: startedAt - 5), + ] + try await sendOverSpark() + rail.balanceSats = 0 + return (hash, startedAt) + } + + func testAFailureOfAnAttemptFiveSecondsBeforeARetryKeepsTheRetryHeld() async throws { + let (hash, startedAt) = try await sendARetryFiveSecondsAfterAFailedAttempt() + final class Failures: @unchecked Sendable { var count = 0 } + let failures = Failures() + Bitkit.LightningService.shared.setEventCallback { event in + if case .paymentFailed = event { + failures.count += 1 + } + } + + // Spark lists only A's failure, then A's failure event arrives late. + await assertRefusedAsDuplicate() + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: startedAt - 5 + ) + XCTAssertEqual(failures.count, 0, "A's failure reached B's screen") + await assertRefusedAsDuplicate() + XCTAssertTrue(Bitkit.LightningService.shared.isEarlierRailAttempt(paymentHash: hash, createdAt: startedAt - 5)) + + // B's own failure ends it. + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: startedAt + ) + await assertReachesTheNode() + } + + func testASparkSendIsRefusedWhileSparkCantList() async throws { + // After a relaunch only Spark's list shows the failures Spark dated for the invoice, so the send can't be dated. + rail.listError = NSError(domain: "spark", code: 3) + rail.balanceSats = 100_000 + + do { + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + XCTFail("Expected the Spark send to be refused") + } catch { + XCTAssertTrue(error is Bitkit.ChannelFreeRailSendRefused, "\(error)") + } + XCTAssertNil(rail.sentBolt11) + } + + func testASendHeldWhileSparksListIsReadIsNotSettledFromThatList() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + let startedAt = 1000 + rail.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: UInt64(startedAt)), + ] + // A send of the invoice is held while the list is read, so the list was read before it started. + rail.onList = { + service.railAttemptsStore.set([hash: startedAt], forKey: Self.uncertainRailSendsKey) + } + + _ = try await service.channelFreeRailPayments() + + XCTAssertEqual(service.railSendHolds[hash], startedAt, "a list read before the send settled it") + } + + func testARetryWhoseHoldEndsDuringTheReadWithoutItsResultListedStaysPending() async throws { + let (hash, _) = try await sendARetryFiveSecondsAfterAFailedAttempt() + let service = Bitkit.LightningService.shared + // The retry's success event ends its hold during the read, and Spark lists only A's failure on every read. + rail.onList = { + service.railAttemptsStore.set([String: Int](), forKey: Self.uncertainRailSendsKey) + } + + let payments = try await service.channelFreeRailPayments().filter { $0.paymentHash == hash } + + XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure") + } + + func testAnExpiredRetryFailsItsOwnRowWhenSparkListsOnlyTheFailureFiveSecondsBeforeIt() async throws { + let (hash, startedAt) = try await sendARetryFiveSecondsAfterAFailedAttempt() + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + defer { service.railSendExpired = previousRecord } + final class Written: @unchecked Sendable { var attempt: Payment?; var calls = 0 } + let written = Written() + service.railSendExpired = { hash in + written.calls += 1 + written.attempt = SparkManager.expiredSendAttempt( + [Self.sparkPayment(hash: hash, status: .failed, timestamp: startedAt - 5)], paymentHash: hash + ) { service.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } + return true + } + let expiresAt = try Self.invoiceExpiresAt() + service.now = { Date(timeIntervalSince1970: expiresAt) } + + await service.endExpiredRailSendUncertainties() + + XCTAssertEqual(written.calls, 1) + XCTAssertNil(written.attempt, "A's details were picked for B's row instead of failing it in place") + XCTAssertNotNil( + SparkManager + .expiredSendAttempt([Self.sparkPayment(hash: hash, status: .failed, timestamp: startedAt)], paymentHash: hash) { _, _ in false } + ) + } + + func testAnEarlierFailureWhileARetryEntersSparksSendCallStaysOffItsScreen() async throws { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(invoice.secondsSinceEpoch() + 60)) } + final class Failures: @unchecked Sendable { var count = 0 } + let failures = Failures() + Bitkit.LightningService.shared.setEventCallback { event in + if case .paymentFailed = event { + failures.count += 1 + } + } + // The earlier attempt's failure arrives while the retry is in Spark's send call, before it is submitted. + rail.beforeSubmit = { + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: 100 + ) + } + + try await sendOverSpark() + + XCTAssertEqual(failures.count, 0, "an earlier attempt's failure reached the retry's screen") + rail.beforeSubmit = nil + rail.balanceSats = 0 + await assertRefusedAsDuplicate() + } + + func testARetryIsRefusedWhileSparkListsAnyAttemptPending() async throws { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(invoice.secondsSinceEpoch() + 60)) } + rail.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .pending, preimage: nil, timestamp: 100), + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: 200), + ] + rail.balanceSats = 100_000 + + await assertRefusedAsDuplicate() + } + private func sendOverSpark() async throws { rail.balanceSats = 100_000 _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) diff --git a/BitkitTests/MoveToSparkLateOutcomeTests.swift b/BitkitTests/MoveToSparkLateOutcomeTests.swift index d63fab83dd..611ab5694c 100644 --- a/BitkitTests/MoveToSparkLateOutcomeTests.swift +++ b/BitkitTests/MoveToSparkLateOutcomeTests.swift @@ -3,6 +3,20 @@ import LDKNode import XCTest final class MoveToSparkLateOutcomeTests: XCTestCase { + @MainActor + func testAMoveKeptForItsResultKeepsItsScreenReachableUntilTheWalletIsWiped() { + let manager = MoveToSparkManager() + XCTAssertFalse(manager.keepsMoveForItsResult) + + _ = manager.beginMove() + XCTAssertTrue(manager.keepsMoveForItsResult, "A move in flight hid its screen once the channels had nothing left to move") + manager.reset() + XCTAssertTrue(manager.keepsMoveForItsResult, "Leaving the screen of a move in flight forgot it") + + manager.resetForWipe() + XCTAssertFalse(manager.keepsMoveForItsResult) + } + func testLateSuccessOfTheInFlightMoveShowsItMovedWithItsFee() { let state = MoveToSparkState.inFlight(amountSats: 40000) XCTAssertTrue(MoveToSparkManager.showsInFlightMove(state, generation: 3, moveGeneration: 3)) diff --git a/BitkitTests/MoveToSparkQuoteTests.swift b/BitkitTests/MoveToSparkQuoteTests.swift new file mode 100644 index 0000000000..80dfaef554 --- /dev/null +++ b/BitkitTests/MoveToSparkQuoteTests.swift @@ -0,0 +1,176 @@ +@testable import Bitkit +import BitkitCore +import LDKNode +import XCTest + +@MainActor +final class MoveToSparkQuoteTests: XCTestCase { + private final class FakeServices: MoveToSparkServices, @unchecked Sendable { + var isSparkUsable = true + var estimate: (UInt64) throws -> UInt64 = { _ in 30 } + private(set) var quotedAmounts: [UInt64] = [] + + func receiveInvoice(description _: String, expirySecs _: UInt32) async throws -> String { + "lnbcrt1move" + } + + func estimateChannelFee(bolt11 _: String, amountSats: UInt64) async throws -> UInt64 { + quotedAmounts.append(amountSats) + return try estimate(amountSats) + } + } + + private struct OtherError: Error {} + + /// Channels that can send 100,000 sats. + private let channels = [ChannelDetails.mock(outboundCapacityMsat: 100_000_000)] + + func testQuoteGrowsToFitTheRealFee() async throws { + let services = FakeServices() + let quote = try await MoveToSparkManager(services: services).makeQuote(channels: channels, targetSats: nil) + XCTAssertEqual(quote, MoveToSparkQuote(invoice: "lnbcrt1move", amountSats: 99968, feeSats: 32)) + XCTAssertEqual(services.quotedAmounts, [99498, 99968]) + } + + func testQuoteKeepsASmallerTarget() async throws { + let services = FakeServices() + let quote = try await MoveToSparkManager(services: services).makeQuote(channels: channels, targetSats: 50000) + XCTAssertEqual(quote.amountSats, 50000) + XCTAssertEqual(quote.feeSats, 32) + XCTAssertEqual(services.quotedAmounts, [50000]) + } + + func testQuoteFallsBackToTheLastFittingAmount() async throws { + let services = FakeServices() + services.estimate = { amount in + guard amount == 99498 else { throw NodeError.RouteNotFound(message: "no route") } + return 30 + } + let quote = try await MoveToSparkManager(services: services).makeQuote(channels: channels, targetSats: nil) + XCTAssertEqual(quote.amountSats, 99498) + XCTAssertEqual(quote.feeSats, 32) + } + + func testNoRouteOnTheFirstRoundIsTooLarge() async { + let services = FakeServices() + services.estimate = { _ in throw NodeError.RouteNotFound(message: "no route") } + await assertQuoteThrows(services, expected: .tooLarge(amountSats: 99498)) + } + + func testAFeeThatNeverFitsIsTooLarge() async { + let services = FakeServices() + var estimate: UInt64 = 500 + services.estimate = { _ in + estimate += 100 + return estimate + } + await assertQuoteThrows(services, expected: .tooLarge(amountSats: 99098)) + XCTAssertEqual(services.quotedAmounts, [99498, 99398, 99298, 99198]) + } + + func testOtherEstimateErrorsAreRethrown() async { + let services = FakeServices() + services.estimate = { _ in throw OtherError() } + do { + _ = try await MoveToSparkManager(services: services).makeQuote(channels: channels, targetSats: nil) + XCTFail("Expected an error") + } catch { + XCTAssertTrue(error is OtherError) + } + } + + func testNothingToMoveWithoutChannels() async { + await assertQuoteThrows(FakeServices(), channels: [], expected: .nothingToMove) + } + + func testSparkUnavailableStopsTheQuote() async { + let services = FakeServices() + services.isSparkUsable = false + await assertQuoteThrows(services, expected: .sparkUnavailable) + XCTAssertTrue(services.quotedAmounts.isEmpty) + } + + private func assertQuoteThrows( + _ services: FakeServices, + channels: [ChannelDetails]? = nil, + expected: MoveToSparkError, + line: UInt = #line + ) async { + do { + _ = try await MoveToSparkManager(services: services).makeQuote(channels: channels ?? self.channels, targetSats: nil) + XCTFail("Expected \(expected)", line: line) + } catch let error as MoveToSparkError { + switch (error, expected) { + case let (.tooLarge(a), .tooLarge(b)): XCTAssertEqual(a, b, line: line) + case (.nothingToMove, .nothingToMove), (.sparkUnavailable, .sparkUnavailable): break + default: XCTFail("Expected \(expected), got \(error)", line: line) + } + } catch { + XCTFail("Expected \(expected), got \(error)", line: line) + } + } +} + +@MainActor +final class MoveToSparkPaymentsTests: XCTestCase { + private var suiteName = "" + private var savedDefaults = UserDefaults.standard + + override func setUp() async throws { + suiteName = "MoveToSparkPaymentsTests-\(UUID().uuidString)" + savedDefaults = MoveToSparkPayments.defaults + MoveToSparkPayments.defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) + } + + override func tearDown() async throws { + MoveToSparkPayments.defaults.removePersistentDomain(forName: suiteName) + MoveToSparkPayments.defaults = savedDefaults + } + + func testHashSurvivesARelaunch() throws { + MoveToSparkPayments.insert("ABCD") + // A relaunch reads the same store anew. + MoveToSparkPayments.defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) + XCTAssertTrue(MoveToSparkPayments.contains("abcd")) + XCTAssertFalse(MoveToSparkPayments.contains("ef01")) + XCTAssertFalse(MoveToSparkPayments.contains(nil)) + } + + func testAnOldMoveIsStillKnown() { + MoveToSparkPayments.insert("abcd", now: Date(timeIntervalSince1970: 1_000_000)) + XCTAssertTrue(MoveToSparkPayments.contains("abcd")) + } + + func testOnlyAMovesSendIsAMoveToSpark() { + MoveToSparkPayments.insert("abcd") + XCTAssertTrue(activity(id: "abcd", type: .sent, message: "").isMoveToSpark) + XCTAssertFalse(activity(id: "ef01", type: .sent, message: MoveToSparkMath.invoiceDescription).isMoveToSpark) + XCTAssertFalse(activity(id: "abcd", type: .received, message: "").isMoveToSpark) + } + + private func activity(id: String, type: BitkitCore.PaymentType, message: String) -> LightningActivity { + LightningActivity( + walletId: WalletScope.default, id: id, txType: type, status: .succeeded, value: 1000, fee: 1, + invoice: "lnbcrt1", message: message, timestamp: 1, preimage: nil, contact: nil, + createdAt: 1, updatedAt: 1, seenAt: nil + ) + } + + func testRestoredHashesAreKnownAndBackedUpSorted() throws { + MoveToSparkPayments.insert("ef01") + MoveToSparkPayments.restore(["ABCD", "ef01"]) + XCTAssertTrue(MoveToSparkPayments.contains("abcd")) + XCTAssertEqual(MoveToSparkPayments.backupSnapshot(), ["abcd", "ef01"]) + + let json = #"{"version":1,"createdAt":1,"tagMetadata":[],"cache":{"hasSeenContactsIntro":true},"moveToSparkPaymentHashes":["abcd"]}"# + XCTAssertEqual(try JSONDecoder().decode(MetadataBackupV1.self, from: Data(json.utf8)).moveToSparkPaymentHashes, ["abcd"]) + let older = #"{"version":1,"createdAt":1,"tagMetadata":[],"cache":{"hasSeenContactsIntro":true}}"# + XCTAssertNil(try JSONDecoder().decode(MetadataBackupV1.self, from: Data(older.utf8)).moveToSparkPaymentHashes) + } + + func testWipeForgetsEveryHash() { + MoveToSparkPayments.insert("abcd") + MoveToSparkPayments.removeAll() + XCTAssertFalse(MoveToSparkPayments.contains("abcd")) + } +} diff --git a/BitkitTests/SparkExitBackupTests.swift b/BitkitTests/SparkExitBackupTests.swift index cf102eb526..a0ba98cc06 100644 --- a/BitkitTests/SparkExitBackupTests.swift +++ b/BitkitTests/SparkExitBackupTests.swift @@ -1,8 +1,15 @@ @testable import Bitkit +import BreezSdkSpark +import CryptoKit import XCTest @MainActor final class SparkExitBackupTests: XCTestCase { + func testAnExitBackupNamesTheNetworkAsSparkDoes() { + XCTAssertEqual(SparkManager.exitBackupNetworkName(.bitcoin), "mainnet") + XCTAssertEqual(SparkManager.exitBackupNetworkName(.regtest), "\(BreezSdkSpark.Network.regtest)") + } + private let walletIndex = 99 override func tearDown() { @@ -135,7 +142,7 @@ final class SparkExitBackupTests: XCTestCase { XCTAssertTrue(uploads.isEmpty, "A fresh export replaced the remote backup whose exit data Spark hasn't imported") } - func testAnUnreadableRemoteExitBackupBacksOffInsteadOfRetryingEveryFewSeconds() async throws { + func testAnUnreachableRemoteExitBackupBacksOffInsteadOfRetryingEveryFewSeconds() async throws { let suite = "SparkExitBackupTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite) } @@ -144,7 +151,7 @@ final class SparkExitBackupTests: XCTestCase { defaults: defaults, backupData: { _ in export }, uploadBackup: { _, _ in }, - fetchBackup: { _ in Data("not an exit backup".utf8) } + fetchBackup: { _ in throw URLError(.notConnectedToInternet) } ) await service.restoreSparkExit() @@ -153,6 +160,213 @@ final class SparkExitBackupTests: XCTestCase { XCTAssertEqual(outcome, .temporarilyUnavailable) } + func testAnUnreadableRemoteExitBackupIsSetAsideAndBackupsGoOn() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + let unreadable = Data("{\"version\":2}".utf8) + var remote = ["SPARK_EXIT": unreadable] + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { remote[$0] = $1 }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { .nothingStaged } + ) + + await service.restoreSparkExit() + let outcome = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(outcome, .completed) + XCTAssertEqual(remote[BackupService.rejectedSparkExitKey(for: unreadable)], unreadable, "The exit data this app can't read was lost") + XCTAssertEqual(remote["SPARK_EXIT"], export) + } + + func testExitDataSparkRejectsIsSetAsideAndBackupsGoOn() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let restored = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 900, network: "regtest", exitState: "newer")) + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + var remote = ["SPARK_EXIT": restored] + var staged: SparkStagedExitImport = .pending + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { remote[$0] = $1 }, + waitForTemporaryFailureDelay: { _ in }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { staged }, + discardStagedSparkExit: { _ in staged = .nothingStaged }, + stagedSparkExitState: { "newer" }, + restoreExitBackup: { _ in } + ) + + await service.restoreSparkExit() + _ = await service.triggerBackup(category: .sparkExit) + XCTAssertEqual(remote["SPARK_EXIT"], restored, "A transient import failure let a fresh export replace the remote copy") + XCTAssertFalse(remote.keys.contains { $0.hasPrefix("SPARK_EXIT_REJECTED") }) + + staged = .rejected + let outcome = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(outcome, .completed) + XCTAssertEqual(staged, .nothingStaged) + XCTAssertEqual(remote[BackupService.rejectedSparkExitKey(for: restored)], restored) + XCTAssertEqual(remote["SPARK_EXIT"], export) + } + + func testDifferentRejectedCopiesNeverOverwriteEachOther() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + let earlier = Data("earlier".utf8) + let later = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 900, network: "regtest", exitState: "later")) + var remote = ["SPARK_EXIT": later, BackupService.rejectedSparkExitKey(for: earlier): earlier] + var staged: SparkStagedExitImport = .rejected + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { remote[$0] = $1 }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { staged }, + discardStagedSparkExit: { _ in staged = .nothingStaged }, + stagedSparkExitState: { "later" } + ) + + _ = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(remote[BackupService.rejectedSparkExitKey(for: earlier)], earlier) + XCTAssertEqual(remote[BackupService.rejectedSparkExitKey(for: later)], later) + let digest = SHA256.hash(data: later).map { String(format: "%02x", $0) }.joined() + XCTAssertEqual(BackupService.rejectedSparkExitKey(for: later), "SPARK_EXIT_REJECTED_" + digest.prefix(16)) + XCTAssertEqual(remote["SPARK_EXIT"], export) + } + + func testRejectedDataAnotherDeviceReplacedRemotelyIsSetAsideFromTheStagedCopy() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + let otherDevice = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 950, network: "regtest", exitState: "other")) + var remote = ["SPARK_EXIT": otherDevice] + var staged: SparkStagedExitImport = .rejected + var restored: [String] = [] + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { remote[$0] = $1 }, + waitForTemporaryFailureDelay: { _ in }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { staged }, + discardStagedSparkExit: { _ in staged = .nothingStaged }, + stagedSparkExitState: { "mine" }, + restoreExitBackup: { restored.append($0.exitState); staged = .pending } + ) + + _ = await service.triggerBackup(category: .sparkExit) + + let kept = try JSONDecoder().decode(SparkExitBackupV1.self, from: XCTUnwrap(remote.first { $0.key.hasPrefix("SPARK_EXIT_REJECTED_") }?.value)) + XCTAssertEqual(kept.exitState, "mine", "The rejected exit data was lost for another device's backup") + XCTAssertEqual(kept.network, "regtest") + XCTAssertEqual(remote["SPARK_EXIT"], otherDevice, "A fresh export replaced exit data another device backed up") + XCTAssertEqual(restored, ["other"], "The other device's exit data was never restored") + } + + func testABackupAnotherDeviceWritesWhileAnUnreadableOneIsSetAsideIsRestoredFirst() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let unreadable = Data("unreadable".utf8) + let otherDevice = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 950, network: "regtest", exitState: "other")) + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + var remote = ["SPARK_EXIT": unreadable] + var restored: [String] = [] + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { key, data in + remote[key] = data + // Another device backs up its exit data while this one sets the unreadable copy aside. + if key.hasPrefix("SPARK_EXIT_REJECTED_") { + remote["SPARK_EXIT"] = otherDevice + } + }, + waitForTemporaryFailureDelay: { _ in }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { .nothingStaged }, + restoreExitBackup: { restored.append($0.exitState) } + ) + + await service.restoreSparkExit() + _ = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(remote[BackupService.rejectedSparkExitKey(for: unreadable)], unreadable) + XCTAssertEqual(restored, ["other"], "A backup written during the set-aside was replaced unread") + } + + func testARestoreOfAnotherDevicesBackupIsNotedBeforeTheStagedCopyGoes() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + let otherDevice = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 950, network: "regtest", exitState: "other")) + var remote = ["SPARK_EXIT": otherDevice] + var staged: SparkStagedExitImport = .rejected + var isRestorePendingWhenDiscarded: Bool? + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { remote[$0] = $1 }, + waitForTemporaryFailureDelay: { _ in }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { staged }, + discardStagedSparkExit: { _ in + // A stop here relaunches with whatever was saved before the staged copy went. + isRestorePendingWhenDiscarded = defaults.bool(forKey: "sparkExitRestorePending") + staged = .nothingStaged + }, + stagedSparkExitState: { "mine" }, + restoreExitBackup: { _ in staged = .pending } + ) + + _ = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(isRestorePendingWhenDiscarded, true, "A stop after the staged copy went would replace the other device's backup unread") + XCTAssertEqual(remote["SPARK_EXIT"], otherDevice) + } + + func testAStagedFileThatCantBeReadKeepsTheRemoteCopy() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + let restored = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 950, network: "regtest", exitState: "restored")) + var remote = ["SPARK_EXIT": restored] + struct Unreadable: Error {} + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { remote[$0] = $1 }, + waitForTemporaryFailureDelay: { _ in }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { .rejected }, + discardStagedSparkExit: { _ in }, + stagedSparkExitState: { throw Unreadable() } + ) + + _ = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(remote["SPARK_EXIT"], restored, "A staged file that couldn't be read let a fresh export replace the remote copy") + } + + func testOnlyInvalidInputMarksExitDataAsRejected() { + XCTAssertEqual(SparkStagedExitImport(importError: SdkError.InvalidInput("unsupported exit state version")), .rejected) + XCTAssertEqual(SparkStagedExitImport(importError: URLError(.notConnectedToInternet)), .pending) + } + func testTheLatestBackupTimeSkipsTheExitData() { XCTAssertFalse(BackupService.latestBackupTimeCategories.contains(.sparkExit), "Reading the time downloads the exit data") XCTAssertTrue(BackupService.latestBackupTimeCategories.contains(.wallet)) @@ -194,4 +408,19 @@ final class SparkExitBackupTests: XCTestCase { XCTAssertTrue(mark.claim(version: SparkManager.exitStateGeneration), "The restart kept the stale exit data backup") } + + @MainActor + func testDiscardingRejectedExitDataKeepsNewerDataStagedMeanwhile() throws { + let walletIndex = 9901 + let file = Env.sparkExitRestore(walletIndex: walletIndex) + defer { try? FileManager.default.removeItem(at: file) } + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("newer".utf8).write(to: file) + + SparkManager.shared.discardStagedExitState("rejected", walletIndex: walletIndex) + XCTAssertEqual(try SparkManager.shared.stagedExitState(walletIndex: walletIndex), "newer") + + SparkManager.shared.discardStagedExitState("newer", walletIndex: walletIndex) + XCTAssertNil(try SparkManager.shared.stagedExitState(walletIndex: walletIndex)) + } } diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 15bab32b61..3aa6e358fa 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -97,4 +97,43 @@ final class SparkRelaunchActivityTests: XCTestCase { guard case let .lightning(lightning)? = activity else { return XCTFail("The send wasn't recorded") } XCTAssertEqual(lightning.contact, "pk:contact") } + + func testAnOlderSparkAttemptsFailureKeepsTheLaterFailedAttemptsRow() async throws { + let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "e7", count: 16) + func failed(at timestamp: UInt64, amountMsat: UInt64, feeMsat: UInt64) -> PaymentDetails { + PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: amountMsat, feePaidMsat: feeMsat, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp + ) + } + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(at: 200, amountMsat: 300_000, feeMsat: 3000)) + + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(at: 100, amountMsat: 250_000, feeMsat: 1000)) + + let activity = try await CoreService.shared.activity.getActivity(id: hash) + guard case let .lightning(lightning)? = activity else { return XCTFail("The send wasn't recorded") } + XCTAssertEqual(lightning.value, 300) + XCTAssertEqual(lightning.fee, 3) + XCTAssertEqual(lightning.timestamp, 200, "the earlier attempt's failure replaced the later attempt's row") + } + + func testALaterSparkAttemptsFailureReplacesAnEarlierFailedAttemptsRow() async throws { + let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "f8", count: 16) + func failed(at timestamp: UInt64, amountMsat: UInt64) -> PaymentDetails { + PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: amountMsat, feePaidMsat: 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp + ) + } + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(at: 100, amountMsat: 250_000)) + + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(at: 200, amountMsat: 300_000)) + + let activity = try await CoreService.shared.activity.getActivity(id: hash) + guard case let .lightning(lightning)? = activity else { return XCTFail("The send wasn't recorded") } + XCTAssertEqual(lightning.value, 300) + XCTAssertEqual(lightning.timestamp, 200) + } } diff --git a/BitkitTests/SparkTransferFlowTests.swift b/BitkitTests/SparkTransferFlowTests.swift index dfa68e491d..6443b85714 100644 --- a/BitkitTests/SparkTransferFlowTests.swift +++ b/BitkitTests/SparkTransferFlowTests.swift @@ -74,7 +74,8 @@ final class SparkTransferFlowTests: XCTestCase { offer: { txid in SparkClaimOffer(txid: txid, vout: 0, kind: .choice( earlyFeeSats: 900, earlyConfirmations: 0, standardFeeSats: 198, standardConfirmations: 3 )) }, - claimEarly: { _ in .repriced(requiredFeeSats: 1500) }, + claimEarly: { _, _ in .repriced(requiredFeeSats: 1500) }, + isUnclaimed: { _ in true }, refresh: {}, sleep: { _ in }, releaseEarlyClaim: { released.append($0.txid) @@ -102,7 +103,8 @@ final class SparkTransferFlowTests: XCTestCase { offer: { txid in SparkClaimOffer(txid: txid, vout: 0, kind: .choice( earlyFeeSats: 900, earlyConfirmations: 0, standardFeeSats: 198, standardConfirmations: 3 )) }, - claimEarly: { _ in .repriced(requiredFeeSats: 1500) }, + claimEarly: { _, _ in .repriced(requiredFeeSats: 1500) }, + isUnclaimed: { _ in true }, refresh: {}, sleep: { _ in }, releaseEarlyClaim: { _ in @@ -131,7 +133,8 @@ final class SparkTransferFlowTests: XCTestCase { offer: { txid in SparkClaimOffer(txid: txid, vout: 0, kind: .choice( earlyFeeSats: 1500, earlyConfirmations: 0, standardFeeSats: 198, standardConfirmations: 3 )) }, - claimEarly: { _ in .claimed }, + claimEarly: { _, _ in .claimed }, + isUnclaimed: { _ in true }, refresh: {}, sleep: { _ in }, releaseEarlyClaim: { released.append($0.txid) @@ -159,30 +162,56 @@ final class SparkTransferFlowTests: XCTestCase { @MainActor func testListedDepositWhoseEarlyClaimKeepsWaitingIsNotUnseen() async { - let flow = pollingFlow( - offers: [choice(earlyFee: 900), choice(earlyFee: 900), choice(earlyFee: 900)], - claims: [.waiting, .waiting, .waiting], - pollAttempts: 3 - ) + let calls = PollCalls() + let flow = pollingFlow(offers: [choice(earlyFee: 900)], claims: [.waiting], pollAttempts: 3, calls: calls) flow.onBroadcast(txid: "txid") await flow.waitForClaim() XCTAssertEqual(flow.claimState, .unavailable) + XCTAssertEqual(calls.offers, 1, "A waiting claim asked the provider for a quote again") + XCTAssertEqual(calls.claims, 1) + XCTAssertEqual(calls.unclaimedChecks, 2) + } + + @MainActor + func testAWaitingEarlyClaimThePollGivesUpOnClearsItsFeeCap() async throws { + let calls = PollCalls() + let flow = pollingFlow(offers: [choice(earlyFee: 900)], claims: [.waiting], pollAttempts: 3, calls: calls) + flow.onBroadcast(txid: "txid") + await flow.waitForClaim() + for _ in 0 ..< 100 where calls.released.isEmpty { + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertEqual(flow.claimState, .unavailable) + XCTAssertEqual(calls.released, ["txid"], "Spark may still claim early while the transfer shows the normal speed") + } + + @MainActor + func testAWaitingEarlyClaimIsCappedAtTheApprovedFeeNotTheFirstQuote() async { + let calls = PollCalls() + let flow = pollingFlow(offers: [choice(earlyFee: 300)], claims: [.waiting], pollAttempts: 2, calls: calls) + flow.onBroadcast(txid: "txid", ceilingSats: 500) + await flow.waitForClaim() + XCTAssertEqual(calls.ceilings, [500], "Spark would leave a later offer under the approved fee unclaimed") } @MainActor func testDepositListedThenGoneWasAdded() async { - let flow = pollingFlow(offers: [choice(earlyFee: 900), nil], claims: [.waiting]) + let flow = pollingFlow(offers: [choice(earlyFee: 900)], claims: [.waiting], unclaimed: [false]) flow.onBroadcast(txid: "txid") await flow.waitForClaim() XCTAssertEqual(flow.claimState, .added) } @MainActor - func testWaitingKeepsPollingUntilClaimed() async { - let flow = pollingFlow(offers: [choice(earlyFee: 900), choice(earlyFee: 900)], claims: [.waiting, .claimed]) + func testWaitingWatchesTheDepositUntilSparkClaimsIt() async { + let calls = PollCalls() + let flow = pollingFlow(offers: [choice(earlyFee: 900)], claims: [.waiting], unclaimed: [true, false], pollAttempts: 5, calls: calls) flow.onBroadcast(txid: "txid") await flow.waitForClaim() XCTAssertEqual(flow.claimState, .added) + XCTAssertEqual(calls.offers, 1) + XCTAssertEqual(calls.claims, 1) + XCTAssertEqual(calls.unclaimedChecks, 2) } @MainActor @@ -215,11 +244,12 @@ final class SparkTransferFlowTests: XCTestCase { offer: { txid in SparkClaimOffer(txid: txid, vout: 0, kind: .choice( earlyFeeSats: 900, earlyConfirmations: 0, standardFeeSats: 198, standardConfirmations: 3 )) }, - claimEarly: { offer in + claimEarly: { offer, _ in await withCheckedContinuation { release = $0 } claimed.append(offer.txid) return .claimed }, + isUnclaimed: { _ in true }, refresh: {}, sleep: { _ in } ) @@ -362,6 +392,20 @@ final class SparkTransferFlowTests: XCTestCase { XCTAssertEqual(flow.claimState, .repriced(feeSats: 800), "Paid an early claim fee the user never approved") } + @MainActor + func testASwipeApprovesNoHigherCeilingThanTheQuoteItShowed() async { + let flow = pollingFlow(offers: [choice(earlyFee: 800)], claims: [.claimed]) + // The requote before sending raised the ceiling over the one the swiped quote showed. + flow.quote = quote(instantMax: 3010) + let ceilingSats = flow.approveSwipe(shownCeilingSats: 337) + XCTAssertEqual(ceilingSats, 337) + + flow.onBroadcast(txid: "txid", ceilingSats: ceilingSats) + await flow.waitForClaim() + + XCTAssertEqual(flow.claimState, .repriced(feeSats: 800), "Claimed early at a ceiling the swipe never showed") + } + @MainActor func testARecoveredFundingKeepsItsOwnApprovalWhenALaterSwipeIsRejected() async { let flow = pollingFlow(offers: [choice(earlyFee: 800)], claims: [.claimed]) @@ -475,19 +519,48 @@ final class SparkTransferFlowTests: XCTestCase { ) } - /// A flow whose poll answers with `offers` in turn (nil once they run out) and whose claims answer with `claims`. + private final class PollCalls { + var offers = 0 + var claims = 0 + var unclaimedChecks = 0 + var ceilings: [UInt64] = [] + var released: [String] = [] + } + + /// A flow whose poll answers with `offers` in turn (nil once they run out), whose claims answer with `claims`, and + /// whose unclaimed checks answer with `unclaimed` (still unclaimed once they run out). @MainActor - private func pollingFlow(offers: [SparkClaimOffer.Kind?], claims: [SparkEarlyClaim] = [], pollAttempts: Int? = nil) -> SparkTransferFlow { + private func pollingFlow( + offers: [SparkClaimOffer.Kind?], + claims: [SparkEarlyClaim] = [], + unclaimed: [Bool] = [], + pollAttempts: Int? = nil, + calls: PollCalls = PollCalls() + ) -> SparkTransferFlow { var offers = offers var claims = claims + var unclaimed = unclaimed let operations = SparkClaimOperations( offer: { txid in + calls.offers += 1 guard !offers.isEmpty, let kind = offers.removeFirst() else { return nil } return SparkClaimOffer(txid: txid, vout: 0, kind: kind) }, - claimEarly: { _ in claims.isEmpty ? .waiting : claims.removeFirst() }, + claimEarly: { _, ceilingSats in + calls.claims += 1 + calls.ceilings.append(ceilingSats) + return claims.isEmpty ? .waiting : claims.removeFirst() + }, + isUnclaimed: { _ in + calls.unclaimedChecks += 1 + return unclaimed.isEmpty ? true : unclaimed.removeFirst() + }, refresh: {}, - sleep: { _ in } + sleep: { _ in }, + releaseEarlyClaim: { offer in + calls.released.append(offer.txid) + return true + } ) return SparkTransferFlow(amountSats: 100_000, quote: quote, operations: operations, pollAttempts: pollAttempts ?? offers.count + 1) } diff --git a/Docs/RELEASE.md b/Docs/RELEASE.md index 1ac48dc6a7..7dd01855e8 100644 --- a/Docs/RELEASE.md +++ b/Docs/RELEASE.md @@ -127,7 +127,7 @@ Apply the shared [store release-note checks](https://github.com/synonymdev/bitki ## 2. Build and Upload to TestFlight -Before archiving, make sure the Breez API key is available (ask the team for the key). Either store it in the macOS keychain item `BREEZ_API_KEY` (copy the key, then run `printf 'add-generic-password -U -a %s -s BREEZ_API_KEY -w %s\n' "$USER" "$(pbpaste)" | security -i && pbcopy Tap "Move To Spark" and verify the screen shows an amount (testTag "MoveToSparkAmount") and a routing fee (testTag "MoveToSparkFee") Swipe to move (testTag "MoveToSparkSwipe") and verify "Moved to Spark" shows the moved amount (testTag "MoveToSparkMoved") and "Close" (testTag "MoveToSparkClose") Tap "Close" (testTag "MoveToSparkClose"), then "Close" on the close confirmation, and verify Lightning Connections shows no channel under OPEN CONNECTIONS, only Spark via Breez, whose balance grew by the moved amount - Go back to Home, open Spending and verify the "Move To Spark" button is gone + Go back to Home, verify Activity lists a "Move to Spark" transfer row with the moved amount plus the routing fee, and that its detail screen is titled "Move to Spark" + Open Spending and verify the "Move To Spark" button is gone