Repository navigation
feat(swift-sdk): use SPV-synced quorums for Platform proof verification - #3417
Conversation
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]>
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
Walkthrough
Pre-merge checks:
|
|
⛔ Final review complete — 1 blocking finding(s) (commit 136612c) · triage: critical |
|
✅ 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:
|
There was a problem hiding this comment.
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
📒 Files selected for processing (7)
packages/swift-sdk/Sources/SwiftDashSDK/Core/SPV/SPVClient.swiftpackages/swift-sdk/Sources/SwiftDashSDK/Core/SPV/SPVContextProvider.swiftpackages/swift-sdk/Sources/SwiftDashSDK/Core/Services/WalletService.swiftpackages/swift-sdk/Sources/SwiftDashSDK/SDK.swiftpackages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swiftpackages/swift-sdk/SwiftExampleApp/SwiftExampleApp/UnifiedAppState.swiftpackages/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 Report✅ All modified and coverable lines are covered by tests.
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
🚀 New features to boost your workflow:
|
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]>
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (4)
packages/rs-platform-wallet/Cargo.tomlpackages/rs-platform-wallet/src/lib.rspackages/rs-platform-wallet/src/spv_context_provider.rspackages/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
- 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]>
|
All review feedback addressed. Additionally, bumped rust-dashcore to |
There was a problem hiding this comment.
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 | 🟠 MajorMake the network switch commit atomically.
The new SPV-first failure paths can throw after the collections are cleared and
dataManager.currentNetworkis advanced, but beforesdkis replaced. On that path the UI says “new network” while platform calls still go through the old SDK instance. IfcurrentNetworkshould 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
initializeSDKandswitchNetwork. 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
📒 Files selected for processing (4)
packages/rs-platform-wallet/Cargo.tomlpackages/rs-platform-wallet/src/spv_context_provider.rspackages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swiftpackages/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
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]>
…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]>
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]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
thepastaclaw
left a comment
There was a problem hiding this comment.
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:
criticalbygpt-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); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-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; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— platform-versioning (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-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.
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix. |
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]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
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]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
thepastaclaw
left a comment
There was a problem hiding this comment.
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:
criticalbygpt-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); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-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; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-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.
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix. |
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]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
thepastaclaw
left a comment
There was a problem hiding this comment.
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:
criticalbygpt-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); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-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; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-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.
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix. |
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
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:Verified.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):SpvContextProvidertakes quorum keys only from an SPV client and never from the trusted service.AdaptiveContextProviderroutes each lookup by mode:core_height_verified, because it does not record which source supplied a quorum's key.ContractSource, which has no quorum keys.SdkBuilder::build. The adaptive provider also reports its trusted provider's proof requirement, so the builder's provider checks apply to them.AdaptiveContextProvider::newrefuses a trusted provider that declares another network, which the builder cannot see behind it.SpvSourceSlotis where an SPV client publishes its quorum lookups. A client claims it and holds it through a lease, one lease at a time.QuorumSourceUnavailable, so the SDK does not ban the node whose proof it could not check.ContextProvidergainsquorum_source(),set_quorum_mode()(refused by default) andspv_source_slot(), forwarded by theArc/Box/Mutexwrappers.QuorumKeySource, inquorum_source.rs.SDK (
dash-sdk):Sdk::set_context_providerreplaces 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.Local contract cache (
rs-sdk-trusted-context-provider):TrustedHttpContextProvideris nowLocalContextResolver. The trusted provider delegates to it.system_contractsloader, which includes the decision-proposals and token-market contracts from protocol 15.replace_known_contractreplaces on purpose.FFI (
rs-sdk-ffi):dash_sdk_create_trusted,dash_sdk_create_spvanddash_sdk_create_adaptivebuild the matching provider. Strict SPV never builds the trusted HTTP provider and ignoresquorum_url.sdk.context_provider()), so it follows a nativeset_context_provider:dash_sdk_get_context_provider_source:0trusted,1SPV,2a provider that names no source);dash_sdk_set_context_provider_mode, refused by a provider without modes);dash_sdk_add_known_contracts, viaregister_data_contract);quorumSource.SDKWrapperkeeps only the SDK, the runtime and, fordash_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_spawnrefuse 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:
Synced;dash-spv keeps masternode sync
Syncedwhen 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
Verifiedare served. Quorum types that name no LLMQ type are refused.Swift:
SDK(network:contextProvider:)defaults to Trusted.SDK.quorumSourcereads the native SDK's current provider,.customfor one that names no source.SDK.QuorumModedocuments each mode.PlatformWalletManager.configure(sdk:)creates the manager throughcreate_with_sdk.AppState.rebuildSdkreserves 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.AppState.makeSdkin the selected quorum mode, and a mode change reaches all of them.Merged with v5.1-dev at
076393c5c0(earlier at9b36712770and46c26cb05f). The latest merge only kept v5.1-dev'stxo_reconcile_schedulebeside this branch'sspv_quorum_leaseinPlatformWalletManager. The first merge brought in the rust-dashcore pin above, the verified quorum provider (#5523, #5720) and its SDK opt-in (#5721). The second:LocalContextResolver. Registration no longer overwrites a newer held contract, as this PR first had it;Earlier merge details:
Sdk::set_context_providerand its tests are as on v5.1-dev. Only the slot behind the setter changed, and clones now share it.How Has This Been Tested?
At
119d13368a, the final scope (provider follow-through in the FFI, SPV client network,create_with_sdkownership tests, one rebuild at a time, background SDK quorum mode):dash-context-providerandrs-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-ffianddash-sdk, same env, 3,931 passed, 0 failed, 33 ignored.cargo clippy --all-targets --all-features -- -D warningsclean ondash-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.1e1970d281with only the new test applied:set_context_provideron an FFI-built adaptive SDK, the source FFI, statusquorumSource, the mode refusal, preloads, document lookups and the slot a manager claims all follow the replacement;create_with_sdk's ownership is correct at the previous head, so those two tests were shown by mutation runs:054f010f6a): fmt and clippy clean on the touched crates; those crates anddash-sdkwith CI's env: 3,990 passed, 0 failed, 33 ignored.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 at1e1970d281). CI's Swift job (warnings as errors) built them and ran them green at054f010f6a. The once-per-process bootstrap has no unit test.At
50d5ed32f6, the runtime provider setter:--all-features --lib --bins --tests.dash-sdk: 929 passed, 0 failed.f603f988: 1,035 passed. These include the 12block_query_testsfrom feat(sdk): verify the block proofs of getBlocks and getOwnerTransactionsInBlock #5834, which callset_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:should_fetch_a_referenced_system_contract_the_sdk_does_not_compile_in. It assumes the withdrawals contract is not compiled in, which--all-featureschanges. The failure predates this change.cargo clippy --all-targets --all-features -- -D warningsis clean ondash-sdk,rs-sdk-ffi,dash-context-provider,rs-sdk-trusted-context-provider,platform-wallet,platform-wallet-ffi,wasm-sdk(also for wasm32) anddash-platform-balance-checker.should_share_a_provider_set_on_one_clone_with_every_cloneandshould_verify_a_mock_answer_with_a_provider_set_after_buildfail when clones copy the slot, as on v5.1-dev.should_finish_a_verification_with_the_provider_it_started_withfails when the re-verification after a key fetch reloads the slot.At
47e3355613, after the second v5.1-dev merge: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 warningsclean ondash-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.should_refuse_a_trusted_provider_for_another_network(red with the constructor fallible but unchecked) and the resolver'sshould_keep_a_newer_contract_over_a_registered_older_one(red with registration overwriting, as before the merge).swiftc -parsehere; the Swift SDK job builds it. The indicator fix has no test, as SwiftExampleAppTests cannot drive a view's modifiers.Earlier rounds:
cargo test --all-features --locked --lib --bins --tests -- --skip shield, CI's package list and env):1655562fbf.strategy_testsbinary ran, not only the two tests PR CI picks.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-storageshield-named SQLite tests: 7 passed.wasm-sdk: 217 native tests passed, and 45 wasm32 tests passed underwasm-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;wasm-sdkfor wasm32.cargo check --workspace --all-targets.should_not_be_ready_while_the_masternode_list_trails_the_header_tip;should_forward_provider_requirements_through_every_wrapper;SDK.quorumSourcefor a strict SPV SDK (Swift).swiftc -parse). The Swift SDK job is the build and test gate.Known limits:
Verifiedis reported as unavailable. A node can name one without being banned.Follow-ups:
dash_sdk_add_known_contractsaccepts system-contract IDs.VerifiedHttpContextProviderbefore the trusted service, on networks whose relay serves/proofs. Today that is testnet only: mainnet's relay refuses/proofs, and Core v24 is not released.core_height_verifiedto the source that supplied a key comes with persisting the verified provider'scontinuation().VerifiedHttpContextProviderkeeps its own contract and token caches and lookup, which duplicateLocalContextResolver. Delegate to the resolver.server, and belongs indpp.TrustedHttpContextProviderreports nonetwork()(feat(sdk): make TrustedHttpContextProvider report its network so the SDK refuses a mismatch #5766), so the builder cannot check it.Invalidreads as missing, so its lookups are charged to the node.Syncedwhile its newest list lags the header tip after given-up tip updates; this PR's readiness adds a two-block lag check. Tracked upstream in dash-spv: masternode sync staysSyncedwhile its newest list falls behind the header tip rust-dashcore#1366.get_quorum_at_heightshould tell a height its retained masternode lists do not cover from a quorum that is absent rust-dashcore#1396). The SDK must then decide per call site, since the height is unverified.set_context_provider, a wallet manager keeps serving the slot it claimed;WasmTrustedContextandVerifiedHttpContextProviderdo not forward the new provider methods.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_provideron 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_statusreportsmode: "custom"instead of"spv"for SDKs built bydash_sdk_create,dash_sdk_create_extendedordash_sdk_create_with_callbacks.dash_sdk_add_known_contractson an SDK whose provider keeps no contracts (callbacks, mock) succeeds as a no-op, asContextProvider::register_data_contract's default documents. On v5.1-dev it returnedInvalidState. 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_spawnandplatform_wallet_manager_spv_startrefuse, with an invalid-parameter error, a network other than the wallet manager's.Checklist:
structure.rs, regeneratedgrovedb-structure.json, and checked the structure viewer link posted on this pull request🤖 Generated with Claude Code
PR Hygiene ·
136612c/skip-botsproceeds without the ones not yet reported/self-reviewedkotlin-sdk(packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/PlatformQueries.kt) — HashEngineeringrs-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 romchornyirs-platform-wallet(packages/rs-platform-wallet/Cargo.toml,packages/rs-platform-wallet/src/lib.rs,packages/rs-platform-wallet/src/manager/mod.rsand 3 more) — HashEngineering or ZocoLini or llbartekll or romchornyirust-sdk-ffi(packages/rs-sdk-ffi/Cargo.toml,packages/rs-sdk-ffi/src/document/create.rs,packages/rs-sdk-ffi/src/document/delete.rsand 11 more) — lklimek or shumkovrust-sdk(packages/rs-sdk/src/platform.rs,packages/rs-sdk/src/sdk.rs,packages/rs-sdk/src/sdk/protocol_gate_tests.rsand 1 more) — lklimek or shumkovswift-sdk(packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift,packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift,packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/AppState.swiftand 15 more) — llbartekll or romchornyijs-wasm-sdk(packages/wasm-sdk/src/context_provider.rs) — shumkovWhen every merge requirement is met, the
PR Hygienecheck passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.