Skip to content
Open
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
614 changes: 392 additions & 222 deletions Cargo.lock

Large diffs are not rendered by default.

69 changes: 28 additions & 41 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ members = [
"crates/webzjs-requests",
"crates/webzjs-wallet",
]
# A path dependency inside the workspace directory would otherwise become a member.
exclude = ["vendor/tonic-web-wasm-client"]

[profile.release]
# Tell `rustc` to optimize for small code size.
Expand All @@ -30,32 +32,36 @@ console_error_panic_hook = { version = "0.1.7" }
tonic-web-wasm-client = "0.8.0"
tokio_with_wasm = { version = "0.7.1", features = ["rt", "rt-multi-thread", "sync", "macros", "time"] }

## Zcash dependencies - upstream librustzcash @ 0a2c6d1a (NU6.3 main, release-candidate versions;
## Nu6_3 = 0x37a5_165b, testnet activation 4,134,000, mainnet activation 3,428,143 — both finalized),
## redirected via [patch.crates-io]. zcash_client_memory = redbridge fork carrying ChainSafe's Snap patches.
## rc crates (pczt, client_backend, zip321, sqlite) keep the explicit -rc.1 so the pre-release matches.
zcash_keys = { version = "0.15.0", features = ["transparent-inputs", "orchard", "sapling", "unstable"] }
zcash_client_backend = { version = "0.24.0-rc.1", default-features = false, features = ["sync", "lightwalletd-tonic", "orchard"] }
zcash_client_memory = { git = "https://github.com/red-dev-inc/zcash_client_memory", branch = "feat/snap-nu63", features = ["orchard", "transparent-inputs"] }
zcash_primitives = { version = "0.29.0" }
zcash_transparent = { version = "0.9.0", default-features = false }
zcash_address = { version = "0.13.0" }
zcash_proofs = { version = "0.29.0", default-features = false, features = ["bundled-prover", "multicore"] }
zip321 = { version = "0.9.0-rc.1" }
zip32 = { version = "0.2" }
zcash_protocol = { version = "0.10.0", default-features = false }
pczt = { version = "0.8.0-rc.1", default-features = false, features = ["orchard", "sapling", "transparent"] }
sapling = { package = "sapling-crypto", version = "0.7", default-features = false }
bip32 = { version = "=0.6.0-pre.1", default-features = false, features = ["alloc"] }
## Zcash dependencies: librustzcash NU7 final stable crates from crates.io (pinned exactly). NU7
## activates on testnet at block 4,465,026 and on mainnet at block 3,543,405 (branch id 0x77190AD9).
## `zcash_client_memory` is our NU7 store (red-dev-inc `feat/snap-nu7`), pinned by exact revision so
## `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_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"] }
zip321 = { version = "=0.10.0" }
zip32 = { version = "0.3" }
zcash_protocol = { version = "=0.11.0", default-features = false }
pczt = { version = "=0.10.0", default-features = false, features = ["orchard", "sapling", "transparent"] }
sapling = { package = "sapling-crypto", version = "0.9", default-features = false }
bip32 = { version = "0.6", default-features = false, features = ["alloc"] }

## gRPC Web dependencies
prost = { version = "0.14", default-features = false }
tonic = { version = "0.14", default-features = false }


# Used in Native tests
zcash_client_sqlite = { version = "0.22.0-rc.1", default-features = false, features = ["unstable", "orchard"] }
zcash_client_sqlite = { version = "=0.23.0", default-features = false, features = ["unstable", "orchard"] }

getrandom = { version = "0.2", features = ["js"] }
# `rand 0.10` (pulled in by the zcash crates) uses getrandom 0.4, which needs its `wasm_js` backend on wasm32.
rand10 = { package = "rand", version = "0.10", default-features = false, features = ["std", "std_rng", "sys_rng", "thread_rng"] }
getrandom04 = { package = "getrandom", version = "0.4", features = ["wasm_js"] }
thiserror = "1.0.63"
indexed_db_futures = "0.5.0"
sha2 = "0.10"
Expand Down Expand Up @@ -84,29 +90,10 @@ tokio = { version = "1.0", features = ["rt", "macros"] }
byte-unit = { version = "5.1.4", features = ["byte"] }

