Skip to content

fix: restore ios backups on android - #1736

Merged
ovitrif merged 7 commits into
masterfrom
fix/ios-backup-restore
Nov 2, 2026
Merged

ovitrif merged 7 commits into
masterfrom
fix/ios-backup-restore

Conversation

@ovitrif

@ovitrif ovitrif commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #1733
Fixes #1737
Twin: synonymdev/bitkit-ios#1173

This PR makes Android restore backups written by bitkit-ios, and reports the categories it could not restore instead of an unconditional WALLET RESTORED.

bitkit-ios encodes the bitkit-core types in its backups (PreActivityMetadata, Activity, IBtInfo, IBtOrder, …) with Swift's synthesized Codable, which differs from kotlinx in three ways:

  • nil optionals are left out, while the generated Kotlin bindings declare nullable fields with no default
  • enums are written as {"regtest":{}}, not "REGTEST"
  • enums with values are written as {"onchain":{"_0":{…}}}, not {"type":"com.synonym.bitkitcore.Activity.Onchain","v1":{…}}

SETTINGS also carries iOS forms (addressTypesToMonitor as "nativeSegwit,taproot", primaryDisplay as "Bitcoin"). The four errors in the issue are only the first failing field of each category. METADATA failing meant the Pubky session never restored, so the profile, Paykit history and contact labels were missing.

The root cause sits in bitkit-core's generated bindings plus each app encoding Core types with its own platform encoder. Core already exports canonical *_to_json / *_from_json helpers; moving both apps onto them is the long-term fix. This PR fixes it on the app side for 3.1.0.

Description

  • Adds BackupJson.kt, a decode-only reader for METADATA, BLOCKTANK and ACTIVITY: it accepts missing nullable fields and, guided by each target type's serializer, rewrites Swift enum shapes into kotlinx's. Android envelopes pass through unchanged, and backups are still written with the app's json, so 3.0.x readers are unaffected.
  • Decodes SETTINGS one setting at a time, so a value this app cannot read keeps its default instead of failing the category, and accepts addressTypesToMonitor as a comma-separated string.
  • Makes PubkySessionBackupV1.kind optional, matching iOS, which writes {} for a kind it no longer restores.
  • Returns the categories that failed from performFullRestoreFromLatestBackup and shows them on the restore screen: "Your wallet and balance are back, but Bitkit could not restore: Profile, Contacts, Tags." A category counts as failed when it does not decode or when saving it fails: WIDGETS, BLOCKTANK and ACTIVITY saves, and METADATA's tags, Pubky session and contact overrides. The line is translated in every locale.
  • Keeps a METADATA envelope that restored only in part out of the post-restore rewrite, so the stored backup is not replaced with partial state.
  • Rejects a SETTINGS envelope without a settings object instead of restoring all defaults over the user's settings.
  • Merges a restored on-chain activity into the row the node sync already created for the same transaction. iOS keys on-chain sends by txid and Android's sync by payment id, so every send made on iOS otherwise showed twice. The restored row keeps its address, fee rate, contact and tags, and takes over the synced row's tags; the synced row is deleted only after the restored one is saved. The restore waits for an in-flight activity sync only while the node runs; a sync still waiting for node start has stored nothing.

Out of Scope

  • BackupRepo / iOS BackupService: moving both apps onto bitkit-core's canonical *_to_json / *_from_json backup serialization.
  • BackupRepo: a category that fails to restore can later be overwritten in VSS by the restoring device's empty state for it. This PR now reports the failure but does not guard the upload.
  • iOS reading Android backups: fixed in the twin.

Design

N/A — no design available.

Preview

Restoring a wallet backed up on iOS: WALLET RESTORED, the iOS profile name, each iOS send once with its tag and contact, and the restored payment requests; then both sends again once after a new block and an app restart.

Restore Payment requests After a new block
restore2x.mp4
restore-part22x.mp4
recheck2x.mp4

QA Notes

