Skip to content

fix(dashpay): derive the wallet encryption key once per contacts pass - #1767

Merged
HashEngineering merged 2 commits into
feat/kotlin-sdk-phase-1from
fix/contacts-pass-derive-key-once
Dec 1, 2026
Merged

HashEngineering merged 2 commits into
feat/kotlin-sdk-phase-1from
fix/contacts-pass-derive-key-once

Conversation

@HashEngineering

@HashEngineering HashEngineering commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Issue being fixed or feature implemented

PlatformSynchronizationService.updateContactRequests derived the wallet encryption key twice in every contacts pass:

  • once into myEncryptionKey, for the invite and transaction-metadata branches;
  • again inside the upgradeIdentity branch running next to them (identityRepository.upgradeIdentity(platformRepo.getWalletEncryptionKey())).

PlatformRepo.getWalletEncryptionKey() has no cache. Each call is a full scrypt derivation (N=65536): about 0.9 s of CPU and a ~64 MB memory spike on a phone, often two at the same moment.

A 12.0.2 field log from a wallet with 233 DashPay contacts shows 64 "Deriving key took ~0.9 s" lines across 25 passes. The pass runs every 15 s in the foreground and every 5 minutes in the background.

What was done?

upgradeIdentity now takes the key the pass already derived, so a normal pass derives it once instead of twice. The same key reaches the same calls, so nothing else changes. A pass that repairs a missing contact keychain still derives a key for that repair, as before.

This is the smallest of several costs in the contacts pass. Every pass also re-downloads and rewrites all profiles and usernames; that is a separate change, to be decided.

Related PR's and Dependencies

From the same 12.0.2 report as #1765 (wallet load off the main thread) and #1766 (reconcile ticker only while the app is open).

Screenshots / Videos

None.

How Has This Been Tested?

  • New: PlatformSyncIntegrityPassTest.aPass_derivesTheWalletEncryptionKeyOnce_andUpgradeIdentityReusesIt. It runs one full pass through updateContactRequests and checks that getWalletEncryptionKey() is called once and that upgradeIdentity receives that same key. The old code derived it twice.
  • PlatformSync* tests on _testNet3Debug: 17/17 pass.
  • Local pre-review: clean.

Not tested on a device.

  • QA (Mobile Team)

Checklist:

  • I have performed a self-review of my own code and added comments where necessary
  • I have added or updated relevant unit/integration/functional/e2e tests

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Improvements
    • Contact request updates during wallet synchronization now reuse the encryption key already obtained in that pass, rather than deriving it again. This reduces redundant work in the update process. The change does not alter the behavior or appearance of contact requests for users.

updateContactRequests derived the key for the invite and metadata branches,
then upgradeIdentity's branch called getWalletEncryptionKey() again. Each call
is a full scrypt derivation (N=65536: about 0.9 s of CPU and a ~64 MB spike
on a phone), so every pass paid twice, often at the same moment. A 12.0.2
field log shows 64 derivations across 25 passes. upgradeIdentity now takes
the key the pass already holds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

updateContactRequests now passes its previously derived wallet encryption key to identityRepository.upgradeIdentity. A test verifies that the pass derives the key once and reuses it.

Changes: Contact request sync

Layer / File(s) Summary
Reuse and verify the encryption key
wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt, wallet/test/de/schildbach/wallet/service/platform/PlatformSyncIntegrityPassTest.kt
updateContactRequests passes the previously derived key to upgradeIdentity. The test checks that the key is derived once and that the same key is passed to upgradeIdentity.

Estimated code review effort: 2 (Simple) | ~8 minutes

Change: Refactor

Suggested reviewers: thepastaclaw

Merge Risk: Minimal · up to fd978

This change removes one redundant wallet key derivation from each contact-request sync pass without changing which key reaches the identity upgrade. It has a focused test, and no merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "fix(dashpay): derive the wallet encryption key once per contacts pass" matches the main change. The summary and objectives say updateContactRequests now reuses the already-derived wallet en…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title "fix(dashpay): derive the wallet encryption key once per contacts pass" matches the main change. The summary and objectives say updateContactRequests now reuses the already-derived wallet encryption key for upgradeIdentity, so one scrypt derivation runs per pass instead of two. The title names the fix and the affected area. It is specific and does not list files. The title does not mention the new test, but that is expected.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between cfbb017 and fd97867.

