Skip to content

feat(swift-sdk): use SPV-synced quorums for Platform proof verification - #3417

Merged
shumkov merged 77 commits into
v5.1-devfrom
feat/ios-spv-quorums
Nov 12, 2026
Merged

shumkov merged 77 commits into
v5.1-devfrom
feat/ios-spv-quorums

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Mar 31, 2026 •

Copy link
Copy Markdown
Member

Issue being fixed or feature implemented

The iOS app can verify Platform proofs with quorum public keys from its own SPV client instead of relying only on the centralized quorum HTTP service. SDK consumers choose the trust model when they build the SDK: Trusted, strict SPV, or Adaptive (switchable Auto/SPV/Trusted, used by SwiftExampleApp).

Trust root. SPV quorum keys are as trustworthy as dash-spv's checks at Platform's rust-dashcore pin. That pin is c9aeac0d, from v5.1-dev via #5729:

ChainLock anchoring is not part of this trust root. dashpay/rust-dashcore#1309 was closed in favour of DIP 175 quorum proof chains (dashpay/rust-dashcore#1309 (comment)), which are a follow-up (see Follow-ups).

What was done?

Providers (dash-context-provider):

  • SpvContextProvider takes quorum keys only from an SPV client and never from the trusted service.
  • AdaptiveContextProvider routes each lookup by mode:
    • Auto uses SPV while it is published and synced, and the trusted provider whenever it is not.
    • A missing key is fetched only on the trusted route.
    • It does not forward core_height_verified, because it does not record which source supplied a quorum's key.
  • Both read contracts and token configurations from a ContractSource, which has no quorum keys.
  • Both report their network to SdkBuilder::build. The adaptive provider also reports its trusted provider's proof requirement, so the builder's provider checks apply to them.
  • AdaptiveContextProvider::new refuses a trusted provider that declares another network, which the builder cannot see behind it.
  • SpvSourceSlot is where an SPV client publishes its quorum lookups. A client claims it and holds it through a lease, one lease at a time.
  • Every "no usable SPV source" outcome is QuorumSourceUnavailable, so the SDK does not ban the node whose proof it could not check.
  • ContextProvider gains quorum_source(), set_quorum_mode() (refused by default) and spv_source_slot(), forwarded by the Arc/Box/Mutex wrappers.
    • Adaptive answers all three.
    • Strict SPV answers its source and slot, and refuses every mode.
    • The trusted provider answers its source.
    • The source enum is QuorumKeySource, in quorum_source.rs.
  • A provider never uses a published SPV source that declares another network than its own: strict SPV fails closed, Auto treats it as not ready.

SDK (dash-sdk):

  • Sdk::set_context_provider replaces the provider at runtime. It keeps feat(sdk)!: let wasm-sdk and evo-sdk opt into the verified quorum context provider #5721's signature, its network and proof-requirement checks, and its errors.
  • Every clone of an SDK shares one provider slot. A provider set on the application's SDK therefore reaches clones made earlier, such as the wallet manager's. On v5.1-dev each clone kept its own copy.
  • Each proof verification uses the provider it read when it started, including across a quorum-key fetch.
  • A replaced routing provider such as Adaptive no longer affects the SDK: its mode and SPV slot stop mattering. The FFI has no setter; Swift switches through Adaptive's modes.

Local contract cache (rs-sdk-trusted-context-provider):

  • The known-contracts and token-configuration part of TrustedHttpContextProvider is now LocalContextResolver. The trusted provider delegates to it.
  • System contracts load through the crate's single system_contracts loader, which includes the decision-proposals and token-market contracts from protocol 15.
  • The token-market gate holds in the resolver and in the trusted provider, before its fallback provider.
  • Adding, preloading and registering a contract keep a held contract of a higher version. This is v5.1-dev's rule from feat(sdk): send, scan and read DashPay private contact requests #5809, which the resolver now owns, so it holds for the SPV and adaptive providers too. replace_known_contract replaces on purpose.

FFI (rs-sdk-ffi):

  • dash_sdk_create_trusted, dash_sdk_create_spv and dash_sdk_create_adaptive build the matching provider. Strict SPV never builds the trusted HTTP provider and ignores quorum_url.
  • Everything about the provider goes through the SDK's current one (sdk.context_provider()), so it follows a native set_context_provider:
    • the source (dash_sdk_get_context_provider_source: 0 trusted, 1 SPV, 2 a provider that names no source);
    • mode changes (dash_sdk_set_context_provider_mode, refused by a provider without modes);
    • contract preloads (dash_sdk_add_known_contracts, via register_data_contract);
    • the 15 document contract lookups;
    • status quorumSource.
  • SDKWrapper keeps only the SDK, the runtime and, for dash_sdk_get_status, the kind and trusted provider it was built with (mode, quorumCount).

Wallet (rs-platform-wallet, rs-platform-wallet-ffi):

  • platform_wallet_manager_create_with_sdk (with the persistence and event extensions) claims the slot of the SDK's current provider (platform_wallet::claim_spv_quorum_lease) before it reads the host's callback vtables. A second manager on the same SDK is refused before it takes the host's callback contexts.

  • SpvRuntime::start / start_and_spawn refuse a client config for another network than the manager's (its SDK's), before they open the store or build a client.

  • The manager serves its SPV quorum keys from creation until shutdown or drop.

  • The source answers only while all of these hold:

    • sync is running;
    • headers and masternode lists are Synced;
    • the newest masternode list is at most two blocks behind the header tip.

    dash-spv keeps masternode sync Synced when later list updates fail. Without the tip check, a stale list would count as ready and its misses would get honest nodes banned.

  • Only quorums dash-spv marked Verified are served. Quorum types that name no LLMQ type are refused.

Swift:

  • SDK(network:contextProvider:) defaults to Trusted.
  • SDK.quorumSource reads the native SDK's current provider, .custom for one that names no source. SDK.QuorumMode documents each mode.
  • PlatformWalletManager.configure(sdk:) creates the manager through create_with_sdk.
  • SwiftExampleApp uses Adaptive with an Auto/SPV/Trusted picker. Same-network SDK rebuilds (devnet settings, the Docker toggle) stop SPV and move the wallet manager onto the rebuilt SDK.
  • SDK rebuilds run one at a time across windows. AppState.rebuildSdk reserves the rebuild before it stops SPV and keeps it through the manager's move, the publish and any rollback; a second rebuild from any window is refused before any of its steps. The bootstrap runs once per process.
  • Every SDK the app builds (bootstrap, rebuilds, background wallet managers) is built by AppState.makeSdk in the selected quorum mode, and a mode change reaches all of them.
  • Its quorum-source indicator follows SPV progress and running state, from a leaf view that observes the wallet manager.

Merged with v5.1-dev at 076393c5c0 (earlier at 9b36712770 and 46c26cb05f). The latest merge only kept v5.1-dev's txo_reconcile_schedule beside this branch's spv_quorum_lease in PlatformWalletManager. The first merge brought in the rust-dashcore pin above, the verified quorum provider (#5523, #5720) and its SDK opt-in (#5721). The second:

Earlier merge details:

How Has This Been Tested?

  • At 119d13368a, the final scope (provider follow-through in the FFI, SPV client network, create_with_sdk ownership tests, one rebuild at a time, background SDK quorum mode):

    • CI's non-shielded phase mirrored locally (CI's package list plus dash-context-provider and rs-sdk-trusted-context-provider, its env, --all-features --locked --lib --bins --tests -- --skip shield): 21,977 passed, 0 failed, 70 ignored, across 79 test binaries. That run predates the review fixes. Their crates were rerun: dash-context-provider, rs-sdk-trusted-context-provider, rs-sdk-ffi, platform-wallet, platform-wallet-ffi and dash-sdk, same env, 3,931 passed, 0 failed, 33 ignored.
    • cargo clippy --all-targets --all-features -- -D warnings clean on dash-context-provider (also without features), rs-sdk-trusted-context-provider, rs-sdk-ffi, platform-wallet, platform-wallet-ffi, rs-unified-sdk-jni, wasm-sdk, dash-sdk.
    • Red → green, each red at 1e1970d281 with only the new test applied:
      • after a native set_context_provider on an FFI-built adaptive SDK, the source FFI, status quorumSource, the mode refusal, preloads, document lookups and the slot a manager claims all follow the replacement;
      • the trusted provider reports its source (red with the trait method and no override).
    • Red → green, with the change:
      • a Mainnet SPV config on a Testnet runtime is refused by both starts, and the store stays empty;
      • mutation reds: a published SPV source of another network is not used, and a start on a running client is refused before reading the wallet manager.
    • create_with_sdk's ownership is correct at the previous head, so those two tests were shown by mutation runs:
      • reading the vtables before the claim makes the first test fail;
      • leaking the lease on a refusal makes the second fail.
    • After merging v5.1-dev (054f010f6a): fmt and clippy clean on the touched crates; those crates and dash-sdk with CI's env: 3,990 passed, 0 failed, 33 ignored.
    • Swift: pasta has no Xcode. The changed Swift was parsed (swiftc -parse), and a review type-checked it against stubbed SDK types under Swift 6 with warnings as errors. The Swift tests' reds are reasoned, not run (the new API does not exist at 1e1970d281). CI's Swift job (warnings as errors) built them and ran them green at 054f010f6a. The once-per-process bootstrap has no unit test.
  • At 50d5ed32f6, the runtime provider setter:

    • All runs use --all-features --lib --bins --tests.
    • dash-sdk: 929 passed, 0 failed.
    • A trial merge with v5.1-dev at f603f988: 1,035 passed. These include the 12 block_query_tests from feat(sdk): verify the block proofs of getBlocks and getOwnerTransactionsInBlock #5834, which call set_context_provider.
    • rs-sdk-ffi: 429 unit tests passed, and its integration test binaries passed.
    • platform-wallet: 1,774 passed.
    • platform-wallet-ffi: 514 passed.
    • dash-context-provider: 18 passed.
    • rs-sdk-trusted-context-provider: 155 passed.
    • wasm-sdk:
      • 221 native tests passed with default features.
      • With all features, one test fails: should_fetch_a_referenced_system_contract_the_sdk_does_not_compile_in. It assumes the withdrawals contract is not compiled in, which --all-features changes. The failure predates this change.
      • 51 wasm32 tests passed.
    • cargo clippy --all-targets --all-features -- -D warnings is clean on dash-sdk, rs-sdk-ffi, dash-context-provider, rs-sdk-trusted-context-provider, platform-wallet, platform-wallet-ffi, wasm-sdk (also for wasm32) and dash-platform-balance-checker.
    • Red → green:
  • At 47e3355613, after the second v5.1-dev merge:

    • CI's non-shielded phase mirrored locally (CI's package list plus dash-context-provider, its env, --all-features --locked --lib --bins --tests -- --skip shield): 21,980 passed, 0 failed, 70 ignored, across 104 test binaries. That run predates only the last commit, which adds one test.
    • rs-sdk-trusted-context-provider: 155 passed (all features), 142 (default features). wasm-sdk: 221 native tests passed.
    • cargo clippy --all-targets --all-features -- -D warnings clean on dash-context-provider, rs-sdk-trusted-context-provider, dash-sdk, rs-sdk-ffi, platform-wallet, platform-wallet-ffi, wasm-sdk; the context-provider crates also without features.
    • Red → green: should_refuse_a_trusted_provider_for_another_network (red with the constructor fallible but unchecked) and the resolver's should_keep_a_newer_contract_over_a_registered_older_one (red with registration overwriting, as before the merge).
    • Swift: only swiftc -parse here; the Swift SDK job builds it. The indicator fix has no test, as SwiftExampleAppTests cannot drive a view's modifiers.

Earlier rounds:

  • Local, mirroring CI's non-shielded phase (cargo test --all-features --locked --lib --bins --tests -- --skip shield, CI's package list and env):
    • 21,808 passed, 0 failed, 70 ignored, across 103 test binaries, at 1655562fbf.
    • The full strategy_tests binary ran, not only the two tests PR CI picks.
  • After the readiness fix and the docs commits:
    • platform-wallet, dash-context-provider, rs-sdk-trusted-context-provider (all features): 1,770 + 17 + 150 unit tests passed. The trusted provider's default-feature build: 138 passed.
    • platform-wallet-storage shield-named SQLite tests: 7 passed.
    • wasm-sdk: 217 native tests passed, and 45 wasm32 tests passed under wasm-bindgen-test-runner.
  • cargo clippy --all-targets --all-features -- -D warnings, with no warnings, on:
    • dash-context-provider, rs-sdk-trusted-context-provider, dash-sdk, platform-wallet, rs-sdk-ffi, platform-wallet-ffi, dash-platform-balance-checker;
    • the two context-provider crates without features;
    • wasm-sdk for wasm32.
  • cargo check --workspace --all-targets.
  • Red → green:
    • should_not_be_ready_while_the_masternode_list_trails_the_header_tip;
    • should_forward_provider_requirements_through_every_wrapper;
    • the token-market gate tests in the resolver and in the trusted provider with a fallback, each red with only its own gate removed;
    • the builder refusal tests, red without the build check.
  • Also covered by tests:
    • routing by mode and readiness, and fail-closed SPV;
    • no trusted fetch on the SPV route;
    • error classes, and exactly one of concurrent claims succeeding;
    • lease lifetime across manager creation and shutdown;
    • strict SPV building without a quorum service;
    • one contract cache across the trusted, SPV and adaptive providers;
    • the SPV runtime bridge on every Tokio runtime flavor;
    • SDK.quorumSource for a strict SPV SDK (Swift).
  • Swift: pasta has no iOS SDK, so the Swift files changed since the last CI run were only syntax-checked (swiftc -parse). The Swift SDK job is the build and test gate.
  • Not done: an on-device or simulator pass against a synced testnet node.

Known limits:

  • Strict SPV protects quorum keys only. Contracts still come from app storage or earlier fetches.
  • An SPV quorum that is not yet Verified is reported as unavailable. A node can name one without being banned.
  • Auto's fallback can be forced. Someone who cuts the client off from its SPV peers drops readiness, and Auto then uses the trusted service until SPV is synced again. Auto means the best source available. Clients that must never use the trusted service choose the SPV mode.

Follow-ups:

Breaking Changes

None that affect consensus. No public SDK, FFI or Swift item that exists on v5.1-dev is removed or changes signature. Behaviour changes:

  • Sdk::set_context_provider on any clone of an SDK replaces the provider for every clone, including clones made before the call. On v5.1-dev it changed only the SDK it was called on and the clones made from it afterwards.
  • dash_sdk_get_status reports mode: "custom" instead of "spv" for SDKs built by dash_sdk_create, dash_sdk_create_extended or dash_sdk_create_with_callbacks.
  • dash_sdk_add_known_contracts on an SDK whose provider keeps no contracts (callbacks, mock) succeeds as a no-op, as ContextProvider::register_data_contract's default documents. On v5.1-dev it returned InvalidState. The document FFIs on such an SDK report "not found in the SDK's context provider" instead of "No trusted context provider configured", with the same codes.
  • SpvRuntime::start / start_and_spawn and platform_wallet_manager_spv_start refuse, with an invalid-parameter error, a network other than the wallet manager's.

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

🤖 Generated with Claude Code

