Skip to content

feat: DashConnect — connect DashPay wallet to DApps via QR key-exchange login (MO-945) - #1510

Merged
HashEngineering merged 19 commits into
masterfrom
feat/dash-connect
Aug 13, 2026
Merged

HashEngineering merged 19 commits into
masterfrom
feat/dash-connect

Conversation

@HashEngineering

@HashEngineering HashEngineering commented Jul 9, 2026 •

Copy link
Copy Markdown
Collaborator

Issue being fixed or feature implemented

MO-945 — DashConnect: allow a user with a DashPay username to connect their wallet to DApps on the Dash network. First target is logging in to yappr on testnet by scanning QR codes.

What was done?

UI (per the Figma designs)

  • New Connections entry on the Tools screen
  • Connections screen with empty state and a state-driven connection list (approved / active / disconnected)
  • "Approve connection" bottom sheet showing what the app can/cannot do, the app's claimed label (displayed as an unauthenticated claim), and the wallet's own username/identity
  • QR scanning via the existing ScanActivity

Dash Platform integration (wallet side of the Yappr key-exchange protocol)

  • Protocol layer (pure Kotlin): dash-key:/dash-st: URI parsing + validation (version, network gating, strict field lengths, on-curve pubkey checks), hash160, ECDH x-coordinate → HKDF-SHA256 (salt dash:key-exchange:v1), AES-256-GCM 60-byte payload — verified byte-for-byte against the published platform-auth fixture vectors
  • Login QR (dash-key:): on approval, derives a deterministic 32-byte login key, encrypts it to the app's ephemeral key, and publishes (or replaces, per the unique ($ownerId, contractId) index) a loginKeyResponse document on the testnet key-exchange contract 7UaqHGBJBbRLJ4fUWS45cnud8PPUugJWoGTt1SKwHJ2P
  • First-login QR (dash-st:): deserializes the IdentityUpdateTransition, validates it end-to-end against the issued login key (rejects forged QRs), signs with the identity master key and broadcasts
  • Login-key derivation (wallet-defined; upstream YAPPR_DET_SIGNER_SPEC.md is not public): HKDF-SHA256(ikm = BLOCKCHAIN_IDENTITY auth-chain key #0, salt = identityId, info = "dash:login-key:v1" || appContractId), keyIndex = 0 — deterministic per (identity, app) and seed-recoverable
  • Local connection status via DataStore, merged with the wallet's own on-chain documents
  • Feature gated to testnet (no mainnet contract deployment)
  • Note: Documents.broadcast is an unimplemented stub in dash-sdk 4.0.0-RC2, so document publish uses the same low-level put/replace path as IdentityVerify

Also repairs two pre-existing compile-blocked unit tests (WalletTransactionMetadataProviderGiftCardTest, MainViewModelTest) that prevented the wallet test suite from building.

How Has This Been Tested?

  • 34 new unit tests covering the protocol layer and repository (:wallet:test_testNet3DebugUnitTest), including exact fixture-vector assertions (hash160, HKDF-derived auth/encryption keys, wire-format request decode, ECDH symmetry, GCM round-trip) and all URI validation rejections
  • :wallet:compileProdDebugKotlin and :wallet:compile_testNet3DebugKotlin build successfully
  • Not yet tested end-to-end against a live yappr instance on testnet (see checklist)

Checklist / open questions before merge

  • End-to-end login against yappr on testnet with a username-loaded wallet
  • Sign-off on the wallet-defined login-key derivation scheme (needs checking against the private YAPPR_DET_SIGNER_SPEC.md)
  • Confirm BlockHeight(10000) (copied from IdentityVerify) is correct for the key-exchange contract publish
  • Decide whether approval should prompt for the PIN interactively (CheckPinDialog) instead of the SecurityGuard path

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added a DashConnect Connections entry in Tools with a new screen to view, scan, and manage connection statuses.
    • Added approve/deny UI for pending connection requests via a confirmation bottom sheet.
    • Added DashConnect deep-link and QR handling for dash-key: / dash-st: (including themed connection icons).
  • Improvements
    • Enhanced QR scanning reliability and improved special-input routing for DashConnect URIs.
    • Added deep-link navigation support to the Connections screen and expanded relevant activity intent filters.
  • Tests
    • Expanded DashConnect URI and key-exchange/derivation test coverage.

HashEngineering and others added 3 commits July 9, 2026 11:51
Add the Connections feature for connecting the DashPay wallet to DApps
on the Dash network (first target: yappr on testnet):

- New "Connections" menu item on the Tools screen
- ConnectionsScreen with empty state and state-driven connection list
  (approved / active / disconnected) per the DashConnect Figma designs
- "Approve connection" bottom sheet with app permissions, username and
  identity details, and Approve/Deny actions
- QR scanning via the existing ScanActivity; the ViewModel classifies
  scans as connection requests (approve sheet) or login requests
- DashConnectRepository interface with a mock implementation as the
  swap point for the upcoming Dash Platform data contract integration

Co-Authored-By: Claude Fable 5 <[email protected]>
…945)

Replace the mock DashConnectRepository with a real implementation of the
Yappr key-exchange login protocol against the testnet key-exchange
contract (7UaqHGBJBbRLJ4fUWS45cnud8PPUugJWoGTt1SKwHJ2P):

