From 4242c30f61a968f0ccc9c51d9d986faefb73ba25 Mon Sep 17 00:00:00 2001 From: undefined Date: Thu, 15 Oct 2026 23:08:35 +0100 Subject: [PATCH 1/6] 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 1986e272cda84d44b736207a201d64e1f3ee767e Mon Sep 17 00:00:00 2001 From: undefined Date: Thu, 15 Oct 2026 23:10:18 +0100 Subject: [PATCH 2/6] 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 e8b71b239d4f42ee2b2cd5018c48b91492025125 Mon Sep 17 00:00:00 2001 From: undefined Date: Fri, 16 Oct 2026 00:02:55 +0100 Subject: [PATCH 3/6] 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 b08f4a7e5ff7caed75acd951660f995fa45aadcc Mon Sep 17 00:00:00 2001 From: undefined Date: Wed, 28 Oct 2026 23:20:20 +0100 Subject: [PATCH 4/6] 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 1a152b230ab5e9521643ed679a8c2b01739b9a75 Mon Sep 17 00:00:00 2001 From: undefined Date: Fri, 16 Oct 2026 12:08:56 +0100 Subject: [PATCH 5/6] Add multi-payment + memo API: propose_payments, propose_from_zip321, transfer_payments --- crates/webzjs-wallet/src/error.rs | 2 + crates/webzjs-wallet/src/lib.rs | 1 + crates/webzjs-wallet/src/payments.rs | 830 +++++++++++++++++++++++++++ crates/webzjs-wallet/src/wallet.rs | 113 +++- 4 files changed, 934 insertions(+), 12 deletions(-) create mode 100644 crates/webzjs-wallet/src/payments.rs diff --git a/crates/webzjs-wallet/src/error.rs b/crates/webzjs-wallet/src/error.rs index a360053..e76bf93 100644 --- a/crates/webzjs-wallet/src/error.rs +++ b/crates/webzjs-wallet/src/error.rs @@ -27,6 +27,8 @@ pub enum Error { AddressGeneration(#[from] zcash_keys::keys::AddressGenerationError), #[error("Error attempting to decode address: {0}")] AddressDecoding(#[from] zcash_address::ParseError), + #[error("Invalid payments: {0}")] + Payments(#[from] crate::payments::PaymentsError), #[error("Error attempting to decode key: {0}")] KeyDecoding(String), #[error("Invalid network string given: {0}")] diff --git a/crates/webzjs-wallet/src/lib.rs b/crates/webzjs-wallet/src/lib.rs index f07a35c..c366c1f 100644 --- a/crates/webzjs-wallet/src/lib.rs +++ b/crates/webzjs-wallet/src/lib.rs @@ -10,6 +10,7 @@ mod balance; mod chain_params; mod error; pub mod init; +pub mod payments; pub mod validation; pub mod wallet; diff --git a/crates/webzjs-wallet/src/payments.rs b/crates/webzjs-wallet/src/payments.rs new file mode 100644 index 0000000..6fffb8b --- /dev/null +++ b/crates/webzjs-wallet/src/payments.rs @@ -0,0 +1,830 @@ +// Copyright 2024 ChainSafe Systems +// SPDX-License-Identifier: Apache-2.0, MIT + +//! Validation of multi-payment requests, each with an optional memo. +//! +//! A transaction can pay several recipients, and each shielded recipient can be sent a memo +//! (up to 512 bytes, encoded per [ZIP 302]). This module checks a list of payments, or a +//! [ZIP 321] payment URI, *before* anything is proposed to the wallet, so mistakes come back as +//! a typed [`PaymentsError`] that names the offending payment instead of an opaque failure from +//! deep inside transaction construction. +//! +//! Everything here is plain functions over plain data so it can be unit-tested without a network. +//! +//! [ZIP 302]: https://zips.z.cash/zip-0302 +//! [ZIP 321]: https://zips.z.cash/zip-0321 + +use std::convert::Infallible; +use std::fmt; + +use zcash_address::{unified, ConversionError, TryFromAddress, ZcashAddress}; +use zcash_client_backend::data_api::AccountBalance; +use zcash_client_backend::zip321::{Payment, TransactionRequest, Zip321Error}; +use zcash_protocol::consensus::NetworkType; +use zcash_protocol::memo::{self, Memo, MemoBytes}; +use zcash_protocol::value::Zatoshis; + +/// The largest memo, in bytes, that a shielded output can carry. +pub const MAX_MEMO_BYTES: usize = 512; + +/// A memo to attach to a payment. +/// +/// An empty text or an empty byte string means "no memo", exactly as if no memo had been given. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MemoInput { + /// Human-readable text, sent as a ZIP 302 text memo. Its UTF-8 encoding must fit in + /// [`MAX_MEMO_BYTES`]. + Text(String), + /// Arbitrary bytes, at most [`MAX_MEMO_BYTES`], sent exactly as given (zero-padded to 512 + /// bytes by ZIP 302). The caller is responsible for the leading byte's meaning: ZIP 302 uses + /// `0xFF` for arbitrary data, and a leading byte of `0xF4` or less marks a text memo. + Bytes(Vec), +} + +/// One payment of a multi-payment transaction. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PaymentSpec { + /// The recipient, as an encoded Zcash address (unified, Sapling or transparent). + pub to: String, + /// The amount, in zatoshis. + pub value: u64, + /// An optional memo. Only shielded recipients can receive one. + pub memo: Option, +} + +/// Why a set of payments was rejected. +/// +/// `index` always refers to the position of the payment in the list the caller supplied (for a +/// payment URI, the index used inside the URI). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PaymentsError { + /// No payments were given. + NoPayments, + /// The recipient is not a valid Zcash address. + InvalidAddress { index: usize }, + /// The recipient is a valid address, but for a different network than the wallet's. + WrongNetwork { + index: usize, + expected: &'static str, + found: &'static str, + }, + /// The amount is not a valid amount of ZEC (for example it exceeds the maximum supply). + InvalidAmount { index: usize }, + /// A payment in a URI has no amount, so the wallet cannot know how much to send. + MissingAmount { index: usize }, + /// A zero amount was requested for a transparent recipient, which consensus forbids. + ZeroValuedTransparentOutput { index: usize }, + /// A memo was given for a recipient that cannot receive one (a transparent address). + MemoForTransparentRecipient { index: usize }, + /// The memo is longer than [`MAX_MEMO_BYTES`] bytes. + MemoTooLong { index: usize, len: usize }, + /// The payments add up to more than can be represented. + TotalOverflow, + /// The payments total more than the account can currently spend. + InsufficientFunds { requested: u64, spendable: u64 }, + /// The payment URI could not be parsed. + InvalidUri(String), + /// The wallet could not build a proposal for these payments (for example, because fees would + /// exceed the remaining balance). + Proposal(String), +} + +impl PaymentsError { + /// A short, stable identifier for the kind of error, suitable for programmatic handling + /// (the human-readable message may change between releases; this will not). + pub fn code(&self) -> &'static str { + match self { + PaymentsError::NoPayments => "no_payments", + PaymentsError::InvalidAddress { .. } => "invalid_address", + PaymentsError::WrongNetwork { .. } => "wrong_network", + PaymentsError::InvalidAmount { .. } => "invalid_amount", + PaymentsError::MissingAmount { .. } => "missing_amount", + PaymentsError::ZeroValuedTransparentOutput { .. } => "zero_valued_transparent_output", + PaymentsError::MemoForTransparentRecipient { .. } => "memo_for_transparent_recipient", + PaymentsError::MemoTooLong { .. } => "memo_too_long", + PaymentsError::TotalOverflow => "total_overflow", + PaymentsError::InsufficientFunds { .. } => "insufficient_funds", + PaymentsError::InvalidUri(_) => "invalid_uri", + PaymentsError::Proposal(_) => "proposal_failed", + } + } +} + +impl fmt::Display for PaymentsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + PaymentsError::NoPayments => write!(f, "At least one payment is required"), + PaymentsError::InvalidAddress { index } => { + write!(f, "Payment {index}: the recipient is not a valid Zcash address") + } + PaymentsError::WrongNetwork { + index, + expected, + found, + } => write!( + f, + "Payment {index}: the recipient address is for the {found} network, but this wallet is on the {expected} network" + ), + PaymentsError::InvalidAmount { index } => { + write!(f, "Payment {index}: the amount is not a valid amount of ZEC") + } + PaymentsError::MissingAmount { index } => { + write!(f, "Payment {index}: the payment request has no amount") + } + PaymentsError::ZeroValuedTransparentOutput { index } => write!( + f, + "Payment {index}: a zero amount cannot be sent to a transparent address" + ), + PaymentsError::MemoForTransparentRecipient { index } => write!( + f, + "Payment {index}: a memo cannot be sent to a transparent address; only shielded recipients can receive memos" + ), + PaymentsError::MemoTooLong { index, len } => write!( + f, + "Payment {index}: the memo is {len} bytes, but at most {MAX_MEMO_BYTES} are allowed" + ), + PaymentsError::TotalOverflow => write!(f, "The payments add up to too large an amount"), + PaymentsError::InsufficientFunds { + requested, + spendable, + } => write!( + f, + "The payments total {requested} zatoshis, but only {spendable} zatoshis are spendable" + ), + PaymentsError::InvalidUri(reason) => { + write!(f, "Invalid payment request URI: {reason}") + } + PaymentsError::Proposal(reason) => { + write!(f, "Could not build a transaction proposal: {reason}") + } + } + } +} + +impl std::error::Error for PaymentsError {} + +/// Payments that passed validation, ready to be proposed. +#[derive(Debug)] +pub struct ValidatedPayments { + pub(crate) request: TransactionRequest, + pub(crate) total: Zatoshis, +} + +impl ValidatedPayments { + /// The sum of all payment amounts (fees are not included). + pub fn total(&self) -> Zatoshis { + self.total + } +} + +/// One payment after its fields have been parsed, before it becomes a ZIP 321 [`Payment`]. +struct Parsed { + address: ZcashAddress, + value: Zatoshis, + memo: Option, +} + +fn network_name(net: NetworkType) -> &'static str { + match net { + NetworkType::Main => "main", + NetworkType::Test => "test", + NetworkType::Regtest => "regtest", + } +} + +/// A converter that accepts every address kind, so that [`ZcashAddress::convert_if_network`] can be +/// used purely to learn whether an address belongs to a given network. +struct AnyAddress; + +impl TryFromAddress for AnyAddress { + type Error = Infallible; + + fn try_from_sprout(_: NetworkType, _: [u8; 64]) -> Result> { + Ok(AnyAddress) + } + fn try_from_sapling(_: NetworkType, _: [u8; 43]) -> Result> { + Ok(AnyAddress) + } + fn try_from_unified( + _: NetworkType, + _: unified::Address, + ) -> Result> { + Ok(AnyAddress) + } + fn try_from_transparent_p2pkh( + _: NetworkType, + _: [u8; 20], + ) -> Result> { + Ok(AnyAddress) + } + fn try_from_transparent_p2sh( + _: NetworkType, + _: [u8; 20], + ) -> Result> { + Ok(AnyAddress) + } + fn try_from_tex(_: NetworkType, _: [u8; 20]) -> Result> { + Ok(AnyAddress) + } +} + +fn check_network( + index: usize, + address: &ZcashAddress, + expected: NetworkType, +) -> Result<(), PaymentsError> { + match address.clone().convert_if_network::(expected) { + Ok(_) => Ok(()), + Err(ConversionError::IncorrectNetwork { expected, actual }) => { + Err(PaymentsError::WrongNetwork { + index, + expected: network_name(expected), + found: network_name(actual), + }) + } + // `AnyAddress` accepts every kind and has no error of its own. + Err(_) => Err(PaymentsError::InvalidAddress { index }), + } +} + +fn to_memo_bytes(index: usize, memo: &MemoInput) -> Result, PaymentsError> { + let too_long = |len: usize| PaymentsError::MemoTooLong { index, len }; + match memo { + MemoInput::Text(text) if text.is_empty() => Ok(None), + MemoInput::Text(text) => { + let parsed: Memo = text.parse().map_err(|e| match e { + memo::Error::TooLong(len) => too_long(len), + // `Memo::from_str` only fails for length. + memo::Error::InvalidUtf8(_) => too_long(text.len()), + })?; + Ok(Some(MemoBytes::from(&parsed))) + } + MemoInput::Bytes(bytes) if bytes.is_empty() => Ok(None), + MemoInput::Bytes(bytes) => MemoBytes::from_bytes(bytes).map(Some).map_err(|e| match e { + memo::Error::TooLong(len) => too_long(len), + memo::Error::InvalidUtf8(_) => too_long(bytes.len()), + }), + } +} + +/// Checks the parsed payments and assembles the ZIP 321 request. +fn assemble(items: Vec) -> Result { + if items.is_empty() { + return Err(PaymentsError::NoPayments); + } + + let mut total = Zatoshis::ZERO; + let mut payments = Vec::with_capacity(items.len()); + for (index, item) in items.into_iter().enumerate() { + if item.memo.is_some() && !item.address.can_receive_memo() { + return Err(PaymentsError::MemoForTransparentRecipient { index }); + } + if item.value == Zatoshis::ZERO && item.address.is_transparent_only() { + return Err(PaymentsError::ZeroValuedTransparentOutput { index }); + } + total = (total + item.value).ok_or(PaymentsError::TotalOverflow)?; + // The checks above cover every way `Payment::new` can refuse. + let payment = Payment::new( + item.address, + Some(item.value), + item.memo, + None, + None, + vec![], + ) + .map_err(|_| PaymentsError::InvalidAddress { index })?; + payments.push(payment); + } + + let request = + TransactionRequest::new(payments).map_err(|e| PaymentsError::Proposal(e.to_string()))?; + Ok(ValidatedPayments { request, total }) +} + +/// Validates a list of payments for a wallet on `network`. +/// +/// Checks, in this order for each payment: the address parses, it belongs to `network`, the amount +/// is valid, the memo fits and the recipient can receive it. At least one payment is required. +pub fn validate_payments( + network: NetworkType, + payments: &[PaymentSpec], +) -> Result { + if payments.is_empty() { + return Err(PaymentsError::NoPayments); + } + + let mut items = Vec::with_capacity(payments.len()); + for (index, spec) in payments.iter().enumerate() { + let address = ZcashAddress::try_from_encoded(&spec.to) + .map_err(|_| PaymentsError::InvalidAddress { index })?; + check_network(index, &address, network)?; + let value = + Zatoshis::from_u64(spec.value).map_err(|_| PaymentsError::InvalidAmount { index })?; + let memo = spec + .memo + .as_ref() + .map(|m| to_memo_bytes(index, m)) + .transpose()? + .flatten(); + items.push(Parsed { + address, + value, + memo, + }); + } + assemble(items) +} + +/// Translates the URI parser's error into one of ours. +/// +/// A payment URI can contain an address and a memo, and the parser's own messages may quote the +/// text that failed to parse. Errors can end up in logs, so this never forwards that text: each +/// case becomes a typed error or a fixed description. +fn uri_error(error: Zip321Error) -> PaymentsError { + let invalid = |reason: &str| PaymentsError::InvalidUri(reason.to_string()); + match error { + Zip321Error::TransparentMemo(index) => PaymentsError::MemoForTransparentRecipient { index }, + Zip321Error::ZeroValuedTransparentOutput(index) => { + PaymentsError::ZeroValuedTransparentOutput { index } + } + Zip321Error::RecipientMissing(index) => PaymentsError::InvalidAddress { index }, + Zip321Error::TooManyPayments(count) => { + PaymentsError::InvalidUri(format!("the request has too many payments ({count})")) + } + Zip321Error::DuplicateParameter(param, index) => PaymentsError::InvalidUri(format!( + "payment {index} has a duplicate {} parameter", + param.name() + )), + Zip321Error::InvalidBase64(_) => invalid("a memo is not valid base64"), + Zip321Error::MemoBytesError(_) => { + invalid("a memo is longer than 512 bytes or is not valid text") + } + _ => invalid("the request is malformed"), + } +} + +/// Validates a [ZIP 321](https://zips.z.cash/zip-0321) payment request URI for a wallet on +/// `network`. Every payment in the URI must specify an amount. +pub fn validate_uri(network: NetworkType, uri: &str) -> Result { + let request = TransactionRequest::from_uri(uri).map_err(uri_error)?; + + let mut items = Vec::new(); + for (&index, payment) in request.payments() { + check_network(index, payment.recipient_address(), network)?; + let value = payment + .amount() + .ok_or(PaymentsError::MissingAmount { index })?; + items.push(Parsed { + address: payment.recipient_address().clone(), + value, + memo: payment.memo().cloned(), + }); + } + assemble(items) +} + +/// Checks that the payments' total does not exceed what the account can spend. +/// +/// This compares amounts only; the network fee is added later when the proposal is built, and a +/// shortfall caused by the fee is reported as [`PaymentsError::InsufficientFunds`] too. +pub fn check_spendable(total: Zatoshis, spendable: Zatoshis) -> Result<(), PaymentsError> { + if total > spendable { + Err(PaymentsError::InsufficientFunds { + requested: total.into_u64(), + spendable: spendable.into_u64(), + }) + } else { + Ok(()) + } +} + +/// The value an account can spend from its shielded pools right now. +/// +/// Counts Sapling, Orchard and Ironwood. Transparent funds must be shielded first, and value that +/// is still waiting for confirmations is not spendable. +pub fn spendable_shielded(balance: &AccountBalance) -> Zatoshis { + [ + balance.sapling_balance().spendable_value(), + balance.orchard_balance().spendable_value(), + balance.ironwood_balance().spendable_value(), + ] + .into_iter() + .fold(Zatoshis::ZERO, |acc, v| (acc + v).unwrap_or(acc)) +} + +#[cfg(test)] +mod tests { + use zcash_address::ToAddress; + use zcash_client_backend::data_api::Balance; + use zcash_protocol::consensus::NetworkType; + use zcash_protocol::value::BalanceError; + + use super::*; + + const MAIN: NetworkType = NetworkType::Main; + const TEST: NetworkType = NetworkType::Test; + + // Well-formed addresses of each kind, built from fixed bytes so the tests need no network. + fn sapling(net: NetworkType) -> String { + ZcashAddress::from_sapling(net, [7u8; 43]).encode() + } + fn transparent(net: NetworkType) -> String { + ZcashAddress::from_transparent_p2pkh(net, [9u8; 20]).encode() + } + + fn pay(to: String, value: u64, memo: Option) -> PaymentSpec { + PaymentSpec { to, value, memo } + } + + fn text(s: &str) -> Option { + Some(MemoInput::Text(s.to_string())) + } + + // ---- rule: at least one payment ---- + + #[test] + fn no_payments_is_rejected() { + assert_eq!( + validate_payments(TEST, &[]).unwrap_err(), + PaymentsError::NoPayments + ); + } + + // ---- rule: addresses belong to the wallet's network ---- + + #[test] + fn address_for_another_network_is_rejected_with_both_names() { + let err = validate_payments(TEST, &[pay(sapling(MAIN), 1000, None)]).unwrap_err(); + assert_eq!( + err, + PaymentsError::WrongNetwork { + index: 0, + expected: "test", + found: "main" + } + ); + // And the other way round. + let err = validate_payments(MAIN, &[pay(transparent(TEST), 1000, None)]).unwrap_err(); + assert_eq!( + err, + PaymentsError::WrongNetwork { + index: 0, + expected: "main", + found: "test" + } + ); + } + + #[test] + fn wrong_network_names_the_offending_payment() { + let err = validate_payments( + TEST, + &[ + pay(sapling(TEST), 1000, None), + pay(sapling(MAIN), 1000, None), + ], + ) + .unwrap_err(); + assert!(matches!(err, PaymentsError::WrongNetwork { index: 1, .. })); + } + + #[test] + fn malformed_address_is_rejected() { + let err = validate_payments(TEST, &[pay("not an address".into(), 1000, None)]).unwrap_err(); + assert_eq!(err, PaymentsError::InvalidAddress { index: 0 }); + } + + // ---- rule: no memo for a transparent recipient ---- + + #[test] + fn memo_to_a_transparent_recipient_is_rejected() { + let err = + validate_payments(TEST, &[pay(transparent(TEST), 1000, text("hello"))]).unwrap_err(); + assert_eq!(err, PaymentsError::MemoForTransparentRecipient { index: 0 }); + let err = validate_payments( + TEST, + &[pay( + transparent(TEST), + 1000, + Some(MemoInput::Bytes(vec![0xff, 1, 2])), + )], + ) + .unwrap_err(); + assert_eq!(err, PaymentsError::MemoForTransparentRecipient { index: 0 }); + } + + #[test] + fn transparent_recipient_without_memo_is_accepted() { + assert!(validate_payments(TEST, &[pay(transparent(TEST), 1000, None)]).is_ok()); + } + + #[test] + fn empty_memo_counts_as_no_memo_even_for_transparent() { + let v = validate_payments( + TEST, + &[ + pay(transparent(TEST), 1000, text("")), + pay(transparent(TEST), 1000, Some(MemoInput::Bytes(vec![]))), + ], + ); + assert!(v.is_ok()); + } + + // ---- rule: memo is at most 512 bytes ---- + + #[test] + fn memo_of_exactly_512_bytes_is_accepted() { + let at_limit = "a".repeat(MAX_MEMO_BYTES); + assert!(validate_payments(TEST, &[pay(sapling(TEST), 1000, text(&at_limit))]).is_ok()); + let bytes = Some(MemoInput::Bytes(vec![0xff; MAX_MEMO_BYTES])); + assert!(validate_payments(TEST, &[pay(sapling(TEST), 1000, bytes)]).is_ok()); + } + + #[test] + fn memo_over_512_bytes_is_rejected_with_its_length() { + let over = "a".repeat(MAX_MEMO_BYTES + 1); + let err = validate_payments(TEST, &[pay(sapling(TEST), 1000, text(&over))]).unwrap_err(); + assert_eq!(err, PaymentsError::MemoTooLong { index: 0, len: 513 }); + let err = validate_payments( + TEST, + &[pay( + sapling(TEST), + 1000, + Some(MemoInput::Bytes(vec![0xff; 600])), + )], + ) + .unwrap_err(); + assert_eq!(err, PaymentsError::MemoTooLong { index: 0, len: 600 }); + } + + #[test] + fn text_memo_length_is_counted_in_utf8_bytes_not_characters() { + // 200 three-byte characters = 600 bytes. + let multibyte = "€".repeat(200); + assert_eq!(multibyte.chars().count(), 200); + let err = + validate_payments(TEST, &[pay(sapling(TEST), 1000, text(&multibyte))]).unwrap_err(); + assert_eq!(err, PaymentsError::MemoTooLong { index: 0, len: 600 }); + } + + // ---- memo encoding follows ZIP 302 (built from librustzcash's own types) ---- + + #[test] + fn text_memo_is_encoded_as_a_zip302_text_memo() { + let v = validate_payments(TEST, &[pay(sapling(TEST), 1000, text("hello"))]).unwrap(); + let payment = v.request.payments().values().next().unwrap(); + let encoded = payment.memo().unwrap(); + assert_eq!(&encoded.as_array()[..5], b"hello"); + assert!(encoded.as_array()[5..].iter().all(|b| *b == 0)); + assert_eq!( + Memo::try_from(encoded.clone()).unwrap(), + "hello".parse::().unwrap() + ); + } + + #[test] + fn binary_memo_is_sent_byte_for_byte_and_zero_padded() { + let raw = vec![0xff, 0xde, 0xad, 0xbe, 0xef]; + let v = validate_payments( + TEST, + &[pay( + sapling(TEST), + 1000, + Some(MemoInput::Bytes(raw.clone())), + )], + ) + .unwrap(); + let encoded = v + .request + .payments() + .values() + .next() + .unwrap() + .memo() + .unwrap(); + assert_eq!(&encoded.as_array()[..5], &raw[..]); + assert!(encoded.as_array()[5..].iter().all(|b| *b == 0)); + // ZIP 302: a leading 0xFF byte marks arbitrary data. + assert!(matches!( + Memo::try_from(encoded.clone()).unwrap(), + Memo::Arbitrary(_) + )); + } + + // ---- multi-payment behaviour ---- + + #[test] + fn several_payments_with_and_without_memos_are_accepted_and_totalled() { + let v = validate_payments( + TEST, + &[ + pay(sapling(TEST), 1_000, text("first")), + pay(sapling(TEST), 2_000, Some(MemoInput::Bytes(vec![0xff, 9]))), + pay(transparent(TEST), 3_000, None), + ], + ) + .unwrap(); + assert_eq!(v.total(), Zatoshis::const_from_u64(6_000)); + assert_eq!(v.request.payments().len(), 3); + // Payments keep the caller's order. + let amounts: Vec = v + .request + .payments() + .values() + .map(|p| p.amount().unwrap().into_u64()) + .collect(); + assert_eq!(amounts, vec![1_000, 2_000, 3_000]); + } + + #[test] + fn amount_above_the_maximum_supply_is_rejected() { + let err = validate_payments(TEST, &[pay(sapling(TEST), u64::MAX, None)]).unwrap_err(); + assert_eq!(err, PaymentsError::InvalidAmount { index: 0 }); + } + + #[test] + fn totals_that_overflow_the_maximum_supply_are_rejected() { + let max = zcash_protocol::value::MAX_MONEY; + let err = validate_payments( + TEST, + &[pay(sapling(TEST), max, None), pay(sapling(TEST), 1, None)], + ) + .unwrap_err(); + assert_eq!(err, PaymentsError::TotalOverflow); + } + + #[test] + fn zero_to_a_transparent_address_is_rejected_but_zero_to_shielded_with_memo_is_fine() { + let err = validate_payments(TEST, &[pay(transparent(TEST), 0, None)]).unwrap_err(); + assert_eq!(err, PaymentsError::ZeroValuedTransparentOutput { index: 0 }); + assert!(validate_payments(TEST, &[pay(sapling(TEST), 0, text("memo only"))]).is_ok()); + } + + // ---- rule: total within the spendable balance ---- + + #[test] + fn total_above_the_spendable_balance_is_rejected() { + let total = Zatoshis::const_from_u64(5_000); + let spendable = Zatoshis::const_from_u64(4_999); + assert_eq!( + check_spendable(total, spendable).unwrap_err(), + PaymentsError::InsufficientFunds { + requested: 5_000, + spendable: 4_999 + } + ); + assert!(check_spendable(total, total).is_ok()); + } + + #[test] + fn spendable_balance_counts_every_shielded_pool_but_not_transparent_or_pending() { + let mut b = AccountBalance::ZERO; + let add = + |v: u64| move |bal: &mut Balance| bal.add_spendable_value(Zatoshis::const_from_u64(v)); + b.with_sapling_balance_mut::<_, BalanceError>(add(100)) + .unwrap(); + b.with_orchard_balance_mut::<_, BalanceError>(add(20)) + .unwrap(); + b.with_ironwood_balance_mut::<_, BalanceError>(add(3)) + .unwrap(); + b.with_unshielded_regular_balance_mut::<_, BalanceError>(add(9_000)) + .unwrap(); + b.with_ironwood_balance_mut::<_, BalanceError>(|bal: &mut Balance| { + bal.add_pending_spendable_value(Zatoshis::const_from_u64(70_000)) + }) + .unwrap(); + assert_eq!(spendable_shielded(&b), Zatoshis::const_from_u64(123)); + } + + // ---- ZIP 321 URIs ---- + + fn uri_for(addr: &str, query: &str) -> String { + format!("zcash:{addr}?{query}") + } + + #[test] + fn uri_with_a_memo_is_parsed_and_validated() { + // memo "Thanks" in base64url + let uri = uri_for(&sapling(TEST), "amount=0.0001&memo=VGhhbmtz"); + let v = validate_uri(TEST, &uri).unwrap(); + assert_eq!(v.total(), Zatoshis::const_from_u64(10_000)); + let memo = v + .request + .payments() + .values() + .next() + .unwrap() + .memo() + .unwrap(); + assert_eq!(&memo.as_array()[..6], b"Thanks"); + } + + #[test] + fn uri_for_another_network_is_rejected() { + let uri = uri_for(&sapling(MAIN), "amount=1"); + assert!(matches!( + validate_uri(TEST, &uri).unwrap_err(), + PaymentsError::WrongNetwork { index: 0, .. } + )); + } + + #[test] + fn uri_payment_without_an_amount_is_rejected() { + let uri = format!("zcash:{}", sapling(TEST)); + assert_eq!( + validate_uri(TEST, &uri).unwrap_err(), + PaymentsError::MissingAmount { index: 0 } + ); + } + + #[test] + fn garbage_uri_is_rejected_without_echoing_it() { + let err = validate_uri(TEST, "https://example.com").unwrap_err(); + assert!(matches!(err, PaymentsError::InvalidUri(_))); + assert!(!err.to_string().contains("example.com")); + } + + #[test] + fn uri_memo_to_a_transparent_address_gets_the_typed_error_with_its_index() { + let uri = uri_for(&transparent(TEST), "amount=1&memo=VGhhbmtz"); + assert_eq!( + validate_uri(TEST, &uri).unwrap_err(), + PaymentsError::MemoForTransparentRecipient { index: 0 } + ); + } + + #[test] + fn uri_errors_never_quote_the_address_or_memo_text() { + let addr = sapling(TEST); + // A real address, then a memo that is not valid base64, and a stray parameter. + for query in [ + "amount=1&memo=%%%not-base64%%%", + "amount=1&amount=2", + "amount=notanumber&memo=VGhhbmtz", + "&&&memo=secret-memo-text", + ] { + let err = validate_uri(TEST, &uri_for(&addr, query)).unwrap_err(); + let shown = format!("{err} {err:?}"); + assert!( + !shown.contains(&addr), + "address leaked for {query}: {shown}" + ); + assert!( + !shown.contains("secret-memo-text"), + "memo leaked for {query}: {shown}" + ); + assert!( + !shown.contains("not-base64"), + "memo leaked for {query}: {shown}" + ); + } + } + + #[test] + fn multi_payment_uri_keeps_each_payments_index() { + let uri = format!( + "zcash:?address={}&amount=1&address.1={}&amount.1=2&memo.1=VGhhbmtz", + sapling(TEST), + sapling(TEST) + ); + let v = validate_uri(TEST, &uri).unwrap(); + assert_eq!(v.request.payments().len(), 2); + assert_eq!(v.total(), Zatoshis::const_from_u64(3 * 100_000_000)); + } + + // ---- stable codes ---- + + #[test] + fn every_error_has_a_distinct_stable_code() { + let all = [ + PaymentsError::NoPayments, + PaymentsError::InvalidAddress { index: 0 }, + PaymentsError::WrongNetwork { + index: 0, + expected: "test", + found: "main", + }, + PaymentsError::InvalidAmount { index: 0 }, + PaymentsError::MissingAmount { index: 0 }, + PaymentsError::ZeroValuedTransparentOutput { index: 0 }, + PaymentsError::MemoForTransparentRecipient { index: 0 }, + PaymentsError::MemoTooLong { index: 0, len: 513 }, + PaymentsError::TotalOverflow, + PaymentsError::InsufficientFunds { + requested: 2, + spendable: 1, + }, + PaymentsError::InvalidUri(String::new()), + PaymentsError::Proposal(String::new()), + ]; + let mut codes: Vec<_> = all.iter().map(PaymentsError::code).collect(); + codes.sort_unstable(); + codes.dedup(); + assert_eq!(codes.len(), all.len()); + assert_eq!(PaymentsError::NoPayments.code(), "no_payments"); + // The message always mentions which payment is wrong. + assert!(PaymentsError::MemoTooLong { index: 3, len: 600 } + .to_string() + .contains("Payment 3")); + } +} diff --git a/crates/webzjs-wallet/src/wallet.rs b/crates/webzjs-wallet/src/wallet.rs index f3c2827..a7e027b 100644 --- a/crates/webzjs-wallet/src/wallet.rs +++ b/crates/webzjs-wallet/src/wallet.rs @@ -10,6 +10,10 @@ use tonic::{ use crate::chain_params::{change_pool_at, orchard_circuit_version, WalletClock}; use crate::error::Error; +use crate::payments::{ + check_spendable, spendable_shielded, validate_payments, validate_uri, PaymentSpec, + PaymentsError, ValidatedPayments, +}; use crate::BlockRange; use webzjs_common::Network; @@ -314,14 +318,15 @@ where } /// - /// Create a transaction proposal to send funds from the wallet to a given address + /// Shared proposal path: builds the change strategy and asks the backend for a proposal for `request`. + /// The outer error is a setup failure; the inner `Err(())` is a backend refusal (e.g. insufficient + /// balance), left for each caller to describe in its own words. /// - pub async fn propose_transfer( + async fn propose_request( &self, account_id: AccountId, - to_address: ZcashAddress, - value: u64, - ) -> Result, Error> { + request: TransactionRequest, + ) -> Result, ()>, Error> { let input_selector = GreedyInputSelector::new(); let change_pool = self.change_pool().await?; @@ -336,10 +341,6 @@ where Zatoshis::from_u64(self.min_split_output_value)?, ), ); - let request = TransactionRequest::new(vec![Payment::without_memo( - to_address, - Zatoshis::from_u64(value)?, - )])?; tracing::info!("Chain height: {:?}", self.db.read().await.chain_height()?); tracing::info!( @@ -350,7 +351,7 @@ where .get_target_and_anchor_heights(self.min_confirmations.trusted())? ); let mut db = self.db.write().await; - let proposal = propose_transfer::<_, _, _,_, ::Error>( + let proposal = propose_transfer::<_, _, _, _, ::Error>( &mut *db, &self.network, account_id, @@ -366,12 +367,100 @@ where // 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()))?; + ); + Ok(proposal.map_err(|_e| ())) + } + + /// + /// Create a transaction proposal to send funds from the wallet to a given address + /// + pub async fn propose_transfer( + &self, + account_id: AccountId, + to_address: ZcashAddress, + value: u64, + ) -> Result, Error> { + let request = TransactionRequest::new(vec![Payment::without_memo( + to_address, + Zatoshis::from_u64(value)?, + )])?; + let proposal = self.propose_request(account_id, request).await?.map_err(|_| { + Error::Generic("something bad happened when calling propose transfer. Possibly insufficient balance..".to_string()) + })?; tracing::info!("Transfer proposal created"); Ok(proposal) } + /// + /// Propose a transaction paying one or more recipients, each with an optional memo. + /// Everything is validated first (see `payments`), so bad input fails with a typed error. + /// + pub async fn propose_payments( + &self, + account_id: AccountId, + payments: Vec, + ) -> Result, Error> { + let validated = validate_payments(self.network.network_type(), &payments)?; + self.propose_validated(account_id, validated).await + } + + /// + /// Propose a transaction from a ZIP 321 payment URI (`zcash:...`). + /// + pub async fn propose_from_zip321( + &self, + account_id: AccountId, + uri: &str, + ) -> Result, Error> { + let validated = validate_uri(self.network.network_type(), uri)?; + self.propose_validated(account_id, validated).await + } + + async fn propose_validated( + &self, + account_id: AccountId, + validated: ValidatedPayments, + ) -> Result, Error> { + let summary = self + .db + .read() + .await + .get_wallet_summary(self.min_confirmations)?; + if let Some(balance) = summary + .as_ref() + .and_then(|s| s.account_balances().get(&account_id)) + { + check_spendable(validated.total(), spendable_shielded(balance))?; + } + let proposal = self + .propose_request(account_id, validated.request) + .await? + .map_err(|_| { + PaymentsError::Proposal( + "the wallet could not build a transaction for these payments".to_string(), + ) + })?; + tracing::info!("Payments proposal created"); + Ok(proposal) + } + + /// + /// Propose, prove, sign and broadcast a multi-recipient payment with optional memos. + /// + pub async fn transfer_payments( + &self, + seed_phrase: &str, + account_hd_index: u32, + from_account_id: AccountId, + payments: Vec, + ) -> Result<(), Error> { + let (usk, _) = usk_from_seed_str(seed_phrase, account_hd_index, &self.network)?; + let proposal = self.propose_payments(from_account_id, payments).await?; + let txids = self.create_proposed_transactions(proposal, &usk).await?; + tracing::info!("Sending transactions"); + self.send_authorized_transactions(&txids).await + } + /// /// Do the proving and signing required to create one or more transaction from the proposal. Created transactions are stored in the wallet database. /// From abcca1990f75512cd8b82c4f47175d00c65bc9d1 Mon Sep 17 00:00:00 2001 From: undefined Date: Fri, 16 Oct 2026 13:57:05 +0100 Subject: [PATCH 6/6] Add JS/PCZT multi-payment API with memos --- crates/webzjs-wallet/src/bindgen/mod.rs | 1 + crates/webzjs-wallet/src/bindgen/payments.rs | 155 +++++++++++++++++++ crates/webzjs-wallet/src/bindgen/proposal.rs | 16 ++ crates/webzjs-wallet/src/bindgen/wallet.rs | 76 +++++++++ crates/webzjs-wallet/src/error.rs | 7 +- crates/webzjs-wallet/src/payments.rs | 131 ++++++++++++++++ crates/webzjs-wallet/src/wallet.rs | 110 ++++++++----- 7 files changed, 460 insertions(+), 36 deletions(-) create mode 100644 crates/webzjs-wallet/src/bindgen/payments.rs diff --git a/crates/webzjs-wallet/src/bindgen/mod.rs b/crates/webzjs-wallet/src/bindgen/mod.rs index cbd27e2..68aa2e6 100644 --- a/crates/webzjs-wallet/src/bindgen/mod.rs +++ b/crates/webzjs-wallet/src/bindgen/mod.rs @@ -1,3 +1,4 @@ +pub mod payments; pub mod proposal; pub mod transaction_history; pub mod wallet; diff --git a/crates/webzjs-wallet/src/bindgen/payments.rs b/crates/webzjs-wallet/src/bindgen/payments.rs new file mode 100644 index 0000000..e246c15 --- /dev/null +++ b/crates/webzjs-wallet/src/bindgen/payments.rs @@ -0,0 +1,155 @@ +//! JavaScript-facing side of the multi-payment API: reading `{ to, value, memo }` objects from +//! JS and describing proposals back to JS. + +use js_sys::{Array, BigInt, Object, Reflect, Uint8Array}; +use wasm_bindgen::prelude::*; + +use crate::error::Error; +use crate::payments::{summarize_proposal, MemoInput, MemoView, PaymentSpec, PaymentsError}; + +#[wasm_bindgen(typescript_custom_section)] +const PAYMENT_TYPES: &'static str = r#" +/** One recipient of a multi-payment transaction. */ +export interface PaymentRequest { + /** Recipient address (unified, Sapling or transparent). */ + to: string; + /** Amount in zatoshis (1 ZEC = 100_000_000). Use a bigint above 2^53. */ + value: number | bigint; + /** + * Optional memo, shielded recipients only (at most 512 bytes). + * A string is sent as a text memo; a Uint8Array is sent as raw bytes. Empty means no memo. + */ + memo?: string | Uint8Array; +} + +/** A memo as it will appear on chain. Raw bytes are the full 512 bytes, never trimmed. */ +export type ProposedMemo = string | Uint8Array; + +export interface ProposedOutput { + to: string; + /** Zatoshis, as a bigint. */ + value: bigint; + /** Absent when the output carries no memo. */ + memo?: ProposedMemo; +} + +export interface ProposedChange { + pool: "sapling" | "orchard" | "ironwood" | "transparent"; + value: bigint; +} + +export interface ProposedStep { + outputs: ProposedOutput[]; + change: ProposedChange[]; + /** ZIP 317 fee of this step, in zatoshis. */ + fee: bigint; +} + +export interface ProposalDescription { + /** Total ZIP 317 fee over all steps, in zatoshis. */ + fee: bigint; + steps: ProposedStep[]; +} +"#; + +fn get(obj: &JsValue, key: &str) -> Option { + Reflect::get(obj, &key.into()) + .ok() + .filter(|v| !v.is_undefined() && !v.is_null()) +} + +fn read_value(v: &JsValue, index: usize) -> Result { + if let Some(n) = v.as_f64() { + // Only whole numbers that a double represents exactly. + if n.fract() == 0.0 && (0.0..=9_007_199_254_740_991.0).contains(&n) { + return Ok(n as u64); + } + return Err(PaymentsError::InvalidAmount { index }); + } + if v.is_bigint() { + return u64::try_from(v.clone()).map_err(|_| PaymentsError::InvalidAmount { index }); + } + Err(PaymentsError::MalformedPayment { index }) +} + +fn read_memo(v: &JsValue, index: usize) -> Result { + if let Some(s) = v.as_string() { + return Ok(MemoInput::Text(s)); + } + if v.is_instance_of::() { + return Ok(MemoInput::Bytes(Uint8Array::from(v.clone()).to_vec())); + } + Err(PaymentsError::InvalidMemoType { index }) +} + +/// Read a JS array of `PaymentRequest` objects. +pub fn payments_from_js(payments: &JsValue) -> Result, Error> { + if !Array::is_array(payments) { + return Err(PaymentsError::NoPayments.into()); + } + Array::from(payments) + .iter() + .enumerate() + .map(|(index, item)| { + let to = get(&item, "to") + .and_then(|v| v.as_string()) + .ok_or(PaymentsError::MalformedPayment { index })?; + let value = read_value( + &get(&item, "value").ok_or(PaymentsError::MalformedPayment { index })?, + index, + )?; + let memo = get(&item, "memo") + .map(|m| read_memo(&m, index)) + .transpose()?; + Ok(PaymentSpec { to, value, memo }) + }) + .collect::>() + .map_err(Error::from) +} + +fn set(obj: &Object, key: &str, value: &JsValue) { + let _ = Reflect::set(obj, &key.into(), value); +} + +/// Describe a proposal as a plain JS object (`ProposalDescription`). +pub fn describe( + proposal: &zcash_client_backend::proposal::Proposal< + zcash_client_backend::fees::StandardFeeRule, + super::wallet::NoteRef, + >, +) -> JsValue { + let summary = summarize_proposal(proposal); + let steps = Array::new(); + for step in &summary.steps { + let outputs = Array::new(); + for o in &step.outputs { + let out = Object::new(); + set(&out, "to", &o.to.as_str().into()); + set(&out, "value", &BigInt::from(o.value).into()); + match &o.memo { + Some(MemoView::Text(t)) => set(&out, "memo", &t.as_str().into()), + Some(MemoView::Bytes(b)) => { + set(&out, "memo", &Uint8Array::from(b.as_slice()).into()) + } + None => {} + } + outputs.push(&out); + } + let change = Array::new(); + for c in &step.change { + let ch = Object::new(); + set(&ch, "pool", &c.pool.into()); + set(&ch, "value", &BigInt::from(c.value).into()); + change.push(&ch); + } + let st = Object::new(); + set(&st, "outputs", &outputs); + set(&st, "change", &change); + set(&st, "fee", &BigInt::from(step.fee).into()); + steps.push(&st); + } + let result = Object::new(); + set(&result, "fee", &BigInt::from(summary.fee).into()); + set(&result, "steps", &steps); + result.into() +} diff --git a/crates/webzjs-wallet/src/bindgen/proposal.rs b/crates/webzjs-wallet/src/bindgen/proposal.rs index 421bb87..0be5c77 100644 --- a/crates/webzjs-wallet/src/bindgen/proposal.rs +++ b/crates/webzjs-wallet/src/bindgen/proposal.rs @@ -22,3 +22,19 @@ impl From for zcash_client_backend::proposal::Proposal u64 { + crate::payments::summarize_proposal(&self.inner).fee + } + + /// What this proposal will do: its fee and, per step, the outputs it pays (address, value, + /// memo) and the change it returns to the wallet. + #[wasm_bindgen(unchecked_return_type = "ProposalDescription")] + pub fn describe(&self) -> JsValue { + super::payments::describe(&self.inner) + } +} diff --git a/crates/webzjs-wallet/src/bindgen/wallet.rs b/crates/webzjs-wallet/src/bindgen/wallet.rs index 89460fc..a2d3ef9 100644 --- a/crates/webzjs-wallet/src/bindgen/wallet.rs +++ b/crates/webzjs-wallet/src/bindgen/wallet.rs @@ -6,6 +6,7 @@ use wasm_bindgen::prelude::*; use tonic_web_wasm_client::Client; +use crate::bindgen::payments::payments_from_js; use crate::error::Error; use crate::validation::validate_confirmations_policy; use crate::wallet::usk_from_seed_str; @@ -345,6 +346,56 @@ impl WebWallet { Ok(proposal.into()) } + /// Propose one transaction that pays one or more recipients, each with an optional memo. + /// + /// Everything is validated first; a failure is an `Error` whose `code` property is one of + /// `no_payments`, `invalid_address`, `wrong_network`, `invalid_amount`, + /// `zero_valued_transparent_output`, `memo_for_transparent_recipient`, `memo_too_long`, + /// `malformed_payment`, `invalid_memo_type`, `total_overflow`, `insufficient_funds` or + /// `proposal_failed`. + /// + /// # Arguments + /// + /// * `account_id` - The ID of the account in this wallet to send funds from + /// * `payments` - A list of `{ to, value, memo? }`. `memo` is a `string` (text memo) or a + /// `Uint8Array` (raw bytes), at most 512 bytes, and only for shielded recipients. + /// + /// # Examples + /// + /// ```javascript + /// const proposal = await wallet.propose_payments(1, [ + /// { to: ua, value: 100000, memo: "hello" }, + /// { to: ua2, value: 50000, memo: new Uint8Array([0xff, 1, 2, 3]) }, + /// ]); + /// console.log(proposal.fee, proposal.describe()); + /// ``` + pub async fn propose_payments( + &self, + account_id: u32, + #[wasm_bindgen(unchecked_param_type = "PaymentRequest[]")] payments: JsValue, + ) -> Result { + let payments = payments_from_js(&payments)?; + let proposal = self + .inner + .propose_payments(AccountId::from(account_id), payments) + .await?; + Ok(proposal.into()) + } + + /// Propose a transaction from a [ZIP 321](https://zips.z.cash/zip-0321) payment URI + /// (`zcash:...`), which may name several recipients and memos. + pub async fn propose_from_zip321( + &self, + account_id: u32, + uri: String, + ) -> Result { + let proposal = self + .inner + .propose_from_zip321(AccountId::from(account_id), &uri) + .await?; + Ok(proposal.into()) + } + /// Generate a valid Zcash transaction from a given proposal /// /// IMPORTANT: This will spawn a new webworker which will handle the proving task which may take 10s of seconds @@ -504,6 +555,31 @@ impl WebWallet { .map(Into::into) } + /// Like `propose_payments`, but creates a PCZT (not signed, not proven, not sent). + pub async fn pczt_create_payments( + &self, + account_id: u32, + #[wasm_bindgen(unchecked_param_type = "PaymentRequest[]")] payments: JsValue, + ) -> Result { + let payments = payments_from_js(&payments)?; + self.inner + .pczt_create_payments(AccountId::from(account_id), payments) + .await + .map(Into::into) + } + + /// Like `propose_from_zip321`, but creates a PCZT (not signed, not proven, not sent). + pub async fn pczt_create_from_zip321( + &self, + account_id: u32, + uri: String, + ) -> Result { + self.inner + .pczt_create_from_zip321(AccountId::from(account_id), &uri) + .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. diff --git a/crates/webzjs-wallet/src/error.rs b/crates/webzjs-wallet/src/error.rs index e76bf93..7893677 100644 --- a/crates/webzjs-wallet/src/error.rs +++ b/crates/webzjs-wallet/src/error.rs @@ -97,7 +97,12 @@ pub enum Error { impl From for JsValue { fn from(e: Error) -> Self { - js_sys::Error::new(&e.to_string()).into() + let js_error = js_sys::Error::new(&e.to_string()); + // Typed payment errors carry a stable `code` so callers need not parse the message. + if let Error::Payments(p) = &e { + let _ = js_sys::Reflect::set(&js_error, &"code".into(), &p.code().into()); + } + js_error.into() } } diff --git a/crates/webzjs-wallet/src/payments.rs b/crates/webzjs-wallet/src/payments.rs index 6fffb8b..aba0aff 100644 --- a/crates/webzjs-wallet/src/payments.rs +++ b/crates/webzjs-wallet/src/payments.rs @@ -80,6 +80,10 @@ pub enum PaymentsError { MemoTooLong { index: usize, len: usize }, /// The payments add up to more than can be represented. TotalOverflow, + /// A payment from JavaScript is not an object with a string `to` and a whole-number `value`. + MalformedPayment { index: usize }, + /// A memo from JavaScript is neither a string nor a `Uint8Array`. + InvalidMemoType { index: usize }, /// The payments total more than the account can currently spend. InsufficientFunds { requested: u64, spendable: u64 }, /// The payment URI could not be parsed. @@ -102,6 +106,8 @@ impl PaymentsError { PaymentsError::ZeroValuedTransparentOutput { .. } => "zero_valued_transparent_output", PaymentsError::MemoForTransparentRecipient { .. } => "memo_for_transparent_recipient", PaymentsError::MemoTooLong { .. } => "memo_too_long", + PaymentsError::MalformedPayment { .. } => "malformed_payment", + PaymentsError::InvalidMemoType { .. } => "invalid_memo_type", PaymentsError::TotalOverflow => "total_overflow", PaymentsError::InsufficientFunds { .. } => "insufficient_funds", PaymentsError::InvalidUri(_) => "invalid_uri", @@ -143,6 +149,14 @@ impl fmt::Display for PaymentsError { f, "Payment {index}: the memo is {len} bytes, but at most {MAX_MEMO_BYTES} are allowed" ), + PaymentsError::MalformedPayment { index } => write!( + f, + "Payment {index}: expected an object with a string `to`, a whole-number `value` in zatoshis and an optional `memo`" + ), + PaymentsError::InvalidMemoType { index } => write!( + f, + "Payment {index}: a memo must be a string (text) or a Uint8Array (raw bytes)" + ), PaymentsError::TotalOverflow => write!(f, "The payments add up to too large an amount"), PaymentsError::InsufficientFunds { requested, @@ -412,6 +426,105 @@ pub fn spendable_shielded(balance: &AccountBalance) -> Zatoshis { .fold(Zatoshis::ZERO, |acc, v| (acc + v).unwrap_or(acc)) } +/// How a memo reads back to a caller: text when it is a ZIP 302 text memo, the raw 512 bytes +/// otherwise. Raw bytes are never trimmed, because trailing zeros cannot be told apart from +/// payload: what is reported is exactly what goes on chain. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MemoView { + Text(String), + Bytes(Vec), +} + +impl MemoView { + /// `None` for the empty memo (`0xF6` followed by zeros), which means "no memo". + pub fn from_memo_bytes(bytes: &MemoBytes) -> Option { + match Memo::try_from(bytes) { + Ok(Memo::Empty) => None, + Ok(Memo::Text(t)) => Some(MemoView::Text(String::from(t))), + // Arbitrary data, future formats and undecodable text all report the raw bytes. + _ => Some(MemoView::Bytes(bytes.as_array().to_vec())), + } + } +} + +/// One output the proposal pays to a recipient. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OutputSummary { + pub to: String, + pub value: u64, + pub memo: Option, +} + +/// One change output the wallet adds back to itself. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ChangeSummary { + /// `"sapling"`, `"orchard"`, `"ironwood"` or `"transparent"`. + pub pool: &'static str, + pub value: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StepSummary { + pub outputs: Vec, + pub change: Vec, + /// ZIP 317 fee of this step, in zatoshis. + pub fee: u64, +} + +/// What a proposal will do, for showing to a user before they approve it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProposalSummary { + /// Total ZIP 317 fee over all steps, in zatoshis. + pub fee: u64, + pub steps: Vec, +} + +fn pool_name(pool: zcash_protocol::PoolType) -> &'static str { + use zcash_protocol::{PoolType, ShieldedPool}; + match pool { + PoolType::Transparent => "transparent", + PoolType::Shielded(ShieldedPool::Sapling) => "sapling", + PoolType::Shielded(ShieldedPool::Orchard) => "orchard", + PoolType::Shielded(ShieldedPool::Ironwood) => "ironwood", + } +} + +/// Describe a proposal: its fee and the outputs it pays. +pub fn summarize_proposal( + proposal: &zcash_client_backend::proposal::Proposal, +) -> ProposalSummary { + let steps: Vec = proposal + .steps() + .iter() + .map(|step| StepSummary { + outputs: step + .transaction_request() + .payments() + .values() + .map(|p| OutputSummary { + to: p.recipient_address().encode(), + value: p.amount().map(u64::from).unwrap_or(0), + memo: p.memo().and_then(MemoView::from_memo_bytes), + }) + .collect(), + change: step + .balance() + .proposed_change() + .iter() + .map(|c| ChangeSummary { + pool: pool_name(c.output_pool()), + value: u64::from(c.value()), + }) + .collect(), + fee: u64::from(step.balance().fee_required()), + }) + .collect(); + ProposalSummary { + fee: steps.iter().map(|s| s.fee).sum(), + steps, + } +} + #[cfg(test)] mod tests { use zcash_address::ToAddress; @@ -814,6 +927,8 @@ mod tests { requested: 2, spendable: 1, }, + PaymentsError::MalformedPayment { index: 0 }, + PaymentsError::InvalidMemoType { index: 0 }, PaymentsError::InvalidUri(String::new()), PaymentsError::Proposal(String::new()), ]; @@ -827,4 +942,20 @@ mod tests { .to_string() .contains("Payment 3")); } + + #[test] + fn memo_view_reports_text_bytes_and_nothing() { + let text = MemoBytes::from(&"hi there".parse::().unwrap()); + assert_eq!( + MemoView::from_memo_bytes(&text), + Some(MemoView::Text("hi there".into())) + ); + + let mut raw = vec![0xFF, 1, 2, 3]; + let bin = MemoBytes::from_bytes(&raw).unwrap(); + raw.resize(512, 0); + assert_eq!(MemoView::from_memo_bytes(&bin), Some(MemoView::Bytes(raw))); + + assert_eq!(MemoView::from_memo_bytes(&MemoBytes::empty()), None); + } } diff --git a/crates/webzjs-wallet/src/wallet.rs b/crates/webzjs-wallet/src/wallet.rs index a7e027b..7b71288 100644 --- a/crates/webzjs-wallet/src/wallet.rs +++ b/crates/webzjs-wallet/src/wallet.rs @@ -319,14 +319,14 @@ where /// /// Shared proposal path: builds the change strategy and asks the backend for a proposal for `request`. - /// The outer error is a setup failure; the inner `Err(())` is a backend refusal (e.g. insufficient + /// The outer error is a setup failure; the inner `Err` is the backend's refusal (debug text) (e.g. insufficient /// balance), left for each caller to describe in its own words. /// async fn propose_request( &self, account_id: AccountId, request: TransactionRequest, - ) -> Result, ()>, Error> { + ) -> Result, String>, Error> { let input_selector = GreedyInputSelector::new(); let change_pool = self.change_pool().await?; @@ -368,7 +368,7 @@ where None, None, ); - Ok(proposal.map_err(|_e| ())) + Ok(proposal.map_err(|e| format!("{:?}", e))) } /// @@ -416,11 +416,13 @@ where self.propose_validated(account_id, validated).await } - async fn propose_validated( + /// Fails with `InsufficientFunds` if the payments exceed the account's spendable shielded balance. + /// With no balance summary yet, the check is skipped and the backend decides. + async fn check_balance_covers( &self, account_id: AccountId, - validated: ValidatedPayments, - ) -> Result, Error> { + validated: &ValidatedPayments, + ) -> Result<(), Error> { let summary = self .db .read() @@ -432,6 +434,15 @@ where { check_spendable(validated.total(), spendable_shielded(balance))?; } + Ok(()) + } + + async fn propose_validated( + &self, + account_id: AccountId, + validated: ValidatedPayments, + ) -> Result, Error> { + self.check_balance_covers(account_id, &validated).await?; let proposal = self .propose_request(account_id, validated.request) .await? @@ -738,40 +749,69 @@ where )); } - // Create the PCZT. - let change_pool = self.change_pool().await?; - let change_strategy = MultiOutputChangeStrategy::new( - StandardFeeRule::Zip317, - None, - change_pool, - DustOutputPolicy::default(), - SplitPolicy::with_min_output_value( - NonZeroUsize::new(self.target_note_count) - .ok_or(Error::FailedToCreateTransaction)?, - Zatoshis::from_u64(self.min_split_output_value)?, - ), - ); - - let input_selector = GreedyInputSelector::new(); let request = TransactionRequest::new(vec![Payment::without_memo( to_address, Zatoshis::from_u64(value)?, )])?; + self.pczt_from_request(account_id, request, |e| { + Error::Generic(format!("something bad happened when calling propose transfer. Possibly insufficient balance... {}", e)) + }) + .await + } + + /// + /// Create a PCZT paying one or more recipients, each with an optional memo. + /// Validated like `propose_payments`; the PCZT still needs proving, signing and sending. + /// + pub async fn pczt_create_payments( + &self, + account_id: AccountId, + payments: Vec, + ) -> Result { + let validated = validate_payments(self.network.network_type(), &payments)?; + self.pczt_create_validated(account_id, validated).await + } + + /// + /// Create a PCZT from a ZIP 321 payment URI. + /// + pub async fn pczt_create_from_zip321( + &self, + account_id: AccountId, + uri: &str, + ) -> Result { + let validated = validate_uri(self.network.network_type(), uri)?; + self.pczt_create_validated(account_id, validated).await + } + + async fn pczt_create_validated( + &self, + account_id: AccountId, + validated: ValidatedPayments, + ) -> Result { + self.check_balance_covers(account_id, &validated).await?; + self.pczt_from_request(account_id, validated.request, |_| { + PaymentsError::Proposal( + "the wallet could not build a transaction for these payments".to_string(), + ) + .into() + }) + .await + } + + /// Shared tail of the PCZT paths: propose for `request`, then build the PCZT. + /// `on_refused` turns the backend's refusal text into the caller's error. + async fn pczt_from_request( + &self, + account_id: AccountId, + request: TransactionRequest, + on_refused: impl FnOnce(String) -> Error, + ) -> Result { + let proposal = self + .propose_request(account_id, request) + .await? + .map_err(on_refused)?; let mut db = self.db.write().await; - let proposal = propose_transfer::<_, _, _,_, ::Error>( - &mut *db, - &self.network, - account_id, - &input_selector, - &change_strategy, - 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:?}")))?; tracing::info!("PCZT proposal created"); let pczt = create_pczt_from_proposal::< _,