Skip to content

feat(swift-example-app): create an entry of any private document type from the shielded pool (type 29) - #6130

Merged
QuantumExplorer merged 9 commits into
v5.1-devfrom
feat/swift-example-private-document-create
Nov 23, 2026
Merged

QuantumExplorer merged 9 commits into
v5.1-devfrom
feat/swift-example-private-document-create

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Basic explanation

A private document type (protocol version 15) stores fixed-size encrypted entries, appended by an anonymous transition paid from the shielded pool (state transition type 29, PrivateDocumentCreateFromShieldedPool). So far, SwiftExampleApp could append an entry only as a DashPay private contact request. With this PR the app can append an entry to any private type of any contract. You fill in a form built from the type's schema, pick the recipient identity and one of its keys, see the fee, and pay from the shielded pool. The new entry then shows on the type's existing Read Entries screen.

Before: Contracts → a contract → a type with the Private badge offered only Read Entries. Type 29 could be sent only from DashPay's Add Contact screen.

After: the same screen also offers Create Entry (documentType.privateEntryCreateLink). On it you pick:

  • a wallet and a sender identity;
  • a recipient identity id and one of its keys, which Rust lists;
  • Anonymous or Deniable MAC.

Then you fill the properties form and see the fee preview (Fee (at least), from Rust) before pressing Create. Each result has its own screen state:

  • success shows the entry's commitment and a link to Read Entries, where the entry shows as Recovered (outgoing) (and as Received when the recipient is one of the wallet's identities);
  • a refusal is shown verbatim;
  • a "may have gone through" result is held, and the screen does not send again.

What "general" means today