Setup

  • iOS source: bitkit-ios master Debug build on a simulator, regtest, CI-default staging VSS (https://bitkit.stag0.blocktank.to/vss_rs_auth), staging Pubky/Homegate, Electrum from bitkit-docker (bitcoind, electrs) on 127.0.0.1:60001.
  • Create a wallet and a Pubky profile, link a Paykit contact, receive a payment request from it and pay it on-chain, receive a second one and leave it pending. Wait until every category under Settings → Security → Data backups is synced, then reset the iOS wallet.
  • Android: this PR's devDebug build on an emulator, adb reverse tcp:60001 tcp:60001.

Journeys

N/A — not drivable; see Manual Tests.

Manual Tests

  • 1. Restore the iOS wallet's recovery phrase on Android → WALLET RESTORED with no incomplete line; the home header shows the iOS profile name, the paid on-chain send is labelled with the contact, and Subscriptions → Payments lists the pending request and the paid one with Proof submitted — needs a wallet backed up from bitkit-ios, which the journey environment cannot create

Automated Checks

  • added BackupJsonTest.kt — decodes METADATA, SETTINGS, BLOCKTANK and ACTIVITY fixtures written by Swift's JSONEncoder from the bitkit-ios models, keeps a default for an unreadable setting, rejects an envelope without settings, and round-trips Android envelopes unchanged
  • updated BackupRepoTest.kt — an iOS METADATA envelope restores the Pubky session and tags; a failed session restore, a failed WIDGETS save, a failed BLOCKTANK save, a failed ACTIVITY save and an undecodable ACTIVITY are reported as failed categories
  • updated ActivityRepoTest.kt — a restored on-chain activity replaces the synced row with the same txid after it is saved and carries its tags; a failed save keeps the synced row; a synced row that already has the restored id stays; the restore waits for an in-flight sync only while the node runs
  • updated WalletViewModelTest.kt, ContentViewTest.kt — follow RestoreState.Completed carrying the failed categories

Evidence

  • 1 passed at fcdde0a (Android 16 emulator, unmodified devDebug build) with a fresh bitkit-ios master wallet (QA): WALLET RESTORED with every category restored, the iOS profile name, the contact-labelled Paykit send, both payment requests, and each iOS send once with its tag, still once after a new block and an app restart. ACTIVITY restored 66 ms after BLOCKTANK; the node was already running, so the run took the branch that waits for an in-flight sync.
  • 1 passed at 94637b3 (Android 16 emulator, unmodified devDebug build), with a source wallet that also made a plain tagged on-chain send (QA): WALLET RESTORED with every category restored, the iOS profile name, the contact-labelled Paykit send, both payment requests, and each iOS send once with its tag. The node sync had stored both sends under its own payment ids; the restore replaced those rows, leaving exactly the 3 iOS rows, and after a new block and an app restart both sends were Confirmed and still shown once.
  • 1 passed at 2e0a8e3 (Android 16 emulator, devDebug), restoring a wallet whose METADATA, ACTIVITY and BLOCKTANK were written by bitkit-ios master, with an extra debug-only log line of each raw envelope that is not on head:
    • Every category logged Restore success, then Full restore success; the screen showed WALLET RESTORED with no incomplete line.
    • METADATA held a pre-activity row with no txId, channelId or paymentHash, the shape that failed in [Bug]: iOS backup restore reports success but loses profile and payment history #1733. ACTIVITY used {"onchain":{"_0":…}} with {"sent":{}}, BLOCKTANK {"regtest":{}}.
    • The home header showed the iOS profile name, the 3,000-sat on-chain send was labelled with the contact, the balance matched iOS (496,857 sats), and Subscriptions → Payments listed the pending 2,000-sat request and the paid 3,000-sat one with Proof submitted.
  • 1 passed again at d8372ad (unmodified build): every category logged Restore success, then Full restore success; WALLET RESTORED with no incomplete line, the iOS profile name in the header, the contact-labelled send, the balance of 496,857 sats, and both payment requests. The restored settings point Electrum at the source's local server, so the first attempt timed out starting the node until that server was reachable again.
  • An earlier run at 3e70234 with SETTINGS also in iOS form (addressTypesToMonitor: "nativeSegwit") restored the same data, with the profile screen showing the iOS pubky.
  • @jvsena42's device run at 2441a8c (review) restored an iOS wallet with settings, widgets, tags, a profile and a contact, and showed the incomplete line naming Profile, Contacts and Tags with the homeserver unreachable.
  • just compile, just test and just lint passed locally at 2e0a8e3 and again at 94637b3; just lint and BackupRepoTest.kt again at d8372ad, which only adds the WIDGETS save check.

Gaps

  • On device the node was already running when ACTIVITY restored, so the skip for a sync blocked on node start is covered by ActivityRepoTest only.
  • Both runs restored through staging Pubky and Homegate rather than the issue's local Pubky testnet, since the Paykit peer matching master's paykit-rs pin runs on staging only.
  • The restored Electrum server reaches the node only after an app restart: the node starts on the default server before SETTINGS is restored. This PR does not change that path (QA); tracked in synonymdev/bitkit-android#1750.

Models used

  • Planning/scoping: claude-opus-5-5 (reasoning: medium)
  • Implementation: claude-opus-5-5 (reasoning: medium)
  • Review: claude-opus-5-5 (reasoning: Not exposed)
  • Review rounds: 1

The review subagent's reasoning setting is not in the session metadata available here.

@ovitrif
ovitrif marked this pull request as ready for review October 30, 2026 12:43
@ovitrif
ovitrif requested review from a team, ben-kaufman and pwltr and removed request for a team October 30, 2026 12:43
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-30T12:44:54.703309Z 2e0a8e3 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@ovitrif
ovitrif requested review from piotr-iohk and removed request for pwltr October 30, 2026 12:44
@greptile-apps

greptile-apps Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The PR changes behavior within the wallet backup restore workflow.

The PR appears safe to merge, with a non-blocking gap in reporting failed widget saves.

Findings

  1. P2 Widget save failures go unreported ▶

Summary

Adds an Android reader for iOS backup shapes and shows which backup categories could not be restored.

  • Android restores iOS backups across profile, settings, and payment history.
  • The restore screen names backup categories that could not be restored.

Acknowledged scope: ovitrif explicitly deferred moving both apps to Core's canonical JSON helpers, protecting failed categories from later ordinary uploads, and duplicate cross-platform activity IDs tracked in #1737.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Download backup category] --> B[Decode backup]
  B --> C[Save restored data]
  B -->|Error| D[Record failed category]
  C -->|Reported error| D
  C -->|Success| E[Continue restore]
  D --> E
  E --> F[Completed with failed categories]
  F --> G[Show complete or incomplete message]
Loading

Reviews (1) · Last reviewed commit: "fix: report restore categories that fail..." · Reviewed by Greptile

@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Regtest APK

Built from fcdde0a (run).

Download bitkit-dev-debug universal APK (expires in 30 days).

@ovitrif

ovitrif commented Oct 30, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed d8372ad: a failed WIDGETS save is now reported among the categories that could not be restored, like BLOCKTANK and ACTIVITY, with a test. This answers the Greptile point on unreported widget save failures (#1736 (comment)).

@piotr-iohk piotr-iohk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

QA review

Scope: Full review of the whole PR diff against its merge base (02e6ae4), at d8372ad. No saved baseline was available. The iOS twin synonymdev/bitkit-ios#1173 at 5a87d1b was used only to compare parity and the backup format. It was not reviewed in full.

No new actionable code findings.

No new actionable code findings. What I traced:

  • iOS backup decoding: the decode-only reader (BackupJson.kt) handles Swift's missing optionals, enum cases with no values and enums with values. I traced it through the METADATA, BLOCKTANK and ACTIVITY callers. Android-written envelopes go through unchanged. Address-type strings use the same form on both platforms (nativeSegwit/taproot).
  • Settings: a SETTINGS envelope is decoded one setting at a time, then restored through WalletConnectionRecovery.restoreSettings, which keeps the PIN reset and the native SegWit rule.
  • Pubky session: PubkySessionBackupV1.kind can now be null. That matches the iOS model (a raw-value Kind?), and restoreSessionBackupState already handles a null kind.
  • Failure reporting: failed categories are carried through every restore path: the fresh-wallet, resume/retry, RN fallback and legacy USDT paths. Only is RestoreState.Completed checks remain, so changing Completed from an object to a data class breaks no equality check.
  • Base comparison: at base, a failed category could already be overwritten in VSS later by this device's partial state, and the PR description lists it as out of scope. Turning save failures into throws does not make it worse.

Validation: the CI build job ran testDevDebugUnitTest successfully on this head, including the new BackupJsonTest and the updated BackupRepoTest, WalletViewModelTest and ContentViewTest. I did not run any tests myself. The relevant code was checked by reading the source. Some e2e-tests-local jobs were still pending when I checked.

Device testing: not performed in this review. The author reports manual case 1 passed at 2e0a8e3e4, an earlier commit than the reviewed head. The incomplete-restore line has not been shown on a device.

Non-blocking consistency suggestions

  • iOS (5a87d1b, BackupService.performRestore) still logs a non-fatal category failure, marks the category complete and shows an unconditional restore success. Android now names the categories that failed. Consider adding the same reporting on iOS later.
  • On Android, any METADATA failure is shown as "Profile, Contacts, Tags", even when only one part failed. For example, if the Pubky session fails, tags that were saved are still listed as not restored.

Suggested additional test cases

  • Android regression, Android-made backup: back up a wallet on this build with non-default settings (Fiat primary display, Classic unit, Taproot monitored, custom Electrum), widgets, tags, a Blocktank order and activity. Wipe it and restore the recovery phrase on this build. Expected: WALLET RESTORED with RestoreSuccessText and no incomplete line, every setting and widget kept, and tags and activity present.
  • Android, incomplete restore shown on a device: restore a wallet whose METADATA holds a Pubky localSeed session while the Pubky homeserver is unreachable from the emulator. Expected: the restore screen shows RestoreIncompleteText naming Profile, Contacts and Tags; Continue reaches home; the wallet balance and activity are restored.

Reviewer model: claude-opus-5-5
Reasoning effort: high

@ovitrif

ovitrif commented Oct 30, 2026

Copy link
Copy Markdown
Collaborator Author

Device run at d8372ad (current head, unmodified devDebug build, Android 16 emulator): manual case 1 passed. Restoring the iOS-made wallet logged Restore success for every category and Full restore success; the screen showed WALLET RESTORED with no incomplete line, and home showed the iOS profile name, the contact-labelled 3,000-sat send and the 496,857-sat balance, with both payment requests under Subscriptions → Payments.

# Conflicts:
#	app/src/main/java/to/bitkit/repositories/BackupRepo.kt
#	app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt
@ovitrif

ovitrif commented Oct 31, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master into this PR at 2441a8c to clear the conflicts in BackupRepo.kt and BackupRepoTest.kt.

  • BackupRepo.kt: kept master's public-address restore around METADATA (reservation capture, PublicAddressRestoreFailed and the pending-restore guard) and put this PR's changes back into it: METADATA and SETTINGS report into the failed-category set, and SETTINGS decodes through decodeSettingsBackup.
  • BackupRepoTest.kt: imports from both sides.

just compile, just test and just lint pass on the merge. The device run from d8372ad still covers the restore path; the merge changed nothing in it beyond master's own address-restore steps.

@ovitrif

ovitrif commented Oct 31, 2026

Copy link
Copy Markdown
Collaborator Author

Setting milestone 3.1.0: this PR closes #1733, which is in 3.1.0.

@ovitrif ovitrif added this to the 3.1.0 milestone Oct 31, 2026

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code scan of the full PR at 2441a8c: no findings. Reviewed as a backup/restore change. The merge's conflict resolutions keep master's public-address restore around METADATA and re-apply this PR's failedCategories and decodeSettingsBackup.

Checked and clean:

  • Malformed input. fromSwiftCodable recurses along the target SerialDescriptor, not the input depth. Unknown keys, unknown enum cases, out-of-range Swift labels (_5), non-object roots and non-JSON all throw inside performRestore's runSuspendCatching and land in failedCategories. None of them crashes. Android envelopes pass through unchanged. None of the 41 bitkit-core enums collides under the strip-_-and-lowercase normalisation.
  • Field mapping against bitkit-ios master (BackupPayloads.swift):
    • The metadata, Blocktank and activity fields match, as do PubkyProfileData.Link, QuickPayLedger/QuickPayRecordPhase and the nullable PubkySessionBackupV1.kind.
    • Swift Activity {"onchain":{"_0":…}} maps to Activity.Onchain(v1). Core's migrate_backup_activities_json accepts old iOS envelopes without walletId.
    • Settings: iOS already emits Android key names. primaryDisplay, displayUnit, coinSelectPreference, usdtPreference, addressTypesToMonitor and electrumServer all map. defaultTransactionSpeed normal/instant fall back to Medium.
  • No data loss. A partial METADATA restore sets needsRewrite = false, so VSS is not rewritten with partial state. ACTIVITY, BLOCKTANK and WIDGETS save failures now report and skip updateRestoredBackupStatus. A SETTINGS envelope without settings throws instead of resetting every setting to default.
  • Failure reporting. failedCategories reaches the fresh restore, retry, RN-fallback and legacy-USDT paths. All 16 onboarding__restore_incomplete_text translations keep %1$s.

Performance: a one-off JsonElement walk per envelope on restore, on ioDispatcher. Not relevant beyond that.

Device gate (partial): 2441a8c — not run yet. Pending: an iOS wallet with tags, a contact, a profile and settings changes, backed up on the simulator and restored on Android (check RestoreSuccessText and the restored data). Then the same restore with the Pubky homeserver unreachable, where RestoreIncompleteText should name the failed categories. Device results will follow in a separate review.

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Device gate: 2441a8c — iOS master f3e97b0 on the iPhone 17 simulator created a wallet and uploaded all 8 backup categories, then Pixel_9 with this PR's CI APK restored the same seed. perf: n/a. l10n: n/a.

Requesting changes for one MEDIUM, inline: every iOS on-chain send restores as two activity rows, not only a Paykit send.

Restore with the homeserver reachable: RestoreSuccessText, Full restore success. Compared field by field against the iOS wallet:

  • Settings: currency, fiat primary, denomination, speed, warn-over-$100, clipboard and swipe-to-hide all match.
  • Widgets: order, the deleted widgets, Price BTC/EUR 1W and Headlines with the date hidden all match.
  • Activity: the receive, its contact and the send amounts match; the send shows twice (inline).
  • Tags: tags on both transactions and on the unpaid pre-activity address match.
  • Pubky profile, contact and contact tag match; balance 270,971 sats matches.

Restore with the homeserver unreachable: RestoreIncompleteText ("could not restore: Profile, Contacts, Tags"), Full restore incomplete, failed: 'METADATA'. Balance, activity, settings and widgets are usable; Profile shows "Unable to load your profile." with Try Again and Disconnect. After the homeserver came back, Try Again restored the session, the profile, the header name and the contact label, and METADATA uploaded.

Not posted as findings:

  • Private contact payments and Settings › Tags (last-used tags) do not carry over, but the iOS SETTINGS envelope has neither key and the PR does not claim them.
  • With the homeserver down, the incomplete text lists Tags as not restored, though transaction and address tags were restored; and Restore success for: 'METADATA' is logged before METADATA is reported failed.

Skipped:

  • ⚠️ Master comparison restore: after the first restore, Android re-uploaded five categories over the iOS envelopes in staging VSS, so a master restore would only read Android-written data. Master cannot decode the iOS ACTIVITY envelope (#1733), so it would show only the synced send row.

@ovitrif

ovitrif commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 0603b21: a restored on-chain activity now merges into the row the node sync already created for the same transaction, so a send made on iOS no longer shows twice after restoring on Android. This answers @jvsena42's changes request (thread) and fixes #1737. The description now lists the merge, the new ActivityRepoTest.kt cases and the reviewer's device run. The merge itself has not been run on a device yet.

@piotr-iohk piotr-iohk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

QA review

Scope: Full reassessment of the whole PR at 0603b21 against its merge base 1337f12. The comparison base has changed (02e6ae4 → 1337f12) since the previous QA review at d8372ad, so no coverage was carried over from it. The merged iOS twin synonymdev/bitkit-ios#1173 at 03a1d5f was used only to compare the backup format and parity. It was not reviewed in full.

1 actionable finding — resolve or provide an evidence-backed rebuttal.

  • Activity merge (0603b21): for the case in @jvsena42's device report, where the node sync row exists before ACTIVITY restores, the restored row now replaces the synced row. Later syncs update it in place through the txId fallback in processOnchainPayment. Its failure path has one issue, inline. The merge has unit tests but, per the author, no device run yet.
  • Re-traced with no new findings: iOS envelope decoding for METADATA, BLOCKTANK and ACTIVITY, Android envelopes passing through unchanged, per-setting SETTINGS decoding, the nullable Pubky session kind, and failed-category reporting through the fresh, resume/retry, RN-fallback and legacy-USDT paths. The earlier non-blocking suggestion still applies: any METADATA failure lists Profile, Contacts and Tags. @jvsena42 observed this with the homeserver unreachable.

Validation: at this head, the CI build built devDebug and ran testDevDebugUnitTest successfully. Lint and E2E also passed. I ran no tests myself; this review is source analysis only.

Device testing: not performed in this review. The author reports manual case 1 passed at d8372ad, and @jvsena42's device run was at 2441a8c. Both are earlier than the activity merge.

Suggested additional test cases

  • Android, iOS-made backup with ordinary on-chain sends: on bitkit-ios, make at least three plain on-chain sends, tag one, and wait for all backup categories to sync. Restore the seed on this build. Expected: each send appears once, with the iOS address, fee rate and tag. After an app restart and a new block, each still appears once.
  • Android, Android-made backup regression: back up a wallet with on-chain sends and receives, a transfer to spending and tags on this build, then wipe and restore it. Expected: no activity rows are removed or duplicated, the tags are kept, and RestoreSuccessText is shown.

Findings

  • [LOW] Activity merge deletes synced rows before the restored rows are saved — inline at app/src/main/java/to/bitkit/repositories/ActivityRepo.kt:1090.

Reviewer model: claude-opus-5-5
Reasoning effort: high

@ovitrif

ovitrif commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 94637b3: the activity restore now deletes a synced duplicate only after the restored rows are saved and its tags are carried over, and it waits for an active sync before looking the duplicates up. A failed save no longer drops those transactions from the list. This answers @piotr-iohk's thread.

@ovitrif
ovitrif requested a review from piotr-iohk November 1, 2026 18:31

@piotr-iohk piotr-iohk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

QA review

Scope: Follow-up review of 94637b32 since 0603b21, against merge base 1337f121. Inherited baseline: prior QA review. This pass covered the activity-restore delta, its callers, and the current 33-file PR inventory. Backup decoding, settings, category failure handling, Pubky session restore, restore UI copy, translations, the unchanged unit fixtures, and the iOS format comparison at 03a1d5fc remain from that baseline.

No new actionable code findings.

restoreFromBackup waits for an in-flight activity sync, records synced on-chain rows with the same txid and tx type, saves the restored rows, then copies tags onto the restored id and deletes the synced row. bitkit-core 0.8.0-rc11 identifies activities by (wallet_id, id) and indexes tx_id without a uniqueness constraint, so the restored txid row can be stored beside the payment-id row. If upsertList throws, the synced row stays. BackupRepo.restoreActivityBackup still fails the ACTIVITY category when this returns a failure. iOS BackupService upserts restored activities directly; the extra delete is Android-only because those iOS on-chain backup ids are the txid while Android sync uses the LDK payment id.

Validation: CI (testDevDebugUnitTest) and Lint succeeded at this revision. E2E was still in progress. This review inspected the changed tests and did not execute them or a device. The author reports just compile, just test, and just lint passed locally at this revision.

Device testing: not performed in this review. The author's device runs are on earlier commits; the PR says the activity merge itself has no device run.

Suggested additional test cases

  • Android devDebug, using the PR setup (iOS regtest wallet with a paid on-chain send, backups synced). Restore that recovery phrase and open activity after WALLET RESTORED. Expected: that send appears once, with the contact label and its tags, and the balance matches the iOS wallet.

Earlier findings reconciled at this revision: 3 verified fixed.

Reviewer model: grok-4.7
Reasoning effort: high

@ovitrif

ovitrif commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator Author

QA for 94637b3:
Tested on an Android 16 emulator (dev debug build of this PR's head), restoring a backup made by bitkit-ios master on an iOS 27 simulator, regtest with the staging backup server.

Restoring an iOS backup on Android passes. Each iOS send shows once with its tag, after the restore and again after a new block and an app restart.

🟢 Restore an iOS backup on Android, Each iOS send once after a new block
Restore an iOS backup on Android

The iOS source wallet had a Pubky profile "Restore 1736", the contact Fixed Price QA Issuer, a 500,000 sat receive, a 1,500 sat Paykit send for a paid request (tag paykit1736), a 20,000 sat plain send (tag plain1736) and one pending request. All its backup categories had synced before the reset.

iOS activity iOS payments
  • Android shows Wallet Restored with the success text, and the log reports every category restored and the full restore as a success.
  • The header reads "Restore 1736".
  • Activity lists the receive and both sends once each. The Paykit send reads "Sent to Fixed Price QA Issuer" with tag paykit1736; the plain send has tag plain1736.
  • The node sync had already stored both sends under its own payment ids. The restore replaced those rows with the iOS ones, so the activity database holds exactly 3 rows, each keyed as on iOS.
  • Payments lists the pending request with Dismiss and Pay, and the paid request as "Proof submitted".
restore2x.mp4
restore-part22x.mp4

Each iOS send once after a new block

After one more block and an app restart, both sends are Confirmed, each still once with its tag. The database still holds 3 rows, and the restore's replacement did not run again.

recheck32x.mp4

🟠 Restored Electrum server applies only after a restart
Restored Electrum server applies only after a restart

Out of scope: this PR does not change how restored settings reach the node.

  • The iOS backup carried the Electrum server tcp://127.0.0.1:60001, and Android's Electrum Server screen shows it as connected after the restore.
  • The node started on the default staging server one second before SETTINGS was restored, and synced against staging for the whole first session. The restored server took effect only after an app restart.
  • During that first session the restored sends showed "Confirms in ±20m", since the staging chain does not have them. After the restart they confirmed against the local chain.

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code scan of the delta 2441a8c..94637b3: no findings. My MEDIUM (iOS sends restored twice) is fixed in code.

Trace:

  • findSyncedOnchainDuplicates waits for an in-flight activity sync, then looks up every restored on-chain row by (walletId, txId). It keeps a match only when the id differs and the txType matches.
  • After the activities, tags and closed-channels slices are saved, each duplicate's tags are appended to the restored row and the synced row is deleted. Core deletes its tags in the same transaction.
  • A later sync finds the restored row through the txid fallback in CoreService and updates it in place, keeping the restored address, fee rate and contact. So a restart or a second sync does not bring the duplicate back.
  • iOS receives share the payment id with Android and are skipped by the id check.
  • Failure paths leave at worst the old duplicate, never a lost row:
    • upsertList failing (new test);
    • a tag copy failing;
    • a crash between save and delete.
  • No wrong merges: Android keeps one on-chain row per wallet and txid. Boosts, RBF, transfers and closes are either separate txids or in-place flags.
  • The merge also runs for Android-made backups, where sends are keyed by txid too, so the same duplicate on master is fixed there.

perf: relevant. Restore can now wait up to 40 s for an in-flight activity sync, and does one indexed query per restored on-chain row. I'll measure the time from Restore success for: 'BLOCKTANK' to Restore success for: 'ACTIVITY' with a sync in flight.

Device gate (partial): 94637b3 — not run yet; pending:

  • an iOS-made backup with sends, receives and tags restored on this build: one row per transaction, tags kept, still one after a block and a restart;
  • an Android-made backup with sends, a transfer and tags restored the same way;
  • the restore timing above.

The device result will follow.

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Device gate result. Requesting changes for one MEDIUM, inline: restore now waits about 10 s, up to 40 s, for an activity sync that is blocked on node start.

The merge itself works:

  • iOS-made backup (fresh iOS master 831ec3e wallet: 1 receive, 2 sends, tags, a tagged unpaid address), restored on Pixel_9:
    • onchain_activity has 3 rows, one per txid, matching the iOS rows field for field (address, value, fee 143, fee rate 1);
    • the tags are on the right rows, and the pre-activity address tag is kept;
    • still 3 rows after a block and a relaunch.
    • Log: Replaced synced activity '701ba3bc…' with restored '6726f473…'.
  • Android-made backup (sends at Normal and Fast, tags): restored the same way, with the same result. The merge fired there too, because the node keys sends by payment id and the backup by txid.
  • Master restores of the same iOS seed also showed 3 rows, because the restore ran before the node synced. They failed BLOCKTANK on the iOS envelope, which this PR fixes.

Device gate: 94637b3 — restore of iOS-made and Android-made backups passed (one row per txid, tags and fields kept across a block and a relaunch); perf: BLOCKTANK → ACTIVITY 9.9 s and 10.8 s with a sync in flight, 0.29 s without (master 0.26–0.28 s); l10n: no UI text changed.

Skipped:

  • ⚠️ Contact on restored sends: the fresh wallet had no Pubky profile.
  • ⚠️ Transfer to spending: Blocktank channel orders return 404 on staging.

Out of scope (same on master): ACTIVITY re-uploads about every 10 s, because each ONCHAIN_WALLET sync calls notifyActivitiesChanged().

@ovitrif

ovitrif commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed fcdde0a: the restore no longer waits for an activity sync that is blocked on node start, which added about 10 s, up to 40 s, to "SETTING UP YOUR WALLET". It still waits while the node runs, when the sync may already have inserted rows the merge replaces. This answers the MEDIUM on the restore wait. ActivityRepoTest adds a case for each state.

@ovitrif

ovitrif commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator Author

QA for fcdde0a:
Tested on an Android 16 emulator (dev debug build of this PR's head), restoring a fresh backup made by bitkit-ios master 4ac0800 on an iOS 27 simulator, regtest with the staging backup server.

Restoring an iOS backup on Android passes again on this head. Each iOS send shows once with its tag, after the restore and again after a new block and an app restart.

🟢 Restore an iOS backup on Android, Each iOS send once after a new block
Restore an iOS backup on Android

The new iOS source wallet had:

  • a Pubky profile "Restore fcdde" and the contact Fixed Price QA Issuer
  • a 500,000 sat receive
  • a 1,500 sat Paykit send for a paid request (tag paykitfcdde)
  • a 20,000 sat plain send (tag plainfcdde)
  • one pending request
iOS activity iOS payments
  • Android shows Wallet Restored with the success text, and the log reports every category restored and the full restore as a success.
  • The header reads "Restore fcdde".
  • The Paykit send reads "Sent to Fixed Price QA Issuer" with tag paykitfcdde, and the plain send has tag plainfcdde.
  • The restore replaced the node sync's rows for both sends, so the activity database holds exactly 3 rows, each keyed as on iOS.
  • Payments lists the pending request with Dismiss and Pay, and the paid request as "Proof submitted".
  • The ACTIVITY step took 66 ms after BLOCKTANK. In this run the node was already running before the restore began, since it starts on the default Electrum server (synonymdev/bitkit-android#1750). So the restore took the branch that still waits for an in-flight sync, and there was none to wait for. The skip for a sync blocked on node start is covered by ActivityRepoTest.
restore2x.mp4
restore-part22x.mp4

Each iOS send once after a new block

After one more block and an app restart, both sends are Confirmed, each still once with its tag, and the database still holds 3 rows.

recheck2x.mp4

@piotr-iohk piotr-iohk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

QA review

Scope: Follow-up review of fcdde0a since the previously reviewed head 94637b3, against the unchanged merge base 1337f12. Inherited baseline: prior QA review. This pass covered the whole delta (ActivityRepo.findSyncedOnchainDuplicates and two new ActivityRepoTest cases), the sync and node-start paths it touches, and the current PR inventory (still the same 33 files). These areas are carried over from that baseline: backup decoding, settings, category failure reporting, Pubky session restore, restore UI copy and translations, the bitkit-core activity schema, the unchanged unit fixtures, and the iOS activity and backup-format comparison at 03a1d5f.

No new actionable code findings.

The restore now waits for an in-flight activity sync only while the node is Running. That resolves @jvsena42's restore-wait report. Node start waits for the restore in WalletViewModel.waitForRestoreIfNeeded, with a 30 s timeout. So in a normal restore the node is not running when ACTIVITY restores. The sync blocked in LightningRepo.executeWhenNodeRunning has not stored anything yet. When the node runs, CoreService.processOnchainPayment finds the restored row through its txId fallback and updates it in place. In the retry path the node is already running, so the wait still applies and the merge still sees rows the sync stored. Restoring only after a successful save is unchanged, so the earlier LOW stays fixed.

One small remaining window is not reported as a finding. The node check is a snapshot. If the restore runs past the 30 s node-start timeout and the node reaches Running in the few milliseconds between the duplicate lookups and upsertList, a resumed sync could insert its own row first, and that send would show twice. Node start takes seconds, so this window is very small.

Validation: the new and existing ActivityRepoTest restore cases were inspected; I did not run them locally. CI's build job, which includes "Run tests", passed at this head (run 41421785213).

Device testing: not performed in this review. @jvsena42's device run at 94637b3 is from the previous build; the restore timing change has not been run on a device at this head.

Suggested additional test cases

  • Android, with a fresh iOS wallet that has at least one on-chain send and full backups: restore the seed on Android. Expected: restore moves from BLOCKTANK to ACTIVITY with no multi-second wait, and Activity shows one row per txid, still after a new block and a relaunch.
  • Android, with an Android-made backup that has on-chain sends: interrupt the restore so that Retry restarts the node, then retry. Expected: the restore waits for the running node's sync, logs Replaced synced activity, and each send appears once.

Reviewer model: claude-opus-5-5
Reasoning effort: high

@piotr-iohk piotr-iohk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving at fcdde0aeb0f0f00a39c0279dc7aae2ba3c4261e8 with the device timing gaps below.

The current-head QA Watch review has no actionable code findings. CI/unit tests, lint and all seven E2E shards passed. Earlier changes-requested reviews are dismissed and all inline threads are resolved.

Targeted device retest on the existing Pixel 6 emulator, Android 13/API 33, using the CI E2E APK (app source matches this head), local Docker regtest/local Pubky and staging VSS:

  • #1733 passed: iOS-written backups restored successfully across METADATA, SETTINGS, WIDGETS, WALLET, BLOCKTANK and ACTIVITY. The profile, contact label, tags and paid/pending requests were present. The paid request showed Proof submitted. Savings 474,714 sats and Spending 502,998 sats matched the source.
  • #1737 passed: a real iOS Paykit send and an ordinary on-chain send each appeared once with their metadata. Logs explicitly confirmed replacement of both node-created duplicate rows. Exactly three on-chain entries remained (one receive, two sends), still correct and confirmed after a new block and app restart.
  • Partial failure passed: making the profile homeserver unreachable produced the explicit “Profile, Contacts, Tags” incomplete-restore warning while wallet/activity restoration completed.
  • Recovery passed: ordinary retry and recovery after releasing a forced node-start delay completed successfully.

Remaining device coverage, accepted as non-blocking for this approval:

  1. ACTIVITY restore while an activity sync is still blocked on node startup. The normal run reached ACTIVITY after the node was running; the forced hold instead hit an earlier wallet-operation timeout.
  2. ACTIVITY restore while the node is Running and an activity sync is demonstrably unfinished. Ordinary running-node retry passed, but that precise overlap was not established.

The conditional waiting logic has unit coverage; neither condition above is claimed as a device pass. This was a targeted retest, not complete PR device coverage. The existing source wallet originated on Android, but iOS wrote the tested metadata/activity backups and made both new sends. No new product defect was confirmed.

@ovitrif

ovitrif commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

Merging: approved by @piotr-iohk on the current head with his device retest, plus the case 1 device run on this head (#1736 (comment)), no open threads, CI green. Ships in 3.1.0.

@ovitrif
ovitrif merged commit cb59453 into master Nov 2, 2026
21 checks passed
@ovitrif
ovitrif deleted the fix/ios-backup-restore branch November 2, 2026 11:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: ios paykit send shows twice after android restore [Bug]: iOS backup restore reports success but loses profile and payment history

3 participants