[patch.crates-io]
# NU6.3: redirect the librustzcash family to upstream main rev 0a2c6d1a (release-candidate versions;
# carries Nu6_3 = 0x37a5_165b, testnet activation 4,134,000, mainnet activation 3,428,143 — both
# finalized, and the Ironwood wallet layer: Signer::sign_ironwood, Verifier::with_ironwood,
# IronwoodDomain scanning). This rev MUST match the rev pinned by the red-dev-inc/zcash_client_memory
# fork, or cargo builds two zcash_primitives -> trait mismatches.
#
# orchard: main patches orchard to the ZIP-374 deferred-anchor-builder branch (rev 3bd2b736, still
# version 0.15.0). We MUST mirror this exact patch, or our crates pull orchard 0.15.0 from crates.io
# while librustzcash pulls the git rev -> two `orchard` versions -> trait mismatch. Drop once it lands
# in an orchard release.
orchard = { git = "https://github.com/zcash/orchard.git", rev = "3bd2b736d1273226595773265313fc3f3428af16" }
equihash = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" }
zcash_address = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" }
zcash_client_backend = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" }
zcash_client_sqlite = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" }
zcash_encoding = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" }
zcash_keys = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" }
zcash_protocol = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" }
zip321 = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" }
zcash_primitives = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" }
zcash_proofs = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" }
pczt = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" }
zcash_transparent = { git = "https://github.com/zcash/librustzcash", rev = "0a2c6d1ae6274e6af2291e312f7b7459516882f2" }
# lightwalletd v0.5.4 (Zcash testnet) answers an empty stream with a trailers-only response, which
# tonic-web-wasm-client 0.8.0 rejects as `MalformedResponse`, so sync fails. See
# vendor/tonic-web-wasm-client/VENDORED.md. Remove once fixed upstream.
tonic-web-wasm-client = { path = "vendor/tonic-web-wasm-client" }

