Skip to content

feat: expose the Rust identity key layout to FFI, Swift and Kotlin hosts - #5647

Draft
Claudius-Maginificent wants to merge 4 commits into
fix/platform-wallet-dip11-identity-key-layoutfrom
fix/platform-wallet-dip11-identity-key-layout-bindings
Draft

Claudius-Maginificent wants to merge 4 commits into
fix/platform-wallet-dip11-identity-key-layoutfrom
fix/platform-wallet-dip11-identity-key-layout-bindings

Conversation

@Claudius-Maginificent

@Claudius-Maginificent Claudius-Maginificent commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR

The iOS and Android apps now ask the wallet's Rust core which keys a new identity needs and how much it must be funded with, instead of each keeping its own copy of those rules. Identities get the same keys as before; only the place that decides them moves.

Stacked on #5645 (base branch = fix/platform-wallet-dip11-identity-key-layout). #5645 can land first on its own, and this PR follows.

User story

As a wallet user, I want the iOS and Android apps to create identities with the same key set and the same minimum funding, so that my identity works the same on both and no app can quietly drift from the rules.

Scenario

Base flow

  1. The user opens "create identity" in the iOS or Android app and chooses a funding amount.
  2. The app shows the minimum funding, derives the keys, and registers the identity.

Actual behavior

  • The key layout and the minimum funding are hard-coded separately in the FFI layer, the Swift app and the Kotlin app. Each copy can drift.

Expected behavior

  • The apps get the key layout and the minimum funding from the Rust core and only pass them through.
  • Identities are created with the same keys as today: ids 0–3, plus the DashPay pair at 4–5 when chosen.
  • Interrupted registrations resume with the new-identity layout. Rust refuses, before signing, a tracked lock that cannot pay for its keys.
  • Identities that already exist behave exactly as before.

Detailed discussion

New host API (rs-platform-wallet-ffi, rs-unified-sdk-jni). The layouts and amounts are computed in rs-platform-wallet; these only marshal them.

  • platform_wallet_identity_creation_key_layout (+_free) returns the key layout for a new identity, with or without DashPay keys.
  • platform_wallet_identity_creation_min_funding_duffs returns the minimum asset-lock funding.
  • platform_wallet_identity_creation_from_addresses_min_fees (+_free) returns the minimum fees for registering from platform addresses.
  • JNI equivalents on IdentityNative: identityCreationKeyLayout, identityCreationMinFundingDuffs, identityCreationFromAddressesMinFees.
  • Golden .bin fixtures pin the layout encodings (new identity, with DashPay keys).

No AUTHENTICATION/MEDIUM key, so no resume layout. #5645 leaves the MEDIUM key out because a creation carries at most 6 keys and no system contract accepts MEDIUM. A resume therefore re-derives the plain new-identity layout. The earlier revision's AssetLockResume layout (FFI value 2, Kotlin ASSET_LOCK_RESUME, Swift .assetLockResume), the platform_wallet_resume_identity_key_layout query, JNI resumeIdentityKeyLayout, Kotlin IdentityRegistration.resumeKeyLayout and Swift resumeIdentityKeyLayout are gone, along with their golden fixture.