Building a generic create first meant settling who an entry is sealed to and how its sender can recover it. The DashPay flow derives both from the contact relationship. For any other type, the wallet's read of a private type's store (read_private_document_entries, #6052) already has a rule for every private type, and this PR seals against that same rule, so what it writes is what the read finds:

  • Recipient key: an ECDSA_SECP256K1 key with purpose ENCRYPTION or DECRYPTION, chosen explicitly by the user from the list Rust returns. A new entry is refused for a disabled key. The read side's scanning_key now calls the same function (is_private_document_key), so the rule lives in one place.
  • Sender: one of the wallet's identities with an enabled ECDSA_SECP256K1 ENCRYPTION key at its identity key slot. The entry's outgoing viewing key is private_document_outgoing_viewing_key of that key's secret, the same derivation the read uses for sent entries. The secret stays inside the mnemonic-resolver signer.
  • Authentication: Anonymous, or a deniable MAC naming that encryption key as the sender key.
  • Fee: the type 29 formula, computed in Rust: compute_private_document_create_from_shielded_pool_fee, the base shielded fee plus a fixed charge per entry from the type's entrySize. The preview uses 2 Orchard actions, the fewest the spend builds with, hence "at least". Up to max_private_document_entries_per_transition (16 at protocol version 15) entries fit one transition; this screen sends one.

Not covered, and left open on purpose (see "Open questions"):

  • signed entries;
  • the contract-bound key keywords a private type may declare;
  • senders whose encryption key does not derive at its identity key slot, such as DashPay Connect application keys.

Issue being fixed or feature implemented

This lets SwiftExampleApp exercise type 29 on a live network for any private type, not only DashPay's, after the protocol version 14 to 15 upgrade rehearsal. The test plan rows for the existing DashPay private flows are in #6117.

What was done?

  • rs-sdk: new platform::private_document_seal. It checks a request to seal an entry of any private type (type is private, recipient and sender keys, properties against the type's schema with validate_private_document_properties, encoded payload fits entrySize - 299) and seals it with platform_encryption::seal_private_document_entry.
  • rs-platform-wallet:
    • IdentityWallet::seal_private_document_entry: finds the sender among the wallet's identities, fetches the contract and recipient, runs the check, then seals inside the signer.
    • PlatformWallet::create_private_document_entry: seals, then pays with the existing private_document_create_from_pool_with_metadata. It is the same builder, redrive record and outcome classification the DashPay private request uses, with no DashPay journal or pair hold, and it takes the wallet generation guard before spending.
    • Plus the recipient key list and the fee preview.
  • Signer: a new ContactCryptoProvider::seal_private_document_entry, defaulted to "unsupported". It is implemented by the mnemonic-resolver signer (rs-sdk-ffi) and the test provider.
  • rs-platform-wallet-ffi: three exports plus a free function (below).
  • Swift: wrappers on PlatformWalletManager in PrivateDocuments.swift, and the new PrivateDocumentEntryCreateView. The view reuses CreateDocumentView's schema-driven DocumentFieldsView and only gathers input and shows what Rust returns. It has no fee arithmetic, no validation and no key fields.
  • Small refactor: the properties-JSON parse and sanitize step that network/document.rs had twice is one helper now (document_properties_from_json), with the same error messages. The new create uses it too.
  • TEST_PLAN.md: a new row DOC-19, and DOC-17's note that no create flow exists now points to it. Counts and the index are updated.
  • Parity: docs/sdk/sdk-parity-manifest.json gains documents.private_document_entry_create, and PARITY_SUMMARY.md is regenerated, as packages/swift-sdk/CLAUDE.md requires. Kotlin is not ported.

No Drive, DPP or consensus code changes, and no shipped generation is touched.

New public interfaces

rs-sdk: dash_sdk::platform::private_document_seal

  • is_private_document_key(&IdentityPublicKey) -> bool: the key can have entries sealed to it. That means ECDSA_SECP256K1, purpose DECRYPTION or ENCRYPTION, disabled keys included, which is what the read scans with.
  • private_document_recipient_key(&Identity, KeyID) -> Result<PublicKey, PrivateDocumentSealError>: the key a new entry may be sealed to. That is the rule above, plus not disabled, plus a valid point.
  • private_document_recipient_keys(&Identity) -> Vec<&IdentityPublicKey>: the keys that pass that check.
  • private_document_sender_key(&Identity, KeyID) -> Result<PublicKey, PrivateDocumentSealError>: an enabled ECDSA_SECP256K1 ENCRYPTION key.
  • enum PrivateDocumentSealError: the module's typed error. It has one variant for each refusal of the request: unknown type, type not private, missing, unusable, disabled or invalid key (each tagged sender or recipient), invalid properties, payload encoding, payload too large. Two more variants are not the caller's fault: secret key mismatch and envelope sealing failure. is_refused_request() tells the two groups apart. platform-wallet converts refusals to PlatformWalletError::InvalidParameter and the rest to InvalidIdentityData.
  • enum PrivateDocumentSenderAuth { Anonymous, DeniableMac }, also re-exported from the platform-wallet crate root.
  • struct PrivateDocumentEntryRequest<'a> { contract, document_type_name, sender, sender_encryption_key_id, auth, recipient, recipient_key_id, properties }, with check(&self, &PlatformVersion) -> Result<(), PrivateDocumentSealError>. It checks that the type is private, both keys, the properties against the schema, and that the encoded payload fits the type's capacity.
  • seal_private_document(&PrivateDocumentEntryRequest, encryption_secret_key: &SecretKey, esk_seed: &[u8; 32], &PlatformVersion) -> Result<BinaryData, PrivateDocumentSealError>:
    • runs check;
    • refuses a secret key that is not the sender key's;
    • seals with the outgoing viewing key derived from that secret.
    • esk_seed must be fresh for every entry.

rs-platform-wallet

  • ContactCryptoProvider::seal_private_document_entry(&self, sender_encryption_key_path: &DerivationPath, request: &PrivateDocumentEntryRequest<'_>, esk_seed: &[u8; 32], platform_version: &PlatformVersion) -> Result<BinaryData, PlatformWalletError>: a new trait method, defaulted to an "unsupported" error, so existing providers keep compiling. The encryption secret key never returns to platform-wallet.

  • IdentityWallet::seal_private_document_entry(&self, crypto, &NewPrivateDocumentEntry) -> Result<SealedPrivateDocumentEntry, PlatformWalletError>. Everything that can be refused is checked before the signer is asked:

    • the sender must be one of the wallet's identities, with an HD index and an enabled encryption key at its slot;
    • the contract must be on a protocol version 15 network and the type private;
    • the properties JSON must parse;
    • the recipient must exist;
    • the request must pass check.

    Then it checks the mnemonic binds the wallet (verify_seed_binds), picks the sender's first encryption key whose slot derives the registered key, and seals with a fresh OS-random esk_seed. Bad input is InvalidParameter(reason); an unknown identity is IdentityNotFound.

  • PlatformWallet::create_private_document_entry(&self, coordinator, seed, account, &NewPrivateDocumentEntry, crypto, prover) -> Result<PrivateDocumentEntryCreated, PlatformWalletError> (feature shielded): seals, takes the generation guard, derives the spend keyset for this call only, then appends the entry paying from account's notes. A result that may have executed is ShieldedSpendUnconfirmed; the notes and the redrive record are kept, as for every pool-paid spend.

  • async fn private_document_recipient_key_choices(&Sdk, Identifier) -> Result<Vec<PrivateDocumentRecipientKey>, PlatformWalletError>: fetches the identity and returns its eligible keys.

  • async fn private_document_create_fee(&Sdk, Identifier, &str, entry_count: usize) -> Result<Credits, PlatformWalletError> and the pure private_document_create_fee_for(&DataContract, &str, entry_count, &PlatformVersion):

    • the fee is computed at PRIVATE_DOCUMENT_CREATE_FEE_PREVIEW_ACTIONS (2) actions, at the network's platform version;
    • an entry count of 0 is refused, as is one above max_private_document_entries_per_transition;
    • a type that is not private is refused.
  • Types:

    • NewPrivateDocumentEntry { data_contract_id, document_type_name, sender_identity_id, recipient_identity_id, recipient_key_id, auth, properties_json };
    • SealedPrivateDocumentEntry { entry, commitment, sender_key_id };
    • PrivateDocumentEntryCreated { commitment, sender_key_id };
    • PrivateDocumentRecipientKey { key_id, purpose }.

rs-sdk-ffi

  • MnemonicResolverCoreSigner::seal_private_document_entry(&self, &DerivationPath, &PrivateDocumentEntryRequest, &[u8; 32], &PlatformVersion) -> Result<BinaryData, MnemonicResolverSignerError>: derives the key at the path inside the signer, seals, and wipes the key.
  • A new error variant, MnemonicResolverSignerError::PrivateDocument(PrivateDocumentSealError).

FFI (rs-platform-wallet-ffi)

All three exports catch panics and reset their out-parameters first. The struct layouts are pinned with compile-time size and offset asserts.

  • platform_wallet_manager_private_document_recipient_keys(handle: Handle, identity_id: *const u8, out_keys: *mut PrivateDocumentRecipientKeysFFI) -> PlatformWalletFFIResult:
    • fetches the identity and writes its eligible keys;
    • PrivateDocumentRecipientKeysFFI is { keys: *mut PrivateDocumentRecipientKeyFFI, count: usize }, and each key is { key_id: u32, purpose: u8 } (1 = ENCRYPTION, 2 = DECRYPTION);
    • release with platform_wallet_private_document_recipient_keys_free(*mut PrivateDocumentRecipientKeysFFI), which is idempotent and accepts null;
    • an unknown identity is ErrorIdentityNotFound.
  • platform_wallet_manager_private_document_create_fee(handle: Handle, data_contract_id: *const u8, document_type_name: *const c_char, entry_count: u32, out_fee: *mut u64) -> PlatformWalletFFIResult: the fee preview above, in credits.
  • platform_wallet_manager_create_private_document_entry(handle: Handle, wallet_id_bytes: *const u8, mnemonic_resolver_handle: *mut MnemonicResolverHandle, account: u32, data_contract_id: *const u8, document_type_name: *const c_char, sender_identity_id: *const u8, recipient_identity_id: *const u8, recipient_key_id: u32, auth_mode: u8, properties_json: *const c_char, out_created: *mut PrivateDocumentEntryCreatedFFI) -> PlatformWalletFFIResult (feature shielded):
    • auth_mode is 0 for anonymous and 1 for deniable MAC; any other value, signed (2) included, is ErrorInvalidParameter;
    • PrivateDocumentEntryCreatedFFI is { commitment: [u8; 32], sender_key_id: u32 };
    • errors follow the shielded spend contract: ErrorShieldedSpendUnconfirmed means the entry may already be on chain, so do not send again;
    • a mnemonic that is not the wallet's is refused before anything is paid;
    • a null pointer is ErrorNullPointer, a refusal of the request (bad key, properties that do not validate or are not a JSON object) is ErrorInvalidParameter, an identity neither the wallet nor the network holds is ErrorIdentityNotFound, and a wallet removed or re-created since the handle was taken is refused before sealing.

Swift (SwiftDashSDK)

  • PrivateDocumentSenderAuth (.anonymous, .deniableMac), PrivateDocumentRecipientKey (keyId, purpose, purposeName), PrivateDocumentEntryCreated (commitment, senderKeyId).
  • PlatformWalletManager.privateDocumentRecipientKeys(identityId:).
  • PlatformWalletManager.privateDocumentCreateFee(contractId:documentTypeName:entryCount:).
  • PlatformWalletManager.createPrivateDocumentEntry(walletId:resolver:account:contractId:documentTypeName:senderIdentityId:recipientIdentityId:recipientKeyId:auth:propertiesJSON:).

They live on the manager, not ManagedPlatformWallet, because the spend needs the manager's shielded coordinator, as sendPrivateContactRequest does.

How Has This Been Tested?

  • cargo test -p dash-sdk --lib private_document_seal: 7 passed. These cover a sealed entry that the recipient opens and verifies by MAC and that the sender's outgoing viewing key recovers, plus the refusals, the eligible key list and the capacity check.
  • cargo test -p platform-wallet --features shielded --lib private_document: 27 passed (21 existing read tests plus 6 new ones):
    • a seal read back by the real read_private_document_entries as Sent, with the same commitment, claimed sender and properties;
    • an anonymous seal;
    • refusals before the signer is asked (with a provider that panics if called);
    • a sender the wallet does not hold;
    • the key choices;
    • the fee preview.
  • After review: private_document_create in platform-wallet 11 passed (malformed JSON, refusal before anything is paid, wallet no longer current, current wallet passes the liveness check); platform-wallet-ffi 7 passed (refusal codes, null identity pointers, a key of another purpose left out). Clippy is clean again on all four crates, and the app builds with warnings as errors.
  • Regression subsets: network::document, 25 passed; private_contact, 145 passed.
  • cargo test -p platform-wallet-ffi --features shielded --lib private_document: 12 passed, including 4 new marshalling tests.
  • cargo test -p rs-sdk-ffi --lib on the private contact request signer tests: 9 passed. The new resolver-signer seal matches a seed-derived seal, and its typed refusal is covered.
  • cargo clippy --all-targets --all-features --locked -- --no-deps -D warnings on dash-sdk, platform-wallet, rs-sdk-ffi and platform-wallet-ffi: clean. cargo fmt --all was run.
  • ./build_ios.sh --target sim (release xcframework) and the SwiftExampleApp simulator build: succeeded. The new FFI symbols are in the header and the view compiles.

Not yet verified

  • No simulator run of the screen, and no run against a protocol version 15 network (DOC-19 says so).
  • No Swift unit tests for the new wrappers.
  • An unconfirmed result through create_private_document_entry itself; it would need funded notes, a real proof and an intercepted broadcast. The result is passed up unchanged from the shared spend, whose unconfirmed handling is tested.
  • Recovery after a restart mid-payment relies on the existing redrive record of pool-paid spends; this flow has no restart test of its own.

Open questions

  1. Signed entries. The envelope's signature mode (auth mode 2) leaves which keys may sign to the application. DashPay signs with an authentication key and names its encryption key. Which keys may sign an entry of a private type that is not DashPay's, and what the sender key id should name, is not decided, so this PR refuses mode 2.
  2. Contract-bound keys. A private type may declare requiresIdentityEncryptionBoundedKey / requiresIdentityDecryptionBoundedKey (PRIVATE_DOCUMENT_TYPE_KEYWORDS in rs-dpp/src/data_contract/document_type/private_document.rs). Neither the read nor this create consults them. DashPay checks key bounds for its own type (bounds_problem in rs-sdk/src/platform/dashpay/private_contact_request.rs). Should a generic create (and read) prefer or require a key bound to the contract when the type declares them?

Breaking Changes

None. The new trait method has a default implementation.

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 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
  • If I added or changed GroveDB structure, I described it in the area's structure.rs, regenerated grovedb-structure.json, and checked the structure viewer link posted on this pull request
  • If I added or changed a system contract's document schemas, I checked the contract viewer link posted on this pull request

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

PR Hygiene · 65c7b33

  • Bots — thepastaclaw not yet — /skip-bots proceeds without the ones not yet reported
  • Self-review — post /self-reviewed
  • Reviewer requests paused — your 5 review slots are occupied; this PR is excluded from reviewers' queues. Required approvals still count without a slot.
  • Build running
  • Approvals
    • sdk-parity — you own it
    • kotlin-sdk (packages/kotlin-sdk/PARITY_SUMMARY.md) — HashEngineering
    • rs-platform-wallet-ffi (packages/rs-platform-wallet-ffi/src/dashpay.rs, packages/rs-platform-wallet-ffi/src/lib.rs, packages/rs-platform-wallet-ffi/src/private_document_create.rs) — HashEngineering or ZocoLini or llbartekll or romchornyi
    • rs-platform-wallet (packages/rs-platform-wallet/src/error.rs, packages/rs-platform-wallet/src/lib.rs, packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs and 5 more) — HashEngineering or ZocoLini or llbartekll or romchornyi
    • rust-sdk-ffi (packages/rs-sdk-ffi/src/mnemonic_resolver_core_signer.rs) — lklimek or shumkov
    • rust-sdk (packages/rs-sdk/src/platform.rs, packages/rs-sdk/src/platform/private_document_seal.rs) — lklimek or shumkov
    • swift-sdk (packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PrivateDocuments.swift, packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentTypeDetailsView.swift, packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/PrivateDocumentEntryCreateView.swift and 1 more) — llbartekll or romchornyi

When every merge requirement is met, the PR Hygiene check passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.

QuantumExplorer and others added 3 commits November 23, 2026 15:34
Add `platform::private_document_seal`: the key rule a wallet reads a
private type's store with (`is_private_document_key`), the keys an entry
may be sealed to now (`private_document_recipient_key`,
`private_document_recipient_keys`), the sender's encryption key check
(`private_document_sender_key`), and `seal_private_document`, which checks
a `PrivateDocumentEntryRequest` against the type (private, schema,
capacity) and seals one entry, anonymous or with a deniable MAC, with the
sender encryption key's outgoing viewing key so the sender's wallet
recovers it from the store alone. Signed entries are not built here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tity, paid from the shielded pool

`PlatformWallet::create_private_document_entry` seals one entry of any
private type from one of the wallet's identities to a chosen key of any
identity (`IdentityWallet::seal_private_document_entry`) and appends it
with the existing type 29 spend, under the wallet generation's lifecycle
gate. The sender seals with its first enabled ECDSA_SECP256K1 ENCRYPTION
key whose identity key slot derives the registered key, so a read of the
store recovers the entry as sent; its secret key stays in the new
`ContactCryptoProvider::seal_private_document_entry` (defaulted to
unsupported, implemented on the resolver-backed signer and the test
provider). The read side's `scanning_key` now uses the SDK's rule.

Also `private_document_recipient_key_choices` (a fetched identity's keys an
entry may be sealed to) and `private_document_create_fee` (the fee the
spend reserves at two actions), and the FFI exports
`platform_wallet_manager_private_document_recipient_keys`,
`platform_wallet_manager_private_document_create_fee` and
`platform_wallet_manager_create_private_document_entry` (shielded builds).
Document properties JSON parsing moves into one helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… (type 29)

A private type's detail screen gains **Create Entry** next to **Read
Entries**: `PrivateDocumentEntryCreateView` picks the paying wallet, the
sender among its identities, the recipient and one of the keys Rust lists
for it, anonymous or deniable-MAC authentication, and fills the
schema-driven document form; it shows the fee Rust previews and the
outcome (created with its commitment and a link to Read Entries, may have
gone through, or Rust's refusal verbatim). The Swift SDK wraps the three
new exports on `PlatformWalletManager`
(`privateDocumentRecipientKeys`, `privateDocumentCreateFee`,
`createPrivateDocumentEntry`), marshalling only.

TEST_PLAN gains DOC-19 and DOC-17 points to it; the parity manifest
records the new capability.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@QuantumExplorer
QuantumExplorer marked this pull request as ready for review November 23, 2026 08:56
@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 23 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 9c38af8 and 23ac124.

Files selected for processing: 20

  • docs/sdk/sdk-parity-manifest.json
  • packages/kotlin-sdk/PARITY_SUMMARY.md
  • packages/rs-platform-wallet-ffi/src/dashpay.rs
  • packages/rs-platform-wallet-ffi/src/lib.rs
  • packages/rs-platform-wallet-ffi/src/private_document_create.rs
  • packages/rs-platform-wallet/src/error.rs
  • packages/rs-platform-wallet/src/lib.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/document.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/mod.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/private_document_create.rs
  • packages/rs-platform-wallet/src/wallet/identity/network/private_documents.rs
  • packages/rs-platform-wallet/src/wallet/platform_wallet.rs
  • packages/rs-sdk-ffi/src/mnemonic_resolver_core_signer.rs
  • packages/rs-sdk/src/platform.rs
  • packages/rs-sdk/src/platform/private_document_seal.rs
  • packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PrivateDocuments.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentTypeDetailsView.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/PrivateDocumentEntryCreateView.swift
  • packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md
  • 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

@github-actions github-actions Bot added this to the v5.1.0 milestone Nov 23, 2026
@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Nov 23, 2026
@thepastaclaw

thepastaclaw commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

⏹️ Not reviewed — PR is closed (merged) (commit 9e82dee)

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

⚠️ DEGRADED — Final validation — Phase 1 + Phase 2

⚠️ DEGRADED review. The primary review models were unavailable (gpt-6.2-astra unavailable: Request rejected (429) · All credentials for model gpt-6.2-astra are cooling down (last error: usage_limit_reached: The ), so this review ran on stand-in models: gpt-5.6-luna → muse-spark-1.3-contributor, gpt-5.6-sol → muse-spark-1.3-contributor, gpt-5.6-terra → muse-spark-1.3-contributor, gpt-6-astra → muse-spark-1.3-contributor, gpt-6.1-sol → muse-spark-1.3-contributor, gpt-6.2-astra → muse-spark-1.3-contributor, gpt-6.2-sol → muse-spark-1.3-contributor. Both review phases and the independent verifiers still ran, but on weaker models, with Phase 1 capped at high effort. Treat the verdict as provisional; a full-strength re-review will run on the next push once the primary models are back.

Nothing blocks: no blocking finding stands on this head.

Adds a generic type-29 private-document create from the shielded pool, with sealing in rs-sdk, orchestration in platform-wallet, three FFI exports, and a schema-driven Swift form. CI shows Kotlin build success with most Rust and e2e jobs skipped and review checks still pending.

🟡 7 suggestion(s)

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: muse-spark-1.3-contributor (standing in for gpt-6.2-astra) (agent: phase2-reviewer, role: general); reviewer 4: muse-spark-1.3-contributor (standing in for gpt-6.2-astra) (agent: phase2-reviewer, role: architecture-layering); reviewer 5: muse-spark-1.3-contributor (standing in for gpt-6.2-astra) (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: muse-spark-1.3-contributor (standing in for gpt-6.2-astra) (agent: phase2-reviewer, role: rust-quality); reviewer 7: muse-spark-1.3-contributor (standing in for gpt-6.2-astra) (agent: phase2-reviewer, role: security-auditor); final verifier: muse-spark-1.3-contributor (standing in for gpt-6.2-sol) (agent: sol-verifier, role: final-verifier)

  • Degraded mode: gpt-6.2-astra unavailable: Request rejected (429) · All credentials for model gpt-6.2-astra are cooling down (last error: usage_limit_reached: The (detected by lane, since 2026-11-23T09:05:53Z); stand-ins gpt-5.6-luna → muse-spark-1.3-contributor, gpt-5.6-sol → muse-spark-1.3-contributor, gpt-5.6-terra → muse-spark-1.3-contributor, gpt-6-astra → muse-spark-1.3-contributor, gpt-6.1-sol → muse-spark-1.3-contributor, gpt-6.2-astra → muse-spark-1.3-contributor, gpt-6.2-sol → muse-spark-1.3-contributor; Phase 1 effort capped at high
  • Triage: critical by gpt-6.2-sol (effort low) — The diff adds an intricate shielded-pool spend flow in the wallet's private_document_create.rs and new recipient-key validation, encryption, and sender recovery-key handling in private_document_seal.rs and mnemonic_resolver_core_signer.rs.
  • 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: muse-spark-1.3-contributor (standing in for gpt-6.2-sol) — final-verifier; agent sol-verifier
  • Phase 2 reviewers: muse-spark-1.3-contributor (standing in for gpt-6.2-astra) — general (completed, effort high); agent phase2-reviewer, muse-spark-1.3-contributor (standing in for gpt-6.2-astra) — architecture-layering (completed, effort high); agent phase2-reviewer, muse-spark-1.3-contributor (standing in for gpt-6.2-astra) — ffi-engineer (completed, effort high); agent phase2-reviewer, muse-spark-1.3-contributor (standing in for gpt-6.2-astra) — rust-quality (completed, effort high); agent phase2-reviewer, muse-spark-1.3-contributor (standing in for 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/rs-platform-wallet-ffi/src/private_document_create.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/private_document_create.rs:474-480: Create export reports fix-the-form refusals as a wallet-operation failure
  Impact: A host calling create with a bad sender, recipient key, properties, or unknown identity gets ErrorWalletOperation and cannot tell fix-the-form input from an operational failure.
  The consequence is hosts cannot branch on the documented ErrorInvalidParameter and ErrorIdentityNotFound codes. The mechanism is the final mapper: seed_mismatch_result passes everything except SeedMismatch to map_spend_result, whose preserved arms cover ShieldedSpendUnconfirmed, PrivateContactRequestPending, WalletRemovedBeforeSend, ProtocolVersionNotActive and a few others but have no arm for PlatformWalletError::InvalidParameter from refused() or PlatformWalletError::IdentityNotFound for unknown sender or recipient, so they fall to the catch-all ErrorWalletOperation with "private document create failed: ...". The sibling read and fee exports use unwrap_result_or_return and From and do preserve those codes. Fix by preserving them here, for example adding Err(e @ PlatformWalletError::InvalidParameter(..)) and Err(e @ PlatformWalletError::IdentityNotFound(..)) arms that return e.into() before the catch-all, or correcting the documented codes.
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/private_document_create.rs:411-415: Null sender and recipient identity pointers report as a bad identifier value
  Impact: A host passing NULL for sender_identity_id or recipient_identity_id gets ErrorInvalidIdentifier, making a programming error look like a bad identifier value.
  The consequence is inconsistent codes for the same mistake in one function. The mechanism is the inner create guards five pointers with check_ptr! but not sender_identity_id and recipient_identity_id; those fall through to read_identifier, whose null branch returns ProtocolError::IdentifierError that converts to ErrorInvalidIdentifier. The sibling recipient-keys and fee exports guard the identity pointer with check_ptr!. Fix by adding the two missing guards alongside the others.
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/private_document_create.rs:73-80: Recipient key purpose byte silently tracks Purpose discriminants with no build signal
  Impact: If dpp renumbers Purpose, hosts silently misread ENCRYPTION as DECRYPTION with no build failure since the numeric values are the cross-language contract.
  The consequence is a silent ABI drift with no compiler signal. The mechanism is purpose: key.purpose as u8 leans on repr(u8) discriminants ENCRYPTION equal to 1 and DECRYPTION equal to 2, documented only in a comment, while the same file pins every struct layout with compile-time size and offset asserts. Fix by making the numbers structural like the layouts, either with an explicit match on Purpose in the From impl or with const asserts pinning Purpose::ENCRYPTION as u8 equal to 1 and Purpose::DECRYPTION as u8 equal to 2 next to the existing layout asserts.

In `packages/rs-platform-wallet/src/wallet/identity/network/private_document_create.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/private_document_create.rs:325-329: Malformed properties JSON is reported as an operational failure instead of an invalid parameter
  Impact: A host sending bad properties_json for a generic private entry gets a wallet-operation or unknown error, so a user-fixable input error reads as an internal failure.
  The consequence is a fix-the-form input reads as an internal failure, contradicting the function's own docs that every refusal of what was asked is InvalidParameter. The mechanism is document_properties_from_json returns PlatformWalletError::InvalidIdentityData for malformed JSON, and neither the blanket FFI From which has an InvalidParameter arm but no InvalidIdentityData arm nor the create path's map_spend_result catch-all maps it to InvalidParameter. Fix by mapping it at this call site where the JSON is direct host input.

In `packages/rs-sdk/src/platform/private_document_seal.rs`:
- [SUGGESTION] packages/rs-sdk/src/platform/private_document_seal.rs:51-80: Seal callers cannot match refusals because key and schema checks return strings
  Impact: Wallet code and any future SDK caller must match message text to tell a bad key from a bad schema, and variant-keyed retry logic cannot recognize these deterministic refusals.
  The consequence is fragile classification that silently mislabels future Generic cases as caller-input errors. The mechanism is private_document_recipient_key and private_document_sender_key return Result with String, validate_private_document_properties returns Result with String, and checked funnels them through Error::Generic; downstream refused() in private_document_create.rs can then only map Generic to InvalidParameter while Protocol errors from encode_private_document_payload leak through as a different Sdk shape for the same user-input failure. The tests confirm the trap by asserting with contains on message text instead of matching a variant. Fix by returning a typed error such as Error::InvalidRequest from the key helpers and the check path and updating the map_err Error::Generic call sites and refused() accordingly; the pre-existing contact-request code uses the same Generic pattern, so this also stops the new module entrenching it.

In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/PrivateDocumentEntryCreateView.swift`:
- [SUGGESTION] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/PrivateDocumentEntryCreateView.swift:503-510: Create screen stays submittable after an unconfirmed spend and allows a second paid entry
  Impact: A user who taps Create Entry again after the may-have-gone-through notice pays a second shielded fee and appends a duplicate entry with a fresh commitment.
  The consequence is a second tap pays again for a duplicate entry. The mechanism is after ShieldedSpendUnconfirmed the view sets outcome to .unconfirmed and releases isSubmitting via defer, but canSubmit only checks wallet, sender, and recipientKeysFor and key and never consults outcome, so the Create button re-enables while the unconfirmed banner is shown. The PR description's does-not-send-again covers only automatic resends. Fix by gating canSubmit or the button on the unconfirmed state until the user changes the form or restarts, for example returning false when outcome is .unconfirmed.

In `packages/rs-platform-wallet/src/wallet/platform_wallet.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:2577-2626: New pool-paid spend path has no test for its guard, removal, or unconfirmed outcomes
  Impact: A regression in the generation gate, WalletRemovedBeforeSend refusal, or ShieldedSpendUnconfirmed handling ships undetected and risks a double-send or a lost-spend confusion for pool-paid entries.
  The consequence is PlatformWallet::create_private_document_entry moves real shielded funds through a seal-then-spend sequence with lifecycle and redrive semantics yet nothing exercises it. The mechanism is the six new wallet tests cover seal_private_document_entry, key choices, and the fee preview, and a repo-wide grep shows no test calling create_private_document_entry at all; the function adds the generation payment guard plus is_current_generation refusal, derive_spend_keyset wiring, and the private_document_create_from_pool_with_metadata redrive and unconfirmed contract the FFI docs promise do not create it again. Fix with focused tests using mock coordinator and prover as the neighboring shielded-spend tests do for refusal-before-spend ordering, removed-wallet refusal with nothing recorded or paid, and unconfirmed-error propagation that tells Swift not to resend.
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.

  • Decide the owner for contract-bound key policy for generic private types — Neither the existing private-document read nor this generic create consults requiresIdentityEncryptionBoundedKey or requiresIdentityDecryptionBoundedKey; DashPay enforces its own bounds check for its type only. A type author declaring those keywords could get entries sealed to unbound keys. This predates the PR and the PR explicitly leaves it open, so it needs a separate design decision covering create and read.
    • Follow-up: Open a follow-up issue to decide whether a generic create and read must prefer or require a contract-bound key when the type declares the keywords, and link it from the PR open question.

Comment on lines +474 to +480
match result {
Ok(created) => {
unsafe { *out_created = created.into() };
PlatformWalletFFIResult::ok()
}
Err(error) => seed_mismatch_result(error)
.unwrap_or_else(|error| map_spend_result(Err(error), CREATE_OPERATION)),

@thepastaclaw thepastaclaw Nov 23, 2026 •

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.

✅ Resolved at efee9317; see the replies below.

🟡 Suggestion: Create export reports fix-the-form refusals as a wallet-operation failure
Impact: A host calling create with a bad sender, recipient key, properties, or unknown identity gets ErrorWalletOperation and cannot tell fix-the-form input from an operational failure.

The consequence is hosts cannot branch on the documented ErrorInvalidParameter and ErrorIdentityNotFound codes. The mechanism is the final mapper: seed_mismatch_result passes everything except SeedMismatch to map_spend_result, whose preserved arms cover ShieldedSpendUnconfirmed, PrivateContactRequestPending, WalletRemovedBeforeSend, ProtocolVersionNotActive and a few others but have no arm for PlatformWalletError::InvalidParameter from refused() or PlatformWalletError::IdentityNotFound for unknown sender or recipient, so they fall to the catch-all ErrorWalletOperation with "private document create failed: ...". The sibling read and fee exports use unwrap_result_or_return and From and do preserve those codes. Fix by preserving them here, for example adding Err(e @ PlatformWalletError::InvalidParameter(..)) and Err(e @ PlatformWalletError::IdentityNotFound(..)) arms that return e.into() before the catch-all, or correcting the documented codes.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 256d47c. The create export now returns InvalidParameter and IdentityNotFound with their own codes before the spend mapper (create_error_result). map_spend_result is unchanged for its other callers. Covered by should_keep_the_create_s_refusal_codes.

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.

Resolved (re-reviewed at efee9317): Thank you — create_error_result now preserves InvalidParameter and IdentityNotFound before the spend mapper, with a test pinning the codes.

Comment on lines +325 to +329
let document_type = contract
.document_type_for_name(&new.document_type_name)
.map_err(|error| PlatformWalletError::InvalidParameter(error.to_string()))?;
let properties: BTreeMap<String, Value> =
document_properties_from_json(document_type, &new.properties_json)?;

@thepastaclaw thepastaclaw Nov 23, 2026 •

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.

✅ Resolved at efee9317; see the replies below.

🟡 Suggestion: Malformed properties JSON is reported as an operational failure instead of an invalid parameter
Impact: A host sending bad properties_json for a generic private entry gets a wallet-operation or unknown error, so a user-fixable input error reads as an internal failure.

The consequence is a fix-the-form input reads as an internal failure, contradicting the function's own docs that every refusal of what was asked is InvalidParameter. The mechanism is document_properties_from_json returns PlatformWalletError::InvalidIdentityData for malformed JSON, and neither the blanket FFI From which has an InvalidParameter arm but no InvalidIdentityData arm nor the create path's map_spend_result catch-all maps it to InvalidParameter. Fix by mapping it at this call site where the JSON is direct host input.

Suggested change
let document_type = contract
.document_type_for_name(&new.document_type_name)
.map_err(|error| PlatformWalletError::InvalidParameter(error.to_string()))?;
let properties: BTreeMap<String, Value> =
document_properties_from_json(document_type, &new.properties_json)?;
let properties: BTreeMap<String, Value> =
document_properties_from_json(document_type, &new.properties_json).map_err(
|error| match error {
PlatformWalletError::InvalidIdentityData(reason) => {
PlatformWalletError::InvalidParameter(reason)
}
other => other,
},
)?;

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 256d47c. Malformed properties_json now maps to InvalidParameter at this call site only; the helper's other callers keep their behavior. Covered by should_refuse_malformed_properties_json_as_an_invalid_parameter.

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.

Resolved (re-reviewed at efee9317): Thank you — malformed properties_json now maps to InvalidParameter at this call site only, leaving the helper's other callers unchanged.

Comment on lines +411 to +415
check_ptr!(wallet_id_bytes);
check_ptr!(mnemonic_resolver_handle);
check_ptr!(data_contract_id);
check_ptr!(document_type_name);
check_ptr!(properties_json);

@thepastaclaw thepastaclaw Nov 23, 2026 •

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.

✅ Resolved at efee9317; see the replies below.

🟡 Suggestion: Null sender and recipient identity pointers report as a bad identifier value
Impact: A host passing NULL for sender_identity_id or recipient_identity_id gets ErrorInvalidIdentifier, making a programming error look like a bad identifier value.

The consequence is inconsistent codes for the same mistake in one function. The mechanism is the inner create guards five pointers with check_ptr! but not sender_identity_id and recipient_identity_id; those fall through to read_identifier, whose null branch returns ProtocolError::IdentifierError that converts to ErrorInvalidIdentifier. The sibling recipient-keys and fee exports guard the identity pointer with check_ptr!. Fix by adding the two missing guards alongside the others.

Suggested change
check_ptr!(wallet_id_bytes);
check_ptr!(mnemonic_resolver_handle);
check_ptr!(data_contract_id);
check_ptr!(document_type_name);
check_ptr!(properties_json);
check_ptr!(wallet_id_bytes);
check_ptr!(mnemonic_resolver_handle);
check_ptr!(data_contract_id);
check_ptr!(document_type_name);
check_ptr!(sender_identity_id);
check_ptr!(recipient_identity_id);
check_ptr!(properties_json);

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 256d47c. Both identity pointers are now guarded with check_ptr!, and the doc comment lists ErrorNullPointer. Covered by should_refuse_a_null_sender_or_recipient_identity_id.

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.

Resolved (re-reviewed at efee9317): Thank you — both identity pointers are now check_ptr! guarded with ErrorNullPointer, covered by the null test.

Comment on lines +73 to +80
impl From<PrivateDocumentRecipientKey> for PrivateDocumentRecipientKeyFFI {
fn from(key: PrivateDocumentRecipientKey) -> Self {
Self {
key_id: key.key_id,
purpose: key.purpose as u8,
}
}
}

@thepastaclaw thepastaclaw Nov 23, 2026 •

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.

✅ Resolved at efee9317; see the replies below.

🟡 Suggestion: Recipient key purpose byte silently tracks Purpose discriminants with no build signal
Impact: If dpp renumbers Purpose, hosts silently misread ENCRYPTION as DECRYPTION with no build failure since the numeric values are the cross-language contract.

The consequence is a silent ABI drift with no compiler signal. The mechanism is purpose: key.purpose as u8 leans on repr(u8) discriminants ENCRYPTION equal to 1 and DECRYPTION equal to 2, documented only in a comment, while the same file pins every struct layout with compile-time size and offset asserts. Fix by making the numbers structural like the layouts, either with an explicit match on Purpose in the From impl or with const asserts pinning Purpose::ENCRYPTION as u8 equal to 1 and Purpose::DECRYPTION as u8 equal to 2 next to the existing layout asserts.

Suggested change
impl From<PrivateDocumentRecipientKey> for PrivateDocumentRecipientKeyFFI {
fn from(key: PrivateDocumentRecipientKey) -> Self {
Self {
key_id: key.key_id,
purpose: key.purpose as u8,
}
}
}
impl From<PrivateDocumentRecipientKey> for PrivateDocumentRecipientKeyFFI {
fn from(key: PrivateDocumentRecipientKey) -> Self {
// Pinned: the wire values 1/2 mirror `Purpose`'s `#[repr(u8)]`
// discriminants; a repr change must update this mapping, not ride along.
const _: () = assert!(dpp::identity::Purpose::ENCRYPTION as u8 == 1);
const _: () = assert!(dpp::identity::Purpose::DECRYPTION as u8 == 2);
Self {
key_id: key.key_id,
purpose: key.purpose as u8,
}
}
}

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 256d47c. The purpose byte now comes from an explicit match on every Purpose variant (ENCRYPTION 1, DECRYPTION 2). A key of any other purpose is left out of the list rather than given a value. Covered by should_leave_out_a_recipient_key_of_another_purpose.

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.

Resolved (re-reviewed at efee9317): Thank you — the purpose byte is now an explicit match on every Purpose variant with other purposes left out, as the new test pins.

Comment on lines +51 to +80
pub fn private_document_recipient_key(
recipient: &Identity,
key_id: KeyID,
) -> Result<PublicKey, String> {
let key = recipient.get_public_key_by_id(key_id).ok_or_else(|| {
format!(
"the recipient identity {} has no key {key_id}",
recipient.id()
)
})?;
if !is_private_document_key(key) {
return Err(format!(
"the recipient key {key_id} is a {} {} key, not an ECDSA_SECP256K1 DECRYPTION or \
ENCRYPTION key",
key.key_type(),
key.purpose()
));
}
enabled_point(key, "recipient")
}

/// The keys of `identity` an entry may be sealed to now
/// ([`private_document_recipient_key`]), by key id.
pub fn private_document_recipient_keys(identity: &Identity) -> Vec<&IdentityPublicKey> {
identity
.public_keys()
.values()
.filter(|key| private_document_recipient_key(identity, key.id()).is_ok())
.collect()
}

@thepastaclaw thepastaclaw Nov 23, 2026 •

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.

✅ Resolved at efee9317; see the replies below.

🟡 Suggestion: Seal callers cannot match refusals because key and schema checks return strings
Impact: Wallet code and any future SDK caller must match message text to tell a bad key from a bad schema, and variant-keyed retry logic cannot recognize these deterministic refusals.

The consequence is fragile classification that silently mislabels future Generic cases as caller-input errors. The mechanism is private_document_recipient_key and private_document_sender_key return Result with String, validate_private_document_properties returns Result with String, and checked funnels them through Error::Generic; downstream refused() in private_document_create.rs can then only map Generic to InvalidParameter while Protocol errors from encode_private_document_payload leak through as a different Sdk shape for the same user-input failure. The tests confirm the trap by asserting with contains on message text instead of matching a variant. Fix by returning a typed error such as Error::InvalidRequest from the key helpers and the check path and updating the map_err Error::Generic call sites and refused() accordingly; the pre-existing contact-request code uses the same Generic pattern, so this also stops the new module entrenching it.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 256d47c. dash_sdk::Error only has a string InvalidRequest, so the module now returns a typed PrivateDocumentSealError, following the EncryptedForError pattern. It has one variant per refusal (type, key by role, properties, encoding, size), plus the two failures that are not the caller's fault. is_refused_request() tells them apart, and the wallet's From maps the refusals to InvalidParameter. The shape-based refused() is gone, and the tests match variants. The DashPay contact-request path is unchanged.

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.

Resolved (re-reviewed at efee9317): Thank you — the typed PrivateDocumentSealError with is_refused_request() replaces the string matching, and wallet maps refusals to InvalidParameter.

Comment on lines +503 to +510
private var canSubmit: Bool {
guard let walletId = selectedWalletId else { return false }
return walletManager.wallet(for: walletId) != nil
&& selectedSenderId != nil
&& recipientKeysFor != nil
&& recipientKeysFor == recipientId
&& selectedRecipientKeyId != nil
}

@thepastaclaw thepastaclaw Nov 23, 2026 •

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.

✅ Resolved at efee9317; see the replies below.

🟡 Suggestion: Create screen stays submittable after an unconfirmed spend and allows a second paid entry
Impact: A user who taps Create Entry again after the may-have-gone-through notice pays a second shielded fee and appends a duplicate entry with a fresh commitment.

The consequence is a second tap pays again for a duplicate entry. The mechanism is after ShieldedSpendUnconfirmed the view sets outcome to .unconfirmed and releases isSubmitting via defer, but canSubmit only checks wallet, sender, and recipientKeysFor and key and never consults outcome, so the Create button re-enables while the unconfirmed banner is shown. The PR description's does-not-send-again covers only automatic resends. Fix by gating canSubmit or the button on the unconfirmed state until the user changes the form or restarts, for example returning false when outcome is .unconfirmed.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in efee931. After a "may have gone through" outcome, Create stays disabled until any input changes or the screen is left. The notice stays visible either way. DOC-19 describes it.

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.

Resolved (re-reviewed at efee9317): Thank you — Create now stays disabled via heldAfterUnconfirmed until any input changes, so a second tap cannot pay again while the notice shows.

Comment on lines +2577 to 2626
pub async fn create_private_document_entry<C, P>(
&self,
coordinator: &Arc<NetworkShieldedCoordinator>,
seed: &[u8],
account: u32,
new: &NewPrivateDocumentEntry,
crypto: &C,
prover: P,
) -> Result<PrivateDocumentEntryCreated, PlatformWalletError>
where
C: ContactCryptoProvider + Sync,
P: OrchardProver,
{
let sealed = self
.identity
.seal_private_document_entry(crypto, new)
.await?;
// Taken before the wallet manager lock the liveness check reads, as
// the teardown takes them, and held until the spend returns.
let _lifecycle = self.core().generation_payment_guard().await;
if !self.core().is_current_generation().await {
return Err(PlatformWalletError::WalletRemovedBeforeSend(hex::encode(
self.wallet_id,
)));
}
let keyset = self.derive_spend_keyset(seed, account).await?;
private_document_create_from_pool_with_metadata(
&self.sdk,
coordinator.store(),
Some(&self.persister),
self.wallet_id,
&keyset,
account,
new.data_contract_id,
&new.document_type_name,
vec![sealed.entry],
None,
&PaymentStarted::default(),
&prover,
)
.await?;
Ok(PrivateDocumentEntryCreated {
commitment: sealed.commitment,
sender_key_id: sealed.sender_key_id,
})
}

/// Withdraw from `account`'s notes to a Core L1 address
/// (Base58Check string). `core_fee_per_byte` is the L1 fee
/// rate (duffs/byte). `seed` supplies the transient spend

@thepastaclaw thepastaclaw Nov 23, 2026 •

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.

✅ Resolved at efee9317; see the replies below.

🟡 Suggestion: New pool-paid spend path has no test for its guard, removal, or unconfirmed outcomes
Impact: A regression in the generation gate, WalletRemovedBeforeSend refusal, or ShieldedSpendUnconfirmed handling ships undetected and risks a double-send or a lost-spend confusion for pool-paid entries.

The consequence is PlatformWallet::create_private_document_entry moves real shielded funds through a seal-then-spend sequence with lifecycle and redrive semantics yet nothing exercises it. The mechanism is the six new wallet tests cover seal_private_document_entry, key choices, and the fee preview, and a repo-wide grep shows no test calling create_private_document_entry at all; the function adds the generation payment guard plus is_current_generation refusal, derive_spend_keyset wiring, and the private_document_create_from_pool_with_metadata redrive and unconfirmed contract the FFI docs promise do not create it again. Fix with focused tests using mock coordinator and prover as the neighboring shielded-spend tests do for refusal-before-spend ordering, removed-wallet refusal with nothing recorded or paid, and unconfirmed-error propagation that tells Swift not to resend.

source: muse-spark-1.3-contributor (phase2-reviewer: rust-quality)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Partly fixed in 256d47c. Writing these tests surfaced a real gap: a removed wallet failed in the seal with WalletNotFound, and a stale handle to a re-created wallet failed with IdentityNotFound, not the documented WalletRemovedBeforeSend. There is now a liveness check before sealing, and the check under the lifecycle gate is kept. New tests: create::should_refuse_a_create_the_check_refuses_before_anything_is_paid, create::should_refuse_a_create_from_a_wallet_no_longer_current and create::should_take_a_current_wallet_s_create_past_the_liveness_check. Not covered: the unconfirmed outcome at this level, which would need funded notes, a real Halo 2 proof and an intercepted broadcast. The result is passed up unchanged with ? from private_document_create_from_pool_with_metadata, whose unconfirmed handling is already tested through submit_private_document_payment.

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.

Resolved (re-reviewed at efee9317): Thank you — the pre-seal liveness check plus the refusal-ordering and removed-wallet tests close the guard/removal gap, and the unconfirmed pass-through from the shared tested spend needs no new branch here.

@github-actions

Copy link
Copy Markdown
Contributor

Bots are done — your move: post /self-reviewed.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 23, 2026
QuantumExplorer and others added 2 commits November 23, 2026 17:04
…l codes

- dash-sdk: the seal module's key, type and properties refusals are a typed
  PrivateDocumentSealError (is_refused_request) instead of Strings funneled
  through Error::Generic; the payload encoding error is one of its variants.
- platform-wallet: From<PrivateDocumentSealError> maps refused requests to
  InvalidParameter by variant, replacing the Generic-shaped refused();
  properties_json that is not a JSON object is InvalidParameter at the create.
  create_private_document_entry refuses a stale wallet handle with
  WalletRemovedBeforeSend before sealing, and gains tests for refusals,
  removed/re-created wallets and the current wallet's path.
- platform-wallet-ffi: the create export keeps ErrorInvalidParameter and
  ErrorIdentityNotFound instead of ErrorWalletOperation, null-checks the
  sender and recipient ids, and marshals the recipient key purpose by an
  explicit match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ed private document create

A create that may have gone through (ShieldedSpendUnconfirmed) left the
button enabled, so a second tap paid again. It now stays disabled until an
input of the form changes or the screen is left.

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

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 23, 2026

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

⚠️ DEGRADED — Re-review — Final validation — Phase 1 + Phase 2

⚠️ DEGRADED review. The primary review models were unavailable (gpt-6.2-sol unavailable: All credentials for model gpt-6.2-sol are cooling down (last error: usage_limit_reached: The usage limit has been reache), so this review ran on stand-in models: gpt-5.6-luna → muse-spark-1.3-contributor, gpt-5.6-sol → muse-spark-1.3-contributor, gpt-5.6-terra → muse-spark-1.3-contributor, gpt-6-astra → muse-spark-1.3-contributor, gpt-6.1-sol → muse-spark-1.3-contributor, gpt-6.2-astra → muse-spark-1.3-contributor, gpt-6.2-sol → muse-spark-1.3-contributor. Both review phases and the independent verifiers still ran, but on weaker models, with Phase 1 capped at high effort. Treat the verdict as provisional; a full-strength re-review will run on the next push once the primary models are back.

Nothing blocks: no blocking finding stands on this head.

New on this head: Adds a generic shielded-pool-paid private document create (type 29) to SwiftExampleApp with Rust seal, wallet spend, FFI exports, and a schema-driven entry form. CI on this head shows in-progress and pending checks with no failures at the snapshot.

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

Review provenance

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

  • Degraded mode: gpt-6.2-sol unavailable: All credentials for model gpt-6.2-sol are cooling down (last error: usage_limit_reached: The usage limit has been reache (detected by probe, since 2026-11-23T09:07:27Z); stand-ins gpt-5.6-luna → muse-spark-1.3-contributor, gpt-5.6-sol → muse-spark-1.3-contributor, gpt-5.6-terra → muse-spark-1.3-contributor, gpt-6-astra → muse-spark-1.3-contributor, gpt-6.1-sol → muse-spark-1.3-contributor, gpt-6.2-astra → muse-spark-1.3-contributor, gpt-6.2-sol → muse-spark-1.3-contributor; Phase 1 effort capped at high
  • Triage: critical by muse-spark-1.3-contributor (standing in for gpt-6.2-sol) (effort low) — Large ~3.9k-line change adds a new shielded-pool spend and entry-sealing path in rs-platform-wallet/src/wallet/identity/network/private_document_create.rs and rs-sdk/src/platform/private_document_seal.rs with recipient/sender key selection and secret handling.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort high); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort high); 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 (zai below 15% reserve: 5h 100% left, weekly 0% left)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • Fresh verifier: muse-spark-1.3-contributor (standing in for gpt-6.2-sol) — final-verifier; agent sol-verifier
  • Phase 2 reviewers: muse-spark-1.3-contributor (standing in for gpt-6.2-astra) — general (completed, effort high); agent phase2-reviewer, muse-spark-1.3-contributor (standing in for gpt-6.2-astra) — architecture-layering (completed, effort high); agent phase2-reviewer, muse-spark-1.3-contributor (standing in for gpt-6.2-astra) — ffi-engineer (completed, effort high); agent phase2-reviewer, muse-spark-1.3-contributor (standing in for gpt-6.2-astra) — rust-quality (completed, effort high); agent phase2-reviewer, muse-spark-1.3-contributor (standing in for gpt-6.2-astra) — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.

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

Comment on lines +474 to +480
match result {
Ok(created) => {
unsafe { *out_created = created.into() };
PlatformWalletFFIResult::ok()
}
Err(error) => seed_mismatch_result(error)
.unwrap_or_else(|error| map_spend_result(Err(error), CREATE_OPERATION)),

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.

Resolved (re-reviewed at efee9317): Thank you — create_error_result now preserves InvalidParameter and IdentityNotFound before the spend mapper, with a test pinning the codes.

Comment on lines +325 to +329
let document_type = contract
.document_type_for_name(&new.document_type_name)
.map_err(|error| PlatformWalletError::InvalidParameter(error.to_string()))?;
let properties: BTreeMap<String, Value> =
document_properties_from_json(document_type, &new.properties_json)?;

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.

Resolved (re-reviewed at efee9317): Thank you — malformed properties_json now maps to InvalidParameter at this call site only, leaving the helper's other callers unchanged.

Comment on lines +411 to +415
check_ptr!(wallet_id_bytes);
check_ptr!(mnemonic_resolver_handle);
check_ptr!(data_contract_id);
check_ptr!(document_type_name);
check_ptr!(properties_json);

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.

Resolved (re-reviewed at efee9317): Thank you — both identity pointers are now check_ptr! guarded with ErrorNullPointer, covered by the null test.

Comment on lines +73 to +80
impl From<PrivateDocumentRecipientKey> for PrivateDocumentRecipientKeyFFI {
fn from(key: PrivateDocumentRecipientKey) -> Self {
Self {
key_id: key.key_id,
purpose: key.purpose as u8,
}
}
}

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.

Resolved (re-reviewed at efee9317): Thank you — the purpose byte is now an explicit match on every Purpose variant with other purposes left out, as the new test pins.

Comment on lines +51 to +80
pub fn private_document_recipient_key(
recipient: &Identity,
key_id: KeyID,
) -> Result<PublicKey, String> {
let key = recipient.get_public_key_by_id(key_id).ok_or_else(|| {
format!(
"the recipient identity {} has no key {key_id}",
recipient.id()
)
})?;
if !is_private_document_key(key) {
return Err(format!(
"the recipient key {key_id} is a {} {} key, not an ECDSA_SECP256K1 DECRYPTION or \
ENCRYPTION key",
key.key_type(),
key.purpose()
));
}
enabled_point(key, "recipient")
}

/// The keys of `identity` an entry may be sealed to now
/// ([`private_document_recipient_key`]), by key id.
pub fn private_document_recipient_keys(identity: &Identity) -> Vec<&IdentityPublicKey> {
identity
.public_keys()
.values()
.filter(|key| private_document_recipient_key(identity, key.id()).is_ok())
.collect()
}

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.

Resolved (re-reviewed at efee9317): Thank you — the typed PrivateDocumentSealError with is_refused_request() replaces the string matching, and wallet maps refusals to InvalidParameter.

Comment on lines +503 to +510
private var canSubmit: Bool {
guard let walletId = selectedWalletId else { return false }
return walletManager.wallet(for: walletId) != nil
&& selectedSenderId != nil
&& recipientKeysFor != nil
&& recipientKeysFor == recipientId
&& selectedRecipientKeyId != nil
}

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.

Resolved (re-reviewed at efee9317): Thank you — Create now stays disabled via heldAfterUnconfirmed until any input changes, so a second tap cannot pay again while the notice shows.

Comment on lines +2577 to 2626
pub async fn create_private_document_entry<C, P>(
&self,
coordinator: &Arc<NetworkShieldedCoordinator>,
seed: &[u8],
account: u32,
new: &NewPrivateDocumentEntry,
crypto: &C,
prover: P,
) -> Result<PrivateDocumentEntryCreated, PlatformWalletError>
where
C: ContactCryptoProvider + Sync,
P: OrchardProver,
{
let sealed = self
.identity
.seal_private_document_entry(crypto, new)
.await?;
// Taken before the wallet manager lock the liveness check reads, as
// the teardown takes them, and held until the spend returns.
let _lifecycle = self.core().generation_payment_guard().await;
if !self.core().is_current_generation().await {
return Err(PlatformWalletError::WalletRemovedBeforeSend(hex::encode(
self.wallet_id,
)));
}
let keyset = self.derive_spend_keyset(seed, account).await?;
private_document_create_from_pool_with_metadata(
&self.sdk,
coordinator.store(),
Some(&self.persister),
self.wallet_id,
&keyset,
account,
new.data_contract_id,
&new.document_type_name,
vec![sealed.entry],
None,
&PaymentStarted::default(),
&prover,
)
.await?;
Ok(PrivateDocumentEntryCreated {
commitment: sealed.commitment,
sender_key_id: sealed.sender_key_id,
})
}

/// Withdraw from `account`'s notes to a Core L1 address
/// (Base58Check string). `core_fee_per_byte` is the L1 fee
/// rate (duffs/byte). `seed` supplies the transient spend

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.

Resolved (re-reviewed at efee9317): Thank you — the pre-seal liveness check plus the refusal-ordering and removed-wallet tests close the guard/removal gap, and the unconfirmed pass-through from the shared tested spend needs no new branch here.

@github-actions

Copy link
Copy Markdown
Contributor

Bots are done — your move: post /self-reviewed.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 23, 2026
QuantumExplorer and others added 2 commits November 23, 2026 17:52
Regenerate packages/kotlin-sdk/PARITY_SUMMARY.md from the merged
manifest (scripts/check_sdk_parity_manifest.py --write-summary).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Regenerate packages/kotlin-sdk/PARITY_SUMMARY.md from the merged
manifest (scripts/check_sdk_parity_manifest.py --write-summary).

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

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 23, 2026
QuantumExplorer and others added 2 commits November 23, 2026 18:01
Resolve TEST_PLAN.md against the DashPay private contact request rows:
keep DOC-17's new DP-20/DP-30 reference with the pointer to DOC-19, and
count DOC-19 on top of the merged Uncommon and Shielded totals.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Regenerate packages/kotlin-sdk/PARITY_SUMMARY.md from the merged
manifest (scripts/check_sdk_parity_manifest.py --write-summary).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@QuantumExplorer
QuantumExplorer merged commit 44f614e into v5.1-dev Nov 23, 2026
6 of 7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

waiting-bots Waiting for the review bots to report on this head

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants