From d5f1a4fd88af5f89fb540357c704ba1c2cbdcf6d Mon Sep 17 00:00:00 2001 From: aratrika Date: Wed, 4 Nov 2026 17:34:58 -0500 Subject: [PATCH 1/8] Port WebZjs to the NU7 crates; derive the change pool from the active upgrade --- Cargo.lock | 557 ++++++++++++------ Cargo.toml | 65 +- crates/webzjs-keys/Cargo.toml | 8 +- crates/webzjs-keys/src/error.rs | 2 + crates/webzjs-keys/src/keys.rs | 8 +- crates/webzjs-keys/src/pczt_describe.rs | 6 +- crates/webzjs-keys/src/pczt_sign.rs | 4 +- crates/webzjs-keys/tests/gen_fixtures.rs | 4 +- crates/webzjs-keys/tests/spoof_pczt.rs | 4 +- crates/webzjs-requests/Cargo.toml | 1 + crates/webzjs-wallet/Cargo.toml | 4 +- .../src/bindgen/transaction_history.rs | 18 +- crates/webzjs-wallet/src/bindgen/wallet.rs | 4 +- crates/webzjs-wallet/src/chain_params.rs | 135 +++++ crates/webzjs-wallet/src/lib.rs | 1 + crates/webzjs-wallet/src/wallet.rs | 116 ++-- 16 files changed, 655 insertions(+), 282 deletions(-) create mode 100644 crates/webzjs-wallet/src/chain_params.rs diff --git a/Cargo.lock b/Cargo.lock index a4e15ff..dc91b55 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14,6 +14,17 @@ dependencies = [ "syn", ] +[[package]] +name = "addchain" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5665045de74fda906c0abfaec40cf2551f88c34dccea869f3fe950dde7209764" +dependencies = [ + "num-bigint 0.4.6", + "num-integer", + "num-traits", +] + [[package]] name = "adler2" version = "2.0.1" @@ -22,23 +33,23 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "aead" -version = "0.5.2" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" dependencies = [ - "crypto-common 0.1.7", - "generic-array", + "crypto-common 0.2.2", + "inout", ] [[package]] name = "aes" -version = "0.8.4" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32" dependencies = [ - "cfg-if", "cipher", - "cpufeatures", + "cpubits", + "cpufeatures 0.3.1", ] [[package]] @@ -233,9 +244,9 @@ checksum = "32637268377fc7b10a8c6d51de3e7fba1ce5dd371a96e342b34e6078db558e7f" [[package]] name = "bellman" -version = "0.14.0" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9afceed28bac7f9f5a508bca8aeeff51cdfa4770c0b967ac55c621e2ddfd6171" +checksum = "973b16549796a1274a63e00159a03250e66e8263e2ac6344b1c9fdfe9b7a8325" dependencies = [ "bitvec", "blake2s_simd", @@ -243,11 +254,9 @@ dependencies = [ "crossbeam-channel", "ff", "group", - "lazy_static", "log", "num_cpus", - "pairing", - "rand_core", + "rand_core 0.10.1", "rayon", "subtle", ] @@ -260,7 +269,7 @@ checksum = "568b6890865156d9043af490d4c4081c385dd68ea10acd6ca15733d511e6b51c" dependencies = [ "hmac 0.12.1", "pbkdf2", - "rand", + "rand 0.8.5", "sha2 0.10.9", "unicode-normalization", "zeroize", @@ -268,16 +277,15 @@ dependencies = [ [[package]] name = "bip32" -version = "0.6.0-pre.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "143f5327f23168716be068f8e1014ba2ea16a6c91e8777bc8927da7b51e1df1f" +checksum = "0271a2fe2a6f05231419e878b5f50152a5a6dbcc60c18855d924892ecc85a33a" dependencies = [ "bs58", - "hmac 0.13.0-pre.4", - "rand_core", - "ripemd 0.2.0-pre.4", + "hmac 0.13.0", + "ripemd 0.2.0", "secp256k1", - "sha2 0.11.0-pre.4", + "sha2 0.11.1", "subtle", "zeroize", ] @@ -333,9 +341,9 @@ dependencies = [ [[package]] name = "block-buffer" -version = "0.11.0-rc.3" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fd016a0ddc7cb13661bf5576073ce07330a693f8608a1320b4e20561cc12cdc" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" dependencies = [ "hybrid-array", ] @@ -355,15 +363,16 @@ dependencies = [ [[package]] name = "bls12_381" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7bc6d6292be3a19e6379786dac800f551e5865a5bb51ebbe3064ab80433f403" +checksum = "18f887f26229478dcd0e0d063566b51c68fb55a38fba21799c5f3371a74ec61f" dependencies = [ "ff", "group", "pairing", - "rand_core", + "rand_core 0.10.1", "subtle", + "zeroize", ] [[package]] @@ -405,9 +414,9 @@ checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3" [[package]] name = "cbc" -version = "0.1.2" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" dependencies = [ "cipher", ] @@ -430,26 +439,26 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "chacha20" -version = "0.9.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", "cipher", - "cpufeatures", + "cpufeatures 0.3.1", + "rand_core 0.10.1", ] [[package]] name = "chacha20poly1305" -version = "0.10.1" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb" dependencies = [ "aead", "chacha20", "cipher", "poly1305", - "zeroize", ] [[package]] @@ -464,15 +473,21 @@ dependencies = [ [[package]] name = "cipher" -version = "0.4.4" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ - "crypto-common 0.1.7", + "block-buffer 0.12.1", + "crypto-common 0.2.2", "inout", - "zeroize", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "cobs" version = "0.3.0" @@ -513,6 +528,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4df6f98652d30167eaeea34d77b730e07c8caba6df17bd4551842b9b8da01deb" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -522,6 +543,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.0" @@ -589,13 +619,22 @@ dependencies = [ [[package]] name = "crypto-common" -version = "0.2.0-rc.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0b8ce8218c97789f16356e7896b3714f26c2ee1079b79c0b7ae7064bb9089fa" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ "hybrid-array", ] +[[package]] +name = "ctutils" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +dependencies = [ + "cmov", +] + [[package]] name = "daggy" version = "0.8.1" @@ -674,13 +713,13 @@ dependencies = [ [[package]] name = "digest" -version = "0.11.0-pre.9" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf2e3d6615d99707295a9673e889bf363a04b2a466bd320c65a72536f7577379" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer 0.11.0-rc.3", - "crypto-common 0.2.0-rc.1", - "subtle", + "block-buffer 0.12.1", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -719,7 +758,8 @@ checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" [[package]] name = "equihash" version = "0.3.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "306286e8dcc39ab3dfceb74c792ce8baffdab90591321d3ffaae64829734c37f" dependencies = [ "blake2b_simd", "corez", @@ -770,8 +810,9 @@ dependencies = [ [[package]] name = "f4jumble" -version = "0.1.1" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cae5503f6dc8629246d7e9b3450d3712e5be20f2ed7f9fb6b67212a4f315adc" dependencies = [ "blake2b_simd", ] @@ -808,15 +849,31 @@ checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "ff" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" dependencies = [ "bitvec", - "rand_core", + "ff_derive", + "rand_core 0.10.1", "subtle", ] +[[package]] +name = "ff_derive" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241afe8c15ffa21933eaefe8a563af36fd9fc98a3e8a044e8f7db52eb1fae3d8" +dependencies = [ + "addchain", + "num-bigint 0.4.6", + "num-integer", + "num-traits", + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -865,14 +922,14 @@ checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" [[package]] name = "fpe" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26c4b37de5ae15812a764c958297cfc50f5c010438f60c6ce75d11b802abd404" +checksum = "5045d51a6a5e85e0a18d909eedd270c4d82ad634fee57ba707692fb3b1add5a7" dependencies = [ "cbc", "cipher", "libm", - "num-bigint", + "num-bigint 0.5.1", "num-integer", "num-traits", ] @@ -1016,10 +1073,24 @@ checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", "libc", - "r-efi", + "r-efi 5.3.0", "wasip2", ] +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + [[package]] name = "getset" version = "0.1.6" @@ -1044,15 +1115,31 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "groth16" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bb1e0bde2dbacd81474ae216c5dd4901307bd1c75fd26ed49590e88048c8442" +dependencies = [ + "bellman", + "byteorder", + "ff", + "group", + "pairing", + "rand 0.10.3", + "rand_core 0.10.1", + "rayon", +] + [[package]] name = "group" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" dependencies = [ "ff", "memuse", - "rand_core", + "rand_core 0.10.1", "subtle", ] @@ -1077,9 +1164,9 @@ dependencies = [ [[package]] name = "halo2_gadgets" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb2a697cad929f706b7987fe804ad57d43622cd37463ba7e4d662a926fdcfea3" +checksum = "8862c7f2d99964760016516103fcc621352e77a505b22b0fc25140f09e4b8bb0" dependencies = [ "arrayvec", "bitvec", @@ -1087,9 +1174,8 @@ dependencies = [ "group", "halo2_poseidon", "halo2_proofs", - "lazy_static", "pasta_curves", - "rand", + "rand 0.10.3", "sinsemilla", "subtle", "uint", @@ -1103,9 +1189,9 @@ checksum = "47716fe1ae67969c5e0b2ef826f32db8c3be72be325e1aa3c1951d06b5575ec5" [[package]] name = "halo2_poseidon" -version = "0.1.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa3da60b81f02f9b33ebc6252d766f843291fb4d2247a07ae73d20b791fc56f" +checksum = "800f76fa421515e2729192e3863bb0a58f30fe17a9a165ea5e778a157adeb579" dependencies = [ "bitvec", "ff", @@ -1115,18 +1201,19 @@ dependencies = [ [[package]] name = "halo2_proofs" -version = "0.3.2" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05713f117155643ce10975e0bee44a274bcda2f4bb5ef29a999ad67c1fa8d4d3" +checksum = "f5af2a9457f494f862cd07b81c2e98a19f50b06a2057b7569450d7c26b167d1c" dependencies = [ "blake2b_simd", "ff", "group", "halo2_legacy_pdqsort", - "indexmap 1.9.3", + "indexmap 2.13.0", "maybe-rayon", "pasta_curves", - "rand_core", + "rand 0.10.3", + "rand_core 0.10.1", "tracing", ] @@ -1212,11 +1299,11 @@ dependencies = [ [[package]] name = "hmac" -version = "0.13.0-pre.4" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4b1fb14e4df79f9406b434b60acef9f45c26c50062cccf1346c6103b8c47d58" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ - "digest 0.11.0-pre.9", + "digest 0.11.3", ] [[package]] @@ -1260,9 +1347,9 @@ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] name = "hybrid-array" -version = "0.2.3" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2d35805454dc9f8662a98d6d61886ffe26bd465f5960e0e55345c70d5c0d2a9" +checksum = "3944cf8cf766b40e2a1a333ee5e9b563f854d5fa49d6a8ca2764e97c6eddb214" dependencies = [ "typenum", ] @@ -1331,9 +1418,9 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "incrementalmerkletree" -version = "0.8.2" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30821f91f0fa8660edca547918dc59812893b497d07c1144f326f07fdd94aba9" +checksum = "c3b0c166f7f34e02988f84a7bed22be9707b1569acc6aeb3afaf34152d0e0400" dependencies = [ "either", ] @@ -1377,11 +1464,11 @@ dependencies = [ [[package]] name = "inout" -version = "0.1.4" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" dependencies = [ - "generic-array", + "hybrid-array", ] [[package]] @@ -1411,16 +1498,17 @@ dependencies = [ [[package]] name = "jubjub" -version = "0.10.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8499f7a74008aafbecb2a2e608a3e13e4dd3e84df198b604451efe93f2de6e61" +checksum = "95fdd9a071f72385ed8b17d819f273d73c3887a93d34d2ac1419fca5b25dbbd2" dependencies = [ "bitvec", "bls12_381", "ff", "group", - "rand_core", + "rand_core 0.10.1", "subtle", + "zeroize", ] [[package]] @@ -1649,6 +1737,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-conv" version = "0.1.0" @@ -1690,16 +1788,11 @@ version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - [[package]] name = "orchard" -version = "0.15.0" -source = "git+https://github.com/zcash/orchard.git?rev=3bd2b736d1273226595773265313fc3f3428af16#3bd2b736d1273226595773265313fc3f3428af16" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae7ceb7b5387bd76cf3c0712f57708795c925cecf097036cedb60b5c3706e8f" dependencies = [ "aes", "bitvec", @@ -1718,8 +1811,8 @@ dependencies = [ "memuse", "nonempty", "pasta_curves", - "rand", - "rand_core", + "rand 0.10.3", + "rand_core 0.10.1", "reddsa", "serde", "sinsemilla", @@ -1728,14 +1821,15 @@ dependencies = [ "visibility", "zcash_note_encryption", "zcash_spec", + "zeroize", "zip32", ] [[package]] name = "pairing" -version = "0.23.0" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81fec4625e73cf41ef4bb6846cafa6d44736525f442ba45e407c4a000a13996f" +checksum = "33f6413397336802d16a342e69a5bd9c8b8cc2fa9fc9298044cd3443f77f1010" dependencies = [ "group", ] @@ -1753,25 +1847,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" dependencies = [ "base64ct", - "rand_core", + "rand_core 0.6.4", "subtle", ] [[package]] name = "pasta_curves" -version = "0.5.1" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3e57598f73cc7e1b2ac63c79c517b31a0877cd7c402cdcaa311b5208de7a095" +checksum = "a0ed53ba43531a06e1f82020907cf192fc3c25d7c0baf5c49c547b74e7103b62" dependencies = [ "blake2b_simd", "ff", "group", "lazy_static", - "rand", + "rand 0.10.3", "static_assertions", "subtle", + "zeroize", ] +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pbkdf2" version = "0.12.2" @@ -1784,12 +1885,12 @@ dependencies = [ [[package]] name = "pczt" -version = "0.8.0-rc.1" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +version = "0.10.0-pre.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbb353f91d5caf22e351cc75e6c531b2a74b7cfbef5274c6ce7d1859a0ab30b4" dependencies = [ "blake2b_simd", "bls12_381", - "document-features", "ff", "getset", "jubjub", @@ -1797,17 +1898,19 @@ dependencies = [ "orchard", "pasta_curves", "postcard", - "rand_core", + "rand_core 0.10.1", "redjubjub", "sapling-crypto", "secp256k1", "serde", "serde_with", + "subtle", "zcash_note_encryption", "zcash_primitives", "zcash_protocol", "zcash_script", "zcash_transparent", + "zeroize", ] [[package]] @@ -1902,12 +2005,11 @@ dependencies = [ [[package]] name = "poly1305" -version = "0.8.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c" dependencies = [ - "cpufeatures", - "opaque-debug", + "cpufeatures 0.3.1", "universal-hash", ] @@ -2046,6 +2148,12 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + [[package]] name = "radium" version = "0.7.0" @@ -2059,8 +2167,29 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", - "rand_chacha", - "rand_core", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] @@ -2070,7 +2199,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", ] [[package]] @@ -2082,14 +2221,29 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "rand_distr" -version = "0.4.3" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" +checksum = "4d431c2703ccf129de4d45253c03f49ebb22b97d6ad79ee3ecfc7e3f4862c1d8" dependencies = [ "num-traits", - "rand", + "rand 0.10.3", ] [[package]] @@ -2116,9 +2270,9 @@ dependencies = [ [[package]] name = "reddsa" -version = "0.5.1" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78a5191930e84973293aa5f532b513404460cd2216c1cfb76d08748c15b40b02" +checksum = "4a70b6dbd7b3277cbd4d89ee750a30bebab3b9951ee4e166ce15c00975fe410f" dependencies = [ "blake2b_simd", "byteorder", @@ -2126,21 +2280,21 @@ dependencies = [ "hex", "jubjub", "pasta_curves", - "rand_core", + "rand_core 0.10.1", "serde", - "thiserror 1.0.69", + "thiserror 2.0.18", "zeroize", ] [[package]] name = "redjubjub" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89b0ac1bc6bb3696d2c6f52cff8fba57238b81da8c0214ee6cd146eb8fde364e" +checksum = "19ff57b3369b472353110bea305ced2612a1380e2d2079dd26c200ed42064421" dependencies = [ - "rand_core", + "rand_core 0.10.1", "reddsa", - "thiserror 1.0.69", + "thiserror 2.0.18", "zeroize", ] @@ -2198,11 +2352,11 @@ dependencies = [ [[package]] name = "ripemd" -version = "0.2.0-pre.4" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e48cf93482ea998ad1302c42739bc73ab3adc574890c373ec89710e219357579" +checksum = "4dd4211456b4172d7e44261920c25acf07367c4f04bb5f5d54fc21b090d9b159" dependencies = [ - "digest 0.11.0-pre.9", + "digest 0.11.3", ] [[package]] @@ -2285,9 +2439,9 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "sapling-crypto" -version = "0.7.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d70756ede56b5e4dd417979777bd87ddb83dfcbd0815dbf8175a9920537f8a0" +checksum = "4a2cbdcfeef20006adf72699cd466f21fe349674277cc05d3fc9b7302db7b182" dependencies = [ "aes", "bellman", @@ -2300,19 +2454,21 @@ dependencies = [ "ff", "fpe", "getset", + "groth16", "group", "hex", "incrementalmerkletree", "jubjub", "lazy_static", "memuse", - "rand", - "rand_core", + "rand 0.10.3", + "rand_core 0.10.1", "redjubjub", "subtle", "tracing", "zcash_note_encryption", "zcash_spec", + "zeroize", "zip32", ] @@ -2348,18 +2504,19 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "secp256k1" -version = "0.29.1" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9465315bc9d4566e1724f0fffcbcc446268cb522e60f9a27bcded6b19c108113" +checksum = "d7f404a8dab7a7a5a631e741d8699aa9c8e1d689fc26ccf897c7187565490b69" dependencies = [ + "rand 0.9.5", "secp256k1-sys", ] [[package]] name = "secp256k1-sys" -version = "0.10.1" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" +checksum = "f6b2992d4a3cd244539a7d5d0966aadbe5ca7fb868a5d7e38c29499b9e709bbd" dependencies = [ "cc", ] @@ -2467,7 +2624,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest 0.10.7", ] @@ -2478,19 +2635,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest 0.10.7", ] [[package]] name = "sha2" -version = "0.11.0-pre.4" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "540c0893cce56cdbcfebcec191ec8e0f470dd1889b6e7a0b503e310a94a168f5" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", - "cpufeatures", - "digest 0.11.0-pre.9", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -2504,9 +2661,9 @@ dependencies = [ [[package]] name = "shardtree" -version = "0.7.1" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8147447aed7be4736e271825b8c3a4432efb7182e71363169b572371ddef452e" +checksum = "211c5ae6ff1fda9efe2cd8b90737744b3b3989f98740319284946bf110b862ed" dependencies = [ "bitflags", "either", @@ -2528,9 +2685,9 @@ checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" [[package]] name = "sinsemilla" -version = "0.1.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d268ae0ea06faafe1662e9967cd4f9022014f5eeb798e0c302c876df8b7af9c" +checksum = "72744738b764bb3bb7bb5dcf71b62d19c2de8a09f850a7388f6088f244037299" dependencies = [ "group", "pasta_curves", @@ -3047,12 +3204,12 @@ dependencies = [ [[package]] name = "universal-hash" -version = "0.5.1" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" dependencies = [ - "crypto-common 0.1.7", - "subtle", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -3343,10 +3500,12 @@ dependencies = [ "bip0039", "bip32", "getrandom 0.2.17", + "getrandom 0.4.3", "js-sys", "orchard", "pczt", - "rand", + "rand 0.10.3", + "rand 0.8.5", "sapling-crypto", "secp256k1", "serde", @@ -3367,6 +3526,7 @@ name = "webzjs-requests" version = "0.1.0" dependencies = [ "getrandom 0.2.17", + "getrandom 0.4.3", "js-sys", "serde-wasm-bindgen", "thiserror 1.0.69", @@ -3386,6 +3546,7 @@ dependencies = [ "console_error_panic_hook", "futures-util", "getrandom 0.2.17", + "getrandom 0.4.3", "hex", "http", "indexed_db_futures", @@ -3395,6 +3556,7 @@ dependencies = [ "pczt", "postcard", "prost", + "rand 0.10.3", "rayon", "ripemd 0.1.3", "sapling-crypto", @@ -3628,8 +3790,9 @@ dependencies = [ [[package]] name = "zcash_address" -version = "0.13.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +version = "0.14.0-pre.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db56348a60fb82895c37475a4a3a39e9eaf47bc4267c05cad42f83b0771b18c8" dependencies = [ "bech32", "bs58", @@ -3641,8 +3804,9 @@ dependencies = [ [[package]] name = "zcash_client_backend" -version = "0.24.0-rc.1" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +version = "0.25.0-pre.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "081a6a497f0016a4de2ef9f45cbca6d271037035f5e7614b2c16363f8c3b4a84" dependencies = [ "async-trait", "base64", @@ -3667,7 +3831,7 @@ dependencies = [ "percent-encoding", "postcard", "prost", - "rand_core", + "rand_core 0.10.1", "rayon", "sapling-crypto", "secp256k1", @@ -3696,13 +3860,13 @@ dependencies = [ [[package]] name = "zcash_client_memory" version = "0.0.0" -source = "git+https://github.com/red-dev-inc/zcash_client_memory?branch=feat%2Fsnap-nu63#1feb38d92d214ec65d410a01c0f9da42b787f76b" dependencies = [ "async-trait", "bip32", "bs58", "byteorder", "bytes", + "getrandom 0.4.3", "group", "incrementalmerkletree", "jubjub", @@ -3737,8 +3901,9 @@ dependencies = [ [[package]] name = "zcash_client_sqlite" -version = "0.22.0-rc.1" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +version = "0.23.0-pre.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e59202fe720b383d4340318785add4ae1870c82cd950159758d96f4f875c0fbd" dependencies = [ "bitflags", "bs58", @@ -3751,9 +3916,11 @@ dependencies = [ "maybe-rayon", "nonempty", "orchard", + "pastey", + "pczt", "prost", - "rand", - "rand_core", + "rand 0.10.3", + "rand_core 0.10.1", "rand_distr", "regex", "rusqlite", @@ -3771,6 +3938,7 @@ dependencies = [ "zcash_client_backend", "zcash_encoding", "zcash_keys", + "zcash_pool_migration", "zcash_primitives", "zcash_protocol", "zcash_script", @@ -3780,8 +3948,9 @@ dependencies = [ [[package]] name = "zcash_encoding" -version = "0.4.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2871fd3c37eaeb635c815a9c97495553bf8237a481b9f8b37eba661764bf937" dependencies = [ "corez", "hex", @@ -3790,8 +3959,9 @@ dependencies = [ [[package]] name = "zcash_keys" -version = "0.15.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +version = "0.17.0-pre.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96e6eaf9ae82ea0e40aadd35df0778f37125fb3405a25e2b1f0d6b45a9884e14" dependencies = [ "bech32", "bip32", @@ -3805,7 +3975,7 @@ dependencies = [ "memuse", "nonempty", "orchard", - "rand_core", + "rand_core 0.10.1", "sapling-crypto", "secrecy", "subtle", @@ -3819,26 +3989,47 @@ dependencies = [ [[package]] name = "zcash_note_encryption" -version = "0.4.1" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77efec759c3798b6e4d829fcc762070d9b229b0f13338c40bf993b7b609c2272" +checksum = "4812d133908ebf1a1c91d2411a109f63a863a152633db1fc7fbb0f774edeae30" dependencies = [ "chacha20", "chacha20poly1305", "cipher", - "rand_core", + "rand_core 0.10.1", "subtle", ] +[[package]] +name = "zcash_pool_migration" +version = "0.2.0-pre.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02dba1fbb3fa84188fa248f5b282e9226434f1608b48d0f1f3139f269d0c7cd2" +dependencies = [ + "blake2b_simd", + "corez", + "getset", + "incrementalmerkletree", + "libm", + "orchard", + "pczt", + "rand_core 0.10.1", + "shardtree", + "zcash_client_backend", + "zcash_keys", + "zcash_primitives", + "zcash_protocol", + "zip32", +] + [[package]] name = "zcash_primitives" -version = "0.29.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +version = "0.31.0-pre.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0329bee4107df1aaaaaab365bdf94fcc0d9a185165c4675dff2397c5af7d13f4" dependencies = [ "blake2b_simd", - "block-buffer 0.11.0-rc.3", "corez", - "crypto-common 0.2.0-rc.1", "document-features", "equihash", "ff", @@ -3848,7 +4039,7 @@ dependencies = [ "memuse", "nonempty", "orchard", - "rand_core", + "rand_core 0.10.1", "redjubjub", "sapling-crypto", "secp256k1", @@ -3862,16 +4053,18 @@ dependencies = [ [[package]] name = "zcash_proofs" -version = "0.29.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +version = "0.31.0-pre.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cc30f2c394b8558269a13f5c9b4188eae7b9b5b659afdc60d1c6fcd861d2311" dependencies = [ "bellman", "blake2b_simd", "bls12_381", "document-features", + "groth16", "group", "jubjub", - "rand_core", + "rand_core 0.10.1", "redjubjub", "sapling-crypto", "tracing", @@ -3881,8 +4074,9 @@ dependencies = [ [[package]] name = "zcash_protocol" -version = "0.10.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +version = "0.11.0-pre.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98aeb25d9f741670fd63f9dbf76bca87d87c4fd32e1a7469bc4c43c4d0af09f7" dependencies = [ "corez", "document-features", @@ -3893,9 +4087,9 @@ dependencies = [ [[package]] name = "zcash_script" -version = "0.4.5" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f872800287d118be71bdf6fe8c869c6a6ff6fb0a5762f68fb2af54c97edf0f2" +checksum = "10106859d08a2a4119af8a0fa8db72afe35647768b562f94b7a2124adad41275" dependencies = [ "bip32", "bitflags", @@ -3919,8 +4113,9 @@ dependencies = [ [[package]] name = "zcash_transparent" -version = "0.9.0" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +version = "0.11.0-pre.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3b7dfde65266233ad2babba2f115d41a786e0270cac1a4644e26b9992dcf375" dependencies = [ "bip32", "bs58", @@ -3983,21 +4178,23 @@ dependencies = [ [[package]] name = "zip32" -version = "0.2.1" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b64bf5186a8916f7a48f2a98ef599bf9c099e2458b36b819e393db1c0e768c4b" +checksum = "601ab4bc5f8312fa39f5411e07eb66b538687064c6e936b34eaa78f1e99ebe4d" dependencies = [ "bech32", "blake2b_simd", "memuse", "subtle", "zcash_spec", + "zeroize", ] [[package]] name = "zip321" -version = "0.9.0-rc.1" -source = "git+https://github.com/zcash/librustzcash?rev=0a2c6d1ae6274e6af2291e312f7b7459516882f2#0a2c6d1ae6274e6af2291e312f7b7459516882f2" +version = "0.10.0-pre.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60e43f36a390a70ff428ee900f50c146fb43277028502717fbbb44918e575488" dependencies = [ "base64", "nom", diff --git a/Cargo.toml b/Cargo.toml index d661552..d11ec2f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,32 +30,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 pre-releases from crates.io (pinned exactly). NU7 is active on +## testnet from block 4,465,026 with consensus branch id 0x77190AD9; mainnet has no NU7 height yet. +## `zcash_client_memory` is a local path override while its NU7 port is developed; switch it to the +## fork's git rev before any PR, CI run or release. +zcash_keys = { version = "=0.17.0-pre.1", features = ["transparent-inputs", "orchard", "sapling", "unstable"] } +zcash_client_backend = { version = "=0.25.0-pre.1", default-features = false, features = ["sync", "lightwalletd-tonic", "orchard", "zeroize"] } +zcash_client_memory = { path = "../zcash_client_memory", features = ["orchard", "transparent-inputs"] } +zcash_primitives = { version = "=0.31.0-pre.1" } +zcash_transparent = { version = "=0.11.0-pre.1", default-features = false } +zcash_address = { version = "=0.14.0-pre.1" } +zcash_proofs = { version = "=0.31.0-pre.1", default-features = false, features = ["bundled-prover", "multicore"] } +zip321 = { version = "=0.10.0-pre.1" } +zip32 = { version = "0.3" } +zcash_protocol = { version = "=0.11.0-pre.0", default-features = false } +pczt = { version = "=0.10.0-pre.1", 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-pre.1", 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" @@ -83,30 +87,5 @@ tempfile = "3.12" 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" } - [workspace.lints.rust] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(wasm_bindgen)', 'cfg(wasm_bindgen_unstable_test_coverage)'] } \ No newline at end of file diff --git a/crates/webzjs-keys/Cargo.toml b/crates/webzjs-keys/Cargo.toml index 50b5226..25e0add 100644 --- a/crates/webzjs-keys/Cargo.toml +++ b/crates/webzjs-keys/Cargo.toml @@ -34,7 +34,7 @@ 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 @@ -42,10 +42,12 @@ 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 @@ -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 diff --git a/crates/webzjs-keys/src/error.rs b/crates/webzjs-keys/src/error.rs index 0b5553f..04d8fb8 100644 --- a/crates/webzjs-keys/src/error.rs +++ b/crates/webzjs-keys/src/error.rs @@ -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}")] diff --git a/crates/webzjs-keys/src/keys.rs b/crates/webzjs-keys/src/keys.rs index efa42b7..75fd006 100644 --- a/crates/webzjs-keys/src/keys.rs +++ b/crates/webzjs-keys/src/keys.rs @@ -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(), } } } @@ -146,7 +146,9 @@ impl UnifiedFullViewingKey { /// pub fn encode(&self, network: &str) -> Result { 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 @@ -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()))?, }) } diff --git a/crates/webzjs-keys/src/pczt_describe.rs b/crates/webzjs-keys/src/pczt_describe.rs index 02a5485..02a43fc 100644 --- a/crates/webzjs-keys/src/pczt_describe.rs +++ b/crates/webzjs-keys/src/pczt_describe.rs @@ -190,12 +190,12 @@ 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 { - 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 { - 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)) } /// True iff this Orchard spend is recoverable under `ofvk`. @@ -414,7 +414,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 = Vec::new(); let mut total_in: u64 = 0; diff --git a/crates/webzjs-keys/src/pczt_sign.rs b/crates/webzjs-keys/src/pczt_sign.rs index ffe9253..334ad0c 100644 --- a/crates/webzjs-keys/src/pczt_sign.rs +++ b/crates/webzjs-keys/src/pczt_sign.rs @@ -163,6 +163,7 @@ pub async fn pczt_sign_inner( KeyRef::Orchard { index } => { signer .sign_orchard( + rand10::rng(), index, &orchard::keys::SpendAuthorizingKey::from(usk.orchard()), ) @@ -174,6 +175,7 @@ pub async fn pczt_sign_inner( // Ironwood reuses the Orchard spend-authorizing key. signer .sign_ironwood( + rand10::rng(), index, &orchard::keys::SpendAuthorizingKey::from(usk.orchard()), ) @@ -183,7 +185,7 @@ pub async fn pczt_sign_inner( } KeyRef::Sapling { index } => { signer - .sign_sapling(index, &usk.sapling().expsk.ask) + .sign_sapling(rand10::rng(), index, usk.sapling().expsk().ask()) .map_err(|e| { Error::PcztSign(format!("Failed to sign Sapling spend {index}: {e:?}")) })?; diff --git a/crates/webzjs-keys/tests/gen_fixtures.rs b/crates/webzjs-keys/tests/gen_fixtures.rs index c297b66..eb0ce3a 100644 --- a/crates/webzjs-keys/tests/gen_fixtures.rs +++ b/crates/webzjs-keys/tests/gen_fixtures.rs @@ -35,8 +35,8 @@ use orchard::Address; use pczt::roles::creator::Creator; use pczt::roles::redactor::Redactor; -use rand::rngs::StdRng; -use rand::{RngCore, SeedableRng}; +use rand10::rngs::StdRng; +use rand10::{Rng, SeedableRng}; use webzjs_common::Network; use zcash_keys::keys::UnifiedSpendingKey; diff --git a/crates/webzjs-keys/tests/spoof_pczt.rs b/crates/webzjs-keys/tests/spoof_pczt.rs index ced536f..3485d19 100644 --- a/crates/webzjs-keys/tests/spoof_pczt.rs +++ b/crates/webzjs-keys/tests/spoof_pczt.rs @@ -87,7 +87,7 @@ fn attacker_addr() -> String { .expect("UFVK has an Orchard key") .clone(); let addr = ofvk.address_at(0u32, orchard::keys::Scope::External); - UnifiedAddress::from_receivers(Some(addr), None, None) + UnifiedAddress::from_receivers(Some(addr), None, None, None, None) .expect("orchard-only UA") .encode(&network) } @@ -305,7 +305,7 @@ fn bridge_orchard_addr() -> String { .expect("UFVK has an Orchard key") .clone(); let addr = ofvk.address_at(0u32, orchard::keys::Scope::External); - UnifiedAddress::from_receivers(Some(addr), None, None) + UnifiedAddress::from_receivers(Some(addr), None, None, None, None) .expect("orchard-only UA") .encode(&network) } diff --git a/crates/webzjs-requests/Cargo.toml b/crates/webzjs-requests/Cargo.toml index 72fcf03..ec6eaa2 100644 --- a/crates/webzjs-requests/Cargo.toml +++ b/crates/webzjs-requests/Cargo.toml @@ -25,6 +25,7 @@ serde-wasm-bindgen.workspace = true # fixes "failed to resolve: use of undeclared crate or module `imp`" error getrandom = { workspace = true, features = ["js"] } +getrandom04.workspace = true [lints] workspace = true diff --git a/crates/webzjs-wallet/Cargo.toml b/crates/webzjs-wallet/Cargo.toml index 81dffa8..fdc395f 100644 --- a/crates/webzjs-wallet/Cargo.toml +++ b/crates/webzjs-wallet/Cargo.toml @@ -64,7 +64,7 @@ zcash_proofs = { workspace = true, default-features = false, features = ["bundle zip321 = { workspace = true } zip32 = { workspace = true } pczt = { workspace = true, default-features = false, features = ["orchard", "sapling", "transparent"] } -orchard = { version = "0.15", default-features = false } +orchard = { version = "0.16", default-features = false } sapling = { workspace = true } bip32.workspace = true ## gRPC Web dependencies @@ -76,6 +76,8 @@ tokio.workspace = true zcash_client_sqlite = { workspace = true, optional = true } getrandom = { workspace = true, features = ["js"] } +getrandom04.workspace = true +rand10.workspace = true thiserror.workspace = true indexed_db_futures = "0.5.0" sha2 = "0.10" diff --git a/crates/webzjs-wallet/src/bindgen/transaction_history.rs b/crates/webzjs-wallet/src/bindgen/transaction_history.rs index 85efabb..9775e10 100644 --- a/crates/webzjs-wallet/src/bindgen/transaction_history.rs +++ b/crates/webzjs-wallet/src/bindgen/transaction_history.rs @@ -226,16 +226,16 @@ pub fn extract_transaction_history( zcash_client_backend::wallet::Recipient::External { output_pool, .. } => { match output_pool { zcash_protocol::PoolType::Transparent => "transparent", - zcash_protocol::PoolType::Shielded( - zcash_protocol::ShieldedProtocol::Sapling, - ) => "sapling", - zcash_protocol::PoolType::Shielded( - zcash_protocol::ShieldedProtocol::Orchard, - ) => "orchard", + zcash_protocol::PoolType::Shielded(zcash_protocol::ShieldedPool::Sapling) => { + "sapling" + } + zcash_protocol::PoolType::Shielded(zcash_protocol::ShieldedPool::Orchard) => { + "orchard" + } // NU6.3 Ironwood pool. - zcash_protocol::PoolType::Shielded( - zcash_protocol::ShieldedProtocol::Ironwood, - ) => "ironwood", + zcash_protocol::PoolType::Shielded(zcash_protocol::ShieldedPool::Ironwood) => { + "ironwood" + } } } zcash_client_backend::wallet::Recipient::EphemeralTransparent { .. } => "transparent", diff --git a/crates/webzjs-wallet/src/bindgen/wallet.rs b/crates/webzjs-wallet/src/bindgen/wallet.rs index 7b29651..6d525f8 100644 --- a/crates/webzjs-wallet/src/bindgen/wallet.rs +++ b/crates/webzjs-wallet/src/bindgen/wallet.rs @@ -214,7 +214,7 @@ impl WebWallet { birthday_height: Option, ) -> Result { let ufvk = UnifiedFullViewingKey::decode(&self.inner.network, encoded_ufvk) - .map_err(Error::KeyParse)?; + .map_err(|e| Error::KeyParse(e.to_string()))?; let derivation = Some(Zip32Derivation::new( seed_fingerprint.into(), zip32::AccountId::try_from(account_hd_index)?, @@ -251,7 +251,7 @@ impl WebWallet { birthday_height: Option, ) -> Result { let ufvk = UnifiedFullViewingKey::decode(&self.inner.network, encoded_ufvk) - .map_err(Error::KeyParse)?; + .map_err(|e| Error::KeyParse(e.to_string()))?; self.inner .import_ufvk( diff --git a/crates/webzjs-wallet/src/chain_params.rs b/crates/webzjs-wallet/src/chain_params.rs new file mode 100644 index 0000000..7bf4067 --- /dev/null +++ b/crates/webzjs-wallet/src/chain_params.rs @@ -0,0 +1,135 @@ +//! Wallet behaviour that depends on the network upgrade in force at the height a transaction +//! will be mined, so it stays correct across upgrades instead of being fixed to one pool. + +use std::time::SystemTime; + +use orchard::circuit::OrchardCircuitVersion; +use zcash_client_backend::util::Clock; +use zcash_protocol::{ + consensus::{BlockHeight, BranchId, OrchardProtocolRevision, Parameters}, + ShieldedPool, +}; + +/// Returns the shielded pool that receives new value (and so change) in a transaction mined at +/// `target_height`. +/// +/// Since NU6.3 the Orchard pool no longer accepts new value: shielded outputs go to the Ironwood +/// pool, which every later upgrade so far keeps (NU7 included). Before NU6.3 they go to Orchard. +/// The answer is derived from the Orchard protocol revision of the consensus branch, never from a +/// hard-coded pool, so a future upgrade that selects a different revision is a compile-time +/// reminder to revisit this function rather than a silent misbehaviour. +pub(crate) fn change_pool_at( + params: &P, + target_height: BlockHeight, +) -> ShieldedPool { + match BranchId::for_height(params, target_height).orchard_protocol_revision() { + Some(OrchardProtocolRevision::V3) => ShieldedPool::Ironwood, + Some(OrchardProtocolRevision::InsecureV1 | OrchardProtocolRevision::V2) | None => { + ShieldedPool::Orchard + } + } +} + +/// Returns the Orchard circuit version used for proofs and verification under `branch`, or +/// `None` if proofs are not (or are no longer) created for that branch. +/// +/// Derived from the branch's Orchard protocol revision, so every branch from NU6.3 onward +/// (including NU7) uses the post-NU6.3 circuit. +pub(crate) fn orchard_circuit_version(branch: BranchId) -> Option { + match branch.orchard_protocol_revision()? { + OrchardProtocolRevision::V3 => Some(OrchardCircuitVersion::PostNu6_3), + OrchardProtocolRevision::V2 => Some(OrchardCircuitVersion::FixedPostNu6_2), + // The pre-NU6.2 circuit is unsound and is never used to prove. + OrchardProtocolRevision::InsecureV1 => None, + } +} + +/// A [`Clock`] that works in a browser. +/// +/// `std::time::SystemTime::now()` panics on `wasm32-unknown-unknown`, which is what the +/// backend's `SystemClock` uses, so on that target the time comes from `Date.now()`. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct WalletClock; + +impl Clock for WalletClock { + fn now(&self) -> SystemTime { + #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] + { + // `Date.now()` is milliseconds since the Unix epoch, as a float. + std::time::UNIX_EPOCH + std::time::Duration::from_millis(js_sys::Date::now() as u64) + } + #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] + { + SystemTime::now() + } + } +} + +#[cfg(test)] +mod tests { + use std::time::UNIX_EPOCH; + + use webzjs_common::Network; + use zcash_protocol::consensus::NetworkUpgrade; + + use super::*; + + fn h(n: u32) -> BlockHeight { + BlockHeight::from_u32(n) + } + + #[test] + fn testnet_change_pool_follows_the_active_upgrade() { + let net = Network::TestNetwork; + let nu6_3 = net.activation_height(NetworkUpgrade::Nu6_3).unwrap(); + let nu7 = net.activation_height(NetworkUpgrade::Nu7).unwrap(); + assert_eq!(u32::from(nu6_3), 4_134_000); + assert_eq!(u32::from(nu7), 4_465_026); + + assert_eq!(change_pool_at(&net, nu6_3 - 1), ShieldedPool::Orchard); + assert_eq!(change_pool_at(&net, nu6_3), ShieldedPool::Ironwood); + assert_eq!(change_pool_at(&net, nu7 - 1), ShieldedPool::Ironwood); + // NU7 keeps the Ironwood pool. + assert_eq!(change_pool_at(&net, nu7), ShieldedPool::Ironwood); + assert_eq!(change_pool_at(&net, h(4_483_500)), ShieldedPool::Ironwood); + } + + #[test] + fn mainnet_change_pool_before_and_after_nu6_3() { + let net = Network::MainNetwork; + let nu6_3 = net.activation_height(NetworkUpgrade::Nu6_3).unwrap(); + assert_eq!(u32::from(nu6_3), 3_428_143); + assert_eq!(change_pool_at(&net, nu6_3 - 1), ShieldedPool::Orchard); + assert_eq!(change_pool_at(&net, nu6_3), ShieldedPool::Ironwood); + // Mainnet has no NU7 height yet; the pool does not depend on it. + assert_eq!(net.activation_height(NetworkUpgrade::Nu7), None); + assert_eq!(change_pool_at(&net, h(4_000_000)), ShieldedPool::Ironwood); + } + + #[test] + fn circuit_version_follows_the_branch() { + assert_eq!( + orchard_circuit_version(BranchId::Nu6_2), + Some(OrchardCircuitVersion::FixedPostNu6_2) + ); + assert_eq!( + orchard_circuit_version(BranchId::Nu6_3), + Some(OrchardCircuitVersion::PostNu6_3) + ); + // The old mapping treated every branch other than NU6.3 as the pre-Ironwood circuit, + // which would have produced invalid proofs under NU7. + assert_eq!( + orchard_circuit_version(BranchId::Nu7), + Some(OrchardCircuitVersion::PostNu6_3) + ); + assert_eq!(orchard_circuit_version(BranchId::Sapling), None); + assert_eq!(orchard_circuit_version(BranchId::Nu6_1), None); + } + + #[test] + fn native_clock_reports_a_plausible_time() { + let now = WalletClock.now().duration_since(UNIX_EPOCH).unwrap(); + // After 2024-01-01. + assert!(now.as_secs() > 1_704_067_200); + } +} diff --git a/crates/webzjs-wallet/src/lib.rs b/crates/webzjs-wallet/src/lib.rs index cacd624..d6a2c90 100644 --- a/crates/webzjs-wallet/src/lib.rs +++ b/crates/webzjs-wallet/src/lib.rs @@ -6,6 +6,7 @@ #[cfg(feature = "wasm")] pub mod bindgen; +mod chain_params; mod error; pub mod init; pub mod validation; diff --git a/crates/webzjs-wallet/src/wallet.rs b/crates/webzjs-wallet/src/wallet.rs index 97b362e..f3c2827 100644 --- a/crates/webzjs-wallet/src/wallet.rs +++ b/crates/webzjs-wallet/src/wallet.rs @@ -8,6 +8,7 @@ use tonic::{ codegen::{Body, Bytes, StdError}, }; +use crate::chain_params::{change_pool_at, orchard_circuit_version, WalletClock}; use crate::error::Error; use crate::BlockRange; use webzjs_common::Network; @@ -47,16 +48,17 @@ use zcash_client_backend::wallet::OvkPolicy; use zcash_client_backend::zip321::{Payment, TransactionRequest}; use zcash_client_memory::{MemBlockCache, MemoryWalletDb}; use zcash_keys::keys::{UnifiedFullViewingKey, UnifiedSpendingKey}; +use zcash_primitives::transaction::builder::BundlePadding; use zcash_primitives::transaction::fees::FeeRule; use zcash_primitives::transaction::TxId; use zcash_proofs::prover::LocalTxProver; -use zcash_protocol::ShieldedProtocol; use zcash_client_backend::sync::run; -use zcash_protocol::consensus::BranchId; use zcash_protocol::consensus::Parameters; +use zcash_protocol::consensus::{BlockHeight, BranchId}; use zcash_protocol::value::Zatoshis; +use zcash_protocol::ShieldedPool; use zip32; use zip32::fingerprint::SeedFingerprint; @@ -301,6 +303,16 @@ where .get_wallet_summary(self.min_confirmations)?) } + /// Returns the pool that change goes to in a transaction mined next, chosen from the network + /// upgrade in force at that height (Ironwood since NU6.3). + async fn change_pool(&self) -> Result { + let tip = self.db.read().await.chain_height()?.ok_or_else(|| { + Error::Generic("Wallet has not been synced yet. Please sync first.".to_string()) + })?; + let target_height: BlockHeight = tip + 1; + Ok(change_pool_at(&self.network, target_height)) + } + /// /// Create a transaction proposal to send funds from the wallet to a given address /// @@ -312,10 +324,11 @@ where ) -> Result, Error> { let input_selector = GreedyInputSelector::new(); + let change_pool = self.change_pool().await?; let change_strategy = MultiOutputChangeStrategy::new( StandardFeeRule::Zip317, None, - ShieldedProtocol::Orchard, + change_pool, DustOutputPolicy::default(), SplitPolicy::with_min_output_value( NonZeroUsize::new(self.target_note_count) @@ -350,6 +363,8 @@ where // spend policy preserves prior behaviour; `None` lets the builder pick // the tx version for the target height (v6 post-NU6.3 activation). &SpendPolicy::default(), + // client_backend 0.25 added optional input locking; no locks are held across calls. + None, None, ) .map_err(|_e| Error::Generic("something bad happened when calling propose transfer. Possibly insufficient balance..".to_string()))?; @@ -380,6 +395,8 @@ where >( &mut *db, &self.network, + &WalletClock, + &mut rand10::rng(), &prover, &prover, &SpendingKeys::from_unified_spending_key(usk.clone()), @@ -496,10 +513,11 @@ where )); } + let change_pool = self.change_pool().await?; let change_strategy = MultiOutputChangeStrategy::new( StandardFeeRule::Zip317, None, - ShieldedProtocol::Orchard, + change_pool, DustOutputPolicy::default(), SplitPolicy::with_min_output_value( NonZeroUsize::new(self.target_note_count) @@ -556,6 +574,7 @@ where account_id, self.min_confirmations, // librustzcash operates under the assumption of zero or one conf being the same but that could change. CoinbaseFilter::AllTransparentOutputs, // shield all transparent outputs (preserves pre-0.23 behavior, before this filter existed) + None, // no input locking ) .map_err(|e| { tracing::error!("pczt_shield: propose_shielding failed: {:?}", e); @@ -574,13 +593,15 @@ where >( &mut *db, &self.network, + &WalletClock, + &mut rand10::rng(), account_id, OvkPolicy::Sender, &proposal, - // client_backend 0.24: explicit expiry height (None = builder default) - // and the Orchard-pool bundle type for the created PCZT. + // Explicit expiry height (None = builder default) and the padding of the + // Orchard-family bundles of the created PCZT. None, - orchard::builder::BundleType::DEFAULT, + BundlePadding::DEFAULT, ) .map_err(|e| { tracing::error!("pczt_shield: create_pczt_from_proposal failed: {:?}", e); @@ -629,10 +650,11 @@ where } // Create the PCZT. + let change_pool = self.change_pool().await?; let change_strategy = MultiOutputChangeStrategy::new( StandardFeeRule::Zip317, None, - ShieldedProtocol::Orchard, + change_pool, DustOutputPolicy::default(), SplitPolicy::with_min_output_value( NonZeroUsize::new(self.target_note_count) @@ -656,6 +678,8 @@ where request, self.min_confirmations, &SpendPolicy::default(), + // client_backend 0.25 added optional input locking; no locks are held across calls. + None, None, ) .map_err(|e| Error::Generic(format!("something bad happened when calling propose transfer. Possibly insufficient balance... {e:?}")))?; @@ -670,13 +694,15 @@ where >( &mut *db, &self.network, + &WalletClock, + &mut rand10::rng(), account_id, OvkPolicy::Sender, &proposal, - // client_backend 0.24: explicit expiry height (None = builder default) - // and the Orchard-pool bundle type for the created PCZT. + // Explicit expiry height (None = builder default) and the padding of the + // Orchard-family bundles of the created PCZT. None, - orchard::builder::BundleType::DEFAULT, + BundlePadding::DEFAULT, ) .map_err(|e| { tracing::error!("pczt_create: create_pczt_from_proposal failed: {:?}", e); @@ -733,25 +759,43 @@ where pczt }; - // orchard 0.15 (NU6.3) requires an explicit circuit version. Derive it from the - // PCZT's target consensus branch, mirroring zcash_primitives' transaction builder: - // Nu6_3 -> PostNu6_3 (the Ironwood-era circuit that enforces the disableCrossAddress - // constraint sealing the Orchard pool); everything current (Nu6_2) -> FixedPostNu6_2. - // The same version must build the verifying key when extracting the transaction below. - let orchard_circuit_version = match BranchId::try_from(*pczt.global().consensus_branch_id()) - { - Ok(BranchId::Nu6_3) => orchard::circuit::OrchardCircuitVersion::PostNu6_3, - _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2, - }; + // Orchard-family bundles (Orchard and Ironwood) need a circuit version, derived from the + // PCZT's target consensus branch via its Orchard protocol revision: NU6.2 uses the fixed + // circuit, and NU6.3 and every later upgrade (NU7 included) the post-NU6.3 circuit that + // enforces the disableCrossAddress constraint. The same version must build the verifying + // key when the transaction is extracted. + let branch = BranchId::try_from(*pczt.global().consensus_branch_id()).map_err(|e| { + Error::PcztProve(format!("PCZT has an unknown consensus branch id: {:?}", e)) + })?; + let orchard_circuit_version = orchard_circuit_version(branch).ok_or_else(|| { + Error::PcztProve(format!( + "Cannot create Orchard proofs for consensus branch {:?}", + branch + )) + })?; let prover = LocalTxProver::bundled(); - let pczt = Prover::new(pczt) - .create_orchard_proof(&orchard::circuit::ProvingKey::build( - orchard_circuit_version, - )) - .map_err(|e| Error::PcztProve(format!("Failed to create Orchard proof: {e:?}")))? - .create_sapling_proofs(&prover, &prover) - .map_err(|e| Error::PcztProve(format!("Failed to create Sapling proofs: {e:?}")))? + let mut proofs = Prover::new(pczt); + if proofs.requires_orchard_proof() || proofs.requires_ironwood_proof() { + let proving_key = orchard::circuit::ProvingKey::build(orchard_circuit_version); + if proofs.requires_orchard_proof() { + proofs = proofs + .create_orchard_proof(rand10::rng(), &proving_key) + .map_err(|e| { + Error::PcztProve(format!("Failed to create Orchard proof: {:?}", e)) + })?; + } + if proofs.requires_ironwood_proof() { + proofs = proofs + .create_ironwood_proof(rand10::rng(), &proving_key) + .map_err(|e| { + Error::PcztProve(format!("Failed to create Ironwood proof: {:?}", e)) + })?; + } + } + let pczt = proofs + .create_sapling_proofs(rand10::rng(), &prover, &prover) + .map_err(|e| Error::PcztProve(format!("Failed to create Sapling proofs: {:?}", e)))? .finish(); Ok(pczt) } @@ -799,16 +843,22 @@ where // Build the Orchard verifying key with the circuit version for this PCZT's target // branch (Nu6_3 -> PostNu6_3, else FixedPostNu6_2), matching how the proof was // created. See the proving-key derivation in the pczt_prove path. - let orchard_circuit_version = match BranchId::try_from(*pczt.global().consensus_branch_id()) - { - Ok(BranchId::Nu6_3) => orchard::circuit::OrchardCircuitVersion::PostNu6_3, - _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2, - }; + let branch = BranchId::try_from(*pczt.global().consensus_branch_id()).map_err(|e| { + Error::PcztSend(format!("PCZT has an unknown consensus branch id: {:?}", e)) + })?; + let orchard_circuit_version = orchard_circuit_version(branch).ok_or_else(|| { + Error::PcztSend(format!( + "Cannot verify Orchard proofs for consensus branch {:?}", + branch + )) + })?; let prover = LocalTxProver::bundled(); let (spend_vk, output_vk) = prover.verifying_keys(); let mut db = self.db.write().await; let txid = extract_and_store_transaction_from_pczt::<_, ()>( &mut *db, + &WalletClock, + &mut rand10::rng(), pczt, Some((&spend_vk, &output_vk)), Some(&orchard::circuit::VerifyingKey::build( From 4785673b30f82ef5d0a7d5c9343f45f26c9505fb Mon Sep 17 00:00:00 2001 From: aratrika Date: Wed, 4 Nov 2026 17:34:58 -0500 Subject: [PATCH 2/8] Vendor tonic-web-wasm-client with a trailers-only response fix --- Cargo.lock | 2 - Cargo.toml | 8 + vendor/tonic-web-wasm-client/Cargo.toml | 110 ++++++ vendor/tonic-web-wasm-client/LICENSE_APACHE | 176 +++++++++ vendor/tonic-web-wasm-client/LICENSE_MIT | 25 ++ vendor/tonic-web-wasm-client/README.md | 62 ++++ vendor/tonic-web-wasm-client/VENDORED.md | 39 ++ .../tonic-web-wasm-client/src/abort_guard.rs | 62 ++++ .../tonic-web-wasm-client/src/body_stream.rs | 65 ++++ vendor/tonic-web-wasm-client/src/call.rs | 118 ++++++ vendor/tonic-web-wasm-client/src/client.rs | 62 ++++ .../tonic-web-wasm-client/src/content_type.rs | 49 +++ vendor/tonic-web-wasm-client/src/error.rs | 63 ++++ vendor/tonic-web-wasm-client/src/fetch.rs | 33 ++ vendor/tonic-web-wasm-client/src/lib.rs | 57 +++ .../src/options/cache.rs | 47 +++ .../src/options/credentials.rs | 26 ++ .../tonic-web-wasm-client/src/options/mod.rs | 141 +++++++ .../tonic-web-wasm-client/src/options/mode.rs | 33 ++ .../src/options/redirect.rs | 27 ++ .../src/options/referrer_policy.rs | 71 ++++ .../src/response_body.rs | 344 ++++++++++++++++++ .../tonic-web-wasm-client/trailers-only.patch | 68 ++++ 23 files changed, 1686 insertions(+), 2 deletions(-) create mode 100644 vendor/tonic-web-wasm-client/Cargo.toml create mode 100644 vendor/tonic-web-wasm-client/LICENSE_APACHE create mode 100644 vendor/tonic-web-wasm-client/LICENSE_MIT create mode 100644 vendor/tonic-web-wasm-client/README.md create mode 100644 vendor/tonic-web-wasm-client/VENDORED.md create mode 100644 vendor/tonic-web-wasm-client/src/abort_guard.rs create mode 100644 vendor/tonic-web-wasm-client/src/body_stream.rs create mode 100644 vendor/tonic-web-wasm-client/src/call.rs create mode 100644 vendor/tonic-web-wasm-client/src/client.rs create mode 100644 vendor/tonic-web-wasm-client/src/content_type.rs create mode 100644 vendor/tonic-web-wasm-client/src/error.rs create mode 100644 vendor/tonic-web-wasm-client/src/fetch.rs create mode 100644 vendor/tonic-web-wasm-client/src/lib.rs create mode 100644 vendor/tonic-web-wasm-client/src/options/cache.rs create mode 100644 vendor/tonic-web-wasm-client/src/options/credentials.rs create mode 100644 vendor/tonic-web-wasm-client/src/options/mod.rs create mode 100644 vendor/tonic-web-wasm-client/src/options/mode.rs create mode 100644 vendor/tonic-web-wasm-client/src/options/redirect.rs create mode 100644 vendor/tonic-web-wasm-client/src/options/referrer_policy.rs create mode 100644 vendor/tonic-web-wasm-client/src/response_body.rs create mode 100644 vendor/tonic-web-wasm-client/trailers-only.patch diff --git a/Cargo.lock b/Cargo.lock index dc91b55..dd9b563 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3036,8 +3036,6 @@ dependencies = [ [[package]] name = "tonic-web-wasm-client" version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "898cd44be5e23e59d2956056538f1d6b3c5336629d384ffd2d92e76f87fb98ff" dependencies = [ "base64", "byteorder", diff --git a/Cargo.toml b/Cargo.toml index d11ec2f..39d5590 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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. @@ -87,5 +89,11 @@ tempfile = "3.12" tokio = { version = "1.0", features = ["rt", "macros"] } byte-unit = { version = "5.1.4", features = ["byte"] } +[patch.crates-io] +# 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)'] } \ No newline at end of file diff --git a/vendor/tonic-web-wasm-client/Cargo.toml b/vendor/tonic-web-wasm-client/Cargo.toml new file mode 100644 index 0000000..ab397f4 --- /dev/null +++ b/vendor/tonic-web-wasm-client/Cargo.toml @@ -0,0 +1,110 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +name = "tonic-web-wasm-client" +version = "0.8.0" +authors = ["Devashish Dixit "] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "grpc-web implementation for use by tonic clients in browsers via webassembly" +homepage = "https://github.com/devashishdxt/tonic-web-wasm-client" +readme = "README.md" +keywords = [ + "grpc", + "grpc-web", + "tonic", + "wasm", +] +categories = [ + "web-programming", + "network-programming", + "asynchronous", +] +license = "MIT/Apache-2.0" +repository = "https://github.com/devashishdxt/tonic-web-wasm-client" + +[lib] +name = "tonic_web_wasm_client" +path = "src/lib.rs" + +[dependencies.base64] +version = "0.22" + +[dependencies.byteorder] +version = "1" + +[dependencies.bytes] +version = "1" + +[dependencies.futures-util] +version = "0.3" +default-features = false + +[dependencies.http] +version = "1" + +[dependencies.http-body] +version = "1" + +[dependencies.http-body-util] +version = "0.1" + +[dependencies.httparse] +version = "1" + +[dependencies.js-sys] +version = "0.3" + +[dependencies.pin-project] +version = "1" + +[dependencies.thiserror] +version = "2" + +[dependencies.tonic] +version = "0.14" +default-features = false + +[dependencies.tower-service] +version = "0.3" + +[dependencies.wasm-bindgen] +version = "0.2" + +[dependencies.wasm-bindgen-futures] +version = "0.4" + +[dependencies.wasm-streams] +version = "0.4" + +[dependencies.web-sys] +version = "0.3" +features = [ + "AbortController", + "AbortSignal", + "Headers", + "ReadableStream", + "ReferrerPolicy", + "Request", + "RequestCache", + "RequestCredentials", + "RequestInit", + "RequestMode", + "RequestRedirect", + "Response", + "ServiceWorkerGlobalScope", +] diff --git a/vendor/tonic-web-wasm-client/LICENSE_APACHE b/vendor/tonic-web-wasm-client/LICENSE_APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/vendor/tonic-web-wasm-client/LICENSE_APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/vendor/tonic-web-wasm-client/LICENSE_MIT b/vendor/tonic-web-wasm-client/LICENSE_MIT new file mode 100644 index 0000000..e8388da --- /dev/null +++ b/vendor/tonic-web-wasm-client/LICENSE_MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018 Devashish Dixit + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/vendor/tonic-web-wasm-client/README.md b/vendor/tonic-web-wasm-client/README.md new file mode 100644 index 0000000..b703193 --- /dev/null +++ b/vendor/tonic-web-wasm-client/README.md @@ -0,0 +1,62 @@ +# tonic-web-wasm-client + +Rust implementation of [`grpc-web`](https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md) protocol that allows +using [`tonic`](https://crates.io/crates/tonic) in browsers via webassembly. + +## Usage + +To use `tonic-web-wasm-client`, you need to add the following to your `Cargo.toml`: + +```toml +[dependencies] +tonic-web-wasm-client = "0.8" +``` + +### Example +To use `tonic` gRPC clients in browser, compile your code with tonic's `transport` feature disabled (this will disable +the default transport layer of tonic). Then initialize the query client as follows: + +```rust +use tonic_web_wasm_client::Client; + +let base_url = "http://localhost:9001"; // URL of the gRPC-web server +let query_client = QueryClient::new(Client::new(base_url)); // `QueryClient` is the client generated by tonic + +let response = query_client.status().await; // Execute your queries the same way as you do with defaule transport layer +``` + +### Building + +Since `tonic-web-wasm-client` is primarily intended for use in browsers, a crate that uses `tonic-web-wasm-client` +can only be built for `wasm32` target architectures: + +```shell +cargo build --target wasm32-unknown-unknown +``` + +Other option is to create a `.cargo/config.toml` in your crate repository and add a build target there: + +```toml +[build] +target = "wasm32-unknown-unknown" +``` + +### Custom `Accept` header: + +This library allows you to set a custom `Accept` header for the requests. This can be useful if you need to specify +a different content type for the responses. But, be aware that if you set a custom `Accept` header, the client may +not be able to handle the response correctly. + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE)) +- MIT license ([LICENSE-MIT](LICENSE-MIT)) + +at your option. + +## Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as +defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. diff --git a/vendor/tonic-web-wasm-client/VENDORED.md b/vendor/tonic-web-wasm-client/VENDORED.md new file mode 100644 index 0000000..eaab074 --- /dev/null +++ b/vendor/tonic-web-wasm-client/VENDORED.md @@ -0,0 +1,39 @@ +# Vendored `tonic-web-wasm-client` 0.8.0, with one fix + +This is `tonic-web-wasm-client` 0.8.0 from crates.io (MIT/Apache-2.0, see the licence files) with +the change in `trailers-only.patch`, wired in through `[patch.crates-io]` in the workspace +`Cargo.toml`. + +## Why + +A gRPC server may answer a call that returns no messages with a *trailers-only* response: HTTP 200, +`grpc-status` in the HTTP headers, and an empty body. lightwalletd v0.5.4 (the Zcash testnet +endpoint, `https://zjs.zec.rocks/testnet`) does this for an empty `GetAddressUtxosStream`, which +every new wallet issues during sync. Mainnet (lightwalletd v0.5.3) sends a body frame instead. + +Upstream 0.8.0 (and 0.9.2) reads the empty body as a truncated message and fails with +`MalformedResponse`, so a wallet could not sync at all on testnet. + +## The change + +`ResponseBody` records whether the response headers carried `grpc-status`. If the body ends before +any frame header *and* the response was trailers-only, it is treated as an empty body. A body that +ends early on any other response is still `MalformedResponse`. + +## Not bumped to 0.9.2 + +0.9.2 has the same behaviour (checked), and requires `js-sys ^0.3.85`, which conflicts with the +workspace's deliberate `wasm-bindgen =0.2.100` / `js-sys =0.3.77` pins (newer versions break the +MetaMask Snap sandbox). + +## Upstream status (checked 2026-10-13) + +Reported upstream as devashishdxt/tonic-web-wasm-client issue #99 (2026-09-25) with PR #113 open +(same idea: end the body when the stream ends between frames with nothing buffered; unmerged, no +reviews). Release 0.9.2 (2026-09-14) does not include it. Do not send our patch separately. + +## To remove + +Drop this directory, the `[patch.crates-io]` entry and the `exclude` entry once the fix is +released upstream. `trailers-only.patch` is a ready-made upstream change (apply with `patch -p1` +from a `tonic-web-wasm-client` checkout). diff --git a/vendor/tonic-web-wasm-client/src/abort_guard.rs b/vendor/tonic-web-wasm-client/src/abort_guard.rs new file mode 100644 index 0000000..a94190f --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/abort_guard.rs @@ -0,0 +1,62 @@ +use std::time::Duration; + +use js_sys::Function; +use wasm_bindgen::{ + prelude::{wasm_bindgen, Closure}, + JsCast, JsValue, +}; +use web_sys::{AbortController, AbortSignal}; + +use crate::Error; + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(js_name = "setTimeout")] + fn set_timeout(handler: &Function, timeout: i32) -> JsValue; + + #[wasm_bindgen(js_name = "clearTimeout")] + fn clear_timeout(handle: JsValue) -> JsValue; +} + +/// A guard that cancels a fetch request when dropped. +pub struct AbortGuard { + ctrl: AbortController, + timeout: Option<(JsValue, Closure)>, +} + +impl AbortGuard { + pub fn new() -> Result { + Ok(AbortGuard { + ctrl: AbortController::new().map_err(Error::js_error)?, + timeout: None, + }) + } + + pub fn signal(&self) -> AbortSignal { + self.ctrl.signal() + } + + pub fn timeout(&mut self, timeout: Duration) { + let ctrl = self.ctrl.clone(); + let abort = Closure::once(move || { + ctrl.abort_with_reason(&"tonic_web_wasm_client::Error::TimedOut".into()) + }); + let timeout = set_timeout( + abort.as_ref().unchecked_ref::(), + timeout.as_millis().try_into().expect("timeout"), + ); + if let Some((id, _)) = self.timeout.replace((timeout, abort)) { + clear_timeout(id); + } + } +} + +impl Drop for AbortGuard { + fn drop(&mut self) { + self.ctrl.abort(); + + if let Some((id, _)) = self.timeout.take() { + clear_timeout(id); + } + } +} diff --git a/vendor/tonic-web-wasm-client/src/body_stream.rs b/vendor/tonic-web-wasm-client/src/body_stream.rs new file mode 100644 index 0000000..81af90c --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/body_stream.rs @@ -0,0 +1,65 @@ +use std::{ + pin::Pin, + task::{Context, Poll}, +}; + +use bytes::Bytes; +use futures_util::{stream::empty, Stream, TryStreamExt}; +use http_body::{Body, Frame}; +use js_sys::Uint8Array; +use wasm_streams::readable::IntoStream; + +use crate::{abort_guard::AbortGuard, Error}; + +pub struct BodyStream { + body_stream: Pin>>>, + _abort: Option, +} + +impl BodyStream { + pub fn new(body_stream: IntoStream<'static>, abort: AbortGuard) -> Self { + let body_stream = body_stream + .map_ok(|js_value| { + let buffer = Uint8Array::new(&js_value); + + let mut bytes_vec = vec![0; buffer.length() as usize]; + buffer.copy_to(&mut bytes_vec); + + bytes_vec.into() + }) + .map_err(Error::js_error); + + Self { + body_stream: Box::pin(body_stream), + _abort: Some(abort), + } + } + + pub fn empty() -> Self { + let body_stream = empty(); + + Self { + body_stream: Box::pin(body_stream), + _abort: None, + } + } +} + +impl Body for BodyStream { + type Data = Bytes; + + type Error = Error; + + fn poll_frame( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + match self.body_stream.as_mut().poll_next(cx) { + Poll::Ready(maybe) => Poll::Ready(maybe.map(|result| result.map(Frame::data))), + Poll::Pending => Poll::Pending, + } + } +} + +unsafe impl Send for BodyStream {} +unsafe impl Sync for BodyStream {} diff --git a/vendor/tonic-web-wasm-client/src/call.rs b/vendor/tonic-web-wasm-client/src/call.rs new file mode 100644 index 0000000..0995d9c --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/call.rs @@ -0,0 +1,118 @@ +use http::{ + header::{ACCEPT, CONTENT_TYPE}, + response::Builder, + HeaderMap, HeaderValue, Request, Response, +}; +use http_body_util::BodyExt; +use js_sys::{Array, Uint8Array}; +use tonic::body::Body; +use wasm_bindgen::JsValue; +use web_sys::{Headers, RequestCredentials, RequestInit}; + +use crate::{fetch::fetch, options::FetchOptions, Error, ResponseBody}; + +pub async fn call( + mut base_url: String, + request: Request, + options: FetchOptions, +) -> Result, Error> { + base_url.push_str(&request.uri().to_string()); + + let headers = prepare_headers(request.headers())?; + let body = prepare_body(request).await?; + + let request = prepare_request(&base_url, headers, body)?; + let (init, abort) = options.request_init()?; + let response = fetch(&request, &init).await?; + + let result = Response::builder().status(response.status()); + let (result, content_type) = set_response_headers(result, &response)?; + + let content_type = content_type.ok_or(Error::MissingContentTypeHeader)?; + let body_stream = response.body().ok_or(Error::MissingResponseBody)?; + + let trailers_only = response.headers().has("grpc-status").unwrap_or(false); + let body = ResponseBody::new(body_stream, &content_type, abort, trailers_only)?; + + result.body(body).map_err(Into::into) +} + +fn prepare_headers(header_map: &HeaderMap) -> Result { + // Construct default headers. + let headers = Headers::new().map_err(Error::js_error)?; + headers + .append(CONTENT_TYPE.as_str(), "application/grpc-web+proto") + .map_err(Error::js_error)?; + headers + .append(ACCEPT.as_str(), "application/grpc-web+proto") + .map_err(Error::js_error)?; + headers.append("x-grpc-web", "1").map_err(Error::js_error)?; + + // Apply default headers. + for (header_name, header_value) in header_map.iter() { + // Allow default headers to be overridden except for `content-type`. + if header_name != CONTENT_TYPE { + headers + .set(header_name.as_str(), header_value.to_str()?) + .map_err(Error::js_error)?; + } + } + + Ok(headers) +} + +async fn prepare_body(request: Request) -> Result, Error> { + let body = Some(request.collect().await?.to_bytes()); + Ok(body.map(|bytes| Uint8Array::from(bytes.as_ref()).into())) +} + +fn prepare_request( + url: &str, + headers: Headers, + body: Option, +) -> Result { + let init = RequestInit::new(); + + init.set_method("POST"); + init.set_headers(headers.as_ref()); + if let Some(ref body) = body { + init.set_body(body); + } + init.set_credentials(RequestCredentials::SameOrigin); + + web_sys::Request::new_with_str_and_init(url, &init).map_err(Error::js_error) +} + +fn set_response_headers( + mut result: Builder, + response: &web_sys::Response, +) -> Result<(Builder, Option), Error> { + let headers = response.headers(); + + let header_iter = js_sys::try_iter(headers.as_ref()).map_err(Error::js_error)?; + + let mut content_type = None; + + if let Some(header_iter) = header_iter { + for header in header_iter { + let header = header.map_err(Error::js_error)?; + let pair: Array = header.into(); + + let header_name = pair.get(0).as_string(); + let header_value = pair.get(1).as_string(); + + match (header_name, header_value) { + (Some(header_name), Some(header_value)) => { + if header_name == CONTENT_TYPE.as_str() { + content_type = Some(header_value.clone()); + } + + result = result.header(header_name, header_value); + } + _ => continue, + } + } + } + + Ok((result, content_type)) +} diff --git a/vendor/tonic-web-wasm-client/src/client.rs b/vendor/tonic-web-wasm-client/src/client.rs new file mode 100644 index 0000000..f4b6fa9 --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/client.rs @@ -0,0 +1,62 @@ +use std::{ + future::Future, + pin::Pin, + task::{Context, Poll}, +}; + +use http::{Request, Response}; +use tonic::body::Body; +use tower_service::Service; + +use crate::{call::call, options::FetchOptions, Error, ResponseBody}; + +/// `grpc-web` based transport layer for `tonic` clients +#[derive(Debug, Clone)] +pub struct Client { + base_url: String, + options: Option, +} + +impl Client { + /// Creates a new client + pub fn new(base_url: String) -> Self { + Self { + base_url, + options: None, + } + } + + /// Creates a new client with options + pub fn new_with_options(base_url: String, options: FetchOptions) -> Self { + Self { + base_url, + options: Some(options), + } + } + + /// Sets the options for the client + pub fn with_options(&mut self, options: FetchOptions) -> &mut Self { + self.options = Some(options); + self + } +} + +impl Service> for Client { + type Response = Response; + + type Error = Error; + + type Future = Pin>>>; + + fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, request: Request) -> Self::Future { + Box::pin(call( + self.base_url.clone(), + request, + self.options.clone().unwrap_or_default(), + )) + } +} diff --git a/vendor/tonic-web-wasm-client/src/content_type.rs b/vendor/tonic-web-wasm-client/src/content_type.rs new file mode 100644 index 0000000..d231959 --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/content_type.rs @@ -0,0 +1,49 @@ +use crate::Error; + +const GRPC_WEB: &str = "application/grpc-web"; +const GRPC_WEB_PROTO: &str = "application/grpc-web+proto"; +const GRPC_WEB_TEXT: &str = "application/grpc-web-text"; +const GRPC_WEB_TEXT_PROTO: &str = "application/grpc-web-text+proto"; + +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum Encoding { + Base64, + None, +} + +impl Encoding { + pub fn from_content_type(content_type: &str) -> Result { + for ct in content_type.split(';') { + match ct.trim() { + GRPC_WEB_TEXT | GRPC_WEB_TEXT_PROTO => return Ok(Encoding::Base64), + GRPC_WEB | GRPC_WEB_PROTO => return Ok(Encoding::None), + _ => continue, + } + } + Err(Error::InvalidContentType(content_type.to_owned())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_encoding_from_content_type() { + let vals = [ + (GRPC_WEB, Encoding::None), + (GRPC_WEB_PROTO, Encoding::None), + (GRPC_WEB_TEXT, Encoding::Base64), + (GRPC_WEB_TEXT_PROTO, Encoding::Base64), + ("application/grpc-web+proto;charset=utf-8", Encoding::None), + ("application/grpc-web+proto; charset=utf-8", Encoding::None), + ("charset=utf-8; application/grpc-web+proto", Encoding::None), + ]; + for (content_type, expected) in vals.iter() { + assert_eq!( + Encoding::from_content_type(content_type).ok(), + Some(*expected) + ); + } + } +} diff --git a/vendor/tonic-web-wasm-client/src/error.rs b/vendor/tonic-web-wasm-client/src/error.rs new file mode 100644 index 0000000..eb4df4a --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/error.rs @@ -0,0 +1,63 @@ +use http::header::{InvalidHeaderName, InvalidHeaderValue, ToStrError}; +use js_sys::Object; +use thiserror::Error; +use wasm_bindgen::{JsCast, JsValue}; + +/// Error type for `tonic-web-wasm-client` +#[derive(Debug, Error)] +pub enum Error { + /// Base64 decode error + #[error("base64 decode error")] + Base64DecodeError(#[from] base64::DecodeError), + /// Header parsing error + #[error("failed to parse headers")] + HeaderParsingError, + /// Header value error + #[error("failed to convert header value to string")] + HeaderValueError(#[from] ToStrError), + /// HTTP error + #[error("http error")] + HttpError(#[from] http::Error), + /// Invalid content type + #[error("invalid content type: {0}")] + InvalidContentType(String), + /// Invalid header name + #[error("invalid header name")] + InvalidHeaderName(#[from] InvalidHeaderName), + /// Invalid header value + #[error("invalid header value")] + InvalidHeaderValue(#[from] InvalidHeaderValue), + /// JS API error + #[error("js api error: {0}")] + JsError(String), + /// Malformed response + #[error("malformed response")] + MalformedResponse, + /// Missing `content-type` header in gRPC response + #[error("missing content-type header in grpc response")] + MissingContentTypeHeader, + /// Missing response body in HTTP call + #[error("missing response body in HTTP call")] + MissingResponseBody, + /// gRPC error + #[error("grpc error")] + TonicStatusError(#[from] tonic::Status), +} + +impl Error { + /// Initialize js error from js value + pub(crate) fn js_error(value: JsValue) -> Self { + let message = js_object_display(&value); + + if message.contains("tonic_web_wasm_client::Error::TimedOut") { + Self::TonicStatusError(tonic::Status::deadline_exceeded("Request timed out")) + } else { + Self::JsError(message) + } + } +} + +fn js_object_display(option: &JsValue) -> String { + let object: &Object = option.unchecked_ref(); + ToString::to_string(&object.to_string()) +} diff --git a/vendor/tonic-web-wasm-client/src/fetch.rs b/vendor/tonic-web-wasm-client/src/fetch.rs new file mode 100644 index 0000000..782e299 --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/fetch.rs @@ -0,0 +1,33 @@ +use js_sys::Promise; +use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue}; +use wasm_bindgen_futures::JsFuture; +use web_sys::{Request, RequestInit, Response}; + +use crate::Error; + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(js_name = fetch)] + fn fetch_with_request_and_init(input: &Request, init: &RequestInit) -> Promise; +} + +fn js_fetch(request: &Request, init: &RequestInit) -> Promise { + let global = js_sys::global(); + + if let Ok(true) = js_sys::Reflect::has(&global, &JsValue::from_str("ServiceWorkerGlobalScope")) + { + global + .unchecked_into::() + .fetch_with_request_and_init(request, init) + } else { + fetch_with_request_and_init(request, init) + } +} + +pub async fn fetch(request: &Request, init: &RequestInit) -> Result { + let js_response = JsFuture::from(js_fetch(request, init)) + .await + .map_err(Error::js_error)?; + + Ok(js_response.unchecked_into()) +} diff --git a/vendor/tonic-web-wasm-client/src/lib.rs b/vendor/tonic-web-wasm-client/src/lib.rs new file mode 100644 index 0000000..d184dac --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/lib.rs @@ -0,0 +1,57 @@ +//! Rust implementation of [`grpc-web`](https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md) protocol that allows +//! using [`tonic`](https://crates.io/crates/tonic) in browsers via webassembly. +//! +//! # Usage +//! +//! To use `tonic-web-wasm-client`, you need to add the following to your `Cargo.toml`: +//! +//! ```toml +//! [dependencies] +//! tonic-web-wasm-client = "0.8" +//! ``` +//! +//! ## Example +//! To use `tonic` gRPC clients in browser, compile your code with tonic's `transport` feature disabled (this will disable +//! the default transport layer of tonic). Then initialize the query client as follows: +//! +//! ```rust,ignore +//! use tonic_web_wasm_client::Client; +//! +//! let base_url = "http://localhost:9001"; // URL of the gRPC-web server +//! let query_client = QueryClient::new(Client::new(base_url)); // `QueryClient` is the client generated by tonic +//! +//! let response = query_client.status().await; // Execute your queries the same way as you do with defaule transport layer +//! ``` +//! +//! ## Building +//! +//! Since `tonic-web-wasm-client` is primarily intended for use in browsers, a crate that uses `tonic-web-wasm-client` +//! can only be built for `wasm32` target architectures: +//! +//! ```shell +//! cargo build --target wasm32-unknown-unknown +//! ``` +//! +//! Other option is to create a `.cargo/config.toml` in your crate repository and add a build target there: +//! +//! ```toml +//! [build] +//! target = "wasm32-unknown-unknown" +//! ``` +//! +//! ## Custom `Accept` header: +//! +//! This library allows you to set a custom `Accept` header for the requests. This can be useful if you need to specify +//! a different content type for the responses. But, be aware that if you set a custom `Accept` header, the client may +//! not be able to handle the response correctly. +mod abort_guard; +mod body_stream; +mod call; +mod client; +mod content_type; +mod error; +mod fetch; +pub mod options; +mod response_body; + +pub use self::{client::Client, error::Error, response_body::ResponseBody}; diff --git a/vendor/tonic-web-wasm-client/src/options/cache.rs b/vendor/tonic-web-wasm-client/src/options/cache.rs new file mode 100644 index 0000000..2bc6443 --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/options/cache.rs @@ -0,0 +1,47 @@ +use web_sys::RequestCache; + +/// Request's cache mode +#[derive(Debug, Clone, Copy, Default)] +pub enum Cache { + /// Fetch will inspect the HTTP cache on the way to the network. If the HTTP cache contains a matching fresh + /// response it will be returned. If the HTTP cache contains a matching stale-while-revalidate response it will be + /// returned, and a conditional network fetch will be made to update the entry in the HTTP cache. If the HTTP cache + /// contains a matching stale response, a conditional network fetch will be returned to update the entry in the HTTP + /// cache. Otherwise, a non-conditional network fetch will be returned to update the entry in the HTTP cache. + #[default] + Default, + + /// Fetch behaves as if there is no HTTP cache at all. + NoStore, + + /// Fetch behaves as if there is no HTTP cache on the way to the network. Ergo, it creates a normal request and + /// updates the HTTP cache with the response. + Reload, + + /// Fetch creates a conditional request if there is a response in the HTTP cache and a normal request otherwise. It + /// then updates the HTTP cache with the response. + NoCache, + + /// Fetch uses any response in the HTTP cache matching the request, not paying attention to staleness. If there was + /// no response, it creates a normal request and updates the HTTP cache with the response. + ForceCache, + + /// Fetch uses any response in the HTTP cache matching the request, not paying attention to staleness. If there was + /// no response, it returns a network error. (Can only be used when request’s mode is "same-origin". Any cached + /// redirects will be followed assuming request’s redirect mode is "follow" and the redirects do not violate + /// request’s mode.) + OnlyIfCached, +} + +impl From for RequestCache { + fn from(value: Cache) -> Self { + match value { + Cache::Default => RequestCache::Default, + Cache::NoStore => RequestCache::NoStore, + Cache::Reload => RequestCache::Reload, + Cache::NoCache => RequestCache::NoCache, + Cache::ForceCache => RequestCache::ForceCache, + Cache::OnlyIfCached => RequestCache::OnlyIfCached, + } + } +} diff --git a/vendor/tonic-web-wasm-client/src/options/credentials.rs b/vendor/tonic-web-wasm-client/src/options/credentials.rs new file mode 100644 index 0000000..c167ee9 --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/options/credentials.rs @@ -0,0 +1,26 @@ +use web_sys::RequestCredentials; + +/// Request's credential mode +#[derive(Debug, Clone, Copy, Default)] +pub enum Credentials { + /// Excludes credentials from this request, and causes any credentials sent back in the response to be ignored. + Omit, + + /// Include credentials with requests made to same-origin URLs, and use any credentials sent back in responses from + /// same-origin URLs. + #[default] + SameOrigin, + + /// Always includes credentials with this request, and always use any credentials sent back in the response. + Include, +} + +impl From for RequestCredentials { + fn from(credentials: Credentials) -> Self { + match credentials { + Credentials::Omit => RequestCredentials::Omit, + Credentials::SameOrigin => RequestCredentials::SameOrigin, + Credentials::Include => RequestCredentials::Include, + } + } +} diff --git a/vendor/tonic-web-wasm-client/src/options/mod.rs b/vendor/tonic-web-wasm-client/src/options/mod.rs new file mode 100644 index 0000000..8d4868c --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/options/mod.rs @@ -0,0 +1,141 @@ +//! Options for underlying `fetch` call +mod cache; +mod credentials; +mod mode; +mod redirect; +mod referrer_policy; + +use std::time::Duration; + +use crate::abort_guard::AbortGuard; + +pub use self::{ + cache::Cache, credentials::Credentials, mode::Mode, redirect::Redirect, + referrer_policy::ReferrerPolicy, +}; +use web_sys::RequestInit; + +/// Options for underlying `fetch` call +#[derive(Debug, Clone, Default)] +pub struct FetchOptions { + /// Request's cache mode + pub cache: Option, + + /// Request's credentials mode + pub credentials: Option, + + /// Requests's integrity + pub integrity: Option, + + /// Request's mode + pub mode: Option, + + /// Request's redirect mode + pub redirect: Option, + + /// Request's referrer + pub referrer: Option, + + /// Request's referrer policy + pub referrer_policy: Option, + + /// Request's timeout duration + pub timeout: Option, +} + +impl FetchOptions { + /// Create new `Options` with default values + pub fn new() -> Self { + Default::default() + } + + /// Set request's cache mode + pub fn cache(mut self, cache: Cache) -> Self { + self.cache = Some(cache); + self + } + + /// Set request's credentials mode + pub fn credentials(mut self, credentials: Credentials) -> Self { + self.credentials = Some(credentials); + self + } + + /// Set request's integrity + pub fn integrity(mut self, integrity: String) -> Self { + self.integrity = Some(integrity); + self + } + + /// Set request's mode + pub fn mode(mut self, mode: Mode) -> Self { + self.mode = Some(mode); + self + } + + /// Set request's redirect mode + pub fn redirect(mut self, redirect: Redirect) -> Self { + self.redirect = Some(redirect); + self + } + + /// Set request's referrer + pub fn referrer(mut self, referrer: String) -> Self { + self.referrer = Some(referrer); + self + } + + /// Set request's referrer policy + pub fn referrer_policy(mut self, referrer_policy: ReferrerPolicy) -> Self { + self.referrer_policy = Some(referrer_policy); + self + } + + /// Set request's timeout duration + pub fn timeout(mut self, timeout: Duration) -> Self { + self.timeout = Some(timeout); + self + } + + pub(crate) fn request_init(&self) -> Result<(RequestInit, AbortGuard), crate::Error> { + let init = RequestInit::new(); + + if let Some(cache) = self.cache { + init.set_cache(cache.into()); + } + + if let Some(credentials) = self.credentials { + init.set_credentials(credentials.into()); + } + + if let Some(ref integrity) = self.integrity { + init.set_integrity(integrity); + } + + if let Some(mode) = self.mode { + init.set_mode(mode.into()); + } + + if let Some(redirect) = self.redirect { + init.set_redirect(redirect.into()); + } + + if let Some(ref referrer) = self.referrer { + init.set_referrer(referrer); + } + + if let Some(referrer_policy) = self.referrer_policy { + init.set_referrer_policy(referrer_policy.into()); + } + + let mut abort = AbortGuard::new()?; + + if let Some(timeout) = self.timeout { + abort.timeout(timeout); + } + + init.set_signal(Some(&abort.signal())); + + Ok((init, abort)) + } +} diff --git a/vendor/tonic-web-wasm-client/src/options/mode.rs b/vendor/tonic-web-wasm-client/src/options/mode.rs new file mode 100644 index 0000000..8d0020b --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/options/mode.rs @@ -0,0 +1,33 @@ +use web_sys::RequestMode; + +/// Request's mode +#[derive(Debug, Clone, Copy, Default)] +pub enum Mode { + /// Used to ensure requests are made to same-origin URLs. Fetch will return a network error if the request is not + /// made to a same-origin URL. + SameOrigin, + + /// For requests whose response tainting gets set to "cors", makes the request a CORS request — in which case, fetch + /// will return a network error if the requested resource does not understand the CORS protocol, or if the requested + /// resource is one that intentionally does not participate in the CORS protocol. + Cors, + + /// Restricts requests to using CORS-safelisted methods and CORS-safelisted request-headers. Upon success, fetch + /// will return an opaque filtered response. + #[default] + NoCors, + + /// This is a special mode used only when navigating between documents. + Navigate, +} + +impl From for RequestMode { + fn from(value: Mode) -> Self { + match value { + Mode::SameOrigin => RequestMode::SameOrigin, + Mode::Cors => RequestMode::Cors, + Mode::NoCors => RequestMode::NoCors, + Mode::Navigate => RequestMode::Navigate, + } + } +} diff --git a/vendor/tonic-web-wasm-client/src/options/redirect.rs b/vendor/tonic-web-wasm-client/src/options/redirect.rs new file mode 100644 index 0000000..725a1ce --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/options/redirect.rs @@ -0,0 +1,27 @@ +use web_sys::RequestRedirect; + +/// Request's redirect mode +#[derive(Debug, Clone, Copy, Default)] +pub enum Redirect { + /// Follow all redirects incurred when fetching a resource. + #[default] + Follow, + + /// Return a network error when a request is met with a redirect. + Error, + + /// Retrieves an opaque-redirect filtered response when a request is met with a redirect, to allow a service worker + /// to replay the redirect offline. The response is otherwise indistinguishable from a network error, to not violate + /// atomic HTTP redirect handling. + Manual, +} + +impl From for RequestRedirect { + fn from(value: Redirect) -> Self { + match value { + Redirect::Follow => RequestRedirect::Follow, + Redirect::Error => RequestRedirect::Error, + Redirect::Manual => RequestRedirect::Manual, + } + } +} diff --git a/vendor/tonic-web-wasm-client/src/options/referrer_policy.rs b/vendor/tonic-web-wasm-client/src/options/referrer_policy.rs new file mode 100644 index 0000000..edd9bc5 --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/options/referrer_policy.rs @@ -0,0 +1,71 @@ +use web_sys::ReferrerPolicy as RequestReferrerPolicy; + +/// Request's referrer policy +#[derive(Debug, Clone, Copy, Default)] +pub enum ReferrerPolicy { + /// Corresponds to no referrer policy, causing a fallback to a referrer policy defined elsewhere, or in the case + /// where no such higher-level policy is available, falling back to the default referrer policy + None, + + /// Specifies that no referrer information is to be sent along with requests to any origin + NoReferrer, + + /// The "no-referrer-when-downgrade" policy sends a request’s full referrerURL stripped for use as a referrer for + /// requests: + /// + /// - whose referrerURL and current URL are both potentially trustworthy URLs, or + /// - whose referrerURL is a non-potentially trustworthy URL + NoReferrerWhenDowngrade, + + /// Specifies that only the ASCII serialization of the request’s referrerURL is sent as referrer information when + /// making both same-origin-referrer requests and cross-origin-referrer requests + Origin, + + /// Specifies that a request’s full referrerURL is sent as referrer information when making same-origin-referrer + /// requests, and only the ASCII serialization of the origin of the request’s referrerURL is sent as referrer + /// information when making cross-origin-referrer requests + OriginWhenCrossOrigin, + + /// specifies that a request’s full referrerURL is sent along for both same-origin-referrer requests and + /// cross-origin-referrer requests + UnsafeUrl, + + /// Specifies that a request’s full referrerURL is sent as referrer information when making same-origin-referrer + /// requests + SameOrigin, + + /// The "strict-origin" policy sends the ASCII serialization of the origin of the referrerURL for requests: + /// + /// - whose referrerURL and current URL are both potentially trustworthy URLs, or + /// - whose referrerURL is a non-potentially trustworthy URL. + StrictOrigin, + + /// Specifies that a request’s full referrerURL is sent as referrer information when making same-origin-referrer + /// requests, and only the ASCII serialization of the origin of the request’s referrerURL when making + /// cross-origin-referrer requests: + /// + /// - whose referrerURL and current URL are both potentially trustworthy URLs, or + /// - whose referrerURL is a non-potentially trustworthy URL + #[default] + StrictOriginWhenCrossOrigin, +} + +impl From for RequestReferrerPolicy { + fn from(value: ReferrerPolicy) -> Self { + match value { + ReferrerPolicy::None => RequestReferrerPolicy::None, + ReferrerPolicy::NoReferrer => RequestReferrerPolicy::NoReferrer, + ReferrerPolicy::NoReferrerWhenDowngrade => { + RequestReferrerPolicy::NoReferrerWhenDowngrade + } + ReferrerPolicy::Origin => RequestReferrerPolicy::Origin, + ReferrerPolicy::OriginWhenCrossOrigin => RequestReferrerPolicy::OriginWhenCrossOrigin, + ReferrerPolicy::UnsafeUrl => RequestReferrerPolicy::UnsafeUrl, + ReferrerPolicy::SameOrigin => RequestReferrerPolicy::SameOrigin, + ReferrerPolicy::StrictOrigin => RequestReferrerPolicy::StrictOrigin, + ReferrerPolicy::StrictOriginWhenCrossOrigin => { + RequestReferrerPolicy::StrictOriginWhenCrossOrigin + } + } + } +} diff --git a/vendor/tonic-web-wasm-client/src/response_body.rs b/vendor/tonic-web-wasm-client/src/response_body.rs new file mode 100644 index 0000000..934c05d --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/response_body.rs @@ -0,0 +1,344 @@ +use std::{ + ops::{Deref, DerefMut}, + pin::Pin, + task::{ready, Context, Poll}, +}; + +use base64::{prelude::BASE64_STANDARD, Engine}; +use byteorder::{BigEndian, ByteOrder}; +use bytes::{BufMut, Bytes, BytesMut}; +use http::{header::HeaderName, HeaderMap, HeaderValue}; +use http_body::Body; +use httparse::{Status, EMPTY_HEADER}; +use pin_project::pin_project; +use wasm_bindgen::JsCast; +use web_sys::ReadableStream; + +use crate::{abort_guard::AbortGuard, body_stream::BodyStream, content_type::Encoding, Error}; + +/// If 8th MSB of a frame is `0` for data and `1` for trailer +const TRAILER_BIT: u8 = 0b10000000; + +pub struct EncodedBytes { + encoding: Encoding, + raw_buf: BytesMut, + buf: BytesMut, +} + +impl EncodedBytes { + pub fn new(content_type: &str) -> Result { + Ok(Self { + encoding: Encoding::from_content_type(content_type)?, + raw_buf: BytesMut::new(), + buf: BytesMut::new(), + }) + } + + // This is to avoid passing a slice of bytes with a length that the base64 + // decoder would consider invalid. + #[inline] + fn max_decodable(&self) -> usize { + (self.raw_buf.len() / 4) * 4 + } + + fn decode_base64_chunk(&mut self) -> Result<(), Error> { + let index = self.max_decodable(); + + if self.raw_buf.len() >= index { + let decoded = BASE64_STANDARD + .decode(self.buf.split_to(index)) + .map(Bytes::from)?; + self.buf.put(decoded); + } + + Ok(()) + } + + fn append(&mut self, bytes: Bytes) -> Result<(), Error> { + match self.encoding { + Encoding::None => self.buf.put(bytes), + Encoding::Base64 => { + self.raw_buf.put(bytes); + self.decode_base64_chunk()?; + } + } + + Ok(()) + } + + fn take(&mut self, length: usize) -> BytesMut { + let new_buf = self.buf.split_off(length); + std::mem::replace(&mut self.buf, new_buf) + } +} + +impl Deref for EncodedBytes { + type Target = BytesMut; + + fn deref(&self) -> &Self::Target { + &self.buf + } +} + +impl DerefMut for EncodedBytes { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.buf + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReadState { + CompressionFlag, + DataLength, + Data(u32), + TrailerLength, + Trailer(u32), + Done, +} + +impl ReadState { + fn finished_data(&self) -> bool { + matches!(self, ReadState::TrailerLength) + || matches!(self, ReadState::Trailer(_)) + || matches!(self, ReadState::Done) + } +} + +/// Type to handle HTTP response +#[pin_project] +pub struct ResponseBody { + #[pin] + body_stream: BodyStream, + buf: EncodedBytes, + incomplete_data: BytesMut, + data: Option, + trailer: Option, + state: ReadState, + finished_stream: bool, + /// Whether the response headers carried `grpc-status`, i.e. the server sent a + /// "trailers-only" response (status in the HTTP headers, no body frames). + trailers_only: bool, +} + +impl ResponseBody { + pub(crate) fn new( + body_stream: ReadableStream, + content_type: &str, + abort: AbortGuard, + trailers_only: bool, + ) -> Result { + let body_stream = + wasm_streams::ReadableStream::from_raw(body_stream.unchecked_into()).into_stream(); + + Ok(Self { + body_stream: BodyStream::new(body_stream, abort), + buf: EncodedBytes::new(content_type)?, + incomplete_data: BytesMut::new(), + data: None, + trailer: None, + state: ReadState::CompressionFlag, + finished_stream: false, + trailers_only, + }) + } + + fn read_stream(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if self.finished_stream { + return Poll::Ready(Ok(())); + } + + let this = self.project(); + + match ready!(this.body_stream.poll_frame(cx)) { + Some(Ok(frame)) => { + if let Some(data) = frame.data_ref() { + if let Err(e) = this.buf.append(data.clone()) { + return Poll::Ready(Err(e)); + } + }; + + Poll::Ready(Ok(())) + } + Some(Err(e)) => Poll::Ready(Err(e)), + None => { + *this.finished_stream = true; + Poll::Ready(Ok(())) + } + } + } + + fn step(self: Pin<&mut Self>) -> Result<(), Error> { + let this = self.project(); + + loop { + match this.state { + ReadState::CompressionFlag => { + if this.buf.is_empty() { + // Can't read compression flag right now + return Ok(()); + } else { + let compression_flag = this.buf.take(1); + + if compression_flag[0] & TRAILER_BIT == 0 { + this.incomplete_data.unsplit(compression_flag); + *this.state = ReadState::DataLength; + } else { + *this.state = ReadState::TrailerLength; + } + } + } + ReadState::DataLength => { + if this.buf.len() < 4 { + // Can't read data length right now + return Ok(()); + } else { + let data_length_bytes = this.buf.take(4); + let data_length = BigEndian::read_u32(data_length_bytes.as_ref()); + + this.incomplete_data.unsplit(data_length_bytes); + *this.state = ReadState::Data(data_length); + } + } + ReadState::Data(data_length) => { + let data_length = *data_length as usize; + + if this.buf.len() < data_length { + // Can't read data right now + return Ok(()); + } else { + this.incomplete_data.unsplit(this.buf.take(data_length)); + + let new_data = this.incomplete_data.split(); + + if let Some(data) = this.data { + data.unsplit(new_data); + } else { + *this.data = Some(new_data); + } + + *this.state = ReadState::CompressionFlag; + } + } + ReadState::TrailerLength => { + if this.buf.len() < 4 { + // Can't read data length right now + return Ok(()); + } else { + let trailer_length_bytes = this.buf.take(4); + let trailer_length = BigEndian::read_u32(trailer_length_bytes.as_ref()); + *this.state = ReadState::Trailer(trailer_length); + } + } + ReadState::Trailer(trailer_length) => { + let trailer_length = *trailer_length as usize; + + if this.buf.len() < trailer_length { + // Can't read trailer right now + return Ok(()); + } else { + let mut trailer_bytes = this.buf.take(trailer_length); + trailer_bytes.put_u8(b'\n'); + + let mut trailers_buf = [EMPTY_HEADER; 64]; + let parsed_trailers = + match httparse::parse_headers(&trailer_bytes, &mut trailers_buf) + .map_err(|_| Error::HeaderParsingError)? + { + Status::Complete((_, headers)) => Ok(headers), + Status::Partial => Err(Error::HeaderParsingError), + }?; + + let mut trailers = HeaderMap::with_capacity(parsed_trailers.len()); + + for parsed_trailer in parsed_trailers { + let header_name = + HeaderName::from_bytes(parsed_trailer.name.as_bytes())?; + let header_value = HeaderValue::from_bytes(parsed_trailer.value)?; + trailers.insert(header_name, header_value); + } + + *this.trailer = Some(trailers); + + *this.state = ReadState::Done; + } + } + ReadState::Done => return Ok(()), + } + } + } +} + +impl Body for ResponseBody { + type Data = Bytes; + + type Error = Error; + + fn poll_frame( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + // Check if there's already some data in buffer and return that + if self.data.is_some() { + let data = self.data.take().unwrap(); + + return Poll::Ready(Some(Ok(http_body::Frame::data(data.freeze())))); + } + + // If reading data is finished return `None` + if self.state.finished_data() { + return Poll::Ready(None); + } + + loop { + // Read bytes from stream + if let Err(e) = ready!(self.as_mut().read_stream(cx)) { + return Poll::Ready(Some(Err(e))); + } + + // Step the state machine + if let Err(e) = self.as_mut().step() { + return Poll::Ready(Some(Err(e))); + } + + if self.data.is_some() { + // If data is available in buffer, return that + let data = self.data.take().unwrap(); + return Poll::Ready(Some(Ok(http_body::Frame::data(data.freeze())))); + } else if self.state.finished_data() { + // If we finished reading data continue return `None` + return Poll::Ready(None); + } else if self.finished_stream { + // A trailers-only response carries its status in the HTTP headers and has an empty + // body: the stream legitimately ends before any frame header. + if self.trailers_only + && self.state == ReadState::CompressionFlag + && self.buf.is_empty() + && self.incomplete_data.is_empty() + { + return Poll::Ready(None); + } + // If stream is finished but data is not finished return error + return Poll::Ready(Some(Err(Error::MalformedResponse))); + } + } + } +} + +impl Default for ResponseBody { + fn default() -> Self { + Self { + body_stream: BodyStream::empty(), + buf: EncodedBytes { + encoding: Encoding::None, + raw_buf: BytesMut::new(), + buf: BytesMut::new(), + }, + incomplete_data: BytesMut::new(), + data: None, + trailer: None, + state: ReadState::Done, + finished_stream: true, + trailers_only: false, + } + } +} diff --git a/vendor/tonic-web-wasm-client/trailers-only.patch b/vendor/tonic-web-wasm-client/trailers-only.patch new file mode 100644 index 0000000..7d465cd --- /dev/null +++ b/vendor/tonic-web-wasm-client/trailers-only.patch @@ -0,0 +1,68 @@ +Only in a: .cargo_vcs_info.json +Only in a: Cargo.toml.orig +diff -ru a/src/call.rs b/src/call.rs +--- a/src/call.rs 2006-07-24 02:21:28 ++++ b/src/call.rs 2026-10-13 19:20:48 +@@ -31,7 +31,8 @@ + let content_type = content_type.ok_or(Error::MissingContentTypeHeader)?; + let body_stream = response.body().ok_or(Error::MissingResponseBody)?; + +- let body = ResponseBody::new(body_stream, &content_type, abort)?; ++ let trailers_only = response.headers().has("grpc-status").unwrap_or(false); ++ let body = ResponseBody::new(body_stream, &content_type, abort, trailers_only)?; + + result.body(body).map_err(Into::into) + } +diff -ru a/src/response_body.rs b/src/response_body.rs +--- a/src/response_body.rs 2006-07-24 02:21:28 ++++ b/src/response_body.rs 2026-10-13 19:20:59 +@@ -115,6 +115,9 @@ + trailer: Option, + state: ReadState, + finished_stream: bool, ++ /// Whether the response headers carried `grpc-status`, i.e. the server sent a ++ /// "trailers-only" response (status in the HTTP headers, no body frames). ++ trailers_only: bool, + } + + impl ResponseBody { +@@ -122,6 +125,7 @@ + body_stream: ReadableStream, + content_type: &str, + abort: AbortGuard, ++ trailers_only: bool, + ) -> Result { + let body_stream = + wasm_streams::ReadableStream::from_raw(body_stream.unchecked_into()).into_stream(); +@@ -134,6 +138,7 @@ + trailer: None, + state: ReadState::CompressionFlag, + finished_stream: false, ++ trailers_only, + }) + } + +@@ -303,6 +308,15 @@ + // If we finished reading data continue return `None` + return Poll::Ready(None); + } else if self.finished_stream { ++ // A trailers-only response carries its status in the HTTP headers and has an empty ++ // body: the stream legitimately ends before any frame header. ++ if self.trailers_only ++ && self.state == ReadState::CompressionFlag ++ && self.buf.is_empty() ++ && self.incomplete_data.is_empty() ++ { ++ return Poll::Ready(None); ++ } + // If stream is finished but data is not finished return error + return Poll::Ready(Some(Err(Error::MalformedResponse))); + } +@@ -324,6 +338,7 @@ + trailer: None, + state: ReadState::Done, + finished_stream: true, ++ trailers_only: false, + } + } + } From 50389e9038597dc924aff4b85eeaf17207be1fe5 Mon Sep 17 00:00:00 2001 From: aratrika Date: Wed, 4 Nov 2026 17:34:58 -0500 Subject: [PATCH 3/8] Expose the Ironwood balance to JavaScript --- Cargo.lock | 1 + crates/webzjs-wallet/Cargo.toml | 3 + crates/webzjs-wallet/src/balance.rs | 73 +++++++++++++++++++ crates/webzjs-wallet/src/bindgen/wallet.rs | 26 +------ crates/webzjs-wallet/src/lib.rs | 1 + packages/web-wallet/src/hooks/useBalance.ts | 5 +- .../web-wallet/src/hooks/useWebzjsActions.ts | 6 +- 7 files changed, 91 insertions(+), 24 deletions(-) create mode 100644 crates/webzjs-wallet/src/balance.rs diff --git a/Cargo.lock b/Cargo.lock index dd9b563..64f67da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3561,6 +3561,7 @@ dependencies = [ "secrecy", "serde", "serde-wasm-bindgen", + "serde_json", "sha2 0.10.9", "subtle", "thiserror 1.0.69", diff --git a/crates/webzjs-wallet/Cargo.toml b/crates/webzjs-wallet/Cargo.toml index fdc395f..fdec6b6 100644 --- a/crates/webzjs-wallet/Cargo.toml +++ b/crates/webzjs-wallet/Cargo.toml @@ -102,5 +102,8 @@ serde.workspace = true postcard = { version = "1.0.10", features = ["alloc"] } serde-wasm-bindgen.workspace = true +[dev-dependencies] +serde_json = "1" + [lints] workspace = true diff --git a/crates/webzjs-wallet/src/balance.rs b/crates/webzjs-wallet/src/balance.rs new file mode 100644 index 0000000..cc1a267 --- /dev/null +++ b/crates/webzjs-wallet/src/balance.rs @@ -0,0 +1,73 @@ +//! The per-account balance reported to JavaScript. +//! +//! Kept outside the `bindgen` module (which only builds for the browser) so the conversion from the +//! backend's balance can be unit-tested natively. A pool that is missing here is a pool whose +//! funds a JavaScript caller cannot see: the wallet would report a zero balance for them. + +use serde::{Deserialize, Serialize}; + +// Only the browser bindings construct it outside tests. +#[cfg_attr(not(feature = "wasm"), allow(dead_code))] +#[derive(Debug, Serialize, Deserialize)] +pub struct AccountBalance { + pub sapling_balance: u64, + pub orchard_balance: u64, + /// Spendable value in the Ironwood pool, which receives new shielded value since NU6.3. + /// Absent (zero) in summaries produced before this field existed. + #[serde(default)] + pub ironwood_balance: u64, + pub unshielded_balance: u64, + /// Change from sent transactions waiting for mining confirmation + pub pending_change: u64, + /// Received notes waiting for required confirmations to become spendable + pub pending_spendable: u64, +} + +impl From for AccountBalance { + fn from(balance: zcash_client_backend::data_api::AccountBalance) -> Self { + AccountBalance { + sapling_balance: balance.sapling_balance().spendable_value().into(), + orchard_balance: balance.orchard_balance().spendable_value().into(), + ironwood_balance: balance.ironwood_balance().spendable_value().into(), + unshielded_balance: balance.unshielded_balance().spendable_value().into(), + pending_change: balance.change_pending_confirmation().into(), + pending_spendable: balance.value_pending_spendability().into(), + } + } +} + +#[cfg(test)] +mod tests { + use zcash_client_backend::data_api::{AccountBalance as BackendBalance, Balance}; + use zcash_protocol::value::{BalanceError, Zatoshis}; + + use super::AccountBalance; + + #[test] + fn ironwood_value_reaches_the_javascript_balance() { + let mut backend = BackendBalance::ZERO; + backend + .with_ironwood_balance_mut::<_, BalanceError>(|b: &mut Balance| { + b.add_spendable_value(Zatoshis::const_from_u64(12_345)) + }) + .unwrap(); + + let js = AccountBalance::from(backend); + + assert_eq!(js.ironwood_balance, 12_345); + // The other pools are untouched, so Ironwood is neither double counted nor dropped. + assert_eq!(js.orchard_balance, 0); + assert_eq!(js.sapling_balance, 0); + } + + #[test] + fn older_serialized_balances_without_the_ironwood_field_still_load() { + let json = r#"{"sapling_balance":1,"orchard_balance":2,"unshielded_balance":3, + "pending_change":4,"pending_spendable":5}"#; + let b: AccountBalance = serde_json::from_str(json).unwrap(); + assert_eq!( + (b.sapling_balance, b.orchard_balance, b.ironwood_balance), + (1, 2, 0) + ); + } +} diff --git a/crates/webzjs-wallet/src/bindgen/wallet.rs b/crates/webzjs-wallet/src/bindgen/wallet.rs index 6d525f8..89460fc 100644 --- a/crates/webzjs-wallet/src/bindgen/wallet.rs +++ b/crates/webzjs-wallet/src/bindgen/wallet.rs @@ -672,6 +672,8 @@ pub struct WalletSummary { // scan_progress: Option>, pub next_sapling_subtree_index: u64, pub next_orchard_subtree_index: u64, + #[serde(default)] + pub next_ironwood_subtree_index: u64, } #[wasm_bindgen] @@ -682,28 +684,7 @@ impl WalletSummary { } } -#[derive(Debug, Serialize, Deserialize)] -pub struct AccountBalance { - pub sapling_balance: u64, - pub orchard_balance: u64, - pub unshielded_balance: u64, - /// Change from sent transactions waiting for mining confirmation - pub pending_change: u64, - /// Received notes waiting for required confirmations to become spendable - pub pending_spendable: u64, -} - -impl From for AccountBalance { - fn from(balance: zcash_client_backend::data_api::AccountBalance) -> Self { - AccountBalance { - sapling_balance: balance.sapling_balance().spendable_value().into(), - orchard_balance: balance.orchard_balance().spendable_value().into(), - unshielded_balance: balance.unshielded_balance().spendable_value().into(), - pending_change: balance.change_pending_confirmation().into(), - pending_spendable: balance.value_pending_spendability().into(), - } - } -} +pub use crate::balance::AccountBalance; impl From> for WalletSummary where @@ -724,6 +705,7 @@ where fully_scanned_height: summary.fully_scanned_height().into(), next_sapling_subtree_index: summary.next_sapling_subtree_index(), next_orchard_subtree_index: summary.next_orchard_subtree_index(), + next_ironwood_subtree_index: summary.next_ironwood_subtree_index(), } } } diff --git a/crates/webzjs-wallet/src/lib.rs b/crates/webzjs-wallet/src/lib.rs index d6a2c90..f07a35c 100644 --- a/crates/webzjs-wallet/src/lib.rs +++ b/crates/webzjs-wallet/src/lib.rs @@ -6,6 +6,7 @@ #[cfg(feature = "wasm")] pub mod bindgen; +mod balance; mod chain_params; mod error; pub mod init; diff --git a/packages/web-wallet/src/hooks/useBalance.ts b/packages/web-wallet/src/hooks/useBalance.ts index cb0d60b..8a934c4 100644 --- a/packages/web-wallet/src/hooks/useBalance.ts +++ b/packages/web-wallet/src/hooks/useBalance.ts @@ -52,11 +52,14 @@ const useBalance = () => { let livePendingSpendable = 0; let liveSapling = 0; let liveOrchard = 0; + let liveIronwood = 0; if (activeBalanceReport) { liveSapling = activeBalanceReport[1].sapling_balance || 0; liveOrchard = activeBalanceReport[1].orchard_balance || 0; - confirmedShielded = liveSapling + liveOrchard; + // Ironwood receives new shielded value since NU6.3; it must be counted or funds show as 0. + liveIronwood = activeBalanceReport[1].ironwood_balance || 0; + confirmedShielded = liveSapling + liveOrchard + liveIronwood; confirmedUnshielded = activeBalanceReport[1].unshielded_balance || 0; livePendingChange = activeBalanceReport[1].pending_change || 0; livePendingSpendable = activeBalanceReport[1].pending_spendable || 0; diff --git a/packages/web-wallet/src/hooks/useWebzjsActions.ts b/packages/web-wallet/src/hooks/useWebzjsActions.ts index 04aa31d..f6ed40d 100644 --- a/packages/web-wallet/src/hooks/useWebzjsActions.ts +++ b/packages/web-wallet/src/hooks/useWebzjsActions.ts @@ -138,13 +138,17 @@ export function useWebZjsActions(): WebzjsActions { const cacheBalanceInSnap = useCallback(async (balanceReport: { sapling_balance?: number; orchard_balance?: number; + ironwood_balance?: number; unshielded_balance?: number; pending_change?: number; pending_spendable?: number; } | null, force = false) => { if (!balanceReport) return; - const confirmed = (balanceReport.sapling_balance ?? 0) + (balanceReport.orchard_balance ?? 0); + const confirmed = + (balanceReport.sapling_balance ?? 0) + + (balanceReport.orchard_balance ?? 0) + + (balanceReport.ironwood_balance ?? 0); const unshielded = balanceReport.unshielded_balance ?? 0; const pending = (balanceReport.pending_change ?? 0) + (balanceReport.pending_spendable ?? 0); const total = confirmed + unshielded + pending; From d22fe76c02610a63575f438a1c1cf590f84df487 Mon Sep 17 00:00:00 2001 From: aratrika Date: Wed, 4 Nov 2026 17:34:58 -0500 Subject: [PATCH 4/8] Depend on the NU7 zcash_client_memory by git revision Replace the local path override with a pinned git revision of the zcash_client_memory NU7 port, so the workspace builds from a clean clone. Repoint it at red-dev-inc/zcash_client_memory once that port merges. --- Cargo.lock | 1 + Cargo.toml | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 64f67da..16beb42 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3859,6 +3859,7 @@ dependencies = [ [[package]] name = "zcash_client_memory" version = "0.0.0" +source = "git+https://github.com/ETIM-PAUL/zcash_client_memory?rev=24e3be417ccfbe4d10d9730aa19e0261385f70d4#24e3be417ccfbe4d10d9730aa19e0261385f70d4" dependencies = [ "async-trait", "bip32", diff --git a/Cargo.toml b/Cargo.toml index 39d5590..426663a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,11 +34,11 @@ tokio_with_wasm = { version = "0.7.1", features = ["rt", "rt-multi-thread", "syn ## Zcash dependencies: librustzcash NU7 pre-releases from crates.io (pinned exactly). NU7 is active on ## testnet from block 4,465,026 with consensus branch id 0x77190AD9; mainnet has no NU7 height yet. -## `zcash_client_memory` is a local path override while its NU7 port is developed; switch it to the -## fork's git rev before any PR, CI run or release. +## `zcash_client_memory` is pinned to its NU7 port (open as a PR on red-dev-inc/zcash_client_memory); +## repoint it at red-dev-inc once that PR merges. zcash_keys = { version = "=0.17.0-pre.1", features = ["transparent-inputs", "orchard", "sapling", "unstable"] } zcash_client_backend = { version = "=0.25.0-pre.1", default-features = false, features = ["sync", "lightwalletd-tonic", "orchard", "zeroize"] } -zcash_client_memory = { path = "../zcash_client_memory", features = ["orchard", "transparent-inputs"] } +zcash_client_memory = { git = "https://github.com/ETIM-PAUL/zcash_client_memory", rev = "24e3be417ccfbe4d10d9730aa19e0261385f70d4", features = ["orchard", "transparent-inputs"] } zcash_primitives = { version = "=0.31.0-pre.1" } zcash_transparent = { version = "=0.11.0-pre.1", default-features = false } zcash_address = { version = "=0.14.0-pre.1" } From c0457174ecb99c67a9d081fba0be54f50d0cf012 Mon Sep 17 00:00:00 2001 From: aratrika Date: Wed, 4 Nov 2026 17:34:58 -0500 Subject: [PATCH 5/8] feat(nu7): portable keys, v1->v2 migration, final NU7 crates, reliable sync --- Cargo.lock | 101 +++++------- Cargo.toml | 30 ++-- crates/webzjs-keys/src/error.rs | 2 + crates/webzjs-keys/src/keys.rs | 95 +++++++++++ packages/snap/snap.config.ts | 5 + packages/snap/snap.manifest.json | 8 +- packages/snap/src/config.ts | 6 + packages/snap/src/index.tsx | 8 + packages/snap/src/rpc/exportSecret.tsx | 110 +++++++++++++ packages/snap/src/rpc/getSeedFingerprint.tsx | 4 +- packages/snap/src/rpc/getViewingKey.tsx | 9 +- packages/snap/src/rpc/migrate.tsx | 70 ++++++++ packages/snap/src/rpc/signPczt.tsx | 7 +- packages/snap/src/types.ts | 3 + packages/snap/src/utils/getSeed.ts | 68 +++++++- packages/web-wallet/src/config/constants.ts | 19 ++- .../web-wallet/src/context/WebzjsContext.tsx | 8 +- packages/web-wallet/src/hooks/useMigration.ts | 153 ++++++++++++++++++ .../web-wallet/src/hooks/useWebzjsActions.ts | 93 +++++++---- .../web-wallet/src/pages/AccountSummary.tsx | 89 +++++++++- 20 files changed, 754 insertions(+), 134 deletions(-) create mode 100644 packages/snap/src/config.ts create mode 100644 packages/snap/src/rpc/exportSecret.tsx create mode 100644 packages/snap/src/rpc/migrate.tsx create mode 100644 packages/web-wallet/src/hooks/useMigration.ts diff --git a/Cargo.lock b/Cargo.lock index 16beb42..10bae53 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -637,11 +637,11 @@ dependencies = [ [[package]] name = "daggy" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70def8d72740e44d9f676d8dab2c933a236663d86dd24319b57a2bed4d694774" +checksum = "804169db156b21258a2545757336922d93dfa229892c75911a0ad141aa0ff241" dependencies = [ - "petgraph 0.7.1", + "petgraph", ] [[package]] @@ -1155,7 +1155,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.13.0", + "indexmap", "slab", "tokio", "tokio-util", @@ -1209,7 +1209,7 @@ dependencies = [ "ff", "group", "halo2_legacy_pdqsort", - "indexmap 2.13.0", + "indexmap", "maybe-rayon", "pasta_curves", "rand 0.10.3", @@ -1226,12 +1226,6 @@ dependencies = [ "byteorder", ] -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - [[package]] name = "hashbrown" version = "0.15.5" @@ -1442,16 +1436,6 @@ dependencies = [ "web-sys", ] -[[package]] -name = "indexmap" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", -] - [[package]] name = "indexmap" version = "2.13.0" @@ -1885,9 +1869,9 @@ dependencies = [ [[package]] name = "pczt" -version = "0.10.0-pre.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbb353f91d5caf22e351cc75e6c531b2a74b7cfbef5274c6ce7d1859a0ab30b4" +checksum = "c6b48fdfdc5c6b58a00514f9b2504fae98f7cde9f741f3477264b411cd69134d" dependencies = [ "blake2b_simd", "bls12_381", @@ -1919,16 +1903,6 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" -[[package]] -name = "petgraph" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772" -dependencies = [ - "fixedbitset", - "indexmap 2.13.0", -] - [[package]] name = "petgraph" version = "0.8.3" @@ -1937,7 +1911,7 @@ checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" dependencies = [ "fixedbitset", "hashbrown 0.15.5", - "indexmap 2.13.0", + "indexmap", ] [[package]] @@ -2102,7 +2076,7 @@ dependencies = [ "itertools", "log", "multimap", - "petgraph 0.8.3", + "petgraph", "prettyplease", "prost", "prost-types", @@ -2474,22 +2448,22 @@ dependencies = [ [[package]] name = "schemerz" -version = "0.2.0" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e82960ac11ccabd77d53c933532612079e01205b5873ec5095f4b3426493434" +checksum = "85a66556ccb695e22d08620703a9526806e533de0094fe993896932592ba3a6c" dependencies = [ "daggy", - "indexmap 1.9.3", + "indexmap", "log", - "thiserror 1.0.69", + "thiserror 2.0.18", "uuid", ] [[package]] name = "schemerz-rusqlite" -version = "0.370.0" +version = "0.371.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca6df8a13fb3b7914f94ac6579bd5e76b9292f135886e6becc3525f9e5116827" +checksum = "c29c257d3233449db8224f7f0fcf51373b59755aec356d8648dc694804132d60" dependencies = [ "rusqlite", "schemerz", @@ -3064,7 +3038,7 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", - "indexmap 2.13.0", + "indexmap", "pin-project-lite", "slab", "sync_wrapper", @@ -3789,9 +3763,9 @@ dependencies = [ [[package]] name = "zcash_address" -version = "0.14.0-pre.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db56348a60fb82895c37475a4a3a39e9eaf47bc4267c05cad42f83b0771b18c8" +checksum = "372023d82d978ab3f27b8e9f7f9b56fc61f3c9cc2b72ec2f8e3bbb278497e474" dependencies = [ "bech32", "bs58", @@ -3803,9 +3777,9 @@ dependencies = [ [[package]] name = "zcash_client_backend" -version = "0.25.0-pre.1" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "081a6a497f0016a4de2ef9f45cbca6d271037035f5e7614b2c16363f8c3b4a84" +checksum = "27228f279facfd6b9dd015cea88538020c30f87c8a4aa59e8ed85808d81febb5" dependencies = [ "async-trait", "base64", @@ -3859,7 +3833,7 @@ dependencies = [ [[package]] name = "zcash_client_memory" version = "0.0.0" -source = "git+https://github.com/ETIM-PAUL/zcash_client_memory?rev=24e3be417ccfbe4d10d9730aa19e0261385f70d4#24e3be417ccfbe4d10d9730aa19e0261385f70d4" +source = "git+https://github.com/red-dev-inc/zcash_client_memory?branch=feat%2Fsnap-nu7#b4c8f0d33c65c5bab4155ddeba4f201ea2d28c43" dependencies = [ "async-trait", "bip32", @@ -3901,9 +3875,9 @@ dependencies = [ [[package]] name = "zcash_client_sqlite" -version = "0.23.0-pre.1" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e59202fe720b383d4340318785add4ae1870c82cd950159758d96f4f875c0fbd" +checksum = "d1d85c3c832c8554da6ed6114c81afef84f7dbb84c2279a3889277a8d2225019" dependencies = [ "bitflags", "bs58", @@ -3959,9 +3933,9 @@ dependencies = [ [[package]] name = "zcash_keys" -version = "0.17.0-pre.1" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96e6eaf9ae82ea0e40aadd35df0778f37125fb3405a25e2b1f0d6b45a9884e14" +checksum = "6e35ad8dafd173b0465e5963b520b241f497d978319faed46547bd81f403fa98" dependencies = [ "bech32", "bip32", @@ -4002,9 +3976,9 @@ dependencies = [ [[package]] name = "zcash_pool_migration" -version = "0.2.0-pre.1" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02dba1fbb3fa84188fa248f5b282e9226434f1608b48d0f1f3139f269d0c7cd2" +checksum = "5b5211aea88f920316150527eda23efe419b507d03c8dda9e655bfbf22bfa68d" dependencies = [ "blake2b_simd", "corez", @@ -4024,9 +3998,9 @@ dependencies = [ [[package]] name = "zcash_primitives" -version = "0.31.0-pre.1" +version = "0.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0329bee4107df1aaaaaab365bdf94fcc0d9a185165c4675dff2397c5af7d13f4" +checksum = "50ad9ffda3d83c35e401b2f914980762f201ab40525cb0aab67b8d91e180e7df" dependencies = [ "blake2b_simd", "corez", @@ -4053,9 +4027,9 @@ dependencies = [ [[package]] name = "zcash_proofs" -version = "0.31.0-pre.1" +version = "0.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cc30f2c394b8558269a13f5c9b4188eae7b9b5b659afdc60d1c6fcd861d2311" +checksum = "f2ec0c92cb3bca94f8d875260b09eaad8f97eb8ebe7b5ca099ad0ae10eb19d84" dependencies = [ "bellman", "blake2b_simd", @@ -4074,9 +4048,9 @@ dependencies = [ [[package]] name = "zcash_protocol" -version = "0.11.0-pre.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98aeb25d9f741670fd63f9dbf76bca87d87c4fd32e1a7469bc4c43c4d0af09f7" +checksum = "266da226b6be42545b9fc299f1def9f5e525764845b8afa874f167155de943ba" dependencies = [ "corez", "document-features", @@ -4113,9 +4087,9 @@ dependencies = [ [[package]] name = "zcash_transparent" -version = "0.11.0-pre.1" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3b7dfde65266233ad2babba2f115d41a786e0270cac1a4644e26b9992dcf375" +checksum = "eb804d0179500e9543502dd6dfa178826617107897e6fe171241e5b767b7a0dd" dependencies = [ "bip32", "bs58", @@ -4128,7 +4102,6 @@ dependencies = [ "secp256k1", "sha2 0.10.9", "subtle", - "zcash_address", "zcash_encoding", "zcash_protocol", "zcash_script", @@ -4192,9 +4165,9 @@ dependencies = [ [[package]] name = "zip321" -version = "0.10.0-pre.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60e43f36a390a70ff428ee900f50c146fb43277028502717fbbb44918e575488" +checksum = "e6960586c9e1a91c734e9175913e22b88f2df11617f1decdefb15dd971ffd383" dependencies = [ "base64", "nom", diff --git a/Cargo.toml b/Cargo.toml index 426663a..d97963e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,21 +32,21 @@ 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: librustzcash NU7 pre-releases from crates.io (pinned exactly). NU7 is active on -## testnet from block 4,465,026 with consensus branch id 0x77190AD9; mainnet has no NU7 height yet. -## `zcash_client_memory` is pinned to its NU7 port (open as a PR on red-dev-inc/zcash_client_memory); -## repoint it at red-dev-inc once that PR merges. -zcash_keys = { version = "=0.17.0-pre.1", features = ["transparent-inputs", "orchard", "sapling", "unstable"] } -zcash_client_backend = { version = "=0.25.0-pre.1", default-features = false, features = ["sync", "lightwalletd-tonic", "orchard", "zeroize"] } -zcash_client_memory = { git = "https://github.com/ETIM-PAUL/zcash_client_memory", rev = "24e3be417ccfbe4d10d9730aa19e0261385f70d4", features = ["orchard", "transparent-inputs"] } -zcash_primitives = { version = "=0.31.0-pre.1" } -zcash_transparent = { version = "=0.11.0-pre.1", default-features = false } -zcash_address = { version = "=0.14.0-pre.1" } -zcash_proofs = { version = "=0.31.0-pre.1", default-features = false, features = ["bundled-prover", "multicore"] } -zip321 = { version = "=0.10.0-pre.1" } +## Zcash dependencies: librustzcash NU7 final stable crates from crates.io (pinned exactly). NU7 is +## active on testnet from block 4,465,026 (branch id 0x77190AD9); mainnet has no NU7 height yet. +## `zcash_client_memory` is our NU7 store branch (red-dev-inc `feat/snap-nu7`). 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", branch = "feat/snap-nu7", 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-pre.0", default-features = false } -pczt = { version = "=0.10.0-pre.1", default-features = false, features = ["orchard", "sapling", "transparent"] } +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"] } @@ -56,7 +56,7 @@ tonic = { version = "0.14", default-features = false } # Used in Native tests -zcash_client_sqlite = { version = "=0.23.0-pre.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. diff --git a/crates/webzjs-keys/src/error.rs b/crates/webzjs-keys/src/error.rs index 04d8fb8..8b792a8 100644 --- a/crates/webzjs-keys/src/error.rs +++ b/crates/webzjs-keys/src/error.rs @@ -22,6 +22,8 @@ pub enum Error { SeedFingerprint, #[error("Failed to derive transparent address from UFVK")] TransparentAddressDerivation, + #[error("BIP-39 error: {0}")] + Bip39(String), } impl From for JsValue { diff --git a/crates/webzjs-keys/src/keys.rs b/crates/webzjs-keys/src/keys.rs index 75fd006..9ba65a1 100644 --- a/crates/webzjs-keys/src/keys.rs +++ b/crates/webzjs-keys/src/keys.rs @@ -190,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 { + let network = Network::from_str(network)?; + let (ua, _) = self + .inner + .default_address(zcash_keys::keys::UnifiedAddressRequest::ALLOW_ALL) + .map_err(|_| Error::TransparentAddressDerivation)?; + Ok(ua.encode(&network)) + } } impl UnifiedFullViewingKey { @@ -213,3 +224,87 @@ pub fn generate_seed_phrase() -> String { let mnemonic = >::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 { + let mnemonic = >::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, Error> { + let mnemonic = + >::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"); + } +} diff --git a/packages/snap/snap.config.ts b/packages/snap/snap.config.ts index f9ebf0f..8e5d297 100644 --- a/packages/snap/snap.config.ts +++ b/packages/snap/snap.config.ts @@ -11,6 +11,11 @@ const config: SnapConfig = { return config; }, input: resolve(__dirname, 'src/index.tsx'), + // Injected into the bundle at build time. NETWORK selects main/testnet derivation; + // build with `NETWORK=test` to target testnet (must match the web wallet's build). + environment: { + NETWORK: process.env.NETWORK ?? 'main', + }, server: { port: 8080, }, diff --git a/packages/snap/snap.manifest.json b/packages/snap/snap.manifest.json index 4c7756e..e1096a4 100644 --- a/packages/snap/snap.manifest.json +++ b/packages/snap/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/ZcashCommunityGrants/WebZjs.git" }, "source": { - "shasum": "omUMy4M7iFO0+mqcG6rGv5/bnDvRbhZaC+qRvX0D22I=", + "shasum": "CAGcWn2ZLrGZthcSubOcsW/tHcOpga3uF3gYpwCKMoU=", "location": { "npm": { "filePath": "dist/bundle.js", @@ -22,7 +22,11 @@ "endowment:lifecycle-hooks": {}, "endowment:webassembly": {}, "endowment:rpc": { - "allowedOrigins": ["https://webzjs.red.dev"] + "allowedOrigins": [ + "https://webzjs.red.dev", + "http://localhost:3000", + "http://app-provider.localhost:3000" + ] }, "snap_getBip44Entropy": [ { diff --git a/packages/snap/src/config.ts b/packages/snap/src/config.ts new file mode 100644 index 0000000..4bc7fba --- /dev/null +++ b/packages/snap/src/config.ts @@ -0,0 +1,6 @@ +/** + * Zcash network this Snap targets. Defaults to `main`; build with `NETWORK=test` for + * testnet. The web wallet MUST target the same network or derived keys won't align. + */ +export const NETWORK: 'main' | 'test' = + process.env.NETWORK === 'test' ? 'test' : 'main'; diff --git a/packages/snap/src/index.tsx b/packages/snap/src/index.tsx index 2d32b1c..61851f5 100644 --- a/packages/snap/src/index.tsx +++ b/packages/snap/src/index.tsx @@ -14,6 +14,8 @@ import { signPczt } from './rpc/signPczt' import { assert, object, number, optional, string } from 'superstruct'; import { getSeedFingerprint } from './rpc/getSeedFingerprint'; +import { exportZcashSecret } from './rpc/exportSecret'; +import { getPortableAddress, completeMigration } from './rpc/migrate'; import type { OnInstallHandler } from "@metamask/snaps-sdk"; import { installDialog } from './utils/dialogs'; @@ -47,6 +49,12 @@ export const onRpcRequest: OnRpcRequestHandler = async ({ request, origin }) => return await signPczt(request.params as SignPcztParams, origin); case 'getSeedFingerprint': return await getSeedFingerprint(); + case 'exportZcashSecret': + return await exportZcashSecret(); + case 'getPortableAddress': + return await getPortableAddress(); + case 'completeMigration': + return await completeMigration(); case 'setBirthdayBlock': assert(request.params, object({ latestBlock: optional(number()) })); return await setBirthdayBlock(request.params as SetBirthdayBlockParams); diff --git a/packages/snap/src/rpc/exportSecret.tsx b/packages/snap/src/rpc/exportSecret.tsx new file mode 100644 index 0000000..2fb287a --- /dev/null +++ b/packages/snap/src/rpc/exportSecret.tsx @@ -0,0 +1,110 @@ +import { UnifiedSpendingKey } from '@zcashcommunitygrants/webzjs-keys'; +import { + getMnemonic, + getSeed, + getActiveDerivationVersion, + PORTABLE_DERIVATION_VERSION, + LEGACY_DERIVATION_VERSION, +} from '../utils/getSeed'; +import { + Box, + Bold, + Copyable, + Divider, + Heading, + Text, +} from '@metamask/snaps-sdk/jsx'; +import { NETWORK } from '../config'; + +type Network = 'main' | 'test'; + +/** + * Reveal the account's portable (v2) BIP-39 phrase + viewing key for import into a + * standard Zcash wallet. SECURITY: shown only in the Snap dialog, never returned to the dApp. + */ +export async function exportZcashSecret( + network: Network = NETWORK, + accountIndex: number = 0, +): Promise { + // 1. Confirm-to-reveal. No secret is derived or shown until the user approves. + const confirmed = await snap.request({ + method: 'snap_dialog', + params: { + type: 'confirmation', + content: ( + + Reveal your Zcash recovery phrase? + + + You are about to reveal the secret recovery phrase for your Zcash + wallet. Make sure no one can see your screen. + + + + This is NOT your MetaMask Secret Recovery Phrase. + {' '} + It is a separate phrase for your Zcash wallet only — back it up + separately. + + + Anyone with this phrase can spend your Zcash funds. Never share it. + Zcash Community Grants will never ask you for it. + + + ), + }, + }); + + if (!confirmed) { + // User declined — nothing was derived or released. + return false; + } + + // 2. Derive the portable (v2) secret. Export always reveals the portable + // account, since the legacy (v1) account cannot be reproduced from a mnemonic. + const mnemonic = await getMnemonic(); + const seed = await getSeed(PORTABLE_DERIVATION_VERSION); + const spendingKey = new UnifiedSpendingKey(network, seed, accountIndex); + const viewingKey = spendingKey.to_unified_full_viewing_key().encode(network); + + // If the account hasn't migrated yet, its funds still live in the legacy + // account — warn so the user doesn't think an empty import means lost money. + const onLegacy = + (await getActiveDerivationVersion()) === LEGACY_DERIVATION_VERSION; + + // 3. Reveal inside the Snap dialog. The phrase is blurred until tapped. + await snap.request({ + method: 'snap_dialog', + params: { + type: 'alert', + content: ( + + Your Zcash wallet recovery phrase + + Import these 24 words into another Zcash wallet (e.g. Zkool or Zodl) + to access this wallet there. Keep them secret and safe. + + + {onLegacy ? ( + + Note: this is your portable Zcash account. If you have + existing funds, they are still in a separate legacy account and + must be migrated to this one before they appear here. + + ) : ( + + )} + + + Viewing key (watch-only — lets another wallet see this account's + balance, but not spend): + + + + ), + }, + }); + + // Never return the secret to the dApp — only an acknowledgement. + return true; +} diff --git a/packages/snap/src/rpc/getSeedFingerprint.tsx b/packages/snap/src/rpc/getSeedFingerprint.tsx index e3e80f0..53485c3 100644 --- a/packages/snap/src/rpc/getSeedFingerprint.tsx +++ b/packages/snap/src/rpc/getSeedFingerprint.tsx @@ -1,11 +1,11 @@ import { SeedFingerprint, } from '@zcashcommunitygrants/webzjs-keys'; -import { getSeed } from '../utils/getSeed'; +import { getSeed, getActiveDerivationVersion } from '../utils/getSeed'; export async function getSeedFingerprint(): Promise { - const seed = await getSeed(); + const seed = await getSeed(await getActiveDerivationVersion()); const seedFingerprint = new SeedFingerprint(seed); diff --git a/packages/snap/src/rpc/getViewingKey.tsx b/packages/snap/src/rpc/getViewingKey.tsx index 5f804fb..2ae3302 100644 --- a/packages/snap/src/rpc/getViewingKey.tsx +++ b/packages/snap/src/rpc/getViewingKey.tsx @@ -1,18 +1,19 @@ import { UnifiedSpendingKey } from '@zcashcommunitygrants/webzjs-keys'; -import { getSeed } from '../utils/getSeed'; +import { getSeed, getActiveDerivationVersion } from '../utils/getSeed'; import { Box, Copyable, Divider, Heading, Text } from '@metamask/snaps-sdk/jsx'; +import { NETWORK } from '../config'; type Network = 'main' | 'test'; export async function getViewingKey( origin: string, - network: Network = 'main', + network: Network = NETWORK, accountIndex: number = 0, ) { try { - // Retrieve the BIP-44 entropy from MetaMask - const seed = await getSeed(); + // Retrieve the seed for this account's active derivation version + const seed = await getSeed(await getActiveDerivationVersion()); // Generate the UnifiedSpendingKey and obtain the Viewing Key const spendingKey = new UnifiedSpendingKey(network, seed, accountIndex); diff --git a/packages/snap/src/rpc/migrate.tsx b/packages/snap/src/rpc/migrate.tsx new file mode 100644 index 0000000..2f092cc --- /dev/null +++ b/packages/snap/src/rpc/migrate.tsx @@ -0,0 +1,70 @@ +import { UnifiedSpendingKey } from '@zcashcommunitygrants/webzjs-keys'; +import { getSeed, PORTABLE_DERIVATION_VERSION } from '../utils/getSeed'; +import { Box, Bold, Divider, Heading, Text } from '@metamask/snaps-sdk/jsx'; +import { NETWORK } from '../config'; + +type Network = 'main' | 'test'; + +/** + * Default unified (shielded) address of the portable (v2) account — the destination + * for a v1 → v2 migration sweep. Public, so safe to return to the dApp. + */ +export async function getPortableAddress( + network: Network = NETWORK, + accountIndex: number = 0, +): Promise { + const seed = await getSeed(PORTABLE_DERIVATION_VERSION); + const spendingKey = new UnifiedSpendingKey(network, seed, accountIndex); + return spendingKey + .to_unified_full_viewing_key() + .get_unified_address(network); +} + +/** + * Stamp `derivationVersion: 2` into Snap state to commit the portable switch. Gated by a + * confirmation; call only AFTER the sweep is broadcast, else v2 shows empty while funds sit in v1. + */ +export async function completeMigration(): Promise { + const confirmed = await snap.request({ + method: 'snap_dialog', + params: { + type: 'confirmation', + content: ( + + Switch to your portable Zcash account? + + + Confirm only after your funds have finished moving to the portable + account. From now on this wallet will use the portable account, whose + recovery phrase you can export. + + + Do not confirm if the migration transaction has not been sent. + + + ), + }, + }); + + if (!confirmed) { + return false; + } + + const existing = (await snap.request({ + method: 'snap_manageState', + params: { operation: 'get' }, + })) as Record | null; + + await snap.request({ + method: 'snap_manageState', + params: { + operation: 'update', + newState: { + ...existing, + derivationVersion: PORTABLE_DERIVATION_VERSION, + }, + }, + }); + + return true; +} diff --git a/packages/snap/src/rpc/signPczt.tsx b/packages/snap/src/rpc/signPczt.tsx index 8f9bb43..24ece68 100644 --- a/packages/snap/src/rpc/signPczt.tsx +++ b/packages/snap/src/rpc/signPczt.tsx @@ -14,11 +14,10 @@ import { pczt_sign, Pczt, } from '@zcashcommunitygrants/webzjs-keys'; -import { getSeed } from '../utils/getSeed'; +import { getSeed, getActiveDerivationVersion } from '../utils/getSeed'; import { SignPcztParams } from 'src/types'; +import { NETWORK } from '../config'; -/** Network the Snap operates on (coinType 133 = Zcash mainnet). */ -const NETWORK = 'main'; const ZATS_PER_ZEC = 100_000_000n; /** @@ -93,7 +92,7 @@ export async function signPczt( const pcztUint8Array = new Uint8Array(Buffer.from(pcztHexTring, 'hex')); const pczt = Pczt.from_bytes(pcztUint8Array); - const seed = await getSeed(); + const seed = await getSeed(await getActiveDerivationVersion()); const spendingKey = new UnifiedSpendingKey(NETWORK, seed, 0); const seedFp = new SeedFingerprint(seed); const ufvk = spendingKey.to_unified_full_viewing_key(); diff --git a/packages/snap/src/types.ts b/packages/snap/src/types.ts index 0d7f37e..cce3229 100644 --- a/packages/snap/src/types.ts +++ b/packages/snap/src/types.ts @@ -29,4 +29,7 @@ export type SnapState = { webWalletSyncStartBlock: string; lastKnownBalance: LastKnownBalance | null; hasPendingTx: boolean | null; + // Key-derivation version for this account (see utils/getSeed.ts). + // Absent → legacy v1 (never silently switch an existing account). + derivationVersion?: number; } & Record; diff --git a/packages/snap/src/utils/getSeed.ts b/packages/snap/src/utils/getSeed.ts index 0572f85..8f0eaed 100644 --- a/packages/snap/src/utils/getSeed.ts +++ b/packages/snap/src/utils/getSeed.ts @@ -1,6 +1,25 @@ import { hexStringToUint8Array } from './hexStringToUint8Array'; +import { + mnemonic_from_entropy, + seed_from_mnemonic, +} from '@zcashcommunitygrants/webzjs-keys'; +import { getSnapState } from '../rpc/getSnapState'; +import type { SnapState } from '../types'; -export async function getSeed(): Promise { +/** + * Snap key-derivation version: v1 (legacy) uses the 32-byte key directly as the seed + * (non-standard, kept spendable); v2 (portable) routes it through BIP-39 so standard wallets reproduce it. + */ +export type DerivationVersion = 1 | 2; + +export const LEGACY_DERIVATION_VERSION: DerivationVersion = 1; +export const PORTABLE_DERIVATION_VERSION: DerivationVersion = 2; + +/** + * Raw 32 bytes of deterministic entropy from MetaMask — the shared input to both + * derivation versions (lets the v1 → v2 sweep sign with v1 while producing v2). + */ +async function getEntropyBytes(): Promise { const entropyNode = await snap.request({ method: 'snap_getBip44Entropy', params: { coinType: 133 }, // 133 is the coin type for Zcash https://github.com/satoshilabs/slips/blob/master/slip-0044.md @@ -16,15 +35,54 @@ export async function getSeed(): Promise { const { privateKey } = entropyNode; const validatedKey = validatePrivateKey(privateKey); - const seed = hexStringToUint8Array(validatedKey); + const entropy = hexStringToUint8Array(validatedKey); - if (seed.length !== 32) { + if (entropy.length !== 32) { throw new Error( - `Invalid seed length: expected 32 bytes, got ${seed.length} bytes`, + `Invalid entropy length: expected 32 bytes, got ${entropy.length} bytes`, ); } - return seed; + return entropy; +} + +/** + * Derive the ZIP-32 seed for `version` (defaults to legacy v1 so existing funds are + * unaffected). Returns 32 bytes for v1, a 64-byte BIP-39 seed for v2. + */ +export async function getSeed( + version: DerivationVersion = LEGACY_DERIVATION_VERSION, +): Promise { + const entropy = await getEntropyBytes(); + + if (version === LEGACY_DERIVATION_VERSION) { + // v1: the 32-byte child key IS the seed (legacy behaviour, unchanged). + return entropy; + } + + // v2: route through standard BIP-39 → 64-byte seed (portable). + const phrase = mnemonic_from_entropy(entropy); + return seed_from_mnemonic(phrase); +} + +/** + * The portable (v2) BIP-39 mnemonic — the user's exportable secret phrase. + * SECURITY: never return to the dApp; reveal only inside a Snap dialog. + */ +export async function getMnemonic(): Promise { + const entropy = await getEntropyBytes(); + return mnemonic_from_entropy(entropy); +} + +/** + * The account's derivation version from Snap state. Absent stamp → v1, so a legacy + * account is never silently switched to v2 (which would hide its funds). + */ +export async function getActiveDerivationVersion(): Promise { + const state = (await getSnapState()) as SnapState | null; + return state?.derivationVersion === PORTABLE_DERIVATION_VERSION + ? PORTABLE_DERIVATION_VERSION + : LEGACY_DERIVATION_VERSION; } function validatePrivateKey(privateKey: string | undefined): string { diff --git a/packages/web-wallet/src/config/constants.ts b/packages/web-wallet/src/config/constants.ts index 4eef760..2f69c78 100644 --- a/packages/web-wallet/src/config/constants.ts +++ b/packages/web-wallet/src/config/constants.ts @@ -1,6 +1,19 @@ -// Override via LIGHTWALLETD_PROXY env var for local dev (e.g. in .env.local) -// Default is the production proxy -export const MAINNET_LIGHTWALLETD_PROXY = process.env.LIGHTWALLETD_PROXY || 'https://zjs.zec.rocks/mainnet'; +// Zcash network this build targets: 'main' (default) or 'test' (NETWORK=test). +// The Snap MUST target the same network, or derived keys/addresses won't align. +export const NETWORK: 'main' | 'test' = + process.env.NETWORK === 'test' ? 'test' : 'main'; + +const MAINNET_PROXY = 'https://zjs.zec.rocks/mainnet'; +const TESTNET_PROXY = 'https://zjs.zec.rocks/testnet'; + +// The lightwalletd gRPC-web proxy for the selected network. +// Override via LIGHTWALLETD_PROXY env var for local dev (e.g. in .env.local). +export const LIGHTWALLETD_PROXY = + process.env.LIGHTWALLETD_PROXY || + (NETWORK === 'test' ? TESTNET_PROXY : MAINNET_PROXY); + +// Back-compat alias for existing imports. +export const MAINNET_LIGHTWALLETD_PROXY = LIGHTWALLETD_PROXY; export const ZATOSHI_PER_ZEC = 1e8; export const RESCAN_INTERVAL = 35000; // 35s sync interval export const NU5_ACTIVATION = 1687104; diff --git a/packages/web-wallet/src/context/WebzjsContext.tsx b/packages/web-wallet/src/context/WebzjsContext.tsx index a3914d0..baba992 100644 --- a/packages/web-wallet/src/context/WebzjsContext.tsx +++ b/packages/web-wallet/src/context/WebzjsContext.tsx @@ -14,7 +14,7 @@ import initWebzJSWallet, { WebWallet, } from '@zcashcommunitygrants/webzjs-wallet'; import initWebzJSKeys from '@zcashcommunitygrants/webzjs-keys'; -import { MAINNET_LIGHTWALLETD_PROXY } from '../config/constants'; +import { NETWORK, LIGHTWALLETD_PROXY } from '../config/constants'; import { Snap } from '../types'; import toast, { Toaster } from 'react-hot-toast'; @@ -118,18 +118,18 @@ export const WebZjsProvider = ({ children }: { children: React.ReactNode }) => { if (bytes) { console.info('Saved wallet detected. Restoring wallet from storage'); try { - wallet = new WebWallet('main', MAINNET_LIGHTWALLETD_PROXY, 1, 1, bytes); + wallet = new WebWallet(NETWORK, LIGHTWALLETD_PROXY, 1, 1, bytes); } catch (deserializeError) { console.warn( 'Failed to restore wallet from storage (possibly incompatible format after upgrade). Creating fresh wallet.', deserializeError ); toast.error('Wallet data incompatible after upgrade. Please re-sync your wallet.'); - wallet = new WebWallet('main', MAINNET_LIGHTWALLETD_PROXY, 1, 1, null); + wallet = new WebWallet(NETWORK, LIGHTWALLETD_PROXY, 1, 1, null); } } else { console.info('No saved wallet detected. Creating new wallet'); - wallet = new WebWallet('main', MAINNET_LIGHTWALLETD_PROXY, 1, 1, null); + wallet = new WebWallet(NETWORK, LIGHTWALLETD_PROXY, 1, 1, null); } dispatch({ type: 'set-web-wallet', payload: wallet }); diff --git a/packages/web-wallet/src/hooks/useMigration.ts b/packages/web-wallet/src/hooks/useMigration.ts new file mode 100644 index 0000000..0c35f59 --- /dev/null +++ b/packages/web-wallet/src/hooks/useMigration.ts @@ -0,0 +1,153 @@ +import { useState } from 'react'; +import { Pczt } from '@zcashcommunitygrants/webzjs-wallet'; +import { Buffer } from 'buffer'; +import { useWebZjsContext } from '../context/WebzjsContext'; +import { useMetaMaskContext } from '../context/MetamaskContext'; +import { useInvokeSnap } from './snaps/useInvokeSnap'; +import { useWebZjsActions } from './useWebzjsActions'; +import useBalance from './useBalance'; +import { zatsToZec } from '../utils'; +import { SignPcztDetails } from '../types/snap'; + +/** + * Fee buffer (zatoshis) held back from the sweep so the migration transaction's + * ZIP-317 fee is covered. Any remainder below this stays as dust in the legacy + * account (recoverable later) — never lost. + */ +const MIGRATION_FEE_BUFFER = 20_000; // 0.0002 ZEC + +export enum MigrationStatus { + IDLE = 'Idle', + PREPARING = 'Preparing migration', + CREATING = 'Building migration transaction', + SIGNING = 'Signing with your current key', + PROVING = 'Proving transaction', + SENDING = 'Moving your funds', + STAMPING = 'Switching to the portable account', + RESYNCING = 'Refreshing your wallet', + DONE = 'Migration complete', + ERROR = 'Migration failed', +} + +interface IUseMigration { + migrateToPortable: () => Promise; + migrationStatus: MigrationStatus; + migrationError: string | null; +} + +/** + * Orchestrates the one-time v1 (legacy) → v2 (portable) sweep: moves the legacy + * account's balance to the portable address, then commits the derivation switch. + */ +export const useMigration = (): IUseMigration => { + const { state } = useWebZjsContext(); + const invokeSnap = useInvokeSnap(); + const { flushDbToStore, fullResync } = useWebZjsActions(); + const { refreshSnapState } = useMetaMaskContext(); + const { spendableBalance } = useBalance(); + + const [migrationStatus, setMigrationStatus] = useState( + MigrationStatus.IDLE, + ); + const [migrationError, setMigrationError] = useState(null); + + const migrateToPortable = async (): Promise => { + setMigrationError(null); + + if (!state.webWallet) { + setMigrationError('Wallet is not ready. Please wait for sync to finish.'); + return; + } + const account = + state.activeAccount === null || state.activeAccount === undefined + ? null + : state.activeAccount; + if (account === null) { + setMigrationError('No active account to migrate.'); + return; + } + + const sweepZats = spendableBalance - MIGRATION_FEE_BUFFER; + if (sweepZats <= 0) { + setMigrationError( + 'Not enough spendable balance to migrate (after the network fee). ' + + 'Wait for sync to finish, or there may be nothing to move.', + ); + return; + } + + try { + setMigrationStatus(MigrationStatus.PREPARING); + // Destination: the portable (v2) account's shielded address. + const toAddress = (await invokeSnap({ + method: 'getPortableAddress', + })) as string; + + setMigrationStatus(MigrationStatus.CREATING); + const sweepZec = zatsToZec(sweepZats).toString(); + const pczt = await state.webWallet.pczt_create( + account, + toAddress, + BigInt(sweepZats), + ); + + setMigrationStatus(MigrationStatus.SIGNING); + // Signed with the active (legacy v1) key — correct, since the spent notes + // belong to v1 and `derivationVersion` has not been switched yet. + const pcztHexTring = Buffer.from(pczt.serialize()).toString('hex'); + const params: SignPcztDetails = { + pcztHexTring, + signDetails: { recipient: toAddress, amount: sweepZec }, + }; + const signedHex = (await invokeSnap({ + method: 'signPczt', + params, + })) as string; + const signedPczt = Pczt.from_bytes( + new Uint8Array(Buffer.from(signedHex, 'hex')), + ); + + setMigrationStatus(MigrationStatus.PROVING); + const provedPczt = await state.webWallet.pczt_prove(signedPczt); + + setMigrationStatus(MigrationStatus.SENDING); + await state.webWallet.pczt_send(provedPczt); + await flushDbToStore(); + + // Only now that the funds are on their way do we commit the switch. + setMigrationStatus(MigrationStatus.STAMPING); + const stamped = (await invokeSnap({ + method: 'completeMigration', + })) as boolean; + if (!stamped) { + // User declined the final confirmation. The sweep is already broadcast; + // the funds are heading to the portable account, but the wallet stays on + // the legacy view until they complete the switch. Surface this clearly. + setMigrationError( + 'Funds were sent to your portable account, but the switch was not ' + + 'confirmed. Re-run the migration to finish switching.', + ); + setMigrationStatus(MigrationStatus.ERROR); + return; + } + + // Re-import the wallet onto the portable (v2) account and re-scan so the + // swept funds show up there. + setMigrationStatus(MigrationStatus.RESYNCING); + await fullResync(); + + // Refresh the cached snap state so the UI sees derivationVersion = 2 and + // hides the "move funds to portable account" prompt now that the switch is done. + await refreshSnapState(); + + setMigrationStatus(MigrationStatus.DONE); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error('Migration failed:', error); + setMigrationError(message); + setMigrationStatus(MigrationStatus.ERROR); + } + }; + + return { migrateToPortable, migrationStatus, migrationError }; +}; diff --git a/packages/web-wallet/src/hooks/useWebzjsActions.ts b/packages/web-wallet/src/hooks/useWebzjsActions.ts index f6ed40d..84da448 100644 --- a/packages/web-wallet/src/hooks/useWebzjsActions.ts +++ b/packages/web-wallet/src/hooks/useWebzjsActions.ts @@ -6,7 +6,7 @@ import { useMetaMask } from './snaps/useMetaMask'; import { useInvokeSnap } from './snaps/useInvokeSnap'; import { useRequestSnap } from './snaps/useRequestSnap'; import { SeedFingerprint, WebWallet } from '@zcashcommunitygrants/webzjs-wallet'; -import { MAINNET_LIGHTWALLETD_PROXY } from '../config/constants'; +import { NETWORK, LIGHTWALLETD_PROXY } from '../config/constants'; import { SnapState } from '../types/snap'; // Synchronous guard: prevents triggerRescan from overlapping with fullResync. @@ -80,6 +80,9 @@ export function useWebZjsActions(): WebzjsActions { } const merged: SnapState = { + // Preserve any existing fields (e.g. derivationVersion set by completeMigration) + // that aren't in the explicit shape below, so a routine state write doesn't wipe them. + ...existing, webWalletSyncStartBlock: birthday ?? '', lastKnownBalance: existing?.lastKnownBalance ?? null, hasPendingTx: existing?.hasPendingTx ?? null, @@ -338,42 +341,74 @@ export function useWebZjsActions(): WebzjsActions { return; } - // Check if we're already at chain tip - skip redundant syncs - // Allow a small buffer (2 blocks) for network propagation - const fullySyncedHeight = fullySyncedRef.current; - const chainHeight = chainHeightRef.current ? Number(chainHeightRef.current) : 0; - if (fullySyncedHeight && chainHeight && fullySyncedHeight >= chainHeight - 2) { - // Already synced to chain tip, just refresh the chain height - try { - const latestBlock = await state.webWallet.get_latest_block(); - if (latestBlock && latestBlock !== chainHeightRef.current) { + const wallet = state.webWallet; + + // Refresh the chain tip up front so we both display it and decide whether a + // sync is needed. + let chainTip = chainHeightRef.current ? Number(chainHeightRef.current) : 0; + try { + const latestBlock = await wallet.get_latest_block(); + if (latestBlock) { + if (latestBlock !== chainHeightRef.current) { dispatch({ type: 'set-chain-height', payload: latestBlock }); - // Only sync if chain has advanced - if (fullySyncedHeight < Number(latestBlock)) { - dispatch({ type: 'set-sync-in-progress', payload: true }); - try { - await withRetry(() => state.webWallet!.sync(), { label: 'sync', retries: 2, baseDelay: 3000 }); - await syncStateWithWallet(); - await flushDbToStore(); - } finally { - dispatch({ type: 'set-sync-in-progress', payload: false }); - } - } } - } catch (err) { - console.error('Error checking chain height:', err); + chainTip = Number(latestBlock); } + } catch (err) { + console.error('Error checking chain height:', err); + return; + } + + // Already synced to the chain tip (small buffer for propagation) — nothing to do. + const fullySyncedHeight = fullySyncedRef.current; + if (fullySyncedHeight && chainTip && fullySyncedHeight >= chainTip - 2) { return; } dispatch({ type: 'set-sync-in-progress', payload: true }); + // Sync in short incremental rounds, persisting + refreshing after each, so one + // sync() that can't finish the backlog doesn't discard the interval's progress. + const MAX_SYNC_ROUNDS = 20; + const SYNC_ROUND_DELAY = 2000; // ms between rounds to let the proxy recover + let consecutiveFailures = 0; + const MAX_CONSECUTIVE_FAILURES = 4; + try { - await withRetry(() => state.webWallet!.sync(), { label: 'sync', retries: 2, baseDelay: 3000 }); - await syncStateWithWallet(); - await flushDbToStore(); - } catch (err: unknown) { - console.warn('Sync failed (will retry next interval):', err); + for (let round = 1; round <= MAX_SYNC_ROUNDS; round++) { + try { + await wallet.sync(); + consecutiveFailures = 0; + + // Persist + refresh after every round so progress survives a later + // failure and the UI advances steadily. + await syncStateWithWallet(); + await flushDbToStore(); + + const summary = await wallet.get_wallet_summary(); + const scannedHeight = summary?.fully_scanned_height ?? 0; + const tip = Number(await wallet.get_latest_block()); + if (scannedHeight >= tip - 2) { + break; // caught up + } + + if (round < MAX_SYNC_ROUNDS) { + await new Promise((r) => setTimeout(r, SYNC_ROUND_DELAY)); + } + } catch (syncErr) { + consecutiveFailures++; + console.warn( + `Sync round ${round} failed (${consecutiveFailures}/${MAX_CONSECUTIVE_FAILURES}); progress is preserved:`, + syncErr, + ); + if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) { + // Give up for now; the next interval resumes from persisted progress. + break; + } + const backoff = SYNC_ROUND_DELAY * Math.pow(2, consecutiveFailures - 1); + await new Promise((r) => setTimeout(r, backoff)); + } + } } finally { dispatch({ type: 'set-sync-in-progress', payload: false }); } @@ -449,7 +484,7 @@ export function useWebZjsActions(): WebzjsActions { // 3. Create fresh wallet in LOCAL variable — old wallet stays in React state + IndexedDB console.info('Full resync: Creating fresh wallet (old wallet preserved as fallback)'); - const freshWallet = new WebWallet('main', MAINNET_LIGHTWALLETD_PROXY, 1, 1, null); + const freshWallet = new WebWallet(NETWORK, LIGHTWALLETD_PROXY, 1, 1, null); // 4. Re-import the account with retry (makes GetTreeState gRPC call) console.info(`Full resync: Re-importing account with birthday ${birthdayBlock}`); diff --git a/packages/web-wallet/src/pages/AccountSummary.tsx b/packages/web-wallet/src/pages/AccountSummary.tsx index e83b49c..356ee2d 100644 --- a/packages/web-wallet/src/pages/AccountSummary.tsx +++ b/packages/web-wallet/src/pages/AccountSummary.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useState } from 'react'; import { zatsToZec } from '../utils'; import { CoinsSvg, ShieldDividedSvg, ShieldSvg } from '../assets'; import useBalance from '../hooks/useBalance'; @@ -7,6 +7,8 @@ import { useWebZjsContext } from 'src/context/WebzjsContext'; import { BlockHeightCard } from 'src/components/BlockHeightCard/BlockHeightCard'; import { useMetaMaskContext } from 'src/context/MetamaskContext'; import { useWebZjsActions } from '../hooks/useWebzjsActions'; +import { useInvokeSnap } from '../hooks/snaps/useInvokeSnap'; +import { useMigration, MigrationStatus } from '../hooks/useMigration'; interface BalanceCard { name: string; @@ -18,8 +20,42 @@ function AccountSummary() { const { totalBalance, spendableBalance, unshieldedBalance, shieldedBalance, hasPending } = useBalance(); const { pendingTxs } = usePendingTransactions(); const { state } = useWebZjsContext(); - const { snapState } = useMetaMaskContext(); + const { snapState, installedSnap } = useMetaMaskContext(); const { fullResync } = useWebZjsActions(); + const invokeSnap = useInvokeSnap(); + const [exporting, setExporting] = useState(false); + const { migrateToPortable, migrationStatus, migrationError } = useMigration(); + + // Show the migration prompt only while the account is still on the legacy (v1) + // derivation. Once switched to the portable account (v2) it is hidden. + const onLegacyDerivation = snapState?.derivationVersion !== 2; + const migrationInProgress = + migrationStatus !== MigrationStatus.IDLE && + migrationStatus !== MigrationStatus.DONE && + migrationStatus !== MigrationStatus.ERROR; + + const handleMigrate = async () => { + const ok = window.confirm( + 'This moves all of your funds from your current (legacy) Zcash account to ' + + 'a new portable account whose recovery phrase you can export. You will ' + + 'approve the transaction in MetaMask. Continue?', + ); + if (!ok) return; + await migrateToPortable(); + }; + + // Triggers the Snap's secure reveal dialog. The secret is shown by MetaMask + // itself and is never returned to this page. + const handleExportKeys = async () => { + setExporting(true); + try { + await invokeSnap({ method: 'exportZcashSecret' }); + } catch (err) { + console.warn('Key export cancelled or failed:', err); + } finally { + setExporting(false); + } + }; const BalanceCards: BalanceCard[] = [ { @@ -96,6 +132,55 @@ function AccountSummary() { syncedFrom={snapState?.webWalletSyncStartBlock} onFullResync={fullResync} /> +
+
+ Export Zcash keys +
+
+ Reveal your Zcash wallet's recovery phrase to import this wallet + into another Zcash wallet (e.g. Zkool or Zodl). The phrase is shown + securely inside MetaMask and is different from your MetaMask Secret + Recovery Phrase. +
+ +
+ {onLegacyDerivation && installedSnap && ( +
+
+ Upgrade to a portable Zcash account +
+
+ Your current Zcash account cannot be exported to other wallets. Move + your funds to a new portable account to get a recovery phrase you can + import anywhere. This sends a transaction you approve in MetaMask. +
+ + {migrationStatus === MigrationStatus.DONE && ( +
+ Migration complete — your funds are now in your portable account. +
+ )} + {migrationError && ( +
+ {migrationError} +
+ )} +
+ )} ); } From 8aadbef97936ce64ab27acb9ece74e93f36100a1 Mon Sep 17 00:00:00 2001 From: aratrika Date: Wed, 11 Nov 2026 09:06:51 -0500 Subject: [PATCH 6/8] fix(snap): harden signing dialog, RPC surface & migration --- Cargo.lock | 2 +- Cargo.toml | 10 +- crates/webzjs-keys/src/error.rs | 2 + crates/webzjs-keys/src/keys.rs | 2 +- crates/webzjs-keys/src/pczt_describe.rs | 4 +- crates/webzjs-keys/src/pczt_sign.rs | 38 ++- crates/webzjs-wallet/src/bindgen/wallet.rs | 15 +- crates/webzjs-wallet/src/chain_params.rs | 7 +- crates/webzjs-wallet/src/wallet.rs | 128 ++++++-- packages/snap/CHANGELOG.md | 38 +++ packages/snap/package.json | 2 +- packages/snap/snap.manifest.json | 10 +- packages/snap/src/index.tsx | 39 ++- packages/snap/src/rpc/exportSecret.tsx | 23 +- packages/snap/src/rpc/getViewingKey.tsx | 64 ++-- packages/snap/src/rpc/migrate.tsx | 39 ++- packages/snap/src/rpc/setBirthdayBlock.tsx | 3 +- packages/snap/src/rpc/setSnapState.tsx | 21 +- packages/snap/src/rpc/signMigration.tsx | 171 +++++++++++ packages/snap/src/rpc/signPczt.tsx | 40 ++- packages/snap/src/utils/dialogs.tsx | 2 +- packages/snap/src/utils/getSeed.ts | 9 +- packages/snap/src/utils/setSyncBlockHeight.ts | 6 + packages/web-wallet/src/App.tsx | 2 +- packages/web-wallet/src/config/constants.ts | 6 +- .../web-wallet/src/context/WebzjsContext.tsx | 4 + .../src/hooks/snaps/useGetSnapState.ts | 21 +- packages/web-wallet/src/hooks/useMigration.ts | 290 ++++++++++++++---- packages/web-wallet/src/hooks/usePCZT.ts | 5 +- .../web-wallet/src/hooks/useWebzjsActions.ts | 30 +- .../web-wallet/src/pages/AccountSummary.tsx | 54 +++- packages/web-wallet/src/types/snap.ts | 3 + .../web-wallet/src/workers/prover.worker.ts | 46 +++ .../web-wallet/src/workers/proverClient.ts | 40 +++ 34 files changed, 951 insertions(+), 225 deletions(-) create mode 100644 packages/snap/CHANGELOG.md create mode 100644 packages/snap/src/rpc/signMigration.tsx create mode 100644 packages/web-wallet/src/workers/prover.worker.ts create mode 100644 packages/web-wallet/src/workers/proverClient.ts diff --git a/Cargo.lock b/Cargo.lock index 10bae53..049ad39 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3833,7 +3833,7 @@ dependencies = [ [[package]] name = "zcash_client_memory" version = "0.0.0" -source = "git+https://github.com/red-dev-inc/zcash_client_memory?branch=feat%2Fsnap-nu7#b4c8f0d33c65c5bab4155ddeba4f201ea2d28c43" +source = "git+https://github.com/red-dev-inc/zcash_client_memory?rev=b4c8f0d33c65c5bab4155ddeba4f201ea2d28c43#b4c8f0d33c65c5bab4155ddeba4f201ea2d28c43" dependencies = [ "async-trait", "bip32", diff --git a/Cargo.toml b/Cargo.toml index d97963e..291f784 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,13 +32,13 @@ 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: librustzcash NU7 final stable crates from crates.io (pinned exactly). NU7 is -## active on testnet from block 4,465,026 (branch id 0x77190AD9); mainnet has no NU7 height yet. -## `zcash_client_memory` is our NU7 store branch (red-dev-inc `feat/snap-nu7`). For local store work, -## swap it to `{ path = "../zcash_client_memory" }`. +## 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", branch = "feat/snap-nu7", features = ["orchard", "transparent-inputs"] } +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" } diff --git a/crates/webzjs-keys/src/error.rs b/crates/webzjs-keys/src/error.rs index 8b792a8..ce93851 100644 --- a/crates/webzjs-keys/src/error.rs +++ b/crates/webzjs-keys/src/error.rs @@ -22,6 +22,8 @@ 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), } diff --git a/crates/webzjs-keys/src/keys.rs b/crates/webzjs-keys/src/keys.rs index 9ba65a1..2bfdae0 100644 --- a/crates/webzjs-keys/src/keys.rs +++ b/crates/webzjs-keys/src/keys.rs @@ -198,7 +198,7 @@ impl UnifiedFullViewingKey { let (ua, _) = self .inner .default_address(zcash_keys::keys::UnifiedAddressRequest::ALLOW_ALL) - .map_err(|_| Error::TransparentAddressDerivation)?; + .map_err(|_| Error::AddressDerivation)?; Ok(ua.encode(&network)) } } diff --git a/crates/webzjs-keys/src/pczt_describe.rs b/crates/webzjs-keys/src/pczt_describe.rs index 02a43fc..1937dcd 100644 --- a/crates/webzjs-keys/src/pczt_describe.rs +++ b/crates/webzjs-keys/src/pczt_describe.rs @@ -598,7 +598,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(()) diff --git a/crates/webzjs-keys/src/pczt_sign.rs b/crates/webzjs-keys/src/pczt_sign.rs index 334ad0c..51dff0d 100644 --- a/crates/webzjs-keys/src/pczt_sign.rs +++ b/crates/webzjs-keys/src/pczt_sign.rs @@ -1,6 +1,7 @@ use crate::error::Error; use crate::{SeedFingerprint, UnifiedSpendingKey}; use pczt::roles::signer::Signer; +use pczt::roles::updater::Updater; use pczt::roles::verifier::Verifier; use std::collections::BTreeMap; use std::convert::Infallible; @@ -48,9 +49,8 @@ pub async fn pczt_sign_inner( Orchard { index: usize, }, - // NU6.3 Ironwood spends reuse the Orchard spend-authorizing key and ZIP-32 - // derivation; they are collected and signed exactly like Orchard, only via - // the Ironwood bundle / `sign_ironwood`. + // Ironwood reuses the Orchard spend-authorizing key and ZIP-32 derivation; + // collected and signed like Orchard, via the Ironwood bundle. Ironwood { index: usize, }, @@ -154,6 +154,38 @@ pub async fn pczt_sign_inner( }) .map_err(|e| Error::PcztSign(format!("Invalid PCZT: {e:?}")))? .finish(); + + // Attach the Sapling proof-generation key: the stateless worker prover has no key, + // so the PGK must travel in the PCZT. It grants proving/viewing only, never spend. + let sapling_spend_indices: Vec = keys + .values() + .flatten() + .filter_map(|keyref| match keyref { + KeyRef::Sapling { index } => Some(*index), + _ => None, + }) + .collect(); + let pczt = if sapling_spend_indices.is_empty() { + pczt + } else { + let pgk = usk.sapling().expsk().proof_generation_key(); + Updater::new(pczt) + .update_sapling_with(|mut updater| { + for index in &sapling_spend_indices { + updater.update_spend_with(*index, |mut spend_updater| { + spend_updater.set_proof_generation_key(pgk.clone()) + })?; + } + Ok(()) + }) + .map_err(|e| { + Error::PcztSign(format!( + "Failed to attach Sapling proof generation key: {e:?}" + )) + })? + .finish() + }; + let mut signer = Signer::new(pczt).unwrap(); //.map_err(|e| anyhow!("Failed to initialize Signer: {:?}", e))?; for (_, spends) in keys { diff --git a/crates/webzjs-wallet/src/bindgen/wallet.rs b/crates/webzjs-wallet/src/bindgen/wallet.rs index 89460fc..599dd8a 100644 --- a/crates/webzjs-wallet/src/bindgen/wallet.rs +++ b/crates/webzjs-wallet/src/bindgen/wallet.rs @@ -504,6 +504,17 @@ impl WebWallet { .map(Into::into) } + /// Creates a PCZT that sweeps the account's entire spendable shielded balance to + /// `to_address` with an exact fee and no change (the v1 → v2 migration move). Fails if + /// any shielded note is not yet spendable; transparent funds must be shielded first. + pub async fn pczt_sweep(&self, account_id: u32, to_address: String) -> Result { + let to_address = ZcashAddress::try_from_encoded(&to_address)?; + self.inner + .pczt_sweep(AccountId::from(account_id), to_address) + .await + .map(Into::into) + } + /// Creates and inserts proofs for a PCZT. /// /// If there are Sapling spends, a ProofGenerationKey needs to be supplied. It can be derived from the UFVK. @@ -524,7 +535,9 @@ impl WebWallet { .map(Into::into) } - pub async fn pczt_send(&self, pczt: Pczt) -> Result<(), Error> { + /// Broadcasts the transaction in `pczt` and returns its txid (raw-byte hex), so the + /// caller can poll `get_transaction_history` for confirmation. + pub async fn pczt_send(&self, pczt: Pczt) -> Result { self.inner.pczt_send(pczt.into()).await } diff --git a/crates/webzjs-wallet/src/chain_params.rs b/crates/webzjs-wallet/src/chain_params.rs index 7bf4067..0d7ccd9 100644 --- a/crates/webzjs-wallet/src/chain_params.rs +++ b/crates/webzjs-wallet/src/chain_params.rs @@ -98,11 +98,14 @@ mod tests { fn mainnet_change_pool_before_and_after_nu6_3() { let net = Network::MainNetwork; let nu6_3 = net.activation_height(NetworkUpgrade::Nu6_3).unwrap(); + let nu7 = net.activation_height(NetworkUpgrade::Nu7).unwrap(); assert_eq!(u32::from(nu6_3), 3_428_143); + assert_eq!(u32::from(nu7), 3_543_405); assert_eq!(change_pool_at(&net, nu6_3 - 1), ShieldedPool::Orchard); assert_eq!(change_pool_at(&net, nu6_3), ShieldedPool::Ironwood); - // Mainnet has no NU7 height yet; the pool does not depend on it. - assert_eq!(net.activation_height(NetworkUpgrade::Nu7), None); + assert_eq!(change_pool_at(&net, nu7 - 1), ShieldedPool::Ironwood); + // NU7 keeps the Ironwood pool. + assert_eq!(change_pool_at(&net, nu7), ShieldedPool::Ironwood); assert_eq!(change_pool_at(&net, h(4_000_000)), ShieldedPool::Ironwood); } diff --git a/crates/webzjs-wallet/src/wallet.rs b/crates/webzjs-wallet/src/wallet.rs index f3c2827..6f67681 100644 --- a/crates/webzjs-wallet/src/wallet.rs +++ b/crates/webzjs-wallet/src/wallet.rs @@ -27,15 +27,17 @@ use std::sync::Arc; use subtle::ConditionallySelectable; use tokio::sync::RwLock; use zcash_address::ZcashAddress; -use zcash_client_backend::data_api::wallet::input_selection::SpendPolicy; +use zcash_client_backend::data_api::wallet::input_selection::{LockedInputPolicy, SpendPolicy}; use zcash_client_backend::data_api::wallet::{ create_pczt_from_proposal, create_proposed_transactions, extract_and_store_transaction_from_pczt, input_selection::GreedyInputSelector, - propose_shielding, propose_transfer, ConfirmationsPolicy, SpendingKeys, + propose_send_max_transfer, propose_shielding, propose_transfer, ConfirmationsPolicy, + SpendingKeys, }; use zcash_client_backend::data_api::CoinbaseFilter; use zcash_client_backend::data_api::{ - Account, AccountBirthday, AccountPurpose, InputSource, WalletRead, WalletSummary, WalletWrite, + Account, AccountBirthday, AccountPurpose, InputSource, MaxSpendMode, WalletRead, WalletSummary, + WalletWrite, }; use zcash_client_backend::data_api::{WalletCommitmentTrees, Zip32Derivation}; use zcash_client_backend::fees::standard::MultiOutputChangeStrategy; @@ -711,6 +713,86 @@ where Ok(pczt) } + /// Sweep an account's entire spendable shielded balance (all pools) to `to_address` + /// with no change — the v1 → v2 migration. Transparent funds are not swept. + pub async fn pczt_sweep( + &self, + account_id: AccountId, + to_address: ZcashAddress, + ) -> Result { + // Ensure the wallet is synced before building, to avoid expiry/anchor errors. + let mut client = self.client.clone(); + let chain_tip: u32 = client + .get_latest_block(service::ChainSpec::default()) + .await? + .into_inner() + .height + .try_into() + .expect("block heights must fit into u32"); + + let wallet_height = self.db.read().await.chain_height()?; + if let Some(wallet_height) = wallet_height { + let wallet_height_u32: u32 = wallet_height.into(); + if chain_tip.saturating_sub(wallet_height_u32) > 10 { + drop(client); + self.sync().await?; + } + } else { + return Err(Error::Generic( + "Wallet has not been synced yet. Please sync before migrating.".to_string(), + )); + } + + let spend_pools = [ + ShieldedPool::Sapling, + ShieldedPool::Orchard, + ShieldedPool::Ironwood, + ]; + + let mut db = self.db.write().await; + let proposal = propose_send_max_transfer::<_, _, _, ::Error>( + &mut *db, + &self.network, + account_id, + &spend_pools, + &StandardFeeRule::Zip317, + to_address, + None, + // Fail rather than hand back a partial sweep that looks complete. + MaxSpendMode::Everything, + self.min_confirmations, + &LockedInputPolicy::Exclude, + None, + ) + .map_err(|e| { + Error::Generic(format!( + "Could not build the migration sweep. Wait for sync to finish and shield any \ + transparent funds first, then retry. ({e:?})" + )) + })?; + + let pczt = create_pczt_from_proposal::< + _, + _, + as InputSource>::Error, + _, + ::Error, + _, + >( + &mut *db, + &self.network, + &WalletClock, + &mut rand10::rng(), + account_id, + OvkPolicy::Sender, + &proposal, + None, + BundlePadding::DEFAULT, + ) + .map_err(|e| Error::PcztCreate(format!("{e:?}")))?; + Ok(pczt) + } + /// /// Prove a PCZT /// @@ -759,48 +841,47 @@ where pczt }; - // Orchard-family bundles (Orchard and Ironwood) need a circuit version, derived from the - // PCZT's target consensus branch via its Orchard protocol revision: NU6.2 uses the fixed - // circuit, and NU6.3 and every later upgrade (NU7 included) the post-NU6.3 circuit that - // enforces the disableCrossAddress constraint. The same version must build the verifying - // key when the transaction is extracted. let branch = BranchId::try_from(*pczt.global().consensus_branch_id()).map_err(|e| { - Error::PcztProve(format!("PCZT has an unknown consensus branch id: {:?}", e)) - })?; - let orchard_circuit_version = orchard_circuit_version(branch).ok_or_else(|| { - Error::PcztProve(format!( - "Cannot create Orchard proofs for consensus branch {:?}", - branch - )) + Error::PcztProve(format!("PCZT has an unknown consensus branch id: {e:?}")) })?; let prover = LocalTxProver::bundled(); let mut proofs = Prover::new(pczt); if proofs.requires_orchard_proof() || proofs.requires_ironwood_proof() { + // Orchard-family bundles need a circuit version (from the consensus branch). + // Computed lazily, so a transparent/Sapling-only PCZT never needs it. + let orchard_circuit_version = orchard_circuit_version(branch).ok_or_else(|| { + Error::PcztProve(format!( + "Cannot create Orchard proofs for consensus branch {branch:?}" + )) + })?; let proving_key = orchard::circuit::ProvingKey::build(orchard_circuit_version); if proofs.requires_orchard_proof() { proofs = proofs .create_orchard_proof(rand10::rng(), &proving_key) .map_err(|e| { - Error::PcztProve(format!("Failed to create Orchard proof: {:?}", e)) + Error::PcztProve(format!("Failed to create Orchard proof: {e:?}")) })?; } if proofs.requires_ironwood_proof() { proofs = proofs .create_ironwood_proof(rand10::rng(), &proving_key) .map_err(|e| { - Error::PcztProve(format!("Failed to create Ironwood proof: {:?}", e)) + Error::PcztProve(format!("Failed to create Ironwood proof: {e:?}")) })?; } } let pczt = proofs .create_sapling_proofs(rand10::rng(), &prover, &prover) - .map_err(|e| Error::PcztProve(format!("Failed to create Sapling proofs: {:?}", e)))? + .map_err(|e| Error::PcztProve(format!("Failed to create Sapling proofs: {e:?}")))? .finish(); Ok(pczt) } - pub async fn pczt_send(&self, pczt: Pczt) -> Result<(), Error> { + /// Extracts, stores and broadcasts the transaction in `pczt`, returning its txid as + /// raw-byte hex (matching the transaction-history encoding) so callers can track when + /// it is mined — the migration flow waits for ≥1 confirmation before switching. + pub async fn pczt_send(&self, pczt: Pczt) -> Result { // Verify the wallet is sufficiently synced before sending // The network only accepts anchors within the last 100 blocks let mut client = self.client.clone(); @@ -844,12 +925,11 @@ where // branch (Nu6_3 -> PostNu6_3, else FixedPostNu6_2), matching how the proof was // created. See the proving-key derivation in the pczt_prove path. let branch = BranchId::try_from(*pczt.global().consensus_branch_id()).map_err(|e| { - Error::PcztSend(format!("PCZT has an unknown consensus branch id: {:?}", e)) + Error::PcztSend(format!("PCZT has an unknown consensus branch id: {e:?}")) })?; let orchard_circuit_version = orchard_circuit_version(branch).ok_or_else(|| { Error::PcztSend(format!( - "Cannot verify Orchard proofs for consensus branch {:?}", - branch + "Cannot verify Orchard proofs for consensus branch {branch:?}" )) })?; let prover = LocalTxProver::bundled(); @@ -871,8 +951,10 @@ where )) })?; drop(db); + let txid_hex = hex::encode(txid.as_ref()); self.send_authorized_transactions(&NonEmpty::new(txid)) - .await + .await?; + Ok(txid_hex) } pub fn pczt_combine(&self, pczts: Vec) -> Result { diff --git a/packages/snap/CHANGELOG.md b/packages/snap/CHANGELOG.md new file mode 100644 index 0000000..a8b37a7 --- /dev/null +++ b/packages/snap/CHANGELOG.md @@ -0,0 +1,38 @@ +# Changelog + +All notable changes to the Zcash WebZjs Snap are documented here. + +## [1.1.0] — unreleased (NU7) + +### Added +- NU7 portable (v2) key derivation, key export (`exportZcashSecret`), and the + v1→v2 account migration (`getPortableAddress`, `completeMigration`, + `signMigration`). +- Ironwood (NU6.3) pool support in the trusted-display and signing paths. + +### Security +- `signPczt`: warn when a transaction has more than one non-change output (a split + payment could otherwise match the claimed total and suppress every warning). +- `signPczt`: the self-migration "✓ your own wallet" confirmation now also requires + the clean-path-A check — a self-migration carrying an extra third-party payment is + flagged, not shown as green. +- `pczt_describe`: a transparent output whose recipient cannot be recovered is marked + unverified, so `pczt_validate` refuses it instead of signing behind a "refused" + label. +- `setSnapStete`: strict schema; the derivation version can no longer be changed by a + caller (the switch is gated by `completeMigration`). +- `setBirthdayBlock` / sync start: the chain tip is validated and the start height is + clamped to NU5 on every path, preventing a scan-from-genesis denial of service. +- `getViewingKey`, `getPortableAddress`, `exportZcashSecret`: network and account are + no longer caller-supplied. +- Input hardening: PCZT hex must be even length; `getViewingKey` no longer masks a + user rejection as a generation failure. + +### Changed +- Export dialog no longer over-promises cross-wallet portability; it names only the + wallet we verified and tells users to confirm their full balance after import. +- Install dialog name matches the manifest (`Zcash WebZjs Wallet`). + +### Migration notes +- Requires the web wallet to request version `>= 1.1.0`; connecting with an older + Snap now prompts an update instead of failing with "Method not found". diff --git a/packages/snap/package.json b/packages/snap/package.json index 0f0a7c4..82f4a1e 100644 --- a/packages/snap/package.json +++ b/packages/snap/package.json @@ -1,6 +1,6 @@ { "name": "@zcashcommunitygrants/webzjs-zcash-snap", - "version": "1.0.2", + "version": "1.1.0", "description": "Zcash Metmamask Snap that utilizes WebZjs.", "repository": { "type": "git", diff --git a/packages/snap/snap.manifest.json b/packages/snap/snap.manifest.json index e1096a4..96ad991 100644 --- a/packages/snap/snap.manifest.json +++ b/packages/snap/snap.manifest.json @@ -1,5 +1,5 @@ { - "version": "1.0.2", + "version": "1.1.0", "description": "WebZjs Snap for Zcash wallet", "proposedName": "Zcash WebZjs Wallet", "repository": { @@ -7,7 +7,7 @@ "url": "https://github.com/ZcashCommunityGrants/WebZjs.git" }, "source": { - "shasum": "CAGcWn2ZLrGZthcSubOcsW/tHcOpga3uF3gYpwCKMoU=", + "shasum": "CvL0mIg7jA50LolmVNknpSvIDCSDTAivbaAxKecystU=", "location": { "npm": { "filePath": "dist/bundle.js", @@ -22,11 +22,7 @@ "endowment:lifecycle-hooks": {}, "endowment:webassembly": {}, "endowment:rpc": { - "allowedOrigins": [ - "https://webzjs.red.dev", - "http://localhost:3000", - "http://app-provider.localhost:3000" - ] + "allowedOrigins": ["https://webzjs.red.dev"] }, "snap_getBip44Entropy": [ { diff --git a/packages/snap/src/index.tsx b/packages/snap/src/index.tsx index 61851f5..6733e5c 100644 --- a/packages/snap/src/index.tsx +++ b/packages/snap/src/index.tsx @@ -12,10 +12,11 @@ import { SetBirthdayBlockParams, SignPcztParams, SnapState } from './types'; import { setSnapState } from './rpc/setSnapState'; import { signPczt } from './rpc/signPczt' -import { assert, object, number, optional, string } from 'superstruct'; +import { assert, object, number, optional, string, boolean, nullable } from 'superstruct'; import { getSeedFingerprint } from './rpc/getSeedFingerprint'; import { exportZcashSecret } from './rpc/exportSecret'; import { getPortableAddress, completeMigration } from './rpc/migrate'; +import { signMigration, SignMigrationParams } from './rpc/signMigration'; import type { OnInstallHandler } from "@metamask/snaps-sdk"; import { installDialog } from './utils/dialogs'; @@ -47,22 +48,43 @@ export const onRpcRequest: OnRpcRequestHandler = async ({ request, origin }) => }), })); return await signPczt(request.params as SignPcztParams, origin); + case 'signMigration': + assert(request.params, object({ pcztHexTring: string() })); + return await signMigration(request.params as unknown as SignMigrationParams, origin); case 'getSeedFingerprint': return await getSeedFingerprint(); case 'exportZcashSecret': - return await exportZcashSecret(); + return await exportZcashSecret(origin); case 'getPortableAddress': - return await getPortableAddress(); + return await getPortableAddress(origin); case 'completeMigration': - return await completeMigration(); + return await completeMigration(origin); case 'setBirthdayBlock': - assert(request.params, object({ latestBlock: optional(number()) })); + // latestBlock is required: an absent value put NaN into the sync-start height. + assert(request.params, object({ latestBlock: number() })); return await setBirthdayBlock(request.params as SetBirthdayBlockParams); case 'getSnapStete': return await getSnapState(); - case 'setSnapStete': - const setSnapStateParams = request.params as unknown as SnapState; - return await setSnapState(setSnapStateParams); + case 'setSnapStete': { + // Strict schema. derivationVersion is accepted but ignored (preserved by + // setSnapState; the switch is gated by completeMigration). + assert( + request.params, + object({ + webWalletSyncStartBlock: string(), + lastKnownBalance: nullable( + object({ + shielded: number(), + unshielded: number(), + timestamp: number(), + }), + ), + hasPendingTx: nullable(boolean()), + derivationVersion: optional(number()), + }), + ); + return await setSnapState(request.params as unknown as SnapState); + } default: throw new Error('Method not found.'); } @@ -79,6 +101,7 @@ export const onUserInput: OnUserInputHandler = async ({ id, event }) => { value: event.value, }, }); + break; default: break; diff --git a/packages/snap/src/rpc/exportSecret.tsx b/packages/snap/src/rpc/exportSecret.tsx index 2fb287a..ca9ab67 100644 --- a/packages/snap/src/rpc/exportSecret.tsx +++ b/packages/snap/src/rpc/exportSecret.tsx @@ -22,10 +22,10 @@ type Network = 'main' | 'test'; * Reveal the account's portable (v2) BIP-39 phrase + viewing key for import into a * standard Zcash wallet. SECURITY: shown only in the Snap dialog, never returned to the dApp. */ -export async function exportZcashSecret( - network: Network = NETWORK, - accountIndex: number = 0, -): Promise { +export async function exportZcashSecret(origin: string): Promise { + // Hardcoded, not caller-supplied: request.params must not choose network/account. + const network: Network = NETWORK; + const accountIndex = 0; // 1. Confirm-to-reveal. No secret is derived or shown until the user approves. const confirmed = await snap.request({ method: 'snap_dialog', @@ -36,8 +36,8 @@ export async function exportZcashSecret( Reveal your Zcash recovery phrase? - You are about to reveal the secret recovery phrase for your Zcash - wallet. Make sure no one can see your screen. + {origin} requested to reveal the secret recovery phrase + for your Zcash wallet. Make sure no one can see your screen. @@ -81,8 +81,15 @@ export async function exportZcashSecret( Your Zcash wallet recovery phrase - Import these 24 words into another Zcash wallet (e.g. Zkool or Zodl) - to access this wallet there. Keep them secret and safe. + Import these 24 words into another Zcash wallet (e.g. Zodl or Zkool) to + access this wallet there. Keep them secret and safe. + + + + Before you rely on another wallet, confirm it shows your full balance. + {' '} + Some wallets handle change addresses differently and may display only + part of your funds after import. {onLegacy ? ( diff --git a/packages/snap/src/rpc/getViewingKey.tsx b/packages/snap/src/rpc/getViewingKey.tsx index 2ae3302..d7a1655 100644 --- a/packages/snap/src/rpc/getViewingKey.tsx +++ b/packages/snap/src/rpc/getViewingKey.tsx @@ -5,43 +5,39 @@ import { NETWORK } from '../config'; type Network = 'main' | 'test'; -export async function getViewingKey( - origin: string, - network: Network = NETWORK, - accountIndex: number = 0, -) { +export async function getViewingKey(origin: string) { + // Hardcoded, not caller-supplied: request.params must not choose network/account. + const network: Network = NETWORK; + const accountIndex = 0; - try { - // Retrieve the seed for this account's active derivation version - const seed = await getSeed(await getActiveDerivationVersion()); + // Retrieve the seed for this account's active derivation version + const seed = await getSeed(await getActiveDerivationVersion()); - // Generate the UnifiedSpendingKey and obtain the Viewing Key - const spendingKey = new UnifiedSpendingKey(network, seed, accountIndex); - const viewingKey = spendingKey.to_unified_full_viewing_key().encode(network); + // Generate the UnifiedSpendingKey and obtain the Viewing Key + const spendingKey = new UnifiedSpendingKey(network, seed, accountIndex); + const viewingKey = spendingKey.to_unified_full_viewing_key().encode(network); - const dialogApproved = await snap.request({ - method: 'snap_dialog', - params: { - type: 'confirmation', - content: ( - - Reveal Viewing Key to the {origin} - - Web wallet {origin} needs access to the Viewing Key, approve this dialog to give permission. The Web Wallet account is serialized and stored only locally in your browser. - Approving gives {origin} your Zcash viewing key, a permanent window into this wallet. It cannot move your money, but whoever holds it can see everything this wallet receives and sends, forever. Do not approve unless you trust this site with this wallet's full financial history. - - - - ), - }, - }); + const dialogApproved = await snap.request({ + method: 'snap_dialog', + params: { + type: 'confirmation', + content: ( + + Reveal Viewing Key to the {origin} + + Web wallet {origin} needs access to the Viewing Key, approve this dialog to give permission. The Web Wallet account is serialized and stored only locally in your browser. + Approving gives {origin} your Zcash viewing key, a permanent window into this wallet. It cannot move your money, but whoever holds it can see everything this wallet receives and sends, forever. Do not approve unless you trust this site with this wallet's full financial history. + + + + ), + }, + }); - if (!dialogApproved) { - throw new Error('User rejected'); - } - - return viewingKey - } catch (error) { - throw new Error('Failed to generate Viewing Key'); + // Surface the real outcome instead of masking a rejection as a generation failure. + if (!dialogApproved) { + throw new Error('User rejected the viewing key request'); } + + return viewingKey; } diff --git a/packages/snap/src/rpc/migrate.tsx b/packages/snap/src/rpc/migrate.tsx index 2f092cc..c6c0879 100644 --- a/packages/snap/src/rpc/migrate.tsx +++ b/packages/snap/src/rpc/migrate.tsx @@ -7,12 +7,36 @@ type Network = 'main' | 'test'; /** * Default unified (shielded) address of the portable (v2) account — the destination - * for a v1 → v2 migration sweep. Public, so safe to return to the dApp. + * for a v1 → v2 migration sweep. Not secret, but it is a stable identifier for this + * MetaMask user, so (like every other identity-revealing RPC here) it is gated by a + * user confirmation that names the requesting origin. */ -export async function getPortableAddress( - network: Network = NETWORK, - accountIndex: number = 0, -): Promise { +export async function getPortableAddress(origin: string): Promise { + // Hardcoded, not caller-supplied: request.params must not choose network/account. + const network: Network = NETWORK; + const accountIndex = 0; + const approved = await snap.request({ + method: 'snap_dialog', + params: { + type: 'confirmation', + content: ( + + Share your portable Zcash address? + + + {origin} is requesting the receiving address of your + portable Zcash account. This is where your funds move during + migration. It is not secret, but only approve if you trust this site. + + + ), + }, + }); + + if (!approved) { + throw new Error('User rejected'); + } + const seed = await getSeed(PORTABLE_DERIVATION_VERSION); const spendingKey = new UnifiedSpendingKey(network, seed, accountIndex); return spendingKey @@ -24,7 +48,7 @@ export async function getPortableAddress( * Stamp `derivationVersion: 2` into Snap state to commit the portable switch. Gated by a * confirmation; call only AFTER the sweep is broadcast, else v2 shows empty while funds sit in v1. */ -export async function completeMigration(): Promise { +export async function completeMigration(origin: string): Promise { const confirmed = await snap.request({ method: 'snap_dialog', params: { @@ -33,6 +57,9 @@ export async function completeMigration(): Promise { Switch to your portable Zcash account? + + Requested by {origin}. + Confirm only after your funds have finished moving to the portable account. From now on this wallet will use the portable account, whose diff --git a/packages/snap/src/rpc/setBirthdayBlock.tsx b/packages/snap/src/rpc/setBirthdayBlock.tsx index fd21c96..40f8cdf 100644 --- a/packages/snap/src/rpc/setBirthdayBlock.tsx +++ b/packages/snap/src/rpc/setBirthdayBlock.tsx @@ -107,7 +107,8 @@ export async function setBirthdayBlock({ method: 'snap_manageState', params: { operation: 'update', - newState: { ...existing, webWalletSyncStartBlock }, + // Stored as a string to match the SnapState contract and the web wallet. + newState: { ...existing, webWalletSyncStartBlock: String(webWalletSyncStartBlock) }, }, }); diff --git a/packages/snap/src/rpc/setSnapState.tsx b/packages/snap/src/rpc/setSnapState.tsx index a573fcf..82590a0 100644 --- a/packages/snap/src/rpc/setSnapState.tsx +++ b/packages/snap/src/rpc/setSnapState.tsx @@ -1,12 +1,31 @@ import { Json } from '@metamask/snaps-sdk'; import { SnapState } from 'src/types'; +/** + * Update Snap state on behalf of the dApp. + * + * `derivationVersion` is the consent gate for the one-way v1 → v2 switch and is NOT + * writable through this path: whatever the caller sends for it is discarded, and the + * stored value is always preserved. It can only change via completeMigration, which is + * behind its own user confirmation. This keeps the trust boundary in the Snap, not the dApp. + */ export async function setSnapState(newSnapState: SnapState): Promise { + const existing = (await snap.request({ + method: 'snap_manageState', + params: { operation: 'get' }, + })) as Record | null; + + const preserved: SnapState = { ...newSnapState }; + delete preserved.derivationVersion; + if (existing && typeof existing.derivationVersion === 'number') { + preserved.derivationVersion = existing.derivationVersion; + } + const state = (await snap.request({ method: 'snap_manageState', params: { operation: 'update', - newState: newSnapState, + newState: preserved, }, })) as unknown as Json; diff --git a/packages/snap/src/rpc/signMigration.tsx b/packages/snap/src/rpc/signMigration.tsx new file mode 100644 index 0000000..152ff95 --- /dev/null +++ b/packages/snap/src/rpc/signMigration.tsx @@ -0,0 +1,171 @@ +import { + Bold, + Box, + Copyable, + Divider, + Heading, + Text, +} from '@metamask/snaps-sdk/jsx'; +import { + SeedFingerprint, + UnifiedSpendingKey, + pczt_describe, + pczt_validate, + pczt_sign, + Pczt, +} from '@zcashcommunitygrants/webzjs-keys'; +import { + getSeed, + getActiveDerivationVersion, + PORTABLE_DERIVATION_VERSION, +} from '../utils/getSeed'; +import { NETWORK } from '../config'; + +const ZATS_PER_ZEC = 100_000_000n; + +export type SignMigrationParams = { + pcztHexTring: string; +}; + +/** A single output recovered from a PCZT by `pczt_describe`. */ +type PcztOutputSummary = { + pool: string; + recipient: string | null; + value: number | bigint; + memo: string | null; + is_change: boolean; + is_ours: boolean; + verified: boolean; +}; + +type PcztSummary = { + network: string; + outputs: PcztOutputSummary[]; + total_in: number | bigint; + total_out: number | bigint; + fee: number | bigint; + migration: unknown; +}; + +function zatsToZec(zats: number | bigint): string { + const z = BigInt(zats); + const frac = (z % ZATS_PER_ZEC).toString().padStart(8, '0'); + return `${z / ZATS_PER_ZEC}.${frac}`; +} + +/** + * Sign the one-time v1 → v2 migration sweep. The Snap re-derives v2 itself and refuses + * unless every output is change or a payment to v2 — the dApp cannot swap the destination. + */ +export async function signMigration( + { pcztHexTring }: SignMigrationParams, + origin: string, +): Promise { + // Odd-length hex would be silently truncated by Buffer.from. + if (!/^[0-9a-fA-F]+$/.test(pcztHexTring) || pcztHexTring.length % 2 !== 0) { + throw new Error('pcztHexTring must be valid, even-length hex'); + } + const pczt = Pczt.from_bytes(new Uint8Array(Buffer.from(pcztHexTring, 'hex'))); + + // Signing key = the account that owns the spent notes (pre-switch this is v1). + const activeVersion = await getActiveDerivationVersion(); + const seedActive = await getSeed(activeVersion); + const uskActive = new UnifiedSpendingKey(NETWORK, seedActive, 0); + const ufvkActive = uskActive.to_unified_full_viewing_key(); + const seedFp = new SeedFingerprint(seedActive); + + // Portable (v2) account — the only permitted destination for the sweep. + const seedV2 = await getSeed(PORTABLE_DERIVATION_VERSION); + const ufvkV2 = new UnifiedSpendingKey(NETWORK, seedV2, 0) + .to_unified_full_viewing_key(); + + // --- Layer B: hard gate under the signing key (spends are ours, value + // balances, fee is sane). Same protection the ordinary signing path applies. + try { + pczt_validate(NETWORK, pczt, ufvkActive); + } catch (e) { + throw new Error( + `This migration failed safety validation and will not be signed: ${ + e instanceof Error ? e.message : String(e) + }`, + ); + } + + // Describe the SAME PCZT under both keys; the deterministic walk lines up outputs by + // index: `active` flags change to the signer, `v2` flags payments to the portable account. + let active: PcztSummary; + let v2: PcztSummary; + try { + active = pczt_describe(NETWORK, pczt, ufvkActive) as PcztSummary; + v2 = pczt_describe(NETWORK, pczt, ufvkV2) as PcztSummary; + } catch (e) { + throw new Error( + `Unable to read the migration transaction: ${ + e instanceof Error ? e.message : String(e) + }`, + ); + } + if (active.outputs.length !== v2.outputs.length) { + throw new Error('Migration PCZT inspection was inconsistent; refusing to sign.'); + } + + // Enforce: every output is either change to the signing account, or a payment to + // the portable (v2) account. Anything else is a swapped destination — reject. + let sweptToPortable = 0n; + for (let i = 0; i < active.outputs.length; i++) { + const out = active.outputs[i]; + const v2Out = v2.outputs[i]; + if (!out || !v2Out) { + throw new Error('Migration PCZT inspection was inconsistent; refusing to sign.'); + } + const isChangeToSelf = out.is_change; + const isToPortable = v2Out.is_ours; + if (isChangeToSelf) continue; + if (isToPortable) { + sweptToPortable += BigInt(out.value); + continue; + } + throw new Error( + 'Refusing to sign: this migration pays an address that is NOT your ' + + 'portable account. The destination may have been tampered with.', + ); + } + if (sweptToPortable === 0n) { + throw new Error('Refusing to sign: this migration moves nothing to your portable account.'); + } + + const content = ( + + Move funds to your portable Zcash account + Origin: {origin} + + + ✓ Destination verified as your own portable account. The Snap + derived it and confirmed every payment lands there. + + + Moving {`${zatsToZec(sweptToPortable)} ZEC`} · Fee:{' '} + {`${zatsToZec(active.fee)} ZEC`} + + + After you approve, your browser may freeze for a few minutes while the + transaction is proved. This is normal — keep the tab open until it finishes. + + + Raw PCZT + + + ); + + const approved = await snap.request({ + method: 'snap_dialog', + params: { type: 'confirmation', content }, + }); + + if (!approved) { + throw new Error('User rejected'); + } + + const pcztSigned = await pczt_sign(NETWORK, pczt, uskActive, seedFp); + return Buffer.from(pcztSigned.serialize()).toString('hex'); +} diff --git a/packages/snap/src/rpc/signPczt.tsx b/packages/snap/src/rpc/signPczt.tsx index 24ece68..2c11c87 100644 --- a/packages/snap/src/rpc/signPczt.tsx +++ b/packages/snap/src/rpc/signPczt.tsx @@ -86,8 +86,9 @@ export async function signPczt( { pcztHexTring, signDetails }: SignPcztParams, origin: string, ): Promise { - if (!/^[0-9a-fA-F]+$/.test(pcztHexTring)) { - throw new Error('pcztHexTring must be valid hex'); + // Odd-length hex would be silently truncated by Buffer.from. + if (!/^[0-9a-fA-F]+$/.test(pcztHexTring) || pcztHexTring.length % 2 !== 0) { + throw new Error('pcztHexTring must be valid, even-length hex'); } const pcztUint8Array = new Uint8Array(Buffer.from(pcztHexTring, 'hex')); const pczt = Pczt.from_bytes(pcztUint8Array); @@ -129,14 +130,16 @@ export async function signPczt( 0n, ); - // Defense-in-depth: compare the site's claim against the verified output. - // The amount is authoritative; the recipient is shown for the user to eyeball - // (a full Unified Address won't string-match our orchard-only re-encoding). + // Defense-in-depth: compare the site's claim against what the PCZT actually does. const claimedZats = zecToZats(signDetails.amount); const amountMatches = claimedZats === verifiedOutgoing; - const recipientMatches = recipientOutputs.some( - (o) => o.recipient === signDetails.recipient, - ); + + // Warn on extra outputs: a split payment can match the claimed total while routing + // value to an attacker, so the aggregate amount check alone is not enough. + const multiplePayments = recipientOutputs.length > 1; + + // No recipient string-match warning: a full UA never equals our per-pool re-encoding, + // so it false-fires on every send. Recipients are shown; extras are caught above. const verifiedSection = summary.outputs.flatMap((o) => [ @@ -168,14 +171,21 @@ export async function signPczt( pool boundary exposes the transfer amount; approving is your consent to make it public. - {migration.to_self ? ( + {migration.to_self && migration.is_clean_path_a ? ( ✓ Destination is your own wallet (self-migration). - ) : ( + ) : !migration.to_self ? ( ⚠ WARNING: this does NOT migrate to your own wallet. The Ironwood funds go to another address. Do not approve unless you intend to send them away. + ) : ( + + ⚠ WARNING: this is not a clean self-migration. Besides the + migration to your own wallet, this transaction carries additional + payments. Check every "Pays:" line above and do not approve unless you + intend them. + )} @@ -208,13 +218,19 @@ export async function signPczt( ) : ( )} - {!recipientMatches ? ( + {multiplePayments ? ( - ⚠ Confirm the verified recipient above matches who you intended to pay. + ⚠ WARNING: this transaction has{' '} + {String(recipientOutputs.length)} separate payments, but the site + described a single recipient. Check every "Pays:" line above — funds may + be going somewhere you did not intend. ) : ( )} + + Confirm the verified recipient(s) above match who you intended to pay. + Raw PCZT diff --git a/packages/snap/src/utils/dialogs.tsx b/packages/snap/src/utils/dialogs.tsx index d16e83f..12d52b0 100644 --- a/packages/snap/src/utils/dialogs.tsx +++ b/packages/snap/src/utils/dialogs.tsx @@ -7,7 +7,7 @@ export const installDialog = async () => { type: 'alert', content: ( - Thank you for installing Zcash Shielded Wallet snap + Thank you for installing Zcash WebZjs Wallet This snap utilizes Zcash Web Wallet. Visit Zcash Web Wallet at{' '} diff --git a/packages/snap/src/utils/getSeed.ts b/packages/snap/src/utils/getSeed.ts index 8f0eaed..f3f2970 100644 --- a/packages/snap/src/utils/getSeed.ts +++ b/packages/snap/src/utils/getSeed.ts @@ -47,12 +47,11 @@ async function getEntropyBytes(): Promise { } /** - * Derive the ZIP-32 seed for `version` (defaults to legacy v1 so existing funds are - * unaffected). Returns 32 bytes for v1, a 64-byte BIP-39 seed for v2. + * Derive the ZIP-32 seed for `version`. Returns 32 bytes for v1, a 64-byte BIP-39 + * seed for v2. The caller must pass the version explicitly: a forgotten argument + * should be a type error, not a silent fall-through to the wrong key. */ -export async function getSeed( - version: DerivationVersion = LEGACY_DERIVATION_VERSION, -): Promise { +export async function getSeed(version: DerivationVersion): Promise { const entropy = await getEntropyBytes(); if (version === LEGACY_DERIVATION_VERSION) { diff --git a/packages/snap/src/utils/setSyncBlockHeight.ts b/packages/snap/src/utils/setSyncBlockHeight.ts index 39b48f8..41ae21c 100644 --- a/packages/snap/src/utils/setSyncBlockHeight.ts +++ b/packages/snap/src/utils/setSyncBlockHeight.ts @@ -5,6 +5,12 @@ export function setSyncBlockHeight( userInputCreationBlock: string | null, latestBlock: number, ): number { + // Guard a bogus chain tip (1, NaN, negative): never start the scan below NU5, or + // the wallet scans from genesis at full CPU — a persisted denial of service. + if (!Number.isInteger(latestBlock) || latestBlock < NU5_ACTIVATION) { + return NU5_ACTIVATION; + } + //In case input was empty, default to latestBlock if (userInputCreationBlock === null) return latestBlock; diff --git a/packages/web-wallet/src/App.tsx b/packages/web-wallet/src/App.tsx index 3b09c22..f33639c 100644 --- a/packages/web-wallet/src/App.tsx +++ b/packages/web-wallet/src/App.tsx @@ -21,7 +21,7 @@ function App() {
Attention - this snap is under active development to bring it up to date - with the latest NU 6.3 update. Users may experience various issues until this update is + with the latest NU 7 update. Users may experience various issues until this update is completed and should exercise caution if using the snap until the update is complete and this banner is removed.
diff --git a/packages/web-wallet/src/config/constants.ts b/packages/web-wallet/src/config/constants.ts index 2f69c78..4c1287a 100644 --- a/packages/web-wallet/src/config/constants.ts +++ b/packages/web-wallet/src/config/constants.ts @@ -12,8 +12,10 @@ export const LIGHTWALLETD_PROXY = process.env.LIGHTWALLETD_PROXY || (NETWORK === 'test' ? TESTNET_PROXY : MAINNET_PROXY); -// Back-compat alias for existing imports. -export const MAINNET_LIGHTWALLETD_PROXY = LIGHTWALLETD_PROXY; export const ZATOSHI_PER_ZEC = 1e8; export const RESCAN_INTERVAL = 35000; // 35s sync interval export const NU5_ACTIVATION = 1687104; + +// Minimum Snap version; passed to wallet_requestSnaps so an outdated Snap updates on +// connect instead of failing with "Method not found" on the new RPCs. +export const REQUIRED_SNAP_VERSION = '1.1.0'; diff --git a/packages/web-wallet/src/context/WebzjsContext.tsx b/packages/web-wallet/src/context/WebzjsContext.tsx index baba992..850c565 100644 --- a/packages/web-wallet/src/context/WebzjsContext.tsx +++ b/packages/web-wallet/src/context/WebzjsContext.tsx @@ -134,6 +134,10 @@ export const WebZjsProvider = ({ children }: { children: React.ReactNode }) => { dispatch({ type: 'set-web-wallet', payload: wallet }); + // DEV-ONLY: expose the wallet for console inspection (per-pool balances, addresses). + if (process.env.NODE_ENV !== 'production') + (window as unknown as { __webWallet?: WebWallet }).__webWallet = wallet; + // Retrieve summary (accounts, balances, etc.) const summary = await wallet.get_wallet_summary(); if (summary) { diff --git a/packages/web-wallet/src/hooks/snaps/useGetSnapState.ts b/packages/web-wallet/src/hooks/snaps/useGetSnapState.ts index 50881d9..a78a1b7 100644 --- a/packages/web-wallet/src/hooks/snaps/useGetSnapState.ts +++ b/packages/web-wallet/src/hooks/snaps/useGetSnapState.ts @@ -1,24 +1,9 @@ import { useCallback } from 'react'; import { useInvokeSnap } from './useInvokeSnap'; -/** - * Cached balance stored in snap state for recovery after cookie/IndexedDB clears. - */ -export type LastKnownBalance = { - shielded: number; // sapling + orchard (in zats) - unshielded: number; // transparent (in zats) - timestamp: number; // When last updated (ms) -}; - -/** - * Snap persistent state stored via snap_manageState. - * Uses `| null` instead of optional to match snap's Json-compatible type. - */ -export interface SnapState { - webWalletSyncStartBlock: string; - lastKnownBalance: LastKnownBalance | null; - hasPendingTx: boolean | null; -} +// Single source of truth for the Snap state shape. +export type { LastKnownBalance, SnapState } from '../../types/snap'; +import type { SnapState } from '../../types/snap'; export const useGetSnapState = () => { const invokeSnap = useInvokeSnap(); diff --git a/packages/web-wallet/src/hooks/useMigration.ts b/packages/web-wallet/src/hooks/useMigration.ts index 0c35f59..ba5c891 100644 --- a/packages/web-wallet/src/hooks/useMigration.ts +++ b/packages/web-wallet/src/hooks/useMigration.ts @@ -1,20 +1,22 @@ -import { useState } from 'react'; +import { useCallback, useEffect, useState } from 'react'; +import { get, set, del } from 'idb-keyval'; import { Pczt } from '@zcashcommunitygrants/webzjs-wallet'; +import { provePcztInWorker } from '../workers/proverClient'; import { Buffer } from 'buffer'; import { useWebZjsContext } from '../context/WebzjsContext'; import { useMetaMaskContext } from '../context/MetamaskContext'; import { useInvokeSnap } from './snaps/useInvokeSnap'; import { useWebZjsActions } from './useWebzjsActions'; import useBalance from './useBalance'; -import { zatsToZec } from '../utils'; -import { SignPcztDetails } from '../types/snap'; -/** - * Fee buffer (zatoshis) held back from the sweep so the migration transaction's - * ZIP-317 fee is covered. Any remainder below this stays as dust in the legacy - * account (recoverable later) — never lost. - */ -const MIGRATION_FEE_BUFFER = 20_000; // 0.0002 ZEC +// IndexedDB key: the txid of a broadcast-but-not-yet-committed migration sweep. +// Its presence means "a sweep is in flight; finish the switch, don't start a new one." +const PENDING_MIGRATION_TXID_KEY = 'pendingMigrationTxid'; + +// How long to wait for the sweep to be mined before giving up (the switch can still +// be finished later via `finishSwitching`). Poll roughly every 8s. +const MINED_POLL_MS = 8_000; +const MINED_MAX_ATTEMPTS = 75; // ~10 minutes export enum MigrationStatus { IDLE = 'Idle', @@ -23,6 +25,7 @@ export enum MigrationStatus { SIGNING = 'Signing with your current key', PROVING = 'Proving transaction', SENDING = 'Moving your funds', + CONFIRMING = 'Waiting for the transaction to confirm', STAMPING = 'Switching to the portable account', RESYNCING = 'Refreshing your wallet', DONE = 'Migration complete', @@ -31,25 +34,166 @@ export enum MigrationStatus { interface IUseMigration { migrateToPortable: () => Promise; + finishSwitching: () => Promise; migrationStatus: MigrationStatus; migrationError: string | null; + /** True if a sweep was broadcast but the switch to v2 hasn't been committed yet. */ + hasPendingMigration: boolean; } /** - * Orchestrates the one-time v1 (legacy) → v2 (portable) sweep: moves the legacy - * account's balance to the portable address, then commits the derivation switch. + * One-time v1 → v2 sweep: move the balance to the portable address, wait for ≥1 + * confirmation, then commit the switch. The txid is persisted so it can be resumed. */ export const useMigration = (): IUseMigration => { const { state } = useWebZjsContext(); const invokeSnap = useInvokeSnap(); const { flushDbToStore, fullResync } = useWebZjsActions(); const { refreshSnapState } = useMetaMaskContext(); - const { spendableBalance } = useBalance(); + const { + shieldedBalance, + unshieldedBalance, + totalPending, + isCached, + loading: balanceLoading, + } = useBalance(); const [migrationStatus, setMigrationStatus] = useState( MigrationStatus.IDLE, ); const [migrationError, setMigrationError] = useState(null); + const [hasPendingMigration, setHasPendingMigration] = useState(false); + + // On mount, surface any in-flight migration so the UI can offer "Finish switching". + useEffect(() => { + (async () => { + try { + const txid = (await get(PENDING_MIGRATION_TXID_KEY)) as string | undefined; + setHasPendingMigration(!!txid); + } catch { + /* idb unavailable — treat as no pending migration */ + } + })(); + }, []); + + const activeAccount = (): number | null => + state.activeAccount === null || state.activeAccount === undefined + ? null + : state.activeAccount; + + /** + * Poll until the sweep `txid` is mined (≥1 confirmation). Throws if it expires or if + * it hasn't confirmed within the time budget (the caller can retry via finishSwitching). + */ + const waitForSweepMined = useCallback( + async (account: number, txid: string): Promise => { + if (!state.webWallet) throw new Error('Wallet is not ready.'); + // Read-only polling: App.tsx background sync advances scanning; we just watch + // the history rather than calling sync() ourselves and racing it. + for (let attempt = 0; attempt < MINED_MAX_ATTEMPTS; attempt++) { + try { + const history = await state.webWallet.get_transaction_history( + account, + 50, + 0, + ); + const txs = (history.transactions ?? []) as Array<{ + txid: string; + status: string; + confirmations: number; + }>; + const entry = txs.find((t) => t.txid === txid); + if (entry) { + if (entry.status === 'Expired') { + throw new Error( + 'The migration transaction expired before it was mined. Your ' + + 'funds are still in your legacy account — please migrate again.', + ); + } + if (entry.status === 'Confirmed' || entry.confirmations >= 1) { + return; + } + } + } catch (e) { + if (e instanceof Error && e.message.includes('expired')) throw e; + console.warn('Migration: could not read tx history while waiting', e); + } + await new Promise((r) => setTimeout(r, MINED_POLL_MS)); + } + throw new Error( + 'Timed out waiting for the migration to confirm. It may still confirm on ' + + 'its own — use "Finish switching" shortly to complete the switch.', + ); + }, + [state.webWallet], + ); + + /** + * With the sweep mined, commit the v1 → v2 switch: confirm in the Snap, clear the + * pending marker, then re-import onto v2 and refresh. Safe to call more than once. + */ + const commitSwitch = useCallback(async (): Promise => { + setMigrationStatus(MigrationStatus.STAMPING); + const stamped = (await invokeSnap({ + method: 'completeMigration', + })) as boolean; + if (!stamped) { + // User declined the final confirmation. Funds are already in the portable + // account; keep the pending marker so they can finish the switch later. + setMigrationError( + 'Your funds are in your portable account, but the switch was not ' + + 'confirmed. Use "Finish switching" to complete it — do not migrate again.', + ); + setMigrationStatus(MigrationStatus.ERROR); + return; + } + + await del(PENDING_MIGRATION_TXID_KEY).catch(() => undefined); + setHasPendingMigration(false); + + setMigrationStatus(MigrationStatus.RESYNCING); + await fullResync(); + await refreshSnapState(); + setMigrationStatus(MigrationStatus.DONE); + }, [invokeSnap, fullResync, refreshSnapState]); + + // Resume an in-flight migration: wait for the recorded sweep to mine, then switch. + const resume = useCallback( + async (account: number, txid: string): Promise => { + setMigrationStatus(MigrationStatus.CONFIRMING); + await waitForSweepMined(account, txid); + await commitSwitch(); + }, + [waitForSweepMined, commitSwitch], + ); + + const finishSwitching = useCallback(async (): Promise => { + setMigrationError(null); + const account = activeAccount(); + if (account === null) { + setMigrationError('No active account.'); + return; + } + let txid: string | undefined; + try { + txid = (await get(PENDING_MIGRATION_TXID_KEY)) as string | undefined; + } catch { + /* fall through to the no-pending message */ + } + if (!txid) { + setMigrationError('There is no migration to finish.'); + return; + } + try { + await resume(account, txid); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error('Finish switching failed:', error); + setMigrationError(message); + setMigrationStatus(MigrationStatus.ERROR); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [resume, state.activeAccount]); const migrateToPortable = async (): Promise => { setMigrationError(null); @@ -58,23 +202,59 @@ export const useMigration = (): IUseMigration => { setMigrationError('Wallet is not ready. Please wait for sync to finish.'); return; } - const account = - state.activeAccount === null || state.activeAccount === undefined - ? null - : state.activeAccount; + const account = activeAccount(); if (account === null) { setMigrationError('No active account to migrate.'); return; } - const sweepZats = spendableBalance - MIGRATION_FEE_BUFFER; - if (sweepZats <= 0) { + // Resume instead of re-sweeping: if a sweep is already in flight, finishing the + // switch is the right action (a second sweep would fail — v1 is already empty). + let pendingTxid: string | undefined; + try { + pendingTxid = (await get(PENDING_MIGRATION_TXID_KEY)) as string | undefined; + } catch { + /* idb unavailable; proceed as a fresh migration */ + } + if (pendingTxid) { + try { + await resume(account, pendingTxid); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error('Resume migration failed:', error); + setMigrationError(message); + setMigrationStatus(MigrationStatus.ERROR); + } + return; + } + + // Pre-flight checks for a clear reason instead of a raw Rust error. The Rust sweep + // also enforces these, but a readable message here avoids a confusing failure. + if (balanceLoading || isCached) { setMigrationError( - 'Not enough spendable balance to migrate (after the network fee). ' + - 'Wait for sync to finish, or there may be nothing to move.', + 'Still syncing. Wait for your balance to finish loading before migrating.', ); return; } + if (totalPending > 0) { + setMigrationError( + 'You have funds still confirming. Wait until nothing is pending, then ' + + 'migrate — otherwise those funds would be left behind.', + ); + return; + } + if (unshieldedBalance > 0) { + setMigrationError( + 'You have transparent (unshielded) funds. Shield them first from the ' + + 'Account page, then migrate. The sweep moves shielded funds only, so ' + + 'transparent balance would otherwise stay in the legacy account.', + ); + return; + } + if (shieldedBalance <= 0) { + setMigrationError('There is no shielded balance to migrate.'); + return; + } try { setMigrationStatus(MigrationStatus.PREPARING); @@ -84,63 +264,43 @@ export const useMigration = (): IUseMigration => { })) as string; setMigrationStatus(MigrationStatus.CREATING); - const sweepZec = zatsToZec(sweepZats).toString(); - const pczt = await state.webWallet.pczt_create( - account, - toAddress, - BigInt(sweepZats), - ); + // Full send-max sweep: moves the entire spendable shielded balance with an + // exact fee and no change, so nothing is stranded in the legacy account. + const pczt = await state.webWallet.pczt_sweep(account, toAddress); setMigrationStatus(MigrationStatus.SIGNING); - // Signed with the active (legacy v1) key — correct, since the spent notes - // belong to v1 and `derivationVersion` has not been switched yet. + // Signed via the migration RPC: the Snap re-derives v2 and refuses unless every + // output lands there. Signs with the active (v1) key that owns the spent notes. const pcztHexTring = Buffer.from(pczt.serialize()).toString('hex'); - const params: SignPcztDetails = { - pcztHexTring, - signDetails: { recipient: toAddress, amount: sweepZec }, - }; const signedHex = (await invokeSnap({ - method: 'signPczt', - params, + method: 'signMigration', + params: { pcztHexTring }, })) as string; const signedPczt = Pczt.from_bytes( new Uint8Array(Buffer.from(signedHex, 'hex')), ); setMigrationStatus(MigrationStatus.PROVING); - const provedPczt = await state.webWallet.pczt_prove(signedPczt); + // Prove in a worker: the Sapling Groth16 prover uses Atomics.wait, illegal on main. + const provedPczt = Pczt.from_bytes( + await provePcztInWorker(signedPczt.serialize()), + ); setMigrationStatus(MigrationStatus.SENDING); - await state.webWallet.pczt_send(provedPczt); + const txid = await state.webWallet.pczt_send(provedPczt); await flushDbToStore(); - // Only now that the funds are on their way do we commit the switch. - setMigrationStatus(MigrationStatus.STAMPING); - const stamped = (await invokeSnap({ - method: 'completeMigration', - })) as boolean; - if (!stamped) { - // User declined the final confirmation. The sweep is already broadcast; - // the funds are heading to the portable account, but the wallet stays on - // the legacy view until they complete the switch. Surface this clearly. - setMigrationError( - 'Funds were sent to your portable account, but the switch was not ' + - 'confirmed. Re-run the migration to finish switching.', - ); - setMigrationStatus(MigrationStatus.ERROR); - return; - } - - // Re-import the wallet onto the portable (v2) account and re-scan so the - // swept funds show up there. - setMigrationStatus(MigrationStatus.RESYNCING); - await fullResync(); + // Record the in-flight sweep BEFORE waiting, so a reload can resume it. The + // switch is NOT committed yet — only after the sweep actually mines. + await set(PENDING_MIGRATION_TXID_KEY, txid).catch(() => undefined); + setHasPendingMigration(true); - // Refresh the cached snap state so the UI sees derivationVersion = 2 and - // hides the "move funds to portable account" prompt now that the switch is done. - await refreshSnapState(); + // Wait for the sweep to be mined (not just broadcast) before switching. If it + // expires or is dropped, we stay on v1 rather than switching to an empty v2. + setMigrationStatus(MigrationStatus.CONFIRMING); + await waitForSweepMined(account, txid); - setMigrationStatus(MigrationStatus.DONE); + await commitSwitch(); } catch (error) { const message = error instanceof Error ? error.message : String(error); console.error('Migration failed:', error); @@ -149,5 +309,11 @@ export const useMigration = (): IUseMigration => { } }; - return { migrateToPortable, migrationStatus, migrationError }; + return { + migrateToPortable, + finishSwitching, + migrationStatus, + migrationError, + hasPendingMigration, + }; }; diff --git a/packages/web-wallet/src/hooks/usePCZT.ts b/packages/web-wallet/src/hooks/usePCZT.ts index 53321ce..55cb143 100644 --- a/packages/web-wallet/src/hooks/usePCZT.ts +++ b/packages/web-wallet/src/hooks/usePCZT.ts @@ -1,5 +1,6 @@ import { useWebZjsContext } from '../context/WebzjsContext'; import { Pczt } from '@zcashcommunitygrants/webzjs-wallet'; +import { provePcztInWorker } from '../workers/proverClient'; import { useInvokeSnap } from './snaps/useInvokeSnap'; import { zecToZats } from '../utils'; import { useWebZjsActions } from './useWebzjsActions'; @@ -60,7 +61,9 @@ export const usePczt = (): IUsePczt => { const provePczt = async (pczt: Pczt): Promise => { try { - return await state.webWallet!.pczt_prove(pczt); + // Prove in a worker: the Sapling Groth16 prover uses Atomics.wait, illegal on main. + const provedBytes = await provePcztInWorker(pczt.serialize()); + return Pczt.from_bytes(provedBytes); } catch (error) { console.error('Error proving PCZT:', error); throw error; diff --git a/packages/web-wallet/src/hooks/useWebzjsActions.ts b/packages/web-wallet/src/hooks/useWebzjsActions.ts index 84da448..e99b587 100644 --- a/packages/web-wallet/src/hooks/useWebzjsActions.ts +++ b/packages/web-wallet/src/hooks/useWebzjsActions.ts @@ -6,13 +6,22 @@ import { useMetaMask } from './snaps/useMetaMask'; import { useInvokeSnap } from './snaps/useInvokeSnap'; import { useRequestSnap } from './snaps/useRequestSnap'; import { SeedFingerprint, WebWallet } from '@zcashcommunitygrants/webzjs-wallet'; -import { NETWORK, LIGHTWALLETD_PROXY } from '../config/constants'; +import { NETWORK, LIGHTWALLETD_PROXY, REQUIRED_SNAP_VERSION, NU5_ACTIVATION } from '../config/constants'; import { SnapState } from '../types/snap'; // Synchronous guard: prevents triggerRescan from overlapping with fullResync. // Module-level so it's shared across all hook instances and immune to stale closures. let _fullResyncActive = false; +// Max sync passes per sync/resync call before giving up and letting the auto-sync +// interval continue catching up. +const MAX_SYNC_ROUNDS = 20; + +// Clamp a birthday to >= NU5: nothing shielded exists earlier, so a bogus value +// (1, NaN) would otherwise scan from near genesis at full CPU. +const clampBirthdayToNU5 = (b: number | undefined): number | undefined => + b === undefined || !Number.isFinite(b) ? undefined : Math.max(Math.floor(b), NU5_ACTIVATION); + interface SyncOptions { skipBalanceCache?: boolean; } @@ -51,7 +60,8 @@ export function useWebZjsActions(): WebzjsActions { const { installedSnap } = useMetaMask(); const { refreshSnapState } = useMetaMaskContext(); const invokeSnap = useInvokeSnap(); - const requestSnap = useRequestSnap(); + // Require a min Snap version so an outdated Snap updates on connect. + const requestSnap = useRequestSnap(undefined, REQUIRED_SNAP_VERSION); // Refs for values read inside triggerRescan but that shouldn't cause it to be recreated const fullySyncedRef = useRef(state.summary?.fully_scanned_height); @@ -369,7 +379,6 @@ export function useWebZjsActions(): WebzjsActions { // Sync in short incremental rounds, persisting + refreshing after each, so one // sync() that can't finish the backlog doesn't discard the interval's progress. - const MAX_SYNC_ROUNDS = 20; const SYNC_ROUND_DELAY = 2000; // ms between rounds to let the proxy recover let consecutiveFailures = 0; const MAX_CONSECUTIVE_FAILURES = 4; @@ -452,10 +461,13 @@ export function useWebZjsActions(): WebzjsActions { method: 'getSnapStete', })) as SnapState | null; - // Use custom birthday if provided, otherwise fall back to stored value - const birthdayBlock = customBirthday ?? (snapState?.webWalletSyncStartBlock - ? Number(snapState.webWalletSyncStartBlock) - : undefined); + // Use custom birthday if provided, otherwise fall back to stored value. + // Clamped to >= NU5 so a bad value can't trigger a scan from near genesis. + const birthdayBlock = clampBirthdayToNU5( + customBirthday ?? (snapState?.webWalletSyncStartBlock + ? Number(snapState.webWalletSyncStartBlock) + : undefined), + ); // Save the new birthday to snap state if custom one was provided if (customBirthday) { @@ -498,7 +510,6 @@ export function useWebZjsActions(): WebzjsActions { // With many blocks to scan, one sync() call can't finish before the // lightwalletd proxy drops the connection, so we keep calling it. console.info('Full resync: Starting sync from birthday'); - const MAX_SYNC_ROUNDS = 20; const SYNC_ROUND_DELAY = 2000; // ms between rounds to let proxy recover let consecutiveFailures = 0; const MAX_CONSECUTIVE_FAILURES = 4; @@ -620,6 +631,9 @@ export function useWebZjsActions(): WebzjsActions { await updateSnapState({ webWalletSyncStartBlock: String(birthdayBlock) }); } + // Never scan below NU5, even from a bad stored birthday. + birthdayBlock = clampBirthdayToNU5(birthdayBlock); + // 3. Create account with recovered credentials const accountId = await state.webWallet.create_account_ufvk( 'account-0', diff --git a/packages/web-wallet/src/pages/AccountSummary.tsx b/packages/web-wallet/src/pages/AccountSummary.tsx index 356ee2d..06d64bc 100644 --- a/packages/web-wallet/src/pages/AccountSummary.tsx +++ b/packages/web-wallet/src/pages/AccountSummary.tsx @@ -24,7 +24,13 @@ function AccountSummary() { const { fullResync } = useWebZjsActions(); const invokeSnap = useInvokeSnap(); const [exporting, setExporting] = useState(false); - const { migrateToPortable, migrationStatus, migrationError } = useMigration(); + const { + migrateToPortable, + finishSwitching, + migrationStatus, + migrationError, + hasPendingMigration, + } = useMigration(); // Show the migration prompt only while the account is still on the legacy (v1) // derivation. Once switched to the portable account (v2) it is hidden. @@ -38,12 +44,19 @@ function AccountSummary() { const ok = window.confirm( 'This moves all of your funds from your current (legacy) Zcash account to ' + 'a new portable account whose recovery phrase you can export. You will ' + - 'approve the transaction in MetaMask. Continue?', + 'approve the transaction in MetaMask.\n\n' + + 'This can take a few minutes and your browser may freeze while the ' + + 'transaction is being proved — this is normal. Please keep this tab open ' + + 'and do not close it until the migration finishes. Continue?', ); if (!ok) return; await migrateToPortable(); }; + const handleFinishSwitching = async () => { + await finishSwitching(); + }; + // Triggers the Snap's secure reveal dialog. The secret is shown by MetaMask // itself and is never returned to this page. const handleExportKeys = async () => { @@ -138,7 +151,7 @@ function AccountSummary() {
Reveal your Zcash wallet's recovery phrase to import this wallet - into another Zcash wallet (e.g. Zkool or Zodl). The phrase is shown + into another Zcash wallet (e.g. Zodl or Zkool). The phrase is shown securely inside MetaMask and is different from your MetaMask Secret Recovery Phrase.
@@ -160,15 +173,32 @@ function AccountSummary() { your funds to a new portable account to get a recovery phrase you can import anywhere. This sends a transaction you approve in MetaMask. - + {hasPendingMigration ? ( + <> +
+ Your funds were already sent to your portable account, but the + switch wasn't finished. Complete it below — do not migrate + again. +
+ + + ) : ( + + )} {migrationStatus === MigrationStatus.DONE && (
Migration complete — your funds are now in your portable account. diff --git a/packages/web-wallet/src/types/snap.ts b/packages/web-wallet/src/types/snap.ts index 4c9ea59..67a1d02 100644 --- a/packages/web-wallet/src/types/snap.ts +++ b/packages/web-wallet/src/types/snap.ts @@ -32,4 +32,7 @@ export interface SnapState { webWalletSyncStartBlock: string; lastKnownBalance: LastKnownBalance | null; hasPendingTx: boolean | null; + // Key-derivation version for this account. Absent → legacy v1. Set to 2 by the + // Snap's completeMigration; the dApp cannot change it (see snap setSnapState.tsx). + derivationVersion?: 1 | 2; } diff --git a/packages/web-wallet/src/workers/prover.worker.ts b/packages/web-wallet/src/workers/prover.worker.ts new file mode 100644 index 0000000..74cdd28 --- /dev/null +++ b/packages/web-wallet/src/workers/prover.worker.ts @@ -0,0 +1,46 @@ +// Dedicated zk-proof worker. Proof generation (Sapling's Groth16 prover in +// particular) blocks on Atomics.wait, which the browser forbids on the main +// thread, so pczt_prove must run here. pczt_prove is stateless (no db/network), +// so an empty wallet instance is all it needs. +import initWebzJSWallet, { + initThreadPool, + WebWallet, + Pczt, +} from '@zcashcommunitygrants/webzjs-wallet'; +import { NETWORK, LIGHTWALLETD_PROXY } from '../config/constants'; + +interface ProveRequest { + id: number; + pcztBytes: Uint8Array; +} + +const post = (msg: unknown, transfer?: Transferable[]) => + (self as unknown as { + postMessage: (m: unknown, t?: Transferable[]) => void; + }).postMessage(msg, transfer); + +let proverPromise: Promise | null = null; + +function getProver(): Promise { + if (!proverPromise) { + proverPromise = (async () => { + await initWebzJSWallet(); + await initThreadPool(navigator.hardwareConcurrency || 4); + return new WebWallet(NETWORK, LIGHTWALLETD_PROXY, 1, 1, null); + })(); + } + return proverPromise; +} + +self.onmessage = async (e: MessageEvent) => { + const { id, pcztBytes } = e.data; + try { + const prover = await getProver(); + const pczt = Pczt.from_bytes(new Uint8Array(pcztBytes)); + const proved = await prover.pczt_prove(pczt); + const out = proved.serialize(); + post({ id, ok: true, pcztBytes: out }, [out.buffer]); + } catch (err) { + post({ id, ok: false, error: String(err) }); + } +}; diff --git a/packages/web-wallet/src/workers/proverClient.ts b/packages/web-wallet/src/workers/proverClient.ts new file mode 100644 index 0000000..a08cc43 --- /dev/null +++ b/packages/web-wallet/src/workers/proverClient.ts @@ -0,0 +1,40 @@ +// Main-thread client for the proving worker. Spawns it lazily and round-trips +// serialized PCZT bytes, so the Atomics.wait-based prover never runs on main. +let worker: Worker | null = null; +let seq = 0; +const pending = new Map< + number, + { resolve: (b: Uint8Array) => void; reject: (e: Error) => void } +>(); + +function getWorker(): Worker { + if (!worker) { + worker = new Worker(new URL('./prover.worker.ts', import.meta.url), { + type: 'module', + }); + worker.onmessage = (e: MessageEvent) => { + const { id, ok, pcztBytes, error } = e.data; + const p = pending.get(id); + if (!p) return; + pending.delete(id); + if (ok) p.resolve(new Uint8Array(pcztBytes)); + else p.reject(new Error(error)); + }; + worker.onerror = (e) => { + const err = new Error(e.message || 'Prover worker error'); + pending.forEach((p) => p.reject(err)); + pending.clear(); + }; + } + return worker; +} + +export function provePcztInWorker(pcztBytes: Uint8Array): Promise { + const w = getWorker(); + const id = ++seq; + const copy = pcztBytes.slice(); // transfer a copy; keep the caller's bytes intact + return new Promise((resolve, reject) => { + pending.set(id, { resolve, reject }); + w.postMessage({ id, pcztBytes: copy }, [copy.buffer]); + }); +} From f1b7832897d8eebe04cc6e95e860122b40cd096d Mon Sep 17 00:00:00 2001 From: aratrika Date: Wed, 11 Nov 2026 22:53:33 -0500 Subject: [PATCH 7/8] fix(snap): close migration + recipient gaps from the second review --- crates/webzjs-keys/src/pczt_describe.rs | 35 +++++++- packages/snap/snap.manifest.json | 2 +- packages/snap/src/index.tsx | 1 + packages/snap/src/rpc/signPczt.tsx | 45 +++++++++- packages/snap/src/types.ts | 2 + packages/web-wallet/src/hooks/useMigration.ts | 86 +++++++++++++------ packages/web-wallet/src/types/snap.ts | 2 + 7 files changed, 144 insertions(+), 29 deletions(-) diff --git a/crates/webzjs-keys/src/pczt_describe.rs b/crates/webzjs-keys/src/pczt_describe.rs index 1937dcd..2afecca 100644 --- a/crates/webzjs-keys/src/pczt_describe.rs +++ b/crates/webzjs-keys/src/pczt_describe.rs @@ -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; @@ -198,6 +198,39 @@ fn encode_sapling(network: &Network, addr: &sapling::PaymentAddress) -> Option Result { + 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| 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`. /// /// Attribution is made **only** via the nullifier bind: [`verify_nullifier`] diff --git a/packages/snap/snap.manifest.json b/packages/snap/snap.manifest.json index 96ad991..06ab9a2 100644 --- a/packages/snap/snap.manifest.json +++ b/packages/snap/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/ZcashCommunityGrants/WebZjs.git" }, "source": { - "shasum": "CvL0mIg7jA50LolmVNknpSvIDCSDTAivbaAxKecystU=", + "shasum": "Ho8HqP5inkNA9fcznjr6yi+HZ1F/zHcCaQWcJ0WDcs0=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/packages/snap/src/index.tsx b/packages/snap/src/index.tsx index 6733e5c..f691914 100644 --- a/packages/snap/src/index.tsx +++ b/packages/snap/src/index.tsx @@ -81,6 +81,7 @@ export const onRpcRequest: OnRpcRequestHandler = async ({ request, origin }) => ), hasPendingTx: nullable(boolean()), derivationVersion: optional(number()), + pendingMigrationTxid: optional(nullable(string())), }), ); return await setSnapState(request.params as unknown as SnapState); diff --git a/packages/snap/src/rpc/signPczt.tsx b/packages/snap/src/rpc/signPczt.tsx index 2c11c87..a7a2c71 100644 --- a/packages/snap/src/rpc/signPczt.tsx +++ b/packages/snap/src/rpc/signPczt.tsx @@ -12,6 +12,7 @@ import { pczt_describe, pczt_validate, pczt_sign, + decode_address_receivers, Pczt, } from '@zcashcommunitygrants/webzjs-keys'; import { getSeed, getActiveDerivationVersion } from '../utils/getSeed'; @@ -138,6 +139,34 @@ export async function signPczt( // value to an attacker, so the aggregate amount check alone is not enough. const multiplePayments = recipientOutputs.length > 1; + // Verify the claimed recipient against the PCZT: decode the site's address into its + // per-pool receivers and confirm every non-change output pays one of them. An + // undecodable address leaves this unverifiable — fall back to an eyeball prompt. + let claimedReceivers: + | { orchard: string | null; sapling: string | null; transparent: string | null } + | null = null; + try { + claimedReceivers = JSON.parse( + decode_address_receivers(NETWORK, signDetails.recipient), + ); + } catch { + claimedReceivers = null; + } + const recipientVerifiable = claimedReceivers !== null; + const recipientMismatch = + recipientVerifiable && + recipientOutputs.some((o) => { + const claimed = + o.pool === 'orchard' + ? claimedReceivers!.orchard + : o.pool === 'sapling' + ? claimedReceivers!.sapling + : o.pool === 'transparent' + ? claimedReceivers!.transparent + : null; + return !claimed || o.recipient !== claimed; + }); + // No recipient string-match warning: a full UA never equals our per-pool re-encoding, // so it false-fires on every send. Recipients are shown; extras are caught above. @@ -228,9 +257,19 @@ export async function signPczt( ) : ( )} - - Confirm the verified recipient(s) above match who you intended to pay. - + {!recipientVerifiable ? ( + + Confirm the verified recipient(s) above match who you intended to pay. + + ) : recipientMismatch ? ( + + ⚠ WARNING: the PCZT pays a different address than the site + requested. Do not approve unless you recognise the verified + recipient(s) above. + + ) : ( + ✓ Recipient matches the address the site requested. + )} Raw PCZT diff --git a/packages/snap/src/types.ts b/packages/snap/src/types.ts index cce3229..7a7c357 100644 --- a/packages/snap/src/types.ts +++ b/packages/snap/src/types.ts @@ -32,4 +32,6 @@ export type SnapState = { // Key-derivation version for this account (see utils/getSeed.ts). // Absent → legacy v1 (never silently switch an existing account). derivationVersion?: number; + // Txid of an in-flight migration sweep (durable mirror of the dApp's IndexedDB marker). + pendingMigrationTxid?: string | null; } & Record; diff --git a/packages/web-wallet/src/hooks/useMigration.ts b/packages/web-wallet/src/hooks/useMigration.ts index ba5c891..8ddd15a 100644 --- a/packages/web-wallet/src/hooks/useMigration.ts +++ b/packages/web-wallet/src/hooks/useMigration.ts @@ -8,9 +8,10 @@ import { useMetaMaskContext } from '../context/MetamaskContext'; import { useInvokeSnap } from './snaps/useInvokeSnap'; import { useWebZjsActions } from './useWebzjsActions'; import useBalance from './useBalance'; +import { SnapState } from '../types/snap'; -// IndexedDB key: the txid of a broadcast-but-not-yet-committed migration sweep. -// Its presence means "a sweep is in flight; finish the switch, don't start a new one." +// Key for the txid of a broadcast-but-not-yet-committed migration sweep. Stored in both +// IndexedDB (fast) and Snap state (durable — survives clearing browser site data). const PENDING_MIGRATION_TXID_KEY = 'pendingMigrationTxid'; // How long to wait for the sweep to be mined before giving up (the switch can still @@ -64,16 +65,62 @@ export const useMigration = (): IUseMigration => { const [migrationError, setMigrationError] = useState(null); const [hasPendingMigration, setHasPendingMigration] = useState(false); + // Mirror the pending marker into Snap state so it survives clearing site data (which + // wipes IndexedDB) and a reload on the same device can still finish the switch. + const writePendingToSnap = async (txid: string | null): Promise => { + try { + const existing = (await invokeSnap({ + method: 'getSnapStete', + })) as SnapState | null; + await invokeSnap({ + method: 'setSnapStete', + params: { + webWalletSyncStartBlock: existing?.webWalletSyncStartBlock ?? '', + lastKnownBalance: existing?.lastKnownBalance ?? null, + hasPendingTx: existing?.hasPendingTx ?? null, + pendingMigrationTxid: txid, + }, + }); + } catch { + /* Snap unavailable — the IndexedDB marker still covers the common path. */ + } + }; + + const setPendingTxid = async (txid: string): Promise => { + await set(PENDING_MIGRATION_TXID_KEY, txid).catch(() => undefined); + await writePendingToSnap(txid); + setHasPendingMigration(true); + }; + + const clearPendingTxid = async (): Promise => { + await del(PENDING_MIGRATION_TXID_KEY).catch(() => undefined); + await writePendingToSnap(null); + setHasPendingMigration(false); + }; + + // Snap state first (durable), then IndexedDB (fast local cache). + const getPendingTxid = async (): Promise => { + try { + const s = (await invokeSnap({ method: 'getSnapStete' })) as SnapState | null; + if (s?.pendingMigrationTxid) return s.pendingMigrationTxid; + } catch { + /* fall through to idb */ + } + try { + const t = (await get(PENDING_MIGRATION_TXID_KEY)) as string | undefined; + return t || undefined; + } catch { + return undefined; + } + }; + // On mount, surface any in-flight migration so the UI can offer "Finish switching". useEffect(() => { (async () => { - try { - const txid = (await get(PENDING_MIGRATION_TXID_KEY)) as string | undefined; - setHasPendingMigration(!!txid); - } catch { - /* idb unavailable — treat as no pending migration */ - } + const txid = await getPendingTxid(); + setHasPendingMigration(!!txid); })(); + // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const activeAccount = (): number | null => @@ -105,6 +152,9 @@ export const useMigration = (): IUseMigration => { const entry = txs.find((t) => t.txid === txid); if (entry) { if (entry.status === 'Expired') { + // Clear the marker so "migrate again" starts fresh instead of + // resuming this dead transaction forever. + await clearPendingTxid(); throw new Error( 'The migration transaction expired before it was mined. Your ' + 'funds are still in your legacy account — please migrate again.', @@ -148,8 +198,7 @@ export const useMigration = (): IUseMigration => { return; } - await del(PENDING_MIGRATION_TXID_KEY).catch(() => undefined); - setHasPendingMigration(false); + await clearPendingTxid(); setMigrationStatus(MigrationStatus.RESYNCING); await fullResync(); @@ -174,12 +223,7 @@ export const useMigration = (): IUseMigration => { setMigrationError('No active account.'); return; } - let txid: string | undefined; - try { - txid = (await get(PENDING_MIGRATION_TXID_KEY)) as string | undefined; - } catch { - /* fall through to the no-pending message */ - } + const txid = await getPendingTxid(); if (!txid) { setMigrationError('There is no migration to finish.'); return; @@ -210,12 +254,7 @@ export const useMigration = (): IUseMigration => { // Resume instead of re-sweeping: if a sweep is already in flight, finishing the // switch is the right action (a second sweep would fail — v1 is already empty). - let pendingTxid: string | undefined; - try { - pendingTxid = (await get(PENDING_MIGRATION_TXID_KEY)) as string | undefined; - } catch { - /* idb unavailable; proceed as a fresh migration */ - } + const pendingTxid = await getPendingTxid(); if (pendingTxid) { try { await resume(account, pendingTxid); @@ -292,8 +331,7 @@ export const useMigration = (): IUseMigration => { // Record the in-flight sweep BEFORE waiting, so a reload can resume it. The // switch is NOT committed yet — only after the sweep actually mines. - await set(PENDING_MIGRATION_TXID_KEY, txid).catch(() => undefined); - setHasPendingMigration(true); + await setPendingTxid(txid); // Wait for the sweep to be mined (not just broadcast) before switching. If it // expires or is dropped, we stay on v1 rather than switching to an empty v2. diff --git a/packages/web-wallet/src/types/snap.ts b/packages/web-wallet/src/types/snap.ts index 67a1d02..650844f 100644 --- a/packages/web-wallet/src/types/snap.ts +++ b/packages/web-wallet/src/types/snap.ts @@ -35,4 +35,6 @@ export interface SnapState { // Key-derivation version for this account. Absent → legacy v1. Set to 2 by the // Snap's completeMigration; the dApp cannot change it (see snap setSnapState.tsx). derivationVersion?: 1 | 2; + // Txid of an in-flight migration sweep (durable mirror of the IndexedDB marker). + pendingMigrationTxid?: string | null; } From 9ad0a589f65e767c34334a2992c76bd9c07c2e68 Mon Sep 17 00:00:00 2001 From: aratrika Date: Thu, 12 Nov 2026 22:19:08 -0500 Subject: [PATCH 8/8] fix(nu7): align fee floor and block-time assumptions with NU7 / ZIP 2009 --- crates/webzjs-keys/src/pczt_describe.rs | 5 +++-- packages/snap/snap.manifest.json | 2 +- packages/snap/src/rpc/setBirthdayBlock.tsx | 6 +++--- packages/web-wallet/src/hooks/useMigration.ts | 5 +++-- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/crates/webzjs-keys/src/pczt_describe.rs b/crates/webzjs-keys/src/pczt_describe.rs index 2afecca..de65c35 100644 --- a/crates/webzjs-keys/src/pczt_describe.rs +++ b/crates/webzjs-keys/src/pczt_describe.rs @@ -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 diff --git a/packages/snap/snap.manifest.json b/packages/snap/snap.manifest.json index 06ab9a2..75fa91b 100644 --- a/packages/snap/snap.manifest.json +++ b/packages/snap/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/ZcashCommunityGrants/WebZjs.git" }, "source": { - "shasum": "Ho8HqP5inkNA9fcznjr6yi+HZ1F/zHcCaQWcJ0WDcs0=", + "shasum": "0Wg814D7LYNA4RSaSfSgzim7mPatDJo4xf+HPY+rqFo=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/packages/snap/src/rpc/setBirthdayBlock.tsx b/packages/snap/src/rpc/setBirthdayBlock.tsx index 40f8cdf..ab743ec 100644 --- a/packages/snap/src/rpc/setBirthdayBlock.tsx +++ b/packages/snap/src/rpc/setBirthdayBlock.tsx @@ -18,9 +18,9 @@ type SetBirthdayBlockParams = { latestBlock: number }; export async function setBirthdayBlock({ latestBlock, }: SetBirthdayBlockParams): Promise { - // Calculate approximate block heights for different time ranges - // Zcash produces ~576 blocks per day (1 block per 75 seconds) - const blocksPerDay = 576; + // Approximate block heights for the time-range hints. NU7 (ZIP 218) sets 25s + // blocks → ~3,456/day. For spans predating NU7 this errs earlier (safe: scans more). + const blocksPerDay = 3456; const oneMonthAgo = Math.max(latestBlock - blocksPerDay * 30, 1687104); const sixMonthsAgo = Math.max(latestBlock - blocksPerDay * 180, 1687104); const oneYearAgo = Math.max(latestBlock - blocksPerDay * 365, 1687104); diff --git a/packages/web-wallet/src/hooks/useMigration.ts b/packages/web-wallet/src/hooks/useMigration.ts index 8ddd15a..2c04324 100644 --- a/packages/web-wallet/src/hooks/useMigration.ts +++ b/packages/web-wallet/src/hooks/useMigration.ts @@ -15,9 +15,10 @@ import { SnapState } from '../types/snap'; const PENDING_MIGRATION_TXID_KEY = 'pendingMigrationTxid'; // How long to wait for the sweep to be mined before giving up (the switch can still -// be finished later via `finishSwitching`). Poll roughly every 8s. +// be finished later via `finishSwitching`). Poll roughly every 8s. Budget set for +// NU7's 25s blocks, where tx expiry arrives sooner in wall-clock (~17 min). const MINED_POLL_MS = 8_000; -const MINED_MAX_ATTEMPTS = 75; // ~10 minutes +const MINED_MAX_ATTEMPTS = 120; // ~16 minutes export enum MigrationStatus { IDLE = 'Idle',