Swift / Kotlin:

  • Key derivation and registration are driven by the Rust layout:
    • Swift: ManagedPlatformWallet, CreateIdentityView, the DashPay claim/reclaim sheets.
    • Kotlin: RegistrationKeys, IdentityRegistration, CreateIdentityScreen, DashpayKeyProvisioning, the claim/reclaim sheets.
  • Deleted: the host slot tables, key counts, fee constants (for example Swift's hard-coded minimum funding) and minimum arithmetic, including Swift IdentityRegistrationKeys.swift.

Breaking for hosts (C ABI and JNI):

  • dash_sdk_derive_and_persist_identity_keys and platform_wallet_preview_identity_registration_key_set take a layout instead of a key count.
  • IDENTITY_REGISTRATION_KEY_SET_COUNT is removed.
  • JNI previewRegistrationKeySet takes a layout.
  • Any host outside this repo that calls these must pass a layout (NewIdentity = 0, NewIdentityWithDashPayKeys = 1).

This PR changes no consensus behavior, hence no !.

Follow-ups (out of scope):

  • remove the JNI copy of the key-0 MASTER check;
  • remove Swift's hard-coded shielded denominations.

Placement follows layer-ownership: bindings marshal and never decide.

Testing

  • New Rust tests cover:
    • FFI marshalling and freeing of the layout and fee results;
    • null-pointer handling;
    • FFI minimums against a real wallet handle;
    • the same base keys derived with and without the DashPay pair;
    • JNI golden encodings and layout ordinals.
  • Kotlin unit tests (RegistrationKeysTest, DashpayKeyProvisioningTest, CreateIdentityFundingPolicyTest) and the Swift integration test were updated for the new API and the 4/6-key layouts.

Verification:

  • cargo clippy -p platform-wallet -p platform-wallet-ffi -p rs-unified-sdk-jni --all-targets --all-features --locked -- --no-deps -D warnings is clean.
  • cargo nextest run on the same crates with --all-features, excluding shielded::: 2000 passed.
  • The JNI golden tests pass against the regenerated fixtures.

Swift and Kotlin were not built locally (no Xcode or JDK on the build host). A grep confirms no reference to the removed symbols is left. CI or a local build needs to confirm them.

Checklist

  • I have performed a self-review of my own code
  • My Rust, FFI, WASM, Swift or Kotlin changes follow the coding conventions
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have described breaking changes in the corresponding section if my code contains any

🤖 Generated with Claude Code

https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG

🤖 Co-authored by Claudius the Magnificent AI Agent

@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Share

@thepastaclaw

thepastaclaw commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

🕓 Review not started yet because this PR is a draft.

  • Request normal review — click when the PR is ready for review.
  • Request priority review — click to move this review to the front of the queue.

Commit 1dce118. Normal review starts when eligible; priority review starts as soon as a slot is available.

@Claudius-Maginificent
Claudius-Maginificent marked this pull request as ready for review October 29, 2026 12:13

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

Final validation — Phase 1 + Phase 2

The Swift Platform-address registration path still selects inputs totaling exactly the requested identity balance, while Rust deducts the identity-creation fee from the lowest input and enforces a maximum input count. As a result, the normal Swift flow can reach registration and be rejected on-chain despite passing the UI balance check. The new C ABI also accepts the layout as a Rust fieldless enum by value, so stale or malformed C callers can trigger undefined behavior instead of receiving an invalid-parameter error.

🔴 1 blocking | 🟡 1 suggestion(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: Reserve the Rust-computed address fee when selecting Swift registration inputs
packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift:1286-1292

This path still builds inputs that sum exactly to targetCredits; it never queries or reserves platform_wallet_identity_creation_from_addresses_min_fees. Rust registers the transition with DeductFromInput(0), so the lowest BTreeMap input must retain the fee in addition to the requested identity balance. With the UI's default of spending the full Platform-payment account balance, the transition is underfunded and rejected after the keys have already been derived and persisted. The greedy selector also has no fee-vector length cap, so many small addresses can exceed the protocol's maximum input count. Kotlin now handles both requirements through creationFromAddressesMinFees and packFundingInputs, but Swift exposes only the Core minimum. Add the Rust fee query to ManagedPlatformWallet and make Swift's input selection use the per-input-count schedule while reserving the fee on the actual lowest address.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.1-sol (effort low) — This is a large cross-language change that directly alters identity key derivation, registration signing inputs, asset-lock funding, and resume behavior, making key handling and funds movement critical surfaces.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort xhigh); agent phase2-reviewer
🤖 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/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift:1286-1292: Reserve the Rust-computed address fee when selecting Swift registration inputs
  This path still builds inputs that sum exactly to `targetCredits`; it never queries or reserves `platform_wallet_identity_creation_from_addresses_min_fees`. Rust registers the transition with `DeductFromInput(0)`, so the lowest BTreeMap input must retain the fee in addition to the requested identity balance. With the UI's default of spending the full Platform-payment account balance, the transition is underfunded and rejected after the keys have already been derived and persisted. The greedy selector also has no fee-vector length cap, so many small addresses can exceed the protocol's maximum input count. Kotlin now handles both requirements through `creationFromAddressesMinFees` and `packFundingInputs`, but Swift exposes only the Core minimum. Add the Rust fee query to `ManagedPlatformWallet` and make Swift's input selection use the per-input-count schedule while reserving the fee on the actual lowest address.

In `packages/rs-platform-wallet-ffi/src/identity_creation_key_layout.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/identity_creation_key_layout.rs:22-39: Validate layout discriminants before crossing the C ABI
  `IdentityCreationKeyLayoutFFI` is a fieldless `#[repr(C)]` Rust enum passed by value to the layout, fee, preview, and derive-and-persist exports. Rust assumes the enum discriminant is one of its declared variants before the function body can safely match it. A C caller can nevertheless pass any integer; in particular, an old binary using the unchanged derive/preview symbols may still pass the former key counts 4 or 6, and the removed resume value was 2. Because those symbols still link, this becomes undefined behavior rather than a recoverable `ErrorInvalidParameter`. Accept a plain integer type such as `u32` at the extern-C boundary, validate 0 and 1, and then convert to the Rust enum. The JNI boundary already follows this safer ordinal-validation pattern.
Out-of-scope follow-up suggestions (1)

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

  • Shielded denomination policy remains duplicated in the mobile hosts — This is a speculative follow-up about future protocol changes, not a defect introduced or worsened by the reviewed identity-layout change. The PR explicitly leaves shielded denomination handling outside this scope, and no concrete current failure was demonstrated.
    • Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.

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

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

The Rust-owned identity layout and host marshalling are generally coherent, but two issues remain. Swift's Platform-payment registration still selects inputs for the requested identity amount without reserving the Rust-computed fee deducted from the lexicographically first input, so exact-balance submissions can be rejected or underfund the identity. The public C ABI also accepts the new fieldless Rust enum directly without validating its discriminant.

🔴 1 blocking | 🟡 1 suggestion(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: Reserve the Rust-computed address fee when selecting Swift registration inputs
packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift:1286-1292

The Swift Platform-payment path calls buildInputs with only targetCredits, and that helper selects inputs whose consumed credits sum exactly to the requested amount. It never obtains or applies the new Rust identity_creation_from_addresses_min_fees schedule. The Rust registration transition uses DeductFromInput(0), so the fee is deducted from the lexicographically first input after the input map is canonicalized; an exact-target selection leaves no fee headroom on that input. A full-balance submission can therefore be rejected with insufficient fee coverage, while a submission that succeeds with available headroom can fund the identity with less than the amount shown to the user. Expose the Rust-owned fee schedule through the Swift wallet layer and select/order inputs so the actual fee for the canonical input count remains on input zero.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality)

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

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 5: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.1-sol (effort low) — This is a large cross-language change that alters identity key derivation, registration signing inputs, and minimum funding/fee calculations across FFI and JNI boundaries, directly affecting key handling and funds movement.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort xhigh); agent phase2-reviewer
🤖 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/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift:1286-1292: Reserve the Rust-computed address fee when selecting Swift registration inputs
  The Swift Platform-payment path calls `buildInputs` with only `targetCredits`, and that helper selects inputs whose consumed credits sum exactly to the requested amount. It never obtains or applies the new Rust `identity_creation_from_addresses_min_fees` schedule. The Rust registration transition uses `DeductFromInput(0)`, so the fee is deducted from the lexicographically first input after the input map is canonicalized; an exact-target selection leaves no fee headroom on that input. A full-balance submission can therefore be rejected with insufficient fee coverage, while a submission that succeeds with available headroom can fund the identity with less than the amount shown to the user. Expose the Rust-owned fee schedule through the Swift wallet layer and select/order inputs so the actual fee for the canonical input count remains on input zero.

In `packages/rs-platform-wallet-ffi/src/identity_creation_key_layout.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/identity_creation_key_layout.rs:22-39: Validate layout discriminants before crossing the C ABI
  (existing thread: https://github.com/dashpay/platform/pull/5647#discussion_r4415729444)
  `IdentityCreationKeyLayoutFFI` is a fieldless `#[repr(C)]` Rust enum passed by value through the exported C functions. `#[repr(C)]` makes valid variants ABI-compatible, but it does not validate an integer supplied by a C caller; an external or stale dynamically linked caller can still pass values such as the former key counts `4` or `6`, the removed resume value `2`, or any other integer. The invalid enum value is undefined behavior before the conversion match can return an error. The JNI ordinal check protects only JNI callers, and documenting the breaking change does not make malformed or ABI-skewed C calls safe. Accept a plain integer at each `extern "C"` boundary, validate the supported ordinals, and construct the Rust enum only after validation.

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

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

Changes requested: 1 blocker

  • Reserve the Rust-computed address fee when selecting Swift registration inputs — packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift:1286-1292 (carried)
    Impact: An iOS user paying from Platform addresses can have enough credits for both the requested identity balance and its fee, yet have registration rejected because the app leaves no fee reserve on the selected payer.

New on this head: This revision gives inactive identity key formats a dedicated wallet error code (82) in Rust, Swift, and Kotlin, and documents that the refusal is based on the newest protocol version the SDK knows after a best-effort refresh. The Kotlin SDK build and emulator tests passed; no Swift build or failing code check is reported, and the review check is pending.

🔴 1 blocking | 🟡 3 suggestion(s)

2 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: Reserve the Rust-computed address fee when selecting Swift registration inputs
Impact: An iOS user paying from Platform addresses can have enough credits for both the requested identity balance and its fee, yet have registration rejected because the app leaves no fee reserve on the selected payer.
packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift:1286-1292

The form can enable Create for a fundable amount and then submit an allocation that Platform rejects. If the user enters the balance of the largest address, canSubmit accepts it against the account total, and buildInputs spends that address in full and stops, even when a second funded address could contribute. The FFI passes the selected inputs in a BTreeMap, and the SDK sets DeductFromInput(0) with no refund output. Platform's fee precheck reads the remaining balance of that input, which is zero in this case; it rejects the registration rather than crediting the identity a smaller amount. Kotlin already uses the Rust minimum for the selected layout and input count. Put fee-aware selection in rs-platform-wallet so both apps can use the same plan for the default amount, Submit eligibility, and submission.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

🟡 Suggestion: New creation-key failures silently default to invalid parameter
Impact: When the wallet adds another creation-key error, hosts can be told to correct their input without the compiler requiring anyone to classify the new failure.
packages/rs-platform-wallet-ffi/src/error.rs:1340-1355

The code-82 change fixes InactiveKeyFormat but leaves the same fallback that previously classified it as malformed input. IdentityCreationKeys(..) still assigns code 2 to every unlisted inner variant. The book's “Error enums stay exhaustive” rule explicitly covers per-variant FFI code selection. Match the inner error exhaustively and group the six current caller-input failures under code 2, preserving the existing codes for the other two variants.

            PlatformWalletError::IdentityCreationKeys(cause) => match cause {
                IdentityCreationKeysError::ValidationUnavailable(..) => {
                    PlatformWalletFFIResultCode::ErrorUnknown
                }
                IdentityCreationKeysError::InactiveKeyFormat { .. } => {
                    PlatformWalletFFIResultCode::ErrorIdentityKeyFormatNotActive
                }
                IdentityCreationKeysError::Empty
                | IdentityCreationKeysError::KeyIdMismatch { .. }
                | IdentityCreationKeysError::DisabledKey { .. }
                | IdentityCreationKeysError::KeyZeroNotMasterAuthentication
                | IdentityCreationKeysError::MissingAuthenticationKey { .. }
                | IdentityCreationKeysError::StructureRefused { .. } => {
                    PlatformWalletFFIResultCode::ErrorInvalidParameter
                }
            },

source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

Still open from earlier rounds (1)

  • 🟡 Suggestion: Validate layout discriminants before crossing the C ABI — packages/rs-platform-wallet-ffi/src/identity_creation_key_layout.rs:22-39 (thread)
Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 7: gpt-6.2-astra (agent: phase2-reviewer, role: rust-quality); reviewer 8: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.2-sol (effort low) — The cross-language change rewires key handling in identity_derive_and_persist.rs, where the Rust layout now drives which identity keys are derived, at which indices, and with which roles they are persisted, even though the intended key sets are unchanged.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift:1286-1292: Reserve the Rust-computed address fee when selecting Swift registration inputs
  Impact: An iOS user paying from Platform addresses can have enough credits for both the requested identity balance and its fee, yet have registration rejected because the app leaves no fee reserve on the selected payer.
  The form can enable Create for a fundable amount and then submit an allocation that Platform rejects. If the user enters the balance of the largest address, `canSubmit` accepts it against the account total, and `buildInputs` spends that address in full and stops, even when a second funded address could contribute. The FFI passes the selected inputs in a `BTreeMap`, and the SDK sets `DeductFromInput(0)` with no refund output. Platform's fee precheck reads the remaining balance of that input, which is zero in this case; it rejects the registration rather than crediting the identity a smaller amount. Kotlin already uses the Rust minimum for the selected layout and input count. Put fee-aware selection in `rs-platform-wallet` so both apps can use the same plan for the default amount, Submit eligibility, and submission.

In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt`:
- [SUGGESTION] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt:819-825: Kotlin reports a failed protocol-version lookup as non-retryable
  Impact: A Kotlin host that uses `isRetryable` to offer Retry can hide it after a temporary lookup failure, even though the same registration can succeed unchanged when connectivity returns.
  `registerWithWalletFunding` accepts caller-supplied keys, including a version-1 authentication key with a usage limit. On a network already at version 14, an unpinned SDK still seeded at 13 tries a proved refresh. If that refresh fails before learning a newer version, `refresh_protocol_version()` returns the retained 13 and the wallet returns code 82 before funding or signing. Kotlin's new `IdentityKeyFormatNotActive` inherits `isRetryable = false`, although submitting the identical request triggers another refresh and can succeed without a network upgrade or a key change. Preserve the refresh failure in Rust when the version is still too low, and distinguish a transient lookup failure from a pinned or confirmed incompatible version in the host mapping and tests.

In `packages/rs-platform-wallet-ffi/src/error.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/error.rs:1340-1355: New creation-key failures silently default to invalid parameter
  Impact: When the wallet adds another creation-key error, hosts can be told to correct their input without the compiler requiring anyone to classify the new failure.
  The code-82 change fixes `InactiveKeyFormat` but leaves the same fallback that previously classified it as malformed input. `IdentityCreationKeys(..)` still assigns code 2 to every unlisted inner variant. The book's “Error enums stay exhaustive” rule explicitly covers per-variant FFI code selection. Match the inner error exhaustively and group the six current caller-input failures under code 2, preserving the existing codes for the other two variants.

In `packages/rs-platform-wallet-ffi/src/identity_creation_key_layout.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/identity_creation_key_layout.rs:22-39: Validate layout discriminants before crossing the C ABI
  (carried; thread: https://github.com/dashpay/platform/pull/5647#discussion_r4415729444)

Comment on lines +819 to +825
* an unpinned SDK refreshes it first, best-effort, so a retry can pass
* once the SDK learns a newer network version. Keys of the Rust
* identity key layout are admitted at every version.
* ← Swift `PlatformWalletError.identityKeyFormatNotActive`.
*/
class IdentityKeyFormatNotActive(message: String, cause: Throwable? = null) :
PlatformWallet(message, cause)

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.

🟡 Suggestion: Kotlin reports a failed protocol-version lookup as non-retryable
Impact: A Kotlin host that uses isRetryable to offer Retry can hide it after a temporary lookup failure, even though the same registration can succeed unchanged when connectivity returns.

registerWithWalletFunding accepts caller-supplied keys, including a version-1 authentication key with a usage limit. On a network already at version 14, an unpinned SDK still seeded at 13 tries a proved refresh. If that refresh fails before learning a newer version, refresh_protocol_version() returns the retained 13 and the wallet returns code 82 before funding or signing. Kotlin's new IdentityKeyFormatNotActive inherits isRetryable = false, although submitting the identical request triggers another refresh and can succeed without a network upgrade or a key change. Preserve the refresh failure in Rust when the version is still too low, and distinguish a transient lookup failure from a pinned or confirmed incompatible version in the host mapping and tests.

source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

@lklimek
lklimek added this pull request to stack #6212 November 24, 2026 10:52
@lklimek
lklimek force-pushed the fix/platform-wallet-dip11-identity-key-layout-bindings branch from 9001dd9 to 3a92d2d Compare November 24, 2026 10:54

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

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

Changes requested: 1 blocker

  • Reserve the Rust-computed address fee when selecting Swift registration inputs — packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift:1286-1292 (carried)
    Impact: A SwiftExampleApp user who accepts the full-balance default for a Platform Payment account with one address holding 1 DASH cannot create the identity.

New on this head: The rebased PR exposes Rust-owned identity creation layouts and funding minimums to mobile hosts, and clarifies that code 82 refers to the newest protocol version the SDK knows. Kotlin SDK build and tests passed, and the Swift SDK build was skipped. Rust workspace CI stopped before tests at formatting differences in two files unchanged from the stacked base.

🔴 1 blocking | 🟡 2 suggestion(s)

2 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: Reserve the Rust-computed address fee when selecting Swift registration inputs
Impact: A SwiftExampleApp user who accepts the full-balance default for a Platform Payment account with one address holding 1 DASH cannot create the identity.
packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift:1286-1292

Platform rejects the default registration for insufficient fee balance. Selecting the account prefills 1 DASH, canSubmit accepts an amount equal to the balance, and buildInputs assigns that entire balance to the identity. The SDK uses DeductFromInput(0), so Platform checks what remains on the first address in Rust's BTreeMap order after subtracting its contribution: zero. With multiple addresses, leaving credits on a different input does not pay the fee. As part of moving registration minimums into Rust, have the wallet return a fee-aware funding plan for the selected layout and use it for the amount prefill, submit gate, and input selection.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

🟡 Suggestion: New creation-key failures silently default to invalid parameter
Impact: If the wallet adds a creation-key error that the caller cannot fix, hosts will still receive an invalid-parameter error unless the FFI mapping is updated.
packages/rs-platform-wallet-ffi/src/error.rs:1342-1356

ValidationUnavailable and InactiveKeyFormat have explicit mappings, but IdentityCreationKeys(..) assigns code 2 to every other inner variant, including future ones. The book requires per-variant FFI error mappings to break compilation when an error variant is added. Group the six remaining variants explicitly under ErrorInvalidParameter so their current behavior stays the same and the next variant requires a deliberate classification.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

Still open from earlier rounds (1)

  • 🟡 Suggestion: Kotlin reports a failed protocol-version lookup as non-retryable — packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt:826-837 (thread)

Disputed — left to maintainers (1)

  • 🟡 Suggestion: Validate layout discriminants before crossing the C ABI — packages/rs-platform-wallet-ffi/src/identity_creation_key_layout.rs:22-39 (thread)
Review provenance

Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 5: gpt-6.2-astra (agent: phase2-reviewer, role: rust-quality); reviewer 6: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); reviewer 7: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 8: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.2-sol (effort low) — The cross-language migration changes key handling itself: identity_derive_and_persist.rs now uses a layout rather than a key count to determine which identity keys it derives and persists, and both mobile clients rely on that layout for registration.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (lane failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift:1286-1292: Reserve the Rust-computed address fee when selecting Swift registration inputs
  Impact: A SwiftExampleApp user who accepts the full-balance default for a Platform Payment account with one address holding 1 DASH cannot create the identity.
  Platform rejects the default registration for insufficient fee balance. Selecting the account prefills 1 DASH, `canSubmit` accepts an amount equal to the balance, and `buildInputs` assigns that entire balance to the identity. The SDK uses `DeductFromInput(0)`, so Platform checks what remains on the first address in Rust's `BTreeMap` order after subtracting its contribution: zero. With multiple addresses, leaving credits on a different input does not pay the fee. As part of moving registration minimums into Rust, have the wallet return a fee-aware funding plan for the selected layout and use it for the amount prefill, submit gate, and input selection.

In `packages/rs-platform-wallet-ffi/src/error.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/error.rs:1342-1356: New creation-key failures silently default to invalid parameter
  Impact: If the wallet adds a creation-key error that the caller cannot fix, hosts will still receive an invalid-parameter error unless the FFI mapping is updated.
  `ValidationUnavailable` and `InactiveKeyFormat` have explicit mappings, but `IdentityCreationKeys(..)` assigns code 2 to every other inner variant, including future ones. The book requires per-variant FFI error mappings to break compilation when an error variant is added. Group the six remaining variants explicitly under `ErrorInvalidParameter` so their current behavior stays the same and the next variant requires a deliberate classification.

In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt`:
- [SUGGESTION] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt:826-837: Kotlin reports a failed protocol-version lookup as non-retryable
  (carried; thread: https://github.com/dashpay/platform/pull/5647#discussion_r4661167772)

@lklimek
lklimek force-pushed the fix/platform-wallet-dip11-identity-key-layout-bindings branch from 3a92d2d to 8fd129e Compare November 24, 2026 12:12
@Claudius-Maginificent
Claudius-Maginificent marked this pull request as draft November 24, 2026 12:16
@Claudius-Maginificent Claudius-Maginificent added the priority: medium Medium priority label Nov 24, 2026
HashEngineering added a commit that referenced this pull request Nov 26, 2026
…and settle the review's suggestions

- ErrorAssetLockRecipientUnknown 81 -> 89 and
  ErrorAssetLockConsumptionUnknown 82 -> 90: #5865 holds 81, #5647
  holds 82, and 83-88 are taken on v5.2-dev. Registry rows moved; next
  allocatable integer 91.
- SQLite restores the derived address, used, in place of a funding row
  whose stored address its index does not derive, so no lock is paid to
  an address the wallet cannot sign for.
- The assignment docs promise no leftover assignment only after a
  refused backend write; after another error the host reads the tracked
  lock first. The recipient callback contract says a standalone
  assignment fills a missing recipient only on an existing, unconsumed
  row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
romchornyi added a commit that referenced this pull request Nov 26, 2026
…ntity-fr (d7d22a9)

The base renumbered the identity-recipient codes to 89 (recipient unknown) and 90
(consumption unknown), since 81 and 82 belong to #5865 and #5647: Swift's raw values, their
docs and the pin tests follow. Both sides' result codes and errors are kept, the schema doc
lists both sides' additions, and the parity summary is regenerated from the merged manifest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lklimek and others added 4 commits December 2, 2026 16:08
Stacked on the Rust-core split of #5645. Restores the host-facing half:
- FFI: platform_wallet_identity_creation_key_layout,
  platform_wallet_identity_creation_min_funding_duffs,
  platform_wallet_identity_creation_from_addresses_min_fees,
  platform_wallet_resume_identity_key_layout and their frees; the
  layout-based dash_sdk_derive_and_persist_identity_keys and
  platform_wallet_preview_identity_registration_key_set
- JNI: identityCreationKeyLayout, identityCreationMinFundingDuffs,
  identityCreationFromAddressesMinFees, resumeIdentityKeyLayout and the
  layout-taking previewRegistrationKeySet, with golden layout BLOBs
  shared with the Kotlin decoder test
- Swift and Kotlin: derive and register the Rust layout (including the
  MEDIUM authentication key), read funding minimums and the resume
  layout from Rust, and drop the host-side key and fee tables

Must land together with the Rust core: without it the example apps send
key sets the creation pre-flight refuses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e bindings

The base PR registers new identities with keys 0-3 (plus the DashPay pair
at 4-5) and no AUTHENTICATION/MEDIUM key, so a resume re-derives the
NewIdentity layout. The bindings follow:

- FFI: IdentityCreationKeyLayoutFFI loses AssetLockResume (= 2) and
  platform_wallet_resume_identity_key_layout is removed.
- JNI: resumeIdentityKeyLayout and ordinal 2 are removed; the layout
  golden files are re-emitted without the MEDIUM row, and the asset-lock
  resume golden is gone (it equals the new-identity one).
- Kotlin and Swift: the ASSET_LOCK_RESUME / assetLockResume layout and
  resumeKeyLayout / resumeIdentityKeyLayout are removed; the example
  apps resume with the new-identity layout.

The host-facing layout and minimum-funding APIs stay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG
…s by its own code

IdentityCreationKeysError::InactiveKeyFormat (creation keys in a version 1
or contract-group-bound format the wallet's protocol version does not admit)
fell into the ErrorInvalidParameter arm, telling hosts their keys were
malformed. It now maps to ErrorIdentityKeyFormatNotActive (82), registered in
ERROR_CODE_REGISTRY.md (81 is held by two open branches), and Swift
(PlatformWalletError.identityKeyFormatNotActive) and Kotlin
(DashSdkError.PlatformWallet.IdentityKeyFormatNotActive) type it. Kotlin
reaches it through JNI's delegation to the FFI registration entry points.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nows

The protocol version refresh before validation is best-effort, so an
inactive key format is relative to the newest version the SDK knows, not
proof that the network still refuses it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lklimek
lklimek force-pushed the fix/platform-wallet-dip11-identity-key-layout-bindings branch from 8fd129e to 1dce118 Compare December 3, 2026 07:11

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority: medium Medium priority

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants