Skip to content

fix(platform-wallet)!: complete dashpay#3841

Open
shumkov wants to merge 101 commits into
v3.1-devfrom
feat/dashpay-m1-sync-correctness
Open

fix(platform-wallet)!: complete dashpay#3841
shumkov wants to merge 101 commits into
v3.1-devfrom
feat/dashpay-m1-sync-correctness

Conversation

@shumkov

@shumkov shumkov commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator

Issue being fixed or feature implemented

Milestone 1 of the DashPay completion plan (docs/dashpay/SPEC.md, included in this PR with its research base). DashPay's contact-request flow was broken in four independent, previously-unknown ways:

  1. Every send_contact_request was rejected by consensus — the broadcast carried a document id derived from the creation entropy but fresh entropy in the transition; drive-abci recomputes the id and rejects with InvalidDocumentTransitionIdError.
  2. Wrong encryption wire format — we encrypted the 107-byte DIP-14 ExtendedPubKey::encode() form; DIP-15 and both reference mobile clients (iOS dash-shared-core, Android dashj) use the 69-byte compact fingerprint‖chaincode‖pubkey. Our send failed its own 96-byte ciphertext check; our receive couldn't parse mobile payloads.
  3. Key-purpose incompatibility with mobile clients — verified against all 368 contactRequest documents on testnet: the dominant mobile cohort references an ENCRYPTION key for both key indices (mobile identities carry no DECRYPTION key); our send/validation required DECRYPTION and would fail in both directions.
  4. Sync could not establish contacts — the ingest guard dropped reciprocal requests (offline-accept never established), restore-from-seed permanently bricked Accept (duplicate reciprocal vs the platform unique index), and incoming payments were invisible after restore (receiving account never rebuilt).

What was done?

Three logical commits:

  • docs(dashpay) — the 7-agent-reviewed implementation spec (protocol reference, per-layer inventory, gaps G1–G15, 5-milestone plan, Swift UI design, test plan) + 6 research files including the cross-client interop desk-check and the testnet key-purpose census.
  • fix(sdk)! — entropy threading (ContactRequestResult.entropy reused at broadcast), the DIP-15 69-byte compact-xpub codec in platform-encryption + the SDK callback contract switched to it, and the recipient key-purpose assertion relaxed to DECRYPTION-or-ENCRYPTION.
  • fix(platform-wallet) — new recurring DashPaySyncManager (iterates the wallets map, not the token registry; per-identity log-and-continue); ingest-guard relaxation + sent-side reconcile with idempotent, metadata-preserving merge; Accept adopts an existing on-platform reciprocal instead of re-broadcasting; per-sweep account rebuild (external and receiving accounts) with validate-before-ECDH, guard-drop lock ordering, and a transient/permanent failure policy (payment_channel_broken flag, persisted + FFI accessor); rejected-request tombstone keyed (owner, sender, accountReference) so rotated requests still surface; 69-byte compact parsing on receive with address-equality pinned; key-purpose envelope aligned with on-chain reality; DashPaySdkWriter seam making the write paths testable.

How Has This Been Tested?