- Protocol layer (pure, unit-tested against the platform-auth fixture
  vectors): dash-key:/dash-st: URI parsing and validation, hash160,
  ECDH x-coordinate + HKDF-SHA256 (salt "dash:key-exchange:v1"),
  AES-256-GCM 60-byte payload, and login-key-derived auth/encryption
  key checks
- Deterministic login-key derivation: HKDF-SHA256 over the
  BLOCKCHAIN_IDENTITY auth-chain key, salted by identity id and
  scoped by app contract id ("dash:login-key:v1"), keyIndex 0
- dash-key approval publishes (or replaces, per the unique
  ($ownerId, contractId) index) a loginKeyResponse document via the
  low-level document put/replace path (Documents.broadcast is
  unimplemented in dash-sdk 4.0.0-RC2)
- dash-st key registration: deserializes the IdentityUpdateTransition,
  validates it end-to-end against the issued login key (forged-QR
  rejection), signs with the identity master key and broadcasts
- Local connection status store via DataStore (DashConnectConfig);
  connection list merges platform docs with local state
- Feature gated to testnet (no mainnet contract deployment); the app
  label from the QR is treated as an unauthenticated claim in the UI

34 unit tests pass (test_testNet3DebugUnitTest).

Co-Authored-By: Claude Fable 5 <[email protected]>
…ewModel

Take the gift-card cache fix from fix/other-review-fixes: the tx metadata
change cache now records the merged gift card values (and the merge
preserves redeemUrlChallenge), with the test updated for the new
order/giftCardChallenge/index parameters of insertGiftCardData.

Update MainViewModelTest for the current MainViewModel signature: mock the
new CrowdNodeApi dependency and stub the collaborators its init block now
touches (BlockchainIdentityConfig.observe(), getWorkInfosByTagFlow,
isRestoringBackup, isPlatformAvailable, TxDisplayCacheService, and the
crowdnode withdrawal reminder saved-state key).

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a testnet-gated DashConnect Connections feature with URI parsing, cryptographic key exchange, persistence, platform integration, Compose UI, QR routing, navigation, localized resources, and supporting tests.

Changes

DashConnect Connections