PR Hygiene · 136612c

  • Bots — thepastaclaw not yet — /skip-bots proceeds without the ones not yet reported
  • Self-review — post /self-reviewed
  • Build failed
  • Approvals
    • files with no dedicated owner — you own it
    • kotlin-sdk (packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/PlatformQueries.kt) — HashEngineering
    • rs-platform-wallet-ffi (packages/rs-platform-wallet-ffi/Cargo.toml, packages/rs-platform-wallet-ffi/src/manager.rs, packages/rs-platform-wallet-ffi/src/spv.rs) — HashEngineering or ZocoLini or llbartekll or romchornyi
    • rs-platform-wallet (packages/rs-platform-wallet/Cargo.toml, packages/rs-platform-wallet/src/lib.rs, packages/rs-platform-wallet/src/manager/mod.rs and 3 more) — HashEngineering or ZocoLini or llbartekll or romchornyi
    • rust-sdk-ffi (packages/rs-sdk-ffi/Cargo.toml, packages/rs-sdk-ffi/src/document/create.rs, packages/rs-sdk-ffi/src/document/delete.rs and 11 more) — lklimek or shumkov
    • rust-sdk (packages/rs-sdk/src/platform.rs, packages/rs-sdk/src/sdk.rs, packages/rs-sdk/src/sdk/protocol_gate_tests.rs and 1 more) — lklimek or shumkov
    • swift-sdk (packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift, packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift, packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swift and 15 more) — llbartekll or romchornyi
    • js-wasm-sdk (packages/wasm-sdk/src/context_provider.rs) — shumkov

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.

Bridge the SPV client's locally synced masternode list data to the
Platform SDK's context provider, replacing the dependency on a trusted
HTTP quorum endpoint. When an SPV client handle is available, the SDK
is created with callback-based quorum lookups that call through to
ffi_dash_spv_get_quorum_public_key and
ffi_dash_spv_get_platform_activation_height.

A "Fallback to Trusted Quorums" toggle (default: ON) in Settings lets
users fall back to the HTTP provider when SPV data is not yet synced.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@github-actions github-actions Bot added this to the v3.1.0 milestone Mar 31, 2026
@coderabbitai

coderabbitai Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

Adds SPV-backed SDK creation using a client handle, introduces Rust quorum resolution through a feature-gated context provider, and adds configurable trusted-quorum fallback behavior to the Swift example app. A specification documents the planned reintegration architecture and validation requirements.

Changes: SPV quorum integration

Layer / File(s) Summary
SPV context provider and feature wiring
packages/rs-platform-wallet/Cargo.toml, packages/rs-platform-wallet/src/lib.rs, packages/rs-platform-wallet/src/spv_context_provider.rs
Adds the feature-gated SpvContextProvider, which resolves quorum keys from a shared masternode-list engine and supplies network activation heights while leaving contract and token lookups empty.
Swift SDK initialization and fallback control
packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift, packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swift, packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/OptionsView.swift
Adds SPV-handle SDK construction, explicit FFI error handling, persisted trusted-quorum fallback state, SPV handle updates, fallback behavior during initialization and network switching, and a corresponding SwiftUI toggle.
Reintegration specification
docs/SPV_CONTEXT_PROVIDER_REINTEGRATION_SPEC.md
Documents the proposed byte-order fix, provider and FFI integration layers, Swift wiring, failure modes, verification plan, and out-of-scope items.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant AppState
  participant SDK
  participant dash_sdk_create_with_spv_context
  participant SpvContextProvider
  AppState->>SDK: initialize with SPV client handle
  SDK->>dash_sdk_create_with_spv_context: pass network and configured context
  dash_sdk_create_with_spv_context->>SpvContextProvider: resolve quorum public key
  SpvContextProvider-->>dash_sdk_create_with_spv_context: return quorum key or error
  dash_sdk_create_with_spv_context-->>SDK: return SDK handle or error
  SDK-->>AppState: use SPV SDK or trusted fallback
Loading

Possibly related PRs

Suggested reviewers: shumkov, llbartekll, lklimek, ZocoLini

Pre-merge checks: Passed 4

Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly summarizes the main change: using SPV-synced quorums for Platform proof verification.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Finishing Touches

🧪 Generate unit tests (beta)

  • Create PR with unit tests
  • Commit unit tests in branch feat/ios-spv-quorums
  • 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 Mar 31, 2026 •

Copy link
Copy Markdown
Collaborator

⛔ Final review complete — 1 blocking finding(s) (commit 136612c) · triage: critical

@github-actions

github-actions Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

✅ DashSDKFFI.xcframework built for this PR.

SwiftPM (host the zip at a stable URL, then use):

.binaryTarget(
  name: "DashSDKFFI",
  url: "https://your.cdn.example/DashSDKFFI.xcframework.zip",
  checksum: "93f085d7f665b623b4cc170feb6c8fc04da6702b601f887c52f8e5181e471994"
)

Xcode manual integration:

  • Download 'DashSDKFFI.xcframework' artifact from the run link above.
  • Drag it into your app target (Frameworks, Libraries & Embedded Content) and set Embed & Sign.
  • If using the Swift wrapper package, point its binaryTarget to the xcframework location or add the package and place the xcframework at the expected path.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swift`:
- Around line 45-49: The published property useTrustedQuorumFallback currently
only persists the flag; update its didSet to immediately reapply the SDK
proof-verification mode so the running app reflects the change. After
UserDefaults.standard.set(...), invoke the function that configures the SDK
trust mode (for example the AppState method that initializes or configures the
SDK client—if you have a method like applySDKMode(), reconfigureClient(), or
setTrustedQuorumFallback(on:)), passing the new useTrustedQuorumFallback value;
if no such function exists, call the code path that reconnects or reinitializes
the SDK client so proof verification is updated immediately. Ensure you
reference AppState and useTrustedQuorumFallback when wiring this change.

In `@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/UnifiedAppState.swift`:
- Around line 126-133: The current network-switch flow lets
walletService.switchNetwork(to:) destroy the SPV client while platformState.sdk
still holds callbacks to the old core handle; update
UnifiedAppState.handleNetworkSwitch to explicitly detach and destroy the old SDK
before tearing down the SPV client: capture the existing platformState.sdk (or
call a teardown method like
platformState.sdk?.destroy()/platformState.clearSDK()), set platformState.sdk =
nil (or call the SDK's close/unbind) on the MainActor to remove callbacks, then
call walletService.switchNetwork(to:) and only after obtaining
walletService.spvClientHandle recreate and assign the new SDK via
platformState.updateSPVClientHandle/new SDK creation — ensuring the old SDK is
fully unbound before SPV teardown.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ed48fb63-d5a9-41ff-b965-9df30eae9aab

📥 Commits

Reviewing files that changed from the base of the PR and between 739754b and f4703d6.

📒 Files selected for processing (7)
  • packages/swift-sdk/Sources/SwiftDashSDK/Core/SPV/SPVClient.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/Core/SPV/SPVContextProvider.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/Core/Services/WalletService.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/UnifiedAppState.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/OptionsView.swift

The quorum/activation-height bridging no longer round-trips through
Swift callbacks. Instead, rs-sdk-ffi now depends on dash-spv-ffi
directly and implements SpvContextProvider in Rust, calling
ffi_dash_spv_get_quorum_public_key and
ffi_dash_spv_get_platform_activation_height without leaving Rust.

A new FFI function dash_sdk_create_with_spv_context(config, spv_client)
replaces the Swift-side ContextProviderCallbacks setup. Swift just
passes the raw FFIDashSpvClient pointer.

- Add dash-spv-ffi dependency to rs-sdk-ffi
- Add spv_context_provider.rs implementing ContextProvider trait
- Add dash_sdk_create_with_spv_context FFI function
- Remove SPVContextProvider.swift (no longer needed)
- Update SDK.swift to call dash_sdk_create_with_spv_context

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@codecov

codecov Bot commented Mar 31, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 64.77%. Comparing base (f7d7c8d) to head (4961a0e).
⚠️ Report is 1369 commits behind head on v5.1-dev.

❗ There is a different number of reports uploaded between BASE (f7d7c8d) and HEAD (4961a0e). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (f7d7c8d) HEAD (4961a0e)
rust 2 1
Additional details and impacted files
@@              Coverage Diff              @@
##           v5.1-dev    #3417       +/-   ##
=============================================
- Coverage     87.40%   64.77%   -22.63%     
=============================================
  Files          2639       24     -2615     
  Lines        333066     2657   -330409     
=============================================
- Hits         291103     1721   -289382     
+ Misses        41963      936    -41027     
Components Coverage Δ
dpp ∅ <ø> (∅)
drive ∅ <ø> (∅)
drive-abci ∅ <ø> (∅)
sdk ∅ <ø> (∅)
dapi-client ∅ <ø> (∅)
platform-version ∅ <ø> (∅)
platform-value ∅ <ø> (∅)
platform-wallet ∅ <ø> (∅)
drive-proof-verifier ∅ <ø> (∅)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Add SpvContextProvider to platform-wallet behind the `spv-context`
feature flag. It holds Arc<RwLock<MasternodeListEngine>> + Network
and implements the ContextProvider trait by reading quorum data
directly from the in-memory masternode list — zero FFI involvement.

The rs-sdk-ffi bridge (which calls dash-spv-ffi functions as Rust
calls in the same binary) remains as the pragmatic adapter until
dash-spv-ffi exposes a public accessor for FFIDashSpvClient's
MasternodeListEngine (currently pub(crate)).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/rs-platform-wallet/Cargo.toml`:
- Line 25: The tokio dependency must enable its sync feature for the spv-context
feature and the feature list must use the modern dep: syntax; update Cargo.toml
so the tokio dependency becomes optional with features = ["sync"] (e.g. tokio =
{ version = "1.41", optional = true, features = ["sync"] }) and update the
spv-context feature entry to include "dep:tokio/sync" (instead of the old name)
so spv_context_provider.rs can safely use tokio::sync::RwLock.

