Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

89 changes: 72 additions & 17 deletions packages/rs-platform-wallet-ffi/src/shielded_send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@
//! crosses the FFI boundary.
//!
//! Feature-gated behind `shielded`. The accompanying
//! [`platform_wallet_shielded_warm_up_prover`] entry-point is
//! also defined here so hosts can pre-build the Halo 2 proving
//! key on a background thread at app startup.
//! [`platform_wallet_shielded_warm_up_prover`] (fire-and-forget) and
//! [`platform_wallet_shielded_prepare_prover`] (blocks until ready)
//! entry-points are also defined here so hosts can pre-build the
//! Halo 2 proving key at app startup.
//!
//! [`ShieldedWallet`]: platform_wallet::wallet::shielded::ShieldedWallet
//! [`ShieldedWallet::shield`]: platform_wallet::wallet::shielded::ShieldedWallet::shield
Expand Down Expand Up @@ -136,28 +137,62 @@ unsafe fn parse_required_platform_address(
}
}

/// Kick off the Halo 2 proving-key build on a background tokio
/// worker if it hasn't been built yet. Returns immediately —
/// hosts can call this at app startup without blocking the UI
/// thread. Subsequent calls are cheap no-ops once the key is
/// cached. The first shielded send still pays the ~30 s build
/// cost only if it fires before the warm-up worker finishes;
/// `platform_wallet_shielded_prover_is_ready` reports whether
/// that's the case.
///
/// Independent of any manager — the cache is a process-global
/// `OnceLock`.
/// Kick off the Halo 2 proving-key build in the background if it
/// hasn't been built yet. Returns immediately — hosts can call this
/// at app startup without blocking the UI thread. Subsequent calls
/// are cheap no-ops once the key is cached.
///
/// The build runs on the runtime's blocking pool and is shared with
/// every other preparation: a shielded send (or
/// [`platform_wallet_shielded_prepare_prover`]) that starts while it
/// is running waits only for the remaining build time.
/// `platform_wallet_shielded_prover_is_ready` reports whether it has
/// finished.
///
/// Independent of any manager — the cache is process-global.
#[no_mangle]
pub unsafe extern "C" fn platform_wallet_shielded_warm_up_prover() {
runtime().spawn_blocking(|| CachedOrchardProver::new().warm_up());
runtime().spawn(async {
// A failed build leaves the cache empty; the next preparation
// (or send) retries and reports the error.
let _ = CachedOrchardProver::prepare().await;
});
}

/// Block the calling thread until the Halo 2 proving key is built,
/// starting the build if nobody has yet. Returns immediately if the key
/// is already cached.
///
/// Shares the single process-wide build with
/// [`platform_wallet_shielded_warm_up_prover`] and with shielded sends,
/// so calling it while a warm-up is running waits only for the
/// remainder. The build runs on the runtime's blocking pool; the calling
/// thread just parks. Call it off the main thread (e.g. from a
/// background dispatch queue) to learn when the prover is ready.
///
/// Returns an error only if the build panicked or the runtime is
/// shutting down; the cache then stays empty and a later call retries.
#[no_mangle]
pub unsafe extern "C" fn platform_wallet_shielded_prepare_prover() -> PlatformWalletFFIResult {
// Preparation spends nothing, so a panic in the runtime bridge is a
// definitive failure rather than an ambiguous spend outcome.
catch_panic_to_code(
"shielded prover preparation",
PlatformWalletFFIResultCode::ErrorWalletOperation,
"No spend was broadcast.",
|| match block_on_worker(CachedOrchardProver::prepare()) {
Ok(()) => PlatformWalletFFIResult::ok(),
Err(e) => e.into(),
},
)
}