Layer / File(s) Summary
Protocol and cryptographic primitives
wallet/src/.../connections/protocol/*, wallet/test/.../connections/protocol/*
Adds validated URI parsing, deterministic login-key derivation, ECDH/AES-GCM operations, derived protocol keys, and tests.
Storage and platform integration
wallet/src/.../connections/DashConnect*.kt, PlatformDashConnectRepository.kt, ConnectionsModule.kt
Adds connection models, DataStore persistence, repository operations, platform login/key registration, lifecycle updates, and Hilt binding.
Connections UI and approval flow
wallet/src/.../connections/*, wallet/src/.../compose_views/ApproveConnectionDialog.kt, wallet/res/values/*, wallet/res/drawable/ic_connections_*
Adds Compose screens, ViewModel state handling, approval dialogs, scanner processing, localized resources, and vector assets.
Routing and QR scanning
wallet/res/navigation/*, wallet/AndroidManifest.xml, wallet/src/.../main/*, common/src/.../address_input/*, common/src/.../scan/*, build.gradle
Adds navigation and deep-link entry points, special-input handling, QR decoding improvements, and the ZXing update.

Existing test dependency wiring

Layer / File(s) Summary
Test fixture updates
wallet/test/de/.../MainViewModelTest.kt, wallet/test/de/.../WalletTransactionMetadataProviderGiftCardTest.kt
Updates mocks, observable flows, and constructor arguments required by existing tests.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Scanner as ScanActivity
  participant Fragment as ConnectionsFragment
  participant ViewModel as ConnectionsViewModel
  participant Repository as PlatformDashConnectRepository
  participant Platform as PlatformService
  Scanner->>Fragment: Return scanned QR content
  Fragment->>ViewModel: onQrScanned(qrContent)
  ViewModel->>Repository: parseQr(qrContent)
  Repository-->>ViewModel: Login or key-registration request
  ViewModel-->>Fragment: Show approval or completion result
  Fragment->>ViewModel: Approve pending request
  ViewModel->>Repository: approveLogin(request)
  Repository->>Platform: Publish loginKeyResponse
Loading

Possibly related PRs

Suggested reviewers: abaranouski

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.64% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: adding DashConnect QR key-exchange login to connect DashPay wallets to DApps.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/dash-connect

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 4

🧹 Nitpick comments (5)
wallet/src/de/schildbach/wallet/service/WalletTransactionMetadataProvider.kt (1)

355-365: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract shared gift-card merge logic to avoid duplication.

The merge block in updateGiftCardMetadata (lines 355–365) is nearly identical to the one in insertOrUpdateGiftCard (lines 705–715). Both merge the same fields with the same fallback strategy. Extracting a helper like mergeGiftCard(incoming: GiftCard, existing: GiftCard): GiftCard would eliminate this duplication and prevent future divergence.

♻️ Proposed refactor: extract merge helper
 private fun mergeGiftCard(incoming: GiftCard, existing: GiftCard): GiftCard =
     existing.copy(
         merchantName = incoming.merchantName.ifEmpty { existing.merchantName },
         price = incoming.price.takeIf { it != 0.0 } ?: existing.price,
         number = incoming.number ?: existing.number,
         pin = incoming.pin ?: existing.pin,
         barcodeValue = incoming.barcodeValue ?: existing.barcodeValue,
         barcodeFormat = incoming.barcodeFormat ?: existing.barcodeFormat,
         merchantUrl = incoming.merchantUrl ?: existing.merchantUrl,
         note = incoming.note ?: existing.note,
         redeemUrlChallenge = incoming.redeemUrlChallenge ?: existing.redeemUrlChallenge
     )

 // In updateGiftCardMetadata:
-        val merged = if (existing == null) {
-            giftCard
-        } else {
-            existing.copy(
-                merchantName = giftCard.merchantName.ifEmpty { existing.merchantName },
-                price = giftCard.price.takeIf { it != 0.0 } ?: existing.price,
-                number = giftCard.number ?: existing.number,
-                pin = giftCard.pin ?: existing.pin,
-                barcodeValue = giftCard.barcodeValue ?: existing.barcodeValue,
-                barcodeFormat = giftCard.barcodeFormat ?: existing.barcodeFormat,
-                merchantUrl = giftCard.merchantUrl ?: existing.merchantUrl,
-                note = giftCard.note ?: existing.note,
-                redeemUrlChallenge = giftCard.redeemUrlChallenge ?: existing.redeemUrlChallenge
-            )
-        }
+        val merged = if (existing == null) giftCard else mergeGiftCard(giftCard, existing)

 // In insertOrUpdateGiftCard:
-            val updatedGiftCard = existingGiftCard.copy(
-                merchantName = giftCard.merchantName.ifEmpty { existingGiftCard.merchantName },
-                price = giftCard.price.takeIf { it != 0.0 } ?: existingGiftCard.price,
-                number = giftCard.number ?: existingGiftCard.number,
-                pin = giftCard.pin ?: existingGiftCard.pin,
-                barcodeValue = giftCard.barcodeValue ?: existingGiftCard.barcodeValue,
-                barcodeFormat = giftCard.barcodeFormat ?: existingGiftCard.barcodeFormat,
-                merchantUrl = giftCard.merchantUrl ?: existingGiftCard.merchantUrl,
-                note = giftCard.note ?: existingGiftCard.note,
-                redeemUrlChallenge = giftCard.redeemUrlChallenge ?: existingGiftCard.redeemUrlChallenge
-            )
+            val updatedGiftCard = mergeGiftCard(giftCard, existingGiftCard)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@wallet/src/de/schildbach/wallet/service/WalletTransactionMetadataProvider.kt`
around lines 355 - 365, Extract the duplicated gift-card field merge logic into
a shared helper, such as mergeGiftCard(incoming: GiftCard, existing: GiftCard):
GiftCard, preserving the current fallback behavior for every field. Replace the
inline copy blocks in updateGiftCardMetadata and insertOrUpdateGiftCard with
calls to this helper.
wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectConfig.kt (2)

90-100: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Non-atomic read-modify-write can lose connection updates.

Both upsertConnection and updateStatus read via getConnections() and then set(...) as separate suspend steps. Concurrent calls (e.g., an approveLogin upsert racing a disconnect status update) can interleave and drop one of the writes. Consider performing the mutation inside a single atomic DataStore edit/update block, or serialize writes through a mutex, so the read and write are one operation.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectConfig.kt`
around lines 90 - 100, Make upsertConnection and updateStatus atomic to prevent
concurrent connection updates from being lost. Replace the separate
getConnections/read and set/write sequence with a single DataStore edit/update
transaction, or serialize both mutations through a shared Mutex; preserve each
method’s existing filtering, replacement, and status-update behavior.

108-116: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Malformed JSON drops all stored connections.

Wrapping the whole array parse in a single try/catch means one corrupt entry discards every persisted connection (label/url/status). Prefer decoding entries individually and skipping only the bad ones, and log the failure rather than swallowing it silently (also addresses the detekt swallowed-exception hint).

♻️ Suggested per-entry decode
     private fun decode(raw: String?): List<StoredConnection> {
         if (raw.isNullOrEmpty()) return emptyList()
         return try {
             val array = JSONArray(raw)
-            (0 until array.length()).map { StoredConnection.fromJson(array.getJSONObject(it)) }
+            (0 until array.length()).mapNotNull { i ->
+                try {
+                    StoredConnection.fromJson(array.getJSONObject(i))
+                } catch (ex: Exception) {
+                    log.warn("skipping malformed stored connection at index $i", ex)
+                    null
+                }
+            }
         } catch (ex: Exception) {
+            log.warn("failed to decode stored connections", ex)
             emptyList()
         }
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectConfig.kt`
around lines 108 - 116, Update decode to parse the JSONArray once, then decode
each element independently, retaining valid StoredConnection results while
skipping malformed entries. In the per-entry catch, log the exception with
appropriate context instead of silently swallowing it, while still returning an
empty list for invalid top-level JSON.

Source: Linters/SAST tools

wallet/test/de/schildbach/wallet/ui/more/connections/protocol/LoginKeyDerivationTest.kt (1)

29-64: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding a fixed-vector test for deriveLoginKey.

The current tests verify invariants (determinism, per-app/identity/chain-key differentiation) but don't pin the exact output against a known DApp fixture. KeyExchangeCryptoTest already uses fixed hex vectors from yappr-vectors.ts for deriveAuthPrivateKey and deriveEncryptionPrivateKey — adding the same for deriveLoginKey would catch derivation mismatches early and align with the PR's open question on "validation of the login-key derivation scheme."

♻️ Suggested addition
 class LoginKeyDerivationTest {
 
     private val chainKey = ByteArray(32) { 0x11 }
     private val identityId = ByteArray(32) { 0xab.toByte() }
     private val contractA = ByteArray(32) { 0xcd.toByte() }
     private val contractB = ByteArray(32) { 0xef.toByte() }
+    // Expected output for (chainKey=0x11*32, identityId=0xab*32, contractA=0xcd*32)
+    // Compute from the DApp fixture and pin it here:
+    private val expectedLoginKeyHex = "<fill-from-fixture>"
 
+    `@Test`
+    fun deriveLoginKey_matchesFixture() {
+        val key = LoginKeyDerivation.deriveLoginKey(chainKey, identityId, contractA)
+        assertEquals(expectedLoginKeyHex, Utils.HEX.encode(key))
+    }
+
     `@Test`
     fun deriveLoginKey_isDeterministicForSameInputs() {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@wallet/test/de/schildbach/wallet/ui/more/connections/protocol/LoginKeyDerivationTest.kt`
around lines 29 - 64, Add a fixed-vector test alongside the existing
deriveLoginKey tests, using the known DApp fixture inputs and expected
hexadecimal output from yappr-vectors.ts, following the pattern in
KeyExchangeCryptoTest. Assert the derived key’s exact bytes so
LoginKeyDerivation.deriveLoginKey is validated against the external derivation
scheme.
wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsViewModel.kt (1)

70-77: 📐 Maintainability & Code Quality | 🔵 Trivial

Consider consolidating approveResult and scanOutcome into ConnectionsUIState per ViewModel guidelines.

As per coding guidelines, ViewModels should use a single UIState data class rather than multiple separate flows. The approveResult and scanOutcome flows could be fields within ConnectionsUIState to comply with this convention. That said, since these are event-like states that get reset after handling, keeping them separate is a defensible design choice — use your judgment.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsViewModel.kt`
around lines 70 - 77, Consolidate the event-like approveResult and scanOutcome
flows into the existing ConnectionsUIState data class, removing the separate
MutableStateFlow and public StateFlow declarations. Update all
ConnectionsViewModel read/write/reset logic and UI collectors to access these
fields through uiState, preserving their current Idle and handled-state
behavior.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@wallet/src/de/schildbach/wallet/ui/compose_views/ApproveConnectionDialog.kt`:
- Around line 74-91: Approval failures in LaunchedEffect are reset without
presenting feedback to the user. In the ApproveResult.Error branch, display the
contained error message using the dialog UI or a Toast before calling
viewModel.resetApproveResult(), while preserving the existing dialog
re-enablement behavior.

In `@wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsFragment.kt`:
- Around line 112-116: Pass an onDismiss callback to
createApproveConnectionDialog in showApproveConnectionDialog, invoking
viewModel.denyPendingRequest() so pending requests are cleared whenever the
dialog is dismissed, including outside-touch dismissal; retain the existing
viewModel and show behavior.

In `@wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsViewModel.kt`:
- Around line 99-104: In the DashConnectQr.Login branch, compute the result of
the suspend function toConnectionRequest(payload.request) before calling
_uiState.update, then pass the precomputed value into the update lambda. Keep
the lambda limited to copying pendingRequest so CAS retries cannot repeat
repository or identity lookups.

In
`@wallet/src/de/schildbach/wallet/ui/more/connections/PlatformDashConnectRepository.kt`:
- Line 216: Replace the unsafe `platformRepo.walletApplication.wallet!!` lookup
in the `Signer` initialization with an explicit null check, throwing
`IllegalStateException("wallet not available")` when the wallet is unavailable,
consistent with the guarded lookups in the surrounding method.

---

Nitpick comments:
In
`@wallet/src/de/schildbach/wallet/service/WalletTransactionMetadataProvider.kt`:
- Around line 355-365: Extract the duplicated gift-card field merge logic into a
shared helper, such as mergeGiftCard(incoming: GiftCard, existing: GiftCard):
GiftCard, preserving the current fallback behavior for every field. Replace the
inline copy blocks in updateGiftCardMetadata and insertOrUpdateGiftCard with
calls to this helper.

In `@wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsViewModel.kt`:
- Around line 70-77: Consolidate the event-like approveResult and scanOutcome
flows into the existing ConnectionsUIState data class, removing the separate
MutableStateFlow and public StateFlow declarations. Update all
ConnectionsViewModel read/write/reset logic and UI collectors to access these
fields through uiState, preserving their current Idle and handled-state
behavior.

In `@wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectConfig.kt`:
- Around line 90-100: Make upsertConnection and updateStatus atomic to prevent
concurrent connection updates from being lost. Replace the separate
getConnections/read and set/write sequence with a single DataStore edit/update
transaction, or serialize both mutations through a shared Mutex; preserve each
method’s existing filtering, replacement, and status-update behavior.
- Around line 108-116: Update decode to parse the JSONArray once, then decode
each element independently, retaining valid StoredConnection results while
skipping malformed entries. In the per-entry catch, log the exception with
appropriate context instead of silently swallowing it, while still returning an
empty list for invalid top-level JSON.

In
`@wallet/test/de/schildbach/wallet/ui/more/connections/protocol/LoginKeyDerivationTest.kt`:
- Around line 29-64: Add a fixed-vector test alongside the existing
deriveLoginKey tests, using the known DApp fixture inputs and expected
hexadecimal output from yappr-vectors.ts, following the pattern in
KeyExchangeCryptoTest. Assert the derived key’s exact bytes so
LoginKeyDerivation.deriveLoginKey is validated against the external derivation
scheme.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d3fe7827-6bf2-462d-9d66-e9f00d1a41b7

📥 Commits

Reviewing files that changed from the base of the PR and between 618ac7b and 19c0734.

📒 Files selected for processing (27)
  • wallet/res/drawable/ic_connections_check_circle.xml
  • wallet/res/drawable/ic_connections_empty.xml
  • wallet/res/drawable/ic_connections_qr.xml
  • wallet/res/drawable/ic_connections_xmark_circle.xml
  • wallet/res/drawable/ic_menu_connections.xml
  • wallet/res/navigation/nav_home.xml
  • wallet/res/values/strings-dashpay.xml
  • wallet/src/de/schildbach/wallet/service/WalletTransactionMetadataProvider.kt
  • wallet/src/de/schildbach/wallet/ui/compose_views/ApproveConnectionDialog.kt
  • wallet/src/de/schildbach/wallet/ui/more/ToolsFragment.kt
  • wallet/src/de/schildbach/wallet/ui/more/ToolsScreen.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsFragment.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsModule.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsScreen.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsViewModel.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectConfig.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectRepository.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/PlatformDashConnectRepository.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/protocol/DashConnectUri.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/protocol/KeyExchangeCrypto.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/protocol/LoginKeyDerivation.kt
  • wallet/test/de/schildbach/wallet/service/WalletTransactionMetadataProviderGiftCardTest.kt
  • wallet/test/de/schildbach/wallet/ui/more/connections/PlatformDashConnectRepositoryTest.kt
  • wallet/test/de/schildbach/wallet/ui/more/connections/protocol/DashConnectUriTest.kt
  • wallet/test/de/schildbach/wallet/ui/more/connections/protocol/KeyExchangeCryptoTest.kt
  • wallet/test/de/schildbach/wallet/ui/more/connections/protocol/LoginKeyDerivationTest.kt
  • wallet/test/de/schildbach/wallet/util/viewModels/MainViewModelTest.kt

HashEngineering and others added 3 commits July 10, 2026 08:52
…(MO-945)

Verified live: login QR scan -> approve -> loginKeyResponse publish/replace,
and first-login key registration adding the two derived keys to the identity,
with yappr completing login on both paths.

QR scanner (shared ScanActivity/CameraManager):
- decode the full preview frame instead of the framing-rect crop (the crop
  forced users inside the camera's minimum focus distance and clipped the
  QR quiet zone)
- meter and focus on the frame center; alternate decode passes with a
  highlight-stretched luminance source — a bright QR card on a dark-mode
  page gets overexposed to ~220..255 luminance, which no binarizer can
  threshold (captured-frame analysis)
- upgrade ZXing 3.3.3 -> 3.5.3 (minSdk is now 24) and enable TRY_HARDER

DashConnect URI handling:
- route dash-key:/dash-st: QRs from the home, payments, and address-input
  scanners to the Connections screen (scannedUri nav argument)
- register dash-key/dash-st schemes in the manifest so the system camera
  and browsers deep-link into the wallet (with cold-start nav retry)

Protocol/platform fixes:
- approve stores the connection as APPROVED (awaiting login); ACTIVE only
  after key registration completes
- replace an existing loginKeyResponse by mutating the queried document —
  a freshly created document gets a new $id and Drive rejects the replace
  with DocumentNotFoundError (40101); also set the document type, which
  query-built Documents leave null (segfaults the native replace call)
- rebuild the dash-st identity update from our own derived keys via
  platformMobilePutPutIdentityUpdateSdk instead of countersigning the
  app's transition: the SDK cannot deserialize the wasm-sdk bincode
  payload (its factory is CBOR-only), the embedded revision/nonce go
  stale, and the wallet should never sign app-supplied transition bytes

UX:
- tap a connection to cancel a pending login, disconnect an active
  session, or remove an old connection (confirmation dialogs)
- log DashConnect errors with stack traces instead of toast-only

Also repairs the two compile-blocked unit tests (swapOrderDao/swapProvider
constructor params from the dash-dex merge). 103 unit tests pass.

Co-Authored-By: Claude Fable 5 <[email protected]>
@HashEngineering

Copy link
Copy Markdown
Collaborator Author

End-to-end verification complete ✅

The full DashConnect flow has now been verified live against yappr on testnet with a Galaxy S22:

  1. Login: scan dash-key: QR → approve → loginKeyResponse published (and replaced on repeat logins) on the key-exchange contract → yappr decrypts the login key
  2. First-login key registration: dash-st: QR → auth (HIGH/ECDSA_HASH160) + encryption (MEDIUM/ECDSA_SECP256K1) keys derived from the login key and added to the identity via a master-key-signed identity update → yappr completes login
  3. Repeat login: no second QR — yappr finds the registered keys and logs straight in

The latest commit (e172ad64d) contains the fixes that made this work, most notably:

  • Scanner: full-frame decoding, center metering + highlight-recovery decode pass (a bright QR on a dark-mode page overexposes past what any binarizer can threshold — root-caused from a captured camera frame), ZXing 3.5.3 + TRY_HARDER
  • dash-key:/dash-st: routing from every scanner entry point plus manifest-registered schemes (system camera / browser deep links)
  • Document replace: must mutate the queried document ($id must match; fresh documents get new entropy → DocumentNotFoundError 40101), and must set type explicitly (query-built Documents leave it null → native segfault)
  • Key registration redesigned: the wallet rebuilds the identity update from its own derived keys via platformMobilePutPutIdentityUpdateSdk rather than countersigning the app's transition — the SDK's StateTransitionFactory is CBOR-only and cannot parse the wasm-sdk bincode payload, the embedded revision/nonce snapshots go stale, and the wallet should never sign app-supplied transition bytes

SDK issues discovered (dashj-platform / kotlin bindings)

  • StateTransitionFactory.createFromBuffer only understands the legacy CBOR envelope; wasm-sdk (bincode) transitions crash the CBOR decoder
  • Document(RustDocument, …) constructor leaves type null; passing it to platformMobilePutReplaceDocumentSdk segfaults in the FFI string conversion (null-check missing on the Rust side)
  • yappr-side note: the registration QR at 200 px (~90+ modules) is undersized for phone camera scanning

🤖 Generated with Claude Code

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
wallet/test/de/schildbach/wallet/ui/more/connections/protocol/DashConnectUriTest.kt (1)

204-209: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Test the opposite scheme as well.

Add assertFalse checks so the helpers are verified to classify schemes exclusively.

Proposed test additions
     assertTrue(DashConnectUri.isKeyUri("dash-key:abc?n=t&v=1"))
     assertTrue(DashConnectUri.isStUri("dash-st:abc?n=t&v=1"))
+    assertFalse(DashConnectUri.isKeyUri("dash-st:abc?n=t&v=1"))
+    assertFalse(DashConnectUri.isStUri("dash-key:abc?n=t&v=1"))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@wallet/test/de/schildbach/wallet/ui/more/connections/protocol/DashConnectUriTest.kt`
around lines 204 - 209, Add negative assertions to schemeDetectors, verifying
isKeyUri rejects the dash-st URI and isStUri rejects the dash-key URI, while
retaining the existing positive assertions.
🧹 Nitpick comments (1)
common/src/main/java/org/dash/wallet/common/ui/scan/CameraManager.java (1)

284-294: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Reuse the stretched luminance buffer.

This allocates up to ~2 MB every other preview frame at 1080p while scanning. Keep a CameraManager buffer sized to the current preview and refill it synchronously.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@common/src/main/java/org/dash/wallet/common/ui/scan/CameraManager.java`
around lines 284 - 294, Update CameraManager around
buildStretchedLuminanceSource to maintain a reusable stretched luminance byte
buffer sized to the current preview resolution, reallocating only when the
required pixel count changes. Refill that buffer synchronously for each call and
pass it to PlanarYUVLuminanceSource instead of allocating a new byte array per
frame.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@wallet/src/de/schildbach/wallet/ui/more/connections/PlatformDashConnectRepository.kt`:
- Around line 293-297: Update completeKeyRegistration to use the dash-st payload
when selecting the approved connection, matching the registration request to its
originating connection before decoding contractId. Do not fall back to the most
recently updated approval; reject the flow with DashConnectUriException when no
specific connection can be matched, preserving correct key registration for
multiple simultaneous logins.

---

Outside diff comments:
In
`@wallet/test/de/schildbach/wallet/ui/more/connections/protocol/DashConnectUriTest.kt`:
- Around line 204-209: Add negative assertions to schemeDetectors, verifying
isKeyUri rejects the dash-st URI and isStUri rejects the dash-key URI, while
retaining the existing positive assertions.

---

Nitpick comments:
In `@common/src/main/java/org/dash/wallet/common/ui/scan/CameraManager.java`:
- Around line 284-294: Update CameraManager around buildStretchedLuminanceSource
to maintain a reusable stretched luminance byte buffer sized to the current
preview resolution, reallocating only when the required pixel count changes.
Refill that buffer synchronously for each call and pass it to
PlanarYUVLuminanceSource instead of allocating a new byte array per frame.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 949dcb51-379f-4a31-9619-e9f9e0d4f3f9

📥 Commits

Reviewing files that changed from the base of the PR and between 036971d and e172ad6.

📒 Files selected for processing (19)
  • build.gradle
  • common/src/main/java/org/dash/wallet/common/ui/address_input/AddressInputFragment.kt
  • common/src/main/java/org/dash/wallet/common/ui/scan/CameraManager.java
  • common/src/main/java/org/dash/wallet/common/ui/scan/ScanActivity.kt
  • wallet/AndroidManifest.xml
  • wallet/res/navigation/nav_home.xml
  • wallet/res/values/strings-dashpay.xml
  • wallet/src/de/schildbach/wallet/ui/main/MainActivity.kt
  • wallet/src/de/schildbach/wallet/ui/main/WalletFragment.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsFragment.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsViewModel.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectConfig.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectRepository.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/PlatformDashConnectRepository.kt
  • wallet/src/de/schildbach/wallet/ui/payments/PaymentsPayFragment.kt
  • wallet/src/de/schildbach/wallet/ui/send/DashAddressInputFragment.kt
  • wallet/test/de/schildbach/wallet/service/WalletTransactionMetadataProviderGiftCardTest.kt
  • wallet/test/de/schildbach/wallet/ui/more/connections/protocol/DashConnectUriTest.kt
  • wallet/test/de/schildbach/wallet/util/viewModels/MainViewModelTest.kt
🚧 Files skipped from review as they are similar to previous changes (2)
  • wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectConfig.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsFragment.kt

HashEngineering and others added 3 commits July 23, 2026 07:33
…MO-945)

After a dash-st key registration the identity carries two HIGH-security
authentication keys: the DashPay identity's own ECDSA_SECP256K1 key (in the
wallet keychain) and the app login key (ECDSA_HASH160, derived from the login
key, not in the wallet). getFirstPublicKey(SecurityLevel.HIGH) could return
the login key, which WalletSignerCallback cannot sign with — the native
signer callback returns 0 and the publish/replace fails. Select the
ECDSA_SECP256K1 HIGH authentication key explicitly so repeat logins after a
key registration succeed.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ity (MO-945)

Consume the updated dash-sdk (4.0.1-SNAPSHOT) and build on its new
state-transition deserialization:

- dash-st validation: verifyKeyRegistrationTransition() natively decodes the
  scanned IdentityUpdate and checks it is for our identity and adds exactly
  our derived login keys before we sign/broadcast our own rebuilt update
  (defence-in-depth against a forged QR).
- approveLogin marks the connection ACTIVE immediately when the derived login
  keys are already on the identity (repeat login completes with no dash-st);
  otherwise APPROVED, awaiting the key-registration scan.
- resolveAppInfo(): show a Platform-sourced name — the app contract's owner
  identity's DashPay profile displayName / DPNS username — falling back to the
  QR label. (The web domain e.g. "yappr.io" is not on-chain, so the subtitle
  shows the DPNS handle.)

UI refresh to the revised Figma:
- empty state: icon/heading/body in a white card, Scan QR button below it
- approve sheet subtitle shows the app label, not the contract id
- APPROVED connections show an in-card blue "scan to complete login" banner
  with an inline small Scan QR button
- ACTIVE connections show status + date + a toggle; toggling off disconnects
  directly (no dialog) and returns the connection to APPROVED (Figma has no
  separate Disconnected state)

Also includes a temporary self-verify query after publishing loginKeyResponse
that logs whether the document is findable by (contractId, appEphemeralPubKeyHash)
— diagnostics for the "app doesn't see the login" investigation; to be removed
once confirmed.

Co-Authored-By: Claude Fable 5 <[email protected]>
- Approve sheet: display the wallet's DPNS label (e.g. "John.Doe") instead of
  the lower-cased normalizedLabel, via DashConnectRepository.resolveWalletUsername()
  (resolves the owner identity's DPNS domain label from Platform, falling back
  to the stored username). The wallet identity id is truncated in the middle
  (7 leading + 5 trailing chars, e.g. "5DbLwAx…zUo8").
- Connections row tap is now a no-op: connections are managed only by the QR
  scan and the row slider, matching the Figma design. Removed the row-tap
  AdaptiveDialog (cancel-login / remove) that was not part of the design.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@coderabbitai coderabbitai Bot 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
build.gradle (1)

34-34: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Document the real source of the API 24 requirement.

The API 24 minimum is established by the Android modules (common and wallet both declare minSdkVersion 24), not by com.google.zxing:core:3.5.3. Adjust the comment to reference the app/module minSdkVersion to avoid implying ZXing 3.5.3 requires Android 7.x.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@build.gradle` at line 34, Update the inline comment on zxingVersion to state
that API 24 is required by the app modules’ minSdkVersion declarations,
specifically common and wallet, rather than implying com.google.zxing:core:3.5.3
requires Android 7.x.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@build.gradle`:
- Line 34: Update the inline comment on zxingVersion to state that API 24 is
required by the app modules’ minSdkVersion declarations, specifically common and
wallet, rather than implying com.google.zxing:core:3.5.3 requires Android 7.x.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: bf9a78c8-0dab-40d5-8e18-2595a3a021fc

📥 Commits

Reviewing files that changed from the base of the PR and between 89f35f2 and 1b43dfd.

📒 Files selected for processing (8)
  • build.gradle
  • wallet/res/values/strings-dashpay.xml
  • wallet/src/de/schildbach/wallet/ui/compose_views/ApproveConnectionDialog.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsFragment.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsScreen.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsViewModel.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectRepository.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/PlatformDashConnectRepository.kt
🚧 Files skipped from review as they are similar to previous changes (5)
  • wallet/res/values/strings-dashpay.xml
  • wallet/src/de/schildbach/wallet/ui/compose_views/ApproveConnectionDialog.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/DashConnectRepository.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/ConnectionsViewModel.kt
  • wallet/src/de/schildbach/wallet/ui/more/connections/PlatformDashConnectRepository.kt

HashEngineering and others added 10 commits July 24, 2026 13:24
…O-945)

dash-st fix (first login was broken for new identities):
yappr's dash-st QR carries IdentityUpdateTransition::serialize bytes WITHOUT
the outer StateTransition enum tag, so StateTransition deserialization read
the payload version byte as the DataContractCreate variant and failed with
UnexpectedVariant. Prepend IdentityUpdate's bincode variant tag (6) before
deserializing, falling back to the raw bytes in case the app ever sends full
StateTransition bytes. Verified end-to-end on testnet: dash-st verified and
2 login keys registered on a fresh identity.

App display resolution:
- DashConnectBranding: yappr-specific name ("Yappr") and website ("yap.pr")
  substituted for the QR's free-text "Login to Yappr" label, pending a
  reusable on-chain metadata path for apps.
- resolveAppDisplay(contractId, qrLabel): contract owner's DashPay
  displayName / DPNS username from Platform, else branding, else raw label;
  url = DPNS handle, else branding website, else blank.
- Approve sheet: title shows the resolved app name; subtitle now shows the
  app website (ConnectionRequest gains appUrl) instead of repeating the name.
- Connections row falls back to branding for name/url when Platform
  resolution comes up empty.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brings in dark mode support (#1480) and the Dash DEX sell-swap fixes (#1519).

Conflicts (both in Tools, where DashConnect added its menu entry):
- ToolsFragment: keep our onConnectionsClick wiring inside master's new
  DashWalletTheme wrapper.
- ToolsScreen: keep the Connections MenuItem in the first Menu block, which
  master now closes before the username-gated Credits Menu.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
After merging dark mode (#1480), MyTheme.Colors is specifically the LIGHT
palette — themes are applied by providing MyTheme.DarkColors through
LocalDashColors. Our screens read MyTheme.Colors directly, so they would have
stayed light while the rest of the app went dark.

- Read colors from LocalDashColors.current in ConnectionsScreenContent,
  ConnectionsEmptyState, ScanToCompleteBanner, ConnectionListItem,
  ApproveConnectionContent, PermissionRow and DetailRow.
- Wrap ConnectionsFragment's ComposeView content in DashWalletTheme (the
  approve sheet already gets it from ComposeBottomSheet, which master wrapped).

The DashConnect drawables need no change: they use brand colours (dash blue,
green, red, mid-grey) that are identical in both themes, matching how master's
own menu icons are defined.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The diagnostic confirmed what it was added to check: after publishing, the
document is findable by (contractId, appEphemeralPubKeyHash) — exactly how the
app polls for it — and the full login now completes end-to-end on testnet.

Its "stored appEphHash=null" line was misleading rather than informative: the
value comes back from the SDK as a type other than ByteArray, so the `as?`
cast yielded null even though the query had just matched on that same field.
Leaving it in would send the next person chasing a non-problem.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
wasm-dpp2's IdentityUpdateTransition::to_bytes() serializes the bare inner
transition, while the StateTransition wrapper's to_bytes() emits the enum tag.
yappr uses the wrapper on its document path but not on the identity-update
path, so the tagless framing we see is incidental and a future refactor could
flip it. Note that this is why both framings are accepted, and that no upstream
spec states which to expect.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
- ConnectionsViewModel: resolve the connection request BEFORE _uiState.update {}.
  update is a compare-and-set retry loop, so a retry would re-run its lambda —
  and that lambda now makes two Platform round trips (resolveWalletUsername and
  resolveAppDisplay), which could repeat and observe different results.
- ApproveConnectionDialog: show why an approval failed. The Error branch reset
  the result to Idle immediately, so the message the ViewModel captured was
  discarded and the sheet simply became interactive again with no explanation
  (which is what made the earlier "Approve doesn't complete" issue log-only to
  diagnose). Keep the Error result so its message renders above the buttons,
  clear it when the sheet is dismissed, and let a retry supersede it.
- PlatformDashConnectRepository: replace wallet!! with an explicit null check,
  consistent with the other guarded lookups in publishLoginKeyResponse.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Constants.SUPPORTS_CONNECT is false by default and set true for _testNet3,
staging and devnet, so the prod flavour never exposes the feature. Fixes two
missing semicolons in the in-progress declaration/assignment.

Beyond the Tools menu entry, the three dash-key:/dash-st: QR interception sites
are now gated too (WalletFragment, PaymentsPayFragment, DashAddressInputFragment).
Without that, a prod build scanning a DashConnect QR would still navigate to the
Connections screen just to report the feature is unavailable; now those URIs fall
through to the normal unrecognised-QR error.

ConnectFlagTest asserts the flag equals !IS_PROD_BUILD, so it runs per flavour
and fails if prod ever ships with DashConnect enabled. Verified: prod false,
_testNet3 true. All four flavours compile.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
# Conflicts:
#	wallet/test/de/schildbach/wallet/service/WalletTransactionMetadataProviderGiftCardTest.kt
The master merge added the same import from both sides, which Kotlin rejects
as ambiguous and broke the test compile.

Co-Authored-By: Claude Opus 4.8 <[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