In `@packages/rs-platform-wallet/src/spv_context_provider.rs`:
- Around line 115-120: The match that sets `height` currently falls through to
`_ => 0`, silently mapping unsupported `self.network` to 0; replace that
fallback with an explicit error return (e.g., return Err(...) or propagate a
suitable error) so callers are notified of an unsupported Network variant.
Modify the block that computes `height` (the match on `self.network` referencing
`Network::Mainnet`, `Network::Testnet`, `Network::Devnet`) to return a
Result<u64, E> (or use the crate's existing error type) and produce a clear
error for the unsupported branch instead of using 0. Ensure callers of the
enclosing function are updated to handle the Result if necessary.
- Around line 79-80: The call to self.masternode_engine.blocking_read() inside
get_quorum_public_key (which is invoked from async
parse_proof_with_metadata_and_proof) can panic; replace blocking_read() with
try_read() on the Tokio RwLock (self.masternode_engine.try_read()) and handle
the None case gracefully by returning an appropriate error or early failure from
get_quorum_public_key (or falling back to a safe default) instead of unwrapping.
Ensure you reference and use the masternode_lists_around_height result from the
acquired guard when present, and propagate a clear error back to the async proof
verification path so it doesn’t panic.
- Around line 76-77: Validate and reject out-of-range quorum_type before
converting to LLMQType: replace the lossy cast "(quorum_type as u8).into()" with
a fallible conversion using TryInto (e.g., let llmq_type: LLMQType =
(quorum_type.try_into()?) or map the TryInto error to a meaningful error) so
values >255 are handled instead of wrapping; keep
QuorumHash::from_byte_array(quorum_hash) as-is and ensure any error returned
propagates to the caller before using ml.quorums.get(&llmq_type).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0b462740-73cb-43f3-9a1b-7653a611fe5e

📥 Commits

Reviewing files that changed from the base of the PR and between ad6904a and d9e478e.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • packages/rs-platform-wallet/Cargo.toml
  • packages/rs-platform-wallet/src/lib.rs
  • packages/rs-platform-wallet/src/spv_context_provider.rs
  • packages/rs-sdk-ffi/src/spv_context_provider.rs
✅ Files skipped from review due to trivial changes (1)
  • packages/rs-platform-wallet/src/lib.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/rs-sdk-ffi/src/spv_context_provider.rs

Comment thread packages/rs-platform-wallet/Cargo.toml Resolved
QuantumExplorer and others added 2 commits April 2, 2026 17:24
- AppState: trigger SDK reconnect when useTrustedQuorumFallback
  changes so the running app reflects the new setting immediately
- UnifiedAppState: nil out old SDK before destroying SPV client
  during network switch to prevent use-after-free on the context
  provider's core_handle pointer
- Cargo.toml: explicitly enable tokio "sync" feature for
  blocking_read() support
- spv_context_provider.rs: replace lossy `as u8` cast with
  try_from + error, add comment explaining why blocking_read is
  safe, return error for unsupported networks instead of silent 0

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Bump rust-dashcore to 3f65002 which includes the
FFIDashSpvClient::masternode_list_engine() accessor (PR #608).

dash_sdk_create_with_spv_context now:
1. Casts the void* to FFIDashSpvClient
2. Extracts Arc<RwLock<MasternodeListEngine>> directly
3. Creates platform_wallet::SpvContextProvider (pure Rust)

The FFI bridge module (rs-sdk-ffi/src/spv_context_provider.rs) is
deleted — quorum lookups go directly from the Platform SDK through
the pure-Rust provider to the in-memory masternode list, with zero
FFI involvement in the data path.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@QuantumExplorer

Copy link
Copy Markdown
Member Author

All review feedback addressed. Additionally, bumped rust-dashcore to 3f65002 which includes the FFIDashSpvClient::masternode_list_engine() accessor (rust-dashcore PR #608). The FFI bridge module (rs-sdk-ffi/src/spv_context_provider.rs) is now deleted — dash_sdk_create_with_spv_context extracts the engine directly and uses the pure-Rust platform_wallet::SpvContextProvider. Zero FFI in the quorum lookup path.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swift (1)

215-267: ⚠️ Potential issue | 🟠 Major

Make the network switch commit atomically.

The new SPV-first failure paths can throw after the collections are cleared and dataManager.currentNetwork is advanced, but before sdk is replaced. On that path the UI says “new network” while platform calls still go through the old SDK instance. If currentNetwork should also be authoritative, it needs the same success-only commit behavior.

♻️ Possible fix
 func switchNetwork(to network: AppNetwork) async {
     guard let modelContext = modelContext else { return }
-
-    // Clear current data
-    identities.removeAll()
-    contracts.removeAll()
-    documents.removeAll()
-    tokens.removeAll()
-
-    // Update DataManager's current network
-    dataManager?.currentNetwork = network

     // Re-initialize SDK with new network
     do {
         isLoading = true
@@
-        sdk = newSDK
+        identities.removeAll()
+        contracts.removeAll()
+        documents.removeAll()
+        tokens.removeAll()
+        dataManager?.currentNetwork = network
+        sdk = newSDK
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swift` around
lines 215 - 267, The switchNetwork method mutates state (clearing
identities/contracts/documents/tokens and advancing dataManager?.currentNetwork)
before potentially failing during SDK creation and load; make the switch atomic
by first creating and initializing the new SDK and loading contracts/data (use
local temporaries like let newSDK and temp collections), and only after
loadKnownContractsIntoSDK and loadPersistedData succeed assign sdk = newSDK, set
dataManager?.currentNetwork = network, and replace
identities/contracts/documents/tokens with the newly loaded data; keep all
error-throwing work (SDK(network:), loadKnownContractsIntoSDK,
loadPersistedData) before mutating shared state so failures leave the existing
sdk and currentNetwork unchanged.
🧹 Nitpick comments (1)
packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swift (1)

104-124: Extract the SPV/trusted SDK creation path into one helper.

The same fallback tree now lives in both initializeSDK and switchNetwork. The next change to error handling or provider selection is easy to land in one path and miss in the other.

Also applies to: 234-253

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swift` around
lines 104 - 124, Extract the SPV/trusted SDK creation logic used in
initializeSDK and switchNetwork into a single helper function (e.g.,
makeSDKForNetwork(network:sdkNetwork, spvHandle:spvClientHandle?,
useFallback:useTrustedQuorumFallback) -> SDK) that encapsulates the fallback
tree: try constructing SDK(network: , spvClientHandle:) if spvHandle != nil, on
failure fall back to SDK(network:) only if useFallback is true, otherwise
rethrow; if spvHandle is nil create SDK(network:) when useFallback is true or
throw SDKError.invalidState when false. Replace the duplicated blocks in
initializeSDK and switchNetwork to call this new helper and preserve the same
NSLog messages and error propagation behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swift`:
- Around line 143-146: The race occurs because updateSPVClientHandle(_:) runs in
handleNetworkSwitch() while switchNetwork(...) can be started asynchronously
from the currentNetwork didSet in OptionsView; modify handleNetworkSwitch() so
that after calling updateSPVClientHandle(_:) it immediately triggers/awaits the
SDK rebuild (call switchNetwork(...) directly or await the spawned Task) to
ensure the SDK is rebuilt with the new spvClientHandle before returning;
reference updateSPVClientHandle(_:), handleNetworkSwitch(), switchNetwork(...),
currentNetwork didSet/OptionsView to locate and change the code paths so the
handle update is always followed synchronously by the SDK rebuild.

---

Outside diff comments:
In `@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swift`:
- Around line 215-267: The switchNetwork method mutates state (clearing
identities/contracts/documents/tokens and advancing dataManager?.currentNetwork)
before potentially failing during SDK creation and load; make the switch atomic
by first creating and initializing the new SDK and loading contracts/data (use
local temporaries like let newSDK and temp collections), and only after
loadKnownContractsIntoSDK and loadPersistedData succeed assign sdk = newSDK, set
dataManager?.currentNetwork = network, and replace
identities/contracts/documents/tokens with the newly loaded data; keep all
error-throwing work (SDK(network:), loadKnownContractsIntoSDK,
loadPersistedData) before mutating shared state so failures leave the existing
sdk and currentNetwork unchanged.

---

Nitpick comments:
In `@packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swift`:
- Around line 104-124: Extract the SPV/trusted SDK creation logic used in
initializeSDK and switchNetwork into a single helper function (e.g.,
makeSDKForNetwork(network:sdkNetwork, spvHandle:spvClientHandle?,
useFallback:useTrustedQuorumFallback) -> SDK) that encapsulates the fallback
tree: try constructing SDK(network: , spvClientHandle:) if spvHandle != nil, on
failure fall back to SDK(network:) only if useFallback is true, otherwise
rethrow; if spvHandle is nil create SDK(network:) when useFallback is true or
throw SDKError.invalidState when false. Replace the duplicated blocks in
initializeSDK and switchNetwork to call this new helper and preserve the same
NSLog messages and error propagation behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1d056420-6f71-49b1-ad49-3434618ac7b3

📥 Commits

Reviewing files that changed from the base of the PR and between d9e478e and 8d2bb27.

📒 Files selected for processing (4)
  • packages/rs-platform-wallet/Cargo.toml
  • packages/rs-platform-wallet/src/spv_context_provider.rs
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/UnifiedAppState.swift
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/rs-platform-wallet/Cargo.toml
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/UnifiedAppState.swift
  • packages/rs-platform-wallet/src/spv_context_provider.rs

QuantumExplorer and others added 2 commits April 2, 2026 17:41
Remove the switchNetwork() call from currentNetwork.didSet to prevent
it racing with UnifiedAppState.handleNetworkSwitch(). The didSet now
only persists the preference. handleNetworkSwitch() is the single
coordinator: it nils the old SDK, switches the wallet, updates the
SPV handle, then calls switchNetwork() to rebuild the SDK.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Replace blocking_read() with try_read() in SpvContextProvider to
  avoid panicking when called from within a Tokio async context
  (proof verification runs inside async tasks)
- Use dep: prefix syntax in spv-context feature to suppress implicit
  feature creation for optional dependencies (Cargo 2021 edition)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@QuantumExplorer
QuantumExplorer marked this pull request as draft May 18, 2026 18:39
@QuantumExplorer QuantumExplorer added the Interesting Something we should do. label Jun 13, 2026
@shumkov shumkov modified the milestones: v4.0.0, v4.1.0 Jul 2, 2026
@shumkov
shumkov changed the base branch from v4.0-dev to v4.1-dev July 2, 2026 08:12
…ovider

Brings PR #3417 (SPV-synced Platform proof verification) up to date with
v4.1-dev (~827 commits) and re-implements its obsolete integration surface
against the restructured PlatformWalletManager architecture.

Re-integration:
- Delegate quorum lookups to SpvRuntime::get_quorum_public_key via a thin
  SpvContextProvider { Arc<SpvRuntime>, Network }, bridging the sync trait
  method to the async lookup with block_in_place + Handle::try_current.
- New FFI entry platform_wallet_manager_create_sdk_with_spv_context in
  platform-wallet-ffi (rs-sdk-ffi cannot reach the manager handle without a
  dependency cycle). Make rs_sdk_ffi::ContextProviderWrapper public; delete the
  now-dead dash_sdk_create_with_spv_context and drop the dash-spv-ffi dep.
- Swift: SDK.init(network:walletManager:) (@mainactor; captures the Sendable
  Handle before the nonisolated C-string closure); AppState builds the SDK
  SPV-first with trusted fallback; accept base's deletion of SPVClient /
  WalletService / UnifiedAppState.

Correctness fixes:
- Remove the erroneous `.reverse()` in SpvRuntime::get_quorum_public_key.
  quorum_hash is internal byte order end-to-end (drive-abci emits it via
  to_byte_array, proven by the consensus-equality check in
  finalize_block_proposal; the masternode engine keys its quorum map in the
  same order), so reversing missed every quorum -> fail-closed rejection,
  silently masked by the trusted-quorum fallback (SPV never actually used).
  Added a regression test pinning the byte order (internal-order hits,
  reversed misses).
- Correct get_platform_activation_height to the shipped trusted-provider
  values (Mainnet 2_132_092, Testnet 1_090_319; were dash-spv-ffi
  "needs verification" placeholders).
- Reclaim the ContextProviderWrapper box after dash_sdk_create_extended
  (which only borrows + Arc-clones it) to avoid leaking it per SDK creation.

Merge breakages resolved: mergiraf-duplicated [workspace.dependencies] with
conflicting rust-dashcore revs; platform-wallet-ffi <-> rs-sdk-ffi dependency
cycle; deleted `manager` feature; redundant spv-context feature gating.

Verified: 3 Rust crates compile + clippy-clean + fmt; byte-order regression
test passes; SwiftExampleApp (simulator) BUILD SUCCEEDED; cbindgen header
emits the new FFI function correctly. Not verified: end-to-end proof
verification against live SPV-synced quorums (integration/on-device only).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@shumkov
shumkov marked this pull request as ready for review July 11, 2026 11:50
The `routing` module held three separate things: the SPV provider, the
adaptive provider and the contract source both read from. The SPV
provider is used on its own, by a strict SPV SDK, and only the adaptive
one routes. So:
- `spv/` holds `SpvContextProvider` (`spv/provider.rs`) and the slot and
  lease its SPV client publishes through (`spv/slot.rs`); `spv/mod.rs`
  has only the module docs, declarations and re-exports;
- `adaptive.rs` holds `AdaptiveContextProvider` and its mode;
- `contract_source.rs` holds `ContractSource`;
- the test helpers move to `test_support.rs`.

Every type is re-exported from the crate root next to `ContextProvider`,
and callers import from there. The `routing` module, added by this PR and
never released, is gone. Code is moved, not changed: the slot's internals
the adaptive provider reads are `pub(crate)` instead of private, and the
18 tests are the same.

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.

@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

At head 1e1970d, the provider refactor preserves the verified trust-root and dependency boundaries, but historical SPV lookup attribution and FFI state after native provider replacement need correction. Independent source comparison confirms that the disputed rollback interleaving is introduced by this PR and remains blocking; 14 prior findings are fixed. This was static-only verification: current Rust, Swift, Kotlin and JS checks pass; the wasm32 rerun is pending after an earlier dependency-installation failure caused by Ubuntu mirror DNS resolution, unrelated to the patch.

🔴 1 blocking | 🟡 3 suggestion(s)

Still open from earlier rounds (3)

  • 🔴 Blocking: Serialize wallet-manager handover in its shared lifecycle owner — packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SdkRebuildSequence.swift:59-64 (thread)
  • 🟡 Suggestion: Validate the SPV runtime's network before publishing its quorum source — packages/rs-platform-wallet/src/manager/spv_quorums.rs:25-28 (thread)
  • 🟡 Suggestion: Test manager refusal at the callback-ownership boundary — packages/rs-platform-wallet-ffi/src/manager.rs:221-230 (thread)
Follow-up candidates (optional) (1)

New non-blocking observations on code unchanged since the last full review. No inline threads are opened for them and later reviews do not repeat them: fix forward or track separately if they are worth it.

🟡 Suggestion: Distinguish unavailable SPV history from an invalid node proof
packages/rs-platform-wallet/src/spv_context_provider.rs:132-138

Running and tip-synchronized does not establish coverage of historical Core heights. At the pinned rust-dashcore revision, prune_after_extending removes older masternode lists, and get_quorum_at_height explicitly supports only retained history. A lookup below that history returns QuorumLookupError, which the wallet stringifies into SpvError and maps here to Generic while SPV is running. The SDK consequently treats the honest response as a failed proof and can ban its node. This is reachable through fetch_blocks and fetch_owner_transactions_in_block: both accept historical heights and deliberately verify without freshness restrictions. The current upstream query has the same undifferentiated failure. Extend dashpay/rust-dashcore's query API to distinguish unavailable historical coverage from a quorum absent within covered history, preserve that distinction here as QuorumSourceUnavailable, and test that it bans no node. Strict SPV must continue failing closed rather than falling back to trusted keys.

source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, 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: platform-versioning); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 8: 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) — The large, cross-layer diff changes proof-verification key handling and trust selection, notably in SpvQuorumSource::get_quorum_public_key in packages/rs-platform-wallet/src/spv_context_provider.rs and the new adaptive provider.
  • 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)
  • Code unchanged since the last final review (33c882a2): 1 new suggestion(s) listed as follow-up candidates, not posted inline
  • 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 — platform-versioning (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 (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-sdk-ffi/src/sdk.rs`:
- [SUGGESTION] packages/rs-sdk-ffi/src/sdk.rs:754-762: Read provider capabilities from the SDK's active provider
  The SDK's shared replaceable slot is authoritative, but quorum_source reads the Adaptive/Trusted/SPV objects retained when SDKWrapper was constructed. Native code can obtain the SDK through dash_sdk_get_inner_sdk_ptr and call its supported set_context_provider method without updating those fields. An Adaptive SDK in SPV mode can then report SPV after replacement with a trusted provider, while dash_sdk_set_context_provider_mode returns success after modifying the discarded Adaptive object. Subsequent known-contract preloads and document lookups likewise keep using the constructor-time local_contracts resolver rather than the replacement's context. This is distinct from the intentional rule that existing caches are not migrated during replacement. Expose active-provider diagnostics and supported controls from the Rust owner, and have FFI operations delegate to that authority, returning an unsupported-operation error where appropriate. Cover native replacement followed by FFI diagnostics, mode changes and contract registration.

In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SdkRebuildSequence.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SdkRebuildSequence.swift:59-64: Serialize wallet-manager handover in its shared lifecycle owner
  (carried; thread: https://github.com/dashpay/platform/pull/3417#discussion_r4526085670)

In `packages/rs-platform-wallet/src/manager/spv_quorums.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/manager/spv_quorums.rs:25-28: Validate the SPV runtime's network before publishing its quorum source
  (carried; thread: https://github.com/dashpay/platform/pull/3417#discussion_r4515829357)

In `packages/rs-platform-wallet-ffi/src/manager.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/manager.rs:221-230: Test manager refusal at the callback-ownership boundary
  (carried; thread: https://github.com/dashpay/platform/pull/3417#discussion_r4515829363)
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.

  • Complete the manager shutdown and restoration contract in #5816 — The base already publishes a replacement after failed wallet restoration and does not establish that every old worker has stopped. These inherited gaps can hide persisted wallets or permit concurrent persistence access; they are separate from the new rollback interleaving reported above.
    • Follow-up: Resolve #5816 in a follow-up PR that exposes native shutdown completion, prevents unsafe replacement, and represents failed restoration as unavailable and retryable rather than successfully empty.

Comment thread packages/rs-sdk-ffi/src/sdk.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix.
Full checklist in the description.

shumkov and others added 5 commits November 12, 2026 09:26
Native code can replace an FFI-built SDK's context provider through
dash_sdk_get_inner_sdk_ptr and Sdk::set_context_provider. The FFI kept
acting on the providers it built: it reported their quorum source,
changed a discarded adaptive provider's mode, handed the wallet manager
a discarded SPV slot, and preloaded and looked up contracts in the
cache it built.

The provider now describes itself and the FFI asks the SDK's current
one:
- ContextProvider gains quorum_source(), set_quorum_mode() (refused by
  default) and spv_source_slot(), forwarded by the Arc/Box and Mutex
  wrappers. AdaptiveContextProvider answers all three, strict SPV its
  source and slot (it refuses every mode), TrustedHttpContextProvider
  its source. The inherent active_source/set_mode/source_slot methods
  they replace are gone.
- The routing enums move to quorum_source.rs;
  AdaptiveContextProviderSource is renamed QuorumKeySource.
- rs-sdk-ffi: SDKWrapper keeps only the SDK, the runtime and, for
  dash_sdk_get_status, the trusted provider and kind it was built with.
  Source, mode, dash_sdk_add_known_contracts (register_data_contract)
  and the 15 document lookups (SDKWrapper::data_contract) all go
  through sdk.context_provider(). The source FFI returns 2 for a
  provider that names no source, or a null handle; status quorumSource
  is live, mode and quorumCount stay build-time and documented.
- platform-wallet owns the slot claim (claim_spv_quorum_lease), which
  platform_wallet_manager_create_with_sdk calls before it reads the
  callback vtables; rs_sdk_ffi::dash_sdk_spv_source_slot is removed.
- Swift: SDK.QuorumSource gains .custom. The preload docs of the Swift
  SDK, the JNI bridge and the Kotlin SDK say the SDK's context provider.

Behaviour changes on v5.1-dev symbols: dash_sdk_add_known_contracts on a
provider that keeps no contracts (callbacks, mock) is a no-op success,
as register_data_contract's default documents, instead of InvalidState;
the document FFIs' lookup error on such an SDK reads "not found in the
SDK's context provider" (same codes).

Red -> green. At 1e1970d with only the new tests applied:
- sdk should_report_the_source_of_a_provider_set_after_build: left 1,
  right 0
- sdk should_refuse_a_mode_change_once_the_adaptive_provider_is_replaced:
  the change was reported as applied
- sdk should_preload_contracts_into_a_provider_set_after_build: "the
  contract must reach the provider set after build"
- status should_report_the_source_of_a_provider_set_after_build: left
  "spv", right "trusted"
- document util tests with the contract on a provider set natively:
  "set_properties failed"
- platform-wallet-ffi should_claim_the_slot_of_a_provider_set_after_build
  (its slot read through 1e1970d's inherent source_slot()): "the
  manager must serve the current provider's slot"
- trusted should_report_its_trusted_source_and_refuse_a_mode_change
  (trait in place, no override): left None, right Some(Trusted)
- provider-crate tests: E0599/E0432 (new API)
Also pinned: a strict SPV SDK refuses every mode through the FFI, and
preloading into a provider that keeps no contracts succeeds.
All pass after the change: dash-context-provider 21, trusted 156,
rs-sdk-ffi 444, platform-wallet spv_quorums 2, platform-wallet-ffi
manager 31.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he manager's

A manager publishes its SPV quorum source for its SDK's network when it
is created, and that source reads the manager's SPV runtime. The runtime
accepted any ClientConfig, and platform_wallet_manager_spv_start fills
its network from a separate argument. A client started for another
network would sync that chain, and Auto would verify the SDK's proofs
with that chain's Platform quorums.

- SpvRuntime::start and start_and_spawn refuse, with InvalidParameter, a
  config whose network is not the wallet manager's (built with
  sdk.network), before they open the store or build a client. The check
  is the last of the start's early checks, so a start on a running
  client is refused as already running without waiting for the wallet
  manager. The FFI only marshals the error.
- A provider never uses a published SPV source that declares another
  network than its own: strict SPV fails closed without blaming the
  node, and Auto treats the source as not ready. SpvQuorumSource reports
  its network and is built only by its manager (crate-private new), so
  a manager serving another SDK's slot through the public Rust API
  cannot vouch for that SDK's proofs either.

Behaviour change on v5.1-dev symbols: SpvRuntime::start /
start_and_spawn and platform_wallet_manager_spv_start refuse a
mismatched network. Not covered: devnet names are not compared, and a
store written by another network is not detected.

Eight runtime tests passed ClientConfig::default() (Mainnet) to Testnet
runtimes to reach other refusals; they now pass ClientConfig::testnet(),
and two that asserted only is_err() now assert ShutdownIncomplete.

Red -> green:
- should_refuse_to_start_a_client_for_another_network_than_its_wallets:
  before the check, start returned Ok(()) for a Mainnet config on a
  Testnet runtime;
- should_not_use_a_published_spv_client_of_another_network: with the
  slot's network check disabled, strict SPV served the Mainnet source;
- should_refuse_a_start_on_a_running_client_before_reading_the_wallet_manager:
  with the network read first, the start timed out behind the held
  wallet manager.
All pass with the change: platform-wallet spv 63, dash-context-provider
22, platform-wallet-ffi spv 7.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
platform_wallet_manager_create_with_sdk claims its SDK's SPV slot before
it reads the host's callback vtables, so a refusal never takes ownership
of the host's contexts, and every refusal after the claim drops the
lease and frees the slot. Nothing tested either.

Two offline tests on a strict SPV SDK (regtest, loopback, nothing it
waits on), with release-counting callback contexts:
- a second manager on one SDK is refused with "already serves" without
  releasing its caller's contexts; destroying the first releases its
  contexts once and frees the SDK for a third;
- a create refused after the claim, for a borrowed context
  (ErrorInvalidParameter) or a null out pointer (ErrorNullPointer),
  leaves the slot free for a later valid create.

The behaviour is correct at HEAD, so the tests pass there. Each was
shown to catch its regression by a mutation run:
- building FFIPersister and FFIEventHandler from the vtables before
  claim_spv_quorum_lease: the first test fails, "a refused create must
  not release the caller's contexts", left (1, 1), right (0, 0);
- std::mem::forget of the lease on create_impl's borrowed-persistence-
  context refusal: the second fails, "the refused creates must have left
  the slot free", left ErrorInvalidParameter, right Success.
platform-wallet-ffi manager tests: 33 passed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every window shares AppState and WalletManagerStore, but each Options
window gated its SDK rebuilds with its own isSwitchingNetwork, and the
store refused only a second activation for the same network, after the
loser had already stopped SPV, prepared settings and built an SDK. Two
windows could therefore run two rebuilds: the losing one's rollback
restored its captured settings over the winning one's (Local -> Testnet
in two windows left Docker on under a Docker-off SDK), and rebuilds for
different networks published in whichever order they resumed. Every
window also ran the bootstrap, which publishes its own SDK and activates
a manager; with activate now awaiting the replaced manager's shutdown, a
window opened during a rebuild could leave the app on one network with
another network's manager active.

One rule now: the SDK, its network and the active manager change only
inside AppState.rebuildSdk, or in the one bootstrap before any window
can rebuild.
- AppState.rebuildSdk reserves the rebuild (isRebuildingSdk) before its
  first suspension and releases it after publish or rollback; a second
  rebuild from any window gets .busy and runs no step. buildSdk and
  publish are private and the rebind tick private(set), so nothing else
  can publish.
- The sequence checks the network before it stops SPV, so a stale tap
  changes nothing.
- OptionsView: isSwitchingNetwork is gone; the UI disables its rebuild
  controls and shows the spinner on appState.isRebuildingSdk, in every
  window. The flows read the settings they change inside prepare, so
  rollBack restores exactly what prepare overwrote, and a devnet edit
  refused as .busy stays pending.
- WalletManagerStore.stopSpvForReconfiguration invalidates pending SPV
  starts and stops the active manager; the rebuild and the custom-peers
  toggle stop through it, so a refused rebuild touches nothing.
- The App runs bootstrap() once per process; later windows await it.
- activatingNetworks, ActivationInProgress and its test are removed:
  with the above no two activations for one network can overlap
  (backgroundManager activates only an uncached network, which never
  suspends), so the guard could never fire.

Tests: AppStateSdkRebuildTests (a second rebuild is refused while the
first stops SPV, and while it activates the manager, without its
rollback running; the reservation frees afterwards), a stale-tap
sequence test, and a test that stopSpvForReconfiguration cancels
pending starts. Expected red at 1e1970d, reasoned, not run: the
AppState tests and the stop test do not compile there (no rebuildSdk,
isRebuildingSdk, .busy or stopSpvForReconfiguration), and the stale-tap
sequence records a stopSpv there because it checks the network only
after the stop. pasta has no Xcode: the changed Swift was parsed with
swiftc -parse, and a review type-checked the changed code against
stubbed SDK types under Swift 6 with warnings as errors; CI's Swift job
builds and runs it. The once-per-process bootstrap has no unit test:
the App struct cannot be driven from SwiftExampleAppTests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
WalletManagerStore.backgroundManager(for:) built its own
SDK(network:, contextProvider: .adaptive) and never applied the quorum
mode, so orphan recovery, wallet creation on another network and the
bootstrap pre-warm verified proofs in Auto, with trusted quorum keys,
while the user had chosen SPV, documented as having no trusted
fallback. The mode was also applied only to the published SDK, so an
SDK built earlier kept the mode it was built with.

AppState now builds every SDK and applies the mode to every SDK it built:
- AppState.makeSdk(for:) builds the adaptive SDK, applies the user's
  mode and loads the stored contracts, synchronously. The bootstrap, SDK
  rebuilds and background managers all build through it, and it keeps a
  weak reference to each SDK it built.
- applyQuorumMode applies the mode to each of those SDKs that is still
  alive, then updates the indicator from the published one, so a mode
  change also reaches the background SDKs.
- WalletManagerStore takes the builder at init, with no default; the App
  creates AppState in init and passes it. backgroundManager builds with
  it, without suspending before activate, so it still activates only an
  uncached network.
- In SPV mode a background manager's proven queries fail closed, with no
  trusted keys and no node banned, unless that network's manager runs
  SPV; this is documented on backgroundManager.

Tests: the store builds a background manager's SDK with the injected
builder, once; an SDK is built in the selected mode; a mode change
reaches two SDKs AppState built. The SDK-building tests point the
app's endpoint settings at loopback and restore them. Expected red at
1e1970d, reasoned, not run: none of them compiles there (no
WalletManagerStore(modelContainer:makeSdk:), no AppState.makeSdk);
there backgroundManager hard-codes Auto and applyQuorumMode reaches
only the published SDK. pasta has no Xcode, so the Swift was parsed
and type-checked against stubs only; CI's Swift job runs it.

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

github-actions Bot commented Nov 12, 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.

v5.1-dev at 076393c. One conflict, in PlatformWalletManager's fields
and their initializers: v5.1-dev's txo_reconcile_schedule (#5796) sits
beside this branch's spv_quorum_lease; both are kept.

Checked on the merge: cargo fmt; clippy -D warnings on
dash-context-provider, rs-sdk-trusted-context-provider, rs-sdk-ffi,
platform-wallet, platform-wallet-ffi and rs-unified-sdk-jni; with CI's
env and --all-features, those crates and dash-sdk: 3,990 passed, 0
failed, 33 ignored.

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

github-actions Bot commented Nov 12, 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.

@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

At 054f010, the active-provider forwarding, SPV startup network checks, callback-ownership regressions, and shared application rebuild reservation are present. One native-lifecycle ownership blocker remains. Verification was static only; current CI reports successful Rust workspace, wasm32, Swift, and Kotlin checks, while review and PR Hygiene remain pending.

🔴 1 blocking

Still open from earlier rounds (1)

  • 🔴 Blocking: Serialize wallet-manager handover in its shared lifecycle owner — packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/WalletManagerStore.swift:295-308 (thread)
Review provenance

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

  • Triage: critical by gpt-6.1-sol (effort low) — This large, intricate change directly changes cryptographic key handling and the trust boundary for Platform proof verification in packages/rs-context-provider/src/adaptive.rs and packages/rs-context-provider/src/spv/provider.rs by selecting which quorum public keys the verifier trusts.
  • 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 (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/WalletManagerStore.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/WalletManagerStore.swift:295-308: Serialize wallet-manager handover in its shared lifecycle owner
  (carried; thread: https://github.com/dashpay/platform/pull/3417#discussion_r4515829348)
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.

  • Preserve explicit failure states during wallet-manager replacement — Replacement still proceeds after an incomplete native shutdown or a failed wallet restore. The baseline already had these limitations, and #5816 tracks both surviving workers accessing persistence and failed reads being presented as an empty manager.
    • Follow-up: Resolve #5816 in a follow-up PR with explicit shutdown/restoration outcomes and a retryable unavailable state exposed through the bindings.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix.
Full checklist in the description.

shumkov and others added 5 commits November 12, 2026 11:21
A mode change reached the SDKs only through the scene's
.onChange(of: platformState.quorumMode), which called
AppState.applyQuorumMode(). The tests called applyQuorumMode() by hand,
so deleting that modifier would have stopped the Quorum Source picker
from changing any SDK without failing a test. The SPV progress and
running observers also re-applied the mode to every SDK on each tick,
although the adaptive provider follows SPV readiness by itself.

- quorumMode's didSet applies the mode to every live SDK AppState built
  and refreshes the indicator; applyQuorumMode is private, and the
  scene's onChange for the mode is gone.
- refreshQuorumSource() only reads the published SDK's current source
  into quorumSource. The SPV observers and the bootstrap, after the
  wallet manager activates, call it; publish no longer re-applies the
  mode, since makeSdk built that SDK in it and every later change
  reached it through didSet.

Test: setting quorumMode, with no applyQuorumMode call, switches two
SDKs AppState built to SPV and moves the indicator of the published one.
Expected red at 054f010, reasoned, not run: there the setter only
saves the mode, so both SDKs stay in Auto and report trusted, and the
indicator keeps its initial trusted. pasta has no Xcode, so the files
were parsed, and the didSet/refresh pattern type-checked and run in a
Swift 6 stub; CI's Swift job runs the test.

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

65e2d3c removed WalletManagerStore's activatingNetworks guard because
no caller could reach it: AppState.rebuildSdk runs one SDK rebuild at a
time, the bootstrap runs once, and backgroundManager activates only a
network without a manager. That made the store's invariant, one manager
replacement per network at a time, hold only while every caller stays
serialized. A replacement suspends while the manager it replaces shuts
down, and a second call in that window would replace the same cached
manager and publish over the first one's without shutting it down.

Two invariants, two owners: AppState's reservation serializes the
rebuild transaction and stays as it is; the store refuses an overlapping
activation itself.
- activate inserts its network into activatingNetworks before it
  configures anything or suspends, and removes it with defer; a call for
  a network already in the set throws ActivationInProgress.
- The error reads "The <network> wallet manager is already being
  replaced, so this change was not applied.", without naming a rebuild,
  since any caller can hit it. OptionsView's activateManager reports
  any activation error with its localized description and rolls the
  rebuild back, and the bootstrap surfaces it as its bootstrap error;
  with the rebuild reservation in place, rebuilds do not reach it.

Test:
testShouldRefuseASecondActivationWhileTheFirstAwaitsTheReplacedManagersShutdown,
restored from dc5f205 and adapted to the store's
makeSdk init. It holds the replaced manager's shutdown open, checks
that a second activation is refused twice with ActivationInProgress
for regtest, configures nothing (its SDK's SPV slot stays free), and
that the first activation then publishes and stays cached. It catches
the typed error instead of matching message text. Expected red at
03083e2, reasoned, not run: the test does not compile there (no
WalletManagerStore.ActivationInProgress); without the guard the second
call configures a manager on its SDK and awaits the same shutdown.
pasta has no Xcode: the files were parsed, and the guard and the typed
catch were type-checked and run in a Swift 6 stub with warnings as
errors; CI's Swift job runs the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
WasmTrustedContext wraps a TrustedHttpContextProvider but did not
forward ContextProvider::quorum_source(), so an SDK built with it read
as one whose provider does not say where its quorum keys come from. The
trait asks a wrapping provider to forward it.

- WasmTrustedContext forwards quorum_source() to the provider it wraps.
  It does not forward set_quorum_mode() or spv_source_slot(): the
  trusted provider has no mode and no SPV slot, so the defaults answer
  the same.
- dash_sdk::platform re-exports QuorumKeySource beside ContextProvider,
  whose quorum_source() returns it, so crates that reach the trait
  through dash_sdk can name it.

Test: a WasmTrustedContext reports Some(Trusted), run natively. Seen
red before the forward (left: None, right: Some(Trusted)) and green
after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since 62501b0 a provider never uses a published SPV source that
declares another network than its own: Auto treats it as not ready and
answers from the trusted provider, and strict SPV fails closed. The
docs of AdaptiveContextProvider::quorum_source and of the Auto and Spv
modes now say so. No behaviour change, so no test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
dash_sdk_get_context_provider_source mapped QuorumKeySource to 0 and 1
by hand. The enum is #[repr(u8)] with those values, so the FFI now casts
it. The existing FFI tests pin the 0/1/2 values; no behaviour change.

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.

@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

Static verification of 136612c confirms the source-discriminant change and WASM forwarding; the reported runtime-bridge test gap is already covered. One in-scope ownership blocker remains in the native manager handover. Current CI passes all executed code checks, including functional, browser, and E2E suites; review/hygiene gates remain pending, and no local builds or tests were run.

🔴 1 blocking

Still open from earlier rounds (1)

  • 🔴 Blocking: Serialize wallet-manager handover in its shared lifecycle owner — packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/WalletManagerStore.swift:303-317 (thread)
Review provenance

Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); 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); reviewer 8: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 9: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 10: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 11: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 12: 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 large, intricate change directly alters cryptographic proof-verification key sourcing and trust-boundary enforcement in packages/rs-context-provider/src/adaptive.rs and packages/rs-platform-wallet/src/spv_context_provider.rs, including SPV verification-status filtering, network binding, and trusted fallback routing.
  • 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 final gate: an independent Phase-2 review ran after iterative findings were reconciled
  • 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, 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 (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/WalletManagerStore.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/WalletManagerStore.swift:303-317: Serialize wallet-manager handover in its shared lifecycle owner
  (carried; thread: https://github.com/dashpay/platform/pull/3417#discussion_r4515829348)
Out-of-scope follow-up suggestions (2)

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.

  • Preserve shutdown and restoration failures in the lifecycle follow-up — The base already failed to establish complete shutdown before replacement and treated wallet-restoration errors as non-fatal, allowing an empty manager to be published. These existing outcome-handling defects remain important because they can expose concurrent persistence access or hide persisted wallets; they are separate from the new handover-placement blocker.
    • Follow-up: Address #5816 in a follow-up PR with explicit shutdown-completion and retryable restoration outcomes propagated from the Rust lifecycle owner through the bindings.
  • Exercise the production runtime bridge across Tokio runtime flavors — False positive at the exact head: packages/rs-platform-wallet/src/spv_context_provider.rs:216-273 constructs the production SpvQuorumSource over an unstarted SpvRuntime and tests outside Tokio, on a current-thread runtime, and on a multithreaded runtime. The unsupported contexts assert QuorumSourceUnavailable, while the supported context executes the real bridge and readiness/key-lookup paths. The prior identity is therefore reconciled FIXED.
    • Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix.
Full checklist in the description.

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

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

Labels

Client Only Interesting Something we should do. priority: medium Medium priority 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.

4 participants