Skip to content
Draft
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
16 changes: 16 additions & 0 deletions .github/workflows/rust-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,19 @@ jobs:
with:
command: clippy
args: --all --lib -- -D warnings -A deprecated -A unused-variables -A unused-imports

no-threads:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v3

- name: Install Rust toolchain
uses: ./.github/actions/install-rust-toolchain

- name: Check the no-threads feature graph
run: ./scripts/check-no-threads.sh

- name: Type-check the no-threads flavour for wasm32
working-directory: crates/webzjs-wallet
run: RUSTFLAGS="" cargo check --lib --target wasm32-unknown-unknown --no-default-features --features "wasm no-threads"
8 changes: 5 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,13 @@ tokio_with_wasm = { version = "0.7.1", features = ["rt", "rt-multi-thread", "syn
## `cargo update` can't silently move it. For local store work, swap it to `{ path = "../zcash_client_memory" }`.
zcash_keys = { version = "=0.17.0", features = ["transparent-inputs", "orchard", "sapling", "unstable"] }
zcash_client_backend = { version = "=0.25.0", default-features = false, features = ["sync", "lightwalletd-tonic", "orchard", "zeroize"] }
zcash_client_memory = { git = "https://github.com/red-dev-inc/zcash_client_memory", rev = "b4c8f0d33c65c5bab4155ddeba4f201ea2d28c43", features = ["orchard", "transparent-inputs"] }
zcash_primitives = { version = "=0.31.0" }
zcash_client_memory = { git = "https://github.com/red-dev-inc/zcash_client_memory", rev = "b4c8f0d33c65c5bab4155ddeba4f201ea2d28c43", default-features = false, features = ["orchard", "transparent-inputs"] }
## `multicore` (rayon) is off here and switched on per crate through each crate's own `multicore` feature,
## so a `no-threads` build does not get it back through feature unification.
zcash_primitives = { version = "=0.31.0", default-features = false, features = ["std", "circuits"] }
zcash_transparent = { version = "=0.11.0", default-features = false }
zcash_address = { version = "=0.14.0" }
zcash_proofs = { version = "=0.31.0", default-features = false, features = ["bundled-prover", "multicore"] }
zcash_proofs = { version = "=0.31.0", default-features = false, features = ["bundled-prover"] }
zip321 = { version = "=0.10.0" }
zip32 = { version = "0.3" }
zcash_protocol = { version = "=0.11.0", default-features = false }
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ This just script uses wasm-pack to build a web-ready copy of `webzjs-wallet` and
just build
```

#### Building without threads

`just build-wallet-single` builds `webzjs-wallet` into `packages/webzjs-wallet-single` with the `no-threads` feature. That build needs no
`SharedArrayBuffer`, so the page does not need the `Cross-Origin-Opener-Policy` / `Cross-Origin-Embedder-Policy` headers. `sync` and
`create_proposed_transactions` then run in the caller's context instead of a spawned worker, so host the `WebWallet` in your own dedicated
Worker to keep the page responsive. `just check-no-threads [file.wasm]` checks the feature graph and, given a built `.wasm`, that it has
no shared memory and no atomics. The default `just build` (`wasm wasm-parallel`) is unchanged. Note that `wasm` without `wasm-parallel` now behaves like `no-threads`: no `wasm_thread`, no `multicore`, and `sync` / `create_proposed_transactions` run in the caller's context (before, `wasm` alone still spawned `wasm_thread` workers). The generated package is named `@zcashcommunitygrants/webzjs-wallet-single` so both packages can live in the yarn workspace.

#### Prerequisites

[Install yarn](https://yarnpkg.com/getting-started/install)
Expand Down
4 changes: 4 additions & 0 deletions crates/webzjs-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ js-sys.workspace = true
pczt = { workspace = true, default-features = false, features = ["orchard", "sapling", "transparent"] }
serde-wasm-bindgen.workspace = true

[features]
default = ["multicore"]
# rayon-backed proving/scanning in zcash_primitives. Off in the `no-threads` wallet build.
multicore = ["zcash_primitives/multicore"]

[lints]
workspace = true
6 changes: 5 additions & 1 deletion crates/webzjs-keys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ crate-type = ["cdylib", "rlib"]
wasm-opt = ["-O4", "-O4"]

[dependencies]
webzjs-common = { path = "../webzjs-common" }
webzjs-common = { path = "../webzjs-common", default-features = false }

js-sys.workspace = true
thiserror.workspace = true
Expand Down Expand Up @@ -50,6 +50,10 @@ getrandom04.workspace = true
rand10.workspace = true

[features]
default = ["multicore"]
# rayon-backed proving/scanning in zcash_primitives. Off in the `no-threads` wallet build.
multicore = ["zcash_primitives/multicore", "webzjs-common/multicore"]

# Exposes `build_owned_demo_pczts` (src/demo_pczt.rs) — used only by the PoC demo
# to construct per-pool sample PCZTs attributable to a given UFVK. Pulls the
# transaction builders (`pczt/zcp-builder`) into the wasm build.
Expand Down
2 changes: 1 addition & 1 deletion crates/webzjs-requests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ wasm-bindgen.workspace = true
js-sys.workspace = true
zcash_protocol.workspace = true
zcash_address.workspace = true
zcash_primitives.workspace = true
zcash_primitives = { workspace = true, features = ["multicore"] }
zip321.workspace = true
thiserror.workspace = true
serde-wasm-bindgen.workspace = true
Expand Down
25 changes: 17 additions & 8 deletions crates/webzjs-wallet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,28 @@ wasm-opt = ["-O4", "-O4"]
[features]
default = ["native", "multicore"]

multicore = ["zcash_proofs/multicore", "zcash_primitives/multicore", "zcash_client_memory/multicore"]
multicore = [
"zcash_proofs/multicore",
"zcash_primitives/multicore",
"zcash_client_memory/multicore",
"webzjs-keys/multicore",
"webzjs-common/multicore",
]

# WASM specific features
wasm = ["console_error_panic_hook", "dep:tracing-web"]
wasm-parallel = ["wasm", "wasm-bindgen-rayon", "multicore"]
wasm-parallel = ["wasm", "wasm-bindgen-rayon", "dep:wasm_thread", "dep:rayon", "multicore"]
# Single-threaded wasm build: no SharedArrayBuffer, no wasm_thread, no rayon pool, so the page needs no
# COOP/COEP headers. Build with `just build-wallet-single`. Mutually exclusive with `wasm-parallel`.
no-threads = ["wasm"]
native = ["tonic/channel", "tonic/gzip", "tonic/tls-webpki-roots", "tokio/macros", "tokio/rt", "tokio/rt-multi-thread"]
sqlite-db = ["dep:zcash_client_sqlite"]
console_error_panic_hook = ["dep:console_error_panic_hook"]
no-bundler = ["wasm-bindgen-rayon?/no-bundler", "wasm_thread/no-bundler"]
no-bundler = ["wasm-bindgen-rayon?/no-bundler", "wasm_thread?/no-bundler"]

[dependencies]
webzjs-common = { path = "../webzjs-common" }
webzjs-keys = { path = "../webzjs-keys" }
webzjs-common = { path = "../webzjs-common", default-features = false }
webzjs-keys = { path = "../webzjs-keys", default-features = false }
## Web dependencies
wasm-bindgen.workspace = true
js-sys.workspace = true
Expand Down Expand Up @@ -60,7 +69,7 @@ zcash_client_memory = { workspace = true, features = ["orchard", "transparent-in
zcash_primitives = { workspace = true }
zcash_address = { workspace = true }
zcash_protocol = { workspace = true, default-features = false }
zcash_proofs = { workspace = true, default-features = false, features = ["bundled-prover", "multicore"] }
zcash_proofs = { workspace = true, default-features = false, features = ["bundled-prover"] }
zip321 = { workspace = true }
zip32 = { workspace = true }
pczt = { workspace = true, default-features = false, features = ["orchard", "sapling", "transparent"] }
Expand Down Expand Up @@ -89,12 +98,12 @@ nonempty = "0.11"
hex = "0.4.3"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
tracing = "0.1.40"
rayon = { version = "1.8", features = ["web_spin_lock"] }
rayon = { version = "1.8", features = ["web_spin_lock"], optional = true }
subtle = "2.6.1"
wasm_thread = { git = "https://github.com/ec2/wasm_thread", rev = "9e432077948d927d49373d1d039c23447d3648df", default-features = false, features = [
"keep_worker_alive",
"es_modules",
] }
], optional = true }

wasm_sync = "0.1.2"
http = { version = "1.1.0", default-features = false }
Expand Down
63 changes: 62 additions & 1 deletion crates/webzjs-wallet/src/bindgen/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::validation::validate_confirmations_policy;
use crate::wallet::usk_from_seed_str;
use crate::{bindgen::proposal::Proposal, Wallet, PRUNING_DEPTH};
use futures_util::TryStreamExt;
#[cfg(feature = "wasm-parallel")]
use wasm_thread as thread;
use webzjs_common::{Network, Pczt};
use webzjs_keys::{ProofGenerationKey, SeedFingerprint};
Expand Down Expand Up @@ -64,7 +65,7 @@ pub type NoteRef = <MemoryWalletDb<Network> as InputSource>::NoteRef;
/// The wallet can be synchronized with the blockchain by calling the `sync` method. This will fetch compact blocks from the connected lightwalletd instance and scan them for transactions.
/// The sync method uses a built-in strategy to determine which blocks is needs to download and scan in order to gain full knowledge of the balances for all accounts that are managed.
///
/// Syncing is a long running process and so is delegated to a WebWorker to prevent from blocking the main thread. It is safe to call other methods on the wallet during syncing although they may take
/// Syncing is a long running process. In the `wasm-parallel` build it is delegated to a WebWorker to prevent from blocking the main thread; in the `no-threads` build it runs in the caller's context, so host the wallet in your own Worker. It is safe to call other methods on the wallet during syncing although they may take
/// longer than usual while they wait for a write-lock to be released.
///
/// ```javascript
Expand Down Expand Up @@ -265,12 +266,30 @@ impl WebWallet {
.map(|id| *id)
}

///
/// Start a background sync task which will fetch and scan blocks from the connected lighwalletd server
///
/// IMPORTANT: This build has no threads, so no worker is spawned: the sync runs in the context of the caller
/// until it completes. Host the `WebWallet` in your own dedicated Worker to keep the page responsive.
/// Certain wallet methods may temporarily block while the wallet is being written to during the sync.
/// A panic during the sync cannot be caught as an `Error` in this build (the wasm module aborts); in the threaded build it is reported as `Error::Sync`.
///
#[cfg(not(feature = "wasm-parallel"))]
pub async fn sync(&self) -> Result<(), Error> {
self.inner.clone().sync().await.map_err(|e| {
let err_string = e.to_string();
tracing::warn!("Sync error (will be retried by caller): {}", err_string);
Error::Sync(err_string)
})
}

///
/// Start a background sync task which will fetch and scan blocks from the connected lighwalletd server
///
/// IMPORTANT: This will spawn a new webworker which will handle the sync task. The sync task will continue to run in the background until the sync process is complete.
/// During this time the main thread will not block but certain wallet methods may temporarily block while the wallet is being written to during the sync.
///
#[cfg(feature = "wasm-parallel")]
pub async fn sync(&self) -> Result<(), Error> {
assert!(!thread::is_web_worker_thread());

Expand Down Expand Up @@ -345,6 +364,47 @@ impl WebWallet {
Ok(proposal.into())
}

/// Generate a valid Zcash transaction from a given proposal
///
/// IMPORTANT: This build has no threads, so no worker is spawned: the proving task runs in the context of the caller and may take 10s of seconds.
/// Host the `WebWallet` in your own dedicated Worker to keep the page responsive.
///
/// # Arguments
///
/// * `proposal` - A proposal object generated by `propose_transfer`
/// * `seed_phrase` - 24 word mnemonic seed phrase. This MUST correspond to the accountID used when creating the proposal.
/// * `account_hd_index` - [ZIP32](https://zips.z.cash/zip-0032) hierarchical deterministic index of the account. This MUST correspond to the accountID used when creating the proposal.
///
/// # Returns
///
/// A list of transaction IDs which can be used to track the status of the transaction on the network.
/// It is returned in a flattened form where each ID is 32 bytes.
/// The transactions themselves are stored within the wallet.
///
/// # Examples
///
/// ```javascript
/// const proposal = await wallet.propose_transfer(1, "u18rakpts0de589sx9dkamcjms3apruqqax9k2s6e7zjxx9vv5kc67pks2trg9d3nrgd5acu8w8arzjjuepakjx38dyxl6ahd948w0mhdt9jxqsntan6px3ysz80s04a87pheg2mqvlzpehrgup7568nfd6ez23xd69ley7802dfvplnfn7c07vlyumcnfjul4pvv630ac336rjhjyak5", 100000000);
/// const authorized_txns = await wallet.create_proposed_transactions(proposal, "...", 1);
/// ```
#[cfg(not(feature = "wasm-parallel"))]
pub async fn create_proposed_transactions(
&self,
proposal: Proposal,
seed_phrase: &str,
account_hd_index: u32,
) -> Result<Vec<u8>, Error> {
let (usk, _) = usk_from_seed_str(seed_phrase, account_hd_index, &self.inner.network)?;
let db = self.inner.clone();

let txids = db
.create_proposed_transactions(proposal.into(), &usk)
.await?;

let flattened_txid_bytes = txids.iter().flat_map(|&x| x.as_ref().clone()).collect();
Ok(flattened_txid_bytes)
}

/// Generate a valid Zcash transaction from a given proposal
///
/// IMPORTANT: This will spawn a new webworker which will handle the proving task which may take 10s of seconds
Expand All @@ -367,6 +427,7 @@ impl WebWallet {
/// const proposal = await wallet.propose_transfer(1, "u18rakpts0de589sx9dkamcjms3apruqqax9k2s6e7zjxx9vv5kc67pks2trg9d3nrgd5acu8w8arzjjuepakjx38dyxl6ahd948w0mhdt9jxqsntan6px3ysz80s04a87pheg2mqvlzpehrgup7568nfd6ez23xd69ley7802dfvplnfn7c07vlyumcnfjul4pvv630ac336rjhjyak5", 100000000);
/// const authorized_txns = await wallet.create_proposed_transactions(proposal, "...", 1);
/// ```
#[cfg(feature = "wasm-parallel")]
pub async fn create_proposed_transactions(
&self,
proposal: Proposal,
Expand Down
3 changes: 3 additions & 0 deletions crates/webzjs-wallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@

//! This is the top level documentation!

#[cfg(all(feature = "no-threads", feature = "wasm-parallel"))]
compile_error!("features `no-threads` and `wasm-parallel` are mutually exclusive");

#[cfg(feature = "wasm")]
pub mod bindgen;

Expand Down
15 changes: 14 additions & 1 deletion justfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,21 @@ build-wallet *features:
cd crates/webzjs-wallet && wasm-pack build -t web --release --scope zcashcommunitygrants --out-dir ../../packages/webzjs-wallet --no-default-features --features="wasm wasm-parallel {{features}}" -Z build-std="panic_abort,std"
./add-worker-module.sh

# Single-threaded wallet: no SharedArrayBuffer, so the page needs no COOP/COEP headers.
# RUSTFLAGS="" overrides the atomics flags of .cargo/config.toml; no -Z build-std is needed.
# add-worker-module.sh is not run: there is no wasm_thread snippet in this flavour.
# The generated package is renamed to @zcashcommunitygrants/webzjs-wallet-single.
build-wallet-single *features:
cd crates/webzjs-wallet && RUSTFLAGS="" wasm-pack build -t web --release --scope zcashcommunitygrants --out-dir ../../packages/webzjs-wallet-single --no-default-features --features="wasm no-threads {{features}}"
# same crate name as the threaded package; yarn refuses two workspaces with one name
node -e "const f='packages/webzjs-wallet-single/package.json',p=JSON.parse(require('fs').readFileSync(f));p.name=p.name.replace(/(-single)?$/,'-single');require('fs').writeFileSync(f,JSON.stringify(p,null,2))"

# Checks the no-threads feature graph; pass a built .wasm to also check for shared memory and atomics.
check-no-threads *wasm:
./scripts/check-no-threads.sh {{wasm}}

build-keys *features:
cd crates/webzjs-keys && wasm-pack build -t web --release --scope zcashcommunitygrants --out-dir ../../packages/webzjs-keys --no-default-features --features="{{features}}" -Z build-std="panic_abort,std"
cd crates/webzjs-keys && wasm-pack build -t web --release --scope zcashcommunitygrants --out-dir ../../packages/webzjs-keys --no-default-features --features="multicore {{features}}" -Z build-std="panic_abort,std"

build-requests *features:
cd crates/webzjs-requests && wasm-pack build -t web --release --scope zcashcommunitygrants --out-dir ../../packages/webzjs-requests --no-default-features --features="{{features}}" -Z build-std="panic_abort,std"
Expand Down
38 changes: 38 additions & 0 deletions scripts/check-no-threads.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Checks that the `no-threads` flavour of webzjs-wallet needs no threads.
#
# scripts/check-no-threads.sh feature graph only (no build needed)
# scripts/check-no-threads.sh <file.wasm> also inspects a built wasm (needs `wasm-tools`)
#
# Graph: with `wasm no-threads`, wasm_thread and wasm-bindgen-rayon are not in the dependency graph and no
# crate enables a thread-pool feature (multicore, threads, web_spin_lock, rayon).
# (The rayon crate itself stays: zcash_client_backend depends on it unconditionally.)
# Wasm: validates with the threads proposal off (no shared memory, no atomic instructions), so the module
# needs no SharedArrayBuffer.
set -euo pipefail

wasm=""
[ "$#" -ge 1 ] && wasm=$(realpath "$1")
cd "$(dirname "$0")/../crates/webzjs-wallet"
fail=0
tree() { cargo tree ${CARGO_TREE_FLAGS:-} --target wasm32-unknown-unknown --no-default-features --features "${FEATURES:-wasm no-threads}" -e features "$@"; }

tree >/dev/null || { echo "FAIL: cannot resolve the graph with features '${FEATURES:-wasm no-threads}'"; exit 1; }

for pkg in wasm_thread wasm-bindgen-rayon; do
if tree -i "$pkg" >/dev/null 2>&1; then echo "FAIL: $pkg is in the no-threads graph"; fail=1; fi
done
# No crate may switch on a thread-pool feature (multicore, maybe-rayon/threads, rayon/web_spin_lock, ...).
bad=$(tree --prefix none | grep -E ' feature "(multicore|threads|web_spin_lock|rayon)"' | sort -u || true)
if [ -n "$bad" ]; then echo "FAIL: thread features enabled:"; echo "$bad"; fail=1; fi

if [ "$#" -ge 1 ]; then
command -v wasm-tools >/dev/null || { echo "FAIL: wasm-tools not installed"; exit 1; }
# With the threads proposal off, validation rejects shared memory and every atomic instruction (incl. atomic.fence).
if ! err=$(wasm-tools validate --features=-threads "$wasm" 2>&1); then
echo "FAIL: $wasm needs the wasm threads proposal (shared memory or atomics): $(head -n 3 <<<"$err" | tr '\n' ' ')"; fail=1
fi
fi

[ "$fail" -eq 0 ] && echo "OK: no-threads checks passed"
exit "$fail"