Files selected for processing: 1

  • wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt
Files skipped from review as they are similar to previous changes: 1

  • wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.

@thepastaclaw

thepastaclaw commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

✅ Final review complete — no blockers (commit fd97867) · triage: critical

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Final validation — Phase 1 + Phase 2

The change reuses the wallet encryption key across the secondary contact-sync tasks, removing the duplicate derivation for identity upgrade while preserving existing behavior. Build and check CI jobs passed; the review check itself remains in progress.

🟡 1 suggestion(s)

Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.

Review provenance

Source: reviewer 1: glm-5.3-flash (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.2-sol (agent: phase2-reviewer, role: general); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: low by gpt-6.2-sol (effort low) — This is a small, well-contained refactor in PlatformSyncService that reuses an already-derived encryption key, with a focused regression test and no change to cryptographic behavior or funds movement.
  • Phase 1 reviewers: glm-5.3-flash — general (completed, effort high); agent phase1-reviewer
  • Phase 1 model: glm-5.3-flash — zai quota: 5h 100% left, weekly 99% left; passed over gemini-3.8-flash-high (antigravity quota lookup failed)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort medium); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt`:
- [SUGGESTION] wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt:1269-1271: A contacts pass can still derive multiple wallet keys when it repairs missing keychains
  Impact: Encrypted-wallet users whose pass adds or repairs missing contact keychains can still incur an additional full scrypt derivation, while the new comment claims there is only one derivation per pass.
  The comment overstates the scope of this optimization and can mislead maintainers investigating remaining scrypt spikes. The shared key is used by the secondary `awaitAll` branches, but the request loops at lines 1218 and 1248 and the integrity-repair callbacks at lines 1843 and 1845 still call `checkAndAddSentRequest`/`checkAndAddReceivedRequest` without their optional key; when a keychain is missing, those helpers derive another key at lines 1519-1532 and 1585-1598. Narrow the comment to the secondary sync tasks, or thread the already-derived key through the repair flow if a pass-wide one-derivation guarantee is intended.
Out-of-scope follow-up suggestions (1)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • Identity creation and restore still derive the wallet key twice — getIdentityFromPublicKeyId() derives the wallet encryption key internally, and identity creation and restore then derive it again immediately afterward. This is the same expensive duplicate-scrypt pattern, but those call sites are outside this contact-sync change.
    • Follow-up: Follow-up PR: thread one derived encryption key through the identity lookup and create/restore paths so each operation performs only one derivation.

Comment on lines +1269 to +1271
// ONE scrypt derivation per pass (N=65536: ~0.9 s of CPU and a
// ~64 MB spike on a phone), shared by every branch below.
// upgradeIdentity derived its own copy, so each pass paid twice.

@thepastaclaw thepastaclaw Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Resolved at fd97867a; see the replies below.

🟡 Suggestion: A contacts pass can still derive multiple wallet keys when it repairs missing keychains
Impact: Encrypted-wallet users whose pass adds or repairs missing contact keychains can still incur an additional full scrypt derivation, while the new comment claims there is only one derivation per pass.

The comment overstates the scope of this optimization and can mislead maintainers investigating remaining scrypt spikes. The shared key is used by the secondary awaitAll branches, but the request loops at lines 1218 and 1248 and the integrity-repair callbacks at lines 1843 and 1845 still call checkAndAddSentRequest/checkAndAddReceivedRequest without their optional key; when a keychain is missing, those helpers derive another key at lines 1519-1532 and 1585-1598. Narrow the comment to the secondary sync tasks, or thread the already-derived key through the repair flow if a pass-wide one-derivation guarantee is intended.

Suggested change
// ONE scrypt derivation per pass (N=65536: ~0.9 s of CPU and a
// ~64 MB spike on a phone), shared by every branch below.
// upgradeIdentity derived its own copy, so each pass paid twice.
// Share the key across secondary sync tasks so identity upgrade
// doesn't run scrypt again. Contact keychain work above is separate.

source: glm-5.3-flash (phase1-reviewer: general); gpt-6.2-sol (phase2-reviewer: general)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in fd97867: the comment now covers only the secondary sync tasks and says that repairing a missing contact keychain still derives its own key. Passing the key into the repair path is left out of this PR, since repairs are rare and the per-pass cost was the duplicate in the secondary tasks.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Resolved (re-reviewed at fd97867a): The updated comment now limits the one-derivation claim to the secondary sync tasks and explicitly states that repairing a missing contact keychain derives separately, so it accurately reflects the unchanged repair paths.

Repairing a missing contact keychain still derives its own key; the comment
claimed one derivation per pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@HashEngineering HashEngineering self-assigned this Nov 30, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-review — Final validation — Phase 1 + Phase 2

New on this head: This head is a comment-only follow-up that narrows the scrypt-sharing description to the secondary sync tasks and documents the separate derivation used by missing-keychain repairs. The build and check CI jobs succeeded; CodeRabbit also succeeded, while the PastaClaw review check remains in progress.

🔴 0 blocking | 🟡 0 suggestion(s) | 💬 0 nitpick(s)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.2-sol (effort low) — The diff changes wallet encryption-key derivation and reuse in PlatformSynchronizationService.updateContactRequests, which is cryptographic key handling even though the change is small and behavior-preserving.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.

No unresolved findings remain from the prior review on this head.

Comment on lines +1269 to +1271
// ONE scrypt derivation per pass (N=65536: ~0.9 s of CPU and a
// ~64 MB spike on a phone), shared by every branch below.
// upgradeIdentity derived its own copy, so each pass paid twice.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Resolved (re-reviewed at fd97867a): The updated comment now limits the one-derivation claim to the secondary sync tasks and explicitly states that repairing a missing contact keychain derives separately, so it accurately reflects the unchanged repair paths.

@HashEngineering

Copy link
Copy Markdown
Collaborator Author

QA run 56 — PASS, one derivation per pass

Tested on a wallet with 22 contact requests and 13 profiles, so the contacts pass had real work to do.

The marker is dashj's own: I/KeyCrypterScrypt: Deriving key took NNN ms for N=65536, r=8, p=1 — the scrypt this PR is about.

20 consecutive derivations captured. Zero pairs.

gaps between derivations (s):
  16.1  16.1  16.1  16.4  16.4  16.1  16.2  16.1  16.1  16.2  16.2  …
  gaps under 2 s — i.e. two derivations inside one pass:  0 of 19

One derivation per contacts pass, evenly spaced at the pass interval. Without the fix each pass would derive twice, the second from upgradeIdentity, which is what your note reports from the 12.0.2 field log.

Each derivation measured 119–136 ms here. That's an emulator; your ~0.9 s figure for a real phone is the one that matters for the user-visible cost.

Limit worth stating

Only the after state was observed on a device. I did not reproduce the paired before — a control needs a build without this PR, and the obvious shortcut (downgrading the device to 12.0.2) isn't available because the older SDK can't read the newer store. So this corroborates your unit test rather than independently proving the double derivation existed on this hardware.


QA run 56, 2026-11-30. Build 12000305 (12.0.3-qa05), branch qa/integration-12.0.3-qa05
off feat/kotlin-sdk-phase-1 @ 19ec4858dd — twelve PRs in ten merges, no conflicts.
Pins: Kotlin SDK 5.1.0-int43-20261126.183836-1, dashj-platform 5.1.0, dashj 24.0.0 — the
same pairing the shipped 12.0.3 builds use. APK sha256
76d464966bcad134c9e5360d8524ae5fb2850b46f6d9e23f83f9d0d08d56a2c3.
Unit tests 4,841 / 330 classes, 2 failures, both reproduced on the bare base.
Devices: Android 16 emulators, testnet at Platform protocol 15.

@HashEngineering
HashEngineering merged commit b8d741e into feat/kotlin-sdk-phase-1 Dec 1, 2026
4 checks passed
HashEngineering added a commit that referenced this pull request Dec 1, 2026
Brings #1767 and #1762. The branch keeps its own pins (Kotlin SDK
5.1.0-int43, dashj-platform 5.1.0).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
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.

2 participants