[workspace.lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(wasm_bindgen)', 'cfg(wasm_bindgen_unstable_test_coverage)'] }
8 changes: 5 additions & 3 deletions crates/webzjs-keys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,20 @@ pczt = { workspace = true, default-features = false, features = [
"transparent",
"tx-extractor",
] }
orchard = { version = "0.15", default-features = false }
orchard = { version = "0.16", default-features = false }
wasm-bindgen-futures = "0.4.43"
serde.workspace = true
serde-wasm-bindgen.workspace = true

# Demo-only: building sample PCZTs for the connected wallet's UFVK. Gated behind
# the `demo-builder` feature so they never bloat the production Snap WASM.
rand = { version = "0.8", optional = true }
secp256k1 = { version = "0.29", optional = true }
secp256k1 = { version = "0.33", optional = true }

# fixes "failed to resolve: use of undeclared crate or module `imp`" error
getrandom = { workspace = true, features = ["js"] }
getrandom04.workspace = true
rand10.workspace = true

[features]
# Exposes `build_owned_demo_pczts` (src/demo_pczt.rs) — used only by the PoC demo
Expand All @@ -72,7 +74,7 @@ pczt = { workspace = true, default-features = false, features = [
rand = "0.8"
# Transparent fixture construction (tests/gen_fixtures.rs) derives a P2PKH pubkey
# and spends it; `secp256k1` is already in the graph via `zcash_transparent`.
secp256k1 = "0.29"
secp256k1 = "0.33"

[lints]
workspace = true
6 changes: 6 additions & 0 deletions crates/webzjs-keys/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ pub enum Error {
Derivation(#[from] zcash_keys::keys::DerivationError),
#[error("Error attempting to decode key: {0}")]
KeyDecoding(String),
#[error("Error attempting to encode key: {0}")]
KeyEncoding(String),
#[error("Failed to sign Pczt: {0}")]
PcztSign(String),
#[error("Failed to describe Pczt: {0}")]
Expand All @@ -20,6 +22,10 @@ pub enum Error {
SeedFingerprint,
#[error("Failed to derive transparent address from UFVK")]
TransparentAddressDerivation,
#[error("Failed to derive unified address from UFVK")]
AddressDerivation,
#[error("BIP-39 error: {0}")]
Bip39(String),
}

impl From<Error> for JsValue {
Expand Down
103 changes: 100 additions & 3 deletions crates/webzjs-keys/src/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ impl UnifiedSpendingKey {

pub fn to_sapling_proof_generation_key(&self) -> ProofGenerationKey {
ProofGenerationKey {
inner: self.inner.sapling().expsk.proof_generation_key(),
inner: self.inner.sapling().expsk().proof_generation_key(),
}
}
}
Expand Down Expand Up @@ -146,7 +146,9 @@ impl UnifiedFullViewingKey {
///
pub fn encode(&self, network: &str) -> Result<String, Error> {
let network = Network::from_str(network)?;
Ok(self.inner.encode(&network))
self.inner
.encode(&network)
.map_err(|e| Error::KeyEncoding(e.to_string()))
}

/// Construct a UFVK from its encoded string representation
Expand All @@ -161,7 +163,7 @@ impl UnifiedFullViewingKey {
let network = Network::from_str(network)?;
Ok(Self {
inner: zcash_keys::keys::UnifiedFullViewingKey::decode(&network, encoding)
.map_err(Error::KeyDecoding)?,
.map_err(|e| Error::KeyDecoding(e.to_string()))?,
})
}

Expand All @@ -188,6 +190,17 @@ impl UnifiedFullViewingKey {
.transparent()
.map(|addr| zcash_keys::encoding::AddressCodec::encode(addr, &network)))
}

/// Default unified (shielded) address for this UFVK, encoded for `network`
/// ("main"/"test"). Destination for the v1 → v2 migration sweep.
pub fn get_unified_address(&self, network: &str) -> Result<String, Error> {
let network = Network::from_str(network)?;
let (ua, _) = self
.inner
.default_address(zcash_keys::keys::UnifiedAddressRequest::ALLOW_ALL)
.map_err(|_| Error::AddressDerivation)?;
Ok(ua.encode(&network))
}
}

impl UnifiedFullViewingKey {
Expand All @@ -211,3 +224,87 @@ pub fn generate_seed_phrase() -> String {
let mnemonic = <Mnemonic<English>>::generate(Count::Words24);
mnemonic.phrase().to_string()
}

/// Encode raw entropy as a standard BIP-39 mnemonic (portable v2 derivation):
/// 32 bytes → the user's exportable 24-word phrase. Deterministic.
#[wasm_bindgen]
pub fn mnemonic_from_entropy(entropy: Box<[u8]>) -> Result<String, Error> {
let mnemonic = <Mnemonic<English>>::from_entropy(entropy.into_vec())
.map_err(|e| Error::Bip39(e.to_string()))?;
Ok(mnemonic.phrase().to_string())
}

/// Derive the 64-byte BIP-39 seed from a mnemonic (portable v2), using an empty
/// passphrase so standard wallets reproduce the same account.
#[wasm_bindgen]
pub fn seed_from_mnemonic(phrase: &str) -> Result<Vec<u8>, Error> {
let mnemonic =
<Mnemonic<English>>::from_phrase(phrase).map_err(|e| Error::Bip39(e.to_string()))?;
Ok(mnemonic.to_seed("").to_vec())
}

#[cfg(test)]
mod portable_derivation_tests {
use super::*;

// Standard BIP-39 test vector: 32 bytes of 0x00 → this exact 24-word phrase.
// Confirms our encoding is standard (so other wallets reproduce the account).
const ALL_ZERO_PHRASE: &str = "abandon abandon abandon abandon abandon abandon abandon \
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
abandon abandon abandon abandon abandon abandon art";

#[test]
fn mnemonic_matches_standard_bip39_vector() {
let phrase = mnemonic_from_entropy(vec![0u8; 32].into_boxed_slice()).unwrap();
assert_eq!(phrase, ALL_ZERO_PHRASE);
}

#[test]
fn derivation_is_deterministic() {
let entropy = [7u8; 32];
let p1 = mnemonic_from_entropy(Box::new(entropy)).unwrap();
let p2 = mnemonic_from_entropy(Box::new(entropy)).unwrap();
assert_eq!(p1, p2, "same entropy must give the same phrase");

let s1 = seed_from_mnemonic(&p1).unwrap();
let s2 = seed_from_mnemonic(&p2).unwrap();
assert_eq!(s1, s2, "same phrase must give the same seed");
assert_eq!(s1.len(), 64, "BIP-39 seed is 64 bytes");
}

#[test]
fn roundtrip_entropy_to_portable_usk() {
// entropy -> mnemonic -> seed -> USK -> UFVK, twice, must match.
let entropy = [0x42u8; 32];
let ufvk = |e: [u8; 32]| {
let phrase = mnemonic_from_entropy(Box::new(e)).unwrap();
let seed = seed_from_mnemonic(&phrase).unwrap();
UnifiedSpendingKey::new("main", seed.into_boxed_slice(), 0)
.unwrap()
.to_unified_full_viewing_key()
.encode("main")
.unwrap()
};
assert_eq!(ufvk(entropy), ufvk(entropy), "portable UFVK must be stable");
}

#[test]
fn v2_portable_differs_from_v1_raw() {
// The whole point of the fix: routing the SAME 32 bytes through BIP-39 (v2)
// yields a DIFFERENT account than using them directly as a seed (v1, the bug).
let entropy = [0x99u8; 32];
let v1 = UnifiedSpendingKey::new("main", Box::new(entropy), 0)
.unwrap()
.to_unified_full_viewing_key()
.encode("main")
.unwrap();
let phrase = mnemonic_from_entropy(Box::new(entropy)).unwrap();
let seed = seed_from_mnemonic(&phrase).unwrap();
let v2 = UnifiedSpendingKey::new("main", seed.into_boxed_slice(), 0)
.unwrap()
.to_unified_full_viewing_key()
.encode("main")
.unwrap();
assert_ne!(v1, v2, "v2 must be a distinct (portable) account from v1");
}
}
50 changes: 43 additions & 7 deletions crates/webzjs-keys/src/pczt_describe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use wasm_bindgen::prelude::*;
use orchard::keys::{FullViewingKey as OrchardFvk, Scope};
use pczt::roles::verifier::Verifier;
use webzjs_common::{pool, MigrationSummary, Network, Pczt, PcztOutputSummary, PcztSummary};
use zcash_keys::address::UnifiedAddress;
use zcash_keys::address::{Address, UnifiedAddress};
use zcash_keys::encoding::AddressCodec;
use zcash_transparent::address::TransparentAddress;
use zcash_transparent::keys::AccountPubKey;
Expand Down Expand Up @@ -78,8 +78,9 @@ pub fn pczt_validate(
// crafted spoof PCZTs without a browser. See tests/spoof_pczt.rs.
// ---------------------------------------------------------------------------

/// ZIP-317 marginal fee per logical action, in zatoshis.
const MARGINAL_FEE: u64 = 5_000;
/// Lower-bound marginal fee per logical action, in zatoshis. Uses the ZIP 2009
/// (ZIP-317 Rev 2) value so this floor accepts both pre- and post-reduction fees.
const MARGINAL_FEE: u64 = 1_000;
/// ZIP-317 grace: the conventional fee covers at least this many logical actions.
const GRACE_ACTIONS: u64 = 2;
/// Defense-in-depth ceiling: a fee more than this multiple of the ZIP-317
Expand Down Expand Up @@ -190,12 +191,45 @@ pub fn pczt_validate_inner(

/// Encode an Orchard receiver as a Unified Address string for display.
fn encode_orchard(network: &Network, addr: &orchard::Address) -> Option<String> {
UnifiedAddress::from_receivers(Some(*addr), None, None).map(|ua| ua.encode(network))
UnifiedAddress::from_receivers(Some(*addr), None, None, None, None).map(|ua| ua.encode(network))
}

/// Encode a Sapling receiver as a Unified Address string for display.
fn encode_sapling(network: &Network, addr: &sapling::PaymentAddress) -> Option<String> {
UnifiedAddress::from_receivers(None, Some(*addr), None).map(|ua| ua.encode(network))
UnifiedAddress::from_receivers(None, Some(*addr), None, None, None).map(|ua| ua.encode(network))
}

/// Decode a claimed recipient address into its per-pool receiver encodings, matching
/// exactly how `pczt_describe` encodes output recipients. Lets the signing dialog verify
/// the site's claimed recipient against the PCZT's real outputs instead of trusting a
/// plain string. Returns a JSON object `{orchard, sapling, transparent}` (null if absent).
#[wasm_bindgen]
pub fn decode_address_receivers(network: &str, address: &str) -> Result<String, Error> {
let net = Network::from_str(network)?;
let addr = Address::decode(&net, address)
.ok_or_else(|| Error::KeyDecoding("could not decode recipient address".into()))?;
let (orchard, sapling, transparent) = match addr {
Address::Unified(ua) => (
ua.orchard().and_then(|a| encode_orchard(&net, a)),
ua.sapling().and_then(|a| encode_sapling(&net, a)),
ua.transparent().map(|a| a.encode(&net)),
),
Address::Sapling(a) => (None, encode_sapling(&net, &a), None),
Address::Transparent(a) => (None, None, Some(a.encode(&net))),
_ => (None, None, None),
};
// Address encodings are bech32m/base58 (no quotes or backslashes), so direct
// interpolation is safe.
let field = |v: &Option<String>| match v {
Some(s) => format!("\"{s}\""),
None => "null".to_string(),
};
Ok(format!(
"{{\"orchard\":{},\"sapling\":{},\"transparent\":{}}}",
field(&orchard),
field(&sapling),
field(&transparent),
))
}

/// True iff this Orchard spend is recoverable under `ofvk`.
Expand Down Expand Up @@ -414,7 +448,7 @@ fn analyze(
let ofvk = ufvk.orchard();
let sdfvk = ufvk.sapling();
let sfvk = sdfvk.map(|dfvk| dfvk.fvk());
let tfvk = ufvk.transparent();
let tfvk = ufvk.p2pkh();

let mut outputs: Vec<PcztOutputSummary> = Vec::new();
let mut total_in: u64 = 0;
Expand Down Expand Up @@ -598,7 +632,9 @@ fn analyze(
// `is_change` here already means "pays one of our transparent
// keys", i.e. ours.
is_ours: is_change,
verified: true,
// Unrecoverable (non-standard) script has no displayable recipient,
// so mark it unverified for pczt_validate_inner to refuse.
verified: addr.is_some(),
});
}
Ok(())
Expand Down
Loading
Loading