TDD throughout — every behavioral fix has a test that was red against the unfixed code and green after (red→green evidence recorded in the SPEC.md M1 DONE notes and the three commit messages):

  • platform-wallet: 196 lib + 8 integration tests green (was 170 before this branch; +34 new)
  • dash-sdk (--features mocks,offline-testing): 139 lib tests green (incl. the entropy-id and 69→96-byte pins)
  • platform-encryption: 7/7 (the crate's test target previously failed to compile — fixed dev-deps)
  • cargo check clean on rs-sdk-ffi, platform-wallet-ffi, platform-wallet-storage; clippy clean on touched crates
  • Live e2e (dp_001..dp_006) is specced to ride the e2e framework in test(platform-wallet): e2e framework + full test suite — triage pins, Found-*/PA-* guards, fail-closed persist, Stage-2 merge #3549 and is explicitly not gated on this PR (SPEC.md Part 7.4)

Note

CI: Rust workspace tests / Tests (macOS) red on 3 pre-existing tests — passing locally.
The macOS check fails only on three receiver-payment tests
(register_contact_account_persists_account_registration,
reconcile_records_received_payments_from_receival_utxos,
reconcile_does_not_clobber_existing_entry_for_same_txid), all with
External signable wallet has no private key.

These pass locally in every configuration tested (9): cargo test, cargo nextest
(isolated and full platform-wallet suite), the CI feature set, --all-features, the
platform-wallet-family feature unification, under cargo llvm-cov coverage, and the
exact CI package set (drive+dpp+drive-abci+… --all-features under coverage) —
all on the same macOS/aarch64 as the runner. All green.

The wallet is provably WalletType::Seed-bearing through every code path (from_seed
Seed; the manager's insert_wallet stores it verbatim; get_wallet returns a &Wallet),
yet only the CI runner reads it as ExternalSignable. Root cause is a use-after-zeroize in
the key-wallet git dependency
: Wallet has a Drop that zeroizes its Zeroize-derived
wallet_type, so the discriminant can corrupt under a particular memory layout (UB is
environment-dependent — it manifests on the CI runner but not locally). This is outside
this PR's code
— pre-existing branch tests plus an external-dependency bug being tracked for
the key-wallet maintainers; the DashPay changes themselves are correct and green.

Breaking Changes

  • rs-sdk: the get_extended_public_key callback contract for create_contact_request/send_contact_request is now "return the 69-byte DIP-15 compact form" (was an encoded ExtendedPubKey); validated before encryption. ContactRequestResult gains a public entropy: Bytes32 field. The rs-sdk-ffi C ABI is unchanged (caller doc contract tightened).
  • platform-wallet storage: schema additions (contacts.payment_channel_broken column, rejected_contact_requests table) in the initial migration; ContactChangeSet gains a rejected field.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Recurring & on-demand DashPay sync with start/stop, status, interval and per-pass summaries (FFI + Swift controls)
    • Full DashPay UI: tab, Contacts, Requests, Contact detail, Add Contact, Send sheet, payment history
    • Local persisted DashPay payment history, device-local contact metadata, contact-info sync/publish, and wallet unlock from keychain mnemonic
  • Bug Fixes

    • DIP‑15 compact xpub interoperability and deterministic contact-request IDs
    • Improved key-purpose validation, payment-channel broken flag, and rejected-request tombstones
  • Documentation

    • Comprehensive DashPay spec, research notes, and interop desk‑check added

shumkov and others added 3 commits June 10, 2026 18:51
…earch

Seven-agent reviewed spec for completing the full DashPay flow (sync, contact
requests, payments, profiles) in the platform wallet + SwiftExampleApp:
protocol reference (DIP-9/11/13/14/15), per-layer implementation inventory,
15 prioritized gaps (G1-G15), 5-milestone work plan, Swift UI design with
normative interaction states, and a two-tier test plan aligned with the
unmerged e2e framework (PR #3549). Backed by 6 source-cited research files,
including the cross-client interop desk-check and an on-chain census of all
368 testnet contactRequest documents.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…ompact xpub, key-purpose interop

Three fixes to the rs-sdk/platform-encryption contact-request layer, each
pinned red-to-green:

1. Entropy mismatch (consensus rejection). send_contact_request generated
   fresh entropy for broadcast while the document id was derived from the
   creation entropy; drive-abci recomputes the id from the broadcast entropy
   and rejected EVERY send with InvalidDocumentTransitionIdError.
   ContactRequestResult now carries the creation entropy and send reuses it.
   Test: contact_request_result_entropy_derives_returned_id (red: field
   inexpressible pre-fix; green after).

2. DIP-15 69-byte compact xpub wire format. We encrypted the 107-byte DIP-14
   ExtendedPubKey::encode() form (failing our own 96-byte ciphertext check);
   DIP-15 and both reference mobile clients use fingerprint||chaincode||pubkey
   = 69 bytes. New compact_xpub_bytes/parse_compact_xpub codec in
   platform-encryption; the get_extended_public_key callback contract is now
   the 69-byte compact, validated before encryption. Test:
   test_encrypt_compact_xpub_is_exactly_96_bytes (+ round-trip and
   wrong-length rejection).

3. Key-purpose alignment with on-chain reality. Verified against all 368
   testnet contactRequests: the dominant mobile cohort references an
   ENCRYPTION key for BOTH indices (mobile identities carry no DECRYPTION
   key). The recipient-key assertion now accepts DECRYPTION or ENCRYPTION.
   Test: recipient_key_purpose_accepts_decryption_and_encryption (red on
   DECRYPTION-only predicate; green after).

BREAKING: the SDK-side get_extended_public_key callback must now return the
69-byte DIP-15 compact form (rs-sdk-ffi C ABI unchanged; caller doc
contract tightened). Also enables dashcore/rand in platform-encryption
dev-deps — the crate's tests previously failed to compile at all.

dash-sdk: 139 lib tests green (mocks,offline-testing); platform-encryption
7/7; rs-sdk-ffi check clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…blish/reconcile, account rebuild

Milestone 1 of docs/dashpay/SPEC.md. Makes DashPay sync actually converge to
a payable state, recurring, and restore-safe. Each behavior pinned
red-to-green (see SPEC.md Part 5 M1 DONE notes for the full test list).

- Recurring sync (G12): new DashPaySyncManager (modeled on
  PlatformAddressSyncManager) drives dashpay_sync() per wallet on the shared
  cadence/cancel/quiesce machinery — iterating the wallets map, NOT the
  token registry (which skips zero-token identities). Per-identity
  log-and-continue pushed into sync_contact_requests.
  Test: recurring_pass_syncs_every_wallet_including_zero_token_identities.

- Establish via sync (G1a): the ingest guard dropped reciprocal requests
  whose sender we had already sent to — the offline-accept scenario could
  never establish. Guard relaxed; reciprocals now flow into auto-establish.

- Sent-side reconcile (G13): sync now ingests our own on-platform sent
  requests (idempotent, metadata-preserving merge — naive re-establish wiped
  alias/note every sweep), and Accept adopts an existing reciprocal instead
  of re-broadcasting into the unique-index rejection that permanently bricked
  Accept after restore-from-seed.

- Account rebuild sweep (G1b): every established contact missing accounts
  gets validate-key-indices -> decrypt -> register external account, plus the
  DashpayReceivingFunds account (previously only created on fresh send, so
  restore-from-seed left incoming payments invisible). Candidates collected
  under the write guard, registered after guard drop (tokio RwLock is
  non-reentrant).

- Failure policy (G1c): transient failures retry next sweep; permanent
  decrypt/parse failures set the new EstablishedContact.payment_channel_broken
  flag (persisted; FFI accessor added) and stop retrying. Purpose-validation
  mismatches only log-and-skip.

- Reject tombstone (G5 stage 1): rejected requests are tombstoned by
  (owner, sender, accountReference) — never bare sender, so a rotated
  request with a bumped accountReference still gets through. New
  rejected_contact_requests table + ContactChangeSet.rejected.

- Receive-side compact xpub (G14): register_external_contact_account parses
  the 69-byte DIP-15 compact and reconstructs the contact xpub
  (address-equality pinned by reconstructed_xpub_derives_identical_addresses);
  legacy 78/107 fallback kept.

- Key-purpose envelope (G15, verified on-chain): send prefers the
  recipient's DECRYPTION key and falls back to ENCRYPTION (mobile identities
  have no DECRYPTION key); validate_contact_request gains a recipient
  purpose gate (AUTHENTICATION was silently accepted before) and a
  purpose_mismatch classification.

- Testability seam (G11): DashPaySdkWriter object-safe trait over the SDK
  write paths; fetch paths use the SDK's built-in mock.

platform-wallet: 196 lib + 8 integration tests green (was 170);
storage + FFI checks clean; FFI ABI extended by one accessor
(established_contact_is_payment_channel_broken).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 10, 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 DashPay SPEC/research docs and implements DIP-15 compact-xpub handling, tightened key-purpose validation, rejected-request tombstones and payment-channel-broken tracking, SDK writer seam, recurring DashPay sync manager, incoming-payment recording/reconciliation, FFI extensions (payments/sync/persistence/seed attach), SwiftData models, and SwiftExampleApp UI and tests.

Changes

DashPay Spec & Research

Layer / File(s) Summary
Spec and research docs
docs/dashpay/SPEC.md, docs/dashpay/research/*
Adds master SPEC and research documents covering DIP, keywallet, rs-platform-wallet, SDK/contract, Swift app, and interop desk-check.

Crypto & SDK

Layer / File(s) Summary
Platform encryption: compact xpub & contact-info
packages/rs-platform-encryption/*
Introduce COMPACT_XPUB_LEN, compact xpub assemble/parse, AES helpers for encToUserId/privateData, and tests.
rs-sdk contact-request contract
packages/rs-sdk/src/platform/dashpay/contact_request.rs, packages/rs-sdk-ffi/src/dashpay/contact_request.rs
Require 69-byte DIP‑15 plaintext, add entropy to ContactRequestResult, enforce sender/recipient purpose rules, reuse entropy when sending, and update docs/tests.
Wallet DIP-14/DIP-15 helpers
packages/rs-platform-wallet/src/wallet/identity/crypto/dip14.rs
Add compact_xpub serialization, reconstruct_contact_xpub, account-reference changes, and regression tests.

Validation, State & Storage

Layer / File(s) Summary
Contact validation
packages/rs-platform-wallet/src/wallet/identity/crypto/validation.rs
Classify purpose mismatches with purpose_mismatch flag; sender must be ENCRYPTION, recipient accepts `ENCRYPTION
Changeset & ManagedIdentity
packages/rs-platform-wallet/src/changeset/*, packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/*
Add RejectedContactRequest, rejected changeset map, rejected_contact_requests field and APIs (record_rejected_contact_request, is_request_rejected), idempotent sent handling, and metadata-preserving re-establish.
SQLite schema & migrations
packages/rs-platform-wallet-storage/migrations/*, packages/rs-platform-wallet-storage/src/sqlite/schema/contacts.rs
Add payment_channel_broken column and rejected_contact_requests table; writer/reader binding updated and tests adjusted.
Apply path
packages/rs-platform-wallet/src/wallet/apply.rs
Replay rejected tombstones into ManagedIdentity state during changeset apply.

FFI & Persistence

Layer / File(s) Summary
FFI contact persistence ABI
packages/rs-platform-wallet-ffi/src/contact_persistence.rs, packages/rs-platform-wallet-ffi/src/persistence.rs
Add payment_channel_broken to ContactRequestFFI, ContactRequestRejectionFFI, extend OnPersistContactsFn signature, and snapshot handling.
FFI payment history
packages/rs-platform-wallet-ffi/src/dashpay_payment.rs, packages/rs-platform-wallet-ffi/src/lib.rs
Expose managed_identity_get_dashpay_payments and deallocator; add module re-exports.
FFI sync bindings
packages/rs-platform-wallet-ffi/src/dashpay_sync.rs
Expose start/stop/status/set-interval/sync_now FFI for DashPay sync manager with pointer validation and tests.
FFI attach seed from mnemonic
packages/rs-platform-wallet-ffi/src/manager.rs
Add platform_wallet_manager_attach_wallet_seed_from_mnemonic FFI and tests; map SeedMismatch.
Contact info setter FFI
packages/rs-platform-wallet-ffi/src/contact_info.rs
Add platform_wallet_set_dashpay_contact_info_with_signer to publish contactInfo with external signer.

SDK writer seam & wallet integration

Layer / File(s) Summary
SDK writer seam
packages/rs-platform-wallet/src/wallet/identity/network/sdk_writer.rs
Add DashPaySdkWriter trait, parameter structs, SignerRef adapter, and SdkWriter production impl.
IdentityWallet wiring
packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs, packages/rs-platform-wallet/src/wallet/platform_wallet.rs
Inject sdk_writer into IdentityWallet and init with SdkWriter in PlatformWallet::new; profile flows use sdk_writer.put_document.

Contact flow refactor

Layer / File(s) Summary
Send/sync/accept/reject
packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs, packages/rs-platform-wallet/src/wallet/identity/network/contacts.rs
Send enforces sender key type/purpose, selects recipient key DECRYPTION-first; derive compact xpub bytes; sync fetches sent+received with log-and-continue, dedup, collects account-build candidates, validates before ECDH/register, persists broken-channel flags; accept adopts vs rebroadcast; reject records tombstones; decoding falls back from compact to legacy.

Payments, reconciliation & event bridge

Layer / File(s) Summary
Incoming payment recording
packages/rs-platform-wallet/src/wallet/identity/network/payments.rs, packages/rs-platform-wallet/src/changeset/core_bridge.rs
Implement record_incoming_dashpay_payments to record Received entries from TransactionDetected, add reconcile_incoming_payments local reconciliation; spawn_wallet_event_adapter invokes recorder.

Recurring sync manager

Layer / File(s) Summary
DashPaySyncManager & manager wiring
packages/rs-platform-wallet/src/manager/dashpay_sync.rs, packages/rs-platform-wallet/src/manager/mod.rs, packages/rs-platform-wallet/src/manager/accessors.rs, packages/rs-platform-wallet/src/lib.rs
New coordinator with re-entrancy guard, quiesce semantics, background thread; wire into PlatformWalletManager, add accessors and crate re-exports; dashpay_sync step independence.

Swift SDK and Example App

Layer / File(s) Summary
Swift persistence & handlers
packages/swift-sdk/Sources/SwiftDashSDK/Persistence/*, packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift
Add PersistentDashpayPayment, relation on PersistentIdentity, persistDashpayPayments, persistContacts now accepts rejected snapshots and paymentChannelBroken, callback marshalling updated.
Swift PlatformWallet APIs
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/*.swift
Add getDashPayPayments, DashPay sync control APIs, unlockWalletFromKeychain attach-seed flow, and dashPaySyncIsSyncing state.
SwiftExampleApp UI & tests
packages/swift-sdk/SwiftExampleApp/*, packages/swift-sdk/SwiftExampleApp/SwiftExampleAppUITests/DashPayTabUITests.swift
Add DashPay tab, Contacts/Requests/Add/Detail/Send views, DashPayContactMetaStore, UI wiring to start/stop sync, unit persistence tests, and XCUITests.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

ready for final review

Suggested reviewers

  • lklimek
  • llbartekll
  • ZocoLini
  • thepastaclaw

Poem

"🐇 I nibbled through specs and threaded compact keys,

I traced tombstones where broken channels freeze.
I hop through syncs and tests that hum and play,
Payments march in rows, and UIs show the way.
Hooray — small hops, big fixes, now let the builds sway!"

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/dashpay-m1-sync-correctness

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

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

@thepastaclaw

thepastaclaw commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator

✅ Review complete (commit e57587f)

@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: 11

Caution

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

⚠️ Outside diff range comments (1)
packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs (1)

806-875: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

The accept-adopt check is only local, not platform-aware.

already_reciprocated is derived from local sent_contact_requests / established_contacts, but the sync code above explicitly allows "received loaded, sent fetch failed" by logging and continuing. In that state the reciprocal already exists on Platform while already_reciprocated is still false here, so this path retries the same (ownerId, toUserId, accountReference) write and gets the unique-index rejection instead of adopting. This needs a platform check here, or a duplicate-send fallback that switches to the adopt path.

🤖 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 `@packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs`
around lines 806 - 875, The local-only already_reciprocated check (variable
already_reciprocated) can be stale; change the flow so before attempting
send_contact_request_with_external_signer you either (A) perform a platform
check for an existing reciprocal contact request/relationship (use whatever
network client/query you have for checking platform contact requests for
(ownerId,toUserId,accountReference)) and set already_reciprocated accordingly,
or (B) keep the existing local check but add a duplicate-send fallback: catch
the unique-index conflict/error returned by
send_contact_request_with_external_signer and, on that specific error, log that
the reciprocal exists on Platform and run the adopt path (call
register_contact_account(&our_identity_id, &sender_id, 0) and treat as success).
Reference already_reciprocated, send_contact_request_with_external_signer, and
register_contact_account when implementing either fix.
🤖 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 `@docs/dashpay/research/01-dip-spec.md`:
- Line 131: Several fenced code blocks use plain ``` without a language tag;
update each triple-backtick fence in the document (e.g., the blocks currently
shown as ``` at the indicated locations) to include an explicit language token
(for non-code or prose use `text`, or a specific language like `json`, `bash`,
`markdown` where applicable) so the markdown linter passes; search for all
occurrences of ``` (including the ones noted around 131, 194, 245, 289, 418,
455) and replace them with ```text or the appropriate language identifier.

In `@docs/dashpay/research/02-rust-dashcore-keywallet.md`:
- Line 232: The markdown contains fenced code blocks without language tags;
update the offending triple-backtick fences to include the appropriate language
identifier (e.g., ```rust, ```bash, or ```text) for the code snippets so
markdownlint passes and syntax highlighting works—locate the plain ``` fences in
the document (the blocks referenced in the review) and replace them with
language-tagged fences.

In `@docs/dashpay/research/05-swift-app.md`:
- Line 47: The fenced code block currently uses a bare triple-backtick fence
(```); add a language tag (e.g., ```swift or ```text) immediately after the
opening backticks to satisfy markdownlint and enable proper syntax highlighting
for that block.

In `@docs/dashpay/research/06-interop-desk-check.md`:
- Line 366: The fenced code block uses plain ``` without a language tag; update
the opening fence to include an appropriate language identifier (for example
`http`, `text`, or `bash`) so markdownlint is satisfied and readability
improves—locate the triple-backtick fenced block in the document and add the
language tag immediately after the opening ``` fence.
- Line 24: The table row contains an extra leading column ("2") so it has four
columns while the table header defines three; remove the extra column in the row
that contains "2" (the row with "ECDH shared-key derivation" and the
libsecp256k1 SHA256 expression) so the row matches the 3-column header layout,
keeping the description "ECDH shared-key derivation" and the verdict "**PASS** —
all three stacks compute libsecp256k1-style `SHA256((y[31]&0x1|0x2) ‖ x)`" as
the remaining columns.

In `@docs/dashpay/SPEC.md`:
- Line 111: Several fenced code blocks in SPEC.md are missing language
identifiers; update each triple-backtick fence (``` ) at the noted examples so
they include an appropriate language tag (e.g., change ``` to ```text, ```rust,
or ```swift as appropriate) to satisfy markdownlint and enable correct syntax
highlighting; search for the bare ``` occurrences (including the ones referenced
near the examples) and replace them with language-tagged fences, ensuring
opening and closing fences remain paired.

In `@packages/rs-platform-wallet/src/manager/dashpay_sync.rs`:
- Around line 221-223: The background loop cleanup currently unconditionally
sets this.background_cancel to None (in the block near start()), which can
overwrite a newer token if stop() and start() race; change the logic so the
background thread only clears background_cancel if the stored cancel token it
captured at spawn time still matches the current token in this.background_cancel
(i.e., capture the Arc/ID of the cancel handle when spawning and
compare-before-clearing); apply the same compare-and-clear pattern in the stop()
/ thread-exit cleanup (references: this.background_cancel, start(), stop()) so a
late-exiting old loop cannot null out a replacement token.

In `@packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs`:
- Around line 103-118: The sender/recipient key selection currently using
sender_identity.public_keys().iter().find(...) (checking Purpose::ENCRYPTION and
KeyType::ECDSA_SECP256K1) can pick a disabled/rotated key; update the logic to
only consider active/enabled keys (e.g., filter by .enabled() or reuse the
existing enabled-key selection utility used for signing) so
sender_encryption_key and recipient_key_index (the call to
select_recipient_key_index should be updated similarly or replaced) always
reference the current active ENCRYPTION/DECRYPTION ECDSA_SECP256K1 key; ensure
you still call .map(...).ok_or_else(...) and preserve error type
PlatformWalletError::InvalidIdentityData when no active key is found.
- Around line 516-556: collect_account_build_candidates currently skips contacts
when info.core_wallet.accounts.dashpay_external_accounts.contains_key(&key) is
true, which prevents retries if register_contact_account previously failed after
inserting an external entry; remove that gating so contacts with an
incoming_request (incoming.encrypted_public_key and key indices) are always
returned as AccountBuildCandidate (unless payment_channel_broken) to allow
build_contact_accounts -> register_contact_account to retry; specifically, in
collect_account_build_candidates remove or change the has_external
check/continue and rely on contact.incoming_request and payment_channel_broken
to decide inclusion (keep AccountBuildCandidate fields: contact_id,
encrypted_public_key, our_decryption_key_index, contact_encryption_key_index).
- Around line 452-509: parse_contact_request_doc currently only extracts
required fields and drops optional fields encryptedAccountLabel and
autoAcceptProof, causing restores to lose these values; update
parse_contact_request_doc (and thus parse_sent_contact_request_doc which calls
it) to also read props.get("encryptedAccountLabel").and_then(|v: &Value|
v.as_str()).map(|s| s.to_owned()) and props.get("autoAcceptProof").and_then(|v:
&Value| v.as_bytes()).cloned() (or appropriate conversions) and pass them into
ContactRequest::new (or the appropriate constructor/factory) so the
ContactRequest created preserves encryptedAccountLabel and autoAcceptProof
during ingest/reconcile. Ensure the match arm pattern includes these Option
values and the fallback logging remains unchanged.

In
`@packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/contact_requests.rs`:
- Around line 116-130: The code removes an incoming request from
self.incoming_contact_requests but the returned ContactChangeSet only records
cs.rejected, so on replay the incoming entry isn't removed; update the change
set returned by the function to also include the incoming-removal for (owner_id,
*sender_id, account_reference) (i.e., add the corresponding removal entry to the
ContactChangeSet alongside cs.rejected) so that replay will delete the
incoming_contact_requests entry when applying the rejection tombstone.

---

Outside diff comments:
In `@packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs`:
- Around line 806-875: The local-only already_reciprocated check (variable
already_reciprocated) can be stale; change the flow so before attempting
send_contact_request_with_external_signer you either (A) perform a platform
check for an existing reciprocal contact request/relationship (use whatever
network client/query you have for checking platform contact requests for
(ownerId,toUserId,accountReference)) and set already_reciprocated accordingly,
or (B) keep the existing local check but add a duplicate-send fallback: catch
the unique-index conflict/error returned by
send_contact_request_with_external_signer and, on that specific error, log that
the reciprocal exists on Platform and run the adopt path (call
register_contact_account(&our_identity_id, &sender_id, 0) and treat as success).
Reference already_reciprocated, send_contact_request_with_external_signer, and
register_contact_account when implementing either fix.
🪄 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: 596c3a94-3c49-4cc0-869e-b392a37c181e

📥 Commits

Reviewing files that changed from the base of the PR and between ba94110 and 9f770b8.

📒 Files selected for processing (38)
  • docs/dashpay/SPEC.md
  • docs/dashpay/research/01-dip-spec.md
  • docs/dashpay/research/02-rust-dashcore-keywallet.md
  • docs/dashpay/research/03-rs-platform-wallet.md
  • docs/dashpay/research/04-sdk-and-contract.md
  • docs/dashpay/research/05-swift-app.md
  • docs/dashpay/research/06-interop-desk-check.md
  • packages/rs-platform-encryption/Cargo.toml
  • packages/rs-platform-encryption/src/lib.rs
  • packages/rs-platform-wallet-ffi/src/established_contact.rs
  • packages/rs-platform-wallet-storage/migrations/V001__initial.rs
  • packages/rs-platform-wallet-storage/src/sqlite/schema/contacts.rs
  • packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs
  • packages/rs-platform-wallet-storage/tests/sqlite_load_reconstruction.rs
  • packages/rs-platform-wallet/src/changeset/changeset.rs
  • packages/rs-platform-wallet/src/changeset/mod.rs
  • packages/rs-platform-wallet/src/lib.rs
  • packages/rs-platform-wallet/src/manager/accessors.rs
  • packages/rs-platform-wallet/src/manager/dashpay_sync.rs
  • packages/rs-platform-wallet/src/manager/mod.rs
  • packages/rs-platform-wallet/src/wallet/apply.rs
  • packages/rs-platform-wallet/src/wallet/identity/crypto/dip14.rs
  • packages/rs-platform-wallet/src/wallet/identity/crypto/validation.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/account_labels.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/contacts.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/dashpay_sync.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/mod.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/profile.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/sdk_writer.rs
  • packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/contact_requests.rs
  • packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs
  • packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/mod.rs
  • packages/rs-platform-wallet/src/wallet/identity/types/dashpay/established_contact.rs
  • packages/rs-platform-wallet/src/wallet/platform_wallet.rs
  • packages/rs-sdk-ffi/src/dashpay/contact_request.rs
  • packages/rs-sdk/src/platform/dashpay/contact_request.rs

Comment thread docs/dashpay/research/01-dip-spec.md Outdated
Comment thread docs/dashpay/research/02-rust-dashcore-keywallet.md Outdated
Comment thread docs/dashpay/research/05-swift-app.md Outdated
Comment thread docs/dashpay/research/06-interop-desk-check.md Outdated
Comment thread docs/dashpay/research/06-interop-desk-check.md Outdated
Comment thread packages/rs-platform-wallet/src/manager/dashpay_sync.rs Outdated
@codecov

codecov Bot commented Jun 10, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 52.54%. Comparing base (e2039e5) to head (30d5112).
⚠️ Report is 33 commits behind head on v3.1-dev.

❗ There is a different number of reports uploaded between BASE (e2039e5) and HEAD (30d5112). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (e2039e5) HEAD (30d5112)
rust 2 1
Additional details and impacted files
@@              Coverage Diff              @@
##           v3.1-dev    #3841       +/-   ##
=============================================
- Coverage     71.20%   52.54%   -18.66%     
=============================================
  Files            20       11        -9     
  Lines          2837     1707     -1130     
=============================================
- Hits           2020      897     -1123     
+ Misses          817      810        -7     
Components Coverage Δ
dpp ∅ <ø> (∅)
drive ∅ <ø> (∅)
drive-abci ∅ <ø> (∅)
sdk ∅ <ø> (∅)
dapi-client ∅ <ø> (∅)
platform-version ∅ <ø> (∅)
platform-value ∅ <ø> (∅)
platform-wallet ∅ <ø> (∅)
drive-proof-verifier ∅ <ø> (∅)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@thepastaclaw thepastaclaw 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.

Code Review

M1 of the DashPay completion plan: the SDK entropy / DIP-15 compact xpub / key-purpose interop fixes are correct, but six in-scope correctness issues block merge. The most concerning is editing V001 in-place (violates the documented append-only migration policy and bricks DB rehydration for the v4.0.0-beta.4 cohort). Additional blockers: the reject path emits an incomplete ChangeSet (no removed_incoming); the new rejected_contact_requests table is written but never read; transient identity fetches in register_external_contact_account are misclassified as permanent and brick the channel; validation.purpose_mismatch is set even when a hard error is also present, masking permanent failures as retryable; and the sync sweep skips superseding requests from established contacts, making the documented payment_channel_broken recovery path unreachable.

🔴 6 blocking | 🟡 2 suggestion(s)

2 additional finding(s) omitted (not in diff).

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `packages/rs-platform-wallet-storage/migrations/V001__initial.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/migrations/V001__initial.rs:186-213: V001 migration edited in-place violates append-only policy and breaks upgrade from v4.0.0-beta.4
  This PR adds `contacts.payment_channel_broken` and a new `rejected_contact_requests` table by editing V001 directly. V001 (without these additions) was already shipped in `v4.0.0-beta.4` (commit da9d3fe84e / schema confirmed via `git show`), and `packages/rs-platform-wallet-storage/README.md:106` explicitly states migrations are append-only and applied by refinery on every `open`. refinery checksums each migration in `refinery_schema_history`; against an existing v4.0.0-beta.4 DB it will either abort with a divergent-checksum error or silently skip V001 (already applied) — in which case neither the new table nor the new column is ever created, and the first runtime write in `contacts.rs:240` (`INSERT INTO rejected_contact_requests …`) or `contacts.rs:194-212` (`payment_channel_broken` column) fails at the SQLite layer. `tc029_migration_fingerprint_stable` does not catch this because it only checks self-stability, not a pinned hash. Add `V002__dashpay_reject_and_broken_channel.rs` doing `ALTER TABLE contacts ADD COLUMN payment_channel_broken INTEGER` and `CREATE TABLE rejected_contact_requests (…)`; the loader at `contacts.rs::load_state` already tolerates NULL `payment_channel_broken`, so a default-less ALTER is compatible.

In `packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/contact_requests.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/contact_requests.rs:109-131: `record_rejected_contact_request` removes incoming in memory but does not emit `removed_incoming`
  The function calls `self.incoming_contact_requests.remove(sender_id)` and returns a `ContactChangeSet` populated only with `cs.rejected`. The unified-`contacts`-table writer at `rs-platform-wallet-storage/src/sqlite/schema/contacts.rs:182-193` only `DELETE`s when `cs.removed_incoming` is non-empty, so the previously persisted state='received' row (with the `incoming_request` blob) stays in SQLite. Once `persister.load()` (TODO at `sqlite/persister.rs:909`) is wired up, the unified contacts reader rebuckets that row as an incoming request, `apply_changeset` re-inserts it into `incoming_contact_requests`, and the FFI surfaces the explicitly-rejected request back to the UI. The persisted delta is also internally inconsistent with the in-memory mutation — a delta-persistence invariant violation. The in-memory `rejected_tombstone_round_trips_and_respects_account_reference` test does not catch this because it round-trips via `apply_changeset`, not the SQLite reader. Fix by also inserting a matching `ReceivedContactRequestKey { owner_id, sender_id: *sender_id }` into `cs.removed_incoming`.

In `packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs:206-222: `rejected_contact_requests` is written but never read — tombstones lost across restart
  The PR adds a writer (`contacts.rs:240`), a migration row (`V001__initial.rs:203`), and an `apply_changeset` branch that restores `ManagedIdentity.rejected_contact_requests` from `cs.rejected`. But `managed_identity_from_entry` hard-codes `rejected_contact_requests: Default::default()` (line 214), and grep confirms no `load_state` reader for the new table. Once `persister.load()` (TODO at `sqlite/persister.rs:909`) is wired up, the in-memory tombstone map is always empty after restart even though SQLite holds the rows. `is_request_rejected` then returns `false`, the sweep's tombstone-skip in `network/contact_requests.rs:396-404` does not fire, and the recurring DashPay loop (G12) resurrects every rejected request on the first sweep — exactly the M1 failure mode the SPEC.md cites as the reason G5 must land with G12. Add a per-wallet `load_state` for `rejected_contact_requests` and route its output into the `ContactChangeSet.rejected` synthesized during rehydration.

In `packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs:711-728: Transient identity fetch failures inside account-build are marked as permanent
  `build_contact_accounts` treats any error from `register_external_contact_account` as permanent and calls `mark_contact_channel_broken`. But `register_external_contact_account` (`network/contacts.rs:400-407`) performs another `Identity::fetch` for the same contact and wraps the DAPI/network error as `PlatformWalletError::InvalidIdentityData`. A transient DAPI hiccup after validation therefore permanently disables the payment channel; subsequent sweeps skip the contact via the `payment_channel_broken` filter at line 530, and recovery only fires if a superseding contactRequest happens to arrive — contradicting the policy in the docstring at lines 573-578 ("Transient (identity fetch / network): logged, left for the next sweep to retry. The broken flag stays clear."). The fix is to perform the contact-identity fetch and treat its failure as transient *before* calling `register_external_contact_account` (mirroring the existing fetch at lines 631-655) and to scope the permanent-broken classification to genuinely non-recoverable failures (decrypt/decode, missing-key, key-type mismatch).
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs:383-392: Superseding requests from established contacts are skipped — `payment_channel_broken` recovery is unreachable
  The received-side ingest drops every doc whose sender is already in `established_contacts` before consulting `accountReference`. `EstablishedContact::reestablish_preserving_metadata` exists precisely to clear `payment_channel_broken = false` when a fresh request flows in (see `types/dashpay/established_contact.rs:84-104`), and `collect_account_build_candidates` documents the recovery contract at lines 528-529 ("never retry a permanently-broken channel — wait for a superseding request (which clears the flag on re-establish)"). But there is no path that reaches `reestablish_preserving_metadata` for an already-established sender from the sync sweep — `add_incoming_contact_request` is only called for new senders here, and the send-side guard at `state/managed_identity/contact_requests.rs:46-48` similarly returns early for established contacts. Net effect: once `payment_channel_broken` is set, it stays set forever. Either (a) detect a superseding incoming request (new `accountReference` for the same sender) and route it through the reestablish path, or (b) change the broken-channel policy so the next sweep can retry under controlled conditions.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs:5733-5749: `select_recipient_key_index` returns disabled keys
  The send-side recipient-key selector iterates `recipient_identity.public_keys()` and returns the first key whose purpose is DECRYPTION (then ENCRYPTION) and whose type is ECDSA_SECP256K1, with no `disabled_at` check. `validate_contact_request` in `crypto/validation.rs` does gate on disabled keys, so if a preferred DECRYPTION key has been rotated/disabled this selector returns it anyway and the broadcast fails downstream with an opaque error instead of falling through to a usable ENCRYPTION key on the same identity. Add `&& k.disabled_at().is_none()` to both branches so selection is consistent with validation.

In `packages/rs-platform-wallet/src/wallet/identity/crypto/validation.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/crypto/validation.rs:50-62: `purpose_mismatch` is set even when a non-purpose hard error is also present
  The docstring at lines 19-29 contracts `purpose_mismatch` as `true` *only* when the sole reason for invalidity is a key-purpose mismatch — it is what tells `build_contact_accounts` at `network/contact_requests.rs:689` to treat the failure as a non-permanent skip instead of marking the channel permanently broken. The implementation does not preserve that invariant: `add_purpose_error` unconditionally sets `purpose_mismatch = true`, and `add_error` never clears it. A request whose key has both a wrong key type (hard, permanent error) and a wrong purpose ends up with `is_valid = false, purpose_mismatch = true`, and the caller skips + retries forever instead of marking broken. The mobile testnet census makes this rare in practice today, but the classifier is the load-bearing primitive the recovery policy is built on — fix `add_error` to clear the flag, and fix `add_purpose_error` to only set it if no prior hard error was recorded.

In `packages/rs-platform-wallet/src/manager/dashpay_sync.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/manager/dashpay_sync.rs:192-227: `stop()` followed quickly by `start()` can let the old thread null out the new cancel token
  `stop()` takes the current `background_cancel`, sets it to `None`, then cancels the old token. The spawned thread exits its loop on cancellation and at lines 221-223 re-acquires the guard and writes `*guard = None`. If `start()` runs between `stop()` and the old thread's cleanup block, the old thread's final clear will overwrite the new token just installed by `start()` — leaving `background_cancel` empty while a fresh sync thread is still running, so a subsequent `stop()`/`quiesce()` will be a no-op against that running thread. The normal shutdown path (`quiesce` waits for in-flight passes) does not hit this, but bare `stop()`/`start()` races can. Fix by capturing the token at spawn time and only clearing the guard if it still holds that same token (`if matches!(*guard, Some(t) if Arc::ptr_eq(...)) { *guard = None; }`).

Comment thread packages/rs-platform-wallet-storage/migrations/V001__initial.rs
Comment thread packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs Outdated
Comment thread packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs Outdated
Comment thread packages/rs-platform-wallet/src/manager/dashpay_sync.rs
shumkov added 6 commits June 12, 2026 21:31
…hout order-by

Two devnet-UAT fixes on the rs-sdk side:

- contact_request_queries: add explicit `ORDER BY $createdAt` to both
  fetch_received/fetch_sent queries. Drive answers a bare
  secondary-index equality (toUserId / $ownerId) with a verified
  proof of ABSENCE even when matching documents exist — isolated
  live against devnet with a host-side probe (equality-only: 0 docs;
  with order-by: found). The order-by binds the query to the
  (field, $createdAt) index so results return. Worth a platform
  issue: drive should reject the under-specified query instead of
  proving absence.

- rs-sdk-ffi: 8MB tokio worker stacks. GroveDB document-query proof
  verification (verify_layer_proof_v1) recurses deep enough to
  overflow the platform-default stack (SIGBUS on the stack guard,
  observed on-device).

No test: requires a live drive node answering proofs; pinned by the
on-device UAT flow (docs/dashpay/SPEC.md Part 7 e2e plan covers it
once PR #3549 lands).
…lock

Devnet UAT (2026-06-12) showed the receiver's payment history was
always empty ("Payments (0)") and friendship-account UTXOs were
silently dropped on every relaunch. Three root causes, all fixed:

1. Incoming payments were never recorded: the old
   try_record_incoming_payment had ZERO callers. Replaced with
   record_incoming_dashpay_payments wired into the wallet-event
   adapter (core_bridge) — every TransactionDetected output paying a
   DashpayReceivingFunds address now records a Received PaymentEntry
   on the owning managed identity, idempotent per txid.

2. No recovery for missed/restored payments: new
   reconcile_incoming_payments() derives missing Received entries
   from the receival accounts' UTXO sets; runs as a local-only third
   step of dashpay_sync() each sweep. Never clobbers an existing
   txid entry (e.g. the sender's own Sent record when both
   identities share a wallet).

3. DashPay account registrations were in-memory only:
   register_contact_account / register_external_contact_account now
   persist an AccountRegistrationEntry + initial pool snapshot (same
   round shape as wallet creation), emitted BEFORE the in-memory
   inserts. Without this the accounts vanished on relaunch and the
   UTXO restore dropped their rows (load: dropped_no_account=2
   observed live). register_contact_account also gains the missing
   early-exit and now mirrors the restored shape into the immutable
   wallet.accounts collection.

Tests (red->green demonstrated against the unfixed code):
- register_contact_account_persists_account_registration: FAILED
  before (no store round), passes after.
- reconcile_records_received_payments_from_receival_utxos: FAILED
  before (stub recorded 0), passes after; also pins idempotency.
- reconcile_does_not_clobber_existing_entry_for_same_txid.
204/204 platform-wallet lib tests green.

Also: attach_wallet_seed manager API + FFI
(platform_wallet_manager_attach_wallet_seed_from_mnemonic) — wallets
rehydrate external-signable after relaunch with the mnemonic still
in the host keychain; this upgrades them in place (idempotent,
SeedMismatch-guarded, BIP44-0 xpub-equality fallback for
pre-network-scoped wallet ids). dashpay-sync loop thread gets an
8MB stack (GroveDB proof recursion SIGBUS, observed on-device).
…payment history

SPEC Part 6 ("nice UI") + M2 tasks 7-11, verified end-to-end on a
devnet: profile create, add contact by id, request/accept,
established contacts, send 0.01 DASH with txid in sender history,
received payments on the recipient's side across relaunches.

FFI (rs-platform-wallet-ffi):
- dashpay_sync.rs: 7 platform_wallet_manager_dashpay_sync_* symbols
  (start/stop/sync_now/is_syncing/is_running/interval get+set);
  sync_now runs via block_on_worker (8MB worker — GroveDB proof
  recursion overflows the caller thread's stack).
- dashpay_payment.rs: managed_identity_get_dashpay_payments getter.
- Persister callback arity 8→10: payment_channel_broken +
  contact-request rejection tombstones now cross the boundary.

Swift SDK:
- PersistentDashpayPayment model + persistence bridge;
  PersistentDashpayContactRequest gains rejection fields;
  PersistentIdentity payment relationship.
- PlatformWalletManagerDashPaySync: start/stop/refresh +
  @published dashPaySyncIsSyncing (1 Hz poll, sibling convention).
- Keychain unlock hook in loadFromPersistor: re-attaches the wallet
  seed via attach_wallet_seed so rehydrated wallets can sign.

SwiftExampleApp:
- New DashPay root tab (Views/DashPay/, 7 views): identity picker
  with @AppStorage persistence, profile header + editor, contacts +
  requests segments (incoming accept/reject, outgoing pending),
  add-contact (DPNS search + identity-id modes), contact detail
  (payments history, local alias/note/hide), send sheet. All §6.4
  interaction states; dashpay.* accessibility ids throughout.
- Contacts consolidated into the DashPay tab: legacy FriendsView
  (917 lines) deleted; IdentityDetailView's DashPay section now
  deep-links to the tab with the identity pre-selected (root tab
  selection moved to AppUIState). SendDashPayPaymentSheet +
  DashPayContact moved to Views/DashPay/.
- AddContactView guards partial base58 input (<32-byte decode
  crashed the FFI identifier precondition).

Tests: DashPayPersistenceTests (15 — persister bridge, tombstone
rotation-survival, payments), DashPayTabUITests (smoke).
Marks M2 + the receiver-side payment path as live-verified
(2026-06-12, devnet): account registrations now persisted, incoming
payments recorded live + reconciled after restore. Notes the drive
query-absence behaviour (equality without order-by proves absence)
referenced from the rs-sdk fix.
…detail

Contacts live in the DashPay tab now — the redirect row added during
the consolidation was an extra menu item with no unique function.
The identity screen keeps only identity-owned concerns (keys, DPNS,
balance, profile).
Three placement fixes from UI review:

- Sync page gains a "DashPay Sync Status" section (spinner while a
  pass is in flight, relative last-sync stamp from the FFI,
  Recurring/Stopped state, Sync Now) — the recurring DashPay loop
  was previously invisible there.
- DashPay tab shows "Received from contacts" under the profile
  header: the active identity's DashpayReceivingFunds balances,
  read from the same lock-free account-balance call the wallet
  list uses.
- Wallets account list hides the DashPay friendship accounts
  (tags 12/13): per-contact protocol plumbing that would bloat the
  list as contacts grow, and external accounts watch the contact's
  addresses (not our funds). Totals are unaffected — receiving
  funds already roll into Core Balance (verified live:
  9.39698657 = BIP44 9.37698657 + 0.02 received); the Storage
  Explorer still lists the raw rows.

Verified on-sim: sync section shows "Last sync: 5 secs /
Recurring"; DashPay tab shows 0.02000000 DASH received; no DashPay
rows remain in the Wallets account list.

@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 (1)
packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift (1)

421-465: ⚡ Quick win

Also assert the payment rows roll back in this atomicity test.

The doc comment says a mid-round persistDashpayPayments write must ride the open changeset and roll back with it, but the test only checks PersistentDashpayContactRequest. If payment persistence starts auto-saving again, this still passes. Add a PersistentDashpayPayment fetch before and after endChangeset(..., success: false) so the regression is pinned end-to-end.

🤖 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
`@packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift`
around lines 421 - 465, In testPaymentRefreshDoesNotCommitAnOpenChangesetRound,
add assertions that verify the payment row staged by persistDashpayPayments is
not visible mid-round and is rolled back after endChangeset(..., success:
false); specifically, call the existing payment-fetch helper (or add/rename a
fetch function for PersistentDashpayPayment rows) to assert count == 0
immediately after the mid-round persist and again after
handler.endChangeset(..., success: false), mirroring the contact-row assertions
so the test verifies payment atomicity as well as contact atomicity.
🤖 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
`@packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- Around line 1919-1925: persistDashpayPayments is swallowing failures from
backgroundContext.save() via try?, which can silently drop payment-history
updates; change the save to propagate or log errors instead of ignoring them:
replace the try? backgroundContext.save() with a throwing or do/catch path
inside persistDashpayPayments that captures the thrown error from
backgroundContext.save(), records telemetry/logging (or rethrows to the caller)
with context (e.g., include which payment batch or wallet ID), and preserve the
existing inChangeset check (if !self.inChangeset) so the save still only runs
when appropriate; update callers or function signature as needed to handle
propagated errors or ensure telemetry is emitted in the catch.

In
`@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift`:
- Around line 35-40: The optimisticSentIds and ownProfile state are
identity-scoped but currently persist across identity switches; update the
activeIdentity handling (the Task that observes activeIdentity) to reset
identity-scoped UI state at the start of the task: clear optimisticSentIds and
set ownProfile to nil (or otherwise remove cached profile) before loading;
alternatively refactor optimisticSentIds and ownProfile to be keyed by owner
identity (e.g., a dictionary keyed by activeIdentity.id) and read/write via that
key, and ensure loadOwnProfileFromCache() does not retain the previous profile
on read failure for the new identity but returns nil so the UI doesn’t show the
old identity’s data.

In
`@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/IdentityDetailView.swift`:
- Around line 1235-1243: The avatar downloader currently accepts any parseable
URL, allowing non-HTTPS schemes; update fetchAvatarBytes to explicitly validate
the URL scheme and reject anything not exactly "https" before creating the
URLRequest, returning an error (or nil) for non-https inputs; locate
fetchAvatarBytes (and the analogous implementation referenced around lines
1390-1410) and add a guard that checks url.scheme?.lowercased() == "https" and
fails early with a clear error to prevent http or other schemes from being
fetched.

In
`@packages/swift-sdk/SwiftExampleApp/SwiftExampleAppUITests/DashPayTabUITests.swift`:
- Around line 92-97: Replace the immediate existence check on the toolbar
refresh button with a timed wait to avoid flakes: locate the `refresh` query
using `Identifier.refreshButton` in DashPayTabUITests (variable `refresh`) and
change the assertion to call `refresh.waitForExistence(timeout: ...)` instead of
checking `refresh.exists`, keeping the same failure message; choose a reasonable
timeout (e.g., 1–5s) consistent with other tests.

---

Nitpick comments:
In
`@packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift`:
- Around line 421-465: In testPaymentRefreshDoesNotCommitAnOpenChangesetRound,
add assertions that verify the payment row staged by persistDashpayPayments is
not visible mid-round and is rolled back after endChangeset(..., success:
false); specifically, call the existing payment-fetch helper (or add/rename a
fetch function for PersistentDashpayPayment rows) to assert count == 0
immediately after the mid-round persist and again after
handler.endChangeset(..., success: false), mirroring the contact-row assertions
so the test verifies payment atomicity as well as contact atomicity.
🪄 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: 9c0b4a7c-c449-41c7-bd16-7979ff30c777

📥 Commits

Reviewing files that changed from the base of the PR and between 9f770b8 and a51606d.

📒 Files selected for processing (42)
  • docs/dashpay/SPEC.md
  • packages/rs-platform-wallet-ffi/src/contact_persistence.rs
  • packages/rs-platform-wallet-ffi/src/dashpay_payment.rs
  • packages/rs-platform-wallet-ffi/src/dashpay_sync.rs
  • packages/rs-platform-wallet-ffi/src/lib.rs
  • packages/rs-platform-wallet-ffi/src/manager.rs
  • packages/rs-platform-wallet-ffi/src/persistence.rs
  • packages/rs-platform-wallet/src/changeset/core_bridge.rs
  • packages/rs-platform-wallet/src/error.rs
  • packages/rs-platform-wallet/src/manager/attach_seed.rs
  • packages/rs-platform-wallet/src/manager/dashpay_sync.rs
  • packages/rs-platform-wallet/src/manager/mod.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/contacts.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/dashpay_sync.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/mod.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/payments.rs
  • packages/rs-sdk-ffi/src/sdk.rs
  • packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs
  • packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayContactRequest.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayPayment.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DashPayPayment.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedIdentity.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerDashPaySync.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/ContentView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SwiftExampleAppApp.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/AddContactView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactDetailView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactsView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayContactMeta.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/SendDashPayPaymentSheet.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/FriendsView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/IdentityDetailView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleAppUITests/DashPayTabUITests.swift
  • packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift
💤 Files with no reviewable changes (1)
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/FriendsView.swift
✅ Files skipped from review due to trivial changes (3)
  • packages/rs-platform-wallet-ffi/src/lib.rs
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/AddContactView.swift
  • docs/dashpay/SPEC.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/rs-platform-wallet/src/wallet/identity/network/mod.rs
  • packages/rs-platform-wallet/src/manager/mod.rs

@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)
packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift (1)

23-26: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Scope the persisted active-identity key by network.

dashpay.activeIdentityId is shared across every network, so selecting an identity on testnet/devnet overwrites the remembered choice for mainnet too. When the user switches back, activeIdentity falls back to the first eligible identity instead of restoring the last selection on that network.

🤖 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
`@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift`
around lines 23 - 26, The persisted AppStorage key stored in DashPayTabView
(`@AppStorage("dashpay.activeIdentityId") private var storedIdentityId`) is
global across networks; change it to be network-scoped by deriving the key from
the current network identifier (e.g., include network.rawValue or chainId) so
each network has its own stored key. Update DashPayTabView to compute the
AppStorage key at runtime (or use a computed property / wrapper that returns
"dashpay.activeIdentityId.\(networkId)") using the view’s network/environment
value and ensure storedIdentityId is read/written through that network-scoped
key so switching networks preserves separate selections.
♻️ Duplicate comments (1)
packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift (1)

169-177: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reset identity-scoped state before loading the next identity.

optimisticSentIds and ownProfile still survive an identity switch, and loadOwnProfileFromCache() explicitly keeps the previous profile on a read failure. That can render identity A's pending-request overlay or profile header under identity B until the cache catches up. Clear those fields at the start of the .task(id:) block, and don't retain the previous ownProfile in the failure path for the new identity.

Also applies to: 420-433

🤖 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
`@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift`
around lines 169 - 177, The task block keyed by .task(id:
activeIdentity?.identityId) is not resetting identity-scoped state: clear
optimisticSentIds and ownProfile immediately at the top of that task before
calling loadOwnProfileFromCache() and walletManager.dashPaySyncNow(); and update
loadOwnProfileFromCache() so that on a cache read failure for the new identity
it does not retain the previous ownProfile (set ownProfile to nil or replace
with an empty/default value) instead of keeping the old profile. Ensure the
reset refers to the existing properties optimisticSentIds and ownProfile and the
loadOwnProfileFromCache() function so the UI doesn't show the previous identity
while the new identity's cache is loaded.
🤖 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
`@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/AccountListView.swift`:
- Around line 35-42: The visible-empty-state logic is still checking the raw
accounts collection instead of the filtered/sorted list, causing the UI to hide
the "No Accounts" state when only accountType 12/13 are present; update the
empty-state checks to use orderedAccounts.isEmpty (or introduce a
visibleAccounts computed collection that filters out accountType 12/13 and reuse
it everywhere) and replace any usages of accounts.isEmpty / !accounts.isEmpty in
AccountListView with checks against that filtered collection so the UI matches
the displayed list (keep AccountListView.sortKey as the sorting helper).

---

Outside diff comments:
In
`@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift`:
- Around line 23-26: The persisted AppStorage key stored in DashPayTabView
(`@AppStorage("dashpay.activeIdentityId") private var storedIdentityId`) is
global across networks; change it to be network-scoped by deriving the key from
the current network identifier (e.g., include network.rawValue or chainId) so
each network has its own stored key. Update DashPayTabView to compute the
AppStorage key at runtime (or use a computed property / wrapper that returns
"dashpay.activeIdentityId.\(networkId)") using the view’s network/environment
value and ensure storedIdentityId is read/written through that network-scoped
key so switching networks preserves separate selections.

---

Duplicate comments:
In
`@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift`:
- Around line 169-177: The task block keyed by .task(id:
activeIdentity?.identityId) is not resetting identity-scoped state: clear
optimisticSentIds and ownProfile immediately at the top of that task before
calling loadOwnProfileFromCache() and walletManager.dashPaySyncNow(); and update
loadOwnProfileFromCache() so that on a cache read failure for the new identity
it does not retain the previous ownProfile (set ownProfile to nil or replace
with an empty/default value) instead of keeping the old profile. Ensure the
reset refers to the existing properties optimisticSentIds and ownProfile and the
loadOwnProfileFromCache() function so the UI doesn't show the previous identity
while the new identity's cache is loaded.
🪄 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: 5cf1916b-35bc-47ca-bb9d-48b3d9493945

📥 Commits

Reviewing files that changed from the base of the PR and between a51606d and a24bb43.

📒 Files selected for processing (4)
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/AccountListView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/CoreContentView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/IdentityDetailView.swift
💤 Files with no reviewable changes (1)
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/IdentityDetailView.swift

@thepastaclaw thepastaclaw 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.

Code Review

All 8 prior findings against 9f770b8 remain STILL VALID at a51606d — verified directly against the worktree (V001 unchanged, record_rejected_contact_request still omits removed_incoming, no reader for rejected_contact_requests, transient identity fetch still permanently breaks channels, purpose_mismatch still sticky, established-contact ingest still skips superseding requests, dashpay_sync cleanup still clobbers cancel token unconditionally, select_recipient_key_index still ignores disabled_at). The M2 delta also introduced one new blocker: Swift wallet deletion does not pre-delete the newly added PersistentDashpayPayment children whose owner inverse is non-optional, mirroring the contact-request pattern that the surrounding comment explicitly calls out as fatal. One FFI suggestion is worth flagging: the new DashpayPaymentFFI derives Copy despite owning two *mut c_char allocations reclaimed by dashpay_payment_array_free. Overflow: 1 valid suggestion dropped (register_external_contact_account persist outside write lock — conf 0.55).

🔴 2 blocking | 🟡 2 suggestion(s)

2 additional finding(s) omitted (not in diff).

6 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs:206-222: rejected_contact_requests is written but never read — tombstones lost across restart
  Verified at HEAD: managed_identity_from_entry still hard-codes rejected_contact_requests: Default::default() at line 214. The writer at contacts.rs:240 (INSERT INTO rejected_contact_requests) and migration row at V001:203 exist, but there is no load_state reader for the new table and apply_changeset only handles live deltas — restored state is always empty. The recurring DashPay loop's tombstone-skip at network/contact_requests.rs:396-404 never fires after a restart, so a rejected contact request is resurrected on the first sweep. Add a per-wallet load_state for rejected_contact_requests and route its output into the ContactChangeSet.rejected synthesized during rehydration.

In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:2980-2996: Wallet deletion omits new DashPay payment children before deleting identities — same fatal pattern as contact requests
  Verified: PersistentDashpayPayment.owner is declared as non-optional (`public var owner: PersistentIdentity`), and the new cascade relationship was added on PersistentIdentity.dashpayPayments in the M2 delta. The PHASE 1 pre-delete loop at lines 2986-2996 iterates dpnsNames, dashpayProfile, and contactRequests — but not dashpayPayments. The surrounding comment (lines 2962-2978) explicitly states this phase exists because SwiftData fatals during save() when it must null out a non-optional inverse on a child processed in the same delete batch. dashpayPayments has the exact same shape as contactRequests, so a wallet with persisted DashPay payments can crash or fail to wipe cleanly when deleted. Add a `for payment in Array(identity.dashpayPayments) { backgroundContext.delete(payment) }` loop alongside the existing pre-deletion.

In `packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs:245-261: select_recipient_key_index returns disabled keys
  Verified at HEAD lines 245-261: the selector iterates recipient_identity.public_keys() and returns the first DECRYPTION (then ENCRYPTION) ECDSA_SECP256K1 key with no disabled_at check. validate_contact_request in crypto/validation.rs does gate on disabled keys, so a recipient with a disabled preferred DECRYPTION key gets returned anyway and the broadcast fails downstream with an opaque error instead of falling through to a usable ENCRYPTION key on the same identity. Beyond reliability, on the send-side this also means the wallet could encrypt the DIP-15 compact xpub to a revoked key whose private half may be compromised. Add `&& k.disabled_at().is_none()` to both branches so selection matches validation.

In `packages/rs-platform-wallet-ffi/src/dashpay_payment.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/dashpay_payment.rs:89-108: DashpayPaymentFFI derives Clone, Copy despite owning *mut c_char strings reclaimed by dashpay_payment_array_free
  Verified at HEAD lines 89-108: DashpayPaymentFFI carries two heap-owned C strings (txid, memo — produced via CString::into_raw in cstring_or_null and reclaimed via CString::from_raw in dashpay_payment_array_free), yet the struct is `#[derive(Debug, Clone, Copy)]`. With Copy the compiler will silently shallow-duplicate the struct on any by-value rebinding inside this crate, and a subsequent free walk on the array (or a stray from_raw on the duplicate) would double-free the txid/memo allocations across the FFI boundary. Today's call sites are sound — the struct is built once, moved into Vec → Box<[T]> → Box::into_raw, and reclaimed exactly once — but the Copy derive removes the borrow-checker guardrail that normally prevents this class of bug at refactor time. Sibling FFI types in this crate that own heap pointers (ContactRequestFFI, WalletChangeSetFFI) deliberately omit Copy for exactly this reason. Drop Copy (and Clone if unneeded) on this struct. The cross-boundary contract is unchanged — Swift consumes by raw pointer.

Comment thread packages/rs-platform-wallet-ffi/src/dashpay_payment.rs
Conflict: identity_handle.rs — both sides appended a test module
(ours: ecdh_key_derivation_tests; upstream: master-derive tests from
the rescan fix). Kept both; 221/221 platform-wallet lib tests green
on the merged tree.

Also folds in a build fix the merged tree needs: upstream
CreateIdentityView's funding-source footer (string concatenation
with an embedded ternary) exceeds the Swift type-checker budget on
Xcode here — hoisted into a static helper, no copy change.
@shumkov shumkov changed the title fix(platform-wallet)!: DashPay sync correctness, consensus entropy fix, and DIP-15 mobile interop (M1) fix(platform-wallet)!: dashpay sync correctness, mobile interop, payments + DashPay tab (M1+M2) Jun 12, 2026
shumkov added 3 commits June 12, 2026 22:07
The explorer-coverage CI guard caught the M2 model addition: every
SwiftData model needs an explorer row + list view + detail view.
Adds the "DashPay Payments" section (network-scoped count, newest
first, full-column read-only detail), mirroring the contact-request
views. check-storage-explorer.sh: 28/28 covered.
…3, M3)

Send side:
- contact requests now carry the DIP-15 masked accountReference
  instead of a hardcoded 0: (version << 28) | (ASK28 ^ account).
  With the contract's unique index (ownerId, toUserId,
  accountReference), the constant 0 meant a superseding request
  after key rotation could never broadcast (duplicate-unique
  rejection) — the version bump is what makes re-keying possible.
- Re-sending to a recipient with a tracked prior request unmasks the
  prior version and bumps it (saturating at the 4-bit max with a
  warning).

Crypto helper fixes (research/06 §3 found both axes wrong):
- HMAC input is now the 69-byte DIP-15 compact xpub (both reference
  clients agree), not the 107-byte DIP-14 encode().
- ASK28 extraction matches iOS dash-shared-core: digest bytes
  [28..32] big-endian >> 4. The reference clients disagree with each
  other here (Android: bytes [0..4] LE) — recipients must disregard
  the field per DIP-15, so the binding consumer is our own
  round-trip; we follow the Rust reference implementation and flag
  the divergence for a DIP clarification.
- New unmask_account_reference recovers (version, account) for the
  sender.

Receive side (DIP-15 "sender rotated their addresses"):
- Sync ingest dedups by (sender, accountReference) instead of bare
  sender id: a known sender with a NEW reference is a rotation
  request and passes the guard (the old guard silently dropped it).
- apply_rotated_incoming_request supersedes the tracked request
  (last-write-wins per pair; simultaneous multi-account rides
  acceptedAccounts later), clears payment_channel_broken — the
  recovery the flag's contract promises — and the sync pass tears
  down the stale external account so the build sweep re-registers
  it from the rotated xpub.

Tests: ASK28 byte-order pin (fails on the old head-of-digest read),
mask/unmask round-trip across version/account ranges, rotation
re-key + broken-flag clear + pending-replace + stranger no-op.
223/223 lib + 9/9 workflow green.
Shared-secret-only callback on the existing host-signer table; the
identity private key never crosses the ABI. EcdhProvider routing
stays internal to platform-wallet so M4's implementation lands
without wallet-API churn. One hook covers both send-side and
decrypt-side ECDH.

@thepastaclaw thepastaclaw 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.

Code Review

Re-verified all 10 prior findings against worktree HEAD aabc21e; every one is STILL VALID — none of the three Swift example-app commits or the v3.1-dev merge touched the dashpay-correctness Rust/Swift hotspots. Carrying forward 7 blockers (append-only V001 violation, rejected-request persistence asymmetry, missing tombstone reader, transient-as-permanent channel breakage, sticky purpose_mismatch, unreachable broken-channel recovery, SwiftData wallet-deletion miss on the new payments cascade) and 3 suggestions (sync stop/start cleanup race, send-side disabled-key selection, Copy on FFI-owned C-strings). REQUEST_CHANGES.

🔴 7 blocking

3 additional finding(s) omitted (not in diff).

3 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/contact_requests.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/contact_requests.rs:109-131: record_rejected_contact_request drops incoming in memory but never persists the deletion
  Verified at HEAD lines 109-131: line 116 calls `self.incoming_contact_requests.remove(sender_id)` but the returned `ContactChangeSet` (lines 127-129) only populates `cs.rejected`. The unified contacts-table writer in `rs-platform-wallet-storage/src/sqlite/schema/contacts.rs` only DELETEs incoming rows when `cs.removed_incoming` is non-empty, so the persisted `state='received'` row with its stale `incoming_request` blob stays in SQLite. Once `persister.load()` is wired up, the contacts reader re-buckets that row as an incoming request and `apply_changeset` re-inserts it — the explicitly-rejected request reappears in the UI. The in-memory mutation and the persisted delta are internally inconsistent. Emit a matching `ReceivedContactRequestKey { owner_id, sender_id: *sender_id }` into `cs.removed_incoming` alongside `cs.rejected`.

In `packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs:206-222: rejected_contact_requests tombstones are written but never restored on rehydration
  Verified at HEAD: `managed_identity_from_entry` still hard-codes `rejected_contact_requests: Default::default()` at line 214. The writer at `contacts.rs:240` (`INSERT INTO rejected_contact_requests`) and the migration row at `V001:203` exist, but no `load_state` reader for the new table exists, and `apply_changeset` only handles live deltas — restored state is always empty. The recurring DashPay loop's tombstone-skip at `network/contact_requests.rs:396-404` therefore never fires after a restart, so a rejected contact request is resurrected on the first sweep and surfaces to the user again. Security framing: the on-platform document is immutable, so the local tombstone is the ONLY thing that suppresses a spammer's repeated contact request — a wipe-on-restart defeats the user's explicit reject. Add a per-wallet `load_state` reader for `rejected_contact_requests` and route its output into the `ContactChangeSet.rejected` synthesized during rehydration.

In `packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs:711-729: Transient DAPI failures inside register_external_contact_account are classified as permanent
  Verified at HEAD lines 711-729: `build_contact_accounts` treats ANY error from `register_external_contact_account` as permanent and calls `mark_contact_channel_broken`. `register_external_contact_account` performs a fresh `Identity::fetch` internally and wraps DAPI/network failures as `PlatformWalletError::InvalidIdentityData`. A single transient DAPI hiccup therefore permanently disables the payment channel; subsequent sweeps skip the contact via the `payment_channel_broken` filter, and recovery only fires if a superseding contactRequest arrives — but the established-contact ingest skip at line 389 makes that path unreachable. Combined, a transient network event bricks a channel forever, and a malicious or unreliable DAPI endpoint becomes a persistent availability attack against payments to a specific contact. Fix by either passing the pre-fetched identity into registration or scoping permanent-broken classification to genuinely non-recoverable failures (decrypt/decode, missing-key, key-type mismatch).
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs:383-404: Established-contact ingest skip makes payment_channel_broken recovery unreachable
  Verified at HEAD lines 383-404: the received-side ingest drops every doc whose sender is already in `established_contacts` (line 389) BEFORE consulting `accountReference`. `EstablishedContact::reestablish_preserving_metadata` exists precisely to clear `payment_channel_broken` when a fresh request flows in, and `collect_account_build_candidates` documents the recovery contract ("never retry a permanently-broken channel — wait for a superseding request which clears the flag on re-establish"). But no path reaches `reestablish_preserving_metadata` for an already-established sender from the sync sweep — `add_incoming_contact_request` is only called for new senders here, and the send-side guard at `state/managed_identity/contact_requests.rs:46-48` also returns early for established contacts. Once `payment_channel_broken` is set, it stays set forever. Either detect a new `accountReference` for the same sender and route through the reestablish path, or change the broken-channel policy to permit controlled retry.
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs:245-261: select_recipient_key_index returns disabled (revoked) keys — DIP-15 compact xpub encrypted to a key whose private half may be compromised
  Verified at HEAD lines 245-261: the selector iterates `recipient_identity.public_keys()` and returns the first DECRYPTION (then ENCRYPTION) ECDSA_SECP256K1 key with no `disabled_at` check. `validate_contact_request` in `crypto/validation.rs` does gate on `disabled_at`, so the asymmetry creates both a reliability bug (an opaque downstream broadcast failure instead of falling through to a usable key) AND a real confidentiality exposure: on send, the wallet encrypts the 69-byte DIP-15 compact xpub (fingerprint‖chaincode‖pubkey — combined with `accountReference` lets the holder derive every receiving address on that account) to a key the recipient has explicitly revoked. Identity-key revocation is the on-platform mechanism for declaring "the private half of this key may be compromised". Add `&& k.disabled_at().is_none()` to both branches so selection matches validation. (Promoted from suggestion to blocking on the security-auditor confidentiality analysis.)

In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:3018-3035: Wallet deletion PHASE 1 omits PersistentDashpayPayment children — same fatal pattern as contactRequests
  Verified at HEAD: PHASE 1 (lines 3024-3034) iterates `dpnsNames`, `dashpayProfile`, and `contactRequests` but NOT `dashpayPayments`. `PersistentDashpayPayment.owner` is non-optional (`PersistentDashpayPayment.swift:98`), and `PersistentIdentity.dashpayPayments` is the cascading inverse added in this PR. The surrounding comment (lines 3018-3023) explicitly states this phase exists because SwiftData fatals during `save()` when it must null out a non-optional inverse on a child processed in the same batch — exactly the shape of the new payments relationship. A wallet with persisted DashPay payment history will hit the SwiftData fatal at PHASE 2 (`save()` after `delete(identity)`), aborting before the wallet row is removed. The user's belief that they wiped DashPay data is wrong, and plaintext memo + counterparty id + amount + txid rows remain on disk. Add a `for payment in Array(identity.dashpayPayments) { backgroundContext.delete(payment) }` loop alongside the existing pre-deletions.

In `packages/rs-platform-wallet/src/manager/dashpay_sync.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/dashpay_sync.rs:192-235: DashPaySyncManager thread cleanup unconditionally clears the cancel token — stop/start race enables use-after-free across FFI
  Verified at HEAD lines 192-235: the spawned thread's cleanup at lines 230-232 writes `*guard = None` on loop exit regardless of which token the slot currently holds. If `stop()` cancels the old token and `start()` installs a fresh token before the old thread reaches cleanup, the old thread clears the NEW token — `background_cancel` is empty while a fresh sync thread is still running. `stop()`/`quiesce()` then become a no-op against that running thread. In this PR's Swift integration the persister and DashPay event callbacks close over an UnsafePointer<Context> allocated on the Swift side; calling `dashpay_sync_manager_destroy` (or the wallet manager's drop) after the visible token was cleared frees that context while the surviving thread continues invoking the callbacks against the freed pointer — a concrete use-after-free crossing the C ABI, reachable through normal start/stop/destroy controls (toggling tabs, login/logout) and widened by attacker-influenced network timing. Capture the spawned token and only clear the slot if it still holds the same token (`Arc::ptr_eq`), mirroring `ShieldedSyncManager`'s generation guard. (Upgraded from suggestion to blocking based on the security-auditor and codex-security cross-checks of the destroy/UAF path.)

Comment thread packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs Outdated
Comment thread packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs Outdated
Comment thread packages/rs-platform-wallet/src/manager/dashpay_sync.rs
shumkov added 2 commits June 12, 2026 22:34
…earch

Decisive: no reference client (DashSync-iOS, dashj, dash-shared-core)
ever implemented contactInfo — our implementation sets the de-facto
convention. Adopts: DIP-15 child derivation (root/65536'+65537'/idx'),
AES-256-ECB encToUserId, IV-prepended AES-256-CBC privateData, CBOR
array [aliasName, note, displayHidden] per the deployed schema (which
contradicts DIP-15 prose — table included), ≥2-contacts publish gate.
… part 1)

The crypto core for DashPay contactInfo documents, following the
conventions recorded in docs/dashpay/research/07 (no reference client
ever implemented this doc type — this sets the de-facto wire format):

- platform-encryption: AES-256-ECB encrypt/decrypt for the 32-byte
  encToUserId (two raw blocks, no IV/padding — DIP-15's own ECB
  soundness argument: the plaintext is a SHA-256 output and the key
  is single-purpose), plus IV-prepended AES-256-CBC helpers for
  privateData. Tests pin the ECB property (identical blocks encrypt
  identically) so a CBC-with-zero-IV regression can't slip in.

- platform-wallet crypto/contact_info.rs: DIP-15 key derivation
  (rootEncryptionKey / 65536' / index' for encToUserId,
  / 65537' / index' for privateData — hardened children of the
  identity's registered ENCRYPTION key path), CBOR codec for the
  deployed schema's array shape [aliasName, note, displayHidden]
  with a 4th ignored padding element lifting tiny payloads to the
  schema's 48-byte ciphertext floor.

Tests: key-derivation determinism + domain separation, CBOR
round-trip incl. all-absent payload, full derive→encrypt→decrypt
round-trip with schema bounds check.

@thepastaclaw thepastaclaw 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.

Code Review

Reconciliation against HEAD 440ffca: prior finding #6 (established-contact ingest skip) is FIXED by the new rotation path. Nine prior findings remain STILL VALID and the new G3 delta introduces two additional blockers — the send-side rotation-version lookup ignores established_contacts (forcing version=0 collisions after auto-establishment) and the receive-side rotation handler replays immutable historical requests as fresh rotations on every sweep, churning the external account. Total: 10 in-scope blockers. Overflow: 1 suggestion (DashpayPaymentFFI Copy) dropped due to budget.

🔴 5 blocking

2 additional finding(s) omitted (not in diff).

5 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs:165-201: Send-side rotation version lookup ignores established_contacts — re-send after auto-establishment reuses version=0 and collides on the unique index
  The new G3 rotation logic computes `previous_version` only from `managed.sent_contact_requests.get(recipient_identity_id)` (line 171). But establishment (`add_incoming_contact_request` line 175 and `apply_established_contact` line 372 in state/managed_identity/contact_requests.rs) explicitly removes the entry from `sent_contact_requests` and parks the prior outgoing request on `EstablishedContact.outgoing_request`. Once the reciprocal arrives and a sweep auto-establishes the pair, the next `send_contact_request` to that recipient sees `previous_version = None` and falls back to `version = 0`. With deterministic xpub/ECDH for the same (sender, recipient) and unchanged `account_index`, the PRF reproduces the same masked `account_reference` as the original sent request. The contract's unique index `($ownerId, toUserId, accountReference)` rejects the broadcast — the exact failure mode G3 was added to prevent. Fall back to `established_contacts[recipient].outgoing_request` (taking the max of both versions if both are present).
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs:441-478: Historical contactRequest documents replay as fresh rotations every sync sweep
  The rotation guard at line 451 only compares the incoming reference against the currently tracked reference (incoming map or established contact). contactRequest documents are immutable, and `fetch_received_contact_requests(identity_id, None)` (line 370) is unfiltered, so every sweep returns both the original v=0 and any rotated v=N documents. Within a single sweep, ingesting v=0 against an already-tracked v=N flips the established contact back to v=0 and queues a teardown (lines 472-478, then 517-528), and the next document in the same iteration flips it forward again. Across sweeps the same churn replays — the external account is torn down and rebuilt on every cycle, generating wasted DAPI traffic. Worse, if the freshest document falls outside the eventual paginated window (post-M3 growth), the contact can regress to the stale xpub. Compare by `created_at`/version monotonicity, not bare reference inequality: only apply rotation when the incoming request strictly supersedes the tracked one.
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs:292-308: select_recipient_key_index returns disabled (revoked) keys — DIP-15 compact xpub encrypted to a key whose private half may be compromised
  Verified at HEAD lines 292-308: the selector iterates `recipient_identity.public_keys()` and returns the first DECRYPTION (then ENCRYPTION) ECDSA_SECP256K1 key with no `disabled_at` check. `validate_contact_request` does gate on `disabled_at`, so the send/receive interop rules are asymmetric. On send, the 69-byte DIP-15 compact xpub (fingerprint‖chaincode‖pubkey — combined with `accountReference` lets the holder derive every receiving address on that account) is encrypted to a key the recipient has explicitly revoked. Identity-key revocation is the on-platform mechanism for declaring 'this key's private half may be compromised'. Add `&& k.disabled_at().is_none()` to both branches so selection matches validation.

In `packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs:206-222: rejected_contact_requests tombstones are written but never restored on rehydration
  `managed_identity_from_entry` still hard-codes `rejected_contact_requests: Default::default()` at line 214. The writer at `sqlite/schema/contacts.rs:240` (INSERT INTO rejected_contact_requests) and the V001 row exist, but there is no `load_state` reader for the new table, and `apply_changeset` only handles live deltas — restored state is always empty after restart. The recurring DashPay loop's tombstone-skip at `network/contact_requests.rs:457` therefore never fires after restart, so a rejected request is resurrected on the first sweep. Because the on-platform document is immutable, wiping the tombstone on restart defeats the user's explicit reject. Add a per-wallet `load_state` reader for `rejected_contact_requests` and route its output into the rehydration changeset / ManagedIdentity field.

In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:3024-3034: Wallet deletion PHASE 1 omits PersistentDashpayPayment children — same fatal pattern as contactRequests
  PHASE 1 iterates `dpnsNames`, `dashpayProfile`, and `contactRequests` but NOT `dashpayPayments`. `PersistentDashpayPayment.owner` is non-optional and `PersistentIdentity.dashpayPayments` is the cascading inverse added in this PR. The surrounding comment (lines 3008-3023) explicitly documents that this phase exists because SwiftData fatals during `save()` when it must null out a non-optional inverse on a child processed in the same batch — exactly the shape of the new payments relationship. A wallet with persisted DashPay payment history will hit the SwiftData fatal at PHASE 2 `save()`, aborting before the wallet row is removed. The user believes their data was wiped; plaintext memo + counterparty id + amount + txid rows remain on disk. Pre-delete `identity.dashpayPayments` alongside the other children.

shumkov and others added 3 commits June 18, 2026 18:35
Timeless-comments cleanup across 18 DashPay source files in rs-platform-wallet /
rs-platform-wallet-ffi: removed internal tracking tokens (G1a..G15 spec gates,
M3 task 13 milestone labels, (P2) priority tags, "stage N") from comments and
tracing log strings. Where a bare gate ID was load-bearing in the sentence, it's
replaced with the plain-English concept it referenced (G4 → "host-side signing
hook", G1c → "transient/permanent failure policy", G3 → "sender key-rotation",
G1b → "established-contact account build", etc.) so each comment is self-contained.

Comment/string-only: no function/type/field/signature/control-flow changes; build
green (platform-wallet + platform-wallet-ffi), zero residual tracker tokens.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Add a status header: the implementable DashPay backlog is done/tested/pushed; the
five remaining unchecked items are blocked on resources outside this codebase
(funded devnet for integration tests + on-device UAT; a registered dashpay
contract change for the encrypted profile ignored-list and query-level DoS
filter) or are a deliberate privacy don't-do marker, not oversights.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…path fix

The friendship-path `account' = 0'` item is no longer just "blocked cross-repo" — the
upstream key-wallet fix is submitted as rust-dashcore#813 (honor the AccountType
`index` instead of a hardcoded 0', red→green test, backward-compatible for account 0).
Also correct the framing: it's not a counterparty-interop break (the recipient pays
from the shared xpub and ignores accountReference per DIP-15) — it's a single-account
limitation, the same gap as the deferred multi-account item, gated on #813.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@shumkov shumkov force-pushed the feat/dashpay-m1-sync-correctness branch from 6512cae to 822b1ee Compare June 18, 2026 11:37
Make the DashPay design docs match what actually shipped on this branch:
- SYNC_CORRECTNESS_SPEC (Spec 0): REVIEWED→IMPLEMENTED — both stages shipped
  (paginated/high-water request sync + id-keyed contact-profile cache), durably
  persisted to both the SQLite persister and SwiftData.
- CONTACTINFO_FORMAT_SPEC (Spec 1): the §4 contactInfo reject/block field marked
  DEFINED-but-NOT-ADOPTED — R1 resolved ignore as local-only, so it is not carried
  on contactInfo; the shipped codec is alias/note/displayHidden/acceptedAccounts.
- BLOCK_SPEC: PAUSED→SUPERSEDED — replaced by the implemented per-sender, reversible,
  local-only Ignore (Spec 2); the contactInfo cross-device route was rejected (R1);
  cross-device deferred to a future encrypted profile field (contract track).
- SPEC.md: added a 2026-06-18 status block mapping the Part-0 gap table (G1–G15) to
  its resolution, plus accountReference (keep-ours) and the account-index path fix
  (upstream rust-dashcore#813 via dashcore bump PR #3936). Points at TODO.md as the
  authoritative item-by-item status.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@thepastaclaw thepastaclaw 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.

Code Review

Cumulative verification at 822b1ee. The latest delta from 6512cae is comment-only test cleanup in platform-wallet-storage migrations; no behavioral changes. All 10 prior findings independently re-verified against the worktree and remain STILL VALID. Headlined by the blocking SwiftData wipe omission of identity.contactProfiles (the in-source PHASE 1 comment explicitly enumerates the non-optional cascade-children that must be pre-deleted and PersistentDashpayContactProfile.owner is exactly such a child), plus the ignored_senders SQLite reader/writer asymmetry, the pre-consent attacker-controlled avatar fetch, and three FFI out-param hygiene defects.

🔴 1 blocking | 🟡 7 suggestion(s) | 💬 2 nitpick(s)

10 additional finding(s)

blocking: Wallet wipe omits contactProfiles before deleting identities — SwiftData fatal will abort user-initiated wipe

packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift (line 3471)

Verified at HEAD (lines 3471-3487): phase 1 deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders, but not contactProfiles. The in-source comment block at 3438-3470 documents exactly why this loop exists: SwiftData fatals during save() when a parent delete has to null out a non-optional inverse on a child in the same batch. This PR adds PersistentIdentity.contactProfiles (PersistentIdentity.swift:150) with cascade inverse PersistentDashpayContactProfile.owner: PersistentIdentity (PersistentDashpayContactProfile.swift:109) — that owner is non-optional, the exact shape the comment cites for the other children it does pre-delete. Any wallet whose recurring DashPay sync has cached a contact profile row (established contacts AND unsolicited senders, see profile.rs:640-650) will hit the documented fatal during phase 2's identity delete, aborting the user-initiated wipe and leaving cached PersistentDashpayContactProfile rows — including sender-controlled avatarUrl/displayName/publicMessage strings — on disk.

                    for identity in identitiesToDelete {
                        for name in Array(identity.dpnsNames) {
                            backgroundContext.delete(name)
                        }
                        if let profile = identity.dashpayProfile {
                            backgroundContext.delete(profile)
                        }
                        for contactProfile in Array(identity.contactProfiles) {
                            backgroundContext.delete(contactProfile)
                        }
                        for cr in Array(identity.contactRequests) {
                            backgroundContext.delete(cr)
                        }
                        for payment in Array(identity.dashpayPayments) {
                            backgroundContext.delete(payment)
                        }
                        for ignored in Array(identity.dashpayIgnoredSenders) {
                            backgroundContext.delete(ignored)
                        }
                    }
suggestion: ignored_senders SQLite writes go to a relational table the reader restores from entry_blob — local Ignore intent silently reverts on cold restart

packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs (line 214)

Verified at HEAD (identities.rs:218): ignored_senders: entry.ignored_senders.clone() rehydrates from the identity's serialized entry_blob (in-place comment at 214-217 confirms this). Meanwhile contacts::apply (contacts.rs:233-267) writes ignore/unignore into the relational ignored_senders table, and ignore_sender/unignore_sender (contact_requests.rs) emit only a ContactChangeSet — they never trigger an IdentityChangeSet so entry_blob.ignored_senders is not refreshed. Once the production Wallet::from_persisted path (currently TODO at persister.rs:909-916) wires this reader into production rehydration, cold restart restores ignored_senders = {} from a stale blob and the next sweep resurfaces the blocked sender's still-immutable on-chain contactRequest. Combined with the pre-consent avatar finding below, a user's local block becomes a restart-resilient deanonymization channel. Either load ignored_senders from the relational table in the reader (which is the schema's source of truth and removes the dual-write hazard), or emit an IdentityChangeSet from ignore/unignore so entry_blob stays in lockstep.

suggestion: Pending incoming requests fetch attacker-controlled avatar URLs before user consent

packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift (line 119)

Verified at HEAD: sync_contact_profiles (profile.rs:640-650) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView → SwiftUI AsyncImage, issuing an HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only checks scheme/length. Spec 2 Ignore mutes only AFTER first render, and (per the SQLite reader asymmetry) won't survive cold restart. Suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab), or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.

suggestion: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale row resurrects on cold start

packages/rs-platform-wallet-ffi/src/identity_persistence.rs (line 587)

Verified at HEAD: allocate_contact_profile_rows explicitly continues past entries with profile == None (in-comment: "Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep"). The FFI projection carries no removal intent, Swift's upsertDashpayContactProfiles is append/refresh-only, and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile flips the in-memory entry to None (profile.rs:594-602), but absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32]), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes.

suggestion: established_contact_get_note leaves *out_note undefined on every early-return path

packages/rs-platform-wallet-ffi/src/established_contact.rs (line 156)

Verified at HEAD: sibling established_contact_get_alias (lines 102-117) writes *out_alias = std::ptr::null_mut(); at line 108 immediately after check_ptr!, establishing the C-ABI contract that out_* is defined-null on early returns. established_contact_get_note (lines 156-169) only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound or contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL — reachable from on-chain note content) leave *out_note indeterminate across the C ABI. A Swift/C caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. Mirror the sibling pattern.

#[no_mangle]
pub unsafe extern "C" fn established_contact_get_note(
    contact_handle: Handle,
    out_note: *mut *mut std::os::raw::c_char,
) -> PlatformWalletFFIResult {
    check_ptr!(out_note);
    *out_note = std::ptr::null_mut();

    let option =
        ESTABLISHED_CONTACT_STORAGE.with_item(contact_handle, |contact| contact.note.clone());
    let option = unwrap_option_or_return!(option);
    let note = unwrap_option_or_return!(option);
    let c_str = unwrap_result_or_return!(std::ffi::CString::new(note));
    unsafe { *out_note = c_str.into_raw() };
    PlatformWalletFFIResult::ok()
}
suggestion: DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths

packages/rs-platform-wallet-ffi/src/dashpay_profile.rs (line 90)

Verified at HEAD: managed_identity_get_dashpay_profile (line 90), platform_wallet_get_dashpay_profile (line 116), and platform_wallet_get_contact_profile (line 153) only assign *out_profile / *out_has_profile inside the present/no-profile match arms. After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input at 125, 163-164) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing entry at 100, 132-133, 173) leave both out pointers indeterminate. DashPayProfileFFI owns multiple *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free). Pre-write *out_profile = DashPayProfileFFI::empty() and *out_has_profile = false immediately after check_ptr! in each function, matching the established_contact_get_alias precedent (line 108).

suggestion: Contact-profile checked_at_ms not durably persisted when profile is unchanged — negative-cache backoff does not survive restart

packages/rs-platform-wallet/src/wallet/identity/network/profile.rs (line 588)

Verified at HEAD: apply_fetched_profile always refreshes checked_at_ms = now_ms (line 599) but returns changed only when the stored profile value differs (equality at 594 compares only profile). sync_contact_profiles calls persister.store only when any_changed is true (717-725). A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an In query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel (restart re-issues per-victim GETs) and creates a cold-start fetch storm. A failed earlier store is also not retried because later sweeps see changed = false. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.

suggestion: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop

packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs (line 42)

Verified at HEAD: fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE = 100 per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. Spec 2 sharpens the trigger: unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick, an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.

nitpick: New restore/persist FFI structs lack compile-time layout guards

packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs (line 352)

Verified at HEAD: sibling #[repr(C)] types crossing the same Swift↔Rust restore/persist boundary carry static-assert size/align guards (AccountAddressPoolFFI, ContactRequestFFI, ContactRequestRemovalFFI, ContactIgnoredSenderFFI, IdentityKeyEntryFFI, IdentityEntryFFI). Three boundary types introduced by this PR don't: PaymentRestoreEntryFFI (wallet_restore_types.rs:352-367), ContactProfileRestoreEntryFFI (wallet_restore_types.rs:383-410), and the persist-side ContactProfileRowFFI (identity_persistence.rs:180-211). The parent IdentityEntryFFI guard pins the pointer/count fields but not the inner row layout Swift indexes through. A silent field reorder, type widen, or padding change on either side would compile cleanly and shift offsets relative to the Swift mirror, potentially mis-attributing restored profiles or payments to the wrong contact id / wrong owner. Add const _: [u8; N] = [0u8; std::mem::size_of::<T>()]; + matching align_of tripwires to all three structs, matching precedent.

nitpick: payments_for_contact doc claims 'newest first' but iteration is lexicographic by hex txid

packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs (line 177)

Verified at HEAD: the rustdoc states the result is ordered 'newest first', but the implementation iterates self.dashpay_payments — a BTreeMap<String, PaymentEntry> keyed by hex tx_id. PaymentEntry carries no timestamp field, so the returned Vec is sorted lexicographically by hex-string txid, not by time. The per-contact payment-history UI consumer renders payments in essentially random (txid-hash) order. Test payments_for_contact_filters_by_counterparty does not assert ordering. A sender who can grind their outgoing txid can also influence display position, providing a small social-engineering surface at the UI layer. Either drop the 'newest first' claim from the docstring, add a created_at_ms field and sort by it, or have the caller stitch ordering from the SPV transaction store.

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

- [BLOCKING] In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:3471-3487: Wallet wipe omits contactProfiles before deleting identities — SwiftData fatal will abort user-initiated wipe
  Verified at HEAD (lines 3471-3487): phase 1 deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders, but not contactProfiles. The in-source comment block at 3438-3470 documents exactly why this loop exists: SwiftData fatals during save() when a parent delete has to null out a non-optional inverse on a child in the same batch. This PR adds PersistentIdentity.contactProfiles (PersistentIdentity.swift:150) with cascade inverse PersistentDashpayContactProfile.owner: PersistentIdentity (PersistentDashpayContactProfile.swift:109) — that owner is non-optional, the exact shape the comment cites for the other children it does pre-delete. Any wallet whose recurring DashPay sync has cached a contact profile row (established contacts AND unsolicited senders, see profile.rs:640-650) will hit the documented fatal during phase 2's identity delete, aborting the user-initiated wipe and leaving cached PersistentDashpayContactProfile rows — including sender-controlled avatarUrl/displayName/publicMessage strings — on disk.
- [SUGGESTION] In `packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs`:214-218: ignored_senders SQLite writes go to a relational table the reader restores from entry_blob — local Ignore intent silently reverts on cold restart
  Verified at HEAD (identities.rs:218): `ignored_senders: entry.ignored_senders.clone()` rehydrates from the identity's serialized entry_blob (in-place comment at 214-217 confirms this). Meanwhile contacts::apply (contacts.rs:233-267) writes ignore/unignore into the relational ignored_senders table, and ignore_sender/unignore_sender (contact_requests.rs) emit only a ContactChangeSet — they never trigger an IdentityChangeSet so entry_blob.ignored_senders is not refreshed. Once the production Wallet::from_persisted path (currently TODO at persister.rs:909-916) wires this reader into production rehydration, cold restart restores ignored_senders = {} from a stale blob and the next sweep resurfaces the blocked sender's still-immutable on-chain contactRequest. Combined with the pre-consent avatar finding below, a user's local block becomes a restart-resilient deanonymization channel. Either load ignored_senders from the relational table in the reader (which is the schema's source of truth and removes the dual-write hazard), or emit an IdentityChangeSet from ignore/unignore so entry_blob stays in lockstep.
- [SUGGESTION] In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift`:119-129: Pending incoming requests fetch attacker-controlled avatar URLs before user consent
  Verified at HEAD: sync_contact_profiles (profile.rs:640-650) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView → SwiftUI AsyncImage, issuing an HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only checks scheme/length. Spec 2 Ignore mutes only AFTER first render, and (per the SQLite reader asymmetry) won't survive cold restart. Suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab), or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/identity_persistence.rs`:587-621: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale row resurrects on cold start
  Verified at HEAD: allocate_contact_profile_rows explicitly continues past entries with profile == None (in-comment: "Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep"). The FFI projection carries no removal intent, Swift's upsertDashpayContactProfiles is append/refresh-only, and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile flips the in-memory entry to None (profile.rs:594-602), but absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32]), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/established_contact.rs`:156-169: established_contact_get_note leaves *out_note undefined on every early-return path
  Verified at HEAD: sibling established_contact_get_alias (lines 102-117) writes `*out_alias = std::ptr::null_mut();` at line 108 immediately after check_ptr!, establishing the C-ABI contract that out_* is defined-null on early returns. established_contact_get_note (lines 156-169) only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound or contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL — reachable from on-chain note content) leave *out_note indeterminate across the C ABI. A Swift/C caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. Mirror the sibling pattern.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/dashpay_profile.rs`:90-185: DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths
  Verified at HEAD: managed_identity_get_dashpay_profile (line 90), platform_wallet_get_dashpay_profile (line 116), and platform_wallet_get_contact_profile (line 153) only assign *out_profile / *out_has_profile inside the present/no-profile match arms. After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input at 125, 163-164) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing entry at 100, 132-133, 173) leave both out pointers indeterminate. DashPayProfileFFI owns multiple *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free). Pre-write `*out_profile = DashPayProfileFFI::empty()` and `*out_has_profile = false` immediately after check_ptr! in each function, matching the established_contact_get_alias precedent (line 108).
- [SUGGESTION] In `packages/rs-platform-wallet/src/wallet/identity/network/profile.rs`:588-725: Contact-profile checked_at_ms not durably persisted when profile is unchanged — negative-cache backoff does not survive restart
  Verified at HEAD: apply_fetched_profile always refreshes checked_at_ms = now_ms (line 599) but returns changed only when the stored profile value differs (equality at 594 compares only profile). sync_contact_profiles calls persister.store only when any_changed is true (717-725). A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an In query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel (restart re-issues per-victim GETs) and creates a cold-start fetch storm. A failed earlier store is also not retried because later sweeps see changed = false. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.
- [SUGGESTION] In `packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs`:42-112: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop
  Verified at HEAD: fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE = 100 per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. Spec 2 sharpens the trigger: unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick, an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.
- [NITPICK] In `packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs`:352-411: New restore/persist FFI structs lack compile-time layout guards
  Verified at HEAD: sibling #[repr(C)] types crossing the same Swift↔Rust restore/persist boundary carry static-assert size/align guards (AccountAddressPoolFFI, ContactRequestFFI, ContactRequestRemovalFFI, ContactIgnoredSenderFFI, IdentityKeyEntryFFI, IdentityEntryFFI). Three boundary types introduced by this PR don't: PaymentRestoreEntryFFI (wallet_restore_types.rs:352-367), ContactProfileRestoreEntryFFI (wallet_restore_types.rs:383-410), and the persist-side ContactProfileRowFFI (identity_persistence.rs:180-211). The parent IdentityEntryFFI guard pins the pointer/count fields but not the inner row layout Swift indexes through. A silent field reorder, type widen, or padding change on either side would compile cleanly and shift offsets relative to the Swift mirror, potentially mis-attributing restored profiles or payments to the wrong contact id / wrong owner. Add `const _: [u8; N] = [0u8; std::mem::size_of::<T>()];` + matching align_of tripwires to all three structs, matching precedent.
- [NITPICK] In `packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs`:177-190: payments_for_contact doc claims 'newest first' but iteration is lexicographic by hex txid
  Verified at HEAD: the rustdoc states the result is ordered 'newest first', but the implementation iterates self.dashpay_payments — a BTreeMap<String, PaymentEntry> keyed by hex tx_id. PaymentEntry carries no timestamp field, so the returned Vec is sorted lexicographically by hex-string txid, not by time. The per-contact payment-history UI consumer renders payments in essentially random (txid-hash) order. Test payments_for_contact_filters_by_counterparty does not assert ordering. A sender who can grind their outgoing txid can also influence display position, providing a small social-engineering surface at the UI layer. Either drop the 'newest first' claim from the docstring, add a created_at_ms field and sort by it, or have the caller stitch ordering from the SPV transaction store.

Inline dry-run could not load the GitHub PR diff because this PR exceeds GitHub's 20,000-line diff limit, so I posted the same verified findings as a top-level review body.

@thepastaclaw thepastaclaw 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.

Code Review

Cumulative review at 30d5112. Latest delta from 822b1ee is docs-only (4 DashPay spec markdown files); no code changed. All 10 prior findings re-verified line-by-line against the worktree and remain valid — three independent agent pairs (general/security/FFI) converged on the same set. Headlined by the blocking SwiftData wipe omission of identity.contactProfiles: lines 3471-3487 still don't pre-delete contactProfiles, while the in-source comment at 3438-3470 explicitly enumerates the non-optional cascade-children that PHASE 1 exists to handle, and PersistentDashpayContactProfile.owner is exactly such a child. Other carryovers cover the SQLite ignored_senders reader/writer asymmetry, pre-consent attacker-controlled avatar fetch, three FFI out-param hygiene defects, the confirmed-absent FFI projection gap, a timestamp-persistence gap, an unbounded paginated retrieve-all, missing #[repr(C)] layout guards, and a docs/behavior mismatch in payments_for_contact.

🔴 1 blocking | 🟡 7 suggestion(s) | 💬 2 nitpick(s)

10 additional finding(s)

blocking: Wallet wipe omits contactProfiles — SwiftData fatal will abort user-initiated wipe and leave attacker-controlled strings on disk

packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift (line 3471)

Verified at HEAD (3471-3487). PHASE 1 deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders, but NOT contactProfiles. The 3438-3470 in-source comment explicitly documents that this loop exists because SwiftData fatals during save() when a parent delete must null out a non-optional inverse on a child in the same batch. This PR introduces PersistentIdentity.contactProfiles whose inverse PersistentDashpayContactProfile.owner is non-optional — the exact shape the comment cites for the other children it does pre-delete. Any wallet whose recurring DashPay sync has cached even one PersistentDashpayContactProfile row (established contacts AND unsolicited senders, since profile.rs:640-650 includes incoming-request senders) will hit the documented fatal during PHASE 2's identity delete (3493-3496), aborting a user-initiated wipe and leaving cached PersistentDashpayContactProfile rows — including sender-controlled avatarUrl / displayName / publicMessage strings — on disk. A user who wipes precisely to scrub a stalker's footprint actually retains it.

                    for identity in identitiesToDelete {
                        for name in Array(identity.dpnsNames) {
                            backgroundContext.delete(name)
                        }
                        if let profile = identity.dashpayProfile {
                            backgroundContext.delete(profile)
                        }
                        for contactProfile in Array(identity.contactProfiles) {
                            backgroundContext.delete(contactProfile)
                        }
                        for cr in Array(identity.contactRequests) {
                            backgroundContext.delete(cr)
                        }
                        for payment in Array(identity.dashpayPayments) {
                            backgroundContext.delete(payment)
                        }
                        for ignored in Array(identity.dashpayIgnoredSenders) {
                            backgroundContext.delete(ignored)
                        }
                    }
suggestion: established_contact_get_note leaves *out_note undefined on every early-return path

packages/rs-platform-wallet-ffi/src/established_contact.rs (line 156)

Verified at HEAD. Sibling established_contact_get_alias (102-117) writes *out_alias = std::ptr::null_mut(); at line 108 immediately after check_ptr!, establishing the C-ABI contract on this module that out-params are defined-null on early returns. established_contact_get_note (156-169) only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound, contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL, reachable from on-chain note content) leave *out_note indeterminate across the ABI. A Swift/C caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. The exported C ABI must not depend on caller hygiene — mirror the sibling pattern.

#[no_mangle]
pub unsafe extern "C" fn established_contact_get_note(
    contact_handle: Handle,
    out_note: *mut *mut std::os::raw::c_char,
) -> PlatformWalletFFIResult {
    check_ptr!(out_note);
    *out_note = std::ptr::null_mut();

    let option =
        ESTABLISHED_CONTACT_STORAGE.with_item(contact_handle, |contact| contact.note.clone());
    let option = unwrap_option_or_return!(option);
    let note = unwrap_option_or_return!(option);
    let c_str = unwrap_result_or_return!(std::ffi::CString::new(note));
    unsafe { *out_note = c_str.into_raw() };
    PlatformWalletFFIResult::ok()
}
suggestion: DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths

packages/rs-platform-wallet-ffi/src/dashpay_profile.rs (line 90)

Verified at HEAD. managed_identity_get_dashpay_profile (90), platform_wallet_get_dashpay_profile (116), and platform_wallet_get_contact_profile (153) only assign *out_profile / *out_has_profile inside the Some/None match arms (102-110, 134-143, 174-183). After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input at 125, 163-164) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing contact entry at 100, 132-133, 173) leave both out pointers indeterminate. DashPayProfileFFI owns four *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free). Pre-write *out_profile = DashPayProfileFFI::empty(); *out_has_profile = false; immediately after check_ptr! in each function, matching the established_contact_get_alias precedent at line 108.

suggestion: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale row resurrects on cold start

packages/rs-platform-wallet-ffi/src/identity_persistence.rs (line 587)

Verified at HEAD. allocate_contact_profile_rows (587-621) explicitly continues past entries with profile == None (590-592: "Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep"). The FFI projection carries no removal intent for absences; Swift's upsertDashpayContactProfiles is append/refresh-only; and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile (profile.rs:594-602) flips the in-memory entry to None, but absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl. This compounds the pre-consent avatar fetch into a tracking channel that outlasts on-chain profile removal. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32] + count), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes on the same callback.

suggestion: Pending incoming requests fetch attacker-controlled avatar URLs before user consent

packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift (line 119)

Verified at HEAD. sync_contact_profiles (profile.rs:640-650) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow (119-129) feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView → SwiftUI AsyncImage, issuing an outbound HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only validates scheme/length. Spec 2 Ignore mutes only AFTER first render, and (per the ignored_senders reader asymmetry below) won't even survive cold restart on the SQLite backend. Suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.

suggestion: ignored_senders SQLite writes go to a relational table the reader restores from entry_blob — local Ignore intent silently reverts on cold restart

packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs (line 214)

Verified at HEAD. Line 218 rehydrates ignored_senders: entry.ignored_senders.clone() from the identity's entry_blob (214-217 comment confirms scalar-snapshot collections ride the identity blob). Meanwhile contacts::apply (contacts.rs:233-267) writes ignore/unignore into the relational ignored_senders table, and ignore_sender / unignore_sender emit only a ContactChangeSet — they never trigger an IdentityChangeSet, so entry_blob.ignored_senders is not refreshed. Once production Wallet::from_persisted (TODO at persister.rs) wires this reader into production rehydration, cold restart restores ignored_senders = {} from a stale blob and the next sweep resurfaces blocked senders' still-immutable on-chain contactRequest. Combined with the pre-consent avatar fetch, the user's local block becomes a restart-resilient deanonymization channel against blocked senders. Either load ignored_senders from the relational table in the reader (the schema's source of truth, removes the dual-write hazard), or emit an IdentityChangeSet from ignore/unignore so entry_blob stays in lockstep.

suggestion: Contact-profile checked_at_ms not durably persisted when profile is unchanged — negative-cache backoff does not survive restart

packages/rs-platform-wallet/src/wallet/identity/network/profile.rs (line 588)

Verified at HEAD. apply_fetched_profile always refreshes checked_at_ms = now_ms (599), but returns changed only when the stored profile value differs (equality at 594 compares only profile). sync_contact_profiles calls persister.store only when any_changed is true (717-725). A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an In query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel (restart re-issues per-victim GETs to known-stable hosts) and creates a cold-start fetch storm. A failed earlier store is also not retried because later sweeps see changed = false. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.

suggestion: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop

packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs (line 42)

Verified at HEAD. fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE = 100 per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. Spec 2 sharpens the trigger: unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick (15s cadence per the updated SYNC_CORRECTNESS_SPEC), an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.

nitpick: New restore/persist FFI structs lack compile-time layout guards

packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs (line 352)

Verified at HEAD. Sibling #[repr(C)] types crossing the same Swift↔Rust restore/persist boundary carry static-assert size/align guards: IdentityKeyEntryFFI (identity_persistence.rs:335-336), IdentityEntryFFI (identity_persistence.rs:376-377), ContactRequestFFI/ContactRequestRemovalFFI/ContactIgnoredSenderFFI (contact_persistence.rs:207-223). Three boundary types introduced by this PR don't: PaymentRestoreEntryFFI (wallet_restore_types.rs:352-367), ContactProfileRestoreEntryFFI (wallet_restore_types.rs:383-410), and the persist-side ContactProfileRowFFI (identity_persistence.rs:180-211). The parent IdentityEntryFFI guard pins the outer pointer/count fields but not the inner row layout Swift indexes through. A silent field reorder, type widen, or padding change on either side compiles cleanly and shifts offsets relative to the Swift mirror, potentially mis-attributing restored profiles or payments to the wrong contact id / wrong owner (cross-account leak of cached profile / payment metadata). Add const _: [u8; N] = [0u8; std::mem::size_of::<T>()]; + matching align_of tripwires to all three structs.

nitpick: payments_for_contact doc claims 'newest first' but iteration is lexicographic by hex txid

packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs (line 177)

Verified at HEAD. The rustdoc at line 177 states the result is ordered 'newest first', but the implementation iterates self.dashpay_payments — a BTreeMap<String, PaymentEntry> keyed by hex tx_id. PaymentEntry carries no timestamp field, so the returned Vec is sorted lexicographically by hex-string txid, not by time. The per-contact payment-history UI consumer therefore renders payments in essentially random (txid-hash) order. The accompanying test payments_for_contact_filters_by_counterparty does not assert ordering. A sender who can grind their outgoing txid can also influence display position, providing a small social-engineering surface at the UI layer. Either drop the 'newest first' claim from the docstring, add a created_at_ms field and sort by it, or have the caller stitch ordering from the SPV transaction store.

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

- [BLOCKING] In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:3471-3487: Wallet wipe omits contactProfiles — SwiftData fatal will abort user-initiated wipe and leave attacker-controlled strings on disk
  Verified at HEAD (3471-3487). PHASE 1 deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders, but NOT contactProfiles. The 3438-3470 in-source comment explicitly documents that this loop exists because SwiftData fatals during save() when a parent delete must null out a non-optional inverse on a child in the same batch. This PR introduces PersistentIdentity.contactProfiles whose inverse PersistentDashpayContactProfile.owner is non-optional — the exact shape the comment cites for the other children it does pre-delete. Any wallet whose recurring DashPay sync has cached even one PersistentDashpayContactProfile row (established contacts AND unsolicited senders, since profile.rs:640-650 includes incoming-request senders) will hit the documented fatal during PHASE 2's identity delete (3493-3496), aborting a user-initiated wipe and leaving cached PersistentDashpayContactProfile rows — including sender-controlled avatarUrl / displayName / publicMessage strings — on disk. A user who wipes precisely to scrub a stalker's footprint actually retains it.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/established_contact.rs`:156-169: established_contact_get_note leaves *out_note undefined on every early-return path
  Verified at HEAD. Sibling established_contact_get_alias (102-117) writes `*out_alias = std::ptr::null_mut();` at line 108 immediately after check_ptr!, establishing the C-ABI contract on this module that out-params are defined-null on early returns. established_contact_get_note (156-169) only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound, contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL, reachable from on-chain note content) leave *out_note indeterminate across the ABI. A Swift/C caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. The exported C ABI must not depend on caller hygiene — mirror the sibling pattern.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/dashpay_profile.rs`:90-185: DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths
  Verified at HEAD. managed_identity_get_dashpay_profile (90), platform_wallet_get_dashpay_profile (116), and platform_wallet_get_contact_profile (153) only assign *out_profile / *out_has_profile inside the Some/None match arms (102-110, 134-143, 174-183). After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input at 125, 163-164) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing contact entry at 100, 132-133, 173) leave both out pointers indeterminate. DashPayProfileFFI owns four *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free). Pre-write `*out_profile = DashPayProfileFFI::empty(); *out_has_profile = false;` immediately after check_ptr! in each function, matching the established_contact_get_alias precedent at line 108.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/identity_persistence.rs`:587-621: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale row resurrects on cold start
  Verified at HEAD. allocate_contact_profile_rows (587-621) explicitly `continue`s past entries with profile == None (590-592: "Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep"). The FFI projection carries no removal intent for absences; Swift's upsertDashpayContactProfiles is append/refresh-only; and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile (profile.rs:594-602) flips the in-memory entry to None, but absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl. This compounds the pre-consent avatar fetch into a tracking channel that outlasts on-chain profile removal. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32] + count), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes on the same callback.
- [SUGGESTION] In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift`:119-129: Pending incoming requests fetch attacker-controlled avatar URLs before user consent
  Verified at HEAD. sync_contact_profiles (profile.rs:640-650) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow (119-129) feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView → SwiftUI AsyncImage, issuing an outbound HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only validates scheme/length. Spec 2 Ignore mutes only AFTER first render, and (per the ignored_senders reader asymmetry below) won't even survive cold restart on the SQLite backend. Suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.
- [SUGGESTION] In `packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs`:214-218: ignored_senders SQLite writes go to a relational table the reader restores from entry_blob — local Ignore intent silently reverts on cold restart
  Verified at HEAD. Line 218 rehydrates `ignored_senders: entry.ignored_senders.clone()` from the identity's entry_blob (214-217 comment confirms scalar-snapshot collections ride the identity blob). Meanwhile contacts::apply (contacts.rs:233-267) writes ignore/unignore into the relational ignored_senders table, and ignore_sender / unignore_sender emit only a ContactChangeSet — they never trigger an IdentityChangeSet, so entry_blob.ignored_senders is not refreshed. Once production Wallet::from_persisted (TODO at persister.rs) wires this reader into production rehydration, cold restart restores ignored_senders = {} from a stale blob and the next sweep resurfaces blocked senders' still-immutable on-chain contactRequest. Combined with the pre-consent avatar fetch, the user's local block becomes a restart-resilient deanonymization channel against blocked senders. Either load ignored_senders from the relational table in the reader (the schema's source of truth, removes the dual-write hazard), or emit an IdentityChangeSet from ignore/unignore so entry_blob stays in lockstep.
- [SUGGESTION] In `packages/rs-platform-wallet/src/wallet/identity/network/profile.rs`:588-725: Contact-profile checked_at_ms not durably persisted when profile is unchanged — negative-cache backoff does not survive restart
  Verified at HEAD. apply_fetched_profile always refreshes checked_at_ms = now_ms (599), but returns `changed` only when the stored profile value differs (equality at 594 compares only profile). sync_contact_profiles calls persister.store only when any_changed is true (717-725). A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an `In` query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel (restart re-issues per-victim GETs to known-stable hosts) and creates a cold-start fetch storm. A failed earlier store is also not retried because later sweeps see `changed = false`. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.
- [SUGGESTION] In `packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs`:42-112: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop
  Verified at HEAD. fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE = 100 per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. Spec 2 sharpens the trigger: unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick (15s cadence per the updated SYNC_CORRECTNESS_SPEC), an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.
- [NITPICK] In `packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs`:352-411: New restore/persist FFI structs lack compile-time layout guards
  Verified at HEAD. Sibling #[repr(C)] types crossing the same Swift↔Rust restore/persist boundary carry static-assert size/align guards: IdentityKeyEntryFFI (identity_persistence.rs:335-336), IdentityEntryFFI (identity_persistence.rs:376-377), ContactRequestFFI/ContactRequestRemovalFFI/ContactIgnoredSenderFFI (contact_persistence.rs:207-223). Three boundary types introduced by this PR don't: PaymentRestoreEntryFFI (wallet_restore_types.rs:352-367), ContactProfileRestoreEntryFFI (wallet_restore_types.rs:383-410), and the persist-side ContactProfileRowFFI (identity_persistence.rs:180-211). The parent IdentityEntryFFI guard pins the outer pointer/count fields but not the inner row layout Swift indexes through. A silent field reorder, type widen, or padding change on either side compiles cleanly and shifts offsets relative to the Swift mirror, potentially mis-attributing restored profiles or payments to the wrong contact id / wrong owner (cross-account leak of cached profile / payment metadata). Add `const _: [u8; N] = [0u8; std::mem::size_of::<T>()];` + matching align_of tripwires to all three structs.
- [NITPICK] In `packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs`:177-190: payments_for_contact doc claims 'newest first' but iteration is lexicographic by hex txid
  Verified at HEAD. The rustdoc at line 177 states the result is ordered 'newest first', but the implementation iterates self.dashpay_payments — a BTreeMap<String, PaymentEntry> keyed by hex tx_id. PaymentEntry carries no timestamp field, so the returned Vec is sorted lexicographically by hex-string txid, not by time. The per-contact payment-history UI consumer therefore renders payments in essentially random (txid-hash) order. The accompanying test payments_for_contact_filters_by_counterparty does not assert ordering. A sender who can grind their outgoing txid can also influence display position, providing a small social-engineering surface at the UI layer. Either drop the 'newest first' claim from the docstring, add a created_at_ms field and sort by it, or have the caller stitch ordering from the SPV transaction store.

Inline dry-run could not load the GitHub PR diff because this PR exceeds GitHub's 20,000-line diff limit, so I posted the same verified findings as a top-level review body.

shumkov and others added 4 commits June 19, 2026 18:52
…ork() removal

Updates all 8 rust-dashcore workspace deps 981e97f1 -> ceee4a9b40 (dev HEAD), which
picks up #813 (DashPay account-index derivation path) and #814 (revert of the temporary
#808 Core 23 nested-masternode-address SML changes), so platform keeps the existing
flat-field masternode shape and no consensus change is needed.

The bump also crosses #802 (removed Address::network(), replaced Network with AddressPrefix
because an address's prefix is ambiguous across testnet/devnet and legacy-regtest). Migrate
the four call sites:
- wasm-sdk validate_address: addr.is_valid_for_network(net) — a bool, exactly what it
  computed and now correct for the shared testnet/devnet prefix.
- platform-wallet derivation_path_for_derived_address: the path only distinguishes mainnet
  (coin 5') from everything else (1'), so probe is_valid_for_network(Mainnet).
- platform-wallet-ffi address rendering (2 sites): an address_display_network helper probes
  mainnet/testnet/regtest, decisive for the bech32m platform-payment addresses rendered here
  (mainnet ds / testnet+devnet tb / regtest dsrt).

Migration tracked in #3939. Full workspace --all-targets compiles.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…ored_senders to fixtures

The Spec 2 local-only Ignore feature (4169bcf) added `contact_profiles` and
`ignored_senders` to IdentityEntry but did not update these two sqlite test fixtures,
so the test crate has not compiled with --all-targets since. Add the (empty) fields.
Pre-existing breakage, unrelated to the rust-dashcore bump; no behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
These files predated a `cargo fmt` pass, so the branch's CI `fmt --check` was red
independent of the dashcore bump. Pure rustfmt output; no behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Clears the warnings that would fail CI `clippy -D warnings`, all in pre-existing branch
DashPay code (none from the dashcore bump):
- manual_repeat_n: repeat(' ').take(n) -> repeat_n(' ', n)
- op_ref: drop the needless & on the left operand
- type_complexity: factor an OwnerContactProfiles type alias
- assertions_on_constants: move the SYNC_OVERLAP_MS static invariant into a const block
- unnecessary_get_then_check (x3): get(k).is_none() -> !contains_key(k)
Behavior-preserving; the two affected assertions are intentional invariant/regression guards.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@thepastaclaw thepastaclaw 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.

Code Review

Cumulative review at HEAD 928c2c5. Latest delta (rustfmt, clippy cleanup, fixtures, and a rust-dashcore Address::network() removal migration introducing the address_display_network probe) is non-substantive except for one new latent issue: the address_display_network probe collapses regtest into testnet because base58 testnet/regtest/devnet addresses share is_valid_for_network(Testnet)=true, so regtest wallets render bech32m platform addresses with the testnet 'tb' HRP instead of 'dsrt'. Nine prior findings are carried forward as STILL VALID; the SQLite ignored_senders finding is downgraded to out-of-scope because the reader is now gated to #[cfg(any(test, feature='__test-helpers'))] and no longer wired into production rehydration. The blocking SwiftData wipe omission (contactProfiles) remains the gating issue.

Reviewed commit: 928c2c5

🔴 1 blocking | 🟡 7 suggestion(s) | 💬 2 nitpick(s)

Verified findings

blocking: [Carried forward — STILL VALID] Wallet wipe omits contactProfiles — SwiftData fatal will abort user-initiated wipe and leave attacker-controlled strings on disk

packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift (line 3471)

Verified at HEAD (3471-3487). PHASE 1 deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders, but NOT contactProfiles. The 3438-3470 in-source comment explicitly documents that this pre-delete loop exists because SwiftData fatals during save() when a parent delete must null out a non-optional inverse on a child in the same batch. PersistentIdentity.contactProfiles (Models/PersistentIdentity.swift:150) inverses to PersistentDashpayContactProfile.owner: PersistentIdentity (non-optional), which is the exact shape the comment cites for the other children it does pre-delete. profile.rs sync_contact_profiles includes incoming_contact_requests senders in the per-owner fetch plan, so any wallet whose recurring DashPay sync has cached even one PersistentDashpayContactProfile row (established contacts and unsolicited senders) will hit the documented fatal during PHASE 2's identity delete (3493-3496), aborting a user-initiated wipe and leaving cached PersistentDashpayContactProfile rows — including sender-controlled avatarUrl / displayName / publicMessage strings — on disk. A user who wipes precisely to scrub a stalker's footprint actually retains it.

                    for identity in identitiesToDelete {
                        for name in Array(identity.dpnsNames) {
                            backgroundContext.delete(name)
                        }
                        if let profile = identity.dashpayProfile {
                            backgroundContext.delete(profile)
                        }
                        for contactProfile in Array(identity.contactProfiles) {
                            backgroundContext.delete(contactProfile)
                        }
                        for cr in Array(identity.contactRequests) {
                            backgroundContext.delete(cr)
                        }
                        for payment in Array(identity.dashpayPayments) {
                            backgroundContext.delete(payment)
                        }
                        for ignored in Array(identity.dashpayIgnoredSenders) {
                            backgroundContext.delete(ignored)
                        }
                    }
suggestion: [New in latest delta] address_display_network cannot return Regtest for base58 inputs — regtest wallets render bech32m platform addresses with the testnet 'tb' HRP

packages/rs-platform-wallet-ffi/src/persistence.rs (line 2475)

Introduced in commit a7b05f7 (Address::network() removal migration). The helper probes Mainnet, then Testnet, falling back to Regtest. Per the rust-dashcore docs cited in the bumped dependency, a single non-mainnet base58 Dash address satisfies is_valid_for_network for Testnet, Regtest, and Devnet simultaneously (the base58 prefix is shared). The input here is a base58 dashcore::Address coming from AddressInfo, so a regtest address always short-circuits at the Testnet branch and the Regtest fallback at line 2482 is unreachable for any base58 input. Net effect: regtest wallets get their bech32m platform-payment addresses rendered with HRP 'tb' instead of 'dsrt', and any tooling/operator that copies those addresses into a regtest-aware tool gets an HRP mismatch. The doc-comment (2471-2474) asserts a behavior the helper does not deliver. Either thread the originating network from the wallet config (WalletInfo carries it), or drop the regtest branch and document explicitly that platform-wallet renders regtest as 'tb'.

suggestion: [Carried forward — STILL VALID] established_contact_get_note leaves *out_note undefined on every early-return path

packages/rs-platform-wallet-ffi/src/established_contact.rs (line 156)

Verified at HEAD. Sibling established_contact_get_alias (102-117) writes *out_alias = std::ptr::null_mut(); at line 108 immediately after check_ptr!, establishing the C-ABI contract on this module that out-params are defined-null on early returns. established_contact_get_note (156-169) only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound, contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL, reachable from on-chain note content) leave *out_note indeterminate across the ABI. A C/Swift caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. The exported C ABI must not depend on caller hygiene — mirror the sibling pattern.

#[no_mangle]
pub unsafe extern "C" fn established_contact_get_note(
    contact_handle: Handle,
    out_note: *mut *mut std::os::raw::c_char,
) -> PlatformWalletFFIResult {
    check_ptr!(out_note);
    *out_note = std::ptr::null_mut();

    let option =
        ESTABLISHED_CONTACT_STORAGE.with_item(contact_handle, |contact| contact.note.clone());
    let option = unwrap_option_or_return!(option);
    let note = unwrap_option_or_return!(option);
    let c_str = unwrap_result_or_return!(std::ffi::CString::new(note));
    unsafe { *out_note = c_str.into_raw() };
    PlatformWalletFFIResult::ok()
}
suggestion: [Carried forward — STILL VALID] DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths

packages/rs-platform-wallet-ffi/src/dashpay_profile.rs (line 90)

Verified at HEAD. managed_identity_get_dashpay_profile (90), platform_wallet_get_dashpay_profile (116), and platform_wallet_get_contact_profile (153) only assign *out_profile / *out_has_profile inside the Some/None match arms (101-110, 134-143, 174-183). After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input at 125, 163-164) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing contact entry) leave both out pointers indeterminate. DashPayProfileFFI owns four *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free). Pre-write *out_profile = DashPayProfileFFI::empty(); *out_has_profile = false; immediately after check_ptr! in each function, matching the established_contact_get_alias precedent at line 108.

suggestion: [Carried forward — STILL VALID] Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale row resurrects on cold start

packages/rs-platform-wallet-ffi/src/identity_persistence.rs (line 587)

Verified at HEAD. allocate_contact_profile_rows explicitly continues past entries with profile == None ('Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep'). The FFI projection carries no removal intent for absences; Swift's upsertDashpayContactProfiles is append/refresh-only; and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile flips the in-memory entry to None, but absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl. This compounds the pre-consent avatar fetch into a tracking channel that outlasts on-chain profile removal. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32] + count), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes on the same callback.

suggestion: [Carried forward — STILL VALID] Pending incoming requests fetch attacker-controlled avatar URLs before user consent

packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift (line 119)

Verified at HEAD. sync_contact_profiles (profile.rs) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow (119-129) feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView → SwiftUI AsyncImage, issuing an outbound HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only validates scheme/length. The Ignore action mutes only AFTER first render. Suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.

suggestion: [Carried forward — STILL VALID] Contact-profile checked_at_ms not durably persisted when profile is unchanged — negative-cache backoff does not survive restart

packages/rs-platform-wallet/src/wallet/identity/network/profile.rs (line 588)

Verified at HEAD. apply_fetched_profile always refreshes checked_at_ms = now_ms, but returns changed only when the stored profile value differs (equality compares only profile content). sync_contact_profiles calls persister.store only when any_changed is true. A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an In query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel and creates a cold-start fetch storm. A failed earlier store is also not retried because later sweeps see changed = false. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.

suggestion: [Carried forward — STILL VALID] Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop

packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs (line 42)

Verified at HEAD. fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE = 100 per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick, an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.

nitpick: [Carried forward — STILL VALID] New restore/persist FFI structs lack compile-time layout guards

packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs (line 352)

Verified at HEAD. Sibling #[repr(C)] types crossing the same Swift↔Rust restore/persist boundary carry static-assert size/align guards: IdentityKeyEntryFFI, IdentityEntryFFI, ContactRequestFFI / ContactRequestRemovalFFI / ContactIgnoredSenderFFI. Three boundary types introduced by this PR don't: PaymentRestoreEntryFFI (wallet_restore_types.rs:352-367), ContactProfileRestoreEntryFFI (wallet_restore_types.rs:383-410), and the persist-side ContactProfileRowFFI (identity_persistence.rs:180-211). The parent IdentityEntryFFI guard pins the outer pointer/count fields but not the inner row layout Swift indexes through. A silent field reorder, type widen, or padding change on either side compiles cleanly and shifts offsets relative to the Swift mirror, potentially mis-attributing restored profiles or payments to the wrong contact id / wrong owner (cross-account leak of cached profile / payment metadata). Add const _: [u8; N] = [0u8; std::mem::size_of::<T>()]; + matching align_of tripwires to all three structs.

nitpick: [Carried forward — STILL VALID] payments_for_contact doc claims 'newest first' but iteration is lexicographic by hex txid

packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs (line 177)

Verified at HEAD. The rustdoc at line 177 states the result is 'newest first', but the implementation iterates self.dashpay_payments — a BTreeMap<String, PaymentEntry> keyed by hex tx_id. PaymentEntry carries no timestamp field, so the returned Vec is sorted lexicographically by hex-string txid, not by time. The per-contact payment-history UI consumer therefore renders payments in essentially random (txid-hash) order. A sender who can grind their outgoing txid can also influence display position, providing a small social-engineering surface at the UI layer. Either drop the 'newest first' claim from the docstring, add a created_at_ms field and sort by it, or have the caller stitch ordering from the SPV transaction store.

_Note: Inline posting failed (command failed (1): python3 scripts/review_poster.py dashpay/platform 3841 928c2c5 --dry-run --prior-sha 30d5112
STDOUT:

STDERR:
Traceback (most recent call last):
File "/Users/claw/.openclaw/workspace/scripts/review_poster.py", li), so I posted the same verified findings as a top-level review body._

On-device UAT (testnet, 2026-06-19) surfaced a bug: an imported identity cannot sign
any state transition — KeychainSigner finds no PersistentPublicKey matching the public
key the Rust SDK supplies, even though all 5 keys are persisted correctly (exact match
to the on-chain keys, verified via SwiftData). The signer matches by publicKeyData only
(not identity-scoped), so the SDK is selecting a key the wallet didn't derive/persist —
a key-selection/derivation issue on the import-existing-identity path. Captured the
repro, diagnosis, and the harness state for resuming via create-in-app.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@thepastaclaw thepastaclaw 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.

Code Review

Verified at adb7b32. The latest delta from 928c2c5 is docs-only (docs/dashpay/TODO.md adding a UAT signing bug entry); no code changed in this delta. All 10 prior findings from the 928c2c5 review were re-verified line-by-line against the worktree and remain STILL VALID. Two blocking issues: (1) the SwiftData wallet-wipe PHASE 1 loop at PlatformWalletPersistenceHandler.swift:3471-3487 still omits identity.contactProfiles despite the in-source comment block at 3438-3470 explicitly enumerating exactly this non-optional-inverse cascade-child shape, and (2) the imported-identity load path at loading.rs:253-263 only attaches a derivation breadcrumb to the MASTER probe key while DPNS/profile flows (dpns.rs:206-220, profile.rs key selection) intentionally exclude MASTER and pick the first HIGH/CRITICAL key — Swift clears privateKeyKeychainIdentifier for rows lacking derivation indices (PlatformWalletPersistenceHandler.swift:1584-1597), so post-import signing fails with the exact KeychainSigner error the TODO.md now documents. Six carried-forward suggestions plus one new rs-sdk-ffi defensive-length check; two nitpicks dropped to stay under the 10-finding budget. CodeRabbit reported zero inline findings; nothing to react to.

🔴 2 blocking | 🟡 8 suggestion(s)

10 additional finding(s)

blocking: Wallet wipe omits contactProfiles — SwiftData fatal aborts the wipe and leaves attacker-controlled DashPay strings on disk

packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift (line 3471)

Verified at HEAD adb7b32. PHASE 1 of the wallet-wipe routine pre-deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders, but not identity.contactProfiles. The in-source comment block at 3438-3470 documents the exact invariant this loop is built to enforce: SwiftData fatals during save() when a parent delete must null out a non-optional inverse on a child in the same save batch, so every cascade-child whose inverse is non-optional must be deleted in its own save() ahead of the parent. PersistentIdentity.contactProfiles is cascade and PersistentDashpayContactProfile.owner is non-optional — exactly that shape. profile.rs sync_contact_profiles explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan (lines 640-650), so any wallet whose recurring DashPay sync has cached even one PersistentDashpayContactProfile row (established contacts OR unsolicited senders) will hit the documented fatal during PHASE 2's identity delete (3493-3496), abort the user-initiated wipe, and leave cached PersistentDashpayContactProfile rows — including sender-controlled avatarUrl, displayName, and publicMessage strings — on disk. A user who wipes precisely to scrub a stalker's footprint actually retains it.

                    for identity in identitiesToDelete {
                        for name in Array(identity.dpnsNames) {
                            backgroundContext.delete(name)
                        }
                        if let profile = identity.dashpayProfile {
                            backgroundContext.delete(profile)
                        }
                        for contactProfile in Array(identity.contactProfiles) {
                            backgroundContext.delete(contactProfile)
                        }
                        for cr in Array(identity.contactRequests) {
                            backgroundContext.delete(cr)
                        }
                        for payment in Array(identity.dashpayPayments) {
                            backgroundContext.delete(payment)
                        }
                        for ignored in Array(identity.dashpayIgnoredSenders) {
                            backgroundContext.delete(ignored)
                        }
                    }
blocking: Imported identity persists derivation breadcrumb only for the master probe key — all signed state transitions fail post-import

packages/rs-platform-wallet/src/wallet/identity/network/loading.rs (line 253)

Verified at HEAD. load_identity_by_index_inner emits a derivation breadcrumb only for the single on-chain key whose hash matched the load/discovery probe, by calling managed.add_key(pub_key, Some((wallet_id, identity_index, MASTER_KEY_INDEX)), ...) at lines 259-263. The identity's other on-chain public keys are persisted via add_identity at 241-247 with no derivation indices, and Swift explicitly clears row.privateKeyKeychainIdentifier for entries whose FFI projection has no derivation indices (PlatformWalletPersistenceHandler.swift:1584-1597). Document-write flows then select the first HIGH/CRITICAL authentication key and intentionally exclude MASTER — dpns.rs:206-220 enforces [SecurityLevel::HIGH, SecurityLevel::CRITICAL] because DPP rejects MASTER on document-side state transitions, and profile.rs follows the same key-selection contract. For an imported identity whose probe matched the master slot but whose document key is a separate HIGH/CRITICAL key, the signer is asked to sign with a public key that has no stored or derivable private material, and KeychainSigner returns 'No PersistentPublicKey row matches the supplied public-key bytes' — exactly the symptom now tracked in docs/dashpay/TODO.md (Verification & hygiene → '🐛 BUG (found in UAT 2026-06-19)'). The bug is genuinely in this PR's diff and breaks DPNS register, DashPay profile set, contact requests, and payments for every imported identity; the in-app create flow works only because it derives and persists breadcrumbs for every key it registers. The load/import path needs to derive and persist breadcrumbs for each wallet-derived on-chain authentication key it may later select for signing, not just the MASTER probe key.

suggestion: established_contact_get_note leaves *out_note undefined on every early-return path

packages/rs-platform-wallet-ffi/src/established_contact.rs (line 156)

Verified at HEAD. Sibling established_contact_get_alias (102-117) writes *out_alias = std::ptr::null_mut(); at line 108 immediately after check_ptr!, establishing the module's C-ABI contract that out-params are defined-null on early returns. established_contact_get_note only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound, contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL — reachable from on-chain note content) leave *out_note indeterminate across the ABI. A C/Swift caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. The exported C ABI must not depend on caller hygiene — mirror the sibling pattern.

#[no_mangle]
pub unsafe extern "C" fn established_contact_get_note(
    contact_handle: Handle,
    out_note: *mut *mut std::os::raw::c_char,
) -> PlatformWalletFFIResult {
    check_ptr!(out_note);
    *out_note = std::ptr::null_mut();

    let option =
        ESTABLISHED_CONTACT_STORAGE.with_item(contact_handle, |contact| contact.note.clone());
    let option = unwrap_option_or_return!(option);
    let note = unwrap_option_or_return!(option);
    let c_str = unwrap_result_or_return!(std::ffi::CString::new(note));
    unsafe { *out_note = c_str.into_raw() };
    PlatformWalletFFIResult::ok()
}
suggestion: Pending incoming requests fetch attacker-controlled avatar URLs before user consent

packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift (line 119)

Verified at HEAD. sync_contact_profiles (profile.rs:640-650) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow (119-129) feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView, which uses SwiftUI AsyncImage — opening the Requests tab issues an HTTPS GET to a sender-controlled host on first render, leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only validates scheme/length. The Ignore action mutes only after first render. Either suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.

suggestion: DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths

packages/rs-platform-wallet-ffi/src/dashpay_profile.rs (line 90)

Verified at HEAD. managed_identity_get_dashpay_profile (90), platform_wallet_get_dashpay_profile (116), and platform_wallet_get_contact_profile (153) only assign *out_profile / *out_has_profile inside the Some/None match arms (101-110, 134-143, 174-183). After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input at 125, 163-164) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing contact entry at 100, 132-133, 173) leave both out pointers indeterminate. DashPayProfileFFI owns four *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free). Pre-write *out_profile = DashPayProfileFFI::empty(); *out_has_profile = false; immediately after check_ptr! in each function, matching the established_contact_get_alias precedent at line 108.

suggestion: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale rows resurrect on cold start

packages/rs-platform-wallet-ffi/src/identity_persistence.rs (line 587)

Verified at HEAD. allocate_contact_profile_rows explicitly continues past entries with profile == None (comment: 'Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep'). The FFI projection carries no removal intent for absences; Swift's upsertDashpayContactProfiles is append/refresh-only; and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile (profile.rs:594-602) flips the in-memory entry to None, but the absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32] + count), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes on the same callback.

suggestion: rs-sdk-ffi forms a Rust slice over caller-supplied xpub bytes before enforcing the fixed 69-byte contract

packages/rs-sdk-ffi/src/dashpay/contact_request.rs (line 250)

DashSDKContactRequestParams now documents extended_public_key as exactly the 69-byte DIP-15 compact xpub, and the underlying Rust SDK validates the length after the callback returns. The C ABI entry points, however, only reject null/zero length and then call std::slice::from_raw_parts(params.extended_public_key, params.extended_public_key_len).to_vec() (≈ lines 317-319 and again in send_contact_request ≈ 563-565) before enforcing the scalar length. A stale or buggy foreign caller can therefore make Rust read an arbitrary-length foreign buffer before the validation error path runs. Reject params.extended_public_key_len != 69 at the C ABI boundary, before forming the slice, so caller-controlled length cannot drive an out-of-bounds read.

suggestion: Contact-profile checked_at_ms not durably persisted on unchanged refresh — negative-cache backoff does not survive restart

packages/rs-platform-wallet/src/wallet/identity/network/profile.rs (line 588)

Verified at HEAD. apply_fetched_profile always refreshes checked_at_ms = now_ms but returns changed only when the stored profile value differs (equality compares only profile content). sync_contact_profiles calls persister.store only when any_changed is true. A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an In query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel (restart re-issues per-victim GETs to known-stable hosts) and creates a cold-start fetch storm; a failed earlier store is also not retried because later sweeps see changed = false. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.

suggestion: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop

packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs (line 42)

Verified at HEAD. fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick, an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.

suggestion: address_display_network cannot return Regtest for base58 inputs — regtest wallets render bech32m platform addresses with the testnet 'tb' HRP

packages/rs-platform-wallet-ffi/src/persistence.rs (line 2475)

Verified at HEAD. The helper probes Mainnet, then Testnet, falling back to Regtest. For base58 Dash addresses (the input here is the dashcore::Address from AddressInfo), testnet/regtest/devnet share the same base58 version prefix, so is_valid_for_network(Testnet) returns true for regtest input and the Regtest fallback at line 2482 is unreachable. build_core_address_entry_ffi then feeds the mis-derived network into PlatformAddress::to_bech32m_string, so regtest wallets get their bech32m platform-payment addresses rendered with HRP 'tb' instead of 'dsrt' — exactly the inverse of the doc-comment at 2471-2474. Security impact is bounded (regtest is dev-only), but operators copying these addresses into a regtest-aware tool see an HRP mismatch and may interact with the wrong network domain. Either thread the originating network from WalletInfo (which carries it) instead of probing, or amend the doc and remove the unreachable arm.

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

- [BLOCKING] In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:3471-3487: Wallet wipe omits contactProfiles — SwiftData fatal aborts the wipe and leaves attacker-controlled DashPay strings on disk
  Verified at HEAD adb7b32e. PHASE 1 of the wallet-wipe routine pre-deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders, but not identity.contactProfiles. The in-source comment block at 3438-3470 documents the exact invariant this loop is built to enforce: SwiftData fatals during save() when a parent delete must null out a non-optional inverse on a child in the same save batch, so every cascade-child whose inverse is non-optional must be deleted in its own save() ahead of the parent. PersistentIdentity.contactProfiles is cascade and PersistentDashpayContactProfile.owner is non-optional — exactly that shape. profile.rs sync_contact_profiles explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan (lines 640-650), so any wallet whose recurring DashPay sync has cached even one PersistentDashpayContactProfile row (established contacts OR unsolicited senders) will hit the documented fatal during PHASE 2's identity delete (3493-3496), abort the user-initiated wipe, and leave cached PersistentDashpayContactProfile rows — including sender-controlled avatarUrl, displayName, and publicMessage strings — on disk. A user who wipes precisely to scrub a stalker's footprint actually retains it.
- [BLOCKING] In `packages/rs-platform-wallet/src/wallet/identity/network/loading.rs`:253-263: Imported identity persists derivation breadcrumb only for the master probe key — all signed state transitions fail post-import
  Verified at HEAD. load_identity_by_index_inner emits a derivation breadcrumb only for the single on-chain key whose hash matched the load/discovery probe, by calling managed.add_key(pub_key, Some((wallet_id, identity_index, MASTER_KEY_INDEX)), ...) at lines 259-263. The identity's other on-chain public keys are persisted via add_identity at 241-247 with no derivation indices, and Swift explicitly clears row.privateKeyKeychainIdentifier for entries whose FFI projection has no derivation indices (PlatformWalletPersistenceHandler.swift:1584-1597). Document-write flows then select the first HIGH/CRITICAL authentication key and intentionally exclude MASTER — dpns.rs:206-220 enforces `[SecurityLevel::HIGH, SecurityLevel::CRITICAL]` because DPP rejects MASTER on document-side state transitions, and profile.rs follows the same key-selection contract. For an imported identity whose probe matched the master slot but whose document key is a separate HIGH/CRITICAL key, the signer is asked to sign with a public key that has no stored or derivable private material, and KeychainSigner returns 'No PersistentPublicKey row matches the supplied public-key bytes' — exactly the symptom now tracked in docs/dashpay/TODO.md (Verification & hygiene → '🐛 BUG (found in UAT 2026-06-19)'). The bug is genuinely in this PR's diff and breaks DPNS register, DashPay profile set, contact requests, and payments for every imported identity; the in-app create flow works only because it derives and persists breadcrumbs for every key it registers. The load/import path needs to derive and persist breadcrumbs for each wallet-derived on-chain authentication key it may later select for signing, not just the MASTER probe key.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/established_contact.rs`:156-169: established_contact_get_note leaves *out_note undefined on every early-return path
  Verified at HEAD. Sibling established_contact_get_alias (102-117) writes `*out_alias = std::ptr::null_mut();` at line 108 immediately after check_ptr!, establishing the module's C-ABI contract that out-params are defined-null on early returns. established_contact_get_note only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound, contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL — reachable from on-chain note content) leave *out_note indeterminate across the ABI. A C/Swift caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. The exported C ABI must not depend on caller hygiene — mirror the sibling pattern.
- [SUGGESTION] In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift`:119-129: Pending incoming requests fetch attacker-controlled avatar URLs before user consent
  Verified at HEAD. sync_contact_profiles (profile.rs:640-650) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow (119-129) feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView, which uses SwiftUI AsyncImage — opening the Requests tab issues an HTTPS GET to a sender-controlled host on first render, leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only validates scheme/length. The Ignore action mutes only after first render. Either suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/dashpay_profile.rs`:90-185: DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths
  Verified at HEAD. managed_identity_get_dashpay_profile (90), platform_wallet_get_dashpay_profile (116), and platform_wallet_get_contact_profile (153) only assign *out_profile / *out_has_profile inside the Some/None match arms (101-110, 134-143, 174-183). After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input at 125, 163-164) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing contact entry at 100, 132-133, 173) leave both out pointers indeterminate. DashPayProfileFFI owns four *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free). Pre-write `*out_profile = DashPayProfileFFI::empty(); *out_has_profile = false;` immediately after check_ptr! in each function, matching the established_contact_get_alias precedent at line 108.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/identity_persistence.rs`:587-621: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale rows resurrect on cold start
  Verified at HEAD. allocate_contact_profile_rows explicitly continues past entries with profile == None (comment: 'Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep'). The FFI projection carries no removal intent for absences; Swift's upsertDashpayContactProfiles is append/refresh-only; and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile (profile.rs:594-602) flips the in-memory entry to None, but the absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32] + count), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes on the same callback.
- [SUGGESTION] In `packages/rs-sdk-ffi/src/dashpay/contact_request.rs`:250-319: rs-sdk-ffi forms a Rust slice over caller-supplied xpub bytes before enforcing the fixed 69-byte contract
  DashSDKContactRequestParams now documents extended_public_key as exactly the 69-byte DIP-15 compact xpub, and the underlying Rust SDK validates the length after the callback returns. The C ABI entry points, however, only reject null/zero length and then call `std::slice::from_raw_parts(params.extended_public_key, params.extended_public_key_len).to_vec()` (≈ lines 317-319 and again in send_contact_request ≈ 563-565) before enforcing the scalar length. A stale or buggy foreign caller can therefore make Rust read an arbitrary-length foreign buffer before the validation error path runs. Reject `params.extended_public_key_len != 69` at the C ABI boundary, before forming the slice, so caller-controlled length cannot drive an out-of-bounds read.
- [SUGGESTION] In `packages/rs-platform-wallet/src/wallet/identity/network/profile.rs`:588-725: Contact-profile checked_at_ms not durably persisted on unchanged refresh — negative-cache backoff does not survive restart
  Verified at HEAD. apply_fetched_profile always refreshes checked_at_ms = now_ms but returns `changed` only when the stored profile value differs (equality compares only profile content). sync_contact_profiles calls persister.store only when any_changed is true. A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an `In` query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel (restart re-issues per-victim GETs to known-stable hosts) and creates a cold-start fetch storm; a failed earlier store is also not retried because later sweeps see `changed = false`. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.
- [SUGGESTION] In `packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs`:42-112: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop
  Verified at HEAD. fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick, an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/persistence.rs`:2475-2484: address_display_network cannot return Regtest for base58 inputs — regtest wallets render bech32m platform addresses with the testnet 'tb' HRP
  Verified at HEAD. The helper probes Mainnet, then Testnet, falling back to Regtest. For base58 Dash addresses (the input here is the dashcore::Address from AddressInfo), testnet/regtest/devnet share the same base58 version prefix, so is_valid_for_network(Testnet) returns true for regtest input and the Regtest fallback at line 2482 is unreachable. build_core_address_entry_ffi then feeds the mis-derived network into PlatformAddress::to_bech32m_string, so regtest wallets get their bech32m platform-payment addresses rendered with HRP 'tb' instead of 'dsrt' — exactly the inverse of the doc-comment at 2471-2474. Security impact is bounded (regtest is dev-only), but operators copying these addresses into a regtest-aware tool see an HRP mismatch and may interact with the wrong network domain. Either thread the originating network from WalletInfo (which carries it) instead of probing, or amend the doc and remove the unreachable arm.

Inline dry-run could not load the GitHub PR diff because this PR exceeds GitHub's 20,000-line diff limit, so I posted the same verified findings as a top-level review body.

Ran the three PR #3841 checks on-device (testnet, iPhone 17 Pro sim):
- ignore-restore: PASS (ignored sender persists across restart + sync; removed_incoming)
- wallet-wipe: PASS (all DashPay tables + identities/keys cleared, no plaintext; seed
  zeroized from keychain - no recovery prompt on relaunch)
- sent-payment Pending->Confirmed: FAIL - a fully-confirmed tx (9 confs + IS-lock,
  detected by the wallet at block 1499050) never flips the DashPay payment off Pending.
  Unit test passes; on-device integration does not fire. Candidate causes recorded
  (chainlock re-detection gap; txid display-ASCII vs internal-raw representation split).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@thepastaclaw thepastaclaw 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.

Code Review

Verified at acd59be (HEAD). The latest commit is docs-only; all 10 prior findings reconciled against the worktree and confirmed STILL VALID. Two blockers carried forward: (1) wallet-wipe PHASE 1 still omits identity.contactProfiles despite the in-source non-optional-inverse invariant comment (PersistentDashpayContactProfile.swift:109 confirms owner is non-optional), and (2) load_identity_by_index_inner still emits a derivation breadcrumb only for the MASTER probe key while document-signing flows select HIGH/CRITICAL keys — the exact symptom now documented in the UAT TODO. One new in-scope blocker from codex verified: confirm_sent_dashpay_payment is gated behind WalletEvent::TransactionDetected (core_bridge.rs:104), so confirmations delivered via BlockProcessed updated/inserted records never flip sent DashPay payments Pending→Confirmed — matching the on-device UAT failure recorded in the latest TODO. Eight suggestion-level carryovers cover FFI out-param hygiene, pre-consent avatar tracking, absences-as-delete projection, caller-controlled xpub slicing, and timestamp persistence/algorithmic-DoS budget gaps. Overflow: 1 suggestion dropped to fit the 10-finding budget (address_display_network regtest HRP, 0.7 conf, regtest-only dev tooling).

🔴 3 blocking | 🟡 7 suggestion(s)

10 additional finding(s)

blocking: Wallet wipe PHASE 1 omits identity.contactProfiles — SwiftData fatal can abort user-initiated wipe and leave attacker-controlled DashPay strings on disk

packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift (line 3471)

Re-verified at acd59be. PHASE 1 pre-deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders, but not identity.contactProfiles. The in-source comment block at 3438-3470 explicitly documents the invariant this loop enforces: SwiftData fatals during save() when a parent delete must null out a non-optional inverse on a child in the same batch, so every cascade-child whose inverse is non-optional must be deleted in its own save() ahead of the parent. PersistentDashpayContactProfile.owner is non-optional (PersistentDashpayContactProfile.swift:109: public var owner: PersistentIdentity, doc-commented 'Non-optional: every contact profile exists because of an owner identity. Cascade-deleted from PersistentIdentity.contactProfiles'). sync_contact_profiles (profile.rs:640-650) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, so any wallet whose recurring DashPay sync has cached even one PersistentDashpayContactProfile row — including unsolicited-sender rows — will hit the documented SwiftData fatal at PHASE 2's identity delete (3493-3496), aborting the user-initiated wipe and leaving sender-controlled avatarUrl / displayName / publicMessage strings on disk. The on-device UAT in the latest TODO reported wipe as PASS, but only ran in-app-created identities with no accumulated unsolicited senders — the structural defect remains.

                    for identity in identitiesToDelete {
                        for name in Array(identity.dpnsNames) {
                            backgroundContext.delete(name)
                        }
                        if let profile = identity.dashpayProfile {
                            backgroundContext.delete(profile)
                        }
                        for contactProfile in Array(identity.contactProfiles) {
                            backgroundContext.delete(contactProfile)
                        }
                        for cr in Array(identity.contactRequests) {
                            backgroundContext.delete(cr)
                        }
                        for payment in Array(identity.dashpayPayments) {
                            backgroundContext.delete(payment)
                        }
                        for ignored in Array(identity.dashpayIgnoredSenders) {
                            backgroundContext.delete(ignored)
                        }
                    }
blocking: Imported identity persists derivation breadcrumb only for the MASTER probe key — every signed state transition fails post-import (now confirmed in UAT)

packages/rs-platform-wallet/src/wallet/identity/network/loading.rs (line 253)

Re-verified at acd59be (lines 253-263 unchanged). load_identity_by_index_inner emits a DIP-9 derivation breadcrumb only for the single key whose hash matched the discovery probe, by calling managed.add_key(pub_key, Some((wallet_id, identity_index, MASTER_KEY_INDEX)), ...) at 259-263. The identity's other on-chain public keys travel via add_identity at 241-246 with no derivation indices, and Swift explicitly clears row.privateKeyKeychainIdentifier for entries whose FFI projection lacks derivation indices (PlatformWalletPersistenceHandler.swift:1584-1597). Document-write flows then intentionally exclude MASTER and select the first HIGH/CRITICAL authentication key — dpns.rs:206-220 enforces [SecurityLevel::HIGH, SecurityLevel::CRITICAL] because DPP rejects MASTER on document-side state transitions, and profile.rs follows the same key-selection contract. For an imported identity whose probe matched the master slot but whose document-signing key is a separate HIGH/CRITICAL slot, the signer is asked to sign with a public key that has no stored or derivable private material, and KeychainSigner returns 'No PersistentPublicKey row matches the supplied public-key bytes'. The new UAT TODO entry ('🐛 BUG (found in UAT 2026-06-19): an IMPORTED identity cannot sign any state transition') is the empirical confirmation. Fix: derive and persist breadcrumbs for every wallet-derived on-chain authentication key the wallet may later select for signing, not just the MASTER probe slot.

blocking: Sent DashPay payments only advance Pending→Confirmed on TransactionDetected — BlockProcessed updates never trigger confirmation (matches UAT failure)

packages/rs-platform-wallet/src/changeset/core_bridge.rs (line 99)

confirm_sent_dashpay_payment is invoked only inside the if let WalletEvent::TransactionDetected { record, .. } = &event arm at core_bridge.rs:104-127. build_core_changeset (180-223) also persists transaction status updates from WalletEvent::BlockProcessed via the inserted/updated/matured record lists (lines 205-216): 'Updated records (re-confirmation, IS-lock applied to a known mempool tx, etc.) ... the record's content does change though, so re-emit it.' Those records carry advancing context (InBlock / InChainLockedBlock) but the spawn_wallet_event_adapter event handler never re-runs sent-payment confirmation against them. send_payment records the outgoing entry as Pending and there is no periodic sent-payment reconciler in this PR. Result: a self-broadcast tx that is detected pre-confirm fires confirm_sent_dashpay_payment with an unconfirmed record (no-op), then when the tx is mined SPV emits a BlockProcessed updated record with InBlock context but the sent-payment row never advances. This matches the UAT failure recorded in docs/dashpay/TODO.md on 2026-06-20: 9 confirmations + InstantSend lock on testnet, ZPERSISTENTTRANSACTION.ZCONTEXT advanced, but ZPERSISTENTDASHPAYPAYMENT.ZSTATUSRAW stayed 0 (Pending) for ~20 min. Fix: invoke confirm_sent_dashpay_payment from the BlockProcessed arm against inserted and updated records as well, or add a reconciler that walks Pending sent payments and projects against the persisted wallet's current TransactionRecord context.

suggestion: established_contact_get_note leaves *out_note undefined on every early-return path — C ABI invariant violated

packages/rs-platform-wallet-ffi/src/established_contact.rs (line 156)

Sibling established_contact_get_alias (102-117) writes *out_alias = std::ptr::null_mut(); at line 108 immediately after check_ptr!, establishing the module's C-ABI contract that out-params are defined-null on early returns. established_contact_get_note only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound, contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL, reachable from on-chain note content controlled by counterparty) leave *out_note indeterminate across the ABI. A caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. The exported ABI must not depend on caller hygiene — mirror the sibling pattern by writing the null sentinel immediately after pointer validation.

suggestion: DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths

packages/rs-platform-wallet-ffi/src/dashpay_profile.rs (line 90)

managed_identity_get_dashpay_profile (90), platform_wallet_get_dashpay_profile (116), and platform_wallet_get_contact_profile (153) only assign *out_profile / *out_has_profile inside the Some/None match arms (101-110, 134-143, 174-183). After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing contact entry) leave both out pointers indeterminate. DashPayProfileFFI owns four *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers. Pre-write *out_profile = DashPayProfileFFI::empty(); *out_has_profile = false; immediately after check_ptr! in each function, matching the established_contact_get_alias precedent at line 108.

suggestion: Pending incoming-request rows fetch attacker-controlled avatar URLs before user consent

packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift (line 119)

sync_contact_profiles (profile.rs:640-650) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow (119-129) feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView → SwiftUI AsyncImage, issuing an outbound HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only validates scheme/length. The Ignore action mutes only AFTER first render. Either suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.

suggestion: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale rows resurrect on cold start

packages/rs-platform-wallet-ffi/src/identity_persistence.rs (line 587)

allocate_contact_profile_rows explicitly continues past entries with profile == None ('Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep'). The Rust→Swift FFI projection carries no removal intent for absences; Swift's upsertDashpayContactProfiles is append/refresh-only; and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile (profile.rs:594-602) flips the in-memory entry to None, but the absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl, defeating on-chain removal. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32] + count), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes on the same callback.

suggestion: rs-sdk-ffi forms a Rust slice over caller-supplied xpub bytes before enforcing the fixed 69-byte contract

packages/rs-sdk-ffi/src/dashpay/contact_request.rs (line 250)

DashSDKContactRequestParams documents extended_public_key as exactly the 69-byte DIP-15 compact xpub, and the underlying Rust SDK validates the length after the callback returns. The C ABI entry points only reject null/zero length (250-255 and 496) and then call std::slice::from_raw_parts(params.extended_public_key, params.extended_public_key_len).to_vec() (~317-319 and again in send_contact_request ~562-565) before any scalar length validation. A stale or buggy foreign caller can therefore make Rust read an arbitrary-length foreign buffer before the validation error path runs — out-of-bounds reads from caller-controlled length cross the FFI boundary into Rust UB. Reject params.extended_public_key_len != 69 at the C ABI boundary in both entry points, before from_raw_parts.

suggestion: Contact-profile checked_at_ms not durably persisted on unchanged refresh — negative-cache backoff does not survive restart

packages/rs-platform-wallet/src/wallet/identity/network/profile.rs (line 588)

apply_fetched_profile always refreshes checked_at_ms = now_ms but returns changed only when the stored profile value differs (equality compares only profile content). sync_contact_profiles calls persister.store only when any_changed is true. A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an In query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel and creates a cold-start fetch storm; a failed earlier store is also not retried because later sweeps see changed = false. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.

suggestion: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop

packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs (line 42)

fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick added in this PR, an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

- [BLOCKING] In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:3471-3487: Wallet wipe PHASE 1 omits identity.contactProfiles — SwiftData fatal can abort user-initiated wipe and leave attacker-controlled DashPay strings on disk
  Re-verified at acd59be2. PHASE 1 pre-deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders, but not identity.contactProfiles. The in-source comment block at 3438-3470 explicitly documents the invariant this loop enforces: SwiftData fatals during save() when a parent delete must null out a non-optional inverse on a child in the same batch, so every cascade-child whose inverse is non-optional must be deleted in its own save() ahead of the parent. PersistentDashpayContactProfile.owner is non-optional (PersistentDashpayContactProfile.swift:109: `public var owner: PersistentIdentity`, doc-commented 'Non-optional: every contact profile exists because of an owner identity. Cascade-deleted from PersistentIdentity.contactProfiles'). sync_contact_profiles (profile.rs:640-650) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, so any wallet whose recurring DashPay sync has cached even one PersistentDashpayContactProfile row — including unsolicited-sender rows — will hit the documented SwiftData fatal at PHASE 2's identity delete (3493-3496), aborting the user-initiated wipe and leaving sender-controlled avatarUrl / displayName / publicMessage strings on disk. The on-device UAT in the latest TODO reported wipe as PASS, but only ran in-app-created identities with no accumulated unsolicited senders — the structural defect remains.
- [BLOCKING] In `packages/rs-platform-wallet/src/wallet/identity/network/loading.rs`:253-263: Imported identity persists derivation breadcrumb only for the MASTER probe key — every signed state transition fails post-import (now confirmed in UAT)
  Re-verified at acd59be2 (lines 253-263 unchanged). load_identity_by_index_inner emits a DIP-9 derivation breadcrumb only for the single key whose hash matched the discovery probe, by calling managed.add_key(pub_key, Some((wallet_id, identity_index, MASTER_KEY_INDEX)), ...) at 259-263. The identity's other on-chain public keys travel via add_identity at 241-246 with no derivation indices, and Swift explicitly clears row.privateKeyKeychainIdentifier for entries whose FFI projection lacks derivation indices (PlatformWalletPersistenceHandler.swift:1584-1597). Document-write flows then intentionally exclude MASTER and select the first HIGH/CRITICAL authentication key — dpns.rs:206-220 enforces [SecurityLevel::HIGH, SecurityLevel::CRITICAL] because DPP rejects MASTER on document-side state transitions, and profile.rs follows the same key-selection contract. For an imported identity whose probe matched the master slot but whose document-signing key is a separate HIGH/CRITICAL slot, the signer is asked to sign with a public key that has no stored or derivable private material, and KeychainSigner returns 'No PersistentPublicKey row matches the supplied public-key bytes'. The new UAT TODO entry ('🐛 BUG (found in UAT 2026-06-19): an IMPORTED identity cannot sign any state transition') is the empirical confirmation. Fix: derive and persist breadcrumbs for every wallet-derived on-chain authentication key the wallet may later select for signing, not just the MASTER probe slot.
- [BLOCKING] In `packages/rs-platform-wallet/src/changeset/core_bridge.rs`:99-128: Sent DashPay payments only advance Pending→Confirmed on TransactionDetected — BlockProcessed updates never trigger confirmation (matches UAT failure)
  confirm_sent_dashpay_payment is invoked only inside the `if let WalletEvent::TransactionDetected { record, .. } = &event` arm at core_bridge.rs:104-127. build_core_changeset (180-223) also persists transaction status updates from WalletEvent::BlockProcessed via the inserted/updated/matured record lists (lines 205-216): 'Updated records (re-confirmation, IS-lock applied to a known mempool tx, etc.) ... the record's content does change though, so re-emit it.' Those records carry advancing context (InBlock / InChainLockedBlock) but the spawn_wallet_event_adapter event handler never re-runs sent-payment confirmation against them. send_payment records the outgoing entry as Pending and there is no periodic sent-payment reconciler in this PR. Result: a self-broadcast tx that is detected pre-confirm fires confirm_sent_dashpay_payment with an unconfirmed record (no-op), then when the tx is mined SPV emits a BlockProcessed `updated` record with InBlock context but the sent-payment row never advances. This matches the UAT failure recorded in docs/dashpay/TODO.md on 2026-06-20: 9 confirmations + InstantSend lock on testnet, ZPERSISTENTTRANSACTION.ZCONTEXT advanced, but ZPERSISTENTDASHPAYPAYMENT.ZSTATUSRAW stayed 0 (Pending) for ~20 min. Fix: invoke confirm_sent_dashpay_payment from the BlockProcessed arm against `inserted` and `updated` records as well, or add a reconciler that walks Pending sent payments and projects against the persisted wallet's current TransactionRecord context.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/established_contact.rs`:156-169: established_contact_get_note leaves *out_note undefined on every early-return path — C ABI invariant violated
  Sibling established_contact_get_alias (102-117) writes `*out_alias = std::ptr::null_mut();` at line 108 immediately after check_ptr!, establishing the module's C-ABI contract that out-params are defined-null on early returns. established_contact_get_note only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound, contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL, reachable from on-chain note content controlled by counterparty) leave *out_note indeterminate across the ABI. A caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. The exported ABI must not depend on caller hygiene — mirror the sibling pattern by writing the null sentinel immediately after pointer validation.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/dashpay_profile.rs`:90-185: DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths
  managed_identity_get_dashpay_profile (90), platform_wallet_get_dashpay_profile (116), and platform_wallet_get_contact_profile (153) only assign *out_profile / *out_has_profile inside the Some/None match arms (101-110, 134-143, 174-183). After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing contact entry) leave both out pointers indeterminate. DashPayProfileFFI owns four *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers. Pre-write `*out_profile = DashPayProfileFFI::empty(); *out_has_profile = false;` immediately after check_ptr! in each function, matching the established_contact_get_alias precedent at line 108.
- [SUGGESTION] In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift`:119-129: Pending incoming-request rows fetch attacker-controlled avatar URLs before user consent
  sync_contact_profiles (profile.rs:640-650) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow (119-129) feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView → SwiftUI AsyncImage, issuing an outbound HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only validates scheme/length. The Ignore action mutes only AFTER first render. Either suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/identity_persistence.rs`:587-621: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale rows resurrect on cold start
  allocate_contact_profile_rows explicitly `continue`s past entries with profile == None ('Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep'). The Rust→Swift FFI projection carries no removal intent for absences; Swift's upsertDashpayContactProfiles is append/refresh-only; and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile (profile.rs:594-602) flips the in-memory entry to None, but the absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl, defeating on-chain removal. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32] + count), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes on the same callback.
- [SUGGESTION] In `packages/rs-sdk-ffi/src/dashpay/contact_request.rs`:250-319: rs-sdk-ffi forms a Rust slice over caller-supplied xpub bytes before enforcing the fixed 69-byte contract
  DashSDKContactRequestParams documents extended_public_key as exactly the 69-byte DIP-15 compact xpub, and the underlying Rust SDK validates the length after the callback returns. The C ABI entry points only reject null/zero length (250-255 and 496) and then call `std::slice::from_raw_parts(params.extended_public_key, params.extended_public_key_len).to_vec()` (~317-319 and again in send_contact_request ~562-565) before any scalar length validation. A stale or buggy foreign caller can therefore make Rust read an arbitrary-length foreign buffer before the validation error path runs — out-of-bounds reads from caller-controlled length cross the FFI boundary into Rust UB. Reject `params.extended_public_key_len != 69` at the C ABI boundary in both entry points, before from_raw_parts.
- [SUGGESTION] In `packages/rs-platform-wallet/src/wallet/identity/network/profile.rs`:588-725: Contact-profile checked_at_ms not durably persisted on unchanged refresh — negative-cache backoff does not survive restart
  apply_fetched_profile always refreshes checked_at_ms = now_ms but returns `changed` only when the stored profile value differs (equality compares only profile content). sync_contact_profiles calls persister.store only when any_changed is true. A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an `In` query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel and creates a cold-start fetch storm; a failed earlier store is also not retried because later sweeps see `changed = false`. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.
- [SUGGESTION] In `packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs`:42-112: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop
  fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick added in this PR, an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.

Inline dry-run could not load the GitHub PR diff because this PR exceeds GitHub's 20,000-line diff limit, so I posted the same verified findings as a top-level review body.

shumkov and others added 3 commits June 20, 2026 16:03
A sent DashPay payment stayed `Pending` forever on-device despite its
transaction reaching full confirmation. The wallet-event adapter ran the
DashPay payment hooks only for `WalletEvent::TransactionDetected`, which
fires only for the first mempool sighting (context `Mempool` /
`InstantSend`) where `is_confirmed()` is false and the sent-payment
confirm hook early-returns. A wallet sees its own broadcast in the
mempool first, so the transaction reaches a confirmed context only when a
block mines it — delivered as `WalletEvent::BlockProcessed` (the record
in `updated`). The bridge consumed `BlockProcessed` for the core
changeset (so the tx row advanced to in-block) but never ran the payment
hooks on those records, so the confirmation never reached the `Sent`
entry.

Route the records carried by `BlockProcessed` (`inserted` + `updated`;
`matured` coinbase excluded) through the same
`record_incoming_dashpay_payments` + `confirm_sent_dashpay_payment` hooks
via a new `dashpay_payment_records` / `run_dashpay_payment_hooks` seam.

The txid representation split between SwiftData tables (payment row =
display-order hex, transaction row = internal-order bytes) is irrelevant
to the Rust match: both the insert (`send_payment`) and the lookup
(confirm path) key by `dashcore::Txid::to_string()`.

Tests would have caught this in CI (red before the `BlockProcessed` arm,
green after):
- block_processed_confirms_sent_payment: end-to-end through the real
  dispatch — a `BlockProcessed` event flips a `Pending` `Sent` entry to
  `Confirmed`. Before fix: stays Pending. After fix: Confirmed.
- dashpay_payment_records_covers_block_processed_inserted_and_updated:
  routing, including matured-exclusion.

Verified on testnet (iPhone 17 Pro sim): the confirm hook fires on the
confirming block and the payment reaches Confirmed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…efresh

The sender-side confirm hook flips a `Sent` payment `Pending -> Confirmed`
in the in-memory model on a Core block event and emits a changeset, but
the Swift changeset/store path does not persist DashPay payments
(`dashpay_payments_overlay` has no FFI persister callback). Payments
reach SwiftData only via the pull-based `refreshDashPayPayments`, which
fired only from `ContactDetailView` (`.task` / `onSent` / manual
Refresh). So a confirmation that arrived while the user watched the
contact screen did not appear until they left and returned or tapped
Refresh.

Refresh payments on each completed DashPay sync pass:
`ContactDetailView.onChange(of: dashPaySyncIsSyncing)` falling-edge ->
`refreshPayments()`, mirroring the sibling `ContactsView` /
`ContactRequestsView` idiom. The 1s poller in `PlatformWalletManager`
mirrors the FFI `isDashPaySyncing()` for the recurring Rust loop too, so
the falling edge fires on every recurring pass.

No automated test: this is a UI-only SwiftUI modifier. Verified on
testnet (iPhone 17 Pro sim): a sent payment auto-flipped to Confirmed in
the contact view with no manual Refresh (Pending at send, Confirmed ~3.5
min later via the recurring sync's falling edge).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Document the root cause (BlockProcessed not routed to the confirm hook,
not the txid representation split), the two-layer fix (Rust routing +
Swift refresh-on-sync), and the 2026-06-20 on-device verification.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@thepastaclaw thepastaclaw 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.

Code Review

Cumulative review at 1a17326. The latest delta (Rust payment-hook routing + Swift refresh-on-sync + docs) resolves prior finding #3 — BlockProcessed inserted/updated records now drive the DashPay payment confirmation hook, with regression tests. Of the remaining 9 prior findings, all are STILL VALID at HEAD and carry forward: two blockers (SwiftData wipe loop still omits identity.contactProfiles despite the in-source non-optional-inverse invariant; load_identity_by_index_inner still emits a derivation breadcrumb only for the MASTER probe key — the UAT-confirmed imported-identity signing failure) plus seven suggestions across FFI out-param hygiene, pre-consent avatar tracking, absence-as-delete projection, caller-controlled xpub slice formation, profile checked_at_ms persistence, and paginated retrieve-all budget. No new defects in the delta itself.

🔴 2 blocking | 🟡 7 suggestion(s)

9 additional finding(s)

blocking: Wallet wipe PHASE 1 omits identity.contactProfiles — SwiftData fatal can abort the wipe and leave attacker-controlled DashPay strings on disk

packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift (line 3471)

Verified at HEAD. PHASE 1 pre-deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders — but not identity.contactProfiles. The in-source comment block at 3438-3470 documents the exact invariant the loop enforces: SwiftData fatals during save() when a parent delete must null out a non-optional inverse on a child in the same batch, so every cascade-child whose inverse is non-optional must be deleted in its own save() ahead of the parent. PersistentDashpayContactProfile.owner is non-optional and cascade-deleted from PersistentIdentity.contactProfiles — exactly the shape the comment names. sync_contact_profiles (profile.rs) includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, so any wallet whose recurring DashPay sync has cached even one PersistentDashpayContactProfile row (including unsolicited-sender rows) will hit the documented SwiftData fatal during PHASE 2's identity delete (3493-3496), aborting the user-initiated wipe and leaving sender-controlled avatarUrl/displayName/publicMessage strings on disk. A user wiping precisely to scrub a stalker's footprint retains it.

                    for identity in identitiesToDelete {
                        for name in Array(identity.dpnsNames) {
                            backgroundContext.delete(name)
                        }
                        if let profile = identity.dashpayProfile {
                            backgroundContext.delete(profile)
                        }
                        for contactProfile in Array(identity.contactProfiles) {
                            backgroundContext.delete(contactProfile)
                        }
                        for cr in Array(identity.contactRequests) {
                            backgroundContext.delete(cr)
                        }
                        for payment in Array(identity.dashpayPayments) {
                            backgroundContext.delete(payment)
                        }
                        for ignored in Array(identity.dashpayIgnoredSenders) {
                            backgroundContext.delete(ignored)
                        }
                    }
blocking: Imported identity persists DIP-9 derivation breadcrumb only for the MASTER probe key — HIGH/CRITICAL-signed state transitions fail post-import (UAT-confirmed)

packages/rs-platform-wallet/src/wallet/identity/network/loading.rs (line 253)

Verified at HEAD. load_identity_by_index_inner emits a derivation breadcrumb only for the single key whose hash matched the discovery probe, by calling managed.add_key(pub_key, Some((wallet_id, identity_index, MASTER_KEY_INDEX)), ...). The identity's other on-chain public keys travel via add_identity at 241-247 with no derivation indices, and Swift explicitly clears row.privateKeyKeychainIdentifier for entries whose FFI projection lacks them (PlatformWalletPersistenceHandler.swift:1584-1597). Document-side signing flows intentionally exclude MASTER and select the first HIGH/CRITICAL authentication key — dpns.rs:206-220 enforces [SecurityLevel::HIGH, SecurityLevel::CRITICAL] because DPP rejects MASTER on document-side state transitions, and profile.rs follows the same contract. For an imported identity whose probe matched the master slot but whose document-signing key is a separate HIGH/CRITICAL slot, the signer is asked to sign with a public key that has no stored or derivable private material, and KeychainSigner returns 'No PersistentPublicKey row matches the supplied public-key bytes' — the symptom recorded in docs/dashpay/TODO.md ('BUG (found in UAT 2026-06-19): an IMPORTED identity cannot sign any state transition'). Fix: derive and persist breadcrumbs for every wallet-derived on-chain authentication key the wallet may later select for signing, not just the MASTER probe slot.

suggestion: established_contact_get_note leaves *out_note undefined on every early-return path — C ABI invariant violated

packages/rs-platform-wallet-ffi/src/established_contact.rs (line 156)

Verified at HEAD. Sibling established_contact_get_alias (102-117) writes *out_alias = std::ptr::null_mut(); at line 108 immediately after check_ptr!, establishing the module's C-ABI contract that out-params are defined-null on early returns. established_contact_get_note (156-169) only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound, contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL — reachable from counterparty-controlled note content) leave *out_note indeterminate across the ABI. A caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. Mirror the sibling pattern.

#[no_mangle]
pub unsafe extern "C" fn established_contact_get_note(
    contact_handle: Handle,
    out_note: *mut *mut std::os::raw::c_char,
) -> PlatformWalletFFIResult {
    check_ptr!(out_note);
    *out_note = std::ptr::null_mut();

    let option =
        ESTABLISHED_CONTACT_STORAGE.with_item(contact_handle, |contact| contact.note.clone());
    let option = unwrap_option_or_return!(option);
    let note = unwrap_option_or_return!(option);
    let c_str = unwrap_result_or_return!(std::ffi::CString::new(note));
    unsafe { *out_note = c_str.into_raw() };
    PlatformWalletFFIResult::ok()
}
suggestion: DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths — enables invalid-free across the ABI

packages/rs-platform-wallet-ffi/src/dashpay_profile.rs (line 90)

Verified at HEAD. managed_identity_get_dashpay_profile (90), platform_wallet_get_dashpay_profile (116), and platform_wallet_get_contact_profile (153) only assign *out_profile / *out_has_profile inside the Some/None match arms. After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input at 125, 163-164) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing contact entry) leave both out pointers indeterminate. DashPayProfileFFI owns three *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free). Pre-write *out_profile = DashPayProfileFFI::empty(); *out_has_profile = false; immediately after check_ptr! in each function, matching the established_contact_get_alias precedent at line 108.

suggestion: Pending incoming-request rows fetch attacker-controlled avatar URLs before user consent

packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift (line 119)

Verified at HEAD. sync_contact_profiles (profile.rs) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow (119-129) feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView → SwiftUI AsyncImage, issuing an HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only validates scheme/length. The Ignore action mutes only AFTER first render. Either suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.

suggestion: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale rows resurrect on cold start

packages/rs-platform-wallet-ffi/src/identity_persistence.rs (line 587)

Verified at HEAD. allocate_contact_profile_rows explicitly continues past entries with profile == None at 590-592 ('Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep'). The Rust→Swift FFI projection carries no removal intent for absences; Swift's upsertDashpayContactProfiles is append/refresh-only; and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile flips the in-memory entry to None, but the absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl, defeating on-chain removal. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32] + count), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes on the same callback.

suggestion: rs-sdk-ffi forms a Rust slice over caller-supplied xpub bytes before enforcing the fixed 69-byte contract

packages/rs-sdk-ffi/src/dashpay/contact_request.rs (line 250)

Verified at HEAD. DashSDKContactRequestParams documents extended_public_key as exactly the 69-byte DIP-15 compact xpub, and the underlying Rust SDK validates the length after the callback returns. Both C ABI entry points (create_contact_request at 250-255/317-319 and send_contact_request mirror at ~496-565) only reject is_null || _len == 0 and then call std::slice::from_raw_parts(params.extended_public_key, params.extended_public_key_len).to_vec() before any scalar length validation. A stale or buggy foreign caller can therefore make Rust read an arbitrary-length foreign buffer before the inner SDK's length validation runs — caller-controlled length drives an out-of-bounds read across the FFI boundary into Rust UB. Reject params.extended_public_key_len != 69 at the C ABI boundary in both entry points, before from_raw_parts.

suggestion: Contact-profile checked_at_ms not durably persisted on unchanged refresh — negative-cache backoff does not survive restart

packages/rs-platform-wallet/src/wallet/identity/network/profile.rs (line 588)

Verified at HEAD. apply_fetched_profile always refreshes checked_at_ms = now_ms but returns changed only when the stored profile value differs (equality compares only profile content). sync_contact_profiles calls persister.store only when any_changed is true. A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an In query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel (restart re-issues per-victim GETs to known-stable hosts) and creates a cold-start fetch storm; a failed earlier store is also not retried because later sweeps see changed = false. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.

suggestion: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop

packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs (line 42)

Verified at HEAD. fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick added in this PR, an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

- [BLOCKING] In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:3471-3487: Wallet wipe PHASE 1 omits identity.contactProfiles — SwiftData fatal can abort the wipe and leave attacker-controlled DashPay strings on disk
  Verified at HEAD. PHASE 1 pre-deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders — but not identity.contactProfiles. The in-source comment block at 3438-3470 documents the exact invariant the loop enforces: SwiftData fatals during save() when a parent delete must null out a non-optional inverse on a child in the same batch, so every cascade-child whose inverse is non-optional must be deleted in its own save() ahead of the parent. PersistentDashpayContactProfile.owner is non-optional and cascade-deleted from PersistentIdentity.contactProfiles — exactly the shape the comment names. sync_contact_profiles (profile.rs) includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, so any wallet whose recurring DashPay sync has cached even one PersistentDashpayContactProfile row (including unsolicited-sender rows) will hit the documented SwiftData fatal during PHASE 2's identity delete (3493-3496), aborting the user-initiated wipe and leaving sender-controlled avatarUrl/displayName/publicMessage strings on disk. A user wiping precisely to scrub a stalker's footprint retains it.
- [BLOCKING] In `packages/rs-platform-wallet/src/wallet/identity/network/loading.rs`:253-263: Imported identity persists DIP-9 derivation breadcrumb only for the MASTER probe key — HIGH/CRITICAL-signed state transitions fail post-import (UAT-confirmed)
  Verified at HEAD. load_identity_by_index_inner emits a derivation breadcrumb only for the single key whose hash matched the discovery probe, by calling managed.add_key(pub_key, Some((wallet_id, identity_index, MASTER_KEY_INDEX)), ...). The identity's other on-chain public keys travel via add_identity at 241-247 with no derivation indices, and Swift explicitly clears row.privateKeyKeychainIdentifier for entries whose FFI projection lacks them (PlatformWalletPersistenceHandler.swift:1584-1597). Document-side signing flows intentionally exclude MASTER and select the first HIGH/CRITICAL authentication key — dpns.rs:206-220 enforces [SecurityLevel::HIGH, SecurityLevel::CRITICAL] because DPP rejects MASTER on document-side state transitions, and profile.rs follows the same contract. For an imported identity whose probe matched the master slot but whose document-signing key is a separate HIGH/CRITICAL slot, the signer is asked to sign with a public key that has no stored or derivable private material, and KeychainSigner returns 'No PersistentPublicKey row matches the supplied public-key bytes' — the symptom recorded in docs/dashpay/TODO.md ('BUG (found in UAT 2026-06-19): an IMPORTED identity cannot sign any state transition'). Fix: derive and persist breadcrumbs for every wallet-derived on-chain authentication key the wallet may later select for signing, not just the MASTER probe slot.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/established_contact.rs`:156-169: established_contact_get_note leaves *out_note undefined on every early-return path — C ABI invariant violated
  Verified at HEAD. Sibling established_contact_get_alias (102-117) writes `*out_alias = std::ptr::null_mut();` at line 108 immediately after check_ptr!, establishing the module's C-ABI contract that out-params are defined-null on early returns. established_contact_get_note (156-169) only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound, contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL — reachable from counterparty-controlled note content) leave *out_note indeterminate across the ABI. A caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. Mirror the sibling pattern.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/dashpay_profile.rs`:90-185: DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths — enables invalid-free across the ABI
  Verified at HEAD. managed_identity_get_dashpay_profile (90), platform_wallet_get_dashpay_profile (116), and platform_wallet_get_contact_profile (153) only assign *out_profile / *out_has_profile inside the Some/None match arms. After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input at 125, 163-164) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing contact entry) leave both out pointers indeterminate. DashPayProfileFFI owns three *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free). Pre-write `*out_profile = DashPayProfileFFI::empty(); *out_has_profile = false;` immediately after check_ptr! in each function, matching the established_contact_get_alias precedent at line 108.
- [SUGGESTION] In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift`:119-129: Pending incoming-request rows fetch attacker-controlled avatar URLs before user consent
  Verified at HEAD. sync_contact_profiles (profile.rs) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow (119-129) feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView → SwiftUI AsyncImage, issuing an HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only validates scheme/length. The Ignore action mutes only AFTER first render. Either suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/identity_persistence.rs`:587-621: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale rows resurrect on cold start
  Verified at HEAD. allocate_contact_profile_rows explicitly `continue`s past entries with profile == None at 590-592 ('Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep'). The Rust→Swift FFI projection carries no removal intent for absences; Swift's upsertDashpayContactProfiles is append/refresh-only; and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile flips the in-memory entry to None, but the absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl, defeating on-chain removal. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32] + count), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes on the same callback.
- [SUGGESTION] In `packages/rs-sdk-ffi/src/dashpay/contact_request.rs`:250-319: rs-sdk-ffi forms a Rust slice over caller-supplied xpub bytes before enforcing the fixed 69-byte contract
  Verified at HEAD. DashSDKContactRequestParams documents extended_public_key as exactly the 69-byte DIP-15 compact xpub, and the underlying Rust SDK validates the length after the callback returns. Both C ABI entry points (create_contact_request at 250-255/317-319 and send_contact_request mirror at ~496-565) only reject `is_null || _len == 0` and then call `std::slice::from_raw_parts(params.extended_public_key, params.extended_public_key_len).to_vec()` before any scalar length validation. A stale or buggy foreign caller can therefore make Rust read an arbitrary-length foreign buffer before the inner SDK's length validation runs — caller-controlled length drives an out-of-bounds read across the FFI boundary into Rust UB. Reject `params.extended_public_key_len != 69` at the C ABI boundary in both entry points, before from_raw_parts.
- [SUGGESTION] In `packages/rs-platform-wallet/src/wallet/identity/network/profile.rs`:588-725: Contact-profile checked_at_ms not durably persisted on unchanged refresh — negative-cache backoff does not survive restart
  Verified at HEAD. apply_fetched_profile always refreshes checked_at_ms = now_ms but returns `changed` only when the stored profile value differs (equality compares only profile content). sync_contact_profiles calls persister.store only when any_changed is true. A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an `In` query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel (restart re-issues per-victim GETs to known-stable hosts) and creates a cold-start fetch storm; a failed earlier store is also not retried because later sweeps see `changed = false`. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.
- [SUGGESTION] In `packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs`:42-112: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop
  Verified at HEAD. fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick added in this PR, an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.

Inline dry-run could not load the GitHub PR diff because this PR exceeds GitHub's 20,000-line diff limit, so I posted the same verified findings as a top-level review body.

shumkov and others added 3 commits June 20, 2026 16:27
…review

Follow-up hardening from the multi-agent review of the sent-payment
confirm fix. No change to the confirmed happy path.

- dashpay_payment_records: make the `match` exhaustive (drop the `_`
  arm). A new upstream `WalletEvent` variant that carries transaction
  records now fails to compile here instead of being silently dropped —
  routing only a subset of record-bearing events is exactly the gap that
  left sent payments stuck Pending.
- carries_payment_records: cheap `matches!` predicate instead of
  allocating and discarding the record Vec on every event.
- block_processed_confirms_sent_payment: add idempotency (a repeated
  block-processing round is a no-op) and matured-exclusion (a confirmed
  record in the `matured` bucket must not confirm a payment) assertions;
  make the test doc-comment timeless.

281/281 platform-wallet lib tests green, clippy clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
From the multi-agent review. `refreshPayments()` is now triggered from
four places (`.task` on appear, `onSent`, the DashPay-sync `onChange`
falling edge, and the manual Refresh button) and had no re-entrancy
guard, so close-together triggers spawned redundant FFI-read +
SwiftData-upsert passes and could flicker the spinner. Add
`guard !isRefreshingPayments else { return }` so overlapping triggers
collapse into one in-flight pass (the upsert is idempotent, so the result
was already correct — this just removes wasted work).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@thepastaclaw thepastaclaw 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.

Code Review

Cumulative review at 40169ae. The latest 3-commit delta (exhaustive WalletEvent match + non-allocating carries_payment_records, hardened BlockProcessed test, Swift refreshPayments re-entrancy guard, docs) introduces no new defects in the changes themselves. All 9 prior findings from the 1a17326 review were verified against HEAD and remain STILL VALID — two carried-forward blockers (SwiftData wallet-wipe PHASE 1 omits identity.contactProfiles despite the in-source non-optional-inverse invariant comment; load_identity_by_index_inner attaches a derivation breadcrumb only to the MASTER probe key, breaking imported-identity HIGH/CRITICAL signing per UAT) plus seven suggestion-level FFI/ABI/persistence/perf issues. Codex-general additionally flagged a real gap: sent payments lack a recurring recovery path if the live confirmation hook is missed (Lagged events are dropped); kept as a suggestion. Review action: REQUEST_CHANGES due to the two unresolved in-scope blockers.

🔴 2 blocking | 🟡 8 suggestion(s)

10 additional finding(s)

blocking: Wallet wipe PHASE 1 omits identity.contactProfiles — SwiftData fatal can abort the wipe and leave sender-controlled DashPay strings on disk

packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift (line 3471)

Verified at HEAD 40169ae. PHASE 1 pre-deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders, but not identity.contactProfiles. The in-source comment block at 3438-3470 documents the exact invariant the loop is built to enforce: SwiftData fatals during save() when a parent delete must null out a non-optional inverse on a child in the same batch, so every cascade-child whose inverse to the parent is non-optional must be deleted in its own save() ahead of the parent. PersistentDashpayContactProfile.owner is non-optional and cascade-deleted from PersistentIdentity.contactProfiles — exactly the shape the comment names. sync_contact_profiles (profile.rs:637-650) includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, so any wallet whose recurring DashPay sync has cached even one PersistentDashpayContactProfile row (including unsolicited-sender rows whose displayName/publicMessage/avatarUrl are sender-controlled) will hit the documented SwiftData fatal at PHASE 2's identity delete (3493-3496). The fatal aborts the user-initiated wipe and leaves those sender-controlled strings on disk — directly defeating a user wiping precisely to scrub a stalker's footprint.

                    for identity in identitiesToDelete {
                        for name in Array(identity.dpnsNames) {
                            backgroundContext.delete(name)
                        }
                        if let profile = identity.dashpayProfile {
                            backgroundContext.delete(profile)
                        }
                        for contactProfile in Array(identity.contactProfiles) {
                            backgroundContext.delete(contactProfile)
                        }
                        for cr in Array(identity.contactRequests) {
                            backgroundContext.delete(cr)
                        }
                        for payment in Array(identity.dashpayPayments) {
                            backgroundContext.delete(payment)
                        }
                        for ignored in Array(identity.dashpayIgnoredSenders) {
                            backgroundContext.delete(ignored)
                        }
                    }
blocking: Imported identity persists DIP-9 derivation breadcrumb only for the MASTER probe key — HIGH/CRITICAL-signed state transitions fail post-import

packages/rs-platform-wallet/src/wallet/identity/network/loading.rs (line 253)

Verified at HEAD 40169ae (lines 253-263 unchanged in the latest delta). load_identity_by_index_inner emits a DIP-9 derivation breadcrumb only for the single on-chain key whose hash matched the discovery probe, by calling managed.add_key(pub_key, Some((wallet_id, identity_index, MASTER_KEY_INDEX)), ...). The identity's other on-chain public keys travel via add_identity at 241-247 with no derivation indices, and Swift clears row.privateKeyKeychainIdentifier for entries whose FFI projection lacks derivation metadata (PlatformWalletPersistenceHandler.swift:1584-1597). Document-side signing flows intentionally exclude MASTER and select the first HIGH/CRITICAL authentication key (dpns.rs:206-220 enforces [SecurityLevel::HIGH, SecurityLevel::CRITICAL] because DPP rejects MASTER on document-side state transitions; profile.rs follows the same contract). For an imported identity whose probe matched the master slot but whose document-signing key is a separate HIGH/CRITICAL slot, the signer is asked to sign with a public key that has no stored or derivable private material, and KeychainSigner returns the symptom recorded in docs/dashpay/TODO.md: 'an IMPORTED identity cannot sign any state transition'. Fix at the boundary: derive and persist breadcrumbs for every wallet-derived on-chain authentication key the wallet may later select for signing, not just the MASTER probe slot, before emitting the IdentityChangeSet that crosses the FFI.

suggestion: established_contact_get_note leaves *out_note undefined on every early-return path — C ABI contract violated relative to sibling

packages/rs-platform-wallet-ffi/src/established_contact.rs (line 156)

Sibling established_contact_get_alias (102-117) writes *out_alias = std::ptr::null_mut(); immediately after check_ptr!, establishing the module's C-ABI contract that out-params are defined-null on early returns. established_contact_get_note only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound, contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL — reachable from counterparty-controlled note content saved via established_contact_set_note) leave *out_note indeterminate across the ABI. A caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. The exported ABI should not depend on caller hygiene — mirror the sibling pattern.

#[no_mangle]
pub unsafe extern "C" fn established_contact_get_note(
    contact_handle: Handle,
    out_note: *mut *mut std::os::raw::c_char,
) -> PlatformWalletFFIResult {
    check_ptr!(out_note);
    *out_note = std::ptr::null_mut();

    let option =
        ESTABLISHED_CONTACT_STORAGE.with_item(contact_handle, |contact| contact.note.clone());
    let option = unwrap_option_or_return!(option);
    let note = unwrap_option_or_return!(option);
    let c_str = unwrap_result_or_return!(std::ffi::CString::new(note));
    unsafe { *out_note = c_str.into_raw() };
    PlatformWalletFFIResult::ok()
}
suggestion: DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths — enables invalid-free across the ABI

packages/rs-platform-wallet-ffi/src/dashpay_profile.rs (line 90)

managed_identity_get_dashpay_profile (90), platform_wallet_get_dashpay_profile (116), and platform_wallet_get_contact_profile (153) only assign *out_profile / *out_has_profile inside the Some/None match arms. After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input at 125, 163-164) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing contact entry) leave both out-pointers indeterminate. DashPayProfileFFI owns three *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free across the ABI). Pre-write *out_profile = DashPayProfileFFI::empty(); *out_has_profile = false; immediately after check_ptr! in each function, matching the established_contact_get_alias precedent and the explicit empty-construction already used in the None match arms.

suggestion: Pending incoming-request rows fetch attacker-controlled avatar URLs before user consent

packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift (line 119)

sync_contact_profiles (profile.rs:637-650) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView → SwiftUI AsyncImage, issuing an outbound HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only validates scheme/length. The Ignore action mutes only AFTER first render. Either suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.

suggestion: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale rows resurrect on cold start

packages/rs-platform-wallet-ffi/src/identity_persistence.rs (line 587)

allocate_contact_profile_rows explicitly continues past entries with profile == None at 590-592 ('Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep'). The Rust→Swift FFI projection carries no removal intent for absences; Swift's upsertDashpayContactProfiles is append/refresh-only; and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile (profile.rs:588-603) flips the in-memory entry to None, but the absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl, defeating on-chain removal. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32] + count), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes on the same callback.

suggestion: rs-sdk-ffi forms a Rust slice over caller-supplied xpub bytes before enforcing the fixed 69-byte contract

packages/rs-sdk-ffi/src/dashpay/contact_request.rs (line 250)

DashSDKContactRequestParams documents extended_public_key as exactly the 69-byte DIP-15 compact xpub, and the underlying Rust SDK validates the length after the callback returns. Both C ABI entry points (create_contact_request at 250-255/317-319 and the send_contact_request mirror) only reject is_null || _len == 0 and then call std::slice::from_raw_parts(params.extended_public_key, params.extended_public_key_len).to_vec() before any scalar length validation. A stale or buggy foreign caller that supplies a length != 69 makes Rust read an arbitrary-length foreign buffer before the inner SDK's length validation error path runs — caller-controlled length drives an out-of-bounds read across the FFI boundary into Rust UB. Reject params.extended_public_key_len != 69 at the C ABI boundary in both entry points, before from_raw_parts.

suggestion: Contact-profile checked_at_ms not durably persisted on unchanged refresh — negative-cache backoff does not survive restart

packages/rs-platform-wallet/src/wallet/identity/network/profile.rs (line 588)

apply_fetched_profile (588-603) always refreshes checked_at_ms = now_ms but returns changed only when the stored profile value differs (line 594 equality compares only profile content). sync_contact_profiles calls persister.store only when any_changed is true (718-725). A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires across the Rust→Swift boundary. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an In query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel (restart re-issues per-victim GETs to known-stable hosts) and creates a cold-start fetch storm; a failed earlier store is also not retried because later sweeps see changed = false. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.

suggestion: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop

packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs (line 42)

fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick added in this PR, an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.

suggestion: Sent payments have no recurring recovery path if the live confirmation hook is missed

packages/rs-platform-wallet/src/wallet/identity/network/dashpay_sync.rs (line 72)

Verified at HEAD: the DashPay sweep runs sync_contact_profiles, sync_contact_infos, and reconcile_incoming_payments, but nothing reconciles Sent entries. Sent entries start as Pending in send_payment and are advanced only by confirm_sent_dashpay_payment when a live wallet event carrying a confirmed TransactionRecord reaches run_dashpay_payment_hooks. The broadcast adapter explicitly logs and drops RecvError::Lagged, and a hook persistence failure relies on a future detection that may never arrive for an already-confirmed tx. Unlike incoming payments, the next dashpay_sync pass cannot inspect stored transaction records and flip Pending Sent entries whose txid is already confirmed, so a missed event leaves the UI permanently Pending until some unrelated re-detection occurs. Consider adding a Sent reconciliation pass that scans Pending sent entries against stored transaction records on each sweep, symmetric with reconcile_incoming_payments.

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

- [BLOCKING] In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:3471-3487: Wallet wipe PHASE 1 omits identity.contactProfiles — SwiftData fatal can abort the wipe and leave sender-controlled DashPay strings on disk
  Verified at HEAD 40169ae156. PHASE 1 pre-deletes `dpnsNames`, `dashpayProfile`, `contactRequests`, `dashpayPayments`, and `dashpayIgnoredSenders`, but not `identity.contactProfiles`. The in-source comment block at 3438-3470 documents the exact invariant the loop is built to enforce: SwiftData fatals during `save()` when a parent delete must null out a non-optional inverse on a child in the same batch, so every cascade-child whose inverse to the parent is non-optional must be deleted in its own `save()` ahead of the parent. `PersistentDashpayContactProfile.owner` is non-optional and cascade-deleted from `PersistentIdentity.contactProfiles` — exactly the shape the comment names. `sync_contact_profiles` (profile.rs:637-650) includes `managed.incoming_contact_requests.keys()` in the per-owner fetch plan, so any wallet whose recurring DashPay sync has cached even one `PersistentDashpayContactProfile` row (including unsolicited-sender rows whose `displayName`/`publicMessage`/`avatarUrl` are sender-controlled) will hit the documented SwiftData fatal at PHASE 2's identity delete (3493-3496). The fatal aborts the user-initiated wipe and leaves those sender-controlled strings on disk — directly defeating a user wiping precisely to scrub a stalker's footprint.
- [BLOCKING] In `packages/rs-platform-wallet/src/wallet/identity/network/loading.rs`:253-263: Imported identity persists DIP-9 derivation breadcrumb only for the MASTER probe key — HIGH/CRITICAL-signed state transitions fail post-import
  Verified at HEAD 40169ae156 (lines 253-263 unchanged in the latest delta). `load_identity_by_index_inner` emits a DIP-9 derivation breadcrumb only for the single on-chain key whose hash matched the discovery probe, by calling `managed.add_key(pub_key, Some((wallet_id, identity_index, MASTER_KEY_INDEX)), ...)`. The identity's other on-chain public keys travel via `add_identity` at 241-247 with no derivation indices, and Swift clears `row.privateKeyKeychainIdentifier` for entries whose FFI projection lacks derivation metadata (PlatformWalletPersistenceHandler.swift:1584-1597). Document-side signing flows intentionally exclude MASTER and select the first HIGH/CRITICAL authentication key (dpns.rs:206-220 enforces `[SecurityLevel::HIGH, SecurityLevel::CRITICAL]` because DPP rejects MASTER on document-side state transitions; profile.rs follows the same contract). For an imported identity whose probe matched the master slot but whose document-signing key is a separate HIGH/CRITICAL slot, the signer is asked to sign with a public key that has no stored or derivable private material, and `KeychainSigner` returns the symptom recorded in docs/dashpay/TODO.md: 'an IMPORTED identity cannot sign any state transition'. Fix at the boundary: derive and persist breadcrumbs for every wallet-derived on-chain authentication key the wallet may later select for signing, not just the MASTER probe slot, before emitting the `IdentityChangeSet` that crosses the FFI.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/established_contact.rs`:156-169: established_contact_get_note leaves *out_note undefined on every early-return path — C ABI contract violated relative to sibling
  Sibling `established_contact_get_alias` (102-117) writes `*out_alias = std::ptr::null_mut();` immediately after `check_ptr!`, establishing the module's C-ABI contract that out-params are defined-null on early returns. `established_contact_get_note` only calls `check_ptr!(out_note)` and skips the pre-null write. Early returns from `unwrap_option_or_return!` (storage NotFound, `contact.note == None`) and `unwrap_result_or_return!` (CString::new failure on interior NUL — reachable from counterparty-controlled note content saved via `established_contact_set_note`) leave `*out_note` indeterminate across the ABI. A caller that doesn't pre-zero the slot can read a stale pointer or pass it to `platform_wallet_string_free`, risking invalid-free or double-free. The exported ABI should not depend on caller hygiene — mirror the sibling pattern.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/dashpay_profile.rs`:90-185: DashPay profile reader trio leaves *out_profile / *out_has_profile undefined on early-return paths — enables invalid-free across the ABI
  `managed_identity_get_dashpay_profile` (90), `platform_wallet_get_dashpay_profile` (116), and `platform_wallet_get_contact_profile` (153) only assign `*out_profile` / `*out_has_profile` inside the Some/None match arms. After `check_ptr!`, early returns from `unwrap_result_or_return!(read_identifier(..))` (invalid 32-byte input at 125, 163-164) and `unwrap_option_or_return!` (handle NotFound, missing managed identity, missing contact entry) leave both out-pointers indeterminate. `DashPayProfileFFI` owns three `*mut c_char` fields released by `dashpay_profile_ffi_free` — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free across the ABI). Pre-write `*out_profile = DashPayProfileFFI::empty(); *out_has_profile = false;` immediately after `check_ptr!` in each function, matching the `established_contact_get_alias` precedent and the explicit empty-construction already used in the None match arms.
- [SUGGESTION] In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift`:119-129: Pending incoming-request rows fetch attacker-controlled avatar URLs before user consent
  `sync_contact_profiles` (profile.rs:637-650) explicitly includes `managed.incoming_contact_requests.keys()` in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. `IncomingRequestRow` feeds `cachedProfile(row.contactIdentityId)?.avatarUrl` into `DashPayAvatarView → SwiftUI AsyncImage`, issuing an outbound HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's `PersistentDashpayContactProfile` SwiftData persistence the channel survives restart; Rust-side `is_valid_avatar_url` only validates scheme/length. The Ignore action mutes only AFTER first render. Either suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip `avatarUrl` from the Rust→Swift projection until the sender becomes an established contact.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/identity_persistence.rs`:587-621: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale rows resurrect on cold start
  `allocate_contact_profile_rows` explicitly `continue`s past entries with `profile == None` at 590-592 ('Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep'). The Rust→Swift FFI projection carries no removal intent for absences; Swift's `upsertDashpayContactProfiles` is append/refresh-only; and `ContactProfileRestoreEntryFFI` rehydrates every persisted row as `ContactProfileEntry { profile: Some(..) }`. When a contact removes their on-chain `dashpay.profile`, `apply_fetched_profile` (profile.rs:588-603) flips the in-memory entry to None, but the absence is dropped at the FFI projection — the stale `PersistentDashpayContactProfile` row survives on disk. On cold start the cache rehydrates as `Some(stale_profile)` and the UI re-issues GETs to the previously attacker-controlled `avatarUrl`, defeating on-chain removal. Project absences as an explicit delete intent across the boundary (e.g. `removed_contact_profile_ids: *const [u8;32] + count`), mirroring the `ContactIgnoredSenderFFI` removal-set shape this PR already establishes on the same callback.
- [SUGGESTION] In `packages/rs-sdk-ffi/src/dashpay/contact_request.rs`:250-319: rs-sdk-ffi forms a Rust slice over caller-supplied xpub bytes before enforcing the fixed 69-byte contract
  `DashSDKContactRequestParams` documents `extended_public_key` as exactly the 69-byte DIP-15 compact xpub, and the underlying Rust SDK validates the length after the callback returns. Both C ABI entry points (`create_contact_request` at 250-255/317-319 and the `send_contact_request` mirror) only reject `is_null || _len == 0` and then call `std::slice::from_raw_parts(params.extended_public_key, params.extended_public_key_len).to_vec()` before any scalar length validation. A stale or buggy foreign caller that supplies a length != 69 makes Rust read an arbitrary-length foreign buffer before the inner SDK's length validation error path runs — caller-controlled length drives an out-of-bounds read across the FFI boundary into Rust UB. Reject `params.extended_public_key_len != 69` at the C ABI boundary in both entry points, before `from_raw_parts`.
- [SUGGESTION] In `packages/rs-platform-wallet/src/wallet/identity/network/profile.rs`:588-725: Contact-profile checked_at_ms not durably persisted on unchanged refresh — negative-cache backoff does not survive restart
  `apply_fetched_profile` (588-603) always refreshes `checked_at_ms = now_ms` but returns `changed` only when the stored profile value differs (line 594 equality compares only profile content). `sync_contact_profiles` calls `persister.store` only when `any_changed` is true (718-725). A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires across the Rust→Swift boundary. After cold start, restored rows carry stale `checked_at_ms`, `should_fetch_profile` immediately re-issues an `In` query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel (restart re-issues per-victim GETs to known-stable hosts) and creates a cold-start fetch storm; a failed earlier store is also not retried because later sweeps see `changed = false`. Return a separate `needs_persist` signal from `apply_fetched_profile` for timestamp-only refreshes, with coarse coalescing if write-amp matters.
- [SUGGESTION] In `packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs`:42-112: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop
  `fetch_contact_requests_paginated` drains every matching document at `CONTACT_REQUEST_PAGE_SIZE` per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any `after_created_at == None` path it walks the entire history in one call. `unignore_sender` resets `high_water_received_ms` to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring `DashPaySyncManager` tick added in this PR, an attacker who spams `contactRequest` documents (varying `accountReference` to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.
- [SUGGESTION] In `packages/rs-platform-wallet/src/wallet/identity/network/dashpay_sync.rs`:72-90: Sent payments have no recurring recovery path if the live confirmation hook is missed
  Verified at HEAD: the DashPay sweep runs `sync_contact_profiles`, `sync_contact_infos`, and `reconcile_incoming_payments`, but nothing reconciles Sent entries. Sent entries start as Pending in `send_payment` and are advanced only by `confirm_sent_dashpay_payment` when a live wallet event carrying a confirmed `TransactionRecord` reaches `run_dashpay_payment_hooks`. The broadcast adapter explicitly logs and drops `RecvError::Lagged`, and a hook persistence failure relies on a future detection that may never arrive for an already-confirmed tx. Unlike incoming payments, the next dashpay_sync pass cannot inspect stored transaction records and flip Pending Sent entries whose txid is already confirmed, so a missed event leaves the UI permanently Pending until some unrelated re-detection occurs. Consider adding a Sent reconciliation pass that scans Pending sent entries against stored transaction records on each sweep, symmetric with `reconcile_incoming_payments`.

Inline dry-run could not load the GitHub PR diff because this PR exceeds GitHub's 20,000-line diff limit, so I posted the same verified findings as a top-level review body.

shumkov and others added 3 commits June 20, 2026 16:53
…for DashPay

Two robustness follow-ups from the multi-agent review of the sent-payment
confirm fix, both about when a Sent payment reaches Confirmed.

InstantSend counts as final for DashPay display. An IS-locked-but-unmined
sent payment previously showed Pending until a block mined it, because the
confirm gate accepted only InBlock / InChainLockedBlock. Now:
- confirm_sent_dashpay_payment also flips on InstantSend context (the
  direct-IS-sighting TransactionDetected path), and
- WalletEvent::TransactionInstantLocked (an IS lock applied to a
  previously-seen tx -- no record, just a txid) is routed to a new
  confirm_sent_dashpay_payment_by_txid path.
So a sent payment shows Confirmed on the IS lock, seconds after broadcast,
without waiting for the surrounding block.

Sent-payment reconcile recovers a missed confirmation. The live confirm
path is a single event; if it is missed (a lagged wallet-event broadcast,
or a relaunch after the tx confirmed but before the flip was captured) the
entry would otherwise stay Pending forever -- received payments self-heal
from receival-account UTXOs, sent payments had no equivalent. Add
IdentityWallet::reconcile_sent_payments (a local-only dashpay_sync step):
for each Pending Sent entry, consult the persisted core tx record
(get_core_tx_record) and flip it when the tx is mined or IS-locked.

Tests:
- instant_send_lock_confirms_sent_payment (TransactionInstantLocked event)
- instant_send_context_record_confirms_sent_payment (IS-context record)
- instant_locked_drives_payment_hooks_without_a_record (routing)
- reconcile_sent_payments_confirms_from_persisted_record (mined -> Confirmed,
  mempool -> Pending, idempotent)

285/285 platform-wallet lib tests green, clippy clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
persistDashpayPayments re-stamped lastUpdated and rewrote every payment
row on every refresh pass, dirtying the rows and re-firing every @query
observer -- and the recurring DashPay-sync falling edge now calls this
even on a quiescent channel, so an open payment list re-rendered every
sync. Only mutate a row (and its lastUpdated) when a field actually
changed.

From the multi-agent review.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…write-amp) done

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@thepastaclaw thepastaclaw 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.

Code Review

Cumulative + incremental review at e57587f. The latest 3-commit delta adds a recurring sent-payment reconcile sweep, treats InstantSend as final for DashPay sent-payment confirmation, and suppresses Swift no-op DashPay row rewrites — resolving prior finding #10. All other 9 prior findings remain STILL VALID at HEAD and are carried forward, including two unresolved in-scope blockers (Swift wallet-wipe PHASE 1 omits identity.contactProfiles; load_identity_by_index_inner emits a DIP-9 breadcrumb only for the MASTER probe key, blocking imported-identity HIGH/CRITICAL signing). One narrow new defect is introduced by the latest delta: the Rust FFI persister adapter still maps context_kind=1 to Ok(None), so the new reconcile_sent_payments InstantSend-recovery branch never sees IS-locked persisted records on the Swift backend.

🔴 2 blocking | 🟡 8 suggestion(s)

10 additional finding(s)

blocking: Wallet wipe PHASE 1 omits identity.contactProfiles — SwiftData fatal can abort the wipe and leave sender-controlled DashPay strings on disk

packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift (line 3483)

PHASE 1's per-identity cascade-child pre-delete loop (3483–3499) deletes dpnsNames, dashpayProfile, contactRequests, dashpayPayments, and dashpayIgnoredSenders, but not identity.contactProfiles. The in-source comment block at 3450–3482 explicitly names the invariant the loop exists to enforce: SwiftData fatals during save() when a parent delete must null out a non-optional inverse on a child in the same batch, so every cascade-child whose inverse is non-optional must be deleted in its own save() ahead of the parent. PersistentDashpayContactProfile.owner is non-optional with cascade-from-parent semantics — exactly the shape the comment names. sync_contact_profiles (profile.rs) explicitly fetches profiles for managed.incoming_contact_requests.keys(), so any wallet whose recurring DashPay sync has cached even one PersistentDashpayContactProfile row (including unsolicited-sender rows whose displayName/publicMessage/avatarUrl are sender-controlled) will hit the documented SwiftData fatal at PHASE 2's identity delete (3505–3508), aborting the user-initiated wipe and leaving sender-controlled strings on disk — directly defeating a user wiping precisely to scrub a stalker's footprint.

                    for identity in identitiesToDelete {
                        for name in Array(identity.dpnsNames) {
                            backgroundContext.delete(name)
                        }
                        if let profile = identity.dashpayProfile {
                            backgroundContext.delete(profile)
                        }
                        for contactProfile in Array(identity.contactProfiles) {
                            backgroundContext.delete(contactProfile)
                        }
                        for cr in Array(identity.contactRequests) {
                            backgroundContext.delete(cr)
                        }
                        for payment in Array(identity.dashpayPayments) {
                            backgroundContext.delete(payment)
                        }
                        for ignored in Array(identity.dashpayIgnoredSenders) {
                            backgroundContext.delete(ignored)
                        }
                    }
blocking: Imported identity persists DIP-9 derivation breadcrumb only for the MASTER probe key — HIGH/CRITICAL-signed state transitions fail post-import (UAT-confirmed)

packages/rs-platform-wallet/src/wallet/identity/network/loading.rs (line 253)

load_identity_by_index_inner emits a DIP-9 derivation breadcrumb only for the single on-chain key whose hash matched the discovery probe, by calling managed.add_key(pub_key, Some((wallet_id, identity_index, MASTER_KEY_INDEX)), ...). The identity's other on-chain public keys travel via add_identity at 241–247 with no derivation indices, and Swift clears row.privateKeyKeychainIdentifier for entries whose FFI projection lacks derivation metadata (PlatformWalletPersistenceHandler.swift:1570–1597). Document-side signing flows intentionally exclude MASTER and select the first HIGH/CRITICAL authentication key (DPP rejects MASTER on document-side state transitions; dpns.rs:206–220 and profile.rs follow that contract). For an imported identity whose probe matched the master slot but whose document-signing key is a separate HIGH/CRITICAL slot, the signer is asked to sign with a public key that has no stored or derivable private material, and KeychainSigner returns the symptom recorded in docs/dashpay/TODO.md ('an IMPORTED identity cannot sign any state transition', UAT 2026-06-19). Derive and persist breadcrumbs for every wallet-derivable on-chain authentication key the wallet may later select for signing — not just the MASTER probe slot — before emitting the IdentityChangeSet that crosses the FFI.

suggestion: FFI get_core_tx_record drops InstantSend rows, defeating the new reconcile_sent_payments IS-recovery path on the Swift backend

packages/rs-platform-wallet-ffi/src/persistence.rs (line 2111)

The latest delta teaches reconcile_sent_payments (payments.rs:148–166) to recover Pending Sent entries when get_core_tx_record returns TransactionContext::InstantSend, and the in-code comment explicitly states 'An InstantSend lock is final for DashPay display'. But the FFI-backed implementation here still returns Ok(None) for context_kind == 1 ('InstantSend requires the IS-lock blob, which the persister doesn't currently store. Treat as miss so the proof flow's SPV wait path completes the proof from the live event stream.'). The Swift coreTxRecord callback (PlatformWalletPersistenceHandler.swift:5074–5122) does return context=1 with valid transactionData for IS-locked rows, but this Rust FFI adapter discards them before the new reconcile code can see them. As a result, the advertised relaunch-after-IS-lock-but-before-block recovery case remains Pending forever on Swift/iOS — the dedicated tests miss it because they inject TransactionContext::InstantSend through a custom Rust persister rather than the FFI fallback. Either reconstruct TransactionContext::InstantSend(IsdLock::default()) (or a synthetic lock) at this boundary when the tx bytes are present, or surface a separate adapter that returns the IS context without requiring the on-disk IS-lock blob.

suggestion: established_contact_get_note leaves *out_note undefined on every early-return path

packages/rs-platform-wallet-ffi/src/established_contact.rs (line 156)

Sibling established_contact_get_alias (102–117) writes *out_alias = std::ptr::null_mut(); immediately after check_ptr!, establishing the module's C-ABI contract that out-params are defined-null on early returns. established_contact_get_note (156–169) only calls check_ptr!(out_note) and skips the pre-null write. Early returns from unwrap_option_or_return! (storage NotFound, contact.note == None) and unwrap_result_or_return! (CString::new failure on interior NUL — reachable from counterparty-controlled note content set via established_contact_set_note) leave *out_note indeterminate across the ABI. A caller that doesn't pre-zero the slot can read a stale pointer or pass it to platform_wallet_string_free, risking invalid-free or double-free. Mirror the sibling pattern so the exported ABI does not depend on caller hygiene.

#[no_mangle]
pub unsafe extern "C" fn established_contact_get_note(
    contact_handle: Handle,
    out_note: *mut *mut std::os::raw::c_char,
) -> PlatformWalletFFIResult {
    check_ptr!(out_note);
    *out_note = std::ptr::null_mut();

    let option =
        ESTABLISHED_CONTACT_STORAGE.with_item(contact_handle, |contact| contact.note.clone());
    let option = unwrap_option_or_return!(option);
    let note = unwrap_option_or_return!(option);
    let c_str = unwrap_result_or_return!(std::ffi::CString::new(note));
    unsafe { *out_note = c_str.into_raw() };
    PlatformWalletFFIResult::ok()
}
suggestion: DashPay profile getter trio leaves *out_profile / *out_has_profile undefined on early-return paths

packages/rs-platform-wallet-ffi/src/dashpay_profile.rs (line 90)

managed_identity_get_dashpay_profile (90–112), platform_wallet_get_dashpay_profile (116–145), and platform_wallet_get_contact_profile (153–185) only assign *out_profile / *out_has_profile inside the Some/None match arms. After check_ptr!, early returns from unwrap_result_or_return!(read_identifier(..)) (invalid 32-byte input at 125, 163–164) and unwrap_option_or_return! (handle NotFound, missing managed identity, missing contact entry) leave both out-pointers indeterminate. DashPayProfileFFI owns *mut c_char fields released by dashpay_profile_ffi_free — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free across the ABI). Pre-write *out_profile = DashPayProfileFFI::empty(); *out_has_profile = false; immediately after check_ptr! in each function, matching the established_contact_get_alias precedent and the explicit empty-construction already used in the None match arms.

suggestion: Pending incoming-request rows fetch attacker-controlled avatar URLs before user consent

packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift (line 119)

sync_contact_profiles (profile.rs) explicitly includes managed.incoming_contact_requests.keys() in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. IncomingRequestRow (119–129) feeds cachedProfile(row.contactIdentityId)?.avatarUrl into DashPayAvatarView → SwiftUI AsyncImage, issuing an outbound HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's PersistentDashpayContactProfile SwiftData persistence the channel survives restart; Rust-side is_valid_avatar_url only validates scheme/length. The Ignore action mutes only AFTER first render. Either suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip avatarUrl from the Rust→Swift projection until the sender becomes an established contact.

suggestion: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale rows resurrect on cold start

packages/rs-platform-wallet-ffi/src/identity_persistence.rs (line 587)

allocate_contact_profile_rows explicitly continues past entries with profile == None ('Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep'). The Rust→Swift FFI projection carries no removal intent for absences; Swift's upsertDashpayContactProfiles is append/refresh-only; and ContactProfileRestoreEntryFFI rehydrates every persisted row as ContactProfileEntry { profile: Some(..) }. When a contact removes their on-chain dashpay.profile, apply_fetched_profile (profile.rs:588–603) flips the in-memory entry to None, but the absence is dropped at the FFI projection — the stale PersistentDashpayContactProfile row survives on disk. On cold start the cache rehydrates as Some(stale_profile) and the UI re-issues GETs to the previously attacker-controlled avatarUrl, defeating on-chain removal. Project absences as an explicit delete intent across the boundary (e.g. removed_contact_profile_ids: *const [u8;32] + count), mirroring the ContactIgnoredSenderFFI removal-set shape this PR already establishes on the same callback.

suggestion: rs-sdk-ffi forms a Rust slice over caller-supplied xpub bytes before enforcing the fixed 69-byte contract

packages/rs-sdk-ffi/src/dashpay/contact_request.rs (line 250)

DashSDKContactRequestParams documents extended_public_key as exactly the 69-byte DIP-15 compact xpub, and the underlying Rust SDK validates the length after the callback returns. The C ABI entry points (create_contact_request at 250–255/317–319 and send_contact_request mirror around 496–565) only reject is_null || _len == 0 and then call std::slice::from_raw_parts(params.extended_public_key, params.extended_public_key_len).to_vec() before any scalar length validation. A stale or buggy foreign caller that supplies a length != 69 makes Rust read an arbitrary-length foreign buffer before the inner SDK's length-validation error path runs — caller-controlled length drives an out-of-bounds read across the FFI boundary into Rust UB. Reject params.extended_public_key_len != 69 at the C ABI boundary in both entry points, before from_raw_parts.

suggestion: Contact-profile checked_at_ms not durably persisted on unchanged refresh — negative-cache backoff does not survive restart

packages/rs-platform-wallet/src/wallet/identity/network/profile.rs (line 588)

apply_fetched_profile (588–603) always refreshes checked_at_ms = now_ms in memory but returns changed only when the stored profile value differs (line 594 equality compares only profile content). sync_contact_profiles calls persister.store only when any_changed is true (718–725). A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires across the Rust→Swift boundary. After cold start, restored rows carry stale checked_at_ms, should_fetch_profile immediately re-issues an In query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel (restart re-issues per-victim GETs to known-stable hosts) and creates a cold-start fetch storm; a failed earlier store is also not retried because later sweeps see changed = false. Return a separate needs_persist signal from apply_fetched_profile for timestamp-only refreshes, with coarse coalescing if write-amp matters.

suggestion: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop

packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs (line 42)

fetch_contact_requests_paginated drains every matching document at CONTACT_REQUEST_PAGE_SIZE per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any after_created_at == None path it walks the entire history in one call. unignore_sender resets high_water_received_ms to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring DashPaySyncManager tick added in this PR, an attacker who spams contactRequest documents (varying accountReference to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

- [BLOCKING] In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:3483-3499: Wallet wipe PHASE 1 omits identity.contactProfiles — SwiftData fatal can abort the wipe and leave sender-controlled DashPay strings on disk
  PHASE 1's per-identity cascade-child pre-delete loop (3483–3499) deletes `dpnsNames`, `dashpayProfile`, `contactRequests`, `dashpayPayments`, and `dashpayIgnoredSenders`, but not `identity.contactProfiles`. The in-source comment block at 3450–3482 explicitly names the invariant the loop exists to enforce: SwiftData fatals during `save()` when a parent delete must null out a non-optional inverse on a child in the same batch, so every cascade-child whose inverse is non-optional must be deleted in its own `save()` ahead of the parent. `PersistentDashpayContactProfile.owner` is non-optional with cascade-from-parent semantics — exactly the shape the comment names. `sync_contact_profiles` (profile.rs) explicitly fetches profiles for `managed.incoming_contact_requests.keys()`, so any wallet whose recurring DashPay sync has cached even one `PersistentDashpayContactProfile` row (including unsolicited-sender rows whose `displayName`/`publicMessage`/`avatarUrl` are sender-controlled) will hit the documented SwiftData fatal at PHASE 2's identity delete (3505–3508), aborting the user-initiated wipe and leaving sender-controlled strings on disk — directly defeating a user wiping precisely to scrub a stalker's footprint.
- [BLOCKING] In `packages/rs-platform-wallet/src/wallet/identity/network/loading.rs`:253-263: Imported identity persists DIP-9 derivation breadcrumb only for the MASTER probe key — HIGH/CRITICAL-signed state transitions fail post-import (UAT-confirmed)
  `load_identity_by_index_inner` emits a DIP-9 derivation breadcrumb only for the single on-chain key whose hash matched the discovery probe, by calling `managed.add_key(pub_key, Some((wallet_id, identity_index, MASTER_KEY_INDEX)), ...)`. The identity's other on-chain public keys travel via `add_identity` at 241–247 with no derivation indices, and Swift clears `row.privateKeyKeychainIdentifier` for entries whose FFI projection lacks derivation metadata (PlatformWalletPersistenceHandler.swift:1570–1597). Document-side signing flows intentionally exclude MASTER and select the first HIGH/CRITICAL authentication key (DPP rejects MASTER on document-side state transitions; dpns.rs:206–220 and profile.rs follow that contract). For an imported identity whose probe matched the master slot but whose document-signing key is a separate HIGH/CRITICAL slot, the signer is asked to sign with a public key that has no stored or derivable private material, and `KeychainSigner` returns the symptom recorded in docs/dashpay/TODO.md ('an IMPORTED identity cannot sign any state transition', UAT 2026-06-19). Derive and persist breadcrumbs for every wallet-derivable on-chain authentication key the wallet may later select for signing — not just the MASTER probe slot — before emitting the `IdentityChangeSet` that crosses the FFI.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/persistence.rs`:2111-2119: FFI get_core_tx_record drops InstantSend rows, defeating the new reconcile_sent_payments IS-recovery path on the Swift backend
  The latest delta teaches `reconcile_sent_payments` (payments.rs:148–166) to recover Pending Sent entries when `get_core_tx_record` returns `TransactionContext::InstantSend`, and the in-code comment explicitly states 'An InstantSend lock is final for DashPay display'. But the FFI-backed implementation here still returns `Ok(None)` for `context_kind == 1` ('InstantSend requires the IS-lock blob, which the persister doesn't currently store. Treat as miss so the proof flow's SPV wait path completes the proof from the live event stream.'). The Swift `coreTxRecord` callback (PlatformWalletPersistenceHandler.swift:5074–5122) does return `context=1` with valid `transactionData` for IS-locked rows, but this Rust FFI adapter discards them before the new reconcile code can see them. As a result, the advertised relaunch-after-IS-lock-but-before-block recovery case remains Pending forever on Swift/iOS — the dedicated tests miss it because they inject `TransactionContext::InstantSend` through a custom Rust persister rather than the FFI fallback. Either reconstruct `TransactionContext::InstantSend(IsdLock::default())` (or a synthetic lock) at this boundary when the tx bytes are present, or surface a separate adapter that returns the IS context without requiring the on-disk IS-lock blob.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/established_contact.rs`:156-169: established_contact_get_note leaves *out_note undefined on every early-return path
  Sibling `established_contact_get_alias` (102–117) writes `*out_alias = std::ptr::null_mut();` immediately after `check_ptr!`, establishing the module's C-ABI contract that out-params are defined-null on early returns. `established_contact_get_note` (156–169) only calls `check_ptr!(out_note)` and skips the pre-null write. Early returns from `unwrap_option_or_return!` (storage NotFound, `contact.note == None`) and `unwrap_result_or_return!` (CString::new failure on interior NUL — reachable from counterparty-controlled note content set via `established_contact_set_note`) leave `*out_note` indeterminate across the ABI. A caller that doesn't pre-zero the slot can read a stale pointer or pass it to `platform_wallet_string_free`, risking invalid-free or double-free. Mirror the sibling pattern so the exported ABI does not depend on caller hygiene.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/dashpay_profile.rs`:90-185: DashPay profile getter trio leaves *out_profile / *out_has_profile undefined on early-return paths
  `managed_identity_get_dashpay_profile` (90–112), `platform_wallet_get_dashpay_profile` (116–145), and `platform_wallet_get_contact_profile` (153–185) only assign `*out_profile` / `*out_has_profile` inside the Some/None match arms. After `check_ptr!`, early returns from `unwrap_result_or_return!(read_identifier(..))` (invalid 32-byte input at 125, 163–164) and `unwrap_option_or_return!` (handle NotFound, missing managed identity, missing contact entry) leave both out-pointers indeterminate. `DashPayProfileFFI` owns `*mut c_char` fields released by `dashpay_profile_ffi_free` — a subsequent free on a slot the caller didn't pre-zero would free garbage pointers (invalid-free or double-free across the ABI). Pre-write `*out_profile = DashPayProfileFFI::empty(); *out_has_profile = false;` immediately after `check_ptr!` in each function, matching the `established_contact_get_alias` precedent and the explicit empty-construction already used in the None match arms.
- [SUGGESTION] In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ContactRequestsView.swift`:119-129: Pending incoming-request rows fetch attacker-controlled avatar URLs before user consent
  `sync_contact_profiles` (profile.rs) explicitly includes `managed.incoming_contact_requests.keys()` in the per-owner fetch plan, populating the contact-profile cache for senders the victim has never accepted. `IncomingRequestRow` (119–129) feeds `cachedProfile(row.contactIdentityId)?.avatarUrl` into `DashPayAvatarView → SwiftUI AsyncImage`, issuing an outbound HTTPS GET to the sender-controlled host on first render — leaking IP, online state, TLS/UA fingerprint, and per-victim URL-token receipt confirmation before any consent action. With this PR's `PersistentDashpayContactProfile` SwiftData persistence the channel survives restart; Rust-side `is_valid_avatar_url` only validates scheme/length. The Ignore action mutes only AFTER first render. Either suppress remote avatars Swift-side for unaccepted senders (initials-only variant for the Requests tab) or strip `avatarUrl` from the Rust→Swift projection until the sender becomes an established contact.
- [SUGGESTION] In `packages/rs-platform-wallet-ffi/src/identity_persistence.rs`:587-621: Confirmed-absent contact profiles cannot cross the Swift persistence boundary — stale rows resurrect on cold start
  `allocate_contact_profile_rows` explicitly `continue`s past entries with `profile == None` ('Skip confirmed-absent entries — the negative cache is not persisted; it rebuilds on the next sweep'). The Rust→Swift FFI projection carries no removal intent for absences; Swift's `upsertDashpayContactProfiles` is append/refresh-only; and `ContactProfileRestoreEntryFFI` rehydrates every persisted row as `ContactProfileEntry { profile: Some(..) }`. When a contact removes their on-chain `dashpay.profile`, `apply_fetched_profile` (profile.rs:588–603) flips the in-memory entry to None, but the absence is dropped at the FFI projection — the stale `PersistentDashpayContactProfile` row survives on disk. On cold start the cache rehydrates as `Some(stale_profile)` and the UI re-issues GETs to the previously attacker-controlled `avatarUrl`, defeating on-chain removal. Project absences as an explicit delete intent across the boundary (e.g. `removed_contact_profile_ids: *const [u8;32] + count`), mirroring the `ContactIgnoredSenderFFI` removal-set shape this PR already establishes on the same callback.
- [SUGGESTION] In `packages/rs-sdk-ffi/src/dashpay/contact_request.rs`:250-319: rs-sdk-ffi forms a Rust slice over caller-supplied xpub bytes before enforcing the fixed 69-byte contract
  `DashSDKContactRequestParams` documents `extended_public_key` as exactly the 69-byte DIP-15 compact xpub, and the underlying Rust SDK validates the length after the callback returns. The C ABI entry points (`create_contact_request` at 250–255/317–319 and `send_contact_request` mirror around 496–565) only reject `is_null || _len == 0` and then call `std::slice::from_raw_parts(params.extended_public_key, params.extended_public_key_len).to_vec()` before any scalar length validation. A stale or buggy foreign caller that supplies a length != 69 makes Rust read an arbitrary-length foreign buffer before the inner SDK's length-validation error path runs — caller-controlled length drives an out-of-bounds read across the FFI boundary into Rust UB. Reject `params.extended_public_key_len != 69` at the C ABI boundary in both entry points, before `from_raw_parts`.
- [SUGGESTION] In `packages/rs-platform-wallet/src/wallet/identity/network/profile.rs`:588-731: Contact-profile checked_at_ms not durably persisted on unchanged refresh — negative-cache backoff does not survive restart
  `apply_fetched_profile` (588–603) always refreshes `checked_at_ms = now_ms` in memory but returns `changed` only when the stored profile value differs (line 594 equality compares only profile content). `sync_contact_profiles` calls `persister.store` only when `any_changed` is true (718–725). A re-check confirming the same present or confirmed-absent profile updates the timestamp in memory only — the FFI persistence callback never fires across the Rust→Swift boundary. After cold start, restored rows carry stale `checked_at_ms`, `should_fetch_profile` immediately re-issues an `In` query for every unchanged contact, and the negative-cache backoff effectively doesn't survive restart. This amplifies the pre-consent avatar tracking channel (restart re-issues per-victim GETs to known-stable hosts) and creates a cold-start fetch storm; a failed earlier store is also not retried because later sweeps see `changed = false`. Return a separate `needs_persist` signal from `apply_fetched_profile` for timestamp-only refreshes, with coarse coalescing if write-amp matters.
- [SUGGESTION] In `packages/rs-sdk/src/platform/dashpay/contact_request_queries.rs`:42-112: Paginated retrieve-all has no per-call total or elapsed budget — algorithmic-DoS surface against the recurring sync loop
  `fetch_contact_requests_paginated` drains every matching document at `CONTACT_REQUEST_PAGE_SIZE` per page with no per-call total cap, no elapsed-time budget, and no caller-visible continuation. On cold start, restore-from-seed, or any `after_created_at == None` path it walks the entire history in one call. `unignore_sender` resets `high_water_received_ms` to None, so any UI un-ignore drops the next sweep onto the full retrieve-all. Combined with the recurring `DashPaySyncManager` tick added in this PR, an attacker who spams `contactRequest` documents (varying `accountReference` to defeat per-request dedup) against one of the wallet's identities can make every recurring sweep monopolize the SDK gRPC client and starve every other identity's sync — a cheap algorithmic-DoS against the verified-proof query path. Add a configurable total-document ceiling per sweep with a resumable cursor, or at minimum a logged-warn + early-break above a threshold.

Inline dry-run could not load the GitHub PR diff because this PR exceeds GitHub's 20,000-line diff limit, so I posted the same verified findings as a top-level review body.

shumkov and others added 2 commits June 20, 2026 22:34
An identity rediscovered from a mnemonic (gap-limit "discover identities"
scan, or load-by-index) could not sign any state transition — every signed
op failed with "No PersistentPublicKey row matches the supplied public-key
bytes". Root cause: discovery emitted a DIP-9 derivation breadcrumb for
ONLY the MASTER key (key_index 0); the identity's other keys arrived
watch-only (no breadcrumb). The Swift signer re-derives a key's private
scalar from its breadcrumb, so a non-master signing key (HIGH / CRITICAL
auth) had no private material — the misleading error fired even though the
public-key row existed.

The pasta-bridge derivation path is NOT the cause: its identity-key path
m/9'/coin'/5'/0'/0'/identity'/key' with keyId == key_index is byte-for-byte
the standard DIP-9/DIP-13 path the wallet uses, so the keys ARE
re-derivable from the mnemonic.

Fix: for each on-chain key, derive the candidate ECDSA auth keypair at
(identity_index, key_id), verify it reproduces the published key with the
canonical IdentityPublicKey::validate_private_key_bytes (the protocol's own
key-ownership primitive -- so the wallet's match can't drift from
consensus), and emit a breadcrumb only for reproducible keys, in one
batched IdentityKeysChangeSet (add_keys). The verify gate is load-bearing:
it never hands a breadcrumb that would make the client materialize + sign
with a key the identity does not authorize on-chain. Keys not re-derivable
from this wallet's seed (foreign, BLS/EdDSA, uncompressed-externally-
registered ECDSA) correctly stay watch-only.

Shared helper IdentityWallet::derive_key_breadcrumbs is used by BOTH
discover_inner and load_identity_by_index_inner -- the load-by-index path
(public loadIdentity(atIndex:) API) had the identical master-only bug.
add_key now delegates to add_keys (one canonical key-layering path).

Migration: an already-imported (broken) identity heals via a full rescan
from index 0 (a fresh wipe + re-import does this); the default resume scan
starts past the known index and won't re-emit.

Reviewed by 4 lenses incl. blockchain-security (spec + implementation).

Tests (TDD red->green vs a master-only mimic):
- breadcrumb_decisions_emits_for_every_reproducible_key
- breadcrumb_decisions_leaves_non_reproducible_key_watch_only
- breadcrumb_decisions_matches_hash160_key
- add_keys_emits_breadcrumbs_per_key / add_keys_empty_is_noop
290/290 platform-wallet lib tests green, clippy clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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.

3 participants