/// Whether the Halo 2 proving key has already been built.
///
/// Useful as a UI indicator ("preparing prover…") before the
/// first shielded send. `false` doesn't mean shielded sends will
/// fail — it just means the next one will pay the ~30s build
/// cost up front.
/// fail — it just means the next one will wait for the build to
/// finish first.
#[no_mangle]
pub unsafe extern "C" fn platform_wallet_shielded_prover_is_ready() -> bool {
CachedOrchardProver::new().is_ready()
Expand Down Expand Up @@ -2294,6 +2329,26 @@ mod tests {
use platform_wallet::wallet::shielded::store::PendingRedrive;
use platform_wallet::wallet::shielded::{FileBackedShieldedStore, ShieldedStore, SubwalletId};

/// The blocking prepare entry point returns only once the real key is
/// cached, and joins a warm-up already in flight. Builds the real Halo 2
/// key (~30 s debug, ~1-3 s release), so ignored by default.
#[test]
#[ignore = "builds the real Halo 2 proving key"]
fn prepare_prover_blocks_until_the_key_is_ready() {
unsafe {
platform_wallet_shielded_warm_up_prover();
let start = std::time::Instant::now();
let result = platform_wallet_shielded_prepare_prover();
assert_eq!(result.code, PlatformWalletFFIResultCode::Success);
assert!(platform_wallet_shielded_prover_is_ready());
eprintln!("prepare_prover waited {:?}", start.elapsed());
// Ready: repeated preparation succeeds and preserves readiness.
let result = platform_wallet_shielded_prepare_prover();
assert_eq!(result.code, PlatformWalletFFIResultCode::Success);
assert!(platform_wallet_shielded_prover_is_ready());
}
}

#[test]
fn encode_memo_text_none_is_empty() {
let bytes = encode_memo_text(None).expect("None must encode");
Expand Down
11 changes: 10 additions & 1 deletion packages/rs-platform-wallet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,15 @@ zip32 = { version = "0.2.0", default-features = false, optional = true }
# Same version as `dash-sdk` so the lockfile resolves a single copy.
futures = { version = "0.3.30", optional = true }

# Apple targets only (shielded feature): the Orchard prover runs key builds
# and proofs on a dedicated rayon pool whose threads request the
# user-initiated QoS class (`pthread_set_qos_class_self_np`), so a build
# started from a background-QoS host thread is never throttled. Same rayon
# major as the one halo2 already pulls in, so the lockfile keeps one copy.
[target.'cfg(target_vendor = "apple")'.dependencies]
rayon = { version = "1.10", optional = true }
libc = { version = "0.2", optional = true }

# Networked, opt-in example binaries. Each one performs real network I/O
# against a live devnet, so they are examples (compiled, never run by
# `cargo test`) rather than `#[ignore]`d tests. They are crate-gated on the
Expand Down Expand Up @@ -130,7 +139,7 @@ default = ["bls", "eddsa"]
test-utils = ["key-wallet/test-utils"]
bls = ["key-wallet/bls", "key-wallet-manager/bls"]
eddsa = ["key-wallet/eddsa", "key-wallet-manager/eddsa"]
shielded = ["dep:grovedb-commitment-tree", "dep:rusqlite", "dep:zip32", "dep:futures", "dash-sdk/shielded", "dpp/shielded-client"]
shielded = ["dep:grovedb-commitment-tree", "dep:rusqlite", "dep:zip32", "dep:futures", "dep:rayon", "dep:libc", "dash-sdk/shielded", "dpp/shielded-client"]
# Opt-in serde derives on the changeset types in `src/changeset/` plus
# the per-identity / DashPay scalar types those changesets carry.
# Activates `key-wallet/serde` (which transitively activates
Expand Down
43 changes: 23 additions & 20 deletions packages/rs-platform-wallet/src/wallet/platform_wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1327,7 +1327,7 @@ impl PlatformWallet {
&self,
seed: &[u8],
account: u32,
) -> Result<super::shielded::OrchardKeySet, PlatformWalletError> {
) -> Result<Arc<super::shielded::OrchardKeySet>, PlatformWalletError> {
use super::shielded::OrchardKeySet;
let bound_fvk = {
let guard = self.shielded_keys.read().await;
Expand All @@ -1347,7 +1347,9 @@ impl PlatformWallet {
"seed does not derive the bound viewing key for shielded account {account}"
)));
}
Ok(keyset)
// `Arc` so the spend proof can move the keyset onto a blocking
// thread without copying the spend authority.
Ok(Arc::new(keyset))
}

/// Send a private shielded → shielded transfer from `account`'s
Expand All @@ -1357,20 +1359,21 @@ impl PlatformWallet {
/// `coordinator` supplies the shared, network-scoped
/// commitment-tree store; `seed` supplies the spend authority —
/// the full `OrchardKeySet` (with the `SpendAuthorizingKey`) is
/// re-derived from it for this call only and dropped on return.
/// re-derived from it for this call only and dropped on return (if
/// the call is cancelled mid-proof, once the in-flight proof on the
/// blocking pool finishes, which holds it by `Arc`).
/// Privilege separation: the ASK never crosses to the
/// coordinator — the spend free function takes the keyset by
/// reference at call time.
///
/// The prover is consumed by value rather than borrowed
/// because `OrchardProver` is impl'd on
/// `&CachedOrchardProver` (the reference type), not on the
/// bare struct. Callers pass `&CachedOrchardProver::new()`
/// and we forward it down to the spend free function's
/// `&P` parameter.
/// `prover` is any [`ShieldedProver`](crate::wallet::shielded::ShieldedProver)
/// — in practice `CachedOrchardProver` or `&CachedOrchardProver`.
/// The spend awaits the prover's shared, off-runtime key
/// preparation and then generates the proof on tokio's blocking
/// pool, so no async worker is held for the multi-second build.
#[cfg(feature = "shielded")]
#[allow(clippy::too_many_arguments)]
pub async fn shielded_transfer_to<P: dpp::shielded::builder::OrchardProver>(
pub async fn shielded_transfer_to<P: crate::wallet::shielded::ShieldedProver>(
&self,
coordinator: &Arc<crate::wallet::shielded::NetworkShieldedCoordinator>,
seed: &[u8],
Expand Down Expand Up @@ -1412,7 +1415,7 @@ impl PlatformWallet {
/// the transient spend authority (see
/// [`shielded_transfer_to`](Self::shielded_transfer_to)).
#[cfg(feature = "shielded")]
pub async fn shielded_unshield_to<P: dpp::shielded::builder::OrchardProver>(
pub async fn shielded_unshield_to<P: crate::wallet::shielded::ShieldedProver>(
&self,
coordinator: &Arc<crate::wallet::shielded::NetworkShieldedCoordinator>,
seed: &[u8],
Expand Down Expand Up @@ -1450,7 +1453,7 @@ impl PlatformWallet {
/// spent notes on top. `seed` supplies the transient spend authority (see
/// [`shielded_transfer_to`](Self::shielded_transfer_to)).
#[cfg(feature = "shielded")]
pub async fn shielded_identity_top_up_from_pool<P: dpp::shielded::builder::OrchardProver>(
pub async fn shielded_identity_top_up_from_pool<P: crate::wallet::shielded::ShieldedProver>(
&self,
coordinator: &Arc<crate::wallet::shielded::NetworkShieldedCoordinator>,
seed: &[u8],
Expand Down Expand Up @@ -1510,7 +1513,7 @@ impl PlatformWallet {
/// [`shielded_transfer_to`](Self::shielded_transfer_to)).
#[cfg(feature = "shielded")]
#[allow(clippy::too_many_arguments)]
pub async fn shielded_withdraw_to<P: dpp::shielded::builder::OrchardProver>(
pub async fn shielded_withdraw_to<P: crate::wallet::shielded::ShieldedProver>(
&self,
coordinator: &Arc<crate::wallet::shielded::NetworkShieldedCoordinator>,
seed: &[u8],
Expand Down Expand Up @@ -1584,7 +1587,7 @@ impl PlatformWallet {
prover: P,
) -> Result<dpp::prelude::Identifier, PlatformWalletError>
where
P: dpp::shielded::builder::OrchardProver,
P: crate::wallet::shielded::ShieldedProver,
IS: dpp::identity::signer::Signer<dpp::identity::IdentityPublicKey> + Send + Sync,
{
let (identity_id, identity) = {
Expand Down Expand Up @@ -1760,7 +1763,7 @@ impl PlatformWallet {
) -> Result<(), PlatformWalletError>
where
S: dpp::identity::signer::Signer<dpp::address_funds::PlatformAddress> + Send + Sync,
P: dpp::shielded::builder::OrchardProver,
P: crate::wallet::shielded::ShieldedProver,
{
self.shielded_shield_from_account_impl(
coordinator,
Expand Down Expand Up @@ -1811,7 +1814,7 @@ impl PlatformWallet {
) -> Result<(), PlatformWalletError>
where
S: dpp::identity::signer::Signer<dpp::address_funds::PlatformAddress> + Send + Sync,
P: dpp::shielded::builder::OrchardProver,
P: crate::wallet::shielded::ShieldedProver,
{
let recipient = Option::<grovedb_commitment_tree::PaymentAddress>::from(
grovedb_commitment_tree::PaymentAddress::from_raw_address_bytes(recipient_raw_43),
Expand Down Expand Up @@ -1851,7 +1854,7 @@ impl PlatformWallet {
) -> Result<(), PlatformWalletError>
where
S: dpp::identity::signer::Signer<dpp::address_funds::PlatformAddress> + Send + Sync,
P: dpp::shielded::builder::OrchardProver,
P: crate::wallet::shielded::ShieldedProver,
{
// Preserve the boundary behavior for non-Swift hosts and avoid taking
// the single-flight/account locks for a request that can never build.
Expand Down Expand Up @@ -1966,7 +1969,7 @@ impl PlatformWallet {
) -> Result<Credits, PlatformWalletError>
where
S: dpp::identity::signer::Signer<IdentityPublicKey> + Send + Sync,
P: dpp::shielded::builder::OrchardProver,
P: crate::wallet::shielded::ShieldedProver,
{
self.shielded_shield_from_identity_impl(
coordinator,
Expand Down Expand Up @@ -2001,7 +2004,7 @@ impl PlatformWallet {
) -> Result<Credits, PlatformWalletError>
where
S: dpp::identity::signer::Signer<IdentityPublicKey> + Send + Sync,
P: dpp::shielded::builder::OrchardProver,
P: crate::wallet::shielded::ShieldedProver,
{
let recipient = Option::<grovedb_commitment_tree::PaymentAddress>::from(
grovedb_commitment_tree::PaymentAddress::from_raw_address_bytes(recipient_raw_43),
Expand Down Expand Up @@ -2039,7 +2042,7 @@ impl PlatformWallet {
) -> Result<Credits, PlatformWalletError>
where
S: dpp::identity::signer::Signer<IdentityPublicKey> + Send + Sync,
P: dpp::shielded::builder::OrchardProver,
P: crate::wallet::shielded::ShieldedProver,
{
if amount == 0 {
return Err(PlatformWalletError::ShieldedBuildError(
Expand Down
5 changes: 3 additions & 2 deletions packages/rs-platform-wallet/src/wallet/shielded/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
//! [`FileBackedShieldedStore`] — storage abstraction; the
//! shared commitment tree lives here. Per-subwallet notes are
//! scoped by [`SubwalletId`] inside the store.
//! - [`CachedOrchardProver`] — lazy-init proving key cache.
//! - [`CachedOrchardProver`] — lazy-init proving key cache with a
//! shared, off-runtime async preparation ([`ShieldedProver`]).
//! - Sync / spend operations live as free functions in the
//! [`sync`] and [`operations`] submodules and take
//! `(sdk, store, persister, wallet_id, keys, …)` explicitly.
Expand Down Expand Up @@ -61,7 +62,7 @@ pub use balance::{
pub use coordinator::NetworkShieldedCoordinator;
pub use file_store::{FileBackedShieldedStore, FileShieldedStoreError};
pub use keys::{AccountViewingKeys, OrchardKeySet};
pub use prover::CachedOrchardProver;
pub use prover::{CachedOrchardProver, ReadyOrchardProver, ShieldedProver};
pub use seed_pool::{SeedPoolOutcome, SeedPoolProgress, DEFAULT_SEED_POOL_TARGET_NOTES};
pub use store::{
IdentityDebitRecoveryRecord, IdentityDebitRecoveryStatus, InMemoryShieldedStore, ShieldedNote,
Expand Down
Loading
Loading