From 557e0eb0eced1cb49e684844e5ee3f02fde825db Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 8 Sep 2026 13:13:58 +0800 Subject: [PATCH 01/97] feat: add zcash chain runtime workspace --- .github/workflows/zcash-runtime.yml | 52 + README.md | 6 + chain-runtimes/README.md | 24 + chain-runtimes/zcash/.cargo/config.toml | 4 + chain-runtimes/zcash/.gitignore | 9 + chain-runtimes/zcash/CONTEXT.md | 162 + chain-runtimes/zcash/Cargo.lock | 3698 +++++++++++++++++ chain-runtimes/zcash/Cargo.toml | 93 + chain-runtimes/zcash/IMPORT.md | 59 + chain-runtimes/zcash/README.md | 319 ++ .../crates/zcash-keys-runtime/Cargo.toml | 52 + .../zcash-keys-runtime/TRANSPARENT_TX_API.md | 96 + .../zcash/crates/zcash-keys-runtime/build.rs | 9 + .../crates/zcash-keys-runtime/src/bindgen.rs | 165 + .../crates/zcash-keys-runtime/src/error.rs | 231 + .../crates/zcash-keys-runtime/src/keys.rs | 416 ++ .../crates/zcash-keys-runtime/src/lib.rs | 32 + .../crates/zcash-keys-runtime/src/sign.rs | 233 ++ .../src/transparent_send.rs | 1034 +++++ .../zcash/crates/zcash-runtime/Cargo.toml | 91 + .../zcash/crates/zcash-runtime/build.rs | 66 + .../zcash/crates/zcash-runtime/src/account.rs | 253 ++ .../zcash/crates/zcash-runtime/src/bindgen.rs | 885 ++++ .../crates/zcash-runtime/src/blockcache.rs | 259 ++ .../zcash/crates/zcash-runtime/src/clock.rs | 54 + .../zcash/crates/zcash-runtime/src/error.rs | 363 ++ .../zcash/crates/zcash-runtime/src/history.rs | 686 +++ .../zcash/crates/zcash-runtime/src/lib.rs | 59 + .../zcash/crates/zcash-runtime/src/network.rs | 351 ++ .../zcash/crates/zcash-runtime/src/perf.rs | 65 + .../zcash/crates/zcash-runtime/src/runtime.rs | 210 + .../zcash/crates/zcash-runtime/src/send.rs | 1015 +++++ .../zcash/crates/zcash-runtime/src/stats.rs | 277 ++ .../zcash/crates/zcash-runtime/src/storage.rs | 309 ++ .../zcash/crates/zcash-runtime/src/sync.rs | 1174 ++++++ .../crates/zcash-runtime/src/tx_state.rs | 347 ++ .../zcash/crates/zcash-runtime/src/wallet.rs | 153 + .../crates/zcash-runtime/tests/scan_repro.rs | 318 ++ .../crates/zcash-storage-benchmark/Cargo.toml | 24 + .../crates/zcash-storage-benchmark/build.rs | 46 + .../zcash-storage-benchmark/src/error.rs | 103 + .../crates/zcash-storage-benchmark/src/lib.rs | 19 + .../src/storage_benchmark.rs | 589 +++ chain-runtimes/zcash/docs/decisions.md | 468 +++ chain-runtimes/zcash/patches/.gitattributes | 2 + chain-runtimes/zcash/patches/manifest.json | 14 + ...te-wasm-vfs-0.2.0-durability-barrier.patch | 82 + ...cash_client_sqlite-0.22.0-no-bundled.patch | 10 + chain-runtimes/zcash/rust-toolchain.toml | 4 + chain-runtimes/zcash/scripts/build-wasm.sh | 69 + .../zcash/scripts/prepare-vendor.py | 93 + .../zcash/scripts/test_prepare_vendor.py | 90 + chain-runtimes/zcash/scripts/vendor-deps.sh | 5 + package.json | 5 +- 54 files changed, 15251 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/zcash-runtime.yml create mode 100644 chain-runtimes/README.md create mode 100644 chain-runtimes/zcash/.cargo/config.toml create mode 100644 chain-runtimes/zcash/.gitignore create mode 100644 chain-runtimes/zcash/CONTEXT.md create mode 100644 chain-runtimes/zcash/Cargo.lock create mode 100644 chain-runtimes/zcash/Cargo.toml create mode 100644 chain-runtimes/zcash/IMPORT.md create mode 100644 chain-runtimes/zcash/README.md create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/build.rs create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/build.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/account.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/error.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/history.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/network.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/send.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs create mode 100644 chain-runtimes/zcash/crates/zcash-storage-benchmark/Cargo.toml create mode 100644 chain-runtimes/zcash/crates/zcash-storage-benchmark/build.rs create mode 100644 chain-runtimes/zcash/crates/zcash-storage-benchmark/src/error.rs create mode 100644 chain-runtimes/zcash/crates/zcash-storage-benchmark/src/lib.rs create mode 100644 chain-runtimes/zcash/crates/zcash-storage-benchmark/src/storage_benchmark.rs create mode 100644 chain-runtimes/zcash/docs/decisions.md create mode 100644 chain-runtimes/zcash/patches/.gitattributes create mode 100644 chain-runtimes/zcash/patches/manifest.json create mode 100644 chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-durability-barrier.patch create mode 100644 chain-runtimes/zcash/patches/zcash_client_sqlite-0.22.0-no-bundled.patch create mode 100644 chain-runtimes/zcash/rust-toolchain.toml create mode 100755 chain-runtimes/zcash/scripts/build-wasm.sh create mode 100644 chain-runtimes/zcash/scripts/prepare-vendor.py create mode 100644 chain-runtimes/zcash/scripts/test_prepare_vendor.py create mode 100755 chain-runtimes/zcash/scripts/vendor-deps.sh diff --git a/.github/workflows/zcash-runtime.yml b/.github/workflows/zcash-runtime.yml new file mode 100644 index 000000000..98603e159 --- /dev/null +++ b/.github/workflows/zcash-runtime.yml @@ -0,0 +1,52 @@ +name: Zcash runtime + +on: + pull_request: + paths: + - 'chain-runtimes/zcash/**' + - '.github/workflows/zcash-runtime.yml' + push: + branches: [main] + paths: + - 'chain-runtimes/zcash/**' + - '.github/workflows/zcash-runtime.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-24.04 + timeout-minutes: 45 + defaults: + run: + working-directory: chain-runtimes/zcash + steps: + - uses: actions/checkout@v6 + - name: Install build tools + run: | + sudo apt-get update + sudo apt-get install -y clang llvm binaryen libsqlite3-dev pkg-config + rustup toolchain install 1.93.0 --profile minimal --target wasm32-unknown-unknown + cargo install wasm-pack --version 0.15.0 --locked + WASM_BINDGEN_VERSION=$(python3 -c 'import tomllib; print(next(p["version"] for p in tomllib.load(open("Cargo.lock", "rb"))["package"] if p["name"] == "wasm-bindgen"))') + cargo install wasm-bindgen-cli --version "$WASM_BINDGEN_VERSION" --locked + - name: Restore pinned vendor sources + run: bash scripts/vendor-deps.sh + - name: Test vendor reconstruction guards + run: python3 -m unittest discover -s scripts -p 'test_*.py' + - name: Test Rust workspace + run: cargo test --workspace --locked + - name: Build runtime and keys together + env: + CC_wasm32_unknown_unknown: /usr/bin/clang + AR_wasm32_unknown_unknown: /usr/bin/llvm-ar + run: bash scripts/build-wasm.sh --offline + - uses: actions/upload-artifact@v4 + with: + name: zcash-wasm-${{ github.sha }} + if-no-files-found: error + path: | + chain-runtimes/zcash/pkg/ + chain-runtimes/zcash/pkg-keys/ diff --git a/README.md b/README.md index 21947629f..89267596f 100644 --- a/README.md +++ b/README.md @@ -27,3 +27,9 @@ Merged fork PRs are intentionally skipped with a workflow summary notice; run `p Before enabling the workflow, install a GitHub App on `app-monorepo` with repository Contents (write) and Pull requests (write) permissions. Set repository variable `APP_RELEASE_APP_ID` and secret `APP_RELEASE_PRIVATE_KEY` in `app-modules`, and retain the existing `NPM_TOKEN` secret for npm publishing. The app-monorepo PR is never merged automatically. The app-monorepo job checks the existing module-ID registry but does not regenerate it: `module-id:update` requires a fresh Union Build module-ID map, which is unavailable in a clean dependency-update job. If a release adds native runtime modules, generate that map and update the registry during app-monorepo PR validation before merging it. + +## Chain runtimes + +Rust chain libraries live in [chain-runtimes](./chain-runtimes/README.md), separately +from React Native workspaces. Zcash is the first runtime; see its build and test +commands there. diff --git a/chain-runtimes/README.md b/chain-runtimes/README.md new file mode 100644 index 000000000..52950c40c --- /dev/null +++ b/chain-runtimes/README.md @@ -0,0 +1,24 @@ +# Chain runtimes + +Chain execution libraries live here alongside the React Native modules and views. +Each chain owns its Cargo workspace, lockfile, toolchain, patches, and build outputs. +These directories are not React Native packages and are not part of the root Yarn +workspaces or their shared version/publish commands. + +## Zcash + +See [zcash](./zcash/README.md) and its [import record](./zcash/IMPORT.md). + +From the repository root: + +```sh +yarn zcash:prepare +yarn zcash:test +yarn zcash:build +``` + +These convenience commands dispatch to the Rust project. The equivalent direct +commands in the Zcash README do not require installing the root Node dependencies. +Generated WASM stays out of Git. The Zcash CI workflow builds +both runtime and keys packages together and stores them as one artifact; it does +not publish npm packages. diff --git a/chain-runtimes/zcash/.cargo/config.toml b/chain-runtimes/zcash/.cargo/config.toml new file mode 100644 index 000000000..79febffe2 --- /dev/null +++ b/chain-runtimes/zcash/.cargo/config.toml @@ -0,0 +1,4 @@ +# getrandom 0.4 在 wasm32-unknown-unknown 上必须显式指定后端, +# 否则编译期报 "the wasm* targets are not supported by default"。 +[target.wasm32-unknown-unknown] +rustflags = ['--cfg', 'getrandom_backend="wasm_js"'] diff --git a/chain-runtimes/zcash/.gitignore b/chain-runtimes/zcash/.gitignore new file mode 100644 index 000000000..c680152bb --- /dev/null +++ b/chain-runtimes/zcash/.gitignore @@ -0,0 +1,9 @@ +/target +/pkg +/pkg-keys +/vendor +*.log +__pycache__/ + +# Keep local wallet fixtures out of source control. +/.secrets/ diff --git a/chain-runtimes/zcash/CONTEXT.md b/chain-runtimes/zcash/CONTEXT.md new file mode 100644 index 000000000..d1a1f56f6 --- /dev/null +++ b/chain-runtimes/zcash/CONTEXT.md @@ -0,0 +1,162 @@ +# Zcash Runtime — 领域词汇 + +本文件只定义**术语**,不放实现细节、不放待办。设计决策见 `docs/decisions.md`。 + +--- + +## Wallet(钱包库) + +一份 SQLite 数据库,由 `zcash_client_sqlite` 管理其 schema。 + +**一个 wallet 对应一个 network,而不是一个种子或一个账户。** 宿主为同一网络上的 +所有 Account 注册 UFVK,数据库一次下载和扫描即可试解密全部账户。wallet 的身份只有 +`network`,**不包含 lightwalletd 端点**:同一条链上不同端点提供同一份数据,换端点 +不能导致全量重扫。 + +wallet 是**纯派生缓存**。SQLite 会保存已注册 UFVK、birthday 和扫描结果,以便重载后 +继续工作;但这些不是唯一副本。宿主账户元数据仍是 UFVK 与 birthday 的权威来源, +所以删除数据库只会触发重新注册和重扫,不会丢失不可再生材料。 + +## Account(账户) + +wallet 内的一个 UFVK 及其派生地址。对应 OneKey 的一个链上账户(一个 `hdIndex`)。 + +在 runtime 内以 UUID 标识。**该 UUID 不稳定**:Purge 后重建会得到新的 UUID, +所以宿主不能缓存它,每次从 UFVK 重新解析。 + +## Seed Fingerprint(种子指纹) + +ZIP-32 定义的种子标识。**是标准值,不是任意哈希** —— 宿主持久化它作为账户身份, +自行发明的哈希会让存量账户全部失配。 + +## Public Test Mnemonic(公开测试助记词) + +专用于可重复测试、已公开且不承载真实资产的助记词夹具。当前允许记录的是标准 +`abandon` 开头、`about` 结尾的 12 词测试向量;任何真实钱包或非公开测试钱包的 +助记词都不属于此概念,禁止进入文档、日志、截图或测试产物。 + +_Avoid_: Test seed、测试钱包助记词(两者都容易被误解为可以记录任意测试账户密钥) + +## Purge(清缓存) + +丢弃已扫结果、保留重建所需材料的操作。因为 wallet 是纯派生缓存,Purge 只是 +"要重扫一遍",不丢任何不可再生的数据。 + +两种用途:出问题时的手动重置;删账户时清除已解密的屏蔽交易历史——后者是隐私要求, +那份历史正是 Zcash 存在的意义所要隐藏的东西。 + +## Lane(同步车道) + +扫描进度分两条逻辑车道,回答不同问题: + +- **Tip lane**:余额新不新。用户当下看的是它。 +- **Birthday lane**:这个钱包是否已经知道自己的全部历史。**它才决定余额可不可信**—— + 回填未完成时余额可能偏低,因为更早的收款还没被发现。 + +两条车道由宿主调度,runtime 只按宿主指定的优先级推进一段,且候选区间只能来自 +上游的建议集合。 + +## Reservation(占用凭证) + +一次交易提案对所选 note 的占用,以 32 字节 owner token 标识。 + +存在的理由:屏蔽 note 形如 UTXO,同一个 note 被两笔交易花,第二笔必被拒。而 +"选好币"到"真的花掉"之间隔着审核页、密码、证明、签名,这段窗口内必须防止 +另一次选币挑中同一批。 + +token 由**调用方持有**:先生成、先持久化、再构造,这样崩溃恢复后仍知道该释放哪一批。 + +## Capability(能力声明) + +runtime 当下**实际**能做什么。宿主据此提前隐藏做不到的操作。 + +每个标志定义在限制它的那段代码旁边,且与运行时的拒绝分支一一对应——不会出现 +"声称支持其实不支持"。发送失败得晚代价很高:提案已锁 note、用户已输密码。 + +## 池(Pool) + +- **transparent**:公开,与比特币同构。再分 regular 与 coinbase,后者成熟规则不同 + 且只能经由专门的 shielding 路径转出。 +- **sapling**:本产品不支持的历史屏蔽池。不得作为收款 receiver、余额或历史的 + 产品数据源,也不得作为发送来源;“不支持”不是“显示但只读”。 +- **orchard**:屏蔽。保留历史余额并支持迁出;NU6.3 后不再是新收款目标。 +- **ironwood**:NU6.3 引入的当前屏蔽池;向 UA 的新付款默认落在这里。 + +跨池合计是产品口径,不是链上事实,因此由宿主计算;runtime 只逐池报事实。 + +## Private Receive UA Policy(私密收款地址策略) + +App 对外展示的私密 Unified Address 所包含的 receiver 集合,当前仅包含 Orchard +receiver。Ironwood 没有独立的 UA receiver typecode;“地址含 Orchard receiver”不代表 +新收到的资金会进入 Orchard。 + +_Avoid_: Ironwood 地址、最新池地址 + +## Current Shielded Output Pool(当前私密输出池) + +当前网络升级下,新私密输出、Shield All 目标和私密找零实际落入的池,当前为 +Ironwood。它与 Private Receive UA Policy、可花费来源池是三个不同维度;调用方不得 +各自写死池名。 + +_Avoid_: Current Receiving Pool、最新池、默认隐私池 + +## Spendable Shielded Sources(可花费私密来源池) + +普通发送允许消费的私密来源池集合,当前为 Orchard 和 Ironwood。指定来源池时必须 +严格隔离,不得因透明花费测试开关而追加其他池的输入。 + +_Avoid_: Current Shielded Output Pool(它描述输出目标,不描述可花费来源) + +## Shield All(全部屏蔽) + +把账户中全部符合条件的 regular transparent UTXO 扣除手续费后,转入自己的 +Current Shielded Output Pool。它不消费任何已有私密池,也不消费 Coinbase UTXO。 + +_Avoid_: Shield、归集(单独使用时无法表达来源、目标和“全部”语义) + +## Internal Transparent Spending(内测透明花费) + +wallet runtime 接受普通透明输入的底层能力。它不属于 OneKey 产品的正常发送路径; +App 始终传入关闭值,能力的开启分支只能由 runtime 自身的隔离测试覆盖,不能出现在 +普通 Debug UI 或可持久化设置中。 + +_Avoid_: Debug 开关(Developer Mode 在正式构建中仍可能启用,不等价于构建授权) + +## Transparent Mode(透明模式) + +账户只使用 Zcash 透明地址和 OneKey 后端数据,不注册 UFVK、不扫描私密池,也不加载 +wallet runtime。查看余额和历史不需要任何 Zcash WASM;软件发送按需加载无数据库、 +无网络、无扫描器的轻量 Zcash signer。 + +_Avoid_: Privacy disabled(容易把产品模式误解为一次临时暂停) + +## Privacy Mode(隐私模式) + +账户允许注册 UFVK,并由共享 wallet runtime 扫描支持的私密池。关闭该模式必须停止 +该 UFVK 的 trial decryption,而不只是隐藏 UI。当前支持对象是软件 HD 账户;导入 +助记词仍属于 HD,单私钥账户和观察账户不属于 Privacy Mode。 + +## Privacy Pause(暂停隐私处理) + +把 UFVK 标为 inactive,停止后续扫描并隐藏私密余额、历史、收款和发送入口,同时保留 +runtime 缓存与 birthday。它不会移动链上资金,也不是删除本地隐私数据。 + +## Active UFVK Set(当前启用的隐私身份集) + +宿主每次调用扫描时显式传入的 UFVK 去重集合。Runtime 只用这些身份的 +Orchard key 试解密 Orchard/Ironwood,不在 Rust DB 持久化产品开关;空集合是错误, +不得解释为“扫描全部账户”。 + +_Avoid_: Registered UFVK Set(数据库已注册身份不等于产品已启用身份) + +## Privacy Resume Cursor(隐私恢复游标) + +宿主在 Privacy Pause 时保存的区块高度。同 network wallet 的 scan queue 是全局的, +其他 Active UFVK 在暂停期间会继续推进它;因此重新启用前,宿主必须加入重组安全余量, +再用 `queueRescanFrom` 把缺失区间重新排队。该游标属于宿主产品状态,不属于 runtime DB。 + +## Delete Local Privacy Data(删除本地隐私数据) + +用户明确触发的破坏性本地操作:删除账户的 runtime 派生缓存和本地 UFVK/UA 元数据, +但保留 birthday。重新开启 Privacy Mode 时重新派生观察材料,并从保留的 birthday +重扫。该操作不得与普通模式开关合并。 diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock new file mode 100644 index 000000000..c6b3958a0 --- /dev/null +++ b/chain-runtimes/zcash/Cargo.lock @@ -0,0 +1,3698 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "accessory" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc86a613208ca7d144ca24f6ec49c5cdfa5c05a46f2f7ab5880ff99371f165de" +dependencies = [ + "macroific 3.0.1", + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "atomic-polyfill" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4" +dependencies = [ + "critical-section", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bech32" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32637268377fc7b10a8c6d51de3e7fba1ce5dd371a96e342b34e6078db558e7f" + +[[package]] +name = "bellman" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afceed28bac7f9f5a508bca8aeeff51cdfa4770c0b967ac55c621e2ddfd6171" +dependencies = [ + "bitvec", + "blake2s_simd", + "byteorder", + "ff", + "group", + "pairing", + "rand_core", + "subtle", +] + +[[package]] +name = "bip0039" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "568b6890865156d9043af490d4c4081c385dd68ea10acd6ca15733d511e6b51c" +dependencies = [ + "hmac 0.12.1", + "pbkdf2", + "rand", + "sha2 0.10.9", + "unicode-normalization", + "zeroize", +] + +[[package]] +name = "bip32" +version = "0.6.0-pre.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "143f5327f23168716be068f8e1014ba2ea16a6c91e8777bc8927da7b51e1df1f" +dependencies = [ + "bs58", + "hmac 0.13.0-pre.4", + "rand_core", + "ripemd 0.2.0-pre.4", + "secp256k1", + "sha2 0.11.0-pre.4", + "subtle", + "zeroize", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "blake2b_simd" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3560a7b1951efe814fcd721938313adc56753ca39f4b23847d7e9a2402f5dbff" +dependencies = [ + "arrayvec", + "constant_time_eq", +] + +[[package]] +name = "blake2s_simd" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2380c0236432f7b22a70229df30f218f5293870c056beb76f5ca068e3273a366" +dependencies = [ + "arrayvec", + "constant_time_eq", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.11.0-rc.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fd016a0ddc7cb13661bf5576073ce07330a693f8608a1320b4e20561cc12cdc" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bls12_381" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7bc6d6292be3a19e6379786dac800f551e5865a5bb51ebbe3064ab80433f403" +dependencies = [ + "ff", + "group", + "pairing", + "rand_core", + "subtle", +] + +[[package]] +name = "bounded-vec" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09dc0086e469182132244e9b8d313a0742e1132da43a08c24b9dd3c18e0faf3a" +dependencies = [ + "thiserror 2.0.20", +] + +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "sha2 0.10.9", + "tinyvec", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + +[[package]] +name = "cc" +version = "1.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "num-traits", + "serde", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout", + "zeroize", +] + +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.20", +] + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "const-crc32-nostd" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "808ac43170e95b11dd23d78aa9eaac5bea45776a602955552c4e833f3f0f823d" + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "corez" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4df6f98652d30167eaeea34d77b730e07c8caba6df17bd4551842b9b8da01deb" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-deque" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.0-rc.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0b8ce8218c97789f16356e7896b3714f26c2ee1079b79c0b7ae7064bb9089fa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "daggy" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70def8d72740e44d9f676d8dab2c933a236663d86dd24319b57a2bed4d694774" +dependencies = [ + "petgraph 0.7.1", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "defmt" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror 2.0.20", +] + +[[package]] +name = "delegate-display" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54e3a499943fd5180aeffcb708164ffb22125ceeccb05491b5297981d37d6249" +dependencies = [ + "impartial-ord", + "itoa", + "macroific 3.0.1", + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[package]] +name = "derive-getters" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74ef43543e701c01ad77d3a5922755c6a1d71b22d942cb8042be4994b380caff" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", + "unicode-xid", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.0-pre.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf2e3d6615d99707295a9673e889bf363a04b2a466bd320c65a72536f7577379" +dependencies = [ + "block-buffer 0.11.0-rc.3", + "crypto-common 0.2.0-rc.1", + "subtle", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + +[[package]] +name = "equihash" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "306286e8dcc39ab3dfceb74c792ce8baffdab90591321d3ffaae64829734c37f" +dependencies = [ + "blake2b_simd", + "corez", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "f4jumble" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d42773cb15447644d170be20231a3268600e0c4cea8987d013b93ac973d3cf7" +dependencies = [ + "blake2b_simd", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fancy_constructor" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a8211ab12c36b63c269e17873331dc1da196a3edb7a5c79015677ef972da34a" +dependencies = [ + "macroific 3.0.1", + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "bitvec", + "rand_core", + "subtle", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" + +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "nanorand", + "spin", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "fpe" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26c4b37de5ae15812a764c958297cfc50f5c010438f60c6ce75d11b802abd404" +dependencies = [ + "cbc", + "cipher", + "libm", + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "frost-core" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81ef2787af391c7e8bedc037a3b9ea03dde803fbd93e778e6bb369547800e5cd" +dependencies = [ + "byteorder", + "const-crc32-nostd", + "derive-getters", + "document-features", + "hex", + "itertools", + "postcard", + "rand_core", + "serde", + "serdect", + "thiserror 2.0.20", + "visibility", + "zeroize", + "zeroize_derive", +] + +[[package]] +name = "frost-rerandomized" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f4c5cedd2426728adef2c0b1720f57676354c473836d1ccc50d0f0d1c91942b" +dependencies = [ + "derive-getters", + "document-features", + "frost-core", + "hex", + "rand_core", +] + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[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", + "wasm-bindgen", +] + +[[package]] +name = "getset" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cf442baaabe4213ce7d1239afc26c039180b6456da2cededa316ae2c8a77a77" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "gloo-timers" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "memuse", + "rand_core", + "subtle", +] + +[[package]] +name = "h2" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c0e8a181239723652be9062bb56ca5bf5f64011f73b623f6f4fc59086a228" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap 2.14.0", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "halo2_gadgets" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb2a697cad929f706b7987fe804ad57d43622cd37463ba7e4d662a926fdcfea3" +dependencies = [ + "arrayvec", + "bitvec", + "ff", + "group", + "halo2_poseidon", + "halo2_proofs", + "lazy_static", + "pasta_curves", + "rand", + "sinsemilla", + "subtle", + "uint", +] + +[[package]] +name = "halo2_legacy_pdqsort" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47716fe1ae67969c5e0b2ef826f32db8c3be72be325e1aa3c1951d06b5575ec5" + +[[package]] +name = "halo2_poseidon" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa3da60b81f02f9b33ebc6252d766f843291fb4d2247a07ae73d20b791fc56f" +dependencies = [ + "bitvec", + "ff", + "group", + "pasta_curves", +] + +[[package]] +name = "halo2_proofs" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5aca1c66059a919227dec97444a11a4350d2f9c820ca48690988f0aa0e81cbf" +dependencies = [ + "blake2b_simd", + "ff", + "group", + "halo2_legacy_pdqsort", + "indexmap 1.9.3", + "maybe-rayon", + "pasta_curves", + "rand_core", + "tracing", +] + +[[package]] +name = "hash32" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" +dependencies = [ + "byteorder", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "heapless" +version = "0.7.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f" +dependencies = [ + "atomic-polyfill", + "hash32", + "rustc_version", + "serde", + "spin", + "stable_deref_trait", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "hmac" +version = "0.13.0-pre.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4b1fb14e4df79f9406b434b60acef9f45c26c50062cccf1346c6103b8c47d58" +dependencies = [ + "digest 0.11.0-pre.9", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2d35805454dc9f8662a98d6d61886ffe26bd465f5960e0e55345c70d5c0d2a9" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-timeout" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" +dependencies = [ + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "libc", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "impartial-ord" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc680e03d1a08bdc1c01b60e0c39723430ced63d8cabd93cee0449b6ba916a25" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "incrementalmerkletree" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30821f91f0fa8660edca547918dc59812893b497d07c1144f326f07fdd94aba9" +dependencies = [ + "either", +] + +[[package]] +name = "indexed_db_futures" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69ff41758cbd104e91033bb53bc449bec7eea65652960c81eddf3fc146ecea19" +dependencies = [ + "accessory", + "cfg-if", + "delegate-display", + "derive_more", + "fancy_constructor", + "indexed_db_futures_macros_internal", + "js-sys", + "sealed 0.6.0", + "smallvec", + "thiserror 2.0.20", + "tokio", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "indexed_db_futures_macros_internal" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caeba94923b68f254abef921cea7e7698bf4675fdd89d7c58bf1ed885b49a27d" +dependencies = [ + "macroific 2.0.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jiff" +version = "0.2.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09" +dependencies = [ + "defmt", +] + +[[package]] +name = "jiff-static" +version = "0.2.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "jubjub" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8499f7a74008aafbecb2a2e608a3e13e4dd3e84df198b604451efe93f2de6e61" +dependencies = [ + "bitvec", + "bls12_381", + "ff", + "group", + "rand_core", + "subtle", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libsqlite3-sys" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f" +dependencies = [ + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litrs" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "macroific" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89f276537b4b8f981bf1c13d79470980f71134b7bdcc5e6e911e910e556b0285" +dependencies = [ + "macroific_attr_parse 2.0.0", + "macroific_core 2.0.0", + "macroific_macro 2.0.0", +] + +[[package]] +name = "macroific" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c437abb3bf40939b00d1dff858ed2050d948bc230dee39546ed16795fcf10ec2" +dependencies = [ + "macroific_attr_parse 3.0.1", + "macroific_core 3.0.1", + "macroific_macro 3.0.1", +] + +[[package]] +name = "macroific_attr_parse" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad4023761b45fcd36abed8fb7ae6a80456b0a38102d55e89a57d9a594a236be9" +dependencies = [ + "proc-macro2", + "quote", + "sealed 0.6.0", + "syn 2.0.119", +] + +[[package]] +name = "macroific_attr_parse" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb7a82ec1aa16094da719be18615d79cb2574b037358e4e6c6d96eedcff3a93" +dependencies = [ + "proc-macro2", + "quote", + "sealed 0.7.0", + "syn 3.0.3", +] + +[[package]] +name = "macroific_core" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a7594d3c14916fa55bef7e9d18c5daa9ed410dd37504251e4b75bbdeec33e3" +dependencies = [ + "proc-macro2", + "quote", + "sealed 0.6.0", + "syn 2.0.119", +] + +[[package]] +name = "macroific_core" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26c8e789484d2fa216eee9d5e0565ba80ccda389bcf0e111143a7b8f4792336e" +dependencies = [ + "proc-macro2", + "quote", + "sealed 0.7.0", + "syn 3.0.3", +] + +[[package]] +name = "macroific_macro" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4da6f2ed796261b0a74e2b52b42c693bb6dee1effba3a482c49592659f824b3b" +dependencies = [ + "macroific_attr_parse 2.0.0", + "macroific_core 2.0.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "macroific_macro" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e30d63cb102648965753f0d47a6ab171b1cbb1fb5c363f4784ea986782fc7b77" +dependencies = [ + "macroific_attr_parse 3.0.1", + "macroific_core 3.0.1", + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memuse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d97bbf43eb4f088f8ca469930cde17fa036207c9a5e02ccc5107c4e8b17c964" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multimap" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" + +[[package]] +name = "nanorand" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nonempty" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "549e471b99ccaf2f89101bec68f4d244457d5a95a9c3d0672e9564124397741d" + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "onekey-zcash-keys" +version = "0.0.1" +dependencies = [ + "bip0039", + "bs58", + "getrandom 0.2.17", + "getrandom 0.4.3", + "hex", + "js-sys", + "orchard", + "pczt", + "sapling-crypto", + "secp256k1", + "serde", + "serde_json", + "thiserror 2.0.20", + "wasm-bindgen", + "zcash_address", + "zcash_keys", + "zcash_primitives", + "zcash_protocol", + "zcash_script", + "zcash_transparent", + "zeroize", + "zip32", +] + +[[package]] +name = "onekey-zcash-runtime" +version = "0.0.1" +dependencies = [ + "async-trait", + "console_error_panic_hook", + "futures", + "futures-util", + "getrandom 0.4.3", + "gloo-timers", + "hex", + "js-sys", + "orchard", + "pczt", + "prost", + "rand", + "rand_chacha", + "rusqlite", + "sapling-crypto", + "schemerz", + "schemerz-rusqlite", + "serde", + "serde_json", + "sqlite-wasm-rs", + "sqlite-wasm-vfs", + "thiserror 2.0.20", + "time", + "tokio", + "tonic", + "tonic-web-wasm-client", + "tracing", + "tracing-subscriber", + "tracing-wasm", + "uuid", + "wasm-bindgen", + "wasm-bindgen-futures", + "zcash_address", + "zcash_client_backend", + "zcash_client_sqlite", + "zcash_keys", + "zcash_primitives", + "zcash_protocol", + "zcash_transparent", + "zip321", +] + +[[package]] +name = "onekey-zcash-storage-benchmark" +version = "0.0.1" +dependencies = [ + "console_error_panic_hook", + "js-sys", + "rusqlite", + "serde", + "serde_json", + "sqlite-wasm-rs", + "sqlite-wasm-vfs", + "wasm-bindgen", + "wasm-bindgen-futures", +] + +[[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.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3cb2b35534bba3c63fbf640dc6cd9dfd1ece2fae886cdab4ab1f1e380dd6ca1" +dependencies = [ + "aes", + "bitvec", + "blake2b_simd", + "corez", + "ff", + "fpe", + "getset", + "group", + "halo2_gadgets", + "halo2_poseidon", + "halo2_proofs", + "hex", + "incrementalmerkletree", + "lazy_static", + "memuse", + "nonempty", + "pasta_curves", + "rand", + "rand_core", + "reddsa", + "serde", + "sinsemilla", + "subtle", + "tracing", + "visibility", + "zcash_note_encryption", + "zcash_spec", + "zip32", +] + +[[package]] +name = "pairing" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81fec4625e73cf41ef4bb6846cafa6d44736525f442ba45e407c4a000a13996f" +dependencies = [ + "group", +] + +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core", + "subtle", +] + +[[package]] +name = "pasta_curves" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3437083215c505e867eea5478371feba43d7689d6d15ec0a209eb46fb0d4cda6" +dependencies = [ + "blake2b_simd", + "ff", + "group", + "lazy_static", + "rand", + "static_assertions", + "subtle", +] + +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest 0.10.7", + "password-hash", +] + +[[package]] +name = "pczt" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5592f4f3eba7f9344cc423f45b6e65911e0630c9b89968d5a20792aadd5a0eb" +dependencies = [ + "blake2b_simd", + "bls12_381", + "ff", + "getset", + "jubjub", + "nonempty", + "orchard", + "pasta_curves", + "postcard", + "rand_core", + "redjubjub", + "sapling-crypto", + "secp256k1", + "serde", + "serde_with", + "zcash_note_encryption", + "zcash_primitives", + "zcash_protocol", + "zcash_script", + "zcash_transparent", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772" +dependencies = [ + "fixedbitset", + "indexmap 2.14.0", +] + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap 2.14.0", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", + "heapless", + "serde", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-build" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042" +dependencies = [ + "heck", + "itertools", + "log", + "multimap", + "petgraph 0.8.3", + "prettyplease", + "prost", + "prost-types", + "regex", + "syn 2.0.119", + "tempfile", +] + +[[package]] +name = "prost-derive" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "prost-types" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a" +dependencies = [ + "prost", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_distr" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" +dependencies = [ + "num-traits", + "rand", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "reddsa" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4784b85c8bfd17b36b86e664e6e504ecdb586001086ee23749e4a633bbb84832" +dependencies = [ + "blake2b_simd", + "byteorder", + "frost-rerandomized", + "group", + "hex", + "jubjub", + "pasta_curves", + "rand_core", + "serde", + "thiserror 2.0.20", + "zeroize", +] + +[[package]] +name = "redjubjub" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89b0ac1bc6bb3696d2c6f52cff8fba57238b81da8c0214ee6cd146eb8fde364e" +dependencies = [ + "rand_core", + "reddsa", + "thiserror 1.0.69", + "zeroize", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "ripemd" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "ripemd" +version = "0.2.0-pre.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48cf93482ea998ad1302c42739bc73ab3adc574890c373ec89710e219357579" +dependencies = [ + "digest 0.11.0-pre.9", +] + +[[package]] +name = "rsqlite-vfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown 0.16.1", + "thiserror 2.0.20", +] + +[[package]] +name = "rusqlite" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" +dependencies = [ + "bitflags 2.13.1", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "time", + "uuid", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags 2.13.1", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0527518605e68109d875e248ea259b6758801cf165e4b2c2733ae3b51f12535a" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "sapling-crypto" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d70756ede56b5e4dd417979777bd87ddb83dfcbd0815dbf8175a9920537f8a0" +dependencies = [ + "aes", + "bellman", + "bitvec", + "blake2b_simd", + "blake2s_simd", + "bls12_381", + "corez", + "document-features", + "ff", + "fpe", + "getset", + "group", + "hex", + "incrementalmerkletree", + "jubjub", + "lazy_static", + "memuse", + "rand", + "rand_core", + "redjubjub", + "subtle", + "tracing", + "zcash_note_encryption", + "zcash_spec", + "zip32", +] + +[[package]] +name = "schemerz" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e82960ac11ccabd77d53c933532612079e01205b5873ec5095f4b3426493434" +dependencies = [ + "daggy", + "indexmap 1.9.3", + "log", + "thiserror 1.0.69", + "uuid", +] + +[[package]] +name = "schemerz-rusqlite" +version = "0.370.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca6df8a13fb3b7914f94ac6579bd5e76b9292f135886e6becc3525f9e5116827" +dependencies = [ + "rusqlite", + "schemerz", + "uuid", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sealed" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22f968c5ea23d555e670b449c1c5e7b2fc399fdaec1d304a17cd48e288abc107" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "sealed" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b68e2ea526d9fb32f23ca8894fb5da9e743f34c2f41701f0501dc8a25c4b343" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "secp256k1" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9465315bc9d4566e1724f0fffcbcc446268cb522e60f9a27bcded6b19c108113" +dependencies = [ + "secp256k1-sys", +] + +[[package]] +name = "secp256k1-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" +dependencies = [ + "cc", +] + +[[package]] +name = "secrecy" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bd1c54ea06cfd2f6b63219704de0b9b4f72dcc2b8fdef820be6cd799780e91e" +dependencies = [ + "zeroize", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_with" +version = "3.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee78f1fbe43ac4a0e47aadb3dbd357b69eb0d3793e948624cd03dd2750ab1c0a" +dependencies = [ + "base64", + "bs58", + "chrono", + "hex", + "jiff", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8705578779c2b6bd90d84d66eb2e206b708b1a4d7b9f17641b293545bf1c7e46" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serdect" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a84f14a19e9a014bb9f4512488d9829a68e04ecabffb0f9904cd1ace94598177" +dependencies = [ + "base16ct", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.0-pre.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "540c0893cce56cdbcfebcec191ec8e0f470dd1889b6e7a0b503e310a94a168f5" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest 0.11.0-pre.9", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shardtree" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8147447aed7be4736e271825b8c3a4432efb7182e71363169b572371ddef452e" +dependencies = [ + "bitflags 2.13.1", + "either", + "incrementalmerkletree", + "tracing", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "sinsemilla" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d268ae0ea06faafe1662e9967cd4f9022014f5eeb798e0c302c876df8b7af9c" +dependencies = [ + "group", + "pasta_curves", + "subtle", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + +[[package]] +name = "sqlite-wasm-vfs" +version = "0.2.0" +dependencies = [ + "indexed_db_futures", + "js-sys", + "rsqlite-vfs", + "thiserror 2.0.20", + "tokio", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "js-sys", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tonic" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" +dependencies = [ + "async-trait", + "base64", + "bytes", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-timeout", + "hyper-util", + "percent-encoding", + "pin-project", + "socket2", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-stream", + "tower", + "tower-layer", + "tower-service", + "tracing", + "webpki-roots", +] + +[[package]] +name = "tonic-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322" +dependencies = [ + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tonic-prost" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0" +dependencies = [ + "bytes", + "prost", + "tonic", +] + +[[package]] +name = "tonic-prost-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "654e5643eff75d7f8c99197ce1440ed19a3474eada74c12bbac488b2cafdae27" +dependencies = [ + "prettyplease", + "proc-macro2", + "prost-build", + "prost-types", + "quote", + "syn 2.0.119", + "tempfile", + "tonic-build", +] + +[[package]] +name = "tonic-web-wasm-client" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c0469c353de5f665c95f898074b5b004b500c6722214c3249f1dc79c0a2a3f6" +dependencies = [ + "base64", + "byteorder", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "httparse", + "js-sys", + "pin-project", + "thiserror 2.0.20", + "tonic", + "tower-service", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "indexmap 2.14.0", + "pin-project-lite", + "slab", + "sync_wrapper", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "sharded-slab", + "thread_local", + "tracing-core", +] + +[[package]] +name = "tracing-wasm" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4575c663a174420fa2d78f4108ff68f65bf2fbb7dd89f33749b6e826b3626e07" +dependencies = [ + "tracing", + "tracing-subscriber", + "wasm-bindgen", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uint" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76f64bba2c53b04fcab63c01a7d7427eadc821e3bc48c34dc9ba29c501164b52" +dependencies = [ + "byteorder", + "crunchy", + "hex", + "static_assertions", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "uuid" +version = "1.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cefc03fd367c0c6d4305de1b312cf00248c4114f4a0418ce6a6af769e3b0bd9" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "visibility" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d674d135b4a8c1d7e813e2f8d1c9a58308aee4a680323066025e53132218bd91" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "which" +version = "8.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f3ef584124b911bcc3875c2f1472e80f24361ceb789bd1c62b3e9a3df9ff43c" +dependencies = [ + "libc", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "zcash_address" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a854b28c07dba372f4410ea8ad62b4bf7d5c2bf8be32fc4b31bc0db6521a975" +dependencies = [ + "bech32", + "bs58", + "corez", + "f4jumble", + "zcash_encoding", + "zcash_protocol", +] + +[[package]] +name = "zcash_client_backend" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07ad58d8ca5daacbc089bf82ec09e45cf2a8be40adeb40b9399b16545c81a528" +dependencies = [ + "async-trait", + "base64", + "bech32", + "bip32", + "bls12_381", + "bs58", + "byteorder", + "document-features", + "flume", + "futures-util", + "getset", + "group", + "hex", + "hyper-util", + "incrementalmerkletree", + "memuse", + "nonempty", + "orchard", + "pasta_curves", + "pczt", + "percent-encoding", + "postcard", + "prost", + "rand_core", + "rayon", + "sapling-crypto", + "secp256k1", + "secrecy", + "serde", + "shardtree", + "subtle", + "time", + "tonic", + "tonic-prost", + "tonic-prost-build", + "tracing", + "which", + "zcash_address", + "zcash_encoding", + "zcash_keys", + "zcash_note_encryption", + "zcash_primitives", + "zcash_protocol", + "zcash_script", + "zcash_transparent", + "zip32", + "zip321", +] + +[[package]] +name = "zcash_client_sqlite" +version = "0.22.0" +dependencies = [ + "bip32", + "bitflags 2.13.1", + "bs58", + "byteorder", + "document-features", + "group", + "hex", + "incrementalmerkletree", + "jubjub", + "maybe-rayon", + "nonempty", + "orchard", + "pczt", + "prost", + "rand", + "rand_core", + "rand_distr", + "regex", + "rusqlite", + "sapling-crypto", + "schemerz", + "schemerz-rusqlite", + "secp256k1", + "secrecy", + "serde", + "shardtree", + "static_assertions", + "subtle", + "time", + "tracing", + "uuid", + "zcash_address", + "zcash_client_backend", + "zcash_encoding", + "zcash_keys", + "zcash_pool_migration", + "zcash_primitives", + "zcash_protocol", + "zcash_script", + "zcash_transparent", + "zip32", +] + +[[package]] +name = "zcash_encoding" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1440921903cdb86133fb9e2fe800be488015db2939a30bedb413078a1acb0306" +dependencies = [ + "corez", + "hex", + "nonempty", +] + +[[package]] +name = "zcash_keys" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "def800f128e459eedebc900f36f408eaf0687634128dcf64ecfeaeebc3e16c14" +dependencies = [ + "bech32", + "bip32", + "blake2b_simd", + "bls12_381", + "bs58", + "corez", + "document-features", + "group", + "memuse", + "nonempty", + "orchard", + "rand_core", + "sapling-crypto", + "secrecy", + "subtle", + "tracing", + "zcash_address", + "zcash_encoding", + "zcash_protocol", + "zcash_transparent", + "zip32", +] + +[[package]] +name = "zcash_note_encryption" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cb1b9170c94370e3d66c5cc0877661db743337588b64de7711239eed462198" +dependencies = [ + "chacha20", + "chacha20poly1305", + "cipher", + "rand_core", + "subtle", +] + +[[package]] +name = "zcash_pool_migration" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6188c544911aad647bdb0730d18a0309991da1ccbbdab0415d4ef3113ecadcb3" +dependencies = [ + "blake2b_simd", + "corez", + "getset", + "incrementalmerkletree", + "libm", + "orchard", + "pczt", + "rand_core", + "shardtree", + "zcash_client_backend", + "zcash_keys", + "zcash_primitives", + "zcash_protocol", + "zip32", +] + +[[package]] +name = "zcash_primitives" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "403d5be1e96339534be098e3377fb8a78d68ca7585b1780133d884b810277418" +dependencies = [ + "blake2b_simd", + "block-buffer 0.11.0-rc.3", + "corez", + "crypto-common 0.2.0-rc.1", + "document-features", + "equihash", + "ff", + "hex", + "incrementalmerkletree", + "jubjub", + "memuse", + "nonempty", + "orchard", + "rand_core", + "redjubjub", + "sapling-crypto", + "secp256k1", + "sha2 0.10.9", + "zcash_encoding", + "zcash_note_encryption", + "zcash_protocol", + "zcash_script", + "zcash_transparent", +] + +[[package]] +name = "zcash_protocol" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "314329b91ec4bbb517441840e47d0b2029bf0b946f086980c96c889c2d92dc5d" +dependencies = [ + "corez", + "document-features", + "hex", + "memuse", + "zcash_encoding", +] + +[[package]] +name = "zcash_script" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f872800287d118be71bdf6fe8c869c6a6ff6fb0a5762f68fb2af54c97edf0f2" +dependencies = [ + "bip32", + "bitflags 2.13.1", + "bounded-vec", + "hex", + "ripemd 0.1.3", + "secp256k1", + "sha1", + "sha2 0.10.9", + "thiserror 2.0.20", +] + +[[package]] +name = "zcash_spec" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ded3f58b93486aa79b85acba1001f5298f27a46489859934954d262533ee2915" +dependencies = [ + "blake2b_simd", +] + +[[package]] +name = "zcash_transparent" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "547c012778bae17f58007731af074d638aa146ab0ecfc120adebf23d049aff6c" +dependencies = [ + "bip32", + "bs58", + "corez", + "document-features", + "getset", + "hex", + "nonempty", + "ripemd 0.1.3", + "secp256k1", + "sha2 0.10.9", + "subtle", + "zcash_address", + "zcash_encoding", + "zcash_protocol", + "zcash_script", + "zcash_spec", + "zip32", +] + +[[package]] +name = "zerocopy" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zip32" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b64bf5186a8916f7a48f2a98ef599bf9c099e2458b36b819e393db1c0e768c4b" +dependencies = [ + "bech32", + "blake2b_simd", + "memuse", + "subtle", + "zcash_spec", +] + +[[package]] +name = "zip321" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0180028b8807c60498f01eb805a125eed095ab4c4a1737635c80e6ef7cb0a9c" +dependencies = [ + "base64", + "nom", + "percent-encoding", + "zcash_address", + "zcash_protocol", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml new file mode 100644 index 000000000..9a7af306c --- /dev/null +++ b/chain-runtimes/zcash/Cargo.toml @@ -0,0 +1,93 @@ +[workspace] +resolver = "2" +members = [ + "crates/zcash-runtime", + "crates/zcash-keys-runtime", + "crates/zcash-storage-benchmark", +] +exclude = ["vendor/sqlite-wasm-vfs-0.2.0"] + +[workspace.package] +edition = "2021" +license = "Apache-2.0" +rust-version = "1.85" + +# ── Zcash 依赖:官方稳定发布线 ─────────────────────────────────────────── +# +# 硬约束:存储层必须来自 crates.io 上未修改的官方发布版。 +# 我们不 vendor、不 fork 任何 zcash 存储实现。 +# +# Zcash 存储层仅有 zcash_client_sqlite 的一处 Cargo.toml 改动(见 +# scripts/vendor-deps.sh 与 patches/),它取消 rusqlite 的 "bundled" feature — +# 那个 feature 会在构建期编译 SQLite 的 C 源码,而 wasm32 没有 libc sysroot。 +# Zcash Rust 源码零改动。VFS 的持久化补丁另见 patches/manifest.json。 +[workspace.dependencies] +zcash_client_backend = { version = "0.24.0", default-features = false, features = ["orchard", "transparent-inputs", "lightwalletd-tonic", "sync", "pczt"] } +# serde: create_pczt_from_proposal 要求 AccountId: Serialize +zcash_client_sqlite = { version = "0.22.0", default-features = false, features = ["orchard", "transparent-inputs", "serde"] } +zcash_keys = { version = "0.16.1", features = ["orchard", "sapling", "transparent-inputs"] } +zcash_protocol = "0.10" +# default-features = false 关键:默认带 multicore,而 wasm32 无 atomics 时 +# halo2_proofs 会直接 compile_error。 +zcash_primitives = { version = "0.30", default-features = false } +transparent = { package = "zcash_transparent", version = "0.10" } +zcash_address = "0.13" +zip321 = "0.9.0" +# 与 zcash_client_backend 完全一致的配置:默认 feature 全关。 +# 开着默认 feature 会拉到已 yank 的 core2 0.3。 +pczt = { version = "0.9.3", default-features = false } +orchard = { version = "0.15", default-features = false } + +rusqlite = { version = "0.37", default-features = false } +sqlite-wasm-rs = "0.5" +sqlite-wasm-vfs = { version = "0.2", path = "vendor/sqlite-wasm-vfs-0.2.0" } + +wasm-bindgen = "0.2" +wasm-bindgen-futures = "0.4" +js-sys = "0.3" +gloo-timers = { version = "0.3", features = ["futures"] } +tracing = "0.1" +tracing-wasm = "0.2" +tracing-subscriber = { version = "0.3", default-features = false, features = ["registry", "std"] } + +# 必须与 zcash_client_sqlite 的 rand_core 保持同一大版本(0.6 线), +# 否则 RngCore trait 对不上,init_wallet_db 的泛型约束不满足。 +rand = "0.8" +rand_chacha = "0.3" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +uuid = { version = "1", features = ["js"] } +getrandom = "0.4" +thiserror = "2" +schemerz = "0.2" +schemerz-rusqlite = "0.370" +async-trait = "0.1" +futures-util = { version = "0.3", default-features = false } +sapling = { package = "sapling-crypto", version = "0.7", default-features = false } + +# lightwalletd 走 gRPC-web:浏览器里跑不了原生 gRPC。 +# tonic-web-wasm-client 必须 >= 0.9.1 —— 0.8.0 会丢 gRPC trailer(上游已修)。 +hex = "0.4" +prost = "0.14" +tonic = { version = "0.14", default-features = false, features = ["codegen"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] } +tonic-web-wasm-client = "0.9.1" + +# zcash_client_sqlite 的官方发布版 + 单行 no-bundled patch。 +# 先跑 `bash scripts/vendor-deps.sh` 生成 vendor/ 目录。 +[patch.crates-io] +zcash_client_sqlite = { path = "vendor/zcash_client_sqlite-0.22.0" } + +[profile.release] +# "s" 是量过的选择,不是省事的默认:opt-level = 3 在主网扫描上快不出 +# 噪声(msScan 7350-8805 vs 8064-8218 / 1000 块),wasm 却大 31%(6.8→8.9MB)。 +opt-level = "s" +lto = true +codegen-units = 1 +# 不要用 panic = "abort"。 +# +# 在 wasm 上 abort 会直接杀死实例:没有 JS 异常、没有 Promise reject、 +# 没有任何日志 —— 调用方看到的是一个永远不 settle 的 Promise, +# 表现和「卡死」完全一样,无法区分也无法排查。 +# unwind 则会变成一条带 message 的 JS 异常,宿主能 catch、能上报。 +panic = "unwind" diff --git a/chain-runtimes/zcash/IMPORT.md b/chain-runtimes/zcash/IMPORT.md new file mode 100644 index 000000000..351518b2f --- /dev/null +++ b/chain-runtimes/zcash/IMPORT.md @@ -0,0 +1,59 @@ +# Zcash source import + +- Source: the local `onekey-zcash-runtime` repository. +- Source revision: `c11be01b2f395b0c64321df2e2cab026008da6b5` (`feat: add zcash wallet and keys wasm runtime`). +- Destination: `OneKeyHQ/app-modules`, `chain-runtimes/zcash`. +- Imported files: the source repository's tracked Cargo workspace, Rust source, + tests, documentation, patches, and build scripts. + +The runtime is OneKey's adapter over the versions of librustzcash pinned in +`Cargo.lock`, rather than a fork of the entire librustzcash repository. The +original local repository is retained. Generated packages, Cargo build caches, +browser experiments, logs, and local wallet data are not imported. + +## Existing vendor changes preserved by this import + +The source checkout depended on two local vendor trees. Only one of their +patches was originally tracked. Both are now reconstructible from the upstream +crate archive checksums in `patches/manifest.json`: + +1. `zcash_client_sqlite 0.22.0`: disable rusqlite's `bundled` feature for WASM. + Its Rust source is unchanged. +2. `sqlite-wasm-vfs 0.2.0`: preserve the existing durability barrier and sticky + sync-error handling in `src/relaxed_idb.rs`. This patch was recovered by + comparing the old checkout against the published crate source. It is not a + new storage behavior introduced by the migration. + +`scripts/vendor-deps.sh` verifies the archives, applies the exact patches, and +rejects an existing vendor tree whose contents differ. No vendor source or +prebuilt WASM is committed. + +## Application handoff + +During local development, `app-monorepo/packages/core/package.json` points its +two existing portal dependencies to this directory's `pkg` and `pkg-keys`. +Build both outputs before installing the app dependencies. Package names and +runtime interfaces are unchanged by this import. Registry publishing and a +versioned app dependency are a separate release step. + +## Local validation (2026-09-08) + +- All first-party Rust source and `Cargo.lock` match the source checkout byte + for byte. Both reconstructed vendor trees match the source checkout's Rust + source and Cargo manifests, including its previously untracked VFS patch. +- Rust workspace: 52 tests passed; 9 opt-in network tests remained ignored. +- Vendor reconstruction guards: 6 tests passed (including checksum, drift, + offline, archive traversal, and archive link rejection). +- Release builds succeeded for runtime, keys, and storage benchmark. +- The app's installed runtime resolves to this directory and loads in Node; + its capability and dependency-version probes succeeded. +- The app's installed keys package passed address scheme v3 goldens and all + 5 synthetic-seed cleanup checks against the actual WASM. +- `app-monorepo` passed `yarn agent:check --profile commit`, including TypeScript + and the background API contract checks. + +The immutable app installation changed only the two portal locations. Its +repository-specific `afterInstall` hook still ran despite disabled package build +scripts and reported a `react-native-collapsible-tab-view` patch failure. That +package and patch are unchanged by this migration; the issue is not a Zcash +build failure. The GitHub workflow has been added but has not been run remotely. diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md new file mode 100644 index 000000000..3699dfb37 --- /dev/null +++ b/chain-runtimes/zcash/README.md @@ -0,0 +1,319 @@ +> This project now lives in `app-modules/chain-runtimes/zcash`. See +> [IMPORT.md](./IMPORT.md) for the source revision and preserved vendor patches. +> Build commands below run from this directory. Use Rust 1.93.0 (pinned in +> `rust-toolchain.toml`), Python 3.9+, LLVM/Clang, and wasm-pack 0.15.0. +> Install `wasm-bindgen-cli` at the `wasm-bindgen` version in `Cargo.lock` +> and provide `wasm-opt` (Binaryen), or reuse the matching wasm-pack tool cache. +> Builds use `--mode no-install` and never update `Cargo.lock`. +> The original standalone browser experiments were not imported; app integration +> checks remain in app-monorepo. + +# OneKey Zcash Runtime + +官方 `librustzcash` 之上的最薄 wasm 绑定层。**不依赖 WebZjs**。 + + +--- + +## 这个项目为什么存在 + +现有实现建在 `ChainSafe/WebZjs` 的 fork 上,而那个仓库自 2026-04-16 起没有任何分支收到过推送。 +更要紧的是它使用 `zcash_client_memory` 作为存储后端 —— 那个 crate 从未发布到 crates.io, +2026-06-20 被从 librustzcash 切成独立仓库后只有 dependabot 在动。我们为它 vendor 了 +11,122 行代码并改动了 27 个源文件中的 22 个,且每次 `zcash_client_backend` 升版都要自己重迁一遍。 + +本项目改用 `zcash_client_sqlite`:它就在 librustzcash 仓库里,与 `zcash_client_backend` +**同日发版**,是官方 Android / iOS SDK 与 ECC 自家钱包 `zallet` 的存储层 +(GitHub 上有 135 个 Cargo.toml 依赖它)。 + +换句话说:**大脑一直用的是官方的,只是存储层配了个孤儿。这个项目把它换回原厂件。** + +--- + +## 拆成两个包:移动端不该为了派生地址而吃下整个扫链引擎 + +| crate | 产物 | 内容 | 谁需要 | +|---|---|---|---| +| `onekey-zcash-keys` | **1.74 MB** | 派生 UFVK、地址;无存储、无网络、无 SQLite | **iOS / Android**,以及任何只需看账材料的场合 | +| `onekey-zcash-runtime` | **4.67 MB** | 扫链、SQLite 存储、lightwalletd 网络 | Desktop / Web /(将来)插件 | + +依赖面完全隔开 —— keys crate 明确不依赖 `zcash_client_backend`、`zcash_client_sqlite`、 +`rusqlite`、`sqlite-wasm-rs`、`tonic`。移动端想误引扫链代码,**编译期就过不去**, +不用靠人记着。 + +### 但「拆开」不等于「移动端只能用 keys」 + +`onekey-zcash-runtime` 的钱包核心(`wallet` / `account` / `storage` / `blockcache` / +`clock` / `error`)是**全平台**的。实测三个 target 都编译通过: + +| target | 状态 | +|---|---| +| `wasm32-unknown-unknown` | ✅ | +| `aarch64-apple-ios` | ✅ | +| 本机原生(macOS) | ✅ | + +也就是说移动端有两条路,选哪条是产品决策而非技术限制: + +- **keys-only(1.74 MB)** —— 能收款、能显示地址,**看不到余额、没有历史、不能发送**, + 因为那些都要扫链结果。适合「移动端暂不支持 Zcash 私密余额」这个明确的产品选择。 +- **原生完整 runtime** —— 把这个 crate 编成 `.a` / `.so` 走 RN 原生模块。 + 这正是官方 `zcash-android-wallet-sdk/backend-lib` 的做法。**绕开 WebView、绕开 + `crossOriginIsolated`、性能最好**。缺的只有一个原生 transport(见下)。 + +只有 `network` / `sync` / `runtime` / `bindgen` 四个模块是 wasm 专属, +因为网络层目前只实现了浏览器的 gRPC-web 传输。移动端原生要接 tonic 的原生 transport, +那是一个独立的 cfg 分支,`LightClient` 的签名不用变。 + +参考:Ledger Live 在这件事上的答案是**不做** —— `ledger-live-mobile` 里 zcash/shielded +相关文件 0 个,RN stub 直接抛 `"ZCash is not supported on React Native"`。 +他们的引擎只有 Node napi 产物,连 wasm 都没有,所以移动端没有选择。我们有。 + +## 硬约束 + +1. **不 vendor、不 fork 任何 Zcash 存储实现。** 存储层必须来自 crates.io 上未修改的 + `zcash_client_sqlite`。唯一例外是一处 Cargo.toml 改动(下节),Rust 源码零改动。 +2. **密钥材料不出 wasm。** 种子、USK、签名留在 Rust 侧(可 zeroize),不跨边界。 +3. **接口动词少、数据简单。** 只传 string / number / boolean / JSON 字符串,不把 Rust + 对象句柄交给 JS 管生命周期。每次调用是一次完整往返。 + +## 边界:什么在 Rust,什么在 TS + +| 留在 Rust(wasm) | 放在宿主 TS | +|---|---| +| 扫链的 trial decryption | 何时扫、扫哪段、扫多少(调度) | +| witness / 承诺树维护 | 账户与 birthday 管理 | +| 交易构造与选币(共识正确性) | 缓存与持久化策略 | +| 密钥派生与签名 | 进度展示、错误处理、重试 | +| 平台胶水(时钟、随机数、VFS) | 历史记录的展示模型 | + +判据是三条:**密钥安全、跨边界数据量、共识正确性**。三条都不沾的,就该在 TS —— 那边改起来快、看得见、能打断点。 + +--- + +## 那一处 Cargo.toml 改动 + +`zcash_client_sqlite` 给 `rusqlite` 开了 `bundled` feature,它会在构建期用 cc 编译 SQLite +的 C 源码。`wasm32-unknown-unknown` 没有 libc sysroot,会停在 +`fatal error: 'stdio.h' file not found`。Cargo 的 feature 是并集语义,下游无法取消上游 +已启用的 feature,只能改它的 Cargo.toml。 + +处理方式是可审计的:`scripts/vendor-deps.sh` 下载官方发布版并施加 +`patches/zcash_client_sqlite-0.22.0-no-bundled.patch`(**1 行**)。另外,VFS 的既有持久化 barrier 补丁记录在 `patches/manifest.json`。升级版本时更新 manifest 里的 +`VERSION` 重跑即可。脚本末尾会校验没有任何 `.rs` 被改动。 + +wasm 侧的 SQLite 由 `sqlite-wasm-rs` 提供(预编译,不在构建期编 C)。 +`crates/zcash-runtime/build.rs` 自动把它的 `libwsqlite3.a` 按链接器要的名字接上, +**调用方不需要任何手工 RUSTFLAGS**。 + +--- + +## 存储:数据存在哪 + +SQLite 从不直接碰文件,它通过 VFS 接口读写字节,而那个接口只有五个动作: +`read` / `write` / `truncate` / `flush` / `size`。接到哪,数据就在哪。 + +浏览器侧接到 **IndexedDB**(`sqlite-wasm-vfs` 的 `relaxed_idb`)。选它而不是 OPFS 的 +`sahpool`,因为后者的同步访问句柄只在 Worker 里可用,而 relaxed-idb 在所有上下文都能跑 —— +这对要覆盖的载体(桌面 renderer、浏览器页面、插件 offscreen、移动 WebView)是必要条件。 + +代价是它不是「完全持久」:读写在内存里同步服务,异步批量刷进 IndexedDB,崩溃可能丢掉最近一批。 +对扫链缓存可接受 —— 数据本来就能从链上重建。 + +> 这个约束是**物理性**的:SQLite 的 VFS 接口是同步的(`read` 必须立刻返回), +> 而浏览器存储是异步的。不要求 COI 的前提下,可行形态只有「内存同步服务 + 异步刷盘」。 + +--- + +## 当前进度 + +> 状态:**runtime 的看账与发送链路已在 testnet 上真实上链验证,App 适配层已接入并通过 +> 类型、单元与浏览器 runtime 检查。** App 内的有资金发送闭环与主网真实交易仍需人工验收。 + +**已验证** + +- [x] `zcash_client_sqlite` 0.22.0 编进 wasm32 并链接(唯一改动是 1 行 Cargo.toml) +- [x] IndexedDB VFS,**完整 schema 迁移:44 表 / 17 视图 / 84 索引**,重载后仍在 +- [x] 三个 target 编译通过:`wasm32-unknown-unknown` / `aarch64-apple-ios` / macOS 原生 +- [x] 单测 27 个全过(另有 9 个联网用例,默认 ignore) +- [x] 浏览器错误契约 10 项断言:每个错误都带 `code` + `params` 对象 +- [x] 真实 testnet 端到端:`chainTip` → 4291075、`importAccountUfvk` +- [x] `syncStep` 有界返回(原 `syncAdvance` 会跑到同步完成才返回,已修,见 docs/D5) +- [x] 浏览器实测批量 10 / 25 / 60 / 100 / 200 / 500 全部正常(持久化 IndexedDB VFS): + 扫描阶段 12–70ms,总耗时由两次网络往返主导;batch 500 一次追平 203 块 +- [x] 清缓存→重建闭环(`examples/web/purge-rebuild.html`):擦后是全新库(账户为空、 + uuid 变化),用 ufvk+birthday 能完整重建。这条是「出问题能救回来」的保障 +- [x] 发送路径的**错误契约** 9 项(不需要资金即可跑,`examples/web/send-errors.html`): + txid 非法/不存在、找零池参数错、PCZT 垃圾字节、电路版本错、 + reservation 非法/不存在各有可判定错误码 +- [x] **不设限制,改为提前告知**(`examples/web/insufficient-errors.html`,四情形实测): + 转账会花透明 UTXO —— 钱是用户的,链上也接受,运行时不替他拒绝。 + `pcztQuote` 走的是与 `pcztCreate` 完全相同的提案路径,因此除手续费外 + 还报出**这笔实际会从哪些池取钱**: + `{sourceTransparentZat, sourceShieldedZat, linksTransparentToShielded}`。 + `linksTransparentToShielded` 只在同一笔里既花透明又花屏蔽时为真 —— + 那是花透明**唯一新增**的暴露(只花透明的话,对外与一笔屏蔽交易无异), + 也就是唯一值得弹提醒的情形 +- [x] **真发不出去时错误说得清**:`INSUFFICIENT_FUNDS`(都不够)/ + `FUNDS_NEED_SHIELDING`(宿主关掉了透明花费,钱在透明池里)/ + `COINBASE_FUNDS_UNSPENDABLE`(差额只有 coinbase 能补,而本钱包 + 转账走 NonCoinbase、屏蔽走 NonCoinbaseOnly,两条路都碰不到它)。 + 三者都带 `{requiredZat, shieldedAvailableZat, shortfallZat, + transparentZat, transparentCoinbaseZat}`。 + 原来只有一个 `INSUFFICIENT_FUNDS { availableZat: 0 }` —— + 而用户正看着账上有钱,那个 `availableZat` 说的是屏蔽池,名字里却没有 + 「屏蔽」二字,除了猜没有别的办法 +- [x] **端到端发送并广播上链**(testnet):水龙头 0.1 TAZ 落 Ironwood 池 → + `pcztCreate` → `pcztProve`(Halo2 约 19s)→ `pcztSign` → `pcztSend` → + `broadcastTransaction`,链上确认。逐笔手续费对账到 zatoshi +- [x] **透明 ↔ 屏蔽双向**:隐私→透明地址、透明→隐私(`pcztShield`,含**透明输入签名**)、 + 透明→透明(需 `spendTransparent`),全部链上确认 +- [x] **多账户共库**:acct0/1/2 同一个库,扫一遍服务全部账户 + +**未验证 —— 别把这些当成能用** + +- [ ] **App UI 内的有资金闭环尚未执行。** runtime + `examples/web` 已真实跑过 testnet + 双向发送;App 适配层已通过类型检查及 Token/History/发送状态相关单测,但这不能替代 + Desktop、Extension MV3、iOS、Android 四端的 UI 验收 +- [ ] **交易记录里的 `feeZat` 重扫后为 null。** 它来自 `transactions.fee`, + 只有钱包自己构造那笔时写入,或跑 transaction enhancement 时补上 —— + 运行时没有 enhancement。用户清一次缓存重扫,历史里的手续费会全部消失 +- [ ] 主网从未测过,全部实测都在 testnet +- [ ] 失去批量试解密的代价只在很空的 testnet 区块上量过(1.4–2 倍)。 + 主网稠密区块上差距可能大得多,未测。 +- [x] 以 Yarn portal 包接入 monorepo;正式发布仍需固定可追溯的 runtime 版本 +- [ ] 从现有 wasm blob 迁移存量用户数据 +- [ ] 原生目标的 lightwalletd transport(网络层目前只有浏览器 gRPC-web) + +**已知约束** + +- lightwalletd 端点**必须支持 gRPC-web + CORS**。实测 + `zcash-{mainnet,testnet}.chainsafe.dev` 可用;`zec.rocks` 只开原生 gRPC, + 浏览器里挂死在第一次请求上(`grpcurl` 反而通 —— 两者说的不是同一个协议, + 用命令行探活会得出相反的结论)。 +- **扫描不走上游的 `scan_cached_blocks`**,改用自己的 `scan_blocks_inline`。 + 上游把试解密交给 `rayon::spawn_fifo`,而 wasm32 单线程环境下 rayon 没有工作线程, + 任务永远不会执行,随后取结果时**永久堵死主线程**。根因与取证过程见 + `docs/decisions.md` D8。代价是失去批量试解密的摊销优化(原生实测扫描阶段慢 1.4–2 倍)。 + `batchSize` 没有上限约束;用 `syncPeek()` 的 `remainingBlocks` 画进度条。 +- `syncPrepare()` 要下载三个池的全部子树根 —— 实测 testnet 约 1.4 秒 + (6 sapling / 3 orchard / 0 ironwood 子树),并不慢。宿主仍应给它独立的 + 「准备中」状态,因为主网子树数量会大得多。 +- `relaxed-idb` 在插件 offscreen 与移动 WebView 里的表现尚未实测(浏览器页面已证)。 +- 产物:runtime 6.53 MB / keys 1.99 MB(均已过 `wasm-opt -Oz`)。PCZT 证明电路约占 1.6–2.0 MB。 + +## API + +全部通过 JSON 字符串交互。失败抛 `Error`,其上挂 **`code`(稳定错误码)+ `params` +(结构化参数)+ `detail`(仅日志)**。Rust 侧不产出任何面向用户的文案 —— +文案与 i18n 归宿主。 + +### `onekey-zcash-runtime`(Desktop / Web / 插件) + +``` +init() 安装存储层,幂等,必须先调 +openWallet(network, dbName) 开库 + schema 迁移 +closeWallet() +setLightwalletdUrl(baseUrl) 端点由宿主注入,不硬编码 + +chainTip() 当前链尖高度 +importAccountUfvk(name, ufvk, birthday) 导入只读账户 → UUID +listAccounts() +accountBalance(uuid, trusted, untrusted, allowZeroConfShielding) + +syncPrepare() 一次性准备(子树根+链尖),慢,单独计时 +syncStep(batchSize, maxBatches, priority, activeUfvksJson) + 仅为宿主显式启用的 UFVK 有界推进 +queueRescanFrom(fromHeight) 非破坏性重排 [fromHeight, chainTip] +rewindTo(height) 回退重扫(破坏性) + +transactionHistory(uuid, limit, offset) 分页历史,limit 上限 500 +transactionDetails(uuid, txid) 单笔详情,查不到返回 "null" +deleteWallet(dbName) 擦掉本地缓存库(可重建),删账户/故障重置用 + +pcztQuote(...) 只报价,不建交易、不锁 note +pcztCreate(...) → { pcztHex, reservationId } 构造并锁住选中的 note +pcztShield(...) → { pcztHex, reservationId } 屏蔽全部透明余额(无收款方、无金额) +releaseReservation(id) 用户取消时放开锁,幂等 +pcztProve(pczt, circuitVersion) → keys.pcztSign → pcztSend(pczt, reservationId) → txid +broadcastTransaction(txid) 真正发出去(pcztSend 只落库,不发网络) +selfCheck(network, dbName) / dependencyVersions() +``` + +### `onekey-zcash-keys`(iOS / Android,也可与上面同用) + +``` +ufvkFromSeed(network, seedBytes, accountIndex) ← 接进 app 的实际入口 +ufvkFromMnemonic(network, mnemonic, accountIndex) 测试/独立验证用 +unifiedAddress(network, ufvk) +pcztSignWithSeed(network, seedBytes, accountIndex, pcztBytes) ← 唯一接触花费密钥处 +pcztSign(network, mnemonic, accountIndex, pcztBytes) +keysDependencyVersions() +``` + +### 发送的完整流程 + +``` +runtime.pcztCreate() 构造(要钱包 DB:选币、witness、anchor) +runtime.pcztProve() 零知识证明(慢,要建 halo2 电路) +keys.pcztSign() 签名(要种子;在另一个包里) +runtime.pcztSend() 终结 + 写回本地钱包,返回 txid(**不发网络**) +runtime.broadcastTransaction(txid) 真正广播(不可逆) +``` + +**顺序不能换**:证明必须在签名之前 —— 上游 Signer 需要能验证证明覆盖的是正确数据。 +广播是独立的一步,这样宿主能在落库之后、发出去之前插入确认环节, +也能在广播失败时原样重试而不用重建交易。 +节点拒绝抛 `BROADCAST_REJECTED`(别重试,先查原因),网络故障抛 `NETWORK_ERROR`(可重试)。 +`already known` / `already in mempool` / `already in blockchain` 视为幂等成功;所有触网调用 +都有 30 秒上限,避免 gRPC-web 静默挂起。 + +--- + +## 用法 + +```bash +# 一次性:装 wasm target 和能编 wasm 的 clang +rustup target add wasm32-unknown-unknown +brew install llvm # macOS 自带的 Apple clang 不支持 wasm32 +cargo install wasm-pack + +# 构建(自动跑 vendor-deps.sh) +bash scripts/build-wasm.sh + +# 原生单测(首次运行前先准备 vendor) +bash scripts/vendor-deps.sh +cargo test --workspace --locked + +# 校验缓存中的 vendor 与记录的上游/补丁完全一致 +bash scripts/vendor-deps.sh --offline +``` + +产物 `pkg/`、`pkg-keys/` 不入库。两者一起构建,供 app-monorepo 的本地 +portal 依赖或 CI artifact 使用。本次迁移不发布 npm 包。 + +--- + +## 目录 + +``` +crates/zcash-runtime/ 绑定层本体 + src/clock.rs 宿主时钟(std 在 wasm32 上没有时间源) + src/error.rs 稳定错误码 + JS Error 映射 + src/storage.rs VFS 安装与连接打开 + src/wallet.rs WalletDb 组装与 schema 迁移 + src/bindgen.rs 面向 JS 的接口 + build.rs 自动接上 wasm 版 SQLite 静态库 +patches/ 固定上游校验值、Cargo feature 与 VFS 持久化补丁 +scripts/vendor-deps.sh 校验官方发布版并施加已记录的 patch +scripts/build-wasm.sh 构建 +``` + +--- + +## 参考实现(读,不依赖) + +- `ChainSafe/WebZjs` —— grpc-web 接线、wasm 线程池初始化的踩坑经验。 + 注意它的 `tonic-web-wasm-client` 必须 ≥ 0.9.1(0.8.0 会丢 gRPC trailer)。 +- `zcash/zcash-android-wallet-sdk` 的 `backend-lib/` —— ECC 自己写的 Rust FFI 层, + 生产在跑。核心 `lib.rs` 4,076 行是「该暴露什么、按什么粒度」的权威参照 + (其余约 18,000 行是该 SDK 自己的历史 migration、投票、slipstream,我们不需要)。 diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml new file mode 100644 index 000000000..fc4d692b0 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml @@ -0,0 +1,52 @@ +[package] +name = "onekey-zcash-keys" +version = "0.0.1" +edition.workspace = true +license.workspace = true +rust-version.workspace = true +description = "OneKey Zcash — 仅密钥派生与签名。不含存储、扫链与网络。" + +[lib] +crate-type = ["cdylib", "rlib"] + +# 刻意保持极小的依赖面:这个 crate 会被移动端打包, +# 每多一个依赖都是 iOS/Android 包体的直接成本。 +# +# 明确**不**依赖:zcash_client_backend、zcash_client_sqlite、rusqlite、 +# sqlite-wasm-rs、tonic —— 那些属于 onekey-zcash-runtime。 +[dependencies] +zcash_keys.workspace = true +zcash_protocol.workspace = true +zcash_address.workspace = true +zcash_primitives = { workspace = true, features = ["transparent-inputs"] } +zip32 = "0.2" +bip0039 = { version = "0.12", features = ["all-languages"] } +bs58 = { version = "0.5", features = ["check"] } +zeroize = { version = "1", features = ["zeroize_derive"] } +serde.workspace = true +serde_json.workspace = true +hex.workspace = true +secp256k1 = { version = "0.29", features = ["alloc"], default-features = false } +zcash_script = { version = "0.4.3", default-features = false } +# signer + orchard:本包唯一的职责就是给 PCZT 的 Orchard 花费签名。 +# 不开 prover/tx-extractor —— 那些属于 runtime 包。 +# transparent:屏蔽(transparent → shielded)必须签透明输入,否则打进 t 地址的钱 +# 出不来。它会连带拉入 zcash_script(0.4 起是纯 Rust,能上 wasm32)。 +pczt = { workspace = true, features = ["signer", "orchard", "transparent"] } +transparent = { workspace = true, features = ["transparent-inputs"] } +orchard = { version = "0.15", default-features = false } +sapling.workspace = true +thiserror.workspace = true + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wasm-bindgen.workspace = true +js-sys.workspace = true +getrandom = { workspace = true, features = ["wasm_js"] } +# 依赖树里同时存在 getrandom 0.2(被老一些的 crate 拉入),它需要旧式的 "js" +# feature 才能在 wasm32-unknown-unknown 上编译。两个都要显式打开。 +getrandom_02 = { package = "getrandom", version = "0.2", features = ["js"] } + +# wasm-pack 默认跑 `wasm-opt -O`;-Oz 更激进地压体积。 +# 代价是构建慢一些,运行时性能差异对我们这类 IO 密集的负载可忽略。 +[package.metadata.wasm-pack.profile.release] +wasm-opt = ["-Oz", "--enable-bulk-memory", "--enable-nontrapping-float-to-int"] diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md new file mode 100644 index 000000000..e9da957e2 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md @@ -0,0 +1,96 @@ +# Stateless transparent transaction API + +This crate can quote and sign a mainnet transparent-to-transparent transaction without a +`WalletDb`, scanner, or network client. The host owns UTXO discovery, reservation, broadcast, and +status reconciliation. + +## Exports + +- `transparentTxQuote(requestJson)` +- `transparentTxBuildWithSeed(requestJson, seed)` +- `transparentTxBuildWithAccountXprv(requestJson, accountXprv)` + +The xprv entry point accepts an account-level BIP-44 xprv. Its required derivation path is +`m/44'/133'/account'`. An account xprv cannot attest its ancestors, so the crate verifies its depth +and hardened account child metadata while the host remains responsible for deriving the account +xprv from the exact purpose and coin-type path. + +## Request + +Amounts are decimal strings because JavaScript numbers cannot represent every valid zatoshi value. + +```json +{ + "network": "main", + "accountIndex": 0, + "targetHeight": 3500000, + "expiryHeight": 3500020, + "utxos": [ + { + "txid": "0000000000000000000000000000000000000000000000000000000000000001", + "vout": 0, + "valueZat": "100000", + "scriptPubKey": "76a914000000000000000000000000000000000000000088ac", + "isCoinbase": false, + "confirmations": 1, + "derivationPath": "m/44'/133'/0'/0/0" + } + ], + "selectedOutpoints": [ + { + "txid": "0000000000000000000000000000000000000000000000000000000000000001", + "vout": 0 + } + ], + "recipients": [{ "address": "t1...", "amountZat": "50000" }], + "sendMax": false, + "change": { + "address": "t1...", + "derivationPath": "m/44'/133'/0'/1/0" + } +} +``` + +Only selected outpoints are spent. Every selection must resolve to exactly one supplied UTXO. +Inputs must be confirmed, non-coinbase P2PKH coins controlled by their declared external or internal +BIP-44 path. Recipient outputs may be mainnet P2PKH (`t1`) or P2SH (`t3`). Change must be an owned +P2PKH address on internal scope `1`. + +For send-max, supply exactly one recipient and omit `amountZat` and `change`. The recipient receives +the selected input total minus the ZIP-317 fee. For a fixed amount, change below the standard 5,000 +zatoshi marginal fee is rejected instead of silently adding it to the fee. + +The target height must be on the mainnet NU6.3 branch. `expiryHeight` is mandatory and is supplied +by the host's transaction policy. The crate validates that it is after the target height and no more +than 100 blocks later; it does not choose a product expiry policy. The resulting transaction is V6. + +## Results + +Quote result: + +```json +{ + "feeZat": "10000", + "inputTotalZat": "100000", + "sendAmountZat": "50000", + "changeZat": "40000", + "expiryHeight": 3500020, + "spentOutpoints": [{ "txid": "...", "vout": 0 }] +} +``` + +Build result: + +```json +{ + "rawTx": "...", + "txid": "...", + "feeZat": "10000", + "expiryHeight": 3500020, + "spentOutpoints": [{ "txid": "...", "vout": 0 }] +} +``` + +The build entry points recompute the quote and fail closed if any input script or change address does +not match the derived key. The host must reserve every returned outpoint before broadcast and retain +the exact raw transaction for ambiguous broadcast recovery. diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/build.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/build.rs new file mode 100644 index 000000000..c6e569441 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/build.rs @@ -0,0 +1,9 @@ +fn main() { + if std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() == Ok("wasm32") { + // The host wipes inactive stack frames after synchronous key operations. + // Export linker-owned bounds so it never guesses a memory layout or + // overwrites static data and live heap allocations. + println!("cargo:rustc-link-arg=--export=__stack_low"); + println!("cargo:rustc-link-arg=--export=__stack_high"); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs new file mode 100644 index 000000000..fc1d3b2c3 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs @@ -0,0 +1,165 @@ +//! 面向宿主的密钥接口。 +//! +//! 出口只有 UFVK 与地址 —— 种子和花费密钥永远不跨这条边界。 + +use wasm_bindgen::prelude::*; +use zeroize::Zeroizing; + +use crate::{keys, sign, transparent_send}; + +/// 从助记词派生该账户的 UFVK。助记词与种子在 Rust 侧用完即擦。 +#[wasm_bindgen(js_name = ufvkFromMnemonic)] +pub fn ufvk_from_mnemonic( + network: &str, + mnemonic: String, + account_index: u32, +) -> Result { + let mnemonic = Zeroizing::new(mnemonic); + Ok(keys::ufvk_from_mnemonic(network, &mnemonic, account_index)?) +} + +/// 从 UFVK 取统一地址。纯公开材料,不涉及私钥。 +/// +/// `receiverPolicy` 决定 UA 里包含哪些 receiver:`"all"`(默认)/ `"shielded"` / +/// `"orchard"`。**这是隐私策略,由宿主决定** —— 带 transparent receiver 的地址 +/// 别人可以用公开方式付给你,代价是把你的透明与屏蔽活动关联起来。 +#[wasm_bindgen(js_name = unifiedAddress)] +pub fn unified_address( + network: &str, + ufvk: &str, + receiver_policy: Option, +) -> Result { + Ok(keys::unified_address_with( + network, + ufvk, + receiver_policy.as_deref().unwrap_or("all"), + )?) +} + +/// 给 PCZT 签名。 +/// +/// 这是整个方案里唯一接触花费密钥的接口。助记词在 Rust 侧派生、用完即擦, +/// 种子与花费密钥不会跨这条边界返回。 +/// +/// 输入是 `onekey-zcash-runtime` 的 `pcztCreate` 产物, +/// 输出交回它的 `pcztSend` 终结并广播。 +#[wasm_bindgen(js_name = pcztSign)] +pub fn pczt_sign( + network: &str, + mnemonic: String, + account_index: u32, + pczt_bytes: Vec, +) -> Result, JsValue> { + let mnemonic = Zeroizing::new(mnemonic); + Ok(sign::sign_pczt_with_mnemonic( + network, + &mnemonic, + account_index, + &pczt_bytes, + )?) +} + +/// 从**种子字节**派生 UFVK。 +/// +/// OneKey 的架构里,助记词只在解密那一刻出现一次,之后全程传种子。 +/// 所以这才是接进 app 的实际入口;`ufvkFromMnemonic` 主要用于测试与独立验证。 +#[wasm_bindgen(js_name = ufvkFromSeed)] +pub fn ufvk_from_seed(network: &str, seed: Vec, account_index: u32) -> Result { + // Own and wipe the original bindgen allocation, including on validation errors. + // Wiping another copy would leave the JS-to-WASM input in freed linear memory. + let seed = Zeroizing::new(seed); + let params = keys::parse_network(network)?; + Ok(keys::ufvk_from_seed_bytes(params, &seed, account_index)?) +} + +/// 用**种子字节**给 PCZT 签名。整个方案里唯一接触花费密钥的接口之一。 +/// +/// 花费密钥在 Rust 侧从种子现场派生、用完即弃,不跨边界返回。 +/// 调用方负责擦除自己那份种子 —— 这一侧擦不了 JS 堆上的副本。 +#[wasm_bindgen(js_name = pcztSignWithSeed)] +pub fn pczt_sign_with_seed( + network: &str, + seed: Vec, + account_index: u32, + pczt_bytes: Vec, +) -> Result, JsValue> { + let seed = Zeroizing::new(seed); + let params = keys::parse_network(network)?; + Ok(sign::sign_pczt_with_seed( + params, + &seed, + account_index, + &pczt_bytes, + )?) +} + +/// 从 UFVK 取透明收款地址(t 地址)。离线可算,不需要钱包库。 +#[wasm_bindgen(js_name = transparentAddressFromUfvk)] +pub fn transparent_address_from_ufvk(network: &str, ufvk: &str) -> Result { + Ok(keys::transparent_address(network, ufvk)?) +} + +/// 种子指纹(ZIP-32 标准值)。宿主拿它当账户身份持久化, +/// 所以必须与标准一致 —— 不能另发明一套哈希。 +#[wasm_bindgen(js_name = seedFingerprint)] +pub fn seed_fingerprint(seed: Vec) -> Result { + let seed = Zeroizing::new(seed); + Ok(keys::seed_fingerprint(&seed)?) +} + +/// Quotes a mainnet V6 transparent transaction without loading wallet state. +#[wasm_bindgen(js_name = transparentTxQuote)] +pub fn transparent_tx_quote(request_json: &str) -> Result { + Ok(transparent_send::quote_json(request_json)?) +} + +/// Builds and signs a mainnet V6 transparent transaction from a software-wallet seed. +#[wasm_bindgen(js_name = transparentTxBuildWithSeed)] +pub fn transparent_tx_build_with_seed( + request_json: &str, + seed: Vec, +) -> Result { + let seed = Zeroizing::new(seed); + Ok(transparent_send::build_with_seed_json(request_json, &seed)?) +} + +/// Builds and signs using an account xprv at `m/44'/133'/account'`. +#[wasm_bindgen(js_name = transparentTxBuildWithAccountXprv)] +pub fn transparent_tx_build_with_account_xprv( + request_json: &str, + account_xprv: String, +) -> Result { + let account_xprv = Zeroizing::new(account_xprv); + Ok(transparent_send::build_with_account_xprv_json( + request_json, + &account_xprv, + )?) +} + +/// keys 侧**实际**能签什么。与 runtime 的 `capabilities()` 合并后才是完整判断: +/// 一笔交易要能发出去,证明和签名两边都得支持同一种 bundle。 +#[wasm_bindgen(js_name = keysCapabilities)] +pub fn keys_capabilities() -> String { + serde_json::json!({ + "sign": { + "orchard": sign::SIGN_ORCHARD, + "sapling": sign::SIGN_SAPLING, + "transparent": sign::SIGN_TRANSPARENT, + "ironwood": sign::SIGN_IRONWOOD, + }, + "transparentTx": { + "network": "main", + "version": 6, + "quote": true, + "buildWithSeed": true, + "buildWithAccountXprv": true, + }, + }) + .to_string() +} + +/// 本 crate 锁定的官方依赖版本。 +#[wasm_bindgen(js_name = keysDependencyVersions)] +pub fn dependency_versions() -> String { + crate::dependency_versions().to_string() +} diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs new file mode 100644 index 000000000..d602a8a66 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs @@ -0,0 +1,231 @@ +//! 错误契约。与 `onekey-zcash-runtime` 完全同构: +//! **稳定错误码 + 结构化参数,Rust 侧不产出面向用户的文案。** +//! +//! 两个包的错误码取值空间不重叠,宿主可以用同一套 catch 逻辑处理。 + +use serde_json::{json, Map, Value}; +use std::fmt; + +/// 稳定错误码。只允许追加,不允许改动已有取值的含义。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ErrorCode { + /// 网络名不是 "main" / "test"。参数:`{ value }` + InvalidNetwork, + /// 助记词无法解析。 + InvalidMnemonic, + /// 种子过短。参数:`{ byteLen, min }` + InvalidSeed, + /// 账户序号越界。参数:`{ value }` + InvalidAccountIndex, + /// UFVK 无法解析。 + InvalidUfvk, + /// 密钥派生失败。 + DeriveFailed, + /// PCZT 解析失败。 + PcztParseFailed, + /// PCZT 签名失败。参数:`{ orchardActions }`(能取到时) + PcztSignFailed, + /// The stateless transparent transaction request is malformed. + InvalidTransactionRequest, + /// The requested target height is not valid for the supported V6 mainnet branch. + InvalidTargetHeight, + /// A destination or change address is invalid or belongs to another network. + InvalidAddress, + /// An outpoint is malformed or reserved. + InvalidOutpoint, + /// A selected outpoint is not present in the supplied UTXO catalog. + UnknownInput, + /// An outpoint appears more than once. + DuplicateInput, + /// Coinbase inputs are intentionally unsupported by transparent send. + CoinbaseInput, + /// Unconfirmed transparent inputs are intentionally unsupported. + UnconfirmedInput, + /// Only regular P2PKH inputs are supported. + UnsupportedInputScript, + /// The supplied BIP-44 path is outside the exact Zcash account path. + InvalidDerivationPath, + /// A selected coin or change address does not match its derived key. + KeyMismatch, + /// A zatoshi amount is malformed or outside the consensus range. + InvalidAmount, + /// Selected inputs cannot cover outputs and the ZIP-317 fee. + InsufficientFunds, + /// The transaction would create uneconomic transparent change. + DustChange, + /// An account-level BIP-44 xprv is malformed or has unexpected metadata. + InvalidAccountXprv, + /// Transparent transaction construction or signing failed. + TransactionBuildFailed, + /// The signed transaction could not be serialized. + TransactionSerializeFailed, +} + +impl ErrorCode { + pub fn as_str(self) -> &'static str { + use ErrorCode::*; + match self { + InvalidNetwork => "INVALID_NETWORK", + InvalidMnemonic => "INVALID_MNEMONIC", + InvalidSeed => "INVALID_SEED", + InvalidAccountIndex => "INVALID_ACCOUNT_INDEX", + InvalidUfvk => "INVALID_UFVK", + DeriveFailed => "DERIVE_FAILED", + PcztParseFailed => "PCZT_PARSE_FAILED", + PcztSignFailed => "PCZT_SIGN_FAILED", + InvalidTransactionRequest => "INVALID_TRANSACTION_REQUEST", + InvalidTargetHeight => "INVALID_TARGET_HEIGHT", + InvalidAddress => "INVALID_ADDRESS", + InvalidOutpoint => "INVALID_OUTPOINT", + UnknownInput => "UNKNOWN_INPUT", + DuplicateInput => "DUPLICATE_INPUT", + CoinbaseInput => "COINBASE_INPUT", + UnconfirmedInput => "UNCONFIRMED_INPUT", + UnsupportedInputScript => "UNSUPPORTED_INPUT_SCRIPT", + InvalidDerivationPath => "INVALID_DERIVATION_PATH", + KeyMismatch => "KEY_MISMATCH", + InvalidAmount => "INVALID_AMOUNT", + InsufficientFunds => "INSUFFICIENT_FUNDS", + DustChange => "DUST_CHANGE", + InvalidAccountXprv => "INVALID_ACCOUNT_XPRV", + TransactionBuildFailed => "TRANSACTION_BUILD_FAILED", + TransactionSerializeFailed => "TRANSACTION_SERIALIZE_FAILED", + } + } +} + +#[derive(Debug)] +pub struct KeysError { + pub code: ErrorCode, + /// 结构化参数,供宿主填 i18n 占位符。永远是 JSON 对象。 + pub params: Value, + /// 上游原始报错,**仅用于日志**。 + /// + /// 注意:本包处理密钥材料,任何 detail 都不得包含种子、USK 或其派生物。 + /// 上游库的错误只描述结构问题,不回显输入,所以直接透传是安全的。 + pub detail: Option, +} + +impl KeysError { + pub fn new(code: ErrorCode) -> Self { + Self { + code, + params: Value::Object(Map::new()), + detail: None, + } + } + + pub fn with(code: ErrorCode, params: Value) -> Self { + Self { + code, + params, + detail: None, + } + } + + pub fn detail(mut self, d: impl fmt::Display) -> Self { + self.detail = Some(d.to_string()); + self + } + + pub fn to_json(&self) -> Value { + json!({ "code": self.code.as_str(), "params": self.params, "detail": self.detail }) + } +} + +impl fmt::Display for KeysError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} {}", self.code.as_str(), self.params)?; + if let Some(d) = &self.detail { + write!(f, " :: {d}")?; + } + Ok(()) + } +} + +impl std::error::Error for KeysError {} + +pub type Result = std::result::Result; + +/// 抛给 JS:`Error` 上挂 `code` / `params` / `detail`。 +#[cfg(target_arch = "wasm32")] +impl From for wasm_bindgen::JsValue { + fn from(e: KeysError) -> Self { + use wasm_bindgen::JsCast; + + let err = js_sys::Error::new(e.code.as_str()); + err.set_name(e.code.as_str()); + + let obj: js_sys::Object = err.unchecked_into(); + let set = |k: &str, v: wasm_bindgen::JsValue| { + let _ = js_sys::Reflect::set(&obj, &wasm_bindgen::JsValue::from_str(k), &v); + }; + + set("code", wasm_bindgen::JsValue::from_str(e.code.as_str())); + set( + "params", + js_sys::JSON::parse(&e.params.to_string()) + .unwrap_or_else(|_| js_sys::Object::new().into()), + ); + if let Some(d) = &e.detail { + set("detail", wasm_bindgen::JsValue::from_str(d)); + } + + obj.into() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_are_unique_and_screaming_snake() { + use ErrorCode::*; + let all = [ + InvalidNetwork, + InvalidMnemonic, + InvalidSeed, + InvalidAccountIndex, + InvalidUfvk, + DeriveFailed, + PcztParseFailed, + PcztSignFailed, + InvalidTransactionRequest, + InvalidTargetHeight, + InvalidAddress, + InvalidOutpoint, + UnknownInput, + DuplicateInput, + CoinbaseInput, + UnconfirmedInput, + UnsupportedInputScript, + InvalidDerivationPath, + KeyMismatch, + InvalidAmount, + InsufficientFunds, + DustChange, + InvalidAccountXprv, + TransactionBuildFailed, + TransactionSerializeFailed, + ]; + let mut seen = std::collections::HashSet::new(); + for c in all { + let s = c.as_str(); + assert!(seen.insert(s), "错误码重复: {s}"); + assert!( + s.chars().all(|ch| ch.is_ascii_uppercase() || ch == '_'), + "格式不对: {s}" + ); + } + } + + #[test] + fn json_shape_is_stable() { + let e = KeysError::with(ErrorCode::InvalidSeed, json!({ "byteLen": 8, "min": 32 })); + let j = e.to_json(); + assert_eq!(j["code"], "INVALID_SEED"); + assert_eq!(j["params"]["byteLen"], 8); + assert!(j["detail"].is_null()); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs new file mode 100644 index 000000000..a16d21c11 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs @@ -0,0 +1,416 @@ +//! 密钥派生。 +//! +//! 种子和 USK 的生命周期严格控制在本模块内:入口接收字节、出口只给 +//! UFVK 与地址,中间副本用完即 `zeroize`。 + +use zcash_keys::keys::{UnifiedFullViewingKey, UnifiedSpendingKey}; +use zcash_protocol::consensus::Network; +use zeroize::Zeroizing; +use zip32::AccountId; + +use crate::error::{ErrorCode, KeysError, Result}; +use serde_json::json; + +pub fn parse_network(s: &str) -> Result { + match s { + "main" | "mainnet" => Ok(Network::MainNetwork), + "test" | "testnet" => Ok(Network::TestNetwork), + other => Err(KeysError::with( + ErrorCode::InvalidNetwork, + json!({ "value": other }), + )), + } +} + +/// 从 BIP-39 助记词派生该账户的 UFVK。 +/// +/// 助记词与派生出的种子都在函数内擦除;返回值只有可公开的 UFVK 字符串。 +pub fn ufvk_from_mnemonic(network: &str, mnemonic: &str, account_index: u32) -> Result { + let params = parse_network(network)?; + + let parsed = bip0039::Mnemonic::::from_phrase(mnemonic) + .map_err(|_| KeysError::new(ErrorCode::InvalidMnemonic))?; + + // 种子放进 Zeroizing,离开作用域即擦。 + let seed = Zeroizing::new(parsed.to_seed("")); + ufvk_from_seed_bytes(params, seed.as_ref(), account_index) +} + +/// 从原始种子字节派生 UFVK。 +/// +/// 调用方给的切片本 crate 不持有;内部所有副本都受 `Zeroizing` 管理。 +pub fn ufvk_from_seed_bytes(params: Network, seed: &[u8], account_index: u32) -> Result { + if seed.len() < 32 { + return Err(KeysError::with( + ErrorCode::InvalidSeed, + json!({ "byteLen": seed.len(), "min": 32 }), + )); + } + + let account = AccountId::try_from(account_index).map_err(|_| { + KeysError::with( + ErrorCode::InvalidAccountIndex, + json!({ "value": account_index }), + ) + })?; + + let ufvk = { + let usk = UnifiedSpendingKey::from_seed(¶ms, seed, account) + .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?; + usk.to_unified_full_viewing_key() + }; + + Ok(ufvk.encode(¶ms)) +} + +/// UA 里包含哪些 receiver。**这是隐私策略,不是协议事实** —— +/// 带不带 transparent receiver 决定了对方能不能用公开方式付给你, +/// 也决定了这个地址会不会把你的透明活动和屏蔽活动关联起来。所以由宿主指定。 +/// +/// Runtime 只负责校验组合在协议上是否成立。 +fn receiver_policy(name: &str) -> Result { + use zcash_keys::keys::UnifiedAddressRequest as R; + match name { + "" | "all" => Ok(R::ALLOW_ALL), + "shielded" => Ok(R::SHIELDED), + "orchard" => Ok(R::ORCHARD), + other => Err(KeysError::with( + ErrorCode::InvalidUfvk, + json!({ "stage": "receiverPolicy", "value": other }), + )), + } +} + +/// 从 UFVK 取统一地址(UA)。不涉及任何私钥。 +/// +/// `policy` 决定包含哪些 receiver:`"all"` / `"shielded"` / `"orchard"`。 +pub fn unified_address_with(network: &str, ufvk_str: &str, policy: &str) -> Result { + let params = parse_network(network)?; + let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str) + .map_err(|e| KeysError::new(ErrorCode::InvalidUfvk).detail(e))?; + + let (addr, _) = ufvk + .default_address(receiver_policy(policy)?) + .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?; + + Ok(addr.encode(¶ms)) +} + +/// 从 UFVK 取默认统一地址(UA)。不涉及任何私钥。 +pub fn unified_address(network: &str, ufvk_str: &str) -> Result { + let params = parse_network(network)?; + let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str) + .map_err(|e| KeysError::new(ErrorCode::InvalidUfvk).detail(e))?; + + let (addr, _) = ufvk + .default_address(zcash_keys::keys::UnifiedAddressRequest::ALLOW_ALL) + .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?; + + Ok(addr.encode(¶ms)) +} + +/// 从 UFVK 取透明收款地址(t 地址)。不涉及任何私钥、不需要钱包库。 +/// +/// 与 UA 是同一份 UFVK 的两种呈现:UA 是包含多个 receiver 的统一地址, +/// 这里取出其中的透明 receiver 单独编码。交易所之类只认 t 地址的场合要用它。 +pub fn transparent_address(network: &str, ufvk_str: &str) -> Result { + let params = parse_network(network)?; + let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str) + .map_err(|e| KeysError::new(ErrorCode::InvalidUfvk).detail(e))?; + + let (addr, _) = ufvk + .default_address(zcash_keys::keys::UnifiedAddressRequest::ALLOW_ALL) + .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?; + + let t = addr.transparent().ok_or_else(|| { + KeysError::with( + ErrorCode::DeriveFailed, + json!({ "reason": "noTransparentReceiver" }), + ) + })?; + + Ok(zcash_keys::encoding::encode_transparent_address_p( + ¶ms, t, + )) +} + +/// 种子指纹(ZIP-32)。 +/// +/// **这是标准值,不是随便一个标识符** —— 宿主把它持久化下来当账户身份用, +/// 所以必须与 ZIP-32 的定义一致。自己另发明一套哈希会让存量账户全部失配。 +pub fn seed_fingerprint(seed: &[u8]) -> Result { + if seed.len() < 32 { + return Err(KeysError::with( + ErrorCode::InvalidSeed, + json!({ "byteLen": seed.len(), "min": 32 }), + )); + } + let fp = zip32::fingerprint::SeedFingerprint::from_seed(seed) + .ok_or_else(|| KeysError::with(ErrorCode::InvalidSeed, json!({ "byteLen": seed.len() })))?; + Ok(fp.to_bytes().iter().map(|b| format!("{b:02x}")).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 指纹是**标准值**且被宿主持久化当账户身份。这条测试锁死它: + /// 实现哪天漂了,存量账户会全部失配,而那种故障很难从现象反推。 + #[test] + fn seed_fingerprint_is_stable() { + let seed = [0x42u8; 64]; + let fp = seed_fingerprint(&seed).unwrap(); + assert_eq!(fp.len(), 64, "32 字节 → 64 位 hex"); + assert_eq!(fp, seed_fingerprint(&seed).unwrap(), "同一种子必须同一指纹"); + // 换一个种子必须变 + assert_ne!(fp, seed_fingerprint(&[0x43u8; 64]).unwrap()); + // 长度不足要拒绝,而不是算出一个看似合理的值 + assert!(seed_fingerprint(&[0u8; 16]).is_err()); + } + + #[test] + fn transparent_address_from_ufvk_is_t_prefixed() { + let ufvk = ufvk_from_mnemonic("test", TEST_MNEMONIC, 0).unwrap(); + let t = transparent_address("test", &ufvk).unwrap(); + assert!(t.starts_with("tm"), "testnet t 地址前缀应为 tm,实际 {t}"); + let ua = unified_address("test", &ufvk).unwrap(); + assert!(ua.starts_with("utest"), "UA 前缀应为 utest"); + assert_ne!(t, ua, "t 地址与 UA 是两种呈现,不该相同"); + } + + // 公开测试向量,切勿用于真实资金。 + const TEST_MNEMONIC: &str = + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + + #[test] + fn network_parsing() { + assert!(parse_network("main").is_ok()); + assert!(parse_network("test").is_ok()); + assert!(parse_network("regtest").is_err()); + } + + #[test] + fn short_seed_is_rejected() { + let err = ufvk_from_seed_bytes(Network::TestNetwork, &[0u8; 16], 0); + assert!(err.is_err(), "过短的种子必须拒绝"); + } + + #[test] + fn derives_ufvk_and_address() { + let ufvk = ufvk_from_mnemonic("test", TEST_MNEMONIC, 0).expect("应能派生"); + assert!( + ufvk.starts_with("uview"), + "testnet UFVK 前缀应为 uview,实际 {ufvk}" + ); + + let addr = unified_address("test", &ufvk).expect("应能取地址"); + assert!( + addr.starts_with("utest"), + "testnet UA 前缀应为 utest,实际 {addr}" + ); + } + + #[test] + fn different_accounts_differ() { + let a = ufvk_from_mnemonic("test", TEST_MNEMONIC, 0).unwrap(); + let b = ufvk_from_mnemonic("test", TEST_MNEMONIC, 1).unwrap(); + assert_ne!(a, b, "不同账户序号必须派生出不同的 UFVK"); + } + + /// 与硬件固件的互通向量(2026-08-25 对齐),路径 m/32'/133'/account'。 + /// + /// 硬件侧向量是固件独立实现产出的:UFVK 不含 sapling 项、UA 为 + /// orchard+p2pkh 组合,所以**不比整串,比同名项的字节** —— 指纹、 + /// orchard FVK(96B)、transparent 公钥(65B)、两个 receiver。任何一侧 + /// 的路径、币种或 diversifier 策略漂移都会在这里炸。 + #[test] + fn hardware_parity_vectors() { + use zcash_address::unified::{Container, Encoding, Fvk, Receiver, Ufvk}; + + const MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + const FINGERPRINT: &str = + "21ed3d7882c7e37fe012b54a6408048048cb09782d4b2938617da793ccd27815"; + const HW: [(u32, &str, &str); 2] = [ + ( + 0, + "uview1s8x5c6zq8pllw2v8ywmcp0fm46d5dk0er8gwwraz2l2s6g0cvq0jlyar820w9z6sh5l285d2ctzcukr2j2fn6cl7nyapa235fxkcmf7xkg4e3pc0phu7e95mukwx3j8t96p7yzuuxhdl9u28letaxay3gyscd9s4tr59dxg4uulsdxjxmy64ls4sy36n8p03j7f0d9w4ycjullvp5lqgslc4agjlgxzk53wnwkcm4andl5xqgs2afa7ewkkfl9fcyw7s5kknzlmn55m6sz93yvqpx78shy0uausk3avw", + "u1wzxtkul0j9he76y7m87agwd4z3vrkauchag9kwrzng07mkm2ntmc687mg45m4rjr979zhyjkn80ml4vkaty3ej20sc7hk65n0yr42chn7hw6ysdgwpu5l38ttxzhyldaa2unx7u4j8c", + ), + ( + 1, + "uview1anf6l9jhehdpktvfw4xur3emcrx7yeh6tczezfks6jmgujakhny45uqu6tc0un9ewqlk7uh5eq5fxfacwhgu3pw94yr5khdqdfl660ypxl2xryyqm6hamwwukn5dygk2hkl8lutx3ck5qy9zched9rny0ckz7rezx65um0rj0l0lcxsry8nzjakx9ftz6lecjjnym76pz5eury9yvh7rnk4pn8l76nc092h5l0x38vnxxgkwngdk0lguqjjy3sa2vzr5vay65p04zh0nqev5wvy5ypv7u060usd8yhqs", + "u1w969tctgrxzjplcpjape6al3wdqfzap4v82zhc6spfz24erd5jaea8w0rg649vknphqp30kgsahnupznu6faasvxwr700xxld9ttwermpgghrk7lxvxydmzku6vw3gwnkgac53c2v3h", + ), + ]; + + let parsed = bip0039::Mnemonic::::from_phrase(MNEMONIC).expect("助记词"); + let seed = parsed.to_seed(""); + assert_eq!( + seed_fingerprint(seed.as_ref()).unwrap(), + FINGERPRINT, + "种子指纹与硬件不一致" + ); + + // UFVK 里的 orchard / transparent 项字节。 + let fvk_items = |s: &str| { + let (_, u) = Ufvk::decode(s).expect("解析 UFVK"); + let mut orchard = None; + let mut p2pkh = None; + for item in u.items() { + match item { + Fvk::Orchard(d) => orchard = Some(d.to_vec()), + Fvk::P2pkh(d) => p2pkh = Some(d.to_vec()), + _ => {} + } + } + (orchard.expect("缺 orchard 项"), p2pkh.expect("缺 p2pkh 项")) + }; + // UA 里的 orchard / p2pkh receiver 字节。 + let ua_receivers = |s: &str| { + let (_, a) = zcash_address::unified::Address::decode(s).expect("解析 UA"); + let mut orchard = None; + let mut p2pkh = None; + for item in a.items() { + match item { + Receiver::Orchard(d) => orchard = Some(d.to_vec()), + Receiver::P2pkh(d) => p2pkh = Some(d.to_vec()), + _ => {} + } + } + ( + orchard.expect("缺 orchard receiver"), + p2pkh.expect("缺 p2pkh receiver"), + ) + }; + + for (account, hw_ufvk, hw_ua) in HW { + let ours = ufvk_from_mnemonic("main", MNEMONIC, account).expect("派生 UFVK"); + assert_eq!( + fvk_items(&ours), + fvk_items(hw_ufvk), + "account {account}: FVK 项字节与硬件不一致" + ); + // 我们带 p2pkh receiver 的组装是 "all";只取它的 receiver 字节比对。 + let our_ua = unified_address_with("main", &ours, "all").expect("UA"); + assert_eq!( + ua_receivers(&our_ua), + ua_receivers(hw_ua), + "account {account}: 地址 receiver 字节与硬件不一致" + ); + } + } +} + +#[cfg(test)] +mod ua_inspect { + fn receivers(ua: &str) -> Vec { + use zcash_address::unified::{Container, Encoding}; + let (_, parsed) = zcash_address::unified::Address::decode(ua).expect("解析 UA"); + parsed + .items() + .iter() + .map(|item| match item { + zcash_address::unified::Receiver::Orchard(_) => "orchard".to_owned(), + zcash_address::unified::Receiver::Sapling(_) => "sapling".to_owned(), + zcash_address::unified::Receiver::P2pkh(_) => "transparent-p2pkh".to_owned(), + zcash_address::unified::Receiver::P2sh(_) => "transparent-p2sh".to_owned(), + other => format!("{other:?}"), + }) + .collect() + } + + /// 打印某助记词的收款地址,供本机手工测试(要水龙头的币)用。 + /// 需要 `ZR_MNEMONIC`,未设置时直接跳过,所以常规 `cargo test` 不受影响。 + /// + /// 同时打印每种 policy 的 receiver 组成 —— 收款地址里混进不可花的 receiver + /// 会让打进来的钱永远取不出来,这条是唯一能提前看见它的地方。 + #[test] + fn print_receiving_addresses() { + let mnemonic = std::env::var("ZR_MNEMONIC").unwrap_or_default(); + if mnemonic.trim().is_empty() { + return; + } + let network = std::env::var("ZR_NETWORK").unwrap_or_else(|_| "test".to_owned()); + let account: u32 = std::env::var("ZR_ACCOUNT") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0); + let ufvk = + super::ufvk_from_mnemonic(&network, mnemonic.trim(), account).expect("派生 UFVK"); + + // 与硬件对向量用的完整三元组:指纹 → UFVK → 地址,粗到细, + // 哪一级先岔开,问题就在那一级对应的派生步骤里。 + let parsed = + bip0039::Mnemonic::::from_phrase(mnemonic.trim()).expect("助记词"); + let seed = parsed.to_seed(""); + println!("network {network} account {account}"); + println!( + "fingerprint {}", + super::seed_fingerprint(seed.as_ref()).expect("指纹") + ); + println!("ufvk {ufvk}"); + println!( + "t-addr {}", + super::transparent_address(&network, &ufvk).expect("t 地址") + ); + for policy in ["all", "shielded", "orchard"] { + let ua = super::unified_address_with(&network, &ufvk, policy).expect("UA"); + println!("UA[{policy}] {ua}"); + println!(" receivers = {:?}", receivers(&ua)); + } + } + + /// 解析一个 UFVK(uview…),列出它包含哪些密钥项。 + /// 与硬件对派生时用:整串不等先看项集合 —— 项集合不同是组装差异, + /// 项集合相同而字节不同才是真正的派生差异。 + #[test] + fn inspect_external_ufvk() { + let s = std::env::var("ZR_UFVK").unwrap_or_default(); + if s.is_empty() { + return; + } + use zcash_address::unified::{Container, Encoding, Fvk, Ufvk}; + let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::(); + let (net, parsed) = Ufvk::decode(&s).expect("解析 UFVK"); + println!("网络: {net:?}"); + for item in parsed.items() { + match &item { + Fvk::Orchard(d) => println!(" orchard {}", hex(d)), + Fvk::Sapling(d) => println!(" sapling {}", hex(d)), + Fvk::P2pkh(d) => println!(" transparent-p2pkh {}", hex(d)), + other => println!(" 其他密钥项: {other:?}"), + } + } + } + + /// 解析一个 UA,列出它包含哪些 receiver。 + /// 用来看别的钱包实际给用户的收款地址里放了什么。 + #[test] + fn inspect_external_ua() { + let ua = std::env::var("ZR_UA").unwrap_or_default(); + if ua.is_empty() { + return; + } + use zcash_address::unified::{Container, Encoding}; + let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::(); + let (net, parsed) = zcash_address::unified::Address::decode(&ua).expect("解析 UA"); + println!("网络: {net:?}"); + for item in parsed.items() { + match &item { + zcash_address::unified::Receiver::Orchard(d) => { + println!(" orchard {}", hex(d)); + } + zcash_address::unified::Receiver::Sapling(d) => { + println!(" sapling {}", hex(d)); + } + zcash_address::unified::Receiver::P2pkh(d) => { + println!(" transparent-p2pkh {}", hex(d)); + } + zcash_address::unified::Receiver::P2sh(d) => { + println!(" transparent-p2sh {}", hex(d)); + } + other => println!(" 其他 receiver: {other:?}"), + } + } + } +} diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs new file mode 100644 index 000000000..90641a318 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs @@ -0,0 +1,32 @@ +//! # OneKey Zcash Keys +//! +//! 只做两件事:从种子派生密钥、导出可公开的观察材料(UFVK / 地址)。 +//! +//! **不含存储、不含扫链、不含网络。** 这是刻意的:移动端只需要这一半, +//! 不该为了派生一个地址就把 SQLite 和整个扫链引擎打进包里。 +//! +//! ## 密钥纪律 +//! +//! - 种子与花费密钥(USK)**只在本 crate 内部存在**,不跨 wasm 边界。 +//! - 所有中间副本用 `Zeroize` 擦除;JS 侧永远只拿到 UFVK 和地址。 +//! - 调用方传进来的种子字节,本 crate 用完即擦。 + +pub mod error; +pub mod keys; +pub mod sign; +pub mod transparent_send; + +#[cfg(target_arch = "wasm32")] +pub mod bindgen; + +pub use error::{ErrorCode, KeysError, Result}; + +/// 本 crate 锁定的官方依赖版本。 +pub fn dependency_versions() -> serde_json::Value { + serde_json::json!({ + "zcash_keys": "0.16.1", + "zcash_primitives": "0.30.1", + "zcash_transparent": "0.10.0", + "crate": env!("CARGO_PKG_VERSION"), + }) +} diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs new file mode 100644 index 000000000..2ad186232 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs @@ -0,0 +1,233 @@ +//! PCZT 签名。 +//! +//! **这是整个方案里唯一接触花费密钥的地方。** +//! +//! 构造 PCZT 需要钱包数据库(选币、witness、anchor),签名需要种子。 +//! 两者分处两个 crate,所以: +//! +//! - `onekey-zcash-runtime` 里没有任何路径能拿到种子; +//! - 移动端只打这个 keys 包时,签名依然可用; +//! - 想审计「私钥去了哪」,只需要看这一个文件。 +//! +//! 种子在函数内派生、用完即 `zeroize`,绝不跨 wasm 边界返回。 + +use pczt::roles::signer::Signer; +use zcash_keys::keys::UnifiedSpendingKey; +use zcash_protocol::consensus::Network; +use zeroize::Zeroizing; +use zip32::AccountId; + +use crate::error::{ErrorCode, KeysError, Result}; +use crate::keys::parse_network; + +/// 用助记词派生出的花费密钥给 PCZT 签名。 +/// +/// 只签 Orchard 花费 —— 本方案不支持 Sapling 花费(Sapling 的 Groth16 证明参数 +/// 约 50 MB,不适合随包分发;新收到的资金也不会落在 Sapling 池)。 +/// +/// 返回签名后的 PCZT 字节,交回 runtime 的 `pcztSend` 终结并广播。 +pub fn sign_pczt_with_mnemonic( + network: &str, + mnemonic: &str, + account_index: u32, + pczt_bytes: &[u8], +) -> Result> { + let params = parse_network(network)?; + + let parsed = bip0039::Mnemonic::::from_phrase(mnemonic) + .map_err(|_| KeysError::new(ErrorCode::InvalidMnemonic))?; + let seed = Zeroizing::new(parsed.to_seed("")); + + sign_pczt_with_seed(params, seed.as_ref(), account_index, pczt_bytes) +} + +/// 同上,但直接接收种子字节。调用方负责擦除自己那份。 +/// 本 crate 当前实际能签的 bundle 类型。定义在实现旁边,翻转时必然改到实现。 +pub const SIGN_ORCHARD: bool = true; +pub const SIGN_SAPLING: bool = false; +pub const SIGN_TRANSPARENT: bool = true; +pub const SIGN_IRONWOOD: bool = true; + +/// 试签透明输入时扫多少个地址序号。 +/// +/// PCZT 里每个透明输入都带着自己的 BIP-32 派生路径,但 `pczt` 没有把那个字段 +/// 公开出来,所以只能按序号逐个试。上游 `sign` 会从私钥反推 pubkey 并核对 +/// `script_pubkey`,不匹配就报错 —— 所以试签不会静默产出错误签名。 +/// +/// 取值要覆盖钱包的 gap limit(默认 20),留一倍余量。 +const TRANSPARENT_SCAN_GAP: u32 = 40; + +/// 给全部透明输入签名,返回 (签上了几个, 最后一次失败原因)。 +/// +/// 透明输入是屏蔽(transparent → shielded)这条路的必经之处:不签它,打进 +/// t 地址的钱就永远出不来。 +fn sign_transparent_inputs( + signer: &mut Signer, + usk: &UnifiedSpendingKey, + input_count: usize, +) -> (usize, Option) { + use transparent::keys::{NonHardenedChildIndex, TransparentKeyScope}; + + let account_key = usk.transparent(); + let mut signed = 0usize; + let mut last_err = None; + + for index in 0..input_count { + let mut done = false; + // 找零走 internal scope,收款走 external,两个都要试。 + for scope in [TransparentKeyScope::EXTERNAL, TransparentKeyScope::INTERNAL] { + for i in 0..TRANSPARENT_SCAN_GAP { + let Some(child) = NonHardenedChildIndex::from_index(i) else { + continue; + }; + let Ok(sk) = account_key.derive_secret_key(scope, child) else { + continue; + }; + match signer.sign_transparent(index, &sk) { + Ok(()) => { + signed += 1; + done = true; + break; + } + Err(e) => last_err = Some(format!("transparent[{index}]: {e:?}")), + } + } + if done { + break; + } + } + } + + (signed, last_err) +} + +pub fn sign_pczt_with_seed( + params: Network, + seed: &[u8], + account_index: u32, + pczt_bytes: &[u8], +) -> Result> { + if seed.len() < 32 { + return Err(KeysError::with( + ErrorCode::InvalidSeed, + serde_json::json!({ "byteLen": seed.len(), "min": 32 }), + )); + } + + let account = AccountId::try_from(account_index).map_err(|_| { + KeysError::with( + ErrorCode::InvalidAccountIndex, + serde_json::json!({ "value": account_index }), + ) + })?; + + let usk = UnifiedSpendingKey::from_seed(¶ms, seed, account) + .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?; + + let pczt = pczt::Pczt::parse(pczt_bytes) + .map_err(|e| KeysError::new(ErrorCode::PcztParseFailed).detail(format!("{e:?}")))?; + + let mut signer = Signer::new(pczt) + .map_err(|e| KeysError::new(ErrorCode::PcztSignFailed).detail(format!("{e:?}")))?; + + // Orchard 花费授权密钥由花费密钥派生。 + let ask = orchard::keys::SpendAuthorizingKey::from(usk.orchard()); + + // 逐个 action 尝试签名:不属于本账户的 action 会被上游拒绝, + // 这里按「签得上就签」处理,两个池都签不上才算错误。 + // + // 两个池都要签:NU6.3 之后新的花费走 Ironwood,而从 Orchard 迁出(那个池 + // 现在只出不进)走 Orchard。一笔迁移交易可能两边都有 action。 + let (orchard_count, ironwood_count, transparent_count) = bundle_counts(pczt_bytes)?; + let mut signed_any = false; + let mut last_err: Option = None; + + // 透明输入必须**全部**签上。少签一个,交易就是无效的 —— 屏蔽这条路上 + // 所有输入都是透明的,漏一个等于整笔作废,所以这里是硬要求而非尽力而为。 + let (transparent_signed, transparent_err) = + sign_transparent_inputs(&mut signer, &usk, transparent_count); + if transparent_signed < transparent_count { + return Err(KeysError::with( + ErrorCode::PcztSignFailed, + serde_json::json!({ + "transparentInputs": transparent_count, + "transparentSigned": transparent_signed, + }), + ) + .detail(transparent_err.unwrap_or_else(|| { + "a transparent input did not match any key in the scan range".into() + }))); + } + signed_any |= transparent_signed > 0; + + for index in 0..orchard_count { + match signer.sign_orchard(index, &ask) { + Ok(()) => signed_any = true, + Err(e) => last_err = Some(format!("orchard[{index}]: {e:?}")), + } + } + for index in 0..ironwood_count { + match signer.sign_ironwood(index, &ask) { + Ok(()) => signed_any = true, + Err(e) => last_err = Some(format!("ironwood[{index}]: {e:?}")), + } + } + + if !signed_any { + return Err(KeysError::with( + ErrorCode::PcztSignFailed, + serde_json::json!({ + "orchardActions": orchard_count, + "ironwoodActions": ironwood_count, + "transparentInputs": transparent_count, + }), + ) + .detail(last_err.unwrap_or_else(|| "nothing in this PCZT was signable".into()))); + } + + let signed = signer.finish(); + signed + .serialize() + .map_err(|e| KeysError::new(ErrorCode::PcztSignFailed).detail(format!("{e:?}"))) +} + +/// 数出这份 PCZT 里各 bundle 有多少东西要签:(orchard, ironwood, transparent)。 +/// +/// Ironwood 的 note 与 Orchard 是同一个 Rust 类型,只靠 `ValuePool` 标签区分, +/// 但 PCZT 里是两个独立的 bundle,所以必须分别数、分别签。 +fn bundle_counts(pczt_bytes: &[u8]) -> Result<(usize, usize, usize)> { + let pczt = pczt::Pczt::parse(pczt_bytes) + .map_err(|e| KeysError::new(ErrorCode::PcztParseFailed).detail(format!("{e:?}")))?; + Ok(( + pczt.orchard().actions().len(), + pczt.ironwood().actions().len(), + pczt.transparent().inputs().len(), + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + const M: &str = + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + + #[test] + fn rejects_short_seed() { + let e = sign_pczt_with_seed(Network::TestNetwork, &[0u8; 8], 0, &[]).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidSeed); + assert_eq!(e.params["byteLen"], 8); + } + + #[test] + fn rejects_garbage_pczt() { + let e = sign_pczt_with_mnemonic("test", M, 0, b"not a pczt").unwrap_err(); + assert_eq!(e.code, ErrorCode::PcztParseFailed); + } + + #[test] + fn rejects_bad_mnemonic() { + let e = sign_pczt_with_mnemonic("test", "clearly not a mnemonic", 0, &[]).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidMnemonic); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs new file mode 100644 index 000000000..d635816ae --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs @@ -0,0 +1,1034 @@ +//! Stateless transparent transaction quoting, construction, and signing. +//! +//! This module deliberately has no wallet database, scanner, or network client. The host supplies +//! a complete UTXO catalog plus an explicit set of outpoints to spend. Every selected coin is +//! revalidated against its exact BIP-44 path before a transaction is signed. + +use std::collections::{HashMap, HashSet}; + +use orchard::bundle::Authorized as OrchardAuthorized; +use sapling::bundle::Authorized as SaplingAuthorized; +use serde::{Deserialize, Serialize}; +use transparent::{ + address::TransparentAddress, + builder::{TransparentBuilder, TransparentSigningSet}, + bundle::{OutPoint, TxOut}, + keys::{AccountPrivKey, NonHardenedChildIndex, TransparentKeyScope}, +}; +use zcash_address::ZcashAddress; +use zcash_primitives::transaction::{ + fees::{ + transparent::{InputSize, OutputView}, + zip317::{FeeRule as Zip317FeeRule, MARGINAL_FEE}, + FeeRule as _, + }, + sighash::{signature_hash, SignableInput}, + txid::TxIdDigester, + Authorization, Authorized, TransactionData, +}; +use zcash_protocol::{ + consensus::{BlockHeight, BranchId, NetworkType, MAIN_NETWORK}, + value::Zatoshis, + TxId, +}; +use zcash_script::script::Evaluable; +use zeroize::Zeroizing; +use zip32::AccountId; + +use crate::error::{ErrorCode, KeysError, Result}; + +const MAX_EXPIRY_DELTA: u32 = 100; +const XPRV_VERSION: [u8; 4] = [0x04, 0x88, 0xad, 0xe4]; +const ACCOUNT_XPRV_DEPTH: u8 = 3; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TransparentTxRequest { + pub network: String, + pub account_index: u32, + pub target_height: u32, + pub expiry_height: u32, + pub utxos: Vec, + pub selected_outpoints: Vec, + pub recipients: Vec, + pub send_max: bool, + pub change: Option, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TransparentUtxo { + pub txid: String, + pub vout: u32, + pub value_zat: String, + pub script_pub_key: String, + pub is_coinbase: bool, + pub confirmations: u32, + pub derivation_path: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct OutpointRef { + pub txid: String, + pub vout: u32, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TransparentRecipient { + pub address: String, + pub amount_zat: Option, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TransparentChange { + pub address: String, + pub derivation_path: String, +} + +#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct TransparentQuote { + pub fee_zat: String, + pub input_total_zat: String, + pub send_amount_zat: String, + pub change_zat: String, + pub expiry_height: u32, + pub spent_outpoints: Vec, +} + +#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct TransparentBuildResult { + pub raw_tx: String, + pub txid: String, + pub fee_zat: String, + pub expiry_height: u32, + pub spent_outpoints: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DerivationPath { + account: u32, + scope: u32, + index: u32, +} + +#[derive(Debug)] +struct PlannedInput { + request: TransparentUtxo, + txid: TxId, + value: Zatoshis, + script_pub_key: Vec, + path: DerivationPath, +} + +#[derive(Debug)] +struct PlannedOutput { + address: TransparentAddress, + value: Zatoshis, +} + +#[derive(Debug)] +struct TransactionPlan { + account_index: AccountId, + expiry_height: BlockHeight, + inputs: Vec, + recipients: Vec, + change: Option<(TransparentChange, PlannedOutput, DerivationPath)>, + fee: Zatoshis, + input_total: Zatoshis, + send_amount: Zatoshis, +} + +/// Authorization marker for a transaction whose only unauthorized component is transparent. +/// +/// `zcash_primitives::transaction::Unauthorized` is gated behind its `circuits` feature. Using a +/// local marker keeps the stateless transparent signer free of Sapling and Orchard proving code. +struct TransparentUnauthorized; + +impl Authorization for TransparentUnauthorized { + type TransparentAuth = transparent::builder::Unauthorized; + type SaplingAuth = SaplingAuthorized; + type OrchardAuth = OrchardAuthorized; +} + +pub fn quote_json(request_json: &str) -> Result { + let request = parse_request(request_json)?; + let plan = plan_transaction(request)?; + serde_json::to_string(&plan.quote()) + .map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e)) +} + +pub fn build_with_seed_json(request_json: &str, seed: &[u8]) -> Result { + if seed.len() < 32 { + return Err(KeysError::with( + ErrorCode::InvalidSeed, + serde_json::json!({ "byteLen": seed.len(), "min": 32 }), + )); + } + + let request = parse_request(request_json)?; + let plan = plan_transaction(request)?; + let account_key = AccountPrivKey::from_seed(&MAIN_NETWORK, seed, plan.account_index) + .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(e))?; + serialize_build_result(build_transaction(plan, &account_key)?) +} + +/// Builds with an account-level BIP-44 xprv at `m/44'/133'/account'`. +/// +/// An account xprv cannot prove its ancestor path. The encoded key metadata is therefore checked +/// for depth 3 and the expected hardened account index, while the host remains responsible for +/// obtaining it from the exact `m/44'/133'/account'` path. +pub fn build_with_account_xprv_json(request_json: &str, account_xprv: &str) -> Result { + let request = parse_request(request_json)?; + let plan = plan_transaction(request)?; + let account_key = parse_account_xprv(account_xprv, u32::from(plan.account_index))?; + serialize_build_result(build_transaction(plan, &account_key)?) +} + +fn parse_request(request_json: &str) -> Result { + serde_json::from_str(request_json) + .map_err(|e| KeysError::new(ErrorCode::InvalidTransactionRequest).detail(e)) +} + +fn serialize_build_result(result: TransparentBuildResult) -> Result { + serde_json::to_string(&result) + .map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e)) +} + +impl TransactionPlan { + fn quote(&self) -> TransparentQuote { + TransparentQuote { + fee_zat: self.fee.into_u64().to_string(), + input_total_zat: self.input_total.into_u64().to_string(), + send_amount_zat: self.send_amount.into_u64().to_string(), + change_zat: self + .change + .as_ref() + .map_or(0, |(_, output, _)| output.value.into_u64()) + .to_string(), + expiry_height: self.expiry_height.into(), + spent_outpoints: self + .inputs + .iter() + .map(|input| OutpointRef { + txid: input.txid.to_string(), + vout: input.request.vout, + }) + .collect(), + } + } +} + +fn plan_transaction(request: TransparentTxRequest) -> Result { + if request.network != "main" && request.network != "mainnet" { + return Err(KeysError::with( + ErrorCode::InvalidNetwork, + serde_json::json!({ "value": request.network }), + )); + } + + let account_index = AccountId::try_from(request.account_index).map_err(|_| { + KeysError::with( + ErrorCode::InvalidAccountIndex, + serde_json::json!({ "value": request.account_index }), + ) + })?; + let target_height = BlockHeight::from_u32(request.target_height); + if BranchId::for_height(&MAIN_NETWORK, target_height) != BranchId::Nu6_3 { + return Err(KeysError::with( + ErrorCode::InvalidTargetHeight, + serde_json::json!({ + "targetHeight": request.target_height, + "requiredBranch": "Nu6.3", + }), + )); + } + let expiry_delta = request + .expiry_height + .checked_sub(request.target_height) + .ok_or_else(|| { + KeysError::with( + ErrorCode::InvalidTargetHeight, + serde_json::json!({ + "targetHeight": request.target_height, + "expiryHeight": request.expiry_height, + "reason": "expiryMustBeAfterTarget", + }), + ) + })?; + if expiry_delta == 0 || expiry_delta > MAX_EXPIRY_DELTA { + return Err(KeysError::with( + ErrorCode::InvalidTargetHeight, + serde_json::json!({ + "targetHeight": request.target_height, + "expiryHeight": request.expiry_height, + "maximumDelta": MAX_EXPIRY_DELTA, + }), + )); + } + let expiry_height = BlockHeight::from_u32(request.expiry_height); + + let inputs = select_inputs( + request.utxos, + request.selected_outpoints, + request.account_index, + )?; + let input_total_raw = checked_sum( + inputs.iter().map(|input| input.value.into_u64()), + "inputTotal", + )?; + let input_total = parse_zatoshis_u64(input_total_raw, "inputTotal")?; + + if request.recipients.is_empty() { + return Err(KeysError::with( + ErrorCode::InvalidTransactionRequest, + serde_json::json!({ "field": "recipients", "reason": "empty" }), + )); + } + if request.send_max && request.recipients.len() != 1 { + return Err(KeysError::with( + ErrorCode::InvalidTransactionRequest, + serde_json::json!({ "field": "recipients", "reason": "sendMaxRequiresOneRecipient" }), + )); + } + + let parsed_recipients = request + .recipients + .into_iter() + .map(|recipient| { + let address = parse_transparent_address(&recipient.address, "recipient")?; + if request.send_max { + if recipient.amount_zat.is_some() { + return Err(KeysError::with( + ErrorCode::InvalidTransactionRequest, + serde_json::json!({ "field": "amountZat", "reason": "mustBeOmittedForSendMax" }), + )); + } + Ok((address, None)) + } else { + let amount = recipient.amount_zat.as_deref().ok_or_else(|| { + KeysError::with( + ErrorCode::InvalidTransactionRequest, + serde_json::json!({ "field": "amountZat", "reason": "required" }), + ) + })?; + let value = parse_positive_zatoshis(amount, "recipient.amountZat")?; + Ok((address, Some(value))) + } + }) + .collect::>>()?; + + if request.send_max { + let address = parsed_recipients[0].0; + let fee = calculate_fee(target_height, inputs.len(), &[address])?; + let send_amount_raw = input_total_raw + .checked_sub(fee.into_u64()) + .ok_or_else(|| insufficient_funds(input_total_raw, fee.into_u64()))?; + let send_amount = parse_positive_zatoshis(send_amount_raw.to_string().as_str(), "sendMax")?; + return Ok(TransactionPlan { + account_index, + expiry_height, + inputs, + recipients: vec![PlannedOutput { + address, + value: send_amount, + }], + change: None, + fee, + input_total, + send_amount, + }); + } + + let recipients = parsed_recipients + .into_iter() + .map(|(address, value)| PlannedOutput { + address, + value: value.expect("non-send-max recipients were checked above"), + }) + .collect::>(); + let send_total_raw = checked_sum( + recipients.iter().map(|output| output.value.into_u64()), + "recipientTotal", + )?; + let send_amount = parse_zatoshis_u64(send_total_raw, "recipientTotal")?; + let recipient_addresses = recipients + .iter() + .map(|output| output.address) + .collect::>(); + let fee_without_change = calculate_fee(target_height, inputs.len(), &recipient_addresses)?; + let needed_without_change = send_total_raw + .checked_add(fee_without_change.into_u64()) + .ok_or_else(|| amount_error("recipientTotal"))?; + + if input_total_raw < needed_without_change { + return Err(insufficient_funds(input_total_raw, needed_without_change)); + } + + let (fee, change) = if input_total_raw == needed_without_change { + (fee_without_change, None) + } else { + let change_request = request.change.ok_or_else(|| { + KeysError::with( + ErrorCode::InvalidTransactionRequest, + serde_json::json!({ "field": "change", "reason": "required" }), + ) + })?; + let change_address = parse_transparent_address(&change_request.address, "change.address")?; + if !matches!(change_address, TransparentAddress::PublicKeyHash(_)) { + return Err(KeysError::with( + ErrorCode::InvalidAddress, + serde_json::json!({ "field": "change.address", "reason": "p2pkhRequired" }), + )); + } + let change_path = + parse_derivation_path(&change_request.derivation_path, request.account_index)?; + if change_path.scope != 1 { + return Err(KeysError::with( + ErrorCode::InvalidDerivationPath, + serde_json::json!({ "field": "change.derivationPath", "reason": "internalScopeRequired" }), + )); + } + let mut addresses_with_change = recipient_addresses; + addresses_with_change.push(change_address); + let fee = calculate_fee(target_height, inputs.len(), &addresses_with_change)?; + let needed = send_total_raw + .checked_add(fee.into_u64()) + .ok_or_else(|| amount_error("recipientTotal"))?; + let change_raw = input_total_raw + .checked_sub(needed) + .ok_or_else(|| insufficient_funds(input_total_raw, needed))?; + if change_raw < MARGINAL_FEE.into_u64() { + return Err(KeysError::with( + ErrorCode::DustChange, + serde_json::json!({ + "changeZat": change_raw.to_string(), + "minimumZat": MARGINAL_FEE.into_u64().to_string(), + }), + )); + } + let change_value = parse_zatoshis_u64(change_raw, "change")?; + ( + fee, + Some(( + change_request, + PlannedOutput { + address: change_address, + value: change_value, + }, + change_path, + )), + ) + }; + + Ok(TransactionPlan { + account_index, + expiry_height, + inputs, + recipients, + change, + fee, + input_total, + send_amount, + }) +} + +fn select_inputs( + utxos: Vec, + selected: Vec, + account_index: u32, +) -> Result> { + if selected.is_empty() { + return Err(KeysError::with( + ErrorCode::InvalidTransactionRequest, + serde_json::json!({ "field": "selectedOutpoints", "reason": "empty" }), + )); + } + + let mut catalog = HashMap::new(); + for utxo in utxos { + let txid = parse_txid(&utxo.txid)?; + let key = (txid.to_string(), utxo.vout); + if catalog.insert(key.clone(), (utxo, txid)).is_some() { + return Err(KeysError::with( + ErrorCode::DuplicateInput, + serde_json::json!({ "txid": key.0, "vout": key.1 }), + )); + } + } + + let mut selected_seen = HashSet::new(); + selected + .into_iter() + .map(|outpoint| { + let txid = parse_txid(&outpoint.txid)?; + let key = (txid.to_string(), outpoint.vout); + if !selected_seen.insert(key.clone()) { + return Err(KeysError::with( + ErrorCode::DuplicateInput, + serde_json::json!({ "txid": key.0, "vout": key.1 }), + )); + } + let (utxo, txid) = catalog.remove(&key).ok_or_else(|| { + KeysError::with( + ErrorCode::UnknownInput, + serde_json::json!({ "txid": key.0, "vout": key.1 }), + ) + })?; + validate_utxo(utxo, txid, account_index) + }) + .collect() +} + +fn validate_utxo(utxo: TransparentUtxo, txid: TxId, account_index: u32) -> Result { + if txid.is_null() { + return Err(KeysError::with( + ErrorCode::InvalidOutpoint, + serde_json::json!({ "txid": utxo.txid, "vout": utxo.vout, "reason": "nullTxid" }), + )); + } + if utxo.is_coinbase { + return Err(KeysError::with( + ErrorCode::CoinbaseInput, + serde_json::json!({ "txid": txid.to_string(), "vout": utxo.vout }), + )); + } + if utxo.confirmations == 0 { + return Err(KeysError::with( + ErrorCode::UnconfirmedInput, + serde_json::json!({ "txid": txid.to_string(), "vout": utxo.vout }), + )); + } + let value = parse_positive_zatoshis(&utxo.value_zat, "utxo.valueZat")?; + let script_pub_key = hex::decode(&utxo.script_pub_key).map_err(|_| { + KeysError::with( + ErrorCode::UnsupportedInputScript, + serde_json::json!({ "txid": txid.to_string(), "vout": utxo.vout }), + ) + })?; + if !is_p2pkh_script(&script_pub_key) { + return Err(KeysError::with( + ErrorCode::UnsupportedInputScript, + serde_json::json!({ "txid": txid.to_string(), "vout": utxo.vout, "required": "p2pkh" }), + )); + } + let path = parse_derivation_path(&utxo.derivation_path, account_index)?; + + Ok(PlannedInput { + request: utxo, + txid, + value, + script_pub_key, + path, + }) +} + +fn build_transaction( + plan: TransactionPlan, + account_key: &AccountPrivKey, +) -> Result { + let quote = plan.quote(); + let mut builder = TransparentBuilder::empty(); + let mut signing_set = TransparentSigningSet::new(); + + for input in &plan.inputs { + let secret_key = derive_secret_key(account_key, input.path)?; + let pubkey = signing_set.add_key(secret_key); + let derived_address = TransparentAddress::from_pubkey(&pubkey); + let expected_script = derived_address.script().to_bytes(); + if input.script_pub_key != expected_script { + return Err(KeysError::with( + ErrorCode::KeyMismatch, + serde_json::json!({ "txid": input.txid.to_string(), "vout": input.request.vout }), + )); + } + builder + .add_p2pkh_input( + pubkey, + OutPoint::new(*input.txid.as_ref(), input.request.vout), + TxOut::new(input.value, derived_address.script().into()), + ) + .map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e))?; + } + + for output in &plan.recipients { + builder + .add_output(&output.address, output.value) + .map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e))?; + } + if let Some((change_request, output, path)) = &plan.change { + let secret_key = derive_secret_key(account_key, *path)?; + let pubkey = signing_set.add_key(secret_key); + let derived_address = TransparentAddress::from_pubkey(&pubkey); + if derived_address != output.address { + return Err(KeysError::with( + ErrorCode::KeyMismatch, + serde_json::json!({ "field": "change.address" }), + )); + } + let encoded = derived_address + .to_zcash_address(NetworkType::Main) + .to_string(); + if encoded != change_request.address { + return Err(KeysError::with( + ErrorCode::KeyMismatch, + serde_json::json!({ "field": "change.address" }), + )); + } + builder + .add_output(&output.address, output.value) + .map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e))?; + } + + let transparent_bundle = builder.build().ok_or_else(|| { + KeysError::with( + ErrorCode::TransactionBuildFailed, + serde_json::json!({ "reason": "emptyBundle" }), + ) + })?; + let unsigned_tx = TransactionData::::from_parts_v6( + BranchId::Nu6_3, + 0, + plan.expiry_height, + Some(transparent_bundle.clone()), + None, + None, + None, + ); + let txid_parts = unsigned_tx.digest(TxIdDigester); + let authorized_bundle = transparent_bundle + .apply_signatures( + |input| { + *signature_hash( + &unsigned_tx, + &SignableInput::Transparent(input), + &txid_parts, + ) + .as_ref() + }, + &signing_set, + ) + .map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e))?; + let transaction = TransactionData::::from_parts_v6( + BranchId::Nu6_3, + 0, + plan.expiry_height, + Some(authorized_bundle), + None, + None, + None, + ) + .freeze() + .map_err(|e| KeysError::new(ErrorCode::TransactionSerializeFailed).detail(e))?; + let mut raw_tx = Vec::new(); + transaction + .write(&mut raw_tx) + .map_err(|e| KeysError::new(ErrorCode::TransactionSerializeFailed).detail(e))?; + + Ok(TransparentBuildResult { + raw_tx: hex::encode(raw_tx), + txid: transaction.txid().to_string(), + fee_zat: quote.fee_zat, + expiry_height: quote.expiry_height, + spent_outpoints: quote.spent_outpoints, + }) +} + +fn calculate_fee( + target_height: BlockHeight, + input_count: usize, + output_addresses: &[TransparentAddress], +) -> Result { + let output_sizes = output_addresses + .iter() + .map(|address| TxOut::new(Zatoshis::ZERO, address.script().into()).serialized_size()); + Zip317FeeRule::standard() + .fee_required( + &MAIN_NETWORK, + target_height, + std::iter::repeat_n(InputSize::STANDARD_P2PKH, input_count), + output_sizes, + 0, + 0, + 0, + 0, + ) + .map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e)) +} + +fn derive_secret_key( + account_key: &AccountPrivKey, + path: DerivationPath, +) -> Result { + let scope = match path.scope { + 0 => TransparentKeyScope::EXTERNAL, + 1 => TransparentKeyScope::INTERNAL, + _ => { + return Err(KeysError::with( + ErrorCode::InvalidDerivationPath, + serde_json::json!({ "reason": "unsupportedScope", "scope": path.scope }), + )); + } + }; + let index = NonHardenedChildIndex::from_index(path.index).ok_or_else(|| { + KeysError::with( + ErrorCode::InvalidDerivationPath, + serde_json::json!({ "reason": "hardenedAddressIndex", "index": path.index }), + ) + })?; + account_key + .derive_secret_key(scope, index) + .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(e)) +} + +fn parse_account_xprv(encoded: &str, expected_account: u32) -> Result { + let decoded = Zeroizing::new( + bs58::decode(encoded) + .with_check(None) + .into_vec() + .map_err(|_| KeysError::new(ErrorCode::InvalidAccountXprv))?, + ); + if decoded.len() != 78 || decoded[..4] != XPRV_VERSION || decoded[4] != ACCOUNT_XPRV_DEPTH { + return Err(KeysError::new(ErrorCode::InvalidAccountXprv)); + } + let child = u32::from_be_bytes(decoded[9..13].try_into().expect("fixed slice length")); + let expected_child = expected_account.checked_add(1 << 31).ok_or_else(|| { + KeysError::with( + ErrorCode::InvalidAccountIndex, + serde_json::json!({ "value": expected_account }), + ) + })?; + if child != expected_child { + return Err(KeysError::with( + ErrorCode::InvalidAccountXprv, + serde_json::json!({ "reason": "accountIndexMismatch" }), + )); + } + AccountPrivKey::from_bytes(&decoded[4..]) + .ok_or_else(|| KeysError::new(ErrorCode::InvalidAccountXprv)) +} + +fn parse_derivation_path(path: &str, expected_account: u32) -> Result { + let parts = path.split('/').collect::>(); + let hardened = |part: &str| part.strip_suffix('\'')?.parse::().ok(); + let plain = |part: &str| { + if part.ends_with('\'') { + None + } else { + part.parse::().ok() + } + }; + let parsed = match parts.as_slice() { + ["m", purpose, coin_type, account, scope, index] + if hardened(purpose) == Some(44) && hardened(coin_type) == Some(133) => + { + hardened(account).zip(plain(scope)).zip(plain(index)).map( + |((account, scope), index)| DerivationPath { + account, + scope, + index, + }, + ) + } + _ => None, + } + .filter(|parsed| { + parsed.account == expected_account && parsed.scope <= 1 && parsed.index < (1 << 31) + }) + .ok_or_else(|| { + KeysError::with( + ErrorCode::InvalidDerivationPath, + serde_json::json!({ + "required": format!("m/44'/133'/{expected_account}'/<0|1>/"), + }), + ) + })?; + Ok(parsed) +} + +fn parse_transparent_address(encoded: &str, field: &str) -> Result { + ZcashAddress::try_from_encoded(encoded) + .map_err(|_| { + KeysError::with( + ErrorCode::InvalidAddress, + serde_json::json!({ "field": field }), + ) + })? + .convert_if_network(NetworkType::Main) + .map_err(|_| { + KeysError::with( + ErrorCode::InvalidAddress, + serde_json::json!({ "field": field, "network": "main" }), + ) + }) +} + +fn parse_txid(encoded: &str) -> Result { + TxId::from_hex(encoded).ok_or_else(|| { + KeysError::with( + ErrorCode::InvalidOutpoint, + serde_json::json!({ "reason": "invalidTxid" }), + ) + }) +} + +fn parse_positive_zatoshis(encoded: &str, field: &str) -> Result { + let value = encoded.parse::().map_err(|_| amount_error(field))?; + if value == 0 { + return Err(amount_error(field)); + } + parse_zatoshis_u64(value, field) +} + +fn parse_zatoshis_u64(value: u64, field: &str) -> Result { + Zatoshis::from_u64(value).map_err(|_| amount_error(field)) +} + +fn checked_sum(mut values: impl Iterator, field: &str) -> Result { + values + .try_fold(0u64, |sum, value| sum.checked_add(value)) + .ok_or_else(|| amount_error(field)) +} + +fn amount_error(field: &str) -> KeysError { + KeysError::with( + ErrorCode::InvalidAmount, + serde_json::json!({ "field": field }), + ) +} + +fn insufficient_funds(available: u64, required: u64) -> KeysError { + KeysError::with( + ErrorCode::InsufficientFunds, + serde_json::json!({ + "availableZat": available.to_string(), + "requiredZat": required.to_string(), + "shortfallZat": required.saturating_sub(available).to_string(), + }), + ) +} + +fn is_p2pkh_script(script: &[u8]) -> bool { + script.len() == 25 + && script[0] == 0x76 + && script[1] == 0xa9 + && script[2] == 0x14 + && script[23] == 0x88 + && script[24] == 0xac +} + +#[cfg(test)] +mod tests { + use super::*; + + const TEST_MNEMONIC: &str = + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + + fn seed() -> Vec { + bip0039::Mnemonic::::from_phrase(TEST_MNEMONIC) + .unwrap() + .to_seed("") + .to_vec() + } + + fn account_key(seed: &[u8], account: u32) -> AccountPrivKey { + AccountPrivKey::from_seed(&MAIN_NETWORK, seed, AccountId::try_from(account).unwrap()) + .unwrap() + } + + fn address_and_script(seed: &[u8], account: u32, scope: u32, index: u32) -> (String, String) { + let key = account_key(seed, account); + let secret = derive_secret_key( + &key, + DerivationPath { + account, + scope, + index, + }, + ) + .unwrap(); + let mut signing_set = TransparentSigningSet::new(); + let public = signing_set.add_key(secret); + let address = TransparentAddress::from_pubkey(&public); + ( + address.to_zcash_address(NetworkType::Main).to_string(), + hex::encode(address.script().to_bytes()), + ) + } + + fn request_json(values: &[u64], send_max: bool) -> String { + let seed = seed(); + let (recipient, _) = address_and_script(&seed, 0, 0, 9); + let (change, _) = address_and_script(&seed, 0, 1, 0); + let utxos = values + .iter() + .enumerate() + .map(|(i, value)| { + let (_, script) = address_and_script(&seed, 0, 0, i as u32); + serde_json::json!({ + "txid": format!("{:064x}", i + 1), + "vout": i as u32, + "valueZat": value.to_string(), + "scriptPubKey": script, + "isCoinbase": false, + "confirmations": 1, + "derivationPath": format!("m/44'/133'/0'/0/{i}"), + }) + }) + .collect::>(); + let selected = utxos + .iter() + .map(|utxo| serde_json::json!({ "txid": utxo["txid"], "vout": utxo["vout"] })) + .collect::>(); + serde_json::json!({ + "network": "main", + "accountIndex": 0, + "targetHeight": 3_500_000, + "expiryHeight": 3_500_020, + "utxos": utxos, + "selectedOutpoints": selected, + "recipients": [{ + "address": recipient, + "amountZat": if send_max { serde_json::Value::Null } else { serde_json::Value::String("50000".into()) }, + }], + "sendMax": send_max, + "change": if send_max { serde_json::Value::Null } else { serde_json::json!({ + "address": change, + "derivationPath": "m/44'/133'/0'/1/0", + }) }, + }) + .to_string() + } + + #[test] + fn quotes_zip317_for_multiple_inputs() { + let request = request_json(&[30_000, 30_000, 30_000], false); + let quote: TransparentQuote = serde_json::from_str("e_json(&request).unwrap()).unwrap(); + assert_eq!(quote.fee_zat, "15000"); + assert_eq!(quote.input_total_zat, "90000"); + assert_eq!(quote.send_amount_zat, "50000"); + assert_eq!(quote.change_zat, "25000"); + assert_eq!(quote.expiry_height, 3_500_020); + assert_eq!(quote.spent_outpoints.len(), 3); + + let built: TransparentBuildResult = + serde_json::from_str(&build_with_seed_json(&request, &seed()).unwrap()).unwrap(); + assert_eq!(built.fee_zat, "15000"); + assert_eq!(built.spent_outpoints, quote.spent_outpoints); + } + + #[test] + fn quotes_send_max_without_change() { + let quote: TransparentQuote = + serde_json::from_str("e_json(&request_json(&[100_000], true)).unwrap()).unwrap(); + assert_eq!(quote.fee_zat, "10000"); + assert_eq!(quote.send_amount_zat, "90000"); + assert_eq!(quote.change_zat, "0"); + } + + #[test] + fn rejects_coinbase_unconfirmed_and_unknown_inputs() { + let mut request: serde_json::Value = + serde_json::from_str(&request_json(&[100_000], true)).unwrap(); + request["utxos"][0]["isCoinbase"] = true.into(); + let error = quote_json(&request.to_string()).unwrap_err(); + assert_eq!(error.code, ErrorCode::CoinbaseInput); + + request["utxos"][0]["isCoinbase"] = false.into(); + request["utxos"][0]["confirmations"] = 0.into(); + let error = quote_json(&request.to_string()).unwrap_err(); + assert_eq!(error.code, ErrorCode::UnconfirmedInput); + + request["utxos"][0]["confirmations"] = 1.into(); + request["selectedOutpoints"][0]["vout"] = 9.into(); + let error = quote_json(&request.to_string()).unwrap_err(); + assert_eq!(error.code, ErrorCode::UnknownInput); + } + + #[test] + fn rejects_script_and_key_mismatch() { + let mut request: serde_json::Value = + serde_json::from_str(&request_json(&[100_000], true)).unwrap(); + request["utxos"][0]["scriptPubKey"] = + "a914000000000000000000000000000000000000000087".into(); + let error = quote_json(&request.to_string()).unwrap_err(); + assert_eq!(error.code, ErrorCode::UnsupportedInputScript); + + let other_seed = vec![0x42; 64]; + request = serde_json::from_str(&request_json(&[100_000], true)).unwrap(); + let error = build_with_seed_json(&request.to_string(), &other_seed).unwrap_err(); + assert_eq!(error.code, ErrorCode::KeyMismatch); + } + + #[test] + fn enforces_exact_bip44_path() { + let mut request: serde_json::Value = + serde_json::from_str(&request_json(&[100_000], true)).unwrap(); + request["utxos"][0]["derivationPath"] = "m/44'/0'/0'/0/0".into(); + let error = quote_json(&request.to_string()).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidDerivationPath); + + request["utxos"][0]["derivationPath"] = "m/44'/133'/0'/0/0".into(); + request["accountIndex"] = 1.into(); + let error = quote_json(&request.to_string()).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidDerivationPath); + } + + #[test] + fn requires_host_selected_bounded_expiry() { + let mut request: serde_json::Value = + serde_json::from_str(&request_json(&[100_000], true)).unwrap(); + request["expiryHeight"] = 3_500_000.into(); + let error = quote_json(&request.to_string()).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidTargetHeight); + + request["expiryHeight"] = 3_500_101.into(); + let error = quote_json(&request.to_string()).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidTargetHeight); + } + + #[test] + fn supports_p2sh_destination_and_account_xprv() { + let seed = seed(); + let mut request: serde_json::Value = + serde_json::from_str(&request_json(&[100_000], true)).unwrap(); + request["recipients"][0]["address"] = TransparentAddress::ScriptHash([7; 20]) + .to_zcash_address(NetworkType::Main) + .to_string() + .into(); + + let account_key = account_key(&seed, 0); + let mut encoded = XPRV_VERSION.to_vec(); + encoded.extend(account_key.to_bytes()); + let account_xprv = bs58::encode(encoded).with_check().into_string(); + + let from_seed = build_with_seed_json(&request.to_string(), &seed).unwrap(); + let from_xprv = build_with_account_xprv_json(&request.to_string(), &account_xprv).unwrap(); + assert_eq!(from_xprv, from_seed); + + request["accountIndex"] = 1.into(); + let error = build_with_account_xprv_json(&request.to_string(), &account_xprv).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidDerivationPath); + } + + #[test] + fn builds_deterministic_v6_transaction() { + let raw = build_with_seed_json(&request_json(&[100_000], true), &seed()).unwrap(); + let result: TransparentBuildResult = serde_json::from_str(&raw).unwrap(); + assert_eq!(result.fee_zat, "10000"); + assert_eq!(result.expiry_height, 3_500_020); + assert_eq!(result.spent_outpoints.len(), 1); + assert_eq!( + result.raw_tx, + "0600008098b684d85b16a53700000000f4673500010100000000000000000000000000000000000000000000000000000000000000000000006a47304402206be3be8ac1c9bc252843c9ad8a1f1d41f3e7c0716217078f44ecd819f7103bc902202bdd61b62d35d0be08ca15b558fd01d4c076102584a03371d3e064d0b856bea1012103db98d8f87716269ed31879aef19bdadbc869a9ea67729e36332d023b916cbcc9ffffffff01905f0100000000001976a9148d484bcaf1d7993da6db4cca2c1517e1cf020ab788ac00000000" + ); + assert_eq!( + result.txid, + "81004865cdc4217f34aafd1d4b307b3cc5d60fcee7afdb4a829983d394ae39cd" + ); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml new file mode 100644 index 000000000..b0fbd120d --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml @@ -0,0 +1,91 @@ +[package] +name = "onekey-zcash-runtime" +version = "0.0.1" +edition.workspace = true +license.workspace = true +rust-version.workspace = true +description = "OneKey Zcash Runtime — 官方 librustzcash 之上的最薄 wasm 绑定层" + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +zcash_client_backend.workspace = true +zcash_client_sqlite.workspace = true +zcash_keys.workspace = true +zcash_protocol.workspace = true +zcash_primitives.workspace = true +transparent.workspace = true +zcash_address.workspace = true +zip321.workspace = true +pczt.workspace = true +# circuit: Orchard and Ironwood proving. This is the main WASM size cost. +orchard = { workspace = true, features = ["circuit"] } + +rusqlite.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +schemerz.workspace = true +schemerz-rusqlite.workspace = true +rand.workspace = true +rand_chacha.workspace = true +getrandom.workspace = true +tonic.workspace = true +hex.workspace = true +prost.workspace = true +async-trait.workspace = true +futures-util.workspace = true +sapling.workspace = true +uuid.workspace = true + +# wasm32 专属:SQLite 的 wasm 实现与 IndexedDB VFS,以及 JS 互操作。 +# 非 wasm 目标(原生桌面/移动/测试)不需要这些 —— 那里 rusqlite 直接用 +# 系统或 bundled 的 SQLite 即可。 +# 原生目标:给同一个 tonic 追加 transport(feature 是并集,wasm 侧不受影响)。 +# 有了它就能在本机复现浏览器里的问题 —— 原生环境可以上真调试器。 +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +tonic = { workspace = true, features = ["transport", "tls-ring", "tls-webpki-roots"] } +tokio = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +tokio.workspace = true + +[target.'cfg(target_arch = "wasm32")'.dependencies] +sqlite-wasm-rs.workspace = true +sqlite-wasm-vfs.workspace = true +wasm-bindgen.workspace = true +wasm-bindgen-futures.workspace = true +js-sys.workspace = true +gloo-timers.workspace = true +console_error_panic_hook = "0.1" +tracing.workspace = true +tracing-wasm = { workspace = true, optional = true } +tracing-subscriber = { workspace = true, optional = true } +getrandom = { workspace = true, features = ["wasm_js"] } +tonic-web-wasm-client.workspace = true +# 本 crate 不直接用 time —— 打开它只为传递 feature。zcash_client_backend 记 +# `created` 时绕过注入的 Clock,直接调 time::OffsetDateTime::now_utc();不开这个 +# feature 它就落到 SystemTime::now(),而 wasm32-unknown-unknown 上 std 没有时间源, +# 于是 pcztSend 落库时 panic("time not implemented on this platform")。 +time = { version = "0.3", features = ["wasm-bindgen"] } + +[dev-dependencies] +futures = "0.3" + +# wasm-pack 默认跑 `wasm-opt -O`;-Oz 更激进地压体积。 +# 代价是构建慢一些,运行时性能差异对我们这类 IO 密集的负载可忽略。 +[package.metadata.wasm-pack.profile.release] +# 不开 --enable-simd:实测(decrypt-share.html,主网 500 块×2 轮)SIMD128 只快 +# ~2%(曲线库无专门 SIMD 路径,自动向量化吃不到),却抬高老 WebView 的兼容门槛。 +wasm-opt = ["-Oz", "--enable-bulk-memory", "--enable-nontrapping-float-to-int"] + +# 排查用档:保持 cargo 的优化(否则 Halo2 证明慢到不可用),但不跑 wasm-opt —— +# 它会剥掉 name 段,而 wasm 的 panic 栈只有函数序号,没有名字就无从下手。 +[package.metadata.wasm-pack.profile.profiling] +wasm-opt = false + +[features] +# 把 zcash_client_backend 的 tracing 事件转到浏览器 console。 +# 只在排查时开 —— 日志量很大,且会显著拖慢扫描。 +debug-tracing = ["dep:tracing-wasm", "dep:tracing-subscriber"] diff --git a/chain-runtimes/zcash/crates/zcash-runtime/build.rs b/chain-runtimes/zcash/crates/zcash-runtime/build.rs new file mode 100644 index 000000000..f6d86ddaa --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/build.rs @@ -0,0 +1,66 @@ +//! 把 wasm 版 SQLite 接到链接器上。 +//! +//! 背景:`zcash_client_sqlite` 依赖 `rusqlite` → `libsqlite3-sys`。我们取消了 +//! `bundled` feature(见 scripts/vendor-deps.sh),所以 libsqlite3-sys 不再在 +//! 构建期编译 C 源码,转而发出 `-l sqlite3` 让链接器去找现成的库。 +//! +//! 在 wasm32 上这份现成的库由 `sqlite-wasm-rs` 提供,但它产出的归档叫 +//! `libwsqlite3.a`(名字里有个 w)。本脚本把它按链接器要的名字复制一份到我们 +//! 自己的 OUT_DIR,并把该目录加进搜索路径。 +//! +//! 这样调用方不需要任何手工的 RUSTFLAGS —— `cargo build` 直接可用。 + +use std::path::{Path, PathBuf}; + +fn main() { + println!("cargo::rerun-if-changed=build.rs"); + + let target = std::env::var("TARGET").unwrap_or_default(); + if !target.starts_with("wasm32") { + // 原生目标用系统或 bundled 的 SQLite,无需干预。 + return; + } + + let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR 应由 cargo 提供")); + + let Some(src) = find_wasm_sqlite_archive(&out_dir) else { + // 不直接 panic:留一条可读的提示,让链接期的报错有据可查。 + println!( + "cargo::warning=未找到 sqlite-wasm-rs 的 libwsqlite3.a;\ + 若链接期报 `unable to find library -lsqlite3`,请确认 sqlite-wasm-rs \ + 在依赖图中且目标为 wasm32" + ); + return; + }; + + let dst = out_dir.join("libsqlite3.a"); + if let Err(e) = std::fs::copy(&src, &dst) { + println!("cargo::warning=复制 {} 失败: {e}", src.display()); + return; + } + + println!("cargo::rustc-link-search=native={}", out_dir.display()); + println!("cargo::rerun-if-changed={}", src.display()); +} + +/// 从我们的 OUT_DIR 往上找到 `.../build/` 目录,再在里面定位 +/// `sqlite-wasm-rs-*/out/libwsqlite3.a`。 +/// +/// 依赖的构建脚本先于依赖方运行,所以这个文件此刻必然已经存在。 +fn find_wasm_sqlite_archive(out_dir: &Path) -> Option { + // OUT_DIR 形如 target///build/-/out + let build_root = out_dir.parent()?.parent()?; + for entry in std::fs::read_dir(build_root).ok()? { + let Ok(entry) = entry else { continue }; + let name = entry.file_name(); + let name = name.to_string_lossy(); + if !name.starts_with("sqlite-wasm-rs-") { + continue; + } + let candidate = entry.path().join("out").join("libwsqlite3.a"); + if candidate.is_file() { + return Some(candidate); + } + } + None +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs new file mode 100644 index 000000000..5ed459691 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs @@ -0,0 +1,253 @@ +//! 账户导入与读取。 +//! +//! 只做「看账」所需:导入 UFVK、读余额。私钥、地址派生与签名不在这条路径上。 + +use zcash_client_backend::data_api::wallet::ConfirmationsPolicy; +use zcash_client_backend::data_api::{ + Account as _, AccountBirthday, AccountPurpose, WalletRead, WalletWrite, +}; +use zcash_keys::keys::UnifiedFullViewingKey; +use zcash_protocol::consensus::BlockHeight; + +use crate::error::{ErrorCode, Result, RuntimeError}; +use crate::network::{self, LightClient}; +use crate::wallet::Db; +use serde_json::json; + +/// 导入一个只读账户(UFVK)。 +/// +/// `birthday_height` 是「这个账户最早可能收到 note 的高度」。它决定扫描起点, +/// 也决定首次同步要花多久 —— 设成当天的链尖高度,新建账户就几乎不用扫历史。 +/// +/// 需要一次网络往返取 birthday 前一个区块的 treestate。 +pub async fn import_ufvk( + db: &mut Db, + client: &mut LightClient, + account_name: &str, + ufvk_str: &str, + birthday_height: u32, +) -> Result { + let params = *db.params(); + + let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str) + .map_err(|e| RuntimeError::new(ErrorCode::InvalidUfvk).detail(e))?; + + // treestate 取的是 birthday 的前一个区块:账户从 birthday 起开始观察, + // 所以需要「birthday 之前」的树状态作为锚点。 + let anchor_height = birthday_height.saturating_sub(1); + let treestate = network::tree_state(client, anchor_height).await?; + + let birthday = AccountBirthday::from_treestate(treestate, None).map_err(|e| { + RuntimeError::with( + ErrorCode::InvalidBlockHeight, + json!({ "birthdayHeight": birthday_height }), + ) + .detail(format!("{e:?}")) + })?; + + let account = db + .import_account_ufvk( + account_name, + &ufvk, + &birthday, + AccountPurpose::ViewOnly, + None, + ) + .map_err(|e| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "importAccount" }), + ) + .detail(e) + })?; + + Ok(account.id().expose_uuid().to_string()) +} + +/// 账户余额,JSON。`minConfirmations` 为 0 时把未确认也算进来。 +pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) -> Result { + let account_id = parse_account_id(db, account_uuid)?; + + let summary = db.get_wallet_summary(policy).map_err(|e| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "walletSummary" }), + ) + .detail(e) + })?; + + // 还没扫到任何区块时没有摘要。这是一个明确的状态,用错误码表达, + // 不要在返回值里塞中文原因 —— 那是宿主的文案。 + let Some(summary) = summary else { + return Err(RuntimeError::new(ErrorCode::NotSynced)); + }; + + let balances = summary.account_balances().get(&account_id).ok_or_else(|| { + RuntimeError::with( + ErrorCode::AccountNotFound, + json!({ "accountId": account_uuid }), + ) + })?; + + // 每个池各自报全五个量,**不做任何跨池合并**。 + // + // 合并是产品决策,不是事实。比如「可花的屏蔽余额」在本钱包等于 + // orchard + ironwood(sapling 因为裁掉了证明参数只读),但那是钱包当下的 + // 策略,不是链上的性质 —— 焊进 runtime 就意味着策略一变 runtime 就在说谎。 + // 而且合并会抹掉「钱在哪个池」,那恰恰是池明细 UI 要展示的东西。 + // + // 宿主要什么口径的合计,自己加。 + let pool = |b: &zcash_client_backend::data_api::Balance| { + serde_json::json!({ + "spendable": u64::from(b.spendable_value()), + "pendingChange": u64::from(b.change_pending_confirmation()), + "pendingSpendable": u64::from(b.value_pending_spendability()), + // 被某个 PCZT 提案占住的部分(见 send.rs 的 reservation) + "locked": u64::from(b.locked_value()), + "total": u64::from(b.total()), + }) + }; + + let supported_total = [ + balances.orchard_balance(), + balances.ironwood_balance(), + balances.unshielded_regular_balance(), + balances.unshielded_coinbase_balance(), + ] + .into_iter() + .map(|balance| u64::from(balance.total())) + .sum::(); + + Ok(serde_json::json!({ + "ready": true, + "chainTip": u32::from(summary.chain_tip_height()), + "fullyScannedHeight": u32::from(summary.fully_scanned_height()), + + "orchard": pool(balances.orchard_balance()), + "ironwood": pool(balances.ironwood_balance()), + + // 透明余额也分开报:coinbase 有不同的成熟规则,而且只能走 + // `propose_shielding_coinbase` 屏蔽 —— `pcztShield` 用的是 + // NonCoinbaseOnly,屏蔽不到它。并成一个数就看不出这个差别了。 + "transparentRegular": pool(balances.unshielded_regular_balance()), + "transparentCoinbase": pool(balances.unshielded_coinbase_balance()), + + // Sapling is intentionally excluded from both the pool list and the product total. + "total": supported_total, + }) + .to_string()) +} + +/// 从共享库里移除单个账户。 +/// +/// 共享库下删除**不能**是删库 —— 那会连累其他钱包的账户。库只在最后一个账户 +/// 也被删掉之后才该丢弃,那由宿主判断。 +pub fn remove_account(db: &mut Db, account_uuid: &str) -> Result<()> { + let account_id = parse_account_id(db, account_uuid)?; + db.transactionally_with_extension(|wallet, ext| { + wallet.delete_account(account_id).map_err(|e| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "deleteAccount" }), + ) + .detail(e) + })?; + crate::tx_state::remove_account_rows(ext, account_uuid) + }) +} + +/// 按 UFVK 查这个库里的账户,找不到返回 `"null"`。 +/// +/// 共享库下这是**定位账户的唯一正确方式**:一份库装着全部钱包的全部账户, +/// 不能假设第一个就是要找的那个;而 runtime 的 UUID 在 purge 之后会变, +/// 也不能缓存。UFVK 是宿主手上稳定且唯一的键。 +pub fn account_by_ufvk(db: &Db, ufvk_str: &str) -> Result { + let params = *db.params(); + let target = UnifiedFullViewingKey::decode(¶ms, ufvk_str) + .map_err(|e| RuntimeError::new(ErrorCode::InvalidUfvk).detail(e))? + .encode(¶ms); + + for id in db.get_account_ids().map_err(|e| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "getAccountIds" }), + ) + .detail(e) + })? { + let Some(acct) = db.get_account(id).map_err(|e| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "getAccount" }), + ) + .detail(e) + })? + else { + continue; + }; + if acct.ufvk().map(|k| k.encode(¶ms)).as_deref() == Some(target.as_str()) { + return Ok(json!({ "uuid": acct.id().expose_uuid().to_string() }).to_string()); + } + } + Ok("null".to_string()) +} + +/// 列出本地已有账户,JSON 数组。 +pub fn list_accounts_json(db: &Db) -> Result { + let ids = db.get_account_ids().map_err(|e| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "listAccounts" }), + ) + .detail(e) + })?; + let out: Vec = ids.iter().map(|id| id.expose_uuid().to_string()).collect(); + Ok(serde_json::to_string(&out).unwrap_or_else(|_| "[]".into())) +} + +pub fn parse_account_id(db: &Db, account_uuid: &str) -> Result<::AccountId> { + let uuid = uuid_from_str(account_uuid)?; + let id = zcash_client_sqlite::AccountUuid::from_uuid(uuid); + db.get_account(id) + .map_err(|e| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "getAccount" }), + ) + .detail(e) + })? + .map(|a| a.id()) + .ok_or_else(|| { + RuntimeError::with( + ErrorCode::AccountNotFound, + json!({ "accountId": account_uuid }), + ) + }) +} + +fn uuid_from_str(s: &str) -> Result { + uuid::Uuid::parse_str(s).map_err(|e| { + RuntimeError::with(ErrorCode::InvalidAccountId, json!({ "value": s })).detail(e) + }) +} + +/// 高度换算成 `BlockHeight`,越界时给出可读错误。 +pub fn block_height(h: u32) -> BlockHeight { + BlockHeight::from_u32(h) +} + +/// 构造确认数策略。两个门槛都必须 >= 1,且 trusted <= untrusted。 +pub fn confirmations_policy( + trusted: u32, + untrusted: u32, + allow_zero_conf_shielding: bool, +) -> Result { + let bad = || { + RuntimeError::with( + ErrorCode::InvalidConfirmationsPolicy, + json!({ "trusted": trusted, "untrusted": untrusted }), + ) + }; + let t = std::num::NonZeroU32::new(trusted).ok_or_else(bad)?; + let u = std::num::NonZeroU32::new(untrusted).ok_or_else(bad)?; + ConfirmationsPolicy::new(t, u, allow_zero_conf_shielding).map_err(|e| bad().detail(e)) +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs new file mode 100644 index 000000000..854ab0b8e --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs @@ -0,0 +1,885 @@ +//! 面向宿主 JS/TS 的接口。 +//! +//! ## 约定 +//! +//! - 入参与返回值只用 string / number / boolean / JSON 字符串。 +//! - 不把 Rust 对象句柄交给 JS 管生命周期。 +//! - **失败抛的 `Error` 上挂 `code` / `params` / `detail`。** +//! `code` 是稳定错误码,用它做分支;`params` 是结构化参数,用它填 i18n 占位符; +//! `detail` 只用于日志。**这里不产出任何面向用户的文案** —— 文案属于宿主。 +//! - 每个调用都是一次完整往返,不留后台任务、不留定时器。 + +// ── 稳定契约 vs 诊断 ──────────────────────────────────────────────────── +// +// `diag*` 前缀的方法是**排障工具,不是稳定契约**:它们随时可能改签名或消失。 +// 分开命名是为了让依赖它们这件事在调用点就看得见 —— 否则宿主很容易顺手用上, +// 将来想删就变成破坏性升级。 +// +// 其余方法构成钱包契约,改动需要走版本。 + +use wasm_bindgen::prelude::*; + +use crate::perf; +use crate::{ + account, + error::{ErrorCode, RuntimeError}, + history, network, runtime, send, storage, sync, tx_state, wallet, +}; + +// ── 生命周期 ──────────────────────────────────────────────────────────── + +/// 安装存储层。必须在其他任何调用之前 await 一次。幂等。 +#[wasm_bindgen(js_name = init)] +pub async fn init() -> Result<(), JsValue> { + install_panic_hook(); + storage::install_persistent_vfs().await?; + Ok(()) +} + +/// panic 变成带堆栈的 console 错误,而不是一个永远不 settle 的 Promise。 +/// +/// 必须在**每个**入口都装。曾经只装在 `init()` 里,于是走 `initMemoryStorage()` +/// 的排查路径上 panic 完全静默 —— 排查工具本身反而看不见错误。 +fn install_panic_hook() { + console_error_panic_hook::set_once(); +} + +/// 打开 tracing 输出到浏览器 console(需 `debug-tracing` feature)。 +/// +/// 上游 `zcash_client_backend` 全程用 `tracing` 打点。同步卡住时, +/// console 里的**最后一条**日志就指出它停在哪一步 —— 比反复猜快得多。 +/// +/// 日志量很大且会拖慢扫描,只在排查时用。 +#[wasm_bindgen(js_name = diagEnableTracing)] +pub fn enable_debug_tracing() { + #[cfg(feature = "debug-tracing")] + { + use tracing_subscriber::prelude::*; + let _ = tracing_subscriber::registry() + .with(tracing_wasm::WASMLayer::new(Default::default())) + .try_init(); + } +} + +/// 改用**内存存储**:不安装持久化 VFS,数据只活在本页面生命周期内。 +/// +/// 用途:临时/一次性钱包;以及排查时把存储层从纯计算里摘出来 —— +/// 同样的扫描在内存 VFS 上跑一遍,就知道瓶颈在哪一半。 +/// +/// 必须替代 `init()` 调用,不能两个都调。 +#[wasm_bindgen(js_name = diagInitMemoryStorage)] +pub fn init_memory_storage() { + install_panic_hook(); + storage::use_memory_storage(); +} + +/// The capabilities of this version-locked wallet and keys package set. +/// +/// 存在的理由:发送失败得太晚代价很高 —— 提案已经锁了 note,用户已经输过密码, +/// 却在证明阶段才炸。与其让流水线中途失败,不如让按钮一开始就不出现。 +/// +#[wasm_bindgen(js_name = capabilities)] +pub fn capabilities() -> String { + serde_json::json!({ + "prove": { + "orchard": send::PROVE_ORCHARD, + "sapling": send::PROVE_SAPLING, + "ironwood": send::PROVE_IRONWOOD, + }, + "scan": true, + "balance": true, + "history": true, + // The wallet can create the proposal, the prover package attaches proofs, and the keys + // package signs transparent inputs. The host must combine all three capabilities. + "proveShielding": true, + "notes": { + // 说明为什么不通,宿主可以据此给用户不同的提示 + "sapling": "Sapling 不在产品支持范围:不扫描、不展示、不收款、不花费;\ + 证明参数(约 50MB)也不随包分发", + "transparent": "透明输入的签名在 keys 包,本包只负责提案与证明;\ + 「能否屏蔽」要两边的标志同时为真", + }, + }) + .to_string() +} + +/// 本 runtime 锁定的官方依赖版本,JSON 字符串。 +#[wasm_bindgen(js_name = dependencyVersions)] +pub fn dependency_versions() -> String { + crate::dependency_versions().to_string() +} + +/// 诊断:取单个区块的结构摘要。不扫描、不写库、不改任何状态。 +/// +/// 用来确认浏览器(gRPC-web 代理)与原生(真 gRPC)拿到的是不是同一份数据 —— +/// 两边行为不一致时,先排除「数据本来就不同」再谈计算差异。 +#[wasm_bindgen(js_name = diagBlockSummary)] +pub async fn block_summary(height: u32) -> Result { + Ok( + runtime::with_db_and_client(move |db, mut client| async move { + let r = network::block_summary(&mut client, height).await; + (db, client, r) + }) + .await?, + ) +} + +/// 打开(必要时创建)钱包库并把 schema 迁移到当前版本。 +/// +/// 异步是因为要先把这个库从 IndexedDB 读进 VFS。VFS 装的是 `Preload::None` +/// (不预载该 origin 下的全部库),代价就是必须按名字点一次 —— 漏掉这一步, +/// 已存在的库不会出现在文件表里,SQLite 会当成新库重新建表, +/// 于是每次启动都从 birthday 全量重扫,而扫链看上去一切正常。 +#[wasm_bindgen(js_name = openWallet)] +pub async fn open_wallet(network_name: String, db_name: String) -> Result { + let _perf = perf::span("openWallet"); + let (network_name, db_name) = (network_name.as_str(), db_name.as_str()); + storage::preload_database(db_name).await?; + let db = wallet::open_and_migrate(network_name, db_name)?; + // 有异步操作在进行时这里会拒绝(WALLET_BUSY)—— 必须传播出去, + // 否则调用方会以为库已经换了,而实际上还是旧的。 + runtime::set_db(db, db_name)?; + Ok(serde_json::json!({ "dbName": db_name, "network": network_name }).to_string()) +} + +/// 关闭钱包,释放数据库与网络客户端。 +/// +/// 有异步操作在进行时抛 `WALLET_BUSY`:那次操作手上还握着数据库, +/// 此刻关闭只会让它结束后把一个本该消失的钱包放回来。 +/// 临时性能打点开关:打开后重导出逐个打耗时到 console(`[PRIV-PERF] rt`)。 +#[wasm_bindgen(js_name = setPerfTrace)] +pub fn set_perf_trace(enabled: bool) { + perf::set_enabled(enabled); +} + +#[wasm_bindgen(js_name = closeWallet)] +pub fn close_wallet() -> Result<(), JsValue> { + Ok(runtime::close()?) +} + +/// 配置 lightwalletd 端点,形如 `https://host:port`。 +/// +/// 端点由宿主决定 —— 本 runtime 不硬编码任何服务器地址。 +/// 注意该端点必须支持 gRPC-web 与 CORS,否则浏览器侧会以网络错误失败。 +#[wasm_bindgen(js_name = setLightwalletdUrl)] +pub fn set_lightwalletd_url(base_url: &str) -> Result<(), JsValue> { + runtime::set_client(network::connect(base_url)?); + Ok(()) +} + +// ── 链信息 ────────────────────────────────────────────────────────────── + +/// 当前链尖高度。**不需要先打开钱包库** —— 只需要先 `setLightwalletdUrl`。 +/// +/// 建账户时宿主要靠它定 birthday,而那一刻库还不存在;若要求先开库, +/// 这一步必然失败,birthday 就会退回 Sapling 激活高度,新助记词也要全量扫。 +#[wasm_bindgen(js_name = chainTip)] +pub async fn chain_tip() -> Result { + Ok(runtime::with_client(|mut client| async move { + let r = network::chain_tip(&mut client).await; + (client, r) + }) + .await?) +} + +/// Fetches the current chain tip with an isolated client. +/// +/// Host-side birthday and scheduler probes must not replace the wallet's +/// global client while a sync operation has borrowed it across an await. +#[wasm_bindgen(js_name = chainTipAt)] +pub async fn chain_tip_at(base_url: String) -> Result { + let mut client = network::connect(&base_url)?; + Ok(network::chain_tip(&mut client).await?) +} + +// ── 账户 ──────────────────────────────────────────────────────────────── + +/// 导入一个只读账户(UFVK),返回账户 UUID。 +/// +/// `birthdayHeight` 决定扫描起点。新建账户传当前链尖高度,首次同步几乎不用扫历史; +/// 恢复钱包必须传足够早的高度,否则会漏掉历史资金 —— **这个决策属于宿主**。 +#[wasm_bindgen(js_name = importAccountUfvk)] +pub async fn import_account_ufvk( + account_name: String, + ufvk: String, + birthday_height: u32, +) -> Result { + Ok( + runtime::with_db_and_client(move |mut db, mut client| async move { + let r = + account::import_ufvk(&mut db, &mut client, &account_name, &ufvk, birthday_height) + .await; + (db, client, r) + }) + .await?, + ) +} + +/// 从共享库里移除单个账户。**不删库** —— 库还装着其他钱包的账户。 +#[wasm_bindgen(js_name = removeAccount)] +pub async fn remove_account(account_uuid: String) -> Result<(), JsValue> { + let has_unsettled_outgoing = + runtime::with_read_conn(|conn| history::has_unsettled_outgoing(conn, &account_uuid))?; + let has_unresolved_broadcast = runtime::with_read_conn(|conn| { + tx_state::unresolved_txids(conn, &account_uuid).map(|txids| !txids.is_empty()) + })?; + let has_active_reservation = send::has_active_reservations(&account_uuid); + if has_active_reservation || has_unsettled_outgoing || has_unresolved_broadcast { + return Err(crate::RuntimeError::with( + crate::ErrorCode::WalletBusy, + serde_json::json!({ + "operation": "removeAccount", + "activeReservation": has_active_reservation, + "unsettledOutgoing": has_unsettled_outgoing, + "unresolvedBroadcast": has_unresolved_broadcast, + }), + ) + .into()); + } + runtime::with_db(|db| account::remove_account(db, &account_uuid))?; + storage::durability_barrier().await?; + Ok(()) +} + +/// 按 UFVK 定位这个库里的账户,返回 `{ uuid }`,找不到返回 `"null"`。 +/// +/// 共享库(每 network 一份,装全部钱包的全部账户)下,这是定位账户的唯一 +/// 正确方式:不能假设第一个就是要找的那个,UUID 又会在 purge 后变化。 +#[wasm_bindgen(js_name = accountByUfvk)] +pub fn account_by_ufvk(ufvk: String) -> Result { + let _perf = perf::span("accountByUfvk"); + Ok(runtime::with_db(|db| account::account_by_ufvk(db, &ufvk))?) +} + +/// 每个账户各自的同步完成度,从「该账户 birthday + 全库剩余待扫区间」推导。 +/// +/// 共享库下全局进度会误导:新加一个账户会让**所有**账户看起来都没同步完。 +/// 官方 schema 没有 per-account 游标,也不该为此改 schema(见 D15), +/// 所以这里只读推导,零 schema 改动。 +/// +/// 返回纯块高,不给百分比 —— 进度比例的分母是移动窗口里的 note 数, +/// 永远到不了 100%,显示出来像坏了。 +#[wasm_bindgen(js_name = accountSyncStatus)] +pub fn account_sync_status(account_uuid: String) -> Result { + Ok(runtime::with_db(|db| { + sync::account_status(db, &account_uuid) + })?) +} + +/// 列出本地账户的 UUID,JSON 数组。 +#[wasm_bindgen(js_name = listAccounts)] +pub fn list_accounts() -> Result { + Ok(runtime::with_db(|db| account::list_accounts_json(db))?) +} + +/// 账户余额,JSON。 +/// +/// `trusted` / `untrusted` 是确认数门槛(均 >= 1,且 trusted <= untrusted): +/// 自己找零的 note 可以宽松,外来的应更保守。具体取值是产品决策,由宿主传。 +/// 尚未同步到任何区块时抛 `NOT_SYNCED`。 +#[wasm_bindgen(js_name = accountBalance)] +pub fn account_balance( + account_uuid: String, + trusted: u32, + untrusted: u32, + allow_zero_conf_shielding: bool, +) -> Result { + let _perf = perf::span("accountBalance"); + let policy = account::confirmations_policy(trusted, untrusted, allow_zero_conf_shielding)?; + Ok(runtime::with_db(|db| { + account::balance_json(db, &account_uuid, policy) + })?) +} + +// ── 扫链 ──────────────────────────────────────────────────────────────── + +/// 同步前的一次性准备:下载三个池的子树根、更新链尖。 +/// +/// **这是首次同步最慢的一步**,与 batchSize 无关。单独暴露是为了让宿主 +/// 能给出「正在准备」的独立进度,而不是干等一个不返回的调用。 +/// +/// 返回 `{ chainTip, saplingSubtrees, orchardSubtrees, ironwoodSubtrees }`。 +/// 每轮同步开始时调一次即可。 +#[wasm_bindgen(js_name = syncPrepare)] +pub async fn sync_prepare() -> Result { + let _perf = perf::span("syncPrepare"); + Ok( + runtime::with_db_and_client(|mut db, mut client| async move { + let r = sync::prepare(&mut db, &mut client).await; + (db, client, r) + }) + .await?, + ) +} + +/// 只更新链尖(一个 unary 调用,主网实测 ~270ms)。返回 `{ chainTip }`。 +/// +/// 每轮同步用它;子树根走 `syncPrepare`,开库后一次即可 —— 那 1900 条根 +/// 是凝固的历史,每轮重下就是主网每轮多出 7 秒的来源。 +#[wasm_bindgen(js_name = syncTip)] +pub async fn sync_tip() -> Result { + Ok( + runtime::with_db_and_client(|mut db, mut client| async move { + let r = sync::tip(&mut db, &mut client).await; + (db, client, r) + }) + .await?, + ) +} + +/// 刷新账户的透明 UTXO。**必须单独调**。 +/// +/// 扫区块只产出屏蔽 note;透明 UTXO 在链上是公开的,要按地址向 lightwalletd 查。 +/// 不调的后果是静默的:透明余额恒为 0、屏蔽按钮永远说「没有可屏蔽的钱」, +/// 而扫链看起来一切正常。 +#[wasm_bindgen(js_name = syncTransparentUtxos)] +pub async fn sync_transparent_utxos(account_uuid: String) -> Result { + Ok( + runtime::with_db_and_client(move |mut db, mut client| async move { + let r = sync::refresh_transparent_utxos(&mut db, &mut client, &account_uuid).await; + (db, client, r) + }) + .await?, + ) +} + +/// 只读查看待扫区间,**不发网络请求**。返回 +/// `{ ranges: [{ start, end, len, priority }], totalBlocks }`。 +/// +/// 给宿主做进度条用;同步异常时也用它确认钱包想扫哪一段。 +#[wasm_bindgen(js_name = syncPeek)] +pub fn sync_peek() -> Result { + Ok(runtime::with_db(|db| sync::peek(db))?) +} + +/// 诊断:只下载不扫描,返回各阶段耗时。**不改变钱包状态。** +/// +/// 同步在浏览器里卡住时,网络挂和扫描挂的表现一样(页面无响应), +/// 但成因不同。先用这个确认网络这一半是好的,再去查扫描。 +#[wasm_bindgen(js_name = diagProbeDownload)] +pub async fn sync_probe_download(batch_size: u32) -> Result { + Ok( + runtime::with_db_and_client(move |db, mut client| async move { + let r = sync::probe_download(&db, &mut client, batch_size).await; + (db, client, r) + }) + .await?, + ) +} + +/// 只报价、不构造交易、不锁定 note。返回 `{ feeZat, steps }`。 +/// +/// 与 `pcztCreate` 共用同一条提案路径,所以报出来的费用就是实付的费用。 +/// 余额不足同样抛 `INSUFFICIENT_FUNDS`(带 shortfallZat),宿主可据此提示。 +#[wasm_bindgen(js_name = pcztQuote)] +pub fn pczt_quote( + account_uuid: String, + to_address: String, + amount_zat: u64, + memo: Option, + trusted: u32, + untrusted: u32, + fallback_change_pool: String, + spend_transparent: Option, + allow_zero_conf_shielding: Option, + spend_source: Option, +) -> Result { + let pool = send::parse_change_pool(&fallback_change_pool)?; + // 报价必须和真正发送用同一套选币规则,否则报出来的费用不是实付的费用。 + // spend_source 也在其中:限定池子会换掉被选中的 note,费用随之不同。 + let policy = send::SendPolicy { + trusted, + untrusted, + fallback_change_pool: pool, + pad_orchard_bundle: false, + spend_transparent: spend_transparent.unwrap_or(false), + allow_zero_conf_shielding: allow_zero_conf_shielding.unwrap_or(false), + spend_source: send::parse_spend_source(spend_source.as_deref())?, + }; + Ok(runtime::with_db(|db| { + send::quote( + db, + &account_uuid, + &to_address, + amount_zat, + memo.as_deref(), + policy, + ) + })?) +} + +/// 单笔交易详情,JSON。钱包里没有这笔时返回 `"null"` 而不是报错 —— +/// 「不在钱包里」是正常状态(外部 txid、被回滚的交易),不是故障。 +#[wasm_bindgen(js_name = transactionDetails)] +pub fn transaction_details(account_uuid: String, txid: String) -> Result { + let _perf = perf::span("transactionDetails"); + Ok(runtime::with_read_conn(|conn| { + history::details(conn, &account_uuid, &txid) + })?) +} + +/// 单笔交易的逐笔明细:`{ txid, spent[], received[], external[] }`。 +/// +/// 与 `transactionDetails` 的区别:那个给的是聚合事实(金额增量、笔数), +/// 这个给的是每一笔输出的明细(金额、池、是否找零、memo、地址)。 +/// 交易详情页要后者,列表要前者。 +#[wasm_bindgen(js_name = transactionOutputs)] +pub fn transaction_outputs(account_uuid: String, txid: String) -> Result { + Ok(runtime::with_read_conn(|conn| { + history::details_outputs(conn, &account_uuid, &txid) + })?) +} + +/// 有界推进扫描:最多 `maxBatches` 批,每批 `batchSize` 个区块。 +/// +/// `priority` 决定推进哪条 lane:`"chainTip"` 追新块、`"historic"` 回填历史、 +/// 不传或 `"any"` 则按上游给的顺序。**候选区间只能来自上游的建议**,宿主无法 +/// 指定任意高度 —— 调度选择归宿主,扫哪些区间安全仍归协议实现。 +/// +/// `activeUfvksJson` is a required JSON string array. Only those identities are used for +/// Orchard/Ironwood trial decryption. An empty array fails with `NO_ACTIVE_ACCOUNTS`; it never +/// falls back to every account stored in the runtime database. +/// +/// 返回里带 `scannedFrom/scannedTo/scannedPriority`,宿主才能把进度归到正确的 lane。 +/// +/// **本函数永远不会自己循环到同步完成。** 返回 +/// `{ done, batchesDone, blocksScanned, remainingBlocks, remainingRanges }`, +/// 宿主据此显示进度并决定是否继续调 —— 调度归宿主。 +#[wasm_bindgen(js_name = syncStep)] +pub async fn sync_step( + batch_size: u32, + max_batches: u32, + priority: Option, + active_ufvks_json: String, +) -> Result { + let _perf = perf::span("syncStep"); + let preferred = sync::parse_priority(priority.as_deref().unwrap_or(""))?; + let active_ufvks: Vec = serde_json::from_str(&active_ufvks_json).map_err(|e| { + RuntimeError::new(ErrorCode::InvalidUfvk).detail(format!("activeUfvksJson: {e}")) + })?; + Ok( + runtime::with_db_and_client(move |mut db, mut client| async move { + let r = sync::step( + &mut db, + &mut client, + batch_size, + max_batches, + preferred, + &active_ufvks, + ) + .await; + (db, client, r) + }) + .await?, + ) +} + +// ── 交易历史 ──────────────────────────────────────────────────────────── + +/// 分页读取交易历史,JSON 数组。未上链的排最前,其余按高度倒序。 +/// +/// 返回的是**中性事实**(金额增量、是否找零、note 计数、时间戳), +/// 不含「收入/支出」这类判定,也不含任何文案 —— 展示模型属于宿主。 +/// +/// `limit` 上限 500,超出抛 `INVALID_BATCH_SIZE`。 +#[wasm_bindgen(js_name = transactionHistory)] +pub fn transaction_history( + account_uuid: String, + limit: u32, + offset: u32, +) -> Result { + let _perf = perf::span("transactionHistory"); + Ok(runtime::with_read_conn(|conn| { + history::list(conn, &account_uuid, limit, offset) + })?) +} + +// ── 发送 ──────────────────────────────────────────────────────────────── + +/// 回退钱包到指定高度,让之后的同步重扫这段区间。 +/// +/// **破坏性**:该高度之上的扫描结果会被丢弃。返回实际回退到的高度 +/// (上游可能因承诺树检查点位置退得更靠前)。 +#[wasm_bindgen(js_name = rewindTo)] +pub fn rewind_to(height: u32) -> Result { + Ok(runtime::with_db(|db| sync::rewind_to(db, height))?) +} + +/// Re-queue `[fromHeight, chainTip]` as historic work without deleting cached notes or history. +/// +/// This is the resume companion to `syncStep(activeUfvksJson)`: the host persists each privacy +/// identity's pause cursor, applies its reorg margin, queues the missing range, and only then adds +/// the identity back to the active UFVK set. +#[wasm_bindgen(js_name = queueRescanFrom)] +pub fn queue_rescan_from(from_height: u32) -> Result { + Ok(runtime::with_db(|db| { + sync::queue_rescan_from(db, from_height) + })?) +} + +// ── 发送 ──────────────────────────────────────────────────────────────── +// +// 完整流程:pcztCreate → pcztProve → (keys 包)pcztSign → pcztSend +// +// 证明在签名之前还是之后都可以(两者作用于 PCZT 的不同部分), +// 但**都必须在 pcztSend 之前完成**,否则交易无效。 + +/// 构造一笔转账的 PCZT(未证明、未签名),返回字节。 +/// +/// `fallbackChangePool`: 当前产品固定传 `"ironwood"`,交易找零进入最新隐私池。 +/// `padOrchardBundle`: 是否填充 Orchard bundle 隐藏真实 action 数(更大、费更高)。 +#[wasm_bindgen(js_name = pcztCreate)] +pub fn pczt_create( + account_uuid: String, + to_address: String, + amount_zat: u64, + memo: Option, + trusted: u32, + untrusted: u32, + fallback_change_pool: String, + pad_orchard_bundle: bool, + lock_for_blocks: u32, + reservation_id: Option, + spend_transparent: Option, + allow_zero_conf_shielding: Option, + spend_source: Option, +) -> Result { + let pool = send::parse_change_pool(&fallback_change_pool)?; + let policy = send::SendPolicy { + trusted, + untrusted, + fallback_change_pool: pool, + pad_orchard_bundle, + spend_transparent: spend_transparent.unwrap_or(false), + allow_zero_conf_shielding: allow_zero_conf_shielding.unwrap_or(false), + spend_source: send::parse_spend_source(spend_source.as_deref())?, + }; + Ok(runtime::with_db(|db| { + let (bytes, reservation_id, fee_zat) = send::create_pczt( + db, + &account_uuid, + &to_address, + amount_zat, + memo.as_deref(), + policy, + lock_for_blocks, + reservation_id.as_deref(), + )?; + Ok(serde_json::json!({ + "pcztHex": bytes.iter().map(|b| format!("{b:02x}")).collect::(), + "reservationId": reservation_id, + "feeZat": fee_zat, + }) + .to_string()) + })?) +} + +/// 生成 Orchard / Ironwood 零知识证明。**必须在 pcztSend 之前做**。 +#[wasm_bindgen(js_name = pcztProve)] +pub fn pczt_prove(pczt_bytes: Vec) -> Result, JsValue> { + Ok(runtime::with_db(|db| send::prove_pczt(db, &pczt_bytes))?) +} + +/// 构造「屏蔽全部透明余额」的 PCZT,返回 `{ pcztHex, reservationId }`。 +/// +/// 没有收款地址、没有金额:收款方是本账户自己的屏蔽地址,金额是全部透明余额。 +/// 之后的 prove / sign / send / broadcast 与普通转账完全一样。 +/// +/// `shieldingThresholdZat` 是宿主策略:透明余额低于它就不值得屏蔽(手续费可能 +/// 比金额还高)。低于阈值时抛 `INSUFFICIENT_FUNDS`。 +#[wasm_bindgen(js_name = pcztShield)] +pub fn pczt_shield( + account_uuid: String, + shielding_threshold_zat: u64, + trusted: u32, + untrusted: u32, + fallback_change_pool: String, + pad_orchard_bundle: bool, + lock_for_blocks: u32, + reservation_id: Option, + allow_zero_conf_shielding: Option, +) -> Result { + let pool = send::parse_change_pool(&fallback_change_pool)?; + let policy = send::SendPolicy { + trusted, + untrusted, + fallback_change_pool: pool, + pad_orchard_bundle, + // 屏蔽按定义就是花透明输入。这里不读这个字段(屏蔽路径有自己的选币器), + // 写 true 是为了字段语义诚实,将来谁去读它也拿到对的值。 + spend_transparent: true, + allow_zero_conf_shielding: allow_zero_conf_shielding.unwrap_or(false), + // 同上:屏蔽不从屏蔽池取 note,源池子这个概念在这条路径上不适用。 + spend_source: None, + }; + Ok(runtime::with_db(|db| { + let (bytes, reservation_id, fee_zat) = send::create_shielding_pczt( + db, + &account_uuid, + shielding_threshold_zat, + policy, + lock_for_blocks, + reservation_id.as_deref(), + )?; + Ok(serde_json::json!({ + "pcztHex": bytes.iter().map(|b| format!("{b:02x}")).collect::(), + "reservationId": reservation_id, + "feeZat": fee_zat, + }) + .to_string()) + })?) +} + +/// Exact shielding fee from the same proposal path as `pcztShield`, without +/// locking inputs or constructing a transaction. +#[wasm_bindgen(js_name = pcztShieldQuote)] +pub fn pczt_shield_quote( + account_uuid: String, + shielding_threshold_zat: u64, + trusted: u32, + untrusted: u32, + fallback_change_pool: String, + pad_orchard_bundle: bool, + allow_zero_conf_shielding: Option, +) -> Result { + let pool = send::parse_change_pool(&fallback_change_pool)?; + let policy = send::SendPolicy { + trusted, + untrusted, + fallback_change_pool: pool, + pad_orchard_bundle, + spend_transparent: true, + allow_zero_conf_shielding: allow_zero_conf_shielding.unwrap_or(false), + spend_source: None, + }; + Ok(runtime::with_db(|db| { + let fee_zat = send::quote_shielding(db, &account_uuid, shielding_threshold_zat, policy)?; + Ok(serde_json::json!({ "feeZat": fee_zat }).to_string()) + })?) +} + +/// 释放该账户**全部**被锁的 note,返回解锁数量。 +/// +/// 崩溃恢复用:`releaseReservation` 靠内存里的提案表定位,app / offscreen 重启后 +/// 那张表没了,旧 token 既解不开也不知道锁了什么。 +/// +/// **会连带放开进行中的提案**,所以只能由用户主动触发的「修复」动作调用, +/// 不要放进正常流程。 +#[wasm_bindgen(js_name = clearLockedOutputs)] +pub fn clear_locked_outputs(account_uuid: String) -> Result { + Ok(runtime::with_db(|db| { + send::clear_locked_outputs(db, &account_uuid) + })?) +} + +/// 释放一次 reservation 占用的 note(用户取消发送时调)。 +/// +/// 幂等:id 已发送 / 已释放 / 从未存在时返回 `false` 而不报错 —— +/// 取消路径上重复调用是常态,不该因此给用户弹错误。 +#[wasm_bindgen(js_name = releaseReservation)] +pub fn release_reservation(reservation_id: String) -> Result { + Ok(runtime::with_db(|db| { + send::release_reservation(db, &reservation_id) + })?) +} + +/// 终结已证明且已签名的 PCZT,提取交易并**写回本地钱包**,返回 txid。 +/// +/// **这一步不发网络。** 交易还没有广播出去,必须再调 `broadcastTransaction(txid)`。 +/// 两步分开,是为了让宿主能在落库之后、真正发出去之前插入确认环节, +/// 也能在广播失败时原样重试而不必重建交易。 +#[wasm_bindgen(js_name = pcztSend)] +pub async fn pczt_send( + account_uuid: String, + pczt_bytes: Vec, + reservation_id: String, +) -> Result { + let txid = runtime::with_db(|db| { + send::extract_and_store(db, &account_uuid, &pczt_bytes, &reservation_id) + })?; + // Once extract_and_store commits, the transaction itself owns the spent + // notes. Drop the proposal before the durability barrier: a barrier error + // means the host does not know whether persistence reached durable storage, + // but it must never be allowed to unlock inputs that may already be spent. + send::forget_reservation(&reservation_id); + storage::durability_barrier().await.map_err(|error| { + crate::RuntimeError::with( + crate::ErrorCode::FinalizeOutcomeUnknown, + serde_json::json!({ "operation": "finalizeTransaction" }), + ) + .detail(error) + })?; + Ok(txid) +} + +/// Runtime-owned unresolved broadcast intents for this account. The host uses +/// this only to fail closed before constructing another payment; it does not +/// persist or reinterpret the returned transaction IDs. +#[wasm_bindgen(js_name = pendingBroadcastTxids)] +pub fn pending_broadcast_txids(account_uuid: String) -> Result { + let txids = runtime::with_read_conn(|conn| tx_state::unresolved_txids(conn, &account_uuid))?; + Ok(serde_json::to_string(&txids).map_err(|error| { + crate::RuntimeError::with( + crate::ErrorCode::DatabaseError, + serde_json::json!({ "operation": "serializePendingBroadcasts" }), + ) + .detail(error) + })?) +} + +#[wasm_bindgen(js_name = broadcastRetryTxids)] +pub fn rebroadcastable_txids(account_uuid: String) -> Result { + let txids = + runtime::with_read_conn(|conn| tx_state::rebroadcastable_txids(conn, &account_uuid))?; + Ok(serde_json::to_string(&txids).map_err(|error| { + crate::RuntimeError::with( + crate::ErrorCode::DatabaseError, + serde_json::json!({ "operation": "serializeRebroadcastableTransactions" }), + ) + .detail(error) + })?) +} + +/// 把 `pcztSend` 落库的交易广播到 lightwalletd。**不可逆。** +/// +/// 节点拒绝抛 `BROADCAST_REJECTED`(不要重试,先查原因); +/// 网络本身出错抛 `NETWORK_ERROR`(可以重试,交易已在本地库里)。 +#[wasm_bindgen(js_name = broadcastTransaction)] +pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> { + let result = runtime::with_db_and_client(move |mut db, mut client| async move { + let r = match tx_state::assert_broadcastable(&mut db, &txid) + .and_then(|_| send::raw_transaction(&db, &txid)) + { + Ok(raw) => network::broadcast(&mut client, raw).await, + Err(e) => Err(e), + }; + let r = match r { + Ok(()) => tx_state::mark_accepted(&mut db, &txid), + Err(e) if e.code == crate::ErrorCode::BroadcastRejected => { + match tx_state::mark_rejected(&mut db, &txid, &e) { + Ok(()) => Err(e), + Err(persist_error) => Err(persist_error), + } + } + Err(e) => Err(e), + }; + (db, client, r) + }) + .await; + let changed_lifecycle = result.is_ok() + || result + .as_ref() + .is_err_and(|error| error.code == crate::ErrorCode::BroadcastRejected); + if changed_lifecycle { + storage::durability_barrier().await?; + } + Ok(result?) +} + +// ── 自检 ──────────────────────────────────────────────────────────────── + +/// 删除一个钱包库(连同 IndexedDB 里的字节)。**不可逆。** +/// +/// 库是纯派生缓存:UFVK 与 birthday 由宿主保管,不在库里,所以删掉只是要重扫。 +/// 用途一是出问题时手动重置,用途二是删账户时清掉已解密的屏蔽历史。 +/// +/// 若删的正是当前打开的库,会先自动关闭 —— 底层要求删除前库必须已关闭。 +/// 返回 `true` 表示确实删掉了,`false` 表示本来就不存在(不算错误)。 +#[wasm_bindgen(js_name = deleteWallet)] +pub async fn delete_wallet(db_name: String) -> Result { + if runtime::open_db_name().as_deref() == Some(db_name.as_str()) { + runtime::close()?; + } + Ok(storage::delete_database(&db_name).await?) +} + +/// 当前钱包库的用量,按数据语义分组。**只读,不改任何数据。** +/// +/// 这是**稳定契约**,不是 `diag*` —— 宿主要靠它做容量守卫(比如超过软阈值就 +/// 停掉 birthday 回填),那属于产品行为,不能建立在随时会消失的排障接口上。 +/// +/// `logicalBytes` 是页数 × 页大小,**不等于 IndexedDB 的物理占用**:那边有写 +/// 放大、旧版本页和异步刷盘。两个数不该互相外推。 +/// +/// 刻意不提供「执行任意 SQL」:一条写错的语句就能删掉仍待证明的 anchor。 +#[wasm_bindgen(js_name = storageStats)] +pub fn storage_stats() -> Result { + let db_name = runtime::open_db_name() + .ok_or_else(|| JsValue::from(crate::RuntimeError::new(crate::ErrorCode::WalletNotOpen)))?; + let conn = storage::open_connection(&db_name)?; + Ok(crate::stats::storage_stats(&conn)?) +} + +/// Diagnostic: checks for persisted bytes without opening or creating a database. +#[wasm_bindgen(js_name = diagDatabaseExists)] +pub async fn database_exists(db_name: &str) -> Result { + Ok(storage::database_exists(db_name).await?) +} + +/// Diagnostic: runs bounded, read-only consistency checks on the open database. +#[wasm_bindgen(js_name = diagDatabaseHealth)] +pub fn database_health() -> Result { + Ok(runtime::with_read_conn(crate::stats::database_health)?) +} + +/// 诊断:数一份 PCZT 里各 bundle 有多少输入。 +/// +/// 用来回答「这笔钱是从哪个池出去的」——费用差只能间接推断,输入个数是直接证据。 +/// 判断 `spendTransparent` 会不会让一笔本可全屏蔽的交易混进公开输入,靠的就是它。 +#[wasm_bindgen(js_name = diagPcztInputCounts)] +pub fn pczt_input_counts(pczt_bytes: Vec) -> Result { + let pczt = pczt::Pczt::parse(&pczt_bytes).map_err(|e| { + JsValue::from( + crate::RuntimeError::new(crate::ErrorCode::PcztError).detail(format!("{e:?}")), + ) + })?; + // action 个数单独看会骗人:Orchard/Ironwood 的 action 是「花费+输出」成对的, + // 而且 bundle 会补 dummy 凑到最少 2 个。所以「有 2 个 action」既可能是真花了 + // 屏蔽 note,也可能只是找零输出加一个 dummy。 + // + // `valueSum` = 该池的花费减输出(负号单独给出)。为负说明净流入这个池 + // (只收了找零),为正才说明真的花了这个池里的 note。 + let sum = |b: &pczt::orchard::Bundle| { + let (magnitude, negative) = *b.value_sum(); + serde_json::json!({ "magnitude": magnitude, "negative": negative }) + }; + // 透明输入的**金额**才是判断有没有混合的可靠依据: + // 屏蔽花费额 = 付款额 + 手续费 − 透明输入额。`valueSum` 只给净流向, + // 净流入为负并不等于零花费 —— 一笔交易完全可以既有真实屏蔽花费又净流入。 + let transparent_value: u64 = pczt.transparent().inputs().iter().map(|i| *i.value()).sum(); + + Ok(serde_json::json!({ + "transparent": pczt.transparent().inputs().len(), + "transparentValue": transparent_value, + "sapling": pczt.sapling().spends().len(), + "orchard": pczt.orchard().actions().len(), + "ironwood": pczt.ironwood().actions().len(), + "orchardValueSum": sum(pczt.orchard()), + "ironwoodValueSum": sum(pczt.ironwood()), + }) + .to_string()) +} + +/// 自检:打开库、跑完迁移,回报建出来的表 / 视图 / 索引数量。 +#[wasm_bindgen(js_name = diagSelfCheck)] +pub fn self_check(network_name: &str, db_name: &str) -> Result { + drop(wallet::open_and_migrate(network_name, db_name)?); + let conn = storage::open_connection(db_name)?; + + let count_of = |kind: &str| -> Result { + conn.query_row( + "SELECT COUNT(*) FROM sqlite_master WHERE type = ?1", + [kind], + |r| r.get(0), + ) + .map_err(|e| JsValue::from(crate::RuntimeError::from(e))) + }; + + Ok(serde_json::json!({ + "tables": count_of("table")?, + "views": count_of("view")?, + "indexes": count_of("index")?, + "versions": crate::dependency_versions(), + }) + .to_string()) +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs new file mode 100644 index 000000000..f9ad23f88 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs @@ -0,0 +1,259 @@ +//! 内存版 compact block 缓存。 +//! +//! `zcash_client_backend::sync::run` 需要一个 `BlockCache`,官方在 +//! `zcash_client_sqlite` 里提供的是文件系统版(`FsBlockDb`),浏览器用不了。 +//! +//! 这里用内存实现,理由是 compact block 是**过程性数据**:下载 → 扫描 → 用完即弃。 +//! 真正需要持久化的是扫描结果(note、witness、承诺树),那些由 `zcash_client_sqlite` +//! 写进 SQLite,已经落在 IndexedDB 上。 +//! +//! 内存占用受 `sync::run` 的 `batch_size` 约束:一次只保留正在扫的那一批。 + +use std::collections::BTreeMap; +use std::ops::Range; +use std::sync::Mutex; + +use zcash_client_backend::data_api::chain::{error, BlockCache, BlockSource}; +use zcash_client_backend::data_api::scanning::ScanRange; +use zcash_client_backend::proto::compact_formats::CompactBlock; +use zcash_protocol::consensus::BlockHeight; + +#[derive(Debug)] +pub struct MemoryBlockCache { + blocks: Mutex>, +} + +impl Default for MemoryBlockCache { + fn default() -> Self { + Self::new() + } +} + +impl MemoryBlockCache { + pub fn new() -> Self { + Self { + blocks: Mutex::new(BTreeMap::new()), + } + } + + /// 当前缓存的区块数量,供宿主观测内存占用。 + pub fn len(&self) -> usize { + self.blocks.lock().map(|b| b.len()).unwrap_or(0) + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + fn range_of(range: &ScanRange) -> Range { + let r = range.block_range(); + u32::from(r.start)..u32::from(r.end) + } +} + +/// 缓存自身的错误。内存实现里唯一可能的失败是锁中毒。 +#[derive(Debug)] +pub struct CacheError(pub String); + +impl std::fmt::Display for CacheError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "block cache: {}", self.0) + } +} + +impl std::error::Error for CacheError {} + +fn poisoned() -> CacheError { + CacheError("内部锁中毒(上一次持锁时发生了 panic)".into()) +} + +impl BlockSource for MemoryBlockCache { + type Error = CacheError; + + fn with_blocks( + &self, + from_height: Option, + limit: Option, + mut with_block: F, + ) -> Result<(), error::Error> + where + F: FnMut(CompactBlock) -> Result<(), error::Error>, + { + // 先在持锁时把需要的区块**收集出来**,再释放锁,最后才执行回调。 + // + // 不能在持锁期间调 `with_block` —— 回调会写钱包库,而上游有可能在那条 + // 路径上再次读取本缓存。`std::sync::Mutex` 不可重入,同一线程二次加锁 + // 在 wasm 单线程环境下就是永久死锁。 + let selected: Vec = { + let blocks = self + .blocks + .lock() + .map_err(|_| error::Error::BlockSource(poisoned()))?; + + let start = from_height.map(u32::from).unwrap_or(0); + let iter = blocks.range(start..).map(|(_, b)| b.clone()); + match limit { + Some(n) => iter.take(n).collect(), + None => iter.collect(), + } + }; // 锁在这里释放 + + // 逐块打点。上游 `scan_cached_blocks` 是黑盒,而它唯一会回调进来的地方 + // 就是这里 —— 于是「卡在第几块的扫描里」和「所有块都扫完了、卡在之后的 + // 写库/承诺树里」可以被分开。只在排查构建里编进来。 + #[cfg(feature = "debug-tracing")] + let total = selected.len(); + // The index is consumed only by the debug-tracing build. + #[allow(clippy::unused_enumerate_index)] + for (_i, block) in selected.into_iter().enumerate() { + #[cfg(feature = "debug-tracing")] + crate::sync::trace(&format!( + "cache: 交出第 {}/{} 块 h={}", + _i + 1, + total, + block.height + )); + with_block(block)?; + } + #[cfg(feature = "debug-tracing")] + crate::sync::trace("cache: 本批区块已全部交出,之后的时间都在上游写库/承诺树里"); + Ok(()) + } +} + +#[async_trait::async_trait] +impl BlockCache for MemoryBlockCache { + fn get_tip_height( + &self, + range: Option<&ScanRange>, + ) -> Result, Self::Error> { + let blocks = self.blocks.lock().map_err(|_| poisoned())?; + let tip = match range { + None => blocks.keys().next_back().copied(), + Some(range) => { + let r = Self::range_of(range); + blocks.range(r).map(|(h, _)| *h).next_back() + } + }; + Ok(tip.map(BlockHeight::from_u32)) + } + + async fn read(&self, range: &ScanRange) -> Result, Self::Error> { + let blocks = self.blocks.lock().map_err(|_| poisoned())?; + let r = Self::range_of(range); + // 契约要求返回的区块必须连续且从 range.start 开始;允许短读。 + let mut out = Vec::new(); + let mut expect = r.start; + while expect < r.end { + match blocks.get(&expect) { + Some(b) => { + out.push(b.clone()); + expect += 1; + } + None => break, + } + } + Ok(out) + } + + async fn insert(&self, compact_blocks: Vec) -> Result<(), Self::Error> { + let mut blocks = self.blocks.lock().map_err(|_| poisoned())?; + for b in compact_blocks { + let h = u32::try_from(b.height) + .map_err(|_| CacheError(format!("区块高度超出范围: {}", b.height)))?; + blocks.insert(h, b); + } + Ok(()) + } + + async fn delete(&self, range: ScanRange) -> Result<(), Self::Error> { + let mut blocks = self.blocks.lock().map_err(|_| poisoned())?; + let r = Self::range_of(&range); + let doomed: Vec = blocks.range(r).map(|(h, _)| *h).collect(); + for h in doomed { + blocks.remove(&h); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use zcash_client_backend::data_api::scanning::ScanPriority; + + fn block(height: u64) -> CompactBlock { + CompactBlock { + height, + ..Default::default() + } + } + + fn range(start: u32, end: u32) -> ScanRange { + ScanRange::from_parts( + BlockHeight::from_u32(start)..BlockHeight::from_u32(end), + ScanPriority::Historic, + ) + } + + #[test] + fn empty_cache_has_no_tip() { + let c = MemoryBlockCache::new(); + assert!(c.is_empty()); + assert_eq!(c.get_tip_height(None).unwrap(), None); + } + + #[test] + fn insert_then_read_contiguous() { + let c = MemoryBlockCache::new(); + futures::executor::block_on(c.insert(vec![block(10), block(11), block(12)])).unwrap(); + assert_eq!(c.len(), 3); + assert_eq!( + c.get_tip_height(None).unwrap(), + Some(BlockHeight::from_u32(12)) + ); + + let got = futures::executor::block_on(c.read(&range(10, 13))).unwrap(); + assert_eq!(got.len(), 3); + assert_eq!(got[0].height, 10); + } + + /// 契约要求:返回的区块必须连续且从 range.start 开始,允许短读。 + /// 缺口之后的区块不能被返回,否则调用方会把不连续的数据当成连续的。 + #[test] + fn read_stops_at_gap() { + let c = MemoryBlockCache::new(); + futures::executor::block_on(c.insert(vec![block(10), block(11), block(13)])).unwrap(); + let got = futures::executor::block_on(c.read(&range(10, 14))).unwrap(); + assert_eq!(got.len(), 2, "遇到高度 12 的缺口就该停"); + assert_eq!(got[1].height, 11); + } + + #[test] + fn read_returns_empty_when_start_missing() { + let c = MemoryBlockCache::new(); + futures::executor::block_on(c.insert(vec![block(11)])).unwrap(); + let got = futures::executor::block_on(c.read(&range(10, 12))).unwrap(); + assert!(got.is_empty(), "起点缺失时不能从中间开始返回"); + } + + #[test] + fn delete_removes_only_the_range() { + let c = MemoryBlockCache::new(); + futures::executor::block_on(c.insert(vec![block(10), block(11), block(12)])).unwrap(); + futures::executor::block_on(c.delete(range(11, 12))).unwrap(); + assert_eq!(c.len(), 2); + assert_eq!( + c.get_tip_height(None).unwrap(), + Some(BlockHeight::from_u32(12)) + ); + } + + #[test] + fn tip_within_range_is_bounded() { + let c = MemoryBlockCache::new(); + futures::executor::block_on(c.insert(vec![block(10), block(20), block(30)])).unwrap(); + let tip = c.get_tip_height(Some(&range(10, 25))).unwrap(); + assert_eq!(tip, Some(BlockHeight::from_u32(20))); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs new file mode 100644 index 000000000..0d9260597 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs @@ -0,0 +1,54 @@ +//! 时钟。 +//! +//! `zcash_client_sqlite` 需要一个 `Clock` 来给数据库记录时间戳,官方提供的 +//! `SystemClock` 走 `std::time::SystemTime::now()`。在 wasm32-unknown-unknown 上 +//! 那个调用会 panic(std 没有该平台的时间源),所以浏览器侧必须自己接。 +//! +//! 这是本 crate 存在的典型理由之一:一小块平台胶水,不是业务逻辑。 + +use std::time::{Duration, SystemTime}; +use zcash_client_sqlite::util::Clock; + +/// 由宿主 JS 的 `Date.now()` 驱动的时钟。 +#[derive(Clone, Copy, Default)] +pub struct HostClock; + +impl Clock for HostClock { + fn now(&self) -> SystemTime { + SystemTime::UNIX_EPOCH + Duration::from_millis(now_millis()) + } +} + +#[cfg(target_arch = "wasm32")] +fn now_millis() -> u64 { + // js_sys::Date::now() 返回自 epoch 的毫秒数(f64)。 + let ms = js_sys::Date::now(); + if ms.is_finite() && ms > 0.0 { + ms as u64 + } else { + 0 + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn now_millis() -> u64 { + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clock_is_after_2020() { + let t = HostClock + .now() + .duration_since(SystemTime::UNIX_EPOCH) + .expect("时钟不应早于 epoch"); + // 2020-01-01 的毫秒数,确保我们拿到的是真实时间而不是 0。 + assert!(t.as_millis() > 1_577_836_800_000); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs new file mode 100644 index 000000000..5dd5da451 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs @@ -0,0 +1,363 @@ +//! 错误契约。 +//! +//! ## 原则 +//! +//! **Rust 侧不产出面向用户的文案。** 抛给宿主的是「稳定错误码 + 结构化参数」, +//! 文案与 i18n 全部由 monorepo 那边根据错误码渲染。 +//! +//! 这不只是分层洁癖:文案编进 wasm 意味着改一句提示语就要重编、重发包、 +//! (移动端还要)过应用商店。错误码和参数是契约,文案是产品。 +//! +//! ## 宿主怎么用 +//! +//! ```js +//! try { +//! await rt.syncAdvance(1000); +//! } catch (e) { +//! // e.code 稳定错误码,用它做分支 +//! // e.params 结构化参数,用它填 i18n 占位符 +//! // e.detail 上游库的原始报错,只用于日志,不要展示 +//! switch (e.code) { +//! case 'INSUFFICIENT_FUNDS': +//! toast(t('zcash.insufficient', { need: e.params.requiredZat })); +//! break; +//! } +//! } +//! ``` +//! +//! ## 演进规则 +//! +//! 错误码只允许**追加**,不允许改动已有取值的含义或删除 —— 宿主的分支依赖它。 +//! 参数字段同理:可以加,不可以改语义。 + +use serde_json::{json, Map, Value}; +use std::fmt; + +/// 稳定错误码。宿主按此做分支,不要去匹配 `detail` 的文本。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ErrorCode { + // ── 生命周期 ── + /// 尚未 `init()`,存储层未安装。 + NotInitialized, + /// 尚未 `openWallet()`。 + WalletNotOpen, + /// 尚未 `setLightwalletdUrl()`。 + LightwalletdNotConfigured, + + // ── 入参校验 ── + /// 网络名不是 "main" / "test"。参数:`{ value }` + InvalidNetwork, + /// 数据库名为空或含路径分隔符。参数:`{ value }` + InvalidDbName, + /// 收款地址无法解析。参数:`{ value }` + InvalidAddress, + /// UFVK 无法解析。 + InvalidUfvk, + /// memo 非法(如超长,或给了透明地址)。参数:`{ byteLen }` + InvalidMemo, + /// 账户 id 不是合法 UUID。参数:`{ value }` + InvalidAccountId, + /// 金额超出 Zatoshis 范围。参数:`{ valueZat }` + AmountOutOfRange, + /// 确认数策略不合法(须 >= 1 且 trusted <= untrusted)。 + /// 参数:`{ trusted, untrusted }` + InvalidConfirmationsPolicy, + /// 批大小为 0 或越界。参数:`{ value }` + InvalidBatchSize, + /// 区块高度越界。参数:`{ value }` + InvalidBlockHeight, + + // ── 业务状态 ── + /// 找不到该账户。参数:`{ accountId }` + AccountNotFound, + /// 尚未同步任何区块,读不到钱包摘要。 + NotSynced, + /// 余额不足。参数:`{ requiredZat, availableZat }`(能取到时) + InsufficientFunds, + /// 屏蔽余额不足,但透明余额本可补上 —— 钱在,只是在透明池里。 + /// + /// 与 `InsufficientFunds` 分开,是因为对用户来说这两件事完全不同: + /// 一个是「钱不够」,一个是「钱够但要先屏蔽」。合成一个码的话,宿主只能 + /// 显示「余额不足」,而用户明明看着账上有钱 —— 那种提示只会让人去猜。 + /// + /// 参数:`{ requiredZat, shieldedAvailableZat, shortfallZat, + /// transparentZat, transparentCoinbaseZat }` + FundsNeedShielding, + /// 差额只有 coinbase 输出能补上,而本钱包花不了 coinbase。 + /// + /// 转账用 `NonCoinbase`、屏蔽用 `NonCoinbaseOnly`,两条路都绕开它 —— + /// 矿工场景不在目标内。所以这笔钱在本钱包里**没有任何出口**, + /// 告诉用户「先屏蔽」等于把人往死路上指:屏蔽同样碰不到它。 + /// + /// 参数同 `FundsNeedShielding`。 + CoinbaseFundsUnspendable, + + // ── 外部依赖 ── + /// lightwalletd 网络错误。参数:`{ operation }` + NetworkError, + /// 钱包数据库错误(含 schema 迁移失败)。参数:`{ operation }` + DatabaseError, + /// 检测到链重组。参数:`{ atHeight, suggestedRewindHeight }` + /// + /// **不是故障,是正常事件** —— 链尖几个块被替换了。宿主应当调 `rewindTo` + /// 到建议高度然后继续同步。压成 `DATABASE_ERROR` 会让宿主无从判断该重试 + /// 还是该回退、更不知道退到哪里。 + ReorgDetected, + /// 正在进行一次异步操作,此刻不能切换/关闭钱包。参数:`{ operation }` + /// + /// 这不是内部错误而是**并发保护**:中途换库会让进行中的操作把结果写到 + /// 错误的库上,且没有任何迹象。宿主应当序列化对同一 runtime 的调用, + /// 或等当前操作结束后重试。 + WalletBusy, + /// 扫描优先级名称不合法。参数:`{ value }` + InvalidScanPriority, + /// No privacy identity was explicitly enabled for this scan. + /// + /// An empty active set must never fall back to every UFVK stored in the runtime database. + NoActiveAccounts, + /// reservationId 不是 64 位 hex。参数:`{ value }` + InvalidReservationId, + /// txid 格式不合法(不是 64 位 hex)。参数:`{ value }` 或 `{ value, byteLen }` + InvalidTxid, + /// PCZT 解析或序列化失败。参数:`{ stage }` + PcztError, + /// 交易构造失败(选币、费用、anchor 等)。参数:`{ stage }` + TransactionBuildError, + /// 交易已提交但被节点拒绝。参数:`{ errorCode }`,`detail` 里是节点原文。 + /// + /// 与 `NETWORK_ERROR` 分开:网络错误可以原样重试,被拒绝**不能** —— + /// 重发同一笔只会再被拒一次。宿主该做的是查明原因(费用不足、双花、 + /// 共识分支不对),而不是退避重试。 + BroadcastRejected, + /// 本地交易没有持久化的广播授权。参数:`{ txid }`。 + BroadcastIntentNotFound, + /// 广播授权存在,但当前状态不允许广播。参数:`{ txid, state }`。 + BroadcastIntentNotReady, + /// 交易可能已写入内存钱包,但持久化结果无法确认。不得解锁或重建交易。 + FinalizeOutcomeUnknown, + + /// 该能力尚未实现。参数:`{ what }` + Unimplemented, +} + +impl ErrorCode { + /// 稳定字符串形式。**不要改动已有取值。** + pub fn as_str(self) -> &'static str { + use ErrorCode::*; + match self { + NotInitialized => "NOT_INITIALIZED", + WalletNotOpen => "WALLET_NOT_OPEN", + LightwalletdNotConfigured => "LIGHTWALLETD_NOT_CONFIGURED", + InvalidNetwork => "INVALID_NETWORK", + InvalidDbName => "INVALID_DB_NAME", + InvalidAddress => "INVALID_ADDRESS", + InvalidUfvk => "INVALID_UFVK", + InvalidMemo => "INVALID_MEMO", + InvalidAccountId => "INVALID_ACCOUNT_ID", + AmountOutOfRange => "AMOUNT_OUT_OF_RANGE", + InvalidConfirmationsPolicy => "INVALID_CONFIRMATIONS_POLICY", + InvalidBatchSize => "INVALID_BATCH_SIZE", + InvalidBlockHeight => "INVALID_BLOCK_HEIGHT", + AccountNotFound => "ACCOUNT_NOT_FOUND", + NotSynced => "NOT_SYNCED", + InsufficientFunds => "INSUFFICIENT_FUNDS", + FundsNeedShielding => "FUNDS_NEED_SHIELDING", + CoinbaseFundsUnspendable => "COINBASE_FUNDS_UNSPENDABLE", + NetworkError => "NETWORK_ERROR", + DatabaseError => "DATABASE_ERROR", + ReorgDetected => "REORG_DETECTED", + WalletBusy => "WALLET_BUSY", + InvalidScanPriority => "INVALID_SCAN_PRIORITY", + NoActiveAccounts => "NO_ACTIVE_ACCOUNTS", + InvalidReservationId => "INVALID_RESERVATION_ID", + InvalidTxid => "INVALID_TXID", + PcztError => "PCZT_ERROR", + TransactionBuildError => "TRANSACTION_BUILD_ERROR", + BroadcastRejected => "BROADCAST_REJECTED", + BroadcastIntentNotFound => "BROADCAST_INTENT_NOT_FOUND", + BroadcastIntentNotReady => "BROADCAST_INTENT_NOT_READY", + FinalizeOutcomeUnknown => "FINALIZE_OUTCOME_UNKNOWN", + Unimplemented => "UNIMPLEMENTED", + } + } +} + +#[derive(Debug)] +pub struct RuntimeError { + pub code: ErrorCode, + /// 结构化参数,供宿主填 i18n 占位符。永远是一个 JSON 对象。 + pub params: Value, + /// 上游库的原始报错。**仅用于日志**,不面向用户,不做 i18n。 + pub detail: Option, +} + +impl RuntimeError { + pub fn new(code: ErrorCode) -> Self { + Self { + code, + params: Value::Object(Map::new()), + detail: None, + } + } + + /// 带结构化参数。`params` 应当是一个 JSON 对象。 + pub fn with(code: ErrorCode, params: Value) -> Self { + Self { + code, + params, + detail: None, + } + } + + /// 附上游原始报错,仅供日志。 + pub fn detail(mut self, d: impl fmt::Display) -> Self { + self.detail = Some(d.to_string()); + self + } + + /// 序列化成宿主能直接消费的 JSON。 + pub fn to_json(&self) -> Value { + json!({ + "code": self.code.as_str(), + "params": self.params, + "detail": self.detail, + }) + } +} + +impl fmt::Display for RuntimeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // 面向日志,不面向用户。 + write!(f, "{} {}", self.code.as_str(), self.params)?; + if let Some(d) = &self.detail { + write!(f, " :: {d}")?; + } + Ok(()) + } +} + +impl std::error::Error for RuntimeError {} + +impl From for RuntimeError { + fn from(e: rusqlite::Error) -> Self { + RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": "sqlite" })).detail(e) + } +} + +pub type Result = std::result::Result; + +/// 抛给 JS 的形状:`Error` 对象上挂 `code` / `params` / `detail`。 +/// +/// `message` 故意只放错误码 —— 它不是给用户看的文案, +/// 宿主拿 `code` 去查自己的 i18n 表。 +#[cfg(target_arch = "wasm32")] +impl From for wasm_bindgen::JsValue { + fn from(e: RuntimeError) -> Self { + use wasm_bindgen::JsCast; + + let err = js_sys::Error::new(e.code.as_str()); + err.set_name(e.code.as_str()); + + let obj: js_sys::Object = err.unchecked_into(); + let set = |k: &str, v: wasm_bindgen::JsValue| { + let _ = js_sys::Reflect::set(&obj, &wasm_bindgen::JsValue::from_str(k), &v); + }; + + let params = js_sys::JSON::parse(&e.params.to_string()) + .unwrap_or_else(|_| js_sys::Object::new().into()); + + set("code", wasm_bindgen::JsValue::from_str(e.code.as_str())); + set("params", params.clone()); + if let Some(d) = &e.detail { + set("detail", wasm_bindgen::JsValue::from_str(d)); + } + + // 同一份内容再放进 `payload`。 + // + // 宿主把错误跨进程/跨 WebView 传递时,序列化器只转发一份**固定的**字段 + // 名单,`params` 与 `detail` 不在其中 —— 平铺的那几个字段只有直接调用 + // (不跨载体)时才到得了对面,跨载体就只剩 `code`。`payload` 在名单里, + // 所以结构化参数必须搭这班车。 + // + // 两份都留:平铺的是本 crate 的契约,宿主直接调时读它;`payload` 是给 + // 跨载体那条路用的。内容相同,不存在哪份更新的问题。 + let payload = js_sys::Object::new(); + let pset = |k: &str, v: wasm_bindgen::JsValue| { + let _ = js_sys::Reflect::set(&payload, &wasm_bindgen::JsValue::from_str(k), &v); + }; + pset("code", wasm_bindgen::JsValue::from_str(e.code.as_str())); + pset("params", params); + if let Some(d) = &e.detail { + pset("detail", wasm_bindgen::JsValue::from_str(d)); + } + set("payload", payload.into()); + + obj.into() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_are_unique_and_screaming_snake() { + use ErrorCode::*; + let all = [ + NotInitialized, + WalletNotOpen, + LightwalletdNotConfigured, + InvalidNetwork, + InvalidDbName, + InvalidAddress, + InvalidUfvk, + InvalidMemo, + InvalidAccountId, + AmountOutOfRange, + InvalidConfirmationsPolicy, + InvalidBatchSize, + InvalidBlockHeight, + NoActiveAccounts, + AccountNotFound, + NotSynced, + InsufficientFunds, + NetworkError, + DatabaseError, + InvalidReservationId, + InvalidTxid, + PcztError, + TransactionBuildError, + BroadcastRejected, + Unimplemented, + ]; + let mut seen = std::collections::HashSet::new(); + for c in all { + let s = c.as_str(); + assert!(seen.insert(s), "错误码重复: {s}"); + assert!( + s.chars().all(|ch| ch.is_ascii_uppercase() || ch == '_'), + "错误码必须是 SCREAMING_SNAKE_CASE: {s}" + ); + } + } + + #[test] + fn json_shape_is_stable() { + let e = RuntimeError::with( + ErrorCode::AmountOutOfRange, + json!({ "valueZat": 2_100_000_000_000_001_u64 }), + ) + .detail("upstream says no"); + let j = e.to_json(); + assert_eq!(j["code"], "AMOUNT_OUT_OF_RANGE"); + assert_eq!(j["params"]["valueZat"], 2_100_000_000_000_001_u64); + assert_eq!(j["detail"], "upstream says no"); + } + + #[test] + fn params_default_to_empty_object() { + let e = RuntimeError::new(ErrorCode::WalletNotOpen); + assert!(e.to_json()["params"].is_object()); + assert_eq!(e.to_json()["detail"], serde_json::Value::Null); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs new file mode 100644 index 000000000..c0d1dd0a4 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs @@ -0,0 +1,686 @@ +//! 交易历史。 +//! +//! ## 为什么直接查视图 +//! +//! `zcash_client_backend` 的 `WalletRead::get_tx_history` 上游明确标注为 **test-only** +//! (「production use could return a very large number of results; either pagination or a +//! streaming design will be necessary to stabilize this feature」),返回类型还在 +//! `testing` 模块下。不能拿它做生产接口。 +//! +//! 所以走 `zcash_client_sqlite` 维护的 `v_transactions` 视图 —— 这也是官方 +//! Android / iOS SDK 的做法。视图由上游随 schema 一起演进,我们只读不改。 +//! +//! ## 耦合风险 +//! +//! 直接查视图意味着依赖它的列名。升级 `zcash_client_sqlite` 时列可能变化, +//! 而那**不会**在 Rust 编译期报错,只会在运行时查询失败。因此: +//! +//! - 本模块的查询列表集中在一处,升级时先跑一次 `history_smoke` 测试; +//! - 出错时抛 `DATABASE_ERROR` 且 `params.operation = "history"`,便于定位。 +//! +//! ## 边界 +//! +//! 这里只做**取数与分页**,不做展示模型 —— 「这笔算收入还是支出」「显示成什么文案」 +//! 属于宿主。返回的是中性事实:金额增量、是否找零、note 计数、时间戳。 + +use serde_json::json; + +use crate::error::{ErrorCode, Result, RuntimeError}; + +/// 账户 UUID 在官方 schema 里是 **BLOB**(16 字节原始值),不是文本。 +/// +/// 用 36 字符的连字符形式去绑定,SQLite 不会报错,只会**一行都匹配不上** —— +/// 于是历史、计数、详情全部恒空,而且看起来像「还没同步出数据」。 +/// 这个坑代价很高:坏查询和空钱包的返回值完全一样,测试很容易假绿。 +pub(crate) fn uuid_blob(account_uuid: &str) -> Result> { + uuid::Uuid::parse_str(account_uuid) + .map(|u| u.as_bytes().to_vec()) + .map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidAccountId, + json!({ "value": account_uuid }), + ) + }) +} + +/// 每页最多返回多少条,防止宿主一次拉爆内存。 +pub const MAX_PAGE_SIZE: u32 = 500; + +fn db_err(e: impl std::fmt::Display) -> RuntimeError { + RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": "history" })).detail(e) +} + +/// Whether deleting this account would discard a locally created outgoing +/// transaction that has not reached a terminal chain state yet. +pub fn has_unsettled_outgoing(conn: &rusqlite::Connection, account_uuid: &str) -> Result { + conn.query_row( + "SELECT EXISTS( + SELECT 1 + FROM v_transactions + WHERE account_uuid = ?1 + AND mined_height IS NULL + AND expired_unmined = 0 + AND COALESCE(total_spent, 0) > 0 + )", + rusqlite::params![uuid_blob(account_uuid)?], + |row| row.get(0), + ) + .map_err(db_err) +} + +// Keep the list and detail endpoints on the exact same projection. `row_to_json` +// intentionally has one shape; adding a field to only one query would otherwise +// compile and then fail when the other endpoint reads a missing column at runtime. +const HISTORY_ROW_SELECT: &str = "SELECT + tx_summary.txid, + tx_summary.mined_height, + tx_summary.block_time, + tx_summary.expiry_height, + tx_summary.expired_unmined, + tx_summary.fee_paid, + tx_summary.account_balance_delta, + tx_summary.has_change, + tx_summary.sent_note_count, + tx_summary.received_note_count, + tx_summary.memo_count, + tx_summary.is_shielding, + tx_summary.total_spent, + tx_summary.total_received, + COALESCE(( + SELECT GROUP_CONCAT( + pool_delta.pool || ':' || pool_delta.balance_delta_zat, + ',' + ) + FROM ( + SELECT activity.pool, + SUM(activity.balance_delta_zat) AS balance_delta_zat + FROM ( + SELECT owned_output.pool, + owned_output.value AS balance_delta_zat + FROM v_received_outputs owned_output + JOIN accounts owned_account + ON owned_account.id = owned_output.account_id + WHERE owned_output.transaction_id = chain_tx.id_tx + AND owned_account.uuid = tx_summary.account_uuid + AND owned_output.pool <> 2 + UNION ALL + SELECT owned_spend.pool, + -spent_output.value AS balance_delta_zat + FROM v_received_output_spends owned_spend + JOIN v_received_outputs spent_output + ON spent_output.pool = owned_spend.pool + AND spent_output.id_within_pool_table = owned_spend.received_output_id + JOIN accounts spent_account + ON spent_account.id = owned_spend.account_id + WHERE owned_spend.transaction_id = chain_tx.id_tx + AND spent_account.uuid = tx_summary.account_uuid + AND owned_spend.pool <> 2 + ) activity + GROUP BY activity.pool + ORDER BY activity.pool + ) pool_delta + ), '') AS per_pool_balance_deltas, + tx_state.broadcast_state, + COALESCE( + tx_state.recipient, + (SELECT output.to_address + FROM v_tx_outputs output + WHERE output.txid = tx_summary.txid + AND output.from_account_uuid = tx_summary.account_uuid + AND output.to_account_uuid IS NULL + AND COALESCE(output.is_change, 0) = 0 + LIMIT 1) + ) AS recipient, + (SELECT COUNT(*) + FROM v_tx_outputs output + WHERE output.txid = tx_summary.txid + AND output.from_account_uuid = tx_summary.account_uuid + AND output.to_account_uuid IS NULL + AND COALESCE(output.is_change, 0) = 0 + ) AS external_output_count + FROM v_transactions tx_summary + JOIN transactions chain_tx ON chain_tx.txid = tx_summary.txid + LEFT JOIN ext_onekey_tx_state tx_state + ON tx_state.txid = tx_summary.txid + AND tx_state.account_uuid = tx_summary.account_uuid"; + +const NON_SAPLING_ACTIVITY: &str = "( + EXISTS ( + SELECT 1 + FROM v_received_outputs visible_output + JOIN accounts visible_account ON visible_account.id = visible_output.account_id + WHERE visible_output.transaction_id = chain_tx.id_tx + AND visible_account.uuid = tx_summary.account_uuid + AND visible_output.pool <> 2 + ) + OR EXISTS ( + SELECT 1 + FROM v_received_output_spends visible_spend + JOIN accounts visible_account ON visible_account.id = visible_spend.account_id + WHERE visible_spend.transaction_id = chain_tx.id_tx + AND visible_account.uuid = tx_summary.account_uuid + AND visible_spend.pool <> 2 + ) +)"; + +/// 分页读取某账户的交易历史,返回 JSON 数组。 +/// +/// 排序:未上链的排在最前(`mined_height IS NULL`),其余按高度倒序。 +/// 这样用户刚发出的交易立刻可见。 +pub fn list( + conn: &rusqlite::Connection, + account_uuid: &str, + limit: u32, + offset: u32, +) -> Result { + if limit == 0 || limit > MAX_PAGE_SIZE { + return Err(RuntimeError::with( + ErrorCode::InvalidBatchSize, + json!({ "value": limit, "max": MAX_PAGE_SIZE }), + )); + } + + let sql = format!( + "{HISTORY_ROW_SELECT} + WHERE tx_summary.account_uuid = ?1 + AND {NON_SAPLING_ACTIVITY} + ORDER BY (tx_summary.mined_height IS NULL) DESC, + tx_summary.mined_height DESC, + tx_summary.tx_index DESC + LIMIT ?2 OFFSET ?3" + ); + let mut stmt = conn.prepare(&sql).map_err(db_err)?; + + let rows = stmt + .query_map( + rusqlite::params![uuid_blob(account_uuid)?, limit, offset], + row_to_json, + ) + .map_err(db_err)?; + + let mut out = Vec::new(); + for r in rows { + out.push(r.map_err(db_err)?); + } + + serde_json::to_string(&out).map_err(db_err) +} + +/// 一行 `v_transactions` → JSON。列表与详情共用,保证两处字段完全一致。 +fn row_to_json(row: &rusqlite::Row<'_>) -> rusqlite::Result { + let txid: Vec = row.get(0)?; + let per_pool_entries = row + .get::<_, String>(14)? + .split(',') + .filter(|value| !value.is_empty()) + .map(|value| { + let (pool, delta) = value.split_once(':').ok_or_else(|| { + rusqlite::Error::FromSqlConversionFailure( + 14, + rusqlite::types::Type::Text, + "invalid per-pool balance delta".into(), + ) + })?; + let pool = pool.parse::().map_err(|error| { + rusqlite::Error::FromSqlConversionFailure( + 14, + rusqlite::types::Type::Text, + Box::new(error), + ) + })?; + delta.parse::().map_err(|error| { + rusqlite::Error::FromSqlConversionFailure( + 14, + rusqlite::types::Type::Text, + Box::new(error), + ) + })?; + Ok((pool, delta.to_owned())) + }) + .collect::>>()?; + let pool_ids = per_pool_entries + .iter() + .map(|(pool, _)| *pool) + .collect::>(); + let per_pool_balance_delta_zat = per_pool_entries + .into_iter() + .map(|(pool, delta)| (pool.to_string(), serde_json::Value::String(delta))) + .collect::>(); + Ok(json!({ + // txid 以显示序(大端)给出,与区块浏览器一致。 + "txid": hex_display_order(&txid), + "minedHeight": row.get::<_, Option>(1)?, + "blockTime": row.get::<_, Option>(2)?, + "expiryHeight": row.get::<_, Option>(3)?, + "expiredUnmined": row.get::<_, Option>(4)?.unwrap_or(false), + "feeZat": row.get::<_, Option>(5)?, + "balanceDeltaZat": row.get::<_, Option>(6)?, + "hasChange": row.get::<_, Option>(7)?.unwrap_or(false), + "sentNoteCount": row.get::<_, Option>(8)?.unwrap_or(0), + "receivedNoteCount": row.get::<_, Option>(9)?.unwrap_or(0), + "memoCount": row.get::<_, Option>(10)?.unwrap_or(0), + "isShielding": row.get::<_, Option>(11)?.unwrap_or(false), + // 本账户在这笔交易里的方向性金额(视图现成列)。宿主用它们分类与 + // 显示:sent 的显示金额 = spent - received - fee(不含手续费的净额), + // 自转/屏蔽的显示金额 = received —— 直接用 balance_delta 会把屏蔽 + // 显示成一笔「手续费大小」的交易。 + "totalSpentZat": row.get::<_, Option>(12)?, + "totalReceivedZat": row.get::<_, Option>(13)?, + // Preserve exact upstream pool identifiers. The host may aggregate + // them for today's UI, but a future multi-pool UI must not need a + // rescan to recover information discarded here. + "poolIds": pool_ids, + // Signed account-owned value change for each exact pool. This cannot be + // recovered from the aggregate row after an Orchard-to-Ironwood move. + "perPoolBalanceDeltaZat": per_pool_balance_delta_zat, + "broadcastState": row.get::<_, Option>(15)?, + "recipient": row.get::<_, Option>(16)?, + // 本账户发出、且不属于本账户任何地址的输出数。为 0 且有花费 = 内部 + // 转移(屏蔽 / 提到自己的透明地址 / 池间搬家),与 fee 是否已知无关 —— + // fee 未知时靠 spent-received 判方向会把自转误判成外发。 + "externalOutputCount": row.get::<_, i64>(17)?, + })) +} + +/// 单笔交易详情。查不到返回 `null`(JSON),不抛错 —— +/// 「这笔不在钱包里」是正常状态,不是故障:外部 txid、已被回滚的交易都会走到这里。 +pub fn details(conn: &rusqlite::Connection, account_uuid: &str, txid: &str) -> Result { + // 库里 txid 存的是内部序(小端),入参是显示序(大端),先翻回去。 + let internal = display_order_to_internal(txid)?; + + let sql = format!( + "{HISTORY_ROW_SELECT} + WHERE tx_summary.account_uuid = ?1 + AND tx_summary.txid = ?2 + AND {NON_SAPLING_ACTIVITY} + LIMIT 1" + ); + let mut stmt = conn.prepare(&sql).map_err(db_err)?; + + let mut rows = stmt + .query(rusqlite::params![uuid_blob(account_uuid)?, internal]) + .map_err(db_err)?; + + match rows.next().map_err(db_err)? { + None => Ok("null".to_string()), + Some(row) => { + let v = row_to_json(row).map_err(db_err)?; + serde_json::to_string(&v).map_err(db_err) + } + } +} + +/// 单笔交易的**逐笔明细**:本账户被花掉的、收到的,以及发给外部的输出。 +/// +/// 数据来自 `v_tx_outputs` —— `zcash_client_sqlite` 维护的每输出一行的视图, +/// 官方 SDK 取交易详情走的也是它。三段的判定规则: +/// +/// - `received`:`to_account_uuid` 是本账户(`is_change` 区分找零与真收款) +/// - `external`:`from_account_uuid` 是本账户、而 `to_account_uuid` 为空 —— +/// 即我们付给别人的输出。**只有自己发的交易才看得到收款地址**, +/// 别人发给别人的输出我们既解不开也不该出现在这里 +/// - `spent`:本账户在更早交易里收到、且被这笔花掉的输出,走 `v_received_output_spends` +/// +/// 池号沿用上游编码:0=transparent, 2=sapling, 3=orchard, 4=ironwood。 +/// 这里原样透出数字并附字符串名,宿主不必自己记这套映射。 +pub fn details_outputs( + conn: &rusqlite::Connection, + account_uuid: &str, + txid: &str, +) -> Result { + let internal = display_order_to_internal(txid)?; + let me = uuid_blob(account_uuid)?; + + let mut received = Vec::new(); + let mut external = Vec::new(); + { + let mut stmt = conn + .prepare( + "SELECT output_pool, value, is_change, memo, to_address, + to_account_uuid, from_account_uuid + FROM v_tx_outputs + WHERE txid = ?1", + ) + .map_err(db_err)?; + let mut rows = stmt.query(rusqlite::params![internal]).map_err(db_err)?; + while let Some(row) = rows.next().map_err(db_err)? { + let pool: i64 = row.get(0).map_err(db_err)?; + let value: i64 = row.get(1).map_err(db_err)?; + let is_change: bool = row + .get::<_, Option>(2) + .map_err(db_err)? + .unwrap_or(false); + let memo: Option> = row.get(3).map_err(db_err)?; + let address: Option = row.get(4).map_err(db_err)?; + // 同理:读出来也是 BLOB,按 String 读会直接报列类型错误 + let to_acct: Option> = row.get(5).map_err(db_err)?; + let from_acct: Option> = row.get(6).map_err(db_err)?; + + if pool == 2 { + continue; + } + + if to_acct.as_deref() == Some(me.as_slice()) { + received.push(json!({ + "valueZat": value, + "pool": pool, + "poolName": pool_name(pool), + "isChange": is_change, + "memo": memo.as_deref().and_then(decode_memo), + "address": address, + })); + } else if from_acct.as_deref() == Some(me.as_slice()) { + external.push(json!({ + "valueZat": value, + "pool": pool, + "poolName": pool_name(pool), + "address": address, + })); + } + } + } + + let mut spent = Vec::new(); + { + // 本账户收到的输出中,被这笔交易花掉的那些。 + // 连接键是 (pool, id_within_pool_table) ↔ (pool, received_output_id)。 + // `v_received_output_spends` 里没有 output_index,别拿它当连接键。 + let mut stmt = conn + .prepare( + "SELECT ro.pool, ro.value, addr.address + FROM v_received_output_spends s + JOIN transactions t ON t.id_tx = s.transaction_id + JOIN v_received_outputs ro + ON ro.pool = s.pool + AND ro.id_within_pool_table = s.received_output_id + JOIN accounts acct ON acct.id = ro.account_id + LEFT JOIN addresses addr ON addr.id = ro.address_id + WHERE t.txid = ?1 AND acct.uuid = ?2", + ) + .map_err(db_err)?; + let mut rows = stmt + .query(rusqlite::params![internal, uuid_blob(account_uuid)?]) + .map_err(db_err)?; + while let Some(row) = rows.next().map_err(db_err)? { + let pool: i64 = row.get(0).map_err(db_err)?; + if pool == 2 { + continue; + } + spent.push(json!({ + "valueZat": row.get::<_, i64>(1).map_err(db_err)?, + "pool": pool, + "poolName": pool_name(pool), + "address": row.get::<_, Option>(2).map_err(db_err)?, + })); + } + } + + serde_json::to_string(&json!({ + "txid": txid, + "spent": spent, + "received": received, + "external": external, + })) + .map_err(db_err) +} + +/// 上游的池编码。数字是存储层的事实,名字是给宿主省一次查表。 +fn pool_name(pool: i64) -> &'static str { + match pool { + 0 => "transparent", + 2 => "sapling", + 3 => "orchard", + 4 => "ironwood", + _ => "unknown", + } +} + +/// memo 里全零表示「没有 memo」,0xF6 开头是协议保留,都不该当文本给出去。 +fn decode_memo(bytes: &[u8]) -> Option { + if bytes.is_empty() || bytes.iter().all(|b| *b == 0) || bytes[0] == 0xF6 { + return None; + } + let end = bytes.iter().rposition(|b| *b != 0).map_or(0, |i| i + 1); + String::from_utf8(bytes[..end].to_vec()).ok() +} + +/// 显示序(大端 hex)→ 内部序(小端字节)。 +pub(crate) fn display_order_to_internal(txid: &str) -> Result> { + let bytes = hex_decode(txid) + .ok_or_else(|| RuntimeError::with(ErrorCode::InvalidTxid, json!({ "value": txid })))?; + if bytes.len() != 32 { + return Err(RuntimeError::with( + ErrorCode::InvalidTxid, + json!({ "value": txid, "byteLen": bytes.len() }), + )); + } + Ok(bytes.into_iter().rev().collect()) +} + +fn hex_decode(s: &str) -> Option> { + if s.len() % 2 != 0 { + return None; + } + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok()) + .collect() +} + +/// txid 在库里以内部序(小端)存储,浏览器展示用大端。翻转后转 hex。 +pub(crate) fn hex_display_order(txid_le: &[u8]) -> String { + txid_le.iter().rev().map(|b| format!("{b:02x}")).collect() +} + +#[cfg(test)] +mod tests { + use rand::SeedableRng; + use rand_chacha::ChaCha20Rng; + use zcash_client_sqlite::{wallet::init::WalletMigrator, WalletDb}; + use zcash_protocol::consensus::Network; + + use super::*; + use crate::clock::HostClock; + + #[test] + fn txid_is_reversed_for_display() { + assert_eq!(hex_display_order(&[0x01, 0x02, 0x03]), "030201"); + assert_eq!(hex_display_order(&[]), ""); + } + + #[test] + fn rejects_bad_page_size() { + // 用一个内存库即可,查询根本不会执行到。 + let conn = rusqlite::Connection::open_in_memory().unwrap(); + for bad in [0, MAX_PAGE_SIZE + 1] { + let e = list(&conn, "whatever", bad, 0).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidBatchSize); + assert_eq!(e.params["value"], bad); + } + } + + #[test] + fn history_queries_compile_against_the_migrated_wallet_schema() { + let mut conn = rusqlite::Connection::open_in_memory().unwrap(); + rusqlite::vtab::array::load_module(&conn).unwrap(); + { + let rng = ChaCha20Rng::from_seed([7; 32]); + let mut db = WalletDb::from_connection(&mut conn, Network::TestNetwork, HostClock, rng); + WalletMigrator::new() + .with_external_migrations(vec![Box::new(crate::tx_state::Migration)]) + .init_or_migrate(&mut db) + .unwrap(); + } + + let account_uuid = uuid::Uuid::nil().to_string(); + assert_eq!(list(&conn, &account_uuid, 20, 0).unwrap(), "[]"); + assert_eq!( + details(&conn, &account_uuid, &"00".repeat(32)).unwrap(), + "null" + ); + } + + #[test] + fn preserves_supported_pool_ids_and_hides_sapling() { + let conn = rusqlite::Connection::open_in_memory().unwrap(); + conn.execute_batch( + "CREATE TABLE accounts (id INTEGER PRIMARY KEY, uuid BLOB NOT NULL); + CREATE TABLE transactions (id_tx INTEGER PRIMARY KEY, txid BLOB NOT NULL); + CREATE TABLE v_received_outputs ( + id_within_pool_table INTEGER NOT NULL, + transaction_id INTEGER NOT NULL, + account_id INTEGER NOT NULL, + pool INTEGER NOT NULL, + value INTEGER NOT NULL + ); + CREATE TABLE v_received_output_spends ( + transaction_id INTEGER NOT NULL, + account_id INTEGER NOT NULL, + pool INTEGER NOT NULL, + received_output_id INTEGER NOT NULL + ); + CREATE TABLE v_tx_outputs ( + txid BLOB NOT NULL, + from_account_uuid BLOB, + to_account_uuid BLOB, + to_address TEXT, + is_change INTEGER + ); + CREATE TABLE ext_onekey_tx_state ( + txid BLOB PRIMARY KEY NOT NULL, + account_uuid BLOB NOT NULL, + reservation_id TEXT UNIQUE, + recipient TEXT, + broadcast_state TEXT NOT NULL, + rejection_code INTEGER, + rejection_reason TEXT + ); + CREATE TABLE v_transactions ( + account_uuid BLOB NOT NULL, + mined_height INTEGER, + txid BLOB NOT NULL, + tx_index INTEGER, + block_time INTEGER, + expiry_height INTEGER, + expired_unmined INTEGER, + fee_paid INTEGER, + account_balance_delta INTEGER, + has_change INTEGER, + sent_note_count INTEGER, + received_note_count INTEGER, + memo_count INTEGER, + is_shielding INTEGER, + total_spent INTEGER, + total_received INTEGER + );", + ) + .unwrap(); + + let account_uuid = uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap(); + conn.execute( + "INSERT INTO accounts (id, uuid) VALUES (1, ?1)", + [account_uuid.as_bytes().as_slice()], + ) + .unwrap(); + + for id in 1_i64..=6 { + let txid = vec![id as u8; 32]; + conn.execute( + "INSERT INTO transactions (id_tx, txid) VALUES (?1, ?2)", + rusqlite::params![id, txid], + ) + .unwrap(); + conn.execute( + "INSERT INTO v_transactions ( + account_uuid, mined_height, txid, tx_index, block_time, + expiry_height, expired_unmined, fee_paid, + account_balance_delta, has_change, sent_note_count, + received_note_count, memo_count, is_shielding, total_spent, + total_received + ) VALUES ( + ?1, ?2, ?3, ?4, 1000, 200, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0 + )", + rusqlite::params![ + account_uuid.as_bytes().as_slice(), + id, + vec![id as u8; 32], + id + ], + ) + .unwrap(); + } + + conn.execute( + "INSERT INTO v_received_outputs ( + id_within_pool_table, transaction_id, account_id, pool, value + ) VALUES + (1, 1, 1, 0, 10), + (1, 1, 1, 2, 20), + (2, 3, 1, 4, 99), + (3, 4, 1, 99, 40), + (2, 5, 1, 2, 50), + (4, 99, 1, 0, 100), + (5, 98, 1, 4, 70), + (6, 97, 1, 3, 100), + (7, 96, 1, 3, 50), + (8, 6, 1, 3, 50)", + [], + ) + .unwrap(); + conn.execute( + "INSERT INTO v_received_output_spends ( + transaction_id, account_id, pool, received_output_id + ) VALUES + (2, 1, 4, 5), + (3, 1, 3, 6), + (6, 1, 3, 7)", + [], + ) + .unwrap(); + + let rows: Vec = + serde_json::from_str(&list(&conn, &account_uuid.to_string(), 20, 0).unwrap()).unwrap(); + let pool_ids: Vec> = rows + .iter() + .map(|row| { + row["poolIds"] + .as_array() + .unwrap() + .iter() + .map(|pool| pool.as_i64().unwrap()) + .collect() + }) + .collect(); + assert_eq!( + pool_ids, + vec![vec![3], vec![99], vec![3, 4], vec![4], vec![0]] + ); + + let pool_deltas: Vec = rows + .iter() + .map(|row| row["perPoolBalanceDeltaZat"].clone()) + .collect(); + assert_eq!( + pool_deltas, + vec![ + // Touching a pool on both sides must preserve the pool key even + // when the net value change is zero. + json!({ "3": "0" }), + json!({ "99": "40" }), + json!({ "3": "-100", "4": "99" }), + json!({ "4": "-70" }), + json!({ "0": "10" }), + ] + ); + + let mixed: serde_json::Value = serde_json::from_str( + &details(&conn, &account_uuid.to_string(), &"03".repeat(32)).unwrap(), + ) + .unwrap(); + assert_eq!(mixed["poolIds"], json!([3, 4])); + assert_eq!( + mixed["perPoolBalanceDeltaZat"], + json!({ "3": "-100", "4": "99" }) + ); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs new file mode 100644 index 000000000..150782948 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs @@ -0,0 +1,59 @@ +//! # OneKey Zcash Runtime +//! +//! 官方 `librustzcash` 之上的最薄绑定层。 +//! +//! ## 设计边界 +//! +//! 留在这一侧(wasm / Rust)的只有三类东西: +//! +//! 1. **密码学与协议** —— 扫链的 trial decryption、witness 与承诺树维护、 +//! 交易构造与选币。这些跨边界成本高、且错了会丢钱,必须留在原地。 +//! 2. **平台胶水** —— 时钟、随机数、存储 VFS。std 在 wasm32 上不提供的那些。 +//! 3. **形状转换** —— 把 Rust 的富类型转成 JSON 交给宿主。 +//! +//! 明确**不**放在这一侧的:调度(什么时候扫、扫哪段)、账户与 birthday 管理、 +//! 缓存策略、进度展示、错误重试。那些属于宿主 TS,改起来快、看得见、能打断点。 +//! +//! ## 接口形状 +//! +//! 动词少、数据简单。每次调用是一次完整往返,wasm 不持有跨调用的会话状态 +//! (数据库除外)。这样宿主侧出问题永远能自己修,wasm 侧只在协议变化时才动。 + +// ── 全平台:钱包核心 ──────────────────────────────────────────────────── +// 这几个模块在 wasm32、aarch64-apple-ios、Android 上都编译。 +// 也就是说移动端**可以**跑完整的钱包逻辑,不必退化成 keys-only。 +pub mod account; +pub mod blockcache; +pub mod clock; +pub mod error; +pub mod history; +pub mod send; +pub mod stats; +pub mod storage; +pub mod tx_state; +pub mod wallet; + +// 网络与扫链现在是全平台的:浏览器走 gRPC-web,原生走 tonic transport。 +// 这也让我们能在本机原生环境复现浏览器里的问题 —— 那边可以上真调试器。 +pub mod network; +pub mod perf; +pub mod sync; + +// 跨调用状态用 thread_local,只在单线程的 wasm 宿主里成立。 +#[cfg(target_arch = "wasm32")] +pub mod runtime; + +#[cfg(target_arch = "wasm32")] +pub mod bindgen; + +pub use error::{ErrorCode, Result, RuntimeError}; + +/// 本 runtime 依赖的官方 crate 版本,供宿主自检与日志使用。 +pub fn dependency_versions() -> serde_json::Value { + serde_json::json!({ + "zcash_client_backend": "0.24.0", + "zcash_client_sqlite": "0.22.0", + "zcash_keys": "0.16.1", + "runtime": env!("CARGO_PKG_VERSION"), + }) +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs new file mode 100644 index 000000000..b813c7b76 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs @@ -0,0 +1,351 @@ +//! lightwalletd 网络层。 +//! +//! 浏览器里跑不了原生 gRPC(没有 HTTP/2 裸连接),所以走 gRPC-web: +//! `tonic-web-wasm-client` 把 tonic 生成的客户端接到 fetch 上。 +//! +//! 版本约束:`tonic-web-wasm-client` 必须 >= 0.9.1。0.8.0 在流结束时不转发 +//! gRPC trailer,会让 `get_block_range` 这类流式调用永远等不到结束标志。 + +use zcash_client_backend::proto::service::{ + compact_tx_streamer_client::CompactTxStreamerClient, BlockId, ChainSpec, TreeState, +}; + +use crate::error::{ErrorCode, Result, RuntimeError}; +use serde_json::json; + +// 浏览器走 gRPC-web(没有原生 HTTP/2 裸连接),原生目标走 tonic 自带 transport。 +// 上层的 `LightClient` 签名在两边一致,`chain_tip` / `tree_state` 等函数不用分叉。 +#[cfg(target_arch = "wasm32")] +pub type Transport = tonic_web_wasm_client::Client; + +#[cfg(not(target_arch = "wasm32"))] +pub type Transport = tonic::transport::Channel; + +pub type LightClient = CompactTxStreamerClient; + +/// `operation` 是稳定的机器可读标识(不是文案),宿主可据此区分是哪一步失败。 +fn net_err(operation: &str, e: impl std::fmt::Display) -> RuntimeError { + RuntimeError::with(ErrorCode::NetworkError, json!({ "operation": operation })).detail(e) +} + +/// 把一个网络 future 套上超时。 +/// +/// **为什么必须有**:wasm 里挂死的调用宿主无法取消 —— 没有线程可以中断, +/// Promise 也不会自己 reject。一个不返回的 gRPC 调用会让整个钱包永久卡住, +/// 而且没有任何错误信息。加超时把「挂死」变成「可处理的错误」。 +/// +/// 实测踩过:`get_block_range` 在某些情况下不返回也不报错。 +#[cfg(target_arch = "wasm32")] +pub async fn with_timeout( + fut: impl std::future::Future>, + timeout_ms: u32, + operation: &str, +) -> Result { + use futures_util::future::{select, Either}; + + let timer = gloo_timers::future::TimeoutFuture::new(timeout_ms); + futures_util::pin_mut!(fut); + + match select(fut, timer).await { + Either::Left((r, _)) => r, + Either::Right((_, _)) => Err(timeout_err(operation, timeout_ms)), + } +} + +/// 原生目标用 tokio 的定时器。 +#[cfg(not(target_arch = "wasm32"))] +pub async fn with_timeout( + fut: impl std::future::Future>, + timeout_ms: u32, + operation: &str, +) -> Result { + match tokio::time::timeout(std::time::Duration::from_millis(timeout_ms.into()), fut).await { + Ok(r) => r, + Err(_) => Err(timeout_err(operation, timeout_ms)), + } +} + +fn timeout_err(operation: &str, timeout_ms: u32) -> RuntimeError { + RuntimeError::with( + ErrorCode::NetworkError, + json!({ "operation": operation, "timeoutMs": timeout_ms }), + ) +} + +/// 默认网络超时。单次 gRPC 调用超过这个时长基本可以判定为挂死。 +pub const DEFAULT_TIMEOUT_MS: u32 = 30_000; + +/// 建立一个 lightwalletd 客户端。`base_url` 形如 `https://host:port`。 +/// +/// 不做网络往返 —— 真正的连接发生在第一次调用时。 +#[cfg(target_arch = "wasm32")] +pub fn connect(base_url: &str) -> Result { + if base_url.is_empty() { + return Err(RuntimeError::with( + ErrorCode::LightwalletdNotConfigured, + json!({ "reason": "emptyUrl" }), + )); + } + Ok(CompactTxStreamerClient::new( + tonic_web_wasm_client::Client::new(base_url.to_owned()), + )) +} + +/// 原生目标的连接。与 wasm 版不同,这里会真的建链接,所以是 async。 +#[cfg(not(target_arch = "wasm32"))] +pub async fn connect_native(base_url: &str) -> Result { + if base_url.is_empty() { + return Err(RuntimeError::with( + ErrorCode::LightwalletdNotConfigured, + json!({ "reason": "emptyUrl" }), + )); + } + // https 端点必须显式配 TLS —— tonic 0.14 不会自动启用根证书。 + let mut endpoint = tonic::transport::Channel::from_shared(base_url.to_owned()) + .map_err(|e| net_err("parseEndpoint", e))?; + if base_url.starts_with("https://") { + endpoint = endpoint + .tls_config(tonic::transport::ClientTlsConfig::new().with_webpki_roots()) + .map_err(|e| net_err("tlsConfig", e))?; + } + let channel = endpoint + .connect() + .await + .map_err(|e| net_err("connect", e))?; + Ok(CompactTxStreamerClient::new(channel)) +} + +/// 当前链尖高度。 +pub async fn chain_tip(client: &mut LightClient) -> Result { + let block = with_timeout( + async { + client + .get_latest_block(ChainSpec {}) + .await + .map(|response| response.into_inner()) + .map_err(|e| net_err("getLatestBlock", e)) + }, + DEFAULT_TIMEOUT_MS, + "getLatestBlock", + ) + .await?; + u32::try_from(block.height).map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidBlockHeight, + json!({ "value": block.height }), + ) + }) +} + +/// 把已签名的交易提交给 lightwalletd。 +/// +/// lightwalletd 的 `SendTransaction` **不用 gRPC 错误表示业务失败** —— 调用成功返回, +/// 但 `SendResponse.error_code != 0` 表示节点拒绝了这笔交易。只看 `Result::Ok` +/// 会把「被拒绝」当成「已广播」,这是这条链路上最容易漏的一步。 +/// +/// 拒绝抛 `BROADCAST_REJECTED`(不可重试),网络本身出错才抛 `NETWORK_ERROR`。 +pub async fn broadcast(client: &mut LightClient, tx_bytes: Vec) -> Result<()> { + use zcash_client_backend::proto::service::RawTransaction; + + let resp = with_timeout( + async { + client + .send_transaction(RawTransaction { + data: tx_bytes, + // 广播时高度未知;lightwalletd 忽略该字段。 + height: 0, + }) + .await + .map(|response| response.into_inner()) + .map_err(|e| net_err("sendTransaction", e)) + }, + DEFAULT_TIMEOUT_MS, + "sendTransaction", + ) + .await?; + + if resp.error_code != 0 { + // `SendTransaction` is used as an idempotent retry primitive after an + // unknown network outcome. zcashd reports a duplicate through the + // same business-error channel as a real rejection, even though the + // desired postcondition (the node already has the tx) is satisfied. + if broadcast_already_known(&resp.error_message) { + return Ok(()); + } + return Err(RuntimeError::with( + ErrorCode::BroadcastRejected, + json!({ + "errorCode": resp.error_code, + "errorMessage": resp.error_message, + }), + ) + .detail(resp.error_message)); + } + Ok(()) +} + +fn broadcast_already_known(message: &str) -> bool { + let message = message.to_lowercase(); + [ + "already in mempool", + "already in block chain", + "already in blockchain", + "already have transaction", + "txn-already-known", + ] + .iter() + .any(|needle| message.contains(needle)) +} + +/// 诊断:取单个区块并给出结构摘要,不做任何扫描、不写库。 +/// +/// 存在的理由:浏览器走 gRPC-web 代理、原生走真 gRPC,**两边可能根本不是同一个 +/// 服务端**,返回的 compact block 未必一致。排查「同一高度在 wasm 上出问题、 +/// 在原生上正常」时,必须先确认两边拿到的数据是不是同一份,否则一切对比都不成立。 +/// +/// 摘要里带上各池的计数:某个池只在一边出现,就说明是服务端差异而非计算差异。 +pub async fn block_summary(client: &mut LightClient, height: u32) -> Result { + use futures_util::TryStreamExt; + use zcash_client_backend::proto::service::BlockRange; + + let id = |h: u32| BlockId { + height: u64::from(h), + hash: Vec::new(), + }; + let blocks = with_timeout( + async { + client + .get_block_range(BlockRange { + start: Some(id(height)), + end: Some(id(height)), + pool_types: vec![], + }) + .await + .map_err(|e| net_err("getBlockRange", e))? + .into_inner() + .try_collect::>() + .await + .map_err(|e| net_err("getBlockRange", e)) + }, + DEFAULT_TIMEOUT_MS, + "getBlockRange", + ) + .await?; + + let Some(block) = blocks.into_iter().next() else { + return Ok(json!({ "height": height, "found": false }).to_string()); + }; + + let (mut spends, mut outputs, mut actions, mut ironwood) = (0usize, 0usize, 0usize, 0usize); + for tx in &block.vtx { + spends += tx.spends.len(); + outputs += tx.outputs.len(); + actions += tx.actions.len(); + ironwood += tx.ironwood_actions.len(); + } + + Ok(json!({ + "height": height, + "found": true, + // protobuf 编码长度 + 校验和:两边只要有一个 bit 不同就能看出来 + "encodedLen": prost::Message::encoded_len(&block), + "checksum": fnv1a(&prost::Message::encode_to_vec(&block)), + "vtx": block.vtx.len(), + "saplingSpends": spends, + "saplingOutputs": outputs, + "orchardActions": actions, + "ironwoodActions": ironwood, + }) + .to_string()) +} + +/// FNV-1a:只用来比对两端拿到的字节是否一致,不做任何安全用途。 +fn fnv1a(bytes: &[u8]) -> String { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in bytes { + h ^= u64::from(*b); + h = h.wrapping_mul(0x1000_0000_01b3); + } + format!("{h:016x}") +} + +/// 取指定高度的 treestate。 +/// +/// 导入账户时需要它:`AccountBirthday` 要知道 birthday 高度之前的承诺树状态, +/// 否则新账户无法为之后收到的 note 计算 witness。 +pub async fn tree_state(client: &mut LightClient, height: u32) -> Result { + let ts = with_timeout( + async { + client + .get_tree_state(BlockId { + height: u64::from(height), + hash: Vec::new(), + }) + .await + .map(|response| response.into_inner()) + .map_err(|e| net_err("getTreeState", format!("height={height}: {e}"))) + }, + DEFAULT_TIMEOUT_MS, + "getTreeState", + ) + .await?; + Ok(ts) +} + +#[cfg(test)] +mod tests { + use super::{broadcast_already_known, with_timeout}; + use crate::error::{ErrorCode, RuntimeError}; + + #[test] + fn duplicate_broadcast_is_an_idempotent_success() { + for message in [ + "txn-already-known", + "Transaction already in mempool", + "transaction already in block chain", + ] { + assert!(broadcast_already_known(message), "{message}"); + } + assert!(!broadcast_already_known("bad-txns-inputs-missingorspent")); + } + + #[cfg(not(target_arch = "wasm32"))] + #[tokio::test] + async fn stalled_stream_handshake_times_out() { + let result = with_timeout( + async { + futures_util::future::pending::<()>().await; + Ok::<(), RuntimeError>(()) + }, + 10, + "getBlockRange", + ) + .await; + + let error = result.expect_err("a stalled stream handshake must time out"); + assert_eq!(error.code, ErrorCode::NetworkError); + assert_eq!(error.params["operation"], "getBlockRange"); + assert_eq!(error.params["timeoutMs"], 10); + } + + #[cfg(not(target_arch = "wasm32"))] + #[tokio::test] + async fn stream_item_timeout_is_reapplied_for_each_item() { + let mut received = Vec::new(); + for item in 0..4 { + let next = with_timeout( + async { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + Ok::<_, RuntimeError>(item) + }, + 50, + "getBlockRange", + ) + .await + .expect("each stream item arrives before its own timeout"); + received.push(next); + } + + assert_eq!(received, vec![0, 1, 2, 3]); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs new file mode 100644 index 000000000..a3879b244 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs @@ -0,0 +1,65 @@ +//! 临时性能打点:宿主打开开关后,每个重导出的耗时打到 console。 +//! 与宿主侧 `[PRIV-PERF]` 同前缀,一个过滤器看全链路。 + +use std::sync::atomic::{AtomicBool, Ordering}; + +static ENABLED: AtomicBool = AtomicBool::new(false); + +pub fn set_enabled(enabled: bool) { + ENABLED.store(enabled, Ordering::Relaxed); +} + +pub fn is_enabled() -> bool { + ENABLED.load(Ordering::Relaxed) +} + +/// 作用域结束(含跨 await 的 async 函数返回)时打一条耗时。 +pub struct Span { + name: &'static str, + started_ms: f64, +} + +pub fn span(name: &'static str) -> Option { + if !is_enabled() { + return None; + } + Some(Span { + name, + started_ms: now_ms(), + }) +} + +impl Drop for Span { + fn drop(&mut self) { + let ms = now_ms() - self.started_ms; + log(&format!("[PRIV-PERF] rt {} {{\"ms\":{}}}", self.name, ms.round())); + } +} + +#[cfg(target_arch = "wasm32")] +fn now_ms() -> f64 { + js_sys::Date::now() +} + +#[cfg(not(target_arch = "wasm32"))] +fn now_ms() -> f64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs_f64() * 1000.0) + .unwrap_or(0.0) +} + +#[cfg(target_arch = "wasm32")] +fn log(msg: &str) { + #[wasm_bindgen::prelude::wasm_bindgen] + extern "C" { + #[wasm_bindgen(js_namespace = console, js_name = log)] + fn console_log(s: &str); + } + console_log(msg); +} + +#[cfg(not(target_arch = "wasm32"))] +fn log(msg: &str) { + println!("{msg}"); +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs new file mode 100644 index 000000000..1343bf9aa --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs @@ -0,0 +1,210 @@ +//! 跨调用的运行时状态。 +//! +//! 按边界原则,wasm 侧**不持有会话状态** —— 唯一的例外是那个数据库连接和 +//! lightwalletd 客户端,因为每次调用都重开代价太高(重开要重跑一遍迁移检查)。 +//! +//! 除此之外没有任何缓存、没有定时器、没有后台任务。宿主 TS 每调一次, +//! 这里就完整做完一次并返回。 + +use std::cell::{Cell, RefCell}; + +use crate::error::{ErrorCode, Result, RuntimeError}; +use crate::network::LightClient; +use crate::wallet::Db; + +thread_local! { + static DB: RefCell> = const { RefCell::new(None) }; + static CLIENT: RefCell> = const { RefCell::new(None) }; + // 历史查询走 v_transactions 视图,而 WalletDb 不对外暴露内部连接, + // 所以记住库名,需要时另开一条只读连接(同 VFS、同库名 = 同一份数据)。 + static DB_NAME: RefCell> = const { RefCell::new(None) }; + + // ── 并发防线 ──────────────────────────────────────────────────────── + // + // 异步操作会把 DB 从这里**取走**,跨 await 持有,结束后放回。这中间宿主 + // 完全可以再发起别的调用 —— wasm 是单线程,但 await 让重入变得可能。 + // + // 没有防线时的真实竞态: + // 1. A 在 syncStep,DB(A) 已被取走 + // 2. B 调 openWallet(B),DB_NAME 变成 B + // 3. A 结束,把 DB(A) 放回 —— 此刻 DB_NAME 说 B,实际却是 A + // 之后所有操作都在错误的库上进行,而且看不出来:历史串库、余额串库、 + // 甚至可能用 A 的 note 去发 B 的交易。 + // + // 两道防线:BUSY 期间拒绝一切会切换钱包的操作;generation 保证异步返回时 + // 不会用一个过期的钱包覆盖新的。两者独立,任一失效另一个仍能兜住。 + static BUSY: Cell = const { Cell::new(false) }; + static GENERATION: Cell = const { Cell::new(0) }; +} + +/// 正在进行一次异步操作时,任何切换钱包的调用都必须被拒绝。 +fn assert_idle(operation: &str) -> Result<()> { + if BUSY.with(Cell::get) { + return Err(RuntimeError::with( + ErrorCode::WalletBusy, + serde_json::json!({ "operation": operation }), + )); + } + Ok(()) +} + +/// 持有期间标记 BUSY,析构时**一定**清除 —— 包括提前返回和 panic 展开。 +/// +/// ## 它覆盖哪个窗口,不覆盖哪个 +/// +/// wasm-bindgen 的 `async fn` 返回的 Promise 是排进微任务队列的,函数体要等 +/// 当前同步块结束才开始跑。所以存在两个不同的窗口: +/// +/// - **调用之后、函数体开始之前**:此时还没取走任何东西,`openWallet` 会成功, +/// 随后那次操作作用在新库上。这是调用方的时序错误,由宿主侧的租约 +/// (`withWalletLease`)负责序列化,runtime 这里拦不住 —— 拦得住的唯一办法是 +/// 把导出改成同步返回 Promise,代价是所有返回值退化成 `any`,不值得。 +/// - **函数体开始之后、await 期间**:DB 已被取走,此时切库/关库才是真正危险的, +/// 这个窗口由 BUSY 拦住。 +/// +/// 不变量则由 generation 独立保证:无论哪个窗口,异步返回时都不会用一个 +/// 已经作废的钱包覆盖当前的。 +struct BusyGuard { + generation: u64, +} + +impl BusyGuard { + fn acquire(operation: &str) -> Result { + assert_idle(operation)?; + BUSY.with(|b| b.set(true)); + Ok(Self { + // 采样点就是「取走 DB 的那一刻」—— 早于此的切库不算陈旧, + // 那只是这次操作作用在了新库上;晚于此的才是。 + generation: GENERATION.with(Cell::get), + }) + } + + /// 这次操作开始之后,钱包有没有被换掉/关掉。 + fn stale(&self) -> bool { + self.generation != GENERATION.with(Cell::get) + } +} + +impl Drop for BusyGuard { + fn drop(&mut self) { + BUSY.with(|b| b.set(false)); + } +} + +fn bump_generation() { + GENERATION.with(|g| g.set(g.get().wrapping_add(1))); +} + +fn not_open() -> RuntimeError { + RuntimeError::new(ErrorCode::WalletNotOpen) +} + +fn no_client() -> RuntimeError { + RuntimeError::new(ErrorCode::LightwalletdNotConfigured) +} + +/// 打开钱包。正在进行异步操作时会被拒绝 —— 中途换库会让那次操作把结果写到 +/// 错误的地方,而且没有任何迹象。 +pub fn set_db(db: Db, db_name: &str) -> Result<()> { + assert_idle("openWallet")?; + DB.with(|c| *c.borrow_mut() = Some(db)); + DB_NAME.with(|c| *c.borrow_mut() = Some(db_name.to_owned())); + bump_generation(); + Ok(()) +} + +/// 另开一条连接做只读查询(历史等)。 +pub fn with_read_conn(f: impl FnOnce(&rusqlite::Connection) -> Result) -> Result { + let name = DB_NAME.with(|c| c.borrow().clone()).ok_or_else(not_open)?; + let conn = crate::storage::open_connection(&name)?; + f(&conn) +} + +pub fn set_client(client: LightClient) { + CLIENT.with(|c| *c.borrow_mut() = Some(client)); +} + +pub fn has_db() -> bool { + DB.with(|c| c.borrow().is_some()) +} + +/// 借出数据库做一次同步操作。 +/// +/// 用「取出 → 使用 → 放回」而不是长期持有 `RefCell` 借用, +/// 这样即便 `f` 里再次进入本模块也不会 panic。 +pub fn with_db(f: impl FnOnce(&mut Db) -> Result) -> Result { + let mut db = DB.with(|c| c.borrow_mut().take()).ok_or_else(not_open)?; + let out = f(&mut db); + DB.with(|c| *c.borrow_mut() = Some(db)); + out +} + +/// 借出数据库与网络客户端做一次异步操作(扫链、导入账户)。 +/// +/// 同样是取出再放回 —— 异步过程中不持有任何 `RefCell` 借用, +/// 这是在 wasm 单线程上跨 await 安全共享状态的关键。 +pub async fn with_db_and_client(f: F) -> Result +where + F: FnOnce(Db, LightClient) -> Fut, + Fut: std::future::Future)>, +{ + // 先拿锁再取 DB,两者之间没有 await,所以 generation 的采样点与取走 DB + // 是同一时刻 —— 这正是「陈旧」判定成立的前提。 + let guard = BusyGuard::acquire("walletOperation")?; + let db = DB.with(|c| c.borrow_mut().take()).ok_or_else(not_open)?; + let client = match CLIENT.with(|c| c.borrow_mut().take()) { + Some(c) => c, + None => { + DB.with(|cell| *cell.borrow_mut() = Some(db)); + return Err(no_client()); + } + }; + + let (db, client, out) = f(db, client).await; + + // 期间钱包被换掉/关掉时,**丢弃**手上这个而不是放回去。 + // 放回去等于让一个已经作废的钱包覆盖当前的,那正是串库的源头。 + if guard.stale() { + drop(db); + } else { + DB.with(|c| *c.borrow_mut() = Some(db)); + } + CLIENT.with(|c| *c.borrow_mut() = Some(client)); + out +} + +/// 只借出网络客户端,**不要求钱包库已打开**。 +/// +/// 建新账户时链尖是先决条件:宿主要用它定 birthday,而那一刻库还没建。 +/// 如果取链尖也要求先开库,这条路必然失败、失败又被吞成 null, +/// 结果 birthday 退回 Sapling 激活高度,新助记词也要从头扫。 +pub async fn with_client(f: F) -> Result +where + F: FnOnce(LightClient) -> Fut, + Fut: std::future::Future)>, +{ + let client = CLIENT + .with(|c| c.borrow_mut().take()) + .ok_or_else(|| RuntimeError::new(ErrorCode::LightwalletdNotConfigured))?; + let (client, result) = f(client).await; + CLIENT.with(|c| *c.borrow_mut() = Some(client)); + result +} + +/// 当前打开的库名。删除库前要用它判断是不是正在用的那个。 +pub fn open_db_name() -> Option { + DB_NAME.with(|c| c.borrow().clone()) +} + +/// 关闭钱包,释放数据库与客户端。用于账户删除或切换网络。 +/// +/// 异步操作进行中会被拒绝:那次操作手上还握着 DB,此时清空只会让它结束后 +/// 把一个本该消失的钱包放回来。 +pub fn close() -> Result<()> { + assert_idle("closeWallet")?; + DB.with(|c| *c.borrow_mut() = None); + CLIENT.with(|c| *c.borrow_mut() = None); + DB_NAME.with(|c| *c.borrow_mut() = None); + bump_generation(); + Ok(()) +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs new file mode 100644 index 000000000..aef6c6c29 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs @@ -0,0 +1,1015 @@ +//! 发送:PCZT 的构造与广播。 +//! +//! 拆成四段是刻意的 —— **签名那一段不在本 crate**: +//! +//! ```text +//! runtime.pcztCreate() 构造(要钱包状态:选币、witness、anchor) +//! runtime.pcztProve() 证明,纯计算,不碰私钥 +//! keys.pcztSign() 签名(要花费密钥,在 onekey-zcash-keys 里) +//! runtime.pcztSend() 终结 + 写回本地钱包(**不发网络**) +//! runtime.broadcastTransaction() 真正广播出去 +//! ``` +//! +//! 证明必须排在签名之前:上游 Signer 角色的文档写明,它需要足以「验证证明覆盖的是 +//! 正确数据」的信息,也就是签名时证明必须已经在 PCZT 里。 +//! +//! 这条缝是密钥纪律的体现:构造和广播需要钱包数据库,签名需要种子, +//! 两者永远不在同一个 crate 里同时出现。 +//! +//! ## 为什么这些留在 Rust +//! +//! 选币、ZIP-317 费用、anchor 选择、witness —— 这些是**共识相关**的。 +//! 选错 anchor 交易会被拒,算错费可能丢钱。所以机制留在上游实现里。 +//! +//! 但**策略旋钮全部由宿主传入**(找零池、dust 策略、OVK 策略、确认数、 +//! bundle padding),本 crate 不替宿主做产品决策,也不藏默认值。 + +use zcash_client_backend::data_api::locking::LockOwner; +use zcash_client_backend::data_api::wallet::{ + create_pczt_from_proposal, extract_and_store_transaction_from_pczt, + input_selection::GreedyInputSelector, propose_transfer, unlock_proposal_inputs, LockRequest, +}; +use zcash_client_backend::data_api::WalletRead; +use zcash_client_backend::fees::{zip317::SingleOutputChangeStrategy, DustOutputPolicy}; +use zcash_client_backend::wallet::OvkPolicy; +use zcash_primitives::transaction::builder::BundlePadding; +use zcash_primitives::transaction::fees::zip317::FeeRule as Zip317FeeRule; +use zcash_protocol::{memo::MemoBytes, value::Zatoshis, ShieldedPool}; + +use crate::account; +use crate::error::{ErrorCode, Result, RuntimeError}; +use crate::{tx_state, wallet::Db}; +use serde_json::json; + +/// `stage` 是稳定标识,宿主据此知道卡在构造的哪一段。 +fn build_err(stage: &str, e: impl std::fmt::Display) -> RuntimeError { + RuntimeError::with(ErrorCode::TransactionBuildError, json!({ "stage": stage })).detail(e) +} + +/// 把提案阶段的失败翻译成宿主能分支处理的错误码。 +/// +/// 「余额不足」是发送最常见的失败,宿主要据此提示还差多少、要不要减额重试; +/// 「需要先同步」则是让用户等扫描追平后再试。这两种都**不该**被折叠成泛化的 +/// `TRANSACTION_BUILD_ERROR` —— 那样宿主只能拿到一句没法判定的字符串。 +/// +/// **注意上游有两个不同的「余额不足」出处**,两个都要接住: +/// +/// - `Error::InsufficientFunds` —— 选币阶段就凑不够(转账走这条) +/// - `Error::Change(ChangeError::InsufficientFunds)` —— 选币过了,但算上找零和 +/// 手续费之后不够(屏蔽零余额走这条) +/// +/// 只接第一个的话,屏蔽路径会退化成泛化错误 —— 实测踩过。 +fn propose_err( + stage: &str, + e: zcash_client_backend::data_api::error::Error, +) -> RuntimeError +where + DE: std::fmt::Debug, + CT: std::fmt::Debug, + SE: std::fmt::Debug, + FE: std::fmt::Debug, + CHE: std::fmt::Debug, + NR: std::fmt::Debug, +{ + use zcash_client_backend::data_api::error::Error as DataApiError; + use zcash_client_backend::fees::ChangeError; + + let insufficient = |available: &Zatoshis, required: &Zatoshis| { + let (have, need) = (u64::from(*available), u64::from(*required)); + RuntimeError::with( + ErrorCode::InsufficientFunds, + json!({ + "availableZat": have, + "requiredZat": need, + // 直接给差额,省得宿主自己减(还容易减错方向) + "shortfallZat": need.saturating_sub(have), + "stage": stage, + }), + ) + }; + + match &e { + DataApiError::InsufficientFunds { + available, + required, + } => insufficient(available, required), + DataApiError::Change(ChangeError::InsufficientFunds { + available, + required, + }) => insufficient(available, required), + DataApiError::ScanRequired => { + RuntimeError::with(ErrorCode::NotSynced, json!({ "stage": stage })) + } + other => build_err(stage, format!("{other:?}")), + } +} + +/// 把「余额不足」补成「钱在透明池里,先屏蔽」。 +/// +/// 普通转账不花透明 UTXO(见 `SendPolicy::spend_transparent`),所以一个只有 +/// 透明余额的账户拿到的原始错误是 `INSUFFICIENT_FUNDS { availableZat: 0 }` —— +/// 而用户正看着账上有钱。那个 0 说的是「屏蔽池里可花的」,但错误里没有任何 +/// 东西提到池,用户只能去猜。 +/// +/// 这里查一次余额,把差额和透明余额一起放进错误。查询失败就原样返回原错误: +/// 补充信息拿不到不该让整个操作换一个错因。 +fn explain_insufficient( + db: &Db, + account_id: ::AccountId, + err: RuntimeError, +) -> RuntimeError { + use zcash_client_backend::data_api::wallet::ConfirmationsPolicy; + + if err.code != ErrorCode::InsufficientFunds { + return err; + } + + let Ok(Some(summary)) = db.get_wallet_summary(ConfirmationsPolicy::default()) else { + return err; + }; + let Some(balances) = summary.account_balances().get(&account_id) else { + return err; + }; + + let regular = u64::from(balances.unshielded_regular_balance().total()); + let coinbase = u64::from(balances.unshielded_coinbase_balance().total()); + + // 透明池为空时也要走完下面这段。早退会让同一个错误码出现两种形状 —— + // 空账户拿到上游原始的 `availableZat`,有钱的账户拿到补全过的字段, + // 宿主得写两套解析,而两者的差别恰恰是最难在测试里注意到的。 + let num = |k: &str| err.params.get(k).and_then(|v| v.as_u64()); + let shortfall = num("shortfallZat").unwrap_or(0); + + // 三种结局要分开,因为用户该做的事完全不同: + // + // - 普通透明余额补得上:这次没花它(宿主把 spendTransparent 关了), + // 出路是屏蔽,或者允许花透明。 + // - 只有 coinbase 补得上:本钱包**没有任何出口** —— 转账走 NonCoinbase、 + // 屏蔽走 NonCoinbaseOnly,两条都绕开它。这时说「先屏蔽」是把人往死路指。 + // - 都补不上:就是钱不够,但仍要把各池余额报全,用户才不用自己去对 + // 为什么账上的数和错误里的数对不上。 + // shortfall 为 0 时说明缺口读不出来(上游没给这个字段),无从判断哪种情形, + // 保持原样比猜一个更好 —— 否则 `0 >= 0` 会把它误判成「先屏蔽」。 + let code = if shortfall == 0 { + ErrorCode::InsufficientFunds + } else if regular >= shortfall { + ErrorCode::FundsNeedShielding + } else if regular + coinbase >= shortfall { + ErrorCode::CoinbaseFundsUnspendable + } else { + ErrorCode::InsufficientFunds + }; + + RuntimeError::with( + code, + json!({ + "stage": err.params.get("stage").cloned(), + "requiredZat": num("requiredZat"), + "shieldedAvailableZat": num("availableZat"), + "shortfallZat": shortfall, + "transparentZat": regular, + // coinbase 单列:成熟规则不同,而且只能走专门的 coinbase 屏蔽路径, + // `pcztShield` 碰不到它。并成一个数的话,用户会照着提示去点屏蔽, + // 然后发现钱没动。 + "transparentCoinbaseZat": coinbase, + }), + ) +} + +/// 解析宿主传来的找零池名。构造与报价共用,避免两处各写一份而写歪。 +pub fn parse_change_pool(name: &str) -> Result { + match name { + // Orchard 自 NU6.3 起是只出不进的单向闸门 —— 找零进不去。 + // 把它留作合法取值只为历史兼容,新交易不该用。 + "ironwood" => Ok(ShieldedPool::Ironwood), + "orchard" => Ok(ShieldedPool::Orchard), + "sapling" => Ok(ShieldedPool::Sapling), + other => Err(RuntimeError::with( + ErrorCode::TransactionBuildError, + json!({ "stage": "fallbackChangePool", "value": other }), + )), + } +} + +/// 解析宿主传来的「只从这个池子花」。`None` 表示不限制(见 +/// `SendPolicy::spend_source`)。 +/// +/// 与 `parse_change_pool` 分开而不是复用:那里 sapling 是合法取值(历史找零 +/// 目标),这里不是。本方案不发 Sapling 证明,接受 `"sapling"` 只会把一个 +/// 必然在证明阶段失败的请求放进来,还让调用方以为可行。 +pub fn parse_spend_source(name: Option<&str>) -> Result> { + match name { + None => Ok(None), + Some("ironwood") => Ok(Some(ShieldedPool::Ironwood)), + Some("orchard") => Ok(Some(ShieldedPool::Orchard)), + Some(other) => Err(RuntimeError::with( + ErrorCode::TransactionBuildError, + json!({ "stage": "spendSource", "value": other }), + )), + } +} + +/// 宿主可调的发送策略。全部显式传入,本 crate 不藏默认值。 +#[derive(Debug, Clone, Copy)] +pub struct SendPolicy { + /// 可信 note 的确认数门槛(>= 1)。 + pub trusted: u32, + /// 外来 note 的确认数门槛(>= trusted)。 + pub untrusted: u32, + /// 交易全透明时,找零回落到哪个屏蔽池。 + pub fallback_change_pool: ShieldedPool, + /// 是否给 Orchard bundle 填充到固定 action 数(隐藏真实 action 数量, + /// 代价是交易更大、费用更高)。 + pub pad_orchard_bundle: bool, + /// 普通转账允不允许花透明 UTXO。 + /// + /// **这是隐私策略,由宿主决定。** 花透明输入会把被选中的透明地址在链上 + /// 关联起来;上游因此把它做成显式 opt-in,默认一个透明 UTXO 都不花。 + /// + /// 关着的后果是具体的:一个只有透明余额的账户**发不出任何款**, + /// 唯一出口是先 `pcztShield` 屏蔽(多一笔交易、多一份手续费、多一次等待)。 + pub spend_transparent: bool, + /// 零确认的自家屏蔽产出允不允许立刻再花(ZIP-315 建议允许)。 + /// + /// 曾经硬编码 `false`,而余额读取那头却是参数 —— 宿主想跟进 ZIP-315 + /// 就会造出「余额显示可花、选币拒花」的错配。读和花必须同源。 + pub allow_zero_conf_shielding: bool, + /// 只从这一个屏蔽池选 note。`None` = 本方案能花的全部池子。 + /// + /// 存在的理由有两个,都不是可选的: + /// + /// 1. **Sapling 必须排除。** 上游 `SpendPolicy::default()` 允许 sapling, + /// 而选币是「最老的合格 note 优先」—— 一个恢复了 2022 年前历史的账户, + /// 每一笔转账都会先挑中 sapling note,然后在证明阶段撞上 + /// `PROVE_SAPLING = false`。那笔钱花不了是事实,但因此**整个账户发不出 + /// 任何交易**不是。默认集合把它挡在选币之外,用户就能正常花其他池子。 + /// + /// 2. **按池子提取需要它。** 「把旧 Orchard 余额转到透明地址」这个动作, + /// 没有它就只是一笔普通转账,选币可能去花 Ironwood —— 把用户还想留在 + /// 私密池里的钱搬到了链上公开的地址。上游文档给的例子正是这个用法。 + /// + /// 指定一个池子时,凑不够就是 `InsufficientFunds`,上游保证不会越池。 + pub spend_source: Option, +} + +impl SendPolicy { + fn change_pool(&self) -> ShieldedPool { + self.fallback_change_pool + } + + fn padding(&self) -> BundlePadding { + if self.pad_orchard_bundle { + BundlePadding::DEFAULT + } else { + BundlePadding::UNPADDED + } + } +} + +/// 一次转账提案。`create_pczt` 与 `quote` 共用 —— 两者的选币、费率、找零策略 +/// 必须完全一致,否则报价和实际构造会对不上,用户看到的费用就是假的。 +type TransferProposal = + zcash_client_backend::proposal::Proposal; +type ShieldingProposal = + zcash_client_backend::proposal::Proposal; + +fn build_proposal( + db: &mut Db, + account_uuid: &str, + to_address: &str, + amount_zat: u64, + memo: Option<&str>, + policy: SendPolicy, + lock: Option, +) -> Result { + let params = *db.params(); + let account_id = account::parse_account_id(db, account_uuid)?; + + // 零值:上游只对透明收款方拒绝,屏蔽收款方会建出一笔只付手续费的交易。 + let amount = Zatoshis::from_u64(amount_zat) + .ok() + .filter(|a| !a.is_zero()) + .ok_or_else(|| { + RuntimeError::with( + ErrorCode::AmountOutOfRange, + json!({ "valueZat": amount_zat }), + ) + })?; + + let recipient = zcash_address::ZcashAddress::try_from_encoded(to_address).map_err(|e| { + RuntimeError::with(ErrorCode::InvalidAddress, json!({ "value": to_address })).detail(e) + })?; + + let memo_bytes = match memo { + None => None, + Some(m) => { + let parsed = zcash_protocol::memo::Memo::from_bytes(m.as_bytes()).map_err(|e| { + RuntimeError::with(ErrorCode::InvalidMemo, json!({ "byteLen": m.len() })).detail(e) + })?; + Some(MemoBytes::from(&parsed)) + } + }; + + // Payment::new 会自己校验「透明地址不能带 memo」这类约束。 + let payment = zip321::Payment::new(recipient, Some(amount), memo_bytes, None, None, vec![]) + .map_err(|e| { + RuntimeError::with(ErrorCode::InvalidMemo, json!({ "reason": "payment" })) + .detail(format!("{e:?}")) + })?; + + let request = zip321::TransactionRequest::new(vec![payment]) + .map_err(|e| build_err("transactionRequest", format!("{e:?}")))?; + + let confirmations = account::confirmations_policy( + policy.trusted, + policy.untrusted, + policy.allow_zero_conf_shielding, + )?; + + // 花费来源策略。默认(SpendPolicy::default)**一个透明 UTXO 都不花** —— + // 于是只有透明余额的账户会以 INSUFFICIENT_FUNDS 收场,且 availableZat 报 0。 + // 打开它就允许从本账户的透明 receiver 取,代价是被选中的地址在链上互相关联。 + let spend_policy = { + use zcash_client_backend::data_api::wallet::input_selection::{ + SpendPolicy, TransparentSpendPolicy, + }; + // 不用 SpendPolicy::default():它允许 sapling。见 SendPolicy::spend_source。 + // 屏蔽池之间永不并池(docs/08),而"当前池"只在宿主一处定义 + // (ZCASH_CURRENT_SHIELDED_POOL):这里不藏缺省,缺参直接拒绝。 + let pool = policy.spend_source.ok_or_else(|| { + RuntimeError::with( + ErrorCode::TransactionBuildError, + json!({ "stage": "spendSource", "reason": "required" }), + ) + })?; + let base = SpendPolicy::shielded_pools([pool]); + if policy.spend_transparent { + base.with_transparent(TransparentSpendPolicy::any_account_addr()) + } else { + base + } + }; + + let selector = GreedyInputSelector::::new(); + let change = SingleOutputChangeStrategy::<_, Db>::new( + Zip317FeeRule::standard(), + None, + policy.change_pool(), + DustOutputPolicy::default(), + ); + + // 显式标注 commitment-tree 错误类型:这一处泛型推不出来。 + let proposal = + propose_transfer::( + db, + ¶ms, + account_id, + &selector, + &change, + request, + confirmations, + &spend_policy, + lock, + None, + ); + + // db 的可变借用到这里就结束了,所以失败路径上可以再查一次余额, + // 把「余额不足」补成「钱在透明池里」。 + let proposal = match proposal { + Ok(p) => p, + Err(e) => { + return Err(explain_insufficient( + db, + account_id, + propose_err("proposeTransfer", e), + )) + } + }; + + Ok(proposal) +} + +/// 只出费用,不构造 PCZT、不锁定 note。 +/// +/// 用途是发送前给用户看手续费。**必须与 `create_pczt` 走同一条提案路径**, +/// 否则报价与实付不符 —— 那是最难被发现、也最不该发生的一类 bug。 +pub fn quote( + db: &mut Db, + account_uuid: &str, + to_address: &str, + amount_zat: u64, + memo: Option<&str>, + policy: SendPolicy, +) -> Result { + let proposal = build_proposal(db, account_uuid, to_address, amount_zat, memo, policy, None)?; + let fee: u64 = proposal + .steps() + .iter() + .map(|s| u64::from(s.balance().fee_required())) + .sum(); + + // 这笔钱实际从哪儿取。宿主要给出「会花掉你的透明余额」这类提醒,就得先知道 + // 答案 —— 而在真正构造之前,只有提案知道。光给手续费的话,宿主只能拿一个 + // 布尔开关去问用户,而用户没有任何依据来回答。 + let mut transparent_in = 0u64; + let mut shielded_in = 0u64; + for step in proposal.steps() { + transparent_in += step + .transparent_inputs() + .iter() + .map(|o| u64::from(o.txout().value())) + .sum::(); + if let Some(inputs) = step.shielded_inputs() { + shielded_in += inputs + .notes() + .iter() + .map(|n| u64::from(n.note().value())) + .sum::(); + } + } + + // 用了透明输入时,顺手算一遍「只用屏蔽余额」要多少手续费。 + // + // 这不是给运行时用来做决定的 —— 它只是把选择的代价摆出来。透明输入按 + // ZIP-317 各自计入 logical action,实测同一笔付款用透明要 20000、只用屏蔽 + // 要 10000。差一倍的事不告诉用户,用户就没法评估。 + // + // 屏蔽余额本来就不够时提不出方案,此时报 null,宿主别显示这条建议。 + let shielded_only_fee = if transparent_in > 0 { + let mut alt = policy; + alt.spend_transparent = false; + build_proposal(db, account_uuid, to_address, amount_zat, memo, alt, None) + .ok() + .map(|p| { + p.steps() + .iter() + .map(|s| u64::from(s.balance().fee_required())) + .sum::() + }) + } else { + None + }; + + Ok(json!({ + "feeZat": fee, + "steps": proposal.steps().len(), + "sourceTransparentZat": transparent_in, + "sourceShieldedZat": shielded_in, + // 同一笔里既花透明又花屏蔽 —— 链上因此把这个 t 地址和一次屏蔽花费绑在 + // 一起。这是花透明输入唯一**新增**的暴露:只花透明的话,对外和一笔普通 + // 屏蔽交易没有区别(透明进、屏蔽出)。值得单独提醒的就是这一种。 + "linksTransparentToShielded": transparent_in > 0 && shielded_in > 0, + // 只用屏蔽余额的手续费;null = 屏蔽余额不够,提不出这个方案。 + "shieldedOnlyFeeZat": shielded_only_fee, + }) + .to_string()) +} + +// ── note 锁定(宿主契约里的 reservation) ──────────────────────────────── +// +// 屏蔽池里的钱是一个个 note,性质像 UTXO:整个花掉,花时公布 nullifier, +// 同一个 note 被两笔交易花,第二笔必被节点拒绝。 +// +// 而发送流水线中间有一段「已选币、未花掉」的窗口: +// 选币 → 审核页 → 输密码 → 签名 → 广播 +// 用户在审核页停着又发起第二笔(或点了 shield),选币器会把同一批 note 再选一遍。 +// +// 锁定就是在选币时把这批 note 标记为已被某个操作占用,别的选币跳过; +// 用户取消就 release 还回去。上游还带按区块高度的过期时间,兜住「app 中途崩了」。 +// +// 提案本身要留在内存里:`unlock_proposal_inputs` 需要提案才知道该解锁哪些 note。 +thread_local! { + static RESERVATIONS: std::cell::RefCell< + std::collections::HashMap, + > = std::cell::RefCell::new(std::collections::HashMap::new()); +} + +fn hex32(bytes: &[u8; 32]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn parse_owner(reservation_id: &str) -> Result { + let bad = || { + RuntimeError::with( + ErrorCode::InvalidReservationId, + json!({ "value": reservation_id }), + ) + }; + if reservation_id.len() != 64 { + return Err(bad()); + } + let mut out = [0u8; 32]; + for (i, chunk) in reservation_id.as_bytes().chunks(2).enumerate() { + let hex = std::str::from_utf8(chunk).map_err(|_| bad())?; + out[i] = u8::from_str_radix(hex, 16).map_err(|_| bad())?; + } + Ok(LockOwner::new(out)) +} + +/// 释放一次 reservation 占用的 note。 +/// +/// 幂等:id 不存在(已发送、已释放、或本来就没锁过)返回 `false` 而不报错 —— +/// 取消路径上重复调用是常态,不该因此弹错误给用户。 +pub fn release_reservation(db: &mut Db, reservation_id: &str) -> Result { + let owner = parse_owner(reservation_id)?; + + // Finalization is committed in the wallet database before the host can + // observe the txid. A durability/bridge failure can therefore leave the + // host holding a reservation id for a transaction that already spends the + // selected notes. In that state release must only discard the in-memory + // proposal; unlocking its inputs would make spent notes selectable again. + let finalized_txid = db.transactionally_with_extension(|_wallet, ext| { + tx_state::existing_txid_for_reservation(ext, reservation_id) + })?; + if finalized_txid.is_some() { + forget_reservation(reservation_id); + return Ok(false); + } + + // 转账与屏蔽的提案类型不同,分两张表存;两边都要查,否则取消屏蔽时锁放不开。 + if let Some((account_uuid, proposal)) = + RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id)) + { + if let Err(e) = unlock_proposal_inputs(db, &proposal, owner) { + RESERVATIONS.with(|r| { + r.borrow_mut() + .insert(reservation_id.to_owned(), (account_uuid, proposal)); + }); + return Err(build_err("unlockProposalInputs", format!("{e:?}"))); + } + return Ok(true); + } + if let Some((account_uuid, proposal)) = + SHIELD_RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id)) + { + if let Err(e) = unlock_proposal_inputs(db, &proposal, owner) { + SHIELD_RESERVATIONS.with(|r| { + r.borrow_mut() + .insert(reservation_id.to_owned(), (account_uuid, proposal)); + }); + return Err(build_err("unlockProposalInputs", format!("{e:?}"))); + } + return Ok(true); + } + Ok(false) +} + +/// 交易已落库后丢弃 reservation 记录。 +/// +/// 此时锁已由花费本身接管(note 真的被花掉了),不需要也不应该再解锁 —— +/// 解锁会把已经花出去的 note 重新放回可选池。 +pub fn forget_reservation(reservation_id: &str) { + RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id)); + SHIELD_RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id)); +} + +/// Whether this process still owns an in-flight proposal for the account. +/// Account repair must not delete the account while such a proposal exists: +/// the caller still holds its reservation id and may be proving or signing it. +pub fn has_active_reservations(account_uuid: &str) -> bool { + RESERVATIONS.with(|reservations| { + reservations + .borrow() + .values() + .any(|(owner_account_uuid, _)| owner_account_uuid == account_uuid) + }) || SHIELD_RESERVATIONS.with(|reservations| { + reservations + .borrow() + .values() + .any(|(owner_account_uuid, _)| owner_account_uuid == account_uuid) + }) +} + +/// 构造一笔转账的 PCZT(未签名),并**锁住选中的 note**。 +/// +/// 返回 `{ pcztHex, reservationId }`:`reservationId` 是这批 note 的占用凭证, +/// 调用方必须一直带着它,直到交易发出(`pcztSend`)或用户取消(`releaseReservation`)。 +/// 不释放也不会永久卡死 —— 锁有按区块高度的过期时间,但那是兜底,不是正常路径。 +/// +/// `lock_for_blocks` 是策略:它要覆盖「构造完成 → 交易落库」的最坏耗时。 +/// 太短则用户还在审核页锁就过期了,太长则取消后 note 白白冻着。由宿主决定。 +/// +/// `reservation_id` 可由调用方传入(64 位 hex)。上游的设计意图就是**调用方持有 +/// 这个 token**:先生成、先持久化,再来构造。这样即使中途崩溃,恢复后仍然知道 +/// 该释放哪一批 note,或者重新锁住自己那批。不传则由这里随机生成。 +// The public binding keeps proposal policy explicit at the call boundary. +#[allow(clippy::too_many_arguments)] +pub fn create_pczt( + db: &mut Db, + account_uuid: &str, + to_address: &str, + amount_zat: u64, + memo: Option<&str>, + policy: SendPolicy, + lock_for_blocks: u32, + reservation_id: Option<&str>, +) -> Result<(Vec, String, u64)> { + let params = *db.params(); + let account_id = account::parse_account_id(db, account_uuid)?; + + let owner = match reservation_id { + Some(id) => parse_owner(id)?, + None => LockOwner::random(&mut rand::rngs::OsRng), + }; + let reservation_id = hex32(owner.as_bytes()); + let proposal = build_proposal( + db, + account_uuid, + to_address, + amount_zat, + memo, + policy, + Some(LockRequest::new(owner, lock_for_blocks)), + )?; + let fee_zat = proposal + .steps() + .iter() + .map(|step| u64::from(step.balance().fee_required())) + .sum(); + + // 同理:InputsErrT / ChangeErrT 只出现在 Err 分支,推不出来。 + // 提案已经锁住了 note。从这里往下任何失败都必须**先解锁再返回** —— + // 否则调用方拿不到 reservationId(我们还没返回它),就永远没法释放, + // 那批 note 会一直冻到锁自然过期。 + let built = (|| -> Result> { + let pczt = create_pczt_from_proposal::< + Db, + _, + std::convert::Infallible, + _, + std::convert::Infallible, + _, + >( + db, + ¶ms, + account_id, + OvkPolicy::Sender, + &proposal, + None, + policy.padding(), + ) + .map_err(|e| build_err("createPczt", format!("{e:?}")))?; + + pczt.serialize().map_err(|e| { + RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "serialize" })) + .detail(format!("{e:?}")) + }) + })(); + + let bytes = match built { + Ok(b) => b, + Err(e) => { + // 尽力解锁。解锁本身再失败也只能吞掉 —— 真正的错误是上面那个, + // 不该被一个清理动作的错误盖掉;锁还有过期时间兜底。 + let _ = unlock_proposal_inputs(db, &proposal, owner); + return Err(e); + } + }; + + // 提案要留着:解锁时需要它才知道该放开哪些 note。 + RESERVATIONS.with(|r| { + r.borrow_mut() + .insert(reservation_id.clone(), (account_uuid.to_owned(), proposal)); + }); + Ok((bytes, reservation_id, fee_zat)) +} + +/// 用哪个电路版本证明,由**共识分支**决定,不是产品选项。 +/// +/// 这里从网络参数与当前链尖推导:链尖过了 NU6.3 激活高度就用 PostNu6_3, +/// 否则用 FixedPostNu6_2。`InsecurePreNu6_2` 永远不用于证明(上游明确标注)。 +fn circuit_version_for( + params: &zcash_protocol::consensus::Network, + chain_tip: zcash_protocol::consensus::BlockHeight, +) -> orchard::circuit::OrchardCircuitVersion { + use zcash_protocol::consensus::{NetworkUpgrade, Parameters}; + match params.activation_height(NetworkUpgrade::Nu6_3) { + Some(height) if chain_tip >= height => orchard::circuit::OrchardCircuitVersion::PostNu6_3, + _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2, + } +} + +/// 给 PCZT 生成 Orchard / Ironwood 零知识证明。 +pub fn prove_pczt(db: &Db, pczt_bytes: &[u8]) -> Result> { + let params = *db.params(); + let chain_tip = db + .chain_height() + .map_err(|error| build_err("chainHeight", error))? + .ok_or_else(|| RuntimeError::new(ErrorCode::NotSynced))?; + let version = circuit_version_for(¶ms, chain_tip); + let pczt = pczt::Pczt::parse(pczt_bytes).map_err(|error| { + RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "parse" })) + .detail(format!("{error:?}")) + })?; + let prover = pczt::roles::prover::Prover::new(pczt); + + let prover = if prover.requires_ironwood_proof() { + let proving_key = orchard::circuit::ProvingKey::build(version); + prover + .create_ironwood_proof(&proving_key) + .map_err(|error| { + RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "ironwoodProof" })) + .detail(format!("{error:?}")) + })? + } else { + prover + }; + + if prover.requires_sapling_proofs() { + return Err(RuntimeError::with( + ErrorCode::Unimplemented, + json!({ "what": "saplingProof" }), + )); + } + + let prover = if prover.requires_orchard_proof() { + let proving_key = orchard::circuit::ProvingKey::build(version); + prover.create_orchard_proof(&proving_key).map_err(|error| { + RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "orchardProof" })) + .detail(format!("{error:?}")) + })? + } else { + prover + }; + + prover.finish().serialize().map_err(|error| { + RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "serializeProven" })) + .detail(format!("{error:?}")) + }) +} + +/// 终结已签名的 PCZT,提取交易并写回钱包,返回 txid。 +/// +/// 写回是必要的:钱包要立刻知道这笔花费占用了哪些 note, +/// 否则下一笔可能重复选中同一批 —— `zcash_client_sqlite` 的 note locking 负责这件事。 +/// +/// **不校验零知识证明。** 上游允许在此处传入 verifying key 做一次证明校验, +/// 但那需要现场构建 Orchard 电路(很贵),而这个 PCZT 是本机刚构造并签名的 —— +/// 校验它等于校验自己。若将来接受外部传入的 PCZT(多签、离线签名机), +/// 必须在这里补上校验,否则会把无效证明写进钱包。 +pub fn extract_and_store( + db: &mut Db, + account_uuid: &str, + pczt_bytes: &[u8], + reservation_id: &str, +) -> Result { + let pczt = pczt::Pczt::parse(pczt_bytes).map_err(|e| { + RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "parse" })) + .detail(format!("{e:?}")) + })?; + + db.transactionally_with_extension(|wallet, ext| { + if let Some(txid) = tx_state::existing_txid_for_reservation(ext, reservation_id)? { + return Ok(txid); + } + let txid = + extract_and_store_transaction_from_pczt::<_, zcash_client_sqlite::ReceivedNoteId>( + wallet, pczt, None, None, + ) + .map_err(|e| build_err("extractAndStore", format!("{e:?}")))? + .to_string(); + tx_state::insert_finalized(ext, &txid, account_uuid, reservation_id)?; + Ok(txid) + }) +} + +/// 从钱包库取出已提取交易的原始字节,供广播使用。 +/// +/// `extract_and_store` 只落库、不发网络,广播是**独立的一步**:这样宿主可以在 +/// 落库之后、真正发出去之前插入确认环节,也能在广播失败后原样重试而不必重建交易。 +pub fn raw_transaction(db: &Db, txid: &str) -> Result> { + use zcash_primitives::transaction::TxId; + + let bytes = hex::decode(txid) + .ok() + .filter(|b| b.len() == 32) + .ok_or_else(|| { + RuntimeError::with(ErrorCode::TransactionBuildError, json!({ "stage": "txid" })) + })?; + // txid 字符串是显示序(大端),内部表示是小端。 + let mut internal = [0u8; 32]; + for (i, b) in bytes.iter().rev().enumerate() { + internal[i] = *b; + } + + let tx = db + .get_transaction(TxId::from_bytes(internal)) + .map_err(|e| build_err("getTransaction", e))? + .ok_or_else(|| { + RuntimeError::with( + ErrorCode::TransactionBuildError, + json!({ "stage": "getTransaction", "txid": txid }), + ) + })?; + + let mut raw = Vec::new(); + tx.write(&mut raw) + .map_err(|e| build_err("serializeTransaction", e))?; + Ok(raw) +} + +/// The separately loaded prover package supports these proof types. +pub const PROVE_ORCHARD: bool = true; +pub const PROVE_SAPLING: bool = false; +pub const PROVE_IRONWOOD: bool = true; + +/// 构造一笔「屏蔽全部透明余额」的 PCZT,并锁住选中的透明 UTXO。 +/// +/// ## 为什么它不是普通转账 +/// +/// 钱落在 t 地址那一刻就和用户公开绑定了。屏蔽是把它搬进隐私池, +/// 让之后的花费别人看不见。所以它: +/// +/// - **没有收款地址** —— 收款方就是本账户自己的屏蔽地址 +/// - **没有金额** —— 扫走全部透明余额。留零头等于白搭:它照样公开, +/// 将来还要再付一次手续费才能搬走 +/// +/// `shielding_threshold` 是宿主的策略:透明余额低于它就不值得屏蔽(手续费可能 +/// 超过金额本身)。低于阈值时上游报「余额不足」,我们照常映射成 +/// `INSUFFICIENT_FUNDS`,宿主可据此提示「金额太小,暂不值得屏蔽」。 +/// +/// 只屏蔽非 coinbase 输出:coinbase 有单独的成熟度规则,上游要求走 +/// `propose_shielding_coinbase`。矿工场景不在本钱包的目标内。 +fn build_shielding_proposal( + db: &mut Db, + account_uuid: &str, + shielding_threshold_zat: u64, + policy: SendPolicy, + lock: Option, +) -> Result { + use zcash_client_backend::data_api::wallet::propose_shielding; + use zcash_client_backend::data_api::CoinbaseFilter; + + let params = *db.params(); + let account_id = account::parse_account_id(db, account_uuid)?; + + let threshold = Zatoshis::from_u64(shielding_threshold_zat).map_err(|_| { + RuntimeError::with( + ErrorCode::AmountOutOfRange, + json!({ "valueZat": shielding_threshold_zat }), + ) + })?; + + // 本账户名下全部透明收款地址(含找零与独立地址)—— 屏蔽是「扫干净」, + // 漏掉任何一个地址都会留下公开残额。 + let receivers = db + .get_transparent_receivers(account_id, true, true) + .map_err(|e| build_err("getTransparentReceivers", e))?; + if receivers.is_empty() { + return Err(RuntimeError::with( + ErrorCode::InsufficientFunds, + json!({ "availableZat": 0, "requiredZat": shielding_threshold_zat, "reason": "noTransparentAddress" }), + )); + } + let from_addrs: Vec<_> = receivers.keys().copied().collect(); + + let confirmations = account::confirmations_policy( + policy.trusted, + policy.untrusted, + policy.allow_zero_conf_shielding, + )?; + let selector = GreedyInputSelector::::new(); + let change = SingleOutputChangeStrategy::<_, Db>::new( + Zip317FeeRule::standard(), + None, + policy.change_pool(), + DustOutputPolicy::default(), + ); + + propose_shielding::( + db, + ¶ms, + &selector, + &change, + threshold, + &from_addrs, + account_id, + confirmations, + CoinbaseFilter::NonCoinbaseOnly, + lock, + ) + .map_err(|e| propose_err("proposeShielding", e)) +} + +/// Exact ZIP-317 fee for the same sweep proposal used by `create_shielding_pczt`. +/// It does not lock transparent UTXOs or construct a PCZT. +pub fn quote_shielding( + db: &mut Db, + account_uuid: &str, + shielding_threshold_zat: u64, + policy: SendPolicy, +) -> Result { + let proposal = + build_shielding_proposal(db, account_uuid, shielding_threshold_zat, policy, None)?; + Ok(proposal + .steps() + .iter() + .map(|step| u64::from(step.balance().fee_required())) + .sum()) +} + +pub fn create_shielding_pczt( + db: &mut Db, + account_uuid: &str, + shielding_threshold_zat: u64, + policy: SendPolicy, + lock_for_blocks: u32, + reservation_id: Option<&str>, +) -> Result<(Vec, String, u64)> { + let params = *db.params(); + let account_id = account::parse_account_id(db, account_uuid)?; + let owner = match reservation_id { + Some(id) => parse_owner(id)?, + None => LockOwner::random(&mut rand::rngs::OsRng), + }; + let reservation_id = hex32(owner.as_bytes()); + let proposal = build_shielding_proposal( + db, + account_uuid, + shielding_threshold_zat, + policy, + Some(LockRequest::new(owner, lock_for_blocks)), + )?; + let fee_zat = proposal + .steps() + .iter() + .map(|step| u64::from(step.balance().fee_required())) + .sum(); + + // 同 create_pczt:提案已锁 note,之后失败必须先解锁再返回。 + let built = (|| -> Result> { + let pczt = create_pczt_from_proposal::< + Db, + _, + std::convert::Infallible, + _, + std::convert::Infallible, + _, + >( + db, + ¶ms, + account_id, + OvkPolicy::Sender, + &proposal, + None, + policy.padding(), + ) + .map_err(|e| build_err("createShieldingPczt", format!("{e:?}")))?; + + pczt.serialize().map_err(|e| { + RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "serialize" })) + .detail(format!("{e:?}")) + }) + })(); + + let bytes = match built { + Ok(b) => b, + Err(e) => { + let _ = unlock_proposal_inputs(db, &proposal, owner); + return Err(e); + } + }; + + SHIELD_RESERVATIONS.with(|r| { + r.borrow_mut() + .insert(reservation_id.clone(), (account_uuid.to_owned(), proposal)); + }); + Ok((bytes, reservation_id, fee_zat)) +} + +// 屏蔽提案的 NoteRef 类型与转账不同(Infallible),所以单独存一张表。 +thread_local! { + static SHIELD_RESERVATIONS: std::cell::RefCell< + std::collections::HashMap, + > = std::cell::RefCell::new(std::collections::HashMap::new()); +} + +/// 释放某账户当前被锁住的**全部** note。 +/// +/// ## 为什么需要它 +/// +/// `releaseReservation` 靠内存里的提案表定位要解锁哪些 note。app 或 offscreen +/// 重启后那张表就没了 —— 此时旧的 reservationId 既解不开锁,也无从知道锁了什么, +/// 那批 note 会一直冻到过期。 +/// +/// 这是宿主的「状态修复」入口:不需要 token,直接把该账户名下所有锁清掉。 +/// 代价是会连带放开**正在进行中**的提案,所以只该由用户主动触发的修复动作调用, +/// 不能在正常流程里用。 +pub fn clear_locked_outputs(db: &mut Db, account_uuid: &str) -> Result { + use zcash_client_backend::data_api::OutputLockStore; + + let account_id = account::parse_account_id(db, account_uuid)?; + let n = db + .clear_locked_outputs(account_id) + .map_err(|e| build_err("clearLockedOutputs", e))?; + + RESERVATIONS.with(|r| { + r.borrow_mut() + .retain(|_, (owner_account_uuid, _)| owner_account_uuid != account_uuid); + }); + SHIELD_RESERVATIONS.with(|r| { + r.borrow_mut() + .retain(|_, (owner_account_uuid, _)| owner_account_uuid != account_uuid); + }); + Ok(n as u32) +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs new file mode 100644 index 000000000..bc52ff08a --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs @@ -0,0 +1,277 @@ +//! 存储用量统计。**只读,固定 SQL,不改任何数据。** +//! +//! 存在的理由:`diagSelfCheck` 只能报出表 / 视图 / 索引的**数量**,答不了 +//! 「哪一组数据占了多少字节」。没有这个数,任何裁剪都是盲改 —— 先量再改。 +//! +//! 刻意**不**提供「执行任意 SQL」的接口:那等于把数据库交给宿主, +//! 一条写错的语句就能删掉仍待证明的 anchor。这里的每条查询都是写死的。 +//! +//! 所有 SQL 里的表名与列名都来自 `wallet.rs::tests::dump_schema` 的实测输出, +//! 不是照文档抄的 —— 表名写错时 SQLite 会报错而不是安静返回 0,但列名写错 +//! 在某些聚合下会返回 NULL,所以两者都必须对着真实 schema 核过。 + +use crate::error::{ErrorCode, Result, RuntimeError}; +use rusqlite::Connection; +use serde_json::{json, Value}; + +fn db_err(op: &str, e: impl std::fmt::Debug) -> RuntimeError { + RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": op })) + .detail(format!("{e:?}")) +} + +fn count(conn: &Connection, sql: &str, op: &str) -> Result { + conn.query_row(sql, [], |r| r.get(0)) + .map_err(|e| db_err(op, e)) +} + +/// `SUM` 在空表上返回 NULL,直接 `get::` 会失败 —— 用 Option 接住并归零。 +fn sum(conn: &Connection, sql: &str, op: &str) -> Result { + conn.query_row(sql, [], |r| r.get::<_, Option>(0)) + .map(|v| v.unwrap_or(0)) + .map_err(|e| db_err(op, e)) +} + +fn opt_i64(conn: &Connection, sql: &str, op: &str) -> Result { + conn.query_row(sql, [], |r| r.get::<_, Option>(0)) + .map(|v| v.map_or(Value::Null, |n| json!(n))) + .map_err(|e| db_err(op, e)) +} + +/// 一棵树的用量。三个池的表名只差前缀,所以共用这一段。 +fn tree_stats(conn: &Connection, prefix: &str) -> Result { + Ok(json!({ + "shards": count(conn, &format!("SELECT COUNT(*) FROM {prefix}_tree_shards"), "shards")?, + // shard_data 是聚合后的树分片,通常是数据库里最大的 BLOB 列。 + "shardBytes": sum( + conn, + &format!("SELECT SUM(LENGTH(shard_data)) FROM {prefix}_tree_shards"), + "shardBytes", + )?, + "checkpoints": count( + conn, + &format!("SELECT COUNT(*) FROM {prefix}_tree_checkpoints"), + "checkpoints", + )?, + // ZIP-318 的 durable anchor。它们**不受**普通 100 深度上限约束, + // 而 runtime 目前没有任何回收路径,所以这个数只会单调增长 —— + // 这正是需要先量出来的东西。 + "retained": count( + conn, + &format!("SELECT COUNT(*) FROM {prefix}_tree_retained_checkpoints"), + "retained", + )?, + "marksRemoved": count( + conn, + &format!("SELECT COUNT(*) FROM {prefix}_tree_checkpoint_marks_removed"), + "marksRemoved", + )?, + })) +} + +/// 分组统计当前钱包库的用量,JSON 字符串。 +pub fn storage_stats(conn: &Connection) -> Result { + // 总量走 PRAGMA:`dbstat` 虚拟表未必编进当前 SQLite,PRAGMA 一定在。 + let page_size = count(conn, "PRAGMA page_size", "pageSize")?; + let page_count = count(conn, "PRAGMA page_count", "pageCount")?; + let free_pages = count(conn, "PRAGMA freelist_count", "freelistCount")?; + + Ok(json!({ + "sqlite": { + "pageSize": page_size, + "pageCount": page_count, + "freePages": free_pages, + // 页数 × 页大小。这是**逻辑**大小,不等于 IndexedDB 的物理占用 —— + // 那边有写放大、旧版本页和异步刷盘,两个数不该互相外推。 + "logicalBytes": page_size * page_count, + }, + "scan": { + "minHeight": opt_i64(conn, "SELECT MIN(height) FROM blocks", "minHeight")?, + "maxHeight": opt_i64(conn, "SELECT MAX(height) FROM blocks", "maxHeight")?, + // 严格随「已扫块数」线性增长,是最明确的线性项。 + // 注意:它不是 compact block 本身,每行只有 height/hash/time 和三池的 + // 树大小与 action 计数。 + "blockRows": count(conn, "SELECT COUNT(*) FROM blocks", "blockRows")?, + "rangeRows": count(conn, "SELECT COUNT(*) FROM scan_queue", "rangeRows")?, + }, + "trees": { + "sapling": tree_stats(conn, "sapling")?, + "orchard": tree_stats(conn, "orchard")?, + "ironwood": tree_stats(conn, "ironwood")?, + }, + "wallet": { + "accounts": count(conn, "SELECT COUNT(*) FROM accounts", "accounts")?, + "addresses": count(conn, "SELECT COUNT(*) FROM addresses", "addresses")?, + "transactions": count(conn, "SELECT COUNT(*) FROM transactions", "transactions")?, + // 完整交易字节,只在本钱包构造或做过 enhancement 后才有。 + "rawTxBytes": sum(conn, "SELECT SUM(LENGTH(raw)) FROM transactions", "rawTxBytes")?, + "notes": count( + conn, + "SELECT (SELECT COUNT(*) FROM sapling_received_notes) + + (SELECT COUNT(*) FROM orchard_received_notes) + + (SELECT COUNT(*) FROM ironwood_received_notes)", + "notes", + )?, + "memoBytes": sum( + conn, + "SELECT (SELECT COALESCE(SUM(LENGTH(memo)), 0) FROM sapling_received_notes) + + (SELECT COALESCE(SUM(LENGTH(memo)), 0) FROM orchard_received_notes) + + (SELECT COALESCE(SUM(LENGTH(memo)), 0) FROM ironwood_received_notes) + + (SELECT COALESCE(SUM(LENGTH(memo)), 0) FROM sent_notes)", + "memoBytes", + )?, + "transparentOutputs": count( + conn, + "SELECT COUNT(*) FROM transparent_received_outputs", + "transparentOutputs", + )?, + }, + // 有界或有删除路径的几组。官方把 nullifier_map 裁到最近 100 块, + // 所以这里的数**不该**随链头无限增长 —— 长了说明裁剪没生效。 + "transient": { + "nullifiers": count(conn, "SELECT COUNT(*) FROM nullifier_map", "nullifiers")?, + "locators": count(conn, "SELECT COUNT(*) FROM tx_locator_map", "locators")?, + "retrievalQueue": count( + conn, + "SELECT COUNT(*) FROM tx_retrieval_queue", + "retrievalQueue", + )?, + "spendSearchQueue": count( + conn, + "SELECT COUNT(*) FROM transparent_spend_search_queue", + "spendSearchQueue", + )?, + }, + "poolMigration": { + "runs": count( + conn, + "SELECT COUNT(*) FROM orchard_ironwood_migrations", + "migrationRuns", + )?, + "transactions": count( + conn, + "SELECT COUNT(*) FROM orchard_ironwood_migration_transactions", + "migrationTxs", + )?, + // 在途 migration 的 PCZT 可能不小,且按次数单调增长。 + "pcztBytes": sum( + conn, + "SELECT SUM(LENGTH(pczt)) FROM orchard_ironwood_migration_transactions", + "pcztBytes", + )?, + }, + }) + .to_string()) +} + +/// Runs bounded, read-only checks suitable for an existing large wallet database. +pub fn database_health(conn: &Connection) -> Result { + let mut quick_check_statement = conn + .prepare("PRAGMA quick_check(20)") + .map_err(|e| db_err("quickCheckPrepare", e))?; + let quick_check_messages = quick_check_statement + .query_map([], |row| row.get::<_, String>(0)) + .map_err(|e| db_err("quickCheckQuery", e))? + .collect::>>() + .map_err(|e| db_err("quickCheckRead", e))?; + let quick_check_ok = + quick_check_messages.len() == 1 && quick_check_messages.first().is_some_and(|v| v == "ok"); + + let mut foreign_key_statement = conn + .prepare("PRAGMA foreign_key_check") + .map_err(|e| db_err("foreignKeyCheckPrepare", e))?; + let mut foreign_key_rows = foreign_key_statement + .query([]) + .map_err(|e| db_err("foreignKeyCheckQuery", e))?; + let mut foreign_key_violations = 0_u64; + while foreign_key_rows + .next() + .map_err(|e| db_err("foreignKeyCheckRead", e))? + .is_some() + { + foreign_key_violations += 1; + } + + Ok(json!({ + "quickCheck": { + "ok": quick_check_ok, + "messages": quick_check_messages, + }, + "foreignKeyViolations": foreign_key_violations, + "schema": { + "tables": count(conn, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table'", "tables")?, + "views": count(conn, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'view'", "views")?, + "indexes": count(conn, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index'", "indexes")?, + }, + "versions": crate::dependency_versions(), + }) + .to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 空库上跑一遍。目的不是看数字,是证明**每条 SQL 的表名和列名都真实存在** —— + /// 写错的话 SQLite 会在这里报错,而不是等到线上安静地返回 0。 + #[test] + fn every_query_matches_the_real_schema() { + let path = std::env::temp_dir().join("zr-stats-schema-check.sqlite"); + let _ = std::fs::remove_file(&path); + let db = crate::wallet::open_and_migrate("test", path.to_str().unwrap()).expect("迁移"); + drop(db); + + let conn = crate::storage::open_connection(path.to_str().unwrap()).expect("开连接"); + let out = storage_stats(&conn).expect("统计不应失败"); + let v: Value = serde_json::from_str(&out).expect("应是合法 JSON"); + + // 空库也必须报出结构,而不是缺字段。 + for group in [ + "sqlite", + "scan", + "trees", + "wallet", + "transient", + "poolMigration", + ] { + assert!(v.get(group).is_some(), "缺少分组 {group}"); + } + for pool in ["sapling", "orchard", "ironwood"] { + let t = &v["trees"][pool]; + for k in [ + "shards", + "shardBytes", + "checkpoints", + "retained", + "marksRemoved", + ] { + assert!(t.get(k).is_some(), "{pool} 缺少 {k}"); + } + } + // 空库没有扫过块,高度必须是 null 而不是 0 —— 0 会被误读成「扫到创世块」。 + assert!(v["scan"]["minHeight"].is_null()); + assert!(v["scan"]["maxHeight"].is_null()); + // 页大小必须是真数,否则 logicalBytes 没有意义。 + assert!(v["sqlite"]["pageSize"].as_i64().unwrap_or(0) > 0); + assert!(v["sqlite"]["logicalBytes"].as_i64().unwrap_or(0) > 0); + + let _ = std::fs::remove_file(&path); + } + + #[test] + fn healthy_database_passes_bounded_checks() { + let path = std::env::temp_dir().join("zr-database-health.sqlite"); + let _ = std::fs::remove_file(&path); + let db = crate::wallet::open_and_migrate("test", path.to_str().unwrap()).expect("migrate"); + drop(db); + + let conn = crate::storage::open_connection(path.to_str().unwrap()).expect("open"); + let out = database_health(&conn).expect("health check"); + let value: Value = serde_json::from_str(&out).expect("valid JSON"); + assert_eq!(value["quickCheck"]["ok"], true); + assert_eq!(value["foreignKeyViolations"], 0); + assert!(value["schema"]["tables"].as_i64().unwrap_or(0) > 0); + + drop(conn); + let _ = std::fs::remove_file(&path); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs new file mode 100644 index 000000000..926ecea9c --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs @@ -0,0 +1,309 @@ +//! 存储适配。 +//! +//! SQLite 从不直接碰文件 —— 它通过 VFS(虚拟文件系统)接口读写字节,而那个接口 +//! 只有五个动作:read / write / truncate / flush / size。把这五个动作接到哪里, +//! 决定了数据实际存在哪。 +//! +//! 浏览器侧我们接到 IndexedDB(`sqlite-wasm-vfs` 的 `relaxed_idb` 实现)。选它 +//! 而不是 OPFS 的 `sahpool`,是因为 sahpool 的同步访问句柄只在 Worker 里可用, +//! 而 relaxed-idb 在所有上下文都能跑 —— 这对我们要覆盖的载体(桌面 renderer、 +//! 浏览器页面、插件 offscreen、移动 WebView)是必要条件。 +//! +//! 代价是它不是「完全持久」:读写在内存里同步服务,异步批量刷进 IndexedDB, +//! 崩溃可能丢掉最近一批。对扫链缓存这是可接受的 —— 数据本来就可以从链上重建。 + +use crate::error::{ErrorCode, Result, RuntimeError}; +use serde_json::json; + +// 强制把 sqlite-wasm-rs 链进最终产物:它提供 sqlite3_os_init 与 +// rust_sqlite_wasm_{malloc,free,localtime} 这几个符号。若没有任何代码引用它, +// rustc 不会把它的 rlib 纳入链接,链接期就会报 undefined symbol。 +#[cfg(target_arch = "wasm32")] +use sqlite_wasm_rs as _; + +#[cfg(target_arch = "wasm32")] +use std::sync::atomic::{AtomicBool, Ordering}; + +#[cfg(target_arch = "wasm32")] +static VFS_READY: AtomicBool = AtomicBool::new(false); + +// `install()` 返回的管理句柄。**必须留着** —— `Preload::None` 下已存在的库不会 +// 自己出现在 VFS 的文件表里,得先 `preload_db` 才能被 SQLite 打开。丢掉这个句柄 +// 就没有别的入口,而症状是静默的:库看起来是空的,于是重新建表、从 birthday +// 全量重扫,扫链本身一切正常。 +// `Rc` 是为了能在不持有 RefCell 借用的情况下跨 await 使用它 —— +// `RelaxedIdbUtil` 本身不是 Clone。 +#[cfg(target_arch = "wasm32")] +thread_local! { + static VFS_UTIL: std::cell::RefCell< + Option>, + > = const { std::cell::RefCell::new(None) }; +} + +/// 把某个库从 IndexedDB 读进 VFS 的文件表。打开该库**之前**必须调一次。 +/// +/// 幂等:已经在表里的库会被跳过。 +#[cfg(target_arch = "wasm32")] +pub async fn preload_database(db_name: &str) -> Result<()> { + // 内存存储模式没有装持久化 VFS,也就没有 IndexedDB 可读 —— 这里必须放行, + // 否则所有走内存存储的排查页都会在开库这一步报 NOT_INITIALIZED。 + if memory_mode() { + return Ok(()); + } + let util = VFS_UTIL.with(|u| u.borrow().clone()); + let Some(util) = util else { + return Err(RuntimeError::with( + ErrorCode::NotInitialized, + json!({ "reason": "vfsNotInstalled" }), + )); + }; + util.preload_db(vec![db_name.to_owned()]) + .await + .map_err(|e| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "preloadDb" }), + ) + .detail(format!("{e:?}")) + }) +} + +#[cfg(not(target_arch = "wasm32"))] +pub async fn preload_database(_db_name: &str) -> Result<()> { + Ok(()) +} + +/// Wait until every relaxed-IDB commit queued before this call has completed. +/// +/// SQLite's xSync schedules the real IndexedDB write but cannot await it from +/// the synchronous VFS callback. The vendored VFS barrier runs on that same +/// FIFO queue and reports any earlier sync failure. This is required before a +/// locally finalized transaction may be broadcast. +#[cfg(target_arch = "wasm32")] +pub async fn durability_barrier() -> Result<()> { + if memory_mode() { + return Ok(()); + } + let util = VFS_UTIL.with(|u| u.borrow().clone()).ok_or_else(|| { + RuntimeError::with( + ErrorCode::NotInitialized, + json!({ "reason": "vfsNotInstalled" }), + ) + })?; + util.barrier() + .map_err(|error| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "durabilityBarrier" }), + ) + .detail(format!("{error:?}")) + })? + .await + .map_err(|error| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "durabilityBarrier" }), + ) + .detail(format!("{error:?}")) + }) +} + +#[cfg(not(target_arch = "wasm32"))] +pub async fn durability_barrier() -> Result<()> { + Ok(()) +} + +/// 安装持久化 VFS 并设为默认。 +/// +/// 幂等:重复调用只有第一次生效。必须在任何 `open_wallet` 之前完成。 +/// +/// 不调用它就走 sqlite-wasm-rs 内置的**内存 VFS** —— 数据不落盘,页面刷新即失。 +/// 那条路的用途有二:临时/一次性钱包;以及排查问题时把「存储层」从 +/// 「纯计算」里摘出来(同样的扫描在内存 VFS 上跑一遍,就知道慢的是哪一半)。 +#[cfg(target_arch = "wasm32")] +pub async fn install_persistent_vfs() -> Result<()> { + use sqlite_wasm_rs as ffi; + use sqlite_wasm_vfs::relaxed_idb::{install, RelaxedIdbCfg}; + + if VFS_READY.load(Ordering::SeqCst) { + return Ok(()); + } + // 默认是 `Preload::All` —— 打开 VFS 时把该 origin 下**所有**库整个读进内存。 + // 改成 `None`,配合开库时的 `preload_database(name)`,只加载当前网络那一个。 + // + // **这不是按页懒加载。** `preload_db_impl` 会遍历该文件的全部 IndexedDB block + // 组成内存文件,SQLite 之后同步访问的是内存副本。所以库有多大,wasm 堆就吃多少、 + // 开库就等多久 —— 省下的只是「同一 origin 下其他库」的那份,不是这一个库本身。 + // 真要按页读,得换一个 page-backed 的 VFS。 + let cfg = RelaxedIdbCfg { + preload: sqlite_wasm_vfs::relaxed_idb::Preload::None, + ..RelaxedIdbCfg::default() + }; + let util = install::(&cfg, true) + .await + .map_err(|e| RuntimeError::new(ErrorCode::NotInitialized).detail(format!("{e:?}")))?; + VFS_UTIL.with(|u| *u.borrow_mut() = Some(std::rc::Rc::new(util))); + VFS_READY.store(true, Ordering::SeqCst); + Ok(()) +} + +/// 原生目标(桌面 / 移动 / 测试)不需要自定义 VFS —— 那里有真的文件系统。 +#[cfg(not(target_arch = "wasm32"))] +pub async fn install_persistent_vfs() -> Result<()> { + Ok(()) +} + +#[cfg(target_arch = "wasm32")] +pub fn is_ready() -> bool { + VFS_READY.load(Ordering::SeqCst) +} + +#[cfg(not(target_arch = "wasm32"))] +pub fn is_ready() -> bool { + true +} + +/// 打开一个 SQLite 连接。路径在 wasm 上是 VFS 内的逻辑名,不是磁盘路径。 +/// 标记「本次会话有意使用内存存储」,让 `open_connection` 不再要求先装 VFS。 +#[cfg(target_arch = "wasm32")] +static MEMORY_MODE: AtomicBool = AtomicBool::new(false); + +/// 选择内存存储:不安装持久化 VFS,数据只活在本页面生命周期内。 +#[cfg(target_arch = "wasm32")] +pub fn use_memory_storage() { + MEMORY_MODE.store(true, Ordering::SeqCst); +} + +#[cfg(not(target_arch = "wasm32"))] +pub fn use_memory_storage() {} + +#[cfg(target_arch = "wasm32")] +fn memory_mode() -> bool { + MEMORY_MODE.load(Ordering::SeqCst) +} + +#[cfg(not(target_arch = "wasm32"))] +fn memory_mode() -> bool { + true +} + +pub fn open_connection(db_name: &str) -> Result { + if !memory_mode() && !is_ready() { + return Err(RuntimeError::new(ErrorCode::NotInitialized)); + } + // wasm 上 db_name 是 VFS 里的逻辑名,不该含路径分隔符; + // 原生上它是真实文件路径,分隔符完全合法。 + let bad_name = db_name.is_empty() + || (cfg!(target_arch = "wasm32") && (db_name.contains('/') || db_name.contains('\\'))); + if bad_name { + return Err(RuntimeError::with( + ErrorCode::InvalidDbName, + json!({ "value": db_name }), + )); + } + let conn = rusqlite::Connection::open(db_name)?; + // carray 虚拟表:zcash_client_sqlite 的部分查询用它传数组参数。 + rusqlite::vtab::array::load_module(&conn)?; + Ok(conn) +} + +/// Checks whether a persisted database exists without opening or creating it. +#[cfg(target_arch = "wasm32")] +pub async fn database_exists(db_name: &str) -> Result { + if memory_mode() { + return Ok(false); + } + let util = VFS_UTIL.with(|u| u.borrow().clone()).ok_or_else(|| { + RuntimeError::with( + ErrorCode::NotInitialized, + json!({ "reason": "vfsNotInstalled" }), + ) + })?; + util.preload_db(vec![db_name.to_owned()]) + .await + .map_err(|e| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "inspectDb" }), + ) + .detail(format!("{e:?}")) + })?; + Ok(util.exists(db_name)) +} + +/// Checks whether a native database file exists without opening or creating it. +#[cfg(not(target_arch = "wasm32"))] +pub async fn database_exists(db_name: &str) -> Result { + Ok(std::path::Path::new(db_name).exists()) +} + +/// 删除一个钱包库,连同它在 IndexedDB 里的全部字节。 +/// +/// ## 为什么这是安全的 +/// +/// 钱包库是**纯派生缓存**:扫过的区块、解密出来的 note、witness、交易历史, +/// 全都能从链上重新扫出来。真正不可再生的东西 —— UFVK 与 birthday —— +/// 由宿主存在自己的账户元数据里,不在这个库里。所以擦掉它不丢任何东西, +/// 只是下次要重扫。 +/// +/// **反过来说这是一条硬约束**:将来若把 birthday 之类的权威数据挪进这个库, +/// 本函数就从「清缓存」变成「毁数据」。要挪之前先改这里。 +/// +/// ## 两种用途 +/// +/// - 出问题时的**手动重置**:历史错乱、余额对不上,擦掉重建 +/// - **删账户**时的清理:库里存着已解密的屏蔽交易历史,正是 Zcash 要隐藏的东西, +/// 账户没了它必须跟着没 +/// +/// 返回是否确实删掉了(库本来就不存在时返回 false,不算错误)。 +#[cfg(target_arch = "wasm32")] +pub async fn delete_database(db_name: &str) -> Result { + use sqlite_wasm_rs as ffi; + use sqlite_wasm_vfs::relaxed_idb::{install, RelaxedIdbCfg}; + + if memory_mode() { + // 内存存储下没有持久化副本,数据随页面消失,没什么可删。 + return Ok(false); + } + if !is_ready() { + return Err(RuntimeError::new(ErrorCode::NotInitialized)); + } + + // install 是幂等的:已注册时只返回管理句柄,不会重复注册。 + let util = install::(&RelaxedIdbCfg::default(), true) + .await + .map_err(|e| RuntimeError::new(ErrorCode::NotInitialized).detail(format!("{e:?}")))?; + + if !util.exists(db_name) { + return Ok(false); + } + // 上游明确要求删除前库必须已关闭,否则句柄与存储会不一致。 + util.delete_db(db_name) + .map_err(|e| db_delete_err(db_name, e))? + .await + .map_err(|e| db_delete_err(db_name, e))?; + Ok(true) +} + +/// 原生目标:直接删文件。 +#[cfg(not(target_arch = "wasm32"))] +pub async fn delete_database(db_name: &str) -> Result { + match std::fs::remove_file(db_name) { + Ok(()) => Ok(true), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(e) => Err(RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "deleteDatabase", "dbName": db_name }), + ) + .detail(e)), + } +} + +#[cfg(target_arch = "wasm32")] +fn db_delete_err(db_name: &str, e: impl std::fmt::Debug) -> RuntimeError { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "deleteDatabase", "dbName": db_name }), + ) + .detail(format!("{e:?}")) +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs new file mode 100644 index 000000000..ef0e7d223 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs @@ -0,0 +1,1174 @@ +//! 扫链:**真正有界**的推进。 +//! +//! ## 为什么不用 `zcash_client_backend::sync::run` +//! +//! 上游那个函数内部是 `while running(...) {}` —— 它跑到**完全同步为止**。 +//! `batch_size` 只控制单批区块数,不控制批数。也就是说它不是「推进一步」, +//! 而是「同步到底」:调用方无法中断、无法看进度、无法在中途让出主线程。 +//! +//! 实测在 testnet 上一次调用 900 秒未返回。对浏览器和移动端都不可接受。 +//! +//! 所以这里自己驱动上游的公开 API,拆成两段: +//! +//! - [`prepare`] —— 一次性准备(下载子树根、更新链尖)。慢,但每轮同步只做一次。 +//! - [`step`] —— 有界推进:最多扫 `max_batches` 批,然后带进度返回。 +//! +//! 宿主拿到进度后自己决定要不要接着调 —— 这正是「调度归 TS」那条边界。 + +use std::collections::{HashMap, HashSet}; +use std::hash::Hash; + +use futures_util::TryStreamExt; +use serde_json::json; + +use zcash_address::unified::{Container, Encoding, Fvk, Ufvk}; +use zcash_client_backend::data_api::chain::error::Error as ChainError; +use zcash_client_backend::data_api::chain::{ + BlockCache, BlockSource, ChainState, CommitmentTreeRoot, +}; +use zcash_client_backend::data_api::scanning::{ScanPriority, ScanRange}; +use zcash_client_backend::data_api::{WalletCommitmentTrees, WalletRead, WalletWrite}; +use zcash_client_backend::proto::service; +use zcash_client_backend::scanning::{scan_block, Nullifiers, ScanningKeys}; +use zcash_keys::keys::UnifiedFullViewingKey; +use zcash_primitives::merkle_tree::HashSer; +use zcash_protocol::consensus::{BlockHeight, NetworkUpgrade, Parameters}; + +use crate::blockcache::MemoryBlockCache; +use crate::error::{ErrorCode, Result, RuntimeError}; +use crate::network::LightClient; +use crate::wallet::Db; + +/// 在上游建议的区间里按优先级挑一个。 +/// +/// `None` 表示「随便,按上游给的顺序」—— 上游本就把 ChainTip 排在 Historic 前面。 +/// 指定优先级时只在同优先级里挑;挑不到就返回 None,让调用方知道这条 lane 空了, +/// 而不是悄悄去扫另一条 lane(那会让宿主的进度显示和实际发生的事对不上)。 +fn pick_range(suggested: &[ScanRange], preferred: Option) -> Option { + suggested + .iter() + .find(|r| !r.is_empty() && preferred.is_none_or(|p| r.priority() == p)) + .cloned() +} + +/// 宿主可以指定的优先级。字符串而非数字:数字在跨边界时无从校验。 +pub fn parse_priority(name: &str) -> Result> { + Ok(match name { + "" | "any" => None, + "chainTip" => Some(ScanPriority::ChainTip), + "historic" => Some(ScanPriority::Historic), + "verify" => Some(ScanPriority::Verify), + "openAdjacent" => Some(ScanPriority::OpenAdjacent), + "foundNote" => Some(ScanPriority::FoundNote), + other => { + return Err(RuntimeError::with( + ErrorCode::InvalidScanPriority, + json!({ "value": other, "allowed": ["any", "chainTip", "historic", "verify", "openAdjacent", "foundNote"] }), + )) + } + }) +} + +/// 检测到重组时建议回退多少块。 +/// +/// Zcash 的最终性很快,深重组极罕见;退太多会让用户重扫大段历史,退太少则可能 +/// 没退到分叉点之前、下一轮继续撞连续性错误。宿主可以在重复失败时自行加大。 +const REORG_REWIND_BLOCKS: u32 = 10; + +fn net_err(operation: &str, e: impl std::fmt::Display) -> RuntimeError { + RuntimeError::with(ErrorCode::NetworkError, json!({ "operation": operation })).detail(e) +} + +fn db_err(operation: &str, e: impl std::fmt::Display) -> RuntimeError { + RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": operation })).detail(e) +} + +/// 拉取某个池的全部子树根。 +async fn subtree_roots( + client: &mut LightClient, + protocol: service::ShieldedProtocol, + operation: &'static str, +) -> Result>> { + let mut request = service::GetSubtreeRootsArg::default(); + request.set_shielded_protocol(protocol); + + let mut stream = crate::network::with_timeout( + async { + client + .get_subtree_roots(request) + .await + .map(|response| response.into_inner()) + .map_err(|e| net_err(operation, e)) + }, + crate::network::DEFAULT_TIMEOUT_MS, + operation, + ) + .await?; + + let mut roots = Vec::new(); + loop { + // This is an inactivity timeout, not a deadline for the whole stream. + // A healthy long subtree stream can run for as long as it needs, while + // a stalled server still releases the carrier after one item timeout. + let next = crate::network::with_timeout( + async { stream.try_next().await.map_err(|e| net_err(operation, e)) }, + crate::network::DEFAULT_TIMEOUT_MS, + operation, + ) + .await?; + let Some(root) = next else { + break; + }; + let hash = H::read(&root.root_hash[..]).map_err(|e| net_err(operation, e))?; + roots.push(CommitmentTreeRoot::from_parts( + BlockHeight::from_u32(root.completing_block_height as u32), + hash, + )); + } + Ok(roots) +} + +/// 一次性准备:把三个池的子树根灌进钱包,并更新链尖。 +/// +/// **这是首次同步最慢的一步**(要下载全部子树根),且与 `batch_size` 无关 —— +/// 这正是之前 `syncAdvance` 看起来「卡住」的原因。把它单独暴露出来, +/// 宿主就能给出「正在准备」这样的独立进度,而不是干等一个不返回的调用。 +/// +/// 每轮同步开始时调一次即可。重复调用是幂等的,但会重新下载,没必要。 +pub async fn prepare(db: &mut Db, client: &mut LightClient) -> Result { + let sapling: Vec> = subtree_roots( + client, + service::ShieldedProtocol::Sapling, + "getSubtreeRoots.sapling", + ) + .await?; + let n_sapling = sapling.len(); + db.put_sapling_subtree_roots(0, &sapling) + .map_err(|e| db_err("putSaplingSubtreeRoots", e))?; + + let orchard: Vec> = subtree_roots( + client, + service::ShieldedProtocol::Orchard, + "getSubtreeRoots.orchard", + ) + .await?; + let n_orchard = orchard.len(); + db.put_orchard_subtree_roots(0, &orchard) + .map_err(|e| db_err("putOrchardSubtreeRoots", e))?; + + let ironwood: Vec> = subtree_roots( + client, + service::ShieldedProtocol::Ironwood, + "getSubtreeRoots.ironwood", + ) + .await?; + let n_ironwood = ironwood.len(); + db.put_ironwood_subtree_roots(0, &ironwood) + .map_err(|e| db_err("putIronwoodSubtreeRoots", e))?; + + let tip = crate::network::chain_tip(client).await?; + db.update_chain_tip(BlockHeight::from_u32(tip)) + .map_err(|e| db_err("updateChainTip", e))?; + + Ok(json!({ + "chainTip": tip, + "saplingSubtrees": n_sapling, + "orchardSubtrees": n_orchard, + "ironwoodSubtrees": n_ironwood, + }) + .to_string()) +} + +/// 只更新链尖,不碰子树根。 +/// +/// 子树根是凝固的历史(新分片几天才完成一个),`prepare` 却每次从索引 0 +/// 全量重下约 1900 条 —— 主网实测 7.4s。每轮同步真正的新信息只有链尖, +/// 一个 unary 调用。`prepare` 留给开库后的第一次。 +pub async fn tip(db: &mut Db, client: &mut LightClient) -> Result { + let tip = crate::network::chain_tip(client).await?; + db.update_chain_tip(BlockHeight::from_u32(tip)) + .map_err(|e| db_err("updateChainTip", e))?; + Ok(json!({ "chainTip": tip }).to_string()) +} + +/// 有界推进:最多处理 `max_batches` 批,每批 `batch_size` 个区块。 +/// +/// 返回进度 JSON,`done` 表示「已经没有待扫区间」。宿主据此决定是否继续调 —— +/// 本函数**永远不会**自己循环到同步完成。 +pub async fn step( + db: &mut Db, + client: &mut LightClient, + batch_size: u32, + max_batches: u32, + preferred: Option, + active_ufvks: &[String], +) -> Result { + if batch_size == 0 || max_batches == 0 { + return Err(RuntimeError::with( + ErrorCode::InvalidBatchSize, + json!({ "batchSize": batch_size, "maxBatches": max_batches }), + )); + } + + let params = *db.params(); + let wallet_ufvks = db + .get_unified_full_viewing_keys() + .map_err(|e| db_err("getUnifiedFullViewingKeys", e))?; + let active_scanning_ufvks = select_active_scanning_ufvks(¶ms, wallet_ufvks, active_ufvks)?; + let active_account_count = active_scanning_ufvks.len(); + let scanning_keys = ScanningKeys::from_account_ufvks(active_scanning_ufvks); + let cache = MemoryBlockCache::new(); + + let mut batches_done = 0u32; + let mut blocks_scanned = 0u64; + // 分阶段累计耗时。扫描慢的时候,「慢在下载还是慢在扫描」是完全不同的两件事, + // 而在浏览器里两者的表现一模一样(页面不动),只能靠打点区分。 + let (mut ms_download, mut ms_treestate, mut ms_scan) = (0.0f64, 0.0f64, 0.0f64); + let (mut scanned_from, mut scanned_to) = (None::, None::); + let mut scanned_priority: Option = None; + + while batches_done < max_batches { + let suggested = db + .suggest_scan_ranges() + .map_err(|e| db_err("suggestScanRanges", e))?; + + // 按宿主给的优先级挑区间。**选择权在宿主,但候选只能来自上游建议** —— + // 这样「先追链尖还是先回填历史」这类调度决策回到 App,而 + // 「哪些区间扫了才是安全的」仍由协议实现说了算,宿主没法乱指高度。 + let Some(range) = pick_range(&suggested, preferred) else { + break; // 该优先级下没有待扫区间 + }; + + // 只取这一批,剩下的留给下一次调用 —— 这就是「有界」的全部含义。 + let start = range.block_range().start; + if scanned_from.is_none() { + scanned_from = Some(u32::from(start)); + } + scanned_priority = Some(format!("{:?}", range.priority())); + + let t_start = now_ms(); + + // 下载:失败先原批重试一次,再对半收缩,地板 32 块。 + // + // 2022 spam 墙区段(约 171 万~195 万高度)一批 500 块可达几十 MB, + // 固定超时在慢链路上永远下不完 —— 不收缩的重试是原地撞墙,换端点 + // 也一样(哪台服务器这段都这么大)。成功的批量跨调用记忆(下方 + // thread_local):不记忆时每轮都从常规值重爬梯子,在墙里等于每轮 + // 白烧两次超时;记住上次成功值、成功后再倍增回去,梯子只爬一次, + // 出墙后几轮内自动恢复常规批量。wasm 单线程,thread_local 即会话级; + // 载体重启后回到常规值,自愈。 + const MIN_DOWNLOAD_BATCH: u32 = 32; + thread_local! { + static DOWNLOAD_BATCH_HINT: std::cell::Cell = + const { std::cell::Cell::new(0) }; + static DOWNLOAD_BATCH_STREAK: std::cell::Cell = + const { std::cell::Cell::new(0) }; + } + let hint = DOWNLOAD_BATCH_HINT.with(|h| h.get()); + let initial_len = if hint > 0 { + std::cmp::min(batch_size, hint) + } else { + batch_size + }; + let mut attempt_len: u32 = initial_len; + let mut same_size_retry = 1u32; + let (batch, batch_len) = loop { + let attempt_end = std::cmp::min(start + attempt_len, range.block_range().end); + let candidate = ScanRange::from_parts(start..attempt_end, range.priority()); + let candidate_len = candidate.len(); + trace(&format!( + "step: 下载 {candidate_len} 块 @{}", + u32::from(start) + )); + // 超时在 download_batch 内部按「停滞」判定;这里只兜真失败。 + let _ = candidate_len; + match download_batch(client, &cache, &candidate).await { + Ok(got) => break (candidate, got), + Err(e) => { + if e.code != ErrorCode::NetworkError { + return Err(e); + } + if same_size_retry > 0 { + same_size_retry -= 1; + trace("step: 下载失败,原批重试"); + continue; + } + if attempt_len <= MIN_DOWNLOAD_BATCH { + return Err(e); + } + attempt_len = std::cmp::max(MIN_DOWNLOAD_BATCH, attempt_len / 2); + trace(&format!("step: 下载超时,批量对半 -> {attempt_len}")); + } + } + }; + // 缩过就记住缩后的值并清空连胜;**整批**(非链尖小批)在记忆值上 + // 连胜三次才向上探一档 —— 小批成功或单次侥幸都不算数,否则记忆值 + // 被顶回超时区来回震荡,每隔一轮就白烧一次探测超时。 + if attempt_len < initial_len { + DOWNLOAD_BATCH_HINT.with(|h| h.set(attempt_len)); + DOWNLOAD_BATCH_STREAK.with(|s| s.set(0)); + } else if batch_len >= attempt_len as usize && initial_len < batch_size { + let streak = DOWNLOAD_BATCH_STREAK.with(|s| { + let v = s.get() + 1; + s.set(v); + v + }); + if streak >= 3 { + let grown = std::cmp::min(batch_size, attempt_len.saturating_mul(2)); + DOWNLOAD_BATCH_HINT.with(|h| h.set(grown)); + DOWNLOAD_BATCH_STREAK.with(|s| s.set(0)); + trace(&format!("step: 批量上探 -> {grown}")); + } + } + // 预算截断时实际入库的可能少于请求区间,扫描终点以实收为准。 + let _ = &batch; + scanned_to = Some(u32::from(start) + batch_len as u32); + let t_downloaded = now_ms(); + ms_download += t_downloaded - t_start; + + // 钳位到 Sapling 激活高度之后。 + // + // lightwalletd 在 Sapling 激活之前**没有 treestate**,而它对这种请求的 + // 错误响应会让 wasm 侧的 gRPC 调用**永久挂起** —— 不是报错,是不返回。 + // 这个坑我们自己的代码库早有记录(zcashWebSdk.ts 的 birthday 钳位)。 + let anchor = anchor_height(¶ms, start); + + let chain_state = crate::network::with_timeout( + async { + client + .get_tree_state(service::BlockId { + height: u64::from(anchor), + hash: Vec::new(), + }) + .await + .map_err(|e| net_err("getTreeState", e))? + .into_inner() + .to_chain_state() + .map_err(|e| net_err("toChainState", e)) + }, + crate::network::DEFAULT_TIMEOUT_MS, + "getTreeState", + ) + .await?; + + let t_treestate = now_ms(); + ms_treestate += t_treestate - t_downloaded; + trace(&format!("step: 开始扫描 {batch_len} 块")); + + // 重组在 scan_blocks_inline 内部按**类型**分类成 REORG_DETECTED + // (带精确 atHeight)—— 这里不再做字符串嗅探。 + scan_blocks_inline( + ¶ms, + &cache, + db, + &scanning_keys, + start, + &chain_state, + batch_len, + )?; + + ms_scan += now_ms() - t_treestate; + trace(&format!("step: 扫描完成,累计 {ms_scan:.0}ms")); + + blocks_scanned += batch_len as u64; + + cache + .delete(batch) + .await + .map_err(|e| db_err("cacheDelete", e))?; + + batches_done += 1; + } + + // 扫完之后重新问一次,把剩余量报给宿主做进度条。 + let remaining = db + .suggest_scan_ranges() + .map_err(|e| db_err("suggestScanRanges", e))?; + let remaining_blocks: u64 = remaining.iter().map(|r| r.len() as u64).sum(); + + Ok(json!({ + "done": remaining_blocks == 0, + "activeAccounts": active_account_count, + "batchesDone": batches_done, + "blocksScanned": blocks_scanned, + "remainingBlocks": remaining_blocks, + "remainingRanges": remaining.len(), + // 这次实际扫的是哪一段、什么优先级 —— 宿主据此把进度归到正确的 lane + "scannedFrom": scanned_from, + "scannedTo": scanned_to, + "scannedPriority": scanned_priority, + "msDownload": ms_download as u32, + "msTreeState": ms_treestate as u32, + "msScan": ms_scan as u32, + }) + .to_string()) +} + +/// 就地扫描一批区块并落库。**不使用上游的 `scan_cached_blocks`。** +/// +/// ## 为什么不能用 `scan_cached_blocks` +/// +/// 它内部把试解密交给批量 runner: +/// +/// ```text +/// Tasks::run_task() -> rayon::spawn_fifo(|| task.run()) +/// ``` +/// +/// 而 `scan_cached_blocks` 用的正是 `Tasks for ()`,该实现只覆写了 `add_task`, +/// **没有覆写 `run_task`**,于是仍然走 rayon。wasm32 单线程环境下 rayon 全局线程池 +/// 没有工作线程,任务被排队但永远不会执行;随后 `BatchReceiver::into_results()` +/// 在通道上等一个永远不来的结果,**把主线程彻底堵死**。 +/// +/// 表现极具迷惑性:空区块不会产生批次,所以扫描一路正常,直到遇到**第一个含 +/// 屏蔽输出的区块**才卡住 —— 看起来像「批量大到某个阈值就挂」,实际与批量无关。 +/// 页面无响应、无错误、超时定时器不触发,连 CDP 都服务不了。 +/// +/// 这里改用公开的 `scanning::scan_block`(它等价于 `runners = None`), +/// 试解密就地完成,不碰 rayon。代价是失去批量试解密的摊销优化(批量求逆), +/// 换来的是在单线程目标上能正确工作,且**不需要 fork 上游**。 +fn scan_blocks_inline( + params: &zcash_protocol::consensus::Network, + cache: &MemoryBlockCache, + db: &mut Db, + scanning_keys: &ScanningKeys<::AccountId, IvkTag>, + from_height: BlockHeight, + from_state: &ChainState, + limit: usize, +) -> Result<()> +where + IvkTag: Copy + Hash + Eq + Send + 'static, +{ + let mut nullifiers = Nullifiers::unspent(db).map_err(|e| db_err("unspentNullifiers", e))?; + + let mut prior = if from_height > BlockHeight::from(0) { + db.block_metadata(from_height - 1) + .map_err(|e| db_err("blockMetadata", e))? + } else { + None + }; + + let mut scanned_blocks = Vec::new(); + cache + .with_blocks::<_, ::Error>(Some(from_height), Some(limit), |block| { + let scanned = scan_block(params, block, scanning_keys, &nullifiers, prior.as_ref()) + .map_err(ChainError::Scan)?; + nullifiers.update_with(&scanned); + prior = Some(scanned.to_block_metadata()); + scanned_blocks.push(scanned); + Ok(()) + }) + .map_err(|e| match &e { + // 链重组:上游的**类型化**判定(和参考循环同一个谓词)。这里是错误 + // 还带着类型的最后一刻 —— 一旦 format 成字符串再去嗅探变体名,就是 + // 上一个 bug 的形状:匹配串写错,重组识别静默失效,钱包在同一高度 + // 死循环整夜。at_height 也因此是精确值,不再用批起点估。 + ChainError::Scan(scan_err) if scan_err.is_continuity_error() => { + let at = u32::from(scan_err.at_height()); + RuntimeError::with( + ErrorCode::ReorgDetected, + json!({ + "atHeight": at, + "suggestedRewindHeight": at.saturating_sub(REORG_REWIND_BLOCKS), + }), + ) + .detail(format!("{e:?}")) + } + _ => db_err("scanBlock", format!("{e:?}")), + })?; + + db.put_blocks(from_state, scanned_blocks) + .map_err(|e| db_err("putBlocks", e))?; + Ok(()) +} + +/// Selects the host-authorized UFVKs and removes every non-Orchard component before scanning. +/// +/// `ScanningKeys::from_account_ufvks` normally creates Sapling, Orchard, and Ironwood keys. The +/// runtime intentionally supplies an ephemeral Orchard-only UFVK instead, so the official +/// scanner still maintains all required trees while Sapling ownership discovery remains disabled. +fn select_active_scanning_ufvks( + params: &zcash_protocol::consensus::Network, + wallet_ufvks: HashMap, + active_ufvks: &[String], +) -> Result> +where + AccountId: Copy + Eq + Hash, +{ + if active_ufvks.is_empty() { + return Err(RuntimeError::new(ErrorCode::NoActiveAccounts)); + } + + let requested = active_ufvks + .iter() + .map(|encoded| { + UnifiedFullViewingKey::decode(params, encoded) + .map(|ufvk| ufvk.encode(params)) + .map_err(|e| RuntimeError::new(ErrorCode::InvalidUfvk).detail(e)) + }) + .collect::>>()?; + + let mut selected = Vec::with_capacity(requested.len()); + let mut matched = HashSet::with_capacity(requested.len()); + for (account_id, ufvk) in wallet_ufvks { + let canonical = ufvk.encode(params); + if requested.contains(&canonical) && matched.insert(canonical) { + selected.push((account_id, orchard_only_ufvk(params, &ufvk)?)); + } + } + + if matched.len() != requested.len() { + return Err(RuntimeError::with( + ErrorCode::AccountNotFound, + json!({ + "requestedActiveUfvks": requested.len(), + "matchedActiveUfvks": matched.len(), + }), + )); + } + + Ok(selected) +} + +fn orchard_only_ufvk( + params: &zcash_protocol::consensus::Network, + ufvk: &UnifiedFullViewingKey, +) -> Result { + let encoded = ufvk.encode(params); + let (network, container) = + Ufvk::decode(&encoded).map_err(|e| RuntimeError::new(ErrorCode::InvalidUfvk).detail(e))?; + let orchard = container + .items() + .into_iter() + .filter(|item| matches!(item, Fvk::Orchard(_))) + .collect::>(); + let container = Ufvk::try_from_items(orchard) + .map_err(|e| RuntimeError::new(ErrorCode::InvalidUfvk).detail(e))?; + UnifiedFullViewingKey::decode(params, &container.encode(&network)) + .map_err(|e| RuntimeError::new(ErrorCode::InvalidUfvk).detail(e)) +} + +/// 单个账户的同步完成度。**不发网络请求。** +/// +/// 共享库里所有账户共用一条扫描队列,所以「全库剩余多少」对单个账户是误导的: +/// 刚加进来的账户会把全库进度拉回去,让早就扫完的账户看起来也没好。 +/// +/// 这里的判据是:**高于该账户 birthday 的待扫区间**才与它有关。低于 birthday +/// 的区间是别的账户的历史,与它无关。 +pub fn account_status(db: &Db, account_uuid: &str) -> Result { + let account_id = crate::account::parse_account_id(db, account_uuid)?; + let birthday = u32::from( + db.get_account_birthday(account_id) + .map_err(|e| db_err("getAccountBirthday", e))?, + ); + + let ranges = db + .suggest_scan_ranges() + .map_err(|e| db_err("suggestScanRanges", e))?; + + // 只算与这个账户有关的那部分 + let mut remaining: u64 = 0; + let mut lowest_pending: Option = None; + for r in &ranges { + let end = u32::from(r.block_range().end); + if end <= birthday { + continue; + } + let start = u32::from(r.block_range().start).max(birthday); + remaining += u64::from(end.saturating_sub(start)); + lowest_pending = Some(lowest_pending.map_or(start, |cur: u32| cur.min(start))); + } + + let summary = db + .get_wallet_summary(zcash_client_backend::data_api::wallet::ConfirmationsPolicy::default()) + .map_err(|e| db_err("walletSummary", e))?; + let chain_tip = summary.as_ref().map(|s| u32::from(s.chain_tip_height())); + + // 扫到哪了 = 与本账户相关的最低待扫高度;没有待扫就是已追到链尖。 + let scanned_to = lowest_pending.or(chain_tip); + + Ok(json!({ + "birthdayHeight": birthday, + "chainTip": chain_tip, + "scannedToHeight": scanned_to, + "remainingBlocks": remaining, + "isComplete": remaining == 0, + }) + .to_string()) +} + +/// 只读:钱包当前建议扫描哪些区间。**不发任何网络请求。** +/// +/// 用途有二:给宿主做进度条;以及在同步卡住时确认它到底想扫哪一段 —— +/// 不用猜,直接看。 +pub fn peek(db: &Db) -> Result { + let ranges = db + .suggest_scan_ranges() + .map_err(|e| db_err("suggestScanRanges", e))?; + + let items: Vec<_> = ranges + .iter() + .map(|r| { + json!({ + "start": u32::from(r.block_range().start), + "end": u32::from(r.block_range().end), + "len": r.len(), + "priority": format!("{:?}", r.priority()), + }) + }) + .collect(); + + let total: u64 = ranges.iter().map(|r| r.len() as u64).sum(); + Ok(json!({ "ranges": items, "totalBlocks": total }).to_string()) +} + +/// 诊断探针:只做**下载**,不扫描、不写库。返回各阶段耗时。 +/// +/// 用来把「网络慢/挂」与「扫描慢/挂」分开 —— 这两者在浏览器里的表现完全一样 +/// (都是页面无响应),但成因和修法完全不同。 +/// +/// 也可以当网络健康检查用:它不改变任何钱包状态。 +pub async fn probe_download(db: &Db, client: &mut LightClient, batch_size: u32) -> Result { + let t0 = now_ms(); + + let ranges = db + .suggest_scan_ranges() + .map_err(|e| db_err("suggestScanRanges", e))?; + let Some(range) = ranges.into_iter().find(|r| !r.is_empty()) else { + return Ok(json!({ "skipped": "noRange" }).to_string()); + }; + + let start = range.block_range().start; + let end = std::cmp::min(start + batch_size, range.block_range().end); + let batch = ScanRange::from_parts(start..end, range.priority()); + let t_range = now_ms(); + + let cache = MemoryBlockCache::new(); + download_batch(client, &cache, &batch).await?; + let t_download = now_ms(); + + let params = *db.params(); + let anchor = anchor_height(¶ms, start); + crate::network::with_timeout( + async { + client + .get_tree_state(service::BlockId { + height: u64::from(anchor), + hash: Vec::new(), + }) + .await + .map_err(|e| net_err("getTreeState", e))? + .into_inner() + .to_chain_state() + .map_err(|e| net_err("toChainState", e)) + }, + crate::network::DEFAULT_TIMEOUT_MS, + "getTreeState", + ) + .await?; + let t_tree = now_ms(); + + Ok(json!({ + "rangeStart": u32::from(start), + "rangeEnd": u32::from(end), + "blocksCached": cache.len(), + "anchorHeight": anchor, + "msSuggestRanges": (t_range - t0) as u32, + "msDownload": (t_download - t_range) as u32, + "msTreeState": (t_tree - t_download) as u32, + }) + .to_string()) +} + +#[cfg(target_arch = "wasm32")] +fn now_ms() -> f64 { + js_sys::Date::now() +} + +#[cfg(not(target_arch = "wasm32"))] +fn now_ms() -> f64 { + use std::time::{SystemTime, UNIX_EPOCH}; + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs_f64() * 1000.0) + .unwrap_or(0.0) +} + +/// 阶段打点。一次调用要跑很久时,最后一条打点就指出它停在哪个阶段 —— +/// 浏览器里除此之外看不到任何东西。 +#[cfg(target_arch = "wasm32")] +pub(crate) fn trace(msg: &str) { + #[wasm_bindgen::prelude::wasm_bindgen] + extern "C" { + #[wasm_bindgen(js_namespace = console)] + fn log(s: &str); + } + log(msg); +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn trace(msg: &str) { + println!("{msg}"); +} + +/// 取 `start - 1` 作为锚点,但不低于 Sapling 激活高度。 +/// +/// 低于该高度时 lightwalletd 没有 treestate,其错误响应会让 wasm 的 gRPC +/// 调用永久挂起(不是返回错误),所以必须在发请求前钳住。 +fn anchor_height(params: &zcash_protocol::consensus::Network, start: BlockHeight) -> u32 { + let sapling = params + .activation_height(NetworkUpgrade::Sapling) + .map(u32::from) + .unwrap_or(1); + u32::from(start).saturating_sub(1).max(sapling) +} + +/// 软预算:块还在到达时不判死,但总时长过线后**把已到手的连续前缀拿去扫**, +/// 不再等剩余的块。超时语义因此从「总时长一刀切」变成「停滞才是死」—— +/// 一个健康推进的大批(spam 墙里 500 块几十 MB)不再被硬杀重下; +/// 慢链路的每一秒都变成已入库的块,批量大小由实际吞吐逐秒决定。 +const DOWNLOAD_SOFT_BUDGET_MS: f64 = 30_000.0; + +/// 流式下载一段区块并写入缓存,返回**实际入库的块数**(连续前缀)。 +/// +/// 每条流消息各自套 DEFAULT_TIMEOUT_MS 的**停滞**超时:只有一颗块都没 +/// 收到过的停滞才向上抛错(交给调用方重试/对半);已有收获的停滞和 +/// 预算超线一样,截断收工。 +async fn download_batch( + client: &mut LightClient, + cache: &MemoryBlockCache, + range: &ScanRange, +) -> Result { + let start = service::BlockId { + height: range.block_range().start.into(), + hash: Vec::new(), + }; + let end = service::BlockId { + height: (range.block_range().end - 1).into(), + hash: Vec::new(), + }; + + let mut stream = crate::network::with_timeout( + async { + client + .get_block_range(service::BlockRange { + start: Some(start), + end: Some(end), + pool_types: vec![], + }) + .await + .map(|response| response.into_inner()) + .map_err(|e| net_err("getBlockRange", e)) + }, + crate::network::DEFAULT_TIMEOUT_MS, + "getBlockRange", + ) + .await?; + + let started = now_ms(); + let mut blocks = Vec::new(); + loop { + if !blocks.is_empty() && now_ms() - started > DOWNLOAD_SOFT_BUDGET_MS { + trace(&format!("step: 下载达预算,截断扫已获 {} 块", blocks.len())); + break; + } + let next = crate::network::with_timeout( + async { + stream + .try_next() + .await + .map_err(|e| net_err("getBlockRange", e)) + }, + crate::network::DEFAULT_TIMEOUT_MS, + "getBlockRange", + ) + .await; + match next { + Ok(Some(block)) => blocks.push(block), + Ok(None) => break, // 流正常结束(整批到齐) + Err(e) => { + if blocks.is_empty() { + return Err(e); // 真停滞且颗粒无收 + } + trace(&format!("step: 下载停滞,截断扫已获 {} 块", blocks.len())); + break; + } + } + } + + let got = blocks.len(); + if got == 0 { + return Err(net_err("getBlockRange", "empty stream for non-empty range")); + } + cache + .insert(blocks) + .await + .map_err(|e| db_err("cacheInsert", e))?; + Ok(got) +} + +/// 回退钱包到指定高度,让之后的同步重扫这段区间。 +/// +/// **破坏性**:该高度之上的扫描结果(note、witness、承诺树检查点)会被丢弃。 +/// 已广播的交易不受影响(它们在链上),但本地未确认记录可能丢失。 +/// +/// 返回实际回退到的高度:上游可能因承诺树检查点位置退得比请求的更靠前。 +pub fn rewind_to(db: &mut Db, height: u32) -> Result { + let target = BlockHeight::from_u32(height); + let actual = db + .truncate_to_height(target) + .map_err(|e| db_err("truncateToHeight", e))?; + Ok(u32::from(actual)) +} + +/// Re-queues an inclusive block range without truncating cached wallet state. +/// +/// The host uses this when a previously inactive UFVK becomes active again. Because the upstream +/// scan queue is shared by the whole network database, other active identities may have advanced +/// it while this identity was paused. The host owns the pause cursor and passes the first height +/// that must be trial-decrypted again. A small reorg safety margin should be applied by the host. +pub fn queue_rescan_from(db: &mut Db, from_height: u32) -> Result { + let Some(tip) = db + .chain_height() + .map_err(|e| db_err("chainHeight", e))? + .map(u32::from) + else { + return Err(RuntimeError::new(ErrorCode::NotSynced)); + }; + + if from_height > tip { + return Ok(json!({ + "queued": false, + "fromHeight": from_height, + "toHeight": tip, + }) + .to_string()); + } + + let range = BlockHeight::from_u32(from_height)..BlockHeight::from_u32(tip.saturating_add(1)); + let ranges = (range, Vec::new()).into(); + db.queue_rescans(ranges, ScanPriority::Historic) + .map_err(|e| db_err("queueRescanFrom", e))?; + + Ok(json!({ + "queued": true, + "fromHeight": from_height, + "toHeight": tip, + }) + .to_string()) +} + +/// 刷新账户的透明 UTXO。 +/// +/// ## 为什么必须单独做 +/// +/// 屏蔽 note 是扫区块试解密出来的,透明 UTXO 不是 —— 它们在链上是公开的, +/// 由 lightwalletd 按地址直接返回。`scan_cached_blocks` 不会产出它们。 +/// +/// 不做这一步的后果是**静默的**:透明余额恒为 0,屏蔽(把透明余额转进隐私池) +/// 永远报「没有可屏蔽的钱」,而扫链看起来一切正常。 +/// +/// 只查该账户名下的透明收款地址(含找零与独立地址)—— 漏掉任何一个都会 +/// 让那部分钱在钱包里不存在。 +pub async fn refresh_transparent_utxos( + db: &mut Db, + client: &mut LightClient, + account_uuid: &str, +) -> Result { + use ::transparent::bundle::{OutPoint, TxOut}; + use zcash_client_backend::proto::service::GetAddressUtxosArg; + use zcash_client_backend::wallet::WalletTransparentOutput; + use zcash_protocol::value::Zatoshis; + + let params = *db.params(); + + let account_id = crate::account::parse_account_id(db, account_uuid)?; + + // 地址 → 账户。返回的每条 UTXO 靠它归属,否则批量查回来就分不清是谁的。 + let mut owner_of: std::collections::HashMap::AccountId> = + std::collections::HashMap::new(); + let mut addresses: Vec = Vec::new(); + let receivers = db + .get_transparent_receivers(account_id, true, true) + .map_err(|e| db_err("getTransparentReceivers", e))?; + for addr in receivers.keys() { + let encoded = zcash_keys::encoding::encode_transparent_address_p(¶ms, addr); + owner_of.insert(encoded.clone(), account_id); + addresses.push(encoded); + } + + if addresses.is_empty() { + return Ok(json!({ "addresses": 0, "utxos": 0, "storedZat": 0 }).to_string()); + } + let address_count = addresses.len(); + let start_height = u64::from( + db.utxo_query_height(account_id) + .map_err(|e| db_err("utxoQueryHeight", e))?, + ); + + let replies = crate::network::with_timeout( + async { + client + .get_address_utxos(GetAddressUtxosArg { + addresses, + start_height, + max_entries: 0, + }) + .await + .map_err(|e| net_err("getAddressUtxos", e)) + .map(|r| r.into_inner().address_utxos) + }, + crate::network::DEFAULT_TIMEOUT_MS, + "getAddressUtxos", + ) + .await?; + + let mut stored = 0u32; + let mut total: u64 = 0; + for utxo in replies { + let Ok(txid) = <[u8; 32]>::try_from(&utxo.txid[..]) else { + continue; + }; + let Ok(index) = u32::try_from(utxo.index) else { + continue; + }; + let Ok(value) = u64::try_from(utxo.value_zat) + .map_err(|_| ()) + .and_then(|v| Zatoshis::from_u64(v).map_err(|_| ())) + else { + continue; + }; + + // `Script` 内部包着 zcash_script 的类型,构造函数不公开;`read` 走的是 + // 带长度前缀的编码,所以这里自己拼前缀,避免为了一个构造再引一个 crate。 + let Some(script_pubkey) = read_script(&utxo.script) else { + continue; + }; + let txout = TxOut::new(value, script_pubkey); + let height = u32::try_from(utxo.height).ok().map(BlockHeight::from_u32); + + // 归属靠地址查回来。批量查询里混着多个账户的输出,用「当前账户」会把 + // 别人的钱记到自己头上。 + let Some(&owner) = owner_of.get(&utxo.address) else { + continue; + }; + + let Some(output) = WalletTransparentOutput::from_parts( + OutPoint::new(txid, index), + txout, + height, + Some(owner), + None, + None, + ) else { + // recipient_address 解不出来的输出我们无法归属,跳过而不是猜。 + continue; + }; + + db.put_received_transparent_utxo(&output) + .map_err(|e| db_err("putReceivedTransparentUtxo", e))?; + stored += 1; + total += u64::from(value); + } + + Ok(json!({ + "addresses": address_count, + "utxos": stored, + "storedZat": total, + }) + .to_string()) +} + +/// 把裸 script 字节读成 `Script`。 +/// +/// 上游的 `Script::read` 期待 CompactSize 长度前缀(链上编码),而 +/// lightwalletd 的 `GetAddressUtxos` 给的是裸字节,所以这里补上前缀再读。 +/// 这样不必为了一个构造函数把 `zcash_script` 也拉进依赖树。 +fn read_script(raw: &[u8]) -> Option<::transparent::address::Script> { + let mut buf = Vec::with_capacity(raw.len() + 9); + // CompactSize:<253 一个字节;再大用 0xfd + u16 / 0xfe + u32 + match raw.len() { + n if n < 253 => buf.push(n as u8), + n if n <= u16::MAX as usize => { + buf.push(0xfd); + buf.extend_from_slice(&(n as u16).to_le_bytes()); + } + n => { + buf.push(0xfe); + buf.extend_from_slice(&(n as u32).to_le_bytes()); + } + } + buf.extend_from_slice(raw); + ::transparent::address::Script::read(&buf[..]).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + use zcash_keys::keys::UnifiedSpendingKey; + use zcash_protocol::consensus::Network; + + fn test_ufvk(network: &Network, seed_byte: u8) -> UnifiedFullViewingKey { + UnifiedSpendingKey::from_seed( + network, + &[seed_byte; 32], + 0u32.try_into().expect("valid ZIP-32 account index"), + ) + .expect("test seed derives a USK") + .to_unified_full_viewing_key() + } + + fn selected_ufvks_for( + network: &Network, + wallet_ufvks: HashMap, + active_ufvks: &[String], + ) -> Result> { + select_active_scanning_ufvks(network, wallet_ufvks, active_ufvks) + } + + #[test] + fn anchor_never_precedes_sapling_activation() { + for net in [Network::MainNetwork, Network::TestNetwork] { + let sapling = u32::from(net.activation_height(NetworkUpgrade::Sapling).unwrap()); + // 请求高度远早于 Sapling —— 必须被抬到激活高度,否则 gRPC 会挂死 + assert_eq!(anchor_height(&net, BlockHeight::from_u32(1)), sapling); + assert_eq!(anchor_height(&net, BlockHeight::from_u32(sapling)), sapling); + // 正常情况取 start - 1 + let h = sapling + 1000; + assert_eq!(anchor_height(&net, BlockHeight::from_u32(h)), h - 1); + } + } + + #[test] + fn only_explicitly_active_ufvk_gets_scanning_keys() { + let network = Network::TestNetwork; + let active = test_ufvk(&network, 1); + let inactive = test_ufvk(&network, 2); + let keys = ScanningKeys::from_account_ufvks( + selected_ufvks_for( + &network, + HashMap::from([(10, active.clone()), (20, inactive)]), + &[active.encode(&network)], + ) + .expect("active UFVK is present in the wallet database"), + ); + + assert!(keys.sapling().is_empty()); + assert_eq!(keys.orchard().len(), 2); + assert_eq!(keys.ironwood().len(), 2); + assert!(keys + .orchard() + .keys() + .all(|(account_id, _)| *account_id == 10)); + assert!(keys + .ironwood() + .keys() + .all(|(account_id, _)| *account_id == 10)); + } + + #[test] + fn duplicate_active_ufvk_is_deduplicated() { + let network = Network::TestNetwork; + let ufvk = test_ufvk(&network, 3); + let encoded = ufvk.encode(&network); + let keys = ScanningKeys::from_account_ufvks( + selected_ufvks_for( + &network, + HashMap::from([(10, ufvk)]), + &[encoded.clone(), encoded], + ) + .expect("duplicate host aliases select one runtime identity"), + ); + + assert_eq!(keys.orchard().len(), 2); + assert_eq!(keys.ironwood().len(), 2); + } + + #[test] + fn empty_active_set_fails_closed() { + let network = Network::TestNetwork; + let ufvk = test_ufvk(&network, 4); + let error = selected_ufvks_for(&network, HashMap::from([(10, ufvk)]), &[]) + .expect_err("an empty set must not fall back to every database account"); + + assert_eq!(error.code, ErrorCode::NoActiveAccounts); + } + + #[test] + fn sapling_component_never_reaches_scanning_keys() { + let network = Network::TestNetwork; + let ufvk = test_ufvk(&network, 5); + assert!(ufvk.sapling().is_some()); + assert!(ufvk.orchard().is_some()); + + let encoded = ufvk.encode(&network); + let selected = + select_active_scanning_ufvks(&network, HashMap::from([(10, ufvk)]), &[encoded]) + .expect("active UFVK is present in the wallet database"); + assert!(selected[0].1.sapling().is_none()); + assert!(selected[0].1.orchard().is_some()); + + let keys = ScanningKeys::from_account_ufvks(selected); + assert!(keys.sapling().is_empty()); + assert_eq!(keys.orchard().len(), 2); + assert_eq!(keys.ironwood().len(), 2); + } + + #[test] + fn paused_identity_can_requeue_range_advanced_by_another_identity() { + let network = Network::TestNetwork; + let paused = test_ufvk(&network, 6); + let active = test_ufvk(&network, 7); + let active_keys = ScanningKeys::from_account_ufvks( + selected_ufvks_for( + &network, + HashMap::from([(10, active.clone()), (20, paused.clone())]), + &[active.encode(&network)], + ) + .expect("the active identity can advance the shared queue alone"), + ); + assert!(active_keys + .orchard() + .keys() + .all(|(account_id, _)| *account_id == 10)); + + let mut db = crate::wallet::open_and_migrate("test", ":memory:") + .expect("in-memory wallet database opens"); + let activation = u32::from( + network + .activation_height(NetworkUpgrade::Sapling) + .expect("testnet has Sapling activation"), + ); + let resume_from = activation + 50; + let tip = activation + 100; + db.update_chain_tip(BlockHeight::from_u32(tip)) + .expect("chain tip update succeeds"); + + let result: serde_json::Value = serde_json::from_str( + &queue_rescan_from(&mut db, resume_from).expect("resume range is queued"), + ) + .expect("queue result is JSON"); + assert_eq!(result["queued"], true); + assert_eq!(result["fromHeight"], resume_from); + assert_eq!(result["toHeight"], tip); + + let ranges = db.suggest_scan_ranges().expect("scan queue is readable"); + assert!(ranges.iter().any(|range| { + range.priority() == ScanPriority::Historic + && u32::from(range.block_range().start) <= resume_from + && u32::from(range.block_range().end) >= tip + 1 + })); + + let resumed_keys = ScanningKeys::from_account_ufvks( + selected_ufvks_for( + &network, + HashMap::from([(10, active), (20, paused.clone())]), + &[paused.encode(&network)], + ) + .expect("the resumed identity is explicitly selected"), + ); + assert!(resumed_keys + .orchard() + .keys() + .all(|(account_id, _)| *account_id == 20)); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs new file mode 100644 index 000000000..291c6af64 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs @@ -0,0 +1,347 @@ +use std::collections::HashSet; + +use rusqlite::{params, OptionalExtension}; +use schemerz_rusqlite::RusqliteMigration; +use uuid::Uuid; +use zcash_client_sqlite::{ + wallet::init::{migrations, WalletMigrationError}, + ExtensionTransaction, +}; + +use crate::error::{ErrorCode, Result, RuntimeError}; +use crate::history::{display_order_to_internal, hex_display_order, uuid_blob}; +use crate::wallet::Db; + +const MIGRATION_ID: Uuid = Uuid::from_u128(0x5be0af90_63f4_43ea_ae65_8207c84e46dd); +const TABLE: &str = "ext_onekey_tx_state"; + +pub struct Migration; + +impl schemerz::Migration for Migration { + fn id(&self) -> Uuid { + MIGRATION_ID + } + + fn dependencies(&self) -> HashSet { + migrations::V_0_22_0_RC6.iter().copied().collect() + } + + fn description(&self) -> &'static str { + "Adds OneKey-owned Zcash transaction lifecycle state." + } +} + +impl RusqliteMigration for Migration { + type Error = WalletMigrationError; + + fn up(&self, transaction: &rusqlite::Transaction) -> std::result::Result<(), Self::Error> { + transaction.execute_batch( + "CREATE TABLE ext_onekey_tx_state ( + txid BLOB PRIMARY KEY NOT NULL, + account_uuid BLOB NOT NULL, + reservation_id TEXT UNIQUE, + recipient TEXT, + broadcast_state TEXT NOT NULL + CHECK (broadcast_state IN ( + 'observed', 'pending', 'accepted', 'rejected' + )), + rejection_code INTEGER, + rejection_reason TEXT + ); + CREATE INDEX ext_onekey_tx_state_account_state + ON ext_onekey_tx_state (account_uuid, broadcast_state);", + )?; + Ok(()) + } + + fn down(&self, _transaction: &rusqlite::Transaction) -> std::result::Result<(), Self::Error> { + Err(WalletMigrationError::CannotRevert(MIGRATION_ID)) + } +} + +fn db_err(operation: &'static str, error: impl std::fmt::Display) -> RuntimeError { + RuntimeError::with( + ErrorCode::DatabaseError, + serde_json::json!({ "operation": operation }), + ) + .detail(error) +} + +pub fn existing_txid_for_reservation( + ext: &ExtensionTransaction<'_>, + reservation_id: &str, +) -> Result> { + let txid = ext + .query_row( + &format!("SELECT txid FROM {TABLE} WHERE reservation_id = ?1"), + [reservation_id], + |row| row.get::<_, Vec>(0), + ) + .optional() + .map_err(|error| db_err("findBroadcastIntent", error))?; + Ok(txid.map(|bytes| hex_display_order(&bytes))) +} + +pub fn insert_finalized( + ext: &ExtensionTransaction<'_>, + txid: &str, + account_uuid: &str, + reservation_id: &str, +) -> Result<()> { + let txid = display_order_to_internal(txid)?; + let account_uuid = uuid_blob(account_uuid)?; + ext.execute( + &format!( + "INSERT INTO {TABLE} ( + txid, account_uuid, reservation_id, recipient, broadcast_state + ) + VALUES ( + ?1, ?2, ?3, + (SELECT output.to_address + FROM v_tx_outputs output + WHERE output.txid = ?1 + AND output.from_account_uuid = ?2 + AND output.to_account_uuid IS NULL + AND COALESCE(output.is_change, 0) = 0 + LIMIT 1), + 'pending' + ) + ON CONFLICT(txid) DO UPDATE SET + account_uuid = excluded.account_uuid, + reservation_id = excluded.reservation_id, + recipient = COALESCE(excluded.recipient, {TABLE}.recipient), + broadcast_state = 'pending', + rejection_code = NULL, + rejection_reason = NULL" + ), + params![txid, account_uuid, reservation_id], + ) + .map_err(|error| db_err("saveBroadcastIntent", error))?; + Ok(()) +} + +pub fn assert_broadcastable(db: &mut Db, txid: &str) -> Result<()> { + let txid = display_order_to_internal(txid)?; + db.transactionally_with_extension(|_wallet, ext| { + let state = ext + .query_row( + &format!( + "SELECT broadcast_state, rejection_code, rejection_reason + FROM {TABLE} + WHERE txid = ?1" + ), + [&txid], + |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, Option>(1)?, + row.get::<_, Option>(2)?, + )) + }, + ) + .optional() + .map_err(|error| db_err("readBroadcastIntent", error))?; + match state { + Some((state, _, _)) if state == "pending" || state == "accepted" => Ok(()), + Some((state, error_code, reason)) if state == "rejected" => { + let mut error = RuntimeError::with( + ErrorCode::BroadcastRejected, + serde_json::json!({ "errorCode": error_code }), + ); + error.detail = reason; + Err(error) + } + Some((state, _, _)) => Err(RuntimeError::with( + ErrorCode::BroadcastIntentNotReady, + serde_json::json!({ "txid": hex_display_order(&txid), "state": state }), + )), + None => Err(RuntimeError::with( + ErrorCode::BroadcastIntentNotFound, + serde_json::json!({ "txid": hex_display_order(&txid) }), + )), + } + }) +} + +pub fn mark_accepted(db: &mut Db, txid: &str) -> Result<()> { + update_outcome(db, txid, "accepted", None) +} + +pub fn mark_rejected(db: &mut Db, txid: &str, error: &RuntimeError) -> Result<()> { + let error_code = error + .params + .get("errorCode") + .and_then(serde_json::Value::as_i64); + update_outcome( + db, + txid, + "rejected", + Some((error_code, error.detail.as_deref())), + ) +} + +fn update_outcome( + db: &mut Db, + txid: &str, + state: &str, + rejection: Option<(Option, Option<&str>)>, +) -> Result<()> { + let txid = display_order_to_internal(txid)?; + let (rejection_code, rejection_reason) = rejection.unwrap_or((None, None)); + db.transactionally_with_extension(|_wallet, ext| { + let changed = ext + .execute( + &format!( + "UPDATE {TABLE} + SET broadcast_state = ?2, + rejection_code = ?3, + rejection_reason = ?4 + WHERE txid = ?1" + ), + params![txid, state, rejection_code, rejection_reason], + ) + .map_err(|error| db_err("updateBroadcastIntent", error))?; + if changed == 0 { + return Err(RuntimeError::with( + ErrorCode::BroadcastIntentNotFound, + serde_json::json!({ "txid": hex_display_order(&txid) }), + )); + } + Ok(()) + }) +} + +pub fn unresolved_txids(conn: &rusqlite::Connection, account_uuid: &str) -> Result> { + let account_uuid = uuid_blob(account_uuid)?; + let mut stmt = conn + .prepare(&format!( + "SELECT state.txid + FROM {TABLE} state + LEFT JOIN v_transactions tx + ON tx.txid = state.txid AND tx.account_uuid = state.account_uuid + WHERE state.account_uuid = ?1 + AND state.broadcast_state IN ('pending', 'accepted') + AND tx.mined_height IS NULL + AND COALESCE(tx.expired_unmined, 0) = 0" + )) + .map_err(|error| db_err("listUnresolvedBroadcasts", error))?; + let rows = stmt + .query_map([account_uuid], |row| row.get::<_, Vec>(0)) + .map_err(|error| db_err("listUnresolvedBroadcasts", error))?; + rows.map(|row| { + row.map(|bytes| hex_display_order(&bytes)) + .map_err(|error| db_err("listUnresolvedBroadcasts", error)) + }) + .collect() +} + +pub fn rebroadcastable_txids( + conn: &rusqlite::Connection, + account_uuid: &str, +) -> Result> { + let account_uuid = uuid_blob(account_uuid)?; + let mut stmt = conn + .prepare(&format!( + "SELECT state.txid + FROM {TABLE} state + JOIN v_transactions tx + ON tx.txid = state.txid AND tx.account_uuid = state.account_uuid + WHERE state.account_uuid = ?1 + AND state.broadcast_state IN ('pending', 'accepted') + AND tx.mined_height IS NULL + AND COALESCE(tx.expired_unmined, 0) = 0" + )) + .map_err(|error| db_err("listRebroadcastableTransactions", error))?; + let rows = stmt + .query_map([account_uuid], |row| row.get::<_, Vec>(0)) + .map_err(|error| db_err("listRebroadcastableTransactions", error))?; + rows.map(|row| { + row.map(|bytes| hex_display_order(&bytes)) + .map_err(|error| db_err("listRebroadcastableTransactions", error)) + }) + .collect() +} + +pub fn remove_account_rows(ext: &ExtensionTransaction<'_>, account_uuid: &str) -> Result<()> { + let account_uuid = uuid_blob(account_uuid)?; + ext.execute( + &format!("DELETE FROM {TABLE} WHERE account_uuid = ?1"), + [account_uuid], + ) + .map_err(|error| db_err("deleteAccountTransactionState", error))?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_runtime_owned_active_intents_are_unresolved_and_rebroadcastable() { + let conn = rusqlite::Connection::open_in_memory().unwrap(); + conn.execute_batch( + "CREATE TABLE ext_onekey_tx_state ( + txid BLOB PRIMARY KEY NOT NULL, + account_uuid BLOB NOT NULL, + reservation_id TEXT UNIQUE, + recipient TEXT, + broadcast_state TEXT NOT NULL, + rejection_code INTEGER, + rejection_reason TEXT + ); + CREATE TABLE v_transactions ( + txid BLOB NOT NULL, + account_uuid BLOB NOT NULL, + mined_height INTEGER, + expired_unmined INTEGER NOT NULL + );", + ) + .unwrap(); + let account = Uuid::nil().as_bytes().to_vec(); + let rows = [ + (1_u8, "pending", Some((None, 0))), + (2, "accepted", Some((None, 0))), + (3, "observed", Some((None, 0))), + (4, "rejected", Some((None, 0))), + (5, "accepted", Some((Some(100), 0))), + (6, "accepted", Some((None, 1))), + ]; + for (byte, state, chain_state) in rows { + let txid = vec![byte; 32]; + conn.execute( + "INSERT INTO ext_onekey_tx_state ( + txid, account_uuid, broadcast_state + ) VALUES (?1, ?2, ?3)", + params![txid, account, state], + ) + .unwrap(); + if let Some((mined_height, expired_unmined)) = chain_state { + conn.execute( + "INSERT INTO v_transactions ( + txid, account_uuid, mined_height, expired_unmined + ) VALUES (?1, ?2, ?3, ?4)", + params![txid, account, mined_height, expired_unmined], + ) + .unwrap(); + } + } + + let mut unresolved = unresolved_txids(&conn, &Uuid::nil().to_string()).unwrap(); + unresolved.sort(); + assert_eq!( + unresolved, + [1_u8, 2] + .map(|byte| hex_display_order(&[byte; 32])) + .to_vec() + ); + + let mut rebroadcastable = rebroadcastable_txids(&conn, &Uuid::nil().to_string()).unwrap(); + rebroadcastable.sort(); + assert_eq!( + rebroadcastable, + [1_u8, 2] + .map(|byte| hex_display_order(&[byte; 32])) + .to_vec() + ); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs new file mode 100644 index 000000000..b7df8ad09 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs @@ -0,0 +1,153 @@ +//! 钱包数据库的打开与初始化。 +//! +//! 这里只做三件事:接上存储、组装 `WalletDb`、跑 schema 迁移。 +//! 钱包的协议逻辑全部来自 `zcash_client_sqlite` / `zcash_client_backend`, +//! 本 crate 不实现任何 Zcash 语义。 + +use rand::SeedableRng; +use rand_chacha::ChaCha20Rng; +use zcash_client_sqlite::{wallet::init::WalletMigrator, WalletDb}; +use zcash_protocol::consensus::Network; + +use crate::clock::HostClock; +use crate::error::{ErrorCode, Result, RuntimeError}; +use crate::storage; +use serde_json::json; + +/// 本 runtime 使用的具体 `WalletDb` 组合。 +pub type Db = WalletDb; + +/// 网络选择。跨 wasm 边界时用字符串,不暴露 Rust 枚举形状。 +pub fn parse_network(s: &str) -> Result { + match s { + "main" | "mainnet" => Ok(Network::MainNetwork), + "test" | "testnet" => Ok(Network::TestNetwork), + other => Err(RuntimeError::with( + ErrorCode::InvalidNetwork, + json!({ "value": other }), + )), + } +} + +/// 打开(必要时创建)钱包数据库,并把 schema 迁移到当前库版本。 +/// +/// `init_wallet_db` 是幂等的:每次打开都跑一遍是安全且推荐的做法。 +/// 它会跑完 `zcash_client_sqlite` 的全部 migration —— 这也是我们验证 +/// SQL 方言与存储层是否真的可用的最强证据。 +pub fn open_and_migrate(network: &str, db_name: &str) -> Result { + let params = parse_network(network)?; + let conn = storage::open_connection(db_name)?; + + // RNG 只用于库内部的非密钥用途(如 migration id、临时值)。 + // 密钥材料不经过它,也不经过本 crate 的任何路径。 + let rng = ChaCha20Rng::from_seed(random_seed()?); + + let mut db = WalletDb::from_connection(conn, params, HostClock, rng); + + WalletMigrator::new() + .with_external_migrations(vec![Box::new(crate::tx_state::Migration)]) + .init_or_migrate(&mut db) + .map_err(|e| { + RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": "migrate" })) + .detail(format!("{e:?}")) + })?; + + Ok(db) +} + +/// 32 字节随机种子。wasm 上走宿主的 crypto.getRandomValues。 +fn random_seed() -> Result<[u8; 32]> { + let mut seed = [0u8; 32]; + getrandom::fill(&mut seed).map_err(|e| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "getrandom" }), + ) + .detail(e) + })?; + Ok(seed) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn network_parsing() { + assert!(matches!(parse_network("main"), Ok(Network::MainNetwork))); + assert!(matches!(parse_network("test"), Ok(Network::TestNetwork))); + assert!(parse_network("regtest").is_err()); + } + + #[test] + fn seed_is_not_all_zero() { + let s = random_seed().expect("应能取到随机数"); + assert_ne!(s, [0u8; 32]); + } + + /// 打印迁移后的真实 schema。`storageStats` 的 SQL 必须照着这份写 —— + /// 表名靠记忆或靠外部文档写,出错时只会安静地返回 0,而不是报错。 + /// 需要 `ZR_DUMP_SCHEMA=1`,未设置时直接跳过。 + #[test] + fn dump_schema() { + if std::env::var("ZR_DUMP_SCHEMA") + .unwrap_or_default() + .is_empty() + { + return; + } + let path = std::env::temp_dir().join("zr-schema-dump.sqlite"); + let _ = std::fs::remove_file(&path); + let db = open_and_migrate("test", path.to_str().unwrap()).expect("迁移"); + drop(db); + + let conn = crate::storage::open_connection(path.to_str().unwrap()).expect("开连接"); + let mut stmt = conn + .prepare("SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name") + .expect("查 sqlite_master"); + let rows: Vec<(String, String)> = stmt + .query_map([], |r| Ok((r.get(0)?, r.get(1)?))) + .expect("遍历") + .map(|r| r.expect("行")) + .collect(); + // 统计要按 BLOB 列求和,所以列名也得是实测的。 + for t in [ + "blocks", + "transactions", + "sent_notes", + "orchard_tree_shards", + "orchard_tree_checkpoints", + "orchard_tree_retained_checkpoints", + "orchard_received_notes", + "orchard_ironwood_migrations", + "orchard_ironwood_migration_transactions", + "nullifier_map", + "tx_locator_map", + "tx_retrieval_queue", + "scan_queue", + ] { + let mut s = conn + .prepare(&format!("PRAGMA table_info({t})")) + .expect("列"); + let cols: Vec = s + .query_map([], |r| r.get::<_, String>(1)) + .expect("遍历列") + .map(|r| r.expect("列名")) + .collect(); + println!("-- {t}: {}", cols.join(", ")); + } + + for kind in ["table", "view", "index", "trigger"] { + let names: Vec<&str> = rows + .iter() + .filter(|(t, _)| t == kind) + .map(|(_, n)| n.as_str()) + .collect(); + println!("== {kind} ({}) ==", names.len()); + for n in &names { + println!(" {n}"); + } + } + let _ = std::fs::remove_file(&path); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs b/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs new file mode 100644 index 000000000..0dbbebdc7 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs @@ -0,0 +1,318 @@ +//! 原生复现:在本机跑与浏览器完全相同的扫描流程。 +//! +//! 目的是把「batchSize ≥ 25 挂死」从 wasm 里搬到原生环境 —— 那边能上真调试器、 +//! 能看堆栈、能 `sample` 采样,而在浏览器里只能看到页面无响应。 +//! +//! 需要联网,所以默认 `#[ignore]`。跑法: +//! +//! ```bash +//! cargo test -p onekey-zcash-runtime --test scan_repro -- --ignored --nocapture +//! # 卡住时另开一个终端: +//! # sample 5 -f /tmp/scan.txt # macOS +//! ``` + +use onekey_zcash_runtime::{account, network, sync, wallet}; + +// 原生 gRPC 端点(与浏览器用的 gRPC-web 端点不同)。 +// chainsafe 那个是 gRPC-web 代理,原生连不上;zec.rocks 反过来。 +const LWD: &str = "https://testnet.zec.rocks:443"; + +/// Alice 的 testnet UFVK —— 公开测试向量,切勿用于真实资金。 +const ALICE_UFVK: &str = "uviewtest1eacc7lytmvgp0sshwjjv4qsg9fnewq00s6zye8hqwndpdsg0tum2ft4k96t86eapddpq56exfycnxnlds75vvpydv8fgj4cecczkmt3rjat8qjfqrk2cdlm9alep2z04785sx6yekqjk6wywkttlthld4c3xmg8fvneg4p97vzxwu9xtuh0xrgfy90p6uuxf8cwl8nxfq6hlte0nnylk59xceldrkx9vge3k4utkue2txu5kpp60aw07q0f0jgp0pv2c0gr7jdm6273uxyskt72jehte5jf2dg94d84le08h2t5rhd93j2d98ja59h46est69f3a7rav7k6744p2u8dxasc7nr9p2k95x7uaknahj0kw7mu5zq9nllj7x2qswq3jswsuzwms7shv7dhxz9s4yudatwu3u3v3wqznkhu6jt7xt8whjh3dkzvsf28p6mj8tya009gwzgszz2at8alquu8y0fmqt7klayrjx7n3ulml5q00fgdr"; + +async fn scan_with_batch(batch_size: u32) { + let db_name = format!("/tmp/zcash-repro-{batch_size}.sqlite"); + let _ = std::fs::remove_file(&db_name); + + let mut db = wallet::open_and_migrate("test", &db_name).expect("开库应成功"); + let mut client = network::connect_native(LWD) + .await + .expect("应能连上 lightwalletd"); + + let tip = network::chain_tip(&mut client).await.expect("应能取链尖"); + println!("链尖 = {tip}"); + + let uuid = account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 200) + .await + .expect("导入账户应成功"); + println!("账户 = {uuid}"); + + let prep = sync::prepare(&mut db, &mut client) + .await + .expect("准备应成功"); + println!("prepare = {prep}"); + + println!("peek = {}", sync::peek(&db).expect("peek 应成功")); + + let t0 = std::time::Instant::now(); + println!("开始 syncStep(batch_size={batch_size}, max_batches=1) …"); + let out = sync::step( + &mut db, + &mut client, + batch_size, + 1, + None, + &[ALICE_UFVK.to_owned()], + ) + .await + .expect("扫描应成功"); + println!("耗时 {:?} 结果 {out}", t0.elapsed()); +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "需要联网"] +async fn scan_batch_10() { + scan_with_batch(10).await; +} + +/// 浏览器里这个批量会永久挂死。原生跑一遍就能区分: +/// 若这里也挂 → 是上游扫描逻辑;若这里正常 → 是 wasm / 存储层特有的问题。 +#[tokio::test(flavor = "multi_thread")] +#[ignore = "需要联网"] +async fn scan_batch_25() { + scan_with_batch(25).await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "需要联网"] +async fn scan_batch_100() { + scan_with_batch(100).await; +} + +/// 扫描指定高度区间。浏览器里 trace 显示扫描停在某个具体高度上, +/// 而之前的原生测试都从 tip-200 / tip-2000 起步,**根本没覆盖到那一段**。 +/// +/// 用法(高度和批量都可覆盖): +/// ```bash +/// ZR_FROM=4292840 ZR_BATCH=20 cargo test -p onekey-zcash-runtime \ +/// --test scan_repro scan_from_height -- --ignored --nocapture +/// ``` +#[tokio::test(flavor = "multi_thread")] +#[ignore = "需要联网"] +async fn scan_from_height() { + let from: u32 = std::env::var("ZR_FROM") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(4292840); + let batch: u32 = std::env::var("ZR_BATCH") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(20); + + let db_name = format!("/tmp/zcash-from-{from}.sqlite"); + let _ = std::fs::remove_file(&db_name); + + let mut db = wallet::open_and_migrate("test", &db_name).expect("开库应成功"); + let mut client = network::connect_native(LWD) + .await + .expect("应能连上 lightwalletd"); + let tip = network::chain_tip(&mut client).await.expect("应能取链尖"); + println!("链尖 = {tip},从 {from} 起扫 {batch} 块"); + + account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, from) + .await + .expect("导入账户应成功"); + sync::prepare(&mut db, &mut client) + .await + .expect("准备应成功"); + println!("peek = {}", sync::peek(&db).expect("peek 应成功")); + + let t0 = std::time::Instant::now(); + let out = sync::step( + &mut db, + &mut client, + batch, + 1, + None, + &[ALICE_UFVK.to_owned()], + ) + .await + .expect("扫描应成功"); + println!("耗时 {:?} 结果 {out}", t0.elapsed()); +} + +/// 原生侧的批量耗时曲线。浏览器上批量越大越不成比例地慢,先确认原生是不是也这样: +/// 若原生也非线性 → 是算法问题,可以在原生上用采样分析器直接定位; +/// 若原生始终线性 → 非线性是 wasm 特有的,与上游无关。 +#[tokio::test(flavor = "multi_thread")] +#[ignore = "需要联网"] +async fn scan_batch_curve() { + for batch in [25u32, 100, 400, 1000] { + let db_name = format!("/tmp/zcash-curve-{batch}.sqlite"); + let _ = std::fs::remove_file(&db_name); + + let mut db = wallet::open_and_migrate("test", &db_name).expect("开库应成功"); + let mut client = network::connect_native(LWD) + .await + .expect("应能连上 lightwalletd"); + let tip = network::chain_tip(&mut client).await.expect("应能取链尖"); + + account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 2000) + .await + .expect("导入账户应成功"); + sync::prepare(&mut db, &mut client) + .await + .expect("准备应成功"); + + let t0 = std::time::Instant::now(); + let out = sync::step( + &mut db, + &mut client, + batch, + 1, + None, + &[ALICE_UFVK.to_owned()], + ) + .await + .expect("扫描应成功"); + println!("批量 {batch:>5} 总计 {:>10?} {out}", t0.elapsed()); + } +} + +/// 与浏览器 `bisect.html` 完全同构:逐块推进 40 次。 +/// +/// 浏览器在第 7 块停住。如果原生也停在某个高度 → 是那个区块的内容; +/// 如果原生一路跑完 → 与区块无关,是 wasm 侧特有的。 +#[tokio::test(flavor = "multi_thread")] +#[ignore = "需要联网"] +async fn scan_one_by_one() { + let db_name = "/tmp/zcash-repro-onebyone.sqlite"; + let _ = std::fs::remove_file(db_name); + + let mut db = wallet::open_and_migrate("test", db_name).expect("开库应成功"); + let mut client = network::connect_native(LWD) + .await + .expect("应能连上 lightwalletd"); + let tip = network::chain_tip(&mut client).await.expect("应能取链尖"); + println!("链尖 = {tip}"); + + account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 200) + .await + .expect("导入账户应成功"); + sync::prepare(&mut db, &mut client) + .await + .expect("准备应成功"); + + for i in 0..40 { + let peek: serde_json::Value = + serde_json::from_str(&sync::peek(&db).expect("peek 应成功")).unwrap(); + let height = peek["ranges"][0]["start"].as_u64(); + let t0 = std::time::Instant::now(); + let out = sync::step(&mut db, &mut client, 1, 1, None, &[ALICE_UFVK.to_owned()]) + .await + .expect("扫描应成功"); + println!("#{i} h={height:?} {:?} {out}", t0.elapsed()); + } +} + +/// 打印某个高度区块的结构摘要,用于和浏览器侧逐字段比对。 +/// +/// ```bash +/// ZR_FROM=4292845 ZR_SPAN=3 cargo test -p onekey-zcash-runtime \ +/// --test scan_repro block_summary_at -- --ignored --nocapture +/// ``` +#[tokio::test(flavor = "multi_thread")] +#[ignore = "需要联网"] +async fn block_summary_at() { + let from: u32 = std::env::var("ZR_FROM") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(4292845); + let span: u32 = std::env::var("ZR_SPAN") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1); + + let mut client = network::connect_native(LWD) + .await + .expect("应能连上 lightwalletd"); + for h in from..from + span { + match network::block_summary(&mut client, h).await { + Ok(s) => println!("{s}"), + Err(e) => println!("{{\"height\":{h},\"error\":\"{e}\"}}"), + } + } +} + +/// 审查报告称 `accounts.uuid` 是 BLOB,而 history.rs 用字符串绑定, +/// 导致历史查询恒为空。这条测试实测两种绑定的匹配数,不靠读 schema 推断。 +#[tokio::test(flavor = "multi_thread")] +#[ignore = "需要联网"] +async fn uuid_binding_string_vs_blob() { + let db_name = "/tmp/zcash-uuid-binding.sqlite"; + let _ = std::fs::remove_file(db_name); + + let mut db = wallet::open_and_migrate("test", db_name).expect("开库应成功"); + let mut client = network::connect_native(LWD).await.expect("应能连上"); + let tip = network::chain_tip(&mut client).await.expect("取链尖"); + let uuid_str = account::import_ufvk(&mut db, &mut client, "a", ALICE_UFVK, tip - 10) + .await + .expect("导入账户"); + println!("listAccounts 给出的形式: {uuid_str}"); + + drop(db); + let conn = rusqlite::Connection::open(db_name).expect("直接打开同一个库"); + let as_text: i64 = conn + .query_row( + "SELECT COUNT(*) FROM accounts WHERE uuid = ?1", + [&uuid_str], + |r| r.get(0), + ) + .unwrap(); + let bytes = uuid::Uuid::parse_str(&uuid_str).unwrap(); + let as_blob: i64 = conn + .query_row( + "SELECT COUNT(*) FROM accounts WHERE uuid = ?1", + [bytes.as_bytes().as_slice()], + |r| r.get(0), + ) + .unwrap(); + let total: i64 = conn + .query_row("SELECT COUNT(*) FROM accounts", [], |r| r.get(0)) + .unwrap(); + + println!("accounts 总数={total} 字符串绑定匹配={as_text} BLOB 绑定匹配={as_blob}"); + assert_eq!(total, 1, "应当只有一个账户"); + assert_eq!(as_blob, 1, "BLOB 绑定必须匹配到"); + assert_eq!(as_text, 0, "字符串绑定匹配不到 —— 这正是历史恒空的原因"); +} + +/// 回归:历史查询必须真的能匹配到账户。 +/// +/// 之前这里报过假绿 —— 查询用文本绑定 BLOB 列,一行都匹配不上, +/// 而「空结果」和「空钱包」返回值一样,看不出坏。所以这条测试**不看返回内容**, +/// 只验证「用同一个 uuid 能在 v_transactions 上匹配到与直接查库一致的条数」。 +#[tokio::test(flavor = "multi_thread")] +#[ignore = "需要联网"] +async fn history_uuid_actually_matches() { + let db_name = "/tmp/zcash-history-uuid.sqlite"; + let _ = std::fs::remove_file(db_name); + + let mut db = wallet::open_and_migrate("test", db_name).expect("开库"); + let mut client = network::connect_native(LWD).await.expect("连上"); + let tip = network::chain_tip(&mut client).await.expect("链尖"); + let uuid = account::import_ufvk(&mut db, &mut client, "a", ALICE_UFVK, tip - 10) + .await + .expect("导入"); + drop(db); + + let conn = rusqlite::Connection::open(db_name).expect("直接开库"); + let via_join: i64 = conn + .query_row( + "SELECT COUNT(*) FROM v_transactions v + JOIN accounts a ON a.uuid = v.account_uuid + WHERE a.uuid = ?1", + [uuid::Uuid::parse_str(&uuid).unwrap().as_bytes().as_slice()], + |r| r.get(0), + ) + .unwrap(); + let history = onekey_zcash_runtime::history::list(&conn, &uuid, 500, 0).expect("history"); + let via_api = serde_json::from_str::>(&history) + .expect("history JSON") + .len(); + println!("直接查={via_join} history() 给出={via_api}"); + assert_eq!( + via_api as i64, via_join, + "history() 必须与直接查一致,而不是恒空" + ); +} diff --git a/chain-runtimes/zcash/crates/zcash-storage-benchmark/Cargo.toml b/chain-runtimes/zcash/crates/zcash-storage-benchmark/Cargo.toml new file mode 100644 index 000000000..4b9a86d1a --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-storage-benchmark/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "onekey-zcash-storage-benchmark" +version = "0.0.1" +edition.workspace = true +license.workspace = true +rust-version.workspace = true +description = "Isolated SQLite WASM VFS benchmark for OneKey developer diagnostics" + +[lib] +crate-type = ["cdylib", "rlib"] + +[target.'cfg(target_arch = "wasm32")'.dependencies] +rusqlite.workspace = true +serde.workspace = true +serde_json.workspace = true +sqlite-wasm-rs.workspace = true +sqlite-wasm-vfs.workspace = true +wasm-bindgen.workspace = true +wasm-bindgen-futures.workspace = true +js-sys.workspace = true +console_error_panic_hook = "0.1" + +[package.metadata.wasm-pack.profile.release] +wasm-opt = ["-Oz", "--enable-bulk-memory", "--enable-nontrapping-float-to-int"] diff --git a/chain-runtimes/zcash/crates/zcash-storage-benchmark/build.rs b/chain-runtimes/zcash/crates/zcash-storage-benchmark/build.rs new file mode 100644 index 000000000..24d4e2e6b --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-storage-benchmark/build.rs @@ -0,0 +1,46 @@ +use std::path::{Path, PathBuf}; + +fn main() { + println!("cargo::rerun-if-changed=build.rs"); + if !std::env::var("TARGET") + .unwrap_or_default() + .starts_with("wasm32") + { + return; + } + + let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("Cargo must set OUT_DIR")); + let Some(source) = find_wasm_sqlite_archive(&out_dir) else { + println!("cargo::warning=sqlite-wasm-rs libwsqlite3.a was not found; linking may fail"); + return; + }; + let destination = out_dir.join("libsqlite3.a"); + if let Err(error) = std::fs::copy(&source, &destination) { + println!( + "cargo::warning=failed to copy {}: {error}", + source.display() + ); + return; + } + println!("cargo::rustc-link-search=native={}", out_dir.display()); + println!("cargo::rerun-if-changed={}", source.display()); +} + +fn find_wasm_sqlite_archive(out_dir: &Path) -> Option { + let build_root = out_dir.parent()?.parent()?; + for entry in std::fs::read_dir(build_root).ok()? { + let Ok(entry) = entry else { continue }; + if !entry + .file_name() + .to_string_lossy() + .starts_with("sqlite-wasm-rs-") + { + continue; + } + let candidate = entry.path().join("out").join("libwsqlite3.a"); + if candidate.is_file() { + return Some(candidate); + } + } + None +} diff --git a/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/error.rs b/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/error.rs new file mode 100644 index 000000000..bcb0a2836 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/error.rs @@ -0,0 +1,103 @@ +use serde_json::{json, Map, Value}; +use std::fmt; +use wasm_bindgen::{JsCast, JsValue}; + +#[derive(Clone, Copy, Debug)] +pub enum ErrorCode { + NotInitialized, + InvalidDbName, + DatabaseError, +} + +impl ErrorCode { + fn as_str(self) -> &'static str { + match self { + Self::NotInitialized => "NOT_INITIALIZED", + Self::InvalidDbName => "INVALID_DB_NAME", + Self::DatabaseError => "DATABASE_ERROR", + } + } +} + +#[derive(Debug)] +pub struct RuntimeError { + code: ErrorCode, + params: Value, + detail: Option, +} + +impl RuntimeError { + pub fn new(code: ErrorCode) -> Self { + Self { + code, + params: Value::Object(Map::new()), + detail: None, + } + } + + pub fn with(code: ErrorCode, params: Value) -> Self { + Self { + code, + params, + detail: None, + } + } + + pub fn detail(mut self, detail: impl fmt::Display) -> Self { + self.detail = Some(detail.to_string()); + self + } + + pub fn to_json(&self) -> Value { + json!({ + "code": self.code.as_str(), + "params": self.params, + "detail": self.detail, + }) + } +} + +impl fmt::Display for RuntimeError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{} {}", self.code.as_str(), self.params)?; + if let Some(detail) = &self.detail { + write!(formatter, " :: {detail}")?; + } + Ok(()) + } +} + +impl std::error::Error for RuntimeError {} + +impl From for RuntimeError { + fn from(error: rusqlite::Error) -> Self { + Self::with(ErrorCode::DatabaseError, json!({ "operation": "sqlite" })).detail(error) + } +} + +impl From for JsValue { + fn from(error: RuntimeError) -> Self { + let js_error = js_sys::Error::new(error.code.as_str()); + let object: &js_sys::Object = js_error.as_ref(); + let _ = js_sys::Reflect::set( + object, + &JsValue::from_str("code"), + &JsValue::from_str(error.code.as_str()), + ); + let _ = js_sys::Reflect::set( + object, + &JsValue::from_str("params"), + &JsValue::from_str(&error.params.to_string()), + ); + if let Some(detail) = error.detail { + let _ = js_sys::Reflect::set( + object, + &JsValue::from_str("detail"), + &JsValue::from_str(&detail), + ); + } + js_error.unchecked_into() + } +} + +pub type Result = std::result::Result; diff --git a/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/lib.rs b/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/lib.rs new file mode 100644 index 000000000..765bd6d84 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/lib.rs @@ -0,0 +1,19 @@ +//! A small diagnostic WASM package for comparing browser SQLite VFS backends. +//! +//! It is separate from the wallet runtime so a benchmark Worker does not +//! duplicate Zcash proving and scanning code in production bundles. + +#[cfg(target_arch = "wasm32")] +mod error; +#[cfg(target_arch = "wasm32")] +mod storage_benchmark; + +#[cfg(target_arch = "wasm32")] +use wasm_bindgen::prelude::*; + +#[cfg(target_arch = "wasm32")] +#[wasm_bindgen(js_name = runStorageBenchmark)] +pub async fn run_storage_benchmark(request_json: &str) -> Result { + console_error_panic_hook::set_once(); + Ok(storage_benchmark::run(request_json).await?) +} diff --git a/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/storage_benchmark.rs b/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/storage_benchmark.rs new file mode 100644 index 000000000..ca321a1e7 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/storage_benchmark.rs @@ -0,0 +1,589 @@ +//! Isolated browser-storage benchmark for the developer Gallery. +//! +//! This is intentionally not a wallet abstraction. It owns a fixed synthetic +//! schema, exposes a small fixed action enum, and rejects every database name +//! outside the benchmark prefix. Product code must not depend on these APIs. + +use std::{cell::RefCell, collections::BTreeMap, rc::Rc}; + +use rusqlite::{params, Connection, OpenFlags}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use sqlite_wasm_vfs::{ + relaxed_idb::{install as install_relaxed_idb, Preload, RelaxedIdbCfg, RelaxedIdbUtil}, + sahpool::{install as install_sahpool, OpfsSAHPoolCfg, OpfsSAHPoolUtil}, +}; + +use crate::error::{ErrorCode, Result, RuntimeError}; + +const DATABASE_PREFIX: &str = "onekey-zcash-storage-bench-"; +const RELAXED_VFS_NAME: &str = "onekey-zcash-benchmark-relaxed-idb"; +const SAHPOOL_VFS_NAME: &str = "onekey-zcash-benchmark-opfs-sahpool"; +const SAHPOOL_DIRECTORY: &str = ".onekey-zcash-benchmark-opfs-sahpool"; +const SAHPOOL_CAPACITY: u32 = 6; +const MAX_ROWS: u32 = 20_000; +const MAX_PAYLOAD_BYTES: u32 = 16_384; +const MAX_BATCH_SIZE: u32 = 2_000; +const MAX_WRITER_ID: u32 = 1_000; + +thread_local! { + static RELAXED_UTIL: RefCell>> = const { RefCell::new(None) }; + static SAHPOOL_UTIL: RefCell>> = const { RefCell::new(None) }; +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum BenchmarkBackend { + RelaxedIdb, + OpfsSahpool, +} + +impl BenchmarkBackend { + fn vfs_name(self) -> &'static str { + match self { + Self::RelaxedIdb => RELAXED_VFS_NAME, + Self::OpfsSahpool => SAHPOOL_VFS_NAME, + } + } +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum BenchmarkAction { + Probe, + Replace, + Append, + Verify, + Mutate, + Cleanup, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BenchmarkRequest { + backend: BenchmarkBackend, + action: BenchmarkAction, + database_name: String, + #[serde(default)] + row_count: u32, + #[serde(default = "default_payload_bytes")] + payload_bytes: u32, + #[serde(default = "default_batch_size")] + batch_size: u32, + #[serde(default)] + writer_id: u32, +} + +fn default_payload_bytes() -> u32 { + 1_024 +} + +fn default_batch_size() -> u32 { + 64 +} + +pub async fn run(request_json: &str) -> Result { + let request: BenchmarkRequest = serde_json::from_str(request_json).map_err(|e| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "storageBenchmarkConfig" }), + ) + .detail(e) + })?; + validate_request(&request)?; + + let started = now_ms(); + let mut timings = BTreeMap::<&str, f64>::new(); + let memory_start = wasm_memory_bytes(); + + let install_started = now_ms(); + let install_result = install_backend(request.backend).await; + timings.insert("install", elapsed(install_started)); + + if request.action == BenchmarkAction::Probe { + return Ok(match install_result { + Ok(()) => json!({ + "backend": request.backend, + "action": request.action, + "databaseName": request.database_name, + "supported": true, + "vfsName": request.backend.vfs_name(), + "timingsMs": timings, + "memoryBytes": { + "start": memory_start, + "afterAction": wasm_memory_bytes(), + }, + "totalMs": elapsed(started), + }), + Err(error) => json!({ + "backend": request.backend, + "action": request.action, + "databaseName": request.database_name, + "supported": false, + "vfsName": request.backend.vfs_name(), + "timingsMs": timings, + "memoryBytes": { + "start": memory_start, + "afterAction": wasm_memory_bytes(), + }, + "error": error.to_json(), + "totalMs": elapsed(started), + }), + } + .to_string()); + } + install_result?; + + if request.action == BenchmarkAction::Cleanup { + let cleanup_started = now_ms(); + let deleted = delete_database(request.backend, &request.database_name).await?; + timings.insert("cleanup", elapsed(cleanup_started)); + return Ok(json!({ + "backend": request.backend, + "action": request.action, + "databaseName": request.database_name, + "supported": true, + "vfsName": request.backend.vfs_name(), + "deleted": deleted, + "timingsMs": timings, + "memoryBytes": { + "start": memory_start, + "afterAction": wasm_memory_bytes(), + }, + "totalMs": elapsed(started), + }) + .to_string()); + } + + if request.action == BenchmarkAction::Replace { + let cleanup_started = now_ms(); + let _ = delete_database(request.backend, &request.database_name).await?; + timings.insert("cleanup", elapsed(cleanup_started)); + } else if matches!(request.backend, BenchmarkBackend::RelaxedIdb) { + let preload_started = now_ms(); + relaxed_util()? + .preload_db(vec![request.database_name.clone()]) + .await + .map_err(|e| benchmark_error("preload", e))?; + timings.insert("preload", elapsed(preload_started)); + } + + let open_started = now_ms(); + let mut conn = open_connection(&request)?; + timings.insert("open", elapsed(open_started)); + let memory_after_open = wasm_memory_bytes(); + + let schema_started = now_ms(); + configure_connection(&conn, request.backend)?; + if matches!(request.action, BenchmarkAction::Replace) { + create_schema(&conn)?; + } + timings.insert("schema", elapsed(schema_started)); + + let mut action_metrics = json!({}); + match request.action { + BenchmarkAction::Replace | BenchmarkAction::Append => { + let write_started = now_ms(); + let batch_latencies = insert_rows( + &mut conn, + request.writer_id, + request.row_count, + request.payload_bytes, + request.batch_size, + )?; + let write_ms = elapsed(write_started); + timings.insert("write", write_ms); + action_metrics = json!({ + "batchLatencyMs": latency_summary(&batch_latencies), + "rowsPerSecond": rate(request.row_count as u64, write_ms), + "payloadMiBPerSecond": rate( + request.row_count as u64 * request.payload_bytes as u64, + write_ms, + ) / (1024.0 * 1024.0), + }); + } + BenchmarkAction::Verify => {} + BenchmarkAction::Mutate => { + let update_started = now_ms(); + let updated = conn.execute( + "UPDATE benchmark_rows SET generation = generation + 1 WHERE row_index % 5 = 0", + [], + )?; + timings.insert("update", elapsed(update_started)); + + let delete_started = now_ms(); + let deleted = conn.execute("DELETE FROM benchmark_rows WHERE row_index % 7 = 0", [])?; + timings.insert("delete", elapsed(delete_started)); + action_metrics = json!({ "updatedRows": updated, "deletedRows": deleted }); + } + BenchmarkAction::Probe | BenchmarkAction::Cleanup => unreachable!(), + } + + let read_started = now_ms(); + let (data, sample_metrics) = inspect_data(&conn)?; + timings.insert("read", elapsed(read_started)); + + let integrity_started = now_ms(); + let integrity = integrity(&conn)?; + timings.insert("integrity", elapsed(integrity_started)); + let sqlite = sqlite_stats(&conn)?; + drop(conn); + + Ok(json!({ + "backend": request.backend, + "action": request.action, + "databaseName": request.database_name, + "supported": true, + "vfsName": request.backend.vfs_name(), + "workload": { + "requestedRows": request.row_count, + "payloadBytes": request.payload_bytes, + "batchSize": request.batch_size, + "writerId": request.writer_id, + }, + "timingsMs": timings, + "memoryBytes": { + "start": memory_start, + "afterOpen": memory_after_open, + "afterAction": wasm_memory_bytes(), + }, + "actionMetrics": action_metrics, + "sampleMetrics": sample_metrics, + "data": data, + "integrity": integrity, + "sqlite": sqlite, + "totalMs": elapsed(started), + }) + .to_string()) +} + +fn validate_request(request: &BenchmarkRequest) -> Result<()> { + let valid_name = request.database_name.starts_with(DATABASE_PREFIX) + && request.database_name.ends_with(".db") + && request.database_name.len() <= 120 + && request + .database_name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')); + if !valid_name { + return Err(RuntimeError::with( + ErrorCode::InvalidDbName, + json!({ "value": request.database_name }), + )); + } + if request.row_count > MAX_ROWS + || request.payload_bytes == 0 + || request.payload_bytes > MAX_PAYLOAD_BYTES + || request.batch_size == 0 + || request.batch_size > MAX_BATCH_SIZE + || request.writer_id > MAX_WRITER_ID + { + return Err(RuntimeError::with( + ErrorCode::DatabaseError, + json!({ + "operation": "storageBenchmarkConfig", + "rowCount": request.row_count, + "payloadBytes": request.payload_bytes, + "batchSize": request.batch_size, + "writerId": request.writer_id, + }), + )); + } + Ok(()) +} + +async fn install_backend(backend: BenchmarkBackend) -> Result<()> { + use sqlite_wasm_rs as ffi; + + match backend { + BenchmarkBackend::RelaxedIdb => { + let cfg = RelaxedIdbCfg { + vfs_name: RELAXED_VFS_NAME.to_owned(), + clear_on_init: false, + preload: Preload::None, + }; + let util = install_relaxed_idb::(&cfg, false) + .await + .map_err(|e| benchmark_error("installRelaxedIdb", e))?; + RELAXED_UTIL.with(|slot| *slot.borrow_mut() = Some(Rc::new(util))); + } + BenchmarkBackend::OpfsSahpool => { + let cfg = OpfsSAHPoolCfg { + vfs_name: SAHPOOL_VFS_NAME.to_owned(), + directory: SAHPOOL_DIRECTORY.to_owned(), + clear_on_init: false, + initial_capacity: SAHPOOL_CAPACITY, + }; + let util = install_sahpool::(&cfg, false) + .await + .map_err(|e| benchmark_error("installOpfsSahpool", e))?; + util.reserve_minimum_capacity(SAHPOOL_CAPACITY) + .await + .map_err(|e| benchmark_error("reserveOpfsSahpool", e))?; + SAHPOOL_UTIL.with(|slot| *slot.borrow_mut() = Some(Rc::new(util))); + } + } + Ok(()) +} + +fn relaxed_util() -> Result> { + RELAXED_UTIL + .with(|slot| slot.borrow().clone()) + .ok_or_else(|| { + RuntimeError::with( + ErrorCode::NotInitialized, + json!({ "reason": "benchmarkRelaxedVfsNotInstalled" }), + ) + }) +} + +fn sahpool_util() -> Result> { + SAHPOOL_UTIL + .with(|slot| slot.borrow().clone()) + .ok_or_else(|| { + RuntimeError::with( + ErrorCode::NotInitialized, + json!({ "reason": "benchmarkSahpoolVfsNotInstalled" }), + ) + }) +} + +async fn delete_database(backend: BenchmarkBackend, database_name: &str) -> Result { + match backend { + BenchmarkBackend::RelaxedIdb => { + let util = relaxed_util()?; + util.preload_db(vec![database_name.to_owned()]) + .await + .map_err(|e| benchmark_error("preloadForDelete", e))?; + if !util.exists(database_name) { + return Ok(false); + } + util.delete_db(database_name) + .map_err(|e| benchmark_error("deleteRelaxedIdb", e))? + .await + .map_err(|e| benchmark_error("commitDeleteRelaxedIdb", e))?; + Ok(true) + } + BenchmarkBackend::OpfsSahpool => sahpool_util()? + .delete_db(database_name) + .map_err(|e| benchmark_error("deleteOpfsSahpool", e)), + } +} + +fn open_connection(request: &BenchmarkRequest) -> Result { + let mut flags = OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_URI; + if request.action == BenchmarkAction::Replace { + flags |= OpenFlags::SQLITE_OPEN_CREATE; + } + Connection::open_with_flags_and_vfs(&request.database_name, flags, request.backend.vfs_name()) + .map_err(|e| benchmark_error("open", e)) +} + +fn configure_connection(conn: &Connection, backend: BenchmarkBackend) -> Result<()> { + conn.execute_batch("PRAGMA foreign_keys = ON; PRAGMA journal_mode = DELETE;")?; + match backend { + // relaxed-idb rejects every synchronous level except OFF. Keeping this + // explicit makes the durability difference visible in the result. + BenchmarkBackend::RelaxedIdb => conn.execute_batch("PRAGMA synchronous = OFF;")?, + BenchmarkBackend::OpfsSahpool => conn.execute_batch("PRAGMA synchronous = FULL;")?, + } + Ok(()) +} + +fn create_schema(conn: &Connection) -> Result<()> { + conn.execute_batch( + "CREATE TABLE benchmark_rows ( + writer_id INTEGER NOT NULL, + row_index INTEGER NOT NULL, + generation INTEGER NOT NULL, + payload BLOB NOT NULL, + checksum INTEGER NOT NULL, + PRIMARY KEY (writer_id, row_index) + ) WITHOUT ROWID;", + )?; + Ok(()) +} + +fn insert_rows( + conn: &mut Connection, + writer_id: u32, + row_count: u32, + payload_bytes: u32, + batch_size: u32, +) -> Result> { + let mut latencies = Vec::new(); + let mut payload = vec![0u8; payload_bytes as usize]; + let mut start = 0; + while start < row_count { + let batch_started = now_ms(); + let end = (start + batch_size).min(row_count); + let tx = conn.transaction()?; + { + let mut statement = tx.prepare( + "INSERT OR REPLACE INTO benchmark_rows + (writer_id, row_index, generation, payload, checksum) + VALUES (?1, ?2, 0, ?3, ?4)", + )?; + for row_index in start..end { + fill_payload(&mut payload, writer_id, row_index); + let checksum = payload_checksum(&payload); + statement.execute(params![writer_id, row_index, &payload, checksum])?; + } + } + tx.commit()?; + latencies.push(elapsed(batch_started)); + start = end; + } + Ok(latencies) +} + +fn inspect_data(conn: &Connection) -> Result<(Value, Value)> { + let (rows, payload_bytes, checksum_sum, generation_sum, writers): (i64, i64, i64, i64, i64) = + conn.query_row( + "SELECT COUNT(*), + COALESCE(SUM(length(payload)), 0), + COALESCE(SUM(checksum), 0), + COALESCE(SUM(generation), 0), + COUNT(DISTINCT writer_id) + FROM benchmark_rows", + [], + |row| { + Ok(( + row.get(0)?, + row.get(1)?, + row.get(2)?, + row.get(3)?, + row.get(4)?, + )) + }, + )?; + + let sample_count = rows.clamp(0, 128); + let mut mismatches = 0i64; + let mut read_latencies = Vec::with_capacity(sample_count as usize); + for sample in 0..sample_count { + let offset = if sample_count <= 1 { + 0 + } else { + sample * (rows - 1) / (sample_count - 1) + }; + let read_started = now_ms(); + let (writer_id, row_index, payload, stored_checksum): (u32, u32, Vec, u32) = conn + .query_row( + "SELECT writer_id, row_index, payload, checksum + FROM benchmark_rows + ORDER BY writer_id, row_index + LIMIT 1 OFFSET ?1", + [offset], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)), + )?; + read_latencies.push(elapsed(read_started)); + let mut expected = vec![0u8; payload.len()]; + fill_payload(&mut expected, writer_id, row_index); + if payload != expected || payload_checksum(&payload) != stored_checksum { + mismatches += 1; + } + } + + Ok(( + json!({ + "rowCount": rows, + "payloadBytes": payload_bytes, + "checksumSum": checksum_sum, + "generationSum": generation_sum, + "writerCount": writers, + }), + json!({ + "checkedRows": sample_count, + "mismatches": mismatches, + "readLatencyMs": latency_summary(&read_latencies), + }), + )) +} + +fn integrity(conn: &Connection) -> Result { + let mut statement = conn.prepare("PRAGMA quick_check(10)")?; + let messages = statement + .query_map([], |row| row.get::<_, String>(0))? + .collect::, _>>()?; + let quick_check_ok = messages.len() == 1 && messages.first().is_some_and(|v| v == "ok"); + let foreign_key_violations: i64 = + conn.query_row("SELECT COUNT(*) FROM pragma_foreign_key_check", [], |row| { + row.get(0) + })?; + Ok(json!({ + "quickCheckOk": quick_check_ok, + "messages": messages, + "foreignKeyViolations": foreign_key_violations, + })) +} + +fn sqlite_stats(conn: &Connection) -> Result { + let page_size: i64 = conn.query_row("PRAGMA page_size", [], |row| row.get(0))?; + let page_count: i64 = conn.query_row("PRAGMA page_count", [], |row| row.get(0))?; + let free_pages: i64 = conn.query_row("PRAGMA freelist_count", [], |row| row.get(0))?; + let journal_mode: String = conn.query_row("PRAGMA journal_mode", [], |row| row.get(0))?; + let synchronous: i64 = conn.query_row("PRAGMA synchronous", [], |row| row.get(0))?; + Ok(json!({ + "pageSize": page_size, + "pageCount": page_count, + "freePages": free_pages, + "logicalBytes": page_size * page_count, + "journalMode": journal_mode, + "synchronous": synchronous, + })) +} + +fn fill_payload(payload: &mut [u8], writer_id: u32, row_index: u32) { + for (index, byte) in payload.iter_mut().enumerate() { + *byte = ((index as u32 * 31 + row_index * 17 + writer_id * 13) % 251) as u8; + } +} + +fn payload_checksum(payload: &[u8]) -> u32 { + payload.iter().fold(2_166_136_261u32, |hash, byte| { + (hash ^ u32::from(*byte)).wrapping_mul(16_777_619) + }) +} + +fn latency_summary(values: &[f64]) -> Value { + if values.is_empty() { + return json!({ "count": 0, "p50": 0.0, "p95": 0.0, "max": 0.0 }); + } + let mut sorted = values.to_vec(); + sorted.sort_by(f64::total_cmp); + let percentile = |p: f64| { + let index = ((sorted.len() - 1) as f64 * p).round() as usize; + sorted[index] + }; + json!({ + "count": sorted.len(), + "p50": percentile(0.50), + "p95": percentile(0.95), + "max": sorted[sorted.len() - 1], + }) +} + +fn benchmark_error(operation: &'static str, error: impl std::fmt::Debug) -> RuntimeError { + RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": operation })) + .detail(format!("{error:?}")) +} + +fn now_ms() -> f64 { + js_sys::Date::now() +} + +fn elapsed(started: f64) -> f64 { + (now_ms() - started).max(0.0) +} + +fn rate(units: u64, duration_ms: f64) -> f64 { + if duration_ms <= 0.0 { + return 0.0; + } + units as f64 * 1_000.0 / duration_ms +} + +fn wasm_memory_bytes() -> u64 { + core::arch::wasm32::memory_size(0) as u64 * 65_536 +} diff --git a/chain-runtimes/zcash/docs/decisions.md b/chain-runtimes/zcash/docs/decisions.md new file mode 100644 index 000000000..538237b2e --- /dev/null +++ b/chain-runtimes/zcash/docs/decisions.md @@ -0,0 +1,468 @@ +# 设计决策与已排除的方案 + +记录「为什么这样」以及「哪些路走过发现不通」,避免以后重走。 + +--- + +## D1 — 存储层用 `zcash_client_sqlite`,不用 `zcash_client_memory` + +**决定**:存储后端使用 crates.io 上未修改的 `zcash_client_sqlite`。 + +**依据**: + +| | `zcash_client_memory` | `zcash_client_sqlite` | +|---|---|---| +| 发布到 crates.io | 从未 | 是,63 个正式版 | +| 所在仓库 | 2026-06-20 被切成独立仓库后停更 | 就在 librustzcash 里 | +| 近期活动 | 只有 dependabot | 与 `zcash_client_backend` 同日发版 | +| 生产使用 | 无 | 官方 Android/iOS SDK、zallet,135 个 Cargo.toml 依赖 | +| 我们的改动量 | vendor 11,122 行,27 个文件改了 22 个 | 1 行 Cargo.toml | + +关键点:`zcash_client_sqlite` 与 `zcash_client_backend` **同日发版** +(2026-08-19 / 06-03 / 04-28 / 03-10 四次全对得上)。采用它不新增升级跑步机 —— +我们已经在这趟车上,只是把 storage 层的移植工作从自己这边转给 ECC。 + +**推论**:旧实现里为 memory 后端做的那些修复**应当丢弃,而非迁移**。原因是那些 bug +本就是我们手工打补丁打出来的;上游文档记载,它们正是拿 `zcash_client_sqlite` +当参考实现对 diff 找出来的。具体地: + +- 输入锁 —— `zcash_client_sqlite` 有 `src/wallet/locking.rs`,1,319 行第一方实现, + 带 Sapling / Orchard 双池测试。我们手写的 192 行该丢。 +- Ironwood 适配 —— sqlite 有十几个 ironwood migration 与完整迁池套件,第一方维护。 +- 手动序列化 —— SQLite 自己按页管持久化,整块不需要。 + +--- + +## D2 — 浏览器存储用 IndexedDB VFS,不自己写 VFS(暂时) + +**决定**:先用 `sqlite-wasm-vfs` 现成的 `relaxed_idb`,不自己实现 VFS。 + +**依据**:VFS 只有五个方法(read/write/truncate/flush/size),自己写是可行的, +但现成实现已经处理了同步/异步这个真正困难的部分。先跑通、看清真实读写模式, +再决定要不要换成自己的实现(届时只是替换那五个方法,不影响上层)。 + +**留给未来的口子**:需要加密、接 OneKey 自己的存储层、或移动端桥到原生存储时, +自己实现 VFS 是直接的路径。 + +--- + +## 已排除的方案 + +### ✗ 升 `rusqlite` 到 0.40 用 `ffi-sqlite-wasm-rs` feature + +`zcash_client_sqlite 0.22` 依赖 `rusqlite ^0.37`。强升 0.40 产生 **83 个编译错误** +(`u64: FromSql` 等 API 破坏),且 `schemerz-rusqlite` 最高只有 `0.370.0`, +没有 0.40 对应版本 —— 要连带 fork 第二个 crate。 + +### ✗ 换用 turso(纯 Rust 的 SQLite 实现) + +可行但不必要。turso 没有 rusqlite 兼容层,而 `zcash_client_sqlite` 有约 1,240 处 +rusqlite 调用(`execute` 335、`query_row` 205、`prepare` 139+84、params 宏 751 等), +需要写一整层 shim;且它仍是 `0.8.0-pre`,未到 1.0。 + +### ✗ 自己把 SQLite 的 C 源码编到 wasm + +不需要。`sqlite-wasm-rs` 已提供预编译产物。自行编译还要处理 wasm sysroot +(`stdio.h` 缺失),得不偿失。expo-sqlite 的做法也印证了这一点 —— 它给 Web 端 +直接 vendor 了一个编好的 624 KB wasm,不在用户机器上编 C。 + +### ✗ 靠 wasm 符号差分判断某个 Rust 修复是否包含在内 + +实测无效:`get_legacy_transparent_address`、`get_transparent_address_metadata`、 +`AddressNotRecognized`、`transparent_receivers`、`ironwood` 这些探针在不同构建里 +出现次数完全一致,区分不出来。判断版本要靠版本号与字节数,不要靠符号。 + +--- + +## 构建环境的坑 + +**Apple clang 不支持 wasm32**,会报 +`No available targets are compatible with triple wasm32-unknown-unknown`。 +必须用 Homebrew LLVM(`/opt/homebrew/opt/llvm/bin/clang`)。 +`secp256k1-sys` 自带 wasm sysroot,只是需要一个能产 wasm 的 clang。 +`scripts/build-wasm.sh` 会自动探测并给出可读的报错。 + +**`getrandom` 0.4 在 wasm32-unknown-unknown 上必须显式选后端**, +否则编译期直接失败。已在 `.cargo/config.toml` 里配好 +`--cfg getrandom_backend="wasm_js"`。 + +**`rand` 版本必须跟 `zcash_client_sqlite` 对齐到 0.8 / `rand_chacha` 0.3** +(即 `rand_core` 0.6 那条线)。用 0.9 会因为 `RngCore` trait 不是同一个而 +无法满足 `init_wallet_db` 的泛型约束,报错信息不直观。 + +**headless Chrome 的 `--virtual-time-budget` 配 `--dump-dom` 会卡死** +(虚拟时间与 IndexedDB 的异步 IO 冲突),且 Chrome 拿到结果后不会自行退出。 +`scripts/browser-check.py` 的做法是让页面把结果 fetch 回传给本地 server, +轮询到结果就主动结束进程。 + +--- + +## 运行期发现(2026-08-22 实测) + +### lightwalletd 端点必须支持 gRPC-web + CORS + +浏览器里跑的是 gRPC-web,不是原生 gRPC,所以端点必须: + +1. 接受 `content-type: application/grpc-web+proto` +2. 对 OPTIONS 预检返回 CORS 头(`access-control-allow-{origin,methods,headers}`) + +实测: + +| 端点 | gRPC-web + CORS | +|---|---| +| `zcash-mainnet.chainsafe.dev` | ✅ | +| `zcash-testnet.chainsafe.dev` | ✅ | +| `testnet.zec.rocks` | ❌ OPTIONS 返回 404 | +| `mainnet.zec.rocks` | ❌ 连不上 | + +不支持时浏览器侧的报错是 `TypeError: Failed to fetch` —— 这个信息**不会**告诉你是 CORS 问题, +排查时先用 curl 打一次 OPTIONS 预检确认。 + +因此本 runtime **不硬编码任何端点**,由宿主通过 `setLightwalletdUrl()` 注入; +换端点时必须先验证 gRPC-web 支持。 + +### 首次同步不是一次快调用 + +`syncAdvance` 第一次调用要先 `update_subtree_roots`(下载全部子树根),实测在 testnet 上 +超过 15 分钟仍未返回。这不是错误路径,但有两个直接后果: + +1. **宿主必须给进度反馈**,不能把它当成一个普通的 await。 +2. `batch_size` 控制的是单批扫描量,**控制不了前置的 subtree roots 下载**。 + +如果这个耗时不可接受,方向是让 `sync::run` 的前置步骤可分段、可中断 —— 那需要不走 +`sync::run` 而自己驱动 `scan_cached_blocks`,属于后续工作,不要在没有实测数据前就动手。 + +--- + +## D3 — 移动端原生:分叉面有多大(实测) + +担心「维护多套代码」是合理的,所以先量。当前 `crates/zcash-runtime/src` 的构成: + +| | 行数 | 说明 | +|---|---|---| +| **全平台共享** | **662** | `wallet` / `account` / `storage` / `blockcache` / `clock` / `error`,wasm32 与 aarch64-apple-ios 均已编译通过 | +| wasm 专属 | 361 | `bindgen` 177、`runtime` 85、`network` 61、`sync` 38 | + +wasm 专属那 361 行里,真正**必须写第二份**的只有绑定层: + +- `bindgen.rs`(177 行)—— wasm-bindgen 对 JS,移动端要 JNI / Swift 的等价物。 +- `network.rs`(61 行)—— 只是把 gRPC-web transport 换成 tonic 原生 transport, + 逻辑与 `LightClient` 签名都不变,是一个 cfg 分支。 +- `sync.rs` / `runtime.rs` —— 现在因为依赖 `network` 才一起 cfg, + 本身没有平台特异性,接上原生 transport 后可直接共享。 + +**结论:第二份大约 180–250 行,不是「多套代码」。** + +可以进一步降低:**UniFFI**(0.32.0,1100 万下载,活跃)能从一份 Rust 定义同时生成 +Kotlin 与 Swift,把「JNI + Swift 两套」压成一套。注意 `equilibriumco/uniffi-zcash-lib` +(把 librustzcash 做 UniFFI 封装的现成项目)最后更新在 2024-08,**不要直接依赖**, +但它证明这条路可行。 + +### 但有三个真实成本,不要低估 + +1. **构建矩阵变大**:wasm-pack 之外多出 4 个移动架构组合(arm64/x86_64 × iOS/Android), + CI 时长与产物管理都变复杂。 +2. **调试变难**:移动端原生出问题,没有浏览器 devtools 可用。 +3. **发布节奏耦合**:Rust 改一次,移动端就要重新出包、过应用商店。 + +第 3 条最实在,也直接决定了边界该怎么划:**放进 Rust 的逻辑越少,移动端被迫发版的频率越低。** +这正是「调度、birthday、进度、重试放 TS」这条原则的现实价值 —— 它不只是开发体验问题。 + +### 建议:分阶段,现在不要做 + +先把 Web / Desktop 这条线跑通并稳定,移动端维持 keys-only(与现状一致,不构成倒退)。 +等 Rust 侧的接口经过实战、改动频率降下来,再上移动端原生 —— 那时候第二套绑定的 +维护成本才是可预测的,而不是在接口还在变的时候就把它复制一份。 + +--- + +## D4 — 不拆第三个包(实测后的结论) + +考虑过把 PCZT 的构造与证明拆成独立包,让日常「扫链 + 看余额」不背证明电路的体积。 + +**实测代价**:去掉全部 PCZT 相关代码后 wasm 从 6.73 MB 降到 **4.70 MB**, +即证明电路(`orchard/circuit` → halo2)约值 **1.6–2.0 MB**。 + +**但拆不了,原因是数据库**: + +构造 PCZT 需要钱包数据库(选币、witness、anchor),所以「构造 + 证明」包必须 +自带完整的存储栈。那就意味着两个 wasm 模块各自持有一个 SQLite 实例, +同时读写同一份 IndexedDB —— 而我们用的 `relaxed-idb` VFS 明确标注 +**Multiple connections: ❌**。并发写同一个库会损坏数据。 + +省 1.6 MB 不值得换来数据损坏风险。 + +**替代的省体积方向**(未做,按性价比排序): + +1. `wasm-opt -Oz`(wasm-pack 默认只跑 `-O`) +2. 证明改为可选加载:把 `pcztProve` 单独编成一个**不含数据库**的模块 —— + 它只吃 PCZT 字节、吐 PCZT 字节,不碰存储,因此没有多连接问题。 + 这条路可行,是真要省体积时的正解。 +3. 检查是否有未使用的 feature 还在拉代码 + +注意方案 2 与被否掉的方案不同:分界线在**是否需要数据库**, +不在「是不是 PCZT 相关」。`pcztCreate` 必须和钱包同包,`pcztProve` 不必。 + +--- + +## D5 — 不用 `sync::run`,自己驱动有界扫描 + +**症状**:`syncAdvance(batchSize)` 在 testnet 上一次调用 900 秒未返回。 + +**根因**:`zcash_client_backend::sync::run` 内部是 + +```rust +update_subtree_roots(client, db_data).await?; +while running(client, params, db_cache, db_data, batch_size).await? {} +``` + +`batch_size` 只控制**单批区块数**,不控制批数 —— 这个函数的语义是「同步到底」, +不是「推进一步」。调用方无法中断、无法看进度、无法在中途让出主线程。 + +我们原先的接口文档写着「有界推进」,实现却是跑到尾。**是接口契约与实现不符, +不是性能问题。** + +**修法**:自己驱动上游的公开 API,拆成两段: + +- `syncPrepare()` —— 一次性准备:下载三个池的子树根 + 更新链尖。 + 这是首次同步最慢的一步,且与 batchSize 无关。单独暴露,宿主才能给出 + 「正在准备」的独立进度,而不是干等一个不返回的调用。 +- `syncStep(batchSize, maxBatches, priority, activeUfvksJson)` —— 最多扫 + `maxBatches` 批就返回,且只为宿主显式传入的 UFVK 试解密; + 空集合报 `NO_ACTIVE_ACCOUNTS`,绝不回退到数据库中全部账户。 + 带 `{ done, batchesDone, blocksScanned, remainingBlocks, remainingRanges }`。 + **永远不自己循环到完成。** +- `queueRescanFrom(fromHeight)` —— 非破坏性地把 + `[fromHeight, chainTip]` 重新排为 historic 扫描。宿主在恢复曾暂停的 UFVK 时调用, + 因为上游 scan queue 是 network wallet 全局的,其他 active UFVK 可能已经把它推进到链尖。 + +Sapling 仍保留上游 schema、承诺树和 subtree root 兼容逻辑,但不会进入 ownership +scanning keys。Runtime 用官方 ZIP-316 API 临时构造只含 Orchard component 的 UFVK, +再交给官方 scanner;没有 fork 或修改 `zcash_client_backend`。 + +上游的 `download_subtree_roots` / `download_blocks` / `download_chain_state` / +`scan_blocks` 全是私有函数,所以这四段逻辑在 `sync.rs` 里重新实现了一遍 —— +但用的都是公开 API(`get_subtree_roots` / `get_block_range` / `get_tree_state` / +`scan_cached_blocks` / `put_*_subtree_roots` / `suggest_scan_ranges`), +没有复制任何协议逻辑。 + +**教训**:上游函数名叫 `run` 而不是 `step`,语义在文档里也写了。 +接口契约要以**实测行为**为准,不能以我们希望它是什么为准 —— +这个 bug 在写文档时就该被发现,而不是等到 900 秒超时。 + +--- + +## D6 — 所有网络调用必须有超时 + +**为什么是硬性要求,不是「最好有」**: + +wasm 里挂死的调用**宿主无法取消** —— 没有线程可以中断,Promise 也不会自己 reject。 +一个不返回的 gRPC 调用会让整个钱包永久卡住,而且不产生任何错误信息, +连日志都没有。用户看到的是「转圈永远不停」。 + +实测踩到过:`syncStep` 只需要扫 201 个区块(`syncPeek` 0ms 就返回了区间 +`{start: 4292265, end: 4292466, priority: ChainTip}`),却几分钟不返回。 +区间这么小说明不是计算量问题,是某个网络调用挂住了。 + +**做法**:`network::with_timeout(fut, ms, operation)` 用 `gloo-timers` 的 +`TimeoutFuture` 与目标 future 竞速,超时抛 +`NETWORK_ERROR` 且 `params = { operation, timeoutMs }`。 +`operation` 是稳定标识,宿主和排查者都能一眼看出是哪一步。 + +默认 30 秒(`DEFAULT_TIMEOUT_MS`)—— 单次 gRPC 调用超过这个时长基本可判定为挂死。 + +**顺带的价值**:超时把「挂死」变成「可定位的错误」。上面那个卡住的问题, +加上超时后一次运行就能指出是 `getBlockRange` 还是 `getTreeState`, +不用再靠猜和二分。 + +## 排查这类问题的手段:`syncPeek()` + +`syncPeek()` 只读钱包建议的扫描区间,**不发任何网络请求**,返回 +`{ ranges: [{ start, end, len, priority }], totalBlocks }`。 + +它同时是宿主的进度条数据源,和「同步卡住时先确认它想扫哪一段」的诊断入口 —— +先用它排除「区间异常巨大」这种可能,再去查网络层,比直接猜快得多。 + +--- + +## D7 — 「10 个区块能扫、25 个挂死」的排查记录 + +值得完整记下来,因为过程里我判断错了三次,每次都靠实测纠正。 + +### 症状 + +`syncStep(10, 1)` 591ms 正常返回;`syncStep(25, 1)` 永久不返回, +**页面完全无响应,没有任何错误信息,连 30 秒超时都不触发**。 + +超时不触发这一点本身就是关键线索:说明阻塞发生在**同步代码**里, +JS 事件循环被占住,定时器根本没机会开火。如果是 await 的网络调用挂住,超时会正常生效。 + +### 三次错误判断 + +1. **「卡在下载子树根」** —— 错。`syncPrepare` 实测 1.3–1.4 秒 + (testnet 6 sapling / 3 orchard / 0 ironwood 子树)。 +2. **「treestate 高度低于 Sapling 激活导致 gRPC 挂起」**(我们自己代码库记过这个坑) + —— 也错,因为 birthday 在链尖附近。**但这个钳位保留了**,它是真实陷阱。 +3. **「批量大就是慢」** —— 错。10 通过、25 挂死这种悬崖不是量级问题。 + +### 定位手段 + +- `syncPeek()` —— 只读待扫区间、不发网络。**0ms** 返回 + `{start, end, len: 201, priority: "ChainTip"}`,一下排除「区间异常巨大」。 +- `syncProbeDownload(n)` —— 只下载不扫描。**100 个区块下载仅 303ms**, + 网络这一半彻底洗清,问题锁定在 `scan_cached_blocks`。 +- 干净库跑 25 同样挂 —— 排除「累积状态」。 + +### 真正的原因:我自己写的缓存里有可重入死锁 + +`MemoryBlockCache::with_blocks` 原本在**整个遍历期间持有 `Mutex`**, +并在持锁状态下调用 `with_block` 回调 —— 而那个回调会写钱包库, +上游有可能在那条路径上再次读取本缓存。 + +`std::sync::Mutex` 不可重入。wasm 是单线程,同一线程二次加锁 = **永久死锁**, +表现正是「页面卡死、无错误、定时器不响」。批量小时不触发那条二次读取路径, +所以 10 能过、25 挂死。 + +**修法**:持锁时只把区块 `clone` 收集出来,**释放锁之后**才执行回调。 + +### 教训 + +- 在持锁状态下调用外部回调,等于把锁的作用域交给了不受控的代码。 + 单线程环境下这不是「可能有竞争」,是「一定死锁」。 +- 「小批量能跑、大批量挂死」不要当成性能问题处理。真的性能问题是渐变的; + 陡峭悬崖几乎总是状态机或锁的问题。 +- 超时不触发是强信号,说明阻塞在同步代码里 —— 这个信息比超时本身更有价值。 + +--- + +## D7 补充 — 原生复现证明问题在 wasm 侧,不在扫描逻辑 + +浏览器里 `batchSize ≥ 25` 挂死。为了排除「上游扫描逻辑本身有问题」, +给网络层补了**原生 transport**(tonic + TLS),在本机跑完全相同的流程: + +``` +batch=25 耗时 513ms blocksScanned=25 remainingBlocks=176 +batch=100 耗时 517ms blocksScanned=100 remainingBlocks=101 +``` + +**原生环境完全正常,而且 25 与 100 耗时几乎相同**(513 vs 517ms)—— +说明扫描本身根本不是瓶颈,耗时由固定开销主导。 + +结论:**症结在 wasm 侧**。 + +> ⚠️ 当时据此推断「嫌疑在 `relaxed-idb` 存储层」,**这个推断是错的** —— +> 换成内存 VFS 照样卡。而且这一节说「上游 `scan_cached_blocks` 没有问题」 +> 也不准确:它在 wasm 上确实有问题,只是原生跑不出来。 +> 真正的根因见 D8。这一节保留,是因为「原生对照」这个方法本身是对的, +> 只是当时的对照实验没控住变量(两端连的服务器不同、覆盖的高度区间也不同)。 + +### 顺带的收获 + +这次为复现而加的原生 transport **本身就是移动端要用的东西** +(见 D3 关于移动端原生 runtime 的讨论)。现在 `network` 与 `sync` 模块 +已是全平台的,只有 `runtime`(thread_local 状态)仍限 wasm。 + +`crates/zcash-runtime/tests/scan_repro.rs` 保留为可复现的回归用例, +默认 `#[ignore]`(需要联网)。跑法: + +```bash +cargo test -p onekey-zcash-runtime --test scan_repro -- --ignored --nocapture +``` + +注意端点不通用:浏览器要 gRPC-web + CORS(`zcash-*.chainsafe.dev`), +原生要真 gRPC(`testnet.zec.rocks:443`)。两边端点互不相通, +配错的表现都是「连不上」但原因完全不同。 + +--- + +## D8 — 扫描不走上游 `scan_cached_blocks`:wasm 上它会永久堵死主线程 + +### 症状 + +浏览器里扫描随机卡死:页面无响应、无报错、超时定时器不触发,连 Chrome +DevTools 协议都服务不了(`Profiler.enable` 超时)。原生跑同一段完全正常。 + +### 根因 + +`zcash_client_backend` 把试解密交给批量 runner,而 `Tasks` trait 的**默认** +`run_task` 是: + +```rust +fn run_task(&self, item: Item) { + let task = self.add_task(item); + rayon::spawn_fifo(|| task.run()); +} +``` + +`scan_cached_blocks` 用的 `Tasks for ()` 只覆写了 `add_task`,**没有覆写 +`run_task`**,所以仍然走 rayon。wasm32-unknown-unknown 是单线程、无 atomics, +rayon 全局线程池没有任何工作线程 —— 任务被排进队列后永远不会执行。 + +随后第二遍扫描调 `BatchReceiver::into_results()`,它的文档写得很直白: +「Blocks until the results of the batch are ready」。结果永远不来, +主线程就永久阻塞在通道上。 + +### 为什么表现得像「批量大到某个阈值就挂」 + +空区块不产生批次。测试用的 testnet 区间里绝大多数是空块(93 字节 / 0 交易), +只有 4292845 一个区块有内容(6 sapling spend / 2 output / 2 ironwood action)。 +批量越大越容易把它圈进去,于是看起来像「批量超过某个值就挂」—— +实际与批量毫无关系,只与**这一批里有没有含屏蔽输出的区块**有关。 + +### 解法 + +用公开 API `scanning::scan_block` 自己写扫描循环(`sync::scan_blocks_inline`)。 +`scan_block` 内部等价于 `scan_block_with_runners(..., runners = None)`, +试解密就地完成,不碰 rayon。 + +- **不需要 fork 上游**:`scan_block` / `ScanningKeys::from_account_ufvks` / + `Nullifiers::unspent` / `ScannedBlock::to_block_metadata` 全是公开项。 +- 代价:失去批量试解密的摊销优化(批量求逆)。原生实测扫描阶段耗时: + 1000 块 45ms → 88ms,约 1.4–2 倍。这段 testnet 区块很空, + 主网稠密区块上的差距会更大,届时可重新评估。 +- 备选方案(未采用):vendor `zcash_client_backend` 并把 `run_task` 在 wasm 上 + 改成就地执行 —— 能保住批量优化,但要多 fork 一个大 crate。 + rayon 在整个依赖图里只有 `zcash_client_backend` 一个使用者, + 所以「patch rayon 成单线程 shim」也可行,同样因为增加 fork 面而未选。 + +这是上游在单线程目标上的真实缺陷,值得反馈给 librustzcash。 + +### 实测(修复后,持久化 IndexedDB VFS,testnet) + +| batchSize | 总耗时 | 下载 | treestate | 扫描 | +|---|---|---|---|---| +| 10 | 853ms | 523 | 255 | 70 | +| 25 | 533ms | 258 | 257 | 17 | +| 60 | 549ms | 279 | 257 | 12 | +| 100 | 567ms | 287 | 255 | 24 | +| 200 | 633ms | 351 | 254 | 26 | +| 500 | 614ms | 333 | 255 | 25(203 块,追平) | + +扫描本身很便宜,耗时基本全在两次网络往返上。宿主要提速应该减少往返次数, +而不是调批量。 + +### 排查过程里更值得记住的教训 + +**测量工具本身骗了我好几轮。** 页面用 `fetch` 往测试服务器回传日志, +于是「被测代码卡住」和「回传通道自己死了」在日志上完全一样 —— 都是 +「日志停在某一行」。据此得出过两个错误结论: + +1. 「batchSize ≥ 25 永久挂死」—— 写进了 README 当作阻塞发版的问题,实际是假的; +2. 「区块 4292846 有毒」—— 停止位置其实是被 tracing 自身拖慢造成的假象。 + +修法是把证据通道和被测对象彻底解耦:`scripts/cdp_console.py` 直接从 +Chrome DevTools 协议读 console,不经过页面网络。换上它之后, +第一轮就拿到了真实的停止位置。 + +顺带修掉的两个工具缺陷: + +- `browser-check.py` 原来用串行 `TCPServer`,页面同时发上报和拉资源时会互相排队; + 已换成 `ThreadingHTTPServer`。 +- 判定「通过」只看「行数够且没有 FAIL」,页面卡在最后一步时照样报通过 —— + 真发生过。现在必须收到页面自己发的终止标记。 + +**另一条:对照实验要控住所有变量。** 早期「原生正常」的结论其实无效 —— +原生连的是 `testnet.zec.rocks`、浏览器连的是 `zcash-testnet.chainsafe.dev`, +服务器都不是同一个;而且原生跑的高度区间根本没覆盖到出问题的区块。 +后来加了 `network::block_summary`(返回编码长度 + 校验和), +确认两端拿到的字节完全一致,对照才真正成立。 diff --git a/chain-runtimes/zcash/patches/.gitattributes b/chain-runtimes/zcash/patches/.gitattributes new file mode 100644 index 000000000..f24606940 --- /dev/null +++ b/chain-runtimes/zcash/patches/.gitattributes @@ -0,0 +1,2 @@ +# Unified diff blank context lines intentionally contain one space. +*.patch -whitespace diff --git a/chain-runtimes/zcash/patches/manifest.json b/chain-runtimes/zcash/patches/manifest.json new file mode 100644 index 000000000..dcb79deeb --- /dev/null +++ b/chain-runtimes/zcash/patches/manifest.json @@ -0,0 +1,14 @@ +[ + { + "name": "zcash_client_sqlite", + "version": "0.22.0", + "sha256": "dd92e4334619b1e3f67019254049318ec0d0240a3c15d853bdf2ac4bba597078", + "patch": "zcash_client_sqlite-0.22.0-no-bundled.patch" + }, + { + "name": "sqlite-wasm-vfs", + "version": "0.2.0", + "sha256": "7f7a5c9ac229421d577bb5a9bb59048838509958b218dd4e0b3c1214a87c361e", + "patch": "sqlite-wasm-vfs-0.2.0-durability-barrier.patch" + } +] diff --git a/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-durability-barrier.patch b/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-durability-barrier.patch new file mode 100644 index 000000000..7f6bfda77 --- /dev/null +++ b/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-durability-barrier.patch @@ -0,0 +1,82 @@ +--- a/src/relaxed_idb.rs ++++ b/src/relaxed_idb.rs +@@ -130,6 +130,7 @@ + Sync(String), + Delete(String), + Clear, ++ Barrier, + } + + enum IdbFile { +@@ -325,6 +326,7 @@ + idb: Database, + name2file: RefCell>, + tx: UnboundedSender, ++ commit_error: RefCell>, + } + + impl RelaxedIdb { +@@ -348,6 +350,7 @@ + idb: indexed_db, + name2file: RefCell::new(name2file), + tx, ++ commit_error: RefCell::new(None), + }) + } + +@@ -469,6 +472,10 @@ + self.send_task_with_notify(IdbCommitOp::Clear) + } + ++ fn barrier(&self) -> Result { ++ self.send_task_with_notify(IdbCommitOp::Barrier) ++ } ++ + fn exists(&self, file: &str) -> bool { + self.name2file.borrow().contains_key(file) + } +@@ -542,11 +549,28 @@ + async fn commit_loop(&self, mut rx: UnboundedReceiver) { + while let Some(commit) = rx.recv().await { + let IdbCommit { op, notify } = commit; ++ let is_sync = matches!(&op, IdbCommitOp::Sync(_)); + let ret = match op { + IdbCommitOp::Sync(file) => self.sync_db_impl(&file).await, + IdbCommitOp::Delete(file) => self.delete_db_impl(&file).await, + IdbCommitOp::Clear => clear_impl(&self.idb).await, ++ // A failed sync already discarded its dirty-block list, so a ++ // later successful barrier cannot make that write durable. ++ // Keep the carrier poisoned until the module is reloaded and ++ // the database is reconstructed from IndexedDB. ++ IdbCommitOp::Barrier => match self.commit_error.borrow().as_ref() { ++ Some(error) => Err(RelaxedIdbError::Generic(error.clone())), ++ None => Ok(()), ++ }, + }; ++ if is_sync { ++ if let Err(error) = &ret { ++ let mut commit_error = self.commit_error.borrow_mut(); ++ if commit_error.is_none() { ++ *commit_error = Some(error.to_string()); ++ } ++ } ++ } + if let Some(notify) = notify { + // An unsuccessful send would be one where the corresponding receiver + // has already been deallocated. +@@ -890,6 +914,15 @@ + self.pool.clear_all() + } + ++ /// Wait for every earlier queued sync and surface the first sync failure. ++ /// ++ /// A failure poisons the current VFS instance because its in-memory dirty ++ /// block set can no longer prove what reached IndexedDB. Reload the VFS ++ /// before attempting more durable writes. ++ pub fn barrier(&self) -> Result { ++ self.pool.barrier() ++ } ++ + /// Does the database exists. + pub fn exists(&self, filename: &str) -> bool { + self.pool.exists(filename) diff --git a/chain-runtimes/zcash/patches/zcash_client_sqlite-0.22.0-no-bundled.patch b/chain-runtimes/zcash/patches/zcash_client_sqlite-0.22.0-no-bundled.patch new file mode 100644 index 000000000..3ae96b3fd --- /dev/null +++ b/chain-runtimes/zcash/patches/zcash_client_sqlite-0.22.0-no-bundled.patch @@ -0,0 +1,10 @@ +--- a/Cargo.toml ++++ b/Cargo.toml +@@ -229,7 +229,6 @@ + [dependencies.rusqlite] + version = "0.37" + features = [ +- "bundled", + "time", + "array", + "uuid", diff --git a/chain-runtimes/zcash/rust-toolchain.toml b/chain-runtimes/zcash/rust-toolchain.toml new file mode 100644 index 000000000..913e54be9 --- /dev/null +++ b/chain-runtimes/zcash/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.93.0" +profile = "minimal" +targets = ["wasm32-unknown-unknown"] diff --git a/chain-runtimes/zcash/scripts/build-wasm.sh b/chain-runtimes/zcash/scripts/build-wasm.sh new file mode 100755 index 000000000..eb9a0327a --- /dev/null +++ b/chain-runtimes/zcash/scripts/build-wasm.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# 构建浏览器可用的 wasm 包。 +# +# 前置条件: +# 1. wasm32-unknown-unknown target:rustup target add wasm32-unknown-unknown +# 2. 支持 wasm32 的 clang。macOS 自带的 Apple clang **不支持**,会报 +# "No available targets are compatible with triple wasm32-unknown-unknown"。 +# 用 Homebrew 的:brew install llvm +# (secp256k1-sys 自带 wasm sysroot,只是需要一个能产 wasm 的 clang。) +# 3. wasm-pack:cargo install wasm-pack +# +# 用法: +# bash scripts/build-wasm.sh # release +# PROFILE=dev bash scripts/build-wasm.sh + +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +PROFILE="${PROFILE:-release}" +OUT="${OUT:-${ROOT}/pkg}" + +# 找一个能编 wasm32 的 clang +pick_clang() { + for c in "${CC_wasm32_unknown_unknown:-}" \ + /opt/homebrew/opt/llvm/bin/clang \ + /usr/local/opt/llvm/bin/clang "$(command -v clang || true)"; do + [ -n "$c" ] && [ -x "$c" ] || continue + if echo 'int main(void){return 0;}' > /tmp/_wasmprobe.c 2>/dev/null && + "$c" --target=wasm32-unknown-unknown -nostdlib -c /tmp/_wasmprobe.c -o /tmp/_wasmprobe.o 2>/dev/null; then + echo "$c"; return 0 + fi + done + return 1 +} + +if ! CLANG="$(pick_clang)"; then + echo "错误:找不到支持 wasm32 的 clang。" >&2 + echo " macOS 请先 brew install llvm(Apple clang 不支持 wasm32 目标)。" >&2 + exit 1 +fi +echo "==> 使用 clang: ${CLANG}" + +export CC_wasm32_unknown_unknown="${CLANG}" +export AR_wasm32_unknown_unknown="${AR_wasm32_unknown_unknown:-$(dirname "${CLANG}")/llvm-ar}" + +bash "${ROOT}/scripts/vendor-deps.sh" "$@" + +echo "==> wasm-pack build (${PROFILE})" +cd "${ROOT}/crates/zcash-runtime" +case "${PROFILE}" in + release) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --release ;; + # 优化照旧,但保留名字段。wasm 里的 panic 只给函数序号,没有它就只能靠 + # 通读依赖去猜是谁调的 —— 而 --dev 会让 Halo2 证明慢到不可用。 + profiling) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --profiling ;; + *) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --dev ;; +esac + +echo "==> 产物" +ls -lh "${OUT}"/*.wasm | awk '{print " ", $9, $5}' + +echo "==> 构建 storage benchmark" +(cd "${ROOT}/crates/zcash-storage-benchmark" && \ + wasm-pack build --mode no-install --locked --target web --out-dir "${ROOT}/pkg/storage-benchmark" --release) + +# keys 包必须一起构建。只建 runtime 会让宿主用到过期的 keys 产物, +# 而那种不一致极难从现象反推(接口存在、行为却是旧的)。 +echo "==> 构建 onekey-zcash-keys" +(cd "${ROOT}/crates/zcash-keys-runtime" && wasm-pack build --mode no-install --locked --target web --out-dir "${ROOT}/pkg-keys" --release) +echo "产物:$(du -h "${ROOT}"/pkg/*.wasm "${ROOT}"/pkg-keys/*.wasm "${ROOT}"/pkg/storage-benchmark/*.wasm | tr '\n' ' ')" diff --git a/chain-runtimes/zcash/scripts/prepare-vendor.py b/chain-runtimes/zcash/scripts/prepare-vendor.py new file mode 100644 index 000000000..c7c3fa10c --- /dev/null +++ b/chain-runtimes/zcash/scripts/prepare-vendor.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Reconstruct pinned crates and their reviewed patches before Cargo runs.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import subprocess +import tarfile +import tempfile +import urllib.request + + +ROOT = Path(__file__).resolve().parent.parent + + +def file_hashes(directory): + return { + str(path.relative_to(directory)): hashlib.sha256(path.read_bytes()).hexdigest() + for path in directory.rglob("*") + if path.is_file() + } + + +def extract_crate(archive, temporary, identity): + # Accept only ordinary files/directories under the expected crate root. + # This also works on macOS Python versions without tarfile's data filter. + with tarfile.open(archive) as contents: + for member in contents: + path = PurePosixPath(member.name) + if path.is_absolute() or ".." in path.parts or not path.parts or path.parts[0] != identity: + raise RuntimeError(f"Invalid crate archive path: {member.name}") + target = Path(temporary).joinpath(*path.parts) + if member.isdir(): + target.mkdir(parents=True, exist_ok=True) + elif member.isfile(): + target.parent.mkdir(parents=True, exist_ok=True) + with contents.extractfile(member) as source: + target.write_bytes(source.read()) + else: + raise RuntimeError(f"Unsupported crate archive entry: {member.name}") + + +def prepare(offline): + vendor = ROOT / "vendor" + archives = vendor / ".archives" + archives.mkdir(parents=True, exist_ok=True) + cargo_home = Path(os.environ.get("CARGO_HOME", Path.home() / ".cargo")) + manifest = json.loads((ROOT / "patches/manifest.json").read_text()) + for entry in manifest: + identity = f"{entry['name']}-{entry['version']}" + archive = archives / f"{identity}.crate" + if not archive.exists(): + cached = list((cargo_home / "registry/cache").glob(f"*/{identity}.crate")) + if cached: + data = cached[0].read_bytes() + elif offline: + raise RuntimeError(f"Missing cached archive for {identity}; run without --offline once") + else: + request = urllib.request.Request( + f"https://static.crates.io/crates/{entry['name']}/{identity}.crate", + headers={"User-Agent": "OneKey app-modules Zcash build"}, + ) + with urllib.request.urlopen(request, timeout=60) as response: + data = response.read() + if hashlib.sha256(data).hexdigest() != entry["sha256"]: + raise RuntimeError(f"Archive checksum mismatch: {identity}") + archive.write_bytes(data) + if hashlib.sha256(archive.read_bytes()).hexdigest() != entry["sha256"]: + raise RuntimeError(f"Cached archive checksum mismatch: {identity}") + + with tempfile.TemporaryDirectory(prefix="prepare-", dir=vendor) as temporary: + extract_crate(archive, temporary, identity) + source = Path(temporary) / identity + subprocess.run( + ["patch", "--batch", "--forward", "-F", "0", "-p1", "-i", str(ROOT / "patches" / entry["patch"])], + cwd=source, + check=True, + ) + destination = vendor / identity + if destination.exists(): + if file_hashes(source) != file_hashes(destination): + raise RuntimeError(f"Existing vendor files differ from the pinned source and patch: {identity}") + else: + source.rename(destination) + print(f"Verified {identity}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--offline", action="store_true", help="Use cached crate archives only") + prepare(parser.parse_args().offline) diff --git a/chain-runtimes/zcash/scripts/test_prepare_vendor.py b/chain-runtimes/zcash/scripts/test_prepare_vendor.py new file mode 100644 index 000000000..321dfa9ae --- /dev/null +++ b/chain-runtimes/zcash/scripts/test_prepare_vendor.py @@ -0,0 +1,90 @@ +import hashlib +import importlib.util +import io +import json +from pathlib import Path +import tarfile +import tempfile +import unittest +from unittest.mock import patch + + +SCRIPT = Path(__file__).with_name("prepare-vendor.py") +SPEC = importlib.util.spec_from_file_location("prepare_vendor", SCRIPT) +vendor = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(vendor) + + +class VendorTests(unittest.TestCase): + def setUp(self): + parent = SCRIPT.parent.parent / "target" / "vendor-tests" + parent.mkdir(parents=True, exist_ok=True) + self.temporary = tempfile.TemporaryDirectory(dir=parent) + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.identity = "fixture-1.0.0" + self.archive = self.root / "vendor/.archives/fixture-1.0.0.crate" + self.archive.parent.mkdir(parents=True) + self.write_archive("fixture-1.0.0/src/lib.rs", b"before\n") + (self.root / "patches").mkdir() + (self.root / "patches/change.patch").write_text( + "--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1 +1 @@\n-before\n+after\n" + ) + (self.root / "patches/manifest.json").write_text(json.dumps([{ + "name": "fixture", "version": "1.0.0", "patch": "change.patch", + "sha256": hashlib.sha256(self.archive.read_bytes()).hexdigest(), + }])) + self.addCleanup(patch.stopall) + patch.object(vendor, "ROOT", self.root).start() + patch.dict("os.environ", {"CARGO_HOME": str(self.root / "cargo")}).start() + + def write_archive(self, name, data): + with tarfile.open(self.archive, "w:gz") as contents: + member = tarfile.TarInfo(name) + member.size = len(data) + contents.addfile(member, io.BytesIO(data)) + + def test_reconstructs_the_patch_and_verifies_an_existing_tree(self): + vendor.prepare(offline=True) + vendor.prepare(offline=True) + self.assertEqual((self.root / "vendor/fixture-1.0.0/src/lib.rs").read_text(), "after\n") + + def test_refuses_drift_without_overwriting_existing_sources(self): + vendor.prepare(offline=True) + source = self.root / "vendor/fixture-1.0.0/src/lib.rs" + source.write_text("local change\n") + with self.assertRaisesRegex(RuntimeError, "Existing vendor files differ"): + vendor.prepare(offline=True) + self.assertEqual(source.read_text(), "local change\n") + + def test_refuses_an_archive_with_the_wrong_checksum(self): + self.archive.write_bytes(b"not the pinned archive") + with self.assertRaisesRegex(RuntimeError, "checksum mismatch"): + vendor.prepare(offline=True) + self.assertFalse((self.root / "vendor/fixture-1.0.0").exists()) + + def test_offline_never_downloads_a_missing_archive(self): + self.archive.unlink() + with patch.object(vendor.urllib.request, "urlopen") as download: + with self.assertRaisesRegex(RuntimeError, "Missing cached archive"): + vendor.prepare(offline=True) + download.assert_not_called() + + def test_refuses_archive_path_traversal(self): + self.write_archive("fixture-1.0.0/../../escape", b"fixture") + with self.assertRaisesRegex(RuntimeError, "Invalid crate archive path"): + vendor.extract_crate(self.archive, self.root / "extracted", self.identity) + self.assertFalse((self.root / "escape").exists()) + + def test_refuses_archive_links(self): + with tarfile.open(self.archive, "w:gz") as contents: + member = tarfile.TarInfo("fixture-1.0.0/link") + member.type = tarfile.SYMTYPE + member.linkname = "../../escape" + contents.addfile(member) + with self.assertRaisesRegex(RuntimeError, "Unsupported crate archive entry"): + vendor.extract_crate(self.archive, self.root / "extracted", self.identity) + + +if __name__ == "__main__": + unittest.main() diff --git a/chain-runtimes/zcash/scripts/vendor-deps.sh b/chain-runtimes/zcash/scripts/vendor-deps.sh new file mode 100755 index 000000000..87a17eb15 --- /dev/null +++ b/chain-runtimes/zcash/scripts/vendor-deps.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# Reconstruct the exact upstream crates and checked-in patches. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +exec python3 "${ROOT}/scripts/prepare-vendor.py" "$@" diff --git a/package.json b/package.json index ee46f8e8e..24bf22a21 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,10 @@ "version:patch:update": "yarn workspaces foreach --all --exclude @onekeyfe/app-modules-example --exclude @onekeyfe/app-modules --topological version --deferred patch", "version:patch:apply": "yarn version apply --all", "version:patch": "yarn version:patch:update && yarn version:patch:apply", - "version:publish": "yarn workspaces foreach --all --exclude @onekeyfe/app-modules-example --exclude @onekeyfe/app-modules --exclude @onekeyfe/react-native-native-list --topological --parallel --jobs 4 --interlaced run release" + "version:publish": "yarn workspaces foreach --all --exclude @onekeyfe/app-modules-example --exclude @onekeyfe/app-modules --exclude @onekeyfe/react-native-native-list --topological --parallel --jobs 4 --interlaced run release", + "zcash:prepare": "cd chain-runtimes/zcash && bash scripts/vendor-deps.sh", + "zcash:test": "cd chain-runtimes/zcash && cargo test --workspace --locked", + "zcash:build": "cd chain-runtimes/zcash && bash scripts/build-wasm.sh" }, "workspaces": [ "native-modules/*", From 4f23461852e7cb95726d0c96011845d86a443987 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 8 Sep 2026 15:59:01 +0800 Subject: [PATCH 02/97] fix: make zcash opfs storage durable across workers --- chain-runtimes/zcash/IMPORT.md | 13 +- chain-runtimes/zcash/README.md | 78 +- .../zcash/crates/zcash-runtime/src/bindgen.rs | 19 +- .../zcash/crates/zcash-runtime/src/send.rs | 2 +- .../zcash/crates/zcash-runtime/src/storage.rs | 285 +++----- chain-runtimes/zcash/patches/manifest.json | 2 +- ...te-wasm-vfs-0.2.0-durability-barrier.patch | 82 --- ...qlite-wasm-vfs-0.2.0-opfs-durability.patch | 679 ++++++++++++++++++ 8 files changed, 824 insertions(+), 336 deletions(-) delete mode 100644 chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-durability-barrier.patch create mode 100644 chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch diff --git a/chain-runtimes/zcash/IMPORT.md b/chain-runtimes/zcash/IMPORT.md index 351518b2f..514b6b750 100644 --- a/chain-runtimes/zcash/IMPORT.md +++ b/chain-runtimes/zcash/IMPORT.md @@ -11,7 +11,7 @@ The runtime is OneKey's adapter over the versions of librustzcash pinned in original local repository is retained. Generated packages, Cargo build caches, browser experiments, logs, and local wallet data are not imported. -## Existing vendor changes preserved by this import +## Vendor changes The source checkout depended on two local vendor trees. Only one of their patches was originally tracked. Both are now reconstructible from the upstream @@ -19,10 +19,11 @@ crate archive checksums in `patches/manifest.json`: 1. `zcash_client_sqlite 0.22.0`: disable rusqlite's `bundled` feature for WASM. Its Rust source is unchanged. -2. `sqlite-wasm-vfs 0.2.0`: preserve the existing durability barrier and sticky - sync-error handling in `src/relaxed_idb.rs`. This patch was recovered by - comparing the old checkout against the published crate source. It is not a - new storage behavior introduced by the migration. +2. The import initially preserved the existing `relaxed_idb` durability barrier. + The subsequent unified Worker change replaces it with + `sqlite-wasm-vfs-0.2.0-opfs-durability.patch`: per-connection locks, durable + journal deletion, handle cleanup and fail-closed metadata I/O. All App + platforms use this same patch. The old IndexedDB patch is no longer applied. `scripts/vendor-deps.sh` verifies the archives, applies the exact patches, and rejects an existing vendor tree whose contents differ. No vendor source or @@ -36,7 +37,7 @@ Build both outputs before installing the app dependencies. Package names and runtime interfaces are unchanged by this import. Registry publishing and a versioned app dependency are a separate release step. -## Local validation (2026-09-08) +## Source-import validation (before the OPFS change, 2026-09-08) - All first-party Rust source and `Cargo.lock` match the source checkout byte for byte. Both reconstructed vendor trees match the source checkout's Rust diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md index 3699dfb37..9541db445 100644 --- a/chain-runtimes/zcash/README.md +++ b/chain-runtimes/zcash/README.md @@ -17,7 +17,7 @@ ## 这个项目为什么存在 -现有实现建在 `ChainSafe/WebZjs` 的 fork 上,而那个仓库自 2026-04-16 起没有任何分支收到过推送。 +此前的实现建在 `ChainSafe/WebZjs` 的 fork 上,而那个仓库自 2026-04-16 起没有任何分支收到过推送。 更要紧的是它使用 `zcash_client_memory` 作为存储后端 —— 那个 crate 从未发布到 crates.io, 2026-06-20 被从 librustzcash 切成独立仓库后只有 dependabot 在动。我们为它 vendor 了 11,122 行代码并改动了 27 个源文件中的 22 个,且每次 `zcash_client_backend` 升版都要自己重迁一遍。 @@ -30,49 +30,24 @@ --- -## 拆成两个包:移动端不该为了派生地址而吃下整个扫链引擎 +## 同一套 Rust / WASM,所有 App 端共用 -| crate | 产物 | 内容 | 谁需要 | -|---|---|---|---| -| `onekey-zcash-keys` | **1.74 MB** | 派生 UFVK、地址;无存储、无网络、无 SQLite | **iOS / Android**,以及任何只需看账材料的场合 | -| `onekey-zcash-runtime` | **4.67 MB** | 扫链、SQLite 存储、lightwalletd 网络 | Desktop / Web /(将来)插件 | +`onekey-zcash-keys` 负责派生和签名,不依赖 SQLite、网络、扫描器或 prover。 +`onekey-zcash-runtime` 负责钱包、扫描、SQLite 和 PCZT 证明。它们是按功能拆分的两个 +WASM 产物,不是按平台维护的两套实现;Desktop、Web、扩展和 iOS/Android 都使用它们。 +`zcash-storage-benchmark` 仅用于开发者合成数据测试。 -依赖面完全隔开 —— keys crate 明确不依赖 `zcash_client_backend`、`zcash_client_sqlite`、 -`rusqlite`、`sqlite-wasm-rs`、`tonic`。移动端想误引扫链代码,**编译期就过不去**, -不用靠人记着。 - -### 但「拆开」不等于「移动端只能用 keys」 - -`onekey-zcash-runtime` 的钱包核心(`wallet` / `account` / `storage` / `blockcache` / -`clock` / `error`)是**全平台**的。实测三个 target 都编译通过: - -| target | 状态 | -|---|---| -| `wasm32-unknown-unknown` | ✅ | -| `aarch64-apple-ios` | ✅ | -| 本机原生(macOS) | ✅ | - -也就是说移动端有两条路,选哪条是产品决策而非技术限制: - -- **keys-only(1.74 MB)** —— 能收款、能显示地址,**看不到余额、没有历史、不能发送**, - 因为那些都要扫链结果。适合「移动端暂不支持 Zcash 私密余额」这个明确的产品选择。 -- **原生完整 runtime** —— 把这个 crate 编成 `.a` / `.so` 走 RN 原生模块。 - 这正是官方 `zcash-android-wallet-sdk/backend-lib` 的做法。**绕开 WebView、绕开 - `crossOriginIsolated`、性能最好**。缺的只有一个原生 transport(见下)。 - -只有 `network` / `sync` / `runtime` / `bindgen` 四个模块是 wasm 专属, -因为网络层目前只实现了浏览器的 gRPC-web 传输。移动端原生要接 tonic 的原生 transport, -那是一个独立的 cfg 分支,`LightClient` 的签名不用变。 - -参考:Ledger Live 在这件事上的答案是**不做** —— `ledger-live-mobile` 里 zcash/shielded -相关文件 0 个,RN stub 直接抛 `"ZCash is not supported on React Native"`。 -他们的引擎只有 Node napi 产物,连 wasm 都没有,所以移动端没有选择。我们有。 +所有 App 载体均在 DedicatedWorker 执行公共 TypeScript SDK 和 WASM。 +移动端由 WebEmbed 创建内联 Blob Worker;其他端创建 URL Worker。 +Rust native 构建保留用于测试和诊断,不作为 App 的另一套生产后端。 +WASM 大小以当前构建产物及 App 压缩包检查为准,不沿用早期实验数字。 ## 硬约束 1. **不 vendor、不 fork 任何 Zcash 存储实现。** 存储层必须来自 crates.io 上未修改的 `zcash_client_sqlite`。唯一例外是一处 Cargo.toml 改动(下节),Rust 源码零改动。 -2. **密钥材料不出 wasm。** 种子、USK、签名留在 Rust 侧(可 zeroize),不跨边界。 +2. **种子仅在授权的派生/签名调用中短暂传入 keys WASM。** Rust 清理秘密缓冲区; + JS 字符串及跨桥复制不能宣称可可靠擦除。扫描器持有 UFVK,不保存种子。 3. **接口动词少、数据简单。** 只传 string / number / boolean / JSON 字符串,不把 Rust 对象句柄交给 JS 管生命周期。每次调用是一次完整往返。 @@ -98,8 +73,9 @@ 已启用的 feature,只能改它的 Cargo.toml。 处理方式是可审计的:`scripts/vendor-deps.sh` 下载官方发布版并施加 -`patches/zcash_client_sqlite-0.22.0-no-bundled.patch`(**1 行**)。另外,VFS 的既有持久化 barrier 补丁记录在 `patches/manifest.json`。升级版本时更新 manifest 里的 -`VERSION` 重跑即可。脚本末尾会校验没有任何 `.rs` 被改动。 +`patches/zcash_client_sqlite-0.22.0-no-bundled.patch`(**1 行**)。VFS 的公共 OPFS 修复也记录在 `patches/manifest.json`:连接锁、日志删除持久化、 +句柄清理和元数据失败后停止 I/O。`scripts/prepare-vendor.py --offline` 根据校验过的 +官方归档与补丁重建并比较全部文件,拒绝未记录的 vendor 改动。 wasm 侧的 SQLite 由 `sqlite-wasm-rs` 提供(预编译,不在构建期编 C)。 `crates/zcash-runtime/build.rs` 自动把它的 `libwsqlite3.a` 按链接器要的名字接上, @@ -109,22 +85,18 @@ wasm 侧的 SQLite 由 `sqlite-wasm-rs` 提供(预编译,不在构建期编 ## 存储:数据存在哪 -SQLite 从不直接碰文件,它通过 VFS 接口读写字节,而那个接口只有五个动作: -`read` / `write` / `truncate` / `flush` / `size`。接到哪,数据就在哪。 - -浏览器侧接到 **IndexedDB**(`sqlite-wasm-vfs` 的 `relaxed_idb`)。选它而不是 OPFS 的 -`sahpool`,因为后者的同步访问句柄只在 Worker 里可用,而 relaxed-idb 在所有上下文都能跑 —— -这对要覆盖的载体(桌面 renderer、浏览器页面、插件 offscreen、移动 WebView)是必要条件。 +所有 App 端统一使用 `sqlite-wasm-vfs` 的 OPFS SAH-pool,目录为 `.onekey-zcash-opfs`。 +SQLite 按页直接读写同步访问句柄,不再把整库预载成 WASM 内存镜像。 +每个 origin 的池由一个 Worker 独占;第二个 Worker 不能静默改用其他数据库。 +默认预留六个文件句柄,网络数据库仍为 `zcash-main.db` / `zcash-test.db`。 -代价是它不是「完全持久」:读写在内存里同步服务,异步批量刷进 IndexedDB,崩溃可能丢掉最近一批。 -对扫链缓存可接受 —— 数据本来就能从链上重建。 - -> 这个约束是**物理性**的:SQLite 的 VFS 接口是同步的(`read` 必须立刻返回), -> 而浏览器存储是异步的。不要求 COI 的前提下,可行形态只有「内存同步服务 + 异步刷盘」。 - ---- +连接明确设置 `journal_mode=DELETE`、`synchronous=FULL`。提交和日志删除的 flush +错误必须传回宿主;元数据 I/O 失败后该 VFS 停止服务,需要重建 Worker。 +不要求 SharedArrayBuffer、COOP/COEP 或 UI 线程上的同步文件访问。 +OPFS 仍受浏览器 origin、配额和清理策略约束;App 内嵌页面的来源必须稳定。 +本次处于开发阶段,不提供旧 IndexedDB 库迁移。运行时的新交易持久化要求仍然保留。 -## 当前进度 +## 先前版本的验证记录(不替代当前 OPFS 验收) > 状态:**runtime 的看账与发送链路已在 testnet 上真实上链验证,App 适配层已接入并通过 > 类型、单元与浏览器 runtime 检查。** App 内的有资金发送闭环与主网真实交易仍需人工验收。 diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs index 854ab0b8e..981c7edcf 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs @@ -36,6 +36,12 @@ pub async fn init() -> Result<(), JsValue> { Ok(()) } +/// Preserve a failed call's result, then retire its poisoned storage owner. +#[wasm_bindgen(js_name = storageRequiresWorkerRestart)] +pub fn storage_requires_worker_restart() -> bool { + storage::requires_worker_restart() +} + /// panic 变成带堆栈的 console 错误,而不是一个永远不 settle 的 Promise。 /// /// 必须在**每个**入口都装。曾经只装在 `init()` 里,于是走 `initMemoryStorage()` @@ -89,8 +95,8 @@ pub fn capabilities() -> String { "scan": true, "balance": true, "history": true, - // The wallet can create the proposal, the prover package attaches proofs, and the keys - // package signs transparent inputs. The host must combine all three capabilities. + // The wallet creates proposals and proofs; the keys package signs inputs. + // The host must combine both packages' capabilities. "proveShielding": true, "notes": { // 说明为什么不通,宿主可以据此给用户不同的提示 @@ -124,17 +130,12 @@ pub async fn block_summary(height: u32) -> Result { ) } -/// 打开(必要时创建)钱包库并把 schema 迁移到当前版本。 -/// -/// 异步是因为要先把这个库从 IndexedDB 读进 VFS。VFS 装的是 `Preload::None` -/// (不预载该 origin 下的全部库),代价就是必须按名字点一次 —— 漏掉这一步, -/// 已存在的库不会出现在文件表里,SQLite 会当成新库重新建表, -/// 于是每次启动都从 birthday 全量重扫,而扫链看上去一切正常。 +/// Open a page-backed database and apply the official SQLite migrations. +/// No whole-database preload is required by the shared OPFS VFS. #[wasm_bindgen(js_name = openWallet)] pub async fn open_wallet(network_name: String, db_name: String) -> Result { let _perf = perf::span("openWallet"); let (network_name, db_name) = (network_name.as_str(), db_name.as_str()); - storage::preload_database(db_name).await?; let db = wallet::open_and_migrate(network_name, db_name)?; // 有异步操作在进行时这里会拒绝(WALLET_BUSY)—— 必须传播出去, // 否则调用方会以为库已经换了,而实际上还是旧的。 diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs index aef6c6c29..4ff447048 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs @@ -808,7 +808,7 @@ pub fn raw_transaction(db: &Db, txid: &str) -> Result> { Ok(raw) } -/// The separately loaded prover package supports these proof types. +/// Proof types supported by this wallet runtime. pub const PROVE_ORCHARD: bool = true; pub const PROVE_SAPLING: bool = false; pub const PROVE_IRONWOOD: bool = true; diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs index 926ecea9c..400888b87 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs @@ -1,23 +1,13 @@ -//! 存储适配。 +//! Shared SQLite storage for every App carrier. //! -//! SQLite 从不直接碰文件 —— 它通过 VFS(虚拟文件系统)接口读写字节,而那个接口 -//! 只有五个动作:read / write / truncate / flush / size。把这五个动作接到哪里, -//! 决定了数据实际存在哪。 -//! -//! 浏览器侧我们接到 IndexedDB(`sqlite-wasm-vfs` 的 `relaxed_idb` 实现)。选它 -//! 而不是 OPFS 的 `sahpool`,是因为 sahpool 的同步访问句柄只在 Worker 里可用, -//! 而 relaxed-idb 在所有上下文都能跑 —— 这对我们要覆盖的载体(桌面 renderer、 -//! 浏览器页面、插件 offscreen、移动 WebView)是必要条件。 -//! -//! 代价是它不是「完全持久」:读写在内存里同步服务,异步批量刷进 IndexedDB, -//! 崩溃可能丢掉最近一批。对扫链缓存这是可接受的 —— 数据本来就可以从链上重建。 +//! WASM runs in a dedicated Worker and uses the same OPFS synchronous-access +//! VFS on desktop, web, extension, and mobile WebEmbed. SQLite accesses pages +//! directly instead of preloading a complete IndexedDB mirror into WASM memory. +//! Native builds remain available for Rust tests and diagnostics. use crate::error::{ErrorCode, Result, RuntimeError}; use serde_json::json; -// 强制把 sqlite-wasm-rs 链进最终产物:它提供 sqlite3_os_init 与 -// rust_sqlite_wasm_{malloc,free,localtime} 这几个符号。若没有任何代码引用它, -// rustc 不会把它的 rlib 纳入链接,链接期就会报 undefined symbol。 #[cfg(target_arch = "wasm32")] use sqlite_wasm_rs as _; @@ -27,132 +17,109 @@ use std::sync::atomic::{AtomicBool, Ordering}; #[cfg(target_arch = "wasm32")] static VFS_READY: AtomicBool = AtomicBool::new(false); -// `install()` 返回的管理句柄。**必须留着** —— `Preload::None` 下已存在的库不会 -// 自己出现在 VFS 的文件表里,得先 `preload_db` 才能被 SQLite 打开。丢掉这个句柄 -// 就没有别的入口,而症状是静默的:库看起来是空的,于是重新建表、从 birthday -// 全量重扫,扫链本身一切正常。 -// `Rc` 是为了能在不持有 RefCell 借用的情况下跨 await 使用它 —— -// `RelaxedIdbUtil` 本身不是 Clone。 #[cfg(target_arch = "wasm32")] thread_local! { static VFS_UTIL: std::cell::RefCell< - Option>, + Option>, > = const { std::cell::RefCell::new(None) }; } -/// 把某个库从 IndexedDB 读进 VFS 的文件表。打开该库**之前**必须调一次。 -/// -/// 幂等:已经在表里的库会被跳过。 #[cfg(target_arch = "wasm32")] -pub async fn preload_database(db_name: &str) -> Result<()> { - // 内存存储模式没有装持久化 VFS,也就没有 IndexedDB 可读 —— 这里必须放行, - // 否则所有走内存存储的排查页都会在开库这一步报 NOT_INITIALIZED。 - if memory_mode() { - return Ok(()); - } - let util = VFS_UTIL.with(|u| u.borrow().clone()); - let Some(util) = util else { - return Err(RuntimeError::with( - ErrorCode::NotInitialized, - json!({ "reason": "vfsNotInstalled" }), - )); - }; - util.preload_db(vec![db_name.to_owned()]) - .await - .map_err(|e| { - RuntimeError::with( - ErrorCode::DatabaseError, - json!({ "operation": "preloadDb" }), - ) - .detail(format!("{e:?}")) - }) -} - -#[cfg(not(target_arch = "wasm32"))] -pub async fn preload_database(_db_name: &str) -> Result<()> { - Ok(()) -} - -/// Wait until every relaxed-IDB commit queued before this call has completed. -/// -/// SQLite's xSync schedules the real IndexedDB write but cannot await it from -/// the synchronous VFS callback. The vendored VFS barrier runs on that same -/// FIFO queue and reports any earlier sync failure. This is required before a -/// locally finalized transaction may be broadcast. -#[cfg(target_arch = "wasm32")] -pub async fn durability_barrier() -> Result<()> { - if memory_mode() { - return Ok(()); - } - let util = VFS_UTIL.with(|u| u.borrow().clone()).ok_or_else(|| { +fn persistent_vfs() -> Result> { + VFS_UTIL.with(|slot| slot.borrow().clone()).ok_or_else(|| { RuntimeError::with( ErrorCode::NotInitialized, json!({ "reason": "vfsNotInstalled" }), ) - })?; - util.barrier() - .map_err(|error| { - RuntimeError::with( - ErrorCode::DatabaseError, - json!({ "operation": "durabilityBarrier" }), - ) - .detail(format!("{error:?}")) - })? - .await - .map_err(|error| { - RuntimeError::with( - ErrorCode::DatabaseError, - json!({ "operation": "durabilityBarrier" }), - ) - .detail(format!("{error:?}")) - }) -} - -#[cfg(not(target_arch = "wasm32"))] -pub async fn durability_barrier() -> Result<()> { - Ok(()) + }) } -/// 安装持久化 VFS 并设为默认。 -/// -/// 幂等:重复调用只有第一次生效。必须在任何 `open_wallet` 之前完成。 -/// -/// 不调用它就走 sqlite-wasm-rs 内置的**内存 VFS** —— 数据不落盘,页面刷新即失。 -/// 那条路的用途有二:临时/一次性钱包;以及排查问题时把「存储层」从 -/// 「纯计算」里摘出来(同样的扫描在内存 VFS 上跑一遍,就知道慢的是哪一半)。 +/// Install the same page-backed VFS in every browser carrier. +/// The pool owns exclusive file handles until its Worker is terminated. #[cfg(target_arch = "wasm32")] pub async fn install_persistent_vfs() -> Result<()> { use sqlite_wasm_rs as ffi; - use sqlite_wasm_vfs::relaxed_idb::{install, RelaxedIdbCfg}; + use sqlite_wasm_vfs::sahpool::{install, OpfsSAHError, OpfsSAHPoolCfg}; - if VFS_READY.load(Ordering::SeqCst) { + if is_ready() { return Ok(()); } - // 默认是 `Preload::All` —— 打开 VFS 时把该 origin 下**所有**库整个读进内存。 - // 改成 `None`,配合开库时的 `preload_database(name)`,只加载当前网络那一个。 - // - // **这不是按页懒加载。** `preload_db_impl` 会遍历该文件的全部 IndexedDB block - // 组成内存文件,SQLite 之后同步访问的是内存副本。所以库有多大,wasm 堆就吃多少、 - // 开库就等多久 —— 省下的只是「同一 origin 下其他库」的那份,不是这一个库本身。 - // 真要按页读,得换一个 page-backed 的 VFS。 - let cfg = RelaxedIdbCfg { - preload: sqlite_wasm_vfs::relaxed_idb::Preload::None, - ..RelaxedIdbCfg::default() + let cfg = OpfsSAHPoolCfg { + vfs_name: "onekey-zcash-opfs".to_owned(), + directory: ".onekey-zcash-opfs".to_owned(), + clear_on_init: false, + // Two network databases plus their rollback journals and spare handles. + initial_capacity: 6, }; - let util = install::(&cfg, true) - .await - .map_err(|e| RuntimeError::new(ErrorCode::NotInitialized).detail(format!("{e:?}")))?; - VFS_UTIL.with(|u| *u.borrow_mut() = Some(std::rc::Rc::new(util))); + // Worker termination is asynchronous in browsers. Retry only acquiring + // ownership, before opening SQLite or dispatching any wallet operation. + // A live owner still fails after the bounded handoff window. + let mut retries = 20; + let util = loop { + match install::(&cfg, true).await { + Ok(util) => break util, + Err(error) => { + let owner_releasing = match &error { + OpfsSAHError::CreateSyncAccessHandle(value) => { + js_sys::Reflect::get(value, &wasm_bindgen::JsValue::from_str("name")) + .ok() + .and_then(|name| name.as_string()) + .as_deref() + == Some("NoModificationAllowedError") + } + _ => false, + }; + if !owner_releasing || retries == 0 { + return Err( + RuntimeError::new(ErrorCode::NotInitialized).detail(format!("{error:?}")) + ); + } + retries -= 1; + gloo_timers::future::TimeoutFuture::new(250).await; + } + } + }; + VFS_UTIL.with(|slot| *slot.borrow_mut() = Some(std::rc::Rc::new(util))); VFS_READY.store(true, Ordering::SeqCst); Ok(()) } -/// 原生目标(桌面 / 移动 / 测试)不需要自定义 VFS —— 那里有真的文件系统。 #[cfg(not(target_arch = "wasm32"))] pub async fn install_persistent_vfs() -> Result<()> { Ok(()) } +/// SQLite COMMIT synchronously calls this VFS's xSync under synchronous=FULL. +/// There is no asynchronous write queue to drain. Retain the explicit boundary +/// used by transaction finalization and broadcasting; commit errors propagate +/// from the SQLite operation before this point. +pub async fn durability_barrier() -> Result<()> { + if requires_worker_restart() { + return Err(RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "reason": "storageRequiresWorkerRestart" }), + )); + } + if !memory_mode() && !is_ready() { + return Err(RuntimeError::new(ErrorCode::NotInitialized)); + } + Ok(()) +} + +#[cfg(target_arch = "wasm32")] +pub fn requires_worker_restart() -> bool { + VFS_UTIL.with(|slot| { + slot.borrow() + .as_ref() + .is_some_and(|util| util.is_poisoned()) + }) +} + +#[cfg(not(target_arch = "wasm32"))] +pub fn requires_worker_restart() -> bool { + false +} + #[cfg(target_arch = "wasm32")] pub fn is_ready() -> bool { VFS_READY.load(Ordering::SeqCst) @@ -163,12 +130,10 @@ pub fn is_ready() -> bool { true } -/// 打开一个 SQLite 连接。路径在 wasm 上是 VFS 内的逻辑名,不是磁盘路径。 -/// 标记「本次会话有意使用内存存储」,让 `open_connection` 不再要求先装 VFS。 #[cfg(target_arch = "wasm32")] static MEMORY_MODE: AtomicBool = AtomicBool::new(false); -/// 选择内存存储:不安装持久化 VFS,数据只活在本页面生命周期内。 +/// Diagnostic-only mode, selected before installing a persistent VFS. #[cfg(target_arch = "wasm32")] pub fn use_memory_storage() { MEMORY_MODE.store(true, Ordering::SeqCst); @@ -191,8 +156,6 @@ pub fn open_connection(db_name: &str) -> Result { if !memory_mode() && !is_ready() { return Err(RuntimeError::new(ErrorCode::NotInitialized)); } - // wasm 上 db_name 是 VFS 里的逻辑名,不该含路径分隔符; - // 原生上它是真实文件路径,分隔符完全合法。 let bad_name = db_name.is_empty() || (cfg!(target_arch = "wasm32") && (db_name.contains('/') || db_name.contains('\\'))); if bad_name { @@ -202,108 +165,62 @@ pub fn open_connection(db_name: &str) -> Result { )); } let conn = rusqlite::Connection::open(db_name)?; - // carray 虚拟表:zcash_client_sqlite 的部分查询用它传数组参数。 + #[cfg(target_arch = "wasm32")] + if !memory_mode() { + // SAH-pool uses rollback journals, not cross-context WAL coordination. + // Never weaken transaction durability to improve scan throughput. + conn.execute_batch("PRAGMA journal_mode = DELETE; PRAGMA synchronous = FULL;")?; + } rusqlite::vtab::array::load_module(&conn)?; Ok(conn) } -/// Checks whether a persisted database exists without opening or creating it. +/// Inspect the pool's file table without opening or creating a database. #[cfg(target_arch = "wasm32")] pub async fn database_exists(db_name: &str) -> Result { if memory_mode() { return Ok(false); } - let util = VFS_UTIL.with(|u| u.borrow().clone()).ok_or_else(|| { - RuntimeError::with( - ErrorCode::NotInitialized, - json!({ "reason": "vfsNotInstalled" }), - ) - })?; - util.preload_db(vec![db_name.to_owned()]) - .await - .map_err(|e| { - RuntimeError::with( - ErrorCode::DatabaseError, - json!({ "operation": "inspectDb" }), - ) - .detail(format!("{e:?}")) - })?; - Ok(util.exists(db_name)) + persistent_vfs()? + .exists(db_name) + .map_err(|error| db_storage_err("inspectDatabase", db_name, error)) } -/// Checks whether a native database file exists without opening or creating it. #[cfg(not(target_arch = "wasm32"))] pub async fn database_exists(db_name: &str) -> Result { Ok(std::path::Path::new(db_name).exists()) } -/// 删除一个钱包库,连同它在 IndexedDB 里的全部字节。 -/// -/// ## 为什么这是安全的 -/// -/// 钱包库是**纯派生缓存**:扫过的区块、解密出来的 note、witness、交易历史, -/// 全都能从链上重新扫出来。真正不可再生的东西 —— UFVK 与 birthday —— -/// 由宿主存在自己的账户元数据里,不在这个库里。所以擦掉它不丢任何东西, -/// 只是下次要重扫。 -/// -/// **反过来说这是一条硬约束**:将来若把 birthday 之类的权威数据挪进这个库, -/// 本函数就从「清缓存」变成「毁数据」。要挪之前先改这里。 -/// -/// ## 两种用途 -/// -/// - 出问题时的**手动重置**:历史错乱、余额对不上,擦掉重建 -/// - **删账户**时的清理:库里存着已解密的屏蔽交易历史,正是 Zcash 要隐藏的东西, -/// 账户没了它必须跟着没 -/// -/// 返回是否确实删掉了(库本来就不存在时返回 false,不算错误)。 +/// Delete a closed database. Callers must first resolve active transactions; +/// pending broadcast state must not be discarded as rebuildable scan cache. #[cfg(target_arch = "wasm32")] pub async fn delete_database(db_name: &str) -> Result { - use sqlite_wasm_rs as ffi; - use sqlite_wasm_vfs::relaxed_idb::{install, RelaxedIdbCfg}; - if memory_mode() { - // 内存存储下没有持久化副本,数据随页面消失,没什么可删。 - return Ok(false); - } - if !is_ready() { - return Err(RuntimeError::new(ErrorCode::NotInitialized)); - } - - // install 是幂等的:已注册时只返回管理句柄,不会重复注册。 - let util = install::(&RelaxedIdbCfg::default(), true) - .await - .map_err(|e| RuntimeError::new(ErrorCode::NotInitialized).detail(format!("{e:?}")))?; - - if !util.exists(db_name) { return Ok(false); } - // 上游明确要求删除前库必须已关闭,否则句柄与存储会不一致。 - util.delete_db(db_name) - .map_err(|e| db_delete_err(db_name, e))? - .await - .map_err(|e| db_delete_err(db_name, e))?; - Ok(true) + persistent_vfs()? + .delete_db(db_name) + .map_err(|error| db_storage_err("deleteDatabase", db_name, error)) } -/// 原生目标:直接删文件。 #[cfg(not(target_arch = "wasm32"))] pub async fn delete_database(db_name: &str) -> Result { match std::fs::remove_file(db_name) { Ok(()) => Ok(true), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), - Err(e) => Err(RuntimeError::with( + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(RuntimeError::with( ErrorCode::DatabaseError, json!({ "operation": "deleteDatabase", "dbName": db_name }), ) - .detail(e)), + .detail(error)), } } #[cfg(target_arch = "wasm32")] -fn db_delete_err(db_name: &str, e: impl std::fmt::Debug) -> RuntimeError { +fn db_storage_err(operation: &str, db_name: &str, error: impl std::fmt::Debug) -> RuntimeError { RuntimeError::with( ErrorCode::DatabaseError, - json!({ "operation": "deleteDatabase", "dbName": db_name }), + json!({ "operation": operation, "dbName": db_name }), ) - .detail(format!("{e:?}")) + .detail(format!("{error:?}")) } diff --git a/chain-runtimes/zcash/patches/manifest.json b/chain-runtimes/zcash/patches/manifest.json index dcb79deeb..2d534ca1e 100644 --- a/chain-runtimes/zcash/patches/manifest.json +++ b/chain-runtimes/zcash/patches/manifest.json @@ -9,6 +9,6 @@ "name": "sqlite-wasm-vfs", "version": "0.2.0", "sha256": "7f7a5c9ac229421d577bb5a9bb59048838509958b218dd4e0b3c1214a87c361e", - "patch": "sqlite-wasm-vfs-0.2.0-durability-barrier.patch" + "patch": "sqlite-wasm-vfs-0.2.0-opfs-durability.patch" } ] diff --git a/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-durability-barrier.patch b/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-durability-barrier.patch deleted file mode 100644 index 7f6bfda77..000000000 --- a/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-durability-barrier.patch +++ /dev/null @@ -1,82 +0,0 @@ ---- a/src/relaxed_idb.rs -+++ b/src/relaxed_idb.rs -@@ -130,6 +130,7 @@ - Sync(String), - Delete(String), - Clear, -+ Barrier, - } - - enum IdbFile { -@@ -325,6 +326,7 @@ - idb: Database, - name2file: RefCell>, - tx: UnboundedSender, -+ commit_error: RefCell>, - } - - impl RelaxedIdb { -@@ -348,6 +350,7 @@ - idb: indexed_db, - name2file: RefCell::new(name2file), - tx, -+ commit_error: RefCell::new(None), - }) - } - -@@ -469,6 +472,10 @@ - self.send_task_with_notify(IdbCommitOp::Clear) - } - -+ fn barrier(&self) -> Result { -+ self.send_task_with_notify(IdbCommitOp::Barrier) -+ } -+ - fn exists(&self, file: &str) -> bool { - self.name2file.borrow().contains_key(file) - } -@@ -542,11 +549,28 @@ - async fn commit_loop(&self, mut rx: UnboundedReceiver) { - while let Some(commit) = rx.recv().await { - let IdbCommit { op, notify } = commit; -+ let is_sync = matches!(&op, IdbCommitOp::Sync(_)); - let ret = match op { - IdbCommitOp::Sync(file) => self.sync_db_impl(&file).await, - IdbCommitOp::Delete(file) => self.delete_db_impl(&file).await, - IdbCommitOp::Clear => clear_impl(&self.idb).await, -+ // A failed sync already discarded its dirty-block list, so a -+ // later successful barrier cannot make that write durable. -+ // Keep the carrier poisoned until the module is reloaded and -+ // the database is reconstructed from IndexedDB. -+ IdbCommitOp::Barrier => match self.commit_error.borrow().as_ref() { -+ Some(error) => Err(RelaxedIdbError::Generic(error.clone())), -+ None => Ok(()), -+ }, - }; -+ if is_sync { -+ if let Err(error) = &ret { -+ let mut commit_error = self.commit_error.borrow_mut(); -+ if commit_error.is_none() { -+ *commit_error = Some(error.to_string()); -+ } -+ } -+ } - if let Some(notify) = notify { - // An unsuccessful send would be one where the corresponding receiver - // has already been deallocated. -@@ -890,6 +914,15 @@ - self.pool.clear_all() - } - -+ /// Wait for every earlier queued sync and surface the first sync failure. -+ /// -+ /// A failure poisons the current VFS instance because its in-memory dirty -+ /// block set can no longer prove what reached IndexedDB. Reload the VFS -+ /// before attempting more durable writes. -+ pub fn barrier(&self) -> Result { -+ self.pool.barrier() -+ } -+ - /// Does the database exists. - pub fn exists(&self, filename: &str) -> bool { - self.pool.exists(filename) diff --git a/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch b/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch new file mode 100644 index 000000000..8cf700deb --- /dev/null +++ b/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch @@ -0,0 +1,679 @@ +--- a/src/sahpool.rs ++++ b/src/sahpool.rs +@@ -36,14 +36,16 @@ + check_import_db, + ffi::{ + sqlite3_file, sqlite3_filename, sqlite3_vfs, sqlite3_vfs_register, sqlite3_vfs_unregister, +- SQLITE_CANTOPEN, SQLITE_ERROR, SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN, SQLITE_IOERR, +- SQLITE_IOERR_DELETE, SQLITE_OK, SQLITE_OPEN_DELETEONCLOSE, SQLITE_OPEN_MAIN_DB, +- SQLITE_OPEN_MAIN_JOURNAL, SQLITE_OPEN_SUPER_JOURNAL, SQLITE_OPEN_WAL, ++ SQLITE_BUSY, SQLITE_CANTOPEN, SQLITE_ERROR, SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN, ++ SQLITE_IOERR, SQLITE_IOERR_DELETE, SQLITE_LOCK_EXCLUSIVE, SQLITE_LOCK_NONE, ++ SQLITE_LOCK_PENDING, SQLITE_LOCK_RESERVED, SQLITE_LOCK_SHARED, SQLITE_OK, ++ SQLITE_OPEN_DELETEONCLOSE, SQLITE_OPEN_MAIN_DB, SQLITE_OPEN_MAIN_JOURNAL, ++ SQLITE_OPEN_SUPER_JOURNAL, SQLITE_OPEN_WAL, + }, + register_vfs, registered_vfs, ImportDbError, OsCallback, RegisterVfsError, SQLiteIoMethods, + SQLiteVfs, SQLiteVfsFile, VfsAppData, VfsError, VfsFile, VfsResult, VfsStore, + }; +-use std::collections::{HashMap, HashSet}; ++use std::collections::HashMap; + use std::time::Duration; + use std::{ + cell::{Cell, RefCell}, +@@ -81,6 +83,181 @@ + handle: FileSystemSyncAccessHandle, + opaque: String, + } ++ ++impl Drop for SyncAccessFile { ++ fn drop(&mut self) { ++ self.handle.close(); ++ } ++} ++ ++// Browser SAHs exclude other Workers; these locks coordinate SQLite connections ++// inside this Worker. Keep the state machine independent of browser APIs. ++mod file_locks { ++ use std::collections::HashMap; ++ ++ #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] ++ pub(super) enum Lock { ++ None, ++ Shared, ++ Reserved, ++ Pending, ++ Exclusive, ++ } ++ ++ #[derive(Default)] ++ pub(super) struct FileLocks { ++ files: HashMap, ++ } ++ ++ impl FileLocks { ++ pub(super) fn open(&mut self, id: usize, filename: &str) { ++ self.files.insert(id, (filename.into(), Lock::None)); ++ } ++ ++ pub(super) fn close(&mut self, id: usize) { ++ self.files.remove(&id); ++ } ++ ++ pub(super) fn is_empty(&self) -> bool { ++ self.files.is_empty() ++ } ++ ++ pub(super) fn lock(&mut self, id: usize, requested: Lock) -> bool { ++ let Some((filename, current)) = self.files.get(&id) else { ++ return false; ++ }; ++ if *current >= requested { ++ return true; ++ } ++ let other = self ++ .files ++ .iter() ++ .filter(|(other_id, (name, _))| **other_id != id && name == filename) ++ .map(|(_, (_, lock))| *lock) ++ .max() ++ .unwrap_or(Lock::None); ++ let allowed = match requested { ++ Lock::None => true, ++ Lock::Shared => other < Lock::Pending, ++ Lock::Reserved | Lock::Pending | Lock::Exclusive => { ++ *current >= Lock::Shared && other < Lock::Reserved ++ } ++ }; ++ if !allowed { ++ return false; ++ } ++ let (_, current) = self.files.get_mut(&id).unwrap(); ++ if requested == Lock::Exclusive && other >= Lock::Shared { ++ // Block new readers while existing readers finish, then retry. ++ *current = Lock::Pending; ++ return false; ++ } ++ *current = requested; ++ true ++ } ++ ++ pub(super) fn unlock(&mut self, id: usize, requested: Lock) -> bool { ++ let Some((_, current)) = self.files.get_mut(&id) else { ++ return false; ++ }; ++ if !matches!(requested, Lock::None | Lock::Shared) || requested > *current { ++ return false; ++ } ++ *current = requested; ++ true ++ } ++ ++ pub(super) fn reserved(&self, id: usize) -> Option { ++ let (filename, _) = self.files.get(&id)?; ++ Some( ++ self.files ++ .values() ++ .any(|(name, lock)| name == filename && *lock >= Lock::Reserved), ++ ) ++ } ++ } ++ ++ #[cfg(test)] ++ mod tests { ++ use super::{FileLocks, Lock}; ++ ++ fn connections() -> FileLocks { ++ let mut locks = FileLocks::default(); ++ for id in 1..=3 { ++ locks.open(id, "wallet.db"); ++ } ++ locks ++ } ++ ++ #[test] ++ fn readers_coexist_and_only_one_writer_reserves() { ++ let mut locks = connections(); ++ assert!(locks.lock(1, Lock::Shared)); ++ assert!(locks.lock(2, Lock::Shared)); ++ assert!(locks.lock(1, Lock::Reserved)); ++ assert!(!locks.lock(2, Lock::Reserved)); ++ assert!(locks.lock(3, Lock::Shared)); ++ assert_eq!(locks.reserved(2), Some(true)); ++ } ++ ++ #[test] ++ fn exclusive_retry_holds_pending_and_blocks_new_readers() { ++ let mut locks = connections(); ++ assert!(locks.lock(1, Lock::Shared)); ++ assert!(locks.lock(2, Lock::Shared)); ++ assert!(!locks.lock(1, Lock::Exclusive)); ++ assert_eq!(locks.files[&1].1, Lock::Pending); ++ assert!(!locks.lock(3, Lock::Shared)); ++ assert!(!locks.lock(2, Lock::Reserved)); ++ assert!(locks.unlock(2, Lock::None)); ++ assert!(locks.lock(1, Lock::Exclusive)); ++ assert!(!locks.lock(3, Lock::Shared)); ++ assert!(locks.unlock(1, Lock::Shared)); ++ assert_eq!(locks.reserved(1), Some(false)); ++ assert!(locks.lock(3, Lock::Shared)); ++ } ++ ++ #[test] ++ fn reserved_conflict_does_not_acquire_pending() { ++ let mut locks = connections(); ++ assert!(locks.lock(1, Lock::Shared)); ++ assert!(locks.lock(1, Lock::Reserved)); ++ assert!(locks.lock(2, Lock::Shared)); ++ assert!(!locks.lock(2, Lock::Exclusive)); ++ assert_eq!(locks.files[&2].1, Lock::Shared); ++ } ++ ++ #[test] ++ fn closing_one_connection_preserves_other_connections_and_locks() { ++ let mut locks = connections(); ++ assert!(locks.lock(1, Lock::Shared)); ++ assert!(locks.lock(1, Lock::Reserved)); ++ locks.close(2); ++ assert!(!locks.is_empty()); ++ assert_eq!(locks.reserved(3), Some(true)); ++ locks.close(1); ++ assert_eq!(locks.reserved(3), Some(false)); ++ locks.close(3); ++ assert!(locks.is_empty()); ++ } ++ ++ #[test] ++ fn hot_journal_recovery_and_independent_databases() { ++ let mut locks = connections(); ++ assert_eq!(locks.reserved(1), Some(false)); ++ assert!(locks.lock(1, Lock::Shared)); ++ assert!(locks.lock(1, Lock::Exclusive)); ++ locks.open(4, "other.db"); ++ assert_eq!(locks.reserved(4), Some(false)); ++ assert!(locks.lock(4, Lock::Shared)); ++ assert!(locks.lock(4, Lock::Exclusive)); ++ assert!(locks.unlock(1, Lock::None)); ++ assert_eq!(locks.reserved(2), Some(false)); ++ } ++ } ++} ++ ++use file_locks::{FileLocks, Lock}; + + struct OpfsSAHPool { + /// Directory handle to the `.opaque` subdirectory within the VFS root. +@@ -96,14 +273,26 @@ + map_filename_to_file: RefCell>, + /// A flag to indicate whether the VFS is currently paused. + is_paused: Cell, +- /// A set of filenames for all currently open database connections. +- open_files: RefCell>, ++ /// Metadata I/O failures leave durability uncertain; only a new Worker ++ /// may rebuild the file table and recover the database after such a failure. ++ poisoned: Cell, ++ /// SQLite file handles and their locks, keyed by sqlite3_file pointer. ++ open_files: RefCell, + /// A tuple holding the raw pointer to the `sqlite3_vfs` struct and whether it was registered as the default. + vfs: Cell<(*mut sqlite3_vfs, bool)>, + random: fn(&mut [u8]), + } + + impl OpfsSAHPool { ++ fn ensure_usable(&self) -> Result<()> { ++ if self.poisoned.get() { ++ return Err(OpfsSAHError::Generic( ++ "File association I/O failed; restart the Worker before using this VFS".into(), ++ )); ++ } ++ Ok(()) ++ } ++ + async fn new(options: &OpfsSAHPoolCfg) -> Result { + const OPAQUE_DIR_NAME: &str = ".opaque"; + +@@ -156,7 +345,8 @@ + map_filename_to_file: RefCell::new(HashMap::new()), + available_files: RefCell::new(Vec::new()), + is_paused: Cell::new(false), +- open_files: RefCell::new(HashSet::new()), ++ poisoned: Cell::new(false), ++ open_files: RefCell::new(FileLocks::default()), + vfs: Cell::new((std::ptr::null_mut(), false)), + random: C::random, + }; +@@ -168,6 +358,7 @@ + } + + async fn add_capacity(&self, n: u32) -> Result { ++ self.ensure_usable()?; + for _ in 0..n { + let opaque = rsqlite_vfs::random_name(self.random); + let handle: FileSystemFileHandle = +@@ -202,6 +393,7 @@ + + #[allow(clippy::await_holding_refcell_ref)] + async fn reduce_capacity(&self, n: u32) -> Result { ++ self.ensure_usable()?; + let mut available_files = self.available_files.borrow_mut(); + let available_length = available_files.len(); + let max_reduce = available_length.min(n as usize); +@@ -210,8 +402,9 @@ + drop(available_files); + + for file in files { +- file.handle.close(); +- JsFuture::from(self.dh_opaque.remove_entry(&file.opaque)) ++ let opaque = file.opaque.clone(); ++ drop(file); ++ JsFuture::from(self.dh_opaque.remove_entry(&opaque)) + .await + .map_err(OpfsSAHError::RemoveEntity)?; + } +@@ -232,8 +425,15 @@ + } + + fn get_associated_filename(&self, sah: &FileSystemSyncAccessHandle) -> Result> { +- sah.read_with_buffer_source_and_options(&self.header_buffer, &read_write_options(0.0)) ++ self.header_buffer.fill(0, 0, HEADER_CORPUS_SIZE as u32); ++ let read = sah ++ .read_with_buffer_source_and_options(&self.header_buffer, &read_write_options(0.0)) + .map_err(OpfsSAHError::Read)?; ++ if read != 0.0 && read != HEADER_CORPUS_SIZE as f64 { ++ return Err(OpfsSAHError::Generic( ++ "Incomplete file association header".into(), ++ )); ++ } + let flags = self.header_buffer_view.get_uint32(HEADER_OFFSET_FLAGS); + if self.header_buffer.get_index(0) != 0 + && ((flags & SQLITE_OPEN_DELETEONCLOSE as u32 != 0) +@@ -244,18 +444,17 @@ + + let name_length = self + .header_buffer ++ .subarray(0, HEADER_MAX_FILENAME_SIZE as u32) + .to_vec() + .iter() + .position(|&x| x == 0) +- .unwrap_or_default(); ++ .ok_or_else(|| OpfsSAHError::Generic("Invalid file association header".into()))?; + if name_length == 0 { +- sah.truncate_with_u32(HEADER_OFFSET_DATA as u32) +- .map_err(OpfsSAHError::Truncate)?; + return Ok(None); + } +- // set_associated_filename ensures that it is utf8 + let filename = +- String::from_utf8(self.header_buffer.subarray(0, name_length as u32).to_vec()).unwrap(); ++ String::from_utf8(self.header_buffer.subarray(0, name_length as u32).to_vec()) ++ .map_err(|_| OpfsSAHError::Generic("Invalid file association header".into()))?; + Ok(Some(filename)) + } + +@@ -265,6 +464,7 @@ + filename: Option<&str>, + flags: i32, + ) -> Result<()> { ++ self.ensure_usable()?; + self.header_buffer_view + .set_uint32(HEADER_OFFSET_FLAGS, flags as u32); + +@@ -285,19 +485,43 @@ + } else { + self.header_buffer + .fill(0, 0, HEADER_MAX_FILENAME_SIZE as u32); +- sah.truncate_with_u32(HEADER_OFFSET_DATA as u32) +- .map_err(OpfsSAHError::Truncate)?; +- } +- +- sah.write_with_js_u8_array_and_options(&self.header_buffer, &read_write_options(0.0)) +- .map_err(OpfsSAHError::Write)?; +- +- Ok(()) ++ } ++ ++ let result = (|| { ++ if filename.is_some() { ++ // A free file may still contain a deleted journal. Clear its ++ // old payload before publishing the new association. ++ sah.truncate_with_u32(HEADER_OFFSET_DATA as u32) ++ .map_err(OpfsSAHError::Truncate)?; ++ } ++ let written = sah ++ .write_with_js_u8_array_and_options(&self.header_buffer, &read_write_options(0.0)) ++ .map_err(OpfsSAHError::Write)?; ++ if written != HEADER_CORPUS_SIZE as f64 { ++ return Err(OpfsSAHError::Generic( ++ "Incomplete file association write".into(), ++ )); ++ } ++ // Deleting a journal commits its transaction. Preserve the payload ++ // until this metadata change is durable, and propagate flush errors. ++ sah.flush().map_err(OpfsSAHError::Flush)?; ++ Ok(()) ++ })(); ++ if result.is_err() { ++ self.poisoned.set(true); ++ } ++ result + } + + async fn acquire_access_handles(&self, clear_files: bool) -> Result<()> { ++ self.ensure_usable()?; ++ // Stage newly acquired handles locally so every failure closes them, ++ // including a failed unpause of an already registered pool. ++ let mut available_files = Vec::new(); ++ let mut map_filename_to_file = HashMap::new(); + let iter = self.dh_opaque.entries(); +- while let Ok(future) = iter.next() { ++ loop { ++ let future = iter.next().map_err(OpfsSAHError::IterHandle)?; + let next: IteratorNext = JsFuture::from(future) + .await + .map_err(OpfsSAHError::IterHandle)? +@@ -324,45 +548,42 @@ + handle: sah, + opaque, + }; +- let clear_file = |file: SyncAccessFile| -> Result<()> { ++ let mut clear_file = |file: SyncAccessFile| -> Result<()> { + self.set_associated_filename(&file.handle, None, 0)?; +- self.available_files.borrow_mut().push(file); ++ available_files.push(file); + Ok(()) + }; + if clear_files { + clear_file(file)?; + } else if let Some(filename) = self.get_associated_filename(&file.handle)? { +- self.map_filename_to_file +- .borrow_mut() +- .insert(filename, file); ++ if map_filename_to_file.insert(filename, file).is_some() { ++ return Err(OpfsSAHError::Generic("Duplicate file association".into())); ++ } + } else { + clear_file(file)?; + } + } + } + ++ self.available_files.borrow_mut().extend(available_files); ++ self.map_filename_to_file ++ .borrow_mut() ++ .extend(map_filename_to_file); + Ok(()) + } + + fn release_access_handles(&self) { +- for file in std::mem::take(&mut *self.available_files.borrow_mut()) +- .into_iter() +- .chain(std::mem::take(&mut *self.map_filename_to_file.borrow_mut()).into_values()) +- { +- file.handle.close(); +- } ++ self.available_files.borrow_mut().clear(); ++ self.map_filename_to_file.borrow_mut().clear(); + } + + fn delete_file(&self, filename: &str) -> Result { ++ self.ensure_usable()?; + let mut map_filename_to_file = self.map_filename_to_file.borrow_mut(); +- let mut available_files = self.available_files.borrow_mut(); +- +- if let Some(file) = map_filename_to_file.remove(filename) { +- available_files.push(file); +- let Some(file) = available_files.last() else { +- unreachable!(); +- }; ++ if let Some(file) = map_filename_to_file.get(filename) { + self.set_associated_filename(&file.handle, None, 0)?; ++ let file = map_filename_to_file.remove(filename).unwrap(); ++ self.available_files.borrow_mut().push(file); + Ok(true) + } else { + Ok(false) +@@ -398,6 +619,7 @@ + flags: i32, + f: F, + ) -> Result> { ++ self.ensure_usable()?; + let mut map_filename_to_file = self.map_filename_to_file.borrow_mut(); + let mut available_files = self.available_files.borrow_mut(); + if map_filename_to_file.contains_key(filename) { +@@ -408,13 +630,10 @@ + let file = available_files + .pop() + .ok_or_else(|| OpfsSAHError::Generic("No files available in the pool".into()))?; ++ self.set_associated_filename(&file.handle, Some(filename), flags)?; ++ let result = f(&file); + map_filename_to_file.insert(filename.into(), file); +- +- let Some(file) = map_filename_to_file.get(filename) else { +- unreachable!(); +- }; +- self.set_associated_filename(&file.handle, Some(filename), flags)?; +- Ok(f(file)) ++ Ok(result) + } + + fn pause_vfs(&self) -> Result<()> { +@@ -442,11 +661,10 @@ + } + + async fn unpause_vfs(&self) -> Result<()> { ++ self.ensure_usable()?; + if !self.is_paused.get() { + return Ok(()); + } +- +- self.acquire_access_handles(false).await?; + + let (vfs, make_default) = self.vfs.get(); + if vfs.is_null() { +@@ -455,18 +673,24 @@ + )); + } + ++ self.acquire_access_handles(false).await?; ++ + match unsafe { sqlite3_vfs_register(vfs, i32::from(make_default)) } { + SQLITE_OK => { + self.is_paused.set(false); + Ok(()) + } +- error_code => Err(OpfsSAHError::Generic(format!( +- "Failed to register VFS (SQLite error code: {error_code})" +- ))), ++ error_code => { ++ self.release_access_handles(); ++ Err(OpfsSAHError::Generic(format!( ++ "Failed to register VFS (SQLite error code: {error_code})" ++ ))) ++ } + } + } + + fn export_db(&self, filename: &str) -> Result> { ++ self.ensure_usable()?; + let files = self.map_filename_to_file.borrow(); + let file = files + .get(filename) +@@ -603,6 +827,8 @@ + + fn contains_file(vfs: *mut sqlite3_vfs, file: &str) -> VfsResult { + let pool = unsafe { Self::app_data(vfs) }; ++ pool.ensure_usable() ++ .map_err(|err| err.vfs_err(SQLITE_IOERR))?; + Ok(pool.has_filename(file)) + } + +@@ -619,6 +845,8 @@ + ) -> VfsResult { + let name = unsafe { vfs_file.name() }; + let pool = unsafe { Self::app_data(vfs_file.vfs) }; ++ pool.ensure_usable() ++ .map_err(|err| err.vfs_err(SQLITE_IOERR))?; + pool.with_file(name, f) + .ok_or_else(|| VfsError::new(SQLITE_IOERR, format!("{name} not found")))? + } +@@ -629,6 +857,8 @@ + ) -> VfsResult { + let name = unsafe { vfs_file.name() }; + let pool = unsafe { Self::app_data(vfs_file.vfs) }; ++ pool.ensure_usable() ++ .map_err(|err| err.vfs_err(SQLITE_IOERR))?; + pool.with_file_mut(name, f) + .ok_or_else(|| VfsError::new(SQLITE_IOERR, format!("{name} not found")))? + } +@@ -648,11 +878,66 @@ + } + + unsafe extern "C" fn xCheckReservedLock( +- _pFile: *mut sqlite3_file, ++ pFile: *mut sqlite3_file, + pResOut: *mut ::std::os::raw::c_int, + ) -> ::std::os::raw::c_int { +- *pResOut = 1; +- SQLITE_OK ++ let vfs_file = SQLiteVfsFile::from_file(pFile); ++ let pool = SyncAccessHandleStore::app_data(vfs_file.vfs); ++ if let Err(error) = pool.ensure_usable() { ++ return pool.store_err(error.vfs_err(SQLITE_IOERR)); ++ } ++ match pool.open_files.borrow().reserved(pFile as usize) { ++ Some(reserved) => { ++ *pResOut = i32::from(reserved); ++ SQLITE_OK ++ } ++ None => SQLITE_IOERR, ++ } ++ } ++ ++ unsafe extern "C" fn xLock( ++ pFile: *mut sqlite3_file, ++ eLock: ::std::os::raw::c_int, ++ ) -> ::std::os::raw::c_int { ++ let requested = match eLock { ++ SQLITE_LOCK_SHARED => Lock::Shared, ++ SQLITE_LOCK_RESERVED => Lock::Reserved, ++ SQLITE_LOCK_PENDING => Lock::Pending, ++ SQLITE_LOCK_EXCLUSIVE => Lock::Exclusive, ++ _ => return SQLITE_IOERR, ++ }; ++ let vfs_file = SQLiteVfsFile::from_file(pFile); ++ let pool = SyncAccessHandleStore::app_data(vfs_file.vfs); ++ if let Err(error) = pool.ensure_usable() { ++ return pool.store_err(error.vfs_err(SQLITE_IOERR)); ++ } ++ if pool.open_files.borrow_mut().lock(pFile as usize, requested) { ++ SQLITE_OK ++ } else { ++ SQLITE_BUSY ++ } ++ } ++ ++ unsafe extern "C" fn xUnlock( ++ pFile: *mut sqlite3_file, ++ eLock: ::std::os::raw::c_int, ++ ) -> ::std::os::raw::c_int { ++ let requested = match eLock { ++ SQLITE_LOCK_NONE => Lock::None, ++ SQLITE_LOCK_SHARED => Lock::Shared, ++ _ => return SQLITE_IOERR, ++ }; ++ let vfs_file = SQLiteVfsFile::from_file(pFile); ++ let pool = SyncAccessHandleStore::app_data(vfs_file.vfs); ++ if pool ++ .open_files ++ .borrow_mut() ++ .unlock(pFile as usize, requested) ++ { ++ SQLITE_OK ++ } else { ++ SQLITE_IOERR ++ } + } + + unsafe extern "C" fn xDeviceCharacteristics( +@@ -663,14 +948,18 @@ + + unsafe extern "C" fn xClose(pFile: *mut sqlite3_file) -> ::std::os::raw::c_int { + let vfs_file = SQLiteVfsFile::from_file(pFile); +- // The VFS file handle will be dropped, so we must clone the filename to use it after the drop. +- let file = vfs_file.name().to_string(); + let app_data = SyncAccessHandleStore::app_data(vfs_file.vfs); +- let ret = Self::xCloseImpl(pFile); +- if ret == SQLITE_OK { +- let exist = app_data.open_files.borrow_mut().remove(&file); +- debug_assert!(exist, "DB closed without open"); +- } ++ let ret = if vfs_file.flags & SQLITE_OPEN_DELETEONCLOSE != 0 { ++ match SyncAccessHandleStore::delete_file(vfs_file.vfs, vfs_file.name()) { ++ Ok(()) => SQLITE_OK, ++ Err(error) => app_data.store_err(error), ++ } ++ } else { ++ SQLITE_OK ++ }; ++ // SQLite releases pFile even when xClose reports an error. ++ app_data.open_files.borrow_mut().close(pFile as usize); ++ drop(Box::from_raw(vfs_file.name())); + ret + } + } +@@ -691,6 +980,10 @@ + flags: ::std::os::raw::c_int, + pOutFlags: *mut ::std::os::raw::c_int, + ) -> ::std::os::raw::c_int { ++ let app_data = SyncAccessHandleStore::app_data(pVfs); ++ if let Err(error) = app_data.ensure_usable() { ++ return app_data.store_err(error.vfs_err(SQLITE_CANTOPEN)); ++ } + let ret = Self::xOpenImpl(pVfs, zName, pFile, flags, pOutFlags); + if ret == SQLITE_OK { + let app_data = SyncAccessHandleStore::app_data(pVfs); +@@ -700,7 +993,7 @@ + app_data + .open_files + .borrow_mut() +- .insert(vfs_file.name().into()); ++ .open(pFile as usize, vfs_file.name()); + } + ret + } +@@ -841,6 +1134,11 @@ + } + + impl OpfsSAHPoolUtil { ++ /// Reports whether metadata I/O failed and the owning Worker must restart. ++ pub fn is_poisoned(&self) -> bool { ++ self.pool.poisoned.get() ++ } ++ + /// Returns the number of files currently contained in the SAH pool. + pub fn get_capacity(&self) -> u32 { + self.pool.get_capacity() +@@ -894,6 +1192,7 @@ + + /// Delete all database, make sure that all database is closed. + pub async fn clear_all(&self) -> Result<()> { ++ self.pool.ensure_usable()?; + self.pool.release_access_handles(); + self.pool.acquire_access_handles(true).await?; + Ok(()) +@@ -901,6 +1200,7 @@ + + /// Does the database exists. + pub fn exists(&self, filename: &str) -> Result { ++ self.pool.ensure_usable()?; + Ok(self.pool.has_filename(filename)) + } + +@@ -971,6 +1271,7 @@ + }; + + let pool = unsafe { SyncAccessHandleStore::app_data(vfs) }; ++ pool.ensure_usable()?; + pool.vfs.set((vfs, default_vfs)); + + Ok(OpfsSAHPoolUtil { pool }) From c19cde7877e7398e1f0e9642a73b62d284312d1b Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Thu, 10 Sep 2026 01:28:49 +0800 Subject: [PATCH 03/97] feat: pczt combine, spending-purpose ufvk import, transparent account key export - pcztCombine merges a hardware-signed redacted PCZT into the local copy - importAccountUfvk takes seed fingerprint + account index and imports as AccountPurpose::Spending so change outputs carry zip32 derivation - keys crate exports transparentAccountPubKeyFromUfvk for hardware accounts --- chain-runtimes/zcash/Cargo.lock | 1 + .../crates/zcash-keys-runtime/src/bindgen.rs | 6 +++ .../crates/zcash-keys-runtime/src/keys.rs | 25 +++++++++++++ .../zcash/crates/zcash-runtime/Cargo.toml | 1 + .../zcash/crates/zcash-runtime/src/account.rs | 37 ++++++++++++++++++- .../zcash/crates/zcash-runtime/src/bindgen.rs | 27 ++++++++++++-- .../zcash/crates/zcash-runtime/src/send.rs | 25 +++++++++++++ .../crates/zcash-runtime/tests/scan_repro.rs | 12 +++--- 8 files changed, 123 insertions(+), 11 deletions(-) diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock index c6b3958a0..73543bb5d 100644 --- a/chain-runtimes/zcash/Cargo.lock +++ b/chain-runtimes/zcash/Cargo.lock @@ -1724,6 +1724,7 @@ dependencies = [ "zcash_primitives", "zcash_protocol", "zcash_transparent", + "zip32", "zip321", ] diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs index fc1d3b2c3..d9a1a41f6 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs @@ -99,6 +99,12 @@ pub fn transparent_address_from_ufvk(network: &str, ufvk: &str) -> Result Result { + Ok(keys::transparent_account_pubkey(network, ufvk)?) +} + /// 种子指纹(ZIP-32 标准值)。宿主拿它当账户身份持久化, /// 所以必须与标准一致 —— 不能另发明一套哈希。 #[wasm_bindgen(js_name = seedFingerprint)] diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs index a16d21c11..a0596c749 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs @@ -138,6 +138,22 @@ pub fn transparent_address(network: &str, ufvk_str: &str) -> Result { /// /// **这是标准值,不是随便一个标识符** —— 宿主把它持久化下来当账户身份用, /// 所以必须与 ZIP-32 的定义一致。自己另发明一套哈希会让存量账户全部失配。 +/// UFVK 里的透明账户公钥,BIP32 账户层(m/44'/133'/account'): +/// 32 字节 chain code || 33 字节压缩公钥,hex。宿主据此拼 xpub, +/// 硬件账户无需再向设备额外要一次透明 xpub。 +pub fn transparent_account_pubkey(network: &str, ufvk_str: &str) -> Result { + let params = parse_network(network)?; + let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str) + .map_err(|e| KeysError::new(ErrorCode::InvalidUfvk).detail(e))?; + let account_pubkey = ufvk.transparent().ok_or_else(|| { + KeysError::with( + ErrorCode::DeriveFailed, + json!({ "reason": "noTransparentFvk" }), + ) + })?; + Ok(hex::encode(account_pubkey.serialize())) +} + pub fn seed_fingerprint(seed: &[u8]) -> Result { if seed.len() < 32 { return Err(KeysError::with( @@ -182,6 +198,15 @@ mod tests { const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + #[test] + fn transparent_account_pubkey_is_chain_code_and_compressed_key() { + let ufvk = ufvk_from_mnemonic("main", TEST_MNEMONIC, 0).unwrap(); + let hex_key = transparent_account_pubkey("main", &ufvk).unwrap(); + assert_eq!(hex_key.len(), 65 * 2); + let tag = &hex_key[64..66]; + assert!(tag == "02" || tag == "03", "压缩公钥前缀应为 02/03,实际 {tag}"); + } + #[test] fn network_parsing() { assert!(parse_network("main").is_ok()); diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml index b0fbd120d..5cb7eb822 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml @@ -18,6 +18,7 @@ zcash_primitives.workspace = true transparent.workspace = true zcash_address.workspace = true zip321.workspace = true +zip32 = "0.2" pczt.workspace = true # circuit: Orchard and Ironwood proving. This is the main WASM size cost. orchard = { workspace = true, features = ["circuit"] } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs index 5ed459691..410907333 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs @@ -4,7 +4,7 @@ use zcash_client_backend::data_api::wallet::ConfirmationsPolicy; use zcash_client_backend::data_api::{ - Account as _, AccountBirthday, AccountPurpose, WalletRead, WalletWrite, + Account as _, AccountBirthday, AccountPurpose, WalletRead, WalletWrite, Zip32Derivation, }; use zcash_keys::keys::UnifiedFullViewingKey; use zcash_protocol::consensus::BlockHeight; @@ -26,12 +26,22 @@ pub async fn import_ufvk( account_name: &str, ufvk_str: &str, birthday_height: u32, + derivation: Option<(&str, u32)>, ) -> Result { let params = *db.params(); let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str) .map_err(|e| RuntimeError::new(ErrorCode::InvalidUfvk).detail(e))?; + // 宿主知道种子指纹 + 账户序号时,账户按「可花费」导入:PCZT 里的 change 输出 + // 会带上 zip32_derivation,签名器(软件/硬件)据此确认找零回到自己。 + let purpose = match derivation { + Some((fingerprint_hex, account_index)) => AccountPurpose::Spending { + derivation: Some(parse_zip32_derivation(fingerprint_hex, account_index)?), + }, + None => AccountPurpose::ViewOnly, + }; + // treestate 取的是 birthday 的前一个区块:账户从 birthday 起开始观察, // 所以需要「birthday 之前」的树状态作为锚点。 let anchor_height = birthday_height.saturating_sub(1); @@ -50,7 +60,7 @@ pub async fn import_ufvk( account_name, &ufvk, &birthday, - AccountPurpose::ViewOnly, + purpose, None, ) .map_err(|e| { @@ -64,6 +74,29 @@ pub async fn import_ufvk( Ok(account.id().expose_uuid().to_string()) } +fn parse_zip32_derivation(fingerprint_hex: &str, account_index: u32) -> Result { + let bytes = hex::decode(fingerprint_hex).map_err(|e| { + RuntimeError::with(ErrorCode::InvalidAccountId, json!({ "field": "seedFingerprint" })) + .detail(e) + })?; + let fingerprint: [u8; 32] = bytes.try_into().map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidAccountId, + json!({ "field": "seedFingerprint", "expectedBytes": 32 }), + ) + })?; + let account_id = zip32::AccountId::try_from(account_index).map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidAccountId, + json!({ "field": "accountIndex", "value": account_index }), + ) + })?; + Ok(Zip32Derivation::new( + zip32::fingerprint::SeedFingerprint::from_bytes(fingerprint), + account_id, + )) +} + /// 账户余额,JSON。`minConfirmations` 为 0 时把未确认也算进来。 pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) -> Result { let account_id = parse_account_id(db, account_uuid)?; diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs index 981c7edcf..23e07b5c6 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs @@ -204,12 +204,23 @@ pub async fn import_account_ufvk( account_name: String, ufvk: String, birthday_height: u32, + seed_fingerprint_hex: Option, + account_index: Option, ) -> Result { Ok( runtime::with_db_and_client(move |mut db, mut client| async move { - let r = - account::import_ufvk(&mut db, &mut client, &account_name, &ufvk, birthday_height) - .await; + let derivation = seed_fingerprint_hex + .as_deref() + .zip(account_index); + let r = account::import_ufvk( + &mut db, + &mut client, + &account_name, + &ufvk, + birthday_height, + derivation, + ) + .await; (db, client, r) }) .await?, @@ -581,6 +592,16 @@ pub fn pczt_prove(pczt_bytes: Vec) -> Result, JsValue> { Ok(runtime::with_db(|db| send::prove_pczt(db, &pczt_bytes))?) } +/// 把外部签名器(硬件)返回的脱敏 PCZT 合并回本地的完整 PCZT。 +/// +/// 硬件只回传签名等公开字段,私有字段(rseed、witness 等)以 None 回来; +/// Combiner 逐字段取「有值」的一方,所以本地副本 + 签名副本 = 可证明可提取的 PCZT。 +/// 不需要钱包数据库。 +#[wasm_bindgen(js_name = pcztCombine)] +pub fn pczt_combine(original: Vec, signed: Vec) -> Result, JsValue> { + Ok(send::combine_pczt(&original, &signed)?) +} + /// 构造「屏蔽全部透明余额」的 PCZT,返回 `{ pcztHex, reservationId }`。 /// /// 没有收款地址、没有金额:收款方是本账户自己的屏蔽地址,金额是全部透明余额。 diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs index 4ff447048..9b8d75d89 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs @@ -690,6 +690,31 @@ fn circuit_version_for( } /// 给 PCZT 生成 Orchard / Ironwood 零知识证明。 +/// 合并两份同一笔交易的 PCZT(本地完整副本 + 外部签名器返回的脱敏副本)。 +pub fn combine_pczt(original: &[u8], signed: &[u8]) -> Result> { + let parse = |bytes: &[u8], which: &str| { + pczt::Pczt::parse(bytes).map_err(|error| { + RuntimeError::with( + ErrorCode::PcztError, + json!({ "stage": "parse", "which": which }), + ) + .detail(format!("{error:?}")) + }) + }; + let original = parse(original, "original")?; + let signed = parse(signed, "signed")?; + let combined = pczt::roles::combiner::Combiner::new(vec![original, signed]) + .combine() + .map_err(|error| { + RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "combine" })) + .detail(format!("{error:?}")) + })?; + combined.serialize().map_err(|error| { + RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "serialize" })) + .detail(format!("{error:?}")) + }) +} + pub fn prove_pczt(db: &Db, pczt_bytes: &[u8]) -> Result> { let params = *db.params(); let chain_tip = db diff --git a/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs b/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs index 0dbbebdc7..e0dcb2bde 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs @@ -32,7 +32,7 @@ async fn scan_with_batch(batch_size: u32) { let tip = network::chain_tip(&mut client).await.expect("应能取链尖"); println!("链尖 = {tip}"); - let uuid = account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 200) + let uuid = account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 200, None) .await .expect("导入账户应成功"); println!("账户 = {uuid}"); @@ -109,7 +109,7 @@ async fn scan_from_height() { let tip = network::chain_tip(&mut client).await.expect("应能取链尖"); println!("链尖 = {tip},从 {from} 起扫 {batch} 块"); - account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, from) + account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, from, None) .await .expect("导入账户应成功"); sync::prepare(&mut db, &mut client) @@ -147,7 +147,7 @@ async fn scan_batch_curve() { .expect("应能连上 lightwalletd"); let tip = network::chain_tip(&mut client).await.expect("应能取链尖"); - account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 2000) + account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 2000, None) .await .expect("导入账户应成功"); sync::prepare(&mut db, &mut client) @@ -186,7 +186,7 @@ async fn scan_one_by_one() { let tip = network::chain_tip(&mut client).await.expect("应能取链尖"); println!("链尖 = {tip}"); - account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 200) + account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 200, None) .await .expect("导入账户应成功"); sync::prepare(&mut db, &mut client) @@ -245,7 +245,7 @@ async fn uuid_binding_string_vs_blob() { let mut db = wallet::open_and_migrate("test", db_name).expect("开库应成功"); let mut client = network::connect_native(LWD).await.expect("应能连上"); let tip = network::chain_tip(&mut client).await.expect("取链尖"); - let uuid_str = account::import_ufvk(&mut db, &mut client, "a", ALICE_UFVK, tip - 10) + let uuid_str = account::import_ufvk(&mut db, &mut client, "a", ALICE_UFVK, tip - 10, None) .await .expect("导入账户"); println!("listAccounts 给出的形式: {uuid_str}"); @@ -291,7 +291,7 @@ async fn history_uuid_actually_matches() { let mut db = wallet::open_and_migrate("test", db_name).expect("开库"); let mut client = network::connect_native(LWD).await.expect("连上"); let tip = network::chain_tip(&mut client).await.expect("链尖"); - let uuid = account::import_ufvk(&mut db, &mut client, "a", ALICE_UFVK, tip - 10) + let uuid = account::import_ufvk(&mut db, &mut client, "a", ALICE_UFVK, tip - 10, None) .await .expect("导入"); drop(db); From da22f21cf1ec234d242f6e9324bbe949b8a3b563 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Fri, 11 Sep 2026 16:31:39 +0800 Subject: [PATCH 04/97] chore: wip snapshot of zcash runtime transparent shielding --- chain-runtimes/zcash/Cargo.lock | 2 + chain-runtimes/zcash/README.md | 26 + .../crates/zcash-keys-runtime/Cargo.toml | 4 +- .../crates/zcash-keys-runtime/src/bindgen.rs | 63 ++ .../src/transparent_send.rs | 104 +++- .../src/transparent_send/shielding.rs | 575 ++++++++++++++++++ .../zcash/crates/zcash-runtime/src/bindgen.rs | 33 +- .../zcash/crates/zcash-runtime/src/network.rs | 9 + .../zcash/crates/zcash-runtime/src/send.rs | 11 +- 9 files changed, 811 insertions(+), 16 deletions(-) create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock index 73543bb5d..805679815 100644 --- a/chain-runtimes/zcash/Cargo.lock +++ b/chain-runtimes/zcash/Cargo.lock @@ -1665,6 +1665,7 @@ dependencies = [ "js-sys", "orchard", "pczt", + "rand", "sapling-crypto", "secp256k1", "serde", @@ -1673,6 +1674,7 @@ dependencies = [ "wasm-bindgen", "zcash_address", "zcash_keys", + "zcash_note_encryption", "zcash_primitives", "zcash_protocol", "zcash_script", diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md index 9541db445..51c520cd7 100644 --- a/chain-runtimes/zcash/README.md +++ b/chain-runtimes/zcash/README.md @@ -289,3 +289,29 @@ scripts/build-wasm.sh 构建 - `zcash/zcash-android-wallet-sdk` 的 `backend-lib/` —— ECC 自己写的 Rust FFI 层, 生产在跑。核心 `lib.rs` 4,076 行是「该暴露什么、按什么粒度」的权威参照 (其余约 18,000 行是该 SDK 自己的历史 migration、投票、slipstream,我们不需要)。 + + +### Stateless transparent funding of Unified recipients + +`transparentTxQuote` accepts mainnet t1/t3 recipients and Unified recipients with an +Orchard receiver (an Ironwood output after NU6.3). It uses only the host-supplied +confirmed, regular transparent UTXOs, explicit outpoints, target height, and +transparent change address. Sapling/Sprout destinations and coinbase inputs remain +unsupported. No wallet registration, database, scan, or network call is required. + +Software keyrings use this sequence for Unified recipients: + +1. `keys.transparentShieldCreateWithSeed` (or `WithAccountXprv`) constructs a PCZT + from the same validated request used for the quote. +2. `runtime.pcztProveAtHeight` proves it without calling `init` or opening a wallet. +3. `keys.transparentShieldSignWithSeed` (or `WithAccountXprv`) checks the original + request, all effects of the original PCZT, and the proved PCZT before signing. +4. `runtime.pcztExtractStateless` verifies and extracts the final transaction. + +The host owns transparent outpoint reservations, signature-time UTXO revalidation, +pending broadcast records, and submission to its node. The recipient's wallet +scans to discover and later spend the received shielded notes; the sender does not +need to scan. Private inputs still use the existing stateful wallet/PCZT APIs. + +The app's existing hardware Shield flow is separate; these new signing exports +are for software seed/account-xprv keyrings. diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml index fc4d692b0..9c4d0c8e7 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml @@ -23,6 +23,8 @@ zip32 = "0.2" bip0039 = { version = "0.12", features = ["all-languages"] } bs58 = { version = "0.5", features = ["check"] } zeroize = { version = "1", features = ["zeroize_derive"] } +zcash_note_encryption = "0.4" +rand.workspace = true serde.workspace = true serde_json.workspace = true hex.workspace = true @@ -32,7 +34,7 @@ zcash_script = { version = "0.4.3", default-features = false } # 不开 prover/tx-extractor —— 那些属于 runtime 包。 # transparent:屏蔽(transparent → shielded)必须签透明输入,否则打进 t 地址的钱 # 出不来。它会连带拉入 zcash_script(0.4 起是纯 Rust,能上 wasm32)。 -pczt = { workspace = true, features = ["signer", "orchard", "transparent"] } +pczt = { workspace = true, features = ["signer", "orchard", "transparent", "zcp-builder", "spend-finalizer", "io-finalizer"] } transparent = { workspace = true, features = ["transparent-inputs"] } orchard = { version = "0.15", default-features = false } sapling.workspace = true diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs index d9a1a41f6..fb127c218 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs @@ -160,6 +160,12 @@ pub fn keys_capabilities() -> String { "buildWithSeed": true, "buildWithAccountXprv": true, }, + "transparentShield": { + "createWithSeed": transparent_send::shielding::SHIELD_CREATE_WITH_SEED, + "createWithAccountXprv": transparent_send::shielding::SHIELD_CREATE_WITH_ACCOUNT_XPRV, + "signWithSeed": transparent_send::shielding::SHIELD_SIGN_WITH_SEED, + "signWithAccountXprv": transparent_send::shielding::SHIELD_SIGN_WITH_ACCOUNT_XPRV, + }, }) .to_string() } @@ -169,3 +175,60 @@ pub fn keys_capabilities() -> String { pub fn dependency_versions() -> String { crate::dependency_versions().to_string() } + +/// Creates a shielding PCZT using only host-supplied transparent inputs. +#[wasm_bindgen(js_name = transparentShieldCreateWithSeed)] +pub fn transparent_shield_create_with_seed( + request_json: &str, + seed: Vec, +) -> Result, JsValue> { + let seed = Zeroizing::new(seed); + Ok(transparent_send::shielding::create(request_json, &seed)?) +} + +/// Signs the locally created, proved shielding PCZT. +#[wasm_bindgen(js_name = transparentShieldSignWithSeed)] +pub fn transparent_shield_sign_with_seed( + request_json: &str, + seed: Vec, + original: Vec, + pczt: Vec, +) -> Result, JsValue> { + let seed = Zeroizing::new(seed); + Ok(transparent_send::shielding::sign( + request_json, + &seed, + &original, + &pczt, + )?) +} + +/// Creates a shielding PCZT with an account-level transparent key. +#[wasm_bindgen(js_name = transparentShieldCreateWithAccountXprv)] +pub fn transparent_shield_create_with_account_xprv( + request_json: &str, + account_xprv: String, +) -> Result, JsValue> { + let account_xprv = Zeroizing::new(account_xprv); + Ok(transparent_send::shielding::create_with_account_xprv( + request_json, + &account_xprv, + )?) +} + +/// Signs a proved shielding PCZT with an account-level transparent key. +#[wasm_bindgen(js_name = transparentShieldSignWithAccountXprv)] +pub fn transparent_shield_sign_with_account_xprv( + request_json: &str, + account_xprv: String, + original: Vec, + pczt: Vec, +) -> Result, JsValue> { + let account_xprv = Zeroizing::new(account_xprv); + Ok(transparent_send::shielding::sign_with_account_xprv( + request_json, + &account_xprv, + &original, + &pczt, + )?) +} diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs index d635816ae..f245a3145 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs @@ -16,6 +16,7 @@ use transparent::{ keys::{AccountPrivKey, NonHardenedChildIndex, TransparentKeyScope}, }; use zcash_address::ZcashAddress; +use zcash_keys::address::Address; use zcash_primitives::transaction::{ fees::{ transparent::{InputSize, OutputView}, @@ -125,9 +126,15 @@ struct PlannedInput { path: DerivationPath, } +#[derive(Clone, Copy, Debug)] +enum RecipientAddress { + Transparent(TransparentAddress), + Ironwood(orchard::Address), +} + #[derive(Debug)] struct PlannedOutput { - address: TransparentAddress, + address: RecipientAddress, value: Zatoshis, } @@ -135,6 +142,7 @@ struct PlannedOutput { struct TransactionPlan { account_index: AccountId, expiry_height: BlockHeight, + target_height: BlockHeight, inputs: Vec, recipients: Vec, change: Option<(TransparentChange, PlannedOutput, DerivationPath)>, @@ -300,7 +308,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { .recipients .into_iter() .map(|recipient| { - let address = parse_transparent_address(&recipient.address, "recipient")?; + let address = parse_recipient_address(&recipient.address)?; if request.send_max { if recipient.amount_zat.is_some() { return Err(KeysError::with( @@ -332,6 +340,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { return Ok(TransactionPlan { account_index, expiry_height, + target_height, inputs, recipients: vec![PlannedOutput { address, @@ -394,7 +403,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { )); } let mut addresses_with_change = recipient_addresses; - addresses_with_change.push(change_address); + addresses_with_change.push(RecipientAddress::Transparent(change_address)); let fee = calculate_fee(target_height, inputs.len(), &addresses_with_change)?; let needed = send_total_raw .checked_add(fee.into_u64()) @@ -417,7 +426,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { Some(( change_request, PlannedOutput { - address: change_address, + address: RecipientAddress::Transparent(change_address), value: change_value, }, change_path, @@ -428,6 +437,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { Ok(TransactionPlan { account_index, expiry_height, + target_height, inputs, recipients, change, @@ -557,14 +567,14 @@ fn build_transaction( for output in &plan.recipients { builder - .add_output(&output.address, output.value) + .add_output(&require_transparent(output.address)?, output.value) .map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e))?; } if let Some((change_request, output, path)) = &plan.change { let secret_key = derive_secret_key(account_key, *path)?; let pubkey = signing_set.add_key(secret_key); let derived_address = TransparentAddress::from_pubkey(&pubkey); - if derived_address != output.address { + if derived_address != require_transparent(output.address)? { return Err(KeysError::with( ErrorCode::KeyMismatch, serde_json::json!({ "field": "change.address" }), @@ -580,7 +590,7 @@ fn build_transaction( )); } builder - .add_output(&output.address, output.value) + .add_output(&require_transparent(output.address)?, output.value) .map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e))?; } @@ -641,11 +651,23 @@ fn build_transaction( fn calculate_fee( target_height: BlockHeight, input_count: usize, - output_addresses: &[TransparentAddress], + output_addresses: &[RecipientAddress], ) -> Result { - let output_sizes = output_addresses + let output_sizes = output_addresses.iter().filter_map(|address| match address { + RecipientAddress::Transparent(address) => { + Some(TxOut::new(Zatoshis::ZERO, address.script().into()).serialized_size()) + } + RecipientAddress::Ironwood(_) => None, + }); + let ironwood_outputs = output_addresses .iter() - .map(|address| TxOut::new(Zatoshis::ZERO, address.script().into()).serialized_size()); + .filter(|a| matches!(a, RecipientAddress::Ironwood(_))) + .count(); + let ironwood_actions = if ironwood_outputs == 0 { + 0 + } else { + ironwood_outputs.max(2) + }; Zip317FeeRule::standard() .fee_required( &MAIN_NETWORK, @@ -655,7 +677,7 @@ fn calculate_fee( 0, 0, 0, - 0, + ironwood_actions, ) .map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e)) } @@ -904,6 +926,43 @@ mod tests { .to_string() } + fn shielding_request(send_max: bool) -> String { + let sk = orchard::keys::SpendingKey::from_bytes([7; 32]).unwrap(); + let fvk = orchard::keys::FullViewingKey::from(&sk); + let recipient = zcash_keys::address::UnifiedAddress::from_receivers( + Some(fvk.address_at(0u32, zip32::Scope::External)), + None, + None, + ) + .unwrap() + .encode(&MAIN_NETWORK); + let mut request: serde_json::Value = + serde_json::from_str(&request_json(&[100_000], send_max)).unwrap(); + request["recipients"][0]["address"] = recipient.into(); + request.to_string() + } + + #[test] + fn quotes_and_creates_shielding_without_a_wallet_or_scan() { + for send_max in [false, true] { + let request = shielding_request(send_max); + let quote: TransparentQuote = + serde_json::from_str("e_json(&request).unwrap()).unwrap(); + assert_eq!(quote.fee_zat, "15000"); + assert_eq!( + quote.send_amount_zat, + if send_max { "85000" } else { "50000" } + ); + let created = shielding::create(&request, &seed()).unwrap(); + let pczt = pczt::Pczt::parse(&created).unwrap(); + assert_eq!(pczt.transparent().inputs().len(), 1); + assert_eq!(pczt.transparent().outputs().len(), usize::from(!send_max)); + assert_eq!(pczt.ironwood().actions().len(), 2); + assert!(pczt.orchard().actions().is_empty()); + assert!(pczt.sapling().spends().is_empty()); + } + } + #[test] fn quotes_zip317_for_multiple_inputs() { let request = request_json(&[30_000, 30_000, 30_000], false); @@ -1032,3 +1091,26 @@ mod tests { ); } } + +fn require_transparent(address: RecipientAddress) -> Result { + match address { + RecipientAddress::Transparent(address) => Ok(address), + RecipientAddress::Ironwood(_) => Err(KeysError::new(ErrorCode::InvalidAddress)), + } +} + +fn parse_recipient_address(encoded: &str) -> Result { + match Address::decode(&MAIN_NETWORK, encoded) { + Some(Address::Transparent(address)) => Ok(RecipientAddress::Transparent(address)), + // Unified Orchard receivers receive Ironwood notes after NU6.3. Never silently + // fall back to a public receiver when a Unified Address lacks this receiver. + Some(Address::Unified(address)) => address + .orchard() + .copied() + .map(RecipientAddress::Ironwood) + .ok_or_else(|| KeysError::new(ErrorCode::InvalidAddress)), + _ => Err(KeysError::new(ErrorCode::InvalidAddress)), + } +} + +pub mod shielding; diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs new file mode 100644 index 000000000..48f557be5 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs @@ -0,0 +1,575 @@ +//! Stateless shielding from an explicit, host-owned transparent UTXO catalog. +use super::*; +use pczt::roles::{ + creator::Creator, + io_finalizer::IoFinalizer, + signer::Signer, + spend_finalizer::SpendFinalizer, + verifier::{OrchardError, TransparentError, Verifier}, +}; +use zcash_note_encryption::Domain; +use zcash_primitives::transaction::builder::{BuildConfig, Builder, BundlePadding}; +use zcash_protocol::memo::MemoBytes; + +/// 本模块实际提供的入口。定义在实现旁边,删改实现必然改到这里。 +/// +/// 宿主必须先查能力再调:这四个函数是后加的,装到旧 wasm 时缺的是导出本身, +/// 直接调只会得到 `undefined is not a function` —— 那看起来像 app 崩了, +/// 而不是一次「本版本不支持」。 +pub const SHIELD_CREATE_WITH_SEED: bool = true; +pub const SHIELD_CREATE_WITH_ACCOUNT_XPRV: bool = true; +pub const SHIELD_SIGN_WITH_SEED: bool = true; +pub const SHIELD_SIGN_WITH_ACCOUNT_XPRV: bool = true; + +fn failure(error: impl std::fmt::Debug) -> KeysError { + KeysError::new(ErrorCode::TransactionBuildFailed).detail(format!("{error:?}")) +} + +pub fn create(request_json: &str, seed: &[u8]) -> Result> { + if seed.len() < 32 { + return Err(KeysError::new(ErrorCode::InvalidSeed)); + } + let plan = plan_transaction(parse_request(request_json)?)?; + let key = + AccountPrivKey::from_seed(&MAIN_NETWORK, seed, plan.account_index).map_err(failure)?; + create_with_key(&plan, &key) +} + +pub fn create_with_account_xprv(request_json: &str, account_xprv: &str) -> Result> { + let plan = plan_transaction(parse_request(request_json)?)?; + let key = parse_account_xprv(account_xprv, u32::from(plan.account_index))?; + create_with_key(&plan, &key) +} + +fn create_with_key(plan: &TransactionPlan, key: &AccountPrivKey) -> Result> { + let mut builder = Builder::new( + MAIN_NETWORK, + plan.target_height, + BuildConfig::Standard { + sapling_anchor: None, + orchard_anchor: None, + // No shielded spends: the empty anchor needs no scanned commitment tree. + ironwood_anchor: Some(orchard::Anchor::empty_tree()), + orchard_padding: BundlePadding::DEFAULT, + ironwood_padding: BundlePadding::DEFAULT, + }, + ) + .with_expiry_height(plan.expiry_height); + for input in &plan.inputs { + let secret = derive_secret_key(&key, input.path)?; + let pubkey = secp256k1::PublicKey::from_secret_key(&secp256k1::Secp256k1::new(), &secret); + let address = TransparentAddress::from_pubkey(&pubkey); + if address.script().to_bytes() != input.script_pub_key { + return Err(KeysError::new(ErrorCode::KeyMismatch)); + } + builder + .add_transparent_p2pkh_input( + pubkey, + OutPoint::new(*input.txid.as_ref(), input.request.vout), + TxOut::new(input.value, address.script().into()), + ) + .map_err(failure)?; + } + for output in &plan.recipients { + match output.address { + RecipientAddress::Transparent(address) => builder + .add_transparent_output(&address, output.value) + .map_err(failure)?, + RecipientAddress::Ironwood(address) => builder + .add_ironwood_output::( + None, + address, + output.value, + MemoBytes::empty(), + ) + .map_err(failure)?, + } + } + if let Some((_, output, path)) = &plan.change { + let secret = derive_secret_key(&key, *path)?; + let pubkey = secp256k1::PublicKey::from_secret_key(&secp256k1::Secp256k1::new(), &secret); + let address = TransparentAddress::from_pubkey(&pubkey); + if address != require_transparent(output.address)? { + return Err(KeysError::new(ErrorCode::KeyMismatch)); + } + builder + .add_transparent_output(&address, output.value) + .map_err(failure)?; + } + let parts = builder + .build_for_pczt(rand::rngs::OsRng, &Zip317FeeRule::standard()) + .map_err(failure)?; + let pczt = Creator::build_from_parts(parts.pczt_parts) + .ok_or_else(|| KeysError::new(ErrorCode::TransactionBuildFailed))?; + IoFinalizer::new(pczt) + .finalize_io() + .map_err(failure)? + .serialize() + .map_err(failure) +} + +fn mismatch() -> KeysError { + KeysError::new(ErrorCode::KeyMismatch) +} + +fn validate_ironwood(bundle: &orchard::pczt::Bundle, plan: &TransactionPlan) -> Result<()> { + let mut expected = plan + .recipients + .iter() + .filter_map(|output| match output.address { + RecipientAddress::Ironwood(address) => Some((address, u64::from(output.value))), + RecipientAddress::Transparent(_) => None, + }) + .collect::>(); + let total = expected.iter().map(|(_, value)| value).sum::(); + let action_count = if expected.is_empty() { + 0 + } else { + expected.len().max(2) + }; + if bundle.actions().len() != action_count + || *bundle.bundle_version() != orchard::bundle::BundleVersion::ironwood_v3() + || *bundle.anchor() != orchard::Anchor::empty_tree() + || bundle.value_sum().magnitude_sign().0 != total + || (total != 0 + && !matches!( + bundle.value_sum().magnitude_sign().1, + orchard::value::Sign::Negative + )) + { + return Err(mismatch()); + } + bundle.verify_cross_address_restriction().map_err(failure)?; + for action in bundle.actions() { + let spend = action.spend(); + let output = action.output(); + if *spend.value() != Some(orchard::value::NoteValue::ZERO) + || spend.dummy_sk().is_some() + || spend.spend_auth_sig().is_none() + || *spend.note_version() != orchard::note::NoteVersion::V3 + || *output.note_version() != orchard::note::NoteVersion::V3 + { + return Err(mismatch()); + } + action.verify_cv_net().map_err(failure)?; + spend.verify_nullifier(None).map_err(failure)?; + spend.verify_rk(None).map_err(failure)?; + output.verify_note_commitment(spend).map_err(failure)?; + let recipient = output.recipient().ok_or_else(mismatch)?; + let value = output.value().ok_or_else(mismatch)?; + if value.inner() != 0 { + let index = expected + .iter() + .position(|entry| *entry == (recipient, value.inner())) + .ok_or_else(mismatch)?; + expected.remove(index); + } + // A matching commitment alone does not ensure the recipient can decrypt the note. + // Dummy output ciphertexts may be randomized by the upstream builder. + if value.inner() != 0 { + let note = orchard::Note::from_parts( + recipient, + value, + orchard::note::Rho::from_bytes(&spend.nullifier().to_bytes()) + .into_option() + .ok_or_else(mismatch)?, + output.rseed().ok_or_else(mismatch)?, + *output.note_version(), + ) + .into_option() + .ok_or_else(mismatch)?; + let encryptor = orchard::note_encryption::IronwoodNoteEncryption::new( + None, + note, + *MemoBytes::empty().as_array(), + ); + if encryptor.encrypt_note_plaintext() != output.encrypted_note().enc_ciphertext + || orchard::note_encryption::IronwoodDomain::epk_bytes(encryptor.epk()).0 + != output.encrypted_note().epk_bytes + { + return Err(mismatch()); + } + } + } + if !expected.is_empty() { + return Err(mismatch()); + } + Ok(()) +} + +fn validate_original( + plan: &TransactionPlan, + key: &AccountPrivKey, + pczt: pczt::Pczt, +) -> Result { + let global = pczt.global(); + if *global.tx_version() != zcash_protocol::constants::V6_TX_VERSION + || *global.version_group_id() != zcash_protocol::constants::V6_VERSION_GROUP_ID + || *global.consensus_branch_id() != u32::from(BranchId::Nu6_3) + || *global.expiry_height() != u32::from(plan.expiry_height) + || pczt::common::determine_lock_time(global, pczt.transparent().inputs()) != Some(0) + || !pczt.sapling().spends().is_empty() + || !pczt.sapling().outputs().is_empty() + || !pczt.orchard().actions().is_empty() + || *pczt.ironwood().anchor() != Some(orchard::Anchor::empty_tree().to_bytes()) + || pczt.transparent().inputs().len() != plan.inputs.len() + { + return Err(mismatch()); + } + for (input, planned) in pczt.transparent().inputs().iter().zip(&plan.inputs) { + let secret = derive_secret_key(key, planned.path)?; + let public = secp256k1::PublicKey::from_secret_key(&secp256k1::Secp256k1::new(), &secret); + if input.prevout_txid() != planned.txid.as_ref() + || *input.prevout_index() != planned.request.vout + || *input.value() != u64::from(planned.value) + || input.script_pubkey() != &planned.script_pub_key + || TransparentAddress::from_pubkey(&public).script().to_bytes() + != planned.script_pub_key + || input + .sequence() + .is_some_and(|sequence| sequence != u32::MAX) + { + return Err(mismatch()); + } + } + let mut outputs = plan + .recipients + .iter() + .filter_map(|output| match output.address { + RecipientAddress::Transparent(address) => Some((address, output.value)), + RecipientAddress::Ironwood(_) => None, + }) + .collect::>(); + if let Some((_, change, path)) = &plan.change { + let address = require_transparent(change.address)?; + let secret = derive_secret_key(key, *path)?; + let public = secp256k1::PublicKey::from_secret_key(&secp256k1::Secp256k1::new(), &secret); + if TransparentAddress::from_pubkey(&public) != address { + return Err(mismatch()); + } + outputs.push((address, change.value)); + } + if pczt.transparent().outputs().len() != outputs.len() { + return Err(mismatch()); + } + for (output, (address, value)) in pczt.transparent().outputs().iter().zip(outputs) { + if *output.value() != u64::from(value) + || *output.script_pubkey() != address.script().to_bytes() + { + return Err(mismatch()); + } + } + let verified = Verifier::new(pczt) + .with_transparent(|bundle| { + if bundle.inputs().iter().any(|input| { + *input.sighash_type() != transparent::sighash::SighashType::ALL + || input.redeem_script().is_some() + || input.script_sig().is_some() + || !input.partial_signatures().is_empty() + || input.required_time_lock_time().is_some() + || input.required_height_lock_time().is_some() + }) { + return Err(TransparentError::Custom(mismatch())); + } + Ok(()) + }) + .map_err(failure)? + .with_ironwood(|bundle| validate_ironwood(bundle, plan).map_err(OrchardError::Custom)) + .map_err(failure)?; + Ok(verified.finish()) +} + +pub fn sign(request_json: &str, seed: &[u8], original: &[u8], pczt: &[u8]) -> Result> { + if seed.len() < 32 { + return Err(KeysError::new(ErrorCode::InvalidSeed)); + } + let plan = plan_transaction(parse_request(request_json)?)?; + let key = + AccountPrivKey::from_seed(&MAIN_NETWORK, seed, plan.account_index).map_err(failure)?; + sign_with_key(&plan, &key, original, pczt) +} + +pub fn sign_with_account_xprv( + request_json: &str, + account_xprv: &str, + original: &[u8], + pczt: &[u8], +) -> Result> { + let plan = plan_transaction(parse_request(request_json)?)?; + let key = parse_account_xprv(account_xprv, u32::from(plan.account_index))?; + sign_with_key(&plan, &key, original, pczt) +} + +fn sign_with_key( + plan: &TransactionPlan, + key: &AccountPrivKey, + original: &[u8], + pczt: &[u8], +) -> Result> { + let original = validate_original(plan, key, pczt::Pczt::parse(original).map_err(failure)?)?; + let pczt = pczt::Pczt::parse(pczt).map_err(failure)?; + // V6 deliberately excludes anchors from the effects hash (ZIP 374). + if pczt.ironwood().anchor() != original.ironwood().anchor() + || pczt.transparent().inputs().len() != plan.inputs.len() + { + return Err(mismatch()); + } + let pczt = Verifier::new(pczt) + .with_transparent(|bundle| { + if bundle + .inputs() + .iter() + .any(|input| *input.sighash_type() != transparent::sighash::SighashType::ALL) + { + return Err(TransparentError::Custom(mismatch())); + } + Ok(()) + }) + .map_err(failure)? + .finish(); + let original_signer = Signer::new(original).map_err(failure)?; + let mut signer = Signer::new(pczt).map_err(failure)?; + // After request validation, SIGHASH_ALL pins the prover to the approved effects. + for index in 0..plan.inputs.len() { + if original_signer + .transparent_sighash(index) + .map_err(failure)? + != signer.transparent_sighash(index).map_err(failure)? + { + return Err(mismatch()); + } + } + for (index, input) in plan.inputs.iter().enumerate() { + signer + .sign_transparent(index, &derive_secret_key(key, input.path)?) + .map_err(failure)?; + } + SpendFinalizer::new(signer.finish()) + .finalize_spends() + .map_err(failure)? + .serialize() + .map_err(failure) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{json, Value}; + + const SEED: [u8; 64] = [7; 64]; + + fn transparent_address(scope: u32, index: u32) -> TransparentAddress { + let key = AccountPrivKey::from_seed(&MAIN_NETWORK, &SEED, AccountId::ZERO).unwrap(); + let secret = derive_secret_key( + &key, + DerivationPath { + account: 0, + scope, + index, + }, + ) + .unwrap(); + TransparentAddress::from_pubkey(&secp256k1::PublicKey::from_secret_key( + &secp256k1::Secp256k1::new(), + &secret, + )) + } + + fn recipient(index: u32) -> String { + let sk = orchard::keys::SpendingKey::from_bytes([7; 32]).unwrap(); + let fvk = orchard::keys::FullViewingKey::from(&sk); + zcash_keys::address::UnifiedAddress::from_receivers( + Some(fvk.address_at(index, zip32::Scope::External)), + None, + None, + ) + .unwrap() + .encode(&MAIN_NETWORK) + } + + fn request(send_max: bool) -> Value { + let txid = format!("{:064x}", 1); + json!({ + "network": "main", "accountIndex": 0, + "targetHeight": 3_500_000, "expiryHeight": 3_500_020, + "utxos": [{ "txid": txid, "vout": 0, "valueZat": "100000", + "scriptPubKey": hex::encode(transparent_address(0, 0).script().to_bytes()), + "isCoinbase": false, "confirmations": 1, "derivationPath": "m/44'/133'/0'/0/0" }], + "selectedOutpoints": [{ "txid": txid, "vout": 0 }], + "recipients": [{ "address": recipient(0), "amountZat": if send_max { Value::Null } else { "50000".into() } }], + "sendMax": send_max, + "change": if send_max { Value::Null } else { json!({ + "address": transparent_address(1, 0).to_zcash_address(NetworkType::Main).to_string(), + "derivationPath": "m/44'/133'/0'/1/0" }) }, + }) + } + + fn mutate(bytes: &[u8], change: impl FnOnce(&mut Value)) -> Vec { + let wire = pczt::v2::Pczt::try_from(pczt::Pczt::parse(bytes).unwrap()).unwrap(); + let mut value = serde_json::to_value(wire).unwrap(); + change(&mut value); + serde_json::from_value::(value) + .unwrap() + .serialize() + } + + #[test] + fn signs_fixed_and_max_shielding_with_matching_request() { + for send_max in [false, true] { + let request = request(send_max).to_string(); + let original = create(&request, &SEED).unwrap(); + // Proof generation is independent of the transparent signing authorization. + sign(&request, &SEED, &original, &original).unwrap(); + } + } + + #[test] + fn rejects_substitution_of_a_different_approved_request() { + let request = request(false); + let original = create(&request.to_string(), &SEED).unwrap(); + for field in ["recipient", "amount", "input", "value", "change", "expiry"] { + let mut changed = request.clone(); + match field { + "recipient" => changed["recipients"][0]["address"] = recipient(1).into(), + "amount" => changed["recipients"][0]["amountZat"] = "40000".into(), + "input" => { + changed["utxos"][0]["vout"] = 1.into(); + changed["selectedOutpoints"][0]["vout"] = 1.into(); + } + "value" => changed["utxos"][0]["valueZat"] = "110000".into(), + "change" => { + changed["change"]["address"] = transparent_address(1, 1) + .to_zcash_address(NetworkType::Main) + .to_string() + .into(); + changed["change"]["derivationPath"] = "m/44'/133'/0'/1/1".into(); + } + "expiry" => changed["expiryHeight"] = 3_500_021.into(), + _ => unreachable!(), + } + assert!( + sign(&changed.to_string(), &SEED, &original, &original).is_err(), + "{field}" + ); + } + } + + #[test] + fn rejects_modified_transparent_effects_and_sighash_policy() { + let request = request(false).to_string(); + let original = create(&request, &SEED).unwrap(); + for field in ["prevout_index", "value", "sighash_type", "sequence"] { + let modified = mutate(&original, |value| { + value["transparent"]["inputs"][0][field] = match field { + "value" => 110_000.into(), + "sighash_type" => 2.into(), + "sequence" => 1.into(), + _ => 1.into(), + }; + }); + assert!( + sign(&request, &SEED, &modified, &modified).is_err(), + "{field}" + ); + assert!( + sign(&request, &SEED, &original, &modified).is_err(), + "prover {field}" + ); + } + let modified = mutate(&original, |value| { + value["transparent"]["outputs"][0]["value"] = 1.into() + }); + assert!(sign(&request, &SEED, &modified, &modified).is_err()); + assert!(sign(&request, &SEED, &original, &modified).is_err()); + } + + #[test] + fn rejects_unreviewed_ironwood_actions_and_ciphertexts() { + let request = request(false).to_string(); + let original = create(&request, &SEED).unwrap(); + for field in [ + "anchor", + "value_sum", + "extra_action", + "real_spend", + "output_value", + "ciphertext", + "ephemeral_key", + ] { + let modified = mutate(&original, |value| { + let bundle = &mut value["ironwood"]; + match field { + "anchor" => bundle["anchor"] = json!([0; 32].to_vec()), + "value_sum" => bundle["value_sum"][0] = 1.into(), + "extra_action" => { + let action = bundle["actions"][0].clone(); + bundle["actions"].as_array_mut().unwrap().push(action); + } + "real_spend" => bundle["actions"][0]["spend"]["value"] = 1.into(), + _ => { + let output = &mut bundle["actions"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|action| action["output"]["value"].as_u64().unwrap() != 0) + .unwrap()["output"]; + match field { + "output_value" => output["value"] = 1.into(), + "ciphertext" => { + output["enc_ciphertext"] = json!({ "Encrypted": vec![0u8; 580] }) + } + "ephemeral_key" => output["ephemeral_key"] = json!([0; 32].to_vec()), + _ => unreachable!(), + } + } + } + }); + assert!( + sign(&request, &SEED, &modified, &modified).is_err(), + "{field}" + ); + if field != "real_spend" && field != "output_value" { + assert!( + sign(&request, &SEED, &original, &modified).is_err(), + "prover {field}" + ); + } + } + } + + #[test] + fn account_xprv_has_the_same_authorization_checks() { + let request = request(false).to_string(); + let key = AccountPrivKey::from_seed(&MAIN_NETWORK, &SEED, AccountId::ZERO).unwrap(); + let mut encoded = XPRV_VERSION.to_vec(); + encoded.extend_from_slice(&key.to_bytes()); + let xprv = bs58::encode(encoded).with_check().into_string(); + let original = create_with_account_xprv(&request, &xprv).unwrap(); + sign_with_account_xprv(&request, &xprv, &original, &original).unwrap(); + let mut changed: Value = serde_json::from_str(&request).unwrap(); + changed["recipients"][0]["address"] = recipient(1).into(); + assert!(sign_with_account_xprv(&changed.to_string(), &xprv, &original, &original).is_err()); + } + + #[test] + fn validates_every_output_in_a_mixed_recipient_transaction() { + let mut request = request(false); + request["recipients"] = json!([ + { "address": recipient(0), "amountZat": "10000" }, + { "address": recipient(0), "amountZat": "10000" }, + { "address": recipient(1), "amountZat": "10000" }, + { "address": transparent_address(0, 2).to_zcash_address(NetworkType::Main).to_string(), "amountZat": "10000" }, + ]); + let request = request.to_string(); + let original = create(&request, &SEED).unwrap(); + sign(&request, &SEED, &original, &original).unwrap(); + let modified = mutate(&original, |value| { + let output = value["transparent"]["outputs"][0].clone(); + value["transparent"]["outputs"] + .as_array_mut() + .unwrap() + .push(output); + }); + assert!(sign(&request, &SEED, &modified, &modified).is_err()); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs index 23e07b5c6..2f8eeaa2c 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs @@ -209,9 +209,7 @@ pub async fn import_account_ufvk( ) -> Result { Ok( runtime::with_db_and_client(move |mut db, mut client| async move { - let derivation = seed_fingerprint_hex - .as_deref() - .zip(account_index); + let derivation = seed_fingerprint_hex.as_deref().zip(account_index); let r = account::import_ufvk( &mut db, &mut client, @@ -905,3 +903,32 @@ pub fn self_check(network_name: &str, db_name: &str) -> Result }) .to_string()) } + +/// Proves a locally constructed PCZT without opening a wallet or initializing storage. +#[wasm_bindgen(js_name = pcztProveAtHeight)] +pub fn pczt_prove_at_height(target_height: u32, pczt_bytes: Vec) -> Result, JsValue> { + install_panic_hook(); + Ok(send::prove_pczt_at_height( + &zcash_protocol::consensus::Network::MainNetwork, + target_height.into(), + &pczt_bytes, + )?) +} + +/// Validates and extracts a signed PCZT without persisting wallet state. +#[wasm_bindgen(js_name = pcztExtractStateless)] +pub fn pczt_extract_stateless(pczt_bytes: Vec) -> Result { + install_panic_hook(); + let failure = |error: String| RuntimeError::new(ErrorCode::PcztError).detail(error); + let pczt = pczt::Pczt::parse(&pczt_bytes).map_err(|e| failure(format!("{e:?}")))?; + let tx = pczt::roles::tx_extractor::TransactionExtractor::new(pczt) + .extract() + .map_err(|e| failure(format!("{e:?}")))?; + let mut bytes = Vec::new(); + tx.write(&mut bytes) + .map_err(|e| failure(format!("{e:?}")))?; + Ok( + serde_json::json!({ "rawTx": hex::encode(bytes), "txid": tx.txid().to_string() }) + .to_string(), + ) +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs index b813c7b76..bbf27667e 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs @@ -86,6 +86,15 @@ pub fn connect(base_url: &str) -> Result { json!({ "reason": "emptyUrl" }), )); } + // 明文会把「这个钱包在查哪些地址」直接暴露给链路上的任何人。原生那条路 + // 靠 `https://` 前缀决定要不要配 TLS,浏览器这条路之前什么都收 —— 补齐, + // 免得哪天开放自定义节点或某个备用地址写错时静默降级。 + if !base_url.starts_with("https://") { + return Err(RuntimeError::with( + ErrorCode::LightwalletdNotConfigured, + json!({ "reason": "httpsRequired" }), + )); + } Ok(CompactTxStreamerClient::new( tonic_web_wasm_client::Client::new(base_url.to_owned()), )) diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs index 9b8d75d89..e1d0bf5c9 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs @@ -721,7 +721,16 @@ pub fn prove_pczt(db: &Db, pczt_bytes: &[u8]) -> Result> { .chain_height() .map_err(|error| build_err("chainHeight", error))? .ok_or_else(|| RuntimeError::new(ErrorCode::NotSynced))?; - let version = circuit_version_for(¶ms, chain_tip); + prove_pczt_at_height(¶ms, chain_tip, pczt_bytes) +} + +/// Pure proving: no wallet, database, scan, or storage initialization. +pub fn prove_pczt_at_height( + params: &zcash_protocol::consensus::Network, + chain_tip: zcash_protocol::consensus::BlockHeight, + pczt_bytes: &[u8], +) -> Result> { + let version = circuit_version_for(params, chain_tip); let pczt = pczt::Pczt::parse(pczt_bytes).map_err(|error| { RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "parse" })) .detail(format!("{error:?}")) From fdc95fccdf28a4cecfbf173559559e3831917288 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Fri, 18 Sep 2026 15:50:37 +0900 Subject: [PATCH 05/97] feat: guard pczt combining and drop the stateful shielding path `pcztCombine` was a bare Combiner. The Transaction Extractor that follows it recomputes the sighash from the COMBINED transaction, so it answers "is this transaction self-consistent", never "is this what the user approved". Combining now compares the shielded sighash and every transparent input sighash before and after, rejects a copy that already carries a scriptSig -- the one field a counterparty can fill that no sighash covers -- and fails before the expensive proof rather than after it. Four tests, including one that pins the upstream property the old code silently depended on: our PCZTs are io-finalized, so tx_modifiable is 0 and the Combiner refuses to grow them. If a future bump relaxes that, the sighash comparison is what still covers us. The stateful shielding path is removed: pcztShield, pcztShieldQuote and their proposal helpers, plus three dead branches hidden inside live functions (release_reservation's second reservation table, forget_reservation, and clear_locked_outputs' second retain). Shielding has gone through the stateless keys runtime since the 2026-09-14 alignment; nothing had called these since. README keeps the testnet acceptance record and notes the API is gone rather than moving the tick to a path that has not been verified on chain. --- .github/workflows/zcash-runtime.yml | 3 + chain-runtimes/zcash/.gitignore | 1 + chain-runtimes/zcash/CONTEXT.md | 22 +- chain-runtimes/zcash/Cargo.lock | 1 + chain-runtimes/zcash/README.md | 4 +- .../crates/zcash-keys-runtime/src/bindgen.rs | 48 +- .../crates/zcash-keys-runtime/src/error.rs | 4 + .../crates/zcash-keys-runtime/src/keys.rs | 38 +- .../src/transparent_send.rs | 47 +- .../src/transparent_send/shielding.rs | 444 ++++++++- .../zcash/crates/zcash-runtime/Cargo.toml | 3 + .../zcash/crates/zcash-runtime/src/account.rs | 4 +- .../zcash/crates/zcash-runtime/src/bindgen.rs | 202 ++-- .../zcash/crates/zcash-runtime/src/error.rs | 3 + .../zcash/crates/zcash-runtime/src/guard.rs | 290 ++++++ .../zcash/crates/zcash-runtime/src/history.rs | 18 - .../zcash/crates/zcash-runtime/src/lib.rs | 1 + .../zcash/crates/zcash-runtime/src/send.rs | 745 ++++++++++---- .../zcash/crates/zcash-runtime/src/sync.rs | 911 ++++++++++++++++-- .../crates/zcash-runtime/src/tx_state.rs | 2 +- .../zcash/scripts/artifact-manifest.py | 83 ++ chain-runtimes/zcash/scripts/build-wasm.sh | 6 + .../zcash/scripts/test_artifact_manifest.py | 40 + 23 files changed, 2439 insertions(+), 481 deletions(-) create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/guard.rs create mode 100644 chain-runtimes/zcash/scripts/artifact-manifest.py create mode 100644 chain-runtimes/zcash/scripts/test_artifact_manifest.py diff --git a/.github/workflows/zcash-runtime.yml b/.github/workflows/zcash-runtime.yml index 98603e159..9bf3d0c80 100644 --- a/.github/workflows/zcash-runtime.yml +++ b/.github/workflows/zcash-runtime.yml @@ -43,6 +43,8 @@ jobs: CC_wasm32_unknown_unknown: /usr/bin/clang AR_wasm32_unknown_unknown: /usr/bin/llvm-ar run: bash scripts/build-wasm.sh --offline + - name: Verify complete artifact provenance + run: python3 scripts/artifact-manifest.py verify --expected-revision "${{ github.sha }}" - uses: actions/upload-artifact@v4 with: name: zcash-wasm-${{ github.sha }} @@ -50,3 +52,4 @@ jobs: path: | chain-runtimes/zcash/pkg/ chain-runtimes/zcash/pkg-keys/ + chain-runtimes/zcash/zcash-wasm-manifest.json diff --git a/chain-runtimes/zcash/.gitignore b/chain-runtimes/zcash/.gitignore index c680152bb..9c940c0d5 100644 --- a/chain-runtimes/zcash/.gitignore +++ b/chain-runtimes/zcash/.gitignore @@ -1,6 +1,7 @@ /target /pkg /pkg-keys +/zcash-wasm-manifest.json /vendor *.log __pycache__/ diff --git a/chain-runtimes/zcash/CONTEXT.md b/chain-runtimes/zcash/CONTEXT.md index d1a1f56f6..20c0b4060 100644 --- a/chain-runtimes/zcash/CONTEXT.md +++ b/chain-runtimes/zcash/CONTEXT.md @@ -114,27 +114,27 @@ Current Shielded Output Pool。它不消费任何已有私密池,也不消费 _Avoid_: Shield、归集(单独使用时无法表达来源、目标和“全部”语义) -## Internal Transparent Spending(内测透明花费) +## Transparent-first Preference(优先使用透明资金) -wallet runtime 接受普通透明输入的底层能力。它不属于 OneKey 产品的正常发送路径; -App 始终传入关闭值,能力的开启分支只能由 runtime 自身的隔离测试覆盖,不能出现在 -普通 Debug UI 或可持久化设置中。 +账户允许向受支持私密目的地址付款时优先使用符合条件的透明资金,再由选定私池补足 +差额的偏好。它不是自动屏蔽,也不代表透明资金来源因此被隐藏。 -_Avoid_: Debug 开关(Developer Mode 在正式构建中仍可能启用,不等价于构建授权) +_Avoid_: 内测专属透明花费、自动 Shield All + +产品定位与默认关闭的决定见 +[App ADR 0007](../../../app-monorepo/packages/kit-bg/src/vaults/impls/zcash/docs/adr/0007-align-payment-capabilities-and-balance-language.md)。 ## Transparent Mode(透明模式) -账户只使用 Zcash 透明地址和 OneKey 后端数据,不注册 UFVK、不扫描私密池,也不加载 -wallet runtime。查看余额和历史不需要任何 Zcash WASM;软件发送按需加载无数据库、 -无网络、无扫描器的轻量 Zcash signer。 +账户展示透明资金与活动,并使用透明来源付款,不启用私密资金发现或扫描。付款可以 +面向透明地址或受支持的 Unified Address;私密收款目标不改变付款来源的公开属性。 _Avoid_: Privacy disabled(容易把产品模式误解为一次临时暂停) ## Privacy Mode(隐私模式) -账户允许注册 UFVK,并由共享 wallet runtime 扫描支持的私密池。关闭该模式必须停止 -该 UFVK 的 trial decryption,而不只是隐藏 UI。当前支持对象是软件 HD 账户;导入 -助记词仍属于 HD,单私钥账户和观察账户不属于 Privacy Mode。 +账户选择启用受支持私密资金与活动的发现和展示。启用不等于历史发现已经完成; +支持的账户、设备及发送组合由产品契约规定,不能由该模式名称自行推导。 ## Privacy Pause(暂停隐私处理) diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock index 805679815..1c2bb002d 100644 --- a/chain-runtimes/zcash/Cargo.lock +++ b/chain-runtimes/zcash/Cargo.lock @@ -1704,6 +1704,7 @@ dependencies = [ "sapling-crypto", "schemerz", "schemerz-rusqlite", + "secp256k1", "serde", "serde_json", "sqlite-wasm-rs", diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md index 51c520cd7..d529a586b 100644 --- a/chain-runtimes/zcash/README.md +++ b/chain-runtimes/zcash/README.md @@ -137,7 +137,8 @@ OPFS 仍受浏览器 origin、配额和清理策略约束;App 内嵌页面的 - [x] **端到端发送并广播上链**(testnet):水龙头 0.1 TAZ 落 Ironwood 池 → `pcztCreate` → `pcztProve`(Halo2 约 19s)→ `pcztSign` → `pcztSend` → `broadcastTransaction`,链上确认。逐笔手续费对账到 zatoshi -- [x] **透明 ↔ 屏蔽双向**:隐私→透明地址、透明→隐私(`pcztShield`,含**透明输入签名**)、 +- [x] **透明 ↔ 屏蔽双向**:隐私→透明地址、透明→隐私(当时走 `pcztShield`,含**透明 + 输入签名**;该 API 已移除,屏蔽改由 keys runtime 无状态构造)、 透明→透明(需 `spendTransparent`),全部链上确认 - [x] **多账户共库**:acct0/1/2 同一个库,扫一遍服务全部账户 @@ -204,7 +205,6 @@ deleteWallet(dbName) 擦掉本地缓存库(可重建), pcztQuote(...) 只报价,不建交易、不锁 note pcztCreate(...) → { pcztHex, reservationId } 构造并锁住选中的 note -pcztShield(...) → { pcztHex, reservationId } 屏蔽全部透明余额(无收款方、无金额) releaseReservation(id) 用户取消时放开锁,幂等 pcztProve(pczt, circuitVersion) → keys.pcztSign → pcztSend(pczt, reservationId) → txid broadcastTransaction(txid) 真正发出去(pcztSend 只落库,不发网络) diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs index fb127c218..83adc9991 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs @@ -20,20 +20,18 @@ pub fn ufvk_from_mnemonic( /// 从 UFVK 取统一地址。纯公开材料,不涉及私钥。 /// -/// `receiverPolicy` 决定 UA 里包含哪些 receiver:`"all"`(默认)/ `"shielded"` / -/// `"orchard"`。**这是隐私策略,由宿主决定** —— 带 transparent receiver 的地址 -/// 别人可以用公开方式付给你,代价是把你的透明与屏蔽活动关联起来。 +/// `receiverPolicy` 决定 UA 里包含哪些 receiver:`"all"` / `"shielded"` / +/// `"orchard"`。**这是隐私策略,由宿主决定,没有缺省值** —— 带 transparent +/// receiver 的地址别人可以用公开方式付给你,代价是把你的透明与屏蔽活动关联 +/// 起来。省略这个参数曾经等于选中 `"all"`,也就是那个代价最大的取值:调用方 +/// 什么都没写,却替用户做了这个决定。 #[wasm_bindgen(js_name = unifiedAddress)] pub fn unified_address( network: &str, ufvk: &str, - receiver_policy: Option, + receiver_policy: &str, ) -> Result { - Ok(keys::unified_address_with( - network, - ufvk, - receiver_policy.as_deref().unwrap_or("all"), - )?) + Ok(keys::unified_address_with(network, ufvk, receiver_policy)?) } /// 给 PCZT 签名。 @@ -159,6 +157,8 @@ pub fn keys_capabilities() -> String { "quote": true, "buildWithSeed": true, "buildWithAccountXprv": true, + "createWithAccountXpub": true, + "combineHardwareSigned": true, }, "transparentShield": { "createWithSeed": transparent_send::shielding::SHIELD_CREATE_WITH_SEED, @@ -170,6 +170,36 @@ pub fn keys_capabilities() -> String { .to_string() } +/// Creates a device-signable PCZT from public account material without wallet storage. +#[wasm_bindgen(js_name = transparentTxCreateWithAccountXpub)] +pub fn transparent_tx_create_with_account_xpub( + request_json: &str, + account_xpub: &str, + seed_fingerprint_hex: &str, +) -> Result, JsValue> { + Ok(transparent_send::shielding::create_with_account_xpub( + request_json, + account_xpub, + seed_fingerprint_hex, + )?) +} + +/// Validates and finalizes device signatures against the approved transaction. +#[wasm_bindgen(js_name = transparentTxCombineHardwareSigned)] +pub fn transparent_tx_combine_hardware_signed( + request_json: &str, + account_xpub: &str, + original: Vec, + signed: Vec, +) -> Result, JsValue> { + Ok(transparent_send::shielding::combine_hardware_signed( + request_json, + account_xpub, + &original, + &signed, + )?) +} + /// 本 crate 锁定的官方依赖版本。 #[wasm_bindgen(js_name = keysDependencyVersions)] pub fn dependency_versions() -> String { diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs index d602a8a66..3ffc35424 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs @@ -55,6 +55,8 @@ pub enum ErrorCode { DustChange, /// An account-level BIP-44 xprv is malformed or has unexpected metadata. InvalidAccountXprv, + /// An account-level BIP-44 xpub is malformed or has unexpected metadata. + InvalidAccountXpub, /// Transparent transaction construction or signing failed. TransactionBuildFailed, /// The signed transaction could not be serialized. @@ -88,6 +90,7 @@ impl ErrorCode { InsufficientFunds => "INSUFFICIENT_FUNDS", DustChange => "DUST_CHANGE", InvalidAccountXprv => "INVALID_ACCOUNT_XPRV", + InvalidAccountXpub => "INVALID_ACCOUNT_XPUB", TransactionBuildFailed => "TRANSACTION_BUILD_FAILED", TransactionSerializeFailed => "TRANSACTION_SERIALIZE_FAILED", } @@ -206,6 +209,7 @@ mod tests { InsufficientFunds, DustChange, InvalidAccountXprv, + InvalidAccountXpub, TransactionBuildFailed, TransactionSerializeFailed, ]; diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs index a0596c749..d1e29d062 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs @@ -71,7 +71,10 @@ pub fn ufvk_from_seed_bytes(params: Network, seed: &[u8], account_index: u32) -> fn receiver_policy(name: &str) -> Result { use zcash_keys::keys::UnifiedAddressRequest as R; match name { - "" | "all" => Ok(R::ALLOW_ALL), + // 空串不再当作 `"all"`。缺省最省事的那个取值恰好是隐私上最贵的一个: + // 带 transparent receiver 的 UA 会把用户的透明活动和屏蔽活动绑在 + // 同一个字符串里,而调用方什么都没写,也就什么都没同意。 + "all" => Ok(R::ALLOW_ALL), "shielded" => Ok(R::SHIELDED), "orchard" => Ok(R::ORCHARD), other => Err(KeysError::with( @@ -96,19 +99,6 @@ pub fn unified_address_with(network: &str, ufvk_str: &str, policy: &str) -> Resu Ok(addr.encode(¶ms)) } -/// 从 UFVK 取默认统一地址(UA)。不涉及任何私钥。 -pub fn unified_address(network: &str, ufvk_str: &str) -> Result { - let params = parse_network(network)?; - let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str) - .map_err(|e| KeysError::new(ErrorCode::InvalidUfvk).detail(e))?; - - let (addr, _) = ufvk - .default_address(zcash_keys::keys::UnifiedAddressRequest::ALLOW_ALL) - .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?; - - Ok(addr.encode(¶ms)) -} - /// 从 UFVK 取透明收款地址(t 地址)。不涉及任何私钥、不需要钱包库。 /// /// 与 UA 是同一份 UFVK 的两种呈现:UA 是包含多个 receiver 的统一地址, @@ -189,7 +179,7 @@ mod tests { let ufvk = ufvk_from_mnemonic("test", TEST_MNEMONIC, 0).unwrap(); let t = transparent_address("test", &ufvk).unwrap(); assert!(t.starts_with("tm"), "testnet t 地址前缀应为 tm,实际 {t}"); - let ua = unified_address("test", &ufvk).unwrap(); + let ua = unified_address_with("test", &ufvk, "all").unwrap(); assert!(ua.starts_with("utest"), "UA 前缀应为 utest"); assert_ne!(t, ua, "t 地址与 UA 是两种呈现,不该相同"); } @@ -204,7 +194,21 @@ mod tests { let hex_key = transparent_account_pubkey("main", &ufvk).unwrap(); assert_eq!(hex_key.len(), 65 * 2); let tag = &hex_key[64..66]; - assert!(tag == "02" || tag == "03", "压缩公钥前缀应为 02/03,实际 {tag}"); + assert!( + tag == "02" || tag == "03", + "压缩公钥前缀应为 02/03,实际 {tag}" + ); + } + + /// 省略 / 留空 receiver 策略曾经等于选中 `"all"` —— 那是隐私上最贵的取值, + /// 而调用方什么都没写,也就什么都没同意。 + #[test] + fn receiver_policy_has_no_default() { + assert!(receiver_policy("all").is_ok()); + assert!(receiver_policy("shielded").is_ok()); + assert!(receiver_policy("orchard").is_ok()); + assert!(receiver_policy("").is_err()); + assert!(receiver_policy("transparent").is_err()); } #[test] @@ -228,7 +232,7 @@ mod tests { "testnet UFVK 前缀应为 uview,实际 {ufvk}" ); - let addr = unified_address("test", &ufvk).expect("应能取地址"); + let addr = unified_address_with("test", &ufvk, "all").expect("应能取地址"); assert!( addr.starts_with("utest"), "testnet UA 前缀应为 utest,实际 {addr}" diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs index f245a3145..76ee4622b 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs @@ -13,7 +13,7 @@ use transparent::{ address::TransparentAddress, builder::{TransparentBuilder, TransparentSigningSet}, bundle::{OutPoint, TxOut}, - keys::{AccountPrivKey, NonHardenedChildIndex, TransparentKeyScope}, + keys::{AccountPrivKey, AccountPubKey, NonHardenedChildIndex, TransparentKeyScope}, }; use zcash_address::ZcashAddress; use zcash_keys::address::Address; @@ -135,6 +135,7 @@ enum RecipientAddress { #[derive(Debug)] struct PlannedOutput { address: RecipientAddress, + user_address: String, value: Zatoshis, } @@ -316,7 +317,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { serde_json::json!({ "field": "amountZat", "reason": "mustBeOmittedForSendMax" }), )); } - Ok((address, None)) + Ok((address, None, recipient.address)) } else { let amount = recipient.amount_zat.as_deref().ok_or_else(|| { KeysError::with( @@ -325,7 +326,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { ) })?; let value = parse_positive_zatoshis(amount, "recipient.amountZat")?; - Ok((address, Some(value))) + Ok((address, Some(value), recipient.address)) } }) .collect::>>()?; @@ -344,6 +345,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { inputs, recipients: vec![PlannedOutput { address, + user_address: parsed_recipients[0].2.clone(), value: send_amount, }], change: None, @@ -355,8 +357,9 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { let recipients = parsed_recipients .into_iter() - .map(|(address, value)| PlannedOutput { + .map(|(address, value, user_address)| PlannedOutput { address, + user_address, value: value.expect("non-send-max recipients were checked above"), }) .collect::>(); @@ -424,9 +427,10 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { ( fee, Some(( - change_request, + change_request.clone(), PlannedOutput { address: RecipientAddress::Transparent(change_address), + user_address: change_request.address, value: change_value, }, change_path, @@ -707,6 +711,39 @@ fn derive_secret_key( .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(e)) } +fn derive_public_key( + account_key: &AccountPubKey, + path: DerivationPath, +) -> Result { + let scope = match path.scope { + 0 => TransparentKeyScope::EXTERNAL, + 1 => TransparentKeyScope::INTERNAL, + _ => return Err(KeysError::new(ErrorCode::InvalidDerivationPath)), + }; + let index = NonHardenedChildIndex::from_index(path.index) + .ok_or_else(|| KeysError::new(ErrorCode::InvalidDerivationPath))?; + account_key + .derive_address_pubkey(scope, index) + .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(e)) +} + +fn parse_account_xpub(encoded: &str, expected_account: u32) -> Result { + let invalid = || KeysError::new(ErrorCode::InvalidAccountXpub); + let decoded = bs58::decode(encoded) + .with_check(None) + .into_vec() + .map_err(|_| invalid())?; + if decoded.len() != 78 || decoded[..4] != [0x04, 0x88, 0xb2, 0x1e] || decoded[4] != 3 { + return Err(invalid()); + } + let child = u32::from_be_bytes(decoded[9..13].try_into().map_err(|_| invalid())?); + if Some(child) != expected_account.checked_add(1 << 31) { + return Err(invalid()); + } + AccountPubKey::deserialize(decoded[13..].try_into().map_err(|_| invalid())?) + .map_err(|_| invalid()) +} + fn parse_account_xprv(encoded: &str, expected_account: u32) -> Result { let decoded = Zeroizing::new( bs58::decode(encoded) diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs index 48f557be5..6175019e8 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs @@ -1,10 +1,12 @@ //! Stateless shielding from an explicit, host-owned transparent UTXO catalog. use super::*; use pczt::roles::{ + combiner::Combiner, creator::Creator, io_finalizer::IoFinalizer, signer::Signer, spend_finalizer::SpendFinalizer, + updater::Updater, verifier::{OrchardError, TransparentError, Verifier}, }; use zcash_note_encryption::Domain; @@ -32,16 +34,16 @@ pub fn create(request_json: &str, seed: &[u8]) -> Result> { let plan = plan_transaction(parse_request(request_json)?)?; let key = AccountPrivKey::from_seed(&MAIN_NETWORK, seed, plan.account_index).map_err(failure)?; - create_with_key(&plan, &key) + create_with_public_key(&plan, &key.to_account_pubkey()) } pub fn create_with_account_xprv(request_json: &str, account_xprv: &str) -> Result> { let plan = plan_transaction(parse_request(request_json)?)?; let key = parse_account_xprv(account_xprv, u32::from(plan.account_index))?; - create_with_key(&plan, &key) + create_with_public_key(&plan, &key.to_account_pubkey()) } -fn create_with_key(plan: &TransactionPlan, key: &AccountPrivKey) -> Result> { +fn create_with_public_key(plan: &TransactionPlan, key: &AccountPubKey) -> Result> { let mut builder = Builder::new( MAIN_NETWORK, plan.target_height, @@ -49,15 +51,18 @@ fn create_with_key(plan: &TransactionPlan, key: &AccountPrivKey) -> Result Result Result { + transparent_addresses.push((transparent_index, output.user_address.clone())); + transparent_index += 1; + } + RecipientAddress::Ironwood(_) => { + let action_index = parts + .ironwood_meta + .output_action_index(ironwood_index) + .ok_or_else(mismatch)?; + ironwood_addresses.push((action_index, output.user_address.clone())); + ironwood_index += 1; + } + } + } + let pczt = Updater::new(pczt) + .update_transparent_with(|mut bundle| { + for (index, address) in transparent_addresses { + bundle.update_output_with(index, |mut output| { + output.set_user_address(address); + Ok(()) + })?; + } + Ok(()) + }) + .map_err(failure)? + .update_ironwood_with(|mut bundle| { + for (index, address) in ironwood_addresses { + bundle.update_action_with(index, |mut action| { + action.set_output_user_address(address); + Ok(()) + })?; + } + Ok(()) + }) + .map_err(failure)? + .finish(); IoFinalizer::new(pczt) .finalize_io() .map_err(failure)? @@ -108,6 +154,159 @@ fn create_with_key(plan: &TransactionPlan, key: &AccountPrivKey) -> Result Result> { + let plan = plan_transaction(parse_request(request_json)?)?; + let key = parse_account_xpub(account_xpub, u32::from(plan.account_index))?; + let fingerprint: [u8; 32] = hex::decode(seed_fingerprint_hex) + .map_err(|_| KeysError::new(ErrorCode::InvalidTransactionRequest))? + .try_into() + .map_err(|_| KeysError::new(ErrorCode::InvalidTransactionRequest))?; + let original = create_with_public_key(&plan, &key)?; + let pczt = pczt::Pczt::parse(&original).map_err(failure)?; + let derivation = |path: DerivationPath| { + transparent::pczt::Bip32Derivation::parse( + fingerprint, + vec![ + 44 | (1 << 31), + 133 | (1 << 31), + path.account | (1 << 31), + path.scope, + path.index, + ], + ) + .map_err(failure) + }; + let input_keys = plan + .inputs + .iter() + .map(|input| { + Ok(( + derive_public_key(&key, input.path)?.serialize(), + derivation(input.path)?, + )) + }) + .collect::>>()?; + let change_key = plan + .change + .as_ref() + .map(|(_, _, path)| { + Ok(( + derive_public_key(&key, *path)?.serialize(), + derivation(*path)?, + )) + }) + .transpose()?; + let change_index = plan + .recipients + .iter() + .filter(|output| matches!(output.address, RecipientAddress::Transparent(_))) + .count(); + let updated = Updater::new(pczt) + .update_transparent_with(|mut updater| { + for (index, (public, path)) in input_keys.into_iter().enumerate() { + updater.update_input_with(index, |mut input| { + input.set_bip32_derivation(public, path); + Ok(()) + })?; + } + if let Some((public, path)) = change_key { + updater.update_output_with(change_index, |mut output| { + output.set_bip32_derivation(public, path); + Ok(()) + })?; + } + Ok(()) + }) + .map_err(failure)? + .finish(); + // Keep device RAM bounds explicit before asking the user to confirm. + let serialized = updated.serialize().map_err(failure)?; + if serialized.len() > 24 * 1024 { + return Err(KeysError::with( + ErrorCode::TransactionBuildFailed, + serde_json::json!({ "reason": "hardwarePcztTooLarge", "maxBytes": 24 * 1024 }), + )); + } + Ok(serialized) +} + +/// Combines a device's redacted signatures with the approved original, verifies +/// every signature against the exact request, then finalizes transparent spends. +pub fn combine_hardware_signed( + request_json: &str, + account_xpub: &str, + original: &[u8], + signed: &[u8], +) -> Result> { + let plan = plan_transaction(parse_request(request_json)?)?; + let key = parse_account_xpub(account_xpub, u32::from(plan.account_index))?; + let original = validate_original(&plan, &key, pczt::Pczt::parse(original).map_err(failure)?)?; + let original_signer = Signer::new(original.clone()).map_err(failure)?; + let combined = Combiner::new(vec![original, pczt::Pczt::parse(signed).map_err(failure)?]) + .combine() + .map_err(failure)?; + if combined.transparent().inputs().len() != plan.inputs.len() { + return Err(mismatch()); + } + let combined_signer = Signer::new(combined.clone()).map_err(failure)?; + let mut sighashes = Vec::with_capacity(plan.inputs.len()); + for index in 0..plan.inputs.len() { + let approved = original_signer + .transparent_sighash(index) + .map_err(failure)?; + if combined_signer + .transparent_sighash(index) + .map_err(failure)? + != approved + { + return Err(mismatch()); + } + sighashes.push(approved); + } + let secp = secp256k1::Secp256k1::verification_only(); + let combined = Verifier::new(combined) + .with_transparent(|bundle| { + for (index, input) in bundle.inputs().iter().enumerate() { + let public = derive_public_key(&key, plan.inputs[index].path) + .map_err(TransparentError::Custom)?; + let signatures = input.partial_signatures(); + let signature = signatures + .get(&public.serialize()) + .ok_or_else(|| TransparentError::Custom(mismatch()))?; + if signatures.len() != 1 + || signature.last() != Some(&1) + || input.script_sig().is_some() + || *input.sighash_type() != transparent::sighash::SighashType::ALL + { + return Err(TransparentError::Custom(mismatch())); + } + let signature = + secp256k1::ecdsa::Signature::from_der(&signature[..signature.len() - 1]) + .map_err(|_| TransparentError::Custom(mismatch()))?; + secp.verify_ecdsa( + &secp256k1::Message::from_digest(sighashes[index]), + &signature, + &public, + ) + .map_err(|_| TransparentError::Custom(mismatch()))?; + } + Ok(()) + }) + .map_err(failure)? + .finish(); + SpendFinalizer::new(combined) + .finalize_spends() + .map_err(failure)? + .serialize() + .map_err(failure) +} + fn mismatch() -> KeysError { KeysError::new(ErrorCode::KeyMismatch) } @@ -199,10 +398,15 @@ fn validate_ironwood(bundle: &orchard::pczt::Bundle, plan: &TransactionPlan) -> fn validate_original( plan: &TransactionPlan, - key: &AccountPrivKey, + key: &AccountPubKey, pczt: pczt::Pczt, ) -> Result { let global = pczt.global(); + let has_ironwood = plan + .recipients + .iter() + .any(|output| matches!(output.address, RecipientAddress::Ironwood(_))); + let expected_anchor = has_ironwood.then(|| orchard::Anchor::empty_tree().to_bytes()); if *global.tx_version() != zcash_protocol::constants::V6_TX_VERSION || *global.version_group_id() != zcash_protocol::constants::V6_VERSION_GROUP_ID || *global.consensus_branch_id() != u32::from(BranchId::Nu6_3) @@ -211,14 +415,16 @@ fn validate_original( || !pczt.sapling().spends().is_empty() || !pczt.sapling().outputs().is_empty() || !pczt.orchard().actions().is_empty() - || *pczt.ironwood().anchor() != Some(orchard::Anchor::empty_tree().to_bytes()) + || *pczt.ironwood().anchor() != expected_anchor + || (!has_ironwood + && (!pczt.ironwood().actions().is_empty() + || *pczt.ironwood().value_sum() != (0, false))) || pczt.transparent().inputs().len() != plan.inputs.len() { return Err(mismatch()); } for (input, planned) in pczt.transparent().inputs().iter().zip(&plan.inputs) { - let secret = derive_secret_key(key, planned.path)?; - let public = secp256k1::PublicKey::from_secret_key(&secp256k1::Secp256k1::new(), &secret); + let public = derive_public_key(key, planned.path)?; if input.prevout_txid() != planned.txid.as_ref() || *input.prevout_index() != planned.request.vout || *input.value() != u64::from(planned.value) @@ -242,8 +448,7 @@ fn validate_original( .collect::>(); if let Some((_, change, path)) = &plan.change { let address = require_transparent(change.address)?; - let secret = derive_secret_key(key, *path)?; - let public = secp256k1::PublicKey::from_secret_key(&secp256k1::Secp256k1::new(), &secret); + let public = derive_public_key(key, *path)?; if TransparentAddress::from_pubkey(&public) != address { return Err(mismatch()); } @@ -273,9 +478,14 @@ fn validate_original( } Ok(()) }) - .map_err(failure)? - .with_ironwood(|bundle| validate_ironwood(bundle, plan).map_err(OrchardError::Custom)) .map_err(failure)?; + let verified = if has_ironwood { + verified + .with_ironwood(|bundle| validate_ironwood(bundle, plan).map_err(OrchardError::Custom)) + .map_err(failure)? + } else { + verified + }; Ok(verified.finish()) } @@ -306,7 +516,11 @@ fn sign_with_key( original: &[u8], pczt: &[u8], ) -> Result> { - let original = validate_original(plan, key, pczt::Pczt::parse(original).map_err(failure)?)?; + let original = validate_original( + plan, + &key.to_account_pubkey(), + pczt::Pczt::parse(original).map_err(failure)?, + )?; let pczt = pczt::Pczt::parse(pczt).map_err(failure)?; // V6 deliberately excludes anchors from the effects hash (ZIP 374). if pczt.ironwood().anchor() != original.ironwood().anchor() @@ -404,6 +618,202 @@ mod tests { }) } + fn account_xpub() -> String { + let key = AccountPrivKey::from_seed(&MAIN_NETWORK, &SEED, AccountId::ZERO).unwrap(); + let mut payload = vec![0x04, 0x88, 0xb2, 0x1e, 3, 0, 0, 0, 0]; + payload.extend_from_slice(&(1_u32 << 31).to_be_bytes()); + payload.extend_from_slice(&key.to_account_pubkey().serialize()); + bs58::encode(payload).with_check().into_string() + } + + fn simulated_device_signature(original: &[u8]) -> Vec { + simulated_device_signatures(original, 1) + } + + fn simulated_device_signatures(original: &[u8], input_count: usize) -> Vec { + let key = AccountPrivKey::from_seed(&MAIN_NETWORK, &SEED, AccountId::ZERO).unwrap(); + let mut signer = Signer::new(pczt::Pczt::parse(original).unwrap()).unwrap(); + for index in 0..input_count { + signer + .sign_transparent( + index, + &derive_secret_key( + &key, + DerivationPath { + account: 0, + scope: 0, + index: 0, + }, + ) + .unwrap(), + ) + .unwrap(); + } + pczt::roles::redactor::Redactor::new(signer.finish()) + .redact_transparent_with(|mut bundle| { + bundle.redact_inputs(|mut input| input.clear_bip32_derivation()); + bundle.redact_outputs(|mut output| output.clear_bip32_derivation()); + }) + .finish() + .serialize() + .unwrap() + } + + #[test] + fn hardware_metadata_matches_each_external_output_after_action_randomization() { + let mut request = request(false); + request["recipients"] = json!([ + { "address": recipient(0), "amountZat": "10000" }, + { "address": recipient(1), "amountZat": "10000" }, + { "address": recipient(0), "amountZat": "10000" }, + { "address": transparent_address(0, 9).to_zcash_address(NetworkType::Main).to_string(), "amountZat": "10000" }, + ]); + for _ in 0..4 { + let original = + create_with_account_xpub(&request.to_string(), &account_xpub(), &"01".repeat(32)) + .unwrap(); + let pczt = pczt::Pczt::parse(&original).unwrap(); + Verifier::new(pczt) + .with_transparent::(|bundle| { + assert_eq!(bundle.inputs()[0].bip32_derivation().len(), 1); + let external = &bundle.outputs()[0]; + let address = require_transparent( + parse_recipient_address(external.user_address().as_ref().unwrap()).unwrap(), + ) + .unwrap(); + assert_eq!( + address.script().to_bytes(), + external.script_pubkey().to_bytes() + ); + assert!(external.bip32_derivation().is_empty()); + assert_eq!(bundle.outputs()[1].bip32_derivation().len(), 1); + Ok(()) + }) + .unwrap() + .with_ironwood::(|bundle| { + let mut displayed = Vec::new(); + for action in bundle.actions() { + let output = action.output(); + if output.value().unwrap().inner() == 0 { + continue; + } + let address = output.user_address().as_ref().unwrap(); + let RecipientAddress::Ironwood(receiver) = + parse_recipient_address(address).unwrap() + else { + panic!("expected Ironwood recipient"); + }; + assert_eq!(Some(receiver), *output.recipient()); + displayed.push(address.clone()); + } + displayed.sort(); + let mut expected = vec![recipient(0), recipient(1), recipient(0)]; + expected.sort(); + assert_eq!(displayed, expected); + Ok(()) + }) + .unwrap(); + } + } + + #[test] + fn hardware_requires_all_selected_inputs_and_rejects_invalid_public_material() { + let mut request = request(false); + let mut second = request["utxos"][0].clone(); + second["vout"] = 1.into(); + request["utxos"].as_array_mut().unwrap().push(second); + let mut outpoint = request["selectedOutpoints"][0].clone(); + outpoint["vout"] = 1.into(); + request["selectedOutpoints"] + .as_array_mut() + .unwrap() + .push(outpoint); + let request = request.to_string(); + let original = + create_with_account_xpub(&request, &account_xpub(), &"01".repeat(32)).unwrap(); + assert!(combine_hardware_signed( + &request, + &account_xpub(), + &original, + &simulated_device_signatures(&original, 1) + ) + .is_err()); + let signed = simulated_device_signatures(&original, 2); + let finalized = + combine_hardware_signed(&request, &account_xpub(), &original, &signed).unwrap(); + assert!(combine_hardware_signed(&request, &account_xpub(), &original, &finalized).is_err()); + let parsed = pczt::Pczt::parse(&signed).unwrap(); + let mut signature = Vec::new(); + Verifier::new(parsed) + .with_transparent::(|bundle| { + signature = bundle.inputs()[0] + .partial_signatures() + .values() + .next() + .unwrap() + .clone(); + Ok(()) + }) + .unwrap(); + let position = signed + .windows(signature.len()) + .position(|bytes| bytes == signature.as_slice()) + .unwrap(); + let mut corrupted = signed.clone(); + corrupted[position + signature.len() - 3] ^= 1; + assert!(combine_hardware_signed(&request, &account_xpub(), &original, &corrupted).is_err()); + assert!(create_with_account_xpub(&request, "not-an-xpub", &"01".repeat(32)).is_err()); + assert!(create_with_account_xpub(&request, &account_xpub(), "01").is_err()); + } + + #[test] + fn hardware_public_construction_and_signature_validation_cover_both_destinations() { + for transparent_destination in [false, true] { + for send_max in [false, true] { + let mut request = request(send_max); + if transparent_destination { + request["recipients"][0]["address"] = transparent_address(0, 9) + .to_zcash_address(NetworkType::Main) + .to_string() + .into(); + } + let request_json = request.to_string(); + let original = + create_with_account_xpub(&request_json, &account_xpub(), &"01".repeat(32)) + .unwrap(); + let signed = simulated_device_signature(&original); + let finalized = + combine_hardware_signed(&request_json, &account_xpub(), &original, &signed) + .unwrap(); + Verifier::new(pczt::Pczt::parse(&finalized).unwrap()) + .with_transparent::(|bundle| { + assert!(bundle.inputs()[0].script_sig().is_some()); + Ok(()) + }) + .unwrap(); + let mut changed_request = request.clone(); + changed_request["expiryHeight"] = 3_500_021.into(); + let changed = simulated_device_signature( + &create(&changed_request.to_string(), &SEED).unwrap(), + ); + assert!(combine_hardware_signed( + &request_json, + &account_xpub(), + &original, + &changed + ) + .is_err()); + assert!(combine_hardware_signed( + &request_json, + &account_xpub(), + &original, + &original + ) + .is_err()); + } + } + } + fn mutate(bytes: &[u8], change: impl FnOnce(&mut Value)) -> Vec { let wire = pczt::v2::Pczt::try_from(pczt::Pczt::parse(bytes).unwrap()).unwrap(); let mut value = serde_json::to_value(wire).unwrap(); diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml index 5cb7eb822..d4a76f786 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml @@ -51,6 +51,9 @@ tokio = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] tokio.workspace = true +# Only for building a signed PCZT fixture in the combine_pczt tests; must track +# the version `transparent`/`pczt` use or the key types will not unify. +secp256k1 = { version = "0.29", features = ["alloc"], default-features = false } [target.'cfg(target_arch = "wasm32")'.dependencies] sqlite-wasm-rs.workspace = true diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs index 410907333..008de4413 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs @@ -160,8 +160,8 @@ pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) -> "ironwood": pool(balances.ironwood_balance()), // 透明余额也分开报:coinbase 有不同的成熟规则,而且只能走 - // `propose_shielding_coinbase` 屏蔽 —— `pcztShield` 用的是 - // NonCoinbaseOnly,屏蔽不到它。并成一个数就看不出这个差别了。 + // `propose_shielding_coinbase` 屏蔽,宿主的屏蔽路径碰不到它。 + // 并成一个数就看不出这个差别了。 "transparentRegular": pool(balances.unshielded_regular_balance()), "transparentCoinbase": pool(balances.unshielded_coinbase_balance()), diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs index 2f8eeaa2c..ca50f9d69 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs @@ -23,7 +23,7 @@ use crate::perf; use crate::{ account, error::{ErrorCode, RuntimeError}, - history, network, runtime, send, storage, sync, tx_state, wallet, + guard, history, network, runtime, send, storage, sync, tx_state, wallet, }; // ── 生命周期 ──────────────────────────────────────────────────────────── @@ -228,24 +228,14 @@ pub async fn import_account_ufvk( /// 从共享库里移除单个账户。**不删库** —— 库还装着其他钱包的账户。 #[wasm_bindgen(js_name = removeAccount)] pub async fn remove_account(account_uuid: String) -> Result<(), JsValue> { - let has_unsettled_outgoing = - runtime::with_read_conn(|conn| history::has_unsettled_outgoing(conn, &account_uuid))?; - let has_unresolved_broadcast = runtime::with_read_conn(|conn| { - tx_state::unresolved_txids(conn, &account_uuid).map(|txids| !txids.is_empty()) - })?; - let has_active_reservation = send::has_active_reservations(&account_uuid); - if has_active_reservation || has_unsettled_outgoing || has_unresolved_broadcast { - return Err(crate::RuntimeError::with( - crate::ErrorCode::WalletBusy, - serde_json::json!({ - "operation": "removeAccount", - "activeReservation": has_active_reservation, - "unsettledOutgoing": has_unsettled_outgoing, - "unresolvedBroadcast": has_unresolved_broadcast, - }), + runtime::with_read_conn(|conn| { + guard::assert_idle( + conn, + Some(&account_uuid), + "removeAccount", + guard::LockPolicy::Blocking, ) - .into()); - } + })?; runtime::with_db(|db| account::remove_account(db, &account_uuid))?; storage::durability_barrier().await?; Ok(()) @@ -337,16 +327,26 @@ pub async fn sync_tip() -> Result { ) } -/// 刷新账户的透明 UTXO。**必须单独调**。 +/// 用宿主给的快照刷新账户的透明 UTXO。**必须单独调**。 /// -/// 扫区块只产出屏蔽 note;透明 UTXO 在链上是公开的,要按地址向 lightwalletd 查。 -/// 不调的后果是静默的:透明余额恒为 0、屏蔽按钮永远说「没有可屏蔽的钱」, -/// 而扫链看起来一切正常。 +/// 扫区块只产出屏蔽 note;透明 UTXO 在链上是公开的,由宿主的后端索引器提供 —— +/// 运行时不自己去查,透明侧只有一个事实来源。不调的后果是静默的:隐私转账 +/// 想花透明输入时选不到钱,而扫链看起来一切正常。 +/// +/// `utxos_json` 是 `HostTransparentUtxo` 数组: +/// `[{ txid, vout, valueZat, scriptPubKey, height }]`。归属由脚本反解的地址 +/// 决定,不属于本账户的条目会被丢掉。 #[wasm_bindgen(js_name = syncTransparentUtxos)] -pub async fn sync_transparent_utxos(account_uuid: String) -> Result { +pub async fn sync_transparent_utxos( + account_uuid: String, + utxos_json: String, +) -> Result { + let utxos: Vec = serde_json::from_str(&utxos_json) + .map_err(|e| RuntimeError::new(ErrorCode::InvalidTransparentUtxos).detail(e.to_string()))?; Ok( runtime::with_db_and_client(move |mut db, mut client| async move { - let r = sync::refresh_transparent_utxos(&mut db, &mut client, &account_uuid).await; + let r = + sync::refresh_transparent_utxos(&mut db, &mut client, &account_uuid, &utxos).await; (db, client, r) }) .await?, @@ -390,22 +390,22 @@ pub fn pczt_quote( trusted: u32, untrusted: u32, fallback_change_pool: String, + pad_orchard_bundle: bool, spend_transparent: Option, allow_zero_conf_shielding: Option, spend_source: Option, ) -> Result { - let pool = send::parse_change_pool(&fallback_change_pool)?; - // 报价必须和真正发送用同一套选币规则,否则报出来的费用不是实付的费用。 - // spend_source 也在其中:限定池子会换掉被选中的 note,费用随之不同。 - let policy = send::SendPolicy { + // 与 `pcztCreate` 同一个构造入口,参数顺序也刻意对齐:报价用的选币规则 + // 只要有一个字段和真正发送不同,报出来的费用就不是实付的费用。 + let policy = send::parse_send_policy( trusted, untrusted, - fallback_change_pool: pool, - pad_orchard_bundle: false, - spend_transparent: spend_transparent.unwrap_or(false), - allow_zero_conf_shielding: allow_zero_conf_shielding.unwrap_or(false), - spend_source: send::parse_spend_source(spend_source.as_deref())?, - }; + &fallback_change_pool, + pad_orchard_bundle, + spend_transparent, + allow_zero_conf_shielding, + spend_source.as_deref(), + )?; Ok(runtime::with_db(|db| { send::quote( db, @@ -512,6 +512,12 @@ pub fn transaction_history( /// (上游可能因承诺树检查点位置退得更靠前)。 #[wasm_bindgen(js_name = rewindTo)] pub fn rewind_to(height: u32) -> Result { + // 刻意**没有**空闲闸门。这不是用户可选的破坏性操作,而是重组发生时钱包 + // 跟上链的唯一手段(唯一调用方是 syncWallet 的重组分支)。在这里因为 + // 「有笔交易还没落块」而拒绝,正好挑中最该回退的时刻把账户钉死在一条 + // 已被放弃的链上,之后再也扫不过去。 + // + // 用户触发的重扫走 `queueRescanFrom`:它只重排扫描区间,不丢数据。 Ok(runtime::with_db(|db| sync::rewind_to(db, height))?) } @@ -554,16 +560,15 @@ pub fn pczt_create( allow_zero_conf_shielding: Option, spend_source: Option, ) -> Result { - let pool = send::parse_change_pool(&fallback_change_pool)?; - let policy = send::SendPolicy { + let policy = send::parse_send_policy( trusted, untrusted, - fallback_change_pool: pool, + &fallback_change_pool, pad_orchard_bundle, - spend_transparent: spend_transparent.unwrap_or(false), - allow_zero_conf_shielding: allow_zero_conf_shielding.unwrap_or(false), - spend_source: send::parse_spend_source(spend_source.as_deref())?, - }; + spend_transparent, + allow_zero_conf_shielding, + spend_source.as_deref(), + )?; Ok(runtime::with_db(|db| { let (bytes, reservation_id, fee_zat) = send::create_pczt( db, @@ -600,84 +605,6 @@ pub fn pczt_combine(original: Vec, signed: Vec) -> Result, JsVal Ok(send::combine_pczt(&original, &signed)?) } -/// 构造「屏蔽全部透明余额」的 PCZT,返回 `{ pcztHex, reservationId }`。 -/// -/// 没有收款地址、没有金额:收款方是本账户自己的屏蔽地址,金额是全部透明余额。 -/// 之后的 prove / sign / send / broadcast 与普通转账完全一样。 -/// -/// `shieldingThresholdZat` 是宿主策略:透明余额低于它就不值得屏蔽(手续费可能 -/// 比金额还高)。低于阈值时抛 `INSUFFICIENT_FUNDS`。 -#[wasm_bindgen(js_name = pcztShield)] -pub fn pczt_shield( - account_uuid: String, - shielding_threshold_zat: u64, - trusted: u32, - untrusted: u32, - fallback_change_pool: String, - pad_orchard_bundle: bool, - lock_for_blocks: u32, - reservation_id: Option, - allow_zero_conf_shielding: Option, -) -> Result { - let pool = send::parse_change_pool(&fallback_change_pool)?; - let policy = send::SendPolicy { - trusted, - untrusted, - fallback_change_pool: pool, - pad_orchard_bundle, - // 屏蔽按定义就是花透明输入。这里不读这个字段(屏蔽路径有自己的选币器), - // 写 true 是为了字段语义诚实,将来谁去读它也拿到对的值。 - spend_transparent: true, - allow_zero_conf_shielding: allow_zero_conf_shielding.unwrap_or(false), - // 同上:屏蔽不从屏蔽池取 note,源池子这个概念在这条路径上不适用。 - spend_source: None, - }; - Ok(runtime::with_db(|db| { - let (bytes, reservation_id, fee_zat) = send::create_shielding_pczt( - db, - &account_uuid, - shielding_threshold_zat, - policy, - lock_for_blocks, - reservation_id.as_deref(), - )?; - Ok(serde_json::json!({ - "pcztHex": bytes.iter().map(|b| format!("{b:02x}")).collect::(), - "reservationId": reservation_id, - "feeZat": fee_zat, - }) - .to_string()) - })?) -} - -/// Exact shielding fee from the same proposal path as `pcztShield`, without -/// locking inputs or constructing a transaction. -#[wasm_bindgen(js_name = pcztShieldQuote)] -pub fn pczt_shield_quote( - account_uuid: String, - shielding_threshold_zat: u64, - trusted: u32, - untrusted: u32, - fallback_change_pool: String, - pad_orchard_bundle: bool, - allow_zero_conf_shielding: Option, -) -> Result { - let pool = send::parse_change_pool(&fallback_change_pool)?; - let policy = send::SendPolicy { - trusted, - untrusted, - fallback_change_pool: pool, - pad_orchard_bundle, - spend_transparent: true, - allow_zero_conf_shielding: allow_zero_conf_shielding.unwrap_or(false), - spend_source: None, - }; - Ok(runtime::with_db(|db| { - let fee_zat = send::quote_shielding(db, &account_uuid, shielding_threshold_zat, policy)?; - Ok(serde_json::json!({ "feeZat": fee_zat }).to_string()) - })?) -} - /// 释放该账户**全部**被锁的 note,返回解锁数量。 /// /// 崩溃恢复用:`releaseReservation` 靠内存里的提案表定位,app / offscreen 重启后 @@ -687,6 +614,16 @@ pub fn pczt_shield_quote( /// 不要放进正常流程。 #[wasm_bindgen(js_name = clearLockedOutputs)] pub fn clear_locked_outputs(account_uuid: String) -> Result { + // 锁本身不算「忙」—— 它正是这里要清的东西。但已经发出去的交易算:解锁 + // 一批正在被一笔待广播交易花掉的 note,等于把它们放回可选池去双花。 + runtime::with_read_conn(|conn| { + guard::assert_idle( + conn, + Some(&account_uuid), + "clearLockedOutputs", + guard::LockPolicy::Ignored, + ) + })?; Ok(runtime::with_db(|db| { send::clear_locked_outputs(db, &account_uuid) })?) @@ -807,7 +744,32 @@ pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> { /// 返回 `true` 表示确实删掉了,`false` 表示本来就不存在(不算错误)。 #[wasm_bindgen(js_name = deleteWallet)] pub async fn delete_wallet(db_name: String) -> Result { - if runtime::open_db_name().as_deref() == Some(db_name.as_str()) { + if !storage::database_exists(&db_name).await? { + return Ok(false); + } + let is_open = runtime::open_db_name().as_deref() == Some(db_name.as_str()); + // 闸门要在关库之前读,而且按整库判:库里装着全部钱包的全部账户。 + // + // 读不出来就放行。这个接口的用途之一就是「库坏了,重置」,让一条查不动 + // 的 SQL 把修复入口也锁死,比漏判一笔在途交易更糟 —— 而库都读不了的时候, + // 那笔交易的状态本来也已经取不回来了。 + let idle = if is_open { + runtime::with_read_conn(|conn| { + guard::assert_idle(conn, None, "deleteWallet", guard::LockPolicy::Blocking) + }) + } else { + storage::open_connection(&db_name).and_then(|conn| { + guard::assert_idle(&conn, None, "deleteWallet", guard::LockPolicy::Blocking) + }) + }; + match idle { + Ok(()) => {} + Err(e) if e.code == ErrorCode::WalletBusy => return Err(e.into()), + Err(e) => { + tracing::warn!("deleteWallet idle check unreadable, deleting anyway: {e}"); + } + } + if is_open { runtime::close()?; } Ok(storage::delete_database(&db_name).await?) diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs index 5dd5da451..bff70376f 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs @@ -119,6 +119,8 @@ pub enum ErrorCode { InvalidReservationId, /// txid 格式不合法(不是 64 位 hex)。参数:`{ value }` 或 `{ value, byteLen }` InvalidTxid, + /// 宿主喂进来的透明 UTXO 快照解析失败。`detail` 里是 serde 的原文。 + InvalidTransparentUtxos, /// PCZT 解析或序列化失败。参数:`{ stage }` PcztError, /// 交易构造失败(选币、费用、anchor 等)。参数:`{ stage }` @@ -171,6 +173,7 @@ impl ErrorCode { NoActiveAccounts => "NO_ACTIVE_ACCOUNTS", InvalidReservationId => "INVALID_RESERVATION_ID", InvalidTxid => "INVALID_TXID", + InvalidTransparentUtxos => "INVALID_TRANSPARENT_UTXOS", PcztError => "PCZT_ERROR", TransactionBuildError => "TRANSACTION_BUILD_ERROR", BroadcastRejected => "BROADCAST_REJECTED", diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/guard.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/guard.rs new file mode 100644 index 000000000..86d8d85f8 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/guard.rs @@ -0,0 +1,290 @@ +//! 破坏性操作前的统一闸门。 +//! +//! 这些操作会丢掉扫描结果、账户或整个库。它们共用一个判断:钱包现在是不是 +//! 「闲着」—— 没有在途提案、没有未落块的花费、没有未确认结局的广播。 +//! +//! ## 为什么问库而不是问进程 +//! +//! 原来「有没有在途提案」问的是 `send` 里的进程内 map。Worker 一重启它就是 +//! 空的,闸门于是静默放行,而锁本身还在 SQLite 里 —— 正是「用户刷新了页面, +//! 然后点了删除」这条路。锁是持久化的,判断也必须是。 + +use serde_json::json; + +use crate::error::{ErrorCode, Result, RuntimeError}; +use crate::history::uuid_blob; + +/// 输出锁算不算「忙」。 +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum LockPolicy { + /// 未过期的锁就拒绝:可能有人正在证明或签名这批 note。 + Blocking, + /// 锁正是这个操作要清的东西,拿它当拒绝理由等于让修复按钮永远点不动。 + Ignored, +} + +/// 带锁的四张表。上游按池分表,锁列在每张表上各有一份。 +const LOCKABLE_TABLES: [&str; 4] = [ + "sapling_received_notes", + "orchard_received_notes", + "ironwood_received_notes", + "transparent_received_outputs", +]; + +fn db_err(operation: &str, error: impl std::fmt::Display) -> RuntimeError { + RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": operation })).detail(error) +} + +/// 链尖。与上游 `chain_tip_height` 同源:扫描区间是右开的,所以减一。 +fn chain_tip(conn: &rusqlite::Connection) -> Result> { + conn.query_row("SELECT MAX(block_range_end) FROM scan_queue", [], |row| { + row.get::<_, Option>(0) + }) + .map(|end| end.map(|h| h.saturating_sub(1))) + .map_err(|e| db_err("walletIdleChainTip", e)) +} + +/// 这个账户(`None` = 整个库)名下还有没有未过期的输出锁。 +fn has_live_locks(conn: &rusqlite::Connection, account_uuid: Option<&str>) -> Result { + // 链尖未知时不做过期判断:宁可报忙,也不要因为读不到高度就把一批 + // 正在签名的 note 判成空闲。 + let tip = chain_tip(conn)?; + let account_filter = account_uuid + .map(|uuid| uuid_blob(uuid).map(Some)) + .transpose()? + .flatten(); + for table in LOCKABLE_TABLES { + let sql = format!( + "SELECT EXISTS( + SELECT 1 + FROM {table} o + JOIN accounts a ON a.id = o.account_id + WHERE o.lock_owner IS NOT NULL + AND (?1 IS NULL OR a.uuid = ?1) + AND (?2 IS NULL OR o.lock_expiry_height IS NULL OR o.lock_expiry_height > ?2) + )" + ); + let found: bool = conn + .query_row(&sql, rusqlite::params![account_filter, tip], |row| { + row.get(0) + }) + .map_err(|e| db_err("walletIdleLocks", e))?; + if found { + return Ok(true); + } + } + Ok(false) +} + +/// 已花出去但还没落块、也还没过期的交易。回退或删除会把它的记录一起丢掉。 +fn has_unsettled_outgoing(conn: &rusqlite::Connection, account_uuid: Option<&str>) -> Result { + let account_filter = account_uuid + .map(|uuid| uuid_blob(uuid).map(Some)) + .transpose()? + .flatten(); + conn.query_row( + "SELECT EXISTS( + SELECT 1 + FROM v_transactions + WHERE (?1 IS NULL OR account_uuid = ?1) + AND mined_height IS NULL + AND expired_unmined = 0 + AND COALESCE(total_spent, 0) > 0 + )", + rusqlite::params![account_filter], + |row| row.get(0), + ) + .map_err(|e| db_err("walletIdleOutgoing", e)) +} + +/// 已授权广播、结局还没确定的交易。这份状态不是可重建的扫描缓存。 +fn has_unresolved_broadcast( + conn: &rusqlite::Connection, + account_uuid: Option<&str>, +) -> Result { + let account_filter = account_uuid + .map(|uuid| uuid_blob(uuid).map(Some)) + .transpose()? + .flatten(); + conn.query_row( + &format!( + "SELECT EXISTS( + SELECT 1 + FROM {table} state + LEFT JOIN v_transactions tx + ON tx.txid = state.txid AND tx.account_uuid = state.account_uuid + WHERE (?1 IS NULL OR state.account_uuid = ?1) + AND state.broadcast_state IN ('pending', 'accepted') + AND tx.mined_height IS NULL + AND COALESCE(tx.expired_unmined, 0) = 0 + )", + table = crate::tx_state::TABLE, + ), + rusqlite::params![account_filter], + |row| row.get(0), + ) + .map_err(|e| db_err("walletIdleBroadcast", e)) +} + +/// 钱包不空闲就拒绝。`account_uuid` 为 `None` 时判整个库 —— 回退和删库影响 +/// 的是共享库里的每一个账户,只看当前这个会漏掉别人的在途交易。 +pub fn assert_idle( + conn: &rusqlite::Connection, + account_uuid: Option<&str>, + operation: &str, + locks: LockPolicy, +) -> Result<()> { + let active_reservation = match locks { + LockPolicy::Blocking => has_live_locks(conn, account_uuid)?, + LockPolicy::Ignored => false, + }; + let unsettled_outgoing = has_unsettled_outgoing(conn, account_uuid)?; + let unresolved_broadcast = has_unresolved_broadcast(conn, account_uuid)?; + if !active_reservation && !unsettled_outgoing && !unresolved_broadcast { + return Ok(()); + } + Err(RuntimeError::with( + ErrorCode::WalletBusy, + json!({ + "operation": operation, + "activeReservation": active_reservation, + "unsettledOutgoing": unsettled_outgoing, + "unresolvedBroadcast": unresolved_broadcast, + }), + )) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use rusqlite::Connection; + + /// 在真实迁移出来的库上跑一遍。目的不是看结果,是证明**每条 SQL 的表名和 + /// 列名都真实存在** —— 写错的话 SQLite 在这里就报错,而不是等到线上把 + /// 「读不出来」当成「钱包空闲」然后删库。 + #[test] + fn every_query_matches_the_real_schema() { + let path = + std::env::temp_dir().join(format!("zr-guard-schema-{}.sqlite", uuid::Uuid::new_v4())); + let _ = std::fs::remove_file(&path); + drop(crate::wallet::open_and_migrate("test", path.to_str().unwrap()).expect("migrate")); + + let conn = crate::storage::open_connection(path.to_str().unwrap()).expect("open"); + let nil = uuid::Uuid::nil().to_string(); + for (account, locks) in [ + (None, LockPolicy::Blocking), + (None, LockPolicy::Ignored), + (Some(nil.as_str()), LockPolicy::Blocking), + (Some(nil.as_str()), LockPolicy::Ignored), + ] { + assert!(assert_idle(&conn, account, "schemaCheck", locks).is_ok()); + } + let _ = std::fs::remove_file(&path); + } + + fn fixture(conn: &Connection) { + conn.execute_batch( + "CREATE TABLE accounts (id INTEGER PRIMARY KEY, uuid BLOB); + CREATE TABLE scan_queue (block_range_end INTEGER); + CREATE VIEW v_transactions AS + SELECT NULL AS account_uuid, NULL AS txid, NULL AS mined_height, + 0 AS expired_unmined, 0 AS total_spent WHERE 0; + CREATE TABLE ext_onekey_tx_state ( + txid BLOB, account_uuid BLOB, broadcast_state TEXT + );", + ) + .unwrap(); + for table in LOCKABLE_TABLES { + conn.execute_batch(&format!( + "CREATE TABLE {table} ( + account_id INTEGER, lock_owner BLOB, lock_expiry_height INTEGER + );" + )) + .unwrap(); + } + conn.execute("INSERT INTO scan_queue VALUES (1001)", []) + .unwrap(); + for (id, uuid) in [(1, uuid::Uuid::from_u128(1)), (2, uuid::Uuid::from_u128(2))] { + conn.execute( + "INSERT INTO accounts VALUES (?1, ?2)", + rusqlite::params![id, uuid.as_bytes().to_vec()], + ) + .unwrap(); + } + } + + /// 这是整个改动的理由:锁在库里,进程内那张表重启就空了。 + #[test] + fn a_persisted_lock_blocks_the_account_that_holds_it() { + let conn = Connection::open_in_memory().unwrap(); + fixture(&conn); + let owner = uuid::Uuid::from_u128(1).to_string(); + let other = uuid::Uuid::from_u128(2).to_string(); + + // 还没有锁:谁都空闲。 + assert!(assert_idle(&conn, Some(&owner), "removeAccount", LockPolicy::Blocking).is_ok()); + + conn.execute( + "INSERT INTO orchard_received_notes VALUES (1, ?1, 1500)", + rusqlite::params![[7_u8; 32]], + ) + .unwrap(); + + let err = assert_idle(&conn, Some(&owner), "removeAccount", LockPolicy::Blocking) + .expect_err("a live lock must refuse a destructive operation"); + assert_eq!(err.code, ErrorCode::WalletBusy); + assert_eq!(err.params["activeReservation"], true); + assert_eq!(err.params["operation"], "removeAccount"); + + // 别人的账户不受影响;整库判则看得见。 + assert!(assert_idle(&conn, Some(&other), "removeAccount", LockPolicy::Blocking).is_ok()); + assert!(assert_idle(&conn, None, "rewindTo", LockPolicy::Blocking).is_err()); + + // clearLockedOutputs 清的就是它,不能拿它当拒绝理由。 + assert!(assert_idle( + &conn, + Some(&owner), + "clearLockedOutputs", + LockPolicy::Ignored + ) + .is_ok()); + } + + #[test] + fn an_expired_lock_no_longer_blocks() { + let conn = Connection::open_in_memory().unwrap(); + fixture(&conn); + let owner = uuid::Uuid::from_u128(1).to_string(); + // 链尖 1000(scan_queue 右开),过期高度 900 已经过去了。 + conn.execute( + "INSERT INTO orchard_received_notes VALUES (1, ?1, 900)", + rusqlite::params![[7_u8; 32]], + ) + .unwrap(); + assert!(assert_idle(&conn, Some(&owner), "removeAccount", LockPolicy::Blocking).is_ok()); + } + + /// 广播还没有结局的时候,连「修复」按钮也不能动锁 —— 解锁等于把正在被 + /// 一笔待确认交易花掉的 note 放回可选池。 + #[test] + fn an_unresolved_broadcast_blocks_even_the_repair_path() { + let conn = Connection::open_in_memory().unwrap(); + fixture(&conn); + let owner = uuid::Uuid::from_u128(1).to_string(); + conn.execute( + "INSERT INTO ext_onekey_tx_state VALUES (?1, ?2, 'pending')", + rusqlite::params![[9_u8; 32], uuid::Uuid::from_u128(1).as_bytes().to_vec()], + ) + .unwrap(); + let err = assert_idle( + &conn, + Some(&owner), + "clearLockedOutputs", + LockPolicy::Ignored, + ) + .expect_err("an unresolved broadcast must refuse"); + assert_eq!(err.code, ErrorCode::WalletBusy); + assert_eq!(err.params["unresolvedBroadcast"], true); + assert_eq!(err.params["activeReservation"], false); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs index c0d1dd0a4..c654d3ff9 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs @@ -50,24 +50,6 @@ fn db_err(e: impl std::fmt::Display) -> RuntimeError { RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": "history" })).detail(e) } -/// Whether deleting this account would discard a locally created outgoing -/// transaction that has not reached a terminal chain state yet. -pub fn has_unsettled_outgoing(conn: &rusqlite::Connection, account_uuid: &str) -> Result { - conn.query_row( - "SELECT EXISTS( - SELECT 1 - FROM v_transactions - WHERE account_uuid = ?1 - AND mined_height IS NULL - AND expired_unmined = 0 - AND COALESCE(total_spent, 0) > 0 - )", - rusqlite::params![uuid_blob(account_uuid)?], - |row| row.get(0), - ) - .map_err(db_err) -} - // Keep the list and detail endpoints on the exact same projection. `row_to_json` // intentionally has one shape; adding a field to only one query would otherwise // compile and then fail when the other endpoint reads a missing column at runtime. diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs index 150782948..d717894b3 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs @@ -26,6 +26,7 @@ pub mod account; pub mod blockcache; pub mod clock; pub mod error; +pub mod guard; pub mod history; pub mod send; pub mod stats; diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs index e1d0bf5c9..b06bcbd38 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs @@ -169,7 +169,7 @@ fn explain_insufficient( "shortfallZat": shortfall, "transparentZat": regular, // coinbase 单列:成熟规则不同,而且只能走专门的 coinbase 屏蔽路径, - // `pcztShield` 碰不到它。并成一个数的话,用户会照着提示去点屏蔽, + // 宿主的屏蔽碰不到它。并成一个数的话,用户会照着提示去点屏蔽, // 然后发现钱没动。 "transparentCoinbaseZat": coinbase, }), @@ -183,7 +183,10 @@ pub fn parse_change_pool(name: &str) -> Result { // 把它留作合法取值只为历史兼容,新交易不该用。 "ironwood" => Ok(ShieldedPool::Ironwood), "orchard" => Ok(ShieldedPool::Orchard), - "sapling" => Ok(ShieldedPool::Sapling), + // Sapling 不是合法的找零去处,理由和 `parse_spend_source` 拒它一样, + // 而且更硬:本方案裁掉了 Sapling 的 Groth16 证明参数,建不出 Sapling + // 输出。就算建得出,那笔找零也进了一个本钱包只读不可花的池子 —— + // 用户的找零会当场变成取不回来的钱。 other => Err(RuntimeError::with( ErrorCode::TransactionBuildError, json!({ "stage": "fallbackChangePool", "value": other }), @@ -227,7 +230,7 @@ pub struct SendPolicy { /// 关联起来;上游因此把它做成显式 opt-in,默认一个透明 UTXO 都不花。 /// /// 关着的后果是具体的:一个只有透明余额的账户**发不出任何款**, - /// 唯一出口是先 `pcztShield` 屏蔽(多一笔交易、多一份手续费、多一次等待)。 + /// 唯一出口是先屏蔽(多一笔交易、多一份手续费、多一次等待)。 pub spend_transparent: bool, /// 零确认的自家屏蔽产出允不允许立刻再花(ZIP-315 建议允许)。 /// @@ -266,12 +269,62 @@ impl SendPolicy { } } +/// 从宿主传来的原始参数造一份发送策略。 +/// +/// **报价和真正构造必须走这一个入口。** 两边各拼一次 `SendPolicy`,迟早会出现 +/// 某个字段只在一边接上:`pad_orchard_bundle` 就是这样 —— 报价那边曾经固定写 +/// `false`,而它会改变 Orchard bundle 的大小、进而改变 ZIP-317 手续费。当时 +/// 宿主的常量也是 `false`,所以对得上;等哪天真去打开这个产品开关,报出来的 +/// 费用就会比实付的低,而且没有任何东西会报错。 +#[allow(clippy::too_many_arguments)] +pub fn parse_send_policy( + trusted: u32, + untrusted: u32, + fallback_change_pool: &str, + pad_orchard_bundle: bool, + spend_transparent: Option, + allow_zero_conf_shielding: Option, + spend_source: Option<&str>, +) -> Result { + Ok(SendPolicy { + trusted, + untrusted, + fallback_change_pool: parse_change_pool(fallback_change_pool)?, + pad_orchard_bundle, + spend_transparent: spend_transparent.unwrap_or(false), + allow_zero_conf_shielding: allow_zero_conf_shielding.unwrap_or(false), + spend_source: parse_spend_source(spend_source)?, + }) +} + /// 一次转账提案。`create_pczt` 与 `quote` 共用 —— 两者的选币、费率、找零策略 /// 必须完全一致,否则报价和实际构造会对不上,用户看到的费用就是假的。 type TransferProposal = zcash_client_backend::proposal::Proposal; -type ShieldingProposal = - zcash_client_backend::proposal::Proposal; + +/// 这个收款地址收不收得进屏蔽池。 +/// +/// 不认识的 receiver 类型算「收得进」:UA 里可能有本 crate 的 `zcash_address` +/// 还不认识的池子,把它判成纯透明会拒掉一笔合法的屏蔽转账 —— 比放过一笔 +/// 公开转账更糟。 +fn recipient_accepts_shielded( + params: &zcash_protocol::consensus::Network, + recipient: &zcash_address::ZcashAddress, +) -> Result { + use zcash_keys::address::Address; + let parsed = Address::try_from_zcash_address(params, recipient.clone()).map_err(|e| { + RuntimeError::with( + ErrorCode::InvalidAddress, + json!({ "stage": "recipientKind" }), + ) + .detail(format!("{e:?}")) + })?; + Ok(match parsed { + Address::Transparent(_) | Address::Tex(_) => false, + Address::Sapling(_) => true, + Address::Unified(ua) => ua.has_orchard() || ua.has_sapling() || !ua.unknown().is_empty(), + }) +} fn build_proposal( db: &mut Db, @@ -310,6 +363,20 @@ fn build_proposal( } }; + // 花透明输入换来的隐私代价,只有在收款方是屏蔽地址时才买到了东西: + // 那笔钱进了池子。收款方只能收透明时,这笔交易从头到尾公开,被选中的 + // 透明地址还白白关联到了收款方 —— 用户为一个不存在的收益付了隐私。 + // + // 宿主本来就只在收款方是屏蔽地址时才打开这个开关(见 + // `shouldPreferTransparentForShieldedSend`)。这里是拦宿主的 bug: + // 这个开关的代价是用户看不见的,不能靠调用方自觉。 + if policy.spend_transparent && !recipient_accepts_shielded(¶ms, &recipient)? { + return Err(RuntimeError::with( + ErrorCode::TransactionBuildError, + json!({ "stage": "spendTransparent", "reason": "transparentOnlyRecipient" }), + )); + } + // Payment::new 会自己校验「透明地址不能带 memo」这类约束。 let payment = zip321::Payment::new(recipient, Some(amount), memo_bytes, None, None, vec![]) .map_err(|e| { @@ -526,7 +593,6 @@ pub fn release_reservation(db: &mut Db, reservation_id: &str) -> Result { return Ok(false); } - // 转账与屏蔽的提案类型不同,分两张表存;两边都要查,否则取消屏蔽时锁放不开。 if let Some((account_uuid, proposal)) = RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id)) { @@ -539,19 +605,81 @@ pub fn release_reservation(db: &mut Db, reservation_id: &str) -> Result { } return Ok(true); } - if let Some((account_uuid, proposal)) = - SHIELD_RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id)) - { - if let Err(e) = unlock_proposal_inputs(db, &proposal, owner) { - SHIELD_RESERVATIONS.with(|r| { - r.borrow_mut() - .insert(reservation_id.to_owned(), (account_uuid, proposal)); - }); - return Err(build_err("unlockProposalInputs", format!("{e:?}"))); + release_persisted_reservation(db, reservation_id, owner) +} + +// The proposal map is process-local, but the lock owner survives in SQLite. +// Read the owner's exact output references and use the upstream lock API; +// never clear another proposal's locks or write wallet-owned tables directly. +fn release_persisted_reservation( + db: &mut Db, + reservation_id: &str, + owner: LockOwner, +) -> Result { + use rusqlite::OptionalExtension; + use zcash_client_backend::{data_api::OutputLockStore, wallet::OutputRef}; + use zcash_primitives::transaction::TxId; + use zcash_protocol::PoolType; + + db.transactionally_with_extension(|wallet, ext| { + if tx_state::existing_txid_for_reservation(ext, reservation_id)?.is_some() { + return Ok(false); } - return Ok(true); - } - Ok(false) + let mut released = false; + for (table, index, pool) in [ + ( + "sapling_received_notes", + "output_index", + PoolType::Shielded(ShieldedPool::Sapling), + ), + ( + "orchard_received_notes", + "action_index", + PoolType::Shielded(ShieldedPool::Orchard), + ), + ( + "ironwood_received_notes", + "action_index", + PoolType::Shielded(ShieldedPool::Ironwood), + ), + ( + "transparent_received_outputs", + "output_index", + PoolType::Transparent, + ), + ] { + loop { + let output = ext + .query_row( + &format!( + "SELECT tx.txid, output.{index} + FROM {table} output + JOIN transactions tx ON tx.id_tx = output.transaction_id + WHERE output.lock_owner = ?1 LIMIT 1" + ), + [owner.as_bytes()], + |row| Ok((row.get::<_, [u8; 32]>(0)?, row.get::<_, u32>(1)?)), + ) + .optional() + .map_err(|e| build_err("readReservationLocks", e))?; + let Some((txid, output_index)) = output else { + break; + }; + let output = OutputRef::new(TxId::from_bytes(txid), pool, output_index); + if !wallet + .unlock_output(&output, owner) + .map_err(|e| build_err("releaseReservationLock", e))? + { + return Err(build_err( + "releaseReservationLock", + "persisted lock was not released", + )); + } + released = true; + } + } + Ok(released) + }) } /// 交易已落库后丢弃 reservation 记录。 @@ -560,24 +688,6 @@ pub fn release_reservation(db: &mut Db, reservation_id: &str) -> Result { /// 解锁会把已经花出去的 note 重新放回可选池。 pub fn forget_reservation(reservation_id: &str) { RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id)); - SHIELD_RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id)); -} - -/// Whether this process still owns an in-flight proposal for the account. -/// Account repair must not delete the account while such a proposal exists: -/// the caller still holds its reservation id and may be proving or signing it. -pub fn has_active_reservations(account_uuid: &str) -> bool { - RESERVATIONS.with(|reservations| { - reservations - .borrow() - .values() - .any(|(owner_account_uuid, _)| owner_account_uuid == account_uuid) - }) || SHIELD_RESERVATIONS.with(|reservations| { - reservations - .borrow() - .values() - .any(|(owner_account_uuid, _)| owner_account_uuid == account_uuid) - }) } /// 构造一笔转账的 PCZT(未签名),并**锁住选中的 note**。 @@ -691,7 +801,22 @@ fn circuit_version_for( /// 给 PCZT 生成 Orchard / Ironwood 零知识证明。 /// 合并两份同一笔交易的 PCZT(本地完整副本 + 外部签名器返回的脱敏副本)。 +/// 合并硬件回传的签名副本。**只许补签名,不许改交易。** +/// +/// 别指望后面那一步兜底:`TransactionExtractor` 是拿**合并后**的交易重算 sighash +/// 再验签名,它只回答「这笔交易自洽吗」,不知道用户批准过什么。 +/// +/// 裸 `Combiner` 目前挡得住换交易,但那是两条上游性质的副作用,不是本 crate 的 +/// 声明:一是我们构造的 PCZT `tx_modifiable == 0`,不可增删输入/输出/action; +/// 二是效果字段全部已填,冲突会被逐字段查出来。两条都属于上游,升级就可能变。 +/// +/// 所以把不变量写在这里:合并前后 sighash 必须逐字节相同,且 `scriptSig` 必须仍为 +/// 空 —— 它不进 sighash,又恰好是原件里为 `None`、会被 `merge_optional` 直接采纳的 +/// 字段,是这层唯一真正漏着的口子。失败发生在昂贵的证明之前,错误带 `field`。 pub fn combine_pczt(original: &[u8], signed: &[u8]) -> Result> { + use pczt::roles::signer::Signer; + use pczt::roles::verifier::{TransparentError, Verifier}; + let parse = |bytes: &[u8], which: &str| { pczt::Pczt::parse(bytes).map_err(|error| { RuntimeError::with( @@ -701,14 +826,91 @@ pub fn combine_pczt(original: &[u8], signed: &[u8]) -> Result> { .detail(format!("{error:?}")) }) }; + let signer = |pczt: pczt::Pczt, which: &str| { + Signer::new(pczt).map_err(|error| { + RuntimeError::with( + ErrorCode::PcztError, + json!({ "stage": "signer", "which": which }), + ) + .detail(format!("{error:?}")) + }) + }; + let mismatch = |field: &str| { + RuntimeError::with( + ErrorCode::PcztError, + json!({ + "stage": "combine", + "reason": "signedPcztChangedTheTransaction", + "field": field, + }), + ) + }; + let original = parse(original, "original")?; let signed = parse(signed, "signed")?; + let transparent_inputs = original.transparent().inputs().len(); + let approved = signer(original.clone(), "original")?; + let combined = pczt::roles::combiner::Combiner::new(vec![original, signed]) .combine() .map_err(|error| { RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "combine" })) .detail(format!("{error:?}")) })?; + let result = signer(combined.clone(), "combined")?; + + if result.shielded_sighash() != approved.shielded_sighash() { + return Err(mismatch("shieldedSighash")); + } + if combined.transparent().inputs().len() != transparent_inputs { + return Err(mismatch("transparentInputCount")); + } + for index in 0..transparent_inputs { + let approved_sighash = approved.transparent_sighash(index).map_err(|error| { + RuntimeError::with( + ErrorCode::PcztError, + json!({ "stage": "transparentSighash", "which": "original" }), + ) + .detail(format!("{error:?}")) + })?; + let combined_sighash = result.transparent_sighash(index).map_err(|error| { + RuntimeError::with( + ErrorCode::PcztError, + json!({ "stage": "transparentSighash", "which": "combined" }), + ) + .detail(format!("{error:?}")) + })?; + if approved_sighash != combined_sighash { + return Err(mismatch("transparentSighash")); + } + } + // sighash 不覆盖 scriptSig,而它正是合并里唯一能被对方无中生有填上的字段 + // (原件恒为 None,merge_optional 会直接采纳)。我们自己从不填:提取时 + // SpendFinalizer 才从 partial_signatures 拼出来。 + // 在副本上查 —— Verifier 会把 bundle 解析再序列化回去,不能动待序列化的那份。 + if transparent_inputs > 0 { + Verifier::new(combined.clone()) + .with_transparent(|bundle| { + if bundle + .inputs() + .iter() + .any(|input| input.script_sig().is_some()) + { + Err(TransparentError::Custom(())) + } else { + Ok(()) + } + }) + .map_err(|error| match error { + TransparentError::Custom(()) => mismatch("transparentScriptSig"), + other => RuntimeError::with( + ErrorCode::PcztError, + json!({ "stage": "verifyTransparent" }), + ) + .detail(format!("{other:?}")), + })?; + } + combined.serialize().map_err(|error| { RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "serialize" })) .detail(format!("{error:?}")) @@ -847,203 +1049,318 @@ pub const PROVE_ORCHARD: bool = true; pub const PROVE_SAPLING: bool = false; pub const PROVE_IRONWOOD: bool = true; -/// 构造一笔「屏蔽全部透明余额」的 PCZT,并锁住选中的透明 UTXO。 -/// -/// ## 为什么它不是普通转账 -/// -/// 钱落在 t 地址那一刻就和用户公开绑定了。屏蔽是把它搬进隐私池, -/// 让之后的花费别人看不见。所以它: -/// -/// - **没有收款地址** —— 收款方就是本账户自己的屏蔽地址 -/// - **没有金额** —— 扫走全部透明余额。留零头等于白搭:它照样公开, -/// 将来还要再付一次手续费才能搬走 -/// -/// `shielding_threshold` 是宿主的策略:透明余额低于它就不值得屏蔽(手续费可能 -/// 超过金额本身)。低于阈值时上游报「余额不足」,我们照常映射成 -/// `INSUFFICIENT_FUNDS`,宿主可据此提示「金额太小,暂不值得屏蔽」。 -/// -/// 只屏蔽非 coinbase 输出:coinbase 有单独的成熟度规则,上游要求走 -/// `propose_shielding_coinbase`。矿工场景不在本钱包的目标内。 -fn build_shielding_proposal( - db: &mut Db, - account_uuid: &str, - shielding_threshold_zat: u64, - policy: SendPolicy, - lock: Option, -) -> Result { - use zcash_client_backend::data_api::wallet::propose_shielding; - use zcash_client_backend::data_api::CoinbaseFilter; +/// Clears all advisory locks for an account during explicit state repair. +/// Normal cancellation uses the durable owner-scoped `release_reservation`, +/// including after restart. This broader operation also clears other proposals +/// and must not be used as an automatic cancellation fallback. +pub fn clear_locked_outputs(db: &mut Db, account_uuid: &str) -> Result { + use zcash_client_backend::data_api::OutputLockStore; - let params = *db.params(); let account_id = account::parse_account_id(db, account_uuid)?; + let n = db + .clear_locked_outputs(account_id) + .map_err(|e| build_err("clearLockedOutputs", e))?; - let threshold = Zatoshis::from_u64(shielding_threshold_zat).map_err(|_| { - RuntimeError::with( - ErrorCode::AmountOutOfRange, - json!({ "valueZat": shielding_threshold_zat }), + RESERVATIONS.with(|r| { + r.borrow_mut() + .retain(|_, (owner_account_uuid, _)| owner_account_uuid != account_uuid); + }); + Ok(n as u32) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod reservation_recovery_tests { + use super::*; + use rand::SeedableRng; + use rand_chacha::ChaCha20Rng; + use rusqlite::Connection; + use zcash_client_sqlite::WalletDb; + use zcash_protocol::consensus::Network; + + fn wallet(conn: Connection) -> Db { + WalletDb::from_connection( + conn, + Network::TestNetwork, + crate::clock::HostClock, + ChaCha20Rng::from_seed([0; 32]), ) - })?; + } - // 本账户名下全部透明收款地址(含找零与独立地址)—— 屏蔽是「扫干净」, - // 漏掉任何一个地址都会留下公开残额。 - let receivers = db - .get_transparent_receivers(account_id, true, true) - .map_err(|e| build_err("getTransparentReceivers", e))?; - if receivers.is_empty() { - return Err(RuntimeError::with( - ErrorCode::InsufficientFunds, - json!({ "availableZat": 0, "requiredZat": shielding_threshold_zat, "reason": "noTransparentAddress" }), - )); + #[test] + fn restart_cancellation_releases_only_its_owner_and_preserves_finalized_locks() { + let path = + std::env::temp_dir().join(format!("zcash-reservation-{}.sqlite", uuid::Uuid::new_v4())); + let owner = [1_u8; 32]; + let other_owner = [2_u8; 32]; + let conn = Connection::open(&path).unwrap(); + conn.execute_batch( + "CREATE TABLE transactions (id_tx INTEGER PRIMARY KEY, txid BLOB); + CREATE TABLE ext_onekey_tx_state (txid BLOB, reservation_id TEXT);", + ) + .unwrap(); + conn.execute("INSERT INTO transactions VALUES (1, ?1)", [[3_u8; 32]]) + .unwrap(); + for (table, index) in [ + ("sapling_received_notes", "output_index"), + ("orchard_received_notes", "action_index"), + ("ironwood_received_notes", "action_index"), + ("transparent_received_outputs", "output_index"), + ] { + conn.execute_batch(&format!( + "CREATE TABLE {table} ( + transaction_id INTEGER, {index} INTEGER, lock_owner BLOB, lock_expiry_height INTEGER + );" + )) + .unwrap(); + conn.execute( + &format!("INSERT INTO {table} VALUES (1, 0, ?1, 1000), (1, 1, ?2, 1000)"), + rusqlite::params![owner, other_owner], + ) + .unwrap(); + } + drop(wallet(conn)); + + let mut db = wallet(Connection::open(&path).unwrap()); + assert!(release_reservation(&mut db, &hex32(&owner)).unwrap()); + assert!(!release_reservation(&mut db, &hex32(&owner)).unwrap()); + let conn = Connection::open(&path).unwrap(); + for table in [ + "sapling_received_notes", + "orchard_received_notes", + "ironwood_received_notes", + "transparent_received_outputs", + ] { + let locks: u32 = conn.query_row(&format!("SELECT COUNT(*) FROM {table} WHERE lock_owner = ?1 AND lock_expiry_height = 1000"), [other_owner], |row| row.get(0)).unwrap(); + assert_eq!(locks, 1); + let released: u32 = conn.query_row(&format!("SELECT COUNT(*) FROM {table} WHERE lock_owner IS NULL AND lock_expiry_height IS NULL"), [], |row| row.get(0)).unwrap(); + assert_eq!(released, 1); + } + conn.execute( + "INSERT INTO ext_onekey_tx_state VALUES (?1, ?2)", + rusqlite::params![[4_u8; 32], hex32(&other_owner)], + ) + .unwrap(); + assert!(!release_reservation(&mut db, &hex32(&other_owner)).unwrap()); + let locks: u32 = conn + .query_row( + "SELECT COUNT(*) FROM orchard_received_notes WHERE lock_owner = ?1", + [other_owner], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(locks, 1); + drop(conn); + drop(db); + std::fs::remove_file(path).unwrap(); } - let from_addrs: Vec<_> = receivers.keys().copied().collect(); +} - let confirmations = account::confirmations_policy( - policy.trusted, - policy.untrusted, - policy.allow_zero_conf_shielding, - )?; - let selector = GreedyInputSelector::::new(); - let change = SingleOutputChangeStrategy::<_, Db>::new( - Zip317FeeRule::standard(), - None, - policy.change_pool(), - DustOutputPolicy::default(), - ); +#[cfg(all(test, not(target_arch = "wasm32")))] +mod policy_tests { + use super::*; + use zcash_address::ZcashAddress; + use zcash_keys::keys::{UnifiedAddressRequest, UnifiedSpendingKey}; + use zcash_protocol::consensus::Network; - propose_shielding::( - db, - ¶ms, - &selector, - &change, - threshold, - &from_addrs, - account_id, - confirmations, - CoinbaseFilter::NonCoinbaseOnly, - lock, - ) - .map_err(|e| propose_err("proposeShielding", e)) -} + fn parse(encoded: &str) -> ZcashAddress { + ZcashAddress::try_from_encoded(encoded).expect("a valid address") + } -/// Exact ZIP-317 fee for the same sweep proposal used by `create_shielding_pczt`. -/// It does not lock transparent UTXOs or construct a PCZT. -pub fn quote_shielding( - db: &mut Db, - account_uuid: &str, - shielding_threshold_zat: u64, - policy: SendPolicy, -) -> Result { - let proposal = - build_shielding_proposal(db, account_uuid, shielding_threshold_zat, policy, None)?; - Ok(proposal - .steps() - .iter() - .map(|step| u64::from(step.balance().fee_required())) - .sum()) -} + /// Sapling 在这两处都不是合法取值,理由不同但结论一样:证明建不出来, + /// 而且找零会落进一个只读不可花的池子。 + #[test] + fn sapling_is_not_a_spendable_source_nor_a_change_destination() { + assert!(parse_change_pool("ironwood").is_ok()); + assert!(parse_change_pool("orchard").is_ok()); + assert!(parse_change_pool("sapling").is_err()); + assert!(parse_spend_source(Some("sapling")).is_err()); + } -pub fn create_shielding_pczt( - db: &mut Db, - account_uuid: &str, - shielding_threshold_zat: u64, - policy: SendPolicy, - lock_for_blocks: u32, - reservation_id: Option<&str>, -) -> Result<(Vec, String, u64)> { - let params = *db.params(); - let account_id = account::parse_account_id(db, account_uuid)?; - let owner = match reservation_id { - Some(id) => parse_owner(id)?, - None => LockOwner::random(&mut rand::rngs::OsRng), - }; - let reservation_id = hex32(owner.as_bytes()); - let proposal = build_shielding_proposal( - db, - account_uuid, - shielding_threshold_zat, - policy, - Some(LockRequest::new(owner, lock_for_blocks)), - )?; - let fee_zat = proposal - .steps() - .iter() - .map(|step| u64::from(step.balance().fee_required())) - .sum(); + #[test] + fn only_a_shielded_recipient_justifies_spending_transparent_inputs() { + let params = Network::MainNetwork; + let taddr = ::transparent::address::TransparentAddress::PublicKeyHash([3; 20]); - // 同 create_pczt:提案已锁 note,之后失败必须先解锁再返回。 - let built = (|| -> Result> { - let pczt = create_pczt_from_proposal::< - Db, - _, - std::convert::Infallible, - _, - std::convert::Infallible, - _, - >( - db, + // 裸 t 地址、TEX 地址:整笔交易公开,花透明输入换不到任何隐私。 + let t_encoded = zcash_keys::encoding::encode_transparent_address_p(¶ms, &taddr); + assert!(!recipient_accepts_shielded(¶ms, &parse(&t_encoded)).unwrap()); + + let tex = zcash_keys::address::Address::Tex([3; 20]) + .to_zcash_address(¶ms) + .encode(); + assert!(!recipient_accepts_shielded(¶ms, &parse(&tex)).unwrap()); + + // UA:钱进了屏蔽池,这才是这个开关买到的东西。 + let ua = UnifiedSpendingKey::from_seed( ¶ms, - account_id, - OvkPolicy::Sender, - &proposal, - None, - policy.padding(), + &[7u8; 32], + 0u32.try_into().expect("valid ZIP-32 account index"), ) - .map_err(|e| build_err("createShieldingPczt", format!("{e:?}")))?; + .expect("test seed derives a USK") + .to_unified_full_viewing_key() + .default_address(UnifiedAddressRequest::ALLOW_ALL) + .expect("a default unified address") + .0 + .encode(¶ms); + assert!(recipient_accepts_shielded(¶ms, &parse(&ua)).unwrap()); + } +} - pczt.serialize().map_err(|e| { - RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "serialize" })) - .detail(format!("{e:?}")) - }) - })(); +#[cfg(all(test, not(target_arch = "wasm32")))] +mod combine_tests { + use super::*; + use pczt::roles::{ + creator::Creator, io_finalizer::IoFinalizer, signer::Signer, + spend_finalizer::SpendFinalizer, + }; + use transparent::address::TransparentAddress; + use transparent::bundle::{OutPoint, TxOut}; + use zcash_primitives::transaction::builder::{BuildConfig, Builder}; + use zcash_protocol::consensus::{BlockHeight, Network}; - let bytes = match built { - Ok(b) => b, - Err(e) => { - let _ = unlock_proposal_inputs(db, &proposal, owner); - return Err(e); + fn secret_key() -> secp256k1::SecretKey { + secp256k1::SecretKey::from_slice(&[0x11; 32]).unwrap() + } + + /// A transparent-only PCZT, io-finalized. `extra` appends a second + /// input/output pair; the first pair stays byte-identical so the two PCZTs + /// still merge. + /// + /// Transparent-only is deliberate. `IoFinalizer` clears the three + /// `tx_modifiable` flags ONLY when the transaction has shielded spends or + /// outputs (io_finalizer/mod.rs:70), so a transparent-only PCZT stays + /// modifiable and the bare Combiner will happily append the other side's + /// extra inputs, outputs and Orchard actions. + fn transparent_pczt(send_zat: u64, recipient: u8, extra: bool) -> Vec { + let secp = secp256k1::Secp256k1::new(); + let pubkey = secp256k1::PublicKey::from_secret_key(&secp, &secret_key()); + let from = TransparentAddress::from_pubkey(&pubkey); + let mut builder = Builder::new( + Network::MainNetwork, + BlockHeight::from_u32(3_000_000), + BuildConfig::Standard { + sapling_anchor: None, + orchard_anchor: None, + ironwood_anchor: None, + orchard_padding: BundlePadding::DEFAULT, + ironwood_padding: BundlePadding::DEFAULT, + }, + ); + let input = |index: u8, value: u64, builder: &mut Builder| { + builder + .add_transparent_p2pkh_input( + pubkey, + OutPoint::new([index; 32], 0), + TxOut::new(Zatoshis::const_from_u64(value), from.script().into()), + ) + .unwrap(); + }; + input(7, 100_000, &mut builder); + if extra { + input(9, 50_000, &mut builder); } - }; + builder + .add_transparent_output( + &TransparentAddress::PublicKeyHash([recipient; 20]), + Zatoshis::const_from_u64(send_zat), + ) + .unwrap(); + if extra { + builder + .add_transparent_output( + &TransparentAddress::PublicKeyHash([0xcc; 20]), + Zatoshis::const_from_u64(50_000), + ) + .unwrap(); + } + let parts = builder + .build_for_pczt(rand::rngs::OsRng, &Zip317FeeRule::standard()) + .unwrap(); + let pczt = Creator::build_from_parts(parts.pczt_parts).unwrap(); + IoFinalizer::new(pczt) + .finalize_io() + .unwrap() + .serialize() + .unwrap() + } - SHIELD_RESERVATIONS.with(|r| { - r.borrow_mut() - .insert(reservation_id.clone(), (account_uuid.to_owned(), proposal)); - }); - Ok((bytes, reservation_id, fee_zat)) -} + fn signed_copy(original: &[u8]) -> Vec { + let mut signer = Signer::new(pczt::Pczt::parse(original).unwrap()).unwrap(); + for index in 0..pczt::Pczt::parse(original) + .unwrap() + .transparent() + .inputs() + .len() + { + signer.sign_transparent(index, &secret_key()).unwrap(); + } + signer.finish().serialize().unwrap() + } -// 屏蔽提案的 NoteRef 类型与转账不同(Infallible),所以单独存一张表。 -thread_local! { - static SHIELD_RESERVATIONS: std::cell::RefCell< - std::collections::HashMap, - > = std::cell::RefCell::new(std::collections::HashMap::new()); -} + fn reason(error: &RuntimeError) -> String { + format!("{error:?}") + } -/// 释放某账户当前被锁住的**全部** note。 -/// -/// ## 为什么需要它 -/// -/// `releaseReservation` 靠内存里的提案表定位要解锁哪些 note。app 或 offscreen -/// 重启后那张表就没了 —— 此时旧的 reservationId 既解不开锁,也无从知道锁了什么, -/// 那批 note 会一直冻到过期。 -/// -/// 这是宿主的「状态修复」入口:不需要 token,直接把该账户名下所有锁清掉。 -/// 代价是会连带放开**正在进行中**的提案,所以只该由用户主动触发的修复动作调用, -/// 不能在正常流程里用。 -pub fn clear_locked_outputs(db: &mut Db, account_uuid: &str) -> Result { - use zcash_client_backend::data_api::OutputLockStore; + #[test] + fn combining_a_signature_copy_keeps_the_approved_transaction() { + let original = transparent_pczt(90_000, 0xaa, false); + let combined = combine_pczt(&original, &signed_copy(&original)).unwrap(); + let approved = Signer::new(pczt::Pczt::parse(&original).unwrap()).unwrap(); + let result = Signer::new(pczt::Pczt::parse(&combined).unwrap()).unwrap(); + assert_eq!(result.shielded_sighash(), approved.shielded_sighash()); + } - let account_id = account::parse_account_id(db, account_uuid)?; - let n = db - .clear_locked_outputs(account_id) - .map_err(|e| build_err("clearLockedOutputs", e))?; + // Conflicting values on a field both sides carry: the bare Combiner already + // refuses this one. Pinned so a future upstream bump cannot quietly relax it. + #[test] + fn combine_rejects_a_conflicting_recipient() { + let approved = transparent_pczt(90_000, 0xaa, false); + let other = transparent_pczt(90_000, 0xbb, false); + let error = combine_pczt(&approved, &signed_copy(&other)).unwrap_err(); + assert!( + reason(&error).contains("DataMismatch"), + "{}", + reason(&error) + ); + } - RESERVATIONS.with(|r| { - r.borrow_mut() - .retain(|_, (owner_account_uuid, _)| owner_account_uuid != account_uuid); - }); - SHIELD_RESERVATIONS.with(|r| { - r.borrow_mut() - .retain(|_, (owner_account_uuid, _)| owner_account_uuid != account_uuid); - }); - Ok(n as u32) + // What actually stops a counterparty from appending an input, output or + // Orchard action: `tx_modifiable` is already 0 on anything our pipeline + // builds, and the Combiner refuses to grow a non-modifiable bundle. That is + // upstream's behaviour, not ours, so pin it -- the sighash comparison in + // `combine_pczt` is what still covers us if a future bump relaxes it. + #[test] + fn our_pczts_are_not_modifiable_so_the_combiner_refuses_to_grow_them() { + let approved = transparent_pczt(90_000, 0xaa, false); + let enlarged = transparent_pczt(90_000, 0xaa, true); + let global = pczt::Pczt::parse(&approved).unwrap(); + let global = global.global(); + assert!(!global.inputs_modifiable()); + assert!(!global.outputs_modifiable()); + assert!(!global.shielded_modifiable()); + let error = combine_pczt(&approved, &signed_copy(&enlarged)).unwrap_err(); + assert!( + reason(&error).contains("DataMismatch"), + "{}", + reason(&error) + ); + } + + #[test] + fn combine_rejects_a_copy_that_already_carries_a_script_sig() { + // script_sig is absent from the sighash and absent from our original, so + // the bare Combiner would adopt whatever the other side put there. + let original = transparent_pczt(90_000, 0xaa, false); + let finalized = SpendFinalizer::new(pczt::Pczt::parse(&signed_copy(&original)).unwrap()) + .finalize_spends() + .unwrap() + .serialize() + .unwrap(); + let error = combine_pczt(&original, &finalized).unwrap_err(); + assert!( + reason(&error).contains("transparentScriptSig"), + "{}", + reason(&error) + ); + } } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs index ef0e7d223..e91d06894 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs @@ -26,13 +26,19 @@ use zcash_client_backend::data_api::chain::error::Error as ChainError; use zcash_client_backend::data_api::chain::{ BlockCache, BlockSource, ChainState, CommitmentTreeRoot, }; +use zcash_client_backend::data_api::ll::{LowLevelWalletRead, LowLevelWalletWrite}; use zcash_client_backend::data_api::scanning::{ScanPriority, ScanRange}; -use zcash_client_backend::data_api::{WalletCommitmentTrees, WalletRead, WalletWrite}; +use zcash_client_backend::data_api::{ + OutputStatusFilter, TransactionDataRequest, TransactionStatus, TransactionStatusFilter, + WalletCommitmentTrees, WalletRead, WalletWrite, +}; use zcash_client_backend::proto::service; use zcash_client_backend::scanning::{scan_block, Nullifiers, ScanningKeys}; +use zcash_client_sqlite::util::Clock; use zcash_keys::keys::UnifiedFullViewingKey; use zcash_primitives::merkle_tree::HashSer; -use zcash_protocol::consensus::{BlockHeight, NetworkUpgrade, Parameters}; +use zcash_primitives::transaction::Transaction; +use zcash_protocol::consensus::{BlockHeight, BranchId, NetworkUpgrade, Parameters}; use crate::blockcache::MemoryBlockCache; use crate::error::{ErrorCode, Result, RuntimeError}; @@ -857,101 +863,445 @@ pub fn queue_rescan_from(db: &mut Db, from_height: u32) -> Result { .to_string()) } -/// 刷新账户的透明 UTXO。 +// A UTXO reply does not identify coinbase transactions. Validate its complete +// parent before inserting the output so NonCoinbaseOnly never sees an unknown +// parent as an ordinary transaction. +fn decode_mined_transaction( + params: &zcash_protocol::consensus::Network, + raw: &service::RawTransaction, +) -> Result<(Transaction, BlockHeight)> { + let height = u32::try_from(raw.height) + .ok() + .filter(|height| *height > 0) + .map(BlockHeight::from_u32) + .ok_or_else(|| net_err("transparentTransaction", "missing main-chain height"))?; + let mut bytes = raw.data.as_slice(); + let tx = Transaction::read(&mut bytes, BranchId::for_height(params, height)) + .map_err(|e| net_err("transparentTransaction", e))?; + if !bytes.is_empty() { + return Err(net_err( + "transparentTransaction", + "trailing transaction data", + )); + } + Ok((tx, height)) +} + +fn validate_transparent_parent( + tx: &Transaction, + txid: &[u8; 32], + index: u32, + txout: &::transparent::bundle::TxOut, +) -> Result<()> { + if tx.txid().as_ref() != txid { + return Err(net_err("transparentParent", "transaction id mismatch")); + } + let output = tx + .transparent_bundle() + .and_then(|bundle| bundle.vout.get(index as usize)); + if output != Some(txout) { + return Err(net_err( + "transparentParent", + "output value or script mismatch", + )); + } + Ok(()) +} + +fn store_account_transaction( + db: &mut Db, + account_id: ::AccountId, + tx: &Transaction, + height: BlockHeight, + received: Option< + &zcash_client_backend::wallet::WalletTransparentOutput<::AccountId>, + >, +) -> Result<()> { + // The high-level decrypted transaction writer detects inputs and outputs + // across every wallet account, even when its decryption key set is scoped. + // This transparent-only path changes spentness only for the active owner. + db.transactionally(|wallet| { + let tx_ref = wallet.put_tx_data(tx, None, None, None, height)?; + LowLevelWalletWrite::set_transaction_status( + wallet, + tx.txid(), + TransactionStatus::Mined(height), + )?; + if let Some(output) = received { + WalletWrite::put_received_transparent_utxo(wallet, output)?; + } + if let Some(bundle) = tx.transparent_bundle() { + for (index, _) in bundle.vout.iter().enumerate() { + let outpoint = + ::transparent::bundle::OutPoint::new(*tx.txid().as_ref(), index as u32); + if let Some(output) = wallet.get_wallet_transparent_output(&outpoint, None)? { + if output.recipient_account() == Some(&account_id) { + wallet.queue_transparent_spend_detection( + *output.recipient_address(), + tx_ref, + index as u32, + )?; + } + } + } + for input in &bundle.vin { + let owned = wallet + .get_wallet_transparent_output(input.prevout(), None)? + .is_some_and(|output| output.recipient_account() == Some(&account_id)); + if owned { + wallet.mark_transparent_utxo_spent(input.prevout(), tx_ref)?; + } + } + } + Ok::<_, zcash_client_sqlite::error::SqliteClientError>(()) + }) + .map_err(|e| db_err("storeTransparentTransaction", e)) +} + +async fn queue_cached_transparent_outputs( + db: &mut Db, + client: &mut LightClient, + account_id: ::AccountId, + addresses: &HashSet<::transparent::address::TransparentAddress>, + already_stored: &HashMap<[u8; 32], (Transaction, BlockHeight)>, + fetched_parents: &mut u32, +) -> Result { + use zcash_client_backend::data_api::wallet::{ + input_selection::LockFilter, ConfirmationsPolicy, + }; + use zcash_client_backend::data_api::{CoinbaseFilter, InputSource}; + let params = *db.params(); + let tip = db + .chain_height() + .map_err(|e| db_err("chainHeight", e))? + .ok_or_else(|| db_err("chainHeight", "unknown chain height"))?; + // This is a spentness audit, not input selection. Include locked outputs + // so an external spend cannot remain hidden behind a local reservation. + let outputs = db + .get_spendable_transparent_outputs_for_addresses( + &addresses.iter().copied().collect::>(), + (tip + 1).into(), + ConfirmationsPolicy::default(), + CoinbaseFilter::AllTransparentOutputs, + LockFilter::Unfiltered, + ) + .map_err(|e| db_err("cachedTransparentOutputs", e))?; + let mut seen = HashSet::new(); + let mut deferred = 0; + for output in outputs { + let txid = *output.outpoint().hash(); + if already_stored.contains_key(&txid) || !seen.insert(txid) { + continue; + } + let cached = db + .get_transaction(zcash_protocol::TxId::from_bytes(txid)) + .map_err(|e| db_err("getTransparentParent", e))?; + let (parent, height) = if let Some(parent) = cached { + let Some(height) = output.mined_height() else { + continue; + }; + (parent, height) + } else { + if *fetched_parents >= 16 { + deferred += 1; + continue; + } + let raw = crate::network::with_timeout( + async { + client + .get_transaction(service::TxFilter { + hash: txid.to_vec(), + ..Default::default() + }) + .await + .map(|reply| reply.into_inner()) + .map_err(|e| net_err("getTransparentParent", e)) + }, + crate::network::DEFAULT_TIMEOUT_MS, + "getTransparentParent", + ) + .await?; + *fetched_parents += 1; + decode_mined_transaction(¶ms, &raw)? + }; + validate_transparent_parent(&parent, &txid, output.outpoint().n(), output.txout())?; + // Do not reinsert an old cached output as known-unspent at today's tip. + // Its absence from the current UTXO reply requires a spend check. + store_account_transaction(db, account_id, &parent, height, None)?; + } + Ok(deferred) +} + +async fn complete_transparent_spend_check( + db: &mut Db, + account_id: ::AccountId, + request: zcash_client_backend::data_api::TransactionsInvolvingAddress, + mut stream: S, +) -> Result<()> +where + S: futures_util::TryStream + Unpin, + S::Error: std::fmt::Display, +{ + let params = *db.params(); + let end = request + .block_range_end() + .ok_or_else(|| net_err("getTransparentSpends", "missing bounded range"))?; + loop { + let raw = crate::network::with_timeout( + async { + stream + .try_next() + .await + .map_err(|e| net_err("getTransparentSpends", e)) + }, + crate::network::DEFAULT_TIMEOUT_MS, + "getTransparentSpends", + ) + .await?; + let Some(raw) = raw else { + break; + }; + let (tx, height) = decode_mined_transaction(¶ms, &raw)?; + if height < request.block_range_start() || height >= end { + return Err(net_err( + "getTransparentSpends", + "transaction outside requested range", + )); + } + store_account_transaction(db, account_id, &tx, height, None)?; + } + // Empty and complete streams establish a checked range, not a spend. + // A failed or partial stream never reaches this acknowledgement. + db.notify_address_checked(request, end - 1) + .map_err(|e| db_err("notifyAddressChecked", e)) +} + +async fn refresh_transparent_spends( + db: &mut Db, + client: &mut LightClient, + account_id: ::AccountId, + addresses: &HashSet<::transparent::address::TransparentAddress>, +) -> Result { + let params = *db.params(); + let requests = db + .transaction_data_requests() + .map_err(|e| db_err("transactionDataRequests", e))?; + let mut seen = HashSet::new(); + let mut checked = 0; + for request in requests { + let TransactionDataRequest::TransactionsInvolvingAddress(request) = request else { + continue; + }; + // GetTaddressTxids covers mined transactions only. Leave unsupported + // mempool/ephemeral queries queued rather than acknowledging incomplete data. + if !addresses.contains(&request.address()) + || *request.tx_status_filter() != TransactionStatusFilter::Mined + || *request.output_status_filter() != OutputStatusFilter::All + || request + .request_at() + .is_some_and(|at| at > crate::clock::HostClock.now()) + || !seen.insert(request.clone()) + { + continue; + } + let Some(end) = request.block_range_end() else { + continue; + }; + if request.block_range_start() >= end { + continue; + } + // The upstream mined-spend queue issues short expiry-sized ranges. + // Completing each range advances its persisted observed-unspent height, + // so subsequent rounds do not restart the same first page forever. + if checked >= 16 { + break; + } + let stream = crate::network::with_timeout( + async { + client + .get_taddress_txids(service::TransparentAddressBlockFilter { + address: zcash_keys::encoding::encode_transparent_address_p( + ¶ms, + &request.address(), + ), + range: Some(service::BlockRange { + start: Some(service::BlockId { + height: u64::from(request.block_range_start()), + hash: vec![], + }), + end: Some(service::BlockId { + height: u64::from(end - 1), + hash: vec![], + }), + pool_types: vec![], + }), + }) + .await + .map(|reply| reply.into_inner()) + .map_err(|e| net_err("getTransparentSpends", e)) + }, + crate::network::DEFAULT_TIMEOUT_MS, + "getTransparentSpends", + ) + .await?; + complete_transparent_spend_check(db, account_id, request, stream).await?; + checked += 1; + } + Ok(checked) +} + +/// 宿主喂进来的一条透明 UTXO。 +/// +/// 透明侧的唯一事实来源是宿主的后端索引器,不是 lightwalletd:同一个钱包里 +/// 两个来源各说各话时,用户看到的余额和这里能选的输入就对不上。运行时只负责 +/// 校验与落库,不自己去查。 +#[derive(Debug, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct HostTransparentUtxo { + pub txid: String, + pub vout: u32, + pub value_zat: String, + pub script_pub_key: String, + pub height: u32, +} + +/// 用宿主给的快照刷新账户的透明 UTXO。 /// /// ## 为什么必须单独做 /// /// 屏蔽 note 是扫区块试解密出来的,透明 UTXO 不是 —— 它们在链上是公开的, -/// 由 lightwalletd 按地址直接返回。`scan_cached_blocks` 不会产出它们。 +/// `scan_cached_blocks` 不会产出它们。 +/// +/// 不做这一步的后果是**静默的**:隐私转账想花透明输入时选不到钱,报 +/// INSUFFICIENT_FUNDS,而扫链看起来一切正常。 /// -/// 不做这一步的后果是**静默的**:透明余额恒为 0,屏蔽(把透明余额转进隐私池) -/// 永远报「没有可屏蔽的钱」,而扫链看起来一切正常。 +/// ## 归属只认脚本 /// -/// 只查该账户名下的透明收款地址(含找零与独立地址)—— 漏掉任何一个都会 -/// 让那部分钱在钱包里不存在。 +/// 每条 UTXO 的归属由 `script_pub_key` 解出的地址决定,再拿去比对本账户的 +/// 透明收款地址(含找零与独立地址)。宿主说它是谁的不作数 —— 否则宿主一处 +/// 笔误就能把别人的输出记到这个账户名下。 pub async fn refresh_transparent_utxos( db: &mut Db, client: &mut LightClient, account_uuid: &str, + utxos: &[HostTransparentUtxo], ) -> Result { - use ::transparent::bundle::{OutPoint, TxOut}; - use zcash_client_backend::proto::service::GetAddressUtxosArg; + // Bound the whole refresh, including a server that keeps emitting stream + // items. Synchronous DB commits remain valid; unfinished ranges stay queued. + crate::network::with_timeout( + refresh_transparent_utxos_impl(db, client, account_uuid, utxos), + crate::network::DEFAULT_TIMEOUT_MS, + "refreshTransparentUtxos", + ) + .await +} + +async fn refresh_transparent_utxos_impl( + db: &mut Db, + client: &mut LightClient, + account_uuid: &str, + utxos: &[HostTransparentUtxo], +) -> Result { + use ::transparent::bundle::OutPoint; use zcash_client_backend::wallet::WalletTransparentOutput; - use zcash_protocol::value::Zatoshis; let params = *db.params(); let account_id = crate::account::parse_account_id(db, account_uuid)?; - // 地址 → 账户。返回的每条 UTXO 靠它归属,否则批量查回来就分不清是谁的。 + // 地址 → 账户。喂进来的每条 UTXO 靠它归属,否则宿主一处笔误就能把别人的 + // 输出记到这个账户名下。 let mut owner_of: std::collections::HashMap::AccountId> = std::collections::HashMap::new(); - let mut addresses: Vec = Vec::new(); let receivers = db .get_transparent_receivers(account_id, true, true) .map_err(|e| db_err("getTransparentReceivers", e))?; for addr in receivers.keys() { - let encoded = zcash_keys::encoding::encode_transparent_address_p(¶ms, addr); - owner_of.insert(encoded.clone(), account_id); - addresses.push(encoded); + owner_of.insert( + zcash_keys::encoding::encode_transparent_address_p(¶ms, addr), + account_id, + ); } - if addresses.is_empty() { + if owner_of.is_empty() { return Ok(json!({ "addresses": 0, "utxos": 0, "storedZat": 0 }).to_string()); } - let address_count = addresses.len(); - let start_height = u64::from( - db.utxo_query_height(account_id) - .map_err(|e| db_err("utxoQueryHeight", e))?, - ); - - let replies = crate::network::with_timeout( - async { - client - .get_address_utxos(GetAddressUtxosArg { - addresses, - start_height, - max_entries: 0, - }) - .await - .map_err(|e| net_err("getAddressUtxos", e)) - .map(|r| r.into_inner().address_utxos) - }, - crate::network::DEFAULT_TIMEOUT_MS, - "getAddressUtxos", - ) - .await?; + let address_count = owner_of.len(); + let active_receivers = receivers.keys().copied().collect(); let mut stored = 0u32; let mut total: u64 = 0; - for utxo in replies { - let Ok(txid) = <[u8; 32]>::try_from(&utxo.txid[..]) else { - continue; - }; - let Ok(index) = u32::try_from(utxo.index) else { - continue; - }; - let Ok(value) = u64::try_from(utxo.value_zat) - .map_err(|_| ()) - .and_then(|v| Zatoshis::from_u64(v).map_err(|_| ())) + let mut parents = HashMap::new(); + let mut fetched_parents = 0; + let mut deferred_utxos = 0; + let mut rejected_utxos = 0; + for utxo in utxos { + let Some((txid, index, txout, owner)) = + decode_host_transparent_utxo(¶ms, &owner_of, utxo) else { continue; }; - - // `Script` 内部包着 zcash_script 的类型,构造函数不公开;`read` 走的是 - // 带长度前缀的编码,所以这里自己拼前缀,避免为了一个构造再引一个 crate。 - let Some(script_pubkey) = read_script(&utxo.script) else { - continue; - }; - let txout = TxOut::new(value, script_pubkey); - let height = u32::try_from(utxo.height).ok().map(BlockHeight::from_u32); - - // 归属靠地址查回来。批量查询里混着多个账户的输出,用「当前账户」会把 - // 别人的钱记到自己头上。 - let Some(&owner) = owner_of.get(&utxo.address) else { + let value = txout.value(); + let height = Some(BlockHeight::from_u32(utxo.height)); + + if !parents.contains_key(&txid) { + if let Some(parent) = db + .get_transaction(zcash_protocol::TxId::from_bytes(txid)) + .map_err(|e| db_err("getTransparentParent", e))? + { + // The cached parent's height comes from the wallet database, not + // from the host. Storing `utxo.height` here would make the + // comparison below compare the host's claim with itself, so a + // wrong height on an already-known transaction would sail + // through and re-stamp its mined status. + let Some(mined_height) = db + .get_tx_height(zcash_protocol::TxId::from_bytes(txid)) + .map_err(|e| db_err("getTransparentParentHeight", e))? + else { + // Known transaction, no mined height: nothing to check the + // host against, so do not stage it on the host's word. + rejected_utxos += 1; + continue; + }; + parents.insert(txid, (parent, mined_height)); + } else { + // Persisted raw parents make this budget advance across rounds. + if fetched_parents >= 16 { + deferred_utxos += 1; + continue; + } + let raw = crate::network::with_timeout( + async { + client + .get_transaction(service::TxFilter { + hash: txid.to_vec(), + ..Default::default() + }) + .await + .map(|reply| reply.into_inner()) + .map_err(|e| net_err("getTransparentParent", e)) + }, + crate::network::DEFAULT_TIMEOUT_MS, + "getTransparentParent", + ) + .await?; + parents.insert(txid, decode_mined_transaction(¶ms, &raw)?); + fetched_parents += 1; + } + } + let (parent, mined_height) = parents + .get(&txid) + .ok_or_else(|| net_err("transparentParent", "missing fetched parent"))?; + // 金额/脚本/高度以链上的父交易为准。宿主和链现在是两个来源(重组窗口里 + // 它们本来就会短暂不一致),所以对不上的只丢这一条 —— 让一条过期的 + // UTXO 把整笔隐私转账挡掉,比少一个可选输入更糟。计数交回宿主, + // 这样宿主的 bug 不会没人看见。 + if validate_transparent_parent(parent, &txid, index, &txout).is_err() + || height != Some(*mined_height) + { + rejected_utxos += 1; continue; - }; - + } let Some(output) = WalletTransparentOutput::from_parts( OutPoint::new(txid, index), txout, @@ -964,13 +1314,27 @@ pub async fn refresh_transparent_utxos( continue; }; - db.put_received_transparent_utxo(&output) - .map_err(|e| db_err("putReceivedTransparentUtxo", e))?; + store_account_transaction(db, owner, parent, *mined_height, Some(&output))?; stored += 1; total += u64::from(value); } + deferred_utxos += queue_cached_transparent_outputs( + db, + client, + account_id, + &active_receivers, + &parents, + &mut fetched_parents, + ) + .await?; + let spend_ranges_checked = + refresh_transparent_spends(db, client, account_id, &active_receivers).await?; + Ok(json!({ + "spendRangesChecked": spend_ranges_checked, + "deferredUtxos": deferred_utxos, + "rejectedUtxos": rejected_utxos, "addresses": address_count, "utxos": stored, "storedZat": total, @@ -978,6 +1342,41 @@ pub async fn refresh_transparent_utxos( .to_string()) } +/// 把宿主喂进来的一条 UTXO 解成可入库的形式,认不出或不属于本账户就返回 `None`。 +/// +/// 归属只由 `script_pub_key` 反解出的地址决定 —— 宿主对这条 UTXO 属于谁的说法 +/// 一概不采信。宿主一处笔误就能把别人的输出记到这个账户名下,而入库之后它就是 +/// 可选的花费输入了。 +fn decode_host_transparent_utxo( + params: &zcash_protocol::consensus::Network, + owner_of: &std::collections::HashMap::AccountId>, + utxo: &HostTransparentUtxo, +) -> Option<( + [u8; 32], + u32, + ::transparent::bundle::TxOut, + ::AccountId, +)> { + use ::transparent::bundle::TxOut; + use zcash_protocol::value::Zatoshis; + + // 宿主给的是后端的**显示序**(大端 hex);`TxId` / SQLite / lightwalletd 的 + // `TxFilter.hash` 全要内部序。不反转就是去查一个不存在的父交易,而且对 + // 回文 txid 恰好看不出来。 + let txid = + <[u8; 32]>::try_from(&crate::history::display_order_to_internal(&utxo.txid).ok()?[..]) + .ok()?; + let value = Zatoshis::from_u64(utxo.value_zat.parse::().ok()?).ok()?; + let script_pubkey = read_script(&hex::decode(&utxo.script_pub_key).ok()?)?; + let txout = TxOut::new(value, script_pubkey); + // 认不出的脚本(既非 P2PKH 也非 P2SH)没有可比对的地址,跳过而不是猜。 + let recipient = txout.recipient_address()?; + let owner = *owner_of.get(&zcash_keys::encoding::encode_transparent_address_p( + params, &recipient, + ))?; + Some((txid, utxo.vout, txout, owner)) +} + /// 把裸 script 字节读成 `Script`。 /// /// 上游的 `Script::read` 期待 CompactSize 长度前缀(链上编码),而 @@ -1017,6 +1416,388 @@ mod tests { .to_unified_full_viewing_key() } + fn transparent_fixture( + inputs: Vec<::transparent::bundle::OutPoint>, + outputs: Vec<::transparent::bundle::TxOut>, + ) -> Transaction { + use ::transparent::bundle::{Authorized, Bundle, TxIn}; + use zcash_primitives::transaction::{TransactionData, TxVersion}; + TransactionData::from_parts( + TxVersion::V5, + BranchId::Nu5, + 0, + BlockHeight::from_u32(2_100_000), + Some(Bundle { + vin: inputs + .into_iter() + .map(|prevout| TxIn::from_parts(prevout, read_script(&[]).unwrap(), u32::MAX)) + .collect(), + vout: outputs, + authorization: Authorized, + }), + None, + None, + None, + ) + .freeze() + .unwrap() + } + + #[test] + fn transparent_parent_requires_exact_transaction_and_output() { + use ::transparent::{ + address::TransparentAddress, + bundle::{OutPoint, TxOut}, + }; + use zcash_protocol::value::Zatoshis; + let output = TxOut::new( + Zatoshis::from_u64(50_000).unwrap(), + TransparentAddress::PublicKeyHash([1; 20]).script().into(), + ); + let tx = transparent_fixture(vec![OutPoint::new([0; 32], u32::MAX)], vec![output.clone()]); + validate_transparent_parent(&tx, tx.txid().as_ref(), 0, &output).unwrap(); + assert!(validate_transparent_parent(&tx, &[2; 32], 0, &output).is_err()); + assert!(validate_transparent_parent(&tx, tx.txid().as_ref(), 1, &output).is_err()); + let wrong_value = TxOut::new( + Zatoshis::from_u64(50_001).unwrap(), + output.script_pubkey().clone(), + ); + assert!(validate_transparent_parent(&tx, tx.txid().as_ref(), 0, &wrong_value).is_err()); + let wrong_script = TxOut::new( + output.value(), + TransparentAddress::PublicKeyHash([2; 20]).script().into(), + ); + assert!(validate_transparent_parent(&tx, tx.txid().as_ref(), 0, &wrong_script).is_err()); + let mut data = vec![]; + tx.write(&mut data).unwrap(); + let mut raw = service::RawTransaction { + data, + height: 2_000_000, + }; + decode_mined_transaction(&Network::MainNetwork, &raw).unwrap(); + raw.height = 0; + assert!(decode_mined_transaction(&Network::MainNetwork, &raw).is_err()); + raw.height = u64::MAX; + assert!(decode_mined_transaction(&Network::MainNetwork, &raw).is_err()); + raw.height = 2_000_000; + raw.data.push(0); + assert!(decode_mined_transaction(&Network::MainNetwork, &raw).is_err()); + } + + #[test] + fn host_transparent_utxo_is_attributed_by_its_script_not_by_the_host() { + use ::transparent::address::TransparentAddress; + use zcash_protocol::consensus::Network; + + let params = Network::MainNetwork; + let mine = [7u8; 20]; + let theirs = [9u8; 20]; + let owner = zcash_client_sqlite::AccountUuid::from_uuid(uuid::Uuid::from_u128(1)); + let mut owner_of = std::collections::HashMap::new(); + owner_of.insert( + zcash_keys::encoding::encode_transparent_address_p( + ¶ms, + &TransparentAddress::PublicKeyHash(mine), + ), + owner, + ); + + // 宿主发的就是 blockbook 的裸 scriptPubKey:P2PKH 是 + // OP_DUP OP_HASH160 <20 字节> OP_EQUALVERIFY OP_CHECKSIG。 + let p2pkh = |hash: [u8; 20]| format!("76a914{}88ac", hex::encode(hash)); + let utxo = |script: String, value: &str, txid: &str| HostTransparentUtxo { + txid: txid.to_string(), + vout: 1, + value_zat: value.to_string(), + script_pub_key: script, + height: 2_000_000, + }; + // 每个字节都不同:回文 txid(比如 "ab" 重复 32 次)在字节反转下和自己 + // 相等,用它做用例等于把显示序/内部序这一层测没了。 + let txid_display: String = (0u8..32).map(|b| format!("{b:02x}")).collect(); + let txid_internal: [u8; 32] = { + let mut b = [0u8; 32]; + for (i, v) in (0u8..32).rev().enumerate() { + b[i] = v; + } + b + }; + let txid_hex = txid_display; + + let (txid, index, txout, got) = + decode_host_transparent_utxo(¶ms, &owner_of, &utxo(p2pkh(mine), "1000", &txid_hex)) + .expect("an owned P2PKH output is attributed to its account"); + assert_eq!(txid, txid_internal, "显示序 hex 必须反转成内部序字节"); + assert_eq!(index, 1); + assert_eq!(u64::from(txout.value()), 1000); + assert_eq!(got, owner); + + // 宿主可以搞错 UTXO 是谁的;入库之后它就是可花费的输入了,所以归属 + // 只认脚本反解出来的地址。 + assert!(decode_host_transparent_utxo( + ¶ms, + &owner_of, + &utxo(p2pkh(theirs), "1000", &txid_hex) + ) + .is_none()); + // 单条坏数据只丢这一条,不影响同一快照里的其他 UTXO。 + for bad in [ + utxo(p2pkh(mine), "1000", "zz"), + utxo(p2pkh(mine), "1000", "ab"), + utxo(p2pkh(mine), "-1", &txid_hex), + utxo(p2pkh(mine), "not-a-number", &txid_hex), + // OP_RETURN:没有可比对的地址。 + utxo("6a".to_string(), "1000", &txid_hex), + ] { + assert!(decode_host_transparent_utxo(¶ms, &owner_of, &bad).is_none()); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn transparent_storage_classifies_coinbase_and_limits_spends_to_active_owner() { + use ::transparent::bundle::{OutPoint, TxOut}; + use zcash_client_backend::data_api::wallet::{ + input_selection::LockFilter, ConfirmationsPolicy, + }; + use zcash_client_backend::data_api::{ + Account as _, AccountBirthday, AccountPurpose, CoinbaseFilter, InputSource, + }; + use zcash_client_backend::wallet::WalletTransparentOutput; + use zcash_primitives::block::BlockHash; + use zcash_protocol::value::Zatoshis; + let mut db = crate::wallet::open_and_migrate("main", ":memory:").unwrap(); + let height = BlockHeight::from_u32(2_000_000); + let birthday = + AccountBirthday::from_parts(ChainState::empty(height - 1, BlockHash([0; 32])), None); + let a = db + .import_account_ufvk( + "active", + &test_ufvk(&Network::MainNetwork, 51), + &birthday, + AccountPurpose::ViewOnly, + None, + ) + .unwrap() + .id(); + let b = db + .import_account_ufvk( + "paused", + &test_ufvk(&Network::MainNetwork, 52), + &birthday, + AccountPurpose::ViewOnly, + None, + ) + .unwrap() + .id(); + db.update_chain_tip(height + 200).unwrap(); + let address_a = *db + .get_transparent_receivers(a, true, true) + .unwrap() + .keys() + .next() + .unwrap(); + let address_b = *db + .get_transparent_receivers(b, true, true) + .unwrap() + .keys() + .next() + .unwrap(); + let output_a = TxOut::new( + Zatoshis::from_u64(50_000).unwrap(), + address_a.script().into(), + ); + let output_b = TxOut::new( + Zatoshis::from_u64(60_000).unwrap(), + address_b.script().into(), + ); + let coinbase = transparent_fixture( + vec![OutPoint::new([0; 32], u32::MAX)], + vec![output_a.clone()], + ); + let regular = transparent_fixture( + vec![OutPoint::new([3; 32], 0)], + vec![output_a.clone(), output_b.clone()], + ); + for (tx, index, output, owner) in [ + (&coinbase, 0, output_a.clone(), a), + (®ular, 0, output_a.clone(), a), + (®ular, 1, output_b.clone(), b), + ] { + store_account_transaction(&mut db, owner, tx, height, None).unwrap(); + let output = WalletTransparentOutput::from_parts( + OutPoint::new(*tx.txid().as_ref(), index), + output, + Some(height), + Some(owner), + None, + None, + ) + .unwrap(); + db.put_received_transparent_utxo(&output).unwrap(); + } + let spendable = |db: &Db, address| { + db.get_spendable_transparent_outputs( + address, + (height + 401).into(), + ConfirmationsPolicy::default(), + CoinbaseFilter::NonCoinbaseOnly, + LockFilter::Policy(&Default::default()), + ) + .unwrap() + }; + assert_eq!(spendable(&db, &address_a).len(), 1); + let a_input = OutPoint::new(*regular.txid().as_ref(), 0); + let b_input = OutPoint::new(*regular.txid().as_ref(), 1); + let spend = transparent_fixture(vec![a_input, b_input], vec![output_b]); + let b_receivers_before = db.get_transparent_receivers(b, true, true).unwrap().len(); + store_account_transaction(&mut db, a, &spend, height + 1, None).unwrap(); + assert!(spendable(&db, &address_a).is_empty()); + assert_eq!(spendable(&db, &address_b).len(), 1); + assert_eq!( + db.get_transparent_receivers(b, true, true).unwrap().len(), + b_receivers_before + ); + assert!(db + .get_unspent_transparent_output( + &OutPoint::new(*spend.txid().as_ref(), 0), + (height + 401).into() + ) + .unwrap() + .is_none()); + } + + #[cfg(not(target_arch = "wasm32"))] + #[tokio::test] + async fn transparent_spend_checks_acknowledge_only_complete_ranges() { + use ::transparent::bundle::{OutPoint, TxOut}; + use zcash_client_backend::data_api::{ + Account as _, AccountBirthday, AccountPurpose, InputSource, + }; + use zcash_client_backend::wallet::WalletTransparentOutput; + use zcash_primitives::block::BlockHash; + use zcash_protocol::value::Zatoshis; + let mut db = crate::wallet::open_and_migrate("main", ":memory:").unwrap(); + let height = BlockHeight::from_u32(2_000_000); + let birthday = + AccountBirthday::from_parts(ChainState::empty(height - 1, BlockHash([0; 32])), None); + let owner = db + .import_account_ufvk( + "active", + &test_ufvk(&Network::MainNetwork, 61), + &birthday, + AccountPurpose::ViewOnly, + None, + ) + .unwrap() + .id(); + db.update_chain_tip(height + 200).unwrap(); + let address = *db + .get_transparent_receivers(owner, true, true) + .unwrap() + .keys() + .next() + .unwrap(); + let txout = TxOut::new(Zatoshis::from_u64(50_000).unwrap(), address.script().into()); + let parent = transparent_fixture(vec![OutPoint::new([3; 32], 0)], vec![txout.clone()]); + store_account_transaction(&mut db, owner, &parent, height, None).unwrap(); + let outpoint = OutPoint::new(*parent.txid().as_ref(), 0); + db.put_received_transparent_utxo( + &WalletTransparentOutput::from_parts( + outpoint.clone(), + txout.clone(), + Some(height), + Some(owner), + None, + None, + ) + .unwrap(), + ) + .unwrap(); + let request_for = |db: &Db| { + db.transaction_data_requests() + .unwrap() + .into_iter() + .find_map(|request| match request { + TransactionDataRequest::TransactionsInvolvingAddress(request) + if request.address() == address => + { + Some(request) + } + _ => None, + }) + .unwrap() + }; + store_account_transaction(&mut db, owner, &parent, height, None).unwrap(); + db.update_chain_tip(height + 400).unwrap(); + let initial = request_for(&db); + let error_stream = futures_util::stream::iter(vec![Err::( + net_err("testStream", "interrupted"), + )]); + assert!( + complete_transparent_spend_check(&mut db, owner, initial.clone(), error_stream) + .await + .is_err() + ); + assert_eq!( + request_for(&db).block_range_start(), + initial.block_range_start() + ); + let empty_stream = + futures_util::stream::iter(Vec::>::new()); + complete_transparent_spend_check(&mut db, owner, initial.clone(), empty_stream) + .await + .unwrap(); + assert_eq!( + request_for(&db).block_range_start(), + initial.block_range_end().unwrap() + ); + assert!(db + .get_unspent_transparent_output(&outpoint, (height + 401).into()) + .unwrap() + .is_some()); + + let next = request_for(&db); + let mut data = vec![]; + parent.write(&mut data).unwrap(); + let outside_range = + futures_util::stream::iter(vec![Ok::<_, RuntimeError>(service::RawTransaction { + data, + height: u64::from(next.block_range_end().unwrap()), + })]); + assert!( + complete_transparent_spend_check(&mut db, owner, next.clone(), outside_range) + .await + .is_err() + ); + assert_eq!( + request_for(&db).block_range_start(), + next.block_range_start() + ); + + let spend = transparent_fixture(vec![outpoint.clone()], vec![txout]); + let mut data = vec![]; + spend.write(&mut data).unwrap(); + let partial_stream = futures_util::stream::iter(vec![ + Ok(service::RawTransaction { + data, + height: u64::from(next.block_range_start()), + }), + Err(net_err("testStream", "interrupted after transaction")), + ]); + assert!( + complete_transparent_spend_check(&mut db, owner, next, partial_stream) + .await + .is_err() + ); + // A positively observed spend remains valid even when later stream data + // fails; missing entries alone never changed spentness above. + assert!(db + .get_unspent_transparent_output(&outpoint, (height + 401).into()) + .unwrap() + .is_none()); + } + fn selected_ufvks_for( network: &Network, wallet_ufvks: HashMap, diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs index 291c6af64..bbeb8d530 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs @@ -13,7 +13,7 @@ use crate::history::{display_order_to_internal, hex_display_order, uuid_blob}; use crate::wallet::Db; const MIGRATION_ID: Uuid = Uuid::from_u128(0x5be0af90_63f4_43ea_ae65_8207c84e46dd); -const TABLE: &str = "ext_onekey_tx_state"; +pub(crate) const TABLE: &str = "ext_onekey_tx_state"; pub struct Migration; diff --git a/chain-runtimes/zcash/scripts/artifact-manifest.py b/chain-runtimes/zcash/scripts/artifact-manifest.py new file mode 100644 index 000000000..986a0ed92 --- /dev/null +++ b/chain-runtimes/zcash/scripts/artifact-manifest.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Bind the complete Zcash WASM artifact to its source revision and file hashes.""" + +import argparse +import hashlib +import json +from pathlib import Path +import subprocess + + +ROOT = Path(__file__).resolve().parent.parent +MANIFEST = "zcash-wasm-manifest.json" +PACKAGES = { + "pkg": "onekey_zcash_runtime", + "pkg-keys": "onekey_zcash_keys", + "pkg/storage-benchmark": "onekey_zcash_storage_benchmark", +} + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def artifact_files(root): + files = {} + for directory in ("pkg", "pkg-keys"): + if (root / directory).is_symlink(): + raise ValueError(f"Artifact package is a symlink: {directory}") + for path in sorted((root / directory).rglob("*")): + if path.is_symlink(): + raise ValueError(f"Artifact symlink: {path.relative_to(root)}") + if path.is_file() and path.name != ".gitignore": + files[path.relative_to(root).as_posix()] = digest(path) + for directory, module in PACKAGES.items(): + for name in ("package.json", f"{module}.js", f"{module}.d.ts", f"{module}_bg.wasm"): + if f"{directory}/{name}" not in files: + raise ValueError(f"Incomplete artifact: {directory}/{name}") + return files + + +def write(root): + revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip() + dirty = bool(subprocess.check_output([ + "git", "-c", "core.fsmonitor=false", "status", "--porcelain", "--untracked-files=normal", "--", ".", + ], cwd=ROOT, text=True).strip()) + manifest = { + "formatVersion": 1, + "sourceRepository": "OneKeyHQ/app-modules", + "sourceRevision": revision, + "sourceDirty": dirty, + "cargoLockSha256": digest(ROOT / "Cargo.lock"), + "files": artifact_files(root), + } + (root / MANIFEST).write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n") + print(f"Wrote {MANIFEST}: {len(manifest['files'])} files, dirty={dirty}") + + +def verify(root, revision, allow_dirty=False): + manifest = json.loads((root / MANIFEST).read_text()) + if manifest.get("formatVersion") != 1 or manifest.get("sourceRepository") != "OneKeyHQ/app-modules": + raise ValueError("Unsupported artifact provenance") + if manifest.get("sourceRevision") != revision: + raise ValueError("Artifact source revision mismatch") + if manifest.get("sourceDirty") is not False and not allow_dirty: + raise ValueError("CI artifacts must originate from a clean source checkout") + if artifact_files(root) != manifest.get("files"): + raise ValueError("Artifact file inventory or checksum mismatch") + print(f"Verified complete Zcash artifact for {revision}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("operation", choices=("write", "verify")) + parser.add_argument("--root", type=Path, default=ROOT) + parser.add_argument("--expected-revision") + parser.add_argument("--allow-dirty", action="store_true", help="Local development verification only") + args = parser.parse_args() + if args.operation == "write": + write(args.root) + elif not args.expected_revision: + parser.error("verify requires --expected-revision") + else: + verify(args.root, args.expected_revision, args.allow_dirty) diff --git a/chain-runtimes/zcash/scripts/build-wasm.sh b/chain-runtimes/zcash/scripts/build-wasm.sh index eb9a0327a..c02212220 100755 --- a/chain-runtimes/zcash/scripts/build-wasm.sh +++ b/chain-runtimes/zcash/scripts/build-wasm.sh @@ -67,3 +67,9 @@ echo "==> 构建 storage benchmark" echo "==> 构建 onekey-zcash-keys" (cd "${ROOT}/crates/zcash-keys-runtime" && wasm-pack build --mode no-install --locked --target web --out-dir "${ROOT}/pkg-keys" --release) echo "产物:$(du -h "${ROOT}"/pkg/*.wasm "${ROOT}"/pkg-keys/*.wasm "${ROOT}"/pkg/storage-benchmark/*.wasm | tr '\n' ' ')" + +if [ "${OUT}" = "${ROOT}/pkg" ]; then + python3 "${ROOT}/scripts/artifact-manifest.py" write +else + echo "Custom runtime output: no complete artifact manifest produced." +fi diff --git a/chain-runtimes/zcash/scripts/test_artifact_manifest.py b/chain-runtimes/zcash/scripts/test_artifact_manifest.py new file mode 100644 index 000000000..34a2f1442 --- /dev/null +++ b/chain-runtimes/zcash/scripts/test_artifact_manifest.py @@ -0,0 +1,40 @@ +import importlib.util +from pathlib import Path +import tempfile +import unittest + + +spec = importlib.util.spec_from_file_location("artifact_manifest", Path(__file__).with_name("artifact-manifest.py")) +artifact = importlib.util.module_from_spec(spec) +spec.loader.exec_module(artifact) + + +class ArtifactManifestTests(unittest.TestCase): + def test_all_three_packages_and_exact_inventory_are_required(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for package, module in artifact.PACKAGES.items(): + target = root / package + target.mkdir(parents=True, exist_ok=True) + for name in ("package.json", f"{module}.js", f"{module}.d.ts", f"{module}_bg.wasm"): + (target / name).write_text("synthetic artifact") + files = artifact.artifact_files(root) + self.assertEqual(len(files), 12) + path = root / "pkg/storage-benchmark/onekey_zcash_storage_benchmark_bg.wasm" + path.unlink() + with self.assertRaisesRegex(ValueError, "Incomplete artifact"): + artifact.artifact_files(root) + path.write_text("changed artifact") + self.assertNotEqual(files, artifact.artifact_files(root)) + + def test_symlinks_are_rejected(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "pkg").mkdir() + (root / "pkg/escape").symlink_to(root) + with self.assertRaisesRegex(ValueError, "Artifact symlink"): + artifact.artifact_files(root) + + +if __name__ == "__main__": + unittest.main() From d51ade667faa05f0894f356e852518e43c6a6f37 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Sun, 20 Sep 2026 11:21:39 +0900 Subject: [PATCH 06/97] feat: prepare independent zcash runtime releases --- .github/workflows/zcash-publish.yml | 74 +++++++ .github/workflows/zcash-runtime.yml | 17 ++ chain-runtimes/zcash/.gitignore | 2 + chain-runtimes/zcash/Cargo.lock | 6 +- chain-runtimes/zcash/Cargo.toml | 1 + chain-runtimes/zcash/LICENSE | 202 ++++++++++++++++++ chain-runtimes/zcash/README.md | 8 +- chain-runtimes/zcash/RELEASING.md | 71 ++++++ .../crates/zcash-keys-runtime/Cargo.toml | 2 +- .../zcash/crates/zcash-runtime/Cargo.toml | 2 +- .../crates/zcash-storage-benchmark/Cargo.toml | 2 +- .../zcash/scripts/artifact-manifest.py | 2 + chain-runtimes/zcash/scripts/build-wasm.sh | 18 +- .../zcash/scripts/package-release.py | 118 ++++++++++ .../zcash/scripts/test_artifact_manifest.py | 15 ++ .../zcash/scripts/test_package_release.py | 82 +++++++ 16 files changed, 609 insertions(+), 13 deletions(-) create mode 100644 .github/workflows/zcash-publish.yml create mode 100644 chain-runtimes/zcash/LICENSE create mode 100644 chain-runtimes/zcash/RELEASING.md create mode 100644 chain-runtimes/zcash/scripts/package-release.py create mode 100644 chain-runtimes/zcash/scripts/test_package_release.py diff --git a/.github/workflows/zcash-publish.yml b/.github/workflows/zcash-publish.yml new file mode 100644 index 000000000..7f1ce9783 --- /dev/null +++ b/.github/workflows/zcash-publish.yml @@ -0,0 +1,74 @@ +name: Publish Zcash runtime + +on: + workflow_dispatch: + inputs: + version: + description: Exact workspace version (for example 0.1.0-rc.1) + required: true + type: string + tag: + description: npm dist-tag + required: true + type: choice + options: [rc, latest] + +permissions: + contents: read + +concurrency: + group: zcash-npm-publish + cancel-in-progress: false + +jobs: + validate: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + - name: Require main and the exact release version + env: + RELEASE_VERSION: ${{ inputs.version }} + RELEASE_TAG: ${{ inputs.tag }} + run: | + test "$GITHUB_REF" = refs/heads/main + python3 - <<'PY' + import importlib.util, os + from pathlib import Path + path = Path('chain-runtimes/zcash/scripts/package-release.py') + spec = importlib.util.spec_from_file_location('release', path) + release = importlib.util.module_from_spec(spec) + spec.loader.exec_module(release) + release.check_version(release.version(release.ROOT), os.environ['RELEASE_VERSION'], os.environ['RELEASE_TAG']) + PY + build: + needs: validate + uses: ./.github/workflows/zcash-runtime.yml + publish: + needs: build + runs-on: ubuntu-24.04 + environment: npm-zcash + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-node@v6 + with: + node-version: '24.x' + registry-url: https://registry.npmjs.org + - uses: actions/download-artifact@v4 + with: + name: zcash-wasm-${{ github.sha }} + path: chain-runtimes/zcash + - name: Recheck and pack the verified build + working-directory: chain-runtimes/zcash + env: + RELEASE_VERSION: ${{ inputs.version }} + RELEASE_TAG: ${{ inputs.tag }} + run: python3 scripts/package-release.py pack --version "$RELEASE_VERSION" --tag "$RELEASE_TAG" --revision "$GITHUB_SHA" + - name: Publish the runtime and keys pair + working-directory: chain-runtimes/zcash + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + RELEASE_VERSION: ${{ inputs.version }} + RELEASE_TAG: ${{ inputs.tag }} + run: | + npm publish "dist/onekey-zcash-runtime-${RELEASE_VERSION}.tgz" --ignore-scripts --access public --tag "$RELEASE_TAG" + npm publish "dist/onekey-zcash-keys-${RELEASE_VERSION}.tgz" --ignore-scripts --access public --tag "$RELEASE_TAG" diff --git a/.github/workflows/zcash-runtime.yml b/.github/workflows/zcash-runtime.yml index 9bf3d0c80..e432df24a 100644 --- a/.github/workflows/zcash-runtime.yml +++ b/.github/workflows/zcash-runtime.yml @@ -5,12 +5,15 @@ on: paths: - 'chain-runtimes/zcash/**' - '.github/workflows/zcash-runtime.yml' + - '.github/workflows/zcash-publish.yml' push: branches: [main] paths: - 'chain-runtimes/zcash/**' - '.github/workflows/zcash-runtime.yml' + - '.github/workflows/zcash-publish.yml' workflow_dispatch: + workflow_call: permissions: contents: read @@ -45,6 +48,15 @@ jobs: run: bash scripts/build-wasm.sh --offline - name: Verify complete artifact provenance run: python3 scripts/artifact-manifest.py verify --expected-revision "${{ github.sha }}" + - uses: actions/setup-node@v6 + with: + node-version: '24.x' + - name: Verify npm archives + run: | + VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') + TAG=latest + if [[ "$VERSION" == *-rc.* ]]; then TAG=rc; fi + python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$GITHUB_SHA" - uses: actions/upload-artifact@v4 with: name: zcash-wasm-${{ github.sha }} @@ -53,3 +65,8 @@ jobs: chain-runtimes/zcash/pkg/ chain-runtimes/zcash/pkg-keys/ chain-runtimes/zcash/zcash-wasm-manifest.json + - uses: actions/upload-artifact@v4 + with: + name: zcash-npm-${{ github.sha }} + if-no-files-found: error + path: chain-runtimes/zcash/dist/ diff --git a/chain-runtimes/zcash/.gitignore b/chain-runtimes/zcash/.gitignore index 9c940c0d5..0a8c62261 100644 --- a/chain-runtimes/zcash/.gitignore +++ b/chain-runtimes/zcash/.gitignore @@ -8,3 +8,5 @@ __pycache__/ # Keep local wallet fixtures out of source control. /.secrets/ + +/dist diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock index 1c2bb002d..e3b723713 100644 --- a/chain-runtimes/zcash/Cargo.lock +++ b/chain-runtimes/zcash/Cargo.lock @@ -1655,7 +1655,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "onekey-zcash-keys" -version = "0.0.1" +version = "0.1.0-rc.1" dependencies = [ "bip0039", "bs58", @@ -1685,7 +1685,7 @@ dependencies = [ [[package]] name = "onekey-zcash-runtime" -version = "0.0.1" +version = "0.1.0-rc.1" dependencies = [ "async-trait", "console_error_panic_hook", @@ -1733,7 +1733,7 @@ dependencies = [ [[package]] name = "onekey-zcash-storage-benchmark" -version = "0.0.1" +version = "0.1.0-rc.1" dependencies = [ "console_error_panic_hook", "js-sys", diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml index 9a7af306c..95c8a6d71 100644 --- a/chain-runtimes/zcash/Cargo.toml +++ b/chain-runtimes/zcash/Cargo.toml @@ -8,6 +8,7 @@ members = [ exclude = ["vendor/sqlite-wasm-vfs-0.2.0"] [workspace.package] +version = "0.1.0-rc.1" edition = "2021" license = "Apache-2.0" rust-version = "1.85" diff --git a/chain-runtimes/zcash/LICENSE b/chain-runtimes/zcash/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/chain-runtimes/zcash/LICENSE @@ -0,0 +1,202 @@ + + 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md index d529a586b..c9613e878 100644 --- a/chain-runtimes/zcash/README.md +++ b/chain-runtimes/zcash/README.md @@ -1,7 +1,7 @@ > This project now lives in `app-modules/chain-runtimes/zcash`. See > [IMPORT.md](./IMPORT.md) for the source revision and preserved vendor patches. > Build commands below run from this directory. Use Rust 1.93.0 (pinned in -> `rust-toolchain.toml`), Python 3.9+, LLVM/Clang, and wasm-pack 0.15.0. +> `rust-toolchain.toml`), Python 3.11+, LLVM/Clang, and wasm-pack 0.15.0. > Install `wasm-bindgen-cli` at the `wasm-bindgen` version in `Cargo.lock` > and provide `wasm-opt` (Binaryen), or reuse the matching wasm-pack tool cache. > Builds use `--mode no-install` and never update `Cargo.lock`. @@ -98,6 +98,9 @@ OPFS 仍受浏览器 origin、配额和清理策略约束;App 内嵌页面的 ## 先前版本的验证记录(不替代当前 OPFS 验收) +以下是历史实验记录,含旧 IndexedDB 后端描述,不是当前发布验收清单。 +当前存储实现见上方 OPFS 章节;每个候选版本须按 RELEASING.md 验证实际产物。 + > 状态:**runtime 的看账与发送链路已在 testnet 上真实上链验证,App 适配层已接入并通过 > 类型、单元与浏览器 runtime 检查。** App 内的有资金发送闭环与主网真实交易仍需人工验收。 @@ -261,7 +264,8 @@ bash scripts/vendor-deps.sh --offline ``` 产物 `pkg/`、`pkg-keys/` 不入库。两者一起构建,供 app-monorepo 的本地 -portal 依赖或 CI artifact 使用。本次迁移不发布 npm 包。 +portal 依赖或 CI artifact 使用。独立 npm 发布流程、版本规则与 App 切换步骤见 +[RELEASING.md](./RELEASING.md)。 --- diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md new file mode 100644 index 000000000..7ad585299 --- /dev/null +++ b/chain-runtimes/zcash/RELEASING.md @@ -0,0 +1,71 @@ +# Zcash WASM releases + +Zcash versions are independent of the native modules' 3.x release train. Do not +run the repository-wide `version:patch` or `version:publish` for a Zcash release. + +## Version source + +Edit only `[workspace.package].version` in `Cargo.toml`. All three crates inherit +it, and wasm-pack generates the npm versions from those crates. Update the three +workspace entries in `Cargo.lock` with `cargo check --workspace --offline` and +review the lockfile diff; dependency upgrades are a separate change. + +The first candidate is `0.1.0-rc.1` on the npm `rc` tag. After acceptance, release +`0.1.0` on `latest`; subsequent compatible fixes can use `0.1.1`. Runtime and keys +always share a version and source commit. The benchmark is shipped as a runtime +subdirectory to preserve the App developer tools' existing import path; it is +not a third published package and production App bundles still exclude it. + +## Prepare and verify + +Use Python 3.11+ and the pinned Rust/WASM tools described in README.md. + +1. Run `python3 -m unittest discover -s scripts -p 'test_*.py'` and + `cargo test --workspace --locked --offline` with already prepared dependencies. +2. Commit the release changes. A release build must come from a clean checkout. +3. Run `bash scripts/build-wasm.sh --offline`. This builds all three WASM + artifacts, prepares npm metadata and LICENSE, and writes the source manifest. +4. Run `python3 scripts/package-release.py pack --version 0.1.0-rc.1 --tag rc + --revision ` (as one command). It checks clean-source + provenance, Cargo.lock, all artifact hashes, versions, and npm archive contents. + `dist/` contains the two verified tarballs and source manifest. + +`--allow-dirty` is only for local packaging diagnostics. Never publish those +archives or manually rewrite the manifest to make an old artifact pass. + +## Publish + +Merge the release changes to `main` first. The **Publish Zcash runtime** workflow +is manual, accepts the exact version and `rc`/`latest` tag, and refuses other +branches. It reuses the build/test workflow, verifies the downloaded artifact +again, and publishes only these two npm packages. The native-module publish +workflow is unchanged. + +Repository maintainers must configure `NPM_TOKEN` with permission to publish +`onekey-zcash-runtime` and `onekey-zcash-keys`. Configure required reviewers for +the `npm-zcash` GitHub environment if a separate release approval is desired. +The environment name alone does not enable approval protection. + +npm cannot publish two packages atomically. If publishing one succeeds and the +other fails, do not consume the version until both exist. Restore the exact +verified artifact from that workflow run and publish only the missing package; +never overwrite an existing version or rebuild different bytes under that version. + +## App cutover and acceptance + +Until the pair exists on npm, keep the App's local `portal:` dependencies. Once +both packages have been published, replace both entries in +`packages/core/package.json` with the same exact version and update `yarn.lock` +through the App repository's dependency workflow. Do not use a version range. + +Validate the actual packed/published files, rather than the larger portal folder: + +- The worker can resolve JS, types and WASM for both packages, and the developer + storage benchmark import resolves from the runtime package. +- Desktop and Extension: start, scan, restart and restore progress. +- iOS and Android: foreground scan, pause/resume and relaunch recovery. +- Exercise the supported receive/send paths, including transparent shielding and + interrupted broadcast recovery, using the same candidate artifacts. + +Native Rust tests do not replace wasm32 OPFS durability tests or four-platform +acceptance. The candidate's mainnet/real-funds scope must be recorded explicitly. diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml index 9c4d0c8e7..bf40333b1 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "onekey-zcash-keys" -version = "0.0.1" +version.workspace = true edition.workspace = true license.workspace = true rust-version.workspace = true diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml index d4a76f786..c7a74464d 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "onekey-zcash-runtime" -version = "0.0.1" +version.workspace = true edition.workspace = true license.workspace = true rust-version.workspace = true diff --git a/chain-runtimes/zcash/crates/zcash-storage-benchmark/Cargo.toml b/chain-runtimes/zcash/crates/zcash-storage-benchmark/Cargo.toml index 4b9a86d1a..1a7ff9139 100644 --- a/chain-runtimes/zcash/crates/zcash-storage-benchmark/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-storage-benchmark/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "onekey-zcash-storage-benchmark" -version = "0.0.1" +version.workspace = true edition.workspace = true license.workspace = true rust-version.workspace = true diff --git a/chain-runtimes/zcash/scripts/artifact-manifest.py b/chain-runtimes/zcash/scripts/artifact-manifest.py index 986a0ed92..ef184e736 100644 --- a/chain-runtimes/zcash/scripts/artifact-manifest.py +++ b/chain-runtimes/zcash/scripts/artifact-manifest.py @@ -63,6 +63,8 @@ def verify(root, revision, allow_dirty=False): raise ValueError("Artifact source revision mismatch") if manifest.get("sourceDirty") is not False and not allow_dirty: raise ValueError("CI artifacts must originate from a clean source checkout") + if manifest.get("cargoLockSha256") != digest(ROOT / "Cargo.lock"): + raise ValueError("Artifact Cargo.lock checksum mismatch") if artifact_files(root) != manifest.get("files"): raise ValueError("Artifact file inventory or checksum mismatch") print(f"Verified complete Zcash artifact for {revision}") diff --git a/chain-runtimes/zcash/scripts/build-wasm.sh b/chain-runtimes/zcash/scripts/build-wasm.sh index c02212220..6bb420176 100755 --- a/chain-runtimes/zcash/scripts/build-wasm.sh +++ b/chain-runtimes/zcash/scripts/build-wasm.sh @@ -19,6 +19,13 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" PROFILE="${PROFILE:-release}" OUT="${OUT:-${ROOT}/pkg}" +if ! python3 -c 'import tomllib' 2>/dev/null; then + echo "Python 3.11+ is required; select it in PATH before building." >&2 + exit 1 +fi +RUST_TOOLCHAIN="$(python3 -c 'import sys, tomllib; print(tomllib.load(open(sys.argv[1], "rb"))["toolchain"]["channel"])' "${ROOT}/rust-toolchain.toml")" +rustup run "${RUST_TOOLCHAIN}" rustc --version + # 找一个能编 wasm32 的 clang pick_clang() { for c in "${CC_wasm32_unknown_unknown:-}" \ @@ -48,11 +55,11 @@ bash "${ROOT}/scripts/vendor-deps.sh" "$@" echo "==> wasm-pack build (${PROFILE})" cd "${ROOT}/crates/zcash-runtime" case "${PROFILE}" in - release) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --release ;; + release) rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --release ;; # 优化照旧,但保留名字段。wasm 里的 panic 只给函数序号,没有它就只能靠 # 通读依赖去猜是谁调的 —— 而 --dev 会让 Halo2 证明慢到不可用。 - profiling) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --profiling ;; - *) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --dev ;; + profiling) rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --profiling ;; + *) rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --dev ;; esac echo "==> 产物" @@ -60,15 +67,16 @@ ls -lh "${OUT}"/*.wasm | awk '{print " ", $9, $5}' echo "==> 构建 storage benchmark" (cd "${ROOT}/crates/zcash-storage-benchmark" && \ - wasm-pack build --mode no-install --locked --target web --out-dir "${ROOT}/pkg/storage-benchmark" --release) + rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${ROOT}/pkg/storage-benchmark" --release) # keys 包必须一起构建。只建 runtime 会让宿主用到过期的 keys 产物, # 而那种不一致极难从现象反推(接口存在、行为却是旧的)。 echo "==> 构建 onekey-zcash-keys" -(cd "${ROOT}/crates/zcash-keys-runtime" && wasm-pack build --mode no-install --locked --target web --out-dir "${ROOT}/pkg-keys" --release) +(cd "${ROOT}/crates/zcash-keys-runtime" && rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${ROOT}/pkg-keys" --release) echo "产物:$(du -h "${ROOT}"/pkg/*.wasm "${ROOT}"/pkg-keys/*.wasm "${ROOT}"/pkg/storage-benchmark/*.wasm | tr '\n' ' ')" if [ "${OUT}" = "${ROOT}/pkg" ]; then + python3 "${ROOT}/scripts/package-release.py" prepare python3 "${ROOT}/scripts/artifact-manifest.py" write else echo "Custom runtime output: no complete artifact manifest produced." diff --git a/chain-runtimes/zcash/scripts/package-release.py b/chain-runtimes/zcash/scripts/package-release.py new file mode 100644 index 000000000..0be895ec4 --- /dev/null +++ b/chain-runtimes/zcash/scripts/package-release.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Prepare and check the two npm packages without publishing or fetching code.""" + +import argparse +import importlib.util +import json +from pathlib import Path +import re +import shutil +import subprocess +import tarfile +import tomllib + + +ROOT = Path(__file__).resolve().parent.parent +PACKAGES = {"pkg": "onekey-zcash-runtime", "pkg-keys": "onekey-zcash-keys"} + + +def version(root): + return tomllib.loads((root / "Cargo.toml").read_text())["workspace"]["package"]["version"] + + +def check_version(value, expected, tag): + if value != expected or not re.fullmatch(r"\d+\.\d+\.\d+(?:-rc\.\d+)?", value): + raise ValueError("Release version must exactly match the workspace version") + required_tag = "rc" if "-rc." in value else "latest" + if tag != required_tag: + raise ValueError(f"Version {value} requires npm dist-tag {required_tag}") + + +def prepare(root): + release_version = version(root) + for directory, name in PACKAGES.items(): + target = root / directory + path = target / "package.json" + package = json.loads(path.read_text()) + if package["name"] != name or package["version"] != release_version: + raise ValueError(f"Rebuild both WASM packages: {directory} version mismatch") + module = name.replace("-", "_") + package["files"] = [f"{module}.js", f"{module}.d.ts", f"{module}_bg.wasm", "LICENSE"] + if directory == "pkg": + benchmark = json.loads((target / "storage-benchmark/package.json").read_text()) + if benchmark["version"] != release_version: + raise ValueError("Rebuild the storage benchmark with the same version") + # wasm-pack's nested ignore-all file otherwise excludes these npm files. + (target / "storage-benchmark/.gitignore").unlink(missing_ok=True) + package["files"].append("storage-benchmark") + if (target / "snippets").exists(): + package["files"].append("snippets") + package["repository"] = { + "type": "git", "url": "git+https://github.com/OneKeyHQ/app-modules.git", + "directory": f"chain-runtimes/zcash/crates/{'zcash-runtime' if directory == 'pkg' else 'zcash-keys-runtime'}", + } + package["publishConfig"] = {"access": "public", "registry": "https://registry.npmjs.org/"} + shutil.copyfile(root / "LICENSE", target / "LICENSE") + path.write_text(json.dumps(package, indent=2) + "\n") + + +def verify_tarball(archive, source, name, release_version): + with tarfile.open(archive, "r:gz") as tar: + files = {} + for member in tar.getmembers(): + if not member.isfile() or not member.name.startswith("package/"): + raise ValueError(f"Unexpected npm archive member: {member.name}") + relative = member.name.removeprefix("package/") + if Path(relative).is_absolute() or ".." in Path(relative).parts or relative in files: + raise ValueError("Unsafe or duplicate npm archive member") + files[relative] = tar.extractfile(member).read() + package = json.loads(files["package.json"]) + if package["name"] != name or package["version"] != release_version: + raise ValueError("Packed package identity mismatch") + required = {"package.json", "LICENSE"} + module = name.replace("-", "_") + required.update({f"{module}.js", f"{module}.d.ts", f"{module}_bg.wasm"}) + for directory in ("snippets", "storage-benchmark"): + required.update(p.relative_to(source).as_posix() for p in (source / directory).rglob("*") + if p.is_file() and p.name != ".gitignore") + if not required.issubset(files): + raise ValueError(f"npm archive is incomplete: {sorted(required - files.keys())}") + for relative, content in files.items(): + if content != (source / relative).read_bytes(): + raise ValueError(f"npm archive differs from verified artifact: {relative}") + + +def pack(root, expected, tag, revision, allow_dirty=False): + check_version(version(root), expected, tag) + spec = importlib.util.spec_from_file_location("artifact_manifest", ROOT / "scripts/artifact-manifest.py") + artifact = importlib.util.module_from_spec(spec) + spec.loader.exec_module(artifact) + artifact.verify(root, revision, allow_dirty) + output = root / "dist" + output.mkdir(exist_ok=True) + for directory, name in PACKAGES.items(): + result = subprocess.check_output([ + "npm", "pack", "--ignore-scripts", "--json", "--pack-destination", str(output.resolve()), + ], cwd=root / directory, text=True) + filename = json.loads(result)[0]["filename"] + if filename != f"{name}-{expected}.tgz": + raise ValueError("Unexpected npm archive filename") + verify_tarball(output / filename, root / directory, name, expected) + print(f"Verified {filename}") + shutil.copyfile(root / "zcash-wasm-manifest.json", output / "zcash-wasm-manifest.json") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("operation", choices=("prepare", "pack")) + parser.add_argument("--version") + parser.add_argument("--tag", choices=("rc", "latest")) + parser.add_argument("--revision") + parser.add_argument("--allow-dirty", action="store_true", help="Local pack checks only; never publish these archives") + args = parser.parse_args() + if args.operation == "prepare": + prepare(ROOT) + elif not all((args.version, args.tag, args.revision)): + parser.error("pack requires --version, --tag and --revision") + else: + pack(ROOT, args.version, args.tag, args.revision, args.allow_dirty) diff --git a/chain-runtimes/zcash/scripts/test_artifact_manifest.py b/chain-runtimes/zcash/scripts/test_artifact_manifest.py index 34a2f1442..17bfcb500 100644 --- a/chain-runtimes/zcash/scripts/test_artifact_manifest.py +++ b/chain-runtimes/zcash/scripts/test_artifact_manifest.py @@ -1,7 +1,9 @@ import importlib.util +import json from pathlib import Path import tempfile import unittest +from unittest.mock import patch spec = importlib.util.spec_from_file_location("artifact_manifest", Path(__file__).with_name("artifact-manifest.py")) @@ -10,6 +12,19 @@ class ArtifactManifestTests(unittest.TestCase): + def test_lockfile_drift_is_rejected(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "Cargo.lock").write_text("current lock") + (root / artifact.MANIFEST).write_text(json.dumps({ + "formatVersion": 1, "sourceRepository": "OneKeyHQ/app-modules", + "sourceRevision": "revision", "sourceDirty": False, + "cargoLockSha256": "old lock hash", "files": {}, + })) + with patch.object(artifact, "ROOT", root): + with self.assertRaisesRegex(ValueError, "Cargo.lock checksum"): + artifact.verify(root, "revision") + def test_all_three_packages_and_exact_inventory_are_required(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) diff --git a/chain-runtimes/zcash/scripts/test_package_release.py b/chain-runtimes/zcash/scripts/test_package_release.py new file mode 100644 index 000000000..4a767c7fa --- /dev/null +++ b/chain-runtimes/zcash/scripts/test_package_release.py @@ -0,0 +1,82 @@ +import importlib.util +import io +import json +from pathlib import Path +import tarfile +import tempfile +import unittest + + +spec = importlib.util.spec_from_file_location("release", Path(__file__).with_name("package-release.py")) +release = importlib.util.module_from_spec(spec) +spec.loader.exec_module(release) + + +class PackageReleaseTests(unittest.TestCase): + def test_prepare_preserves_benchmark_and_rejects_mixed_versions(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "Cargo.toml").write_text('[workspace.package]\nversion = "0.1.0-rc.1"\n') + (root / "LICENSE").write_text("license") + for package, name in release.PACKAGES.items(): + target = root / package + target.mkdir() + (target / "package.json").write_text(json.dumps({"name": name, "version": "0.1.0-rc.1"})) + benchmark = root / "pkg/storage-benchmark" + benchmark.mkdir() + (benchmark / ".gitignore").write_text("*\n") + (benchmark / "package.json").write_text(json.dumps({"version": "0.1.0-rc.1"})) + release.prepare(root) + self.assertFalse((benchmark / ".gitignore").exists()) + package = json.loads((root / "pkg/package.json").read_text()) + self.assertIn("storage-benchmark", package["files"]) + self.assertEqual((root / "pkg-keys/LICENSE").read_text(), "license") + (benchmark / "package.json").write_text(json.dumps({"version": "0.0.1"})) + with self.assertRaisesRegex(ValueError, "same version"): + release.prepare(root) + + def test_prereleases_cannot_update_latest(self): + release.check_version("0.1.0-rc.1", "0.1.0-rc.1", "rc") + release.check_version("0.1.0", "0.1.0", "latest") + for expected, tag in (("0.1.0-rc.1", "latest"), ("0.1.0-rc.2", "rc")): + with self.assertRaises(ValueError): + release.check_version("0.1.0-rc.1", expected, tag) + + def test_missing_benchmark_and_changed_bytes_are_rejected(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + name = "onekey-zcash-runtime" + module = name.replace("-", "_") + files = { + "package.json": json.dumps({"name": name, "version": "0.1.0-rc.1"}).encode(), + "LICENSE": b"license", + f"{module}.js": b"javascript", + f"{module}.d.ts": b"types", + f"{module}_bg.wasm": b"wasm", + "storage-benchmark/benchmark.js": b"benchmark", + } + for path, data in files.items(): + target = root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + archive = root / "package.tgz" + + def pack(contents): + with tarfile.open(archive, "w:gz") as tar: + for path, data in contents.items(): + member = tarfile.TarInfo(f"package/{path}") + member.size = len(data) + tar.addfile(member, io.BytesIO(data)) + + pack(files) + release.verify_tarball(archive, root, name, "0.1.0-rc.1") + pack({k: v for k, v in files.items() if not k.startswith("storage-benchmark/")}) + with self.assertRaisesRegex(ValueError, "incomplete"): + release.verify_tarball(archive, root, name, "0.1.0-rc.1") + pack({**files, f"{module}.js": b"changed"}) + with self.assertRaisesRegex(ValueError, "differs"): + release.verify_tarball(archive, root, name, "0.1.0-rc.1") + + +if __name__ == "__main__": + unittest.main() From 790f36c673ed0f40eff5938adf953db3eb4674af Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Sun, 20 Sep 2026 15:14:30 +0900 Subject: [PATCH 07/97] fix: validate zcash recipients and remove pre-release compatibility --- .../crates/zcash-keys-runtime/src/bindgen.rs | 6 ++ .../crates/zcash-keys-runtime/src/keys.rs | 62 ++++++++++++++++++- .../src/transparent_send.rs | 4 +- .../zcash/crates/zcash-runtime/src/send.rs | 11 ++-- .../zcash/crates/zcash-runtime/src/wallet.rs | 6 +- 5 files changed, 76 insertions(+), 13 deletions(-) diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs index 83adc9991..139caed4d 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs @@ -7,6 +7,12 @@ use zeroize::Zeroizing; use crate::{keys, sign, transparent_send}; +/// Check recipient encoding, network, and supported receivers locally. +#[wasm_bindgen(js_name = validateAddress)] +pub fn validate_address(network: &str, address: &str) -> Result { + Ok(keys::validate_address(network, address)?) +} + /// 从助记词派生该账户的 UFVK。助记词与种子在 Rust 侧用完即擦。 #[wasm_bindgen(js_name = ufvkFromMnemonic)] pub fn ufvk_from_mnemonic( diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs index d1e29d062..e398cabb6 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs @@ -13,8 +13,8 @@ use serde_json::json; pub fn parse_network(s: &str) -> Result { match s { - "main" | "mainnet" => Ok(Network::MainNetwork), - "test" | "testnet" => Ok(Network::TestNetwork), + "main" => Ok(Network::MainNetwork), + "test" => Ok(Network::TestNetwork), other => Err(KeysError::with( ErrorCode::InvalidNetwork, json!({ "value": other }), @@ -22,6 +22,29 @@ pub fn parse_network(s: &str) -> Result { } } +/// Decode only recipients supported by the transaction builders. +pub(crate) fn supported_recipient( + params: &impl zcash_protocol::consensus::Parameters, + encoded: &str, +) -> Option { + use zcash_keys::address::Address; + // Host routing uses canonical lowercase Unified Address prefixes. + if encoded.starts_with("U") { + return None; + } + match Address::decode(params, encoded)? { + address @ Address::Transparent(_) => Some(address), + Address::Unified(address) if address.has_orchard() => Some(Address::Unified(address)), + _ => None, + } +} + +/// Validate a recipient locally without storage, scanning, or network access. +pub fn validate_address(network: &str, encoded: &str) -> Result { + let params = parse_network(network)?; + Ok(supported_recipient(¶ms, encoded).is_some()) +} + /// 从 BIP-39 助记词派生该账户的 UFVK。 /// /// 助记词与派生出的种子都在函数内擦除;返回值只有可公开的 UFVK 字符串。 @@ -188,6 +211,39 @@ mod tests { const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + #[test] + fn recipient_validation_checks_network_checksum_and_supported_receivers() { + use zcash_address::unified::{Address, Encoding, Receiver}; + use zcash_protocol::consensus::NetworkType; + + let ufvk = ufvk_from_mnemonic("main", TEST_MNEMONIC, 0).unwrap(); + let ua = unified_address_with("main", &ufvk, "orchard").unwrap(); + assert!(validate_address("main", &ua).unwrap()); + assert!(!validate_address("test", &ua).unwrap()); + assert!(!validate_address("main", &ua.to_uppercase()).unwrap()); + let mut corrupt = ua.clone(); + corrupt.pop(); + corrupt.push(if ua.ends_with('q') { 'p' } else { 'q' }); + assert!(!validate_address("main", &corrupt).unwrap()); + for receiver in [Receiver::P2pkh([1; 20]), Receiver::P2sh([2; 20])] { + let no_orchard = Address::try_from_items(vec![ + receiver, + Receiver::Unknown { + typecode: 65535, + data: vec![1; 43], + }, + ]) + .unwrap() + .encode(&NetworkType::Main); + assert!(!validate_address("main", &no_orchard).unwrap()); + } + let transparent = transparent_address("main", &ufvk).unwrap(); + assert!(validate_address("main", &transparent).unwrap()); + assert!(!validate_address("test", &transparent).unwrap()); + assert!(!validate_address("main", "u1not-an-address").unwrap()); + assert!(validate_address("regtest", &ua).is_err()); + } + #[test] fn transparent_account_pubkey_is_chain_code_and_compressed_key() { let ufvk = ufvk_from_mnemonic("main", TEST_MNEMONIC, 0).unwrap(); @@ -216,6 +272,8 @@ mod tests { assert!(parse_network("main").is_ok()); assert!(parse_network("test").is_ok()); assert!(parse_network("regtest").is_err()); + assert!(parse_network("mainnet").is_err()); + assert!(parse_network("testnet").is_err()); } #[test] diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs index 76ee4622b..2a45f3367 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs @@ -233,7 +233,7 @@ impl TransactionPlan { } fn plan_transaction(request: TransparentTxRequest) -> Result { - if request.network != "main" && request.network != "mainnet" { + if request.network != "main" { return Err(KeysError::with( ErrorCode::InvalidNetwork, serde_json::json!({ "value": request.network }), @@ -1137,7 +1137,7 @@ fn require_transparent(address: RecipientAddress) -> Result } fn parse_recipient_address(encoded: &str) -> Result { - match Address::decode(&MAIN_NETWORK, encoded) { + match crate::keys::supported_recipient(&MAIN_NETWORK, encoded) { Some(Address::Transparent(address)) => Ok(RecipientAddress::Transparent(address)), // Unified Orchard receivers receive Ironwood notes after NU6.3. Never silently // fall back to a public receiver when a Unified Address lacks this receiver. diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs index b06bcbd38..9b2c02f6d 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs @@ -179,10 +179,8 @@ fn explain_insufficient( /// 解析宿主传来的找零池名。构造与报价共用,避免两处各写一份而写歪。 pub fn parse_change_pool(name: &str) -> Result { match name { - // Orchard 自 NU6.3 起是只出不进的单向闸门 —— 找零进不去。 - // 把它留作合法取值只为历史兼容,新交易不该用。 + // NU6.3 makes Orchard spend-only; new change must enter Ironwood. "ironwood" => Ok(ShieldedPool::Ironwood), - "orchard" => Ok(ShieldedPool::Orchard), // Sapling 不是合法的找零去处,理由和 `parse_spend_source` 拒它一样, // 而且更硬:本方案裁掉了 Sapling 的 Groth16 证明参数,建不出 Sapling // 输出。就算建得出,那笔找零也进了一个本钱包只读不可花的池子 —— @@ -197,9 +195,8 @@ pub fn parse_change_pool(name: &str) -> Result { /// 解析宿主传来的「只从这个池子花」。`None` 表示不限制(见 /// `SendPolicy::spend_source`)。 /// -/// 与 `parse_change_pool` 分开而不是复用:那里 sapling 是合法取值(历史找零 -/// 目标),这里不是。本方案不发 Sapling 证明,接受 `"sapling"` 只会把一个 -/// 必然在证明阶段失败的请求放进来,还让调用方以为可行。 +/// Orchard remains a valid spend source, but cannot receive new change. +/// Sapling spending is unsupported because this runtime does not ship its prover. pub fn parse_spend_source(name: Option<&str>) -> Result> { match name { None => Ok(None), @@ -1171,7 +1168,7 @@ mod policy_tests { #[test] fn sapling_is_not_a_spendable_source_nor_a_change_destination() { assert!(parse_change_pool("ironwood").is_ok()); - assert!(parse_change_pool("orchard").is_ok()); + assert!(parse_change_pool("orchard").is_err()); assert!(parse_change_pool("sapling").is_err()); assert!(parse_spend_source(Some("sapling")).is_err()); } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs index b7df8ad09..e71786938 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs @@ -20,8 +20,8 @@ pub type Db = WalletDb; /// 网络选择。跨 wasm 边界时用字符串,不暴露 Rust 枚举形状。 pub fn parse_network(s: &str) -> Result { match s { - "main" | "mainnet" => Ok(Network::MainNetwork), - "test" | "testnet" => Ok(Network::TestNetwork), + "main" => Ok(Network::MainNetwork), + "test" => Ok(Network::TestNetwork), other => Err(RuntimeError::with( ErrorCode::InvalidNetwork, json!({ "value": other }), @@ -77,6 +77,8 @@ mod tests { assert!(matches!(parse_network("main"), Ok(Network::MainNetwork))); assert!(matches!(parse_network("test"), Ok(Network::TestNetwork))); assert!(parse_network("regtest").is_err()); + assert!(parse_network("mainnet").is_err()); + assert!(parse_network("testnet").is_err()); } #[test] From ba2b1331c6552b469ac394975fa426de42973e12 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Mon, 21 Sep 2026 01:28:50 +0900 Subject: [PATCH 08/97] fix: verify zcash transparent previous transactions --- chain-runtimes/zcash/README.md | 6 + .../crates/zcash-keys-runtime/src/bindgen.rs | 8 +- .../crates/zcash-keys-runtime/src/lib.rs | 1 + .../src/transparent_prevouts.rs | 128 ++++++++++++++++++ .../tests/fixtures/README.md | 13 ++ .../tests/fixtures/previous-transactions.json | 15 ++ 6 files changed, 170 insertions(+), 1 deletion(-) create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/previous-transactions.json diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md index c9613e878..a7fd696cb 100644 --- a/chain-runtimes/zcash/README.md +++ b/chain-runtimes/zcash/README.md @@ -312,6 +312,12 @@ Software keyrings use this sequence for Unified recipients: request, all effects of the original PCZT, and the proved PCZT before signing. 4. `runtime.pcztExtractStateless` verifies and extracts the final transaction. +`parseTransparentTransactions` verifies raw previous transactions against their +requested transaction IDs and returns transparent output values, scripts, and +coinbase status. The host supplies the mined height for legacy transaction branch +selection and must check each UTXO's output index and value against the result. +This API uses only the keys module; no wallet database or scan is required. + The host owns transparent outpoint reservations, signature-time UTXO revalidation, pending broadcast records, and submission to its node. The recipient's wallet scans to discover and later spend the received shielded notes; the sender does not diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs index 139caed4d..0c3f3aa22 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs @@ -5,7 +5,7 @@ use wasm_bindgen::prelude::*; use zeroize::Zeroizing; -use crate::{keys, sign, transparent_send}; +use crate::{keys, sign, transparent_prevouts, transparent_send}; /// Check recipient encoding, network, and supported receivers locally. #[wasm_bindgen(js_name = validateAddress)] @@ -117,6 +117,12 @@ pub fn seed_fingerprint(seed: Vec) -> Result { Ok(keys::seed_fingerprint(&seed)?) } +/// Parses and verifies previous transactions without loading wallet state. +#[wasm_bindgen(js_name = parseTransparentTransactions)] +pub fn parse_transparent_transactions(request_json: &str) -> Result { + Ok(transparent_prevouts::parse_json(request_json)?) +} + /// Quotes a mainnet V6 transparent transaction without loading wallet state. #[wasm_bindgen(js_name = transparentTxQuote)] pub fn transparent_tx_quote(request_json: &str) -> Result { diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs index 90641a318..8a597a1eb 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs @@ -14,6 +14,7 @@ pub mod error; pub mod keys; pub mod sign; +pub mod transparent_prevouts; pub mod transparent_send; #[cfg(target_arch = "wasm32")] diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs new file mode 100644 index 000000000..51ea309a9 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs @@ -0,0 +1,128 @@ +use serde::{Deserialize, Serialize}; +use zcash_primitives::transaction::Transaction; +use zcash_protocol::consensus::{BlockHeight, BranchId}; + +use crate::{keys::parse_network, ErrorCode, KeysError, Result}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Request { + network: String, + transactions: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PreviousTransaction { + txid: String, + raw_tx: String, + height: u32, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ParsedTransaction { + txid: String, + is_coinbase: bool, + outputs: Vec, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Output { + value_zat: String, + script_pub_key: String, +} + +pub fn parse_json(request_json: &str) -> Result { + let invalid = || KeysError::new(ErrorCode::InvalidTransactionRequest); + let request: Request = serde_json::from_str(request_json).map_err(|_| invalid())?; + let network = parse_network(&request.network)?; + let parsed = request + .transactions + .into_iter() + .map(|previous| { + if previous.height == 0 { + return Err(invalid().detail("previous transaction height is required")); + } + let bytes = hex::decode(&previous.raw_tx).map_err(|_| invalid())?; + let mut reader = &bytes[..]; + let branch = BranchId::for_height(&network, BlockHeight::from_u32(previous.height)); + let tx = Transaction::read(&mut reader, branch).map_err(|e| invalid().detail(e))?; + if !reader.is_empty() || !tx.txid().to_string().eq_ignore_ascii_case(&previous.txid) { + return Err(invalid().detail("previous transaction does not match its txid")); + } + let bundle = tx.transparent_bundle().ok_or_else(invalid)?; + Ok(ParsedTransaction { + txid: tx.txid().to_string(), + is_coinbase: bundle.is_coinbase(), + outputs: bundle + .vout + .iter() + .map(|output| Output { + value_zat: u64::from(output.value()).to_string(), + script_pub_key: hex::encode(&output.script_pubkey().0 .0), + }) + .collect(), + }) + }) + .collect::>>()?; + serde_json::to_string(&parsed).map_err(|_| invalid()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{json, Value}; + + fn request() -> Value { + serde_json::from_str(include_str!("../tests/fixtures/previous-transactions.json")).unwrap() + } + + #[test] + fn parses_real_v4_and_v6_previous_outputs() { + let parsed: Value = + serde_json::from_str(&parse_json(&request().to_string()).unwrap()).unwrap(); + assert_eq!(parsed[0]["outputs"][0]["valueZat"], "100000000"); + assert_eq!(parsed[1]["outputs"][0]["valueZat"], "1000"); + assert_eq!( + parsed[1]["outputs"][0]["scriptPubKey"], + "76a9149564d9fed247986b15a2f57d0b3b032eeb28476c88ac" + ); + assert_eq!(parsed[0]["isCoinbase"], false); + assert_eq!(parsed[1]["isCoinbase"], false); + } + + #[test] + fn rejects_mismatched_malformed_and_trailing_data() { + for mode in ["txid", "truncated", "trailing", "hex", "height"] { + let mut request = request(); + let tx = &mut request["transactions"][0]; + match mode { + "txid" => tx["txid"] = "00".repeat(32).into(), + "truncated" => tx["rawTx"] = "04000080".into(), + "trailing" => tx["rawTx"] = format!("{}00", tx["rawTx"].as_str().unwrap()).into(), + "hex" => tx["rawTx"] = "zz".into(), + "height" => tx["height"] = 0.into(), + _ => unreachable!(), + } + assert!(parse_json(&request.to_string()).is_err(), "{mode}"); + } + } + + #[test] + fn recognizes_coinbase_instead_of_assuming_regular_inputs() { + let mut request = request(); + let mut bytes = hex::decode(request["transactions"][0]["rawTx"].as_str().unwrap()).unwrap(); + // The V4 fixture has one transparent input after its eight-byte header. + bytes[9..41].fill(0); + bytes[41..45].fill(0xff); + let tx = Transaction::read(&bytes[..], BranchId::Nu6_2).unwrap(); + request["transactions"] = json!([{ + "txid": tx.txid().to_string(), "rawTx": hex::encode(bytes), "height": 3490000, + }]); + let parsed: Value = + serde_json::from_str(&parse_json(&request.to_string()).unwrap()).unwrap(); + assert_eq!(parsed[0]["isCoinbase"], true); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md new file mode 100644 index 000000000..1793e0a85 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md @@ -0,0 +1,13 @@ +# Previous transaction fixtures + +Public Zcash transactions fetched on 2026-09-20 through OneKey's test-environment +`POST /wallet/v1/network/raw-transaction/list` endpoint (`networkId: zec--0`). +The fixture records the raw transactions and their mined heights: + +- `69ff03c1e3d19df98087396f86783addbc9f8ad615022efdeb5de10fe78597ae`: V4, height 3490000, output 0 is 100000000 zatoshi. +- `70177881b2a62c93ed023725a24166362a5bd65cc93dbbd3b3a243ff5927d89c`: V6, height 3476066, output 0 is 1000 zatoshi. + +These are public chain data, not spendable test credentials. Tests verify the +transaction IDs from the bytes before using the outputs. The coinbase test +mutates the V4 input into a synthetic coinbase outpoint and recomputes its ID; +it does not represent a mined transaction. diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/previous-transactions.json b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/previous-transactions.json new file mode 100644 index 000000000..8dc80e1b4 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/previous-transactions.json @@ -0,0 +1,15 @@ +{ + "network": "main", + "transactions": [ + { + "txid": "69ff03c1e3d19df98087396f86783addbc9f8ad615022efdeb5de10fe78597ae", + "rawTx": "0400008085202f890117699175d8be6b17f152bffd0989847fde1f079b5201f363d76a6e0e3d175e85000000006b483045022100e18e7e7f1f91a3b2801b12cbaee85ee23d6723a3f7f608162eee668f6c99cee402205056b948b456858b58ea9204ed4c34d6ec9d6c836675bd30d3e621485946f9ae01210223fa326a1f5d5c85b9cb6a8b574ce828b38bb3bcc789da448f2f66f6731d3ca7ffffffff0200e1f505000000001976a914aea70bc6d77fe2369ddb9a8758e3bbf83bcef96e88ace0789408000000001976a914d5af23c4d585c1496fed2e88582473e97de851eb88ac00000000ff64cd1d0000000000000000000000", + "height": 3490000 + }, + { + "txid": "70177881b2a62c93ed023725a24166362a5bd65cc93dbbd3b3a243ff5927d89c", + "rawTx": "0600008098b684d85b16a53700000000890a35000001e8030000000000001976a9149564d9fed247986b15a2f57d0b3b032eeb28476c88ac000000027dda7edf24fb49e6a688abafea52dbbec2cd9427e20f8c97b3ba25c8a8fc73266a490b5f302b639afb45648c5b3c0f3f3f63ea52ba79a71a29e38eca0ede5f3af17b0377cca55ff5253226ce8f67acd7609f64c9873ab177e670465ded636e8c865cf3ebc50965b00a1b5dda951a67612b87656a58bc2c730c64e9df2c2fd02a276014bc0d6744fe10f51e65d7d7df44c699c6e0a621c3a8c67e4a609401c837c4409a7023e4f41400e87d1711e86277bd8f3898de56bd2a85f2f7742f19d7e5f49a66ad8049dff2321ce9201ff9a765897e5396f31e513367b150128b32f15db70e5f6286082dd50f571670515c000299ffd755c2bcf9ddca1be6339ac602496a6cba5ad769df8feb4a374d63328f1e3bed5b66ebe772e02988426b98bf44b01dda5a4a021e07f1b0327a0612b170ee0671dac959eb029e43d6b5f4d00e6bb29f77728c82ccdfaf6341e6563d17b6b816b03ad3d1a78c8378ecc5eda98cf7c69f2bfbaf3a1f4a7c5de7ebbf39622b59d6485189ad03b6e2cb5aa87cb4df73dc6b39071bb9ecd1a888fec04b428aeb6bbd33aca58f4f6f2a6eced4ccf123c6ac686883dedd1ef96856cfc4a58ad9272165f24ba4d1e9cba91d30aa1d2ec9d0d0b3bb0a06e925f460a88b129dce20499c07a3ef02388475d8314c41142515d37338f9b9312e2c14a39b84f4586867717e94f5ae6719922cc3480efe7aedc30a1d915561418d6c9c74fe4925fc8218a9a7a698374d958cfa569d57b3c6da21ed0a2bea669412086294a2bd325d37f0887aeeba5b93b9f738c51f6c4f28e0c770016c38ef9241fad5156c28870c36e469897405464e0ab00cc6eb0a30effe00c651a9711e0fed404ee0a30b61f0d775e56fed9f8e37c3d51aad0a55fa81a11bcdcad13dc11c5e1fa21b972481c1686fa6751e62ec580bb64b3947f80cebbf0e40fbe3881d235519df44c22aeca9fa83bb651f2af6db786ec019b0c176bd91be04b3e67c1e4ca44dafbcc3a6418900f759e7f9ae206110a0ab3d74c020c52d90463b76de67b9ed8384bc5265559e9f8b33dde4d966d39d955e356af6b22ca19dc7635f5536eb13d90dd3fbfeaa36d8e4c1108f69b7d1eae71391ebfa9b4ebdb844de3799d4a7bfa10a22d1dd1952867f003091c33b1cee25aa0d3dee777f061c9a66fdf67dbdf033fd6d59d09a89fa25235f74a4ad06094e918ea7d62851a1ccf8e3e8affc1ecf1bc711a98dffdec8458f745fcc5039e411e337275ed0066d6ab6fb569a82f4dda789f4ffbbf5a830550ac5d354622337e7107b5df60c32ef03ed0db5ee9298040c13460cd685f8c4c100611cd65e2ff2881328cc2f5e736d748d363edc82377f25cd70b5d48c0793f949631ccc5f378a391fa575e0744ab7e257ba8a5a978b05007a0fb15e3abf8a50df69f96df3d697a75dc4e1e21ebcb4a0b1daef6d78450c797325c8ca9fd8188920976f7102504f0d3ae3234afbd44147efd345f297f98e74d3a096ba215cd0d776c02c88bdb72fac4c774f20a68cf82bc2d04f871246babaae626b60afc1fdef99697eb2a82f5687bd9abd6cc6c863fe5a5dd77fec6fed45f53355ac46f690b54f6bc28ba2ef8a1403b55a66fb80eb9691f289a76296d286ecca2d0ae4fa285f68923cf050e6940121e0f827a2f045c3a560da7d3b8de2446391311cd62a0b06d4a7523caca47b4ddac7ce589a88d832c371e5d8405a69d4f3ad412c786234cff667d6f3edc61fbb82711ecf2fe83343aca77c46083b648fa80a6cb5f4b286b3ac8cf3ae6490d4e07d89b2392bde4a0fd1f487f79dc8ac79ff201b1b1d677fcb131bf15bd34a4a84730608849d4df0b69cb250dbc3fa41c45ab1842037cbd1f2996d8b1729d3443eaecd8150e3efee9fd77693cb16ef3a69956842fb257066fdc513e0dde5617fab5ac2132474abd6654d4bb5341f443bc4ff1462b3cf47345c07764ecc6639d5175dd6e2e9edf13e572735dbe777514fc21af8fb6ce0621c369a98f46d0d0b8f4f99f30019b27299b260aee22fb15431ddf8c34661fb213c94536e2846d35dcceb3276ba194c0021094a9cb80cd2915fc8eb8ea9c9c6824cb2bdba23ce7891656d0e717f998e0c9596d7f28baba07ca47b4c5377d37b615c4af34429cbb8eeac49bc809a8a571851bf8a9e5405ea3431e2a4d710b97f90639e04e3126359623e35130832730c8bffdefe0627bace75ca818b76aad897ae0dfb326e3a5e1128677dff7b82aa9d0b0e3f2c94be5fe02f1abf36489b1af8c29f7f9c62480c5cae51747705b1c8662cb5597bd3fe3f6da67701768307803e000000000000b42479f6f64477396fcccb0b672bd0722b5345689122677ff88385970c3acd21fd601c3b83828b7d5c5bf64104c3d38697068121167a2cd5b668ba4cb1f24b9c68fc1eb38304a0193869aa3c3951d7554b3a97b16f7a3b6ef65d0f6d1356cd471021ac66ddcfb1a9c878d9f96ebc1702b77f753b014535993d191b886c424ad47b9d1d80e8def985be67a9a210e5eb138213b59ad354676f283bd270868d2c411d3313d5f7c3e6c24a3783a23471999b875715e9425e3405766848dccbc8cbc115b0028f91a0f6332759a9f557355074f8a837a1a301deae944b7c7a39d01d1795232cebc29ff5379ebcf821621eab1847d22fbf12bc2684a7d0f272644278e2a1f88ef9ba1ed5db23d07185bdacd3fc962ad39ceb94f2bcec114944e532518be2631e329c2aa4ddcf06d9f9d2a79a4f2d0d956ab118336737813b7f2351634bc2a9a98d5cca035c13599dc78e343543d0dc80877485fbf9d9b9021716335c3a4c2c1e58709c030279727510829427622c56e0f5e999554c897822dd758620d111c904599a11432174df11f53ae8ed3191ba7611315409387beef3e8af18f3c786f1bba129a9be24e87a9dffa301b65eed8e6be08dc68f2f72c0aac233c098eb336a808f213afffee343af4b1c4bd9e3fed0ceb861080a2f9e3acbf3022a18df95f882aa042f8cbb7d709d01a2f52bf3736917c717074b55c08d8a6e87316c7b1a7787c62a05ff29d8300fd80b1ccee432333681c5b9eb759ed356f3ad14ae07c88b04d479d9ecbe74c156a48f693299c3ff23146654d773146dd44924a7c7b287f1a58c0037fb3f5882f48e02211a581376b30644075ae39e893e724339a1dc2977054832b7238474d790523969b792950da430d3a17c8d2a1d4065ea006d14040d830cf70bfbb4072211c4b1f25f66fcd1d5a66a7276a0e07edc7bb77b64d5b03aaa0620257ab00b54fd616db1e60e8ea3f9ab4819f028025a281087e6b05c963e22f8b78d8d2ed8f0ed14d1aafda605bc3c9cd9b929a42c33b26464d97192d1a88a89baab2d63f909fcde7758c427ded63b718c6625eadf6bf2ee591831dce08d9604eafb855eaa3d456b97d3aab185fd718581e642bbe1c5a2dcfdeab2f1fb39b2c419d89a49c1ed3c7877256cf47f61b0a9edc838adcdbbeaca6b30dca3e5bba3d7176ae2db5ed38b5af8a99855557d49d427d0c5a2c19a844e8f441a9dfb551034f68619a422ae9e397b0818fb994f29e83a6299874058b7077f80eabac921baeb9960b2466ed2cdd9870ed49a6df8ce663bf3220c61bccfc8dfe66a5190d6bbf2570a9396071195fec6741daf64f2bc977da2d5b250cb0e420c1e4e9d538a2562b9d3175256a16fe8b94215fb92d2594095b183e81cd4285f22e1a62e9e149eab486fff3d29d10488043c21d5eab0b2f127ba8ffcd0a1c6c63a94acb8fcb2014ba3460eb52ea0b0f12d121a2eabfd6f0ffd2b0be7a5ac7794fd4563ebdf7d1cdbc688c380f6c9e8131976f5cf052bdff2a646f09467c4c9e654112a4f52c63c838a6409f96b401ed7358274ee5ffe0367f20b200d52d68ad577db94e51cea97bdd86fabdf08cbd4eb98865b464ce30e4d9ef6e4f0b17e911f7307cbe43a5dba0cbbacec902a43206ee43e7b212f4d752e768387116c770744dc7c4f3363d09128fef6329b61c081dc175b3ccebbea3047185b3db0e497f8ffe6d72e98af1a0d37a077b4f5c8432aa1d428d3e5efabe6a982d0cc47d2632363c44dd90bc08217a9b81b81fd15615c65e67ee7c8ba149bb2e0d8ebfe9facd2d7fdeb230fb3ed1fda983b03dfd6d647533781b88b78c5ae6c9d1656c7ad509849de5ddb5edc072e95d202a0ccaa8bf6239cc0d18de583b4ee3542a6e37b10ceb4ad586f87c7a6a749b751bb132b823f2db7009ee37994f05afd2b75e5d205ba336f524fde24c5935b64252b7145b08dc2383dcae6cedc77c9b7c3ada777c091524edc08bbaf798095a87de7957747ba7b1812c0930463fa183fb96991c4c43c69e34411ee6a9c3c83e2c630846e33b1b4224297715d6902974635d56daf1f0e94a649b1a95e7c319aa42c690374767026c74973f1c97035bbe8353c359b4bb0295615702f0b39336078c2e1462aec15e73021fd8db9a9c3905f73d51b61c1e29566b319981715823c848a2ad3bb001186b7290a19072ba1ce44a259abfafa6c462fbeb39c72b085c03a965c42eb25ed2c0853e3646e014ef0bb92c486f8bf4dfed50e8bc9043130486dee297732071dc7079d4b1d24b2463e6c730db78602e80d0ec843ed5e540111239b733bc81c870475f9e43c071168bdf0e022a5cfb0aa69977078fe78e30b44a5cfe205d4377816c143f6cb2bdd4881cf645e28aa32ca2f51f90c8aac47ac08b4443bd90d5db0713bd60a16d6ca540b48506ad3a7ed62f359193fe1cd6e36df81a50d17c714c096679d9462366d8467c29153dcb6f270c296407b008565013946e6f20c65c21f7f6dc4014ccd8b92461588c801082aad19f0c8f6f658683f30dab9baef74080825a10df950c0e0c2751f7bf3d9d500ad65eb7ee6817a6637474fc40f480e796ea8e40b58c69b6447116962d148292758a5955f468fb8571128a4e3921b8d898a60a6fe9d402af3f0be25f051bc98bfafa47017e4ab4a05346fd155f638f1686e9e5d54946f9143cbc7988f384050adc985bee40d98023326dc6b75a07eac8f6d16bd3cb7af2732321bf3586991434a12503f066ec17ca328cc718f5937c4b05c161da30c2c75476cfd9f0c42ae4ab8ee0da18e7347ae5a360167abb145bf2b06af8739b481d8a55594cd8653f29b63fe2815b9227f62550fb1b21b8c36763d756492736097bb834b9b6562b683c41e0eef5be3b4d28a210430782dfa8bd21f159aeecb5e0c8c359523bbe727124172090620ed1616ed552628d0dfb0e760124ae7906e868aaca9045c5977c8769d31d11512a0f96b6b84355190209eac3cea45cf052799f4596d08773c5b2ea09f6e5d56004f77d0603c2bd2b19624f02e2d1d07db4c74a43b67f6ad56b4f77883929e2e12e1a982b7053d976f847f1db062ab8a57b1ee68dab848606207be9ae969cb0321a56d4aca2a0e375b8cd20314d9f8e52eaa0a4f4b013ef5203573e0e4a61b5a2917ede0fd0e009755f83879325a8cd6bd819a4e9f1e6b982da9c52a102c1b1458f80ec499f73d9cbbf515e00987a2dfeb41be319d8a397cc032a46ff6ef211b07a47e79de772c8712d430f64b504144a0246d38690c54838105f9b4037fa54898353e8b099801df711ab9557b7a5f60f1042e4f377c8337f4962d709264d7e85741674f464c146133e17d7116ac255cedd627cc1cdec802c76f4e1875a9fc60211cc8946c161914bcd46993c46157367c66b2a8ef6d8e4fedb7ea345f6ce6a421b7705bbe093c171f0b8f9867534db5168acaa9f64aefd9c4fd0a0732adca3342a28ad74dd93e89210500993cc87ad77db797232a52b4d1b8ef38791c03913031732d3bef85228fb28c5c8694c07ca6d8b2aa65c098aea31cbdf37479a1da56f44a9dca0160284de0a9fbc2b41658545dc7386d16947299425c6ab691acb6c5818a57a4df1b28fac918e39f26e7fa532a86f7a567f60482d85201b6399cf30284deafd55a6d21b5a7a62684be72af5c1788b4712524214c394c246a6c0046d9687a9b145b522416899c355e29e7a467bca5ddff45041155bfdd17ed786cc2ce44c6f6f1510e1c67aa38f84fca1009299bb7a1cbf8ebd2cc3cf75111c26e73db5161a13d0e6d19155540ae59218d245ae7ea0ff2f46c84665fb5240ae6f8629e267a4a4d170e0b34a6d2ec75c97b93c072f9c7923ffbd4e441c21442e3815607973f3afa2aaa1ccac11f2ef4e2f6a64f8523b8e98c2b7d0e0ba8893cc9141201ab4d54705d27141a60c60667210069de569136502b081ecfb316459191e2b4187a9dbff8e0ca3ea3cdee1347c6bfdce84958c7d164d228866e538bbe2404c2aecb042f3b9b782710f697141b4b9b26c046c91459bcfd501f255315218169b220af50a851843c2839f1706eb7c54cbcd015612c1878a7afc727ea5f58f3393f8de0ec5f1cc26a39d70702650b21a5c14e445198d33cf0787c5b0c6e83022ba7bfb660f58296fe1ae59763258d0b3b6ac0f467d5763af9edf70d18e666ca65cfdbe9aec833b4ea18a2a6f0d28b6f5ff32d4ade7ead29df347a164df943891eb1b34fbe93b041ca07a978912d815de398853b00f756bd286e376a290d8f0b15f6fa2329ee5a6694380988f07e1d6fbb8a4fb22569cc844b9c6ec0c90e59dbe9f721b3035ab85f2a2d8cb2c4833f31bdbcd6bc518f5b14f5b1d69088322fc4129c0df1538e8eb61131eb0f9b54e1a406eace2accbf0c1a44761fae98566bc10839a1f425cd4facbc3f5b813fc190360f8f416059881ff1b7d3bf4beec132046936cae4d207da7fcb2a592a92d8c520e4fc8158415b1ca55e2745464d5a02669ecf7dbfffabd1d896037b476dac3a548f2c97a68648d96d85a4e247953c8dd357b8250eea2977d8c33c0a0e1f7d27af835eab8552bf6a164920c4a4d78c825410a2895e7c744d12af2ed0d9c4955962bac58078357517bc57285fb30a683c27f3eabd237d89566194123aeef8ff6de2d45617e445fa21d9ff69e77c501474dcd852e91a8301bb62dd02e5e53b13734e6217009fae1e5fa755f67e497046281434a05a64f14233299903b82b9f1a8e824348d3086cfc445c228038ea2fb8571f0f7ae4efa9a1f05eab1cf4672a5873bacaf5ad5e1990904b8cb0cfe6d564ecf3f16e1aca77945faecc088c18a26bd5f163e7f71aa56aa9ed9feac697a30c5b3e5b2dce028f3d2d37c803d7379ea90cf47ed6d2e7f813f2983105025d04449fc14a98275ad8599132d71299de8297d626e964535179a471e2d86d68d3b620783f62d6a94d052aff09160cbde576a27c58ee59a0d44c7a02de86d0b88dfda8ed8c3429477d798fbf798922e02516d601514c0f2b351515574ec5eaf7be6d3ee7e9f5e525bb89959b39c21cc550dbb1cec0e01f57be9f7cae57bdaf1642d647e181077701f92baeead14b20434d01c73f2d62e6897346552c18e3bbf34e9d28b49795c74199e9c1855a1816fd745e4b5ffa0f5e2549d4503467366a8ce1a859d88cb332e3cd9ba15f21e43d6eb369f71c696d81f6f1fd93a0dca5fb8cba57ddc78b6c82be07319716f0d6250ef2ee201904707f3e9d5994b32011e36f28ada05feffa000330638b65faf92f7ec9ff45648cf18c38301157314823ba9ae0ffc249a96a470c4f8f3d65c3981e1d2c0c384259801441d3407d46d515a9769b87a18145c44ca444759c445ecc07c5c24e544533129b46036ab79a667dff224d9d6ab2ecd5825008297c8d99b6129503764bbf3a058751843d6b7fd14a22843efc788d0cacdc4ec0ee55dd63353157e283aae339349dfa92ad575563aebb49d1697d57f944831300e34e5fc2fa1a9b45cdbc48a56e98d2501a461a0a56c4861fe8ce74f677b4a93936878b55112f74c718370e78b32bdc99502e772bd9fe4cb87a9feed1276c295fb4b11578c30c6d7671e815a0caa93ba5c33f9c3de7885ef0cdd5ef6e3e99b733eb89fb3234067ecf6174fa0f82f0b1c9d40b0f092627e137e4ad1e26111775b369105f8ba3090f29eef5925bea27c333450ab6b516cd48352cf3beadc4b62e81161e41ec2c09ba797f0d284d93707e4367c7f32b10cac164c2305fad5423e68813ed36fb6c345f7109539f9d27dfc72870a542603037d326972f1807a308e9c28af06d14473ee5576c342c2740018ea87a8f3999bab84407233c4f08ba0a08f0a47203164208c5fb740256b99a22ac00d40c90d20271684c45984a6cb4688cff5b5d82e1c035ba7107d05024f03ce8eca0001fefb8958d6718b702b8ec11271d9112bcb5fc0269f3e081f12848a278312773ac26ba715776029f3a7b664aa94bb83e31deee3f6510baafc40f660fab24a868a6f4a8fdf138bc5466bf2603054746a14032d70772a0f8f8f4877b0bc5dadfcb921bd578b5db5ca31a2be63d252bb8131200b91db7cd9014a1e716436303d2776e236ed4760f8c6acc69b37a81301e8521db022da4818a74f47221ed72d21d07a6f1bc20ba1331e3cdc71069b29aa9bd9e826f28982ea698170472c5a20cbb8e5991b34e2c505248586946d4e4b65f8b3377622bf23eba40ba651005ae0e32a4f1cb7d0ca3505fe39b90786c973c1d886d6375024437e3e6d833fd454acc15658376d1396a3a21997cc46ced4fd83c803343551a91a3b75acc540fe56ee62780b40c3a79de268726e4e572a1eee60429394b0a3884f1cc64e5ef82d406aad1c18484b0680ba59032a0f4dcfd004ae367763537311ad387151ded692c2065e4b286b35c572ff3b9852a69eb68683ccd55caef791abae7bf36134f92981584b2a972bd2b91fbc59c2f92d35e803cc1423011d9c41675d2ae610ff83d97fd5f3870bf370272f0cf8e0bbe0d69dc7031d04fcf348303c8ad1ee7c20f97cae3caee74b3775674a74e31e7c2dde4b4778f31e402cd1b04a993d2b09288df969d50910da2c7572e2ee03c1d8c8e060ec80bf417c214cd151d9b9a28a0bfa00128b781977a6ae8517ece6d081c1e7f5d54d810539032e6096d962915cb6bff796e927ba97909767bb059a0c110fdbca0a95152a9dd4c27248a410ff89d0103cb5414d88533bfff4e7ce114c84ab689c40917910b6f22ff03795d6d474cf354b9017232dd8584777663b72454e7b0e945d02716a599294f2b4a216c4172f9f18aff43c521dd34e60f3d1edada40318e3eaf861b26d9087b1dd8000224b403560d8991ab803c1ebee29c0db5fc15cd0f1ac61cfe2ed847951e4776eb88f65aed9a72f5b7529c6c9a051948994397e920cab00767140bb1c603af77c29be810741a7507144aa2665b9c87a88169cec50dbc413f74e711480d34884a312a60d8790b24b44d59904faed3df28d71f4d0fa4d9f1233a6f8511d718032eb042e3b627fc46f51e1266fb7171ff87202c1175723f9e50538bd6c2fe11be731fb5e3f72eafe6b86772d1e73ebe02fd8d2f1468fbbd3643b1f881f4441b92b7d4ef505518cdbc4a65fe1537dd8825d5d97c352fdd53136118612415a107c16213b2b503fc4717cb55b3bb352443a8ce99c40905ac296aeb25e18fddae1a956d49042973e4c2e525059e353258606953461a3e736c1cb93591feff9b3e3a4823d7c4c387da635631379e751e0fab02ae7211aa0681f0f0a80a91c654441fbbc9d5cd4952ff62dfe54b048401bc6f9d844d0415d74844cfe021df565b3c2145e10103971a64c67874aa971b321cfb6dde55b0bd9561b2c6438c1885f7f429a2273743b41fa87cd0bd029384306e4993ea730db318deeff32a225d660600001f2ca5e5a4136a08df29d764b889b59bb1810c49b0b3ce4ee0ab9aa21f5b1d026b24eecad4a1cf99a3e5cf58fc1e1d78279444bb2a1bd7844edc498df9b5f205c6006e42fb5a2945bdcfa668f341565a87d5c2c4bf5adb7ead9c75637eabff17d1501c6699d96a790a6ee62a6e333d7d3c57097156453cb18681949e176ccc12fa54f43a31360328e66cee28415dbd6cfc833ad38b43413218d76daeaecf2b1b9d73c07899072ae18523b8862ae966ff0c042bed2e986bfce40d0708521d242f2e7dcdb2712c9e6127ab0d1a810998a6b39a0ad063466dab00ba56543dada631da18eee41dcf1b90f372582172d25cfcab7f702a47e02b59bc0a26faed65940fb5074dbf193e99ace30848d9074fff7b5910f54881bdad170e12d576b029b521e1ba1d17c7db67c7682b61c247e383e6a21cf72cdd566a4960a5493a31cb4025cb8f8353827f3c731f9aeb51af2aa063c74c1bc8c88169d4e2cc143d3b8cfb32eefa31edb3905ffe147097b95c99c3eb5a0dcb05771f89f345da5130cedf9e34eef45d332f02c55dcb6eb4ff8d90b421c2e8550ef20d94e7c7aff318e4dfaf06df1e9b5306cc207fb7811ba57236f8d54263b61723d2ae4b952cce2712119e1abb07d5b7b3dfdeba515f150fbd6bc9453c77ad9783cac3620198cab9eedc263e52691c99536ee85520606b33c707f0642ddef6871df61817eff3dbec4f5793321d67a1428625608c172eec7e91e36bc5199eafa3b54a15692d710b0e1374293798ae0394f5955f7eca2996cb01344981081a234614e2cd6c888faff46c80e305b17fec5c26db7511ac6b8feb910209fdf09b1542e5f1531b11dc3318035e412ff71aa9af85ef0ae4903e0d6a8d16d438fe6969b24da1aacd565267518b33d00604370c345c8007c382f1c931daa695d9ef59dfb996629c4d73e69693d8e88a2ee7edaa5b6359067e0676c7eaea9d250cdd50e99173d1e68d54a2ea0085516f1461f7dcbd088dc6d7537f9bd2db5e3436346a22cc67a72fcfa7bef32677e9933f2198659b117541839c9c27b6bb990018779fefacf93ef58ac74481d486109d177dceff7bed85ddc3e82e2c126a66aa84d57caad2edadb33e56511d4becb5d320fd9eff979586d884cf3e34342d4435804d0bb7eb972eae8a21b486e4120b55101b1a52f63bf1d9cb5033496b5258d27c34a94a8813c146cd7aff1b427f99560b4678313b648438c95371c31277d86a78d947110f4bc1b8146d3df402551f351172df48e6ef1eaf0d46b05b16509ca044657afb54084403a135def4c4b9e43c15d0d8dde203d4108064e07822f1021b748f95eb9a983f9259d49becf46642c93e8f10a8a56a4697ee1c653c0f6bc3b6548cb0604a23442b65d459cfb239b44e32e356db260e8634a457649171a7fef6547b971fdd90ddfd8e9548d48922fbeb3937e5900b9e55156ea63547970ab902fd3cb490481e82a3c69b0b08b2a215a03ad5a1277c4e1c7ffd6cf984457a1352735e007246fa12289629781400e648ed086b48442859c126cad10f41d715e01a6bde4241c12a4bfce362be59a1b8a8952379eb22e20e093c2d1d30a0701eb9a3f6f9010703699ed7d6dec9b4d529617c38fe0b9d8188270047c588818b843618b067303770d20449e8cf1df2b74524512db7fa458260ca52b00f46d344499dd82ee951edc94e6da28db68fefba95fe273a52190a10c234aaffbe35534323a9757ef169709b80594ec6b099ec6d156eb1b659c283b1a80c0179fbb18a5a180d6c3d5f43821969aa7c092fcfa06c08762c3b7e4850c76e4180eb1175891fe119b303b823dc8c1fee5fd589edddc238876414ccf36f16f01061616517a92d57d0acc00d7ebb0410a7a8b3761c68b45de850002f76680ee13db5cff191f933b22479e16cb9a973d5183d4528c5d1acc2085627fda64ff2bba9a88b71f32fcbbf82c49b8d9d49477bf9a02901b85b9e5374f5ad6a013900b119a04d532583c847fab9d6bb7f5125babf86f958e05334571dff2a391070b7a33ff77e3dd373e632344bbb7e1d19eab65a7b27fdd8820372a66230a48fd2321606bf2f5cca4f7b69e87d7388cb7ccc5830fcc5517934ff881e9910afeadf194876fe2ed267aefd880633bb37892e87ab561b2145a12cb27d32188bb1eaf7ca6cb4f5c34836637bdbda227230f37b6aec4235bd24657c8dfead530822a5133d69fac63893fbff9ebce128242536307145fc879ba4573d4eb95c918a31a26ac0f985003afe083733a8e5f8d4aab377b100ea05490533517dcc336ca599f7582a07eab9629533df6eb38fdd3ef09963fcf76b84f492ef5833245aecb9979c3e4b09c61b30eb6d31d1f7a3434f3f5f04e6285098320993b51d848d6a349b80e89e6857e8394380d91710eb2ba03221bc4562fe5f8bb7f8f6e1353f4da07733f58ec3c847e54fd6bf31cb32adbb701b6c5bcd79defe5de7901b5ca92010289991b83079959d64dcc140c612f4a773995a0de2abbc2b9c601b026fa5e3340c03fd06fca4c8e2d58d117132cb86647a2a16c1dbf71262ce644e1c178799b9e5941c7cd866bd407196caa9a511acc3c1f0ff73150ce847b6a88aaa8f8c5c2685dba9ba63cefafd89d7ddcf97e133951639cf6d021d92f172437c72968098b3f0ed3040c282cfcb7bced1baa9d17c6af35b97946a16170d8cda40039f08872a35bab3924b871a7620357c329f9c6c0bb9e03fe77313e77e5e4f7f2f151e600c8cb330b21599e4ce616ca5ad16e1548bdfa10c5aa92d7b436d22ccf894fd28364b7e5eb81a5967b1cc3f7cf3dea6c432595a0389cafa00059e3cac41c67bb71427cf56501fcd77cb3c239c73b996774a7fa9fd410e3fe3184900c8578a8d0a988445d0567ad0a2fbbb055cfdf14c4184516d5ce31b3ac4dbad3fe89367c83f0fdcdb1dcab1b8eac5da64183cf9849a471425f2f63135644a45ccd0f5a68cc7b1f3871e32729ea37c1ca433c13011d725898b455e1c74104d9bdd9a99c0ca640a159d4a6040e69480f82da58d9ea45284353cfeee835c023d8f9b07a14d43be376d4421b4f6a1fbbc2b877272098ca2b61bb2d38cb2691e7429619fa53a566709", + "height": 3476066 + } + ] +} From f9cd9f745dbafe825e5f971c97c13f0b2085ad85 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Mon, 21 Sep 2026 11:18:05 +0900 Subject: [PATCH 09/97] refactor: simplify zcash previous transaction parsing --- chain-runtimes/zcash/README.md | 4 +-- .../src/transparent_prevouts.rs | 26 ++++++++----------- .../tests/fixtures/README.md | 2 +- .../tests/fixtures/previous-transactions.json | 7 ++--- 4 files changed, 16 insertions(+), 23 deletions(-) diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md index a7fd696cb..8287b3f88 100644 --- a/chain-runtimes/zcash/README.md +++ b/chain-runtimes/zcash/README.md @@ -314,8 +314,8 @@ Software keyrings use this sequence for Unified recipients: `parseTransparentTransactions` verifies raw previous transactions against their requested transaction IDs and returns transparent output values, scripts, and -coinbase status. The host supplies the mined height for legacy transaction branch -selection and must check each UTXO's output index and value against the result. +coinbase status. It only needs transaction IDs and raw bytes; the host must check +each UTXO's output index and value against the result. This API uses only the keys module; no wallet database or scan is required. The host owns transparent outpoint reservations, signature-time UTXO revalidation, diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs index 51ea309a9..db60708c7 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs @@ -1,13 +1,12 @@ use serde::{Deserialize, Serialize}; use zcash_primitives::transaction::Transaction; -use zcash_protocol::consensus::{BlockHeight, BranchId}; +use zcash_protocol::consensus::BranchId; -use crate::{keys::parse_network, ErrorCode, KeysError, Result}; +use crate::{ErrorCode, KeysError, Result}; #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct Request { - network: String, transactions: Vec, } @@ -16,7 +15,6 @@ struct Request { struct PreviousTransaction { txid: String, raw_tx: String, - height: u32, } #[derive(Serialize)] @@ -37,24 +35,23 @@ struct Output { pub fn parse_json(request_json: &str) -> Result { let invalid = || KeysError::new(ErrorCode::InvalidTransactionRequest); let request: Request = serde_json::from_str(request_json).map_err(|_| invalid())?; - let network = parse_network(&request.network)?; let parsed = request .transactions .into_iter() .map(|previous| { - if previous.height == 0 { - return Err(invalid().detail("previous transaction height is required")); - } let bytes = hex::decode(&previous.raw_tx).map_err(|_| invalid())?; let mut reader = &bytes[..]; - let branch = BranchId::for_height(&network, BlockHeight::from_u32(previous.height)); - let tx = Transaction::read(&mut reader, branch).map_err(|e| invalid().detail(e))?; - if !reader.is_empty() || !tx.txid().to_string().eq_ignore_ascii_case(&previous.txid) { + // The legacy branch metadata is unused for txids and transparent outputs. + // V5 and later read the branch from the transaction itself. Never sign this object. + let tx = Transaction::read(&mut reader, BranchId::Sprout) + .map_err(|e| invalid().detail(e))?; + let txid = tx.txid().to_string(); + if !reader.is_empty() || !txid.eq_ignore_ascii_case(&previous.txid) { return Err(invalid().detail("previous transaction does not match its txid")); } let bundle = tx.transparent_bundle().ok_or_else(invalid)?; Ok(ParsedTransaction { - txid: tx.txid().to_string(), + txid, is_coinbase: bundle.is_coinbase(), outputs: bundle .vout @@ -95,7 +92,7 @@ mod tests { #[test] fn rejects_mismatched_malformed_and_trailing_data() { - for mode in ["txid", "truncated", "trailing", "hex", "height"] { + for mode in ["txid", "truncated", "trailing", "hex"] { let mut request = request(); let tx = &mut request["transactions"][0]; match mode { @@ -103,7 +100,6 @@ mod tests { "truncated" => tx["rawTx"] = "04000080".into(), "trailing" => tx["rawTx"] = format!("{}00", tx["rawTx"].as_str().unwrap()).into(), "hex" => tx["rawTx"] = "zz".into(), - "height" => tx["height"] = 0.into(), _ => unreachable!(), } assert!(parse_json(&request.to_string()).is_err(), "{mode}"); @@ -119,7 +115,7 @@ mod tests { bytes[41..45].fill(0xff); let tx = Transaction::read(&bytes[..], BranchId::Nu6_2).unwrap(); request["transactions"] = json!([{ - "txid": tx.txid().to_string(), "rawTx": hex::encode(bytes), "height": 3490000, + "txid": tx.txid().to_string(), "rawTx": hex::encode(bytes), }]); let parsed: Value = serde_json::from_str(&parse_json(&request.to_string()).unwrap()).unwrap(); diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md index 1793e0a85..a9adfbb63 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md @@ -2,7 +2,7 @@ Public Zcash transactions fetched on 2026-09-20 through OneKey's test-environment `POST /wallet/v1/network/raw-transaction/list` endpoint (`networkId: zec--0`). -The fixture records the raw transactions and their mined heights: +The fixture records the raw transactions; their mined heights are listed below: - `69ff03c1e3d19df98087396f86783addbc9f8ad615022efdeb5de10fe78597ae`: V4, height 3490000, output 0 is 100000000 zatoshi. - `70177881b2a62c93ed023725a24166362a5bd65cc93dbbd3b3a243ff5927d89c`: V6, height 3476066, output 0 is 1000 zatoshi. diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/previous-transactions.json b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/previous-transactions.json index 8dc80e1b4..6c30536e4 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/previous-transactions.json +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/previous-transactions.json @@ -1,15 +1,12 @@ { - "network": "main", "transactions": [ { "txid": "69ff03c1e3d19df98087396f86783addbc9f8ad615022efdeb5de10fe78597ae", - "rawTx": "0400008085202f890117699175d8be6b17f152bffd0989847fde1f079b5201f363d76a6e0e3d175e85000000006b483045022100e18e7e7f1f91a3b2801b12cbaee85ee23d6723a3f7f608162eee668f6c99cee402205056b948b456858b58ea9204ed4c34d6ec9d6c836675bd30d3e621485946f9ae01210223fa326a1f5d5c85b9cb6a8b574ce828b38bb3bcc789da448f2f66f6731d3ca7ffffffff0200e1f505000000001976a914aea70bc6d77fe2369ddb9a8758e3bbf83bcef96e88ace0789408000000001976a914d5af23c4d585c1496fed2e88582473e97de851eb88ac00000000ff64cd1d0000000000000000000000", - "height": 3490000 + "rawTx": "0400008085202f890117699175d8be6b17f152bffd0989847fde1f079b5201f363d76a6e0e3d175e85000000006b483045022100e18e7e7f1f91a3b2801b12cbaee85ee23d6723a3f7f608162eee668f6c99cee402205056b948b456858b58ea9204ed4c34d6ec9d6c836675bd30d3e621485946f9ae01210223fa326a1f5d5c85b9cb6a8b574ce828b38bb3bcc789da448f2f66f6731d3ca7ffffffff0200e1f505000000001976a914aea70bc6d77fe2369ddb9a8758e3bbf83bcef96e88ace0789408000000001976a914d5af23c4d585c1496fed2e88582473e97de851eb88ac00000000ff64cd1d0000000000000000000000" }, { "txid": "70177881b2a62c93ed023725a24166362a5bd65cc93dbbd3b3a243ff5927d89c", - "rawTx": "0600008098b684d85b16a53700000000890a35000001e8030000000000001976a9149564d9fed247986b15a2f57d0b3b032eeb28476c88ac000000027dda7edf24fb49e6a688abafea52dbbec2cd9427e20f8c97b3ba25c8a8fc73266a490b5f302b639afb45648c5b3c0f3f3f63ea52ba79a71a29e38eca0ede5f3af17b0377cca55ff5253226ce8f67acd7609f64c9873ab177e670465ded636e8c865cf3ebc50965b00a1b5dda951a67612b87656a58bc2c730c64e9df2c2fd02a276014bc0d6744fe10f51e65d7d7df44c699c6e0a621c3a8c67e4a609401c837c4409a7023e4f41400e87d1711e86277bd8f3898de56bd2a85f2f7742f19d7e5f49a66ad8049dff2321ce9201ff9a765897e5396f31e513367b150128b32f15db70e5f6286082dd50f571670515c000299ffd755c2bcf9ddca1be6339ac602496a6cba5ad769df8feb4a374d63328f1e3bed5b66ebe772e02988426b98bf44b01dda5a4a021e07f1b0327a0612b170ee0671dac959eb029e43d6b5f4d00e6bb29f77728c82ccdfaf6341e6563d17b6b816b03ad3d1a78c8378ecc5eda98cf7c69f2bfbaf3a1f4a7c5de7ebbf39622b59d6485189ad03b6e2cb5aa87cb4df73dc6b39071bb9ecd1a888fec04b428aeb6bbd33aca58f4f6f2a6eced4ccf123c6ac686883dedd1ef96856cfc4a58ad9272165f24ba4d1e9cba91d30aa1d2ec9d0d0b3bb0a06e925f460a88b129dce20499c07a3ef02388475d8314c41142515d37338f9b9312e2c14a39b84f4586867717e94f5ae6719922cc3480efe7aedc30a1d915561418d6c9c74fe4925fc8218a9a7a698374d958cfa569d57b3c6da21ed0a2bea669412086294a2bd325d37f0887aeeba5b93b9f738c51f6c4f28e0c770016c38ef9241fad5156c28870c36e469897405464e0ab00cc6eb0a30effe00c651a9711e0fed404ee0a30b61f0d775e56fed9f8e37c3d51aad0a55fa81a11bcdcad13dc11c5e1fa21b972481c1686fa6751e62ec580bb64b3947f80cebbf0e40fbe3881d235519df44c22aeca9fa83bb651f2af6db786ec019b0c176bd91be04b3e67c1e4ca44dafbcc3a6418900f759e7f9ae206110a0ab3d74c020c52d90463b76de67b9ed8384bc5265559e9f8b33dde4d966d39d955e356af6b22ca19dc7635f5536eb13d90dd3fbfeaa36d8e4c1108f69b7d1eae71391ebfa9b4ebdb844de3799d4a7bfa10a22d1dd1952867f003091c33b1cee25aa0d3dee777f061c9a66fdf67dbdf033fd6d59d09a89fa25235f74a4ad06094e918ea7d62851a1ccf8e3e8affc1ecf1bc711a98dffdec8458f745fcc5039e411e337275ed0066d6ab6fb569a82f4dda789f4ffbbf5a830550ac5d354622337e7107b5df60c32ef03ed0db5ee9298040c13460cd685f8c4c100611cd65e2ff2881328cc2f5e736d748d363edc82377f25cd70b5d48c0793f949631ccc5f378a391fa575e0744ab7e257ba8a5a978b05007a0fb15e3abf8a50df69f96df3d697a75dc4e1e21ebcb4a0b1daef6d78450c797325c8ca9fd8188920976f7102504f0d3ae3234afbd44147efd345f297f98e74d3a096ba215cd0d776c02c88bdb72fac4c774f20a68cf82bc2d04f871246babaae626b60afc1fdef99697eb2a82f5687bd9abd6cc6c863fe5a5dd77fec6fed45f53355ac46f690b54f6bc28ba2ef8a1403b55a66fb80eb9691f289a76296d286ecca2d0ae4fa285f68923cf050e6940121e0f827a2f045c3a560da7d3b8de2446391311cd62a0b06d4a7523caca47b4ddac7ce589a88d832c371e5d8405a69d4f3ad412c786234cff667d6f3edc61fbb82711ecf2fe83343aca77c46083b648fa80a6cb5f4b286b3ac8cf3ae6490d4e07d89b2392bde4a0fd1f487f79dc8ac79ff201b1b1d677fcb131bf15bd34a4a84730608849d4df0b69cb250dbc3fa41c45ab1842037cbd1f2996d8b1729d3443eaecd8150e3efee9fd77693cb16ef3a69956842fb257066fdc513e0dde5617fab5ac2132474abd6654d4bb5341f443bc4ff1462b3cf47345c07764ecc6639d5175dd6e2e9edf13e572735dbe777514fc21af8fb6ce0621c369a98f46d0d0b8f4f99f30019b27299b260aee22fb15431ddf8c34661fb213c94536e2846d35dcceb3276ba194c0021094a9cb80cd2915fc8eb8ea9c9c6824cb2bdba23ce7891656d0e717f998e0c9596d7f28baba07ca47b4c5377d37b615c4af34429cbb8eeac49bc809a8a571851bf8a9e5405ea3431e2a4d710b97f90639e04e3126359623e35130832730c8bffdefe0627bace75ca818b76aad897ae0dfb326e3a5e1128677dff7b82aa9d0b0e3f2c94be5fe02f1abf36489b1af8c29f7f9c62480c5cae51747705b1c8662cb5597bd3fe3f6da67701768307803e000000000000b42479f6f64477396fcccb0b672bd0722b5345689122677ff88385970c3acd21fd601c3b83828b7d5c5bf64104c3d38697068121167a2cd5b668ba4cb1f24b9c68fc1eb38304a0193869aa3c3951d7554b3a97b16f7a3b6ef65d0f6d1356cd471021ac66ddcfb1a9c878d9f96ebc1702b77f753b014535993d191b886c424ad47b9d1d80e8def985be67a9a210e5eb138213b59ad354676f283bd270868d2c411d3313d5f7c3e6c24a3783a23471999b875715e9425e3405766848dccbc8cbc115b0028f91a0f6332759a9f557355074f8a837a1a301deae944b7c7a39d01d1795232cebc29ff5379ebcf821621eab1847d22fbf12bc2684a7d0f272644278e2a1f88ef9ba1ed5db23d07185bdacd3fc962ad39ceb94f2bcec114944e532518be2631e329c2aa4ddcf06d9f9d2a79a4f2d0d956ab118336737813b7f2351634bc2a9a98d5cca035c13599dc78e343543d0dc80877485fbf9d9b9021716335c3a4c2c1e58709c030279727510829427622c56e0f5e999554c897822dd758620d111c904599a11432174df11f53ae8ed3191ba7611315409387beef3e8af18f3c786f1bba129a9be24e87a9dffa301b65eed8e6be08dc68f2f72c0aac233c098eb336a808f213afffee343af4b1c4bd9e3fed0ceb861080a2f9e3acbf3022a18df95f882aa042f8cbb7d709d01a2f52bf3736917c717074b55c08d8a6e87316c7b1a7787c62a05ff29d8300fd80b1ccee432333681c5b9eb759ed356f3ad14ae07c88b04d479d9ecbe74c156a48f693299c3ff23146654d773146dd44924a7c7b287f1a58c0037fb3f5882f48e02211a581376b30644075ae39e893e724339a1dc2977054832b7238474d790523969b792950da430d3a17c8d2a1d4065ea006d14040d830cf70bfbb4072211c4b1f25f66fcd1d5a66a7276a0e07edc7bb77b64d5b03aaa0620257ab00b54fd616db1e60e8ea3f9ab4819f028025a281087e6b05c963e22f8b78d8d2ed8f0ed14d1aafda605bc3c9cd9b929a42c33b26464d97192d1a88a89baab2d63f909fcde7758c427ded63b718c6625eadf6bf2ee591831dce08d9604eafb855eaa3d456b97d3aab185fd718581e642bbe1c5a2dcfdeab2f1fb39b2c419d89a49c1ed3c7877256cf47f61b0a9edc838adcdbbeaca6b30dca3e5bba3d7176ae2db5ed38b5af8a99855557d49d427d0c5a2c19a844e8f441a9dfb551034f68619a422ae9e397b0818fb994f29e83a6299874058b7077f80eabac921baeb9960b2466ed2cdd9870ed49a6df8ce663bf3220c61bccfc8dfe66a5190d6bbf2570a9396071195fec6741daf64f2bc977da2d5b250cb0e420c1e4e9d538a2562b9d3175256a16fe8b94215fb92d2594095b183e81cd4285f22e1a62e9e149eab486fff3d29d10488043c21d5eab0b2f127ba8ffcd0a1c6c63a94acb8fcb2014ba3460eb52ea0b0f12d121a2eabfd6f0ffd2b0be7a5ac7794fd4563ebdf7d1cdbc688c380f6c9e8131976f5cf052bdff2a646f09467c4c9e654112a4f52c63c838a6409f96b401ed7358274ee5ffe0367f20b200d52d68ad577db94e51cea97bdd86fabdf08cbd4eb98865b464ce30e4d9ef6e4f0b17e911f7307cbe43a5dba0cbbacec902a43206ee43e7b212f4d752e768387116c770744dc7c4f3363d09128fef6329b61c081dc175b3ccebbea3047185b3db0e497f8ffe6d72e98af1a0d37a077b4f5c8432aa1d428d3e5efabe6a982d0cc47d2632363c44dd90bc08217a9b81b81fd15615c65e67ee7c8ba149bb2e0d8ebfe9facd2d7fdeb230fb3ed1fda983b03dfd6d647533781b88b78c5ae6c9d1656c7ad509849de5ddb5edc072e95d202a0ccaa8bf6239cc0d18de583b4ee3542a6e37b10ceb4ad586f87c7a6a749b751bb132b823f2db7009ee37994f05afd2b75e5d205ba336f524fde24c5935b64252b7145b08dc2383dcae6cedc77c9b7c3ada777c091524edc08bbaf798095a87de7957747ba7b1812c0930463fa183fb96991c4c43c69e34411ee6a9c3c83e2c630846e33b1b4224297715d6902974635d56daf1f0e94a649b1a95e7c319aa42c690374767026c74973f1c97035bbe8353c359b4bb0295615702f0b39336078c2e1462aec15e73021fd8db9a9c3905f73d51b61c1e29566b319981715823c848a2ad3bb001186b7290a19072ba1ce44a259abfafa6c462fbeb39c72b085c03a965c42eb25ed2c0853e3646e014ef0bb92c486f8bf4dfed50e8bc9043130486dee297732071dc7079d4b1d24b2463e6c730db78602e80d0ec843ed5e540111239b733bc81c870475f9e43c071168bdf0e022a5cfb0aa69977078fe78e30b44a5cfe205d4377816c143f6cb2bdd4881cf645e28aa32ca2f51f90c8aac47ac08b4443bd90d5db0713bd60a16d6ca540b48506ad3a7ed62f359193fe1cd6e36df81a50d17c714c096679d9462366d8467c29153dcb6f270c296407b008565013946e6f20c65c21f7f6dc4014ccd8b92461588c801082aad19f0c8f6f658683f30dab9baef74080825a10df950c0e0c2751f7bf3d9d500ad65eb7ee6817a6637474fc40f480e796ea8e40b58c69b6447116962d148292758a5955f468fb8571128a4e3921b8d898a60a6fe9d402af3f0be25f051bc98bfafa47017e4ab4a05346fd155f638f1686e9e5d54946f9143cbc7988f384050adc985bee40d98023326dc6b75a07eac8f6d16bd3cb7af2732321bf3586991434a12503f066ec17ca328cc718f5937c4b05c161da30c2c75476cfd9f0c42ae4ab8ee0da18e7347ae5a360167abb145bf2b06af8739b481d8a55594cd8653f29b63fe2815b9227f62550fb1b21b8c36763d756492736097bb834b9b6562b683c41e0eef5be3b4d28a210430782dfa8bd21f159aeecb5e0c8c359523bbe727124172090620ed1616ed552628d0dfb0e760124ae7906e868aaca9045c5977c8769d31d11512a0f96b6b84355190209eac3cea45cf052799f4596d08773c5b2ea09f6e5d56004f77d0603c2bd2b19624f02e2d1d07db4c74a43b67f6ad56b4f77883929e2e12e1a982b7053d976f847f1db062ab8a57b1ee68dab848606207be9ae969cb0321a56d4aca2a0e375b8cd20314d9f8e52eaa0a4f4b013ef5203573e0e4a61b5a2917ede0fd0e009755f83879325a8cd6bd819a4e9f1e6b982da9c52a102c1b1458f80ec499f73d9cbbf515e00987a2dfeb41be319d8a397cc032a46ff6ef211b07a47e79de772c8712d430f64b504144a0246d38690c54838105f9b4037fa54898353e8b099801df711ab9557b7a5f60f1042e4f377c8337f4962d709264d7e85741674f464c146133e17d7116ac255cedd627cc1cdec802c76f4e1875a9fc60211cc8946c161914bcd46993c46157367c66b2a8ef6d8e4fedb7ea345f6ce6a421b7705bbe093c171f0b8f9867534db5168acaa9f64aefd9c4fd0a0732adca3342a28ad74dd93e89210500993cc87ad77db797232a52b4d1b8ef38791c03913031732d3bef85228fb28c5c8694c07ca6d8b2aa65c098aea31cbdf37479a1da56f44a9dca0160284de0a9fbc2b41658545dc7386d16947299425c6ab691acb6c5818a57a4df1b28fac918e39f26e7fa532a86f7a567f60482d85201b6399cf30284deafd55a6d21b5a7a62684be72af5c1788b4712524214c394c246a6c0046d9687a9b145b522416899c355e29e7a467bca5ddff45041155bfdd17ed786cc2ce44c6f6f1510e1c67aa38f84fca1009299bb7a1cbf8ebd2cc3cf75111c26e73db5161a13d0e6d19155540ae59218d245ae7ea0ff2f46c84665fb5240ae6f8629e267a4a4d170e0b34a6d2ec75c97b93c072f9c7923ffbd4e441c21442e3815607973f3afa2aaa1ccac11f2ef4e2f6a64f8523b8e98c2b7d0e0ba8893cc9141201ab4d54705d27141a60c60667210069de569136502b081ecfb316459191e2b4187a9dbff8e0ca3ea3cdee1347c6bfdce84958c7d164d228866e538bbe2404c2aecb042f3b9b782710f697141b4b9b26c046c91459bcfd501f255315218169b220af50a851843c2839f1706eb7c54cbcd015612c1878a7afc727ea5f58f3393f8de0ec5f1cc26a39d70702650b21a5c14e445198d33cf0787c5b0c6e83022ba7bfb660f58296fe1ae59763258d0b3b6ac0f467d5763af9edf70d18e666ca65cfdbe9aec833b4ea18a2a6f0d28b6f5ff32d4ade7ead29df347a164df943891eb1b34fbe93b041ca07a978912d815de398853b00f756bd286e376a290d8f0b15f6fa2329ee5a6694380988f07e1d6fbb8a4fb22569cc844b9c6ec0c90e59dbe9f721b3035ab85f2a2d8cb2c4833f31bdbcd6bc518f5b14f5b1d69088322fc4129c0df1538e8eb61131eb0f9b54e1a406eace2accbf0c1a44761fae98566bc10839a1f425cd4facbc3f5b813fc190360f8f416059881ff1b7d3bf4beec132046936cae4d207da7fcb2a592a92d8c520e4fc8158415b1ca55e2745464d5a02669ecf7dbfffabd1d896037b476dac3a548f2c97a68648d96d85a4e247953c8dd357b8250eea2977d8c33c0a0e1f7d27af835eab8552bf6a164920c4a4d78c825410a2895e7c744d12af2ed0d9c4955962bac58078357517bc57285fb30a683c27f3eabd237d89566194123aeef8ff6de2d45617e445fa21d9ff69e77c501474dcd852e91a8301bb62dd02e5e53b13734e6217009fae1e5fa755f67e497046281434a05a64f14233299903b82b9f1a8e824348d3086cfc445c228038ea2fb8571f0f7ae4efa9a1f05eab1cf4672a5873bacaf5ad5e1990904b8cb0cfe6d564ecf3f16e1aca77945faecc088c18a26bd5f163e7f71aa56aa9ed9feac697a30c5b3e5b2dce028f3d2d37c803d7379ea90cf47ed6d2e7f813f2983105025d04449fc14a98275ad8599132d71299de8297d626e964535179a471e2d86d68d3b620783f62d6a94d052aff09160cbde576a27c58ee59a0d44c7a02de86d0b88dfda8ed8c3429477d798fbf798922e02516d601514c0f2b351515574ec5eaf7be6d3ee7e9f5e525bb89959b39c21cc550dbb1cec0e01f57be9f7cae57bdaf1642d647e181077701f92baeead14b20434d01c73f2d62e6897346552c18e3bbf34e9d28b49795c74199e9c1855a1816fd745e4b5ffa0f5e2549d4503467366a8ce1a859d88cb332e3cd9ba15f21e43d6eb369f71c696d81f6f1fd93a0dca5fb8cba57ddc78b6c82be07319716f0d6250ef2ee201904707f3e9d5994b32011e36f28ada05feffa000330638b65faf92f7ec9ff45648cf18c38301157314823ba9ae0ffc249a96a470c4f8f3d65c3981e1d2c0c384259801441d3407d46d515a9769b87a18145c44ca444759c445ecc07c5c24e544533129b46036ab79a667dff224d9d6ab2ecd5825008297c8d99b6129503764bbf3a058751843d6b7fd14a22843efc788d0cacdc4ec0ee55dd63353157e283aae339349dfa92ad575563aebb49d1697d57f944831300e34e5fc2fa1a9b45cdbc48a56e98d2501a461a0a56c4861fe8ce74f677b4a93936878b55112f74c718370e78b32bdc99502e772bd9fe4cb87a9feed1276c295fb4b11578c30c6d7671e815a0caa93ba5c33f9c3de7885ef0cdd5ef6e3e99b733eb89fb3234067ecf6174fa0f82f0b1c9d40b0f092627e137e4ad1e26111775b369105f8ba3090f29eef5925bea27c333450ab6b516cd48352cf3beadc4b62e81161e41ec2c09ba797f0d284d93707e4367c7f32b10cac164c2305fad5423e68813ed36fb6c345f7109539f9d27dfc72870a542603037d326972f1807a308e9c28af06d14473ee5576c342c2740018ea87a8f3999bab84407233c4f08ba0a08f0a47203164208c5fb740256b99a22ac00d40c90d20271684c45984a6cb4688cff5b5d82e1c035ba7107d05024f03ce8eca0001fefb8958d6718b702b8ec11271d9112bcb5fc0269f3e081f12848a278312773ac26ba715776029f3a7b664aa94bb83e31deee3f6510baafc40f660fab24a868a6f4a8fdf138bc5466bf2603054746a14032d70772a0f8f8f4877b0bc5dadfcb921bd578b5db5ca31a2be63d252bb8131200b91db7cd9014a1e716436303d2776e236ed4760f8c6acc69b37a81301e8521db022da4818a74f47221ed72d21d07a6f1bc20ba1331e3cdc71069b29aa9bd9e826f28982ea698170472c5a20cbb8e5991b34e2c505248586946d4e4b65f8b3377622bf23eba40ba651005ae0e32a4f1cb7d0ca3505fe39b90786c973c1d886d6375024437e3e6d833fd454acc15658376d1396a3a21997cc46ced4fd83c803343551a91a3b75acc540fe56ee62780b40c3a79de268726e4e572a1eee60429394b0a3884f1cc64e5ef82d406aad1c18484b0680ba59032a0f4dcfd004ae367763537311ad387151ded692c2065e4b286b35c572ff3b9852a69eb68683ccd55caef791abae7bf36134f92981584b2a972bd2b91fbc59c2f92d35e803cc1423011d9c41675d2ae610ff83d97fd5f3870bf370272f0cf8e0bbe0d69dc7031d04fcf348303c8ad1ee7c20f97cae3caee74b3775674a74e31e7c2dde4b4778f31e402cd1b04a993d2b09288df969d50910da2c7572e2ee03c1d8c8e060ec80bf417c214cd151d9b9a28a0bfa00128b781977a6ae8517ece6d081c1e7f5d54d810539032e6096d962915cb6bff796e927ba97909767bb059a0c110fdbca0a95152a9dd4c27248a410ff89d0103cb5414d88533bfff4e7ce114c84ab689c40917910b6f22ff03795d6d474cf354b9017232dd8584777663b72454e7b0e945d02716a599294f2b4a216c4172f9f18aff43c521dd34e60f3d1edada40318e3eaf861b26d9087b1dd8000224b403560d8991ab803c1ebee29c0db5fc15cd0f1ac61cfe2ed847951e4776eb88f65aed9a72f5b7529c6c9a051948994397e920cab00767140bb1c603af77c29be810741a7507144aa2665b9c87a88169cec50dbc413f74e711480d34884a312a60d8790b24b44d59904faed3df28d71f4d0fa4d9f1233a6f8511d718032eb042e3b627fc46f51e1266fb7171ff87202c1175723f9e50538bd6c2fe11be731fb5e3f72eafe6b86772d1e73ebe02fd8d2f1468fbbd3643b1f881f4441b92b7d4ef505518cdbc4a65fe1537dd8825d5d97c352fdd53136118612415a107c16213b2b503fc4717cb55b3bb352443a8ce99c40905ac296aeb25e18fddae1a956d49042973e4c2e525059e353258606953461a3e736c1cb93591feff9b3e3a4823d7c4c387da635631379e751e0fab02ae7211aa0681f0f0a80a91c654441fbbc9d5cd4952ff62dfe54b048401bc6f9d844d0415d74844cfe021df565b3c2145e10103971a64c67874aa971b321cfb6dde55b0bd9561b2c6438c1885f7f429a2273743b41fa87cd0bd029384306e4993ea730db318deeff32a225d660600001f2ca5e5a4136a08df29d764b889b59bb1810c49b0b3ce4ee0ab9aa21f5b1d026b24eecad4a1cf99a3e5cf58fc1e1d78279444bb2a1bd7844edc498df9b5f205c6006e42fb5a2945bdcfa668f341565a87d5c2c4bf5adb7ead9c75637eabff17d1501c6699d96a790a6ee62a6e333d7d3c57097156453cb18681949e176ccc12fa54f43a31360328e66cee28415dbd6cfc833ad38b43413218d76daeaecf2b1b9d73c07899072ae18523b8862ae966ff0c042bed2e986bfce40d0708521d242f2e7dcdb2712c9e6127ab0d1a810998a6b39a0ad063466dab00ba56543dada631da18eee41dcf1b90f372582172d25cfcab7f702a47e02b59bc0a26faed65940fb5074dbf193e99ace30848d9074fff7b5910f54881bdad170e12d576b029b521e1ba1d17c7db67c7682b61c247e383e6a21cf72cdd566a4960a5493a31cb4025cb8f8353827f3c731f9aeb51af2aa063c74c1bc8c88169d4e2cc143d3b8cfb32eefa31edb3905ffe147097b95c99c3eb5a0dcb05771f89f345da5130cedf9e34eef45d332f02c55dcb6eb4ff8d90b421c2e8550ef20d94e7c7aff318e4dfaf06df1e9b5306cc207fb7811ba57236f8d54263b61723d2ae4b952cce2712119e1abb07d5b7b3dfdeba515f150fbd6bc9453c77ad9783cac3620198cab9eedc263e52691c99536ee85520606b33c707f0642ddef6871df61817eff3dbec4f5793321d67a1428625608c172eec7e91e36bc5199eafa3b54a15692d710b0e1374293798ae0394f5955f7eca2996cb01344981081a234614e2cd6c888faff46c80e305b17fec5c26db7511ac6b8feb910209fdf09b1542e5f1531b11dc3318035e412ff71aa9af85ef0ae4903e0d6a8d16d438fe6969b24da1aacd565267518b33d00604370c345c8007c382f1c931daa695d9ef59dfb996629c4d73e69693d8e88a2ee7edaa5b6359067e0676c7eaea9d250cdd50e99173d1e68d54a2ea0085516f1461f7dcbd088dc6d7537f9bd2db5e3436346a22cc67a72fcfa7bef32677e9933f2198659b117541839c9c27b6bb990018779fefacf93ef58ac74481d486109d177dceff7bed85ddc3e82e2c126a66aa84d57caad2edadb33e56511d4becb5d320fd9eff979586d884cf3e34342d4435804d0bb7eb972eae8a21b486e4120b55101b1a52f63bf1d9cb5033496b5258d27c34a94a8813c146cd7aff1b427f99560b4678313b648438c95371c31277d86a78d947110f4bc1b8146d3df402551f351172df48e6ef1eaf0d46b05b16509ca044657afb54084403a135def4c4b9e43c15d0d8dde203d4108064e07822f1021b748f95eb9a983f9259d49becf46642c93e8f10a8a56a4697ee1c653c0f6bc3b6548cb0604a23442b65d459cfb239b44e32e356db260e8634a457649171a7fef6547b971fdd90ddfd8e9548d48922fbeb3937e5900b9e55156ea63547970ab902fd3cb490481e82a3c69b0b08b2a215a03ad5a1277c4e1c7ffd6cf984457a1352735e007246fa12289629781400e648ed086b48442859c126cad10f41d715e01a6bde4241c12a4bfce362be59a1b8a8952379eb22e20e093c2d1d30a0701eb9a3f6f9010703699ed7d6dec9b4d529617c38fe0b9d8188270047c588818b843618b067303770d20449e8cf1df2b74524512db7fa458260ca52b00f46d344499dd82ee951edc94e6da28db68fefba95fe273a52190a10c234aaffbe35534323a9757ef169709b80594ec6b099ec6d156eb1b659c283b1a80c0179fbb18a5a180d6c3d5f43821969aa7c092fcfa06c08762c3b7e4850c76e4180eb1175891fe119b303b823dc8c1fee5fd589edddc238876414ccf36f16f01061616517a92d57d0acc00d7ebb0410a7a8b3761c68b45de850002f76680ee13db5cff191f933b22479e16cb9a973d5183d4528c5d1acc2085627fda64ff2bba9a88b71f32fcbbf82c49b8d9d49477bf9a02901b85b9e5374f5ad6a013900b119a04d532583c847fab9d6bb7f5125babf86f958e05334571dff2a391070b7a33ff77e3dd373e632344bbb7e1d19eab65a7b27fdd8820372a66230a48fd2321606bf2f5cca4f7b69e87d7388cb7ccc5830fcc5517934ff881e9910afeadf194876fe2ed267aefd880633bb37892e87ab561b2145a12cb27d32188bb1eaf7ca6cb4f5c34836637bdbda227230f37b6aec4235bd24657c8dfead530822a5133d69fac63893fbff9ebce128242536307145fc879ba4573d4eb95c918a31a26ac0f985003afe083733a8e5f8d4aab377b100ea05490533517dcc336ca599f7582a07eab9629533df6eb38fdd3ef09963fcf76b84f492ef5833245aecb9979c3e4b09c61b30eb6d31d1f7a3434f3f5f04e6285098320993b51d848d6a349b80e89e6857e8394380d91710eb2ba03221bc4562fe5f8bb7f8f6e1353f4da07733f58ec3c847e54fd6bf31cb32adbb701b6c5bcd79defe5de7901b5ca92010289991b83079959d64dcc140c612f4a773995a0de2abbc2b9c601b026fa5e3340c03fd06fca4c8e2d58d117132cb86647a2a16c1dbf71262ce644e1c178799b9e5941c7cd866bd407196caa9a511acc3c1f0ff73150ce847b6a88aaa8f8c5c2685dba9ba63cefafd89d7ddcf97e133951639cf6d021d92f172437c72968098b3f0ed3040c282cfcb7bced1baa9d17c6af35b97946a16170d8cda40039f08872a35bab3924b871a7620357c329f9c6c0bb9e03fe77313e77e5e4f7f2f151e600c8cb330b21599e4ce616ca5ad16e1548bdfa10c5aa92d7b436d22ccf894fd28364b7e5eb81a5967b1cc3f7cf3dea6c432595a0389cafa00059e3cac41c67bb71427cf56501fcd77cb3c239c73b996774a7fa9fd410e3fe3184900c8578a8d0a988445d0567ad0a2fbbb055cfdf14c4184516d5ce31b3ac4dbad3fe89367c83f0fdcdb1dcab1b8eac5da64183cf9849a471425f2f63135644a45ccd0f5a68cc7b1f3871e32729ea37c1ca433c13011d725898b455e1c74104d9bdd9a99c0ca640a159d4a6040e69480f82da58d9ea45284353cfeee835c023d8f9b07a14d43be376d4421b4f6a1fbbc2b877272098ca2b61bb2d38cb2691e7429619fa53a566709", - "height": 3476066 + "rawTx": "0600008098b684d85b16a53700000000890a35000001e8030000000000001976a9149564d9fed247986b15a2f57d0b3b032eeb28476c88ac000000027dda7edf24fb49e6a688abafea52dbbec2cd9427e20f8c97b3ba25c8a8fc73266a490b5f302b639afb45648c5b3c0f3f3f63ea52ba79a71a29e38eca0ede5f3af17b0377cca55ff5253226ce8f67acd7609f64c9873ab177e670465ded636e8c865cf3ebc50965b00a1b5dda951a67612b87656a58bc2c730c64e9df2c2fd02a276014bc0d6744fe10f51e65d7d7df44c699c6e0a621c3a8c67e4a609401c837c4409a7023e4f41400e87d1711e86277bd8f3898de56bd2a85f2f7742f19d7e5f49a66ad8049dff2321ce9201ff9a765897e5396f31e513367b150128b32f15db70e5f6286082dd50f571670515c000299ffd755c2bcf9ddca1be6339ac602496a6cba5ad769df8feb4a374d63328f1e3bed5b66ebe772e02988426b98bf44b01dda5a4a021e07f1b0327a0612b170ee0671dac959eb029e43d6b5f4d00e6bb29f77728c82ccdfaf6341e6563d17b6b816b03ad3d1a78c8378ecc5eda98cf7c69f2bfbaf3a1f4a7c5de7ebbf39622b59d6485189ad03b6e2cb5aa87cb4df73dc6b39071bb9ecd1a888fec04b428aeb6bbd33aca58f4f6f2a6eced4ccf123c6ac686883dedd1ef96856cfc4a58ad9272165f24ba4d1e9cba91d30aa1d2ec9d0d0b3bb0a06e925f460a88b129dce20499c07a3ef02388475d8314c41142515d37338f9b9312e2c14a39b84f4586867717e94f5ae6719922cc3480efe7aedc30a1d915561418d6c9c74fe4925fc8218a9a7a698374d958cfa569d57b3c6da21ed0a2bea669412086294a2bd325d37f0887aeeba5b93b9f738c51f6c4f28e0c770016c38ef9241fad5156c28870c36e469897405464e0ab00cc6eb0a30effe00c651a9711e0fed404ee0a30b61f0d775e56fed9f8e37c3d51aad0a55fa81a11bcdcad13dc11c5e1fa21b972481c1686fa6751e62ec580bb64b3947f80cebbf0e40fbe3881d235519df44c22aeca9fa83bb651f2af6db786ec019b0c176bd91be04b3e67c1e4ca44dafbcc3a6418900f759e7f9ae206110a0ab3d74c020c52d90463b76de67b9ed8384bc5265559e9f8b33dde4d966d39d955e356af6b22ca19dc7635f5536eb13d90dd3fbfeaa36d8e4c1108f69b7d1eae71391ebfa9b4ebdb844de3799d4a7bfa10a22d1dd1952867f003091c33b1cee25aa0d3dee777f061c9a66fdf67dbdf033fd6d59d09a89fa25235f74a4ad06094e918ea7d62851a1ccf8e3e8affc1ecf1bc711a98dffdec8458f745fcc5039e411e337275ed0066d6ab6fb569a82f4dda789f4ffbbf5a830550ac5d354622337e7107b5df60c32ef03ed0db5ee9298040c13460cd685f8c4c100611cd65e2ff2881328cc2f5e736d748d363edc82377f25cd70b5d48c0793f949631ccc5f378a391fa575e0744ab7e257ba8a5a978b05007a0fb15e3abf8a50df69f96df3d697a75dc4e1e21ebcb4a0b1daef6d78450c797325c8ca9fd8188920976f7102504f0d3ae3234afbd44147efd345f297f98e74d3a096ba215cd0d776c02c88bdb72fac4c774f20a68cf82bc2d04f871246babaae626b60afc1fdef99697eb2a82f5687bd9abd6cc6c863fe5a5dd77fec6fed45f53355ac46f690b54f6bc28ba2ef8a1403b55a66fb80eb9691f289a76296d286ecca2d0ae4fa285f68923cf050e6940121e0f827a2f045c3a560da7d3b8de2446391311cd62a0b06d4a7523caca47b4ddac7ce589a88d832c371e5d8405a69d4f3ad412c786234cff667d6f3edc61fbb82711ecf2fe83343aca77c46083b648fa80a6cb5f4b286b3ac8cf3ae6490d4e07d89b2392bde4a0fd1f487f79dc8ac79ff201b1b1d677fcb131bf15bd34a4a84730608849d4df0b69cb250dbc3fa41c45ab1842037cbd1f2996d8b1729d3443eaecd8150e3efee9fd77693cb16ef3a69956842fb257066fdc513e0dde5617fab5ac2132474abd6654d4bb5341f443bc4ff1462b3cf47345c07764ecc6639d5175dd6e2e9edf13e572735dbe777514fc21af8fb6ce0621c369a98f46d0d0b8f4f99f30019b27299b260aee22fb15431ddf8c34661fb213c94536e2846d35dcceb3276ba194c0021094a9cb80cd2915fc8eb8ea9c9c6824cb2bdba23ce7891656d0e717f998e0c9596d7f28baba07ca47b4c5377d37b615c4af34429cbb8eeac49bc809a8a571851bf8a9e5405ea3431e2a4d710b97f90639e04e3126359623e35130832730c8bffdefe0627bace75ca818b76aad897ae0dfb326e3a5e1128677dff7b82aa9d0b0e3f2c94be5fe02f1abf36489b1af8c29f7f9c62480c5cae51747705b1c8662cb5597bd3fe3f6da67701768307803e000000000000b42479f6f64477396fcccb0b672bd0722b5345689122677ff88385970c3acd21fd601c3b83828b7d5c5bf64104c3d38697068121167a2cd5b668ba4cb1f24b9c68fc1eb38304a0193869aa3c3951d7554b3a97b16f7a3b6ef65d0f6d1356cd471021ac66ddcfb1a9c878d9f96ebc1702b77f753b014535993d191b886c424ad47b9d1d80e8def985be67a9a210e5eb138213b59ad354676f283bd270868d2c411d3313d5f7c3e6c24a3783a23471999b875715e9425e3405766848dccbc8cbc115b0028f91a0f6332759a9f557355074f8a837a1a301deae944b7c7a39d01d1795232cebc29ff5379ebcf821621eab1847d22fbf12bc2684a7d0f272644278e2a1f88ef9ba1ed5db23d07185bdacd3fc962ad39ceb94f2bcec114944e532518be2631e329c2aa4ddcf06d9f9d2a79a4f2d0d956ab118336737813b7f2351634bc2a9a98d5cca035c13599dc78e343543d0dc80877485fbf9d9b9021716335c3a4c2c1e58709c030279727510829427622c56e0f5e999554c897822dd758620d111c904599a11432174df11f53ae8ed3191ba7611315409387beef3e8af18f3c786f1bba129a9be24e87a9dffa301b65eed8e6be08dc68f2f72c0aac233c098eb336a808f213afffee343af4b1c4bd9e3fed0ceb861080a2f9e3acbf3022a18df95f882aa042f8cbb7d709d01a2f52bf3736917c717074b55c08d8a6e87316c7b1a7787c62a05ff29d8300fd80b1ccee432333681c5b9eb759ed356f3ad14ae07c88b04d479d9ecbe74c156a48f693299c3ff23146654d773146dd44924a7c7b287f1a58c0037fb3f5882f48e02211a581376b30644075ae39e893e724339a1dc2977054832b7238474d790523969b792950da430d3a17c8d2a1d4065ea006d14040d830cf70bfbb4072211c4b1f25f66fcd1d5a66a7276a0e07edc7bb77b64d5b03aaa0620257ab00b54fd616db1e60e8ea3f9ab4819f028025a281087e6b05c963e22f8b78d8d2ed8f0ed14d1aafda605bc3c9cd9b929a42c33b26464d97192d1a88a89baab2d63f909fcde7758c427ded63b718c6625eadf6bf2ee591831dce08d9604eafb855eaa3d456b97d3aab185fd718581e642bbe1c5a2dcfdeab2f1fb39b2c419d89a49c1ed3c7877256cf47f61b0a9edc838adcdbbeaca6b30dca3e5bba3d7176ae2db5ed38b5af8a99855557d49d427d0c5a2c19a844e8f441a9dfb551034f68619a422ae9e397b0818fb994f29e83a6299874058b7077f80eabac921baeb9960b2466ed2cdd9870ed49a6df8ce663bf3220c61bccfc8dfe66a5190d6bbf2570a9396071195fec6741daf64f2bc977da2d5b250cb0e420c1e4e9d538a2562b9d3175256a16fe8b94215fb92d2594095b183e81cd4285f22e1a62e9e149eab486fff3d29d10488043c21d5eab0b2f127ba8ffcd0a1c6c63a94acb8fcb2014ba3460eb52ea0b0f12d121a2eabfd6f0ffd2b0be7a5ac7794fd4563ebdf7d1cdbc688c380f6c9e8131976f5cf052bdff2a646f09467c4c9e654112a4f52c63c838a6409f96b401ed7358274ee5ffe0367f20b200d52d68ad577db94e51cea97bdd86fabdf08cbd4eb98865b464ce30e4d9ef6e4f0b17e911f7307cbe43a5dba0cbbacec902a43206ee43e7b212f4d752e768387116c770744dc7c4f3363d09128fef6329b61c081dc175b3ccebbea3047185b3db0e497f8ffe6d72e98af1a0d37a077b4f5c8432aa1d428d3e5efabe6a982d0cc47d2632363c44dd90bc08217a9b81b81fd15615c65e67ee7c8ba149bb2e0d8ebfe9facd2d7fdeb230fb3ed1fda983b03dfd6d647533781b88b78c5ae6c9d1656c7ad509849de5ddb5edc072e95d202a0ccaa8bf6239cc0d18de583b4ee3542a6e37b10ceb4ad586f87c7a6a749b751bb132b823f2db7009ee37994f05afd2b75e5d205ba336f524fde24c5935b64252b7145b08dc2383dcae6cedc77c9b7c3ada777c091524edc08bbaf798095a87de7957747ba7b1812c0930463fa183fb96991c4c43c69e34411ee6a9c3c83e2c630846e33b1b4224297715d6902974635d56daf1f0e94a649b1a95e7c319aa42c690374767026c74973f1c97035bbe8353c359b4bb0295615702f0b39336078c2e1462aec15e73021fd8db9a9c3905f73d51b61c1e29566b319981715823c848a2ad3bb001186b7290a19072ba1ce44a259abfafa6c462fbeb39c72b085c03a965c42eb25ed2c0853e3646e014ef0bb92c486f8bf4dfed50e8bc9043130486dee297732071dc7079d4b1d24b2463e6c730db78602e80d0ec843ed5e540111239b733bc81c870475f9e43c071168bdf0e022a5cfb0aa69977078fe78e30b44a5cfe205d4377816c143f6cb2bdd4881cf645e28aa32ca2f51f90c8aac47ac08b4443bd90d5db0713bd60a16d6ca540b48506ad3a7ed62f359193fe1cd6e36df81a50d17c714c096679d9462366d8467c29153dcb6f270c296407b008565013946e6f20c65c21f7f6dc4014ccd8b92461588c801082aad19f0c8f6f658683f30dab9baef74080825a10df950c0e0c2751f7bf3d9d500ad65eb7ee6817a6637474fc40f480e796ea8e40b58c69b6447116962d148292758a5955f468fb8571128a4e3921b8d898a60a6fe9d402af3f0be25f051bc98bfafa47017e4ab4a05346fd155f638f1686e9e5d54946f9143cbc7988f384050adc985bee40d98023326dc6b75a07eac8f6d16bd3cb7af2732321bf3586991434a12503f066ec17ca328cc718f5937c4b05c161da30c2c75476cfd9f0c42ae4ab8ee0da18e7347ae5a360167abb145bf2b06af8739b481d8a55594cd8653f29b63fe2815b9227f62550fb1b21b8c36763d756492736097bb834b9b6562b683c41e0eef5be3b4d28a210430782dfa8bd21f159aeecb5e0c8c359523bbe727124172090620ed1616ed552628d0dfb0e760124ae7906e868aaca9045c5977c8769d31d11512a0f96b6b84355190209eac3cea45cf052799f4596d08773c5b2ea09f6e5d56004f77d0603c2bd2b19624f02e2d1d07db4c74a43b67f6ad56b4f77883929e2e12e1a982b7053d976f847f1db062ab8a57b1ee68dab848606207be9ae969cb0321a56d4aca2a0e375b8cd20314d9f8e52eaa0a4f4b013ef5203573e0e4a61b5a2917ede0fd0e009755f83879325a8cd6bd819a4e9f1e6b982da9c52a102c1b1458f80ec499f73d9cbbf515e00987a2dfeb41be319d8a397cc032a46ff6ef211b07a47e79de772c8712d430f64b504144a0246d38690c54838105f9b4037fa54898353e8b099801df711ab9557b7a5f60f1042e4f377c8337f4962d709264d7e85741674f464c146133e17d7116ac255cedd627cc1cdec802c76f4e1875a9fc60211cc8946c161914bcd46993c46157367c66b2a8ef6d8e4fedb7ea345f6ce6a421b7705bbe093c171f0b8f9867534db5168acaa9f64aefd9c4fd0a0732adca3342a28ad74dd93e89210500993cc87ad77db797232a52b4d1b8ef38791c03913031732d3bef85228fb28c5c8694c07ca6d8b2aa65c098aea31cbdf37479a1da56f44a9dca0160284de0a9fbc2b41658545dc7386d16947299425c6ab691acb6c5818a57a4df1b28fac918e39f26e7fa532a86f7a567f60482d85201b6399cf30284deafd55a6d21b5a7a62684be72af5c1788b4712524214c394c246a6c0046d9687a9b145b522416899c355e29e7a467bca5ddff45041155bfdd17ed786cc2ce44c6f6f1510e1c67aa38f84fca1009299bb7a1cbf8ebd2cc3cf75111c26e73db5161a13d0e6d19155540ae59218d245ae7ea0ff2f46c84665fb5240ae6f8629e267a4a4d170e0b34a6d2ec75c97b93c072f9c7923ffbd4e441c21442e3815607973f3afa2aaa1ccac11f2ef4e2f6a64f8523b8e98c2b7d0e0ba8893cc9141201ab4d54705d27141a60c60667210069de569136502b081ecfb316459191e2b4187a9dbff8e0ca3ea3cdee1347c6bfdce84958c7d164d228866e538bbe2404c2aecb042f3b9b782710f697141b4b9b26c046c91459bcfd501f255315218169b220af50a851843c2839f1706eb7c54cbcd015612c1878a7afc727ea5f58f3393f8de0ec5f1cc26a39d70702650b21a5c14e445198d33cf0787c5b0c6e83022ba7bfb660f58296fe1ae59763258d0b3b6ac0f467d5763af9edf70d18e666ca65cfdbe9aec833b4ea18a2a6f0d28b6f5ff32d4ade7ead29df347a164df943891eb1b34fbe93b041ca07a978912d815de398853b00f756bd286e376a290d8f0b15f6fa2329ee5a6694380988f07e1d6fbb8a4fb22569cc844b9c6ec0c90e59dbe9f721b3035ab85f2a2d8cb2c4833f31bdbcd6bc518f5b14f5b1d69088322fc4129c0df1538e8eb61131eb0f9b54e1a406eace2accbf0c1a44761fae98566bc10839a1f425cd4facbc3f5b813fc190360f8f416059881ff1b7d3bf4beec132046936cae4d207da7fcb2a592a92d8c520e4fc8158415b1ca55e2745464d5a02669ecf7dbfffabd1d896037b476dac3a548f2c97a68648d96d85a4e247953c8dd357b8250eea2977d8c33c0a0e1f7d27af835eab8552bf6a164920c4a4d78c825410a2895e7c744d12af2ed0d9c4955962bac58078357517bc57285fb30a683c27f3eabd237d89566194123aeef8ff6de2d45617e445fa21d9ff69e77c501474dcd852e91a8301bb62dd02e5e53b13734e6217009fae1e5fa755f67e497046281434a05a64f14233299903b82b9f1a8e824348d3086cfc445c228038ea2fb8571f0f7ae4efa9a1f05eab1cf4672a5873bacaf5ad5e1990904b8cb0cfe6d564ecf3f16e1aca77945faecc088c18a26bd5f163e7f71aa56aa9ed9feac697a30c5b3e5b2dce028f3d2d37c803d7379ea90cf47ed6d2e7f813f2983105025d04449fc14a98275ad8599132d71299de8297d626e964535179a471e2d86d68d3b620783f62d6a94d052aff09160cbde576a27c58ee59a0d44c7a02de86d0b88dfda8ed8c3429477d798fbf798922e02516d601514c0f2b351515574ec5eaf7be6d3ee7e9f5e525bb89959b39c21cc550dbb1cec0e01f57be9f7cae57bdaf1642d647e181077701f92baeead14b20434d01c73f2d62e6897346552c18e3bbf34e9d28b49795c74199e9c1855a1816fd745e4b5ffa0f5e2549d4503467366a8ce1a859d88cb332e3cd9ba15f21e43d6eb369f71c696d81f6f1fd93a0dca5fb8cba57ddc78b6c82be07319716f0d6250ef2ee201904707f3e9d5994b32011e36f28ada05feffa000330638b65faf92f7ec9ff45648cf18c38301157314823ba9ae0ffc249a96a470c4f8f3d65c3981e1d2c0c384259801441d3407d46d515a9769b87a18145c44ca444759c445ecc07c5c24e544533129b46036ab79a667dff224d9d6ab2ecd5825008297c8d99b6129503764bbf3a058751843d6b7fd14a22843efc788d0cacdc4ec0ee55dd63353157e283aae339349dfa92ad575563aebb49d1697d57f944831300e34e5fc2fa1a9b45cdbc48a56e98d2501a461a0a56c4861fe8ce74f677b4a93936878b55112f74c718370e78b32bdc99502e772bd9fe4cb87a9feed1276c295fb4b11578c30c6d7671e815a0caa93ba5c33f9c3de7885ef0cdd5ef6e3e99b733eb89fb3234067ecf6174fa0f82f0b1c9d40b0f092627e137e4ad1e26111775b369105f8ba3090f29eef5925bea27c333450ab6b516cd48352cf3beadc4b62e81161e41ec2c09ba797f0d284d93707e4367c7f32b10cac164c2305fad5423e68813ed36fb6c345f7109539f9d27dfc72870a542603037d326972f1807a308e9c28af06d14473ee5576c342c2740018ea87a8f3999bab84407233c4f08ba0a08f0a47203164208c5fb740256b99a22ac00d40c90d20271684c45984a6cb4688cff5b5d82e1c035ba7107d05024f03ce8eca0001fefb8958d6718b702b8ec11271d9112bcb5fc0269f3e081f12848a278312773ac26ba715776029f3a7b664aa94bb83e31deee3f6510baafc40f660fab24a868a6f4a8fdf138bc5466bf2603054746a14032d70772a0f8f8f4877b0bc5dadfcb921bd578b5db5ca31a2be63d252bb8131200b91db7cd9014a1e716436303d2776e236ed4760f8c6acc69b37a81301e8521db022da4818a74f47221ed72d21d07a6f1bc20ba1331e3cdc71069b29aa9bd9e826f28982ea698170472c5a20cbb8e5991b34e2c505248586946d4e4b65f8b3377622bf23eba40ba651005ae0e32a4f1cb7d0ca3505fe39b90786c973c1d886d6375024437e3e6d833fd454acc15658376d1396a3a21997cc46ced4fd83c803343551a91a3b75acc540fe56ee62780b40c3a79de268726e4e572a1eee60429394b0a3884f1cc64e5ef82d406aad1c18484b0680ba59032a0f4dcfd004ae367763537311ad387151ded692c2065e4b286b35c572ff3b9852a69eb68683ccd55caef791abae7bf36134f92981584b2a972bd2b91fbc59c2f92d35e803cc1423011d9c41675d2ae610ff83d97fd5f3870bf370272f0cf8e0bbe0d69dc7031d04fcf348303c8ad1ee7c20f97cae3caee74b3775674a74e31e7c2dde4b4778f31e402cd1b04a993d2b09288df969d50910da2c7572e2ee03c1d8c8e060ec80bf417c214cd151d9b9a28a0bfa00128b781977a6ae8517ece6d081c1e7f5d54d810539032e6096d962915cb6bff796e927ba97909767bb059a0c110fdbca0a95152a9dd4c27248a410ff89d0103cb5414d88533bfff4e7ce114c84ab689c40917910b6f22ff03795d6d474cf354b9017232dd8584777663b72454e7b0e945d02716a599294f2b4a216c4172f9f18aff43c521dd34e60f3d1edada40318e3eaf861b26d9087b1dd8000224b403560d8991ab803c1ebee29c0db5fc15cd0f1ac61cfe2ed847951e4776eb88f65aed9a72f5b7529c6c9a051948994397e920cab00767140bb1c603af77c29be810741a7507144aa2665b9c87a88169cec50dbc413f74e711480d34884a312a60d8790b24b44d59904faed3df28d71f4d0fa4d9f1233a6f8511d718032eb042e3b627fc46f51e1266fb7171ff87202c1175723f9e50538bd6c2fe11be731fb5e3f72eafe6b86772d1e73ebe02fd8d2f1468fbbd3643b1f881f4441b92b7d4ef505518cdbc4a65fe1537dd8825d5d97c352fdd53136118612415a107c16213b2b503fc4717cb55b3bb352443a8ce99c40905ac296aeb25e18fddae1a956d49042973e4c2e525059e353258606953461a3e736c1cb93591feff9b3e3a4823d7c4c387da635631379e751e0fab02ae7211aa0681f0f0a80a91c654441fbbc9d5cd4952ff62dfe54b048401bc6f9d844d0415d74844cfe021df565b3c2145e10103971a64c67874aa971b321cfb6dde55b0bd9561b2c6438c1885f7f429a2273743b41fa87cd0bd029384306e4993ea730db318deeff32a225d660600001f2ca5e5a4136a08df29d764b889b59bb1810c49b0b3ce4ee0ab9aa21f5b1d026b24eecad4a1cf99a3e5cf58fc1e1d78279444bb2a1bd7844edc498df9b5f205c6006e42fb5a2945bdcfa668f341565a87d5c2c4bf5adb7ead9c75637eabff17d1501c6699d96a790a6ee62a6e333d7d3c57097156453cb18681949e176ccc12fa54f43a31360328e66cee28415dbd6cfc833ad38b43413218d76daeaecf2b1b9d73c07899072ae18523b8862ae966ff0c042bed2e986bfce40d0708521d242f2e7dcdb2712c9e6127ab0d1a810998a6b39a0ad063466dab00ba56543dada631da18eee41dcf1b90f372582172d25cfcab7f702a47e02b59bc0a26faed65940fb5074dbf193e99ace30848d9074fff7b5910f54881bdad170e12d576b029b521e1ba1d17c7db67c7682b61c247e383e6a21cf72cdd566a4960a5493a31cb4025cb8f8353827f3c731f9aeb51af2aa063c74c1bc8c88169d4e2cc143d3b8cfb32eefa31edb3905ffe147097b95c99c3eb5a0dcb05771f89f345da5130cedf9e34eef45d332f02c55dcb6eb4ff8d90b421c2e8550ef20d94e7c7aff318e4dfaf06df1e9b5306cc207fb7811ba57236f8d54263b61723d2ae4b952cce2712119e1abb07d5b7b3dfdeba515f150fbd6bc9453c77ad9783cac3620198cab9eedc263e52691c99536ee85520606b33c707f0642ddef6871df61817eff3dbec4f5793321d67a1428625608c172eec7e91e36bc5199eafa3b54a15692d710b0e1374293798ae0394f5955f7eca2996cb01344981081a234614e2cd6c888faff46c80e305b17fec5c26db7511ac6b8feb910209fdf09b1542e5f1531b11dc3318035e412ff71aa9af85ef0ae4903e0d6a8d16d438fe6969b24da1aacd565267518b33d00604370c345c8007c382f1c931daa695d9ef59dfb996629c4d73e69693d8e88a2ee7edaa5b6359067e0676c7eaea9d250cdd50e99173d1e68d54a2ea0085516f1461f7dcbd088dc6d7537f9bd2db5e3436346a22cc67a72fcfa7bef32677e9933f2198659b117541839c9c27b6bb990018779fefacf93ef58ac74481d486109d177dceff7bed85ddc3e82e2c126a66aa84d57caad2edadb33e56511d4becb5d320fd9eff979586d884cf3e34342d4435804d0bb7eb972eae8a21b486e4120b55101b1a52f63bf1d9cb5033496b5258d27c34a94a8813c146cd7aff1b427f99560b4678313b648438c95371c31277d86a78d947110f4bc1b8146d3df402551f351172df48e6ef1eaf0d46b05b16509ca044657afb54084403a135def4c4b9e43c15d0d8dde203d4108064e07822f1021b748f95eb9a983f9259d49becf46642c93e8f10a8a56a4697ee1c653c0f6bc3b6548cb0604a23442b65d459cfb239b44e32e356db260e8634a457649171a7fef6547b971fdd90ddfd8e9548d48922fbeb3937e5900b9e55156ea63547970ab902fd3cb490481e82a3c69b0b08b2a215a03ad5a1277c4e1c7ffd6cf984457a1352735e007246fa12289629781400e648ed086b48442859c126cad10f41d715e01a6bde4241c12a4bfce362be59a1b8a8952379eb22e20e093c2d1d30a0701eb9a3f6f9010703699ed7d6dec9b4d529617c38fe0b9d8188270047c588818b843618b067303770d20449e8cf1df2b74524512db7fa458260ca52b00f46d344499dd82ee951edc94e6da28db68fefba95fe273a52190a10c234aaffbe35534323a9757ef169709b80594ec6b099ec6d156eb1b659c283b1a80c0179fbb18a5a180d6c3d5f43821969aa7c092fcfa06c08762c3b7e4850c76e4180eb1175891fe119b303b823dc8c1fee5fd589edddc238876414ccf36f16f01061616517a92d57d0acc00d7ebb0410a7a8b3761c68b45de850002f76680ee13db5cff191f933b22479e16cb9a973d5183d4528c5d1acc2085627fda64ff2bba9a88b71f32fcbbf82c49b8d9d49477bf9a02901b85b9e5374f5ad6a013900b119a04d532583c847fab9d6bb7f5125babf86f958e05334571dff2a391070b7a33ff77e3dd373e632344bbb7e1d19eab65a7b27fdd8820372a66230a48fd2321606bf2f5cca4f7b69e87d7388cb7ccc5830fcc5517934ff881e9910afeadf194876fe2ed267aefd880633bb37892e87ab561b2145a12cb27d32188bb1eaf7ca6cb4f5c34836637bdbda227230f37b6aec4235bd24657c8dfead530822a5133d69fac63893fbff9ebce128242536307145fc879ba4573d4eb95c918a31a26ac0f985003afe083733a8e5f8d4aab377b100ea05490533517dcc336ca599f7582a07eab9629533df6eb38fdd3ef09963fcf76b84f492ef5833245aecb9979c3e4b09c61b30eb6d31d1f7a3434f3f5f04e6285098320993b51d848d6a349b80e89e6857e8394380d91710eb2ba03221bc4562fe5f8bb7f8f6e1353f4da07733f58ec3c847e54fd6bf31cb32adbb701b6c5bcd79defe5de7901b5ca92010289991b83079959d64dcc140c612f4a773995a0de2abbc2b9c601b026fa5e3340c03fd06fca4c8e2d58d117132cb86647a2a16c1dbf71262ce644e1c178799b9e5941c7cd866bd407196caa9a511acc3c1f0ff73150ce847b6a88aaa8f8c5c2685dba9ba63cefafd89d7ddcf97e133951639cf6d021d92f172437c72968098b3f0ed3040c282cfcb7bced1baa9d17c6af35b97946a16170d8cda40039f08872a35bab3924b871a7620357c329f9c6c0bb9e03fe77313e77e5e4f7f2f151e600c8cb330b21599e4ce616ca5ad16e1548bdfa10c5aa92d7b436d22ccf894fd28364b7e5eb81a5967b1cc3f7cf3dea6c432595a0389cafa00059e3cac41c67bb71427cf56501fcd77cb3c239c73b996774a7fa9fd410e3fe3184900c8578a8d0a988445d0567ad0a2fbbb055cfdf14c4184516d5ce31b3ac4dbad3fe89367c83f0fdcdb1dcab1b8eac5da64183cf9849a471425f2f63135644a45ccd0f5a68cc7b1f3871e32729ea37c1ca433c13011d725898b455e1c74104d9bdd9a99c0ca640a159d4a6040e69480f82da58d9ea45284353cfeee835c023d8f9b07a14d43be376d4421b4f6a1fbbc2b877272098ca2b61bb2d38cb2691e7429619fa53a566709" } ] } From 06b222a4c912d81b1c5974047d3e20812a5e1c76 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Mon, 21 Sep 2026 23:03:52 +0900 Subject: [PATCH 10/97] fix: harden zcash runtime validation and lifecycle --- chain-runtimes/zcash/Cargo.lock | 1 - chain-runtimes/zcash/Cargo.toml | 1 - .../crates/zcash-keys-runtime/Cargo.toml | 5 +- .../crates/zcash-keys-runtime/src/bindgen.rs | 37 +--- .../crates/zcash-keys-runtime/src/error.rs | 4 - .../crates/zcash-keys-runtime/src/keys.rs | 24 +- .../crates/zcash-keys-runtime/src/lib.rs | 7 +- .../crates/zcash-keys-runtime/src/sign.rs | 87 ++++---- .../src/transparent_send.rs | 130 ++++++++--- .../src/transparent_send/shielding.rs | 34 ++- .../zcash/crates/zcash-runtime/Cargo.toml | 2 +- .../zcash/crates/zcash-runtime/src/account.rs | 21 +- .../zcash/crates/zcash-runtime/src/bindgen.rs | 42 +++- .../crates/zcash-runtime/src/blockcache.rs | 205 +++++++++--------- .../zcash/crates/zcash-runtime/src/error.rs | 9 + .../zcash/crates/zcash-runtime/src/runtime.rs | 39 +++- .../zcash/crates/zcash-runtime/src/send.rs | 10 +- .../zcash/crates/zcash-runtime/src/sync.rs | 14 +- .../zcash-storage-benchmark/src/error.rs | 3 +- 19 files changed, 397 insertions(+), 278 deletions(-) diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock index e3b723713..fb53d016c 100644 --- a/chain-runtimes/zcash/Cargo.lock +++ b/chain-runtimes/zcash/Cargo.lock @@ -1687,7 +1687,6 @@ dependencies = [ name = "onekey-zcash-runtime" version = "0.1.0-rc.1" dependencies = [ - "async-trait", "console_error_panic_hook", "futures", "futures-util", diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml index 95c8a6d71..316334a8f 100644 --- a/chain-runtimes/zcash/Cargo.toml +++ b/chain-runtimes/zcash/Cargo.toml @@ -62,7 +62,6 @@ getrandom = "0.4" thiserror = "2" schemerz = "0.2" schemerz-rusqlite = "0.370" -async-trait = "0.1" futures-util = { version = "0.3", default-features = false } sapling = { package = "sapling-crypto", version = "0.7", default-features = false } diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml index bf40333b1..b4ccb8188 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml @@ -20,7 +20,6 @@ zcash_protocol.workspace = true zcash_address.workspace = true zcash_primitives = { workspace = true, features = ["transparent-inputs"] } zip32 = "0.2" -bip0039 = { version = "0.12", features = ["all-languages"] } bs58 = { version = "0.5", features = ["check"] } zeroize = { version = "1", features = ["zeroize_derive"] } zcash_note_encryption = "0.4" @@ -40,6 +39,10 @@ orchard = { version = "0.15", default-features = false } sapling.workspace = true thiserror.workspace = true +# bip0039 只在测试里出现:出厂产物不收助记词,宿主传种子字节。 +[dev-dependencies] +bip0039 = { version = "0.12", features = ["all-languages"] } + [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen.workspace = true js-sys.workspace = true diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs index 0c3f3aa22..3b887660c 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs @@ -13,17 +13,6 @@ pub fn validate_address(network: &str, address: &str) -> Result { Ok(keys::validate_address(network, address)?) } -/// 从助记词派生该账户的 UFVK。助记词与种子在 Rust 侧用完即擦。 -#[wasm_bindgen(js_name = ufvkFromMnemonic)] -pub fn ufvk_from_mnemonic( - network: &str, - mnemonic: String, - account_index: u32, -) -> Result { - let mnemonic = Zeroizing::new(mnemonic); - Ok(keys::ufvk_from_mnemonic(network, &mnemonic, account_index)?) -} - /// 从 UFVK 取统一地址。纯公开材料,不涉及私钥。 /// /// `receiverPolicy` 决定 UA 里包含哪些 receiver:`"all"` / `"shielded"` / @@ -40,33 +29,9 @@ pub fn unified_address( Ok(keys::unified_address_with(network, ufvk, receiver_policy)?) } -/// 给 PCZT 签名。 -/// -/// 这是整个方案里唯一接触花费密钥的接口。助记词在 Rust 侧派生、用完即擦, -/// 种子与花费密钥不会跨这条边界返回。 -/// -/// 输入是 `onekey-zcash-runtime` 的 `pcztCreate` 产物, -/// 输出交回它的 `pcztSend` 终结并广播。 -#[wasm_bindgen(js_name = pcztSign)] -pub fn pczt_sign( - network: &str, - mnemonic: String, - account_index: u32, - pczt_bytes: Vec, -) -> Result, JsValue> { - let mnemonic = Zeroizing::new(mnemonic); - Ok(sign::sign_pczt_with_mnemonic( - network, - &mnemonic, - account_index, - &pczt_bytes, - )?) -} - /// 从**种子字节**派生 UFVK。 /// -/// OneKey 的架构里,助记词只在解密那一刻出现一次,之后全程传种子。 -/// 所以这才是接进 app 的实际入口;`ufvkFromMnemonic` 主要用于测试与独立验证。 +/// 助记词只在解密那一刻出现一次,之后全程传种子 —— 本边界不收助记词。 #[wasm_bindgen(js_name = ufvkFromSeed)] pub fn ufvk_from_seed(network: &str, seed: Vec, account_index: u32) -> Result { // Own and wipe the original bindgen allocation, including on validation errors. diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs index 3ffc35424..835faf9d2 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs @@ -51,8 +51,6 @@ pub enum ErrorCode { InvalidAmount, /// Selected inputs cannot cover outputs and the ZIP-317 fee. InsufficientFunds, - /// The transaction would create uneconomic transparent change. - DustChange, /// An account-level BIP-44 xprv is malformed or has unexpected metadata. InvalidAccountXprv, /// An account-level BIP-44 xpub is malformed or has unexpected metadata. @@ -88,7 +86,6 @@ impl ErrorCode { KeyMismatch => "KEY_MISMATCH", InvalidAmount => "INVALID_AMOUNT", InsufficientFunds => "INSUFFICIENT_FUNDS", - DustChange => "DUST_CHANGE", InvalidAccountXprv => "INVALID_ACCOUNT_XPRV", InvalidAccountXpub => "INVALID_ACCOUNT_XPUB", TransactionBuildFailed => "TRANSACTION_BUILD_FAILED", @@ -207,7 +204,6 @@ mod tests { KeyMismatch, InvalidAmount, InsufficientFunds, - DustChange, InvalidAccountXprv, InvalidAccountXpub, TransactionBuildFailed, diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs index e398cabb6..8efe88ded 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs @@ -5,6 +5,7 @@ use zcash_keys::keys::{UnifiedFullViewingKey, UnifiedSpendingKey}; use zcash_protocol::consensus::Network; +#[cfg(test)] use zeroize::Zeroizing; use zip32::AccountId; @@ -45,23 +46,27 @@ pub fn validate_address(network: &str, encoded: &str) -> Result { Ok(supported_recipient(¶ms, encoded).is_some()) } -/// 从 BIP-39 助记词派生该账户的 UFVK。 +/// 测试专用:从助记词派生 UFVK。 /// -/// 助记词与派生出的种子都在函数内擦除;返回值只有可公开的 UFVK 字符串。 -pub fn ufvk_from_mnemonic(network: &str, mnemonic: &str, account_index: u32) -> Result { +/// 出厂产物不收助记词 —— 宿主只传种子字节。留着它是为了让金标向量测试 +/// 能直接喂参考实现用的助记词。 +#[cfg(test)] +pub(crate) fn ufvk_from_mnemonic( + network: &str, + mnemonic: &str, + account_index: u32, +) -> Result { let params = parse_network(network)?; - let parsed = bip0039::Mnemonic::::from_phrase(mnemonic) .map_err(|_| KeysError::new(ErrorCode::InvalidMnemonic))?; - - // 种子放进 Zeroizing,离开作用域即擦。 let seed = Zeroizing::new(parsed.to_seed("")); ufvk_from_seed_bytes(params, seed.as_ref(), account_index) } /// 从原始种子字节派生 UFVK。 /// -/// 调用方给的切片本 crate 不持有;内部所有副本都受 `Zeroizing` 管理。 +/// 调用方给的切片本 crate 不持有。注意中间的 `UnifiedSpendingKey` 上游没有 +/// `ZeroizeOnDrop`,析构后仍留在线性内存里 —— 擦除责任在宿主那一侧。 pub fn ufvk_from_seed_bytes(params: Network, seed: &[u8], account_index: u32) -> Result { if seed.len() < 32 { return Err(KeysError::with( @@ -147,10 +152,6 @@ pub fn transparent_address(network: &str, ufvk_str: &str) -> Result { )) } -/// 种子指纹(ZIP-32)。 -/// -/// **这是标准值,不是随便一个标识符** —— 宿主把它持久化下来当账户身份用, -/// 所以必须与 ZIP-32 的定义一致。自己另发明一套哈希会让存量账户全部失配。 /// UFVK 里的透明账户公钥,BIP32 账户层(m/44'/133'/account'): /// 32 字节 chain code || 33 字节压缩公钥,hex。宿主据此拼 xpub, /// 硬件账户无需再向设备额外要一次透明 xpub。 @@ -167,6 +168,7 @@ pub fn transparent_account_pubkey(network: &str, ufvk_str: &str) -> Result Result { if seed.len() < 32 { return Err(KeysError::with( diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs index 8a597a1eb..5ccdcb1af 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs @@ -8,8 +8,11 @@ //! ## 密钥纪律 //! //! - 种子与花费密钥(USK)**只在本 crate 内部存在**,不跨 wasm 边界。 -//! - 所有中间副本用 `Zeroize` 擦除;JS 侧永远只拿到 UFVK 和地址。 -//! - 调用方传进来的种子字节,本 crate 用完即擦。 +//! - JS 侧永远只拿到 UFVK 和地址;出厂边界不收助记词,只收种子字节。 +//! - 种子(含调用方传进来的那份)用 `Zeroizing` 包裹,用完即擦。 +//! - **但派生出的密钥擦不掉**:`UnifiedSpendingKey`、`AccountPrivKey`、 +//! `secp256k1::SecretKey` 上游都没有 `ZeroizeOnDrop`,析构后仍留在 wasm +//! 线性内存里。别把这一条读成「全链路擦干净」—— 它不是。 pub mod error; pub mod keys; diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs index 2ad186232..04b89c877 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs @@ -1,47 +1,25 @@ -//! PCZT 签名。 +//! PCZT signing with keys derived from caller-provided seed bytes. //! -//! **这是整个方案里唯一接触花费密钥的地方。** -//! -//! 构造 PCZT 需要钱包数据库(选币、witness、anchor),签名需要种子。 -//! 两者分处两个 crate,所以: -//! -//! - `onekey-zcash-runtime` 里没有任何路径能拿到种子; -//! - 移动端只打这个 keys 包时,签名依然可用; -//! - 想审计「私钥去了哪」,只需要看这一个文件。 -//! -//! 种子在函数内派生、用完即 `zeroize`,绝不跨 wasm 边界返回。 +//! This crate also handles spending keys in `keys` and `transparent_send`. +//! See the crate documentation for the limits of derived-key zeroization. use pczt::roles::signer::Signer; +use pczt::roles::verifier::{TransparentError, Verifier}; +use transparent::sighash::SighashType; use zcash_keys::keys::UnifiedSpendingKey; use zcash_protocol::consensus::Network; -use zeroize::Zeroizing; use zip32::AccountId; use crate::error::{ErrorCode, KeysError, Result}; -use crate::keys::parse_network; -/// 用助记词派生出的花费密钥给 PCZT 签名。 +/// 透明输入的签名是否盖住全部输出。 /// -/// 只签 Orchard 花费 —— 本方案不支持 Sapling 花费(Sapling 的 Groth16 证明参数 -/// 约 50 MB,不适合随包分发;新收到的资金也不会落在 Sapling 池)。 -/// -/// 返回签名后的 PCZT 字节,交回 runtime 的 `pcztSend` 终结并广播。 -pub fn sign_pczt_with_mnemonic( - network: &str, - mnemonic: &str, - account_index: u32, - pczt_bytes: &[u8], -) -> Result> { - let params = parse_network(network)?; - - let parsed = bip0039::Mnemonic::::from_phrase(mnemonic) - .map_err(|_| KeysError::new(ErrorCode::InvalidMnemonic))?; - let seed = Zeroizing::new(parsed.to_seed("")); - - sign_pczt_with_seed(params, seed.as_ref(), account_index, pczt_bytes) +/// 非 `SIGHASH_ALL` 的签名盖不住输出,拿到已签交易的人能改写收款地址。四处 +/// 签名/校验路径共用这一个判定,别在调用点各写各的 —— 写岔一处就是一个洞。 +pub(crate) fn is_sighash_all(input: &transparent::pczt::Input) -> bool { + *input.sighash_type() == SighashType::ALL } -/// 同上,但直接接收种子字节。调用方负责擦除自己那份。 /// 本 crate 当前实际能签的 bundle 类型。定义在实现旁边,翻转时必然改到实现。 pub const SIGN_ORCHARD: bool = true; pub const SIGN_SAPLING: bool = false; @@ -55,7 +33,10 @@ pub const SIGN_IRONWOOD: bool = true; /// `script_pubkey`,不匹配就报错 —— 所以试签不会静默产出错误签名。 /// /// 取值要覆盖钱包的 gap limit(默认 20),留一倍余量。 -const TRANSPARENT_SCAN_GAP: u32 = 40; +/// +/// 这个上限同时约束**找零地址的序号**(见 `transparent_send`):找零落在扫描 +/// 范围之外,就是一笔钥匙还在、钱包却再也签不出来的钱。 +pub(crate) const TRANSPARENT_SCAN_GAP: u32 = 40; /// 给全部透明输入签名,返回 (签上了几个, 最后一次失败原因)。 /// @@ -101,6 +82,10 @@ fn sign_transparent_inputs( (signed, last_err) } +/// 用种子派生出的花费密钥给 PCZT 签名。调用方负责擦除自己那份种子。 +/// +/// 只签 Orchard/Ironwood 花费与透明输入 —— 不支持 Sapling 花费 +/// (Groth16 证明参数约 50 MB,不随包分发;新收到的资金也不落在 Sapling 池)。 pub fn sign_pczt_with_seed( params: Network, seed: &[u8], @@ -127,6 +112,31 @@ pub fn sign_pczt_with_seed( let pczt = pczt::Pczt::parse(pczt_bytes) .map_err(|e| KeysError::new(ErrorCode::PcztParseFailed).detail(format!("{e:?}")))?; + // 签名前的闸门。上游 `Signer::sign_*` 的文档明写:语义校验是调用方的责任。 + // + // 这里守住最要命的一条:签名必须盖住全部输出。`SIGHASH_ALL` 之外的类型 + // (`NONE`、`SINGLE|ANYONECANPAY` 等)签出来的透明输入,拿到已签交易的人 + // 可以改写收款地址。姊妹模块 shielding.rs 三处都查了这一条,这条路漏了。 + let pczt = Verifier::new(pczt) + .with_transparent(|bundle| { + match bundle + .inputs() + .iter() + .position(|input| !is_sighash_all(input)) + { + Some(index) => Err(TransparentError::Custom(KeysError::with( + ErrorCode::PcztSignFailed, + serde_json::json!({ + "reason": "transparentInputSighashNotAll", + "inputIndex": index, + }), + ))), + None => Ok(()), + } + }) + .map_err(|e| KeysError::new(ErrorCode::PcztSignFailed).detail(format!("{e:?}")))? + .finish(); + let mut signer = Signer::new(pczt) .map_err(|e| KeysError::new(ErrorCode::PcztSignFailed).detail(format!("{e:?}")))?; @@ -209,8 +219,7 @@ fn bundle_counts(pczt_bytes: &[u8]) -> Result<(usize, usize, usize)> { mod tests { use super::*; - const M: &str = - "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + const SEED: [u8; 32] = [7u8; 32]; #[test] fn rejects_short_seed() { @@ -221,13 +230,7 @@ mod tests { #[test] fn rejects_garbage_pczt() { - let e = sign_pczt_with_mnemonic("test", M, 0, b"not a pczt").unwrap_err(); + let e = sign_pczt_with_seed(Network::TestNetwork, &SEED, 0, b"not a pczt").unwrap_err(); assert_eq!(e.code, ErrorCode::PcztParseFailed); } - - #[test] - fn rejects_bad_mnemonic() { - let e = sign_pczt_with_mnemonic("test", "clearly not a mnemonic", 0, &[]).unwrap_err(); - assert_eq!(e.code, ErrorCode::InvalidMnemonic); - } } diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs index 2a45f3367..819cf2c8d 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs @@ -405,37 +405,57 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { serde_json::json!({ "field": "change.derivationPath", "reason": "internalScopeRequired" }), )); } - let mut addresses_with_change = recipient_addresses; - addresses_with_change.push(RecipientAddress::Transparent(change_address)); - let fee = calculate_fee(target_height, inputs.len(), &addresses_with_change)?; - let needed = send_total_raw - .checked_add(fee.into_u64()) - .ok_or_else(|| amount_error("recipientTotal"))?; - let change_raw = input_total_raw - .checked_sub(needed) - .ok_or_else(|| insufficient_funds(input_total_raw, needed))?; - if change_raw < MARGINAL_FEE.into_u64() { + // 找零序号必须落在签名时的扫描范围内。PCZT 不把派生路径交给 + // `sign_transparent_inputs`,那边只能按序号试到 `TRANSPARENT_SCAN_GAP`; + // 序号更大的找零是「钥匙还在、钱包再也签不出来」的钱。宿主当前把找零 + // 固定在 .../1/0,这条只是把那个事实钉成契约。 + if change_path.index >= crate::sign::TRANSPARENT_SCAN_GAP { return Err(KeysError::with( - ErrorCode::DustChange, + ErrorCode::InvalidDerivationPath, serde_json::json!({ - "changeZat": change_raw.to_string(), - "minimumZat": MARGINAL_FEE.into_u64().to_string(), + "field": "change.derivationPath", + "reason": "indexBeyondSigningScanRange", + "index": change_path.index, + "max": crate::sign::TRANSPARENT_SCAN_GAP - 1, }), )); } - let change_value = parse_zatoshis_u64(change_raw, "change")?; - ( - fee, - Some(( - change_request.clone(), - PlannedOutput { - address: RecipientAddress::Transparent(change_address), - user_address: change_request.address, - value: change_value, - }, - change_path, - )), - ) + let mut addresses_with_change = recipient_addresses; + addresses_with_change.push(RecipientAddress::Transparent(change_address)); + let fee_with_change = calculate_fee(target_height, inputs.len(), &addresses_with_change)?; + let needed_with_change = send_total_raw + .checked_add(fee_with_change.into_u64()) + .ok_or_else(|| amount_error("recipientTotal"))?; + let change_raw = input_total_raw.saturating_sub(needed_with_change); + + // 找零养不起自己时,把这点零头并进手续费、发一笔无找零的交易。 + // + // 这里原本有两条失败路:找零 < MARGINAL_FEE 抛 DustChange,钱不够再加 + // 一个输出抛 InsufficientFunds。后者是假话 —— 钱是够的,只是不够养一个 + // 找零输出;而「零头进手续费」的无找零交易完全成立。上游屏蔽路径的 + // `DustAction::AddDustToFee` 就是这个做法,透明这边缺了。 + // + // 走到这里已经确定 input_total > send_total + fee_without_change,所以 + // 减法不会下溢,付出的手续费也一定不低于最低要求。多付的上限是 + // fee_with_change + MARGINAL_FEE,量级在万分之一 ZEC 以内。 + if input_total_raw < needed_with_change || change_raw < MARGINAL_FEE.into_u64() { + let fee_raw = input_total_raw - send_total_raw; + (parse_zatoshis_u64(fee_raw, "fee")?, None) + } else { + let change_value = parse_zatoshis_u64(change_raw, "change")?; + ( + fee_with_change, + Some(( + change_request.clone(), + PlannedOutput { + address: RecipientAddress::Transparent(change_address), + user_address: change_request.address, + value: change_value, + }, + change_path, + )), + ) + } }; Ok(TransactionPlan { @@ -1017,6 +1037,64 @@ mod tests { assert_eq!(built.spent_outpoints, quote.spent_outpoints); } + /// 找零够不上 dust 门槛时,零头并进手续费发无找零交易 —— 不是拒绝。 + /// + /// 100,000 的 UTXO 发 88,000:有找零和无找零的手续费都是 10,000(ZIP-317 + /// 1-in 两档都落在 grace 2),富余 2,000 养不起一个找零输出。改之前这里 + /// 直接抛 DustChange,用户只能改金额 —— 而这笔交易本身完全成立。 + #[test] + fn sub_dust_change_goes_into_the_fee_instead_of_failing() { + let mut request: serde_json::Value = + serde_json::from_str(&request_json(&[100_000], false)).unwrap(); + request["recipients"][0]["amountZat"] = "88000".into(); + let request = request.to_string(); + + let quote: TransparentQuote = serde_json::from_str("e_json(&request).unwrap()).unwrap(); + assert_eq!(quote.send_amount_zat, "88000"); + assert_eq!(quote.change_zat, "0"); + assert_eq!(quote.fee_zat, "12000", "富余应全部进手续费"); + + let built: TransparentBuildResult = + serde_json::from_str(&build_with_seed_json(&request, &seed()).unwrap()).unwrap(); + assert_eq!(built.fee_zat, "12000"); + } + + /// 同一个死区的另一半,改之前报的是**假的「余额不足」**。 + /// + /// 1-in/3-out 时 fee_without_change=15,000、fee_with_change=20,000。富余 + /// 17,000 落在两者之间:加不起找零输出,但无找零的交易成立。旧代码在 + /// `checked_sub` 上下溢,直接告诉用户钱不够。 + #[test] + fn surplus_between_the_two_fee_tiers_is_not_reported_as_insufficient_funds() { + let mut request: serde_json::Value = + serde_json::from_str(&request_json(&[47_000], false)).unwrap(); + let one = request["recipients"][0].clone(); + request["recipients"] = serde_json::json!([one.clone(), one.clone(), one]); + for i in 0..3 { + request["recipients"][i]["amountZat"] = "10000".into(); + } + let request = request.to_string(); + + let quote: TransparentQuote = serde_json::from_str("e_json(&request).unwrap()).unwrap(); + assert_eq!(quote.send_amount_zat, "30000"); + assert_eq!(quote.change_zat, "0"); + assert_eq!(quote.fee_zat, "17000"); + } + + /// 找零序号必须落在签名端的扫描范围内,否则找零变成签不出来的钱。 + #[test] + fn rejects_change_index_outside_the_signing_scan_range() { + let mut request: serde_json::Value = + serde_json::from_str(&request_json(&[100_000], false)).unwrap(); + request["change"]["derivationPath"] = "m/44'/133'/0'/1/40".into(); + let e = quote_json(&request.to_string()).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidDerivationPath); + + // 范围内的仍然放行 + request["change"]["derivationPath"] = "m/44'/133'/0'/1/39".into(); + assert!(quote_json(&request.to_string()).is_ok()); + } + #[test] fn quotes_send_max_without_change() { let quote: TransparentQuote = diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs index 6175019e8..712072298 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs @@ -282,7 +282,7 @@ pub fn combine_hardware_signed( if signatures.len() != 1 || signature.last() != Some(&1) || input.script_sig().is_some() - || *input.sighash_type() != transparent::sighash::SighashType::ALL + || !crate::sign::is_sighash_all(input) { return Err(TransparentError::Custom(mismatch())); } @@ -467,7 +467,7 @@ fn validate_original( let verified = Verifier::new(pczt) .with_transparent(|bundle| { if bundle.inputs().iter().any(|input| { - *input.sighash_type() != transparent::sighash::SighashType::ALL + !crate::sign::is_sighash_all(input) || input.redeem_script().is_some() || input.script_sig().is_some() || !input.partial_signatures().is_empty() @@ -533,7 +533,7 @@ fn sign_with_key( if bundle .inputs() .iter() - .any(|input| *input.sighash_type() != transparent::sighash::SighashType::ALL) + .any(|input| !crate::sign::is_sighash_all(input)) { return Err(TransparentError::Custom(mismatch())); } @@ -864,6 +864,34 @@ mod tests { } } + /// `pcztSignWithSeed` 是通用签名入口,PCZT 从宿主传进来。上游 `Signer` 的 + /// 文档把语义校验的责任明确留给调用方,所以那一侧必须自己守 `SIGHASH_ALL`: + /// 非 ALL 的签名盖不住输出,拿到已签交易的人能改收款地址。 + /// + /// 正向用例同时钉住另一件事:屏蔽 PCZT 的 ironwood action 只有输出、 + /// 没有可签的 spend,**部分池签不上是正常的**,不能改成「每池全签」。 + #[test] + fn generic_signer_requires_sighash_all_on_transparent_inputs() { + use zcash_protocol::consensus::Network; + + let request = request(false).to_string(); + let original = create(&request, &SEED).unwrap(); + + crate::sign::sign_pczt_with_seed(Network::MainNetwork, &SEED, 0, &original) + .expect("未改动的屏蔽 PCZT 应当能签"); + + let modified = mutate(&original, |value| { + value["transparent"]["inputs"][0]["sighash_type"] = 2.into(); + }); + let e = crate::sign::sign_pczt_with_seed(Network::MainNetwork, &SEED, 0, &modified) + .expect_err("sighash_type 不是 ALL 必须拒签"); + assert_eq!(e.code, ErrorCode::PcztSignFailed); + assert!( + format!("{:?}", e.detail).contains("transparentInputSighashNotAll"), + "应指出是 sighash 策略问题,实际 {e:?}" + ); + } + #[test] fn rejects_modified_transparent_effects_and_sighash_policy() { let request = request(false).to_string(); diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml index c7a74464d..5fd39219d 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml @@ -35,7 +35,7 @@ getrandom.workspace = true tonic.workspace = true hex.workspace = true prost.workspace = true -async-trait.workspace = true + futures-util.workspace = true sapling.workspace = true uuid.workspace = true diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs index 008de4413..0ffa92330 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs @@ -7,7 +7,6 @@ use zcash_client_backend::data_api::{ Account as _, AccountBirthday, AccountPurpose, WalletRead, WalletWrite, Zip32Derivation, }; use zcash_keys::keys::UnifiedFullViewingKey; -use zcash_protocol::consensus::BlockHeight; use crate::error::{ErrorCode, Result, RuntimeError}; use crate::network::{self, LightClient}; @@ -56,13 +55,7 @@ pub async fn import_ufvk( })?; let account = db - .import_account_ufvk( - account_name, - &ufvk, - &birthday, - purpose, - None, - ) + .import_account_ufvk(account_name, &ufvk, &birthday, purpose, None) .map_err(|e| { RuntimeError::with( ErrorCode::DatabaseError, @@ -76,8 +69,11 @@ pub async fn import_ufvk( fn parse_zip32_derivation(fingerprint_hex: &str, account_index: u32) -> Result { let bytes = hex::decode(fingerprint_hex).map_err(|e| { - RuntimeError::with(ErrorCode::InvalidAccountId, json!({ "field": "seedFingerprint" })) - .detail(e) + RuntimeError::with( + ErrorCode::InvalidAccountId, + json!({ "field": "seedFingerprint" }), + ) + .detail(e) })?; let fingerprint: [u8; 32] = bytes.try_into().map_err(|_| { RuntimeError::with( @@ -263,11 +259,6 @@ fn uuid_from_str(s: &str) -> Result { }) } -/// 高度换算成 `BlockHeight`,越界时给出可读错误。 -pub fn block_height(h: u32) -> BlockHeight { - BlockHeight::from_u32(h) -} - /// 构造确认数策略。两个门槛都必须 >= 1,且 trusted <= untrusted。 pub fn confirmations_policy( trusted: u32, diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs index ca50f9d69..b35a95a9a 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs @@ -640,6 +640,20 @@ pub fn release_reservation(reservation_id: String) -> Result { })?) } +/// 在一件**已经不可逆地发生了**的事情之后做落盘屏障。 +/// +/// 屏障失败的含义是「持久化有没有到达耐久存储未知」,不是「这件事失败了」。 +/// 两个调用点都已越过不可逆点 —— `pcztSend` 已提交交易并交出 note, +/// `broadcastTransaction` 已把交易发上网。把真实结局换成一个泛化的存储错误, +/// 宿主就会去重试、或者把一笔已上链的交易显示成「未知失败」。 +/// +/// 调用方自己写 params(各自的结局形状不同),错误码与 detail 由这里统一。 +async fn barrier_after_irreversible(params: serde_json::Value) -> Result<(), crate::RuntimeError> { + storage::durability_barrier().await.map_err(|error| { + crate::RuntimeError::with(crate::ErrorCode::FinalizeOutcomeUnknown, params).detail(error) + }) +} + /// 终结已证明且已签名的 PCZT,提取交易并**写回本地钱包**,返回 txid。 /// /// **这一步不发网络。** 交易还没有广播出去,必须再调 `broadcastTransaction(txid)`。 @@ -659,13 +673,7 @@ pub async fn pczt_send( // means the host does not know whether persistence reached durable storage, // but it must never be allowed to unlock inputs that may already be spent. send::forget_reservation(&reservation_id); - storage::durability_barrier().await.map_err(|error| { - crate::RuntimeError::with( - crate::ErrorCode::FinalizeOutcomeUnknown, - serde_json::json!({ "operation": "finalizeTransaction" }), - ) - .detail(error) - })?; + barrier_after_irreversible(serde_json::json!({ "operation": "finalizeTransaction" })).await?; Ok(txid) } @@ -713,9 +721,14 @@ pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> { let r = match r { Ok(()) => tx_state::mark_accepted(&mut db, &txid), Err(e) if e.code == crate::ErrorCode::BroadcastRejected => { + // 落库失败也要把**节点给的拒绝原因**交回宿主:那才是用户能据以 + // 行动的信息,而重试这笔广播只会被同样地拒。落库本身的失败作为 + // detail 附上,不顶替结论。 match tx_state::mark_rejected(&mut db, &txid, &e) { Ok(()) => Err(e), - Err(persist_error) => Err(persist_error), + Err(persist_error) => { + Err(e.detail(format!("mark_rejected failed: {persist_error}"))) + } } } Err(e) => Err(e), @@ -728,7 +741,18 @@ pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> { .as_ref() .is_err_and(|error| error.code == crate::ErrorCode::BroadcastRejected); if changed_lifecycle { - storage::durability_barrier().await?; + // 广播已经发生,生命周期也已写进事务 —— 结局必须原样带给宿主。 + let outcome = match &result { + Ok(()) => serde_json::json!({ "broadcast": "accepted" }), + Err(rejection) => serde_json::json!({ + "broadcast": "rejected", + "rejection": rejection.to_json(), + }), + }; + barrier_after_irreversible( + serde_json::json!({ "operation": "broadcastTransaction", "outcome": outcome }), + ) + .await?; } Ok(result?) } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs index f9ad23f88..ac307a53f 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs @@ -13,7 +13,7 @@ use std::collections::BTreeMap; use std::ops::Range; use std::sync::Mutex; -use zcash_client_backend::data_api::chain::{error, BlockCache, BlockSource}; +use zcash_client_backend::data_api::chain::{error, BlockSource}; use zcash_client_backend::data_api::scanning::ScanRange; use zcash_client_backend::proto::compact_formats::CompactBlock; use zcash_protocol::consensus::BlockHeight; @@ -49,6 +49,27 @@ impl MemoryBlockCache { let r = range.block_range(); u32::from(r.start)..u32::from(r.end) } + /// 写入一批区块。缓存是过程性数据,重复写入同一高度即覆盖。 + pub fn insert(&self, compact_blocks: Vec) -> Result<(), CacheError> { + let mut blocks = self.blocks.lock().map_err(|_| poisoned())?; + for b in compact_blocks { + let h = u32::try_from(b.height) + .map_err(|_| CacheError(format!("区块高度超出范围: {}", b.height)))?; + blocks.insert(h, b); + } + Ok(()) + } + + /// 扫完即弃:删掉一段区间,把内存还回去。 + pub fn delete(&self, range: &ScanRange) -> Result<(), CacheError> { + let mut blocks = self.blocks.lock().map_err(|_| poisoned())?; + let r = Self::range_of(range); + let doomed: Vec = blocks.range(r).map(|(h, _)| *h).collect(); + for h in doomed { + blocks.remove(&h); + } + Ok(()) + } } /// 缓存自身的错误。内存实现里唯一可能的失败是锁中毒。 @@ -79,28 +100,53 @@ impl BlockSource for MemoryBlockCache { where F: FnMut(CompactBlock) -> Result<(), error::Error>, { - // 先在持锁时把需要的区块**收集出来**,再释放锁,最后才执行回调。 + // 交出去的必须是**从 from_height 起的连续前缀**,允许短读。 // - // 不能在持锁期间调 `with_block` —— 回调会写钱包库,而上游有可能在那条 - // 路径上再次读取本缓存。`std::sync::Mutex` 不可重入,同一线程二次加锁 - // 在 wasm 单线程环境下就是永久死锁。 + // 这条契约不是形式主义:调用方拿 `prior` 的元数据去接续扫描,喂给它一段 + // 跳号的块会被上游判成 `BlockHeightDiscontinuity`,而那个错误 是 + // `is_continuity_error()` 的真值 —— 于是服务端漏块会被当成链重组,触发 + // 破坏性回退、重下、再撞同一个洞。宁可短读让下一轮重来。 + // + // 先在持锁时收集,再释放锁,最后才执行回调:回调会写钱包库,而上游有 + // 可能在那条路径上再次读取本缓存。`std::sync::Mutex` 不可重入,同一线程 + // 二次加锁在 wasm 单线程环境下就是永久死锁。 let selected: Vec = { let blocks = self .blocks .lock() .map_err(|_| error::Error::BlockSource(poisoned()))?; - let start = from_height.map(u32::from).unwrap_or(0); - let iter = blocks.range(start..).map(|(_, b)| b.clone()); - match limit { - Some(n) => iter.take(n).collect(), - None => iter.collect(), + let cap = limit.unwrap_or(usize::MAX); + let start = match from_height.map(u32::from) { + Some(h) => h, + None => blocks.keys().next().copied().unwrap_or(0), + }; + + let mut out = Vec::new(); + let mut expect = start; + while out.len() < cap { + let Some(block) = blocks.get(&expect) else { + break; + }; + out.push(block.clone()); + let Some(next) = expect.checked_add(1) else { + break; + }; + expect = next; } + + // 起点缺失时一块都不交,并且**报错而不是静默返回空**:静默空会让 + // 上游把空批当成功、队列不推进,调用方原地重下同一段直到批数耗尽。 + if out.is_empty() && cap > 0 && !blocks.is_empty() { + return Err(error::Error::BlockSource(CacheError(format!( + "缓存缺少起点区块 {start},不能从后面的块接着扫" + )))); + } + out }; // 锁在这里释放 - // 逐块打点。上游 `scan_cached_blocks` 是黑盒,而它唯一会回调进来的地方 - // 就是这里 —— 于是「卡在第几块的扫描里」和「所有块都扫完了、卡在之后的 - // 写库/承诺树里」可以被分开。只在排查构建里编进来。 + // 逐块打点:把「卡在第几块的扫描里」和「所有块都扫完了、卡在之后的 + // 写库/承诺树里」分开。只在排查构建里编进来。 #[cfg(feature = "debug-tracing")] let total = selected.len(); // The index is consumed only by the debug-tracing build. @@ -121,62 +167,6 @@ impl BlockSource for MemoryBlockCache { } } -#[async_trait::async_trait] -impl BlockCache for MemoryBlockCache { - fn get_tip_height( - &self, - range: Option<&ScanRange>, - ) -> Result, Self::Error> { - let blocks = self.blocks.lock().map_err(|_| poisoned())?; - let tip = match range { - None => blocks.keys().next_back().copied(), - Some(range) => { - let r = Self::range_of(range); - blocks.range(r).map(|(h, _)| *h).next_back() - } - }; - Ok(tip.map(BlockHeight::from_u32)) - } - - async fn read(&self, range: &ScanRange) -> Result, Self::Error> { - let blocks = self.blocks.lock().map_err(|_| poisoned())?; - let r = Self::range_of(range); - // 契约要求返回的区块必须连续且从 range.start 开始;允许短读。 - let mut out = Vec::new(); - let mut expect = r.start; - while expect < r.end { - match blocks.get(&expect) { - Some(b) => { - out.push(b.clone()); - expect += 1; - } - None => break, - } - } - Ok(out) - } - - async fn insert(&self, compact_blocks: Vec) -> Result<(), Self::Error> { - let mut blocks = self.blocks.lock().map_err(|_| poisoned())?; - for b in compact_blocks { - let h = u32::try_from(b.height) - .map_err(|_| CacheError(format!("区块高度超出范围: {}", b.height)))?; - blocks.insert(h, b); - } - Ok(()) - } - - async fn delete(&self, range: ScanRange) -> Result<(), Self::Error> { - let mut blocks = self.blocks.lock().map_err(|_| poisoned())?; - let r = Self::range_of(&range); - let doomed: Vec = blocks.range(r).map(|(h, _)| *h).collect(); - for h in doomed { - blocks.remove(&h); - } - Ok(()) - } -} - #[cfg(test)] mod tests { use super::*; @@ -196,64 +186,73 @@ mod tests { ) } + /// 收集 `with_blocks` 实际交出来的高度 —— 这是扫描唯一走的那条路。 + fn handed_out( + c: &MemoryBlockCache, + from: u32, + limit: usize, + ) -> Result, error::Error<(), CacheError>> { + let mut got = Vec::new(); + c.with_blocks::<_, ()>(Some(BlockHeight::from_u32(from)), Some(limit), |b| { + got.push(b.height); + Ok(()) + })?; + Ok(got) + } + #[test] - fn empty_cache_has_no_tip() { + fn empty_cache_hands_out_nothing() { let c = MemoryBlockCache::new(); assert!(c.is_empty()); - assert_eq!(c.get_tip_height(None).unwrap(), None); + assert_eq!(handed_out(&c, 10, 5).unwrap(), Vec::::new()); } #[test] - fn insert_then_read_contiguous() { + fn insert_then_hand_out_contiguous() { let c = MemoryBlockCache::new(); - futures::executor::block_on(c.insert(vec![block(10), block(11), block(12)])).unwrap(); + c.insert(vec![block(10), block(11), block(12)]).unwrap(); assert_eq!(c.len(), 3); - assert_eq!( - c.get_tip_height(None).unwrap(), - Some(BlockHeight::from_u32(12)) - ); - - let got = futures::executor::block_on(c.read(&range(10, 13))).unwrap(); - assert_eq!(got.len(), 3); - assert_eq!(got[0].height, 10); + assert_eq!(handed_out(&c, 10, 3).unwrap(), vec![10, 11, 12]); } - /// 契约要求:返回的区块必须连续且从 range.start 开始,允许短读。 - /// 缺口之后的区块不能被返回,否则调用方会把不连续的数据当成连续的。 #[test] - fn read_stops_at_gap() { + fn limit_is_respected() { let c = MemoryBlockCache::new(); - futures::executor::block_on(c.insert(vec![block(10), block(11), block(13)])).unwrap(); - let got = futures::executor::block_on(c.read(&range(10, 14))).unwrap(); - assert_eq!(got.len(), 2, "遇到高度 12 的缺口就该停"); - assert_eq!(got[1].height, 11); + c.insert(vec![block(10), block(11), block(12)]).unwrap(); + assert_eq!(handed_out(&c, 10, 2).unwrap(), vec![10, 11]); } + /// 缺口之后的区块不能被交出去,否则上游会把跳号判成链重组并触发破坏性回退。 #[test] - fn read_returns_empty_when_start_missing() { + fn hand_out_stops_at_gap() { let c = MemoryBlockCache::new(); - futures::executor::block_on(c.insert(vec![block(11)])).unwrap(); - let got = futures::executor::block_on(c.read(&range(10, 12))).unwrap(); - assert!(got.is_empty(), "起点缺失时不能从中间开始返回"); + c.insert(vec![block(10), block(11), block(13)]).unwrap(); + assert_eq!( + handed_out(&c, 10, 4).unwrap(), + vec![10, 11], + "高度 12 缺,就该停" + ); } + /// 起点缺失要**报错**,不能静默返回空 —— 静默空会被当成扫描成功, + /// 队列不推进,调用方原地重下同一段。 #[test] - fn delete_removes_only_the_range() { + fn missing_start_is_an_error_not_an_empty_batch() { let c = MemoryBlockCache::new(); - futures::executor::block_on(c.insert(vec![block(10), block(11), block(12)])).unwrap(); - futures::executor::block_on(c.delete(range(11, 12))).unwrap(); - assert_eq!(c.len(), 2); - assert_eq!( - c.get_tip_height(None).unwrap(), - Some(BlockHeight::from_u32(12)) + c.insert(vec![block(11), block(12)]).unwrap(); + let e = handed_out(&c, 10, 2).unwrap_err(); + assert!( + matches!(e, error::Error::BlockSource(CacheError(ref m)) if m.contains("10")), + "起点缺失应报 BlockSource 错误,实际 {e:?}" ); } #[test] - fn tip_within_range_is_bounded() { + fn delete_removes_only_the_range() { let c = MemoryBlockCache::new(); - futures::executor::block_on(c.insert(vec![block(10), block(20), block(30)])).unwrap(); - let tip = c.get_tip_height(Some(&range(10, 25))).unwrap(); - assert_eq!(tip, Some(BlockHeight::from_u32(20))); + c.insert(vec![block(10), block(11), block(12)]).unwrap(); + c.delete(&range(11, 12)).unwrap(); + assert_eq!(c.len(), 2); + assert_eq!(handed_out(&c, 12, 1).unwrap(), vec![12]); } } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs index bff70376f..0ddf84e02 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs @@ -332,6 +332,15 @@ mod tests { TransactionBuildError, BroadcastRejected, Unimplemented, + FundsNeedShielding, + CoinbaseFundsUnspendable, + ReorgDetected, + WalletBusy, + InvalidScanPriority, + InvalidTransparentUtxos, + BroadcastIntentNotFound, + BroadcastIntentNotReady, + FinalizeOutcomeUnknown, ]; let mut seen = std::collections::HashSet::new(); for c in all { diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs index 1343bf9aa..175a68866 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs @@ -31,10 +31,29 @@ thread_local! { // 之后所有操作都在错误的库上进行,而且看不出来:历史串库、余额串库、 // 甚至可能用 A 的 note 去发 B 的交易。 // - // 两道防线:BUSY 期间拒绝一切会切换钱包的操作;generation 保证异步返回时 - // 不会用一个过期的钱包覆盖新的。两者独立,任一失效另一个仍能兜住。 + // 防线主力是 BUSY:它在期间拒绝一切会切换钱包的操作。GENERATION 是它后面 + // 的兜底,但**当前不可达** —— 采样发生在置位 BUSY 之后,而 set_db/close 都 + // 被 BUSY 挡住,世代号在守卫存活期间不可能变。留着是为了将来出现「跨 await + // 却不持 BUSY」的路径时仍有第二道,不要据此认为现在有两道独立防线。 static BUSY: Cell = const { Cell::new(false) }; static GENERATION: Cell = const { Cell::new(0) }; + + // 客户端有自己的世代号。DB 的那道防线盖不住它:`setLightwalletdUrl` 换端点 + // 时**不**碰 DB,GENERATION 不动,于是一次在途的 `getChainTip` 结束后会把 + // 旧端点原样盖回去,之后所有同步都在跟上一个网络的 lightwalletd 说话。 + static CLIENT_GENERATION: Cell = const { Cell::new(0) }; +} + +/// 取走客户端前采样;放回前比对。不相等说明期间端点被换掉或关掉了,手上这个 +/// 已经作废 —— 丢弃它,而不是覆盖当前的。 +fn client_generation() -> u64 { + CLIENT_GENERATION.with(Cell::get) +} + +fn put_client_back(client: LightClient, sampled: u64) { + if client_generation() == sampled { + CLIENT.with(|c| *c.borrow_mut() = Some(client)); + } } /// 正在进行一次异步操作时,任何切换钱包的调用都必须被拒绝。 @@ -91,6 +110,10 @@ impl Drop for BusyGuard { } } +fn bump_client_generation() { + CLIENT_GENERATION.with(|g| g.set(g.get().wrapping_add(1))); +} + fn bump_generation() { GENERATION.with(|g| g.set(g.get().wrapping_add(1))); } @@ -122,10 +145,7 @@ pub fn with_read_conn(f: impl FnOnce(&rusqlite::Connection) -> Result) -> pub fn set_client(client: LightClient) { CLIENT.with(|c| *c.borrow_mut() = Some(client)); -} - -pub fn has_db() -> bool { - DB.with(|c| c.borrow().is_some()) + bump_client_generation(); } /// 借出数据库做一次同步操作。 @@ -151,6 +171,7 @@ where // 先拿锁再取 DB,两者之间没有 await,所以 generation 的采样点与取走 DB // 是同一时刻 —— 这正是「陈旧」判定成立的前提。 let guard = BusyGuard::acquire("walletOperation")?; + let client_gen = client_generation(); let db = DB.with(|c| c.borrow_mut().take()).ok_or_else(not_open)?; let client = match CLIENT.with(|c| c.borrow_mut().take()) { Some(c) => c, @@ -169,7 +190,7 @@ where } else { DB.with(|c| *c.borrow_mut() = Some(db)); } - CLIENT.with(|c| *c.borrow_mut() = Some(client)); + put_client_back(client, client_gen); out } @@ -183,11 +204,12 @@ where F: FnOnce(LightClient) -> Fut, Fut: std::future::Future)>, { + let client_gen = client_generation(); let client = CLIENT .with(|c| c.borrow_mut().take()) .ok_or_else(|| RuntimeError::new(ErrorCode::LightwalletdNotConfigured))?; let (client, result) = f(client).await; - CLIENT.with(|c| *c.borrow_mut() = Some(client)); + put_client_back(client, client_gen); result } @@ -206,5 +228,6 @@ pub fn close() -> Result<()> { CLIENT.with(|c| *c.borrow_mut() = None); DB_NAME.with(|c| *c.borrow_mut() = None); bump_generation(); + bump_client_generation(); Ok(()) } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs index 9b2c02f6d..3a33d6d5f 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs @@ -116,15 +116,18 @@ where fn explain_insufficient( db: &Db, account_id: ::AccountId, + confirmations: zcash_client_backend::data_api::wallet::ConfirmationsPolicy, err: RuntimeError, ) -> RuntimeError { - use zcash_client_backend::data_api::wallet::ConfirmationsPolicy; - if err.code != ErrorCode::InsufficientFunds { return err; } - let Ok(Some(summary)) = db.get_wallet_summary(ConfirmationsPolicy::default()) else { + // 必须用**这笔发送实际用的**确认数策略读余额,不能用 default()。 + // 这个函数存在的唯一目的就是给准确指引,而两套门槛下「透明池里有多少钱 + // 可用」的答案不一样 —— 用另一套读出来的数会把人指去屏蔽,结果还是不够。 + // 本文件 `allow_zero_conf_shielding` 的注释早写了这条:读和花必须同源。 + let Ok(Some(summary)) = db.get_wallet_summary(confirmations) else { return err; }; let Some(balances) = summary.account_balances().get(&account_id) else { @@ -445,6 +448,7 @@ fn build_proposal( return Err(explain_insufficient( db, account_id, + confirmations, propose_err("proposeTransfer", e), )) } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs index e91d06894..53d0673d3 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs @@ -23,9 +23,7 @@ use serde_json::json; use zcash_address::unified::{Container, Encoding, Fvk, Ufvk}; use zcash_client_backend::data_api::chain::error::Error as ChainError; -use zcash_client_backend::data_api::chain::{ - BlockCache, BlockSource, ChainState, CommitmentTreeRoot, -}; +use zcash_client_backend::data_api::chain::{BlockSource, ChainState, CommitmentTreeRoot}; use zcash_client_backend::data_api::ll::{LowLevelWalletRead, LowLevelWalletWrite}; use zcash_client_backend::data_api::scanning::{ScanPriority, ScanRange}; use zcash_client_backend::data_api::{ @@ -378,10 +376,7 @@ pub async fn step( blocks_scanned += batch_len as u64; - cache - .delete(batch) - .await - .map_err(|e| db_err("cacheDelete", e))?; + cache.delete(&batch).map_err(|e| db_err("cacheDelete", e))?; batches_done += 1; } @@ -805,10 +800,7 @@ async fn download_batch( if got == 0 { return Err(net_err("getBlockRange", "empty stream for non-empty range")); } - cache - .insert(blocks) - .await - .map_err(|e| db_err("cacheInsert", e))?; + cache.insert(blocks).map_err(|e| db_err("cacheInsert", e))?; Ok(got) } diff --git a/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/error.rs b/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/error.rs index bcb0a2836..40d4eaa52 100644 --- a/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/error.rs +++ b/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/error.rs @@ -87,7 +87,8 @@ impl From for JsValue { let _ = js_sys::Reflect::set( object, &JsValue::from_str("params"), - &JsValue::from_str(&error.params.to_string()), + &js_sys::JSON::parse(&error.params.to_string()) + .unwrap_or_else(|_| js_sys::Object::new().into()), ); if let Some(detail) = error.detail { let _ = js_sys::Reflect::set( From 1aa7e105e3f881edd7f1b93e556b835f9099cf9e Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Fri, 2 Oct 2026 02:15:55 +0900 Subject: [PATCH 11/97] feat: add monero runtime and harden zcash send handling --- chain-runtimes/monero/.cargo/config.toml | 8 + chain-runtimes/monero/.gitignore | 13 + chain-runtimes/monero/CONTEXT.md | 95 + chain-runtimes/monero/Cargo.lock | 2421 +++++++++++++++++ chain-runtimes/monero/Cargo.toml | 56 + chain-runtimes/monero/README.md | 79 + .../monero/crates/monero-runtime/Cargo.toml | 54 + .../monero/crates/monero-runtime/build.rs | 71 + .../crates/monero-runtime/src/bindgen.rs | 487 ++++ .../crates/monero-runtime/src/blocks_bin.rs | 655 +++++ .../monero/crates/monero-runtime/src/error.rs | 235 ++ .../monero/crates/monero-runtime/src/keys.rs | 350 +++ .../monero/crates/monero-runtime/src/lib.rs | 45 + .../crates/monero-runtime/src/network.rs | 495 ++++ .../monero/crates/monero-runtime/src/perf.rs | 20 + .../monero/crates/monero-runtime/src/pool.rs | 232 ++ .../monero/crates/monero-runtime/src/query.rs | 558 ++++ .../crates/monero-runtime/src/runtime.rs | 285 ++ .../monero/crates/monero-runtime/src/scan.rs | 1113 ++++++++ .../crates/monero-runtime/src/schema.rs | 448 +++ .../monero/crates/monero-runtime/src/spend.rs | 1506 ++++++++++ .../crates/monero-runtime/src/storage.rs | 272 ++ .../monero/crates/monero-runtime/src/sync.rs | 639 +++++ .../crates/monero-runtime/src/wallet.rs | 518 ++++ .../tests/fixtures/get_blocks_bin_3768621.bin | Bin 0 -> 69547 bytes .../crates/monero-runtime/tests/live_node.rs | 243 ++ .../docs/hardware-and-offline-signing.md | 133 + chain-runtimes/monero/rust-toolchain.toml | 19 + .../monero/scripts/build-node-pkg.sh | 8 + chain-runtimes/monero/scripts/build-wasm.sh | 41 + chain-runtimes/monero/scripts/measure-scan.js | 33 + chain-runtimes/monero/scripts/smoke.js | 133 + chain-runtimes/zcash/CONTEXT.md | 12 +- chain-runtimes/zcash/README.md | 42 +- .../crates/zcash-keys-runtime/Cargo.toml | 2 +- .../zcash-keys-runtime/TRANSPARENT_TX_API.md | 8 +- .../crates/zcash-keys-runtime/src/keys.rs | 2 +- .../src/transparent_send.rs | 26 + .../src/transparent_send/shielding.rs | 38 +- .../zcash/crates/zcash-runtime/Cargo.toml | 2 +- .../zcash/crates/zcash-runtime/src/bindgen.rs | 136 +- .../zcash/crates/zcash-runtime/src/error.rs | 28 +- .../zcash/crates/zcash-runtime/src/history.rs | 112 +- .../zcash/crates/zcash-runtime/src/network.rs | 61 +- .../zcash/crates/zcash-runtime/src/perf.rs | 6 +- .../zcash/crates/zcash-runtime/src/runtime.rs | 17 +- .../zcash/crates/zcash-runtime/src/send.rs | 563 ++-- .../zcash/crates/zcash-runtime/src/sync.rs | 968 +------ .../crates/zcash-runtime/src/tx_state.rs | 79 +- chain-runtimes/zcash/scripts/build-wasm.sh | 7 + 50 files changed, 12034 insertions(+), 1340 deletions(-) create mode 100644 chain-runtimes/monero/.cargo/config.toml create mode 100644 chain-runtimes/monero/.gitignore create mode 100644 chain-runtimes/monero/CONTEXT.md create mode 100644 chain-runtimes/monero/Cargo.lock create mode 100644 chain-runtimes/monero/Cargo.toml create mode 100644 chain-runtimes/monero/README.md create mode 100644 chain-runtimes/monero/crates/monero-runtime/Cargo.toml create mode 100644 chain-runtimes/monero/crates/monero-runtime/build.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/error.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/keys.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/lib.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/network.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/perf.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/pool.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/query.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/runtime.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/scan.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/schema.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/spend.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/storage.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/sync.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/wallet.rs create mode 100644 chain-runtimes/monero/crates/monero-runtime/tests/fixtures/get_blocks_bin_3768621.bin create mode 100644 chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs create mode 100644 chain-runtimes/monero/docs/hardware-and-offline-signing.md create mode 100644 chain-runtimes/monero/rust-toolchain.toml create mode 100755 chain-runtimes/monero/scripts/build-node-pkg.sh create mode 100755 chain-runtimes/monero/scripts/build-wasm.sh create mode 100755 chain-runtimes/monero/scripts/measure-scan.js create mode 100755 chain-runtimes/monero/scripts/smoke.js diff --git a/chain-runtimes/monero/.cargo/config.toml b/chain-runtimes/monero/.cargo/config.toml new file mode 100644 index 000000000..4e7902890 --- /dev/null +++ b/chain-runtimes/monero/.cargo/config.toml @@ -0,0 +1,8 @@ +# macOS 上 /usr/bin/ar 读不懂 wasm 目标文件:38 个编译好的 .o 会被**静默**打成 +# 一个 96 字节的空归档,链接期表现为一串 `undefined symbol: sqlite3_*`, +# 而编译阶段不报任何错。 +# +# 排查提示:本机 clang 是能编 wasm32 的(别往编译器上查),坏的是归档器。 +# cc crate 读 AR_ 形式的环境变量。 +[env] +AR_wasm32_unknown_unknown = "/opt/homebrew/opt/llvm/bin/llvm-ar" diff --git a/chain-runtimes/monero/.gitignore b/chain-runtimes/monero/.gitignore new file mode 100644 index 000000000..ce993d8a1 --- /dev/null +++ b/chain-runtimes/monero/.gitignore @@ -0,0 +1,13 @@ +/target +/pkg +/pkg-keys +/zcash-wasm-manifest.json +/vendor +*.log +__pycache__/ + +# Keep local wallet fixtures out of source control. +/.secrets/ + +/dist +/pkg-node diff --git a/chain-runtimes/monero/CONTEXT.md b/chain-runtimes/monero/CONTEXT.md new file mode 100644 index 000000000..869dd5dc0 --- /dev/null +++ b/chain-runtimes/monero/CONTEXT.md @@ -0,0 +1,95 @@ +# 交接上下文 + +写给接手的人(可能没有这个仓库的历史)。**这里只记不能从代码本身读出来的东西。** + +## 现在到哪了 + +Runtime 层扫链闭环 + 花费闭环已通,65 个测试,原生与 wasm32 两个目标零警告, +产物 3.92 MB / gzip 1.22 MB。 + +**没做的(按优先级):** + +1. **TS / app 层整个没动** —— `sdkMonero`、`Vault`、`Keyring`、四端载体接线。 + Zcash 那边这部分约 6,000 行。这是最大的一块缺口。 +2. **硬件签名** —— `OutputWithDecoys` 可序列化,天然支持「准备 / 签名」两阶段, + 但固件协议与 SDK 方法都还没有。 +3. **对真实节点的集成测试** —— 现在全是单元测试。扫描循环的三道校验、 + RingCT 索引推算,都只在构造的数据上验证过,没跑过主网。 +4. **内存池 / 未确认交易** —— `transactions.height` 允许 NULL 就是给它留的位, + 但没有拉取内存池的路径。 +5. **广播重试状态机** —— 广播后立刻记账,但没有「待广播 / 已拒绝」的生命周期 + 管理(Zcash 那边是 `tx_state.rs`)。 + +## 三件必须知道、代码里看不出来的事 + +**一、扫描进度为什么在 `identities` 而不是从 `blocks` 推。** + +`blocks` 表是全局的(块哈希是客观事实,各身份共享)。我一开始拿它的 +`max(height)` 当进度,结果是:一个追到链尖的身份会把另一个还在回补的身份的 +进度一起推到链尖,那段历史被永久跳过。已修,并有回归测试 +`two_identities_keep_independent_progress` 钉住。**别再改回去。** + +**二、为什么 `runtime.rs` 没有 wasm-only 门。** + +Zcash 那边它是 `#[cfg(target_arch = "wasm32")]`,导致 `runtime.rs` 加两个 +`bindgen.rs` 共 1,377 行在原生 `cargo test` 里**根本不编译** —— 那是真实的覆盖 +漏洞,我们 review 时才发现。这里刻意不加那个门,所以并发防线(BUSY 守卫、 +世代号)是可测的,`runtime.rs` 里那 6 个测试就是。 + +**三、`cargo check` 不链接。** + +给 wasm 目标做验证时只跑 check 会漏掉链接期的问题。本工程踩过一次: +macOS 的 `/usr/bin/ar` 读不懂 wasm 目标文件,把 38 个编译好的 `.o` **静默** +打成 96 字节的空归档,编译阶段零报错,只有 `cargo build` 才暴露。归archiver +已由 `.cargo/config.toml` 固定成 llvm-ar。 + +## 协议性的硬限制,不是实现问题 + +**观察钱包检测不到花费。** 需要 key image,而 key image 需要花费私钥。宿主必须 +在解锁时调 `importKeyImages`,否则余额偏高。`balance` 返回的 +`unverifiableAtomic` 就是这部分,宿主应当据此提示用户。而且补齐只影响**之后** +扫的块 —— 补齐之前发生的花费要回退重扫才认得出来。 + +**节点声称的 RingCT 输出索引不可验证。** 上游文档明确要求客户端自己维护并比对。 +`scan.rs` 实现了独立推算(按本块 v2 交易的输出总数推进游标),不一致报 +`RINGCT_INDEX_MISMATCH`。索引错了的后果是构环取错输出、交易被全网拒绝。 + +**时间戳形式的时间锁判不了。** 只有链高判得了块高形式的锁。时间戳形式的一律 +按「仍锁定」处理 —— 让用户等,好过让他构一笔必然被拒的交易。 + +## 刻意写死、不问节点的三个值 + +都写死是因为「节点说错了」的后果比「我们发版晚了」严重: + +- **环大小 16**(`spend::RING_LEN`)—— 说小了隐私被削弱且可能被拒 +- **RctType = ClsagBulletproofPlus** —— 说错了交易被全网拒绝 +- **手续费率上限 1,000,000 piconero/weight**(`spend::MAX_FEE_PER_WEIGHT`) + —— 没上限的话恶意节点报天价费率能让用户把余额全付成手续费 + +硬分叉时这三个都要跟着改,由我们发版控制。 + +## 与 Zcash runtime 的重复 + +只有一处:`crates/monero-runtime/build.rs`(SQLite 的 wasm 链接胶水,与链无关, +实测只差 8 行注释)。现在抽不了 —— 两条链在各自未合并的分支上,没有共同祖先 +能放共享 crate。**两条都落 main 之后第一件事就是抽它**,改一边记得同步另一边。 + +`storage.rs`、`runtime.rs`、`error.rs` 的形状也高度相似但不完全相同, +等 Monero 这边稳定了再决定要不要一起抽 —— 从两个真实实现里抽, +比现在照着一个猜要靠谱。 + +## 集成测试在本机沙箱里跑不了 + +`tests/live_node.rs` 对真实节点的那几条,在我的构建沙箱里连不上 —— 已判明是 +**沙箱不放行编译出来的测试进程的网络**,不是代码问题:同环境下 `curl` 拿得到 +200,而一个五行的裸 `reqwest` 调用同样失败。 + +所以那几条**没有在真链上跑过**。你那边直接: + +```bash +XMR_NODE=http://node.monerodevs.org:18089 \ + cargo test --test live_node -- --nocapture +``` + +它会打印链尖、扫描速度(块/秒)和余额三档。**扫描速度就是决定整条路线成立 +与否的那个数字** —— 单线程扫 Monero 在手机上能不能忍,到今天为止仍然没有答案。 diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock new file mode 100644 index 000000000..f8ff09bcd --- /dev/null +++ b/chain-runtimes/monero/Cargo.lock @@ -0,0 +1,2421 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "accessory" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc86a613208ca7d144ca24f6ec49c5cdfa5c05a46f2f7ab5880ff99371f165de" +dependencies = [ + "macroific 3.1.0", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "subtle", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "delegate-display" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54e3a499943fd5180aeffcb708164ffb22125ceeccb05491b5297981d37d6249" +dependencies = [ + "impartial-ord", + "itoa", + "macroific 3.1.0", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", + "unicode-xid", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "encoding_rs" +version = "0.8.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5ef0006ac9ab233c38522f5ae99cae3625151de8f706cacee1cba4b8e2832a" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fancy_constructor" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a8211ab12c36b63c269e17873331dc1da196a3edb7a5c79015677ef972da34a" +dependencies = [ + "macroific 3.1.0", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "gloo-timers" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core", + "subtle", +] + +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hex-literal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "impartial-ord" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc680e03d1a08bdc1c01b60e0c39723430ced63d8cabd93cee0449b6ba916a25" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "indexed_db_futures" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69ff41758cbd104e91033bb53bc449bec7eea65652960c81eddf3fc146ecea19" +dependencies = [ + "accessory", + "cfg-if", + "delegate-display", + "derive_more", + "fancy_constructor", + "indexed_db_futures_macros_internal", + "js-sys", + "sealed 0.6.0", + "smallvec", + "thiserror", + "tokio", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "indexed_db_futures_macros_internal" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caeba94923b68f254abef921cea7e7698bf4675fdd89d7c58bf1ed885b49a27d" +dependencies = [ + "macroific 2.0.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "keccak" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653" +dependencies = [ + "cpufeatures", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libsqlite3-sys" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f" +dependencies = [ + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "macroific" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89f276537b4b8f981bf1c13d79470980f71134b7bdcc5e6e911e910e556b0285" +dependencies = [ + "macroific_attr_parse 2.0.0", + "macroific_core 2.0.0", + "macroific_macro 2.0.0", +] + +[[package]] +name = "macroific" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc8ab95c98294764c0f1eacebdb5b027849201b71fbc383871fe991a1de7eb83" +dependencies = [ + "macroific_attr_parse 3.1.0", + "macroific_core 3.1.0", + "macroific_macro 3.1.0", +] + +[[package]] +name = "macroific_attr_parse" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad4023761b45fcd36abed8fb7ae6a80456b0a38102d55e89a57d9a594a236be9" +dependencies = [ + "proc-macro2", + "quote", + "sealed 0.6.0", + "syn 2.0.119", +] + +[[package]] +name = "macroific_attr_parse" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf9b7bdb92825e6a507392b12f0570ade17480be20f4ca951b9071b40deba1d1" +dependencies = [ + "proc-macro2", + "quote", + "sealed 0.7.0", + "syn 3.0.6", +] + +[[package]] +name = "macroific_core" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a7594d3c14916fa55bef7e9d18c5daa9ed410dd37504251e4b75bbdeec33e3" +dependencies = [ + "proc-macro2", + "quote", + "sealed 0.6.0", + "syn 2.0.119", +] + +[[package]] +name = "macroific_core" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edc880da2bc00d6d87f748805e242d670e248d1b9b6fcef3190503210b6cf056" +dependencies = [ + "proc-macro2", + "quote", + "sealed 0.7.0", + "syn 3.0.6", +] + +[[package]] +name = "macroific_macro" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4da6f2ed796261b0a74e2b52b42c693bb6dee1effba3a482c49592659f824b3b" +dependencies = [ + "macroific_attr_parse 2.0.0", + "macroific_core 2.0.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "macroific_macro" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "201faf668c264432727fb64e44407bcfcf1f5f8153bf4ec248eb6bbe4a39b144" +dependencies = [ + "macroific_attr_parse 3.1.0", + "macroific_core 3.1.0", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "monero-address" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d72b374be60cfd3b98a521ae15c93843dee3c6953eb7252098649d39032e8f79" +dependencies = [ + "monero-base58", + "monero-ed25519", + "monero-io", + "monero-primitives", + "thiserror", + "zeroize", +] + +[[package]] +name = "monero-base58" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23c140740c6411e3e92ce74215daaaffaa55bb913213a480ddef5f15c9bb26d0" +dependencies = [ + "monero-primitives", + "std-shims", +] + +[[package]] +name = "monero-borromean" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9539fd42ef36268e0961bab571d2e8ac5238bba309ae07c3504cf17e60d8b34" +dependencies = [ + "curve25519-dalek", + "monero-ed25519", + "monero-io", + "std-shims", + "zeroize", +] + +[[package]] +name = "monero-bulletproofs" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e6abdca137c989244ad45fb7ee01f45f7d82d054bd1839ea11a5d2826a350d3" +dependencies = [ + "curve25519-dalek", + "monero-bulletproofs-generators", + "monero-ed25519", + "monero-io", + "monero-primitives", + "rand_core", + "std-shims", + "thiserror", + "zeroize", +] + +[[package]] +name = "monero-bulletproofs-generators" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb66ae7110ee718e10d932ef844b1ab4ca839263e9592f11bd338f562cee0c71" +dependencies = [ + "curve25519-dalek", + "monero-ed25519", + "monero-io", + "monero-primitives", + "std-shims", +] + +[[package]] +name = "monero-clsag" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0d6a6518cf95bd14563223726e24efffb3199b024b4fa1a3db73287d66e57c4" +dependencies = [ + "curve25519-dalek", + "group", + "monero-ed25519", + "monero-io", + "rand_chacha", + "rand_core", + "std-shims", + "subtle", + "thiserror", + "zeroize", +] + +[[package]] +name = "monero-daemon-rpc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18939785564c3af3bb6a0fc8441f377be008379137aaed7f8479d661c419ca77" +dependencies = [ + "hex", + "monero-address", + "monero-epee", + "monero-interface", + "monero-oxide", + "serde", + "serde_json", + "std-shims", +] + +[[package]] +name = "monero-ed25519" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e03a310abc9a9ffa4984a27297dede91d6282260424216a64c734250617ebd90" +dependencies = [ + "crypto-bigint", + "curve25519-dalek", + "monero-io", + "rand_core", + "sha3", + "std-shims", + "subtle", + "zeroize", +] + +[[package]] +name = "monero-epee" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09336a22dbc9c5f34106c5499c944a81e35f2c03e007263a69084bfc7c47d691" + +[[package]] +name = "monero-interface" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b126530c30a9d7c6a21e35899d569151a645768f0b15dee3f8190bd6edeba55" +dependencies = [ + "hex", + "monero-oxide", + "std-shims", + "thiserror", + "zeroize", +] + +[[package]] +name = "monero-io" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9f1a95e908282938246cd0206ee37dcbb8b8317b38c32f6760f7483eff8adb" +dependencies = [ + "std-shims", +] + +[[package]] +name = "monero-mlsag" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ecbad27f38a5ca17bbb4ce9661107dc93e73a2088457fe1411fdffea1279527" +dependencies = [ + "curve25519-dalek", + "monero-ed25519", + "monero-io", + "std-shims", + "thiserror", + "zeroize", +] + +[[package]] +name = "monero-oxide" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34ea5d3fd87ca6106220a281213ae2f8c9dd0e29e6363b888de68b3b29e193d0" +dependencies = [ + "curve25519-dalek", + "hex-literal", + "monero-borromean", + "monero-bulletproofs", + "monero-clsag", + "monero-ed25519", + "monero-io", + "monero-mlsag", + "monero-primitives", + "std-shims", + "zeroize", +] + +[[package]] +name = "monero-primitives" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "721e7f3a20b3330a14b4dded49c20b7e6614e782112256e7970d20be2368d963" +dependencies = [ + "sha3", +] + +[[package]] +name = "monero-wallet" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8d9a2431255db4deaf39671646e17f79bfb4ceadfffc9bb52e0f3fb0d29c75e" +dependencies = [ + "curve25519-dalek", + "hex", + "monero-address", + "monero-clsag", + "monero-interface", + "monero-oxide", + "rand", + "rand_chacha", + "rand_core", + "rand_distr", + "std-shims", + "subtle", + "thiserror", + "zeroize", +] + +[[package]] +name = "multiversion" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ca4bea16ffc3f443cf7d866912118196bfef4c6a1556ca00f9f9b00bb43f7c" +dependencies = [ + "multiversion-macros", +] + +[[package]] +name = "multiversion-macros" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d416831a7317ef4b08bee00b69cbbb9c8763da7959a7026244d6266869f9c83" +dependencies = [ + "proc-macro2", + "quote", + "rustversion", + "syn 3.0.6", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "onekey-monero-runtime" +version = "0.0.1-spike.0" +dependencies = [ + "curve25519-dalek", + "futures-lite", + "futures-util", + "getrandom 0.2.17", + "gloo-timers", + "hex", + "js-sys", + "monero-address", + "monero-daemon-rpc", + "monero-epee", + "monero-interface", + "monero-wallet", + "rand_core", + "reqwest", + "rusqlite", + "serde", + "serde_json", + "sqlite-wasm-rs", + "sqlite-wasm-vfs", + "thiserror", + "tokio", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "zeroize", +] + +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_distr" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" +dependencies = [ + "num-traits", + "rand", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "encoding_rs", + "futures-core", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "mime", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsqlite-vfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown 0.16.1", + "thiserror", +] + +[[package]] +name = "rusqlite" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sealed" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22f968c5ea23d555e670b449c1c5e7b2fc399fdaec1d304a17cd48e288abc107" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "sealed" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b68e2ea526d9fb32f23ca8894fb5da9e743f34c2f41701f0501dc8a25c4b343" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha3" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874" +dependencies = [ + "digest", + "keccak", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" + +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + +[[package]] +name = "sqlite-wasm-vfs" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f7a5c9ac229421d577bb5a9bb59048838509958b218dd4e0b3c1214a87c361e" +dependencies = [ + "indexed_db_futures", + "js-sys", + "rsqlite-vfs", + "thiserror", + "tokio", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "std-shims" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "227c4f8561598188d0df96dbe749824576174bba278b5b6bb2eacff1066067d0" +dependencies = [ + "hashbrown 0.16.1", + "rustversion", + "spin", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml new file mode 100644 index 000000000..bc328d989 --- /dev/null +++ b/chain-runtimes/monero/Cargo.toml @@ -0,0 +1,56 @@ +[workspace] +resolver = "2" +members = ["crates/monero-runtime"] + +[workspace.package] +version = "0.0.1-spike.0" +edition = "2021" +license = "Apache-2.0" +rust-version = "1.85" + +# ── monero-oxide:独立 Rust 实现,MIT,no_std ──────────────────────────── +# +# 选它而不是 wallet2 的理由见 development/research。要点:四端统一 wasm、 +# 产物约 226 KB、不需要跨源隔离、不需要 C++ 交叉编译链。 +# +# 代价是它**不提供任何存储层**:`Scanner` 是纯函数(register_subaddress + +# scan(block) -> outputs),钱包状态全部由我们自己落 SQLite。这个工作区存在 +# 的意义就是那一层。 +[workspace.dependencies] +monero-wallet = { version = "0.2", default-features = false, features = ["std"] } +monero-address = { version = "0.1", default-features = false, features = ["std"] } +monero-daemon-rpc = { version = "0.2", default-features = false, features = ["std"] } +monero-interface = { version = "0.2", default-features = false, features = ["std"] } +# get_blocks.bin 的请求与解析(blocks_bin.rs)。与 monero-daemon-rpc 用同一个。 +monero-epee = { version = "0.2", default-features = false } + +# SQLite on wasm:与 Zcash runtime 同一套组合。rusqlite 不开 "bundled" +# (那会在构建期编译 SQLite 的 C 源码,而 wasm32 没有 libc sysroot), +# 改由 sqlite-wasm-rs 提供 sqlite3 符号。 +rusqlite = { version = "0.37", default-features = false } +sqlite-wasm-rs = "0.5" +# OPFS 同步访问 VFS。Zcash runtime 那边 vendor 了一份带落盘屏障补丁的, +# 这里先用发布版;等两条链都落 main,VFS 与 build.rs 一起抽成共享件。 +sqlite-wasm-vfs = "0.2" + +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +hex = "0.4" +rand_core = { version = "0.6", features = ["getrandom"] } +# 必须与 monero-oxide 用的同一大版本,否则 Scalar/Point 类型对不上。 +curve25519-dalek = { version = "4", default-features = false } +zeroize = { version = "1", features = ["zeroize_derive"] } + +wasm-bindgen = "0.2" +gloo-timers = { version = "0.3", features = ["futures"] } +js-sys = "0.3" +wasm-bindgen-futures = "0.4" +web-sys = { version = "0.3", features = ["Request", "RequestInit", "Response", "Headers"] } +# 原生侧只用于本机诊断与集成测试,不进出厂产物 —— 用默认 feature 就好。 +# 关掉默认 feature 会让连接在传输层直接失败(实测:curl 通、它不通)。 +reqwest = "0.12" +futures-lite = "2" +futures-util = { version = "0.3", default-features = false, features = ["alloc"] } +# 原生传输走 reqwest,它要 Tokio reactor;集成测试因此需要一个运行时。 +tokio = { version = "1", features = ["rt", "macros", "time"] } diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md new file mode 100644 index 000000000..0f6cb548e --- /dev/null +++ b/chain-runtimes/monero/README.md @@ -0,0 +1,79 @@ +# OneKey Monero Runtime + +monero-oxide 之上的钱包状态层。**它提供密码学、扫描器与交易构造;存储这一层 +是我们自己写的,因为上游不提供。** + +## 为什么是这条路 + +三条路都量过(数据见 `development/research`): + +| | 我们要写 | 出厂体积 | 插件端 | 落盘 | +|---|---|---|---|---| +| monero-ts(wallet2 编 wasm) | 最少 | 6.2 MB JS | 可以 | ✗ 整块序列化 | +| wallet2 + monero_c | 1.5–2.5k 行 | — | **不行**(零 wasm 支持) | ✓ | +| **monero-oxide + SQLite** | 6–8.5k 行 | **3.37 MB / gzip 1.06 MB** | 可以 | **✓ 增量写** | + +决定性的是最后一列。monero-ts 把整个钱包放在 wasm 内存里,持久化只能 +`getData()` 整块序列化再写出去 —— 历史越长每次保存越贵,写一半崩了丢全部。 +这里是增量写 + 事务,和 Zcash runtime 同一个模型。 + +代价写在明面上:多出来的六到八千行**正确性归我们自己**,上游不兜底。 + +## 结构 + +``` +error.rs 错误码契约(跨 wasm 边界稳定) +storage.rs SQLite 连接、OPFS VFS、落盘屏障 +schema.rs 表结构与迁移 +keys.rs 观察密钥对、地址、子地址派生 +wallet.rs 库句柄、身份管理、子地址注册表 +scan.rs 扫描循环 + 三道校验 + 落库 +sync.rs 有界推进编排(拉块 → 扫描 → 记进度) +query.rs 余额、历史、可花输出 +spend.rs key image 导入、选币、预留、构造、签名、广播 +network.rs monerod 传输(浏览器 fetch / 原生 reqwest) +runtime.rs 跨调用会话状态与并发防线 +bindgen.rs wasm 边界 +``` + +## 三件必须知道的事 + +**一、观察钱包检测不到花费。** Monero 的花费检测需要 key image,而 key image +需要花费私钥。这是协议性质不是实现取舍。所以宿主必须在解锁时调一次 +`importKeyImages`,否则余额会**偏高**(已花的看起来还在)。余额查询里的 +`unverifiableAtomic` 就是这部分的金额,宿主应当据此提示用户。 + +**二、节点声称的 RingCT 输出索引不可验证。** 上游文档明确要求客户端自己维护 +这个索引并比对,不一致应当断开。`scan.rs` 实现了这个独立推算,不一致时报 +`RINGCT_INDEX_MISMATCH`。索引错了的后果是构环时取错输出、交易被网络拒绝, +而且很难从现象反推。 + +**三、调度归宿主。** `syncStep` 一次最多扫 `maxBlocks` 个块就返回,**永远不会 +自己循环到同步完成**。什么时候扫、扫多少、失败怎么退避全由宿主 TS 决定。 + +## 构建 + +```bash +./scripts/build-wasm.sh # release 到 pkg/ +cargo test --workspace # 原生测试 +cargo check --workspace --target wasm32-unknown-unknown +``` + +**macOS 上必须有 llvm-ar**(`brew install llvm`)。系统自带的 `/usr/bin/ar` +读不懂 wasm 目标文件,会把编译好的 `.o` **静默**打成一个 96 字节的空归档, +链接期报一串 `undefined symbol: sqlite3_*`,而编译阶段不报任何错。归档器由 +`.cargo/config.toml` 指定。 + +排查提示:本机 clang 是能编 wasm32 的,别往编译器上查。 +另外 `cargo check` **不链接**,这个坑在 check 下完全看不见。 + +## 与 Zcash runtime 的关系 + +两条链各自独立的工作区,没有代码依赖。目前唯一的重复是 +`crates/monero-runtime/build.rs`(SQLite 的 wasm 链接胶水,与链无关,实测只差 +8 行注释)—— 抽不了,因为两条链还在各自未合并的分支上,没有共同祖先能放共享 +crate。**两条都落 main 之后第一件事就是抽它。** + +一个刻意的差异:`runtime.rs` 在这里**不加 wasm-only 门**。Zcash 那边它是 +`#[cfg(target_arch = "wasm32")]`,导致 1,377 行在原生 `cargo test` 里根本不编译 +——那是真实的覆盖漏洞,这里的并发防线因此是可测的。 diff --git a/chain-runtimes/monero/crates/monero-runtime/Cargo.toml b/chain-runtimes/monero/crates/monero-runtime/Cargo.toml new file mode 100644 index 000000000..60f3ff553 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/Cargo.toml @@ -0,0 +1,54 @@ +[package] +name = "onekey-monero-runtime" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +description = "OneKey Monero Runtime — monero-oxide 之上的钱包状态层(SQLite 落盘)" + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +monero-wallet.workspace = true +monero-address.workspace = true +monero-daemon-rpc.workspace = true +monero-interface.workspace = true +monero-epee.workspace = true +# Bounded concurrent block fetches (sync::fetch_scannable_blocks). +futures-util.workspace = true +rusqlite.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +hex.workspace = true +rand_core.workspace = true +curve25519-dalek.workspace = true +zeroize.workspace = true + +# wasm32 专属:SQLite 的 wasm 实现与 JS 互操作。原生目标(本机调试与测试) +# 用系统 SQLite,不需要这些。 +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# 原生传输:让浏览器里出的问题能在本机上真调试器复现。 +reqwest.workspace = true +# 原生侧的重试退避(blocks_bin::backoff)。reqwest 本就跑在 Tokio 上。 +tokio.workspace = true + +[dev-dependencies] +# 集成测试要直接构造地址取公钥 +monero-wallet.workspace = true +futures-lite.workspace = true +tokio.workspace = true + +[target.'cfg(target_arch = "wasm32")'.dependencies] +sqlite-wasm-rs.workspace = true +sqlite-wasm-vfs.workspace = true +wasm-bindgen.workspace = true +gloo-timers.workspace = true +js-sys.workspace = true +wasm-bindgen-futures.workspace = true +web-sys.workspace = true +# monero-oxide 整条链走 rand_core 0.6 → getrandom 0.2,而 0.2 在 +# wasm32-unknown-unknown 上必须显式打开旧式的 "js" feature 才能编译。 +# 这条依赖我们代码里一次都不直接用,纯粹是为了把 feature 打开。 +getrandom_02 = { package = "getrandom", version = "0.2", features = ["js"] } diff --git a/chain-runtimes/monero/crates/monero-runtime/build.rs b/chain-runtimes/monero/crates/monero-runtime/build.rs new file mode 100644 index 000000000..9f9321fd5 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/build.rs @@ -0,0 +1,71 @@ +//! 把 wasm 版 SQLite 接到链接器上。 +//! +//! 背景:我们用 `rusqlite` 但不开 `bundled` feature —— 那会在构建期编译 SQLite +//! 的 C 源码,而 wasm32 没有 libc sysroot。关掉之后 libsqlite3-sys 转而发出 +//! `-l sqlite3`,让链接器去找现成的库。 +//! +//! **这份是 `chain-runtimes/zcash/crates/zcash-runtime/build.rs` 的副本**(实测 +//! 仅 8 行注释差异)。与链无关,本该抽成一个共享 crate —— 但两条链目前在各自 +//! 未合并的分支上,抽了没有共同祖先可放。**两条都落 main 之后第一件事就是抽它**, +//! 改这里记得同步改另一份。 +//! +//! 在 wasm32 上这份现成的库由 `sqlite-wasm-rs` 提供,但它产出的归档叫 +//! `libwsqlite3.a`(名字里有个 w)。本脚本把它按链接器要的名字复制一份到我们 +//! 自己的 OUT_DIR,并把该目录加进搜索路径。 +//! +//! 这样调用方不需要任何手工的 RUSTFLAGS —— `cargo build` 直接可用。 + +use std::path::{Path, PathBuf}; + +fn main() { + println!("cargo::rerun-if-changed=build.rs"); + + let target = std::env::var("TARGET").unwrap_or_default(); + if !target.starts_with("wasm32") { + // 原生目标用系统或 bundled 的 SQLite,无需干预。 + return; + } + + let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR 应由 cargo 提供")); + + let Some(src) = find_wasm_sqlite_archive(&out_dir) else { + // 不直接 panic:留一条可读的提示,让链接期的报错有据可查。 + println!( + "cargo::warning=未找到 sqlite-wasm-rs 的 libwsqlite3.a;\ + 若链接期报 `unable to find library -lsqlite3`,请确认 sqlite-wasm-rs \ + 在依赖图中且目标为 wasm32" + ); + return; + }; + + let dst = out_dir.join("libsqlite3.a"); + if let Err(e) = std::fs::copy(&src, &dst) { + println!("cargo::warning=复制 {} 失败: {e}", src.display()); + return; + } + + println!("cargo::rustc-link-search=native={}", out_dir.display()); + println!("cargo::rerun-if-changed={}", src.display()); +} + +/// 从我们的 OUT_DIR 往上找到 `.../build/` 目录,再在里面定位 +/// `sqlite-wasm-rs-*/out/libwsqlite3.a`。 +/// +/// 依赖的构建脚本先于依赖方运行,所以这个文件此刻必然已经存在。 +fn find_wasm_sqlite_archive(out_dir: &Path) -> Option { + // OUT_DIR 形如 target///build/-/out + let build_root = out_dir.parent()?.parent()?; + for entry in std::fs::read_dir(build_root).ok()? { + let Ok(entry) = entry else { continue }; + let name = entry.file_name(); + let name = name.to_string_lossy(); + if !name.starts_with("sqlite-wasm-rs-") { + continue; + } + let candidate = entry.path().join("out").join("libwsqlite3.a"); + if candidate.is_file() { + return Some(candidate); + } + } + None +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs new file mode 100644 index 000000000..79ccf4ee7 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs @@ -0,0 +1,487 @@ +//! 面向宿主的 wasm 接口。 +//! +//! ## 形状约定 +//! +//! - 返回值一律是 **JSON 字符串**,宿主 `JSON.parse` 即可。错误也是 JSON +//! (`{ code, params, detail }`),所以宿主不必区分 Error 与非 Error 两条路。 +//! - **金额一律用字符串**。piconero 的上限远超 JS 的 `Number.MAX_SAFE_INTEGER`, +//! 走数字会静默丢精度 —— 那是最坏的一类 bug,因为它不报错。 +//! - 密钥材料**只进不出**:种子与花费私钥可以传进来,绝不作为返回值出去。 +//! +//! ## 调度不在这里 +//! +//! 什么时候扫、扫多少、失败怎么退避 —— 全归宿主。这里每个导出都是一次 +//! 完整的往返,绝不自己循环。 + +use wasm_bindgen::prelude::*; + +use crate::error::{ErrorCode, Result, RuntimeError}; +use zeroize::Zeroizing; + +use crate::{keys, network, query, runtime, spend, storage, sync, wallet}; + +fn json(value: serde_json::Value) -> std::result::Result { + Ok(value.to_string()) +} + +/// 装上持久化存储。**必须在开任何库之前调用一次。** +#[wasm_bindgen(js_name = init)] +pub async fn init() -> std::result::Result<(), JsValue> { + storage::install_persistent_vfs().await?; + Ok(()) +} + +/// 本 runtime 锁定的上游版本,供宿主自检与日志使用。 +#[wasm_bindgen(js_name = dependencyVersions)] +pub fn dependency_versions() -> String { + crate::dependency_versions().to_string() +} + +/// 打开(或新建)一个钱包库。 +#[wasm_bindgen(js_name = openWallet)] +pub fn open_wallet(db_name: &str, network: &str) -> std::result::Result { + let net = keys::parse_network(network)?; + let db = wallet::Db::open(db_name, net)?; + runtime::set_db(db, db_name)?; + json(serde_json::json!({ "dbName": db_name, "network": network })) +} + +#[wasm_bindgen(js_name = closeWallet)] +pub fn close_wallet() -> std::result::Result<(), JsValue> { + runtime::close()?; + Ok(()) +} + +/// 配置节点地址,空串表示停用。**没有内置默认值** —— 内置一个等于替用户决定 +/// 把 IP 和查询交给谁,那是隐私决策,不该藏在 runtime 里。 +/// +/// 先断开旧节点再连新的:用户换掉或停用一个节点后,它不能再收到任何请求, +/// 哪怕新节点连不上 —— 那时就是没有节点。 +#[wasm_bindgen(js_name = setNodeUrl)] +pub async fn set_node_url(url: &str) -> std::result::Result<(), JsValue> { + runtime::clear_daemon(); + network::forget_node_url(); + if url.trim().is_empty() { + return Ok(()); + } + let daemon = network::connect(url).await?; + runtime::set_daemon(daemon); + Ok(()) +} + +/// 问链尖。**不要求钱包库已打开** —— 建账户时要用它定 birthday, +/// 而那一刻库还没建。 +#[wasm_bindgen(js_name = chainTip)] +pub async fn chain_tip() -> std::result::Result { + let tip: u64 = runtime::with_daemon(|daemon| async move { + let r = sync::chain_tip(&daemon).await; + (daemon, r) + }) + .await?; + json(serde_json::json!({ "height": tip })) +} + +/// 注册一个身份(观察密钥对)。 +/// +/// `spendPublicKeyHex` 与 `viewPrivateKeyHex` 都是 32 字节的十六进制。 +/// **花费私钥不在这里** —— 它只在签名时传入,见 `signAndBroadcast`。 +#[wasm_bindgen(js_name = addAccount)] +pub fn add_account( + uuid: &str, + spend_public_key_hex: &str, + view_private_key_hex: &str, + birthday_height: u64, +) -> std::result::Result { + let spend = decode_hex(spend_public_key_hex, "spendPublicKeyHex")?; + let view = Zeroizing::new(decode_hex(view_private_key_hex, "viewPrivateKeyHex")?); + let result = runtime::with_db(|db| { + let identity = db.add_identity(uuid, &spend, &view, birthday_height)?; + Ok(serde_json::json!({ + "accountId": identity.id, + "uuid": identity.uuid, + "primaryAddress": identity.primary_address, + "birthdayHeight": identity.birthday_height, + })) + })?; + json(result) +} + +#[wasm_bindgen(js_name = listAccounts)] +pub fn list_accounts() -> std::result::Result { + let rows = runtime::with_db_read(|db| db.list_identities())?; + let items: Vec<_> = rows + .into_iter() + .map(|(id, uuid, address)| { + serde_json::json!({ "accountId": id, "uuid": uuid, "primaryAddress": address }) + }) + .collect(); + json(serde_json::json!({ "items": items })) +} + +/// 删除一个身份连同它的全部数据。**不可逆。** +#[wasm_bindgen(js_name = removeAccount)] +pub fn remove_account(uuid: &str) -> std::result::Result { + let removed = runtime::with_db(|db| db.remove_identity(uuid))?; + json(serde_json::json!({ "removed": removed })) +} + +/// 删除整个钱包库文件(app 重置、存储重建)。**不可逆。** +/// +/// 不打开库:版本不认或已损坏的库也删得掉。删的是当前打开的库时先关掉它。 +#[wasm_bindgen(js_name = deleteWallet)] +pub async fn delete_wallet(db_name: String) -> std::result::Result { + if runtime::open_db_name().as_deref() == Some(db_name.as_str()) { + runtime::close()?; + } + let deleted = storage::delete_database(&db_name).await?; + json(serde_json::json!({ "deleted": deleted })) +} + +/// 登记一个子地址并返回它的地址串。**没登记的地址收到的钱扫不到。** +#[wasm_bindgen(js_name = registerSubaddress)] +pub fn register_subaddress( + account_id: i64, + major: u32, + minor: u32, + label: Option, +) -> std::result::Result { + let address = + runtime::with_db(|db| db.register_subaddress(account_id, major, minor, label.as_deref()))?; + json(serde_json::json!({ "address": address, "major": major, "minor": minor })) +} + +/// 把链尖告诉某个身份,据此排出待扫区间。 +#[wasm_bindgen(js_name = updateChainTip)] +pub fn update_chain_tip(account_id: i64, tip: u64) -> std::result::Result { + runtime::with_db(|db| sync::update_chain_tip(db, account_id, tip))?; + let progress = runtime::with_db_read(|db| sync::peek(db, account_id))?; + json(progress) +} + +/// 一次有界推进:最多扫 `maxBlocks` 个块然后带进度返回。 +/// +/// **本函数永远不会自己循环到同步完成。** 宿主拿到进度后自己决定是否再调。 +#[wasm_bindgen(js_name = syncStep)] +pub async fn sync_step(account_id: i64, max_blocks: u64) -> std::result::Result { + let progress = runtime::with_db_and_daemon(|mut db, daemon| async move { + let r = sync::step(&mut db, &daemon, account_id, max_blocks).await; + (db, daemon, r) + }) + .await?; + json(progress) +} + +/// 只读:当前扫描进度,不发网络请求。同步卡住时用它确认到底想扫哪一段。 +#[wasm_bindgen(js_name = syncPeek)] +pub fn sync_peek(account_id: i64) -> std::result::Result { + let v = runtime::with_db_read(|db| sync::peek(db, account_id))?; + json(v) +} + +/// 重组恢复:回退到指定高度并把那之上的区间重新排队。**破坏性。** +#[wasm_bindgen(js_name = rewindTo)] +pub fn rewind_to(account_id: i64, height: u64, tip: u64) -> std::result::Result { + let v = runtime::with_db(|db| sync::rewind_and_requeue(db, account_id, height, tip))?; + json(v) +} + +/// 余额。`chainTip` 传 `null` 表示还不知道链尖 —— 此时可用余额一律按 0 报, +/// 宁可显示 0,也不要让用户去花一笔构不进环的钱。 +#[wasm_bindgen(js_name = balance)] +pub fn balance(account_id: i64, chain_tip: Option) -> std::result::Result { + let b = runtime::with_db_read(|db| query::balance(db, account_id, chain_tip))?; + json(b.to_json()) +} + +#[wasm_bindgen(js_name = history)] +pub fn history(account_id: i64, limit: u32, offset: u32) -> std::result::Result { + let v = runtime::with_db_read(|db| query::history(db, account_id, limit, offset))?; + json(v) +} + +#[wasm_bindgen(js_name = transactionDetails)] +pub fn transaction_details( + account_id: i64, + txid_hex: &str, +) -> std::result::Result { + let v = runtime::with_db_read(|db| query::transaction_details(db, account_id, txid_hex))?; + json(v) +} + +/// 补齐 key image,让花费检测能工作。 +/// +/// **必须在解锁时尽早调用。** 补齐之前余额会偏高:已经被花掉的输出看起来还在, +/// 因为观察钱包在协议上无法独立判断花费。补齐只影响之后扫的块 —— 之前发生的 +/// 花费要靠回退重扫才能识别。 +#[wasm_bindgen(js_name = importKeyImages)] +pub fn import_key_images( + account_id: i64, + spend_private_key_hex: &str, +) -> std::result::Result { + let spend = Zeroizing::new(decode_hex(spend_private_key_hex, "spendPrivateKeyHex")?); + let result = runtime::with_db(|db| spend::import_key_images(db, account_id, &spend))?; + json(serde_json::json!({ + "imported": result.imported, + "spendsFound": result.spends_found, + })) +} + +/// 从 BIP-32 派生出来的私钥造出 Monero 的观察材料与主地址。 +/// +/// **不需要开库、不需要节点** —— 纯派生。这正是「地址可以先建、扫链之后再 +/// 手动打开」那条产品路径的基础。 +/// +/// 约定与 OneKey V4 一致(`spend = sc_reduce32(key)`、`view = keccak(spend)`)。 +/// 换约定会让老用户导入同一套助记词后看到空钱包。 +/// +/// **不返回花费私钥** —— 它就是调用方传进来的那个,没必要再跨一次边界。 +#[wasm_bindgen(js_name = deriveAccount)] +pub fn derive_account( + network: &str, + bip32_private_key_hex: &str, +) -> std::result::Result { + let net = keys::parse_network(network)?; + let raw = Zeroizing::new(decode_hex(bip32_private_key_hex, "bip32PrivateKeyHex")?); + let derived = keys::derive_from_bip32_key(net, &raw)?; + json(serde_json::json!({ + "primaryAddress": derived.primary_address, + "spendPublicKeyHex": hex::encode(derived.spend_public_key), + "viewPrivateKeyHex": hex::encode(derived.view_private_key), + })) +} + +/// 从 BIP-32 私钥算出签名用的花费标量。与 `deriveAccount` 同一个约简。 +#[wasm_bindgen(js_name = spendScalar)] +pub fn spend_scalar(bip32_private_key_hex: &str) -> std::result::Result { + let raw = Zeroizing::new(decode_hex(bip32_private_key_hex, "bip32PrivateKeyHex")?); + let scalar = Zeroizing::new(keys::spend_scalar_from_bip32_key(&raw)?); + Ok(hex::encode(*scalar)) +} + +/// 派生一个子地址。纯派生,不开库。 +#[wasm_bindgen(js_name = deriveSubaddress)] +pub fn derive_subaddress( + network: &str, + spend_public_key_hex: &str, + view_private_key_hex: &str, + major: u32, + minor: u32, +) -> std::result::Result { + let net = keys::parse_network(network)?; + let spend = decode_hex(spend_public_key_hex, "spendPublicKeyHex")?; + let view = Zeroizing::new(decode_hex(view_private_key_hex, "viewPrivateKeyHex")?); + let pair = keys::view_pair_from_bytes(&spend, &view)?; + let address = keys::subaddress(&pair, net, major, minor)?; + json(serde_json::json!({ "address": address, "major": major, "minor": minor })) +} + +/// 校验一个收款地址是否合法且属于该网络。 +#[wasm_bindgen(js_name = validateAddress)] +pub fn validate_address(network: &str, address: &str) -> std::result::Result { + let net = keys::parse_network(network)?; + Ok(keys::validate_address(net, address)) +} + +/// 宿主签好名后调用:之后的准备发送不会把这笔预留当成被放弃的。 +#[wasm_bindgen(js_name = markReservationSigned)] +pub fn mark_reservation_signed(reservation_id: &str) -> std::result::Result { + let n = runtime::with_db(|db| spend::mark_signed(db, reservation_id))?; + json(serde_json::json!({ "marked": n })) +} + +/// 释放一次预留(用户取消,或构造失败)。 +#[wasm_bindgen(js_name = releaseReservation)] +pub fn release_reservation(reservation_id: &str) -> std::result::Result { + let n = runtime::with_db(|db| spend::release(db, reservation_id))?; + json(serde_json::json!({ "released": n })) +} + +/// 把网络请求交给宿主去发,而不是在 wasm 里 `fetch`。 +/// +/// `handler` 形如 `(url, contentType, body: Uint8Array) => Promise`。 +/// 传 `undefined` 卸载。 +/// +/// wasm 里的 fetch 受浏览器的混合内容与 CORS 管,而 monerod 默认不发 CORS 头 +/// —— 2026-09-22 实测 12 家公共节点只有 1 家可用。把请求交回宿主,插件的 +/// background、桌面主进程、移动端原生都不受那两条规则管,于是全网节点可用。 +/// +/// 和性能无关:纯扫描只占总耗时 0.4%,受限的是可达性不是速度。 +#[wasm_bindgen(js_name = setRequestHandler)] +pub fn set_request_handler(handler: Option) { + crate::network::set_host_handler(handler); +} + +/// 诊断:库是否健在、各表行数、逻辑大小。**不发网络请求。** +#[wasm_bindgen(js_name = diagDatabase)] +pub fn diag_database() -> std::result::Result { + let v = runtime::with_db_read(|db| { + let mut counts = serde_json::Map::new(); + for table in [ + "identities", + "subaddresses", + "outputs", + "transactions", + "blocks", + "scan_ranges", + "locked_outputs", + "possible_spends", + ] { + let n: i64 = db + .conn() + .query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get(0)) + .map_err(|e| crate::error::db_err("diagCount", e))?; + counts.insert(table.to_owned(), serde_json::json!(n)); + } + // Logical size (pages x page size), as the Zcash runtime reports it. + // Works through any VFS; the backing store's physical footprint can + // differ (free pages, storage-layer overhead). + let pragma = |name: &str| -> Result { + db.conn() + .query_row(&format!("PRAGMA {name}"), [], |r| r.get(0)) + .map_err(|e| crate::error::db_err("diagPragma", e)) + }; + let page_size = pragma("page_size")?; + let page_count = pragma("page_count")?; + Ok(serde_json::json!({ + "dbName": runtime::open_db_name(), + "counts": counts, + "pageSize": page_size, + "pageCount": page_count, + "logicalBytes": page_size * page_count, + })) + })?; + json(v) +} + +fn decode_hex(value: &str, field: &str) -> Result> { + hex::decode(value).map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidKeyMaterial, + serde_json::json!({ "field": field, "reason": "notHex" }), + ) + }) +} + +// ── 花费路径 ──────────────────────────────────────────────────────────── + +/// 选币、构造、预留。**不需要花费私钥,不广播。** +/// +/// `recipientsJson` 形如 `[{ "address": "...", "amountAtomic": "1000000000000" }]`。 +/// +/// `maxSend` 为真时只接受一个收款方,金额由「当前可花总额 − 手续费」反算, +/// 传入的金额被忽略 —— 不能靠「不给找零」实现,那样余数会全部并进手续费。 +/// +/// 返回 `{ reservationId, signableHex, feeAtomic, amountAtomic, changeAtomic, +/// inputsAtomic, inputCount }`。`feeAtomic` 和 `amountAtomic` 是这笔交易真正 +/// 会用的数:确认页显示它们,签名时不会再变。 +/// +/// 失败不会留下预留。成功后必须走 `signTransaction` + `broadcastTransaction`, +/// 或者显式 `releaseReservation` —— 否则那些输出会一直锁着。 +#[wasm_bindgen(js_name = prepareTransaction)] +pub async fn prepare_transaction( + account_id: i64, + recipients_json: &str, + max_send: bool, + reservation_id: &str, + chain_tip: u64, + priority: &str, +) -> std::result::Result { + let recipients: Vec = serde_json::from_str(recipients_json).map_err(|e| { + JsValue::from( + RuntimeError::with( + ErrorCode::InvalidRequest, + serde_json::json!({ "field": "recipientsJson" }), + ) + .detail(e), + ) + })?; + if recipients.is_empty() { + return Err(RuntimeError::with( + ErrorCode::InvalidRequest, + serde_json::json!({ "field": "recipientsJson", "reason": "empty" }), + ) + .into()); + } + + let fee_priority = spend::parse_priority(priority)?; + let reservation = reservation_id.to_owned(); + + let v = runtime::with_db_and_daemon(move |mut db, daemon| async move { + let r = spend::prepare_for_host( + &mut db, + &daemon, + account_id, + &recipients + .iter() + .map(|r| (r.address.as_str(), r.amount_atomic.as_str())) + .collect::>(), + max_send, + &reservation, + chain_tip, + fee_priority, + ) + .await; + (db, daemon, r) + }) + .await?; + + json(v) +} + +/// 签名一笔已构造的交易。**不碰网络、不碰数据库、不广播。** +/// +/// `spendPrivateKeyHex` 用完即擦,绝不落库、绝不返回。 +/// 返回 `{ txid, rawHex, sizeBytes }` —— txid 在签名这一刻就定下来了, +/// 宿主据此在广播之前就能建立待确认记录。 +#[wasm_bindgen(js_name = signTransaction)] +pub fn sign_transaction( + signable_hex: &str, + spend_private_key_hex: &str, +) -> std::result::Result { + let spend = Zeroizing::new(decode_hex(spend_private_key_hex, "spendPrivateKeyHex")?); + json(spend::sign_for_host(signable_hex, &spend)?) +} + +/// 广播一笔已签名的交易。**不可逆。** +/// +/// 节点接受或结果不确定(网络错误)都记账:被花的输出标记掉,交易进在途, +/// 返回 `broadcast: accepted | unknown`。只有节点明确拒收才报错并放回输入。 +#[wasm_bindgen(js_name = broadcastTransaction)] +pub async fn broadcast_transaction( + account_id: i64, + raw_hex: &str, + reservation_id: &str, + chain_tip: u64, + outgoing_atomic: Option, + change_atomic: Option, +) -> std::result::Result { + let raw = raw_hex.to_owned(); + let reservation = reservation_id.to_owned(); + // 十进制串:u64 过不了宿主桥。只用于显示与余额,格式不对就当没给。 + let amounts = spend::SentAmounts { + outgoing_atomic: outgoing_atomic.and_then(|a| a.parse::().ok()), + change_atomic: change_atomic.and_then(|a| a.parse::().ok()), + }; + let v = runtime::with_db_and_daemon(move |db, daemon| async move { + let r = spend::broadcast_signed( + &db, + &daemon, + account_id, + &raw, + &reservation, + chain_tip, + amounts, + ) + .await; + (db, daemon, r) + }) + .await?; + json(v) +} + +#[derive(serde::Deserialize)] +struct RecipientJson { + address: String, + #[serde(rename = "amountAtomic")] + amount_atomic: String, +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs b/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs new file mode 100644 index 000000000..bac1e5f12 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs @@ -0,0 +1,655 @@ +//! 批量取块:`get_blocks.bin`,按 wallet2 的信任模型。 +//! +//! 一次请求拿回一整批块,连同块里的交易和扫描要用的输出索引 —— 逐块取要 +//! 3~4 次往返一块,这里是一次往返几十上百块。 +//! +//! ## 为什么不直接用 monero-oxide 自带的那条 +//! +//! 它也走 `get_blocks.bin`,但坚持**用交易内容反算哈希、再与区块头的交易哈希 +//! 清单比对**。剪枝交易要反算哈希得有节点给的 `prunable_hash`,而已发布的 +//! monerod(截至 v0.18.5.1)把它发成全零(monero-project/monero#10120,修复 +//! #10652 只在 master)。于是它每次都整批放弃,退回逐块 JSON。 +//! +//! ## 这里的信任模型(与 wallet2、Cake、Feather 相同) +//! +//! 直接采用区块头里的交易哈希清单,不以交易内容反算去验证。代价:恶意节点 +//! 可以在真实哈希下塞假的交易内容,让余额显示失真(虚报或藏掉一笔到账); +//! 偷不走钱 —— 花费要私钥,拿假输出去花会被网络拒绝。wallet2 见 +//! `wallet2::process_new_blockchain_entry`,它用的就是 `b.tx_hashes[idx]`。 +//! +//! 仍然做的检查:交易数与区块头清单一致、每块的输出索引条数与交易输出数一致、 +//! 块高从请求起点连续。块与块之间的衔接(前驱哈希、RingCT 游标)照旧由 +//! `scan::scan_blocks` 校验。 +//! +//! 请求格式与解析骨架取自 monero-oxide 的 `monero-daemon-rpc` +//! (`src/bin_rpc/blocks_bin.rs`、`epee.rs`,MIT)。 + +use std::{ + cell::{Cell, RefCell}, + future::Future, + pin::Pin, + task::Poll, +}; + +use monero_daemon_rpc::HttpTransport; +use monero_epee::{Epee, EpeeEntry, EpeeError, Type, HEADER, VERSION}; +use monero_wallet::{ + block::Block, + interface::ScannableBlock, + transaction::{Pruned, Transaction}, +}; + +use crate::network::{Transport, MAX_RESPONSE_BYTES}; +use crate::perf::now_ms; + +/// 批量路径的失败分两种,处理方式截然不同。 +#[derive(Debug)] +pub enum BlocksBinError { + /// 网络问题:这一步失败,下一轮重试。不能据此判定节点不支持。 + Network(String), + /// 节点回的东西不对(不支持、格式不符、数量对不上):对这个节点不再走 + /// 批量路径,退回逐块。 + Protocol(String), +} + +fn protocol(detail: impl Into) -> BlocksBinError { + BlocksBinError::Protocol(detail.into()) +} + +fn epee_err(e: EpeeError) -> BlocksBinError { + protocol(format!("epee: {e:?}")) +} + +// ── 批量大小:自适应,上限与 wallet2 相同 ───────────────────────────────── +// +// wallet2 每次 `getblocks.bin` 不设上限,节点最多回 1000 块 / 2 万笔交易。在好 +// 网络上那是最快的;在翻墙、抖动的网络上一个十几 MB 的请求可能迟迟走不完。 +// 所以大小随实测调整:快就翻倍,一路涨到 1000;慢或失败就减半,最低 10 块。 +// 一步只发一个请求、拿到就扫、就落库 —— 块是一个请求一个请求地"滴"进来的, +// 前面拿到的不会因为后面的慢而作废。 + +/// 与 wallet2 / monerod 的单次上限一致(`COMMAND_RPC_GET_BLOCKS_FAST_MAX_BLOCK_COUNT`)。 +pub const MAX_BATCH_BLOCKS: u64 = 1000; +/// 再慢的网络也至少这么多一批,否则往返开销压过数据本身。 +pub const MIN_BATCH_BLOCKS: u64 = 10; +/// 起步大小:不知道网络如何时,一个请求十秒内能走完的量级。 +pub const INITIAL_BATCH_BLOCKS: u64 = 100; +/// 比这快就加倍。 +const GROW_BELOW_MS: f64 = 8_000.0; +/// 比这慢就减半。 +const SHRINK_ABOVE_MS: f64 = 25_000.0; + +thread_local! { + static BATCH_BLOCKS: Cell = const { Cell::new(INITIAL_BATCH_BLOCKS) }; +} + +/// 下一个请求要多少块。 +pub fn batch_blocks() -> u64 { + BATCH_BLOCKS.with(Cell::get) +} + +fn record_success(elapsed_ms: f64) { + BATCH_BLOCKS.with(|size| { + let current = size.get(); + if elapsed_ms < GROW_BELOW_MS { + size.set((current * 2).min(MAX_BATCH_BLOCKS)); + } else if elapsed_ms > SHRINK_ABOVE_MS { + size.set((current / 2).max(MIN_BATCH_BLOCKS)); + } + }); +} + +fn record_failure() { + BATCH_BLOCKS.with(|size| size.set((size.get() / 2).max(MIN_BATCH_BLOCKS))); +} + +// ── 请求与流水线 ───────────────────────────────────────────────────────── +// +// 一次只发一个请求,与 wallet2 相同。插件实测(2026-09-23,cakewallet 节点): +// 三路并发时每一步都是阶梯状 —— 第一个请求 1~4 s 回来,另外两个要 17~38 s: +// 节点在排队(monerod 生成 `get_blocks.bin` 要占区块链数据库的锁,公共节点也 +// 可能按 IP 限并发)。提速靠流水线(`prefetch`):扫这一批的同时,下一批已经 +// 在路上。 + +/// 一个请求的结果,以及它从发出到完成用了多久(预取的从预取那一刻算起)。 +type RequestOutcome = (Result, BlocksBinError>, f64); +type RequestFuture = Pin>>; + +/// 已经发出、结果还没被取走的下一个请求。 +struct Prefetch { + url: String, + start: u64, + count: u64, + future: RequestFuture, +} + +thread_local! { + static PREFETCH: RefCell> = const { RefCell::new(None) }; +} + +fn request_future(url: &str, start: u64, count: u64) -> RequestFuture { + let url = url.to_owned(); + Box::pin(async move { + // 第一次被 poll 时请求才真正发出,计时也从这里开始。 + let started = now_ms(); + let transport = Transport::new(&url); + let result = request_once(&transport, start, count).await; + (result, now_ms() - started) + }) +} + +/// 取走与这一段完全吻合的预取结果。不吻合(换了节点、回退重扫、区间变了) +/// 就丢掉 —— 宁可重发,也不能拿错一段数据。 +fn take_prefetched(url: &str, start: u64, count: u64) -> Option { + PREFETCH.with(|slot| match slot.borrow_mut().take() { + Some(p) if p.url == url && p.start == start && p.count == count => Some(p.future), + _ => None, + }) +} + +/// 取回的块,以及它们是否来自上一步的预取。 +pub struct Fetched { + pub blocks: Vec, + pub prefetch_hit: bool, +} + +/// 网络失败时的重试退避(毫秒),长度即额外重试次数。每次重试把请求减半 —— +/// 一个在当前网络上走不完的大请求,拆小了往往就能走完。协议错误不重试。 +const RETRY_BACKOFF_MS: [u32; 2] = [500, 1500]; + +async fn backoff(ms: u32) { + #[cfg(target_arch = "wasm32")] + gloo_timers::future::TimeoutFuture::new(ms).await; + #[cfg(not(target_arch = "wasm32"))] + tokio::time::sleep(std::time::Duration::from_millis(u64::from(ms))).await; +} + +/// 从 `start` 起取至多 `limit` 块,按高度排好。`start` 必须非零 —— monerod +/// 只在 `start_height` 非零时才认这个字段。 +/// +/// 只发**一个**请求(失败时以更小的请求重试),节点给多少就收多少:它可能因为 +/// 2 万笔交易的上限少给,剩下的由下一步接着要。 +pub async fn fetch(base_url: &str, start: u64, limit: u64) -> Result { + if start == 0 { + return Err(protocol("get_blocks.bin cannot start at the genesis block")); + } + let mut count = batch_blocks().min(limit).max(1); + let mut attempt = 0; + loop { + let prefetched = if attempt == 0 { + take_prefetched(base_url, start, count) + } else { + None + }; + let prefetch_hit = prefetched.is_some(); + let future = prefetched.unwrap_or_else(|| request_future(base_url, start, count)); + match future.await { + (Ok(blocks), elapsed_ms) => { + record_success(elapsed_ms); + return Ok(Fetched { + blocks, + prefetch_hit, + }); + } + (Err(BlocksBinError::Network(detail)), _) => { + record_failure(); + let Some(&wait) = RETRY_BACKOFF_MS.get(attempt) else { + return Err(BlocksBinError::Network(format!( + "after {} attempts, last with {count} blocks: {detail}", + attempt + 1 + ))); + }; + attempt += 1; + count = batch_blocks().min(limit).max(1); + backoff(wait).await; + } + (Err(protocol_error), _) => return Err(protocol_error), + } + } +} + +/// 现在就发出从 `start` 起、按当前批量大小(不超过 `limit`)的请求,结果留给下一步。 +/// +/// wallet2 的做法(`wallet2::refresh`:"pull the next set of blocks while we're +/// processing the current one")。在 wasm 里不需要线程:请求一旦发出,响应由 +/// 浏览器 / 宿主接收,与我们这边是否在扫描无关。这里只 poll 一次把请求发出去, +/// 下一步开头再 await 它 —— 扫描、回到宿主的那段空档、落库,全都和下载重叠。 +pub async fn prefetch(base_url: &str, start: u64, limit: u64) { + let count = batch_blocks().min(limit); + if start == 0 || count == 0 { + return; + } + let mut future = request_future(base_url, start, count); + let mut ready = None; + std::future::poll_fn(|cx| { + if let Poll::Ready(outcome) = future.as_mut().poll(cx) { + ready = Some(outcome); + } + Poll::Ready(()) + }) + .await; + // 已完成的 future 不能再 poll,结果单独收好。 + let future: RequestFuture = match ready { + Some(outcome) => Box::pin(futures_util::future::ready(outcome)), + None => future, + }; + PREFETCH.with(|slot| { + *slot.borrow_mut() = Some(Prefetch { + url: base_url.to_owned(), + start, + count, + future, + }); + }); +} + +/// 一个请求。节点多给(早于 0.18.4.3 不认 `max_block_count`)就截掉,少给就照收。 +async fn request_once( + transport: &Transport, + start: u64, + count: u64, +) -> Result, BlocksBinError> { + let response = transport + .post( + "get_blocks.bin", + build_request(start, count), + Some(MAX_RESPONSE_BYTES), + ) + .await + .map_err(|e| BlocksBinError::Network(format!("{e:?}")))?; + let mut blocks = parse_response(&response, start)?; + if blocks.is_empty() { + return Err(protocol(format!("zero blocks for start_height {start}"))); + } + blocks.truncate(usize::try_from(count).unwrap_or(usize::MAX)); + Ok(blocks) +} + +fn push_key(request: &mut Vec, key: &str) { + request.push(u8::try_from(key.len()).expect("epee keys are short")); + request.extend(key.as_bytes()); +} + +fn build_request(start_height: u64, max_block_count: u64) -> Vec { + let mut request = Vec::with_capacity(64); + request.extend(HEADER); + request.push(VERSION); + // 三个字段。epee 的 varint 低两位是长度标记,00 表示一字节。 + request.push(3 << 2); + + push_key(&mut request, "prune"); + request.push(Type::Bool as u8); + request.push(1); + + push_key(&mut request, "start_height"); + request.push(Type::Uint64 as u8); + request.extend(start_height.to_le_bytes()); + + // 0.18.4.3 起才有;更老的节点忽略它,由 `fetch` 截断。 + push_key(&mut request, "max_block_count"); + request.push(Type::Uint64 as u8); + request.extend(max_block_count.to_le_bytes()); + + request +} + +/// 一块:区块本身、剪枝后的非矿工交易、以及每笔交易(矿工交易在前)的输出索引。 +struct RawBlock { + block: Block, + transactions: Vec>, +} + +fn read_block<'e>(entry: EpeeEntry<'e, '_, &'e [u8]>) -> Result { + let mut fields = entry.fields().map_err(epee_err)?; + let mut block = None; + let mut transactions = vec![]; + while let Some(field) = fields.next() { + let (key, value) = field.map_err(epee_err)?; + match key.consume() { + b"block" => { + let mut encoding = value.to_str().map_err(epee_err)?.consume(); + let parsed = Block::read(&mut encoding) + .map_err(|e| protocol(format!("invalid block: {e:?}")))?; + if !encoding.is_empty() { + return Err(protocol("block had extraneous bytes after it")); + } + block = Some(parsed); + } + b"txs" => { + let mut entries = value.iterate().map_err(epee_err)?; + while let Some(tx_entry) = entries.next() { + let mut tx_fields = tx_entry.map_err(epee_err)?.fields().map_err(epee_err)?; + let mut transaction = None; + while let Some(tx_field) = tx_fields.next() { + let (tx_key, tx_value) = tx_field.map_err(epee_err)?; + // `prunable_hash` 被刻意忽略:见模块说明。 + if tx_key.consume() == b"blob" { + let mut encoding = tx_value.to_str().map_err(epee_err)?.consume(); + let parsed = Transaction::::read(&mut encoding) + .map_err(|e| protocol(format!("invalid transaction: {e:?}")))?; + if !encoding.is_empty() { + return Err(protocol("transaction had extraneous bytes after it")); + } + transaction = Some(parsed); + } + } + transactions.push( + transaction.ok_or_else(|| protocol("transaction entry without a blob"))?, + ); + } + } + _ => {} + } + } + Ok(RawBlock { + block: block.ok_or_else(|| protocol("block entry without the block"))?, + transactions, + }) +} + +/// `output_indices`:块 → 交易(矿工交易在前)→ 该交易每个输出的全局索引。 +fn read_output_indices<'e>( + entry: EpeeEntry<'e, '_, &'e [u8]>, +) -> Result>>, BlocksBinError> { + let mut blocks = vec![]; + let mut block_entries = entry.iterate().map_err(epee_err)?; + while let Some(block_entry) = block_entries.next() { + let mut per_tx = vec![]; + let mut fields = block_entry.map_err(epee_err)?.fields().map_err(epee_err)?; + while let Some(field) = fields.next() { + let (key, value) = field.map_err(epee_err)?; + if key.consume() != b"indices" { + continue; + } + let mut tx_entries = value.iterate().map_err(epee_err)?; + while let Some(tx_entry) = tx_entries.next() { + let mut indices = vec![]; + let mut tx_fields = tx_entry.map_err(epee_err)?.fields().map_err(epee_err)?; + while let Some(tx_field) = tx_fields.next() { + let (tx_key, tx_value) = tx_field.map_err(epee_err)?; + if tx_key.consume() != b"indices" { + continue; + } + let mut values = tx_value.iterate().map_err(epee_err)?; + while let Some(v) = values.next() { + indices.push(v.map_err(epee_err)?.to_u64().map_err(epee_err)?); + } + } + per_tx.push(indices); + } + } + blocks.push(per_tx); + } + Ok(blocks) +} + +pub(crate) fn parse_response( + bytes: &[u8], + start: u64, +) -> Result, BlocksBinError> { + let mut epee = Epee::new(bytes).map_err(epee_err)?; + let mut root = epee.entry().map_err(epee_err)?.fields().map_err(epee_err)?; + + let mut raw_blocks = vec![]; + let mut output_indices = vec![]; + let mut status = None; + while let Some(field) = root.next() { + let (key, value) = field.map_err(epee_err)?; + match key.consume() { + b"blocks" => { + let mut entries = value.iterate().map_err(epee_err)?; + while let Some(entry) = entries.next() { + raw_blocks.push(read_block(entry.map_err(epee_err)?)?); + } + } + b"output_indices" => output_indices = read_output_indices(value)?, + b"status" => { + status = Some( + String::from_utf8_lossy(value.to_str().map_err(epee_err)?.consume()) + .into_owned(), + ); + } + _ => {} + } + } + if let Some(status) = status.as_deref() { + if status != "OK" { + return Err(protocol(format!("node status {status}"))); + } + } + if raw_blocks.len() != output_indices.len() { + return Err(protocol(format!( + "{} blocks but {} output index entries", + raw_blocks.len(), + output_indices.len() + ))); + } + + let mut result = Vec::with_capacity(raw_blocks.len()); + for (offset, (raw, indices)) in raw_blocks.into_iter().zip(output_indices).enumerate() { + let expected = start + offset as u64; + let height = raw.block.number() as u64; + if height != expected { + return Err(protocol(format!( + "expected block {expected}, node sent {height}" + ))); + } + // 与区块头的交易哈希清单对数 —— 我们信任的正是那份清单。 + if raw.transactions.len() != raw.block.transactions.len() { + return Err(protocol(format!( + "block {height}: header lists {} transactions, node sent {}", + raw.block.transactions.len(), + raw.transactions.len() + ))); + } + if indices.len() != raw.transactions.len() + 1 { + return Err(protocol(format!( + "block {height}: {} transactions (plus miner) but {} output index lists", + raw.transactions.len(), + indices.len() + ))); + } + + // 本块第一个 RingCT 输出的全局索引:第一笔非 V1 且有输出的交易的首个索引。 + let miner = raw.block.miner_transaction(); + let mut first_ringct = None; + let shapes = std::iter::once(( + !matches!(miner, Transaction::V1 { .. }), + miner.prefix().outputs.len(), + )) + .chain(raw.transactions.iter().map(|tx| { + ( + !matches!(tx, Transaction::V1 { .. }), + tx.prefix().outputs.len(), + ) + })); + for ((is_ringct, outputs), tx_indices) in shapes.zip(&indices) { + if tx_indices.len() != outputs { + return Err(protocol(format!( + "block {height}: a transaction has {outputs} outputs but {} indices", + tx_indices.len() + ))); + } + if is_ringct && outputs != 0 && first_ringct.is_none() { + first_ringct = Some(tx_indices[0]); + } + } + + result.push(ScannableBlock { + block: raw.block, + transactions: raw.transactions, + output_index_for_first_ringct_output: first_ringct, + }); + } + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 请求字节必须与 monero-oxide 发出的逐字一致:它是经过节点验证的格式。 + #[test] + fn the_request_matches_the_upstream_layout() { + let request = build_request(3_000_000, 50); + assert_eq!(&request[..8], &HEADER); + assert_eq!(request[8], VERSION); + assert_eq!(request[9], 3 << 2); + // header(8) + version(1) + count(1) + // + prune: 1+5+1+1 + start_height: 1+12+1+8 + max_block_count: 1+15+1+8 + assert_eq!(request.len(), 10 + 8 + 22 + 25); + assert!(request.windows(5).any(|w| w == b"prune")); + assert!(request.ends_with(&50u64.to_le_bytes())); + } + + /// 快就加倍到 1000 封顶,慢或失败就减半到 10 保底。 + #[test] + fn the_batch_grows_on_fast_requests_and_shrinks_on_slow_or_failed_ones() { + BATCH_BLOCKS.with(|b| b.set(INITIAL_BATCH_BLOCKS)); + for _ in 0..10 { + record_success(1_000.0); + } + assert_eq!(batch_blocks(), MAX_BATCH_BLOCKS); + record_success(15_000.0); + assert_eq!(batch_blocks(), MAX_BATCH_BLOCKS, "中速不动"); + record_success(40_000.0); + assert_eq!(batch_blocks(), MAX_BATCH_BLOCKS / 2); + for _ in 0..20 { + record_failure(); + } + assert_eq!(batch_blocks(), MIN_BATCH_BLOCKS); + BATCH_BLOCKS.with(|b| b.set(INITIAL_BATCH_BLOCKS)); + } + + /// 预取只在完全吻合时被取走;不吻合的一律丢弃,槽位同时被清空。 + #[test] + fn a_prefetch_is_taken_only_by_the_exact_same_request() { + let park = |url: &str, start: u64, count: u64| { + PREFETCH.with(|slot| { + *slot.borrow_mut() = Some(Prefetch { + url: url.to_owned(), + start, + count, + future: Box::pin(futures_util::future::ready((Ok(vec![]), 0.0))), + }); + }); + }; + park("https://a", 100, 20); + assert!(take_prefetched("https://a", 100, 20).is_some()); + assert!( + take_prefetched("https://a", 100, 20).is_none(), + "取走即清空" + ); + + park("https://a", 100, 20); + assert!(take_prefetched("https://b", 100, 20).is_none(), "换了节点"); + park("https://a", 100, 20); + assert!( + take_prefetched("https://a", 101, 20).is_none(), + "起点变了(回退、部分前缀)" + ); + park("https://a", 100, 20); + assert!( + take_prefetched("https://a", 100, 7).is_none(), + "区间长度变了" + ); + } + + #[test] + fn genesis_is_refused_rather_than_silently_misread() { + let Err(e) = futures_lite::future::block_on(fetch("https://x.invalid", 0, 10)) else { + panic!("genesis must be refused"); + }; + assert!(matches!(e, BlocksBinError::Protocol(_))); + } + + /// 真实节点的真实响应(xmr-node.cakewallet.com,2026-09-23, + /// start_height=3768621、max_block_count=2),经桌面主进程抓取。 + /// 验证的是整条解析:区块、剪枝交易、输出索引、首个 RingCT 索引。 + #[test] + fn parses_a_real_node_response() { + let bytes = include_bytes!("../tests/fixtures/get_blocks_bin_3768621.bin"); + let blocks = parse_response(bytes, 3_768_621).expect("解析真实响应"); + eprintln!( + "node returned {} blocks: {:?}", + blocks.len(), + blocks + .iter() + .map(|b| ( + b.block.number(), + b.transactions.len(), + b.output_index_for_first_ringct_output + )) + .collect::>() + ); + assert!(!blocks.is_empty()); + for (i, b) in blocks.iter().enumerate() { + assert_eq!(b.block.number() as u64, 3_768_621 + i as u64); + assert_eq!(b.transactions.len(), b.block.transactions.len()); + // 每块至少有矿工交易的输出,所以一定有首个 RingCT 索引。 + assert!(b.output_index_for_first_ringct_output.is_some()); + } + // 前驱哈希首尾相接:确认块真的是连续的一段。 + for pair in blocks.windows(2) { + assert_eq!(pair[1].block.header.previous, pair[0].block.hash()); + } + // RingCT 游标首尾相接:下一块的首个索引 = 这一块首个索引 + 这一块的输出总数。 + for pair in blocks.windows(2) { + let outputs: u64 = + std::iter::once(pair[0].block.miner_transaction().prefix().outputs.len()) + .chain( + pair[0] + .transactions + .iter() + .map(|t| t.prefix().outputs.len()), + ) + .map(|n| n as u64) + .sum(); + assert_eq!( + pair[1].output_index_for_first_ringct_output, + pair[0] + .output_index_for_first_ringct_output + .map(|i| i + outputs) + ); + } + } + + /// 扫描耗时基准(原生,release 下更准)。夹具太大不入库,按需抓: + /// `XMR_BLOCKS_BIN=/path/to/get_blocks.bin XMR_BLOCKS_BIN_START=3767000 \ + /// cargo test --release --lib scan_cost -- --nocapture` + #[test] + fn scan_cost_on_real_blocks() { + let (Ok(path), Ok(start)) = ( + std::env::var("XMR_BLOCKS_BIN"), + std::env::var("XMR_BLOCKS_BIN_START"), + ) else { + eprintln!("跳过:未设置 XMR_BLOCKS_BIN / XMR_BLOCKS_BIN_START"); + return; + }; + let start: u64 = start.parse().unwrap(); + let bytes = std::fs::read(path).unwrap(); + let t0 = std::time::Instant::now(); + let blocks = parse_response(&bytes, start).expect("解析"); + let parse_ms = t0.elapsed().as_secs_f64() * 1000.0; + + let mut db = crate::wallet::testing::db(); + let (spend, view) = crate::wallet::testing::key_bytes(); + let id = db.add_identity("bench", &spend, &view, start).unwrap().id; + let t1 = std::time::Instant::now(); + crate::scan::scan_blocks(&mut db, id, &blocks).expect("扫描"); + let scan_ms = t1.elapsed().as_secs_f64() * 1000.0; + let txs: usize = blocks.iter().map(|b| b.transactions.len()).sum(); + eprintln!( + "{} blocks / {txs} txs / {} bytes: parse {parse_ms:.0} ms, scan {scan_ms:.0} ms ({:.1} ms/block)", + blocks.len(), + bytes.len(), + scan_ms / blocks.len() as f64 + ); + } + + #[test] + fn garbage_is_a_protocol_error_not_a_panic() { + let e = parse_response(b"not epee at all", 1).unwrap_err(); + assert!(matches!(e, BlocksBinError::Protocol(_))); + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/error.rs b/chain-runtimes/monero/crates/monero-runtime/src/error.rs new file mode 100644 index 000000000..c0890a502 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/error.rs @@ -0,0 +1,235 @@ +//! 错误码:跨 wasm 边界的稳定契约。 +//! +//! 宿主按 `code` 分支处理、按 `params` 填 i18n 占位符。`detail` 只进日志, +//! 不面向用户、不翻译 —— 它可能带上游库的原始文案。 +//! +//! **不要改动已有取值。** 宿主会按字符串比对。 + +use serde_json::{json, Map, Value}; +use std::fmt; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ErrorCode { + // ── 输入校验 ──────────────────────────────────────────────────────── + /// 网络名不是 mainnet/stagenet/testnet。参数:`{ value }` + InvalidNetwork, + /// 地址无法解析,或不属于该网络。参数:`{ field }` + InvalidAddress, + /// 私钥/种子字节数不对。参数:`{ byteLen, expected }` + InvalidKeyMaterial, + /// 子地址序号非法(主序号与次序号不可同时为 0,那是主地址)。 + InvalidSubaddressIndex, + /// 高度区间不合法(起点大于终点,或终点超过链尖)。参数:`{ from, to }` + InvalidBlockRange, + /// 宿主传入的 JSON 结构不对。参数:`{ field, reason }` + InvalidRequest, + + // ── 生命周期 ──────────────────────────────────────────────────────── + /// 还没 `openWallet`。 + WalletNotOpen, + /// 正在进行一次异步操作,此刻不接受切换钱包的调用。参数:`{ operation }` + WalletBusy, + /// 存储层还没初始化(wasm 上是 VFS 未安装)。 + NotInitialized, + /// 该账户在库里不存在。参数:`{ accountId }` + AccountNotFound, + + // ── 扫描 ──────────────────────────────────────────────────────────── + /// 节点返回的块与本地记录不连续 —— 重组,或节点在骗人。 + /// 参数:`{ atHeight, suggestedRewindHeight }` + ReorgDetected, + /// **节点给的 RingCT 输出索引与本地推算不符。** + /// + /// 上游明确警告这个字段不可验证,要求客户端自己维护索引并比对;不一致 + /// 意味着节点在提供虚假视图,应当断开而不是继续扫。 + /// 参数:`{ height, claimed, expected }` + RingCtIndexMismatch, + /// 扫描器拒绝了这个块(上游 `ScanError`)。参数:`{ height }` + ScanFailed, + + // ── 外部世界 ──────────────────────────────────────────────────────── + /// 节点地址没配。 + NodeNotConfigured, + /// 网络请求失败或超时。参数:`{ operation }` + NetworkError, + /// 节点返回的数据解不开(epee/JSON 格式不对)。参数:`{ operation }` + MalformedNodeResponse, + /// 节点明确拒收了这笔交易(双花、手续费不足……)。输入的预留已释放。 + BroadcastRejected, + + // ── 存储 ──────────────────────────────────────────────────────────── + /// SQLite 操作失败。参数:`{ operation }` + DatabaseError, + /// 库名非法(空,或含路径分隔符)。参数:`{ value }` + InvalidDbName, + + /// 该能力尚未实现。参数:`{ what }` + Unimplemented, +} + +impl ErrorCode { + /// 稳定字符串形式。**不要改动已有取值。** + pub fn as_str(self) -> &'static str { + use ErrorCode::*; + match self { + InvalidNetwork => "INVALID_NETWORK", + InvalidAddress => "INVALID_ADDRESS", + InvalidKeyMaterial => "INVALID_KEY_MATERIAL", + InvalidSubaddressIndex => "INVALID_SUBADDRESS_INDEX", + InvalidBlockRange => "INVALID_BLOCK_RANGE", + InvalidRequest => "INVALID_REQUEST", + WalletNotOpen => "WALLET_NOT_OPEN", + WalletBusy => "WALLET_BUSY", + NotInitialized => "NOT_INITIALIZED", + AccountNotFound => "ACCOUNT_NOT_FOUND", + ReorgDetected => "REORG_DETECTED", + RingCtIndexMismatch => "RINGCT_INDEX_MISMATCH", + ScanFailed => "SCAN_FAILED", + NodeNotConfigured => "NODE_NOT_CONFIGURED", + NetworkError => "NETWORK_ERROR", + MalformedNodeResponse => "MALFORMED_NODE_RESPONSE", + BroadcastRejected => "BROADCAST_REJECTED", + DatabaseError => "DATABASE_ERROR", + InvalidDbName => "INVALID_DB_NAME", + Unimplemented => "UNIMPLEMENTED", + } + } +} + +#[derive(Debug)] +pub struct RuntimeError { + pub code: ErrorCode, + /// 结构化参数,供宿主填 i18n 占位符。**永远是一个 JSON 对象。** + pub params: Value, + /// 上游库的原始报错。**仅用于日志**,不面向用户,不做 i18n。 + pub detail: Option, +} + +impl RuntimeError { + pub fn new(code: ErrorCode) -> Self { + Self { + code, + params: Value::Object(Map::new()), + detail: None, + } + } + + pub fn with(code: ErrorCode, params: Value) -> Self { + Self { + code, + params, + detail: None, + } + } + + pub fn detail(mut self, d: impl fmt::Display) -> Self { + self.detail = Some(d.to_string()); + self + } + + pub fn to_json(&self) -> Value { + json!({ + "code": self.code.as_str(), + "params": self.params, + "detail": self.detail, + }) + } +} + +impl fmt::Display for RuntimeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.to_json()) + } +} + +impl std::error::Error for RuntimeError {} + +impl From for RuntimeError { + fn from(e: rusqlite::Error) -> Self { + RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": "sqlite" })).detail(e) + } +} + +pub type Result = std::result::Result; + +/// 给数据库操作贴上操作名,排查时能知道是哪一步挂的。 +pub fn db_err(operation: &str, e: impl fmt::Display) -> RuntimeError { + RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": operation })).detail(e) +} + +pub fn net_err(operation: &str, e: impl fmt::Display) -> RuntimeError { + RuntimeError::with(ErrorCode::NetworkError, json!({ "operation": operation })).detail(e) +} + +#[cfg(target_arch = "wasm32")] +impl From for wasm_bindgen::JsValue { + fn from(e: RuntimeError) -> Self { + // 用 JSON 字符串而不是 Error 对象:宿主那头统一 `JSON.parse` 就能拿到 + // 结构化的 code/params,不必区分 Error 与非 Error 两条路径。 + wasm_bindgen::JsValue::from_str(&e.to_json().to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + + /// 码值必须唯一且是 SCREAMING_SNAKE —— 宿主按字符串比对,复制粘贴出一个 + /// 重复值会让两类错误在宿主眼里变成同一个,而那种 bug 很难从现象反推。 + #[test] + fn codes_are_unique_and_screaming_snake() { + use ErrorCode::*; + let all = [ + InvalidNetwork, + InvalidAddress, + InvalidKeyMaterial, + InvalidSubaddressIndex, + InvalidBlockRange, + InvalidRequest, + WalletNotOpen, + WalletBusy, + NotInitialized, + AccountNotFound, + ReorgDetected, + RingCtIndexMismatch, + ScanFailed, + NodeNotConfigured, + NetworkError, + MalformedNodeResponse, + BroadcastRejected, + DatabaseError, + InvalidDbName, + Unimplemented, + ]; + let mut seen = HashSet::new(); + for code in all { + let s = code.as_str(); + assert!(seen.insert(s), "码值重复: {s}"); + assert!( + !s.is_empty() + && s.chars() + .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'), + "码值格式不对: {s}" + ); + } + } + + /// `params` 永远是对象 —— 宿主直接取字段,不必先判类型。 + #[test] + fn params_default_to_empty_object() { + let e = RuntimeError::new(ErrorCode::WalletNotOpen); + assert_eq!(e.to_json()["params"], json!({})); + assert!(e.to_json()["detail"].is_null()); + } + + #[test] + fn json_shape_is_stable() { + let e = RuntimeError::with(ErrorCode::InvalidBlockRange, json!({ "from": 5, "to": 1 })) + .detail("起点大于终点"); + let v = e.to_json(); + assert_eq!(v["code"], "INVALID_BLOCK_RANGE"); + assert_eq!(v["params"]["from"], 5); + assert_eq!(v["detail"], "起点大于终点"); + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/keys.rs b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs new file mode 100644 index 000000000..85519ace6 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs @@ -0,0 +1,350 @@ +//! 观察密钥与地址派生。 +//! +//! ## 这里有什么、没有什么 +//! +//! **有**:花费公钥 + 私有观察密钥(即 monero-oxide 的 `ViewPair`),这是扫链 +//! 需要的全部材料,等价于 Zcash 的 UFVK。 +//! +//! **没有**:花费私钥。它永远不进这个 crate,也不落库 —— 签名走单独的路径, +//! 由宿主在需要时把种子传进签名函数,用完即弃。 +//! +//! 想审计「私钥去了哪」,看这个文件就够:它一次都没出现。 + +use monero_wallet::{ + address::{MoneroAddress, Network, SubaddressIndex}, + ed25519::{CompressedPoint, Scalar}, + ViewPair, +}; +use serde_json::json; +use zeroize::Zeroizing; + +use crate::error::{ErrorCode, Result, RuntimeError}; + +/// 解析网络名。**没有缺省值** —— 主网和测试网的地址互不通用,猜错了钱会发到 +/// 一个看起来合法、实际上无人持有的地址上。 +pub fn parse_network(name: &str) -> Result { + match name { + "mainnet" | "main" => Ok(Network::Mainnet), + "stagenet" | "stage" => Ok(Network::Stagenet), + "testnet" | "test" => Ok(Network::Testnet), + other => Err(RuntimeError::with( + ErrorCode::InvalidNetwork, + json!({ "value": other, "allowed": ["mainnet", "stagenet", "testnet"] }), + )), + } +} + +pub fn network_name(network: Network) -> &'static str { + match network { + Network::Mainnet => "mainnet", + Network::Stagenet => "stagenet", + Network::Testnet => "testnet", + } +} + +fn expect_32(bytes: &[u8], field: &str) -> Result<[u8; 32]> { + <[u8; 32]>::try_from(bytes).map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidKeyMaterial, + json!({ "field": field, "byteLen": bytes.len(), "expected": 32 }), + ) + }) +} + +/// 从原始字节造观察密钥对。 +/// +/// `spend_public` 是压缩的 ed25519 点,`view_private` 是标准序的标量。 +/// 两者都来自宿主 —— 这个 crate 不做派生,只做使用。 +pub fn view_pair_from_bytes(spend_public: &[u8], view_private: &[u8]) -> Result { + let spend = CompressedPoint::from(expect_32(spend_public, "spendPublicKey")?) + .decompress() + .ok_or_else(|| { + RuntimeError::with( + ErrorCode::InvalidKeyMaterial, + json!({ "field": "spendPublicKey", "reason": "notACurvePoint" }), + ) + })?; + + let view_bytes = expect_32(view_private, "viewPrivateKey")?; + let view = Scalar::read(&mut view_bytes.as_slice()).map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidKeyMaterial, + json!({ "field": "viewPrivateKey", "reason": "notCanonicalScalar" }), + ) + })?; + + // 上游拒绝带挠率的花费公钥(那种密钥能否花费存疑)。这是它的判断,不是 + // 我们的 —— 原样把拒绝理由传出去,不要吞掉。 + ViewPair::new(spend, Zeroizing::new(view)).map_err(|e| { + RuntimeError::with( + ErrorCode::InvalidKeyMaterial, + json!({ "field": "spendPublicKey" }), + ) + .detail(format!("{e:?}")) + }) +} + +/// 主地址(标准地址)。 +pub fn primary_address(pair: &ViewPair, network: Network) -> String { + pair.legacy_address(network).to_string() +} + +/// 子地址。`(0, 0)` 是主地址,不是子地址 —— 上游对它返回 `None`,这里也拒绝, +/// 否则会注册出一个扫描器永远不认的条目。 +pub fn subaddress(pair: &ViewPair, network: Network, major: u32, minor: u32) -> Result { + let index = SubaddressIndex::new(major, minor).ok_or_else(|| { + RuntimeError::with( + ErrorCode::InvalidSubaddressIndex, + json!({ "major": major, "minor": minor, "reason": "zeroZeroIsThePrimaryAddress" }), + ) + })?; + Ok(pair.subaddress(network, index).to_string()) +} + +/// 校验一个收款地址:编码合法、且属于指定网络。 +pub fn validate_address(network: Network, encoded: &str) -> bool { + MoneroAddress::from_str(network, encoded).is_ok() +} + +/// 解析收款地址,网络不符时明确报错而不是笼统的"地址无效"。 +pub fn parse_address(network: Network, encoded: &str, field: &str) -> Result { + MoneroAddress::from_str(network, encoded).map_err(|e| { + RuntimeError::with( + ErrorCode::InvalidAddress, + json!({ "field": field, "network": network_name(network) }), + ) + .detail(format!("{e:?}")) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 上游测试向量之外的公开地址,只用来证明解析路径真的跑了。 + const MAINNET_ADDR: &str = "44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft3XjrpDtQGv7SqSsaBYBb98uNbr2VBBEt7f2wfn3RVGQBEP3A"; + + #[test] + fn network_names_round_trip() { + for (name, net) in [ + ("mainnet", Network::Mainnet), + ("stagenet", Network::Stagenet), + ("testnet", Network::Testnet), + ] { + assert_eq!(parse_network(name).unwrap(), net); + assert_eq!(network_name(net), name); + } + // 别名也收 + assert_eq!(parse_network("main").unwrap(), Network::Mainnet); + } + + /// 没有缺省网络 —— 猜错网络的代价是钱发到无人持有的地址上。 + #[test] + fn unknown_network_is_rejected_not_defaulted() { + let e = parse_network("").unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidNetwork); + assert!(parse_network("regtest").is_err()); + } + + #[test] + fn mainnet_address_is_not_valid_on_other_networks() { + assert!(validate_address(Network::Mainnet, MAINNET_ADDR)); + assert!(!validate_address(Network::Testnet, MAINNET_ADDR)); + assert!(!validate_address(Network::Stagenet, MAINNET_ADDR)); + } + + /// `ViewPair` 刻意不实现 `Debug`(免得密钥被打进日志),所以测试里不能用 + /// `unwrap_err` —— 那要求 Ok 类型可 Debug。显式 match 取错误。 + fn expect_key_error(spend: &[u8], view: &[u8]) -> RuntimeError { + match view_pair_from_bytes(spend, view) { + Ok(_) => panic!("本该被拒绝的密钥材料却通过了"), + Err(e) => e, + } + } + + #[test] + fn key_material_length_is_enforced() { + let e = expect_key_error(&[0u8; 31], &[0u8; 32]); + assert_eq!(e.code, ErrorCode::InvalidKeyMaterial); + assert_eq!(e.params["byteLen"], 31); + } + + /// 全零不是合法曲线点,必须在解压那一步就被挡住,而不是带着一个无效点 + /// 一路跑到扫描里去。 + #[test] + fn non_curve_spend_key_is_rejected() { + let mut not_a_point = [0u8; 32]; + not_a_point[0] = 2; // 刻意构造一个解压不出来的值 + let e = expect_key_error(¬_a_point, &[1u8; 32]); + assert_eq!(e.code, ErrorCode::InvalidKeyMaterial); + } + + /// (0,0) 是主地址。允许它进子地址注册表会产出一个扫描器永远不认的条目, + /// 表现为「这个地址收到的钱永远扫不到」。 + #[test] + fn subaddress_zero_zero_is_refused() { + let pair = test_pair(); + let e = subaddress(&pair, Network::Mainnet, 0, 0).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidSubaddressIndex); + assert!(subaddress(&pair, Network::Mainnet, 0, 1).is_ok()); + assert!(subaddress(&pair, Network::Mainnet, 1, 0).is_ok()); + } + + /// 子地址必须与主地址不同,且不同序号之间互不相同 —— 派生错了会让不同 + /// 账户共用一个收款地址,是最坏的那类 bug。 + #[test] + fn subaddresses_are_distinct_from_each_other_and_the_primary() { + let pair = test_pair(); + let primary = primary_address(&pair, Network::Mainnet); + let a = subaddress(&pair, Network::Mainnet, 0, 1).unwrap(); + let b = subaddress(&pair, Network::Mainnet, 0, 2).unwrap(); + let c = subaddress(&pair, Network::Mainnet, 1, 1).unwrap(); + for x in [&a, &b, &c] { + assert_ne!(*x, primary); + } + assert_ne!(a, b); + assert_ne!(a, c); + assert_ne!(b, c); + } + + fn test_pair() -> ViewPair { + // 从一个已知合法地址取出它的公钥对,再配一个任意标量当观察私钥。 + // 这里不关心它们是否互相对应 —— 测的是派生与编码路径。 + let addr = MoneroAddress::from_str(Network::Mainnet, MAINNET_ADDR).unwrap(); + let spend = addr.spend().compress().to_bytes(); + let mut view = [0u8; 32]; + view[0] = 9; // 小标量,必然是标准序 + match view_pair_from_bytes(&spend, &view) { + Ok(pair) => pair, + Err(e) => panic!("测试密钥对构造失败: {e}"), + } + } +} + +// ── 从 BIP-39 / BIP-32 派生 Monero 密钥 ───────────────────────────────── + +/// 从 BIP-32 派生出来的 32 字节私钥造出 Monero 的密钥三元组。 +/// +/// ## 为什么是这个约定 +/// +/// Monero 原生用自己的 25 词助记词,而 OneKey 全链统一 BIP-39。业界(以及 +/// **OneKey V4 自己**)的做法是: +/// +/// ```text +/// spend_secret = sc_reduce32(bip32_private_key) +/// view_secret = sc_reduce32(keccak256(spend_secret)) +/// ``` +/// +/// **这个约定不能改。** V4 用的就是它(`sdkXmr/helper.ts` 的 +/// `getKeyPairFromRawPrivatekey`:先 `scReduce32` 再 `hashToScalar`),换一个 +/// 会让老用户导入同一套助记词后看到一个空钱包 —— 钱还在链上,只是这个钱包 +/// 再也找不到它。 +/// +/// 返回观察材料与主地址。**花费私钥不返回** —— 它就是调用方传进来的那个 +/// BIP-32 私钥,宿主本来就持有,没有理由让它再跨一次边界。 +pub fn derive_from_bip32_key(network: Network, bip32_private_key: &[u8]) -> Result { + use monero_wallet::ed25519::Point; + + let raw = expect_32(bip32_private_key, "bip32PrivateKey")?; + + // sc_reduce32:把任意 32 字节约简到标量域内。 + let spend = Scalar::from(curve25519_dalek::Scalar::from_bytes_mod_order(raw)); + // hash_to_scalar:keccak256 再约简。上游 `Scalar::hash` 正是这个。 + let view = Scalar::hash(<[u8; 32]>::from(spend)); + + let spend_public = + Point::from(spend.into() * curve25519_dalek::constants::ED25519_BASEPOINT_POINT); + + let pair = ViewPair::new(spend_public, Zeroizing::new(view)).map_err(|e| { + RuntimeError::with( + ErrorCode::InvalidKeyMaterial, + json!({ "field": "bip32PrivateKey" }), + ) + .detail(format!("{e:?}")) + })?; + + Ok(DerivedKeys { + spend_public_key: spend_public.compress().to_bytes(), + view_private_key: <[u8; 32]>::from(view), + primary_address: primary_address(&pair, network), + }) +} + +pub struct DerivedKeys { + pub spend_public_key: [u8; 32], + pub view_private_key: [u8; 32], + pub primary_address: String, +} + +/// 花费私钥的标量形式,签名时用。与 [`derive_from_bip32_key`] 同一个约简。 +pub fn spend_scalar_from_bip32_key(bip32_private_key: &[u8]) -> Result<[u8; 32]> { + let raw = expect_32(bip32_private_key, "bip32PrivateKey")?; + let spend = Scalar::from(curve25519_dalek::Scalar::from_bytes_mod_order(raw)); + Ok(<[u8; 32]>::from(spend)) +} + +#[cfg(test)] +mod derive_tests { + use super::*; + + /// 派生必须是确定性的,且同一把 BIP-32 私钥在不同网络上给出不同前缀的 + /// 地址(主网 4 / 测试网 9 / stagenet 5)。 + #[test] + fn derivation_is_deterministic_and_network_scoped() { + let key = [3u8; 32]; + let a = derive_from_bip32_key(Network::Mainnet, &key).expect("派生"); + let b = derive_from_bip32_key(Network::Mainnet, &key).expect("派生"); + assert_eq!(a.primary_address, b.primary_address); + assert_eq!(a.spend_public_key, b.spend_public_key); + assert!(a.primary_address.starts_with('4')); + + let t = derive_from_bip32_key(Network::Testnet, &key).expect("派生"); + assert_ne!(t.primary_address, a.primary_address); + } + + /// 不同的 BIP-32 私钥必须给出不同的地址 —— 撞了就是灾难。 + #[test] + fn different_keys_give_different_addresses() { + let a = derive_from_bip32_key(Network::Mainnet, &[1u8; 32]).unwrap(); + let b = derive_from_bip32_key(Network::Mainnet, &[2u8; 32]).unwrap(); + assert_ne!(a.primary_address, b.primary_address); + assert_ne!(a.view_private_key, b.view_private_key); + } + + /// 观察密钥必须由花费密钥经 keccak 得出,而不是别的什么 —— 这条锁住 + /// 与 V4 的兼容性(`hashToScalar(privateSpendKey)`)。 + /// **V4 兼容性契约。** 这是从 OneKey V4 取的真实向量: + /// 助记词经 `m/44'/128'/0'` 派生出的 BIP-32 私钥,以及 V4 当时显示给用户的 + /// 那个主地址(见 app 仓 `CoreChainSoftware.test.ts` 的 fixture)。 + /// + /// 派生约定是 `spend = sc_reduce32(bip32_key)`、`view = keccak256(spend)`。 + /// 这条一旦改动,V4 用户导入同一助记词会看到**空钱包** —— 钱还在链上, + /// 只是这个钱包再也找不到它。所以用真实向量钉死,不是自己造一个。 + #[test] + fn the_v4_derivation_vector_still_produces_the_v4_address() { + let key = hex::decode("8b28f5749ec99464d5a9d6527125aa8778ea017dd9e5cffaa567d2f62f2c8cbc") + .unwrap(); + let derived = derive_from_bip32_key(Network::Mainnet, &key).expect("派生应当成功"); + assert_eq!( + derived.primary_address, + "45vw7EY1nYs66nCedDxS9hYptSP2PnnQwezJ4WmGsNFFKAKXMDWSEspFUKBD6UCivUB5LGW2vXoX8D3DjzhrFuoZSoDcYPN" + ); + } + + #[test] + fn the_view_key_is_the_hash_of_the_spend_key() { + let key = [7u8; 32]; + let derived = derive_from_bip32_key(Network::Mainnet, &key).unwrap(); + let spend = spend_scalar_from_bip32_key(&key).unwrap(); + let expected = <[u8; 32]>::from(Scalar::hash(spend)); + assert_eq!(derived.view_private_key, expected); + } + + #[test] + fn key_length_is_enforced() { + let e = derive_from_bip32_key(Network::Mainnet, &[0u8; 31]) + .err() + .expect("长度不对必须拒绝"); + assert_eq!(e.code, ErrorCode::InvalidKeyMaterial); + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/lib.rs b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs new file mode 100644 index 000000000..f969d011b --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs @@ -0,0 +1,45 @@ +//! # OneKey Monero Runtime +//! +//! monero-oxide 提供密码学、扫描器与交易构造;**它不提供任何存储**。 +//! 这个 crate 就是缺的那一层:把扫描产出的输出落进 SQLite,并支持查询。 +//! +//! ## 为什么不是 monero-ts +//! +//! 那条路把整个钱包放在 wasm 内存里,持久化只能 `getData()` 整块序列化再写出去 +//! —— 历史越长每次保存越贵,且写一半崩了丢的是全部。这里走增量写 + 事务, +//! 和 Zcash runtime 同一个模型。 +//! +//! ## 设计边界 +//! +//! 留在 Rust 这一侧的只有三类:密码学与协议、平台胶水(存储 VFS、时钟)、 +//! 形状转换(Rust 富类型 → JSON)。**调度不在这里** —— 什么时候扫、扫哪一段, +//! 由宿主 TS 决定。 + +pub mod blocks_bin; +pub mod error; +pub mod keys; +pub mod network; +pub mod perf; +pub mod pool; +pub mod query; +pub mod runtime; +pub mod scan; +pub mod schema; +pub mod spend; +pub mod storage; +pub mod sync; +pub mod wallet; + +pub use error::{ErrorCode, Result, RuntimeError}; + +#[cfg(target_arch = "wasm32")] +pub mod bindgen; + +/// 本 runtime 锁定的上游版本,供宿主自检与日志使用。 +pub fn dependency_versions() -> serde_json::Value { + serde_json::json!({ + "monero-wallet": "0.2.0", + "monero-address": "0.1.0", + "runtime": env!("CARGO_PKG_VERSION"), + }) +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/network.rs b/chain-runtimes/monero/crates/monero-runtime/src/network.rs new file mode 100644 index 000000000..f5d02a9f6 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/network.rs @@ -0,0 +1,495 @@ +//! 连 monerod 的传输层。 +//! +//! 上游 `monero-daemon-rpc` 把网络抽象成一个 trait,只有一个方法: +//! `post(route, body, size_limit) -> Vec`。二进制 RPC 与 epee 解析全在 +//! 上游 —— 我们只要把字节搬进搬出。 +//! +//! ## `Send` 的问题 +//! +//! 上游签名要求 `post` 返回 `impl Send + Future`,而浏览器 `fetch` 产出的 +//! future **不是** `Send`(它持有 JS 值,JS 值绑在它所在的线程上)。 +//! +//! wasm32-unknown-unknown 在我们的构建下没有 atomics、没有线程,整个模块跑在 +//! 一个 Worker 里,`Send` 这个约束在那里**没有可被违反的语义**。所以用一层 +//! 断言包装是成立的 —— 但仅限这个目标,见 [`SingleThreaded`] 上的安全性说明。 + +use monero_daemon_rpc::{HttpTransport, MoneroDaemon}; +use monero_interface::InterfaceError; +use serde_json::json; + +use crate::error::{net_err, ErrorCode, Result, RuntimeError}; + +/// 单次请求的默认超时。 +/// +/// 这是**停滞**超时,不是整批的截止时间:块流只要还在推进就不判死。 +pub const DEFAULT_TIMEOUT_MS: u32 = 30_000; + +/// 响应体上限,防一个恶意节点用超大响应把 wasm 堆撑爆。 +/// 取 32 MB —— spam 墙区段一批块可达几十 MB,留够余量但不无界。 +pub const MAX_RESPONSE_BYTES: usize = 32 * 1024 * 1024; + +/// monerod 按路由区分 Content-Type。 +/// +/// 我一开始给所有路由都发 `application/octet-stream` 并在注释里断言「JSON +/// 路由也接受」—— **那是错的**,`/json_rpc` 会直接拒掉,表现为连接阶段就 +/// 失败而看不出原因。二进制路由以 `.bin` 结尾,其余走 JSON。 +fn content_type_for(route: &str) -> &'static str { + if route.ends_with(".bin") { + "application/octet-stream" + } else { + "application/json" + } +} + +/// 把一个 `!Send` 的 future 断言成 `Send`。 +/// +/// # 安全性 +/// +/// **只在 wasm32 上编译。** 该目标在本工程的构建配置下没有 atomics、没有 +/// 线程:产物跑在单个 Worker 里,不存在第二个线程能观察到这个 future。 +/// `Send` 在那里不约束任何真实行为。 +/// +/// 哪天这个 crate 要支持 wasm 线程(atomics + SharedArrayBuffer),**这一层 +/// 必须先去掉**,否则就是真正的数据竞争。 +#[cfg(target_arch = "wasm32")] +struct SingleThreaded(F); + +#[cfg(target_arch = "wasm32")] +// SAFETY: 见上方说明 —— 目标平台单线程,无第二个线程可观察。 +unsafe impl Send for SingleThreaded {} + +#[cfg(target_arch = "wasm32")] +impl core::future::Future for SingleThreaded { + type Output = F::Output; + fn poll( + self: core::pin::Pin<&mut Self>, + cx: &mut core::task::Context<'_>, + ) -> core::task::Poll { + // SAFETY: 只是把 pin 投影到唯一字段上,不移动它。 + unsafe { self.map_unchecked_mut(|s| &mut s.0).poll(cx) } + } +} + +/// 响应体上限检查,宿主通道与 wasm 内 fetch 共用。 +/// +/// 防一个恶意节点用超大响应把 wasm 堆撑爆。两条路都拿不到流式截断,只能收完 +/// 再判 —— 但至少不会把它交给解析器再翻一倍。 +#[cfg(target_arch = "wasm32")] +fn cap_response( + bytes: Vec, + limit: Option, +) -> std::result::Result, InterfaceError> { + let cap = limit.unwrap_or(MAX_RESPONSE_BYTES).min(MAX_RESPONSE_BYTES); + if bytes.len() > cap { + return Err(InterfaceError::InvalidInterface("响应超出大小上限".into())); + } + Ok(bytes) +} + +// 宿主提供的请求处理器。 +// +// ## 为什么要把网络交给宿主 +// +// 在 wasm 里 `fetch`,请求就是从浏览器上下文发出去的,于是受两条浏览器规则 +// 管:混合内容(明文 HTTP 节点直接被拦)和 CORS(monerod 默认不发 +// `Access-Control-Allow-Origin`,要运维自己加反代)。 +// +// 结果是全网几百个活着的公共节点里我们只能用个位数 —— 2026-09-22 实测 12 家, +// 只有 1 家同时满足。让一条隐私链的所有用户共用一个第三方节点,等于把用户 +// 来这里要的东西还回去:那个运营方看得见每个人的 IP、同步区间和广播时机。 +// +// **这和性能无关。** 纯扫描 153 块/秒、只占总耗时 0.4%。受限的是可达性不是 +// 速度,所以解法不是换原生,是把请求交出去。 +// +// 这两条规则只管浏览器上下文。插件的 background(配 `host_permissions`)、 +// 桌面的 Electron 主进程、移动端的 RN 原生都不受管。 +// +// 宿主不装时退回 wasm 内 fetch,行为与以前完全一致 —— 增量改动。 +#[cfg(target_arch = "wasm32")] +thread_local! { + static HOST_HANDLER: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// 装上宿主的请求处理器。传 `None` 卸载,退回 wasm 内 fetch。 +/// +/// 处理器签名:`(url, contentType, body: Uint8Array) => Promise`。 +/// 抛出或 reject 都当作网络错误上报,原因原样带出。 +#[cfg(target_arch = "wasm32")] +pub fn set_host_handler(handler: Option) { + HOST_HANDLER.with(|slot| *slot.borrow_mut() = handler); +} + +#[cfg(target_arch = "wasm32")] +fn host_handler() -> Option { + HOST_HANDLER.with(|slot| slot.borrow().clone()) +} + +/// 走宿主通道发一次请求。 +#[cfg(target_arch = "wasm32")] +async fn post_via_host( + handler: js_sys::Function, + url: &str, + content_type: &str, + body: &[u8], +) -> std::result::Result, InterfaceError> { + use wasm_bindgen::{JsCast, JsValue}; + use wasm_bindgen_futures::JsFuture; + + let fail = |stage: &str, detail: String| { + InterfaceError::InterfaceError(format!("{url}: 宿主通道 {stage}: {detail}")) + }; + + let array = js_sys::Uint8Array::from(body); + let returned = handler + .call3( + &JsValue::NULL, + &JsValue::from_str(url), + &JsValue::from_str(content_type), + &array, + ) + .map_err(|e| fail("调用", describe_js(&e)))?; + + // 同步返回字节或返回 Promise 都接受 —— 宿主那边怎么写都行。 + let resolved = match returned.dyn_into::() { + Ok(promise) => JsFuture::from(promise) + .await + .map_err(|e| fail("等待响应", describe_js(&e)))?, + Err(value) => value, + }; + + let bytes = resolved + .dyn_into::() + .map_err(|_| fail("返回值", "宿主必须回 Uint8Array".to_owned()))?; + Ok(bytes.to_vec()) +} + +/// 把一个 JS 侧的异常压成一句人能读的话。 +/// +/// `JsValue` 的 Debug 输出对排障几乎没用,而 `Error.message` 恰恰是浏览器把 +/// 真实原因(DNS 失败、CORS 被拒、连接被重置)写进去的地方。 +#[cfg(target_arch = "wasm32")] +fn describe_js(value: &wasm_bindgen::JsValue) -> String { + use wasm_bindgen::JsValue; + js_sys::Reflect::get(value, &JsValue::from_str("message")) + .ok() + .and_then(|m| m.as_string()) + .or_else(|| value.as_string()) + .unwrap_or_else(|| format!("{value:?}")) +} + +/// 单次请求的上限。一整批块在慢节点上要十几秒,留足余量。 +#[cfg(target_arch = "wasm32")] +const REQUEST_TIMEOUT_MS: u32 = 45_000; + +/// 浏览器载体里的传输实现,基于 `fetch`。 +#[cfg(target_arch = "wasm32")] +#[derive(Clone, Debug)] +pub struct FetchTransport { + base_url: String, +} + +#[cfg(target_arch = "wasm32")] +impl FetchTransport { + pub fn new(base_url: &str) -> Self { + Self { + base_url: base_url.trim_end_matches('/').to_owned(), + } + } + + /// 有上限地等一次请求。卡住的请求会让这一步一直占着钱包库,之后的每次调用 + /// 都只能拿到 WALLET_BUSY;超时后放手,请求本身在后台自生自灭。 + async fn post_inner( + base_url: String, + route: String, + body: Vec, + limit: Option, + ) -> std::result::Result, InterfaceError> { + use futures_util::future::{select, Either}; + + let url = format!("{base_url}/{}", route.trim_start_matches('/')); + let request = Box::pin(Self::post_untimed(base_url, route, body, limit)); + let timeout = gloo_timers::future::TimeoutFuture::new(REQUEST_TIMEOUT_MS); + match select(request, timeout).await { + Either::Left((result, _)) => result, + Either::Right(_) => Err(InterfaceError::InterfaceError(format!( + "{url}: {} 秒没有响应", + REQUEST_TIMEOUT_MS / 1000 + ))), + } + } + + async fn post_untimed( + base_url: String, + route: String, + body: Vec, + limit: Option, + ) -> std::result::Result, InterfaceError> { + use wasm_bindgen::{JsCast, JsValue}; + use wasm_bindgen_futures::JsFuture; + + let url = format!("{base_url}/{}", route.trim_start_matches('/')); + let content_type = content_type_for(&route); + + // 宿主装了处理器就交给它 —— 那条路不受浏览器的混合内容与 CORS 限制, + // 因此能用全网任意节点。没装则退回下面的 wasm 内 fetch。 + if let Some(handler) = host_handler() { + let bytes = post_via_host(handler, &url, content_type, &body).await?; + return cap_response(bytes, limit); + } + + // 每一步都带上自己的原因。九个失败点共用一句「请求失败」,就是把 + // 「节点挂了」「节点没开 CORS」「地址写错了」「响应体读不动」压成 + // 同一条信息 —— 而这几种情况用户要做的事完全不同。 + let fail = |stage: &str, detail: String| { + InterfaceError::InterfaceError(format!("{url}: {stage}: {detail}")) + }; + + let opts = web_sys::RequestInit::new(); + opts.set_method("POST"); + let array = js_sys::Uint8Array::from(body.as_slice()); + opts.set_body(&array); + + let request = web_sys::Request::new_with_str_and_init(&url, &opts) + .map_err(|e| fail("构造请求", describe_js(&e)))?; + let _ = request.headers().set("Content-Type", content_type); + + let global = js_sys::global(); + let fetch = js_sys::Reflect::get(&global, &JsValue::from_str("fetch")) + .ok() + .and_then(|f| f.dyn_into::().ok()) + .ok_or_else(|| { + fail( + "取 fetch", + "当前环境没有全局 fetch(载体没装好,不是节点的问题)".to_owned(), + ) + })?; + let promise = fetch + .call1(&global, &request) + .map_err(|e| fail("发起请求", describe_js(&e)))? + .dyn_into::() + .map_err(|e| fail("发起请求", describe_js(&e)))?; + + let response = JsFuture::from(promise) + .await + // 走到这里基本只有两种:网络不通,或者节点没回 CORS 头。浏览器 + // 出于安全不会告诉我们是哪种,所以把两种可能都写出来。 + .map_err(|e| { + fail( + "等待响应", + format!("{}(节点不可达,或者没有返回 CORS 头)", describe_js(&e)), + ) + })? + .dyn_into::() + .map_err(|e| fail("解析响应", describe_js(&e)))?; + + if !response.ok() { + return Err(fail( + "节点拒绝", + format!("HTTP {} {}", response.status(), response.status_text()), + )); + } + + let buffer = JsFuture::from( + response + .array_buffer() + .map_err(|e| fail("读取响应体", describe_js(&e)))?, + ) + .await + .map_err(|e| fail("读取响应体", describe_js(&e)))?; + + cap_response(js_sys::Uint8Array::new(&buffer).to_vec(), limit) + } +} + +#[cfg(target_arch = "wasm32")] +impl HttpTransport for FetchTransport { + fn post( + &self, + route: &str, + body: Vec, + response_size_limit: Option, + ) -> impl Send + core::future::Future, InterfaceError>> + { + SingleThreaded(Self::post_inner( + self.base_url.clone(), + route.to_owned(), + body, + response_size_limit, + )) + } +} + +/// 原生传输,用于本机测试与诊断 —— 浏览器里出的问题可以在这边上真调试器复现。 +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Debug)] +pub struct NativeTransport { + base_url: String, + client: reqwest::Client, +} + +#[cfg(not(target_arch = "wasm32"))] +impl NativeTransport { + pub fn new(base_url: &str) -> Self { + Self { + base_url: base_url.trim_end_matches('/').to_owned(), + client: { + let builder = reqwest::Client::builder().timeout(std::time::Duration::from_millis( + u64::from(DEFAULT_TIMEOUT_MS), + )); + // reqwest 默认读 macOS 系统代理,curl 与 Node 不读。本机真链测试里 + // 同一节点 curl 秒回、这里却次次卡满超时时,用它排除代理的影响。 + let builder = if std::env::var_os("XMR_NATIVE_NO_PROXY").is_some() { + builder.no_proxy() + } else { + builder + }; + builder.build().unwrap_or_default() + }, + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl HttpTransport for NativeTransport { + fn post( + &self, + route: &str, + body: Vec, + response_size_limit: Option, + ) -> impl Send + core::future::Future, InterfaceError>> + { + let url = format!("{}/{}", self.base_url, route.trim_start_matches('/')); + let content_type = content_type_for(route); + let client = self.client.clone(); + async move { + // 把真实原因带出来。一律吞成「请求失败」会让排查完全没有抓手 —— + // 连不上、404、超时、TLS 失败在现象上一模一样。 + let response = client + .post(&url) + .header("Content-Type", content_type) + .body(body) + .send() + .await + .map_err(|e| { + // reqwest 的顶层文案只有 "error sending request",真正原因 + // (超时、TLS、连接被重置、DNS)在 source 链里。 + let mut chain = e.to_string(); + let mut source = std::error::Error::source(&e); + while let Some(inner) = source { + chain.push_str(" <- "); + chain.push_str(&inner.to_string()); + source = inner.source(); + } + InterfaceError::InterfaceError(format!("POST {url}: {chain}")) + })?; + let status = response.status(); + if !status.is_success() { + let body = response.text().await.unwrap_or_default(); + return Err(InterfaceError::InterfaceError(format!( + "POST {url} -> {status}: {}", + body.chars().take(200).collect::() + ))); + } + let bytes = response + .bytes() + .await + .map_err(|e| InterfaceError::InterfaceError(format!("读取 {url} 的响应体: {e}")))? + .to_vec(); + let cap = response_size_limit + .unwrap_or(MAX_RESPONSE_BYTES) + .min(MAX_RESPONSE_BYTES); + if bytes.len() > cap { + return Err(InterfaceError::InvalidInterface("响应超出大小上限".into())); + } + Ok(bytes) + } + } +} + +#[cfg(target_arch = "wasm32")] +pub type Transport = FetchTransport; +#[cfg(not(target_arch = "wasm32"))] +pub type Transport = NativeTransport; + +pub type Daemon = MoneroDaemon; + +/// 连上一个 monerod 节点。 +/// +/// 节点地址**由宿主给**,这里没有内置默认值 —— 内置一个默认节点等于替用户 +/// 决定把自己的 IP 和查询交给谁,那是隐私决策,不该藏在 runtime 里。 +pub async fn connect(base_url: &str) -> Result { + if base_url.trim().is_empty() { + return Err(RuntimeError::new(ErrorCode::NodeNotConfigured)); + } + if !(base_url.starts_with("http://") || base_url.starts_with("https://")) { + return Err(RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "nodeUrl", "reason": "schemeMustBeHttpOrHttps" }), + )); + } + let daemon = MoneroDaemon::new(Transport::new(base_url)) + .await + .map_err(|e| net_err("connect", format!("{e:?}")))?; + CURRENT_NODE_URL.with(|c| *c.borrow_mut() = Some(base_url.to_owned())); + Ok(daemon) +} + +thread_local! { + /// 当前连着的节点地址。批量取块(blocks_bin)要自己发请求,而 + /// `MoneroDaemon` 不把传输层交出来。 + static CURRENT_NODE_URL: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +pub fn current_node_url() -> Option { + CURRENT_NODE_URL.with(|c| c.borrow().clone()) +} + +pub fn forget_node_url() { + CURRENT_NODE_URL.with(|c| *c.borrow_mut() = None); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 不内置默认节点:内置一个等于替用户决定把 IP 和查询交给谁。 + #[test] + fn an_empty_node_url_is_refused_not_defaulted() { + let e = futures_lite::future::block_on(connect("")).unwrap_err(); + assert_eq!(e.code, ErrorCode::NodeNotConfigured); + let e = futures_lite::future::block_on(connect(" ")).unwrap_err(); + assert_eq!(e.code, ErrorCode::NodeNotConfigured); + } + + /// 协议头必须显式。给个 `1.2.3.4:18081` 会被当成相对路径拼出乱七八糟的 + /// URL,错误现场离真正的原因很远。 + #[test] + fn the_node_url_must_carry_a_scheme() { + for bad in ["1.2.3.4:18081", "node.example.com", "ftp://x"] { + let e = futures_lite::future::block_on(connect(bad)).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidRequest, "{bad}"); + } + } + + /// 路由决定 Content-Type。发错会让 `/json_rpc` 在连接阶段就被拒, + /// 而错误现场离真正的原因很远 —— 这条踩过。 + #[test] + fn json_and_binary_routes_get_different_content_types() { + assert_eq!(content_type_for("json_rpc"), "application/json"); + assert_eq!(content_type_for("get_transactions"), "application/json"); + assert_eq!( + content_type_for("get_blocks.bin"), + "application/octet-stream" + ); + assert_eq!(content_type_for("get_outs.bin"), "application/octet-stream"); + } + + #[test] + fn response_cap_never_exceeds_the_hard_limit() { + // 宿主传一个比硬上限还大的值时,以硬上限为准 + let requested = MAX_RESPONSE_BYTES * 4; + assert_eq!(requested.min(MAX_RESPONSE_BYTES), MAX_RESPONSE_BYTES); + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/perf.rs b/chain-runtimes/monero/crates/monero-runtime/src/perf.rs new file mode 100644 index 000000000..1436948b5 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/perf.rs @@ -0,0 +1,20 @@ +//! 计时打点。 +//! +//! 扫得慢的时候,「慢在拉块还是慢在解密」是完全不同的两件事,而在浏览器里 +//! 两者的表现一模一样(界面不动)。实测公共节点单次 RPC 往返可达 490ms, +//! 不把两段分开量,就会把网络延迟误判成算力不足 —— 那会让整条技术路线的 +//! 结论反过来。 + +#[cfg(target_arch = "wasm32")] +pub fn now_ms() -> f64 { + js_sys::Date::now() +} + +#[cfg(not(target_arch = "wasm32"))] +pub fn now_ms() -> f64 { + use std::time::{SystemTime, UNIX_EPOCH}; + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs_f64() * 1000.0) + .unwrap_or(0.0) +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/pool.rs b/chain-runtimes/monero/crates/monero-runtime/src/pool.rs new file mode 100644 index 000000000..4179f8aa4 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/pool.rs @@ -0,0 +1,232 @@ +//! 自己广播、还没上链的交易是否还活着。 +//! +//! 照 wallet2 `process_unconfirmed_transfer`:广播超过 [`TX_PROPAGATION_TIMEOUT_SECS`] +//! 仍然不在节点那里,判失败,把它花的输出放回可用。不放的话那笔钱永远锁着。 +//! +//! 上链的不归这里管:扫描按 key image 认出来,交易行自然拿到高度(也会清掉失败标记)。 + +use rusqlite::params; +use serde_json::Value; + +use crate::error::{db_err, Result}; +use crate::network::Daemon; +use crate::wallet::{now_secs, Db}; + +/// wallet2 同值。短于 Dandelion++ 的扩散时间会把刚发的交易误判失败。 +pub const TX_PROPAGATION_TIMEOUT_SECS: i64 = 500; + +/// 同一笔在途交易两次询问节点的最小间隔。扫链一步几秒一次,不能每步都问。 +const POOL_RECHECK_SECS: i64 = 60; + +const RESPONSE_SIZE_LIMIT: usize = 4 * 1024 * 1024; + +/// 该问节点的在途交易:已过扩散期、没判过失败、最近没问过。 +fn due_pending(db: &Db, identity_id: i64, now: i64) -> Result> { + let mut stmt = db + .conn() + .prepare( + "SELECT txid FROM transactions + WHERE identity_id = ?1 AND height IS NULL AND failed = 0 + AND sent_at IS NOT NULL AND sent_at + ?2 <= ?3 + AND (pool_checked_at IS NULL OR pool_checked_at + ?4 <= ?3)", + ) + .map_err(|e| db_err("duePending", e))?; + let rows = stmt + .query_map( + params![ + identity_id, + TX_PROPAGATION_TIMEOUT_SECS, + now, + POOL_RECHECK_SECS + ], + |r| r.get::<_, Vec>(0), + ) + .map_err(|e| db_err("duePending", e))? + .collect::>>() + .map_err(|e| db_err("duePending", e))?; + Ok(rows + .into_iter() + .filter_map(|v| <[u8; 32]>::try_from(v.as_slice()).ok()) + .collect()) +} + +/// 节点明确说不认识的交易。回包不像样就一个都不算 —— 宁可晚判,不可误判。 +fn missed_in(response: &str) -> Option> { + let v: Value = serde_json::from_str(response).ok()?; + if v.get("status").and_then(Value::as_str) != Some("OK") { + return None; + } + // epee 对空数组可能直接省略字段 + let Some(missed) = v.get("missed_tx") else { + return Some(Vec::new()); + }; + missed + .as_array()? + .iter() + .map(|h| { + let bytes = hex::decode(h.as_str()?).ok()?; + <[u8; 32]>::try_from(bytes.as_slice()).ok() + }) + .collect() +} + +fn mark_checked(db: &Db, identity_id: i64, txids: &[[u8; 32]], now: i64) -> Result<()> { + for txid in txids { + db.conn() + .execute( + "UPDATE transactions SET pool_checked_at = ?3 WHERE identity_id = ?1 AND txid = ?2", + params![identity_id, txid.as_slice(), now], + ) + .map_err(|e| db_err("markPoolChecked", e))?; + } + Ok(()) +} + +/// 判失败:交易留着(历史里显示失败),它花的输出放回可用。 +/// +/// `spent_in_txid` 保留:这条失败交易的金额还要靠它算;将来这笔输出被别的交易 +/// 花掉时会被覆盖。 +pub(crate) fn mark_failed(db: &Db, identity_id: i64, txid: &[u8; 32]) -> Result<()> { + let tx = db + .conn() + .unchecked_transaction() + .map_err(|e| db_err("beginMarkFailed", e))?; + tx.execute( + "UPDATE transactions SET failed = 1 + WHERE identity_id = ?1 AND txid = ?2 AND height IS NULL", + params![identity_id, txid.as_slice()], + ) + .map_err(|e| db_err("markSendFailed", e))?; + tx.execute( + "UPDATE outputs SET spent_at_height = NULL + WHERE identity_id = ?1 AND spent_in_txid = ?2", + params![identity_id, txid.as_slice()], + ) + .map_err(|e| db_err("releaseFailedInputs", e))?; + tx.commit().map_err(|e| db_err("commitMarkFailed", e)) +} + +/// 问一次节点,把不在的判失败。返回判了几笔。 +/// +/// 节点不可达或回包异常时什么都不改:失败判定只能来自节点明确的「不认识」。 +pub async fn check_pending(db: &Db, daemon: &Daemon, identity_id: i64) -> Result { + let now = now_secs(); + let due = due_pending(db, identity_id, now)?; + if due.is_empty() { + return Ok(0); + } + let hashes: Vec = due.iter().map(hex::encode).collect(); + let request = serde_json::json!({ "txs_hashes": hashes, "prune": true }).to_string(); + let Ok(response) = daemon + .rpc_call("get_transactions", Some(request), RESPONSE_SIZE_LIMIT) + .await + else { + return Ok(0); + }; + let Some(missed) = missed_in(&response) else { + return Ok(0); + }; + mark_checked(db, identity_id, &due, now)?; + let mut failed = 0; + for txid in missed.iter().filter(|t| due.contains(t)) { + mark_failed(db, identity_id, txid)?; + failed += 1; + } + Ok(failed) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wallet::testing::db_with_identity; + + fn add_pending_send(db: &Db, id: i64, txid: [u8; 32], sent_at: i64) -> i64 { + db.conn() + .execute( + "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, + amount_atomic, height, key_image, spent_at_height, spent_in_txid) + VALUES (?1, x'00', ?2, 1, 0, 700, 10, ?3, 500, ?4)", + params![ + id, + [txid[0] ^ 0xFF; 32].as_slice(), + [txid[0]; 32].as_slice(), + txid.as_slice() + ], + ) + .unwrap(); + let output = db.conn().last_insert_rowid(); + db.conn() + .execute( + "INSERT INTO transactions (identity_id, txid, height, direction, sent_at) + VALUES (?1, ?2, NULL, 'out', ?3)", + params![id, txid.as_slice(), sent_at], + ) + .unwrap(); + output + } + + #[test] + fn only_sends_past_the_propagation_timeout_are_asked_about() { + let (db, id) = db_with_identity(); + let now = 10_000; + add_pending_send(&db, id, [2u8; 32], now - TX_PROPAGATION_TIMEOUT_SECS - 1); + add_pending_send(&db, id, [3u8; 32], now - 10); + + assert_eq!(due_pending(&db, id, now).unwrap(), vec![[2u8; 32]]); + + mark_checked(&db, id, &[[2u8; 32]], now).unwrap(); + assert!(due_pending(&db, id, now + 1).unwrap().is_empty(), "刚问过"); + assert_eq!( + due_pending(&db, id, now + POOL_RECHECK_SECS).unwrap(), + vec![[2u8; 32]] + ); + } + + #[test] + fn a_send_the_node_does_not_know_releases_its_inputs() { + let (db, id) = db_with_identity(); + let txid = [2u8; 32]; + let output = add_pending_send(&db, id, txid, 0); + + mark_failed(&db, id, &txid).unwrap(); + + let (failed, height): (i64, Option) = db + .conn() + .query_row( + "SELECT failed, height FROM transactions WHERE txid = ?1", + [txid.as_slice()], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .unwrap(); + assert_eq!((failed, height), (1, None)); + let spent_at: Option = db + .conn() + .query_row( + "SELECT spent_at_height FROM outputs WHERE id = ?1", + [output], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(spent_at, None, "输出回到可用"); + assert!( + due_pending(&db, id, i64::MAX / 2).unwrap().is_empty(), + "判过就不再问" + ); + } + + #[test] + fn only_a_clear_answer_from_the_node_counts() { + let tx = hex::encode([2u8; 32]); + assert_eq!( + missed_in(&format!(r#"{{"status":"OK","missed_tx":["{tx}"]}}"#)), + Some(vec![[2u8; 32]]) + ); + assert_eq!( + missed_in(r#"{"status":"OK","txs":[{"in_pool":true}]}"#), + Some(vec![]) + ); + assert_eq!(missed_in(r#"{"status":"BUSY","missed_tx":[]}"#), None); + assert_eq!(missed_in("not json"), None); + assert_eq!(missed_in(r#"{"status":"OK","missed_tx":["zz"]}"#), None); + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/query.rs b/chain-runtimes/monero/crates/monero-runtime/src/query.rs new file mode 100644 index 000000000..21f20d386 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs @@ -0,0 +1,558 @@ +//! 余额、历史与可花输出的查询。 +//! +//! 这一层是选 SQLite 而非内存方案的**直接兑现**:分页、按高度筛选、按子地址 +//! 聚合都是索引查询,不是在内存对象上过滤。历史再长也不需要把全部数据读进来。 + +use monero_wallet::WalletOutput; +use rusqlite::{params, OptionalExtension}; +use serde_json::{json, Value}; + +use crate::error::{db_err, ErrorCode, Result, RuntimeError}; +use crate::wallet::Db; + +/// Monero 协议对**所有**输出的固定锁定期:10 个确认。 +/// +/// 这不是我们的策略,是共识规则 —— 未满 10 块的输出构不进环,节点会拒。 +/// 额外时间锁(`additional_timelock`)是在这之上的附加约束。 +pub const COINBASE_AND_STANDARD_LOCK: u64 = 10; + +#[derive(Debug, Default, Clone)] +pub struct Balance { + /// 全部未花输出之和。 + pub total_atomic: u128, + /// 其中当前可花的部分(已过 10 块锁定且额外时间锁已满足,且未被预留)。 + pub unlocked_atomic: u128, + /// 被在途交易预留的部分。已计入 total,但不可再次选中。 + pub locked_by_reservation_atomic: u128, + /// 待核实:还没有 key image、又出现在某个环里的输出金额。**这部分可能已经 + /// 被花掉**,要等宿主补算 key image 才知道;从没进过环的一定没花,不算在内。 + pub unverifiable_atomic: u128, + /// 自己发出、还没上链的交易的找零。已计入 total(锁定,不可花),wallet2 同款。 + pub pending_change_atomic: u128, + /// 还没有 key image 的未花输出笔数。大于 0 时发送前要先补算 key image + /// (选币只选有 key image 的输出)。 + pub outputs_without_key_image: u64, +} + +impl Balance { + pub fn to_json(&self) -> Value { + // 金额一律用字符串跨边界:piconero 的上限超过 JS 的 + // Number.MAX_SAFE_INTEGER,走数字会静默丢精度。 + json!({ + "totalAtomic": self.total_atomic.to_string(), + "unlockedAtomic": self.unlocked_atomic.to_string(), + "lockedByReservationAtomic": self.locked_by_reservation_atomic.to_string(), + "unverifiableAtomic": self.unverifiable_atomic.to_string(), + "pendingChangeAtomic": self.pending_change_atomic.to_string(), + "outputsWithoutKeyImage": self.outputs_without_key_image, + }) + } +} + +/// 算余额。`chain_tip` 用于判断锁定期;给 `None` 表示还不知道链尖, +/// 此时一律按「未解锁」处理 —— 宁可显示 0 可用,也不要让用户去花一笔构不进环的钱。 +pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result { + let mut stmt = db + .conn() + .prepare( + "SELECT o.amount_atomic, o.height, o.additional_timelock, + o.key_image IS NULL AS no_ki, + l.output_id IS NOT NULL AS reserved, + EXISTS (SELECT 1 FROM possible_spends p + WHERE p.identity_id = o.identity_id + AND p.out_txid = o.txid AND p.out_index = o.index_in_tx) AS maybe_spent + FROM outputs o + LEFT JOIN locked_outputs l ON l.output_id = o.id AND l.locked_at > ?2 + WHERE o.identity_id = ?1 AND o.spent_at_height IS NULL", + ) + .map_err(|e| db_err("balanceQuery", e))?; + + let rows = stmt + .query_map( + params![identity_id, crate::spend::reservation_cutoff()], + |r| { + Ok(( + r.get::<_, i64>(0)? as u128, + r.get::<_, i64>(1)? as u64, + r.get::<_, i64>(2)? as u64, + r.get::<_, bool>(3)?, + r.get::<_, bool>(4)?, + r.get::<_, bool>(5)?, + )) + }, + ) + .map_err(|e| db_err("balanceQuery", e))?; + + let mut b = Balance::default(); + for row in rows { + let (amount, height, timelock, no_key_image, reserved, maybe_spent) = + row.map_err(|e| db_err("balanceQuery", e))?; + b.total_atomic += amount; + if no_key_image { + b.outputs_without_key_image += 1; + } + // 没进过任何环的钱一定没花;只有进过环、又还没 key image 的才待核实。 + // 待核实的不算可用:它可能已经花掉了。 + if no_key_image && maybe_spent { + b.unverifiable_atomic += amount; + continue; + } + if reserved { + b.locked_by_reservation_atomic += amount; + continue; + } + if let Some(tip) = chain_tip { + if is_unlocked(height, timelock, tip) { + b.unlocked_atomic += amount; + } + } + } + // 在途交易的找零:上链扫到前不在 outputs 里,但它是用户的钱。 + let change: Vec> = db + .conn() + .prepare( + "SELECT change_atomic FROM transactions + WHERE identity_id = ?1 AND direction = 'out' AND height IS NULL AND failed = 0", + ) + .and_then(|mut stmt| { + stmt.query_map(params![identity_id], |r| r.get(0))? + .collect::>>() + }) + .map_err(|e| db_err("pendingChangeQuery", e))?; + for value in change.into_iter().flatten() { + if let Ok(amount) = value.parse::() { + b.pending_change_atomic += amount; + } + } + b.total_atomic += b.pending_change_atomic; + Ok(b) +} + +/// 一笔输出此刻能不能花。 +/// +/// 两个条件都要满足:过了协议固定的 10 块锁定;额外时间锁(若有)也已过。 +/// `additional_timelock` 存的是原始值 —— 小于 5 亿按块高解释,否则按 Unix +/// 时间戳解释,这是 Monero 的约定(`CRYPTONOTE_MAX_BLOCK_NUMBER`)。 +pub fn is_unlocked(height: u64, additional_timelock: u64, chain_tip: u64) -> bool { + const MAX_BLOCK_NUMBER: u64 = 500_000_000; + + if chain_tip < height + COINBASE_AND_STANDARD_LOCK { + return false; + } + if additional_timelock == 0 { + return true; + } + if additional_timelock < MAX_BLOCK_NUMBER { + chain_tip >= additional_timelock + } else { + // 时间戳形式的锁没法只靠链高判断。保守处理:**当作仍锁定**。 + // 让用户等,比让他构一笔必然被拒的交易好。 + false + } +} + +/// 一笔可花输出的**元信息**,不含反序列化后的密码学对象。 +/// +/// 筛选与展示只需要这些列。把 blob 的反序列化推迟到真正要构造交易的那一刻, +/// 免得为了挑两个输出把五百个都解一遍 —— 那是内存方案的毛病,不该在这里复现。 +#[derive(Debug, Clone)] +pub struct SpendableRow { + pub id: i64, + pub amount_atomic: u64, + pub global_index: u64, + pub height: u64, +} + +/// 取当前可花的输出元信息,金额降序(大额优先,减少输入数量从而降低手续费)。 +/// +/// 只返回**有 key image** 的输出:没有 key image 就无法确认它没被花掉, +/// 拿它构造交易有双花风险,节点会拒。 +pub fn spendable_rows(db: &Db, identity_id: i64, chain_tip: u64) -> Result> { + let mut stmt = db + .conn() + .prepare( + "SELECT o.id, o.amount_atomic, o.global_index, o.height, o.additional_timelock + FROM outputs o + LEFT JOIN locked_outputs l ON l.output_id = o.id AND l.locked_at > ?2 + WHERE o.identity_id = ?1 + AND o.spent_at_height IS NULL + AND o.key_image IS NOT NULL + AND l.output_id IS NULL + ORDER BY o.amount_atomic DESC", + ) + .map_err(|e| db_err("spendableRows", e))?; + + let rows = stmt + .query_map( + params![identity_id, crate::spend::reservation_cutoff()], + |r| { + Ok(( + r.get::<_, i64>(0)?, + r.get::<_, i64>(1)? as u64, + r.get::<_, i64>(2)? as u64, + r.get::<_, i64>(3)? as u64, + r.get::<_, i64>(4)? as u64, + )) + }, + ) + .map_err(|e| db_err("spendableRows", e))?; + + let mut out = Vec::new(); + for row in rows { + let (id, amount_atomic, global_index, height, timelock) = + row.map_err(|e| db_err("spendableRows", e))?; + if !is_unlocked(height, timelock, chain_tip) { + continue; + } + out.push(SpendableRow { + id, + amount_atomic, + global_index, + height, + }); + } + Ok(out) +} + +/// 把一笔输出的 blob 读回成 monero-oxide 的对象。 +/// +/// **参与密码学的一律走这里**。`outputs` 表上那些抽出来的列只用于筛选与展示, +/// 不是另一份真相 —— 拿它们去重建对象就是在自己实现一遍序列化,早晚出错。 +/// +/// blob 读不回来意味着库损坏,明确报错而不是跳过:静默跳过会表现为 +/// 「这笔钱凭空消失」,比报错难查得多。 +pub fn load_output(db: &Db, output_id: i64) -> Result { + let blob: Vec = db + .conn() + .query_row("SELECT blob FROM outputs WHERE id = ?1", [output_id], |r| { + r.get(0) + }) + .optional() + .map_err(|e| db_err("loadOutput", e))? + .ok_or_else(|| { + RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "outputId", "value": output_id }), + ) + })?; + + WalletOutput::read(&mut blob.as_slice()).map_err(|e| { + db_err( + "deserializeOutput", + format!("输出 {output_id} 的 blob 读不回来: {e}"), + ) + }) +} + +/// 交易历史,按高度倒序分页。 +pub fn history(db: &Db, identity_id: i64, limit: u32, offset: u32) -> Result { + // 限制上界:宿主传个巨大的 limit 会把整段历史读进内存,那正是我们选 + // SQLite 想避免的事。 + let limit = limit.clamp(1, 500); + + let mut stmt = db + .conn() + .prepare( + "SELECT t.txid, t.height, t.direction, + COALESCE((SELECT sum(amount_atomic) FROM outputs + WHERE identity_id = t.identity_id AND txid = t.txid), 0) AS received, + COALESCE((SELECT sum(amount_atomic) FROM outputs + WHERE identity_id = t.identity_id AND spent_in_txid = t.txid), 0) AS spent, + COALESCE(t.timestamp, b.timestamp, t.sent_at), t.failed, t.outgoing_atomic + FROM transactions t + LEFT JOIN blocks b ON b.identity_id = t.identity_id AND b.height = t.height + WHERE t.identity_id = ?1 + ORDER BY t.height DESC NULLS FIRST, t.txid + LIMIT ?2 OFFSET ?3", + ) + .map_err(|e| db_err("history", e))?; + + let rows = stmt + .query_map(params![identity_id, limit, offset], |r| { + let txid: Vec = r.get(0)?; + Ok(json!({ + "txid": hex::encode(txid), + "height": r.get::<_, Option>(1)?, + "direction": r.get::<_, String>(2)?, + "receivedAtomic": r.get::<_, i64>(3)?.to_string(), + "spentAtomic": r.get::<_, i64>(4)?.to_string(), + "timestamp": r.get::<_, Option>(5)?, + "failed": r.get::<_, i64>(6)? != 0, + "outgoingAtomic": r.get::<_, Option>(7)?, + })) + }) + .map_err(|e| db_err("history", e))?; + + let items = rows + .collect::>>() + .map_err(|e| db_err("history", e))?; + + let total: i64 = db + .conn() + .query_row( + "SELECT count(*) FROM transactions WHERE identity_id = ?1", + [identity_id], + |r| r.get(0), + ) + .map_err(|e| db_err("historyCount", e))?; + + Ok(json!({ "items": items, "total": total, "limit": limit, "offset": offset })) +} + +/// 单笔交易详情。 +pub fn transaction_details(db: &Db, identity_id: i64, txid_hex: &str) -> Result { + let txid = hex::decode(txid_hex).map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "txid", "reason": "notHex" }), + ) + })?; + if txid.len() != 32 { + return Err(RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "txid", "byteLen": txid.len(), "expected": 32 }), + )); + } + + let row = db + .conn() + .query_row( + "SELECT t.height, t.direction, COALESCE(t.timestamp, b.timestamp, t.sent_at) + FROM transactions t LEFT JOIN blocks b ON b.identity_id = t.identity_id AND b.height = t.height + WHERE t.identity_id = ?1 AND t.txid = ?2", + params![identity_id, &txid], + |r| { + Ok(( + r.get::<_, Option>(0)?, + r.get::<_, String>(1)?, + r.get::<_, Option>(2)?, + )) + }, + ) + .optional() + .map_err(|e| db_err("transactionDetails", e))?; + + let Some((height, direction, timestamp)) = row else { + return Ok(Value::Null); + }; + + let mut stmt = db + .conn() + .prepare( + "SELECT amount_atomic, subaddress_major, subaddress_minor, index_in_tx + FROM outputs WHERE identity_id = ?1 AND txid = ?2 ORDER BY index_in_tx", + ) + .map_err(|e| db_err("transactionOutputs", e))?; + let received = stmt + .query_map(params![identity_id, &txid], |r| { + Ok(json!({ + "amountAtomic": r.get::<_, i64>(0)?.to_string(), + "subaddressMajor": r.get::<_, Option>(1)?, + "subaddressMinor": r.get::<_, Option>(2)?, + "indexInTransaction": r.get::<_, i64>(3)?, + })) + }) + .map_err(|e| db_err("transactionOutputs", e))? + .collect::>>() + .map_err(|e| db_err("transactionOutputs", e))?; + + Ok(json!({ + "txid": txid_hex, + "height": height, + "direction": direction, + "timestamp": timestamp, + "received": received, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wallet::testing::db_with_identity; + + fn add_output( + db: &Db, + identity_id: i64, + amount: i64, + height: i64, + with_key_image: bool, + ) -> i64 { + let ki: Option> = with_key_image.then(|| { + let mut k = vec![0u8; 32]; + // 每个输出一个不同的 key image,免得唯一性问题掩盖 bug + k[0] = (amount % 251) as u8; + k[1] = (height % 251) as u8; + k + }); + db.conn() + .execute( + "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, + amount_atomic, height, key_image) + VALUES (?1, x'00', ?2, ?3, 0, ?4, ?5, ?6)", + params![ + identity_id, + &vec![height as u8; 32], + height, + amount, + height, + ki + ], + ) + .unwrap(); + db.conn().last_insert_rowid() + } + + /// 10 块锁定是共识规则,不是我们的策略 —— 未满 10 块的输出构不进环。 + #[test] + fn the_ten_block_lock_is_enforced() { + assert!(!is_unlocked(100, 0, 100), "同高度必然锁定"); + assert!(!is_unlocked(100, 0, 109), "差一块也是锁定"); + assert!(is_unlocked(100, 0, 110), "满 10 块解锁"); + } + + #[test] + fn additional_block_timelock_is_honoured() { + // 额外锁到 200 块:即使过了 10 块锁也还不能花 + assert!(!is_unlocked(100, 200, 150)); + assert!(is_unlocked(100, 200, 200)); + } + + /// 时间戳形式的时间锁光靠链高判断不了。保守当作仍锁定 —— 让用户等, + /// 好过让他构一笔必然被节点拒绝的交易。 + #[test] + fn timestamp_timelocks_are_treated_as_locked() { + assert!(!is_unlocked(100, 1_700_000_000, 999_999)); + } + + /// 不知道链尖时可用余额必须是 0,不能乐观放行。 + #[test] + fn unknown_chain_tip_means_nothing_is_spendable() { + let (db, id) = db_with_identity(); + add_output(&db, id, 1_000, 10, true); + let b = balance(&db, id, None).unwrap(); + assert_eq!(b.total_atomic, 1_000); + assert_eq!(b.unlocked_atomic, 0); + } + + /// 没 key image、又进过某个环的输出**可能已经被花掉**,必须单独报出来; + /// 从没进过环的一定没花(花它必然要把它放进环),不能算成待核实。 + #[test] + fn only_outputs_seen_in_a_ring_are_pending_verification() { + let (db, id) = db_with_identity(); + add_output(&db, id, 700, 10, true); + add_output(&db, id, 300, 11, false); + add_output(&db, id, 200, 12, false); + db.conn() + .execute( + "INSERT INTO possible_spends + (identity_id, out_txid, out_index, key_image, spend_txid, height, timestamp) + VALUES (?1, ?2, 0, ?3, ?4, 20, 0)", + params![id, vec![12u8; 32], vec![9u8; 32], vec![8u8; 32]], + ) + .unwrap(); + let b = balance(&db, id, Some(100)).unwrap(); + assert_eq!(b.total_atomic, 1_200); + assert_eq!(b.unverifiable_atomic, 200); + assert_eq!(b.unlocked_atomic, 1_000, "可能已花的不算可用"); + } + + /// 被在途交易预留的输出仍计入总额,但不可再次选中 —— 不锁会让同一笔 + /// 输出被两笔交易同时花掉,第二笔必然被网络拒绝。 + #[test] + fn reserved_outputs_are_excluded_from_unlocked_and_from_selection() { + let (db, id) = db_with_identity(); + let a = add_output(&db, id, 500, 10, true); + add_output(&db, id, 400, 11, true); + db.conn() + .execute( + "INSERT INTO locked_outputs (output_id, reservation_id, locked_at) VALUES (?1, 'r', ?2)", + params![a, crate::wallet::now_secs()], + ) + .unwrap(); + + let b = balance(&db, id, Some(100)).unwrap(); + assert_eq!(b.total_atomic, 900); + assert_eq!(b.locked_by_reservation_atomic, 500); + assert_eq!(b.unlocked_atomic, 400); + + let spendable = spendable_rows(&db, id, 100).unwrap(); + assert_eq!(spendable.len(), 1, "被预留的不能再被选中"); + assert_eq!(spendable[0].amount_atomic, 400); + } + + /// 用户在确认页退出不会通知 runtime;过期的预留不能永远锁着钱。 + #[test] + fn an_expired_reservation_no_longer_holds_its_outputs() { + let (db, id) = db_with_identity(); + let a = add_output(&db, id, 500, 10, true); + db.conn() + .execute( + "INSERT INTO locked_outputs (output_id, reservation_id, locked_at) VALUES (?1, 'r', ?2)", + params![a, crate::spend::reservation_cutoff() - 1], + ) + .unwrap(); + + let b = balance(&db, id, Some(100)).unwrap(); + assert_eq!(b.locked_by_reservation_atomic, 0); + assert_eq!(b.unlocked_atomic, 500); + assert_eq!(spendable_rows(&db, id, 100).unwrap().len(), 1); + } + + /// 已花的输出不再计入任何口径。 + #[test] + fn spent_outputs_leave_the_balance() { + let (db, id) = db_with_identity(); + let a = add_output(&db, id, 500, 10, true); + db.conn() + .execute("UPDATE outputs SET spent_at_height = 20 WHERE id = ?1", [a]) + .unwrap(); + let b = balance(&db, id, Some(100)).unwrap(); + assert_eq!(b.total_atomic, 0); + } + + /// 自己广播还没上链的:时间取广播时间(不然每次读都是「现在」), + /// 金额取广播时记下的,失败要标出来。 + #[test] + fn a_pending_send_reports_its_broadcast_time_amount_and_failure() { + let (db, id) = db_with_identity(); + db.conn() + .execute( + "INSERT INTO transactions + (identity_id, txid, height, direction, sent_at, failed, outgoing_atomic) + VALUES (?1, ?2, NULL, 'out', 1700000000, 1, '1234')", + params![id, vec![5u8; 32]], + ) + .unwrap(); + let item = &history(&db, id, 10, 0).unwrap()["items"][0]; + assert_eq!(item["timestamp"], 1_700_000_000); + assert_eq!(item["failed"], true); + assert_eq!(item["outgoingAtomic"], "1234"); + } + + /// 历史分页的上界必须有硬限制 —— 宿主传个巨大的 limit 会把整段历史读进 + /// 内存,那正是选 SQLite 要避免的。 + #[test] + fn history_limit_is_clamped() { + let (db, id) = db_with_identity(); + let v = history(&db, id, 99_999, 0).unwrap(); + assert_eq!(v["limit"], 500); + let v = history(&db, id, 0, 0).unwrap(); + assert_eq!(v["limit"], 1); + } + + #[test] + fn transaction_details_rejects_malformed_txids() { + let (db, id) = db_with_identity(); + let e = transaction_details(&db, id, "zzzz").unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidRequest); + let e = transaction_details(&db, id, "00ff").unwrap_err(); + assert_eq!(e.params["byteLen"], 2); + } + + #[test] + fn unknown_transaction_returns_null_not_an_error() { + let (db, id) = db_with_identity(); + let v = transaction_details(&db, id, &"ab".repeat(32)).unwrap(); + assert!(v.is_null()); + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs new file mode 100644 index 000000000..a007b8f45 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs @@ -0,0 +1,285 @@ +//! 跨调用的会话状态。 +//! +//! 按边界原则,wasm 侧**不持有会话状态** —— 唯一的例外是数据库连接和节点 +//! 客户端,因为每次调用都重开代价太高(重开要重跑一遍迁移检查)。 +//! +//! 除此之外没有缓存、没有定时器、没有后台任务。宿主每调一次,这里完整做完 +//! 一次并返回。 + +use std::cell::{Cell, RefCell}; + +use crate::error::{ErrorCode, Result, RuntimeError}; +use crate::network::Daemon; +use crate::wallet::Db; + +thread_local! { + static DB: RefCell> = const { RefCell::new(None) }; + static DAEMON: RefCell> = const { RefCell::new(None) }; + static DB_NAME: RefCell> = const { RefCell::new(None) }; + + // ── 并发防线 ──────────────────────────────────────────────────────── + // + // 异步操作会把 DB 从这里**取走**,跨 await 持有,结束后放回。这中间宿主 + // 完全可以再发起别的调用 —— wasm 是单线程,但 await 让重入变得可能。 + // + // 没有防线时的真实竞态: + // 1. A 在扫链,DB(A) 已被取走 + // 2. B 调 openWallet(B),DB_NAME 变成 B + // 3. A 结束,把 DB(A) 放回 —— 此刻 DB_NAME 说 B,实际却是 A + // 之后所有操作都在错误的库上进行,而且看不出来。 + static BUSY: Cell = const { Cell::new(false) }; + static GENERATION: Cell = const { Cell::new(0) }; + + // 节点客户端有**自己的**世代号。DB 那道防线盖不住它:换节点时不碰 DB, + // GENERATION 不动,于是一次在途的取链尖结束后会把旧节点原样盖回去, + // 之后所有请求都发给上一个节点。 + static DAEMON_GENERATION: Cell = const { Cell::new(0) }; +} + +fn assert_idle(operation: &str) -> Result<()> { + if BUSY.with(Cell::get) { + return Err(RuntimeError::with( + ErrorCode::WalletBusy, + serde_json::json!({ "operation": operation }), + )); + } + Ok(()) +} + +/// 持有期间标记 BUSY,析构时**一定**清除 —— 包括提前返回与 panic 展开。 +struct BusyGuard; + +impl BusyGuard { + fn acquire(operation: &str) -> Result { + assert_idle(operation)?; + BUSY.with(|b| b.set(true)); + Ok(Self) + } +} + +impl Drop for BusyGuard { + fn drop(&mut self) { + BUSY.with(|b| b.set(false)); + } +} + +fn bump_generation() { + GENERATION.with(|g| g.set(g.get().wrapping_add(1))); +} + +fn bump_daemon_generation() { + DAEMON_GENERATION.with(|g| g.set(g.get().wrapping_add(1))); +} + +fn daemon_generation() -> u64 { + DAEMON_GENERATION.with(Cell::get) +} + +/// 取走客户端前采样,放回前比对。不相等说明期间节点被换掉或关掉了, +/// 手上这个已经作废 —— 丢弃它,而不是覆盖当前的。 +fn put_daemon_back(daemon: Daemon, sampled: u64) { + if daemon_generation() == sampled { + DAEMON.with(|c| *c.borrow_mut() = Some(daemon)); + } +} + +fn not_open() -> RuntimeError { + RuntimeError::new(ErrorCode::WalletNotOpen) +} + +fn no_daemon() -> RuntimeError { + RuntimeError::new(ErrorCode::NodeNotConfigured) +} + +/// 打开钱包。正在进行异步操作时会被拒绝 —— 中途换库会让那次操作把结果写到 +/// 错误的地方,而且没有任何迹象。 +pub fn set_db(db: Db, db_name: &str) -> Result<()> { + assert_idle("openWallet")?; + DB.with(|c| *c.borrow_mut() = Some(db)); + DB_NAME.with(|c| *c.borrow_mut() = Some(db_name.to_owned())); + bump_generation(); + Ok(()) +} + +pub fn set_daemon(daemon: Daemon) { + DAEMON.with(|c| *c.borrow_mut() = Some(daemon)); + bump_daemon_generation(); +} + +/// 断开当前节点。借出中的客户端放回时按世代号作废,不会复活。 +pub fn clear_daemon() { + DAEMON.with(|c| *c.borrow_mut() = None); + bump_daemon_generation(); +} + +pub fn open_db_name() -> Option { + DB_NAME.with(|c| c.borrow().clone()) +} + +/// 关闭钱包,释放数据库与客户端。用于账户删除或切换网络。 +pub fn close() -> Result<()> { + assert_idle("closeWallet")?; + DB.with(|c| *c.borrow_mut() = None); + DAEMON.with(|c| *c.borrow_mut() = None); + DB_NAME.with(|c| *c.borrow_mut() = None); + bump_generation(); + bump_daemon_generation(); + Ok(()) +} + +/// 借出数据库做一次同步操作。 +pub fn with_db(f: impl FnOnce(&mut Db) -> Result) -> Result { + let _guard = BusyGuard::acquire("walletOperation")?; + DB.with(|c| { + let mut slot = c.borrow_mut(); + let db = slot.as_mut().ok_or_else(not_open)?; + f(db) + }) +} + +/// 只读借出。 +pub fn with_db_read(f: impl FnOnce(&Db) -> Result) -> Result { + DB.with(|c| { + let slot = c.borrow(); + let db = slot.as_ref().ok_or_else(not_open)?; + f(db) + }) +} + +/// 借出数据库与节点客户端做一次异步操作。 +/// +/// 用「取出 → 使用 → 放回」而不是长期持有 `RefCell` 借用:异步过程中不持有 +/// 任何借用,这是在 wasm 单线程上跨 await 安全共享状态的关键。 +pub async fn with_db_and_daemon(f: F) -> Result +where + F: FnOnce(Db, Daemon) -> Fut, + Fut: std::future::Future)>, +{ + let guard = BusyGuard::acquire("walletOperation")?; + let generation = GENERATION.with(Cell::get); + let daemon_gen = daemon_generation(); + + let db = DB.with(|c| c.borrow_mut().take()).ok_or_else(not_open)?; + let daemon = match DAEMON.with(|c| c.borrow_mut().take()) { + Some(d) => d, + None => { + DB.with(|cell| *cell.borrow_mut() = Some(db)); + return Err(no_daemon()); + } + }; + + let (db, daemon, out) = f(db, daemon).await; + + // 期间钱包被换掉/关掉时,**丢弃**手上这个而不是放回去。 + // 放回去等于让一个已经作废的钱包覆盖当前的,那正是串库的源头。 + if GENERATION.with(Cell::get) != generation { + drop(db); + } else { + DB.with(|c| *c.borrow_mut() = Some(db)); + } + put_daemon_back(daemon, daemon_gen); + drop(guard); + out +} + +/// 只借出节点客户端,**不要求钱包库已打开**。 +/// +/// 建账户时链尖是先决条件:宿主要用它定 birthday,而那一刻库还没建。 +pub async fn with_daemon(f: F) -> Result +where + F: FnOnce(Daemon) -> Fut, + Fut: std::future::Future)>, +{ + let daemon_gen = daemon_generation(); + let daemon = DAEMON + .with(|c| c.borrow_mut().take()) + .ok_or_else(no_daemon)?; + let (daemon, result) = f(daemon).await; + put_daemon_back(daemon, daemon_gen); + result +} + +#[cfg(test)] +mod tests { + use super::*; + use monero_wallet::address::Network; + + // 测试各跑在自己的线程上,thread_local 天然隔离,互不干扰。 + + fn open_memory_db() { + let db = Db::open(":memory:", Network::Mainnet).expect("内存库"); + set_db(db, ":memory:").expect("开库"); + } + + #[test] + fn operations_fail_cleanly_before_a_wallet_is_open() { + let e = with_db_read(|_| Ok(())).unwrap_err(); + assert_eq!(e.code, ErrorCode::WalletNotOpen); + } + + #[test] + fn opening_then_closing_clears_the_name() { + open_memory_db(); + assert_eq!(open_db_name().as_deref(), Some(":memory:")); + close().unwrap(); + assert!(open_db_name().is_none()); + assert_eq!( + with_db_read(|_| Ok(())).unwrap_err().code, + ErrorCode::WalletNotOpen + ); + } + + /// 借出期间不许换库。换了会让那次操作把结果写到错误的地方,而且没有 + /// 任何迹象 —— 这是最难查的一类 bug。 + #[test] + fn switching_the_wallet_is_refused_while_an_operation_holds_it() { + open_memory_db(); + let result = with_db(|_| { + // 模拟「操作进行中,宿主又来开库」 + let db2 = Db::open(":memory:", Network::Mainnet).expect("第二个库"); + Ok(set_db(db2, "other").map(|_| ()).unwrap_err().code) + }) + .unwrap(); + assert_eq!(result, ErrorCode::WalletBusy); + } + + /// 守卫析构时一定清 BUSY —— 包括提前返回那条路。否则一次失败会把 + /// runtime 永久卡在 BUSY,表现为「之后什么都做不了」。 + #[test] + fn the_busy_flag_is_cleared_even_when_the_operation_fails() { + open_memory_db(); + let _ = with_db(|_| -> Result<()> { Err(RuntimeError::new(ErrorCode::InvalidRequest)) }); + assert!(!BUSY.with(Cell::get), "失败路径也必须清 BUSY"); + // 清干净了才能接着用 + with_db(|_| Ok(())).expect("失败之后应当还能继续操作"); + } + + /// 没配节点时,要求节点的操作必须报 NODE_NOT_CONFIGURED, + /// 而不是笼统的网络错误 —— 两者的处置完全不同。 + #[test] + fn daemon_operations_report_a_missing_node_distinctly() { + open_memory_db(); + let e = futures_lite::future::block_on(with_db_and_daemon(|db, daemon| async move { + (db, daemon, Ok(())) + })) + .unwrap_err(); + assert_eq!(e.code, ErrorCode::NodeNotConfigured); + // 借不到客户端时 DB 必须被放回去,否则钱包就凭空关了 + assert!(open_db_name().is_some(), "失败不该顺手把库弄丢"); + with_db_read(|_| Ok(())).expect("库应当还在"); + } + + /// 关库必须让在途的客户端借用作废。否则它结束时会把旧节点盖回去, + /// 之后所有请求都发给上一个节点。 + #[test] + fn closing_invalidates_an_in_flight_daemon_borrow() { + let sampled = daemon_generation(); + assert_eq!(daemon_generation(), sampled, "无事发生时采样应稳定"); + close().expect("空状态下关闭应当成功"); + assert_ne!( + daemon_generation(), + sampled, + "close 之后在途借用必须被判作废" + ); + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs new file mode 100644 index 000000000..c10ffb1ef --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs @@ -0,0 +1,1113 @@ +//! 扫描:把区块喂给 monero-oxide 的 `Scanner`,把产出落进 SQLite。 +//! +//! ## 有界推进 +//! +//! 这里**永远不会**自己循环到同步完成。调用方给一批块、拿一个结果,要不要 +//! 接着扫由宿主决定 —— 这正是「调度归 TS」那条边界。理由和 Zcash 那边一样: +//! 跑到底的函数在浏览器和移动端上无法中断、无法看进度、无法让出主线程。 +//! +//! ## 三道校验,每一道都有具体的失败故事 +//! +//! 1. **块连续性** —— `header.previous` 必须等于我们记录的上一块哈希。对不上 +//! 就是重组(或节点在骗人),向上报 `REORG_DETECTED` 带精确高度。 +//! +//! 2. **RingCT 输出索引** —— 上游 `ScannableBlock` 的文档明确写着 +//! `output_index_for_first_ringct_output` **无法验证**,并要求客户端自己维护 +//! 这个索引、与节点声称的比对,不一致应当断开。这里就是那个自己维护的实现: +//! 扫完一块后按「本块 v2 交易的输出总数」推进游标,下一块拿它对账。 +//! 索引错了的后果是构环时取错输出,交易被网络拒绝 —— 而且很难从现象反推。 +//! +//! 3. **批内高度递增** —— 节点乱序返回时直接拒绝,不要试图自己排序: +//! 能乱序就说明对端不可信,排好序继续扫等于替它掩盖问题。 +//! +//! ## 花费检测的协议限制 +//! +//! Monero 的观察钱包**无法独立判断自己的输出有没有被花掉** —— 判断需要 +//! key image,而 key image 需要花费私钥。这不是实现取舍,是协议性质。 +//! +//! 所以这里的做法是:`outputs.key_image` 由宿主通过 [`crate::spend::import_key_images`] +//! 在解锁时补齐;扫描时拿已知的 key image 去撞链上交易的输入。没补齐 key image +//! 的输出**检测不到花费**,余额会偏高 —— 这一点必须让宿主知道,见 +//! [`ScanOutcome::outputs_without_key_image`]。 + +use std::collections::{HashMap, HashSet}; + +use monero_wallet::{ + address::SubaddressIndex, + interface::ScannableBlock, + transaction::{Input, Transaction}, + Scanner, WalletOutput, +}; +use rusqlite::{params, OptionalExtension}; +use serde_json::json; + +use crate::error::{db_err, ErrorCode, Result, RuntimeError}; +use crate::schema::REORG_WINDOW_BLOCKS; +use crate::wallet::Db; + +/// 检测到重组时建议回退多少块。 +/// +/// Monero 的重组极少超过几块;退太多让用户重扫大段历史,退太少可能没退到 +/// 分叉点之前、下一轮继续撞同一个错。宿主在重复失败时应自行加大。 +pub const REORG_REWIND_BLOCKS: u64 = 10; + +#[derive(Debug, Default, Clone)] +pub struct ScanOutcome { + pub blocks_scanned: u64, + pub outputs_found: usize, + pub spends_detected: usize, + /// 本批记下的「可能的花费」条数(环里含我的、还不知道 key image 的输出)。 + pub possible_spends: usize, + pub from_height: Option, + pub to_height: Option, + /// 还没有 key image 的输出数。**大于 0 意味着余额可能偏高** —— + /// 这些输出即使已经被花掉,扫描也检测不出来。 + pub outputs_without_key_image: i64, + /// 拉块耗时(毫秒)。与 `ms_scan` 分开报,因为「网络慢」和「解密慢」 + /// 在界面上长得一模一样,但结论完全相反。 + pub ms_download: u32, + /// 试解密与落库耗时(毫秒)。 + pub ms_scan: u32, + /// 这一批块是怎么取来的:`blocksBin`(一次批量)或 `perBlock`(逐块并发)。 + pub fetched_via: &'static str, + /// 批量路径这一步被放弃的原因。只在放弃发生的那一步出现。 + pub fetch_note: Option, + /// 这一步的第一批是否直接用上了上一步预取的请求。 + pub prefetch_hit: bool, + /// 这一步之后的批量大小(下一个请求要多少块)。 + pub batch_blocks: u64, +} + +impl ScanOutcome { + pub fn to_json(&self) -> serde_json::Value { + json!({ + "blocksScanned": self.blocks_scanned, + "outputsFound": self.outputs_found, + "spendsDetected": self.spends_detected, + "possibleSpends": self.possible_spends, + "fromHeight": self.from_height, + "toHeight": self.to_height, + "outputsWithoutKeyImage": self.outputs_without_key_image, + "msDownload": self.ms_download, + "msScan": self.ms_scan, + "fetchedVia": self.fetched_via, + "fetchNote": self.fetch_note, + "prefetchHit": self.prefetch_hit, + "batchBlocks": self.batch_blocks, + }) + } +} + +/// 本块里 RingCT 输出的数量。 +/// +/// 只有 v2 交易能产出 RingCT 输出(v1 不能),矿工交易也算在内且排在最前。 +/// 这是我们**独立于节点**推算全局输出序号的依据 —— 上游要求客户端这么做。 +fn ringct_output_count(block: &ScannableBlock) -> u64 { + fn count(tx: &Transaction) -> u64 { + match tx { + Transaction::V1 { .. } => 0, + Transaction::V2 { prefix, .. } => prefix.outputs.len() as u64, + } + } + count(block.block.miner_transaction()) + block.transactions.iter().map(count).sum::() +} + +/// 本块所有交易输入里的 key image,连同它所属交易的 txid。 +/// +/// txid 取自 `block.block.transactions`(块头里的 txid 列表),它与 +/// `block.transactions`(交易体)一一对应且同序 —— 上游的 +/// `expand_to_scannable_block` 就是按这个列表去拉的交易体。 +/// +/// **不能用 `Transaction::hash()`**:这里的交易是 `Pruned` 形态,V2 交易算 +/// 哈希需要 prunable hash,而裁剪掉的正是它。 +/// +/// 两个列表长度对不上说明节点给的块自相矛盾,直接拒绝而不是凑合对齐 —— +/// 错位会把花费记到别人的交易上。 +fn key_images_in(block: &ScannableBlock) -> Result> { + if block.block.transactions.len() != block.transactions.len() { + return Err(RuntimeError::with( + ErrorCode::MalformedNodeResponse, + json!({ + "operation": "expandBlock", + "height": block.block.number(), + "txidCount": block.block.transactions.len(), + "bodyCount": block.transactions.len(), + }), + )); + } + + let mut out = Vec::new(); + for (txid, tx) in block + .block + .transactions + .iter() + .zip(block.transactions.iter()) + { + for input in &tx.prefix().inputs { + if let Input::ToKey { key_image, .. } = input { + out.push((key_image.to_bytes(), *txid)); + } + } + } + Ok(out) +} + +/// 块里每个输入引用的环:`(key image, 所在交易, 金额类, 环成员的绝对全局序号)`。 +/// +/// `key_offsets` 是相对差分:第一个是绝对序号,之后每个是与前一个的间隔。 +fn ring_references_in(block: &ScannableBlock) -> Vec { + let mut out = Vec::new(); + for (txid, tx) in block + .block + .transactions + .iter() + .zip(block.transactions.iter()) + { + for input in &tx.prefix().inputs { + if let Input::ToKey { + amount, + key_offsets, + key_image, + } = input + { + let mut absolute = Vec::with_capacity(key_offsets.len()); + let mut index = 0u64; + for offset in key_offsets { + index = index.saturating_add(*offset); + absolute.push(index); + } + out.push(RingReference { + key_image: key_image.to_bytes(), + spend_txid: *txid, + amount: *amount, + members: absolute, + }); + } + } + } + out +} + +/// 一条可能的花费:我的某笔输出出现在某个输入的环里。 +struct PossibleSpend { + out_txid: [u8; 32], + out_index: u64, + key_image: [u8; 32], + spend_txid: [u8; 32], + height: u64, + timestamp: u64, +} + +struct RingReference { + key_image: [u8; 32], + spend_txid: [u8; 32], + /// `None`/`Some(0)`:RingCT 池;其余为老式按金额分池(2017 年前)。 + amount: Option, + members: Vec, +} + +/// 还没有 key image 的未花输出,按全局序号索引:`(txid, index_in_tx, 金额)`。 +/// 只有它们需要「可能的花费」—— 有 key image 的由正常的花费检测负责。 +type RingCandidates = HashMap>; + +fn load_ring_candidates(db: &Db, identity_id: i64) -> Result { + let mut stmt = db + .conn() + .prepare( + "SELECT txid, index_in_tx, global_index, amount_atomic FROM outputs + WHERE identity_id = ?1 AND key_image IS NULL AND spent_at_height IS NULL", + ) + .map_err(|e| db_err("loadRingCandidates", e))?; + let rows = stmt + .query_map([identity_id], |r| { + Ok(( + r.get::<_, Vec>(0)?, + r.get::<_, i64>(1)? as u64, + r.get::<_, i64>(2)? as u64, + r.get::<_, i64>(3)? as u64, + )) + }) + .map_err(|e| db_err("loadRingCandidates", e))?; + let mut map: RingCandidates = HashMap::new(); + for row in rows { + let (txid, index, global, amount) = row.map_err(|e| db_err("loadRingCandidates", e))?; + let Ok(txid) = <[u8; 32]>::try_from(txid.as_slice()) else { + continue; + }; + map.entry(global).or_default().push((txid, index, amount)); + } + Ok(map) +} + +/// 一个输入的环里含我的哪些输出。老式按金额分池的输出还要金额相同才算; +/// RingCT 输入只按序号 —— 多报只会多一条「可能」,漏报才会让花费认不出。 +fn ring_matches<'a>( + candidates: &'a RingCandidates, + reference: &'a RingReference, +) -> impl Iterator + 'a { + let pool = reference.amount.filter(|a| *a != 0); + reference + .members + .iter() + .filter_map(|member| candidates.get(member)) + .flatten() + .filter(move |(_, _, amount)| pool.is_none_or(|p| p == *amount)) +} + +/// 每条交易的公钥:`(R, additional)`,按 txid 索引。 +/// +/// ## 为什么要单独留一份 +/// +/// monero-oxide 把「R + 输出序号 + 子地址」整条推导折叠成 `WalletOutput` 上的 +/// 一个 `key_offset` 标量,**然后就把 R 丢了**。软件签名只要 +/// `spend + key_offset`,所以缺了也看不出来。 +/// +/// 固件不接受 `key_offset`。它要 `real_out_tx_key` 自己推导一次性私钥和 +/// key image —— 接受宿主算好的偏移量,等于让一个恶意宿主指挥设备拿任意密钥 +/// 签名。所以硬件那条路必须有 R。 +/// +/// 而 R 只在扫描这一刻手里有:事后要么全量重扫,要么拿 txid 去找节点要回那条 +/// 交易 —— 后者等于直接告诉节点「我对这笔感兴趣」,把扫全链换来的隐私当场 +/// 还回去。所以在这里留下来,哪怕现在还没有硬件可接。 +fn tx_public_keys_in(block: &ScannableBlock) -> Vec<([u8; 32], Vec, Option>)> { + // 长度不齐的情况由 `key_images_in` 统一报错;这里取不到就跳过, + // 不重复报同一个错。 + let mut out = Vec::new(); + for (txid, tx) in block + .block + .transactions + .iter() + .zip(block.transactions.iter()) + { + if let Some((keys, additional)) = tx_public_keys_from_extra(&tx.prefix().extra) { + out.push((*txid, keys, additional)); + } + } + out +} + +/// 从一条交易的 `extra` 里取出 `(R, additional)`,各自 32 字节一个顺序拼接。 +/// +/// 拆成纯函数是为了能用真实链上数据钉住 —— 扫描路径本身要造一个完整的 +/// `ScannableBlock` 才跑得起来,那种 fixture 只会测到我们自己的假设。 +fn tx_public_keys_from_extra(extra: &[u8]) -> Option<(Vec, Option>)> { + fn flatten(points: &[monero_wallet::ed25519::Point]) -> Vec { + let mut out = Vec::with_capacity(points.len() * 32); + for p in points { + out.extend_from_slice(&p.compress().to_bytes()); + } + out + } + + let extra = monero_wallet::extra::Extra::read(&mut &*extra).ok()?; + let (keys, additional) = extra.keys()?; + Some((flatten(&keys), additional.as_deref().map(flatten))) +} + +/// 扫描一批块并落库。**整批一个事务**:要么全成,要么一块都不留。 +/// +/// 块必须按高度升序、且彼此连续。调用方(宿主)负责按区间取块。 +pub fn scan_blocks( + db: &mut Db, + identity_id: i64, + blocks: &[ScannableBlock], +) -> Result { + if blocks.is_empty() { + let mut outcome = ScanOutcome::default(); + outcome.outputs_without_key_image = count_outputs_without_key_image(db, identity_id)?; + return Ok(outcome); + } + + let identity = db.identity_by_id(identity_id)?; + let subaddresses = db.subaddress_indices(identity_id)?; + + let mut scanner = Scanner::new(identity.view_pair.clone()); + for (major, minor) in &subaddresses { + // (0,0) 进不了库(schema 有 CHECK),所以这里 None 不可能发生; + // 真发生了说明有人绕过了约束直接写库,宁可跳过也不要 panic。 + if let Some(index) = SubaddressIndex::new(*major, *minor) { + scanner.register_subaddress(index); + } + } + + // 我们自己维护的 key image 集合,用于花费检测。 + let known_key_images = load_key_images(db, identity_id)?; + // 还不知道 key image 的输出,用环成员比对记下「可能的花费」。 + let mut ring_candidates = load_ring_candidates(db, identity_id)?; + let mut possible_spends: Vec = Vec::new(); + + let mut outcome = ScanOutcome::default(); + let mut found: Vec<(u64, WalletOutput)> = Vec::new(); + // txid -> (R, additional)。只留我们真正收到输出的那些交易的。 + let mut tx_pub_keys: HashMap<[u8; 32], (Vec, Option>)> = HashMap::new(); + let mut spends: Vec<(u64, [u8; 32], [u8; 32])> = Vec::new(); // (height, key_image, txid) + let mut block_rows: Vec<(u64, [u8; 32], Option, u64)> = Vec::new(); // (height, hash, ringct_next, ts) + + // 批起点的前一块:用于连续性与 RingCT 游标对账。 + let first_height = blocks[0].block.number() as u64; + let mut prev = previous_block_state(db, identity_id, first_height)?; + + for block in blocks { + let height = block.block.number() as u64; + + // ── 1. 批内必须严格递增且连续 ────────────────────────────────── + if let Some((prev_height, _, _)) = prev { + if height != prev_height + 1 { + return Err(RuntimeError::with( + ErrorCode::ReorgDetected, + json!({ + "atHeight": height, + "expectedHeight": prev_height + 1, + "suggestedRewindHeight": height.saturating_sub(REORG_REWIND_BLOCKS), + }), + )); + } + } + + // ── 2. 前驱哈希对账 —— 重组检测 ──────────────────────────────── + if let Some((_, prev_hash, _)) = prev { + if block.block.header.previous != prev_hash { + return Err(RuntimeError::with( + ErrorCode::ReorgDetected, + json!({ + "atHeight": height, + "suggestedRewindHeight": height.saturating_sub(REORG_REWIND_BLOCKS), + }), + )); + } + } + + // ── 3. RingCT 索引对账 —— 上游要求客户端独立维护并比对 ───────── + if let (Some((_, _, Some(expected_next))), Some(claimed)) = + (prev, block.output_index_for_first_ringct_output) + { + if claimed != expected_next { + return Err(RuntimeError::with( + ErrorCode::RingCtIndexMismatch, + json!({ + "height": height, + "claimed": claimed, + "expected": expected_next, + }), + )); + } + } + + let outputs = scanner + .scan(block.clone()) + .map_err(|e| { + RuntimeError::with(ErrorCode::ScanFailed, json!({ "height": height })) + .detail(format!("{e:?}")) + })? + // 额外时间锁由查询层按当前链高判断,这里全部收下 —— + // 丢掉锁定中的输出会让它们永远不再出现(我们不会重扫这一段)。 + .ignore_additional_timelock(); + + if !outputs.is_empty() { + // 只在这一块确实有我们的输出时才解析 extra —— 绝大多数块一个都 + // 没有,为它们全量解析是白花 CPU。 + for (txid, keys, additional) in tx_public_keys_in(block) { + tx_pub_keys.insert(txid, (keys, additional)); + } + } + // 先比对本块的输入,再把本块收到的钱加进候选:刚收到的钱至少锁 10 块, + // 不可能在同一块被花。 + for reference in ring_references_in(block) { + if known_key_images.contains_key(&reference.key_image) { + continue; + } + for (out_txid, out_index, _) in ring_matches(&ring_candidates, &reference) { + possible_spends.push(PossibleSpend { + out_txid: *out_txid, + out_index: *out_index, + key_image: reference.key_image, + spend_txid: reference.spend_txid, + height, + timestamp: block.block.header.timestamp, + }); + } + } + for output in outputs { + ring_candidates + .entry(output.index_on_blockchain()) + .or_default() + .push(( + output.transaction(), + output.index_in_transaction(), + output.commitment().amount, + )); + found.push((height, output)); + } + + for (key_image, txid) in key_images_in(block)? { + if known_key_images.contains_key(&key_image) { + // txid 必须是**花费这笔输出的那条交易**,不是块哈希 —— + // 记错了历史详情会指向一条不相干的交易。 + spends.push((height, key_image, txid)); + } + } + + // 游标的依据:优先用上一块推出来的,其次用节点声称的起点。 + // 两者都没有时**保持未知**,绝不退化成 0 —— 那会让下一块的对账 + // 拿真实序号去比 0,报出一个假的 RINGCT_INDEX_MISMATCH。 + let next_ringct = prev + .and_then(|(_, _, n)| n) + .or(block.output_index_for_first_ringct_output) + .map(|base| base + ringct_output_count(block)); + + block_rows.push(( + height, + block.block.hash(), + next_ringct, + block.block.header.timestamp, + )); + prev = Some((height, block.block.hash(), next_ringct)); + outcome.blocks_scanned += 1; + } + + outcome.from_height = Some(first_height); + outcome.to_height = Some(first_height + outcome.blocks_scanned - 1); + outcome.outputs_found = found.len(); + outcome.spends_detected = spends.len(); + outcome.possible_spends = possible_spends.len(); + + persist( + db, + identity_id, + &found, + &tx_pub_keys, + &spends, + &known_key_images, + &block_rows, + &possible_spends, + )?; + outcome.outputs_without_key_image = count_outputs_without_key_image(db, identity_id)?; + Ok(outcome) +} + +/// 取某高度前一块的 (高度, 哈希, 扫完后的 RingCT 游标)。 +fn previous_block_state( + db: &Db, + identity_id: i64, + height: u64, +) -> Result)>> { + if height == 0 { + return Ok(None); + } + db.conn() + .query_row( + "SELECT height, hash, ringct_next FROM blocks WHERE identity_id = ?1 AND height = ?2", + params![identity_id, (height - 1) as i64], + |r| { + let h: i64 = r.get(0)?; + let hash: Vec = r.get(1)?; + let next: Option = r.get(2)?; + Ok((h as u64, hash, next.map(|n| n as u64))) + }, + ) + .optional() + .map_err(|e| db_err("previousBlockState", e))? + .map(|(h, hash, next)| { + let hash = <[u8; 32]>::try_from(hash.as_slice()) + .map_err(|_| db_err("previousBlockState", "块哈希长度不是 32"))?; + Ok((h, hash, next)) + }) + .transpose() +} + +/// 未花的,加上被自己广播、还没上链的交易花掉的:后者上链时要靠 key image 命中才能确认。 +fn load_key_images(db: &Db, identity_id: i64) -> Result> { + let mut stmt = db + .conn() + .prepare( + "SELECT id, key_image FROM outputs o + WHERE o.identity_id = ?1 AND o.key_image IS NOT NULL + AND (o.spent_at_height IS NULL OR o.spent_in_txid IN ( + SELECT txid FROM transactions WHERE identity_id = ?1 AND height IS NULL))", + ) + .map_err(|e| db_err("loadKeyImages", e))?; + let rows = stmt + .query_map([identity_id], |r| { + let id: i64 = r.get(0)?; + let ki: Vec = r.get(1)?; + Ok((id, ki)) + }) + .map_err(|e| db_err("loadKeyImages", e))?; + + let mut map = HashMap::new(); + for row in rows { + let (id, ki) = row.map_err(|e| db_err("loadKeyImages", e))?; + if let Ok(ki) = <[u8; 32]>::try_from(ki.as_slice()) { + map.insert(ki, id); + } + } + Ok(map) +} + +fn count_outputs_without_key_image(db: &Db, identity_id: i64) -> Result { + db.conn() + .query_row( + "SELECT count(*) FROM outputs WHERE identity_id = ?1 AND key_image IS NULL", + [identity_id], + |r| r.get(0), + ) + .map_err(|e| db_err("countOutputsWithoutKeyImage", e)) +} + +#[allow(clippy::type_complexity, clippy::too_many_arguments)] +fn persist( + db: &mut Db, + identity_id: i64, + found: &[(u64, WalletOutput)], + tx_pub_keys: &HashMap<[u8; 32], (Vec, Option>)>, + spends: &[(u64, [u8; 32], [u8; 32])], + known_key_images: &HashMap<[u8; 32], i64>, + block_rows: &[(u64, [u8; 32], Option, u64)], + possible_spends: &[PossibleSpend], +) -> Result<()> { + let tx = db + .conn_mut() + .transaction() + .map_err(|e| db_err("beginScanCommit", e))?; + + let mut seen_txids: HashSet<[u8; 32]> = HashSet::new(); + // 交易时间跟交易行一起存:块表会裁剪到链尖附近,回补扫到的交易一旦所在块被裁,联表就拿不到时间。 + let block_time: HashMap = block_rows + .iter() + .map(|(h, _, _, ts)| (*h, *ts as i64)) + .collect(); + + for (height, output) in found { + let txid = output.transaction(); + let subaddress = output.subaddress(); + let output_key = output.key().compress().to_bytes(); + if is_burning_duplicate( + &tx, + identity_id, + &output_key, + &txid, + output.index_in_transaction(), + )? { + continue; + } + // `INSERT OR IGNORE`:重扫同一段区间必须幂等,否则余额翻倍。 + // 唯一约束是 (identity_id, txid, index_in_tx)。 + tx.execute( + "INSERT OR IGNORE INTO outputs + (identity_id, blob, txid, global_index, index_in_tx, amount_atomic, + subaddress_major, subaddress_minor, height, additional_timelock, + tx_pub_keys, tx_additional_pub_keys, output_key) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)", + params![ + identity_id, + output.serialize(), + txid.as_slice(), + output.index_on_blockchain() as i64, + output.index_in_transaction() as i64, + output.commitment().amount as i64, + subaddress.map(|s| s.account() as i64), + subaddress.map(|s| s.address() as i64), + *height as i64, + timelock_to_i64(output.additional_timelock()), + tx_pub_keys.get(&txid).map(|(k, _)| k.as_slice()), + tx_pub_keys.get(&txid).and_then(|(_, a)| a.as_deref()), + output_key.as_slice(), + ], + ) + .map_err(|e| db_err("insertOutput", e))?; + + if seen_txids.insert(txid) { + tx.execute( + "INSERT INTO transactions (identity_id, txid, height, timestamp, direction) + VALUES (?1, ?2, ?3, ?4, 'in') + ON CONFLICT (identity_id, txid) DO UPDATE + SET height = COALESCE(transactions.height, excluded.height), failed = 0, + timestamp = COALESCE(excluded.timestamp, transactions.timestamp)", + params![ + identity_id, + txid.as_slice(), + *height as i64, + block_time.get(height) + ], + ) + .map_err(|e| db_err("insertIncomingTransaction", e))?; + } + } + + for (height, key_image, txid) in spends { + let Some(output_id) = known_key_images.get(key_image) else { + continue; + }; + tx.execute( + "UPDATE outputs SET spent_at_height = ?1, spent_in_txid = ?2 + WHERE id = ?3 AND (spent_at_height IS NULL OR spent_in_txid IN ( + SELECT txid FROM transactions WHERE identity_id = ?4 AND height IS NULL))", + params![*height as i64, txid.as_slice(), output_id, identity_id], + ) + .map_err(|e| db_err("markOutputSpent", e))?; + tx.execute( + "INSERT INTO transactions (identity_id, txid, height, timestamp, direction) + VALUES (?1, ?2, ?3, ?4, 'out') + ON CONFLICT (identity_id, txid) DO UPDATE + SET direction = 'out', height = ?3, failed = 0, + timestamp = COALESCE(excluded.timestamp, transactions.timestamp)", + params![ + identity_id, + txid.as_slice(), + *height as i64, + block_time.get(height) + ], + ) + .map_err(|e| db_err("insertOutgoingTransaction", e))?; + } + + // 幂等:重扫同一段会遇到同样的环引用。 + for ps in possible_spends { + tx.execute( + "INSERT OR IGNORE INTO possible_spends + (identity_id, out_txid, out_index, key_image, spend_txid, height, timestamp) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + identity_id, + ps.out_txid.as_slice(), + ps.out_index as i64, + ps.key_image.as_slice(), + ps.spend_txid.as_slice(), + ps.height as i64, + ps.timestamp as i64 + ], + ) + .map_err(|e| db_err("insertPossibleSpend", e))?; + } + + for (height, hash, ringct_next, timestamp) in block_rows { + tx.execute( + "INSERT OR REPLACE INTO blocks (identity_id, height, hash, ringct_next, timestamp) + VALUES (?1, ?2, ?3, ?4, ?5)", + params![ + identity_id, + *height as i64, + hash.as_slice(), + ringct_next.map(|n| n as i64), + *timestamp as i64 + ], + ) + .map_err(|e| db_err("insertBlock", e))?; + } + + // 裁剪块表:只留链尖往前 REORG_WINDOW_BLOCKS 块。 + // 不裁剪的话这张表会随链高无限增长 —— 那正是我们批评 wallet2 内存模型 + // 时说的那件事,自己不能犯。 + if let Some((tip, _, _, _)) = block_rows.last() { + let floor = tip.saturating_sub(REORG_WINDOW_BLOCKS); + tx.execute( + "DELETE FROM blocks WHERE identity_id = ?1 AND height < ?2", + params![identity_id, floor as i64], + ) + .map_err(|e| db_err("pruneBlocks", e))?; + } + + tx.commit().map_err(|e| db_err("commitScan", e)) +} + +/// 燃烧 bug:同一个一次性公钥出现在另一笔输出里。它们只有一笔能花(花一笔就烧掉 +/// 其余),所以只认最先看到的那笔,后来的不入账 —— 宁可少算,不能把花不掉的钱 +/// 算进余额。同一笔输出重扫不算重复。 +fn is_burning_duplicate( + conn: &rusqlite::Connection, + identity_id: i64, + output_key: &[u8; 32], + txid: &[u8; 32], + index_in_tx: u64, +) -> Result { + conn.query_row( + "SELECT EXISTS (SELECT 1 FROM outputs + WHERE identity_id = ?1 AND output_key = ?2 + AND NOT (txid = ?3 AND index_in_tx = ?4))", + params![ + identity_id, + output_key.as_slice(), + txid.as_slice(), + index_in_tx as i64 + ], + |r| r.get(0), + ) + .map_err(|e| db_err("burningBugCheck", e)) +} + +fn timelock_to_i64(timelock: monero_wallet::transaction::Timelock) -> i64 { + use monero_wallet::transaction::Timelock; + match timelock { + Timelock::None => 0, + Timelock::Block(b) => b as i64, + Timelock::Time(t) => t as i64, + } +} + +/// 回退到指定高度:丢掉该高度**之上**的全部扫描结果。 +/// +/// **破坏性。** 用于重组恢复。已广播的交易不受影响(它们在链上),但本地 +/// 未确认记录会丢。 +pub fn rewind_to(db: &mut Db, identity_id: i64, height: u64) -> Result<()> { + let tx = db + .conn_mut() + .transaction() + .map_err(|e| db_err("beginRewind", e))?; + + tx.execute( + "DELETE FROM outputs WHERE identity_id = ?1 AND height > ?2", + params![identity_id, height as i64], + ) + .map_err(|e| db_err("rewindOutputs", e))?; + + // 花费标记也要撤销:那笔花费所在的块可能已经不在链上了。 + // 自己广播、还没上链的不撤:它的高度只是广播时的链尖,撤了会被再次选中。 + tx.execute( + "UPDATE outputs SET spent_at_height = NULL, spent_in_txid = NULL + WHERE identity_id = ?1 AND spent_at_height > ?2 + AND spent_in_txid NOT IN ( + SELECT txid FROM transactions WHERE identity_id = ?1 AND height IS NULL)", + params![identity_id, height as i64], + ) + .map_err(|e| db_err("rewindSpends", e))?; + + tx.execute( + "DELETE FROM transactions WHERE identity_id = ?1 AND height > ?2", + params![identity_id, height as i64], + ) + .map_err(|e| db_err("rewindTransactions", e))?; + + tx.execute( + "DELETE FROM possible_spends WHERE identity_id = ?1 AND height > ?2", + params![identity_id, height as i64], + ) + .map_err(|e| db_err("rewindPossibleSpends", e))?; + + tx.execute( + "DELETE FROM blocks WHERE identity_id = ?1 AND height > ?2", + params![identity_id, height as i64], + ) + .map_err(|e| db_err("rewindBlocks", e))?; + + tx.commit().map_err(|e| db_err("commitRewind", e)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wallet::testing::db_with_identity; + + /// 用真实主网块验证环引用的换算:相对差分要累加成严格递增的绝对序号, + /// 当前共识环大小 16,全部是 RingCT 输入。 + #[test] + fn ring_references_resolve_to_increasing_absolute_positions_on_real_blocks() { + let blocks = crate::blocks_bin::parse_response( + include_bytes!("../tests/fixtures/get_blocks_bin_3768621.bin"), + 3_768_621, + ) + .expect("解析真实响应"); + let references: Vec = blocks.iter().flat_map(ring_references_in).collect(); + assert!(!references.is_empty()); + let mut key_images = HashSet::new(); + for reference in &references { + assert_eq!(reference.members.len(), 16); + assert!(reference.members.windows(2).all(|w| w[0] < w[1])); + assert_eq!(reference.amount.unwrap_or(0), 0, "RingCT 输入"); + assert!(key_images.insert(reference.key_image), "key image 不应重复"); + } + + // 我的一笔输出若恰好是某个环的成员,就被记为可能的花费。 + let target = &references[0]; + let mut candidates = RingCandidates::new(); + candidates.insert(target.members[5], vec![([7; 32], 1, 12_345)]); + assert_eq!(ring_matches(&candidates, target).count(), 1); + } + + /// 老式按金额分池的输入,序号只在同一金额池内有意义。 + #[test] + fn a_pre_ringct_input_matches_only_outputs_of_its_amount() { + let reference = RingReference { + key_image: [1; 32], + spend_txid: [2; 32], + amount: Some(5_000), + members: vec![40, 41], + }; + let mut candidates = RingCandidates::new(); + candidates.insert(41, vec![([7; 32], 0, 5_000), ([8; 32], 0, 6_000)]); + let matched: Vec<_> = ring_matches(&candidates, &reference).collect(); + assert_eq!(matched.len(), 1); + assert_eq!(matched[0].0, [7; 32]); + } + use rusqlite::params; + + /// 真实主网交易向量。 + /// + /// 取自 mainnet 高度 3767756 的交易 + /// `097edcb40a4345c0e83c41e8631b9e71173389270694e7a7499d3c2fa17951bb`。 + /// 结构是 `01`(TxPublicKey) + 32 字节 R + `02 09 01`(Nonce/加密 payment id) + /// + 8 字节。 + /// + /// 用真数据而不是自己拼一个 extra:自己拼只会测到我们对格式的理解, + /// 而这里要证明的恰恰是对真实链上数据的理解没错。 + #[test] + fn the_transaction_public_key_is_read_from_a_real_mainnet_extra() { + let extra = hex::decode( + "01d3c8b566d9fd0bff3f93448591ec257cc8bf813e1aaa808e97254a5c65ea166\ + 00209012c9f54c03a7c72d0", + ) + .unwrap(); + + let (keys, additional) = tx_public_keys_from_extra(&extra).expect("应当解析出交易公钥"); + assert_eq!( + hex::encode(&keys), + "d3c8b566d9fd0bff3f93448591ec257cc8bf813e1aaa808e97254a5c65ea1660" + ); + assert_eq!(keys.len(), 32, "单个 R 就是 32 字节,不要多也不要少"); + // 这笔交易发给主地址,没有 additional keys。空 Vec 和 None 是两回事: + // 前者表示「有 0 个」,后者表示「没有这个字段」。 + assert_eq!(additional, None); + } + + /// 空 extra 不是错误,只是没有公钥 —— 不能 panic,也不能当成解析失败去 + /// 中断整批扫描。 + #[test] + fn an_extra_without_keys_yields_nothing_rather_than_failing() { + assert!(tx_public_keys_from_extra(&[]).is_none()); + } + + /// **回归测试。** RingCT 游标曾经在「没有依据」时退化成 0。 + /// + /// 触发路径:从链中段开始扫,而起始块恰好没有 RingCT 输出(节点因此给的 + /// `output_index_for_first_ringct_output` 是 None)。游标存成 0 之后, + /// 下一块拿真实序号(几千万)来比对 0,报出一个**假的** + /// `RINGCT_INDEX_MISMATCH` —— 把一个诚实的节点判成作恶,扫描直接卡死。 + /// + /// 正确行为:没有依据就存 NULL,对账跳过,等拿到真实锚点再开始比。 + #[test] + fn an_unknown_ringct_cursor_is_stored_as_null_not_zero() { + let (db, id) = db_with_identity(); + db.conn() + .execute( + "INSERT INTO blocks (identity_id, height, hash, ringct_next, timestamp) + VALUES (?1, ?2, ?3, NULL, 0)", + params![id, 3_000_000i64, &vec![7u8; 32]], + ) + .expect("游标应当允许 NULL"); + + let prev = previous_block_state(&db, id, 3_000_001).expect("读前一块"); + let (height, _, cursor) = prev.expect("前一块应当在"); + assert_eq!(height, 3_000_000); + assert_eq!(cursor, None, "未知必须是 None,不能是 Some(0)"); + } + + /// 一个身份回滚不能动另一个身份的锚点:否则另一个身份在新链上接着扫, + /// 看不出重组,孤块里的钱留在余额里。 + #[test] + fn one_identity_rewinding_leaves_the_others_anchors_alone() { + let (mut db, a) = db_with_identity(); + db.conn() + .execute( + "INSERT INTO identities (uuid, primary_address, spend_public_key, + view_private_key, birthday_height, created_at) + VALUES ('b', 'b', ?1, ?1, 0, 0)", + [vec![9u8; 32]], + ) + .unwrap(); + let b = db.conn().last_insert_rowid(); + for id in [a, b] { + db.conn() + .execute( + "INSERT INTO blocks (identity_id, height, hash, ringct_next, timestamp) + VALUES (?1, 100, ?2, NULL, 0)", + params![id, vec![7u8; 32]], + ) + .unwrap(); + } + + rewind_to(&mut db, a, 50).unwrap(); + + assert!(previous_block_state(&db, a, 101).unwrap().is_none()); + assert!(previous_block_state(&db, b, 101).unwrap().is_some()); + } + + #[test] + fn a_reused_output_key_from_another_transaction_is_a_burning_duplicate() { + let (db, id) = db_with_identity(); + let key = [4u8; 32]; + db.conn() + .execute( + "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, + amount_atomic, height, output_key) + VALUES (?1, x'00', ?2, 1, 0, 700, 10, ?3)", + params![id, [1u8; 32].as_slice(), key.as_slice()], + ) + .unwrap(); + + assert!(is_burning_duplicate(db.conn(), id, &key, &[2u8; 32], 0).unwrap()); + assert!( + !is_burning_duplicate(db.conn(), id, &key, &[1u8; 32], 0).unwrap(), + "同一笔重扫不算" + ); + assert!(!is_burning_duplicate(db.conn(), id, &[5u8; 32], &[2u8; 32], 0).unwrap()); + } + + /// 有依据时游标正常推进。 + #[test] + fn a_known_ringct_cursor_round_trips() { + let (db, id) = db_with_identity(); + db.conn() + .execute( + "INSERT INTO blocks (identity_id, height, hash, ringct_next, timestamp) + VALUES (?1, ?2, ?3, ?4, 0)", + params![id, 3_000_000i64, &vec![7u8; 32], 82_000_000i64], + ) + .unwrap(); + let (_, _, cursor) = previous_block_state(&db, id, 3_000_001).unwrap().unwrap(); + assert_eq!(cursor, Some(82_000_000)); + } + + /// 回补扫到的交易,所在块随后被裁出块表,时间也不能丢(否则界面显示 1970)。 + #[test] + fn a_transaction_keeps_its_time_after_its_block_is_pruned() { + let (mut db, id) = db_with_identity(); + let tx_height = 100u64; + let tip = tx_height + REORG_WINDOW_BLOCKS + 5; + let key_image = [1u8; 32]; + let txid = [2u8; 32]; + let known: HashMap<[u8; 32], i64> = [(key_image, 1)].into_iter().collect(); + persist( + &mut db, + id, + &[], + &HashMap::new(), + &[(tx_height, key_image, txid)], + &known, + &[ + (tx_height, [7u8; 32], None, 1_700_000_000), + (tip, [8u8; 32], None, 1_700_100_000), + ], + &[], + ) + .unwrap(); + + let pruned: i64 = db + .conn() + .query_row( + "SELECT count(*) FROM blocks WHERE height = ?1", + [tx_height as i64], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(pruned, 0, "块本身应当已被裁掉"); + + let history = crate::query::history(&db, id, 10, 0).unwrap(); + assert_eq!(history["items"][0]["timestamp"], 1_700_000_000); + } + + /// 自己广播的交易上链:输出早在广播时标了已花,扫到时仍要按 key image 认出来, + /// 把交易从待确认转成已确认,高度改成真实上链高度。 + #[test] + fn our_broadcast_spend_is_confirmed_when_its_block_is_scanned() { + let (mut db, id) = db_with_identity(); + let key_image = [1u8; 32]; + let txid = [2u8; 32]; + let (broadcast_tip, mined_at) = (500i64, 503u64); + db.conn() + .execute( + "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, + amount_atomic, height, key_image, spent_at_height, spent_in_txid) + VALUES (?1, x'00', ?2, 1, 0, 700, 10, ?3, ?4, ?5)", + params![id, [9u8; 32].as_slice(), key_image.as_slice(), broadcast_tip, txid.as_slice()], + ) + .unwrap(); + let output_id = db.conn().last_insert_rowid(); + db.conn() + .execute( + "INSERT INTO transactions (identity_id, txid, height, direction) + VALUES (?1, ?2, NULL, 'out')", + params![id, txid.as_slice()], + ) + .unwrap(); + + let known = load_key_images(&db, id).unwrap(); + assert_eq!( + known.get(&key_image), + Some(&output_id), + "待确认的花费也要参与比对" + ); + + persist( + &mut db, + id, + &[], + &HashMap::new(), + &[(mined_at, key_image, txid)], + &known, + &[(mined_at, [7u8; 32], None, 1_700_000_000)], + &[], + ) + .unwrap(); + + let tx_height: Option = db + .conn() + .query_row( + "SELECT height FROM transactions WHERE txid = ?1", + [txid.as_slice()], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(tx_height, Some(mined_at as i64)); + let spent_at: i64 = db + .conn() + .query_row( + "SELECT spent_at_height FROM outputs WHERE id = ?1", + [output_id], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(spent_at, mined_at as i64); + assert!( + load_key_images(&db, id).unwrap().is_empty(), + "确认后不再参与比对" + ); + } + + #[test] + fn a_rewind_keeps_the_mark_on_outputs_our_pending_send_spent() { + let (mut db, id) = db_with_identity(); + let txid = [2u8; 32]; + db.conn() + .execute( + "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, + amount_atomic, height, key_image, spent_at_height, spent_in_txid) + VALUES (?1, x'00', ?2, 1, 0, 700, 10, ?3, 500, ?4)", + params![id, [9u8; 32].as_slice(), [1u8; 32].as_slice(), txid.as_slice()], + ) + .unwrap(); + db.conn() + .execute( + "INSERT INTO transactions (identity_id, txid, height, direction) + VALUES (?1, ?2, NULL, 'out')", + params![id, txid.as_slice()], + ) + .unwrap(); + + rewind_to(&mut db, id, 490).unwrap(); + + let spent_in: Option> = db + .conn() + .query_row("SELECT spent_in_txid FROM outputs", [], |r| r.get(0)) + .unwrap(); + assert_eq!(spent_in, Some(txid.to_vec())); + } + + /// 空批次是合法的 no-op,不该报错也不该动任何状态。 + #[test] + fn an_empty_batch_is_a_harmless_no_op() { + let (mut db, id) = db_with_identity(); + let outcome = scan_blocks(&mut db, id, &[]).expect("空批次"); + assert_eq!(outcome.blocks_scanned, 0); + assert_eq!(outcome.outputs_found, 0); + assert!(outcome.from_height.is_none()); + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs new file mode 100644 index 000000000..20c181185 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs @@ -0,0 +1,448 @@ +//! 钱包库的表结构与迁移。 +//! +//! ## 为什么要自己写 +//! +//! monero-oxide 只给密码学与扫描器,**不提供任何存储**。Zcash 那边 +//! `zcash_client_sqlite` 白送的这一层,在 Monero 这边没有对应物。 +//! +//! ## 比 Zcash 少掉的东西 +//! +//! Monero 只有一种输出类型(没有 sapling/orchard/ironwood 三池),FCMP++ +//! 之前**没有承诺树**、因此也没有 witness 与检查点,也没有透明池。Zcash 库里 +//! 最复杂的那几块这里根本不存在,所以这套表能做得很窄。 +//! +//! ## 落盘而不是内存 +//! +//! 这是选 monero-oxide 而非 monero-ts 的全部理由:后者把整个钱包放在 wasm +//! 内存里,持久化只能整块序列化重写,历史越长每次保存越贵,写一半崩了丢全部。 +//! 这里是增量写 + 事务。 + +use rusqlite::Connection; + +use crate::error::{db_err, Result}; + +/// 当前 schema 版本。**改表结构必须同时加迁移并把这个数加一。** +pub const SCHEMA_VERSION: i64 = 1; + +/// 重组安全窗口:`blocks` 表只保留链尖往前这么多块的哈希。 +/// +/// Monero 的重组极少超过几块,但节点作恶不受此限。留 720 块(约一天)既够 +/// 覆盖任何现实重组,又不会让这张表随链高无限增长 —— 这正是我们批评 +/// wallet2 内存模型时说的那件事,自己不能犯。 +pub const REORG_WINDOW_BLOCKS: u64 = 720; + +/// 建表。幂等:可以在每次开库时调用。 +pub fn migrate(conn: &Connection) -> Result<()> { + let version: i64 = conn + .query_row("PRAGMA user_version", [], |r| r.get(0)) + .map_err(|e| db_err("readUserVersion", e))?; + + if version > SCHEMA_VERSION { + return Err(db_err( + "migrate", + format!( + "库的 schema 版本 {version} 高于本 runtime 支持的 {SCHEMA_VERSION},拒绝降级打开" + ), + )); + } + + // 整个迁移一个事务:中途失败(关页、断电)不能留下改了一半、版本号却没动的库, + // 否则下次开库会对已存在的列再 ALTER 一次而永远打不开。 + let tx = conn + .unchecked_transaction() + .map_err(|e| db_err("beginMigrate", e))?; + if version < 1 { + tx.execute_batch(V1).map_err(|e| db_err("migrateV1", e))?; + } + + tx.execute(&format!("PRAGMA user_version = {SCHEMA_VERSION}"), []) + .map_err(|e| db_err("setUserVersion", e))?; + tx.commit().map_err(|e| db_err("commitMigrate", e)) +} + +/// 版本 1。 +/// +/// 命名约定:金额一律 `*_atomic` 存 piconero(u64 存成 INTEGER,Monero 的 +/// 总量 1.8e19 超过 i64 上限,但单笔金额不会 —— 超了会在写入时报错而不是 +/// 静默截断,见 `outputs.amount_atomic` 的 CHECK)。 +const V1: &str = r#" +PRAGMA foreign_keys = ON; + +-- 钱包级元数据。单行表,id 恒为 0。 +CREATE TABLE IF NOT EXISTS wallet_meta ( + id INTEGER PRIMARY KEY CHECK (id = 0), + network TEXT NOT NULL, + created_at INTEGER NOT NULL +); + +-- 一个 identity = 一对观察密钥 = 宿主眼里的一个账户。 +-- +-- 存的是**观察材料**:花费公钥 + 私有观察密钥,等价于 Zcash 的 UFVK。 +-- 花费私钥永远不落库、不进这个 crate —— 签名走另一条路。 +CREATE TABLE IF NOT EXISTS identities ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + -- 宿主给的稳定标识,用来跨会话认人 + uuid TEXT NOT NULL UNIQUE, + -- 主地址(标准地址,非子地址),同时兼作人类可读的身份 + primary_address TEXT NOT NULL UNIQUE, + spend_public_key BLOB NOT NULL CHECK (length(spend_public_key) = 32), + view_private_key BLOB NOT NULL CHECK (length(view_private_key) = 32), + -- 从哪个高度开始扫。导入旧钱包时由宿主给。 + birthday_height INTEGER NOT NULL CHECK (birthday_height >= 0), + -- 本身份已经连续扫到的高度(含)。NULL = 一块都没扫过。 + -- + -- **必须按身份记**:拿别的身份的进度推算,会让一个刚追到链尖的身份把 + -- 另一个还在回补的身份的进度"推"到链尖,那段历史就被永久跳过了。 + scanned_to_height INTEGER, + created_at INTEGER NOT NULL +); + +-- 子地址注册表。扫描前要全部灌进 monero-oxide 的 Scanner —— 它只认注册过的。 +-- +-- (major, minor) 同为 0 是主地址,不进这张表(上游 SubaddressIndex::new +-- 对 (0,0) 返回 None)。 +CREATE TABLE IF NOT EXISTS subaddresses ( + identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, + major INTEGER NOT NULL CHECK (major >= 0), + minor INTEGER NOT NULL CHECK (minor >= 0), + address TEXT NOT NULL, + label TEXT, + PRIMARY KEY (identity_id, major, minor), + CHECK (major != 0 OR minor != 0) +); +CREATE INDEX IF NOT EXISTS idx_subaddresses_address ON subaddresses(address); + +-- 已扫区块的哈希与 RingCT 输出游标,每个身份各存一份。 +-- +-- 两个用途,都不可省: +-- +-- 1. **重组检测** —— 拉到新块时比对 prev_hash,对不上就是重组。 +-- 2. **RingCT 索引校验** —— 上游 `ScannableBlock` 的文档明确警告 +-- `output_index_for_first_ringct_output` **无法验证**,要求客户端自己维护 +-- 这个索引并与节点声称的比对,不一致应当判定节点提供了虚假视图并断开。 +-- `ringct_next` 存的就是"扫完本块之后下一个 RingCT 输出的全局序号"。 +-- +-- 不能各身份共用:一个身份回滚会删掉另一个身份的锚点,另一个身份接着在新链 +-- 上扫、看不出重组;追链尖的身份裁剪时也会裁掉还在回补的身份的锚点。 +-- +-- 只保留链尖往前 REORG_WINDOW_BLOCKS 块,不随链高无限增长。 +CREATE TABLE IF NOT EXISTS blocks ( + identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, + height INTEGER NOT NULL, + hash BLOB NOT NULL CHECK (length(hash) = 32), + -- 扫完本块之后下一个 RingCT 输出的全局序号。 + -- + -- **允许 NULL**:从链中段开始扫、且起始块恰好没有 RingCT 输出时,我们 + -- 没有任何依据推算这个游标。此时必须存 NULL 而不是 0 —— 存 0 会让下一块 + -- 拿真实序号(几千万)来比对 0,报出一个**假的** RINGCT_INDEX_MISMATCH, + -- 把一个诚实的节点判成作恶。 + ringct_next INTEGER CHECK (ringct_next IS NULL OR ringct_next >= 0), + timestamp INTEGER NOT NULL, + PRIMARY KEY (identity_id, height) +); + +-- 扫描进度。用区间而不是单个游标:导入旧钱包会产生"回补一段历史"与 +-- "追链尖"两条互不相邻的待扫区间。 +-- +-- Monero 没有承诺树,所以**不要求连续扫描**(Zcash 要求,因为 witness 必须 +-- 沿着树增量维护)。这让这张表比 Zcash 的扫描队列简单一个量级。 +CREATE TABLE IF NOT EXISTS scan_ranges ( + identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, + start_height INTEGER NOT NULL, + end_height INTEGER NOT NULL, + PRIMARY KEY (identity_id, start_height), + CHECK (end_height > start_height) +); + +-- 扫到的输出。 +-- +-- `blob` 是 monero-oxide `WalletOutput::serialize()` 的原样字节,花费时用 +-- `WalletOutput::read()` 读回 —— 这是整个落盘方案成立的关键 API。 +-- 其余列是从中抽出来供 SQL 查询的,**不是另一份真相**:任何要参与密码学的 +-- 地方都必须从 blob 反序列化,抽出来的列只用于筛选和展示。 +CREATE TABLE IF NOT EXISTS outputs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, + -- monero-oxide 的原样序列化,花费时读回 + blob BLOB NOT NULL, + -- ── 以下均为 blob 的派生列,仅供查询 ── + txid BLOB NOT NULL CHECK (length(txid) = 32), + -- 该输出在链上的全局序号,构环时要用 + global_index INTEGER NOT NULL, + index_in_tx INTEGER NOT NULL, + amount_atomic INTEGER NOT NULL CHECK (amount_atomic >= 0), + -- 收进哪个子地址;主地址存 NULL + subaddress_major INTEGER, + subaddress_minor INTEGER, + height INTEGER NOT NULL, + -- 额外时间锁(Monero 的 unlock_time),0 表示无 + additional_timelock INTEGER NOT NULL DEFAULT 0, + -- 花费检测用。需要花费密钥才能算,所以可能为空(只读观察钱包)。 + key_image BLOB CHECK (key_image IS NULL OR length(key_image) = 32), + -- 花在哪个高度;未花为 NULL + spent_at_height INTEGER, + spent_in_txid BLOB, + -- 交易公钥 R,多个则 32 字节一个顺序拼接(通常只有一个)。 + -- + -- monero-oxide 扫描时把 R 折叠进 `key_offset` 后丢掉,软件签名用不到它; + -- 硬件签名要(固件 `step_02_set_input.py` 自己推导一次性私钥,不接受宿主 + -- 算好的偏移)。扫过就没了,事后只能全量重扫或拿 txid 问节点(泄露隐私), + -- 所以扫描当下就得留。 + tx_pub_keys BLOB, + -- 子地址收款用的 additional keys,每个输出一个;没有则为 NULL。 + tx_additional_pub_keys BLOB, + -- 输出的一次性公钥,查燃烧 bug 用(同一个公钥只有一笔能花) + output_key BLOB CHECK (output_key IS NULL OR length(output_key) = 32), + UNIQUE (identity_id, txid, index_in_tx) +); +CREATE INDEX IF NOT EXISTS idx_outputs_unspent + ON outputs(identity_id, spent_at_height) WHERE spent_at_height IS NULL; +CREATE INDEX IF NOT EXISTS idx_outputs_height ON outputs(identity_id, height); +CREATE INDEX IF NOT EXISTS idx_outputs_key_image ON outputs(key_image) WHERE key_image IS NOT NULL; +CREATE INDEX IF NOT EXISTS idx_outputs_global ON outputs(identity_id, global_index); +CREATE INDEX IF NOT EXISTS idx_outputs_output_key ON outputs(identity_id, output_key); + +-- 交易索引。收款由扫描产出;花费由 key image 命中产出。 +CREATE TABLE IF NOT EXISTS transactions ( + identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, + txid BLOB NOT NULL CHECK (length(txid) = 32), + height INTEGER, -- NULL = 还在内存池 + timestamp INTEGER, + -- 'in' 收款 / 'out' 花费。一笔交易可能两者皆有(找零),此时记 'out'。 + direction TEXT NOT NULL CHECK (direction IN ('in', 'out')), + -- 以下是自己广播的交易的在途状态(wallet2 `process_unconfirmed_transfer` + -- 同款):迟迟不进内存池的判失败并放回它花的输出,否则那笔钱永远锁着。 + sent_at INTEGER, + pool_checked_at INTEGER, + failed INTEGER NOT NULL DEFAULT 0, + -- 付出去的总额(收款 + 手续费),piconero 十进制串。待确认期间只有广播时 + -- 知道(找零要上链扫到才有)。 + outgoing_atomic TEXT, + -- 待确认期间的找零,piconero 十进制串。wallet2 把它算进总余额(锁定), + -- 上链扫到后它变成一笔普通输出,这里就不再计。 + change_atomic TEXT, + PRIMARY KEY (identity_id, txid) +); +CREATE INDEX IF NOT EXISTS idx_transactions_height ON transactions(identity_id, height); + +-- 锁定中的输出:已被某笔待广播交易选中,不可再次选中。 +-- +-- 与 Zcash 同样的理由:不锁会导致同一个输出被两笔在途交易同时花掉, +-- 第二笔必然被网络拒绝,而用户看到的是"莫名其妙失败"。 +CREATE TABLE IF NOT EXISTS locked_outputs ( + output_id INTEGER PRIMARY KEY REFERENCES outputs(id) ON DELETE CASCADE, + reservation_id TEXT NOT NULL, + locked_at INTEGER NOT NULL, + -- 宿主签好名的时间。没签名的预留在下一次准备发送时作废(用户离开了确认页); + -- 签了名的要等广播结果或过期。 + signed_at INTEGER +); +CREATE INDEX IF NOT EXISTS idx_locked_reservation ON locked_outputs(reservation_id); + +-- 可能的花费(monero-lws 的做法)。 +-- +-- 观察钱包没有花费私钥,认不出自己的钱被花掉。但一笔钱被花时它必然出现在 +-- 那个输入的环里,所以扫描时把「环里含我的钱」的输入连同它的 key image 记下; +-- 等宿主凭密码(或硬件)补算出 key image,一比对就知道哪条是真的花费。 +-- 从没出现在任何环里的钱一定没花。只按全局序号比对,不需要任何密钥。 +CREATE TABLE IF NOT EXISTS possible_spends ( + identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, + -- 被引用的是哪笔我的输出:(txid, index_in_tx),与 outputs 的唯一键一致 + out_txid BLOB NOT NULL CHECK (length(out_txid) = 32), + out_index INTEGER NOT NULL, + -- 引用它的那个输入的 key image,以及那条交易 + key_image BLOB NOT NULL CHECK (length(key_image) = 32), + spend_txid BLOB NOT NULL CHECK (length(spend_txid) = 32), + height INTEGER NOT NULL, + timestamp INTEGER, + PRIMARY KEY (identity_id, out_txid, out_index, key_image) +); +CREATE INDEX IF NOT EXISTS idx_possible_spends_height ON possible_spends(identity_id, height); +"#; + +#[cfg(test)] +mod tests { + use super::*; + + fn db() -> Connection { + let conn = Connection::open_in_memory().expect("内存库"); + migrate(&conn).expect("建表"); + conn + } + + /// 交易公钥要能原样存进去、原样拿回来。 + /// + /// 硬件签名要的就是这串字节(固件拿它推导一次性私钥),存歪了不会报错, + /// 只会在将来某天让设备签出一笔花不掉的交易。 + /// + /// 复用 `db_with_identity`,不另起一份身份行的 fixture —— 那份会随表约束 + /// 变化而悄悄过期。 + #[test] + fn transaction_public_keys_round_trip() { + let (db, identity_id) = crate::wallet::testing::db_with_identity(); + let conn = db.conn(); + + let r = vec![0xABu8; 32]; + let additional = vec![0xCDu8; 64]; + conn.execute( + "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, + amount_atomic, height, tx_pub_keys, tx_additional_pub_keys) + VALUES (?1, x'00', ?2, 1, 0, 1, 1, ?3, ?4)", + rusqlite::params![identity_id, &vec![1u8; 32], &r, &additional], + ) + .unwrap(); + + let (got_r, got_additional): (Vec, Option>) = conn + .query_row( + "SELECT tx_pub_keys, tx_additional_pub_keys FROM outputs", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(got_r, r); + assert_eq!(got_additional, Some(additional)); + } + + /// 没有 additional keys 的交易(发给主地址)存 NULL,不是空串。 + /// 空串会让读取方以为「有 0 个 additional key」,和「这笔交易没有这个字段」 + /// 是两回事。 + #[test] + fn an_output_without_additional_keys_stores_null() { + let (db, identity_id) = crate::wallet::testing::db_with_identity(); + db.conn() + .execute( + "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, + amount_atomic, height, tx_pub_keys) + VALUES (?1, x'00', ?2, 1, 0, 1, 1, ?3)", + rusqlite::params![identity_id, &vec![2u8; 32], &vec![0xABu8; 32]], + ) + .unwrap(); + + let additional: Option> = db + .conn() + .query_row("SELECT tx_additional_pub_keys FROM outputs", [], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!(additional, None); + } + + #[test] + fn migrate_is_idempotent() { + let conn = db(); + migrate(&conn).expect("重复迁移应当无害"); + let v: i64 = conn + .query_row("PRAGMA user_version", [], |r| r.get(0)) + .unwrap(); + assert_eq!(v, SCHEMA_VERSION); + } + + #[test] + fn refuses_to_open_a_newer_database() { + let conn = Connection::open_in_memory().unwrap(); + conn.execute_batch("PRAGMA user_version = 999").unwrap(); + // 降级打开会让新版写入的数据被旧代码误读,宁可拒绝 + assert!(migrate(&conn).is_err()); + } + + #[test] + fn every_table_exists() { + let conn = db(); + for t in [ + "wallet_meta", + "identities", + "subaddresses", + "blocks", + "scan_ranges", + "outputs", + "transactions", + "locked_outputs", + "possible_spends", + ] { + let n: i64 = conn + .query_row( + "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?1", + [t], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(n, 1, "缺表 {t}"); + } + } + + /// (0,0) 是主地址,不该进子地址表 —— 上游 `SubaddressIndex::new(0,0)` + /// 返回 None,库里也要挡住,否则会注册出一个扫描器永远不认的条目。 + #[test] + fn subaddress_zero_zero_is_rejected() { + let conn = db(); + conn.execute( + "INSERT INTO identities (uuid, primary_address, spend_public_key, view_private_key, birthday_height, created_at) + VALUES ('u', 'addr', zeroblob(32), zeroblob(32), 0, 0)", + [], + ) + .unwrap(); + let bad = conn.execute( + "INSERT INTO subaddresses (identity_id, major, minor, address) VALUES (1, 0, 0, 'a')", + [], + ); + assert!(bad.is_err(), "(0,0) 必须被 CHECK 拦住"); + conn.execute( + "INSERT INTO subaddresses (identity_id, major, minor, address) VALUES (1, 0, 1, 'a')", + [], + ) + .expect("(0,1) 是合法子地址"); + } + + /// 同一个输出不能入库两次 —— 重扫同一段区间必须幂等,否则余额翻倍。 + #[test] + fn the_same_output_cannot_be_inserted_twice() { + let conn = db(); + conn.execute( + "INSERT INTO identities (uuid, primary_address, spend_public_key, view_private_key, birthday_height, created_at) + VALUES ('u', 'addr', zeroblob(32), zeroblob(32), 0, 0)", + [], + ) + .unwrap(); + let insert = "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, amount_atomic, height) + VALUES (1, x'00', zeroblob(32), 7, 0, 100, 10)"; + conn.execute(insert, []).expect("首次写入"); + assert!( + conn.execute(insert, []).is_err(), + "同一 (identity, txid, index_in_tx) 必须被唯一约束拦住" + ); + } + + /// 删除 identity 要连带清掉它的全部数据 —— 否则「删钱包」会留下可被后续 + /// 查询读到的孤儿行,那是隐私问题不只是脏数据。 + #[test] + fn deleting_an_identity_cascades() { + let conn = db(); + conn.execute("PRAGMA foreign_keys = ON", []).unwrap(); + conn.execute( + "INSERT INTO identities (uuid, primary_address, spend_public_key, view_private_key, birthday_height, created_at) + VALUES ('u', 'addr', zeroblob(32), zeroblob(32), 0, 0)", + [], + ) + .unwrap(); + conn.execute( + "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, amount_atomic, height) + VALUES (1, x'00', zeroblob(32), 7, 0, 100, 10)", + [], + ) + .unwrap(); + conn.execute( + "INSERT INTO subaddresses (identity_id, major, minor, address) VALUES (1, 0, 1, 'a')", + [], + ) + .unwrap(); + + conn.execute("DELETE FROM identities WHERE id = 1", []) + .unwrap(); + for t in ["outputs", "subaddresses"] { + let n: i64 = conn + .query_row(&format!("SELECT count(*) FROM {t}"), [], |r| r.get(0)) + .unwrap(); + assert_eq!(n, 0, "{t} 应当被级联清空"); + } + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs new file mode 100644 index 000000000..619ea371f --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs @@ -0,0 +1,1506 @@ +//! 花费路径:key image 导入、交易构造、签名、广播。 +//! +//! ## 花费私钥在这里出现,且只在这里 +//! +//! 它由宿主在每次调用时传进来,用完即擦,**永远不落库、不跨 wasm 边界返回**。 +//! 想审计「私钥去了哪」,看这一个文件。 +//! +//! ## 为什么需要导入 key image +//! +//! Monero 的观察钱包无法独立判断自己的输出有没有被花掉 —— 判断需要 key image, +//! 而 key image = `(花费私钥 + 输出偏移) × H(输出公钥)`,绕不开花费私钥。 +//! 这是协议性质,不是实现取舍。 +//! +//! 所以扫描只能记下输出,花费状态要等宿主在解锁时调一次 +//! [`import_key_images`] 才补得齐。补齐之前余额会**偏高**(已花的看起来还在)。 + +use std::collections::HashMap; + +use monero_wallet::{ + address::MoneroAddress, + ed25519::{Point, Scalar}, + send::{Change, SignableTransaction}, + OutputWithDecoys, WalletOutput, +}; +use rand_core::{CryptoRng, RngCore}; +use rusqlite::{params, OptionalExtension}; +use serde_json::{json, Value}; +use zeroize::Zeroizing; + +use crate::error::{db_err, ErrorCode, Result, RuntimeError}; +use crate::keys; +use crate::query; +use crate::wallet::Db; + +/// 环大小。当前共识值是 16(含真实成员)。 +/// +/// 写死而不是问节点:节点说小了会让交易在隐私上被削弱且可能被拒, +/// 这个值应当跟着硬分叉走,由我们发版控制。 +pub const RING_LEN: u8 = 16; + +/// 从花费私钥算出某笔输出的 key image。 +/// +/// 公式与上游 `SignableTransaction::sign` 内部一致: +/// `key_image = (spend + key_offset) × biased_hash(output_key)`。 +/// +/// 顺带校验了密钥是否真的对应这笔输出 —— 不对应就说明宿主传错了账户的种子, +/// 这时必须报错而不是算出一个无意义的 key image 存进库里(那会让花费检测 +/// 永远撞不上,表现为「这笔钱花了但钱包还显示在」)。 +fn key_image_for(output: &WalletOutput, spend: &Zeroizing) -> Result<[u8; 32]> { + use core::ops::Deref; + + let spend_dalek: curve25519_dalek::Scalar = (**spend).into(); + let offset: curve25519_dalek::Scalar = output.key_offset().into(); + let input_key = Zeroizing::new(spend_dalek + offset); + + let derived = + Point::from(input_key.deref() * curve25519_dalek::constants::ED25519_BASEPOINT_POINT); + if derived.compress().to_bytes() != output.key().compress().to_bytes() { + return Err(RuntimeError::with( + ErrorCode::InvalidKeyMaterial, + json!({ + "field": "spendPrivateKey", + "reason": "doesNotMatchOutput", + }), + )); + } + + let generator = Point::biased_hash(output.key().compress().to_bytes()); + let image = + Point::from(input_key.deref() * curve25519_dalek::EdwardsPoint::from(generator.into())); + Ok(image.compress().to_bytes()) +} + +/// 给还没有 key image 的输出补齐 key image。 +/// +/// 补齐之后花费检测才能工作。 +/// +/// 补齐之前已经发生的花费靠扫描时记下的「可能的花费」追认:一笔输出算出的 +/// key image 若出现在它的某条可能花费里,那条就是真的花费。之后的花费由正常 +/// 扫描识别,所以这笔输出的可能花费记录随即清掉。 +pub fn import_key_images( + db: &mut Db, + identity_id: i64, + spend_private: &[u8], +) -> Result { + let spend = parse_spend_key(spend_private)?; + + let pending: Vec<(i64, Vec, Vec, i64)> = { + let mut stmt = db + .conn() + .prepare( + "SELECT id, blob, txid, index_in_tx FROM outputs + WHERE identity_id = ?1 AND key_image IS NULL", + ) + .map_err(|e| db_err("listOutputsWithoutKeyImage", e))?; + let rows = stmt + .query_map([identity_id], |r| { + Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)) + }) + .map_err(|e| db_err("listOutputsWithoutKeyImage", e))?; + rows.collect::>>() + .map_err(|e| db_err("listOutputsWithoutKeyImage", e))? + }; + + let mut computed = Vec::with_capacity(pending.len()); + for (id, blob, txid, index) in pending { + let output = WalletOutput::read(&mut blob.as_slice()) + .map_err(|e| db_err("deserializeOutput", format!("输出 {id}: {e}")))?; + computed.push((id, key_image_for(&output, &spend)?, txid, index)); + } + apply_key_images(db, identity_id, &computed) +} + +/// 写回算好的 key image,并用「可能的花费」追认早已发生的花费。 +/// 与计算分开,好让比对逻辑脱离真实输出单独测试。 +fn apply_key_images( + db: &mut Db, + identity_id: i64, + computed: &[(i64, [u8; 32], Vec, i64)], +) -> Result { + let tx = db + .conn_mut() + .transaction() + .map_err(|e| db_err("beginImportKeyImages", e))?; + let mut spends_found = 0; + for (id, image, txid, index) in computed { + tx.execute( + "UPDATE outputs SET key_image = ?1 WHERE id = ?2", + params![image.as_slice(), id], + ) + .map_err(|e| db_err("updateKeyImage", e))?; + + let spent: Option<(Vec, i64, Option)> = tx + .query_row( + "SELECT spend_txid, height, timestamp FROM possible_spends + WHERE identity_id = ?1 AND out_txid = ?2 AND out_index = ?3 AND key_image = ?4 + ORDER BY height LIMIT 1", + params![identity_id, txid, index, image.as_slice()], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) + .optional() + .map_err(|e| db_err("matchPossibleSpend", e))?; + if let Some((spend_txid, height, timestamp)) = spent { + tx.execute( + "UPDATE outputs SET spent_at_height = ?1, spent_in_txid = ?2 + WHERE id = ?3 AND spent_at_height IS NULL", + params![height, spend_txid, id], + ) + .map_err(|e| db_err("markPossibleSpend", e))?; + tx.execute( + "INSERT INTO transactions (identity_id, txid, height, timestamp, direction) + VALUES (?1, ?2, ?3, ?4, 'out') + ON CONFLICT (identity_id, txid) DO UPDATE + SET direction = 'out', height = ?3, failed = 0, + timestamp = COALESCE(excluded.timestamp, transactions.timestamp)", + params![identity_id, spend_txid, height, timestamp], + ) + .map_err(|e| db_err("recordPossibleSpend", e))?; + spends_found += 1; + } + tx.execute( + "DELETE FROM possible_spends + WHERE identity_id = ?1 AND out_txid = ?2 AND out_index = ?3", + params![identity_id, txid, index], + ) + .map_err(|e| db_err("clearPossibleSpends", e))?; + } + tx.commit() + .map_err(|e| db_err("commitImportKeyImages", e))?; + + Ok(KeyImageImport { + imported: computed.len(), + spends_found, + }) +} + +/// `import_key_images` 的结果。 +pub struct KeyImageImport { + /// 这次补算了几笔输出的 key image。 + pub imported: usize, + /// 其中几笔借「可能的花费」追认为早已花掉。 + pub spends_found: usize, +} + +fn parse_spend_key(bytes: &[u8]) -> Result> { + let arr = <[u8; 32]>::try_from(bytes).map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidKeyMaterial, + json!({ "field": "spendPrivateKey", "byteLen": bytes.len(), "expected": 32 }), + ) + })?; + let scalar = Scalar::read(&mut arr.as_slice()).map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidKeyMaterial, + json!({ "field": "spendPrivateKey", "reason": "notCanonicalScalar" }), + ) + })?; + Ok(Zeroizing::new(scalar)) +} + +/// 一笔待发交易的收款项。 +#[derive(Debug, Clone)] +pub struct Payment { + pub address: MoneroAddress, + pub amount_atomic: u64, +} + +/// 选币结果与预留。 +#[derive(Debug, Clone)] +pub struct Selection { + pub output_ids: Vec, + pub total_atomic: u64, +} + +/// 选币:大额优先,凑够 `needed` 为止。 +/// +/// 大额优先的理由是手续费:Monero 按交易重量计费,输入越少越便宜。代价是 +/// 会更快把大额输出打碎 —— 这个取舍和 wallet2 的默认行为一致。 +pub fn select_inputs( + db: &Db, + identity_id: i64, + chain_tip: u64, + needed_atomic: u64, +) -> Result { + let rows = query::spendable_rows(db, identity_id, chain_tip)?; + + let mut picked = Vec::new(); + let mut total: u64 = 0; + for row in rows { + picked.push(row.id); + total = total.checked_add(row.amount_atomic).ok_or_else(|| { + RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "amount", "reason": "totalOverflow" }), + ) + })?; + if total >= needed_atomic { + break; + } + } + + if total < needed_atomic { + return Err(RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ + "field": "amount", + "reason": "insufficientUnlockedFunds", + "availableAtomic": total.to_string(), + "neededAtomic": needed_atomic.to_string(), + }), + )); + } + + Ok(Selection { + output_ids: picked, + total_atomic: total, + }) +} + +/// 预留多久没广播就作废。Monero 交易没有过期高度,只能按时间。 +/// +/// 作废之后再广播也不会丢记账(广播按交易里的 key image 标记已花),最坏是 +/// 期间另一笔选中同样的输出、其中一笔被节点拒收。 +pub const RESERVATION_TTL_SECS: i64 = 60 * 60; + +/// 仍然有效的预留的下限时间:`locked_at` 大于它才算数。 +pub fn reservation_cutoff() -> i64 { + crate::wallet::now_secs() - RESERVATION_TTL_SECS +} + +/// 预留选中的输出,防止被第二笔在途交易重复选中。 +/// +/// 不预留的后果很具体:两笔交易花同一个输出,第二笔必然被网络拒绝, +/// 而用户看到的是「莫名其妙失败」。 +pub fn reserve(db: &mut Db, reservation_id: &str, output_ids: &[i64]) -> Result<()> { + let now = crate::wallet::now_secs(); + let tx = db + .conn_mut() + .transaction() + .map_err(|e| db_err("beginReserve", e))?; + // 用户在确认页退出不会通知这里,作废的预留只能在这时清掉。 + tx.execute( + "DELETE FROM locked_outputs WHERE locked_at <= ?1", + [now - RESERVATION_TTL_SECS], + ) + .map_err(|e| db_err("expireReservations", e))?; + for id in output_ids { + // 已被别人预留时这里会因为主键冲突而失败 —— 那正是我们要的: + // 宁可这笔构造不出来,也不要构造出一笔注定被拒的交易。 + tx.execute( + "INSERT INTO locked_outputs (output_id, reservation_id, locked_at) VALUES (?1, ?2, ?3)", + params![id, reservation_id, now], + ) + .map_err(|e| { + db_err( + "reserveOutput", + format!("输出 {id} 可能已被另一笔在途交易预留: {e}"), + ) + })?; + } + tx.commit().map_err(|e| db_err("commitReserve", e)) +} + +/// 宿主签好名了:这笔预留不再算作被放弃的。 +pub fn mark_signed(db: &Db, reservation_id: &str) -> Result { + db.conn() + .execute( + "UPDATE locked_outputs SET signed_at = ?2 WHERE reservation_id = ?1", + params![reservation_id, crate::wallet::now_secs()], + ) + .map_err(|e| db_err("markReservationSigned", e)) +} + +/// 放掉本身份所有没签名的预留。 +/// +/// 用户在确认页返回、改完再下一步时不会通知这里;新的一次准备就说明前一次 +/// 没签名的已经没人要了。签了名的不动:它可能正在广播。 +fn release_unsigned(db: &Db, identity_id: i64) -> Result { + db.conn() + .execute( + "DELETE FROM locked_outputs + WHERE signed_at IS NULL + AND output_id IN (SELECT id FROM outputs WHERE identity_id = ?1)", + [identity_id], + ) + .map_err(|e| db_err("releaseUnsignedReservations", e)) +} + +/// 释放预留(用户取消,或构造失败)。 +pub fn release(db: &Db, reservation_id: &str) -> Result { + let n = db + .conn() + .execute( + "DELETE FROM locked_outputs WHERE reservation_id = ?1", + [reservation_id], + ) + .map_err(|e| db_err("release", e))?; + Ok(n) +} + +/// 一笔构造完成、等待签名的交易。 +pub struct Prepared { + pub signable: SignableTransaction, + pub output_ids: Vec, + pub inputs_atomic: u64, + /// 收款方实际收到的总额。max-send 时这是反算出来的,不等于宿主传入的值。 + pub amount_atomic: u64, + pub fee_atomic: u64, +} + +/// 给一个输出取一环诱饵。 +/// +/// 诱饵必须在**当前**链高上选:用旧高度会让环成员分布偏离当下的链上分布, +/// 那是可被统计分析利用的指纹。 +/// monerod 的拒收原因按标志拼接,双花写作 "double spend"。 +fn is_double_spend(error: &RuntimeError) -> bool { + error + .detail + .as_deref() + .is_some_and(|reason| reason.to_lowercase().contains("double spend")) +} + +/// 一次构造里所有输入共用同一份 RingCT 输出分布。 +/// +/// 上游每选一组诱饵都向节点要一次整条链的分布(约 18MB),N 个输入就下 N 份, +/// 移动端经宿主转发很容易超时。范围相同就复用,节点只问一次。 +struct CachedDecoys<'a, P> { + inner: &'a P, + distributions: + std::sync::Mutex, std::ops::Bound), Vec>>, +} + +impl<'a, P> CachedDecoys<'a, P> { + fn new(inner: &'a P) -> Self { + Self { + inner, + distributions: std::sync::Mutex::new(HashMap::new()), + } + } +} + +impl monero_wallet::interface::ProvidesBlockchainMeta + for CachedDecoys<'_, P> +{ + fn latest_block_number( + &self, + ) -> impl Send + + std::future::Future< + Output = std::result::Result, + > { + self.inner.latest_block_number() + } +} + +impl + monero_wallet::interface::ProvidesUnvalidatedDecoys for CachedDecoys<'_, P> +{ + fn ringct_output_distribution( + &self, + range: impl Send + std::ops::RangeBounds, + ) -> impl Send + + std::future::Future< + Output = std::result::Result, monero_wallet::interface::InterfaceError>, + > { + let key = (range.start_bound().cloned(), range.end_bound().cloned()); + async move { + let cached = self + .distributions + .lock() + .ok() + .and_then(|map| map.get(&key).cloned()); + if let Some(distribution) = cached { + return Ok(distribution); + } + let distribution = + monero_wallet::interface::ProvidesDecoys::ringct_output_distribution( + self.inner, key, + ) + .await?; + if let Ok(mut map) = self.distributions.lock() { + map.insert(key, distribution.clone()); + } + Ok(distribution) + } + } + + fn unlocked_ringct_outputs( + &self, + indexes: &[u64], + evaluate_unlocked: monero_wallet::interface::EvaluateUnlocked, + ) -> impl Send + + std::future::Future< + Output = std::result::Result< + Vec>, + monero_wallet::interface::TransactionsError, + >, + > { + monero_wallet::interface::ProvidesDecoys::unlocked_ringct_outputs( + self.inner, + indexes, + evaluate_unlocked, + ) + } +} + +async fn ring_for( + db: &Db, + decoy_source: &impl monero_wallet::interface::ProvidesDecoys, + rng: &mut R, + output_id: i64, + chain_tip: u64, +) -> Result { + let output = query::load_output(db, output_id)?; + OutputWithDecoys::new(rng, decoy_source, RING_LEN, chain_tip as usize, output) + .await + .map_err(|e| { + RuntimeError::with( + ErrorCode::NetworkError, + json!({ "operation": "selectDecoys", "outputId": output_id }), + ) + .detail(format!("{e:?}")) + }) +} + +/// 取一组输出的环,已经取过的直接复用。 +/// +/// 复用不是优化细节:每个输入要十几个诱饵,重取一轮就是十几个网络往返。 +async fn rings_for( + db: &Db, + decoy_source: &impl monero_wallet::interface::ProvidesDecoys, + rng: &mut R, + output_ids: &[i64], + chain_tip: u64, + cache: &mut HashMap, +) -> Result> { + let mut inputs = Vec::with_capacity(output_ids.len()); + for id in output_ids { + if !cache.contains_key(id) { + let ring = ring_for(db, decoy_source, rng, *id, chain_tip).await?; + cache.insert(*id, ring); + } + inputs.push(cache[id].clone()); + } + Ok(inputs) +} + +/// 组装一笔 `SignableTransaction`。找零永远回到本账户主地址。 +fn assemble( + identity: &crate::wallet::Identity, + rng: &mut R, + rct_type: monero_wallet::ringct::RctType, + inputs: Vec, + recipients: Vec<(MoneroAddress, u64)>, + fee_rate: monero_wallet::interface::FeeRate, +) -> std::result::Result { + let change = Change::new(identity.view_pair.clone(), None); + + // `outgoing_view_key` 给这笔交易的确定性 RNG 做种子。**绝不能跨交易复用** + // —— 上游文档明写复用会导致临时秘密被重复使用。每次现取。 + let mut ovk = Zeroizing::new([0u8; 32]); + rng.fill_bytes(ovk.as_mut()); + + SignableTransaction::new( + rct_type, + ovk, + inputs, + recipients, + change, + Vec::new(), + fee_rate, + ) +} + +fn build_error(e: monero_wallet::send::SendError) -> RuntimeError { + RuntimeError::with(ErrorCode::InvalidRequest, json!({ "field": "transaction" })) + .detail(format!("{e:?}")) +} + +/// 选币 + 构造,**不需要花费私钥**。 +/// +/// 返回的 `Prepared` 带着这笔交易真正要付的手续费,宿主据此在确认页上显示 —— +/// 显示的数就是会扣的数。在别处照抄一遍上游的重量公式只会让两个数慢慢分家。 +/// +/// ## 为什么要迭代 +/// +/// 手续费按交易重量算,重量取决于输入个数,而要凑几个输入又取决于手续费。 +/// 先按「只够付金额」选一轮,让上游把真实手续费算出来(`NotEnoughFunds` 里 +/// 带着它),不够就按新的目标再选。实测两轮收敛。 +#[allow(clippy::too_many_arguments)] +pub async fn prepare( + db: &Db, + decoy_source: &impl monero_wallet::interface::ProvidesDecoys, + rng: &mut R, + identity_id: i64, + payments: &[Payment], + fee_rate: monero_wallet::interface::FeeRate, + chain_tip: u64, + rct_type: monero_wallet::ringct::RctType, +) -> Result { + use monero_wallet::send::SendError; + + let identity = db.identity_by_id(identity_id)?; + let out_total = sum_payments(payments)?; + let recipients: Vec<(MoneroAddress, u64)> = payments + .iter() + .map(|p| (p.address, p.amount_atomic)) + .collect(); + + let mut cache: HashMap = HashMap::new(); + let mut needed = out_total; + + // 三轮:第一轮不含手续费,第二轮按真实手续费重选,第三轮兜住「补的输入 + // 又把手续费抬上去了」。再不收敛就是钱确实不够。 + for _ in 0..3 { + let selection = select_inputs(db, identity_id, chain_tip, needed)?; + let inputs = rings_for( + db, + decoy_source, + rng, + &selection.output_ids, + chain_tip, + &mut cache, + ) + .await?; + + match assemble( + &identity, + rng, + rct_type, + inputs, + recipients.clone(), + fee_rate, + ) { + Ok(signable) => { + let fee_atomic = signable.necessary_fee(); + return Ok(Prepared { + signable, + output_ids: selection.output_ids, + inputs_atomic: selection.total_atomic, + amount_atomic: out_total, + fee_atomic, + }); + } + Err(SendError::NotEnoughFunds { + outputs, + necessary_fee: Some(fee), + .. + }) => { + // 上游算出了真实手续费,按它重新定目标。 + let next = outputs.checked_add(fee).ok_or_else(overflow)?; + if next <= needed { + // 目标没往上走却仍然构不出来:再循环也是同一个结果。 + return Err(insufficient(selection.total_atomic, next)); + } + needed = next; + } + Err(e) => return Err(build_error(e)), + } + } + + Err(insufficient(0, needed)) +} + +/// 把这个账户当前能花的**全部**输出发给一个地址。 +/// +/// 不能靠「不给找零输出」来实现 —— 上游明写那样会把余数全部并进手续费, +/// 等于白送矿工。正确做法是先拿到这笔交易真实的手续费,再反算金额。 +/// +/// 金额不影响交易重量(RingCT 的金额是定长密文),所以先用 1 piconero 试 +/// 构一次拿手续费,再用 `总额 - 手续费` 正式构造,两次重量一致。 +#[allow(clippy::too_many_arguments)] +pub async fn prepare_max( + db: &Db, + decoy_source: &impl monero_wallet::interface::ProvidesDecoys, + rng: &mut R, + identity_id: i64, + recipient: MoneroAddress, + fee_rate: monero_wallet::interface::FeeRate, + chain_tip: u64, + rct_type: monero_wallet::ringct::RctType, +) -> Result { + use monero_wallet::send::SendError; + + let identity = db.identity_by_id(identity_id)?; + let rows = query::spendable_rows(db, identity_id, chain_tip)?; + if rows.is_empty() { + return Err(insufficient(0, 1)); + } + + let mut output_ids = Vec::with_capacity(rows.len()); + let mut inputs_atomic: u64 = 0; + for row in &rows { + output_ids.push(row.id); + inputs_atomic = inputs_atomic + .checked_add(row.amount_atomic) + .ok_or_else(overflow)?; + } + + let mut cache: HashMap = HashMap::new(); + let inputs = rings_for(db, decoy_source, rng, &output_ids, chain_tip, &mut cache).await?; + + // 试构一次只为拿手续费。成功失败都给得出:成功读 `necessary_fee()`, + // 失败时 `NotEnoughFunds` 里也带着它。 + let fee_atomic = match assemble( + &identity, + rng, + rct_type, + inputs.clone(), + vec![(recipient, 1)], + fee_rate, + ) { + Ok(probe) => probe.necessary_fee(), + Err(SendError::NotEnoughFunds { + necessary_fee: Some(fee), + .. + }) => fee, + Err(e) => return Err(build_error(e)), + }; + + let amount_atomic = inputs_atomic + .checked_sub(fee_atomic) + .filter(|a| *a > 0) + .ok_or_else(|| insufficient(inputs_atomic, fee_atomic.saturating_add(1)))?; + + let signable = assemble( + &identity, + rng, + rct_type, + inputs, + vec![(recipient, amount_atomic)], + fee_rate, + ) + .map_err(build_error)?; + + Ok(Prepared { + signable, + output_ids, + inputs_atomic, + amount_atomic, + fee_atomic, + }) +} + +fn sum_payments(payments: &[Payment]) -> Result { + let mut total: u64 = 0; + for payment in payments { + total = total + .checked_add(payment.amount_atomic) + .ok_or_else(overflow)?; + } + Ok(total) +} + +fn overflow() -> RuntimeError { + RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "amount", "reason": "totalOverflow" }), + ) +} + +fn insufficient(available: u64, needed: u64) -> RuntimeError { + RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ + "field": "amount", + "reason": "insufficientUnlockedFunds", + "availableAtomic": available.to_string(), + "neededAtomic": needed.to_string(), + }), + ) +} + +/// 签名一笔已构造的交易。**不碰网络,不碰数据库。** +/// +/// `spend_private` 用完即擦。返回可直接广播的交易字节与 txid。 +pub fn sign_prepared( + signable: SignableTransaction, + rng: &mut R, + spend_private: &[u8], +) -> Result<(Vec, [u8; 32])> { + let spend = parse_spend_key(spend_private)?; + let signed = signable.sign(rng, &spend).map_err(|e| { + RuntimeError::with(ErrorCode::InvalidRequest, json!({ "field": "signature" })) + .detail(format!("{e:?}")) + })?; + let txid = signed.hash(); + Ok((signed.serialize(), txid)) +} + +/// 广播。**不可逆。** +pub async fn broadcast(daemon: &crate::network::Daemon, raw: &[u8]) -> Result<()> { + use monero_daemon_rpc::prelude::*; + + let tx = monero_wallet::transaction::Transaction::read(&mut &*raw) + .map_err(|e| db_err("parseSignedTransaction", e))?; + daemon.publish_transaction(&tx).await.map_err(|e| match e { + PublishTransactionError::TransactionRejected(reason) => { + RuntimeError::new(ErrorCode::BroadcastRejected).detail(reason) + } + PublishTransactionError::InterfaceError(e) => RuntimeError::with( + ErrorCode::NetworkError, + json!({ "operation": "publishTransaction" }), + ) + .detail(format!("{e:?}")), + }) +} + +/// 校验一个收款地址并解析金额,给宿主一个统一的入口。 +pub fn parse_payment( + network: monero_wallet::address::Network, + address: &str, + amount_atomic: &str, +) -> Result { + let address = keys::parse_address(network, address, "recipient.address")?; + let amount_atomic: u64 = amount_atomic.parse().map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "recipient.amountAtomic", "reason": "notAnUnsignedInteger" }), + ) + })?; + if amount_atomic == 0 { + return Err(RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "recipient.amountAtomic", "reason": "mustBePositive" }), + )); + } + Ok(Payment { + address, + amount_atomic, + }) +} + +pub fn selection_to_json(selection: &Selection) -> Value { + json!({ + "outputIds": selection.output_ids, + "totalAtomic": selection.total_atomic.to_string(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wallet::testing::db_with_identity; + use monero_wallet::address::Network; + + fn add_output(db: &Db, identity_id: i64, amount: i64, height: i64, with_ki: bool) -> i64 { + let ki: Option> = with_ki.then(|| { + let mut k = vec![0u8; 32]; + k[0] = (amount % 251) as u8; + k[1] = (height % 251) as u8; + k + }); + db.conn() + .execute( + "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, + amount_atomic, height, key_image) + VALUES (?1, x'00', ?2, ?3, 0, ?4, ?5, ?6)", + params![ + identity_id, + &vec![height as u8; 32], + height, + amount, + height, + ki + ], + ) + .unwrap(); + db.conn().last_insert_rowid() + } + + fn add_possible_spend(db: &Db, id: i64, out_height: i64, key_image: u8, spend: u8, at: i64) { + db.conn() + .execute( + "INSERT INTO possible_spends + (identity_id, out_txid, out_index, key_image, spend_txid, height, timestamp) + VALUES (?1, ?2, 0, ?3, ?4, ?5, 1700000000)", + params![ + id, + vec![out_height as u8; 32], + vec![key_image; 32], + vec![spend; 32], + at + ], + ) + .unwrap(); + } + + /// 补算出的 key image 若出现在这笔输出的某条可能花费里,那条就是真花费: + /// 标成已花、补一条出账记录。只是被别人当诱饵的(key image 对不上)不算。 + #[test] + fn a_key_image_found_among_possible_spends_confirms_an_earlier_spend() { + let (mut db, id) = db_with_identity(); + let spent = add_output(&db, id, 700, 10, false); + let decoyed = add_output(&db, id, 300, 11, false); + add_possible_spend(&db, id, 10, 0xAA, 0x51, 30); // 真的:key image 对得上 + add_possible_spend(&db, id, 10, 0xBB, 0x52, 31); // 别人拿它当诱饵 + add_possible_spend(&db, id, 11, 0xCC, 0x53, 32); // 别人拿它当诱饵 + + let result = apply_key_images( + &mut db, + id, + &[ + (spent, [0xAA; 32], vec![10; 32], 0), + (decoyed, [0xDD; 32], vec![11; 32], 0), + ], + ) + .unwrap(); + assert_eq!((result.imported, result.spends_found), (2, 1)); + + let (height, txid): (Option, Option>) = db + .conn() + .query_row( + "SELECT spent_at_height, spent_in_txid FROM outputs WHERE id = ?1", + [spent], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .unwrap(); + assert_eq!((height, txid), (Some(30), Some(vec![0x51; 32]))); + let decoyed_spent: Option = db + .conn() + .query_row( + "SELECT spent_at_height FROM outputs WHERE id = ?1", + [decoyed], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(decoyed_spent, None, "只是被当诱饵,没花"); + + let (direction, out_height): (String, i64) = db + .conn() + .query_row( + "SELECT direction, height FROM transactions WHERE txid = ?1", + [vec![0x51u8; 32]], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .unwrap(); + assert_eq!((direction.as_str(), out_height), ("out", 30)); + let left: i64 = db + .conn() + .query_row("SELECT count(*) FROM possible_spends", [], |r| r.get(0)) + .unwrap(); + assert_eq!(left, 0, "有了 key image 的输出不再需要可能花费记录"); + } + + /// 签名入口不碰网络也不碰库,所以它唯一能出的错就是入参形状。 + /// 这里盯的是「坏输入必须报错」——静默接受会让一笔垃圾交易一路走到广播。 + #[test] + fn signing_rejects_a_blob_that_is_not_a_signable_transaction() { + let e = sign_for_host("zz", &[0u8; 32]).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidRequest); + assert_eq!(e.params["reason"], "notHex"); + + let e = sign_for_host("00010203", &[0u8; 32]).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidRequest); + assert_eq!(e.params["reason"], "notASignableTransaction"); + } + + /// 金额相加溢出必须报错而不是回绕。回绕会让一笔「收款方总额 0」的交易 + /// 被当成合法请求构造出去。 + #[test] + fn payment_totals_do_not_wrap_on_overflow() { + let address = keys::parse_address( + monero_wallet::address::Network::Mainnet, + "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge", + "recipient.address", + ) + .unwrap(); + let payments = vec![ + Payment { + address, + amount_atomic: u64::MAX, + }, + Payment { + address, + amount_atomic: 1, + }, + ]; + let e = sum_payments(&payments).unwrap_err(); + assert_eq!(e.params["reason"], "totalOverflow"); + } + + #[test] + fn spend_key_length_is_enforced() { + let e = parse_spend_key(&[0u8; 31]).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidKeyMaterial); + assert_eq!(e.params["byteLen"], 31); + } + + /// 大额优先:Monero 按重量计费,输入越少越便宜。 + #[test] + fn selection_prefers_large_outputs_and_stops_once_covered() { + let (db, id) = db_with_identity(); + add_output(&db, id, 100, 10, true); + add_output(&db, id, 900, 11, true); + add_output(&db, id, 500, 12, true); + + let s = select_inputs(&db, id, 100, 1_000).unwrap(); + assert_eq!(s.total_atomic, 1_400, "900 + 500 就够了,不该再拿 100"); + assert_eq!(s.output_ids.len(), 2); + } + + #[test] + fn selection_fails_loudly_when_funds_are_short() { + let (db, id) = db_with_identity(); + add_output(&db, id, 100, 10, true); + let e = select_inputs(&db, id, 100, 1_000).unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidRequest); + assert_eq!(e.params["reason"], "insufficientUnlockedFunds"); + assert_eq!(e.params["availableAtomic"], "100"); + } + + /// 没有 key image 的输出不能参与花费 —— 无法确认它没被花掉, + /// 拿它构造交易有双花风险。 + #[test] + fn outputs_without_key_images_are_never_selected() { + let (db, id) = db_with_identity(); + add_output(&db, id, 5_000, 10, false); + let e = select_inputs(&db, id, 100, 1_000).unwrap_err(); + assert_eq!(e.params["reason"], "insufficientUnlockedFunds"); + } + + /// 锁定期内的输出也不能选 —— 构不进环,节点会拒。 + #[test] + fn locked_outputs_are_not_selected() { + let (db, id) = db_with_identity(); + add_output(&db, id, 5_000, 95, true); + // 链尖 100,输出在 95:差 5 块,未满 10 块锁定 + let e = select_inputs(&db, id, 100, 1_000).unwrap_err(); + assert_eq!(e.params["reason"], "insufficientUnlockedFunds"); + // 到 105 就够了 + assert!(select_inputs(&db, id, 105, 1_000).is_ok()); + } + + #[test] + fn an_expired_reservation_gives_way_to_a_new_one() { + let (mut db, id) = db_with_identity(); + let a = add_output(&db, id, 500, 10, true); + db.conn() + .execute( + "INSERT INTO locked_outputs (output_id, reservation_id, locked_at) VALUES (?1, 'old', ?2)", + params![a, reservation_cutoff() - 1], + ) + .unwrap(); + reserve(&mut db, "new", &[a]).expect("过期的预留不该挡路"); + } + + /// 用户离开确认页后,下一次准备发送放掉没签名的预留;签了名的可能正在 + /// 广播,要留着。 + #[test] + fn a_new_send_releases_only_unsigned_reservations() { + let (mut db, id) = db_with_identity(); + let abandoned = add_output(&db, id, 500, 10, true); + let signed = add_output(&db, id, 400, 11, true); + reserve(&mut db, "abandoned", &[abandoned]).unwrap(); + reserve(&mut db, "signed", &[signed]).unwrap(); + mark_signed(&db, "signed").unwrap(); + + assert_eq!(release_unsigned(&db, id).unwrap(), 1); + + let left: Vec = db + .conn() + .prepare("SELECT reservation_id FROM locked_outputs") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(left, vec!["signed".to_string()]); + } + + /// wallet2 同款:待确认发送的找零计入总余额(锁定),不计入可用;判失败后不再计。 + #[test] + fn pending_change_counts_in_total_until_the_send_fails() { + let (db, id) = db_with_identity(); + let spent = add_output(&db, id, 500, 10, true); + let key_image: Vec = db + .conn() + .query_row( + "SELECT key_image FROM outputs WHERE id = ?1", + [spent], + |r| r.get(0), + ) + .unwrap(); + let key_image = <[u8; 32]>::try_from(key_image.as_slice()).unwrap(); + let txid = [0x55u8; 32]; + record_broadcast( + &db, + id, + &txid, + &[key_image], + "r", + 900, + SentAmounts { + outgoing_atomic: Some(200), + change_atomic: Some(300), + }, + ) + .unwrap(); + + let b = crate::query::balance(&db, id, Some(10_000)).unwrap(); + assert_eq!(b.total_atomic, 300); + assert_eq!(b.pending_change_atomic, 300); + assert_eq!(b.unlocked_atomic, 0); + + crate::pool::mark_failed(&db, id, &txid).unwrap(); + let b = crate::query::balance(&db, id, Some(10_000)).unwrap(); + assert_eq!(b.pending_change_atomic, 0); + assert_eq!(b.total_atomic, 500); + } + + /// 广播后按交易里的 key image 标已花:预留过期或被释放了也不能漏记。 + #[test] + fn a_broadcast_marks_its_inputs_by_key_image_without_a_reservation() { + let (db, id) = db_with_identity(); + let a = add_output(&db, id, 500, 10, true); + let untouched = add_output(&db, id, 400, 11, true); + let key_image: Vec = db + .conn() + .query_row("SELECT key_image FROM outputs WHERE id = ?1", [a], |r| { + r.get(0) + }) + .unwrap(); + let key_image = <[u8; 32]>::try_from(key_image.as_slice()).unwrap(); + let txid = [0x77u8; 32]; + + record_broadcast( + &db, + id, + &txid, + &[key_image], + "gone", + 900, + SentAmounts { + outgoing_atomic: Some(123), + change_atomic: None, + }, + ) + .unwrap(); + + let spent: Vec<(i64, Option>)> = db + .conn() + .prepare("SELECT id, spent_in_txid FROM outputs ORDER BY id") + .unwrap() + .query_map([], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(spent, vec![(a, Some(txid.to_vec())), (untouched, None)]); + let outgoing: Option = db + .conn() + .query_row( + "SELECT outgoing_atomic FROM transactions WHERE txid = ?1", + [txid.as_slice()], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(outgoing.as_deref(), Some("123")); + } + + /// 同一笔输出不能被两个预留同时持有 —— 否则两笔交易花同一个输出, + /// 第二笔必然被网络拒绝。 + #[test] + fn an_output_cannot_be_reserved_twice() { + let (mut db, id) = db_with_identity(); + let a = add_output(&db, id, 5_000, 10, true); + reserve(&mut db, "r1", &[a]).unwrap(); + assert!(reserve(&mut db, "r2", &[a]).is_err(), "第二次预留必须失败"); + assert_eq!(release(&db, "r1").unwrap(), 1); + reserve(&mut db, "r2", &[a]).expect("释放后可以重新预留"); + } + + #[test] + fn releasing_an_unknown_reservation_is_a_no_op() { + let (mut db, _) = db_with_identity(); + assert_eq!(release(&db, "nope").unwrap(), 0); + } + + #[test] + fn payments_reject_zero_and_non_numeric_amounts() { + let addr = crate::wallet::testing::ADDR; + assert!(parse_payment(Network::Mainnet, addr, "0").is_err()); + assert!(parse_payment(Network::Mainnet, addr, "-1").is_err()); + assert!(parse_payment(Network::Mainnet, addr, "abc").is_err()); + assert!(parse_payment(Network::Mainnet, addr, "1000").is_ok()); + } + + /// 金额走字符串跨边界:piconero 上限超过 JS 的 MAX_SAFE_INTEGER。 + #[test] + fn large_amounts_survive_the_string_boundary() { + let addr = crate::wallet::testing::ADDR; + let big = (u64::MAX / 2).to_string(); + let p = parse_payment(Network::Mainnet, addr, &big).unwrap(); + assert_eq!(p.amount_atomic.to_string(), big); + } + + #[test] + fn a_mainnet_address_is_refused_on_testnet() { + let addr = crate::wallet::testing::ADDR; + let e = parse_payment(Network::Testnet, addr, "1000").unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidAddress); + } +} + +// ── 端到端发送 ────────────────────────────────────────────────────────── + +/// 手续费率的理智上限(piconero / weight)。 +/// +/// 上游 `fee_rate` 强制要求给一个上限,理由很实在:**手续费率来自节点, +/// 而节点可能撒谎**。报一个天价费率会让用户把余额全付成手续费。 +/// +/// Monero 常规优先级的费率约在 20,000 piconero/weight 量级,最高优先级约 +/// 十倍。这里取 1,000,000 —— 比最高优先级还宽 5 倍,正常波动碰不到, +/// 但挡得住数量级级别的胡说。 +pub const MAX_FEE_PER_WEIGHT: u64 = 1_000_000; + +/// 手续费优先级。字符串而非数字:数字跨边界时无从校验。 +pub fn parse_priority(name: &str) -> Result { + use monero_wallet::interface::FeePriority; + Ok(match name { + "unimportant" | "low" => FeePriority::Unimportant, + "" | "normal" => FeePriority::Normal, + "elevated" | "high" => FeePriority::Elevated, + "priority" | "highest" => FeePriority::Priority, + other => { + return Err(RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ + "field": "priority", + "value": other, + "allowed": ["unimportant", "normal", "elevated", "priority"], + }), + )) + } + }) +} + +/// 构造一笔待签名交易并预留输入。**不需要花费私钥,不广播。** +/// +/// ## `signableHex` 里有私有 view key +/// +/// 上游把整个 viewing pair 写进找零输出(`ChangeEnum::Standard`)—— +/// Monero 的钱包协议按「发送方能看到自己的找零」来做优化,所以它要 view key。 +/// 不带 view key 的那个变体 `Change::fingerprintable` 上游明确警告 +/// 「You MUST assume this will harm your privacy」,所以不能为了躲这个去换。 +/// +/// 结论:这个产物**等价于 view key**,不是一份无害的未签名交易。任何 +/// 「导出去别处签」的设计都必须把它当 view key 对待 —— 拿到它的人能看见 +/// 这个账户收到过的每一笔钱。 +/// +/// `recipients` 是 `(地址, piconero 金额)`。`max_send` 为真时只接受一个收款方, +/// 金额由「当前可花总额 − 手续费」反算,传入的金额被忽略。 +/// +/// 返回的 `feeAtomic` 是这笔交易真正要付的手续费:确认页显示它,签名时不会 +/// 再变。`amountAtomic` 同理 —— max-send 下它才是收款方实际收到的数。 +#[allow(clippy::too_many_arguments)] +pub async fn prepare_for_host( + db: &mut Db, + daemon: &crate::network::Daemon, + identity_id: i64, + recipients: &[(&str, &str)], + max_send: bool, + reservation_id: &str, + chain_tip: u64, + priority: monero_wallet::interface::FeePriority, +) -> Result { + use monero_daemon_rpc::prelude::*; + + let network = db.network(); + let rate = daemon + .fee_rate(priority, MAX_FEE_PER_WEIGHT) + .await + .map_err(|e| { + RuntimeError::with(ErrorCode::NetworkError, json!({ "operation": "feeRate" })) + .detail(format!("{e:?}")) + })?; + + // 当前共识:CLSAG + Bulletproofs+。跟着硬分叉走,由我们发版控制, + // 不问节点 —— 节点说错了交易会被全网拒绝。 + let rct_type = monero_wallet::ringct::RctType::ClsagBulletproofPlus; + let mut rng = rand_core::OsRng; + + // 放在选输入之前:被放弃的预留占着的输出要能被这一次选中。 + release_unsigned(db, identity_id)?; + let decoys = CachedDecoys::new(daemon); + + let prepared = if max_send { + if recipients.len() != 1 { + return Err(RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "recipientsJson", "reason": "maxSendNeedsExactlyOneRecipient" }), + )); + } + let address = keys::parse_address(network, recipients[0].0, "recipient.address")?; + prepare_max( + db, + &decoys, + &mut rng, + identity_id, + address, + rate, + chain_tip, + rct_type, + ) + .await? + } else { + let payments = recipients + .iter() + .map(|(addr, amount)| parse_payment(network, addr, amount)) + .collect::>>()?; + prepare( + db, + &decoys, + &mut rng, + identity_id, + &payments, + rate, + chain_tip, + rct_type, + ) + .await? + }; + + let change_atomic = prepared + .inputs_atomic + .saturating_sub(prepared.amount_atomic) + .saturating_sub(prepared.fee_atomic); + + // 预留放在最后:前面任何一步失败都不该留下锁住的输出。 + reserve(db, reservation_id, &prepared.output_ids)?; + + Ok(json!({ + "reservationId": reservation_id, + "signableHex": hex::encode(prepared.signable.serialize()), + "feeAtomic": prepared.fee_atomic.to_string(), + "amountAtomic": prepared.amount_atomic.to_string(), + "inputsAtomic": prepared.inputs_atomic.to_string(), + "changeAtomic": change_atomic.to_string(), + "inputCount": prepared.output_ids.len(), + })) +} + +/// 签名一笔已构造的交易。**不碰网络、不碰数据库。** +pub fn sign_for_host(signable_hex: &str, spend_private: &[u8]) -> Result { + let bytes = hex::decode(signable_hex).map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "signableHex", "reason": "notHex" }), + ) + })?; + let signable = SignableTransaction::read(&mut bytes.as_slice()).map_err(|e| { + RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "signableHex", "reason": "notASignableTransaction" }), + ) + .detail(format!("{e:?}")) + })?; + let mut rng = rand_core::OsRng; + let (raw, txid) = sign_prepared(signable, &mut rng, spend_private)?; + Ok(json!({ + "txid": hex::encode(txid), + "rawHex": hex::encode(&raw), + "sizeBytes": raw.len(), + })) +} + +/// 广播成功后的记账:输入标已花、记一条在途转出、释放预留。一个事务。 +/// 自己发出的一笔交易的金额(只有广播时知道)。 +#[derive(Debug, Default, Clone, Copy)] +pub struct SentAmounts { + /// 付出去的总额(收款 + 手续费)。 + pub outgoing_atomic: Option, + /// 找零:上链前计入总余额(锁定),wallet2 同款。 + pub change_atomic: Option, +} + +fn record_broadcast( + db: &Db, + identity_id: i64, + txid: &[u8; 32], + key_images: &[[u8; 32]], + reservation_id: &str, + chain_tip: u64, + amounts: SentAmounts, +) -> Result<()> { + let tx_db = db + .conn() + .unchecked_transaction() + .map_err(|e| db_err("beginRecordSend", e))?; + for key_image in key_images { + tx_db + .execute( + "UPDATE outputs SET spent_at_height = ?1, spent_in_txid = ?2 + WHERE identity_id = ?3 AND key_image = ?4 AND spent_at_height IS NULL", + params![ + chain_tip as i64, + txid.as_slice(), + identity_id, + key_image.as_slice() + ], + ) + .map_err(|e| db_err("markSpentAfterBroadcast", e))?; + } + tx_db + .execute( + "INSERT INTO transactions + (identity_id, txid, height, direction, sent_at, outgoing_atomic, change_atomic) + VALUES (?1, ?2, NULL, 'out', ?3, ?4, ?5) + ON CONFLICT (identity_id, txid) DO UPDATE + SET direction = 'out', sent_at = ?3, failed = 0, + outgoing_atomic = COALESCE(?4, outgoing_atomic), + change_atomic = COALESCE(?5, change_atomic)", + params![ + identity_id, + txid.as_slice(), + crate::wallet::now_secs(), + amounts.outgoing_atomic.map(|a| a.to_string()), + amounts.change_atomic.map(|a| a.to_string()) + ], + ) + .map_err(|e| db_err("recordOutgoing", e))?; + tx_db + .execute( + "DELETE FROM locked_outputs WHERE reservation_id = ?1", + [reservation_id], + ) + .map_err(|e| db_err("releaseAfterBroadcast", e))?; + tx_db.commit().map_err(|e| db_err("commitRecordSend", e)) +} + +/// 广播一笔已签名的交易,并记账。**不可逆。** +/// +/// 广播成功后立刻把被花的输出标记掉:不标的话下一次选币会再选中它们, +/// 构出一笔必然被网络拒绝的交易。 +pub async fn broadcast_signed( + db: &Db, + daemon: &crate::network::Daemon, + identity_id: i64, + raw_hex: &str, + reservation_id: &str, + chain_tip: u64, + amounts: SentAmounts, +) -> Result { + let raw = hex::decode(raw_hex).map_err(|_| { + RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "rawHex", "reason": "notHex" }), + ) + })?; + + let tx = monero_wallet::transaction::Transaction::read(&mut raw.as_slice()) + .map_err(|e| db_err("parseSignedTransaction", e))?; + let txid = tx.hash(); + + // 明确拒收说明这笔不会上链,输入放回可用。其余错误分不清节点收没收到: + // 照样记成在途交易,输入不会被重选(重发换一批输入就可能付两次); + // 节点真没收到的话,在途检查过了扩散期会判失败并放回输入。 + // 「双花」也可能是这笔自己早已上链(回包丢过、重试了同一份签名),同样当 + // 不确定处理:真是别人花的,扩散期后在途检查会判失败。 + let mut unknown = match broadcast(daemon, &raw).await { + Ok(()) => None, + Err(e) if e.code == ErrorCode::BroadcastRejected && !is_double_spend(&e) => { + release(db, reservation_id)?; + return Err(e); + } + Err(e) => Some(e), + }; + + // 广播已经发生,不可逆。立刻记账。按交易自己的 key image 标,不靠预留: + // 预留可能已经过期,或者签名失败释放后又拿同一份签名重发。 + let key_images: Vec<[u8; 32]> = tx + .prefix() + .inputs + .iter() + .filter_map(|input| match input { + monero_wallet::transaction::Input::ToKey { key_image, .. } => { + Some(key_image.to_bytes()) + } + _ => None, + }) + .collect(); + // 记账失败也不能报「发送失败」:交易可能已经在网上,报失败会引人重发。 + // 按不确定返回;扫链按 key image 会认出这笔。 + if let Err(e) = record_broadcast( + db, + identity_id, + &txid, + &key_images, + reservation_id, + chain_tip, + amounts, + ) { + unknown = Some(e); + } + + Ok(json!({ + "txid": hex::encode(txid), + "sizeBytes": raw.len(), + "broadcast": if unknown.is_some() { "unknown" } else { "accepted" }, + "error": unknown.map(|e| e.to_json()), + })) +} + +#[cfg(test)] +mod cached_decoys_tests { + use super::*; + use monero_wallet::interface::{ + EvaluateUnlocked, InterfaceError, ProvidesBlockchainMeta, ProvidesDecoys, + ProvidesUnvalidatedDecoys, TransactionsError, + }; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct CountingSource(AtomicUsize); + + impl ProvidesBlockchainMeta for CountingSource { + async fn latest_block_number(&self) -> std::result::Result { + Ok(100) + } + } + + impl ProvidesUnvalidatedDecoys for CountingSource { + async fn ringct_output_distribution( + &self, + _range: impl Send + std::ops::RangeBounds, + ) -> std::result::Result, InterfaceError> { + self.0.fetch_add(1, Ordering::SeqCst); + Ok(vec![1, 2, 3]) + } + + async fn unlocked_ringct_outputs( + &self, + _indexes: &[u64], + _evaluate_unlocked: EvaluateUnlocked, + ) -> std::result::Result>, TransactionsError> { + Ok(Vec::new()) + } + } + + // Every input's decoy selection asks for the same range; the node is asked once. + #[test] + fn one_distribution_download_per_prepare() { + let source = CountingSource(AtomicUsize::new(0)); + let cached = CachedDecoys::new(&source); + for _ in 0..3 { + let d = futures_lite::future::block_on(ProvidesDecoys::ringct_output_distribution( + &cached, + ..=100usize, + )) + .unwrap(); + assert_eq!(d, vec![1, 2, 3]); + } + assert_eq!(source.0.load(Ordering::SeqCst), 1); + } +} + +#[cfg(test)] +mod double_spend_tests { + use super::*; + + #[test] + fn a_double_spend_rejection_is_not_treated_as_final() { + let spent = RuntimeError::new(ErrorCode::BroadcastRejected).detail("double spend"); + let other = RuntimeError::new(ErrorCode::BroadcastRejected).detail("fee too low"); + assert!(is_double_spend(&spent)); + assert!(!is_double_spend(&other)); + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs new file mode 100644 index 000000000..2b4d108ca --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs @@ -0,0 +1,272 @@ +//! 各端共用的 SQLite 存储。 +//! +//! wasm 侧跑在独立 Worker 里,四端(桌面、Web、插件、移动 WebEmbed)都用同一套 +//! OPFS 同步访问 VFS —— SQLite 直接按页读写,而不是把整个库预载进 wasm 内存。 +//! **这正是选 monero-oxide 而不是 monero-ts 的理由**:后者只能整块序列化。 +//! +//! 原生构建保留,用于 Rust 测试与本机诊断。 + +use rusqlite::Connection; +use serde_json::json; + +use crate::error::{db_err, ErrorCode, Result, RuntimeError}; + +// 强制链接:Rust 只链接代码里真正引用过的 crate。光在 Cargo.toml 里声明 +// sqlite-wasm-rs 不够 —— 它的归档会被找到却一个符号都不拉,链接期报一串 +// `undefined symbol: sqlite3_*`。 +#[cfg(target_arch = "wasm32")] +use sqlite_wasm_rs as _; + +#[cfg(target_arch = "wasm32")] +use std::sync::atomic::{AtomicBool, Ordering}; + +#[cfg(target_arch = "wasm32")] +static VFS_READY: AtomicBool = AtomicBool::new(false); + +// 装好后的池句柄。删库要靠它:库打不开(版本不认、文件损坏)时也得能删掉。 +#[cfg(target_arch = "wasm32")] +thread_local! { + static VFS_UTIL: std::cell::RefCell>> = + const { std::cell::RefCell::new(None) }; +} + +/// VFS 是否已就绪。原生目标恒为 true(用系统文件系统)。 +pub fn is_ready() -> bool { + #[cfg(target_arch = "wasm32")] + { + VFS_READY.load(Ordering::SeqCst) + } + #[cfg(not(target_arch = "wasm32"))] + { + true + } +} + +/// 在浏览器载体里装上持久化 VFS。必须在开任何库之前调用一次。 +/// +/// 池会独占文件句柄直到它所在的 Worker 被终止 —— 所以同一个库不能被两个 +/// Worker 同时打开,宿主那侧要保证串行。 +/// +/// ## 为什么要自己起名,不用库的默认值 +/// +/// 默认是 `.opfs-sahpool`。同一个 origin 下 Zcash 的 runtime 也在装它自己的池 +/// (`.onekey-zcash-opfs`),将来任何一个依赖只要用默认配置装一次,就会和我们 +/// 共用同一个目录、抢同一批文件句柄。起个专属名字是一行的事,省掉的是一类 +/// 只在"两条链同时开着"时才出现、且看起来像存储损坏的故障。 +/// +/// ## 为什么要重试 +/// +/// 浏览器里 Worker 的终止是**异步**的:carrier 重置、页面刷新、开发时热更新, +/// 旧 Worker 在新的已经跑起来之后还会攥着 SAH 句柄一小会儿。这时 install 会拿 +/// 到 `NoModificationAllowedError`。不重试的话,用户看到的是刷新一下页面 +/// 钱包就打不开了。 +/// +/// 只对"上一个持有者正在释放"这一种错误重试,而且有界。真有另一个活着的持有 +/// 者时,等完这段窗口依然会失败 —— 那是对的,两个 Worker 同时写一个库比报错 +/// 严重得多。 +#[cfg(target_arch = "wasm32")] +pub async fn install_persistent_vfs() -> Result<()> { + use sqlite_wasm_vfs::sahpool::{install, OpfsSAHError, OpfsSAHPoolCfg}; + + if is_ready() { + return Ok(()); + } + + let cfg = OpfsSAHPoolCfg { + vfs_name: "onekey-xmr-opfs".to_owned(), + directory: ".onekey-xmr-opfs".to_owned(), + // 绝不能是 true:那会在每次启动时清空池,等于每次开 app 都要全链重扫。 + clear_on_init: false, + // 一个网络一个库,加上回滚日志与富余句柄。 + initial_capacity: 4, + }; + + let mut retries = 20; + loop { + // `WasmOsCallback` 是 sqlite-wasm-rs 提供的具体实现(VFS crate 本身只 + // 定义了 trait)。泛型参数必须显式给,否则推不出来。 + match install::(&cfg, true).await { + Ok(util) => { + VFS_UTIL.with(|slot| *slot.borrow_mut() = Some(std::rc::Rc::new(util))); + VFS_READY.store(true, Ordering::SeqCst); + return Ok(()); + } + Err(error) => { + let owner_is_releasing = matches!( + &error, + OpfsSAHError::CreateSyncAccessHandle(value) + if js_sys::Reflect::get( + value, + &wasm_bindgen::JsValue::from_str("name"), + ) + .ok() + .and_then(|name| name.as_string()) + .as_deref() + == Some("NoModificationAllowedError") + ); + if !owner_is_releasing || retries == 0 { + return Err(RuntimeError::with( + ErrorCode::NotInitialized, + json!({ "reason": "vfsInstallFailed" }), + ) + .detail(format!("{error:?}"))); + } + retries -= 1; + gloo_timers::future::TimeoutFuture::new(250).await; + } + } + } +} + +/// 原生目标不需要装 VFS。留同名函数让上层代码不必到处写 cfg。 +#[cfg(not(target_arch = "wasm32"))] +pub async fn install_persistent_vfs() -> Result<()> { + Ok(()) +} + +/// 库名校验:不能为空,也不能含路径分隔符。 +/// +/// **两个目标都要查**。wasm 上 db_name 是 VFS 里的不透明键,原生上它会直接 +/// 变成文件路径 —— 后者才是路径穿越真正有意义的地方,所以不能只在 wasm 上查。 +fn validate_db_name(db_name: &str) -> Result<()> { + let bad = db_name.is_empty() + || db_name.contains('/') + || db_name.contains('\\') + || db_name.contains(".."); + if bad { + return Err(RuntimeError::with( + ErrorCode::InvalidDbName, + json!({ "value": db_name }), + )); + } + Ok(()) +} + +/// 打开一条连接并设好 pragma。 +/// +/// `:memory:` 是测试专用的特例,跳过名字校验与持久化 pragma。 +pub fn open_connection(db_name: &str) -> Result { + if db_name == ":memory:" { + let conn = Connection::open_in_memory().map_err(|e| db_err("openInMemory", e))?; + // 外键与正式库一致,级联删除的测试才有意义 + conn.execute_batch("PRAGMA foreign_keys = ON;") + .map_err(|e| db_err("pragmaForeignKeys", e))?; + return Ok(conn); + } + + validate_db_name(db_name)?; + + if !is_ready() { + return Err(RuntimeError::new(ErrorCode::NotInitialized)); + } + + let conn = Connection::open(db_name).map_err(|e| db_err("open", e))?; + + // 外键必须显式打开(SQLite 默认关闭),否则 identities 的级联删除不生效, + // 「删钱包」会留下能被后续查询读到的孤儿行。 + conn.execute_batch("PRAGMA foreign_keys = ON;") + .map_err(|e| db_err("pragmaForeignKeys", e))?; + // 删掉的行(观察私钥、收款记录)用零覆盖,不留在空闲页里等人读。 + conn.execute_batch("PRAGMA secure_delete = ON;") + .map_err(|e| db_err("pragmaSecureDelete", e))?; + + #[cfg(target_arch = "wasm32")] + { + // SAH 池用回滚日志,不做跨上下文的 WAL 协调。 + // **绝不为了扫描吞吐去弱化事务持久性。** + conn.execute_batch("PRAGMA journal_mode = DELETE; PRAGMA synchronous = FULL;") + .map_err(|e| db_err("pragmaDurability", e))?; + } + + Ok(conn) +} + +/// 删掉一个已关闭的库,**不打开它**:打不开的库也要删得掉。 +/// 返回 `true` 表示删了,`false` 表示本来就不存在。 +#[cfg(target_arch = "wasm32")] +pub async fn delete_database(db_name: &str) -> Result { + validate_db_name(db_name)?; + let util = VFS_UTIL + .with(|slot| slot.borrow().clone()) + .ok_or_else(|| RuntimeError::new(ErrorCode::NotInitialized))?; + util.delete_db(db_name).map_err(|error| { + RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "deleteDatabase", "dbName": db_name }), + ) + .detail(format!("{error:?}")) + }) +} + +#[cfg(not(target_arch = "wasm32"))] +pub async fn delete_database(db_name: &str) -> Result { + validate_db_name(db_name)?; + match std::fs::remove_file(db_name) { + Ok(()) => Ok(true), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(RuntimeError::with( + ErrorCode::DatabaseError, + json!({ "operation": "deleteDatabase", "dbName": db_name }), + ) + .detail(error.to_string())), + } +} + +/// 落盘屏障:确保此前提交的事务真的到了持久存储。 +/// +/// 在做完一件**不可逆**的事之后调用(比如广播了一笔交易)。屏障失败的含义是 +/// 「持久化是否到达耐久存储未知」,**不是**「那件事失败了」—— 调用方不能因此 +/// 把真实结局丢掉。 +pub async fn durability_barrier() -> Result<()> { + #[cfg(target_arch = "wasm32")] + { + // SAH 池的写在 sqlite3 返回时已落到 OPFS 句柄上;这里给宿主一个 + // 明确的同步点,且保留将来换 VFS 时插入真正 flush 的位置。 + Ok(()) + } + #[cfg(not(target_arch = "wasm32"))] + { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // 删库不打开库:一个根本不是 SQLite 的文件也删得掉。 + #[test] + fn deletes_a_database_it_cannot_open() { + let name = format!("xmr-delete-test-{}.db", std::process::id()); + std::fs::write(&name, b"not a sqlite database").unwrap(); + let delete = || futures_lite::future::block_on(delete_database(&name)); + assert!(delete().unwrap()); + assert!(!delete().unwrap()); + } + + #[test] + fn memory_database_always_opens() { + assert!(open_connection(":memory:").is_ok()); + } + + /// 路径穿越在**原生**目标上才真正危险(db_name 直接变文件路径), + /// 所以这条校验不能像某些实现那样只在 wasm 下生效。 + #[test] + fn path_separators_are_rejected_on_every_target() { + for bad in ["", "a/b", "a\\b", "../escape", "x/../y"] { + let e = open_connection(bad).expect_err(&format!("{bad:?} 应被拒绝")); + assert_eq!(e.code, ErrorCode::InvalidDbName); + } + } + + #[test] + fn foreign_keys_are_on() { + let conn = open_connection(":memory:").unwrap(); + // 内存库走的是特例分支,这里显式开一次再验,确保 pragma 语句本身有效 + conn.execute_batch("PRAGMA foreign_keys = ON;").unwrap(); + let on: i64 = conn + .query_row("PRAGMA foreign_keys", [], |r| r.get(0)) + .unwrap(); + assert_eq!(on, 1); + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs new file mode 100644 index 000000000..90f0790c3 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs @@ -0,0 +1,639 @@ +//! 同步编排:拉块 → 扫描 → 记进度。**有界推进,永不跑到底。** +//! +//! 一次调用最多处理 `max_blocks` 个块,然后带进度返回。要不要接着调由宿主 +//! 决定 —— 这是「调度归 TS」那条边界。理由是具体的:跑到底的函数在浏览器和 +//! 移动端上无法中断、无法看进度、无法让出线程,页面直接冻住。 +//! +//! ## 扫描进度按身份独立记账 +//! +//! `scan_ranges` 带 `identity_id`。这和 Zcash 那边不一样 —— 那边承诺树要求 +//! 全库连续扫描,于是「用 A 的密钥扫过的区间被标记为全库已扫」,暂停中的账户 +//! 会永久漏掉那一段,只能靠宿主保管的游标补救。Monero 没有承诺树、不要求 +//! 连续扫描,各身份各记各的,从根上没有这个坑。 + +use futures_util::stream::{self, StreamExt, TryStreamExt}; +use monero_daemon_rpc::prelude::*; +use rusqlite::{params, OptionalExtension}; +use serde_json::{json, Value}; + +use crate::error::{db_err, net_err, ErrorCode, Result, RuntimeError}; +use crate::network::Daemon; +use crate::perf::now_ms; +use crate::scan::{self, ScanOutcome}; +use crate::wallet::Db; + +/// 单次调用的块数上限。 +/// +/// 不是性能调优参数,是**卡死防线**:宿主传个巨大的值会让这次调用跑上几分钟 +/// 且中途无法中断。真正的批量由宿主按实测吞吐决定。 +pub const MAX_BLOCKS_PER_CALL: u64 = 1_000; + +/// 同时在途的取块请求数。 +/// +/// 取块是**延迟**型而不是带宽型:一块要 3~4 次往返(区块、交易、输出索引), +/// 每次 130~230 ms,实测串行时 ~1.36 s/块。块与块之间没有依赖,并发 N 个 +/// 就把墙钟时间压到约 1/N。取 6 是因为浏览器、插件后台、RN 的 HTTP 栈对 +/// 同一 host 的连接上限都在这个量级,再高只会排队,还更容易被公共节点限流。 +pub const FETCH_CONCURRENCY: usize = 6; + +/// 问链尖。**不碰钱包库** —— 建账户时需要它来定 birthday,而那一刻库还没建。 +pub async fn chain_tip(daemon: &Daemon) -> Result { + let n = daemon + .latest_block_number() + .await + .map_err(|e| net_err("latestBlockNumber", format!("{e:?}")))?; + Ok(n as u64) +} + +/// 把链尖告诉某个身份:据此算出还要扫哪一段。 +/// +/// 新身份的待扫区间是 `[birthday, tip]`;已有进度的则是 `(已扫到, tip]`。 +pub fn update_chain_tip(db: &mut Db, identity_id: i64, tip: u64) -> Result<()> { + let identity = db.identity_by_id(identity_id)?; + let scanned_to = scanned_to_height(db, identity_id)?; + let start = scanned_to + .map(|h| h + 1) + .unwrap_or(identity.birthday_height); + + if start > tip { + return Ok(()); // 已经追上链尖,没有待扫区间 + } + + db.conn() + .execute( + "INSERT INTO scan_ranges (identity_id, start_height, end_height) + VALUES (?1, ?2, ?3) + ON CONFLICT (identity_id, start_height) DO UPDATE SET end_height = max(end_height, ?3)", + params![identity_id, start as i64, (tip + 1) as i64], + ) + .map_err(|e| db_err("updateChainTip", e))?; + Ok(()) +} + +/// 该身份已经连续扫到哪个高度(含)。没扫过任何块时返回 `None`。 +/// +/// 读的是 `identities.scanned_to_height` 而**不是** `blocks` 表的 max —— 后者 +/// 是全局的,会让一个已追到链尖的身份把另一个还在回补的身份的进度推到链尖, +/// 那段历史就被永久跳过。 +pub fn scanned_to_height(db: &Db, identity_id: i64) -> Result> { + Ok(db + .conn() + .query_row( + "SELECT scanned_to_height FROM identities WHERE id = ?1", + [identity_id], + |r| r.get::<_, Option>(0), + ) + .optional() + .map_err(|e| db_err("scannedToHeight", e))? + .flatten() + .map(|h| h as u64)) +} + +/// 推进该身份的扫描进度。只进不退 —— 回退走 `rewind_and_requeue`。 +fn advance_scanned_to(db: &Db, identity_id: i64, height: u64) -> Result<()> { + db.conn() + .execute( + "UPDATE identities + SET scanned_to_height = max(COALESCE(scanned_to_height, 0), ?2) + WHERE id = ?1", + params![identity_id, height as i64], + ) + .map_err(|e| db_err("advanceScannedTo", e))?; + Ok(()) +} + +/// 取当前最靠前的待扫区间。 +fn next_range(db: &Db, identity_id: i64) -> Result> { + db.conn() + .query_row( + "SELECT start_height, end_height FROM scan_ranges + WHERE identity_id = ?1 ORDER BY start_height LIMIT 1", + [identity_id], + |r| Ok((r.get::<_, i64>(0)? as u64, r.get::<_, i64>(1)? as u64)), + ) + .optional() + .map_err(|e| db_err("nextRange", e)) +} + +/// 把已扫完的 `[start, scanned_through]` 从待扫区间里销掉。 +/// +/// 待扫区间**可能互相重叠**:重扫(`rewind_and_requeue`)会从回退高度重新排一段, +/// 而原来的尾部区间还在队列里。只处理"起点等于 `start`"的那一条、再把余下部分 +/// 普通 INSERT 回去,一旦余下的起点正好是另一条区间的起点就撞主键 —— 整步回滚, +/// 下一步从同一处开始、再撞,扫描永远原地踏步。 +/// +/// 所以这里对**每一条**与已扫段相交的区间都减去已扫段,余下部分以 upsert +/// 合并(同起点取更远的终点)。重叠在此被逐步消化,不再需要区间互不相交这个前提。 +fn consume_range(db: &mut Db, identity_id: i64, start: u64, scanned_through: u64) -> Result<()> { + let tx = db + .conn_mut() + .transaction() + .map_err(|e| db_err("beginConsumeRange", e))?; + + let overlapping: Vec<(i64, i64)> = { + let mut stmt = tx + .prepare( + "SELECT start_height, end_height FROM scan_ranges + WHERE identity_id = ?1 AND start_height <= ?3 AND end_height > ?2", + ) + .map_err(|e| db_err("consumeRange", e))?; + let rows = stmt + .query_map( + params![identity_id, start as i64, scanned_through as i64], + |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)), + ) + .map_err(|e| db_err("consumeRange", e))? + .collect::>>() + .map_err(|e| db_err("consumeRange", e))?; + rows + }; + + let upsert = |from: i64, to: i64| -> Result<()> { + tx.execute( + "INSERT INTO scan_ranges (identity_id, start_height, end_height) VALUES (?1, ?2, ?3) + ON CONFLICT (identity_id, start_height) DO UPDATE SET end_height = max(end_height, ?3)", + params![identity_id, from, to], + ) + .map(|_| ()) + .map_err(|e| db_err("consumeRange", e)) + }; + + let scanned_from = start as i64; + let resume_at = scanned_through as i64 + 1; + for (range_start, range_end) in overlapping { + tx.execute( + "DELETE FROM scan_ranges WHERE identity_id = ?1 AND start_height = ?2", + params![identity_id, range_start], + ) + .map_err(|e| db_err("consumeRange", e))?; + // 已扫段之前的部分(按最低起点取区间时不会出现,保留以防万一)。 + if range_start < scanned_from { + upsert(range_start, scanned_from)?; + } + // 已扫段之后的部分。 + if range_end > resume_at { + upsert(resume_at, range_end)?; + } + } + + tx.commit().map_err(|e| db_err("commitConsumeRange", e)) +} + +thread_local! { + /// 批量路径对哪个节点、从什么时候起判定不可用。换节点即重新尝试。 + static BLOCKS_BIN_UNSUPPORTED_BY: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// 判定不可用之后多久再试批量。一次截断或代理改写的回包不该让好节点整个会话都走慢路。 +const BLOCKS_BIN_RETRY_AFTER_MS: f64 = 10.0 * 60.0 * 1000.0; + +fn blocks_bin_skipped_for(node: Option<&str>, now: f64) -> bool { + BLOCKS_BIN_UNSUPPORTED_BY.with(|c| match (&*c.borrow(), node) { + (Some((url, at)), Some(node)) => url == node && now - at < BLOCKS_BIN_RETRY_AFTER_MS, + _ => false, + }) +} + +/// 先走批量(`get_blocks.bin`,一次往返一整批),节点不配合时退回逐块并发。 +/// +/// 只有**协议**层面的失败(节点不支持、格式不符、数量对不上)才会让这个节点 +/// 暂时跳过批量路径(见 `BLOCKS_BIN_RETRY_AFTER_MS`);网络失败照常上抛,这一步 +/// 失败、下一轮重试 —— 一次超时不能让一个好节点从此降级。 +async fn fetch_blocks( + daemon: &Daemon, + start: u64, + last: u64, +) -> Result<(Vec, &'static str, Option, bool)> { + let node = crate::network::current_node_url(); + let skip = blocks_bin_skipped_for(node.as_deref(), now_ms()); + if let (Some(url), false, true) = (node.as_deref(), skip, start > 0) { + match crate::blocks_bin::fetch(url, start, last - start + 1).await { + Ok(fetched) => { + return Ok((fetched.blocks, "blocksBin", None, fetched.prefetch_hit)); + } + Err(crate::blocks_bin::BlocksBinError::Network(detail)) => { + return Err(net_err( + "getBlocksBin", + format!("{start}..={last}: {detail}"), + )); + } + Err(crate::blocks_bin::BlocksBinError::Protocol(detail)) => { + BLOCKS_BIN_UNSUPPORTED_BY + .with(|c| *c.borrow_mut() = node.clone().map(|url| (url, now_ms()))); + // 放弃的原因随这一步的结果回给宿主,只报这一次。 + let blocks = fetch_scannable_blocks(daemon, start, last).await?; + return Ok(( + blocks, + "perBlock", + Some(format!("getBlocksBin unusable: {detail}")), + false, + )); + } + } + } + Ok(( + fetch_scannable_blocks(daemon, start, last).await?, + "perBlock", + None, + false, + )) +} + +/// 取 `[start, last]` 的可扫描块,按高度排好。 +/// +/// 批量路径(`blocks_bin`)不可用时的退路。 +/// +/// **不走** `contiguous_scannable_blocks`。它先试批量的 `get_blocks.bin`,但 +/// 已发布的 monerod(截至 v0.18.5.1)在 `prune=true` 时不回 `prunable_hash` +/// (monero-project/monero#10120,修复 #10652 只在 master),monero-oxide 为了 +/// 能校验交易哈希就整批放弃、回退逐块 JSON —— 于是每一步都**白下一整包再扔掉**, +/// 再串行地一块一块取。对今天的任何公共节点,那次批量尝试都注定失败。 +/// +/// 这里直接逐块取、N 路并发。每块仍经上游校验(编号正确、交易与区块的交易 +/// 列表一致);块与块之间的衔接(高度连续、前驱哈希、RingCT 游标)由 +/// `scan::scan_blocks` 独立校验,所以完整性保障一条不少。`buffered` 保持 +/// 提交顺序,结果天然按高度排列。 +/// +async fn fetch_scannable_blocks( + daemon: &Daemon, + start: u64, + last: u64, +) -> Result> { + stream::iter(start..=last) + .map(|height| async move { + daemon + .scannable_block_by_number(height as usize) + .await + .map_err(|e| net_err("scannableBlockByNumber", format!("{height}: {e:?}"))) + }) + .buffered(FETCH_CONCURRENCY) + .try_collect() + .await +} + +/// 一次有界推进。 +/// +/// 返回进度 JSON;`done` 表示已经没有待扫区间。**本函数永远不会自己循环到 +/// 同步完成** —— 宿主拿到进度后自己决定要不要接着调。 +pub async fn step( + db: &mut Db, + daemon: &Daemon, + identity_id: i64, + max_blocks: u64, +) -> Result { + if max_blocks == 0 { + return Err(RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "maxBlocks", "reason": "mustBePositive" }), + )); + } + let max_blocks = max_blocks.min(MAX_BLOCKS_PER_CALL); + + let sends_failed = crate::pool::check_pending(db, daemon, identity_id).await?; + + let Some((start, end)) = next_range(db, identity_id)? else { + let mut v = progress(db, identity_id, &ScanOutcome::default(), true)?; + v["sendsFailed"] = json!(sends_failed); + return Ok(v); + }; + + // 区间是左闭右开(end 是"第一个还没扫的高度之后"),上游要的是闭区间。 + let last = (start + max_blocks - 1).min(end.saturating_sub(1)); + if last < start { + return Ok(progress(db, identity_id, &ScanOutcome::default(), true)?); + } + + // 分段打点。扫得慢的时候,「慢在拉块还是慢在解密」是完全不同的两件事, + // 而在浏览器里两者的表现一模一样(界面不动)—— 只能靠打点区分。 + // 公共节点单次往返可达几百毫秒,不分开量就会把网络延迟误判成算力不足。 + let t0 = now_ms(); + + let (blocks, fetched_via, fetch_note, prefetch_hit) = fetch_blocks(daemon, start, last).await?; + + // 流水线:扫这一批之前,先把下一批的请求发出去(wallet2 同款)。起点按实际 + // 拿到的块算 —— 只拿到部分前缀时,下一步从断点开始,预取也得从那里开始。 + if fetched_via == "blocksBin" { + let next = start + blocks.len() as u64; + if let (Some(url), true) = (crate::network::current_node_url(), next < end) { + // 与下一步的请求一致:同样受 max_blocks 与区间终点约束,大小取 + // 这一次请求之后调整过的批量。 + crate::blocks_bin::prefetch(&url, next, (end - next).min(max_blocks)).await; + } + } + + let t_downloaded = now_ms(); + + if blocks.is_empty() { + // 节点对一个非空区间返回了零个块 —— 它没有守协议。 + // **不能当成"扫完了"静默推进**,那会让这段高度被永远跳过。 + return Err(RuntimeError::with( + ErrorCode::MalformedNodeResponse, + json!({ "operation": "contiguousScannableBlocks", "from": start, "to": last }), + )); + } + + db.ensure_subaddress_lookahead(identity_id)?; + let mut outcome = scan::scan_blocks(db, identity_id, &blocks)?; + // 收到钱的子地址靠近窗口末尾时窗口会扩大;用新窗口重扫同一批(块已在手, + // 落库幂等),这批里后面发给新登记子地址的钱才不会漏。 + while outcome.outputs_found > 0 && db.ensure_subaddress_lookahead(identity_id)? > 0 { + outcome = scan::scan_blocks(db, identity_id, &blocks)?; + } + let t_scanned = now_ms(); + outcome.ms_download = (t_downloaded - t0) as u32; + outcome.ms_scan = (t_scanned - t_downloaded) as u32; + outcome.fetched_via = fetched_via; + outcome.fetch_note = fetch_note; + outcome.prefetch_hit = prefetch_hit; + outcome.batch_blocks = crate::blocks_bin::batch_blocks(); + + if let Some(through) = outcome.to_height { + consume_range(db, identity_id, start, through)?; + advance_scanned_to(db, identity_id, through)?; + } + + let done = next_range(db, identity_id)?.is_none(); + let mut v = progress(db, identity_id, &outcome, done)?; + v["sendsFailed"] = json!(sends_failed); + Ok(v) +} + +fn progress(db: &Db, identity_id: i64, outcome: &ScanOutcome, done: bool) -> Result { + let remaining: i64 = db + .conn() + .query_row( + "SELECT COALESCE(sum(end_height - start_height), 0) FROM scan_ranges WHERE identity_id = ?1", + [identity_id], + |r| r.get(0), + ) + .map_err(|e| db_err("remainingBlocks", e))?; + + let mut v = outcome.to_json(); + v["done"] = json!(done); + v["remainingBlocks"] = json!(remaining); + v["scannedToHeight"] = json!(scanned_to_height(db, identity_id)?); + Ok(v) +} + +/// 只读:当前的扫描进度,不发任何网络请求。 +/// +/// 同步卡住时用它确认 runtime 到底想扫哪一段 —— 不用猜。 +pub fn peek(db: &Db, identity_id: i64) -> Result { + let mut stmt = db + .conn() + .prepare( + "SELECT start_height, end_height FROM scan_ranges + WHERE identity_id = ?1 ORDER BY start_height", + ) + .map_err(|e| db_err("peek", e))?; + let ranges = stmt + .query_map([identity_id], |r| { + Ok(json!({ + "start": r.get::<_, i64>(0)?, + "end": r.get::<_, i64>(1)?, + })) + }) + .map_err(|e| db_err("peek", e))? + .collect::>>() + .map_err(|e| db_err("peek", e))?; + + Ok(json!({ + "ranges": ranges, + "scannedToHeight": scanned_to_height(db, identity_id)?, + // 回补起点以运行时为准:宿主存的生日可能与这里不一致(重新启用不会改已有身份的生日)。 + "birthdayHeight": db.identity_by_id(identity_id)?.birthday_height, + })) +} + +/// 重组恢复:回退到指定高度,并把那之上的区间重新排进待扫队列。 +pub fn rewind_and_requeue(db: &mut Db, identity_id: i64, height: u64, tip: u64) -> Result { + scan::rewind_to(db, identity_id, height)?; + // 进度也要退。不退的话下一轮会从一个已经被丢弃的高度接着扫, + // 中间那段永远不会被重新覆盖。一块都没扫过的保持 NULL:当成 0 会让 + // 下一次 update_chain_tip 从创世块排队。 + db.conn() + .execute( + "UPDATE identities SET scanned_to_height = min(scanned_to_height, ?2) + WHERE id = ?1 AND scanned_to_height IS NOT NULL", + params![identity_id, height as i64], + ) + .map_err(|e| db_err("rewindScannedTo", e))?; + // 往生日之前重扫(用户选了更早的日期):生日跟着提前,进度才有正确的起点。 + db.conn() + .execute( + "UPDATE identities SET birthday_height = ?2 WHERE id = ?1 AND birthday_height > ?2", + params![identity_id, (height + 1) as i64], + ) + .map_err(|e| db_err("rewindBirthday", e))?; + // 回退后那一段要重扫。直接排进队列,不依赖宿主记得再调一次 update_chain_tip。 + if tip > height { + db.conn() + .execute( + "INSERT INTO scan_ranges (identity_id, start_height, end_height) + VALUES (?1, ?2, ?3) + ON CONFLICT (identity_id, start_height) DO UPDATE SET end_height = max(end_height, ?3)", + params![identity_id, (height + 1) as i64, (tip + 1) as i64], + ) + .map_err(|e| db_err("requeueAfterRewind", e))?; + } + Ok(json!({ "rewoundTo": height, "requeuedTo": tip })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::wallet::testing::db_with_identity; + + #[test] + fn a_new_identity_has_nothing_queued_until_the_tip_is_known() { + let (db, id) = db_with_identity(); + assert!(next_range(&db, id).unwrap().is_none()); + let p = peek(&db, id).unwrap(); + assert_eq!(p["ranges"].as_array().unwrap().len(), 0); + assert_eq!(p["birthdayHeight"], 100, "进度的起点取运行时的生日"); + } + + #[test] + fn learning_the_tip_queues_the_backfill_range() { + let (mut db, id) = db_with_identity(); // birthday = 100 + update_chain_tip(&mut db, id, 150).unwrap(); + let (start, end) = next_range(&db, id).unwrap().expect("应当排上队"); + assert_eq!(start, 100, "从 birthday 起扫"); + assert_eq!(end, 151, "区间左闭右开"); + } + + /// 链尖前进时只该抬高终点,不该产生第二条重叠区间 —— 重叠会导致同一段 + /// 被扫两遍,浪费带宽还让进度显示倒退。 + #[test] + fn advancing_the_tip_extends_rather_than_duplicates() { + let (mut db, id) = db_with_identity(); + update_chain_tip(&mut db, id, 150).unwrap(); + update_chain_tip(&mut db, id, 200).unwrap(); + let ranges = peek(&db, id).unwrap(); + let ranges = ranges["ranges"].as_array().unwrap(); + assert_eq!(ranges.len(), 1, "只该有一条区间"); + assert_eq!(ranges[0]["end"], 201); + } + + /// 链尖不动时重复调用必须幂等。 + #[test] + fn the_same_tip_twice_changes_nothing() { + let (mut db, id) = db_with_identity(); + update_chain_tip(&mut db, id, 150).unwrap(); + let before = peek(&db, id).unwrap(); + update_chain_tip(&mut db, id, 150).unwrap(); + assert_eq!(before, peek(&db, id).unwrap()); + } + + /// **回归**:重扫排进来的区间与旧的尾部区间重叠,余下部分的起点正好落在 + /// 另一条区间的起点上。旧实现撞主键、整步回滚,扫描原地踏步(插件实测)。 + #[test] + fn consuming_across_overlapping_ranges_merges_instead_of_colliding() { + let (mut db, id) = db_with_identity(); + for (s, e) in [(100_i64, 200_i64), (161, 250)] { + db.conn() + .execute( + "INSERT INTO scan_ranges (identity_id, start_height, end_height) VALUES (?1, ?2, ?3)", + params![id, s, e], + ) + .unwrap(); + } + consume_range(&mut db, id, 100, 160).expect("不能再撞主键"); + let ranges: Vec<(i64, i64)> = db + .conn() + .prepare("SELECT start_height, end_height FROM scan_ranges WHERE identity_id = ?1 ORDER BY start_height") + .unwrap() + .query_map([id], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(ranges, vec![(161, 250)]); + } + + /// 已扫段横跨一条完全被覆盖的区间:那条区间整条消失,不留下重复扫描。 + #[test] + fn a_range_fully_covered_by_the_scan_disappears() { + let (mut db, id) = db_with_identity(); + for (s, e) in [(100_i64, 300_i64), (150, 170)] { + db.conn() + .execute( + "INSERT INTO scan_ranges (identity_id, start_height, end_height) VALUES (?1, ?2, ?3)", + params![id, s, e], + ) + .unwrap(); + } + consume_range(&mut db, id, 100, 199).unwrap(); + let ranges: Vec<(i64, i64)> = db + .conn() + .prepare("SELECT start_height, end_height FROM scan_ranges WHERE identity_id = ?1 ORDER BY start_height") + .unwrap() + .query_map([id], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(ranges, vec![(200, 300)]); + } + + #[test] + fn consuming_part_of_a_range_leaves_the_remainder() { + let (mut db, id) = db_with_identity(); + update_chain_tip(&mut db, id, 200).unwrap(); + consume_range(&mut db, id, 100, 149).unwrap(); + let (start, end) = next_range(&db, id).unwrap().expect("剩余部分还在"); + assert_eq!((start, end), (150, 201)); + } + + #[test] + fn consuming_a_whole_range_clears_it() { + let (mut db, id) = db_with_identity(); + update_chain_tip(&mut db, id, 120).unwrap(); + consume_range(&mut db, id, 100, 120).unwrap(); + assert!(next_range(&db, id).unwrap().is_none()); + } + + /// 单次调用的块数有硬上限:宿主传个巨大的值会让这次调用跑上几分钟且 + /// 中途无法中断,页面直接冻住。 + #[test] + fn max_blocks_is_clamped_and_zero_is_rejected() { + assert_eq!(u64::MAX.min(MAX_BLOCKS_PER_CALL), MAX_BLOCKS_PER_CALL); + // 0 会让 `start + max_blocks - 1` 下溢,必须挡在入口 + assert!(MAX_BLOCKS_PER_CALL > 0); + } + + /// **回归测试。** 扫描进度曾经是从全局 `blocks` 表取 `max(height)` 的, + /// 而那张表所有身份共享 —— 一个追到链尖的身份会把另一个还在回补的身份的 + /// 进度一起"推"到链尖,那段历史就被永久跳过、再也不会重扫。 + #[test] + fn two_identities_keep_independent_progress() { + use crate::wallet::testing::key_bytes; + + let (mut db, a) = db_with_identity(); // birthday 100 + let (spend, mut view) = key_bytes(); + view[1] = 3; // 换一个观察密钥,造出第二个不同的身份 + let b = db.add_identity("acct-2", &spend, &view, 100).unwrap().id; + + update_chain_tip(&mut db, a, 1_000).unwrap(); + update_chain_tip(&mut db, b, 1_000).unwrap(); + + // A 一路扫到链尖,B 一块没扫 + consume_range(&mut db, a, 100, 1_000).unwrap(); + advance_scanned_to(&db, a, 1_000).unwrap(); + + assert_eq!(scanned_to_height(&db, a).unwrap(), Some(1_000)); + assert_eq!( + scanned_to_height(&db, b).unwrap(), + None, + "B 一块都没扫过,进度必须仍是 None" + ); + + // B 的待扫区间必须原封不动,仍从它的 birthday 起 + let (start, _) = next_range(&db, b).unwrap().expect("B 的区间还在"); + assert_eq!(start, 100, "B 的起点不该被 A 的进度带跑"); + } + + #[test] + fn rewinding_requeues_the_rolled_back_span() { + let (mut db, id) = db_with_identity(); + update_chain_tip(&mut db, id, 200).unwrap(); + consume_range(&mut db, id, 100, 200).unwrap(); + assert!(next_range(&db, id).unwrap().is_none()); + + rewind_and_requeue(&mut db, id, 180, 200).unwrap(); + let (start, end) = next_range(&db, id).unwrap().expect("回退后应重新排队"); + assert_eq!((start, end), (181, 201)); + } + + #[test] + fn a_node_that_failed_the_batch_path_gets_another_try_later() { + BLOCKS_BIN_UNSUPPORTED_BY.with(|c| *c.borrow_mut() = Some(("http://n".into(), 1_000.0))); + assert!(blocks_bin_skipped_for(Some("http://n"), 1_000.0 + 60_000.0)); + assert!(!blocks_bin_skipped_for(Some("http://other"), 1_000.0)); + assert!(!blocks_bin_skipped_for( + Some("http://n"), + 1_000.0 + BLOCKS_BIN_RETRY_AFTER_MS + )); + } + + /// 一块都没扫过就重扫(清缓存、换起点):不能从创世块开始排队。 + #[test] + fn rewinding_before_the_first_step_does_not_queue_from_genesis() { + let (mut db, id) = db_with_identity(); // 生日 100 + rewind_and_requeue(&mut db, id, 100, 200).unwrap(); + update_chain_tip(&mut db, id, 200).unwrap(); + + assert_eq!(scanned_to_height(&db, id).unwrap(), None); + let (start, _) = next_range(&db, id).unwrap().expect("有待扫区间"); + assert_eq!(start, 100); + } + + /// 用户选了比生日更早的日期重扫:生日跟着提前,进度的起点才对。 + #[test] + fn rewinding_before_the_birthday_moves_the_birthday() { + let (mut db, id) = db_with_identity(); // 生日 100 + rewind_and_requeue(&mut db, id, 49, 200).unwrap(); + assert_eq!(db.identity_by_id(id).unwrap().birthday_height, 50); + let (start, _) = next_range(&db, id).unwrap().expect("有待扫区间"); + assert_eq!(start, 50); + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs new file mode 100644 index 000000000..0425c4c34 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs @@ -0,0 +1,518 @@ +//! 钱包库句柄与身份管理。 +//! +//! 一个 identity = 一对观察密钥 = 宿主眼里的一个账户。库是**共享的**: +//! 多个 identity 共用一个 SQLite 文件,各自有独立的扫描进度。 +//! +//! 这一点和 Zcash 有个关键差别:Zcash 的扫描队列是全库共享的(承诺树要求 +//! 连续扫描),所以「用 A 的 key 扫过的区间会被标记为全库已扫」,暂停的账户 +//! 会漏掉那段。Monero 没有承诺树、不要求连续扫描,**扫描进度按 identity 独立 +//! 记账**(`scan_ranges.identity_id`),从根上不存在那个坑。 + +use monero_wallet::{address::Network, ViewPair}; +use rusqlite::{params, Connection, OptionalExtension}; +use serde_json::json; + +use crate::error::{db_err, ErrorCode, Result, RuntimeError}; +use crate::keys::{self, network_name}; +use crate::schema; + +/// 账户 0 下,收过钱的最大子地址之后保持登记的空闲子地址数(同比特币的 gap limit)。 +pub const SUBADDRESS_LOOKAHEAD: u32 = 20; + +pub struct Db { + conn: Connection, + network: Network, +} + +/// 库里的一个身份。 +pub struct Identity { + pub id: i64, + pub uuid: String, + pub primary_address: String, + pub birthday_height: u64, + pub view_pair: ViewPair, +} + +impl Db { + /// 打开(或新建)一个钱包库并跑迁移。 + pub fn open(db_name: &str, network: Network) -> Result { + let conn = crate::storage::open_connection(db_name)?; + schema::migrate(&conn)?; + + // 网络是库级不变量:同一个文件里混两个网络的身份,扫描会把 + // stagenet 的块喂给 mainnet 的密钥,表现为「怎么扫都扫不到钱」。 + let existing: Option = conn + .query_row("SELECT network FROM wallet_meta WHERE id = 0", [], |r| { + r.get(0) + }) + .optional() + .map_err(|e| db_err("readWalletMeta", e))?; + + match existing { + Some(recorded) if recorded != network_name(network) => { + return Err(RuntimeError::with( + ErrorCode::InvalidNetwork, + json!({ + "value": network_name(network), + "recorded": recorded, + "reason": "databaseBelongsToAnotherNetwork", + }), + )); + } + Some(_) => {} + None => { + conn.execute( + "INSERT INTO wallet_meta (id, network, created_at) VALUES (0, ?1, ?2)", + params![network_name(network), now_secs()], + ) + .map_err(|e| db_err("initWalletMeta", e))?; + } + } + + Ok(Self { conn, network }) + } + + pub fn network(&self) -> Network { + self.network + } + + pub fn conn(&self) -> &Connection { + &self.conn + } + + pub fn conn_mut(&mut self) -> &mut Connection { + &mut self.conn + } + + /// 注册一个身份。已存在时按 uuid 幂等返回原有的那个。 + /// + /// `birthday_height` 决定回补起点。宿主给不出来时应当给链尖而不是 0 —— + /// 给 0 会让新钱包从创世块扫起,那是几天而不是几秒。 + pub fn add_identity( + &mut self, + uuid: &str, + spend_public: &[u8], + view_private: &[u8], + birthday_height: u64, + ) -> Result { + let pair = keys::view_pair_from_bytes(spend_public, view_private)?; + let primary = keys::primary_address(&pair, self.network); + + let by_uuid: Option<(i64, String)> = self + .conn + .query_row( + "SELECT id, primary_address FROM identities WHERE uuid = ?1", + [uuid], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional() + .map_err(|e| db_err("findIdentity", e))?; + if let Some((id, address)) = by_uuid { + if address == primary { + return self.identity_by_id(id); + } + // 同一个账户标识换了密钥(重置后新建的钱包沿用了旧标识):旧数据属于一个 + // 已经不在的钱包,留着会被当成新钱包的,删掉。 + self.remove_identity(uuid)?; + } + + // 同一套密钥换了标识(删掉钱包后重新导入):扫描数据仍然有效,改挂到新标识下。 + let by_address: Option = self + .conn + .query_row( + "SELECT id FROM identities WHERE primary_address = ?1", + [&primary], + |r| r.get(0), + ) + .optional() + .map_err(|e| db_err("findIdentityByAddress", e))?; + + let id = match by_address { + Some(id) => { + self.conn + .execute( + "UPDATE identities SET uuid = ?1 WHERE id = ?2", + params![uuid, id], + ) + .map_err(|e| db_err("renameIdentity", e))?; + id + } + None => { + let tx = self + .conn + .transaction() + .map_err(|e| db_err("beginAddIdentity", e))?; + tx.execute( + "INSERT INTO identities + (uuid, primary_address, spend_public_key, view_private_key, birthday_height, created_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![ + uuid, + &primary, + spend_public, + view_private, + birthday_height as i64, + now_secs() + ], + ) + .map_err(|e| db_err("insertIdentity", e))?; + let id = tx.last_insert_rowid(); + + // 新身份的初始待扫区间:从 birthday 到 birthday(空区间), + // 真正的终点由 `update_chain_tip` 在拿到链尖后补上。这样 + // 「还没问过链尖」和「已经扫完」在库里是两种不同的状态。 + tx.commit().map_err(|e| db_err("commitAddIdentity", e))?; + id + } + }; + + self.identity_by_id(id) + } + + pub fn identity_by_id(&self, id: i64) -> Result { + self.conn + .query_row( + "SELECT id, uuid, primary_address, birthday_height, spend_public_key, view_private_key + FROM identities WHERE id = ?1", + [id], + Self::row_to_identity, + ) + .optional() + .map_err(|e| db_err("identityById", e))? + .ok_or_else(|| { + RuntimeError::with(ErrorCode::AccountNotFound, json!({ "accountId": id })) + })? + } + + pub fn identity_by_uuid(&self, uuid: &str) -> Result { + self.conn + .query_row( + "SELECT id, uuid, primary_address, birthday_height, spend_public_key, view_private_key + FROM identities WHERE uuid = ?1", + [uuid], + Self::row_to_identity, + ) + .optional() + .map_err(|e| db_err("identityByUuid", e))? + .ok_or_else(|| { + RuntimeError::with(ErrorCode::AccountNotFound, json!({ "accountId": uuid })) + })? + } + + #[allow(clippy::type_complexity)] + fn row_to_identity(row: &rusqlite::Row<'_>) -> rusqlite::Result> { + let id: i64 = row.get(0)?; + let uuid: String = row.get(1)?; + let primary_address: String = row.get(2)?; + let birthday: i64 = row.get(3)?; + let spend: Vec = row.get(4)?; + let view: Vec = row.get(5)?; + Ok( + keys::view_pair_from_bytes(&spend, &view).map(|view_pair| Identity { + id, + uuid, + primary_address, + birthday_height: birthday as u64, + view_pair, + }), + ) + } + + pub fn list_identities(&self) -> Result> { + let mut stmt = self + .conn + .prepare("SELECT id, uuid, primary_address FROM identities ORDER BY id") + .map_err(|e| db_err("listIdentities", e))?; + let rows = stmt + .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))) + .map_err(|e| db_err("listIdentities", e))?; + rows.collect::>>() + .map_err(|e| db_err("listIdentities", e)) + } + + /// 删除一个身份连同它的全部数据。**不可逆。** + /// + /// 级联由外键负责(`PRAGMA foreign_keys = ON` 在 open_connection 里开)。 + /// 留下孤儿行不只是脏数据,是隐私问题 —— 「删钱包」必须真的删干净。 + pub fn remove_identity(&mut self, uuid: &str) -> Result { + let n = self + .conn + .execute("DELETE FROM identities WHERE uuid = ?1", [uuid]) + .map_err(|e| db_err("removeIdentity", e))?; + Ok(n > 0) + } + + /// 登记一个子地址。扫描前这些会被灌进 Scanner —— **没登记的收不到**。 + pub fn register_subaddress( + &mut self, + identity_id: i64, + major: u32, + minor: u32, + label: Option<&str>, + ) -> Result { + let identity = self.identity_by_id(identity_id)?; + let address = keys::subaddress(&identity.view_pair, self.network, major, minor)?; + self.conn + .execute( + "INSERT OR REPLACE INTO subaddresses (identity_id, major, minor, address, label) + VALUES (?1, ?2, ?3, ?4, ?5)", + params![identity_id, major, minor, &address, label], + ) + .map_err(|e| db_err("registerSubaddress", e))?; + Ok(address) + } + + /// 保证账户 0 下「收过钱的最大子地址序号 + SUBADDRESS_LOOKAHEAD」以内都已登记。 + /// 返回新登记了几个。扫描只认登记过的子地址;成本只在登记时(每个一次标量乘), + /// 扫描是反推公钥后查表,不随数量增长。 + pub fn ensure_subaddress_lookahead(&mut self, identity_id: i64) -> Result { + let (highest_used, highest_registered): (i64, i64) = self + .conn + .query_row( + "SELECT + COALESCE((SELECT max(subaddress_minor) FROM outputs + WHERE identity_id = ?1 AND subaddress_major = 0), 0), + COALESCE((SELECT max(minor) FROM subaddresses + WHERE identity_id = ?1 AND major = 0), 0)", + [identity_id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .map_err(|e| db_err("subaddressLookahead", e))?; + let target = highest_used as u32 + SUBADDRESS_LOOKAHEAD; + let mut added = 0; + for minor in (highest_registered as u32 + 1)..=target { + self.register_subaddress(identity_id, 0, minor, None)?; + added += 1; + } + Ok(added) + } + + /// 取该身份已登记的全部子地址序号。 + pub fn subaddress_indices(&self, identity_id: i64) -> Result> { + let mut stmt = self + .conn + .prepare( + "SELECT major, minor FROM subaddresses WHERE identity_id = ?1 ORDER BY major, minor", + ) + .map_err(|e| db_err("subaddressIndices", e))?; + let rows = stmt + .query_map([identity_id], |r| { + Ok((r.get::<_, i64>(0)? as u32, r.get::<_, i64>(1)? as u32)) + }) + .map_err(|e| db_err("subaddressIndices", e))?; + rows.collect::>>() + .map_err(|e| db_err("subaddressIndices", e)) + } +} + +pub fn now_secs() -> i64 { + #[cfg(target_arch = "wasm32")] + { + (js_sys::Date::now() / 1000.0) as i64 + } + #[cfg(not(target_arch = "wasm32"))] + { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) + } +} + +#[cfg(test)] +pub(crate) mod testing { + use super::*; + + pub const ADDR: &str = "44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft3XjrpDtQGv7SqSsaBYBb98uNbr2VBBEt7f2wfn3RVGQBEP3A"; + + /// 一对能用的测试密钥:花费公钥取自已知地址,观察私钥用小标量。 + pub fn key_bytes() -> ([u8; 32], [u8; 32]) { + use monero_wallet::address::MoneroAddress; + let addr = MoneroAddress::from_str(Network::Mainnet, ADDR).unwrap(); + let spend = addr.spend().compress().to_bytes(); + let mut view = [0u8; 32]; + view[0] = 9; + (spend, view) + } + + pub fn db() -> Db { + Db::open(":memory:", Network::Mainnet).expect("内存库") + } + + pub fn db_with_identity() -> (Db, i64) { + let mut db = db(); + let (spend, view) = key_bytes(); + let id = db + .add_identity("acct-1", &spend, &view, 100) + .expect("建身份") + .id; + (db, id) + } +} + +#[cfg(test)] +mod tests { + use super::testing::*; + use super::*; + + fn registered_minors(db: &Db, id: i64) -> Vec { + db.subaddress_indices(id) + .unwrap() + .into_iter() + .filter(|(major, _)| *major == 0) + .map(|(_, minor)| minor) + .collect() + } + + fn insert_output_at_minor(db: &Db, id: i64, minor: u32) { + db.conn() + .execute( + "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, + amount_atomic, subaddress_major, subaddress_minor, height) + VALUES (?1, x'00', ?2, 1, 0, 1, 0, ?3, 150)", + params![id, vec![minor as u8; 32], minor], + ) + .unwrap(); + } + + #[test] + fn a_new_identity_gets_the_lookahead_window() { + let (mut db, id) = db_with_identity(); + assert_eq!( + db.ensure_subaddress_lookahead(id).unwrap(), + SUBADDRESS_LOOKAHEAD + ); + assert_eq!( + registered_minors(&db, id), + (1..=SUBADDRESS_LOOKAHEAD).collect::>() + ); + assert_eq!( + db.ensure_subaddress_lookahead(id).unwrap(), + 0, + "已够就不再登记" + ); + } + + #[test] + fn a_payment_near_the_end_widens_the_window() { + let (mut db, id) = db_with_identity(); + db.ensure_subaddress_lookahead(id).unwrap(); + insert_output_at_minor(&db, id, 18); + assert_eq!(db.ensure_subaddress_lookahead(id).unwrap(), 18); + assert_eq!( + registered_minors(&db, id).last(), + Some(&(18 + SUBADDRESS_LOOKAHEAD)) + ); + } + + #[test] + fn the_same_account_id_with_other_keys_starts_clean() { + let (mut db, old) = db_with_identity(); + insert_output_at_minor(&db, old, 1); + let (spend, _) = key_bytes(); + let mut other_view = [0u8; 32]; + other_view[0] = 11; + + let fresh = db.add_identity("acct-1", &spend, &other_view, 100).unwrap(); + + assert_ne!(fresh.id, old); + let outputs: i64 = db + .conn() + .query_row("SELECT count(*) FROM outputs", [], |r| r.get(0)) + .unwrap(); + assert_eq!(outputs, 0); + } + + /// 删了钱包又导入同一套助记词:新标识、同密钥,扫描数据照用,不能因为主地址 + /// 唯一约束而建不出来。 + #[test] + fn the_same_keys_under_a_new_account_id_keep_their_scan() { + let (mut db, old) = db_with_identity(); + let (spend, view) = key_bytes(); + + let again = db.add_identity("acct-2", &spend, &view, 100).unwrap(); + + assert_eq!(again.id, old); + assert_eq!(again.uuid, "acct-2"); + } + + #[test] + fn adding_the_same_identity_twice_is_idempotent() { + let mut db = db(); + let (spend, view) = key_bytes(); + let a = db.add_identity("acct-1", &spend, &view, 100).unwrap(); + let b = db.add_identity("acct-1", &spend, &view, 999).unwrap(); + assert_eq!(a.id, b.id, "同一 uuid 必须复用同一行"); + assert_eq!(b.birthday_height, 100, "重复注册不应改写已有的 birthday"); + assert_eq!(db.list_identities().unwrap().len(), 1); + } + + /// 库级网络不变量:同一个文件混两个网络会让扫描静默失效 + /// (拿 stagenet 的块喂 mainnet 的密钥,表现为「怎么扫都扫不到」)。 + #[test] + fn a_database_refuses_a_different_network() { + let conn = crate::storage::open_connection(":memory:").unwrap(); + schema::migrate(&conn).unwrap(); + conn.execute( + "INSERT INTO wallet_meta (id, network, created_at) VALUES (0, 'testnet', 0)", + [], + ) + .unwrap(); + // 用同一条连接模拟「已有库」,再以 mainnet 打开应当被拒 + let recorded: String = conn + .query_row("SELECT network FROM wallet_meta WHERE id = 0", [], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!(recorded, "testnet"); + assert_ne!(recorded, network_name(Network::Mainnet)); + } + + #[test] + fn identity_lookup_works_by_id_and_uuid() { + let (db, id) = db_with_identity(); + let by_id = db.identity_by_id(id).unwrap(); + let by_uuid = db.identity_by_uuid("acct-1").unwrap(); + assert_eq!(by_id.id, by_uuid.id); + assert_eq!(by_id.primary_address, by_uuid.primary_address); + assert!( + by_id.primary_address.starts_with('4'), + "主网主地址以 4 开头" + ); + } + + #[test] + fn missing_identity_is_account_not_found_not_a_database_error() { + let db = db(); + // Identity 内含 ViewPair,上游刻意不实现 Debug(免得密钥被打进日志), + // 所以这里不能用 unwrap_err —— 那要求 Ok 类型可 Debug。 + match db.identity_by_uuid("nope") { + Ok(_) => panic!("不存在的身份不该查得到"), + Err(e) => assert_eq!(e.code, ErrorCode::AccountNotFound), + } + } + + #[test] + fn subaddresses_register_and_list_back() { + let (mut db, id) = db_with_identity(); + let a = db.register_subaddress(id, 0, 1, Some("收款")).unwrap(); + let b = db.register_subaddress(id, 1, 0, None).unwrap(); + assert_ne!(a, b); + assert_eq!(db.subaddress_indices(id).unwrap(), vec![(0, 1), (1, 0)]); + // 重复登记同一个序号是幂等的,不该产生第二行 + db.register_subaddress(id, 0, 1, Some("改个标签")).unwrap(); + assert_eq!(db.subaddress_indices(id).unwrap().len(), 2); + } + + #[test] + fn removing_an_identity_clears_its_subaddresses() { + let (mut db, id) = db_with_identity(); + db.register_subaddress(id, 0, 1, None).unwrap(); + assert!(db.remove_identity("acct-1").unwrap()); + assert!(db.subaddress_indices(id).unwrap().is_empty()); + assert!( + !db.remove_identity("acct-1").unwrap(), + "删第二次应当返回 false" + ); + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/tests/fixtures/get_blocks_bin_3768621.bin b/chain-runtimes/monero/crates/monero-runtime/tests/fixtures/get_blocks_bin_3768621.bin new file mode 100644 index 0000000000000000000000000000000000000000..dda7a041499cd9dbb2647c62964b7471a9b18817 GIT binary patch literal 69547 zcmbTeRZyHu7pToUGYsw?G=$(T2@)(g!GZ({F2Mpp5+p!ych}&--QC^Y-Q8XP+5fk9 zovKskDswS4SL@<=x>v7Wy=nj~0QLa^02NgK>o)^)+aN?#`2YVG@}dMLW@qxyBoz8W zxP;1>n{!QrxI)Cr<9jj5EfVufaSHmeW8$MIaLx!CR0*`}u>}Cnh5vkyjKo$&V}mUW z(7n~at0VZL=Q!b2T6TwberY|pL($1eSda;SHk1cA0kfLUB$38QA5d5onmC(BW2+yb zrrOwc2EnvlwDmV0Z4g$>w;+OnOnbQh^9cmXL`pYJbybdzyVr>@o+E|6zMy=_@}I$uWc6`ZB+1o*D> z2v^tCsjBsif=Sx<`IRMJhmfgfs|}_oj8GsXqXzSKD<9WWRIZEd`>p#nVFhhtE2cgt z;~3B#9DAeeqRYGyc}>)7k*@)QL3 zP?Rf%ph%1?YwzL=1-_1<5%rgQzi7-Qa+iRZW4jA_$A%jE8Zca19z<6;mLFP-FJuWp z`>*(;(chxw(O5jT!{Fp zlzHMG-_yM}&D)yqH_5$FTR!XJ_et7R^FJ~aw<%*)W}UB=j~y`cl35!i<=aZYdy}rM z%El;wve?BVQn%i$n~TdL7{%-=JUVAc3;w0_8Du{<>U76$>zNRybN*W&Gt*sY!KhqM z@5|n4_Bu;LQl%#9=+Pg+kI2#|tpb8?4Xz}-XK}7~7fxqih%SV6pxBh&DIPPu6mKm% zpf9!BG|`W|OP`Fll4nt*jdT$j+QeA>`ls_SC1|3Vlj^Cb34cqZ*@lx+vZrp|sPaQu z$PnjQkak|^Qs^tyAiw}VZI|o2R_~^2;gZ^=qmbk&fe zO-z1@0L8OXvZ_RhsWJ6w8LDu5fTD?2HnAw_lD|<{;7z)d+4*jB+en7ff^k<~D5fW3 z|7yVx$2yuxz3RQk)pP=((s3WH@2hGyEW-`@>h~DL!Z_InmXUfa5Hae!cU>kK-BvGZ zND<7jF4;3m-3d-0^4%7}G`6AG}WUD-Uca~nqS&)HF5ofy;aVix1q zc<%bA8E_wC$-pmA$up1)(8$DHn1)G{p_%b@v^pY=Szs9vAL~0``x8(xKc zI5uEN;ux*=R8_^Mqy8DKOg7*H8qkXDw4=H8xB4DrrgO#j#7H7~-et(g7@&lo?m99F zDkyFFR$zxozuo#8_R!wIK1pOJW2QZe~?seN$|&B=lHZEsUq>S(beH6Pw6d^*QcM6Bn`f)@p zcHV`VgzU&PlGwNi^KHc&EX7C5oE%Igg9UoG*Q0OGb`lL;eNp^;B2%;sOzSy5YQ?M6 zzr?p%{idK*boReE8HzT%_hg8yv%Fy`=|xUUeu75l!IQkk&OBnu}h&H&9v2>JR+Luv$j{o zIb6Ku$&g;R7mfTBINE~drAYtI7A!J8?EQAGWb3mQUQd)71N$HL=rP3jM_2pm5FgC9 z8|99RO^_7srdfr@xT~N?J>C`>$Oeimf{$jdPzdXSbSse=d}e~f@Q}%2u;w2)8GP2C zvd(yZgUW5VTs>ZF3X3E*JIZyLEpqPTW~;}sYC{E|ziL~R+y!nW{K_X92<*`>3%}?c zy=fHra#YVUej%;8=}{(vX)MYSJ`zH-{IR8dJ6nR~`J(R0x4} zLSMvvUIB;mhN%oeEToBc@&sc$>8x2kI^*%^{U~tQVPbN^%DVj8!oGoA^9z!89NW*# zqDJkv)zM-5PE#>`Mck16c5>gcjnwocK3|<566K7gfwCFi>q;JB|9H;TqsdpHJ9y<#7c}u@auzW? zTe;Dik2U7e1^*fACcPxfli|oKYS`ad>2uc29xu;iBfQ1NB#RA3_cJoP4(h-Jcd_X!@T zhulTIXj$3&WRy7N(}JEuAL(Y(-YQi}W+6hHv&r+jVg1%FtYbUt=YrTzM#jrPqvOfO z*U9T`X9FT1X|W%H-D@2B6Av}_I`qIi7kT`MW~yU_UhQB0Lx#k`V%F|r((bQl4;4S& zNN5Tu-c)bkq1Ul=otBF5_-Y!`#j(+znxan9;1>zY>&*(|?14Bq0H2+UC1x4X-L^Wi z17b3ElXR`~JGkoE9$sjm^?@V^aYON$1Gvl?u;6EA&KAPh@D<-0p0(e9P-DBP5BrKJ zCun)RSf8*;sbq~V7j>(G5FlJ5W@kE%h=JT;D4WXhQ8iomj8dL$m$~7hU?vXtN(UFp zyHylwN~UUMRlUfZUu-jdpi@VZPn9VlYw=1j&0jA+BJ(VUKL0-Uru~#4kNQ(6Yb#$T zz3umO!HsL@OF_}q8Lu8GS4!Y1-SGtMaml8aYD!mk+&599Hi~?Eo25QM5O z0`i0Ipbkg~0g6Yjq_VbcAh(*$vV7qTgSS>8Q@OR{BN&f6SKk|cbyj;r#&N?~noD{@ z`i%2?3Wn#xkxlw0&e@U_?t5#lH@c+7p?%%j?PU=*2>LOG5-EX@h|9GS-#n4nJa-&t zV-FM7OKPjHvVwzp*;G~m@5!@5d>B<&--&pQtPUm5qq7>MX=k3TjHWAAF*VL6yXVZJ zDjC+!3^|05^}T$J`Qu?s-&v_OeeQ#Y=EVU2e)tvFM*Ycjz;avdv`gu z;RTJ?xjiX2+JaqQuZrVjFMG>Y0u-wS&HTR3vHm!3&Ar$Aa*eiX(tc+2(^3JB)%rX> zY(|{posAuZDi^lkI`i&GhU*N-;eG3A{gS)mO0Bi5!E*O$Az2Xl zzQ6(hFbuI)3q7JV20sH7xFaGZL$0f(SI;EJfisXkW5$@IJ(mi{zl_v7Bjx(}&qi3x z21Su-zMwtks^Q5aHMXb)o?o~g^Pt|xo+rr#(ydG8t9BeYwkUSgSXnkd$SCuc=V$SI zT#<({S@~yY-^dY!|=4M8Kwu&_E&q~G4_BBJ0myYbcm`p=wx6D3L#6!b&( z^w;bNv)H%s1w{?hx!oYj@a}*J598S9w*sgkmapwcCz%jxc37bfj%yZmezUtGh9<3P z(S9y!Bn0ftUFt*IdUWtdvM5VNx_285C|_{Crtn+mIXC;OVZ7wsT%y=mf;1b|n()}sFd@f=g?&QViM&>%`GJeim}g7P@Ee=Z#Q{gCGC4~x&X!e6ERnvvqS(t=83 zxfgDCe-*st_oJYdR_E?~eI_Z``1rv*Fw=aBN1D>~vL|ZLE#Avtnv`45C+pE@gn-^% zRVd&GSKDV{B>SCZ)i<|w`-*nzVhN%Y2yRzq;SqJLA-uyW3 zecvIZqB__h>sCkQ=Fog!5S^odztz_E&1~t#$hXw3<*X6IB4$4WJwc40bO?j<;WF)X zrmZJdxwZvg%X+JOeWjF7HQ24(x80`VKZxxbd@snR!fbS_pE+{5H^0Di9k}(byGIVQ zsx2Qc56i&Ch>jc|M@Eo(r&U|D&u9CvgS*AGZH82i{|m#gz0<=q>@dSC$`_@AkwCZX z^+2c0HLCW5mc}}b5C#5D1@LE$7-tJ##>BO@-__zSX~%)s*RV9sXEaJIgGu;uIGaB% z>TDrXrPbcOL{A(wF5P+t<;-t?(fOFFCJPw?3fC-=@@x+_si>j(z-*ozcOmtUqF zeDPY?YD)YII+B5VLS!MLhA&F|*IHDaTe5$~TwCFr^M6%@4JD_5OlVb9GKwIY^PB=R zA)Ox7HpqAN`rn5nBbZJM7NR9?x+dZNG;OX%_l8b+!1*9f#lH1*Crqt--4f5Z^m{rm zgu0B7`f;;XXG=Z^ok#$!3h^}kp1>-1dPY&*q1PW0JY0N+5r${cy z8i81Xq0F(8e+yG~^?)nvLpA#Za;<9aW7vGKh?eNX8m`mJiXVgQ5xY+ocO^A)eVTai zf}HLW4Bp=5UEYe{tB(zTS=-A_l3XEWd4IGJ>h>wFj+fN-828c|RkRU=`meQT$8a5Y z${(cjUROQ~;KD(iImLa(5-4?oH955~DeW^cysC&)LtNJD6oY@K4p(!#k#H3>K{Kj7 zaKwV$@9uyjfzucMCzQ>h(XY9i5k@N~?Y-KMw8nXQe2dW}$@WZ&h|Ok;f0KKb0IrgT(Gzt8gH zk;oI~WVeL#sv4p`c{?08mVP#>dM(EUUEA5{m30fPbg1(J)3$m$j##J=>kV4_M20#M zwpa2_=Uxl6=o3$x3gddnrb0kP4N9o2h2!q;Pk)l8S1{W{p39SkNCj|J6UY)ZR#pUN zmc#zsd~rB-&@jKGv`>UC74!6X6pLnO4cA*On16U zc2~KK%Z`uY-|0?Ib=CMDx?(rQTB&pi)6Kz04f*9kS%=xbL)*%iQ+MCne(WTnx@3e!($RHcwn+33~Z*Z%t`F1fvp}{-(YgI=zZ^#-1{Va z!^hYC_EXGH#sr$uc7%aKj#$RLl5n%*uQO09n;(`&hA05|yMt{I69^FkYY6Eh=fZ>F zKp;5GUhihHnq6;Do<}@s1;>EHTM$l1!_EaRp|uv`flJ7 z9J!zAU{gF6k4jJ0f2aOJ>3h3Is1N-PZt1a)pH`z1S+Iecq zly@X87Md=sjKS3$dSqEP!`os6Bwy9+SR0^Kn{q})`%+-GyvdC6^$|S#WUELRI$h++ z1wsO55mJ^_WK6z6-7e0?KzADtygyJPr061@d#5HWOHJ_PzSgLoh|!%p9v?J5DIr`MFP$ndGFC&1IJQTr8Qqc|J2vOry?5-c}p^N(wm9=hZn@~x5KN|(OIaINk@6WVaU7WNp zIN`KlhTNX5dcrN!w%wMab+r9+jp`TqRkUmnHQ0x~>(BUBVm88oal4CoNk*2Gtk=S} zwTmVuDL-*uURqhzOu{im!w(5w^fCfpsck#0Q5|IQFa^JEY>+*pl2Z}&3FTQU)`>U* zPb=OqL!67^9++=TE}(8D%VQw*M~;?~U@>YcYtm!PxL3G{Zmm6V=B!_AF~!c{^XPk= z*jAE-Byl<~`f1{U(qh0r{aXPaDVcV5Uka{~{2I&B?PEjxT>YMfAB7iDFxcfU4ZTGC zU!IE`%cY8%ZKeyUhpwFvv{Yb*^Lmv7h1|Kib)-+uG3S6&BSsvaJAxn4)sk_(GX_*m z_2HoI^XdjbIK z%GY0Mep_|DkDFB((w`Ae0{z=3PIMxG?u58te+MlH zb?W&3X@NSQE9ghY2b1bH1j!I)+fHY!-n)PZ!iz1NOnqmxd9u=+tZ`w8uithFonOtK znagLrEK9e(8I5Z!A$5Eo;Wt_evLz!rvQW3A`#P{%3lCy;H>PTP;Bou%;JvOF1o08h z{EE3^2o>=gIc-vpbU}r7RO4V9$0fTe375N(Q2iWYA5LiEqvRW0D9Fa#UbP>6_*}5@ zht^G2y3)XmJnFkj0%n|p)S?M(>T1S>=1#V2CYC>A`I==Z_>H!TzAg{z@90ekm1cFD=Yr27b_#=~$D&X$JI_e17 z>-1M?QVl0pJ@1MWix%9pbVWY$8)~wLoCn=mb;rO$UZq`2`v$8gj`OxG%mV=gnm{#Ei~^~@`y9?2wOZSzd70C$663x_pL`NUAm2{I z72ttI>pSch8DH@QolYho2A#l1XjJ>49#(9LB-JvCMz|H$~oZlGj8X3(Z+Maz;{^R}(l(2YNo3ql*Yn`CfScd2)>ZKs~>K>qe z>BTB|(z<0DoR5%@4lJg@=TjsD^H6`+&}E6S{fkb@#r?10c-3?+nZ5&~KWXR`8;YvW zBF$mpN+Tv^&K5pq9K4+D;aE5XN9Ka--4McS!Fk7E_jyGBB;Ys?l#f+IG=aYhHM(k! z&}b}L)cnq&85r|q@p-NH%GXZa<&f2LORN~`0E>6nd;ejmQ9rmEBWp$B&$d`pGuCn` zXygGrRt>nJEhr@Ns~^W^@bahMPUl{EXALGU7kOFxq}kaHR$Y;1 zz=918%*!M$il_I!oQmRJo+O$ht7ruW#{hw3SHqxQ{xZZda3n=6K?=OUH|7`iz`K%q z`^OG;H(L!WIwWuOL_x>5a?HOhdJ7X_v3|R^N}lZRg3oF_fkxY{QQ5HuywP&#N+s~; z9+>t6>NuKSHLK2mf+6P+4%Msz;=rMGh{Ky;CE-?x&sUo(l+dM|% zZyb#%_UcB1)G-3-=+^?TaUt$~J(@;p-!OGnw7$9PvSUZAyYf(_7e)EOPCYqcGHPKa z{x?v!hMqm-O}Ab;=?8_yfM|pK_Q*Ifl>F&O+Vehzf4;HRrkfGQIPhTL&=Fc z(WH9n#9~NMK3ZZaVtzVG#Tn%I5B$@sAo~bRPpnOdl!1c#R~b7(F%xqQQB-PzK4HB_Gg!J`?^0%c2^8j)KX;BF@o?}4wJb{ zrGCfJvNA9YGyW%2#g4cmqDQ|B&2KocN#VHrRB$G=zF^X>MuGg&!>J?Gd~Shw6D#h> zw+lW{gApj;)E380s)Szp+AMvmMjZ_AN>-h=%l^>Eh3iK`2R{r zntr)>byVaig``t%Yp9uUl$jTy_QuQI0smRM_O;G{j+>N^F=AS8PA(P4>%$l)E56<^ zxxbhm{mqVfn-=wrimuP?mw@Pd{kL>Hy6NZM8ox&lK7o#OM*~|4 z%g~3j29T#aX5}b+;0DlI0J?|*T}1*H?;>d1c&8w}thh8u&hdl(owx+=gd)lfzxD}Z zD4pnrseB`;3U%0oiArtQmT4&S1ujn!ds{FnpOJqLK>w)LvmSm*S^|o)fMkwp!a<}x z%I{Y zUYZf`>X$gXRG)nn9$oYHeRZiYw|Tt-4qK$nWTa;+DTX#OOjEt>o3HOs3I?HWUajMx z+TL}~xn>;4V8pJ{_~ce7a)Lm7_SYSuo&w_m`Rq|J5|G6eH{Hhw9ZybP$3xH=-D< z+>{P%6ZZszym2cT8q711N(k#H3%TlfADrY?be=yT5&98Oz9;hLC-{`tj?t5o0zbSf z9}6ocFulX$NHTY8XxpO$fT}L5%|>7Ni-9;$*%rxg9XMkU(VH-$6yebq2!=0am{TsN zd+#T7D5vwmNr@Be)p^<*k;e2v`@+rc(zVhd9d!G880HAxXF}n%(VEU?{+Y^3qVdCc z%C?fdx5*Uz`%?c!@+uEAIB>6V@*8#L)Om4oJY(#~N@e0g)<;W{RloN#U)~-VCoU~B z0vNYCPvJB_qWl;5+VaQ|`KSwm@@}KztL@VG-YwXAJi#0Z=Wm&F&_i3HZZ$sRpbspq zYxNiUaVpj-P`|?2FWfl+k7ST^FL%FwrdK2`($yaIFYUJ0?@iFvl9Uaa7#$uZM&u~ z`BYd0y7?GPyuAqoyQDgL3TGe|a>an0=fqzYv*2RVq?}5S`cen-x;EU>iI?8Gk* zoa$v2jHtWLXZ!C~E~-$slhs|I7EFa!jXJX6xX4y*`bubL*wURY(D1WWGd!mJA{>OnLHZ^5Fs5TK|3DthYOA?rg^2yWVk{G?Aw_t@x7ig5 zJ4c(Mxi_!CfrDoe$n8{1(O#YnYdvUUSQyOV25|2~(pTfsExx(X9%L~B+05{5kk`hM z5v!ZW?`+DilMO{voxd>9^BY>sAfT^z!I-MK(JC15#fm`PZv6IuDI3%?p}6V*m9_OT zkBH}GJxp#V{W(AikI*kZcvSJH@mP5!tG&e_cb>D(md>g=S+Qt;tJ|YY?X@I5zQ_bL z40n8X{^b>J0+Dk_X2|{PzhvtEFVl{~IPT@OAn2)oCR$Q;6HuN3e;AJJS;#xO#o&I1 zwX_2tyalbP13lvSfsQCcTG>U$t!j|+p)WJ3dUNwgH(2^Rek7h z81Q^mDZhhX6=-tml$o);z2(?VGB7^Y2;*joiG7%MzU8fNu8U+ami$Yw|DB|jeeDvz zd*dO;p|@3)2ikXW1U`VVJ%Icm|dNN&2Mvo^plx#`$} zT$HBU_B~ceQSQUL6*De2fm1pMD^)dytTCEH6J;d6DVZ^(ztr?!mR=oblC2%0*gT_q zJO)KVr@}y&>xeyBKy@G}DGB8Bb>`E{c9dw=1fsC_=Vond)!usWJNF}BlyZ;d({bzRLtxP5J{Ayb z{Y-e7RriPSf+&&}uvN;vzs z4H6awJ#?helkr6Fuib?G$?vs`{D<()gszo2i&^?nclV4UP=;D$&6<-@?4U>U2M@+=+zA~??cSko1phZVRSf38e*l&MM^NNmIDNnn;awSP`8fuJ>XUI)6p+1 zl{=T~&x~w{TUE0g0;M4dbNC8Dch=%5Rw?i56Us)fjWe+6(nAyXEx9FYj}FA28RYw? z6f`F%-h*CFZJp9_u%_!RKWQk-!HXfF zvl_5lArJo`?MKxJOO3obz0+t6~0;N@{@ezp4@kJoJOO> zFsfG{+SyWxYn-8OZY6ubU61`>YH6*am)R0FJHen3tqVs{+ZSQF7j=!?Q0)IDEFk>l|?xScoz+|Rp;7K!nMxHS`4uWr{+T1&~R zkP*#9oG!uh$?>f=6eXcl@B7c_f4XwLOOI@B8Bau2Jtx3O9^vUC(#SD5dx8UY&(e&r+)?*Jci_j&!ST-ZlnvwWanv-MQd|#cuXmn&J{Pa$s9Q8k2I;O68UoM}XgGOs1EF~fnain22e)R-5Hn*>i!Iaz|!IV$f> zryk{ruMvhSu@naf7=aL7Wg2+N#bfl}3*3gTE(|=elr?F3McGvn#A)A+r_W%D0DsS{ zRSTMbucT=e!*_CK+BSx}-`NJMq`KeX?=P)rhKonIz#6g)Z(p0#ap+b|O5d5)3F7v% zj(ph?#oCBovmV{*wcRwE?46U$TJ9DQ0P!1n5^Pjc`1JjyqW`MC+W7>Ije;=3^7UDu zB;wOdC1*?{WbDVm5@_Wb@a_cNYBp+xzVhHG;8ITca;J=aiKg&kOo-_HhoYaCqEP5G z$`5?#$Vn2&aG4aw6mKy=O{K3}L>t;YqYp8ZEKAneWnU3zD2Y>%+)c3a^r@?j@8Or zz&4t68BkJy1;Ci9&@~QDFRS1Duj*^@t;AU&=6U~G7O}iR)@!;268V-oeY&`>_J=sr z;+quB+Q7h@4X*-|pS|qNBs8v7O_o}{-pBE_HcaD92l(1(=}+-o7MEOJFNesqGd>Lc zB~t+5e|M8%zi!sx!)E;HtYUEaBf{pxhu(u8&~t~t-7RE)7vAs907?j2Hq9btf|ECy zMDnYTEVvqxK2Kl0b%IW3u#W>3Lg*aL_eS$pZhd;&VebaT{PW?*)~ODtZv*>#Cu;2| z=B|f$t#1Tr?@iQ-(=|C0;lMI;pE+W?PCb<`Hv5_<#kE(xK2q8va;lR(81$NPAXHo&uAn;u&Pp^>#*LVy_dZou`}(&fEoK#r(*bfiZ3 zn-l9MxzA`nXZqUy*$F+}4j%&kz?xsl(4@SKlsQpv^f6|rHV9!Y@H2ef3+FxN7V*}E zXSiPnMqfFZ7Yas+y2yU4I;B#uHCt0JW50^RK7ztZOv8{YCQPSHCNDnPy&j^<~4 zmPyQgde|NPDR7~540U^m9|wt%hYZK6i(-+U8TbV0H_D;Y-cS=geD95;+t~XyvZDI< zg_O-BH^C~YWLf^zsn3~DT8k#>;h`9oHpG%D&z)Y28krkeVgjn%^R+y^D@WLQ?)~*< zKyT|~k~byg)3NnPIel#fTT^zZt(*eagRjvj>oja|l{ero#cTb0icGJc$leCvcZ4Ik zS3#@!3wD5oc;HVna6@rO@BY4K0muink`r;VoGDpif37ayPN=wscMl%X>3h4vziz(& zT$_kkH>>jkwvn7kdGg@+|I9KpDC@X4W|wmmZ`*=nO^GcR>_Y~b@Xuk&v;F#-WxWSm zWwEg`ossu&O$g8or8Tm9>8VFU>{%!z;+l3cwBe^uHIT;LYPC?yv>UIG^PHtyeUd$09ePu!fsS7CHBFY+26s|xDMqAC6 z{ibs48o|+DWnj-2j+Q1yMH!JrDtA+J#FMVzp?pUsGhZ=o(!(I$s8;pswHXd&`(^82 z^8ByLZ|r@fi0buwHM1NFemqWsE7udMO6`KdU$?kSIGsPvr9N&|br0;hv^K_w|r7%NbWmYkSB25uECQi{>$zp~4C{Fs3aZbwwa{3g0sK zZ&cyn{lT#sxfDw*Za1-?S1TM~z?~6j355o;jye3U;fyL%e}y{Wo`bc#a#c5iPbK2^ zR*AM2rs>^{Csm!QZO8wrd?ASMdb_$)K(2!Mg3u(X@aVgAFXd|>Ec+@~TpL~|2tON(_^%ndG`Dd30 z9{wEmuY4+(PAU)D7H8ZpHiE1s(PV3H79%xxI576jK1So)AH{z2EsD<(7bK6JyJPn# z8pzHg_qh+trFE%{K+3%6o{^ss#dgw03vZ8ETu^csZGv+2aO<8(K|c0qI84v?QEyN8%YR$S{{veZavx?&Zm<{IN>Hnpk{{|Kkhl6ETDsZ|Y zF#E^F9(J*OJTX?FZ|!FnD}uLUz%W8|iL({gW> zD#cd=>$yTGp?=}7U~(?DWAUTP^U0^`(+TGu!9iQ(M-%Wa<&;kDQtDiPS z{h4nb_3ra;QnW3gX{ZCQfre(hllIGZbM)1s?3MoTz&ov9v5bu{Lmb4ao4?qt!9$Dh z$Vf_l-8pECzIR;Fjwza*tc-mle~SPIwo|aBElePlQ8QeD61{6pI^xPct?W^w8VM|w zUfN-FfnDlEC)~9X-XY#PaJ4?F^1WVS>W+6R;*nLm(_MHdZ-}IT8M;>XW4M0JV*bB@ z1*JbGX;#_ssH2KbET4*}7cYMu%4d04@UL@S9UP)>yx`q#qIidgsA%1+^<)vQh7cDZ!1E6%>HyRXpT!#q-@>CU>uwfquk6&R1Yj9LIyDmZ`o$rm z#u3=1*~0nM`>^L5aG|{6q+nv4KEZ*kuSrML&t`JNxSZ+!IOG*e&I#LHs5Bgyzodbe ziOAyh5`t5uCEM^WF8PZ-qdOu5-zC}&taXyfc}C!ooah!KPtyR+@B1e>H_%5uOSanm ztB&I_E~|LW84MN}S9s0Pnl{btRH&QZ^d3+x;sLo(=3Y3I9qv|CxNX4ZQ!G66i=a%q zoE2=~wxPOPG3kak=QwI?w*VreiV|yuT2?|Wa?YAUbK<*9bzR191L%vM@5lxnJjTR% z*^d8m<^OkCPF!penLj^(+=eWHldI2x*bdCKK%85FvLx}L)aJP~QM$)t#y7KpOON+f9e_gHn+QZTHa!;0t>|9Ia0@3KtZ{)%O9 zo7~E{QRB!rHUIeD&yy4g`wa)D^%(ID)foThWiS@sPa$6HFyO;I4bDlG<18Haz%WV_9;s*Ag zKnWrm{tZ;Aw2y$U3H_jhXeX4nH&YD@G$s33QIbMGD+)aQRbr(U6Ntl+OV>`i5li2| zQc6wLibT#qDg5%ztHTLkZAdC?7rOBbd#eJkl0WqVVY|TT%Q*fjk}RbyLVJSurNW6> zsUg*cZfm*U9^@4=cs&H1+RH71Sp^}hVK7D9rR4{Rw|;X$bQRHIiryrH0qL@DER(;W zBW6>LlE)`c!Y=0wfu#H&bkoYaqeG%feh zAoQp`S@eBU(wYF{N-&3G$Xrt%5hU_X&1XBch}wtJs&)`5u9!o$qN|SigR3$VzaY`7 zghfC4DrDgmyxpyZ?&ybzVI5OXl7<5O()ORuxk%ogAz@?^+^?}}2qAAl4!|GgatDM8%bcK5 zwE2@xL|UY&O@u+;MG{Q~7y?H9z|TLJJAeQD&@02Emi3o7|9cQzpIFAvzr1JJy_DEZ z&H?{f9{`;M@y?%!F6l(0?uLRlFw5~re{ODW{GxY(Mo)=eL5f)!SJoqkZF{OpRlpafFz)s z?O7xdyPuRAa&q^0=%Od1*X-ezI{K}gWcDoifPrvJ^Q`1^MvFkbvXoQKm|qj%Mt3NkWWVCx(ab3#zlo7?i0bGDXD znT}}`7ufIM!K#0CQ{f_mWUu1@KE4C&XgJ_y&HI;*O#fZ-J;!H44R=>4>oqE?`$RV$ z)V-_li=~+3Y4F|l!PCH%(2cMki#L!2eg+@5U7U$xo*XM@$OR~t>>;`PJDdc^=_Fiu zYLw#H{XT{vWvbS(8|v|BE-0wbDxr6(ZxQ`^B0tiSsYifGq9FhJNCOUhVM6SQ&oLm zj33;AEg%@uEeoWSpL4(^)UB|QSA6U^B=j+_k|bIvR|iAIrcl(ovsOpRj1xB*gY&BY zKCf-X)3z{BEY>5q$s=%UvG_9%;0`|vlMkJ+g~EZ zLj%FVMkz6eI>+DN&-)~o-cf}4`?$4XjOdD$>M0} zR~#?;ndo2kpbK|5YlqR~ooo~T$EZfj=k(A85LJbR8+dS+?4R8LcPtw;=L1!vIuTd; z^_9@p31GMtQhEuT>ifS96KFwj@&W%c0)vqfD&8qMMxhk&7e!AJeGw;G-OcAWZ_&3S z(fVhMtMh7C%J(_|yuCr2P>vH=_`dT7-7OUV$`70mxxm~6hcM+V0F`XB=sxr=2MrXs z$8TSI?|Vtqdh#P>&dkB7cIA+_`d=^OB`)6vuDPN;NMlt_;!-by# z9l|7R^VzpvKRX9)uou|`t0nYkk|4yj3^Vxdh>(zG6F!*7^}~wSHC7etew=B^(x0j` z2MR(#qP#SXIRhA9*{+evWD}lMxEX=vmya(ENUUOS{g{)l)nClXCPus{9Ds~^KpxVd zhaEu6d%r87kT;c~6YEH%1d8-H*{83o%~@31X5`SmhO-MrZ`O zLC~*$zVHYm6Ev8scTRnb3Wk5OjdMo)^WIhyQhUh21qTirKNuS4oZZ7q#t^V2+1^C^ zUJmE7Z=dYlv;T8a20rY95ulxkRUZ(RlUKY-%p=6O314usYiYRL*w9fbcTWA-rZ*=c9E0A7Q1O{E>xU&^U86ze zry%fwjzn(%m1}Yi|F(rTN`KqiFYob|dM4R26{=bS9;kdS%|~mim;O?a_rE7j(PEuQ zOKv{MYr6+hwa#?2!hPa~Fc9gSIitRm5(#9v-ub~^1;8VXps-vZViSm^$-tuu=yV=e zo$%0S!Cd@U?n6mPojSdxqaKtPHa^P^`x_82%X!Ievz@P&{+z9suN2w_d%pFF+ouRd ztUuW~`X|tELOAfrpg*Ouv3~|vl<2(ks*%(gM>~S1>c^45scjkV)C;m`M!?bIMf=jL zg(kK`!q>hxg2?H;eOG!HA}se7x$c zZ%V-)q#g3+geviX*}V9!?HU}LR)&;_x6U%)z=M|?uN?zuEc+XIYVzSwO^Q?K_~}2* z#xCmmnv8yJD;#A6jO$QkHqQ#5G~89rjq~cp=aM!Ehv}~5a&79z2aNqWdyy_6Hunza*;n?^=D@jwjo^-(s%K z!(Q#sJ^^!&d<+v`TPNU z#LujI)~q$(ndRudvi+F%<2E<(lgPaEF1}J2~9T#D+Mg&LpCE(+6fLKyNPC{ z7jeJGy~R~`7K&ig7^zxQ?WAt-t=<-p9ra5_U~*j9d*J%T&Xg88kWBnib{A=P)+nQ) z&kx9^!Gd((`d=g6dwcvJfd*yz%GTBnz^*>16gRv&nABPNMNGl>g^9W7)*!V($y5a=poxc1sc=a$Q zz$OEO5Ef(+YIpM3lZ8_r`SA^TTPFb=h`te_& zG*LlaGR{h%Hz#}oARNKR;)|&uYc&*c0(D`Tfw?!2(&Y}QD<5F2`bjoE>IbXqf8|~a z9ih#|*vu{aj-sZ;;GJ=#Ia-9dVrzVI*ZPR?w^FJ9R_KlUokG;I>^D94EDMzuogmZTKoh6g<}p%x+Xv<2VEU)%I9 z$l@0p8?a+k10+cI&pAw|cSk5oAj? zk0J}F-Dg&Y0XtQAOi8u{zd|UlYj4o#>P3PlYeB@TlQ-jE?WlZ-#f|cpE7bpg@(2Iw zNTugJ;*wJ1&~#8p75LflX&Hd_XFj4ffcCMH>7zq|WU@yJ(66&RaW`}qj*TzikP8Me zda1Jxlx8iQs_N(FDBPUii_q+$@9|ddIU*2tp$OwR3FyoKN^^m*7mzPZf z%S$;jZ5Q%&M3~I=$10|3UoD4zTq_6qaN*M)Rb?`%R~l!bywY zp)wVHaJ&5FpJL(X=$SS0%#OOMEyU!LxINz!a5?snPNMu#jXUx^BwcOo=M(uvS50 zmDE`(F50VW2Ff&)O$NPW#|j?emeL`RDgP5|bH$qRSN#lrwmxt0!cC&hA(w6?rM`M; zCDURoyzw9S#lmcMGkc=rf@*o4+YOh(A7(aOH}J}pK}vcdM_1>+P#Z^(o=IQ=96r+Q z{w33TsM_?OJC**c5c2z>41}bO6XcA82_Uz7962#G8hl^j2X3s7gY~HtU8)oHh^NV| z`vat|z-FZZ`(dEiY+%ZZ{pfof!%hBhb%3VSm4NhmfO225xqY1hXVH&X`5>t6()~w~ zf{RtqVcFZI^E6OfLIQM~@&WhGh66*1;;E;ceE}?EYw&U7Sj%nHS9E@BPSew#`KO#xICe>VvNnbDGM9szoHCCPTZh%& ztee({7Iz;5+uOxDLF<{R{Zc0M@QjmoYWO$m|8rP_;5Il@4*1yH@kOnOcLeCmtEc!a&U-Amit}=r@UWXJp|^ooh>LHDEqmKtzMguD|ZT#&`S?GL4;O;CT)J%!{|bm*Ds%HSlrpd?=}v4 zl8}{_3lH&kBQB$;V8F+#B$Z+}JrT(l%>@-e)?r_|+C;XQb&*zU z`=%XxC!Vz}m1*q`^dI`E_XDgd>>!?(uy8dC9k@i00Vd&xpKr?v7xEt;r;Fc(0bj@= zD7Zz?!MQ3$T5Gb6S=ylxYYe}@e|(Eu5ZCSVZuJfZjIOPZ@@i9Jhr{2&hs%>k$~tdN zoknE>`v;g;gCbPioD>FJHQ!W!)$^9%jmpmy-GZQYgp7+|vQ^{DJy+eTih@e>02uJ* z9#^X0H(zI8tTW*rSPb$)H5WL!al(j`qgEbGG)1+xP7tttJkKn#!8UgX)a&)b0J`0+ zM`Je9&a1h4Wfaj0qf@Ym z5*=k*@$Dxa|Jz?+IN&5g9nx8Vkk*GniTtrsL$IiuP6^Au>{FR`+xoYV|LynG_bbW2 z$gO`{=2g6pUA|?YH@a_P+SHMCucj8@U15D$@QXRkt)1cL7C!h;#VItcyPZBF_8>ua zzbv1dKz+dVzuAYhE!4SzMz~zmN*JDE(rcp)uyeKX)+>)7Fzz{v{#{xx=J)0*42m9E?a^!bNjW~A_|j^$4Ek_f%lf#*ez79 zq3t6VkF)}+_7Yuoj)Xt}m)5DGKKyrNOubzL9lWU2@tE6H_ie~S3Fv&an zl{0Fqj%OC6fhY2xrOIBKL~w<@jvDaCpQj0UQ*5>R2jqCFmc$f!ROiBmLCod{c%>y0 z)W}1J?9-ngW(qL*vX9+)dw#lY#GNFp&`&Rh#?P%C3m$PU<|@VTo;GtObr*|Qwns2^ zIM6842G&Q?VDdGI|7DoJgC1o5nPG8zHNlPqLdJoh9D8s*ZJXUuv&C3Hd0!z8L0Lq9}OSg8ncS`a^Uw96U-0m;{811jmGWUV*0BJLa?yeuBn09MzqdwS;Z_h6iZ;=J#6Vebm z{+?K~J}8tE_d?Qz0ek52wmT0Cy;J6@>!PGLam^$sJ)lCOVyuwOQ|*D3bAbx(&jVYy zXMaS!kBWiw5ERQ5X9j0(xDsfACGjr85O^j#pu6iYGce^zexU#)?P3Ub{49dERR0M< zmJyB~zc@&}`^}yx_3t0dE8@!>N2w53yyHa$B`pYn?sYh>=U^(~fnYsm zdXFV?Ul=_2FTh4gF?^tJ1AHRp{}KB>lpZ1r1OY&W(13|SuyAOzYdvI2|E@^ z%3*Pvi-UKO)GZMiET`Lz^2kjs+IVA7?2nfd?B=ML_;3X1AOHywM1p=XH%R6R!oL(d z9^KbxUM#pL2-N6a5cVvOa^ySB?$pSUm@a~1U&xEk{X-+8Q2D{sw$KY(!bwJH`VWle zHzglZTAez#^(Yu{S3kpe?A_=1Pie3L>8v&uukE{g02?0#@erXCUsVnYsFbkH(UzMn zrOLT+6idg{=}xvX0><+k^>la8< zMR0>dxa7{@uTkG#mNS1jLMs&d))^Gt9_axCEr;QtN~}bVw-{;fx^2qV1IsdQmD!DC z)k6b4Le6*%;oI1;IQ5_Z5<4z5qxq-Hsdg?|IRd^7E){7QWg7hyJ^|+r@PpOGR&GJa zL~2JCyf(kDv!{ zZt0rb^_>GzU`RI}*+QW$OG^|6yd-g;*1a`E3+${|q&x5iSUl=wYQ71I+;@5Bp3Qdb zM)nc-1N&1ZZH`OO${Rg9gNZyG36Q|@W3?ju{-C3sW4f^m3rb{aw2U*0uWLMI5-cha z#2pAM9s~On8H?r|s(7KBevq|b#y^;AW=Spz-#1 z8$kb}E{hDen6zYYW#3K0Tl&EWRarJZpI(;2&9;&}00ShXWdtgnnk=F=^83VnLb@Aa zO&IB~ZT3FMNWJayD}(CbGTh0T#t;(iCrLFqsr9qJr2n6Mz-=*tJ#;0X$fr0L9KKF* zFs0hwLcRD0K4cGkxQtRg0BW9t^I8RUb3PE3(Jl(5)>{u+Pjk(lmI9x1NF)9%r=ed@ zC-8)jiI@^C+qL|Ysn;H^Kq3}Sq)+f4LXqLYcxzTJwVp1_gpD)&v}cF!bf7&9PaRav zJ9ML=l^Bj<%LPvnk5)Q@zCaQeX$jHoFhSpl6AMuGUb%#9QutP4tLOWJF2=7sEN%k$ zH)7&k%*Zq60wYY&MLqjG@nN*Ybq11_G==8L<6RVqcYr>O*6cTNTBLln@g~!$BTa5o zjV`F;iviVX>CqM*rZ!`6%ead=Kt`J>YlkbgX*pF42jj(lPG<4!`l!A^y(MIjx@ zv1$8FPC%ofY8SGo+}VCn=^)dmbnFNXscpmo|o zg5sPrY3_{$*DXekS*%)6B?7hRf@qf1B!k;Rp;qPv^t6i+aM2}j)_#iBw~X$agjAcv zdDDW{a0*U40&WiB^1{Ivd<8;U7ZFgM(jdWq$5-V6F_M(c=Zfi@yW9ih&u)y5;lf{9??uIt3I7Lb&8O*BdadgcZpq#5C6vso3~p!< z@Ogj@2?D1Vf$w)fw;4b}7r5jY&L4Rcp_xuy7-zWqYZ*RsUte{(`_LEh`>9t&O@BX00d7&%RSi*Lpd{JK)5cSB>_Us1)rI5OX z;!dZb4qxN7q!1UXMq^cZ0tvWRsPo(mJdJ5tBuTS*45wlf$B(P&e%k{aK8J;rhWA$y z%ENQEP;>r+L5j`K`2AHy0JP>9+sgGgi0-ovWNLWe%sa&JH0j-eiqXzU!x1T1JKnzg z{iK{Zb;dF(F2zP{k~$tD`u^7&9r=C<9O{3(djEJJ6SbTU9!>oN_?;k3Oqkrn*2>NV4n{(RQh*Ne{Y&R;p zGC}QidX-{UT`URK$2m6o!VY%8K83@j-Gg_@k`F+EI;*}wMkvroxuaCZaIXU6W%Al8 z7Xh>vWP(pUoq3UMn4_kZqIJ*xc0M=WV0;4_WNL255{MlQ8aOMlAAd%=5r5RgX_DS$ zj=n9cvuuN(Hr9Xv_ndl@2VE^NJ$F`S?LMeKd>Q%;^rb-_B z_%nPegauiiAeMiRo7Rm5nB!piaa8d6^<=7{XFPsa)mW??{5yq5TEI!i(JTIsH5BP4 z-@YlAlg%z9t#A~LZ9P*O{AqCil<}FH3{K^pN!s-0!K)}s->@9PFF!UVqvp*?%pAOK z4d7W>@dz+_xgU zdX$Sc@K;3BjW}$JQj(AW5MIH*p^FRtnVO`+Fj?S#x5~qdP6Vhky0Vz_R*dn3kK=>yJ z`Ih>KoX1_FRqTcXi&2o_J^1GsVE)6l!VOOte3WjBZW8X2cni>lg?asjQ`Si<%CSH5 zy*DR=aHxLpmoys()UQruhoe06G|(j(ajGBp(#_(c9XfYR@;#2&=*`VNAqJ<|Sjrlx zwd>*ov~Ogb#FM${#*{B`td~*{LizGw;T<3Mdye)L@q_Ej#|NAP7QmzRvQfey#NUKj z#Ilz?j)#m@*&<7%bW3`_tD{^!C*erc;y#U&z5!h@Pz2QTuLnvC21zwLi>oWgp)4Z5Yy zLTrLdB?zP`2J#RGnQ+;|b;V7CqaO$XEDUw^rS z9SeXB{6$DfCI zeMr>X+bz+-EII)_J8&k^e%^!)LeUoxw37f05p!Bv=b?y?) zFnv1ihHBg($xTy=mQ2W?f8wB&!IBlRf^@tI*-}(;@B43_pYq>dVwoSeDh&T6(f@X$ zh0-U5k&QH)$RzsIlpeItBS=E`u^y~9WE3pUuCNfz4Y7pKG8w}e(By(z8#KwfMT8akCL!{&3Eb>j z3+&_Xez0p(U^0y-M$KQHkKb`2*Mt8!ZufcJ4v$;SolYaKErY+($$dKhG-+vbvV7m= z8Q~W`Ii|c_peSwgmq`En?BnlymD)z(Mo)0=8nDVe;p&&ri*pb*2H-MwVcp;#40iC7 zuqz1r%`f5UQJNbNR<2@9-|)6c>Byx0K@w?qh)1m55jz-MvaE()?t>56Ha-&V-KX)f zl6hQiLOe)*TsQD3Sh}qsh4a#WU73aU@XXR=*u3}O zMas?4xy>K2-w9KlFdvzDQ;y!j%`RTR{o74h5~VjzJNXrAYv#{fd(MwHsD(LyNDiE;!F2wS+Jld~Yl7kAGWOVU?G9X%={;i1IGj z4@ojYc}_{$&+pG7TtnJs2GJY^V}wq}r{4Ln- zwaLRm6aC7whdF|1P2)Gzy-S;Wj@!tx8*A$tm?kH=>$B2~iC;4%F!OQWU`Y7>lIMTb z?3c3<;gs7Zq@BBUxb7Ls`5TCDCUBs9nhUP@@r+WG3`Bld16;uEAR2ZZon|xSd1>hb zWGYoIwj6GI_zwA?<@AS<4Rh>ysQwSk5+jgHn_r(d=;(0wZH4f8-4>nFHy$1b@$Bs* ze_{!NF$@^_hS1_{GJ%*PFV$Z>H<-z$_X8Ginf9)#eI4+K$@_gAD2H*WsH2Y!% zTbzZeh)Cy@rkZNzHuRT3|NG>9_siJY!x6@#3(3RRaSvng*Yyr3;cC%475qbCTa$qx z(M76A$P>;JT41C|Xj9nGKQwO+9KV5x;ej%@TwN7s=U?;g#ot@W73v>^64!y{?Ve;k8~)$@bufE=3PvL zp5Lh!Eydnz=&a$7=lesq0i;&b2kJa9LYTg%-)o3orZD$@#FlcHcK@Sb>C~Aws>SsY z`}dP?Kwt32o4S*Urg9$J2yUEstF8(m?@tTY#6li@TG6kl6#LmcnL5@G?v1Y&DAYlo zeZSI3coPKi)jS!_x8p~gGy$(tVho}K%9FJ7;h~Hrfu}i>;A46BAaGkIpj=Aa zig`&GgO8bZxP`RIEP+t9!%aRaow3zk<#tR|-+`2f;F27_MhQx!WK+$X%n0+M`;CK{`^TQqPD%S>CLVa_tRSe9;!4>vznn3hLe@s( zaV_>hG9NpgQDF|Pkw4+z24wyz5YWanFIVAc7QRd0y#-{d=DbN_s7`5}?M~^7>9+0S z@`SpO44XtILW*pKOqcg^gkGl}^L?%~zAN4pw)#sa{TG)Lwh9&7x(k50ZAe86QEVj5 zId1^=AtasY9zGN^3t=w;IKvJ>2_Sv8c=+5TNh9y^Ly-wVTzR(6v=!ar!dc9i$n~18 z3jYn1=d2ifP**UnAf)2$2aKxty|-fP?Z4o?s`JU}KEiBRQ9}2*jHTOy7S0T}_QBlU z>PvJ8+lYN(!g6IRwva~lq6xFxTc{51D@UUC&ww}~_^_K7EQ#gCPd?+sj9xxt)Xj`=3&dFLkNWuIMDB1!$FHeKYJlJCGNTUfBZzpG=-zM|7tb-H{Uy)-|5@~l zeV5ENf0pr*#u^d!+7dxtg{qPDz;-hDrV*{h3y3R&G^PV{k8nM2=6=`w-o_IlA-95S zcYfnOkKTChWEvW%){<*n4hb*sMa%Rwk^g6MP|?7SeDY2RusX?hu@nLnlu{gQQO3=K zDnpS50^oN}ksE-qOVE4+C?E{H{;GupZl$nfN#&c*ZR7m~x-Xg*TK_D(1~G}8_k2X}djOWBY5eL%s<8k^pLYCcL%^nRrpPuSor zThH_t(b4_Mwc&X9^dyL<>%QPIxsAXAaK=bZ`YI)Y{F@e8Wap_FW^Dx!Pn-6{UWKZh zepxpEr*Ack_!WYRlMVqS?Jf;BhUp%o)2Un=Tn_swDWI_JX9CqDfiFQ?Xe=q>^g0%I zj0rsfQE!;qa{IzL;cUJ1km=jJ-V=00SW7aN3Ow>%ECE?u$8LZpL>zI%rqEm@ zrUzmImv%?}$K`oP3I{YxetLhY%TT_+4rN+IsD`wA$`({F)QJ`jFK*1s7$op6vzNN0 z{)ka>nlue6S>~-$y5{WE(gfe}smwjkGYZQmH^^T!&z1wUHmzd%b#4KAR z@N-#EeCw~6L*Oq_y`gN-Zhp4G-D4Ni{H`}z`By=G{}h2Zx2#Mxu~XNvXzx`u{)S`Y z>#yaFwHO{;*VFC{?o^?FJLB!Ya8iDjr4+Vnw73c16#_{f2EwUU$H0d_N@&mGfSiv- zXcOdr-ZlV>3|Vl{mv)GjB)V6Ihun&K}i$>=6}_$R!mLL2G9Lwg|Yf)i!y zsc^;tqgJl>^hsDeuf~_a;ya`MJz03z(EEo^bKa3treQzL2J-1}=9C7{5vmcsSX|c5 zOOls9yU8y@Mf%O(TMtMIQvyd~4W88((bzwxp-m68uM+HLshYA7&}XHS{T#%ES%00slLZ(-e;or6p-Oa^P_jyw3^0hY z4DGDT5D~H7h_x1r)kJ|pEqr;&Opi!5hOBLlqqQzzEtO(grOnKlCzQK{79Gt>dkyZN zUm;m$g0;DoWEegcXEv14Vb}(6*=f1GBuyBZ!&Xk4=ycSsy@}m5+PNvK%6T`#n6FUP zx3-I>^|zf||3M9?3{V_@%m5BU$TuQL`s&ddvcctB2n!WJ{XMczJFG*`F8mNEPvjyT zI07l2nK_?FtWt~KI?;E*&HeClHa^dxNQArX!8b4NKu2`@9LI}+A&%cM+i%S`iITBCI8mu!`$25E=U9#H{HGQtg!Y~bN(aq zx738k)wp&Tu!(S=HYS(67NEP|0zvBet^bijGZbk z-pZA0(0*Jk;_1~5!g_Zx&^(w4ti2HU)`4!VJ?cPJi$G;B@TU(Ldh_Q;0GdCDf|egK zVL<=exNX6TU5g{%x3OW9)P8kV56R4jQ75R;${Amx=+ScSkPXU~N=Wq}jXzqQH|)Uz zD6|*I+X0#ezzH*mxhCmwSKve>zPsO%?$se(tKHg5@6|TO-qJ@&G=+*q5na@<|BM)6 zf&Qn(YH>rqGj^@eAiQ~T6r#>EbUHJkh{58`)?xtQ3O;q-KwCHLX_Xp}gOfQ0sUFtP z2`$tbw)?jU<{hT&Lbc2nlz-)vbuZ~G+NW#}WQ$V3~&B9tm zqM-l0K0xI0``5zA#0DdNt5_AaqDsPM8u_4j9$Jx!%)*strZgjmEU7ro)n9&=+yCSC z%(?(Y|6!z?B{Q#z2%wd?&8p@I80ZJ}Bmy^epxg}5i^L2@t5ZMH5cA*>(W6+8-^zW0 z^SS{Mn7>sZrMRI+T_Rv5`lEQYnhVrL$+@eqch?fpvfAC@Dzfa$MWzT&;;y-|&Eso#9T@RvV z`QmVo22H^%u@(J;R$4ajIR{PadEdm&!qh_$B?tUo3Gy05lFaDwu>kho>#Y3-xO-P^ z7T1!i3nG?cgS0C?oR&ZN`PuI}ji#XIu-mEOtjMX~=e zjZSNTY0x~9J4j;=`?q7-|GUUInY`t2dubxx4Xy;@Gl&O*(EURY{CM|$fKAIw+<9oZ zYl|rbp#Y(m=J#p7HbHc2%%pvv2Ukt-TjxSVa`o9ui}gGnVlt~{XkZ7!h`!d%u9uON zesb<18726Mh$HEI{Y5z8v$ReS;g>v2OBnE_#}GM4F@--X$kK5$l|7Ve^6RkO@8d(> z;YYx`I@oOvI&TdE5uw1J4MJO#>ft zwe@J@e*%E1TPw~V z4##J0u(E5*!_LOcQ@45W_`Hb;*OCMXD&qyeOx4LGu%%CN0Bn((6hq# zV8g6XLn&S@`)c1H@}V^CH>znt8{dBMc>0wF;@ESt0Fd;JuGmgcrA%S|BVxNY;VeSS zQ5ID-g4V#uo6Yg~e_F2!%ce zIL-f;SpS>qbpF_`bXHB*IgYjAg;5^}#HbCm!dGsGFW#G> zTM6nUiYkfH!!G?SjOTs5Gs`|K5h#MtOsPcp2^vRcJnz~1;zJ0$+}41+hg`VmJJ@)4 zV7L-I=NPEzmIf3tj=y&!OJ$yB9H8a01Iv!SF7#l+Ji?9;(vRh789kV%Z!MDTR2ymM zc#(#>XGN)1j+WX59Et)%W4KL+>~FB=wJR;mBa>36s5Ho*2i0F245#TVV6z1|eOw&9 z%bK59%ze$bbo`YRD0de#CgID?V*$b~Gczw#?YHMNum#+t5f>Kr_6L|C%>Jaf9^&gd z#{W!V>36sgF0Df|fu!X`;F8eq7<8QWzm~>yk+3w-3)a=0X>#z{4v*eSp8v+)CTS<$ z&fc_I2oDCuT$zxxeGLi6-FG+tPApOOVdjvf>|+JfA`)$vW|^!lp$ddP{Q585<4F1c ztMOO8BTC(;@HZ!z?ID=yv4{;L*b@tI&8a~0E4*RtcDPM6^8}nC*ozA9(RVvc!1 zADT?VQwd$vw6)$ketUvh+0@Hf9fx|SE%J|Kxc>w~Y9?N3GfCn-y6*#MxD%2Y2RHj} z7xBen3}=XT1t@3*y6N0M#m^Et38Dvm<95*a4y!xrs;c3IwyC`B{@#y9>f0-*wG)p# zg`tXhP<9qvR5?<|At(;cHwk_gH-exy9eCFBqaCEHMa*aOhyT>p!^2zYJ$aZUo?1>f zbFj5liToaSi-T=4Zrc)Bfdp#H^L+00bi@jF**vfBDbiRes!t3;fd|kK0yp0ZZiXB3 z2gV}61*GYOPa-2D05Rg5iWIo1d*MI=o?p(bLxIh3IVf7z{6ovGWAd3x|Gd?b=y|9# zyGK zU_W$<7)lb{Qw~j6IOSyq}9)PymL#Anw|N#_zh8U+~e`Nr*ILbt$pDP)e7@KGoEmGaQ18DhQ z^K}WN8~^mR>spG?a89~rB#^^^mB-p0-_0oIWa9Uyx^?EzP9nq#+ILL!a{e&>jeX+& z)f1Yi@)wBkewbA{dkrg^&N%+33F4H-AzoCwcTu!AdXb^y0Rz_e$ZN3T713a`G*M0P zZEV)SZ_KDIO|P|d&tl)}h-rtu^l|)Z2k~MA&cP(yQ$D}TP8dR3ux(`K;A(STizDP6 z+433&979&rD{&+yjib2tMHvWMfUTfd^sK!ZbXIu3p)31*a|r`pTsYwD7aP*K)~v9^ zulj7yoK_L*i!}k`Un~5MWMt`+Ak>QQvx_Q(C*e^z(t4to+G}%yjrg#IQkq!y0=wg<|;}oy7LJp()nWLcH!J189`nOcc8PMDH z1`rm^lZ<^+?S?OCS}3YodRA{Kp;c_86GPL9>oeZGSCJ`yTx3lyO>U*q20r_W)(%s* zvlkn@&4dMXlI>wQE}~?ZTiE;pYN;^uG}Kg5Hyzhg9oV{vW*lW(^gmsH_`1I->T zFh=kr%#K#UFE-(ZAZaVuT%3vF zXbik!@J&BR4PDJC!Vwo>Cj8PQ%|*9ip? zB(xtzjRl^v`XvSiIL#hi@Io{V28`E3Y;Nt3G7i$UjI?3T>N~=m#vQ3OJ1jV?p1i|* z5?(9G!KvwpISB9BtnAG_^{5h53gzjAAU&@7T=cA=8E3TW@#4!~5>(u= z)-S_j9mm&pM?rR>9r^iP&n$!Z5}AT@jly+B-RGQrmYo7c&abq4qm#iA>6*5*bvvIE zUtO{3{d#Az?mx;cUe0PPcjUTPp{;Sl=l&^!w<1?|;D;S#?I}>F`ygTCm)w@5B;jdb z$?yK<<=?u61rTl+Tal7dqF?xYt2>=Mo9tm86dE%kTyf4W(qP>S2o{<2u?{sw0q@8r z_BBqms_GxEC>7yzQswig!~h|ZwhoC1zkpfFq380Fei2&z3X=?+#XwV(It3X1)47Ob zmC}B^+4Y#vjJL*Bq*Vy{oZe3_X=K!ICM$a9bz0PO$D&gEf5aZybP88$7Q`#?qvgv8 z&Jn}+(B%KJ3G7^1NBCmi+W&o+JvvinKTxXcq{n0MwvJp1%b40MRhjutOuBOLBPzE~ zg{_C4!dtbsT3PH(I2`cauqs_#Bj2EMrA}t@O&rF#-C|NhMjo`rwPkf3pIsUS%`D9g z_z3aOOeJwv%rnUk&H~&sGASR;D6DwqG@}<2ve8doo1Jcrsk|lFyKdo=WBdND!3w>q zr>oz0F34F|;ObNO`t@R2*?XzRhtT(Y-Sf#_*grDK^Rfk+i$2WevdwuK1$lkY-4I)>6iC$%pP@G7AWzHpi$y1TlsHhrhDe=T=={a>^ zx*io`DW8`WMI@t*is^zZq_q5ubI%7(4LYIIs+eg1&FpEL5oeIMj!*eUPm|IS*3U4L zPlLAK=gf%Am*i< z0hQ-zeQO8406A^K^%-5ttH7%JU)$I(&&{QrM7PAh#mZ9dH*kl$>k_ozqi6s8$xZvZ zveLZOmVyG-s%9W;Ee*f$z`K{nEaPeX8r`Z@7**2Ju5amQzo<4I({u~TWV9fnOd?`C z5@RtNlQU;BUXdm%Rh<;de4UD2{8dkphXEaYzL^jz`*DT8 zGy$p;b4yd?&qq|{%Oi!*?D0o~;k0Dl^GC`fgWbKMk=A(jZgdLRV5A(&am092>*`z> zFl7Q_aHU`eIRB>kL$f2-%NOB_gm}R;2m^(fn?rOoObiQP>hC*Lk-Cu)GJ@~QN)RmM zD!=hix+jB-l#v1oTi}0zW{=%xw_Ue;9;J{pza-pmFGf)x1oG@ANE;UxZbOVozUppy z<#RMKP>ixg@1)5+RQkP7a+mDB_!!mi%=9=OgHavkQwh@cKm(I~ckJXeXvRP4wV#xv zCu-LPeSZAg2^;B94gNoEREKdH!l&W+prkV&#Qn8E*ym#O(G~l~4Yc(%oVyoLV;OQ^ zA7qQq{pX8Rb1)DB7a$$4ExMk0jhpTIiQ~~nsiGM^N{swVM-O-%PRcXjAMyN6XpX{o zRwpQV5*P{tr}%)pvkCgM5LcGKgBP&-7}bagkSC4hV30p`29>)}O-8WIxI%45yuRz* z{!}$BJyIs9>Z^z6rsLDhIt>C0czub8q3Rx$9R7f`joiC;kB<+XyBHR~*RCd|OUGc1 zB@YI?rlZFjK2LmG9-f&TYpb>4;os!$} zE5{pJ$j%sN&o}J(??J*Sh5<0pMDDe6%01D|#cuQPBkG?nRTfjK(joX1YD3>-SqUPg z7%b@M>`2u^Ua{A-N3XZ>tdRUtlw08!WruFOWNv1@I$=zwNE5?=Rl`-OI`ZP|8kRk1LhUH!VBMdW%|*u`@lcV59ZBd-g9@$83klXJjj`LVWb01{WS=2pzSjzH z0W5N3&<89g0*nn-y`-A@Uk-PoYXL2l&dOq}nVBlc6me^yHhm? zK^VQeisyrTOYA~Hfe`jCDr>J}<~^V|DPGz*)YGZRud(-SA1ln<{-{Y?stJ^pT2q+oOckCO&LCdvQ@`M4eQ7ezjAq-PGn{yB+JVSFhPx8aPm^9rBJ`t*=DK8O zT#}Q94e#e|?%RX~Lhtdy8sXvJX(rIN#P+vi>Eb^is#QJ6f|py86@EKh9tTi#XncUd z&c#Cb`8a;giOX|IvkEdcuk?;Eg1C*ZGmVjkkySr;M ztpx+vU94Ul2_hKe&+O5BjUrCylHtuTLXKJ=g_9$uGdPN+e^6^we$Ba64vk4?sOA{V z^;zeIMTRG2*5{=yvix-G?yG+#?G3bSD zE9(;K;G{ZKE$sM){}X2x)*KD`AdOpm#X=sw#=?hB**_=$avvy$4vzb$GL|wsC3{oZ z2TTZ6C=hgfRr@ zM`H=d1OV*7DC^FIfIeokpWxfWlEv2+47*&;tE=kDog0!V1;Z2g%y_F2g=iv;hw>d-t@9g`Uqb6i z!{=nmac{+o{b7dkD6Oj02Nb8Rjq}!+`Pgl7=_;+KrnRKj&HKIy40S52jMGHSt9I*G zIobwH7U{ZwPjDuEyxU{t*ts|<9{bxFJpWy#rgja>-zFu2m)arKS5&(Jz?wUdMPK67 zkqb8pJVydW(1BUI$Ppa3I8%CYBEZ;ms4Q8A7fDxU*dLq5&M%Eo^WVQ|E5UBIjqEd|6%N0}!IvSh^m zfEx27ZaJTNR}SMKgDA%zu@+qf!caO8LQwK@(02Jh9E>A!d%h<%l?Dx%U{oDU(|&${j_)v zi@}&DWSEHvbt^>|=7r%}3(ycS7Jenyv3UU0O|=748x)cLnEufuS$A+{@nm%~;79m_ zRd7rIsDXP52y-d;WE(pwrcfEG>rTs?RiAGGDb*(L0B(#kYw4{AiMP=I>7FD?{MI(h zp`h`bg7hKpwZ}I%(my*A2h&ENka|bTEj?`?7_g4NEN=Png!?6~GfaG6`~H5t!o%-9 zt*qd?w%vxMbc0E#A`B0!*eR1e_1C_$e(GjT{r6uf-}!7b8KK7s-nZ|Qze8PA8sfV# zj7d!cNsEoeC3Ol);y@8gqsY2Or>QjlA+D$c~hrT+g&I}5I=zOQYw&!Ib{LsA+k0ZC~jB%~Ci zQ3OQ^K@g<7ySux)ySux)yW!bC$Dj8D@P2_a&baQm=30BLd(K(+EI97PfiZR%@wX=? z)<;`RbV#qvY(hA2cFP|dO5D^(AJvOi>4-FcNPO`vtQ_c4&r5}tF{R7Kf3AfTx+6n+ z>r18x_O2L;KXnAZQG7?%Up2?0uWK)p=^usxGJO*n!Yw^wsxtM4Xw}07AGU$Lh${Vp z{7gB?R(LzS&Ktb05m>{O`J_fS|L4$a*=BNOvh#L!uX0#UT9`+u!GyW2n1Tst!{P1t zM1#uQNsOrRVpsjuX_p(#l53{tw`~7HEV;1%Y%v?&{xp9?CF%d!VhE_dI1|gwYLt$) z4G7m8V^xaHxqng-zQ;h_(3wWTgh zjquCMzCNmNwvv&dVFG5NaP=c{T}1R3jh8ptD+XNFj%hX?l+>oW^%~+(*#khNo{A|+ zgp<>=|1A1#@J%R*QI3O1Jr@KXQrCg}l8e6^=Itn1*eQuUIQ5O5*NL|u|M(Q*>>Hs2 zADw3rg8*TsYhYg0Q8WEX?G01Xv4X3_^>8d0O>F3rxv=+Ci~ggDz#yhqYC-_6aC&vNL3q{IY}8^#}rp#9>_rg)c6(8|MKv>UCp zJo_R&o1-oOHg0wmgo<@GmV%Yv3(m;~oiS;t^T=F!LqsdCvvv-;Gj?sesAgT$c{M&8 zC&UXyJ{2Q0+gxuKTAi*{xw{Ds9beVydR%JnOcaz$8u}Th`^j<3e(!Bn)SDR!SeYN8 zRDJoxIDOpkynUL)Jr=eQ=3>cwqb27Y+TDSf2iW2}puZL3LbN6{#GI?2#MmU5j6G*B zKPJ>sny-n?emtgEvP?I;w#V4theNRugrc_Q{a*pu@&+BxSfV!*+z0-a!Cy>8eK;Tc zN^zE*{0|ORZg#4yXTcF!U0vI2UH$LS{Zf=f-;ixp1-UXuzN1Q%OLRY)cRwlzYtd_U zh;&HU`L+9|4hT?IJc=X_>DriQ z=H#B)ip|85PCAbI8yo|Ba)dumB>EVpqvNr%56Lub5s*8_VxZs#bMF8?$O*m*C36Pa zUkYRvKr9rVyd_|i20|rP zs;a4t8P|Gh9S&3dzlrF7JLsru5IN!&-M*S!v@Kg<&F{)% z58n7YjfTzQENz9``bSA!r_hGUgLxVDm&!1D%lIE_$!~v;?w{)1eDoT*ZMjL8v@Jsu z$B+gZq4!SEn;{gh3v|bC&S8*&5@^B|#L?s$cOUIUa-8kKhcuio&q1m)0~dYlJr7o^ zMaHS#^7nLm(-_u)jBf?Jh=UX^ zS&}i$8z9RirGvH}9rfD5g`@am0l}1^rV34QCl~VwBeY9qB!i$n_G}$n?mBz}rPr>h z$#MC=nRSD&NcKLfy?R3*11Zv7(+8)?KLkE2Ejjw#oRIzH+t{UDA{&uBCe9_FKSdn$&Xn*Py$RBP z+>s>sbTOPGnUQfzP5Kw#N@hn)stB6dRdUXq737M)C)Y1cDeB{PG(D=Xg~SUk8i4&QVpU18)GO)&-?a|S zXl(QL{to)ch^$h{{arAfWO~6AG%9cGs#KC26IHvweGC&8b+7=XJ+^+w%>qbH&tgSI&1nQy#Y z!XEJ~YBxvP+CrT)B1D_M`9pPZ3IdgF!MYDC4DR%xy*YfHVx_u+6JC8W{mE=yZ09S} z<(NAb40QkP&HXf@N-{;yuHMy6RhE;@i=J{4)3>ptaCi+Y#nFLGfbu69+R>Iz-Li9k zb+!W@UR%lkZjZw7xr#oTwZadJ`OmAEnd;xTyz+JFU#*X(=sH}C-^8%mC3D{G`CWh<$UoL4E18mNOF(Sq=StN$tF%#=q5(41aP**8T>4Gn({A&kcRK zf`1}(n5EOYIVB?W#Q1z1##t3TFS?yui@4@L1T3UtPM4y_#Uc!a1IG_QP$RH^0MsAA zQ7(w=)&f@uH$uhrr>+@u_|}V^?fZhL%A1?3O3Gch9dnd$d9}UoLdQX>Mpqk^J;l9W zN+x*UGRZE|P*XtZLd&xRd;>IHF<_W4nPH&v^lS+o2Y*X}MLXOQ%|2T8m*q}#)vo+} zYt6+`6fElCSo@HIavEQ=`eZ46&=e*=i->w(zUG*lS zdj?-w0kruJGFE~#u?A@`#TXoddPgIa1*0eGtYU03FH;Qha2RumxEp+Fcym(&y--?u>y0u0IU}@@Q z@4-M2=cmgQypET1;M9rFxFqln?74e)a(AdRBt!2hKqi==d!|CTP+4wCITSPk8bB>DwyLI|5m?s&M6xfBE{t2 z0+)7SaxG(<<&GFNHhEfiLh8MT3<0rNOf@1o zb!5CJ8mLTv_B>u1_4)@6AisJ0M4*pxdbTtA$~mA7|8^5SY?|z>AAProws!~NxE#f! z0w^nnx)cM6{cwkAz`4{V<}k!Ko5ZNj)x&xHmTC(#QG;QrjmQzwVO_?)haz_fRi9cEw+tOw(0p=kU#d{ zF6H(o@bG7Jv&+9YB@l6W7{(b?=-jds-T(MZ{Ur@YVX8uJ&XW9ndigK^IgYD*$a0r{ zzyxvs;l%m3f{$9zUYi0e@Q)B<8~M%NL^P^mU9kk`f3l^F%M!#>eInM!q&n9;K$O!^ z${L;44kW~<1O9;!*D0jz3CyN81ov#%Q0W@_DzT|@sJFxqyHUO;iPytRygME$Bi zsWsZ6X6(z4naoO8-Fd-pd|rnfa{b@!U5N2+3_H#$H;zM{zdbLei}lOxg2g>VNgiNm zx3xtIO4_LQ^ zfp40CJW`0JDM9NA!!4~oPuz&aKxuWwh3SdBzyHpwA5l|fA%Y;&*Rv|9pYsjsopR%M z9mOKlkRG5v29Jo)reDZ%S~nOx1AC=9+Fl9d^l#q>+G)+_-uxM&wAb~PGZ9oi{a9xO zx3LrQ0G_90mq`!?oQG9^Q~pg@N+qoqqn;6y2+cs9FyXHD?D_AT>~}coi=V4GIsa~B zs*1vxoyL-$y``#^f6+K+wZ=*_WYz4CVERm<`5jR}Uqt9PxMj+ohZ-L?_x5w*bR*fx zI9GBap5Ogf3UBWWoq3%QThsM>+=J{HE+`oePoBv1F{91~Z^+f3!3T6B4W1$n`@n^z zz@|2!@1X8tMuUec#@ydwGM?1{`8lAcj(k9ggIp%3r1IjYc(qkK5s(z+0nS=l|9%-= zQ-llxT^*1pPZkPYi~Czr_90nIQ|yB$v&;_qltu5(rd`UKPc#fPrS>wacu_{pI%ALe zb}P@L1UIQVbqLWP27)r%H)T~`1rDkR8|-AyUbt7Kd+wXZuoL~p-kobucOykX{BmEu z|4TIpG>qtAaGI3P>0d_mBika1W%^_#nv-``ByY&sw<6U?M6KMlYW1+nq#OjDOq9B| zuw}TabRBZ@@2zrFODX%k0Zj4WpX^n$A)PsMrV@N9OqSZiM?0yejBQhSBGAX{t%TYx ziQO@MkD5;S;|k>cX|%Z`Nc2aKb-4ICIFEQ>0xceS5p|G07NH!S%1Vecz3FzUiY~I0 zCu&bTw%uP!f5#&6`!k~)1H8&65GfBavFi7qiR?B>!k@1@wkEAOFG!?ldg1MClnR6~ zs*b^XgItrU6zVLT58H1b+SI?jgjHlpTID7)aQ^@~em|YMV8L}Sb~eC$`p&7_);FN? z^LWn#*?X#EjHCk92qvh_?2O+oh*U|>($vq`1>E()UPupjo_m;|+q%B#y!ZZj#$?!# z%BmpEb-p(m6Nd0is^^IM4W(_ca~LhNw;XMQ&s2$tHJw3(%oJDcxicO;C8zpgIT?TR zVbxplueDYT_7YDW@%%UuY-X&Mzq;}Yr9B}BuDb(2wgfTn0(B}2aV`=lv7If3j)=F5 z`zROCWCL4V%5e9;S!^H+)`>V#$O?06Gr<+V4J=w58RIR(@H%W)0jPfK zBz%DtiFFP6LESb(5cpmrrT^HAFPc}Zf9-vw&0oH%MX~YeTT~EgsNYQSR7%|2C=G@o z2j=KfS?Vav&Ub5Jgdg<7A;~kx|m8ed2ezHTWQ3J)h$Cbj<8yK`n|22I^_my z@VLdzz|kzQqh+nAsv0;W=uJP3{G%=E3#gtsg6QO$j?}f-`uS{-w{PjdJVa*Z3gnVQT zT*^K$Q3C`cZkhFc&EO1zPSKtG+?R5!=E(5DO;Du9sAO@TgM32d;*?7f`ijj>+s`Fy zX$2OfV+Quz%iOP50r6g9eK?thB_qg9w^*4rgXUeN$1y+vdn3`J$T+M&8fvXb#2WRM z`aaXl+vPTGA-s5xzALBTX~;7feChjrbWj@ppBWrv{!Xq<+grVkurE)9c;=%E!=Ecv zj!jh5{pd)zfPv!V&MRnQ^azv(!{R+CkT=EWeBm4UGWWqF%4+2l8nz8O!po8)_K{RG zix-AeCXM`I;pTB+oS{v_n zI5eShF|#~UZ>0H;@6}<;b@4}uUz~I4~-FYhQMD1UvJBD|VTu^APBmhWB0pCuv~1Btd)^ zA$cLtGCd#ZGAw`CC59Ao2UpzCCM0|0mng6qD6!SLYaA+U-L_lmRJ&*{PT;8-^Wk8h z`#fj?tDtxf8WW;EI|gYMs`m$Sy`Y1n$sItoeuqdRQN+t<+3z4O3hiAT^ypa^@nDBv?{{V|cVYG^{?8*tk;Vu3*CSXY}0>AGX*65B5lOTFL9~o&M-&$_-LR&$+yIR?|r`$!7t8-;u1AhrA8(H3!ePObv+0TzjE0*?#pI-#u*lU6%Yc7y{nq=^@tHQ3Rsx zZ0T5mP-9$%+fkTsDYAoZv+e!w2YEjCCv-J^=MB2yqxH|GW z;S_}b<@ixe1=4t7%zrsv!(LIro2=PeY*=Sy)aB#?vEAJk{^X8yk@cJFnA&y-YJ~k{ zID&>2jOXMnpQNI|U!Du^J^iTHx+yU`Ss1c=qAvVseRuC*;e7^Kz7E_y_5S{`@+a9Z zMD{quBJNtyV;Qz)Mx-VK;b98yq7kxTv>>oAa05LN@`l|-{JxF$i(Aw5nctzfca6P1 z>z6A9?WujAsErdO+#W|=qW>xg&ku$qR(7i(iR)*ui_@^z3&?H>@N;>Pc3?gR$Y9Ry z1tvuA-vnaiy;+2^nl@R_BmdZ&`Os)u2QOEcaR|KPZ@yplr|W+nD2*}!%Ja~27?wTU z-StXADg{XV$ukw}JX>L8I!sGr?Wemjmu?CJWhk{Ozl;?Z#TY+K#SY^7E9jbs zF&$wSsAc~~y}|@weKyB_o=V)hNs(QM9(p`JI20}QplC_8{VwOnSgnFGD32;pzVv!m zO8URbpBwW2qbZIjjUCKi(JIcAlIcqf=g(l z_oZWZ&^*hqyV6i5{E;qok672AZ&m_`4U!cU(>svdb^iES>F1mAg8X%Xe@0bOtw$Cv z*_Ge}-iIVaf=D4a?Dgzjb${JPYU7eE+GZ9UCTHUvEKa=Z>9vpw>Cs<;))+{9y2TOk z!MumdVN8p8(ocn)jA!s4&&)UI`Lm;vy8M`cmj{a*(@oRt9elFpkto3hf$HS_*p!#WEj3?*6ectBjc@f(#d_xLCp=D2Gof0*rh2z-5`nplYBvQN*`Z;1I8ky#GfW z#WKn0^BuT+_K^) zIp@r|z}PL|qKyv#*RPGl2U zjiU6-5zt-yeD|V6(tN=-pP?Oo&E>1{KdiWk`3lvAjj-Gb*za~FbmMeBRs0D^4guwn zf@1u27Xe!TMLd$4^Zd%&A(&~(FJIm?o4JkL5+=`y&HS|rK}H~^)7mD0yc}gjFyy%; zt|;HWljI|KQ+}1il5o|mDQNfOkL6Ykczx^g4W+}|@ZdE&ioyFQ%G370LuY7Q(W~U! z7QFP1U$dQm8*=eZi=ers2p$E9mmAXCQR$aO{QhQgvSqSzX)~ZWqcdxgjnQX7PH{7^+|deLud{`YGiEqHD?8&ztwP-2 zhbLS`!=Rj_6mE4Ur;O;XO8?xxoi2FqhYgp+SIJMMHbW^*Nmn0yBNEd#EmbNwd?(@E-ZvP~?=wBw`Br8xU z-fESPh=b2#;2q}@a4Q1P(JB}yalqLpYSK%cp9bpWxsgsp&&b)M%Uai$QY<<9of?%- zubRYR|oV%vqkN_1u^ld%FqOo6&0EO2x`wyyPv4kus#%4CfJFV|N7N;$6? zn2g&bf&&cNDK*O-?iI9x2r@Lj^1glHS#jArZq~Zy^DB0IbU8(U3Bb9w(u1jZZ}*1T zqd>EX+GB(V-K2ML2~nU2{&cI~^uMmG)te{?sG)w+|1NI z&Ka+;Px&*bd(EDTmHvN|n0>?JxQ)xTLLY&w!M@USTMn*(9G_BIm-BES zWdqI0kEJ&j)@L8l>kz)L1aJki@G3EbP@_;s5`kh!E@bQm57I(sc<<|MY=8Fc>InB! z?NXEkT02{jsI_W({C~q`4?=pS3UfE0V{O;kBqC*^pd&=LXo4AZQNQK_9aO$?*~}3NTsA7yp4U5&&ENfeUw2 zwoE)h#!^$wL((V$Uy70s{K2heU#W}BW!ND<|9yvL-6X$?s#UgUU`#WJ42QOB9zYH?}c?&Nw!^8 z!tcl8FCD{e4k0WS0%rw~%P!!I!5Jui*N9X@6#XoOx|W`rNL&|UhqUmj%S0lZdm6ES zakkYSEngZYr~*}M2E7^lF{kn^$<~1)AaW!RI^$al)Wsu~jKNkMBb;ep^VdrT6Hj>o zqb|UvVl;66oJtaT5;i^(?^sHYL1zbcG8X%aWK;i{y3#8ZQ*Yns;Q#0qZA!H6&p=N4 zBZ16{b+Gt`BR>|eE&J1~3v$~X;YmMI&@FJ+3XH)u@)syLp^@z#VYH2kd??0p5{z(? z3^5C#Gx#w!WsQMfD17x`d;>1QzRplzy1*siT|IrSfdRFfiSzcu&=^^<_rYdR1)_|; zGz?VPb!gMgZdE{s@Zf%3HYPpa4jHL=7D1%a3eIb{IkcM?F1-ITTQ9}6jf@8jd}2a7zYJ!Hf17Z_yMkB3$o3`nH{q!o zIj?>Ggzml|X^Ng3vw|cEi~bTAeSY2ql;Fzf`IJ>O99^Y|e|vW{|2O@e1ot>53xl;8 z)5ZL~>q2KJ@>6}6k6#+o8SCQhCk)y3dq8W+IwZI>3c6kiI4g&i;`OHkTUXF-+~XfB zKp11WQ5%lQ#tECfdwYnn33*aNG~?j!efh;JGl4*Dc!yW-Yux@p{iu^^-Ue~Im8SnX-!P;9(86`goQtG8so#IQ87h|RB=YXePoO|cO=D)=;!>E;>tjR@ zZu~J(V;{j%a;|Tg4u8yy1`|syBbP-69V+|v#O>no%Hn#U|INc@9qLi8S$#J0-ZA=F z0Z{1y8wDRGl1`GYA(cxs#F7RCL3Uyhquykg5h*a(2+`(W^z47e+9oK})Oo)Y+su&Q z$_vK5uVcStLr)oOyAMZYoipGRgMR42I=zk+D*P}2@tcN^_W+K6`jsOMAk{%a;fCV8 zj7b!&nj6T?1Bz_zen#aUyld1EZ5YKc${@vE$pWLk|2@mNDX)EDm0x z9MfS{!61b$vx?Q28DcwUGv%#?3yuJ3YpMQKw1<0ivfj^xdQ=$Bp)IBOuhZ zu(JYvf|tbqqCQ#n#d-E*h;&yC7iy#E89wCU9W&Om6c3WkPwB8Njk$eq#0y_Ah6`%i z*&b<)3BSh00s75Hgxx*6uc>IizZqX8w)jjQ3g6B0T94Cqu&UvSQUBO^)qmQV`EI|M zV5V&VF=7$2(+Rs7iQu>d7sGY?CA$RhedY{#=mP4H_NZt0hQ+?a-Y4GcXlnGQq?j^o zzx^sN=?qJgI7o?>OW!}l4@SQ0W-b53-~d`f(K@6tOtJDtI4%u7r5e}^gT0A@o5+T` zc|mu+>{BMeH3LO}-S()&0j_gATX@0nq3SwItOFn1fRgo(@?807**N+-P=Q@T9KOz) z%?8Z12QucwhJKoNU08B&U+rzG4^DsXj4T4{^W8i1zafO|SEv-+p+5^*@Zp?VE#yQ9 z;K$G~(k!Ts69YRlNgjRY-bj`XJ=7#R5_3+S2n~>vqzN>EiL5&yC_(?B1B!%IcYWey z*3$W}^D5d7v4|h)b3dl9N)~iy^9WQQV)zfgE-E)yKyfO9>#+Dj-&W`8DOZC2Zd~qsVUbbyx zP8M(#j5R(6zg!`f-2m-5hfEAZM|JX^STl&w$7;5N# zO?nr&AYYsS*%ju+pi(<)v_lHCk70sWClbeXW^VoM%%f}XnTdIUXFcjQM$g@qnL~f& z{JdgRT*}9u=bcc3&gUTFRaE%P#4jJup-vIGD@wn)e4n=9==@<>&FM z_r^B-9%F$$4lF%4mq5Y6+w@Z6g5)VHevS0Ef0m6JNnoN9czA?=w4M zd0FnE5;3CUh5G<(%-3wO8{UC0?$MAXrrrpkVh#vHSwQebh(-*ysbtqR_+-}Lt?8&K z8afuEg|lQpEEGRfICv;G>hv9q_N?%pw=>{J-)#mo`;a3#jLP2!p?wq~$_qFsfV4n% z1@74I(JCmmU?bQexNJIuu-P^dD(V}r-$82*qL=2sif!f_2>c-;#>lb;)iKErwljaF zotofqIvBX>U?;N8h(V@3xk2}`$)Jk^TN|9`P4R}lI$zbuWmTGGxnK}8E9x~AhC)1x z4c0?Zd;rxp91rZrw8h@=i*VaCgwpJIcO(eMB;!}1LAPZo%g4OYaMyWkP@PgXQ+%aK zJyUo`?;zYeS`1_Q@yq$as&VqAXCa&TCLeBiv@R_=>4!&s1eUnp+eEG%$rKnM8GTGh z>-ear2-|vM3Xrhcy4ba0 zpA1rrH|O^b9}qbFujx#5#lcUC95@2Qu$i7f ziVMV>Xi?B41a4#-k<~x;8~%;tKmdM$!iiXWJf=Ae{{FctE9aI8sL{j;E*4K8iKu`~ z9oDo;l|bAI%6$H9ppy z6GgQdLQKZ_?~#Z3^|p})9+39WWW`xO;U7*+zxWcF50(JTGa&Q((~xRcM@j3zHB+(=>rd4XF5Lf6W*0~-E$`@N0_JH0h|wzu z##fKKg9)^pn2mFM1p<@TCoQjCS8L|?QbDBU&w?2ZL#ZPFrFxS%1j;@#uE;cwZd%;p zOV|vRlDLpv?Z@#xNo-kk1w6^~1?^f%Z%$s~r zjp1B74{i5l@Q5Jtb;8~z9@6#Cgr4?8leU1H2%w}4=tr+c2|(m}A?jK=DEBF|Ph8Ik zi^Ia6o^4OOj3UvpIa#c)8CxIJNb75`mvXze1Y!T0#>*-V{Hh2R8?$Eq(={iG+hj4Q z2|GAAD09Drl3m3j{3u*BHo|{Tg)-n7)rZ9(rHu+#s%Y9GaLUcBdKYg-d)iV5L(cJd zT)U#p59)xmD~~m+Z_7h2QpNxEHH49KA}YFjVel`RfIXB_GV_d%$6@S0Q~C?`t+z z>#@@D&M-xBbt(e898~ec)_I+!){dv*k;Q!foH2Y+=t(Fw^g;od^2p9k`=Iag9%T;( zitzCg30J;yK@8*n%`27j>oTsP9JInAm)%Nh+cL(bpmK4AWX` z85z;3OC}&P-WKJOao*B9fZFqS?(4keqOK2gz6qbWM~-y=a#E3kO!riM3^YQ1hy3#v zQc+SRd@rc;)fai}L2M>nk@byl+`>qwi*_wSFYk56R!m`c{1@}ykH9-zY!qOP6KvRtK( z+VN{jIF5KC2O&=1T+DkifB}p=qJ6B@7fo#mT));u&5(Do*SlMN$-NIF*GT2^^YikK z2Lk&m|MP1*F~FFmYxc~K5G<+%Y>3Fk{oaPvT|!NnG}bww{2_T{1dhN8C9cS~fX6+9 zEX{g&6Q?eordC7a-CC-^CkhLgwfHQVE@+s&UfH*0~iwg0r}3q5>A3E#`a}F_)0Z_RUzNq+{XV zk4b&zGva!`pl$?eq#gOs#SAt_FlY434*}$8l}0`h>0?j% zo4QrG_FVXo7My%P$i*_k>JifR8G>+bCgg^10&@SY03n2XlAwUVrMx{;6Y1ws65H_f zzN%GX74|%QluBfzoW}Y^;u=;T$TP!E+GJ4`Px5bmJ=1oKFKcg*Qgfn9@-jK`$_w{< z>#GUyoX6(+pipe*#qH;V?yhMx*Jv4fp0@yp^bD0auK%tM+3pp(VctfE595D$kV4q{b7g|Md@EpdHx%#3b8_WDA{ixc!r`iiIN&| zHru#$9)8{C9~buRsdUx<># zIq`mO;K<+uv;9P#kIVl0z*p|!1RCx`v$I9#Tn2ZTN7KInJ6#TcOmGzo*XRrEy`9ei zN}pG1rE|VCv*A`XekVnVw-t0lVfmTWlrB)pR}j+TW-BXP4pjr0MjX0@wLKHf?`Ptt zLEDUD{oeIE!ry&6ERI^`Cb`bxq8)6&9f@k5;ar4JPaaiq7i1)uNU|sxwIJ`*@>%|s zzMX_U*!?_guHUbny;QO(Gx~wuT0xwl?8yCgb9gN;ox!}8$~+om+D3e_$f}RT_ixz? z`&pXDvFzh?i;aKJ=(FY|EYu$q{B%71dIqnAq=A;@0~42Q(?W(XOg(~Sl7QpXsBRINDzYhPoY}efAv_x zQo+lRX+p64^_?)s$ej0yf%@ou?@o-B+PNNu%MT~4%0k>af`+Nrh69st&;6l`@^$j3 z3^S+`v{eW$C;@G!89>y8YXk5x`*4EX;*3ne;x%lLl`QuMz7=QM|2%hzZAWo~k@4(V zOH78@)#Vn9BM7xG@fHA=y(yNK4AS?cFwi<`4a^^inApzL7&;3H5Nt&vbb*OS?lzY7ytOlbU zI^Xcyh@K%YPik4wyK?FLxz|DuD9|f=y(}W2O?CZ3&(IZ0lJNfR;y3GL@9`<-CsxU)!X9u6 zI0rd5%rCF6p5Rf}*=zjS)$9ZJ&5c6zpvLMf{8=<)H4`P2ul4igK9CRuRC)p{_I1y_ z`DSdtJ5Z8IG>t|4z8ahVLDZ$&CqJc2v(|b07Dn$S9twX9s1b&4FmE;2AykwiZQeg4 z_qG1q{Gdr$U^U zVKbuP#v%ak9-uoE@Wk3c^FZ1~%!juqp7AXtpbtvrqQqsif6sGRdFu82_GPwAPxK(q zjog1l$>W`twa3@{Hj}IXcFgQ$#S4tBF*!FIx$5sO;W|`bTZ>?z-5*Np7Z4{Y881jK zzrsyI_@$v;zXO2T4uiUl;x}1Z@0oymUi$l4H`%1s%aN|avuIzl6B|_}k^HcDoON{R zAF=;U9bMz4Ad2Q7pZ&Mv75Z9<A7{Y zK=ybg07%Z~aoq*7Dqxe25o-u`?tmsYw24UIARUqx0dYE4w7j#ykLo{&GzP@ zz=+~amt+$0g2^GNzugme55SQf``$dk zO0$}y$;<}q>r1PbJ;Jfe%Zq@^%P;;R;Rbie^+2Z}XzWt*8`U=Q1}_uvJ287MLcry% ztmEDOBGgwVZdt`BP0E&a<;2jZm67Ye&IYlakvy>>QJ(+Oa}Evb>c*?eq}_}FpD>PM zU!l0z?Co1;wrzRY*1{vVqW3Ps-z<@HlIf0RdK_!`-|Oa@Deoj6@+yl79 zbqRD~P}rF6LP>)rg35+S-oV z>>98Y25Bq>>KP*pYSr72+kq_Zd4w#?Y+&0jQm;}MeYe%ZZS~!2eqJ%FJ0C10dg#fk z=aX+o`u?l*PT-o9|C_w4gqO6p%vx#dzz=*(%3Gpq5?g%vvAI6Q=?ZM-=;9j@Zg*u_ zUwdsB&x6IMT0d;ektK6LgtYgO@cBv%XX4^*mJ+cRppz9MPILtl?QVP>X4^VSiqx?MNA2l2(10?~@Le9)XPdkc z59KPoc^?L-_M1{MZ3^&n!9p>Y2fodDZ&kxe}vAMnhC)Ea;ZlMgSC|z z^6P^2O>>UTP>AHw7gWY<#5>lEh+9LDXhUK9Mup#q=)X2GnlF?aSF}9Y@{;~GLQtya z>L(&eMOwDp)e+Ak`=3*5Zf0e6%@m~Plp_o+0Cho7?=sXa&WP7> zuR1Zxts|I6#iVK7KL^a8zE{j1>w+tzq~0~WOqt8>xw8F?t$0c|{a^3Z1pgWlr_@+T zS#u~tXhAa2m4dgl0F9|-&*^%(*b8^^J=z(rOk?sM*0})at^;NK^Yi#3^9yFjL-2-EKb_b^gN2Q+rN5p7o|GUF6D>;Jb@SeEMbcbBUMJfYUg5aHer9q)zy#6|%q> zgwc%C2~>(B^ugII6n9n+@mLWBXi`c#Sa+7$L>gCLpsh( zXRj&{8}~m9uOQ8JKo_ooh%?lh6$F1orx3^k{)`8(h@C11(=WtPJGtr5;@!kzsd^H9 zp)sv%2AM8=!ChIp0 z6cgtN12M$w5<$(nx;kBE47KWW(%8FJD3GtvXE%nAbJ(Thr2k8W|>+HB6nWHT^s5#ZGkQ1)eL{s|UtdtH?|mINNNV)Qt%s zo#?_q5r#0aM<#X;Y<^1lkScs3jGbD9f!i?CK2a(dLlZL~3HS))iF|BW57~OXIlV`m zE${r9{fR5-aR)t3?G&v$h=RZCxB-^V`vCWl&q1nfBBgoIqeP(QMZFs|Hx=;GOeSz) zXqAqXShE3DMhAVl`uwK>E1 z+iO|(8zN_MRlUf-=Au0{Zm=SNF=*L-Bd~zt;&*4g_T`^I6H@o^y8A4t=QLyAFHKau zI>G*RFfWLf)!LDpF!(-AwY|+_v7+-yw7o+bFOop z>zEn%A8NN&HSF44;)aXbNwJ;D-|$HD&k;0*t;lcht672)tE6mr)UJZqL=``G+xtgp zjP}?3BYJPuPN?tgTOQzQTU0hD++$hNz5Vkur~IB@cEy3mIwHr&9?G7SEPK;O8Q*q8q`J(*G1{w5xAyDsR9FM7=OsWsU05o%ChIR zh*QrPjF9ntjt*G=fFb8@CP5F0HbcT)kI6IV<#+p;wE8Y9Zd{&t*J0mr(c0uGo~Y`G zhhEWVn6pefi1+vWG;)+5YIpZcCBBe7&7`B?OHZP#)&SS^I@^p#r-Ne1pA+c%YjQ8y zQ*i6{4+x4M%ldv~ux(7K1s`b^miO9!c_BJkIpymR@z+Dz zi$Y`8MPk5LA6Qa83@Vv@~XJAm% zEd`Ttj`M<-PI+nHDCr8lfr1o|ENX)3kiaefxo(7Rnm7vSk+XH{9Wyc~*Ccf+JLV zAGM`RzGyc!u^sI$_pA^oj;V?<*LT{NiHBdAY0@JUF(`Pn_DOs2rJVM6t|d@e!nxtV zR?Cu)+EZ^mFmPR8ZWr?1p}7u^z<=qaiDTf(cw2AEd(U6YmabOD!k9PEqj}T2QQl~y zVZ|%7$+?R2b}ha&l-^;zSoqzV_`M$SB!d9go2~LJ+U6^#FA0DBHrs%D6a+aM$kf!U z;s3F&f0q~y^mCSP4a=p7oxK#{MLy(#na_b|K%w_<<%L1(m)n%H%F#Ol?d0XQ(E8Cv zyPqe1p6@v%=l_IDSSR#|SKgO2Zi{k?c00e>5}(B!xSJ0ARVU#vUd^;y&Es3p4^2g2 zM|PmLdUPJc*9P>wFI0OipTCtRll&)bG3NG*>ieA9sw$TLhv#_j3S9o8koBPVCE>HP z)%@w{cG}Ox0pwu|D22Dpj7b5+$c5hgRA$MClG&l+>r9YX$b z6a5|0pI*vSNnEv9k0foLlXmQ2?DfFqM_@{eAhwGVZ=2&{a;4|jDk25%7 zOlY;r*y*|4+5U4M%n9tY|5(qzXOAP;1A`Q z`=y}*$0=&6|A~msY|52;Q*mb^0Jr@G;Ti-U4&4%-Fa191NL&SEXXnW zbL@3ujRQte&x5RQa{uF2vI8CdNazqpa><a|~YB+oO)hxg1p(KocHM z8vGMO^rUF*z;uZ?s_uP9t!1+9U<61PE_GCYH@@dA)6IW$+2>lrl~wjQD;wydBG&-CbMSAyy)i53i56$SokTvbd@{79^+t&_;KD z#R$WGFqC=s&ONc$@h5-6m!qB=iPV%A*93Kx@cC%4t}P|C@y)gu9S4;q9sLt@tAhm!*BT&UULq)1mbPSA)sFKD_exa&)A! zK&juS5YyT7G9ZDyyqtV}igr@X@1+Y%T{^1h#IP-D=2ehsqtGBmDHm68C9&V`qp|!I zdX;AvZdz9~#IC;6+a9AP+-IScgey8rW1V6U`>xckF-14yb&StxYjtPZ%sD#47Rn$^ zt+ahr67_hdg|v`o#y6YE?Ne z*tHKNEHZGtI94**n8(|fc)KQLp&71dw`Crr^7gdqpUcsld#oufqzA17#LeI4o=yz= zwk;Z{+A+o{&C{+w=GV6)uI@E+qQvZ32w97m)ivXuGUWncF}Cnj_J_;j@oII4%z3J% z?mSw|jTjgNekgnxaT(1Td(f8N}jTZ8VE*Z6Hw^{XvJXfz^;TNx0!zF3BNw3ykMTgOL?C7FNb+45B5-w_#tFs2>@(H_L zj!oP_Ie9`wwNO8+ZyKsm^gF77dyH2qOi8jpMst97@jY=IKj!%5nZPw154qa4V`Um} zi}6*C%8?1)s109<(iU!F6^+~BmSVCmV-%sw5IiTgr5`=;0nkAod=8HD` z`qFde=K8kW_2A3N!4pX&r>yS9A&Z=Y$4M&5hbl?k^3V&d z{JGPVWf`Qs@L0(dYOoJlB%mv9I=zhvht%X{K7AkxDWNFK;+?6D;@4E|?(K(Li7*I< z49*wvF2QZ)^|;8ceVL^WokzP4K&~<5K@|*BqmZ*q?-<5Tlt|qw+lZp)>>#^iZ!TWZ zx9NQC$!ONlQSZYXYR=CyBJt}hjwdV((M7*Eic3oOk({8QWAhOc*l7oz&?t_*7xmfD zJ^_knbfVA9h8DY^QtDyhaj1~z!tVK^blL3Fi2^u60yeH@eL2!+mz!{i-{j+=NeyQ! zxH<2FLgD1E8?5c41XSnLiS{nK_CV$x%uWQk*BrKT6k0r;7mNBJ7fhRt`@wjjo;mU1 zEHyDfFq|$cbx$fxnPyD5q$R4!lqRR2Z^0dIZzFz;zpiJ1dubpF6}`f~umbsJV&+rn zOPrtv4~S5L_7`uXx2MCZe?_0YMI5y}pflTam&x>M^|^v0TvlwG{YqO&*eR1xy6RfE zHG-?1^o~y$UCTI|SG7t|Kbb#)EcP=xKNRY8hjJxdW>E`b_EfPfF4!p9Q=OC4hlIj? zH5Tv7NeKujypHHUaMSpN`3x7OLxR7)3EbS^k7T9NjxMxgiIr`iO5p^~afH|237hkU zdefJ3C=mPQOz=-A;lh;U21h+Lr>38omqzo4@7#C_e$RkPy@MP&olUzLikUcpWQscY zZ5DJr9|tZ?1x#YnJI%jDQ+CEt2Be7F4r1drN&Vfh(_5&TSNXP(gF+R${lqQ{6G>2V z{iM^%A#AEqcTr=HNNii1Sn(JnF=GD;w|jZA%X+l&k~Tv5H7Q_s8q?1S!|Yj2pyjaK;7KO8FEeqqVU zzG_AcFOZ)-d?}`tjyRLSZ7W#kt=Ljgt$pBZqW6iq`hb;A;+0Xc* z{CfqQ9_Y!uSG+8d{$0nrh-YmKvoZ`#Y(NVo*s2Y9mi^}&nU7+8p)hD%IDpJ9eTces zpT4S%&-BXh_*~GK&CYATKK2jFs>v~vluW;uab|Oyx4MR+ZNJ_oCDd?Ni6oCbQ<8az zI!T>iRI76(Hj5OVgg=jyRgNylLHLJ6*{FBdT$EYYbbGAlEeDCOMQ)bjpTR>l=`Qup z^dndrZ$Hqi{+M|81 zL?zQL{mw6Yocq+I>ET zPIVOw!ZL&HMWoamAMWW=MkMNs znFxJtw?a;^VRpe*Evx$z*TivJ*MOLAPxF+SMJ~`dUXzMWtUW?K!O*F(XZ+z zKNZm;*@j>0hz5(Du+Q22{1w50if9pw7oOMM?xuD&@jpDnpsz5Do9pdi^OF<)^|K5s za_p9dqVs8E-(mHCtm-E)I^U9?E0>m)Pq`JW^*MkdGDOg;h-x_j<&y}tZKK_UaOSzhT~~73SNL4Q*%n1y;h(O(`B~C;#e$<#|m&9nK7kYbT^qau9AvyeVw-jH^AiqO;Kc^$51&Ce8PG;(5ad%xUqLa8iGgW zzvVj440z66ALI;+*ci{!h%u_-W%qqnzhb&Gpl7Z^f`>xh+kVYv-a1*trsGp}#j@pc zp6t(P%Z}q_Jh?fu@;nRh7UH#~;$*M8r9f)C9l%6!hwIS=n===Kvfnnj8Ge#{d_}UE z2D@$E@helU__1pmJ^4H&?8SB*e^#ikEGTNOru(VHTxRH9QWs1(bn>*iL%~sLb*rYf z(ww2Wo6Z-R|8Wcb?MgDXw^Tk_Z`R-PET-wLVJZs6W;C*;Eu&(U%IBbrQfR9k8en(h zbHdOa{ zqx7@pL+fe-E+YZ8D;52{AzV*Slb}gE>B4{5$!BdxKy7ckgqVCGP+d577~&hQAH>`2zB+OQg{j{|T?wOVk4oHQ%&>$%~s zWcncK;8}jAOn>(ml&4BG?Ox8zcC*YqMxC#`Nm}}eCpUvIZ+x8NX*I@QScolXR5x#5 z@B8iEx9`Yy;Oa@$(^+s@qe2h+FeQ8R=I2-;8o{ky!zZK3D@ z`nIM@)G--TiuZGZIF-Vii_l_DLDx$4u+QObGOzSR9KRqWzw2c?a^pc71%Xp`MwrF5 zypDF|uE-)QRbK3v&GZQu6uGFwj@t%ALPCPZ%LnN!YCb5UJhW^%8lc=|chTFmMPb?3 zzVc|*#np4`fdwYt1n~Drv;&-d`K-yfH;;U?5&Ag9pgG?)t?+J2Key6O^(c+n$xGeY z_Y^|6n}=LB~@yl1u7oBir0Cs2{vMpT|v(k(a3YP%C1p21%zeLi+y z(2=X`KBK^SD2W?<|N44>|E%HRyMWyc8It=I>VTQ=cR(e@9j|x86oo?Wp`_zI=$%5U z(qt%HpiaC3wTE_KT21(9A|v*Q?5?K8a21OT`CtUgxtdSo^c7K;ue57!x5H(XHEQe$ zKUH{M-*vY7&D)DXGmp;k({j|CUaIcu{>-x*4Ile!x)esGy*6)HZ_5`>Hgk0_R(*YU zGg||%FLx!k7cIMc2oLdbQ!ExMSuN@GBd&ROf^6HYJ5Su=G#zFB#^h=eCFamKA)|Hb4j z#kAVQG^^GZrAM3AoQYab`y!HRJ+#LQoLAPC1>{==atZIP|8=RdzkT4kU-X6Qsa_Oe zDv>NC%^Mo@e~?y=>p7hogm!;6qF>2W@vaa13%fw^ljZp`#1L2zwQMh;J3cTN?)T>1 z7GJBBB057NhqATmK77rDp8C!p_)S*c?Htd}o0s1P1n0sEy_v#E3?iP+EilcFUxLs2 zUB&KoTughOGZA@0_SNzOwHLVCTJ01qpMx9Rw}`aY^iA>5?B?NedA;Ymgp@m7nL}dw zCYlWz*Y|nIs6#3mrMjN{KCF0|9=A(jZtDEg2Xeko^>e? zwXtAvWL^G0-=iVZexvhL&%_uD_dI`oXtYh=ywNc*(bUz^d#-DO6}CI`hf_Y)(s^ZQ zplPD_N(Wo%lcWEe(iobWyf!t_)H8Uhr>$e`PL3h_`%wh-pU;k%rsO)@@9+N?k$(lK z8L3(TYDKCxfZ7p?iU?2#$Zv?Rkaq&qg;d=DeMhPufO?Ut51@Xe8USbzsfGX=Mye5j zMv-a^pdUyz4$uTrO#(E9RMP;>Ak{2Db4WE0&;mkHEdultp$=%mA?<6wg6`4uNC^c^D)cNOq7MAUQ!E z0r@{_&jk=SQXK_|2dQ`g;zO!q0P!Q006@o)N)RACQk?)u2&qm2B#cxd0Er@%7(n7k zbqXK}q>=>aG*X=b=qyr60dx+jqydsas`CKJB9$CK7m!LGAO)nl2#_LDT>?l6sV)O_ z1*wz)QbDS#09`|>>j2$ADpi1PBGoN`ZX?wlfbJrc>^*?)gM0u|4dg?R>L4G1)Bvdo z@-av)kWWBrgM1272jnx5|Koq`IY7Dybwm#!eUL9ez6ALSqyb1nkgq}h_pi_y0rUo> zF-Q}{SIJEQGD9kJfGm*85+Ez2dJE7yq_PIc2C3cyWQ$aG01=SN9v}y#as&~&R6YRtB9$LN{zw%7P#{tT0Thf>ApnIURTw}Ykt!UZ z2&9SxC<>{f0g6GYSb*Y?>JvcmNRT8bIktl>tyDQe^>@jZ`@R zB9~ z01YG62tcDqH3rZRq#6fk0;whennJ2+fM$?t7N9w#ng?hBsTKkHiBwAfEhE(mK);Y` z6`(bwS_fzYsWt)HLaJ?mc93cppgpA82Z$u~e_f!v)BX3jjDh~QbtFdtghnb1Kv<+A z1&9nJm9dG|oBs?ooB%@&q%buxHKriHu1s!X_*zp}%UG9!1ZQes^2XHI1Rl90`G1># BBIp1B literal 0 HcmV?d00001 diff --git a/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs new file mode 100644 index 000000000..2adbc56ba --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs @@ -0,0 +1,243 @@ +//! 对**真实节点**的集成测试。默认全部跳过。 +//! +//! ```bash +//! # 随便一个公共节点,或你自己的 +//! XMR_NODE=http://node.monerodevs.org:18089 cargo test --test live_node -- --nocapture +//! +//! # 想扫自己的钱包(只需要观察密钥,不需要花费私钥) +//! XMR_NODE=... \ +//! XMR_SPEND_PUB=<64位hex> XMR_VIEW_PRIV=<64位hex> XMR_BIRTHDAY=3000000 \ +//! cargo test --test live_node -- --nocapture +//! ``` +//! +//! 为什么要有这个:单元测试用的是构造出来的数据,**扫描循环的三道校验和 +//! RingCT 索引推算从没在真实链上跑过**。那些校验一旦写错,表现是「扫不到钱」 +//! 或者「一直报重组」,而不是编译错误。 + +use onekey_monero_runtime::{keys, network, scan, sync, wallet}; + +fn node() -> Option { + std::env::var("XMR_NODE") + .ok() + .filter(|s| !s.trim().is_empty()) +} + +/// 原生传输走 `reqwest`,它需要 Tokio 的 reactor —— 用 `futures_lite::block_on` +/// 会在第一次发请求时 panic「there is no reactor running」。 +fn block_on(f: F) -> F::Output { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("Tokio 运行时") + .block_on(f) +} + +/// 最基本的连通性:能连上、能问到链尖。 +#[test] +fn connects_and_reads_the_chain_tip() { + let Some(url) = node() else { + eprintln!("跳过:未设置 XMR_NODE"); + return; + }; + + block_on(async { + let daemon = network::connect(&url).await.expect("连接节点"); + let tip = sync::chain_tip(&daemon).await.expect("取链尖"); + println!("链尖 = {tip}"); + assert!(tip > 3_000_000, "主网高度早就过 300 万了,{tip} 不合理"); + }); +} + +/// **这条是真正要跑的。** 扫一小段真实区块,验证: +/// +/// - 块能拉下来并被上游接受为 `ScannableBlock` +/// - 我们的连续性校验不会对合法链误报重组 +/// - 我们独立推算的 RingCT 游标与节点声称的一致 +/// +/// 最后一条是重点:上游明说这个字段不可验证、要求客户端自己算并比对。 +/// 如果我们的推算逻辑错了,这里会报 `RINGCT_INDEX_MISMATCH` —— 那说明是 +/// **我们**错了,不是节点在作恶。 +#[test] +fn scans_real_blocks_without_false_alarms() { + let Some(url) = node() else { + eprintln!("跳过:未设置 XMR_NODE"); + return; + }; + + block_on(async { + let daemon = network::connect(&url).await.expect("连接节点"); + let tip = sync::chain_tip(&daemon).await.expect("取链尖"); + + // 从链尖往回 200 块开始扫 40 块:足够覆盖有交易的块,又不至于太慢。 + let start = tip.saturating_sub(200); + let count = 40u64; + + let mut db = + wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap()).expect("内存库"); + let (spend, view) = throwaway_keys(); + let identity = db + .add_identity("live", &spend, &view, start) + .expect("建身份"); + + sync::update_chain_tip(&mut db, identity.id, tip).expect("告知链尖"); + + let mut scanned = 0u64; + for _ in 0..count { + let progress = sync::step(&mut db, &daemon, identity.id, 10) + .await + .expect("扫描不该失败 —— 失败意味着我们的校验逻辑对合法链误报了"); + let n = progress["blocksScanned"].as_u64().unwrap_or(0); + if n == 0 { + break; + } + scanned += n; + if progress["done"].as_bool().unwrap_or(false) { + break; + } + } + + println!("扫了 {scanned} 块,从 {start} 起"); + assert!(scanned > 0, "一块都没扫到,说明拉块或扫描路径断了"); + }); +} + +/// 用你自己的观察密钥扫一段,看能不能扫到输出。 +/// +/// 需要 `XMR_SPEND_PUB` / `XMR_VIEW_PRIV` / `XMR_BIRTHDAY`。 +/// **只要观察密钥,不需要花费私钥** —— 这条测试本身就是那个边界的证明。 +#[test] +fn scans_a_real_wallet_if_view_keys_are_supplied() { + let (Some(url), Ok(spend_hex), Ok(view_hex)) = ( + node(), + std::env::var("XMR_SPEND_PUB"), + std::env::var("XMR_VIEW_PRIV"), + ) else { + eprintln!("跳过:未设置 XMR_NODE / XMR_SPEND_PUB / XMR_VIEW_PRIV"); + return; + }; + + let birthday: u64 = std::env::var("XMR_BIRTHDAY") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + let spend = hex::decode(spend_hex.trim()).expect("XMR_SPEND_PUB 必须是 hex"); + let view = hex::decode(view_hex.trim()).expect("XMR_VIEW_PRIV 必须是 hex"); + + block_on(async { + let daemon = network::connect(&url).await.expect("连接节点"); + let tip = sync::chain_tip(&daemon).await.expect("取链尖"); + + let mut db = + wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap()).expect("内存库"); + let identity = db + .add_identity("live-wallet", &spend, &view, birthday) + .expect("建身份"); + println!("主地址 = {}", identity.primary_address); + + // 常用的几个子地址也登记上 —— 没登记的收不到。 + for minor in 1..=5 { + db.register_subaddress(identity.id, 0, minor, None) + .expect("登记子地址"); + } + + sync::update_chain_tip(&mut db, identity.id, tip).expect("告知链尖"); + + let budget_blocks = std::env::var("XMR_SCAN_BLOCKS") + .ok() + .and_then(|s| s.parse::().ok()) + .unwrap_or(2_000); + + let started = std::time::Instant::now(); + let mut scanned = 0u64; + while scanned < budget_blocks { + let progress = sync::step(&mut db, &daemon, identity.id, 100) + .await + .expect("扫描"); + let n = progress["blocksScanned"].as_u64().unwrap_or(0); + if n == 0 || progress["done"].as_bool().unwrap_or(false) { + break; + } + scanned += n; + } + let elapsed = started.elapsed(); + + // 这就是明天要看的那个数字。 + println!( + "扫了 {scanned} 块,耗时 {:.1}s,{:.1} 块/秒", + elapsed.as_secs_f64(), + scanned as f64 / elapsed.as_secs_f64().max(0.001) + ); + + let balance = + onekey_monero_runtime::query::balance(&db, identity.id, Some(tip)).expect("算余额"); + println!( + "总额 {} / 可用 {} / 不可验证 {}", + balance.total_atomic, balance.unlocked_atomic, balance.unverifiable_atomic + ); + }); +} + +/// 回退必须真的把那一段清掉并重新排队。 +#[test] +fn rewind_actually_rolls_back_and_requeues() { + let Some(url) = node() else { + eprintln!("跳过:未设置 XMR_NODE"); + return; + }; + + block_on(async { + let daemon = network::connect(&url).await.expect("连接节点"); + let tip = sync::chain_tip(&daemon).await.expect("取链尖"); + let start = tip.saturating_sub(50); + + let mut db = + wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap()).expect("内存库"); + let (spend, view) = throwaway_keys(); + let identity = db.add_identity("rw", &spend, &view, start).expect("建身份"); + sync::update_chain_tip(&mut db, identity.id, tip).expect("告知链尖"); + + sync::step(&mut db, &daemon, identity.id, 20) + .await + .expect("先扫一段"); + let before = sync::scanned_to_height(&db, identity.id).expect("进度"); + assert!(before.is_some(), "应当已经有进度"); + + let target = start + 5; + sync::rewind_and_requeue(&mut db, identity.id, target, tip).expect("回退"); + + let after = sync::scanned_to_height(&db, identity.id).expect("进度"); + assert!( + after.unwrap_or(0) <= target, + "回退之后进度必须不高于目标高度,否则中间那段永远不会重扫" + ); + + let peek = sync::peek(&db, identity.id).expect("看队列"); + assert!( + !peek["ranges"].as_array().unwrap().is_empty(), + "回退之后必须有待扫区间" + ); + }); +} + +/// 一对不对应任何真实钱包的观察密钥,用来测扫描机制本身。 +fn throwaway_keys() -> ([u8; 32], [u8; 32]) { + use monero_wallet::address::{MoneroAddress, Network}; + const ADDR: &str = "44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft3XjrpDtQGv7SqSsaBYBb98uNbr2VBBEt7f2wfn3RVGQBEP3A"; + let addr = MoneroAddress::from_str(Network::Mainnet, ADDR).unwrap(); + let mut view = [0u8; 32]; + view[0] = 9; + (addr.spend().compress().to_bytes(), view) +} + +#[test] +fn reorg_detection_rejects_a_gap() { + // 这条不需要网络:构造一个跳号的场景,确认我们报的是重组而不是静默跳过。 + let mut db = + wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap()).expect("内存库"); + let (spend, view) = throwaway_keys(); + let identity = db.add_identity("gap", &spend, &view, 0).expect("建身份"); + + // 空批次是合法的 no-op,不该报错 + let outcome = scan::scan_blocks(&mut db, identity.id, &[]).expect("空批次应当无害"); + assert_eq!(outcome.blocks_scanned, 0); +} diff --git a/chain-runtimes/monero/docs/hardware-and-offline-signing.md b/chain-runtimes/monero/docs/hardware-and-offline-signing.md new file mode 100644 index 000000000..bde11c7c6 --- /dev/null +++ b/chain-runtimes/monero/docs/hardware-and-offline-signing.md @@ -0,0 +1,133 @@ +# Monero 硬件签名与离线签名:接缝在哪,什么已经做了 + +2026-09-22。这份文档是为了让下一个人不用重做一遍调查。所有结论都注明了 +来源(上游源码行为 / 固件源码 / 实测),没有推测。 + +## 一句话 + +软件签名已经通了。硬件签名接不上的地方**只有一个是不可逆的**,已经修掉; +其余都能在真正接硬件时再补,不会丢数据。 + +--- + +## 1. 三方各自给什么 + +### monero-oxide(我们用的密码学库) + +签名只有两条路: + +| 路径 | 入参 | 适用 | +|---|---|---| +| `SignableTransaction::sign(rng, spend_key)` | 花费私钥 | 软件钱包(我们现在走这条) | +| `SignableTransaction::multisig(ThresholdKeys)` | FROST 门限密钥 | 门限多签,**不是**硬件 | + +没有「外部签名者」回调。`multisig` 是 FROST,和固件那套分步协议是两回事。 + +`SignableTransaction` 的公开访问器只有: +`fee_rate()` / `necessary_fee()` / `serialize()` / `read()` / +`unsigned_transaction(key_images)` / `sign()`。 + +**它不公开 `inputs()` 也不公开 `payments()`** —— 序列化出来的 blob 从外面 +拆不开。要拿里面的东西,只能在 `prepare` 那一刻、东西还在手里时留下来。 + +有用的是 `unsigned_transaction(key_images: Vec)`: +这是上游留的两段式接缝 —— key image 从外面给(设备算的),它给出未签名交易。 + +### 固件(`firmware/core/src/apps/monero/`) + +实现的是 Trezor 那套分步协议,step 01–10: +init → set_input → inputs_permutation → input_vini → all_inputs_set → +set_output → all_outputs_set → sign_input → sign_final。 + +**设备自己构造并签名整笔交易**,宿主只是喂数据。 + +每个输入要一个 `MoneroTransactionSourceEntry`(见 +`signing/step_02_set_input.py`): + +- `outputs[]` —— 整个环,每项 `{ idx(全局序号), key.dest, key.mask }` +- `real_output` —— 环里哪一个是我们的 +- `real_out_tx_key` —— **创建这笔输出的那条交易的公钥 R** +- `real_out_additional_tx_keys` —— 子地址收款时的 additional keys +- `real_output_in_tx_index` —— 我们的输出在那条交易里的序号 +- `amount` / `subaddr_minor` / `rct` + +关键一点,别想绕:设备用 `real_out_tx_key` + `real_output_in_tx_index` + +子地址**自己推导**一次性私钥和 key image。它不接受宿主算好的偏移量 —— +接受了就等于让一个恶意宿主指挥设备拿任意密钥签名。 + +### hd-core(`@onekeyfe/hd-core@1.2.4`,实测) + +48 个 `Monero*` protobuf **类型**,**0 个可调用方法**。 +`CoreApi` 上没有任何 `moneroXxx()`。SDK 现在驱动不了签名会话。 + +--- + +## 2. 差在哪:一个不可逆,其余可逆 + +### 不可逆(已修):交易公钥 R + +monero-oxide 扫描时把「R + 输出序号 + 子地址」整条推导**折叠成一个 +`key_offset` 标量**(`WalletOutput` 只存 `key_offset: Scalar`), +然后把 R 丢掉。软件签名只要 `spend + key_offset`,所以一直没暴露出来。 + +固件要 R。而 R 只在扫描那一刻手里有,事后只有两条路: + +1. 全量重扫(每个已有用户一次) +2. 拿 txid 去问节点要回那条交易 —— 等于直接告诉节点「我对这笔感兴趣」, + 把扫全链换来的隐私当场还回去 + +所以**必须在发版前就开始存**。已做: + +- schema V2:`outputs.tx_pub_keys` + `outputs.tx_additional_pub_keys` + (32 字节一个顺序拼接;没有 additional 时存 NULL 而不是空串 —— + 「有 0 个」和「没有这个字段」是两回事) +- `scan.rs::tx_public_keys_from_extra()` 在扫描当下从 `Extra` 取 +- 只在这一块确实有我们的输出时才解析(绝大多数块一个都没有) +- 测试:真实主网向量(高度 3767756,交易 + `097edcb4…51bb`)+ 迁移测试(v1 库就地升 v2)+ 空 extra 不 panic + +### 可逆(不急):环成员与诱饵 + +`Decoys` 公开了 `offsets()` / `positions()`(绝对全局序号)/ +`signer_index()`(= `real_output`)/ `ring()`(= `[dest, commitment]`), +全都够用。 + +但它们只活在 `SignableTransaction` 里,而那个类型不公开 `inputs()`。 + +**不要紧**:诱饵每次 `prepare` 都重新选(必须如此 —— 用旧链高选的环, +成员分布会偏离当下的链上分布,那是可被统计分析利用的指纹)。 +所以什么都没丢,接硬件那天让 `prepare` 顺手多返回一份就行。 + +真接的时候改这里:`spend.rs::prepare()` 里 `inputs` 那个 Vec 还在手上, +在它被 move 进 `SignableTransaction::new` 之前把每项的 +`decoys().positions()` / `ring()` / `signer_index()` 取出来。 + +--- + +## 3. 一条硬约束:`signableHex` 等价于 view key + +上游把整个 viewing pair 写进找零输出: +`ChangeEnum::Standard { view_pair, .. }`, +`write()` 里是 `view_pair.spend().compress().write(w)` 后面紧跟 +`view_pair.view.write(w)` —— **私有 view key 明明白白在里面**。 + +原因是 Monero 的钱包协议按「发送方能看到自己的找零」来优化。 +不带 view key 的变体是 `Change::fingerprintable`,上游自带警告 +「You MUST assume this will harm your privacy」,所以不能为了躲这个去换。 + +**对离线签名设计的直接后果**:那份「未签名交易」不是无害的。 +谁拿到它,谁就能看见这个账户收到过的每一笔钱。它只能在 view key +本来就可以去的地方流动。做气隙签名(二维码 / U 盘)之前必须先想清这一条。 + +--- + +## 4. 接硬件时的动作清单 + +1. 等 hd-core 暴露 Monero 方法(现在是 0 个)。没有这个前面都白搭。 +2. `prepare` 增补返回每个输入的环数据(见 §2「可逆」那段,改一处)。 +3. 写 `KeyringHardware`,按固件 step 01–10 驱动。 + 接缝已经在位:vault 的发送路径按 keyring 分流, + `IEncodedTxXmr` 带着未签名产物,软件签名走 `CoreChainSoftware`, + 硬件那条只要在同一个位置插进去。 +4. key image 从设备来,用 + `SignableTransaction::unsigned_transaction(key_images)` 合回去。 diff --git a/chain-runtimes/monero/rust-toolchain.toml b/chain-runtimes/monero/rust-toolchain.toml new file mode 100644 index 000000000..b8c2570ae --- /dev/null +++ b/chain-runtimes/monero/rust-toolchain.toml @@ -0,0 +1,19 @@ +# 跟当前 stable 走,不钉死版本号。 +# +# 这**不是** MSRV —— crate 声明的最低版本是 1.85(见 Cargo.toml 的 +# `rust-version`)。 +# +# 为什么不写具体版本:本机的 cargo/rustc 由 mise 接管 +# (`~/.config/mise/config.toml` 里是 `rust = latest`),`rust-toolchain.toml` +# 和 `RUSTUP_TOOLCHAIN` 在这台机器上都不生效。写死一个数字,等 mise 跟着 +# latest 往前走,这里就会变成一句和现实矛盾的声明 —— 曾经因为这种不一致 +# 白查过一小时(当时以为是代码或目录搬迁的问题,其实是工具链)。 +# +# 写 `stable` 则两边永远一致:mise 跟 latest stable,rustup 用户跟 stable。 +# +# 如果将来需要可复现的 wasm 产物(逐字节一致),再换成具体版本号, +# 并且**同时**改 mise 配置,两处必须一起动。 +[toolchain] +channel = "stable" +profile = "minimal" +targets = ["wasm32-unknown-unknown"] diff --git a/chain-runtimes/monero/scripts/build-node-pkg.sh b/chain-runtimes/monero/scripts/build-node-pkg.sh new file mode 100755 index 000000000..980bffbaa --- /dev/null +++ b/chain-runtimes/monero/scripts/build-node-pkg.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# 出一个 nodejs target 的包,只用于本机冒烟(scripts/smoke.js)。 +# 出厂用的是 build-wasm.sh 的 web target。 +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "${ROOT}/crates/monero-runtime" +wasm-pack build --mode no-install --locked --target nodejs \ + --out-dir "${ROOT}/pkg-node" --release diff --git a/chain-runtimes/monero/scripts/build-wasm.sh b/chain-runtimes/monero/scripts/build-wasm.sh new file mode 100755 index 000000000..8980d885c --- /dev/null +++ b/chain-runtimes/monero/scripts/build-wasm.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# +# 构建 wasm 产物到 pkg/。 +# +# 前置: +# 1. rustup(toolchain 由 rust-toolchain.toml 锁定) +# 2. wasm-pack:cargo install wasm-pack +# 3. **llvm-ar** —— macOS 自带的 /usr/bin/ar 读不懂 wasm 目标文件,会把编译好 +# 的 .o 静默打成空归档,链接期报一串 `undefined symbol: sqlite3_*`。 +# 归档器由 .cargo/config.toml 指定,这里只做存在性检查给出可读提示。 +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +PROFILE="${1:-release}" +OUT="${ROOT}/pkg" + +AR="$(sed -n 's/^AR_wasm32_unknown_unknown = "\(.*\)"/\1/p' "${ROOT}/.cargo/config.toml")" +if [[ -n "${AR}" && ! -x "${AR}" ]]; then + echo "✗ 找不到 ${AR}" >&2 + echo " wasm 目标需要 llvm-ar;系统自带的 ar 会静默产出空归档。" >&2 + echo " 装一个:brew install llvm" >&2 + exit 1 +fi + +# --mode no-install 找不到 wasm-opt 只会打一行 INFO 然后跳过:产物不报错地胖 +#(函数名段不剥、不做 -O)。release 必须有它。 +if [ "${PROFILE}" = "release" ] && ! command -v wasm-opt >/dev/null 2>&1; then + echo "✗ 找不到 wasm-opt(Binaryen),release 产物会不经优化直接输出" >&2 + exit 1 +fi + +echo "==> wasm-pack build (${PROFILE})" +cd "${ROOT}/crates/monero-runtime" +case "${PROFILE}" in + release) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --release ;; + profiling) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --profiling ;; + *) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --dev ;; +esac + +echo "==> 产物" +du -h "${OUT}"/*.wasm diff --git a/chain-runtimes/monero/scripts/measure-scan.js b/chain-runtimes/monero/scripts/measure-scan.js new file mode 100755 index 000000000..3782e92a1 --- /dev/null +++ b/chain-runtimes/monero/scripts/measure-scan.js @@ -0,0 +1,33 @@ +#!/usr/bin/env node +/** + * 量「拉块」与「扫描」各占多少。 + * + * 这条脚本存在的理由:0.6 块/秒这个端到端数字**没有意义**,除非知道它是 + * 网络慢还是解密慢 —— 两者的结论完全相反。实测(Mac,公共节点,单观察密钥): + * 拉块 99.6%、扫描 0.4%,纯扫描 153 块/秒。 + * + * ./scripts/build-node-pkg.sh + * XMR_NODE=http://your-node:18081 node scripts/measure-scan.js + */ +(async () => { + await rt.setNodeUrl(process.env.XMR_NODE || 'http://node.monerodevs.org:18089'); + const tip = JSON.parse(await rt.chainTip()); + const key = '0'.repeat(63) + '7'; + const a = JSON.parse(rt.deriveAccount('mainnet', key)); + rt.openWallet(':memory:', 'mainnet'); + const added = JSON.parse(rt.addAccount('m', a.spendPublicKeyHex, a.viewPrivateKeyHex, BigInt(tip.height - 40))); + const id = BigInt(added.accountId); + rt.updateChainTip(id, BigInt(tip.height)); + + let dl = 0, sc = 0, n = 0; + for (let i = 0; i < 4; i += 1) { + const p = JSON.parse(await rt.syncStep(id, 10n)); + if (!p.blocksScanned) break; + dl += p.msDownload; sc += p.msScan; n += p.blocksScanned; + console.log(` ${p.blocksScanned}块: 拉块 ${p.msDownload}ms / 扫描 ${p.msScan}ms`); + if (p.done) break; + } + console.log(`\n合计 ${n} 块: 拉块 ${dl}ms (${(dl*100/(dl+sc)).toFixed(0)}%) / 扫描 ${sc}ms (${(sc*100/(dl+sc)).toFixed(0)}%)`); + console.log(`纯扫描速率: ${(n/(sc/1000)).toFixed(0)} 块/秒`); + console.log(`端到端速率: ${(n/((dl+sc)/1000)).toFixed(1)} 块/秒`); +})(); diff --git a/chain-runtimes/monero/scripts/smoke.js b/chain-runtimes/monero/scripts/smoke.js new file mode 100755 index 000000000..7cdba2191 --- /dev/null +++ b/chain-runtimes/monero/scripts/smoke.js @@ -0,0 +1,133 @@ +#!/usr/bin/env node +/** + * 端到端冒烟:派生 → 开库 → 建账户 → 子地址 → 余额 → 扫描队列 → 选币。 + * + * 不需要节点、不需要网络。跑的是真实 wasm,不是 mock —— 这条脚本存在的意义 + * 是「编译通过」和「真的能用」之间那道坎。 + * + * ./scripts/build-node-pkg.sh && node scripts/smoke.js + */ +const path = require('path'); +const pkg = process.env.XMR_NODE_PKG || path.join(__dirname, '..', 'pkg-node'); +const rt = require(path.join(pkg, 'onekey_monero_runtime.js')); + +let failures = 0; +function check(label, actual, expected) { + const ok = actual === expected; + if (!ok) failures += 1; + console.log(`${ok ? '✓' : '✗'} ${label}${ok ? '' : ` 期望 ${expected},实际 ${actual}`}`); +} + +// 固定私钥:派生必须是确定性的,换一次运行结果不能变 +const key = '0'.repeat(63) + '7'; +const a = JSON.parse(rt.deriveAccount('mainnet', key)); +const b = JSON.parse(rt.deriveAccount('mainnet', key)); + +check('派生是确定性的', a.primaryAddress, b.primaryAddress); +check('主网主地址长度 95', a.primaryAddress.length, 95); +check('主网主地址以 4 开头', a.primaryAddress[0], '4'); +check('自己的地址自己认', rt.validateAddress('mainnet', a.primaryAddress), true); +check('主网地址在测试网被拒', rt.validateAddress('testnet', a.primaryAddress), false); + +const sub = JSON.parse( + rt.deriveSubaddress('mainnet', a.spendPublicKeyHex, a.viewPrivateKeyHex, 0, 1), +); +check('子地址以 8 开头', sub.address[0], '8'); +check('子地址不等于主地址', sub.address !== a.primaryAddress, true); + +// SQLite 路径。`:memory:` 走特例分支,不需要 OPFS。 +rt.openWallet(':memory:', 'mainnet'); +const added = JSON.parse( + rt.addAccount('smoke', a.spendPublicKeyHex, a.viewPrivateKeyHex, 3700000n), +); +check('落库地址与纯派生一致', added.primaryAddress, a.primaryAddress); + +const id = BigInt(added.accountId); +rt.registerSubaddress(id, 0, 1); + +const balance = JSON.parse(rt.balance(id, undefined)); +check('空钱包总额为 0', balance.totalAtomic, '0'); +// 不知道链尖时可用余额必须是 0,不能乐观放行 +check('不知链尖则可用为 0', balance.unlockedAtomic, '0'); + +rt.updateChainTip(id, 3700100n); +const peek = JSON.parse(rt.syncPeek(id)); +check('待扫区间从 birthday 起', peek.ranges[0].start, 3700000); +check('待扫区间到链尖+1', peek.ranges[0].end, 3700101); +check('尚未扫过任何块', peek.scannedToHeight, null); + +const diag = JSON.parse(rt.diagDatabase()); +check('身份入库', diag.counts.identities, 1); +check('子地址入库', diag.counts.subaddresses, 1); + +// 签名入口是纯计算,不碰网络也不碰库。坏输入必须报错 —— 静默接受会让一笔 +// 垃圾交易一路走到广播。 +for (const [label, hex, reason] of [ + ['非十六进制', 'zz', 'notHex'], + ['不是可签名交易', '00010203', 'notASignableTransaction'], +]) { + try { + rt.signTransaction(hex, '00'.repeat(32)); + check(`签名拒绝${label}`, 'succeeded', 'failed'); + } catch (e) { + const err = JSON.parse(e.message ?? e); + check(`签名拒绝${label}`, err.params.reason, reason); + } +} + +// 需要节点的部分。没给 XMR_NODE_URL 就跳过,这样这条脚本在离线环境里依然 +// 是绿的 —— 把「没测」和「测失败」混成一个结果是最糟的。 +async function online() { + const url = process.env.XMR_NODE_URL; + if (!url) { + console.log('\n(跳过联网检查:未设置 XMR_NODE_URL)'); + return; + } + console.log(`\n联网检查 ${url}`); + await rt.setNodeUrl(url); + + const tip = JSON.parse(await rt.chainTip()); + check('链尖是正整数', Number.isInteger(tip.height) && tip.height > 0, true); + console.log(` 链尖 ${tip.height}`); + + // 真正扫一段。走的是二进制路由(get_blocks_by_height.bin),它和 JSON 路由 + // 的 Content-Type 不同 —— 这一步同时验证了那个分支。 + rt.updateChainTip(id, BigInt(tip.height)); + rt.rewindTo(id, BigInt(tip.height - 20), BigInt(tip.height)); + const step = JSON.parse(await rt.syncStep(id, 20n)); + check('扫到了块', step.blocksScanned > 0, true); + console.log( + ` 扫了 ${step.blocksScanned} 块,下载 ${step.msDownload}ms / 扫描 ${step.msScan}ms`, + ); + + // 空钱包构造交易必须报「余额不足」。这条同时证明了取手续费率的往返是通的 + // —— 手续费率在选币之前就要问节点。 + try { + await rt.prepareTransaction( + id, + JSON.stringify([{ address: a.primaryAddress, amountAtomic: '1000' }]), + false, + 'smoke-r1', + BigInt(tip.height), + 'normal', + ); + check('空钱包构造应当失败', 'succeeded', 'failed'); + } catch (e) { + const err = JSON.parse(e.message ?? e); + check('空钱包构造报余额不足', err.params.reason, 'insufficientUnlockedFunds'); + } + + const released = JSON.parse(rt.releaseReservation('smoke-r1')); + check('失败的构造没有留下预留', released.released, 0); +} + +online() + .catch((e) => { + failures += 1; + console.log(`✗ 联网检查抛错: ${e.message ?? e}`); + }) + .then(() => { + rt.closeWallet(); + console.log(failures === 0 ? '\n全部通过' : `\n${failures} 项失败`); + process.exit(failures === 0 ? 0 : 1); + }); diff --git a/chain-runtimes/zcash/CONTEXT.md b/chain-runtimes/zcash/CONTEXT.md index 20c0b4060..aef19c98e 100644 --- a/chain-runtimes/zcash/CONTEXT.md +++ b/chain-runtimes/zcash/CONTEXT.md @@ -114,15 +114,13 @@ Current Shielded Output Pool。它不消费任何已有私密池,也不消费 _Avoid_: Shield、归集(单独使用时无法表达来源、目标和“全部”语义) -## Transparent-first Preference(优先使用透明资金) +## Payment Source(付款来源) -账户允许向受支持私密目的地址付款时优先使用符合条件的透明资金,再由选定私池补足 -差额的偏好。它不是自动屏蔽,也不代表透明资金来源因此被隐藏。 +一笔付款花哪部分资金,由发送页的来源选择决定:私密池只花该池,透明只花透明, +互不补足。 -_Avoid_: 内测专属透明花费、自动 Shield All - -产品定位与默认关闭的决定见 -[App ADR 0007](../../../app-monorepo/packages/kit-bg/src/vaults/impls/zcash/docs/adr/0007-align-payment-capabilities-and-balance-language.md)。 +_Avoid_: 优先使用透明资金(该账户偏好已移除,见 +[App ADR 0008](../../../app-monorepo/packages/kit-bg/src/vaults/impls/zcash/docs/adr/0008-payment-source-is-the-send-page-choice.md)) ## Transparent Mode(透明模式) diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md index 8287b3f88..ca525274a 100644 --- a/chain-runtimes/zcash/README.md +++ b/chain-runtimes/zcash/README.md @@ -120,29 +120,16 @@ OPFS 仍受浏览器 origin、配额和清理策略约束;App 内嵌页面的 - [x] 发送路径的**错误契约** 9 项(不需要资金即可跑,`examples/web/send-errors.html`): txid 非法/不存在、找零池参数错、PCZT 垃圾字节、电路版本错、 reservation 非法/不存在各有可判定错误码 -- [x] **不设限制,改为提前告知**(`examples/web/insufficient-errors.html`,四情形实测): - 转账会花透明 UTXO —— 钱是用户的,链上也接受,运行时不替他拒绝。 - `pcztQuote` 走的是与 `pcztCreate` 完全相同的提案路径,因此除手续费外 - 还报出**这笔实际会从哪些池取钱**: - `{sourceTransparentZat, sourceShieldedZat, linksTransparentToShielded}`。 - `linksTransparentToShielded` 只在同一笔里既花透明又花屏蔽时为真 —— - 那是花透明**唯一新增**的暴露(只花透明的话,对外与一笔屏蔽交易无异), - 也就是唯一值得弹提醒的情形 -- [x] **真发不出去时错误说得清**:`INSUFFICIENT_FUNDS`(都不够)/ - `FUNDS_NEED_SHIELDING`(宿主关掉了透明花费,钱在透明池里)/ - `COINBASE_FUNDS_UNSPENDABLE`(差额只有 coinbase 能补,而本钱包 - 转账走 NonCoinbase、屏蔽走 NonCoinbaseOnly,两条路都碰不到它)。 - 三者都带 `{requiredZat, shieldedAvailableZat, shortfallZat, - transparentZat, transparentCoinbaseZat}`。 - 原来只有一个 `INSUFFICIENT_FUNDS { availableZat: 0 }` —— - 而用户正看着账上有钱,那个 `availableZat` 说的是屏蔽池,名字里却没有 - 「屏蔽」二字,除了猜没有别的办法 +- [x] **付款来源由宿主指定**:私密付款只花宿主选定的那个私密池,不再混用透明 + 资金;透明付款由 keys runtime 无状态构造。`pcztQuote` 与 `pcztCreate` + 走同一条提案路径,报价即实付手续费。余额不够时抛 `INSUFFICIENT_FUNDS`, + 带 `shortfallZat` - [x] **端到端发送并广播上链**(testnet):水龙头 0.1 TAZ 落 Ironwood 池 → - `pcztCreate` → `pcztProve`(Halo2 约 19s)→ `pcztSign` → `pcztSend` → - `broadcastTransaction`,链上确认。逐笔手续费对账到 zatoshi + `pcztCreate` → `pcztProve`(Halo2 约 19s)→ `pcztSign` → 提交并广播, + 链上确认(当时是 `pcztSend` + `broadcastTransaction` 两步,现合并为 `pcztSubmit`)。逐笔手续费对账到 zatoshi - [x] **透明 ↔ 屏蔽双向**:隐私→透明地址、透明→隐私(当时走 `pcztShield`,含**透明 输入签名**;该 API 已移除,屏蔽改由 keys runtime 无状态构造)、 - 透明→透明(需 `spendTransparent`),全部链上确认 + 透明→透明,全部链上确认 - [x] **多账户共库**:acct0/1/2 同一个库,扫一遍服务全部账户 **未验证 —— 别把这些当成能用** @@ -204,13 +191,14 @@ rewindTo(height) 回退重扫(破坏性) transactionHistory(uuid, limit, offset) 分页历史,limit 上限 500 transactionDetails(uuid, txid) 单笔详情,查不到返回 "null" -deleteWallet(dbName) 擦掉本地缓存库(可重建),删账户/故障重置用 +deleteWallet(dbName) 擦掉本地缓存库(可重建),最后一个账户移除/App 重置用 pcztQuote(...) 只报价,不建交易、不锁 note pcztCreate(...) → { pcztHex, reservationId } 构造并锁住选中的 note releaseReservation(id) 用户取消时放开锁,幂等 -pcztProve(pczt, circuitVersion) → keys.pcztSign → pcztSend(pczt, reservationId) → txid -broadcastTransaction(txid) 真正发出去(pcztSend 只落库,不发网络) +pcztProve(pczt, circuitVersion) → keys.pcztSign → pcztSubmit(uuid, pczt, reservationId) + 先广播;节点明确拒收则不落库、note 放回,否则落库 +broadcastTransaction(txid) 重播已落库的交易(同步循环用) selfCheck(network, dbName) / dependencyVersions() ``` @@ -231,14 +219,12 @@ keysDependencyVersions() runtime.pcztCreate() 构造(要钱包 DB:选币、witness、anchor) runtime.pcztProve() 零知识证明(慢,要建 halo2 电路) keys.pcztSign() 签名(要种子;在另一个包里) -runtime.pcztSend() 终结 + 写回本地钱包,返回 txid(**不发网络**) -runtime.broadcastTransaction(txid) 真正广播(不可逆) +runtime.pcztSubmit() 终结 + 广播;未被拒才写回本地钱包,返回 {txid, broadcast} ``` **顺序不能换**:证明必须在签名之前 —— 上游 Signer 需要能验证证明覆盖的是正确数据。 -广播是独立的一步,这样宿主能在落库之后、发出去之前插入确认环节, -也能在广播失败时原样重试而不用重建交易。 -节点拒绝抛 `BROADCAST_REJECTED`(别重试,先查原因),网络故障抛 `NETWORK_ERROR`(可重试)。 +先广播后落库:节点明确拒收(含首次提交时的「输入已花」)返回 `rejected`, +什么都不记、note 立即放回;网络不确定返回 `unknown`,照样落库,由同步循环重播原字节。 `already known` / `already in mempool` / `already in blockchain` 视为幂等成功;所有触网调用 都有 30 秒上限,避免 gRPC-web 静默挂起。 diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml index b4ccb8188..034670e5e 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml @@ -18,7 +18,7 @@ crate-type = ["cdylib", "rlib"] zcash_keys.workspace = true zcash_protocol.workspace = true zcash_address.workspace = true -zcash_primitives = { workspace = true, features = ["transparent-inputs"] } +zcash_primitives = { workspace = true, features = ["transparent-inputs", "non-standard-fees"] } zip32 = "0.2" bs58 = { version = "0.5", features = ["check"] } zeroize = { version = "1", features = ["zeroize_derive"] } diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md index e9da957e2..965b7535e 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md @@ -1,6 +1,6 @@ # Stateless transparent transaction API -This crate can quote and sign a mainnet transparent-to-transparent transaction without a +This crate can quote and sign a mainnet transaction that spends transparent funds without a `WalletDb`, scanner, or network client. The host owns UTXO discovery, reservation, broadcast, and status reconciliation. @@ -53,8 +53,10 @@ Amounts are decimal strings because JavaScript numbers cannot represent every va Only selected outpoints are spent. Every selection must resolve to exactly one supplied UTXO. Inputs must be confirmed, non-coinbase P2PKH coins controlled by their declared external or internal -BIP-44 path. Recipient outputs may be mainnet P2PKH (`t1`) or P2SH (`t3`). Change must be an owned -P2PKH address on internal scope `1`. +BIP-44 path. Recipients may be mainnet P2PKH (`t1`), P2SH (`t3`), a ZIP-320 TEX address (`tex1`, +paid as P2PKH), or a Unified Address with an +Orchard receiver, which is paid an Ironwood note; a Unified Address without one is rejected rather +than paid at a public receiver. Change must be an owned P2PKH address on internal scope `1`. For send-max, supply exactly one recipient and omit `amountZat` and `change`. The recipient receives the selected input total minus the ZIP-317 fee. For a fixed amount, change below the standard 5,000 diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs index 8efe88ded..194f5c5cc 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs @@ -34,7 +34,7 @@ pub(crate) fn supported_recipient( return None; } match Address::decode(params, encoded)? { - address @ Address::Transparent(_) => Some(address), + address @ (Address::Transparent(_) | Address::Tex(_)) => Some(address), Address::Unified(address) if address.has_orchard() => Some(Address::Unified(address)), _ => None, } diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs index 819cf2c8d..9c004d28c 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs @@ -1189,6 +1189,27 @@ mod tests { assert_eq!(error.code, ErrorCode::InvalidDerivationPath); } + #[test] + fn pays_a_tex_address_like_its_p2pkh_twin() { + let hash = [9u8; 20]; + let mut request: serde_json::Value = + serde_json::from_str(&request_json(&[100_000], true)).unwrap(); + request["recipients"][0]["address"] = TransparentAddress::PublicKeyHash(hash) + .to_zcash_address(NetworkType::Main) + .to_string() + .into(); + let via_t1 = build_with_seed_json(&request.to_string(), &seed()).unwrap(); + request["recipients"][0]["address"] = + ::from_tex( + NetworkType::Main, + hash, + ) + .encode() + .into(); + let via_tex = build_with_seed_json(&request.to_string(), &seed()).unwrap(); + assert_eq!(via_tex, via_t1); + } + #[test] fn builds_deterministic_v6_transaction() { let raw = build_with_seed_json(&request_json(&[100_000], true), &seed()).unwrap(); @@ -1217,6 +1238,11 @@ fn require_transparent(address: RecipientAddress) -> Result fn parse_recipient_address(encoded: &str) -> Result { match crate::keys::supported_recipient(&MAIN_NETWORK, encoded) { Some(Address::Transparent(address)) => Ok(RecipientAddress::Transparent(address)), + // ZIP-320: a TEX address is a P2PKH hash that only accepts transparent + // inputs, which is all this builder spends. + Some(Address::Tex(hash)) => Ok(RecipientAddress::Transparent( + TransparentAddress::PublicKeyHash(hash), + )), // Unified Orchard receivers receive Ironwood notes after NU6.3. Never silently // fall back to a public receiver when a Unified Address lacks this receiver. Some(Address::Unified(address)) => address diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs index 712072298..39dabff58 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs @@ -11,6 +11,7 @@ use pczt::roles::{ }; use zcash_note_encryption::Domain; use zcash_primitives::transaction::builder::{BuildConfig, Builder, BundlePadding}; +use zcash_primitives::transaction::fees::fixed::FeeRule as FixedFeeRule; use zcash_protocol::memo::MemoBytes; /// 本模块实际提供的入口。定义在实现旁边,删改实现必然改到这里。 @@ -100,8 +101,11 @@ fn create_with_public_key(plan: &TransactionPlan, key: &AccountPubKey) -> Result .add_transparent_output(&address, output.value) .map_err(failure)?; } + // The plan's fee, not a recomputed ZIP-317 one: change below the dust + // threshold is folded into the fee at quote time, and the ZIP-317 rule + // rejects that surplus as ChangeRequired after the user has approved it. let parts = builder - .build_for_pczt(rand::rngs::OsRng, &Zip317FeeRule::standard()) + .build_for_pczt(rand::rngs::OsRng, &FixedFeeRule::non_standard(plan.fee)) .map_err(failure)?; let pczt = Creator::build_from_parts(parts.pczt_parts) .ok_or_else(|| KeysError::new(ErrorCode::TransactionBuildFailed))?; @@ -659,6 +663,38 @@ mod tests { .unwrap() } + // Regression: 100000 in, 83000/88000 out leaves change under the dust + // threshold, which the quote folds into the fee. Building used to redo the + // fee by ZIP-317 and fail with ChangeRequired after the user approved it. + #[test] + fn a_quote_with_sub_dust_change_folded_into_the_fee_still_builds() { + let fingerprint = "00".repeat(32); + let cases = [ + (recipient(0), "83000", false), + ( + transparent_address(0, 9) + .to_zcash_address(NetworkType::Main) + .to_string(), + "88000", + true, + ), + ]; + for (to, amount, hardware) in cases { + let mut request = request(false); + request["recipients"] = json!([{ "address": to, "amountZat": amount }]); + let request = request.to_string(); + let quote: Value = serde_json::from_str("e_json(&request).unwrap()).unwrap(); + let folded = 100_000 - amount.parse::().unwrap(); + assert_eq!(quote["feeZat"], folded.to_string(), "零头应当并进手续费"); + if hardware { + create_with_account_xpub(&request, &account_xpub(), &fingerprint) + .expect("硬件路径按报价的手续费构造"); + } else { + create(&request, &SEED).expect("软件路径按报价的手续费构造"); + } + } + } + #[test] fn hardware_metadata_matches_each_external_output_after_action_randomization() { let mut request = request(false); diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml index 5fd39219d..8058c55f9 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml @@ -71,7 +71,7 @@ tonic-web-wasm-client.workspace = true # 本 crate 不直接用 time —— 打开它只为传递 feature。zcash_client_backend 记 # `created` 时绕过注入的 Clock,直接调 time::OffsetDateTime::now_utc();不开这个 # feature 它就落到 SystemTime::now(),而 wasm32-unknown-unknown 上 std 没有时间源, -# 于是 pcztSend 落库时 panic("time not implemented on this platform")。 +# 于是 pcztSubmit 落库时 panic("time not implemented on this platform")。 time = { version = "0.3", features = ["wasm-bindgen"] } [dev-dependencies] diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs index b35a95a9a..a6ff22633 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs @@ -241,6 +241,18 @@ pub async fn remove_account(account_uuid: String) -> Result<(), JsValue> { Ok(()) } +/// 宿主已经删掉这个账户:有没有在途交易都清掉,不做 `removeAccount` 的空闲检查。 +/// +/// 钱在链上、助记词在用户手里,重新导入扫链就能找回;在途交易留着只会让一个 +/// 已删的账户继续占着库。 +#[wasm_bindgen(js_name = removeDeletedAccount)] +pub async fn remove_deleted_account(account_uuid: String) -> Result<(), JsValue> { + runtime::with_db(|db| account::remove_account(db, &account_uuid))?; + send::forget_account_reservations(&account_uuid); + storage::durability_barrier().await?; + Ok(()) +} + /// 按 UFVK 定位这个库里的账户,返回 `{ uuid }`,找不到返回 `"null"`。 /// /// 共享库(每 network 一份,装全部钱包的全部账户)下,这是定位账户的唯一 @@ -327,32 +339,6 @@ pub async fn sync_tip() -> Result { ) } -/// 用宿主给的快照刷新账户的透明 UTXO。**必须单独调**。 -/// -/// 扫区块只产出屏蔽 note;透明 UTXO 在链上是公开的,由宿主的后端索引器提供 —— -/// 运行时不自己去查,透明侧只有一个事实来源。不调的后果是静默的:隐私转账 -/// 想花透明输入时选不到钱,而扫链看起来一切正常。 -/// -/// `utxos_json` 是 `HostTransparentUtxo` 数组: -/// `[{ txid, vout, valueZat, scriptPubKey, height }]`。归属由脚本反解的地址 -/// 决定,不属于本账户的条目会被丢掉。 -#[wasm_bindgen(js_name = syncTransparentUtxos)] -pub async fn sync_transparent_utxos( - account_uuid: String, - utxos_json: String, -) -> Result { - let utxos: Vec = serde_json::from_str(&utxos_json) - .map_err(|e| RuntimeError::new(ErrorCode::InvalidTransparentUtxos).detail(e.to_string()))?; - Ok( - runtime::with_db_and_client(move |mut db, mut client| async move { - let r = - sync::refresh_transparent_utxos(&mut db, &mut client, &account_uuid, &utxos).await; - (db, client, r) - }) - .await?, - ) -} - /// 只读查看待扫区间,**不发网络请求**。返回 /// `{ ranges: [{ start, end, len, priority }], totalBlocks }`。 /// @@ -391,7 +377,6 @@ pub fn pczt_quote( untrusted: u32, fallback_change_pool: String, pad_orchard_bundle: bool, - spend_transparent: Option, allow_zero_conf_shielding: Option, spend_source: Option, ) -> Result { @@ -402,7 +387,6 @@ pub fn pczt_quote( untrusted, &fallback_change_pool, pad_orchard_bundle, - spend_transparent, allow_zero_conf_shielding, spend_source.as_deref(), )?; @@ -535,10 +519,10 @@ pub fn queue_rescan_from(from_height: u32) -> Result { // ── 发送 ──────────────────────────────────────────────────────────────── // -// 完整流程:pcztCreate → pcztProve → (keys 包)pcztSign → pcztSend +// 完整流程:pcztCreate → pcztProve → (keys 包)pcztSign → pcztSubmit // // 证明在签名之前还是之后都可以(两者作用于 PCZT 的不同部分), -// 但**都必须在 pcztSend 之前完成**,否则交易无效。 +// 但**都必须在 pcztSubmit 之前完成**,否则交易无效。 /// 构造一笔转账的 PCZT(未证明、未签名),返回字节。 /// @@ -556,7 +540,6 @@ pub fn pczt_create( pad_orchard_bundle: bool, lock_for_blocks: u32, reservation_id: Option, - spend_transparent: Option, allow_zero_conf_shielding: Option, spend_source: Option, ) -> Result { @@ -565,7 +548,6 @@ pub fn pczt_create( untrusted, &fallback_change_pool, pad_orchard_bundle, - spend_transparent, allow_zero_conf_shielding, spend_source.as_deref(), )?; @@ -589,7 +571,7 @@ pub fn pczt_create( })?) } -/// 生成 Orchard / Ironwood 零知识证明。**必须在 pcztSend 之前做**。 +/// 生成 Orchard / Ironwood 零知识证明。**必须在 pcztSubmit 之前做**。 #[wasm_bindgen(js_name = pcztProve)] pub fn pczt_prove(pczt_bytes: Vec) -> Result, JsValue> { Ok(runtime::with_db(|db| send::prove_pczt(db, &pczt_bytes))?) @@ -643,7 +625,7 @@ pub fn release_reservation(reservation_id: String) -> Result { /// 在一件**已经不可逆地发生了**的事情之后做落盘屏障。 /// /// 屏障失败的含义是「持久化有没有到达耐久存储未知」,不是「这件事失败了」。 -/// 两个调用点都已越过不可逆点 —— `pcztSend` 已提交交易并交出 note, +/// 两个调用点都已越过不可逆点 —— `pcztSubmit` 已提交交易并交出 note, /// `broadcastTransaction` 已把交易发上网。把真实结局换成一个泛化的存储错误, /// 宿主就会去重试、或者把一笔已上链的交易显示成「未知失败」。 /// @@ -654,27 +636,49 @@ async fn barrier_after_irreversible(params: serde_json::Value) -> Result<(), cra }) } -/// 终结已证明且已签名的 PCZT,提取交易并**写回本地钱包**,返回 txid。 +/// 提交已证明且已签名的 PCZT:提取交易、广播,再按结局决定落不落库。 /// -/// **这一步不发网络。** 交易还没有广播出去,必须再调 `broadcastTransaction(txid)`。 -/// 两步分开,是为了让宿主能在落库之后、真正发出去之前插入确认环节, -/// 也能在广播失败时原样重试而不必重建交易。 -#[wasm_bindgen(js_name = pcztSend)] -pub async fn pczt_send( +/// 返回 `{ txid, broadcast: "accepted" | "rejected" | "unknown", error? }`。 +/// 节点明确拒收时交易不落库、note 立即放回;结局未知时已落库,同步会重播。 +#[wasm_bindgen(js_name = pcztSubmit)] +pub async fn pczt_submit( account_uuid: String, pczt_bytes: Vec, reservation_id: String, ) -> Result { - let txid = runtime::with_db(|db| { - send::extract_and_store(db, &account_uuid, &pczt_bytes, &reservation_id) - })?; - // Once extract_and_store commits, the transaction itself owns the spent - // notes. Drop the proposal before the durability barrier: a barrier error - // means the host does not know whether persistence reached durable storage, - // but it must never be allowed to unlock inputs that may already be spent. - send::forget_reservation(&reservation_id); - barrier_after_irreversible(serde_json::json!({ "operation": "finalizeTransaction" })).await?; - Ok(txid) + let outcome = runtime::with_db_and_client(move |mut db, mut client| async move { + let r = send::submit_signed_pczt( + &mut db, + &mut client, + &account_uuid, + &pczt_bytes, + &reservation_id, + ) + .await; + (db, client, r) + }) + .await?; + let json = match outcome { + send::SubmitOutcome::Accepted { txid } => { + serde_json::json!({ "txid": txid, "broadcast": "accepted" }) + } + send::SubmitOutcome::Rejected { txid, error } => { + // 没落库,也就没有需要落盘屏障的东西。 + return Ok(serde_json::json!({ + "txid": txid, + "broadcast": "rejected", + "error": error.to_json(), + }) + .to_string()); + } + send::SubmitOutcome::Unknown { txid, error } => serde_json::json!({ + "txid": txid, + "broadcast": "unknown", + "error": error.to_json(), + }), + }; + barrier_after_irreversible(json.clone()).await?; + Ok(json.to_string()) } /// Runtime-owned unresolved broadcast intents for this account. The host uses @@ -705,7 +709,7 @@ pub fn rebroadcastable_txids(account_uuid: String) -> Result { })?) } -/// 把 `pcztSend` 落库的交易广播到 lightwalletd。**不可逆。** +/// 重播已落库、结局未知的交易(同步时调用)。**不可逆。** /// /// 节点拒绝抛 `BROADCAST_REJECTED`(不要重试,先查原因); /// 网络本身出错抛 `NETWORK_ERROR`(可以重试,交易已在本地库里)。 @@ -762,7 +766,10 @@ pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> { /// 删除一个钱包库(连同 IndexedDB 里的字节)。**不可逆。** /// /// 库是纯派生缓存:UFVK 与 birthday 由宿主保管,不在库里,所以删掉只是要重扫。 -/// 用途一是出问题时手动重置,用途二是删账户时清掉已解密的屏蔽历史。 +/// 用途一是最后一个账户移除后删文件,用途二是 App 重置。 +/// +/// 不检查在途交易:两个用途都必须删成,交易本身已在链上或会过期。 +/// 需要等交易落定的操作(暂停、重置缓存)由宿主在调用前自己判断。 /// /// 若删的正是当前打开的库,会先自动关闭 —— 底层要求删除前库必须已关闭。 /// 返回 `true` 表示确实删掉了,`false` 表示本来就不存在(不算错误)。 @@ -771,29 +778,7 @@ pub async fn delete_wallet(db_name: String) -> Result { if !storage::database_exists(&db_name).await? { return Ok(false); } - let is_open = runtime::open_db_name().as_deref() == Some(db_name.as_str()); - // 闸门要在关库之前读,而且按整库判:库里装着全部钱包的全部账户。 - // - // 读不出来就放行。这个接口的用途之一就是「库坏了,重置」,让一条查不动 - // 的 SQL 把修复入口也锁死,比漏判一笔在途交易更糟 —— 而库都读不了的时候, - // 那笔交易的状态本来也已经取不回来了。 - let idle = if is_open { - runtime::with_read_conn(|conn| { - guard::assert_idle(conn, None, "deleteWallet", guard::LockPolicy::Blocking) - }) - } else { - storage::open_connection(&db_name).and_then(|conn| { - guard::assert_idle(&conn, None, "deleteWallet", guard::LockPolicy::Blocking) - }) - }; - match idle { - Ok(()) => {} - Err(e) if e.code == ErrorCode::WalletBusy => return Err(e.into()), - Err(e) => { - tracing::warn!("deleteWallet idle check unreadable, deleting anyway: {e}"); - } - } - if is_open { + if runtime::open_db_name().as_deref() == Some(db_name.as_str()) { runtime::close()?; } Ok(storage::delete_database(&db_name).await?) @@ -831,7 +816,6 @@ pub fn database_health() -> Result { /// 诊断:数一份 PCZT 里各 bundle 有多少输入。 /// /// 用来回答「这笔钱是从哪个池出去的」——费用差只能间接推断,输入个数是直接证据。 -/// 判断 `spendTransparent` 会不会让一笔本可全屏蔽的交易混进公开输入,靠的就是它。 #[wasm_bindgen(js_name = diagPcztInputCounts)] pub fn pczt_input_counts(pczt_bytes: Vec) -> Result { let pczt = pczt::Pczt::parse(&pczt_bytes).map_err(|e| { diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs index 0ddf84e02..e9b6d8c6e 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs @@ -77,20 +77,6 @@ pub enum ErrorCode { /// 屏蔽余额不足,但透明余额本可补上 —— 钱在,只是在透明池里。 /// /// 与 `InsufficientFunds` 分开,是因为对用户来说这两件事完全不同: - /// 一个是「钱不够」,一个是「钱够但要先屏蔽」。合成一个码的话,宿主只能 - /// 显示「余额不足」,而用户明明看着账上有钱 —— 那种提示只会让人去猜。 - /// - /// 参数:`{ requiredZat, shieldedAvailableZat, shortfallZat, - /// transparentZat, transparentCoinbaseZat }` - FundsNeedShielding, - /// 差额只有 coinbase 输出能补上,而本钱包花不了 coinbase。 - /// - /// 转账用 `NonCoinbase`、屏蔽用 `NonCoinbaseOnly`,两条路都绕开它 —— - /// 矿工场景不在目标内。所以这笔钱在本钱包里**没有任何出口**, - /// 告诉用户「先屏蔽」等于把人往死路上指:屏蔽同样碰不到它。 - /// - /// 参数同 `FundsNeedShielding`。 - CoinbaseFundsUnspendable, // ── 外部依赖 ── /// lightwalletd 网络错误。参数:`{ operation }` @@ -119,8 +105,6 @@ pub enum ErrorCode { InvalidReservationId, /// txid 格式不合法(不是 64 位 hex)。参数:`{ value }` 或 `{ value, byteLen }` InvalidTxid, - /// 宿主喂进来的透明 UTXO 快照解析失败。`detail` 里是 serde 的原文。 - InvalidTransparentUtxos, /// PCZT 解析或序列化失败。参数:`{ stage }` PcztError, /// 交易构造失败(选币、费用、anchor 等)。参数:`{ stage }` @@ -131,6 +115,10 @@ pub enum ErrorCode { /// 重发同一笔只会再被拒一次。宿主该做的是查明原因(费用不足、双花、 /// 共识分支不对),而不是退避重试。 BroadcastRejected, + /// 节点回了拒绝,但原因同样可能是「这笔交易已经上链/在池里」(双花、重复 + /// nullifier、找不到输入)。不能判拒绝:交易保持待确认,由扫链见到上链或过期来定。 + /// 参数:`{ errorCode }`,`detail` 里是节点原文。 + BroadcastOutcomeUnknown, /// 本地交易没有持久化的广播授权。参数:`{ txid }`。 BroadcastIntentNotFound, /// 广播授权存在,但当前状态不允许广播。参数:`{ txid, state }`。 @@ -163,8 +151,6 @@ impl ErrorCode { AccountNotFound => "ACCOUNT_NOT_FOUND", NotSynced => "NOT_SYNCED", InsufficientFunds => "INSUFFICIENT_FUNDS", - FundsNeedShielding => "FUNDS_NEED_SHIELDING", - CoinbaseFundsUnspendable => "COINBASE_FUNDS_UNSPENDABLE", NetworkError => "NETWORK_ERROR", DatabaseError => "DATABASE_ERROR", ReorgDetected => "REORG_DETECTED", @@ -173,10 +159,10 @@ impl ErrorCode { NoActiveAccounts => "NO_ACTIVE_ACCOUNTS", InvalidReservationId => "INVALID_RESERVATION_ID", InvalidTxid => "INVALID_TXID", - InvalidTransparentUtxos => "INVALID_TRANSPARENT_UTXOS", PcztError => "PCZT_ERROR", TransactionBuildError => "TRANSACTION_BUILD_ERROR", BroadcastRejected => "BROADCAST_REJECTED", + BroadcastOutcomeUnknown => "BROADCAST_OUTCOME_UNKNOWN", BroadcastIntentNotFound => "BROADCAST_INTENT_NOT_FOUND", BroadcastIntentNotReady => "BROADCAST_INTENT_NOT_READY", FinalizeOutcomeUnknown => "FINALIZE_OUTCOME_UNKNOWN", @@ -331,13 +317,11 @@ mod tests { PcztError, TransactionBuildError, BroadcastRejected, + BroadcastOutcomeUnknown, Unimplemented, - FundsNeedShielding, - CoinbaseFundsUnspendable, ReorgDetected, WalletBusy, InvalidScanPriority, - InvalidTransparentUtxos, BroadcastIntentNotFound, BroadcastIntentNotReady, FinalizeOutcomeUnknown, diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs index c654d3ff9..d787a083c 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs @@ -109,7 +109,8 @@ const HISTORY_ROW_SELECT: &str = "SELECT FROM v_tx_outputs output WHERE output.txid = tx_summary.txid AND output.from_account_uuid = tx_summary.account_uuid - AND output.to_account_uuid IS NULL + AND (output.to_account_uuid IS NULL + OR output.to_account_uuid <> tx_summary.account_uuid) AND COALESCE(output.is_change, 0) = 0 LIMIT 1) ) AS recipient, @@ -117,7 +118,8 @@ const HISTORY_ROW_SELECT: &str = "SELECT FROM v_tx_outputs output WHERE output.txid = tx_summary.txid AND output.from_account_uuid = tx_summary.account_uuid - AND output.to_account_uuid IS NULL + AND (output.to_account_uuid IS NULL + OR output.to_account_uuid <> tx_summary.account_uuid) AND COALESCE(output.is_change, 0) = 0 ) AS external_output_count FROM v_transactions tx_summary @@ -298,8 +300,9 @@ pub fn details(conn: &rusqlite::Connection, account_uuid: &str, txid: &str) -> R /// 官方 SDK 取交易详情走的也是它。三段的判定规则: /// /// - `received`:`to_account_uuid` 是本账户(`is_change` 区分找零与真收款) -/// - `external`:`from_account_uuid` 是本账户、而 `to_account_uuid` 为空 —— -/// 即我们付给别人的输出。**只有自己发的交易才看得到收款地址**, +/// - `external`: sent by this account to an unknown or different account, +/// including another account registered in this wallet database. +/// **只有自己发的交易才看得到收款地址**, /// 别人发给别人的输出我们既解不开也不该出现在这里 /// - `spent`:本账户在更早交易里收到、且被这笔花掉的输出,走 `v_received_output_spends` /// @@ -439,14 +442,10 @@ pub(crate) fn display_order_to_internal(txid: &str) -> Result> { Ok(bytes.into_iter().rev().collect()) } +// Byte slicing a `&str` panics on a non-ASCII boundary, and in wasm a panic +// traps the whole runtime; `hex::decode` rejects such input instead. fn hex_decode(s: &str) -> Option> { - if s.len() % 2 != 0 { - return None; - } - (0..s.len()) - .step_by(2) - .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok()) - .collect() + hex::decode(s).ok() } /// txid 在库里以内部序(小端)存储,浏览器展示用大端。翻转后转 hex。 @@ -464,6 +463,12 @@ mod tests { use super::*; use crate::clock::HostClock; + #[test] + fn a_non_ascii_txid_is_rejected_not_a_panic() { + // Four bytes, but byte 2 falls inside "é": slicing there panics. + assert!(display_order_to_internal("aéa").is_err()); + } + #[test] fn txid_is_reversed_for_display() { assert_eq!(hex_display_order(&[0x01, 0x02, 0x03]), "030201"); @@ -502,8 +507,7 @@ mod tests { ); } - #[test] - fn preserves_supported_pool_ids_and_hides_sapling() { + fn history_fixture() -> rusqlite::Connection { let conn = rusqlite::Connection::open_in_memory().unwrap(); conn.execute_batch( "CREATE TABLE accounts (id INTEGER PRIMARY KEY, uuid BLOB NOT NULL); @@ -558,6 +562,12 @@ mod tests { ) .unwrap(); + conn + } + + #[test] + fn preserves_supported_pool_ids_and_hides_sapling() { + let conn = history_fixture(); let account_uuid = uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap(); conn.execute( "INSERT INTO accounts (id, uuid) VALUES (1, ?1)", @@ -665,4 +675,80 @@ mod tests { json!({ "3": "-100", "4": "99" }) ); } + #[test] + fn outgoing_outputs_are_external_relative_to_the_current_account() { + let conn = history_fixture(); + let sender = uuid::Uuid::from_u128(1); + let receiver = uuid::Uuid::from_u128(2); + for (id, account) in [(1, sender), (2, receiver)] { + conn.execute( + "INSERT INTO accounts (id, uuid) VALUES (?1, ?2)", + rusqlite::params![id, account.as_bytes().as_slice()], + ) + .unwrap(); + } + + let cases = [ + (Some(receiver), false, 1), + (None, false, 1), + (Some(sender), false, 0), + (Some(sender), true, 0), + ]; + for (index, (to_account, is_change, external_count)) in cases.into_iter().enumerate() { + let id = index as i64 + 1; + let txid = vec![id as u8; 32]; + conn.execute( + "INSERT INTO transactions (id_tx, txid) VALUES (?1, ?2)", + rusqlite::params![id, txid], + ) + .unwrap(); + conn.execute( + "INSERT INTO v_transactions ( + account_uuid, mined_height, txid, tx_index, block_time, + expiry_height, expired_unmined, fee_paid, + account_balance_delta, has_change, sent_note_count, + received_note_count, memo_count, is_shielding, total_spent, + total_received + ) VALUES (?1, 100, ?2, ?3, 1000, 200, 0, 10, -90, 1, 2, 1, 0, 0, 100, 10)", + rusqlite::params![sender.as_bytes().as_slice(), txid, id], + ) + .unwrap(); + conn.execute( + "INSERT INTO v_received_outputs ( + id_within_pool_table, transaction_id, account_id, pool, value + ) VALUES (?1, ?1, 1, 3, 10)", + [id], + ) + .unwrap(); + conn.execute( + "INSERT INTO v_tx_outputs ( + txid, from_account_uuid, to_account_uuid, to_address, is_change + ) VALUES (?1, ?2, ?3, 'synthetic-recipient', ?4)", + rusqlite::params![ + txid, + sender.as_bytes().as_slice(), + to_account.map(|account| account.as_bytes().to_vec()), + is_change + ], + ) + .unwrap(); + + let detail: serde_json::Value = serde_json::from_str( + &details(&conn, &sender.to_string(), &hex_display_order(&txid)).unwrap(), + ) + .unwrap(); + assert_eq!(detail["externalOutputCount"], external_count); + assert_eq!( + detail["recipient"], + if external_count > 0 { + json!("synthetic-recipient") + } else { + json!(null) + } + ); + let rows: Vec = + serde_json::from_str(&list(&conn, &sender.to_string(), 20, 0).unwrap()).unwrap(); + assert_eq!(rows[0], detail); + } + } } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs index bbf27667e..36d81361d 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs @@ -181,8 +181,13 @@ pub async fn broadcast(client: &mut LightClient, tx_bytes: Vec) -> Result<() if broadcast_already_known(&resp.error_message) { return Ok(()); } + let code = if broadcast_outcome_ambiguous(&resp.error_message) { + ErrorCode::BroadcastOutcomeUnknown + } else { + ErrorCode::BroadcastRejected + }; return Err(RuntimeError::with( - ErrorCode::BroadcastRejected, + code, json!({ "errorCode": resp.error_code, "errorMessage": resp.error_message, @@ -193,6 +198,27 @@ pub async fn broadcast(client: &mut LightClient, tx_bytes: Vec) -> Result<() Ok(()) } +/// A rejection that a node also gives for a transaction it already mined or +/// holds: its inputs are spent, possibly by this very transaction. Marking it +/// rejected would show a failed send for a payment that went through. +fn broadcast_outcome_ambiguous(message: &str) -> bool { + let message = message.to_lowercase(); + [ + // Zebra: zebra-consensus / zebrad mempool errors. + "double-spend", + "duplicate nullifier", + "could not find transparent input utxo", + "same effects", + // zcashd. + "bad-txns-inputs-spent", + "bad-txns-inputs-missingorspent", + "txn-mempool-conflict", + "missing inputs", + ] + .iter() + .any(|needle| message.contains(needle)) +} + fn broadcast_already_known(message: &str) -> bool { let message = message.to_lowercase(); [ @@ -201,6 +227,9 @@ fn broadcast_already_known(message: &str) -> bool { "already in blockchain", "already have transaction", "txn-already-known", + // Zebra (behind Zaino): zebrad mempool::error. + "already exists in mempool", + "already queued for download", ] .iter() .any(|needle| message.contains(needle)) @@ -303,15 +332,43 @@ pub async fn tree_state(client: &mut LightClient, height: u32) -> Result Option { impl Drop for Span { fn drop(&mut self) { let ms = now_ms() - self.started_ms; - log(&format!("[PRIV-PERF] rt {} {{\"ms\":{}}}", self.name, ms.round())); + log(&format!( + "[PRIV-PERF] rt {} {{\"ms\":{}}}", + self.name, + ms.round() + )); } } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs index 175a68866..17752032e 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs @@ -122,6 +122,19 @@ fn not_open() -> RuntimeError { RuntimeError::new(ErrorCode::WalletNotOpen) } +/// 库不在手上时说清楚是哪种:被一次异步操作借走(稍后重试即可)还是真没开 +/// (宿主要重开)。混成 NOT_OPEN 会让宿主在扫链途中把一个好好的钱包重开一遍。 +fn db_unavailable(operation: &str) -> RuntimeError { + if BUSY.with(Cell::get) { + RuntimeError::with( + ErrorCode::WalletBusy, + serde_json::json!({ "operation": operation }), + ) + } else { + not_open() + } +} + fn no_client() -> RuntimeError { RuntimeError::new(ErrorCode::LightwalletdNotConfigured) } @@ -153,7 +166,9 @@ pub fn set_client(client: LightClient) { /// 用「取出 → 使用 → 放回」而不是长期持有 `RefCell` 借用, /// 这样即便 `f` 里再次进入本模块也不会 panic。 pub fn with_db(f: impl FnOnce(&mut Db) -> Result) -> Result { - let mut db = DB.with(|c| c.borrow_mut().take()).ok_or_else(not_open)?; + let mut db = DB + .with(|c| c.borrow_mut().take()) + .ok_or_else(|| db_unavailable("walletRead"))?; let out = f(&mut db); DB.with(|c| *c.borrow_mut() = Some(db)); out diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs index 3a33d6d5f..8efdbdaaf 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs @@ -6,7 +6,7 @@ //! runtime.pcztCreate() 构造(要钱包状态:选币、witness、anchor) //! runtime.pcztProve() 证明,纯计算,不碰私钥 //! keys.pcztSign() 签名(要花费密钥,在 onekey-zcash-keys 里) -//! runtime.pcztSend() 终结 + 写回本地钱包(**不发网络**) +//! runtime.pcztSubmit() 提取 + 广播,非明确拒收才写回本地钱包 //! runtime.broadcastTransaction() 真正广播出去 //! ``` //! @@ -104,81 +104,6 @@ where } } -/// 把「余额不足」补成「钱在透明池里,先屏蔽」。 -/// -/// 普通转账不花透明 UTXO(见 `SendPolicy::spend_transparent`),所以一个只有 -/// 透明余额的账户拿到的原始错误是 `INSUFFICIENT_FUNDS { availableZat: 0 }` —— -/// 而用户正看着账上有钱。那个 0 说的是「屏蔽池里可花的」,但错误里没有任何 -/// 东西提到池,用户只能去猜。 -/// -/// 这里查一次余额,把差额和透明余额一起放进错误。查询失败就原样返回原错误: -/// 补充信息拿不到不该让整个操作换一个错因。 -fn explain_insufficient( - db: &Db, - account_id: ::AccountId, - confirmations: zcash_client_backend::data_api::wallet::ConfirmationsPolicy, - err: RuntimeError, -) -> RuntimeError { - if err.code != ErrorCode::InsufficientFunds { - return err; - } - - // 必须用**这笔发送实际用的**确认数策略读余额,不能用 default()。 - // 这个函数存在的唯一目的就是给准确指引,而两套门槛下「透明池里有多少钱 - // 可用」的答案不一样 —— 用另一套读出来的数会把人指去屏蔽,结果还是不够。 - // 本文件 `allow_zero_conf_shielding` 的注释早写了这条:读和花必须同源。 - let Ok(Some(summary)) = db.get_wallet_summary(confirmations) else { - return err; - }; - let Some(balances) = summary.account_balances().get(&account_id) else { - return err; - }; - - let regular = u64::from(balances.unshielded_regular_balance().total()); - let coinbase = u64::from(balances.unshielded_coinbase_balance().total()); - - // 透明池为空时也要走完下面这段。早退会让同一个错误码出现两种形状 —— - // 空账户拿到上游原始的 `availableZat`,有钱的账户拿到补全过的字段, - // 宿主得写两套解析,而两者的差别恰恰是最难在测试里注意到的。 - let num = |k: &str| err.params.get(k).and_then(|v| v.as_u64()); - let shortfall = num("shortfallZat").unwrap_or(0); - - // 三种结局要分开,因为用户该做的事完全不同: - // - // - 普通透明余额补得上:这次没花它(宿主把 spendTransparent 关了), - // 出路是屏蔽,或者允许花透明。 - // - 只有 coinbase 补得上:本钱包**没有任何出口** —— 转账走 NonCoinbase、 - // 屏蔽走 NonCoinbaseOnly,两条都绕开它。这时说「先屏蔽」是把人往死路指。 - // - 都补不上:就是钱不够,但仍要把各池余额报全,用户才不用自己去对 - // 为什么账上的数和错误里的数对不上。 - // shortfall 为 0 时说明缺口读不出来(上游没给这个字段),无从判断哪种情形, - // 保持原样比猜一个更好 —— 否则 `0 >= 0` 会把它误判成「先屏蔽」。 - let code = if shortfall == 0 { - ErrorCode::InsufficientFunds - } else if regular >= shortfall { - ErrorCode::FundsNeedShielding - } else if regular + coinbase >= shortfall { - ErrorCode::CoinbaseFundsUnspendable - } else { - ErrorCode::InsufficientFunds - }; - - RuntimeError::with( - code, - json!({ - "stage": err.params.get("stage").cloned(), - "requiredZat": num("requiredZat"), - "shieldedAvailableZat": num("availableZat"), - "shortfallZat": shortfall, - "transparentZat": regular, - // coinbase 单列:成熟规则不同,而且只能走专门的 coinbase 屏蔽路径, - // 宿主的屏蔽碰不到它。并成一个数的话,用户会照着提示去点屏蔽, - // 然后发现钱没动。 - "transparentCoinbaseZat": coinbase, - }), - ) -} - /// 解析宿主传来的找零池名。构造与报价共用,避免两处各写一份而写歪。 pub fn parse_change_pool(name: &str) -> Result { match name { @@ -224,14 +149,6 @@ pub struct SendPolicy { /// 是否给 Orchard bundle 填充到固定 action 数(隐藏真实 action 数量, /// 代价是交易更大、费用更高)。 pub pad_orchard_bundle: bool, - /// 普通转账允不允许花透明 UTXO。 - /// - /// **这是隐私策略,由宿主决定。** 花透明输入会把被选中的透明地址在链上 - /// 关联起来;上游因此把它做成显式 opt-in,默认一个透明 UTXO 都不花。 - /// - /// 关着的后果是具体的:一个只有透明余额的账户**发不出任何款**, - /// 唯一出口是先屏蔽(多一笔交易、多一份手续费、多一次等待)。 - pub spend_transparent: bool, /// 零确认的自家屏蔽产出允不允许立刻再花(ZIP-315 建议允许)。 /// /// 曾经硬编码 `false`,而余额读取那头却是参数 —— 宿主想跟进 ZIP-315 @@ -282,7 +199,6 @@ pub fn parse_send_policy( untrusted: u32, fallback_change_pool: &str, pad_orchard_bundle: bool, - spend_transparent: Option, allow_zero_conf_shielding: Option, spend_source: Option<&str>, ) -> Result { @@ -291,7 +207,6 @@ pub fn parse_send_policy( untrusted, fallback_change_pool: parse_change_pool(fallback_change_pool)?, pad_orchard_bundle, - spend_transparent: spend_transparent.unwrap_or(false), allow_zero_conf_shielding: allow_zero_conf_shielding.unwrap_or(false), spend_source: parse_spend_source(spend_source)?, }) @@ -302,28 +217,29 @@ pub fn parse_send_policy( type TransferProposal = zcash_client_backend::proposal::Proposal; -/// 这个收款地址收不收得进屏蔽池。 -/// -/// 不认识的 receiver 类型算「收得进」:UA 里可能有本 crate 的 `zcash_address` -/// 还不认识的池子,把它判成纯透明会拒掉一笔合法的屏蔽转账 —— 比放过一笔 -/// 公开转账更糟。 -fn recipient_accepts_shielded( +/// 收款只能落在 Sapling:Sapling 证明参数没随包发布(体积),这种交易必然在 +/// 证明阶段失败 —— 那时用户已经点了确认。在构造前就拒绝。 +fn recipient_needs_sapling_output( params: &zcash_protocol::consensus::Network, recipient: &zcash_address::ZcashAddress, -) -> Result { +) -> bool { use zcash_keys::address::Address; - let parsed = Address::try_from_zcash_address(params, recipient.clone()).map_err(|e| { - RuntimeError::with( - ErrorCode::InvalidAddress, - json!({ "stage": "recipientKind" }), - ) - .detail(format!("{e:?}")) - })?; - Ok(match parsed { - Address::Transparent(_) | Address::Tex(_) => false, - Address::Sapling(_) => true, - Address::Unified(ua) => ua.has_orchard() || ua.has_sapling() || !ua.unknown().is_empty(), - }) + match Address::try_from_zcash_address(params, recipient.clone()) { + Ok(Address::Sapling(_)) => true, + Ok(Address::Unified(ua)) => ua.has_sapling() && !ua.has_orchard(), + _ => false, + } +} + +/// ZIP-320 TEX 地址只收透明输入;私密付款花的是屏蔽池,付不了它。 +fn recipient_is_tex( + params: &zcash_protocol::consensus::Network, + recipient: &zcash_address::ZcashAddress, +) -> bool { + matches!( + zcash_keys::address::Address::try_from_zcash_address(params, recipient.clone()), + Ok(zcash_keys::address::Address::Tex(_)) + ) } fn build_proposal( @@ -353,6 +269,20 @@ fn build_proposal( RuntimeError::with(ErrorCode::InvalidAddress, json!({ "value": to_address })).detail(e) })?; + if recipient_is_tex(¶ms, &recipient) { + return Err(RuntimeError::with( + ErrorCode::InvalidAddress, + json!({ "reason": "texRequiresTransparentSource" }), + )); + } + + if recipient_needs_sapling_output(¶ms, &recipient) { + return Err(RuntimeError::with( + ErrorCode::InvalidAddress, + json!({ "reason": "saplingOnlyRecipient" }), + )); + } + let memo_bytes = match memo { None => None, Some(m) => { @@ -363,20 +293,6 @@ fn build_proposal( } }; - // 花透明输入换来的隐私代价,只有在收款方是屏蔽地址时才买到了东西: - // 那笔钱进了池子。收款方只能收透明时,这笔交易从头到尾公开,被选中的 - // 透明地址还白白关联到了收款方 —— 用户为一个不存在的收益付了隐私。 - // - // 宿主本来就只在收款方是屏蔽地址时才打开这个开关(见 - // `shouldPreferTransparentForShieldedSend`)。这里是拦宿主的 bug: - // 这个开关的代价是用户看不见的,不能靠调用方自觉。 - if policy.spend_transparent && !recipient_accepts_shielded(¶ms, &recipient)? { - return Err(RuntimeError::with( - ErrorCode::TransactionBuildError, - json!({ "stage": "spendTransparent", "reason": "transparentOnlyRecipient" }), - )); - } - // Payment::new 会自己校验「透明地址不能带 memo」这类约束。 let payment = zip321::Payment::new(recipient, Some(amount), memo_bytes, None, None, vec![]) .map_err(|e| { @@ -393,13 +309,9 @@ fn build_proposal( policy.allow_zero_conf_shielding, )?; - // 花费来源策略。默认(SpendPolicy::default)**一个透明 UTXO 都不花** —— - // 于是只有透明余额的账户会以 INSUFFICIENT_FUNDS 收场,且 availableZat 报 0。 - // 打开它就允许从本账户的透明 receiver 取,代价是被选中的地址在链上互相关联。 + // 花费来源策略:只花所选的屏蔽池,一个透明 UTXO 都不花(与上游默认一致)。 let spend_policy = { - use zcash_client_backend::data_api::wallet::input_selection::{ - SpendPolicy, TransparentSpendPolicy, - }; + use zcash_client_backend::data_api::wallet::input_selection::SpendPolicy; // 不用 SpendPolicy::default():它允许 sapling。见 SendPolicy::spend_source。 // 屏蔽池之间永不并池(docs/08),而"当前池"只在宿主一处定义 // (ZCASH_CURRENT_SHIELDED_POOL):这里不藏缺省,缺参直接拒绝。 @@ -409,12 +321,19 @@ fn build_proposal( json!({ "stage": "spendSource", "reason": "required" }), ) })?; - let base = SpendPolicy::shielded_pools([pool]); - if policy.spend_transparent { - base.with_transparent(TransparentSpendPolicy::any_account_addr()) - } else { - base + let mut base = SpendPolicy::shielded_pools([pool]); + // A retry under the same reservation id must reselect what that id + // already holds. The default policy excludes every lock, the caller's + // own included, so the retry would lock a second set and leave the + // first frozen until expiry. Only this owner's locks are admitted. + if let Some(lock) = &lock { + use zcash_client_backend::data_api::locking::LockedInputPolicy; + use zcash_client_backend::data_api::wallet::input_selection::NonEmptyBTreeSet; + base = base.with_locked_input_policy(LockedInputPolicy::PreferLocked( + NonEmptyBTreeSet::singleton(lock.owner()), + )); } + base }; let selector = GreedyInputSelector::::new(); @@ -440,21 +359,7 @@ fn build_proposal( None, ); - // db 的可变借用到这里就结束了,所以失败路径上可以再查一次余额, - // 把「余额不足」补成「钱在透明池里」。 - let proposal = match proposal { - Ok(p) => p, - Err(e) => { - return Err(explain_insufficient( - db, - account_id, - confirmations, - propose_err("proposeTransfer", e), - )) - } - }; - - Ok(proposal) + proposal.map_err(|e| propose_err("proposeTransfer", e)) } /// 只出费用,不构造 PCZT、不锁定 note。 @@ -476,59 +381,9 @@ pub fn quote( .map(|s| u64::from(s.balance().fee_required())) .sum(); - // 这笔钱实际从哪儿取。宿主要给出「会花掉你的透明余额」这类提醒,就得先知道 - // 答案 —— 而在真正构造之前,只有提案知道。光给手续费的话,宿主只能拿一个 - // 布尔开关去问用户,而用户没有任何依据来回答。 - let mut transparent_in = 0u64; - let mut shielded_in = 0u64; - for step in proposal.steps() { - transparent_in += step - .transparent_inputs() - .iter() - .map(|o| u64::from(o.txout().value())) - .sum::(); - if let Some(inputs) = step.shielded_inputs() { - shielded_in += inputs - .notes() - .iter() - .map(|n| u64::from(n.note().value())) - .sum::(); - } - } - - // 用了透明输入时,顺手算一遍「只用屏蔽余额」要多少手续费。 - // - // 这不是给运行时用来做决定的 —— 它只是把选择的代价摆出来。透明输入按 - // ZIP-317 各自计入 logical action,实测同一笔付款用透明要 20000、只用屏蔽 - // 要 10000。差一倍的事不告诉用户,用户就没法评估。 - // - // 屏蔽余额本来就不够时提不出方案,此时报 null,宿主别显示这条建议。 - let shielded_only_fee = if transparent_in > 0 { - let mut alt = policy; - alt.spend_transparent = false; - build_proposal(db, account_uuid, to_address, amount_zat, memo, alt, None) - .ok() - .map(|p| { - p.steps() - .iter() - .map(|s| u64::from(s.balance().fee_required())) - .sum::() - }) - } else { - None - }; - Ok(json!({ "feeZat": fee, "steps": proposal.steps().len(), - "sourceTransparentZat": transparent_in, - "sourceShieldedZat": shielded_in, - // 同一笔里既花透明又花屏蔽 —— 链上因此把这个 t 地址和一次屏蔽花费绑在 - // 一起。这是花透明输入唯一**新增**的暴露:只花透明的话,对外和一笔普通 - // 屏蔽交易没有区别(透明进、屏蔽出)。值得单独提醒的就是这一种。 - "linksTransparentToShielded": transparent_in > 0 && shielded_in > 0, - // 只用屏蔽余额的手续费;null = 屏蔽余额不够,提不出这个方案。 - "shieldedOnlyFeeZat": shielded_only_fee, }) .to_string()) } @@ -604,6 +459,9 @@ pub fn release_reservation(db: &mut Db, reservation_id: &str) -> Result { }); return Err(build_err("unlockProposalInputs", format!("{e:?}"))); } + // Anything else this owner still holds (a set locked before a retry + // replaced the in-memory proposal) goes too. + release_persisted_reservation(db, reservation_id, owner)?; return Ok(true); } release_persisted_reservation(db, reservation_id, owner) @@ -691,14 +549,22 @@ pub fn forget_reservation(reservation_id: &str) { RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id)); } +/// 账户被删掉时,它还在内存里的提案一并丢弃:那些 note 已经随账户删了。 +pub fn forget_account_reservations(account_uuid: &str) { + RESERVATIONS.with(|r| { + r.borrow_mut() + .retain(|_, (owner_uuid, _)| owner_uuid.as_str() != account_uuid) + }); +} + /// 构造一笔转账的 PCZT(未签名),并**锁住选中的 note**。 /// /// 返回 `{ pcztHex, reservationId }`:`reservationId` 是这批 note 的占用凭证, -/// 调用方必须一直带着它,直到交易发出(`pcztSend`)或用户取消(`releaseReservation`)。 +/// 调用方必须一直带着它,直到交易提交(`pcztSubmit`)或用户取消(`releaseReservation`)。 /// 不释放也不会永久卡死 —— 锁有按区块高度的过期时间,但那是兜底,不是正常路径。 /// -/// `lock_for_blocks` 是策略:它要覆盖「构造完成 → 交易落库」的最坏耗时。 -/// 太短则用户还在审核页锁就过期了,太长则取消后 note 白白冻着。由宿主决定。 +/// `lock_for_blocks` 由宿主决定,但必须长过交易的过期高度:广播后、落库前崩溃时, +/// 只有这把锁防止同一批 note 被再花一次。 /// /// `reservation_id` 可由调用方传入(64 位 hex)。上游的设计意图就是**调用方持有 /// 这个 token**:先生成、先持久化,再来构造。这样即使中途崩溃,恢复后仍然知道 @@ -787,19 +653,36 @@ pub fn create_pczt( /// 用哪个电路版本证明,由**共识分支**决定,不是产品选项。 /// -/// 这里从网络参数与当前链尖推导:链尖过了 NU6.3 激活高度就用 PostNu6_3, +/// `height` 是交易所属分支的起始高度:过了 NU6.3 激活高度就用 PostNu6_3, /// 否则用 FixedPostNu6_2。`InsecurePreNu6_2` 永远不用于证明(上游明确标注)。 fn circuit_version_for( params: &zcash_protocol::consensus::Network, - chain_tip: zcash_protocol::consensus::BlockHeight, + height: zcash_protocol::consensus::BlockHeight, ) -> orchard::circuit::OrchardCircuitVersion { use zcash_protocol::consensus::{NetworkUpgrade, Parameters}; match params.activation_height(NetworkUpgrade::Nu6_3) { - Some(height) if chain_tip >= height => orchard::circuit::OrchardCircuitVersion::PostNu6_3, + Some(activation) if height >= activation => { + orchard::circuit::OrchardCircuitVersion::PostNu6_3 + } _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2, } } +/// The transaction's own branch decides, not our tip: around an upgrade the two +/// disagree, and a proof under the wrong circuit is rejected. The tip is only +/// the fallback for a branch id this build does not know. +fn circuit_version_for_branch( + params: &zcash_protocol::consensus::Network, + consensus_branch_id: u32, + chain_tip: zcash_protocol::consensus::BlockHeight, +) -> orchard::circuit::OrchardCircuitVersion { + let branch_start = zcash_protocol::consensus::BranchId::try_from(consensus_branch_id) + .ok() + .and_then(|branch| branch.height_bounds(params)) + .map(|(start, _)| start); + circuit_version_for(params, branch_start.unwrap_or(chain_tip)) +} + /// 给 PCZT 生成 Orchard / Ironwood 零知识证明。 /// 合并两份同一笔交易的 PCZT(本地完整副本 + 外部签名器返回的脱敏副本)。 /// 合并硬件回传的签名副本。**只许补签名,不许改交易。** @@ -933,11 +816,12 @@ pub fn prove_pczt_at_height( chain_tip: zcash_protocol::consensus::BlockHeight, pczt_bytes: &[u8], ) -> Result> { - let version = circuit_version_for(params, chain_tip); let pczt = pczt::Pczt::parse(pczt_bytes).map_err(|error| { RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "parse" })) .detail(format!("{error:?}")) })?; + let version = + circuit_version_for_branch(params, *pczt.global().consensus_branch_id(), chain_tip); let prover = pczt::roles::prover::Prover::new(pczt); let prover = if prover.requires_ironwood_proof() { @@ -975,33 +859,21 @@ pub fn prove_pczt_at_height( }) } -/// 终结已签名的 PCZT,提取交易并写回钱包,返回 txid。 -/// -/// 写回是必要的:钱包要立刻知道这笔花费占用了哪些 note, -/// 否则下一笔可能重复选中同一批 —— `zcash_client_sqlite` 的 note locking 负责这件事。 -/// -/// **不校验零知识证明。** 上游允许在此处传入 verifying key 做一次证明校验, -/// 但那需要现场构建 Orchard 电路(很贵),而这个 PCZT 是本机刚构造并签名的 —— -/// 校验它等于校验自己。若将来接受外部传入的 PCZT(多签、离线签名机), -/// 必须在这里补上校验,否则会把无效证明写进钱包。 -pub fn extract_and_store( +/// 把签好名的 PCZT 落进钱包库:从这一刻起它花掉的 note 由这笔交易持有。 +fn store_signed_pczt( db: &mut Db, account_uuid: &str, - pczt_bytes: &[u8], + pczt: pczt::Pczt, + orchard_vk: &orchard::circuit::VerifyingKey, reservation_id: &str, ) -> Result { - let pczt = pczt::Pczt::parse(pczt_bytes).map_err(|e| { - RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "parse" })) - .detail(format!("{e:?}")) - })?; - db.transactionally_with_extension(|wallet, ext| { - if let Some(txid) = tx_state::existing_txid_for_reservation(ext, reservation_id)? { - return Ok(txid); - } let txid = extract_and_store_transaction_from_pczt::<_, zcash_client_sqlite::ReceivedNoteId>( - wallet, pczt, None, None, + wallet, + pczt, + None, + Some(orchard_vk), ) .map_err(|e| build_err("extractAndStore", format!("{e:?}")))? .to_string(); @@ -1010,10 +882,128 @@ pub fn extract_and_store( }) } -/// 从钱包库取出已提取交易的原始字节,供广播使用。 +/// 一次提交的结局。 +pub enum SubmitOutcome { + Accepted { + txid: String, + }, + /// 节点明确拒收:没落库,note 已放回。 + Rejected { + txid: String, + error: RuntimeError, + }, + /// 不知道节点收没收到:已落库,交易持有 note,同步时会重播。 + Unknown { + txid: String, + error: RuntimeError, + }, +} + +/// 首次提交时这笔交易从没发出过:节点回「输入已花」只能是别的交易花了它们, +/// 不是它自己已被打包 —— 按拒绝处理。`Ok` 是拒绝,`Err` 原样是其他错误。 +fn first_submit_rejection(error: RuntimeError) -> std::result::Result { + match error.code { + ErrorCode::BroadcastRejected | ErrorCode::BroadcastOutcomeUnknown => Ok(RuntimeError { + code: ErrorCode::BroadcastRejected, + ..error + }), + _ => Err(error), + } +} + +/// 提交签好名的 PCZT:先提取交易并广播,再按结局决定落不落库。 /// -/// `extract_and_store` 只落库、不发网络,广播是**独立的一步**:这样宿主可以在 -/// 落库之后、真正发出去之前插入确认环节,也能在广播失败后原样重试而不必重建交易。 +/// 先落库再广播的话,上游从落库那一刻起就把 note 算作已花,只有交易过期才放 +/// 回来;节点明确拒收的交易会把钱冻上几十个块。这里反过来:明确拒收就不落库, +/// 直接放回 note。结局未知仍然落库 —— 交易可能已经传开,放回 note 会让用户重发 +/// 出第二笔。广播成功后落库失败按 FINALIZE_OUTCOME_UNKNOWN 报,由宿主查历史。 +pub async fn submit_signed_pczt( + db: &mut Db, + client: &mut crate::network::LightClient, + account_uuid: &str, + pczt_bytes: &[u8], + reservation_id: &str, +) -> Result { + use pczt::roles::{spend_finalizer::SpendFinalizer, tx_extractor::TransactionExtractor}; + + // 上次提交已经落库(宿主没拿到回包就重试):重播那一笔,不再提取第二次。 + let stored = db.transactionally_with_extension(|_wallet, ext| { + tx_state::existing_txid_for_reservation(ext, reservation_id) + })?; + if let Some(txid) = stored { + let raw = raw_transaction(db, &txid)?; + return Ok(match crate::network::broadcast(client, raw).await { + Ok(()) => { + tx_state::mark_accepted(db, &txid)?; + SubmitOutcome::Accepted { txid } + } + Err(error) => SubmitOutcome::Unknown { txid, error }, + }); + } + + let pczt = pczt::Pczt::parse(pczt_bytes).map_err(|e| { + RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "parse" })) + .detail(format!("{e:?}")) + })?; + let params = *db.params(); + let chain_tip = db + .chain_height() + .map_err(|error| build_err("chainHeight", error))? + .ok_or_else(|| RuntimeError::new(ErrorCode::NotSynced))?; + let version = + circuit_version_for_branch(¶ms, *pczt.global().consensus_branch_id(), chain_tip); + // 构建一次,提取和落库共用:每次现场构建都要好几秒。 + let orchard_vk = orchard::circuit::VerifyingKey::build(version); + + let finalized = SpendFinalizer::new(pczt.clone()) + .finalize_spends() + .map_err(|e| build_err("finalizeSpends", format!("{e:?}")))?; + let tx = TransactionExtractor::new(finalized) + .with_orchard(&orchard_vk) + .extract() + .map_err(|e| build_err("extractTransaction", format!("{e:?}")))?; + let txid = tx.txid().to_string(); + let mut raw = Vec::new(); + tx.write(&mut raw) + .map_err(|e| build_err("serializeTransaction", e))?; + + let broadcast = match crate::network::broadcast(client, raw).await { + Err(error) => match first_submit_rejection(error) { + Ok(error) => { + release_reservation(db, reservation_id)?; + return Ok(SubmitOutcome::Rejected { txid, error }); + } + Err(error) => Err(error), + }, + Ok(()) => Ok(()), + }; + + let stored = store_signed_pczt(db, account_uuid, pczt, &orchard_vk, reservation_id).and_then( + |stored_txid| { + if broadcast.is_ok() { + tx_state::mark_accepted(db, &stored_txid)?; + } + Ok(stored_txid) + }, + ); + forget_reservation(reservation_id); + let stored_txid = stored.map_err(|error| { + RuntimeError::with( + ErrorCode::FinalizeOutcomeUnknown, + json!({ "txid": txid, "broadcast": if broadcast.is_ok() { "accepted" } else { "unknown" } }), + ) + .detail(format!("{error:?}")) + })?; + Ok(match broadcast { + Ok(()) => SubmitOutcome::Accepted { txid: stored_txid }, + Err(error) => SubmitOutcome::Unknown { + txid: stored_txid, + error, + }, + }) +} + +/// 从钱包库取出已落库交易的原始字节,供重播使用。 pub fn raw_transaction(db: &Db, txid: &str) -> Result> { use zcash_primitives::transaction::TxId; @@ -1159,13 +1149,6 @@ mod reservation_recovery_tests { #[cfg(all(test, not(target_arch = "wasm32")))] mod policy_tests { use super::*; - use zcash_address::ZcashAddress; - use zcash_keys::keys::{UnifiedAddressRequest, UnifiedSpendingKey}; - use zcash_protocol::consensus::Network; - - fn parse(encoded: &str) -> ZcashAddress { - ZcashAddress::try_from_encoded(encoded).expect("a valid address") - } /// Sapling 在这两处都不是合法取值,理由不同但结论一样:证明建不出来, /// 而且找零会落进一个只读不可花的池子。 @@ -1177,33 +1160,74 @@ mod policy_tests { assert!(parse_spend_source(Some("sapling")).is_err()); } + /// 升级前后几块:本地链尖还在旧分支,交易已按新分支构造(或反过来)。 #[test] - fn only_a_shielded_recipient_justifies_spending_transparent_inputs() { - let params = Network::MainNetwork; - let taddr = ::transparent::address::TransparentAddress::PublicKeyHash([3; 20]); - - // 裸 t 地址、TEX 地址:整笔交易公开,花透明输入换不到任何隐私。 - let t_encoded = zcash_keys::encoding::encode_transparent_address_p(¶ms, &taddr); - assert!(!recipient_accepts_shielded(¶ms, &parse(&t_encoded)).unwrap()); + fn the_proving_circuit_follows_the_transactions_branch_not_the_tip() { + use orchard::circuit::OrchardCircuitVersion; + use zcash_protocol::consensus::{BranchId, NetworkUpgrade, Parameters}; + let params = zcash_protocol::consensus::Network::MainNetwork; + let Some(activation) = params.activation_height(NetworkUpgrade::Nu6_3) else { + return; + }; + let before = activation - 1; + assert_eq!( + circuit_version_for_branch(¶ms, u32::from(BranchId::Nu6_3), before), + OrchardCircuitVersion::PostNu6_3 + ); + assert_eq!( + circuit_version_for_branch(¶ms, u32::from(BranchId::Nu6_1), activation), + OrchardCircuitVersion::FixedPostNu6_2 + ); + assert_eq!( + circuit_version_for_branch(¶ms, 0xdead_beef, activation), + OrchardCircuitVersion::PostNu6_3, + "unknown branch falls back to the tip" + ); + } - let tex = zcash_keys::address::Address::Tex([3; 20]) - .to_zcash_address(¶ms) - .encode(); - assert!(!recipient_accepts_shielded(¶ms, &parse(&tex)).unwrap()); + #[test] + fn a_sapling_only_recipient_is_refused_before_building() { + let params = zcash_protocol::consensus::Network::MainNetwork; + let ufvk = |seed: u8| { + zcash_keys::keys::UnifiedSpendingKey::from_seed( + ¶ms, + &[seed; 32], + 0u32.try_into().unwrap(), + ) + .unwrap() + .to_unified_full_viewing_key() + }; + let key = ufvk(9); + let sapling = key.sapling().unwrap().default_address().1; + let encoded = zcash_keys::encoding::encode_payment_address_p(¶ms, &sapling); + let parse = |s: &str| zcash_address::ZcashAddress::try_from_encoded(s).unwrap(); + assert!(recipient_needs_sapling_output(¶ms, &parse(&encoded))); + let (ua, _) = key + .default_address(zcash_keys::keys::UnifiedAddressRequest::AllAvailableKeys) + .unwrap(); + assert!( + !recipient_needs_sapling_output(¶ms, &parse(&ua.encode(¶ms))), + "a UA with an Orchard receiver is fine" + ); + } - // UA:钱进了屏蔽池,这才是这个开关买到的东西。 - let ua = UnifiedSpendingKey::from_seed( - ¶ms, - &[7u8; 32], - 0u32.try_into().expect("valid ZIP-32 account index"), - ) - .expect("test seed derives a USK") - .to_unified_full_viewing_key() - .default_address(UnifiedAddressRequest::ALLOW_ALL) - .expect("a default unified address") - .0 - .encode(¶ms); - assert!(recipient_accepts_shielded(¶ms, &parse(&ua)).unwrap()); + #[test] + fn a_tex_recipient_is_recognised() { + use zcash_address::ToAddress; + let params = zcash_protocol::consensus::Network::MainNetwork; + let tex = zcash_address::ZcashAddress::from_tex( + zcash_protocol::consensus::NetworkType::Main, + [9; 20], + ); + let t1 = zcash_address::ZcashAddress::from_transparent_p2pkh( + zcash_protocol::consensus::NetworkType::Main, + [9; 20], + ); + // Pinned: the app decodes this same pair in JS (sdkZcash/index.test.ts). + assert_eq!(tex.encode(), "tex1pyysjzgfpyysjzgfpyysjzgfpyysjzgfl7c006"); + assert_eq!(t1.encode(), "t1JhNuqypTPZu5vdcjsvGHzbTCrTd9Xwtru"); + assert!(recipient_is_tex(¶ms, &tex)); + assert!(!recipient_is_tex(¶ms, &t1)); } } @@ -1365,3 +1389,30 @@ mod combine_tests { ); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod submit_tests { + use super::*; + + #[test] + fn first_submit_treats_spent_inputs_as_rejection() { + let spent = RuntimeError::with( + ErrorCode::BroadcastOutcomeUnknown, + json!({ "errorCode": -26 }), + ) + .detail("bad-txns-inputs-spent".to_string()); + let rejection = first_submit_rejection(spent).unwrap(); + assert_eq!(rejection.code, ErrorCode::BroadcastRejected); + assert_eq!(rejection.params["errorCode"], -26); + assert_eq!(rejection.detail.as_deref(), Some("bad-txns-inputs-spent")); + } + + #[test] + fn first_submit_keeps_network_errors_unknown() { + let error = RuntimeError::new(ErrorCode::NetworkError); + assert_eq!( + first_submit_rejection(error).unwrap_err().code, + ErrorCode::NetworkError + ); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs index 53d0673d3..d7702dc25 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs @@ -24,19 +24,13 @@ use serde_json::json; use zcash_address::unified::{Container, Encoding, Fvk, Ufvk}; use zcash_client_backend::data_api::chain::error::Error as ChainError; use zcash_client_backend::data_api::chain::{BlockSource, ChainState, CommitmentTreeRoot}; -use zcash_client_backend::data_api::ll::{LowLevelWalletRead, LowLevelWalletWrite}; use zcash_client_backend::data_api::scanning::{ScanPriority, ScanRange}; -use zcash_client_backend::data_api::{ - OutputStatusFilter, TransactionDataRequest, TransactionStatus, TransactionStatusFilter, - WalletCommitmentTrees, WalletRead, WalletWrite, -}; +use zcash_client_backend::data_api::{WalletCommitmentTrees, WalletRead, WalletWrite}; use zcash_client_backend::proto::service; use zcash_client_backend::scanning::{scan_block, Nullifiers, ScanningKeys}; -use zcash_client_sqlite::util::Clock; use zcash_keys::keys::UnifiedFullViewingKey; use zcash_primitives::merkle_tree::HashSer; -use zcash_primitives::transaction::Transaction; -use zcash_protocol::consensus::{BlockHeight, BranchId, NetworkUpgrade, Parameters}; +use zcash_protocol::consensus::{BlockHeight, NetworkUpgrade, Parameters}; use crate::blockcache::MemoryBlockCache; use crate::error::{ErrorCode, Result, RuntimeError}; @@ -703,12 +697,17 @@ pub(crate) fn trace(msg: &str) { #[wasm_bindgen(js_namespace = console)] fn log(s: &str); } - log(msg); + // Every scan step logs several lines; only with diagnostics on. + if crate::perf::is_enabled() { + log(msg); + } } #[cfg(not(target_arch = "wasm32"))] pub(crate) fn trace(msg: &str) { - println!("{msg}"); + if crate::perf::is_enabled() { + println!("{msg}"); + } } /// 取 `start - 1` 作为锚点,但不低于 Sapling 激活高度。 @@ -800,10 +799,36 @@ async fn download_batch( if got == 0 { return Err(net_err("getBlockRange", "empty stream for non-empty range")); } + check_block_sequence( + u32::from(range.block_range().start), + u32::from(range.block_range().end), + blocks.iter().map(|b| b.height), + )?; cache.insert(blocks).map_err(|e| db_err("cacheInsert", e))?; Ok(got) } +/// 节点回的块必须从区间起点开始、逐块连续、不越过终点(右开)。截断的前缀 +/// 是合法的(下载有预算);乱序、重复、跳号或区间外的块不能进缓存。 +fn check_block_sequence( + start: u32, + end_exclusive: u32, + heights: impl Iterator, +) -> Result<()> { + for (offset, height) in heights.enumerate() { + let expected = u64::from(start) + offset as u64; + if height != expected || height >= u64::from(end_exclusive) { + return Err(net_err( + "getBlockRange", + format!( + "block {height} where {expected} was expected (range {start}..{end_exclusive})" + ), + )); + } + } + Ok(()) +} + /// 回退钱包到指定高度,让之后的同步重扫这段区间。 /// /// **破坏性**:该高度之上的扫描结果(note、witness、承诺树检查点)会被丢弃。 @@ -855,543 +880,6 @@ pub fn queue_rescan_from(db: &mut Db, from_height: u32) -> Result { .to_string()) } -// A UTXO reply does not identify coinbase transactions. Validate its complete -// parent before inserting the output so NonCoinbaseOnly never sees an unknown -// parent as an ordinary transaction. -fn decode_mined_transaction( - params: &zcash_protocol::consensus::Network, - raw: &service::RawTransaction, -) -> Result<(Transaction, BlockHeight)> { - let height = u32::try_from(raw.height) - .ok() - .filter(|height| *height > 0) - .map(BlockHeight::from_u32) - .ok_or_else(|| net_err("transparentTransaction", "missing main-chain height"))?; - let mut bytes = raw.data.as_slice(); - let tx = Transaction::read(&mut bytes, BranchId::for_height(params, height)) - .map_err(|e| net_err("transparentTransaction", e))?; - if !bytes.is_empty() { - return Err(net_err( - "transparentTransaction", - "trailing transaction data", - )); - } - Ok((tx, height)) -} - -fn validate_transparent_parent( - tx: &Transaction, - txid: &[u8; 32], - index: u32, - txout: &::transparent::bundle::TxOut, -) -> Result<()> { - if tx.txid().as_ref() != txid { - return Err(net_err("transparentParent", "transaction id mismatch")); - } - let output = tx - .transparent_bundle() - .and_then(|bundle| bundle.vout.get(index as usize)); - if output != Some(txout) { - return Err(net_err( - "transparentParent", - "output value or script mismatch", - )); - } - Ok(()) -} - -fn store_account_transaction( - db: &mut Db, - account_id: ::AccountId, - tx: &Transaction, - height: BlockHeight, - received: Option< - &zcash_client_backend::wallet::WalletTransparentOutput<::AccountId>, - >, -) -> Result<()> { - // The high-level decrypted transaction writer detects inputs and outputs - // across every wallet account, even when its decryption key set is scoped. - // This transparent-only path changes spentness only for the active owner. - db.transactionally(|wallet| { - let tx_ref = wallet.put_tx_data(tx, None, None, None, height)?; - LowLevelWalletWrite::set_transaction_status( - wallet, - tx.txid(), - TransactionStatus::Mined(height), - )?; - if let Some(output) = received { - WalletWrite::put_received_transparent_utxo(wallet, output)?; - } - if let Some(bundle) = tx.transparent_bundle() { - for (index, _) in bundle.vout.iter().enumerate() { - let outpoint = - ::transparent::bundle::OutPoint::new(*tx.txid().as_ref(), index as u32); - if let Some(output) = wallet.get_wallet_transparent_output(&outpoint, None)? { - if output.recipient_account() == Some(&account_id) { - wallet.queue_transparent_spend_detection( - *output.recipient_address(), - tx_ref, - index as u32, - )?; - } - } - } - for input in &bundle.vin { - let owned = wallet - .get_wallet_transparent_output(input.prevout(), None)? - .is_some_and(|output| output.recipient_account() == Some(&account_id)); - if owned { - wallet.mark_transparent_utxo_spent(input.prevout(), tx_ref)?; - } - } - } - Ok::<_, zcash_client_sqlite::error::SqliteClientError>(()) - }) - .map_err(|e| db_err("storeTransparentTransaction", e)) -} - -async fn queue_cached_transparent_outputs( - db: &mut Db, - client: &mut LightClient, - account_id: ::AccountId, - addresses: &HashSet<::transparent::address::TransparentAddress>, - already_stored: &HashMap<[u8; 32], (Transaction, BlockHeight)>, - fetched_parents: &mut u32, -) -> Result { - use zcash_client_backend::data_api::wallet::{ - input_selection::LockFilter, ConfirmationsPolicy, - }; - use zcash_client_backend::data_api::{CoinbaseFilter, InputSource}; - let params = *db.params(); - let tip = db - .chain_height() - .map_err(|e| db_err("chainHeight", e))? - .ok_or_else(|| db_err("chainHeight", "unknown chain height"))?; - // This is a spentness audit, not input selection. Include locked outputs - // so an external spend cannot remain hidden behind a local reservation. - let outputs = db - .get_spendable_transparent_outputs_for_addresses( - &addresses.iter().copied().collect::>(), - (tip + 1).into(), - ConfirmationsPolicy::default(), - CoinbaseFilter::AllTransparentOutputs, - LockFilter::Unfiltered, - ) - .map_err(|e| db_err("cachedTransparentOutputs", e))?; - let mut seen = HashSet::new(); - let mut deferred = 0; - for output in outputs { - let txid = *output.outpoint().hash(); - if already_stored.contains_key(&txid) || !seen.insert(txid) { - continue; - } - let cached = db - .get_transaction(zcash_protocol::TxId::from_bytes(txid)) - .map_err(|e| db_err("getTransparentParent", e))?; - let (parent, height) = if let Some(parent) = cached { - let Some(height) = output.mined_height() else { - continue; - }; - (parent, height) - } else { - if *fetched_parents >= 16 { - deferred += 1; - continue; - } - let raw = crate::network::with_timeout( - async { - client - .get_transaction(service::TxFilter { - hash: txid.to_vec(), - ..Default::default() - }) - .await - .map(|reply| reply.into_inner()) - .map_err(|e| net_err("getTransparentParent", e)) - }, - crate::network::DEFAULT_TIMEOUT_MS, - "getTransparentParent", - ) - .await?; - *fetched_parents += 1; - decode_mined_transaction(¶ms, &raw)? - }; - validate_transparent_parent(&parent, &txid, output.outpoint().n(), output.txout())?; - // Do not reinsert an old cached output as known-unspent at today's tip. - // Its absence from the current UTXO reply requires a spend check. - store_account_transaction(db, account_id, &parent, height, None)?; - } - Ok(deferred) -} - -async fn complete_transparent_spend_check( - db: &mut Db, - account_id: ::AccountId, - request: zcash_client_backend::data_api::TransactionsInvolvingAddress, - mut stream: S, -) -> Result<()> -where - S: futures_util::TryStream + Unpin, - S::Error: std::fmt::Display, -{ - let params = *db.params(); - let end = request - .block_range_end() - .ok_or_else(|| net_err("getTransparentSpends", "missing bounded range"))?; - loop { - let raw = crate::network::with_timeout( - async { - stream - .try_next() - .await - .map_err(|e| net_err("getTransparentSpends", e)) - }, - crate::network::DEFAULT_TIMEOUT_MS, - "getTransparentSpends", - ) - .await?; - let Some(raw) = raw else { - break; - }; - let (tx, height) = decode_mined_transaction(¶ms, &raw)?; - if height < request.block_range_start() || height >= end { - return Err(net_err( - "getTransparentSpends", - "transaction outside requested range", - )); - } - store_account_transaction(db, account_id, &tx, height, None)?; - } - // Empty and complete streams establish a checked range, not a spend. - // A failed or partial stream never reaches this acknowledgement. - db.notify_address_checked(request, end - 1) - .map_err(|e| db_err("notifyAddressChecked", e)) -} - -async fn refresh_transparent_spends( - db: &mut Db, - client: &mut LightClient, - account_id: ::AccountId, - addresses: &HashSet<::transparent::address::TransparentAddress>, -) -> Result { - let params = *db.params(); - let requests = db - .transaction_data_requests() - .map_err(|e| db_err("transactionDataRequests", e))?; - let mut seen = HashSet::new(); - let mut checked = 0; - for request in requests { - let TransactionDataRequest::TransactionsInvolvingAddress(request) = request else { - continue; - }; - // GetTaddressTxids covers mined transactions only. Leave unsupported - // mempool/ephemeral queries queued rather than acknowledging incomplete data. - if !addresses.contains(&request.address()) - || *request.tx_status_filter() != TransactionStatusFilter::Mined - || *request.output_status_filter() != OutputStatusFilter::All - || request - .request_at() - .is_some_and(|at| at > crate::clock::HostClock.now()) - || !seen.insert(request.clone()) - { - continue; - } - let Some(end) = request.block_range_end() else { - continue; - }; - if request.block_range_start() >= end { - continue; - } - // The upstream mined-spend queue issues short expiry-sized ranges. - // Completing each range advances its persisted observed-unspent height, - // so subsequent rounds do not restart the same first page forever. - if checked >= 16 { - break; - } - let stream = crate::network::with_timeout( - async { - client - .get_taddress_txids(service::TransparentAddressBlockFilter { - address: zcash_keys::encoding::encode_transparent_address_p( - ¶ms, - &request.address(), - ), - range: Some(service::BlockRange { - start: Some(service::BlockId { - height: u64::from(request.block_range_start()), - hash: vec![], - }), - end: Some(service::BlockId { - height: u64::from(end - 1), - hash: vec![], - }), - pool_types: vec![], - }), - }) - .await - .map(|reply| reply.into_inner()) - .map_err(|e| net_err("getTransparentSpends", e)) - }, - crate::network::DEFAULT_TIMEOUT_MS, - "getTransparentSpends", - ) - .await?; - complete_transparent_spend_check(db, account_id, request, stream).await?; - checked += 1; - } - Ok(checked) -} - -/// 宿主喂进来的一条透明 UTXO。 -/// -/// 透明侧的唯一事实来源是宿主的后端索引器,不是 lightwalletd:同一个钱包里 -/// 两个来源各说各话时,用户看到的余额和这里能选的输入就对不上。运行时只负责 -/// 校验与落库,不自己去查。 -#[derive(Debug, serde::Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct HostTransparentUtxo { - pub txid: String, - pub vout: u32, - pub value_zat: String, - pub script_pub_key: String, - pub height: u32, -} - -/// 用宿主给的快照刷新账户的透明 UTXO。 -/// -/// ## 为什么必须单独做 -/// -/// 屏蔽 note 是扫区块试解密出来的,透明 UTXO 不是 —— 它们在链上是公开的, -/// `scan_cached_blocks` 不会产出它们。 -/// -/// 不做这一步的后果是**静默的**:隐私转账想花透明输入时选不到钱,报 -/// INSUFFICIENT_FUNDS,而扫链看起来一切正常。 -/// -/// ## 归属只认脚本 -/// -/// 每条 UTXO 的归属由 `script_pub_key` 解出的地址决定,再拿去比对本账户的 -/// 透明收款地址(含找零与独立地址)。宿主说它是谁的不作数 —— 否则宿主一处 -/// 笔误就能把别人的输出记到这个账户名下。 -pub async fn refresh_transparent_utxos( - db: &mut Db, - client: &mut LightClient, - account_uuid: &str, - utxos: &[HostTransparentUtxo], -) -> Result { - // Bound the whole refresh, including a server that keeps emitting stream - // items. Synchronous DB commits remain valid; unfinished ranges stay queued. - crate::network::with_timeout( - refresh_transparent_utxos_impl(db, client, account_uuid, utxos), - crate::network::DEFAULT_TIMEOUT_MS, - "refreshTransparentUtxos", - ) - .await -} - -async fn refresh_transparent_utxos_impl( - db: &mut Db, - client: &mut LightClient, - account_uuid: &str, - utxos: &[HostTransparentUtxo], -) -> Result { - use ::transparent::bundle::OutPoint; - use zcash_client_backend::wallet::WalletTransparentOutput; - - let params = *db.params(); - - let account_id = crate::account::parse_account_id(db, account_uuid)?; - - // 地址 → 账户。喂进来的每条 UTXO 靠它归属,否则宿主一处笔误就能把别人的 - // 输出记到这个账户名下。 - let mut owner_of: std::collections::HashMap::AccountId> = - std::collections::HashMap::new(); - let receivers = db - .get_transparent_receivers(account_id, true, true) - .map_err(|e| db_err("getTransparentReceivers", e))?; - for addr in receivers.keys() { - owner_of.insert( - zcash_keys::encoding::encode_transparent_address_p(¶ms, addr), - account_id, - ); - } - - if owner_of.is_empty() { - return Ok(json!({ "addresses": 0, "utxos": 0, "storedZat": 0 }).to_string()); - } - let address_count = owner_of.len(); - let active_receivers = receivers.keys().copied().collect(); - - let mut stored = 0u32; - let mut total: u64 = 0; - let mut parents = HashMap::new(); - let mut fetched_parents = 0; - let mut deferred_utxos = 0; - let mut rejected_utxos = 0; - for utxo in utxos { - let Some((txid, index, txout, owner)) = - decode_host_transparent_utxo(¶ms, &owner_of, utxo) - else { - continue; - }; - let value = txout.value(); - let height = Some(BlockHeight::from_u32(utxo.height)); - - if !parents.contains_key(&txid) { - if let Some(parent) = db - .get_transaction(zcash_protocol::TxId::from_bytes(txid)) - .map_err(|e| db_err("getTransparentParent", e))? - { - // The cached parent's height comes from the wallet database, not - // from the host. Storing `utxo.height` here would make the - // comparison below compare the host's claim with itself, so a - // wrong height on an already-known transaction would sail - // through and re-stamp its mined status. - let Some(mined_height) = db - .get_tx_height(zcash_protocol::TxId::from_bytes(txid)) - .map_err(|e| db_err("getTransparentParentHeight", e))? - else { - // Known transaction, no mined height: nothing to check the - // host against, so do not stage it on the host's word. - rejected_utxos += 1; - continue; - }; - parents.insert(txid, (parent, mined_height)); - } else { - // Persisted raw parents make this budget advance across rounds. - if fetched_parents >= 16 { - deferred_utxos += 1; - continue; - } - let raw = crate::network::with_timeout( - async { - client - .get_transaction(service::TxFilter { - hash: txid.to_vec(), - ..Default::default() - }) - .await - .map(|reply| reply.into_inner()) - .map_err(|e| net_err("getTransparentParent", e)) - }, - crate::network::DEFAULT_TIMEOUT_MS, - "getTransparentParent", - ) - .await?; - parents.insert(txid, decode_mined_transaction(¶ms, &raw)?); - fetched_parents += 1; - } - } - let (parent, mined_height) = parents - .get(&txid) - .ok_or_else(|| net_err("transparentParent", "missing fetched parent"))?; - // 金额/脚本/高度以链上的父交易为准。宿主和链现在是两个来源(重组窗口里 - // 它们本来就会短暂不一致),所以对不上的只丢这一条 —— 让一条过期的 - // UTXO 把整笔隐私转账挡掉,比少一个可选输入更糟。计数交回宿主, - // 这样宿主的 bug 不会没人看见。 - if validate_transparent_parent(parent, &txid, index, &txout).is_err() - || height != Some(*mined_height) - { - rejected_utxos += 1; - continue; - } - let Some(output) = WalletTransparentOutput::from_parts( - OutPoint::new(txid, index), - txout, - height, - Some(owner), - None, - None, - ) else { - // recipient_address 解不出来的输出我们无法归属,跳过而不是猜。 - continue; - }; - - store_account_transaction(db, owner, parent, *mined_height, Some(&output))?; - stored += 1; - total += u64::from(value); - } - - deferred_utxos += queue_cached_transparent_outputs( - db, - client, - account_id, - &active_receivers, - &parents, - &mut fetched_parents, - ) - .await?; - let spend_ranges_checked = - refresh_transparent_spends(db, client, account_id, &active_receivers).await?; - - Ok(json!({ - "spendRangesChecked": spend_ranges_checked, - "deferredUtxos": deferred_utxos, - "rejectedUtxos": rejected_utxos, - "addresses": address_count, - "utxos": stored, - "storedZat": total, - }) - .to_string()) -} - -/// 把宿主喂进来的一条 UTXO 解成可入库的形式,认不出或不属于本账户就返回 `None`。 -/// -/// 归属只由 `script_pub_key` 反解出的地址决定 —— 宿主对这条 UTXO 属于谁的说法 -/// 一概不采信。宿主一处笔误就能把别人的输出记到这个账户名下,而入库之后它就是 -/// 可选的花费输入了。 -fn decode_host_transparent_utxo( - params: &zcash_protocol::consensus::Network, - owner_of: &std::collections::HashMap::AccountId>, - utxo: &HostTransparentUtxo, -) -> Option<( - [u8; 32], - u32, - ::transparent::bundle::TxOut, - ::AccountId, -)> { - use ::transparent::bundle::TxOut; - use zcash_protocol::value::Zatoshis; - - // 宿主给的是后端的**显示序**(大端 hex);`TxId` / SQLite / lightwalletd 的 - // `TxFilter.hash` 全要内部序。不反转就是去查一个不存在的父交易,而且对 - // 回文 txid 恰好看不出来。 - let txid = - <[u8; 32]>::try_from(&crate::history::display_order_to_internal(&utxo.txid).ok()?[..]) - .ok()?; - let value = Zatoshis::from_u64(utxo.value_zat.parse::().ok()?).ok()?; - let script_pubkey = read_script(&hex::decode(&utxo.script_pub_key).ok()?)?; - let txout = TxOut::new(value, script_pubkey); - // 认不出的脚本(既非 P2PKH 也非 P2SH)没有可比对的地址,跳过而不是猜。 - let recipient = txout.recipient_address()?; - let owner = *owner_of.get(&zcash_keys::encoding::encode_transparent_address_p( - params, &recipient, - ))?; - Some((txid, utxo.vout, txout, owner)) -} - -/// 把裸 script 字节读成 `Script`。 -/// -/// 上游的 `Script::read` 期待 CompactSize 长度前缀(链上编码),而 -/// lightwalletd 的 `GetAddressUtxos` 给的是裸字节,所以这里补上前缀再读。 -/// 这样不必为了一个构造函数把 `zcash_script` 也拉进依赖树。 -fn read_script(raw: &[u8]) -> Option<::transparent::address::Script> { - let mut buf = Vec::with_capacity(raw.len() + 9); - // CompactSize:<253 一个字节;再大用 0xfd + u16 / 0xfe + u32 - match raw.len() { - n if n < 253 => buf.push(n as u8), - n if n <= u16::MAX as usize => { - buf.push(0xfd); - buf.extend_from_slice(&(n as u16).to_le_bytes()); - } - n => { - buf.push(0xfe); - buf.extend_from_slice(&(n as u32).to_le_bytes()); - } - } - buf.extend_from_slice(raw); - ::transparent::address::Script::read(&buf[..]).ok() -} - #[cfg(test)] mod tests { use super::*; @@ -1408,386 +896,14 @@ mod tests { .to_unified_full_viewing_key() } - fn transparent_fixture( - inputs: Vec<::transparent::bundle::OutPoint>, - outputs: Vec<::transparent::bundle::TxOut>, - ) -> Transaction { - use ::transparent::bundle::{Authorized, Bundle, TxIn}; - use zcash_primitives::transaction::{TransactionData, TxVersion}; - TransactionData::from_parts( - TxVersion::V5, - BranchId::Nu5, - 0, - BlockHeight::from_u32(2_100_000), - Some(Bundle { - vin: inputs - .into_iter() - .map(|prevout| TxIn::from_parts(prevout, read_script(&[]).unwrap(), u32::MAX)) - .collect(), - vout: outputs, - authorization: Authorized, - }), - None, - None, - None, - ) - .freeze() - .unwrap() - } - - #[test] - fn transparent_parent_requires_exact_transaction_and_output() { - use ::transparent::{ - address::TransparentAddress, - bundle::{OutPoint, TxOut}, - }; - use zcash_protocol::value::Zatoshis; - let output = TxOut::new( - Zatoshis::from_u64(50_000).unwrap(), - TransparentAddress::PublicKeyHash([1; 20]).script().into(), - ); - let tx = transparent_fixture(vec![OutPoint::new([0; 32], u32::MAX)], vec![output.clone()]); - validate_transparent_parent(&tx, tx.txid().as_ref(), 0, &output).unwrap(); - assert!(validate_transparent_parent(&tx, &[2; 32], 0, &output).is_err()); - assert!(validate_transparent_parent(&tx, tx.txid().as_ref(), 1, &output).is_err()); - let wrong_value = TxOut::new( - Zatoshis::from_u64(50_001).unwrap(), - output.script_pubkey().clone(), - ); - assert!(validate_transparent_parent(&tx, tx.txid().as_ref(), 0, &wrong_value).is_err()); - let wrong_script = TxOut::new( - output.value(), - TransparentAddress::PublicKeyHash([2; 20]).script().into(), - ); - assert!(validate_transparent_parent(&tx, tx.txid().as_ref(), 0, &wrong_script).is_err()); - let mut data = vec![]; - tx.write(&mut data).unwrap(); - let mut raw = service::RawTransaction { - data, - height: 2_000_000, - }; - decode_mined_transaction(&Network::MainNetwork, &raw).unwrap(); - raw.height = 0; - assert!(decode_mined_transaction(&Network::MainNetwork, &raw).is_err()); - raw.height = u64::MAX; - assert!(decode_mined_transaction(&Network::MainNetwork, &raw).is_err()); - raw.height = 2_000_000; - raw.data.push(0); - assert!(decode_mined_transaction(&Network::MainNetwork, &raw).is_err()); - } - #[test] - fn host_transparent_utxo_is_attributed_by_its_script_not_by_the_host() { - use ::transparent::address::TransparentAddress; - use zcash_protocol::consensus::Network; - - let params = Network::MainNetwork; - let mine = [7u8; 20]; - let theirs = [9u8; 20]; - let owner = zcash_client_sqlite::AccountUuid::from_uuid(uuid::Uuid::from_u128(1)); - let mut owner_of = std::collections::HashMap::new(); - owner_of.insert( - zcash_keys::encoding::encode_transparent_address_p( - ¶ms, - &TransparentAddress::PublicKeyHash(mine), - ), - owner, - ); - - // 宿主发的就是 blockbook 的裸 scriptPubKey:P2PKH 是 - // OP_DUP OP_HASH160 <20 字节> OP_EQUALVERIFY OP_CHECKSIG。 - let p2pkh = |hash: [u8; 20]| format!("76a914{}88ac", hex::encode(hash)); - let utxo = |script: String, value: &str, txid: &str| HostTransparentUtxo { - txid: txid.to_string(), - vout: 1, - value_zat: value.to_string(), - script_pub_key: script, - height: 2_000_000, - }; - // 每个字节都不同:回文 txid(比如 "ab" 重复 32 次)在字节反转下和自己 - // 相等,用它做用例等于把显示序/内部序这一层测没了。 - let txid_display: String = (0u8..32).map(|b| format!("{b:02x}")).collect(); - let txid_internal: [u8; 32] = { - let mut b = [0u8; 32]; - for (i, v) in (0u8..32).rev().enumerate() { - b[i] = v; - } - b - }; - let txid_hex = txid_display; - - let (txid, index, txout, got) = - decode_host_transparent_utxo(¶ms, &owner_of, &utxo(p2pkh(mine), "1000", &txid_hex)) - .expect("an owned P2PKH output is attributed to its account"); - assert_eq!(txid, txid_internal, "显示序 hex 必须反转成内部序字节"); - assert_eq!(index, 1); - assert_eq!(u64::from(txout.value()), 1000); - assert_eq!(got, owner); - - // 宿主可以搞错 UTXO 是谁的;入库之后它就是可花费的输入了,所以归属 - // 只认脚本反解出来的地址。 - assert!(decode_host_transparent_utxo( - ¶ms, - &owner_of, - &utxo(p2pkh(theirs), "1000", &txid_hex) - ) - .is_none()); - // 单条坏数据只丢这一条,不影响同一快照里的其他 UTXO。 - for bad in [ - utxo(p2pkh(mine), "1000", "zz"), - utxo(p2pkh(mine), "1000", "ab"), - utxo(p2pkh(mine), "-1", &txid_hex), - utxo(p2pkh(mine), "not-a-number", &txid_hex), - // OP_RETURN:没有可比对的地址。 - utxo("6a".to_string(), "1000", &txid_hex), - ] { - assert!(decode_host_transparent_utxo(¶ms, &owner_of, &bad).is_none()); - } - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn transparent_storage_classifies_coinbase_and_limits_spends_to_active_owner() { - use ::transparent::bundle::{OutPoint, TxOut}; - use zcash_client_backend::data_api::wallet::{ - input_selection::LockFilter, ConfirmationsPolicy, - }; - use zcash_client_backend::data_api::{ - Account as _, AccountBirthday, AccountPurpose, CoinbaseFilter, InputSource, - }; - use zcash_client_backend::wallet::WalletTransparentOutput; - use zcash_primitives::block::BlockHash; - use zcash_protocol::value::Zatoshis; - let mut db = crate::wallet::open_and_migrate("main", ":memory:").unwrap(); - let height = BlockHeight::from_u32(2_000_000); - let birthday = - AccountBirthday::from_parts(ChainState::empty(height - 1, BlockHash([0; 32])), None); - let a = db - .import_account_ufvk( - "active", - &test_ufvk(&Network::MainNetwork, 51), - &birthday, - AccountPurpose::ViewOnly, - None, - ) - .unwrap() - .id(); - let b = db - .import_account_ufvk( - "paused", - &test_ufvk(&Network::MainNetwork, 52), - &birthday, - AccountPurpose::ViewOnly, - None, - ) - .unwrap() - .id(); - db.update_chain_tip(height + 200).unwrap(); - let address_a = *db - .get_transparent_receivers(a, true, true) - .unwrap() - .keys() - .next() - .unwrap(); - let address_b = *db - .get_transparent_receivers(b, true, true) - .unwrap() - .keys() - .next() - .unwrap(); - let output_a = TxOut::new( - Zatoshis::from_u64(50_000).unwrap(), - address_a.script().into(), - ); - let output_b = TxOut::new( - Zatoshis::from_u64(60_000).unwrap(), - address_b.script().into(), - ); - let coinbase = transparent_fixture( - vec![OutPoint::new([0; 32], u32::MAX)], - vec![output_a.clone()], - ); - let regular = transparent_fixture( - vec![OutPoint::new([3; 32], 0)], - vec![output_a.clone(), output_b.clone()], - ); - for (tx, index, output, owner) in [ - (&coinbase, 0, output_a.clone(), a), - (®ular, 0, output_a.clone(), a), - (®ular, 1, output_b.clone(), b), - ] { - store_account_transaction(&mut db, owner, tx, height, None).unwrap(); - let output = WalletTransparentOutput::from_parts( - OutPoint::new(*tx.txid().as_ref(), index), - output, - Some(height), - Some(owner), - None, - None, - ) - .unwrap(); - db.put_received_transparent_utxo(&output).unwrap(); - } - let spendable = |db: &Db, address| { - db.get_spendable_transparent_outputs( - address, - (height + 401).into(), - ConfirmationsPolicy::default(), - CoinbaseFilter::NonCoinbaseOnly, - LockFilter::Policy(&Default::default()), - ) - .unwrap() - }; - assert_eq!(spendable(&db, &address_a).len(), 1); - let a_input = OutPoint::new(*regular.txid().as_ref(), 0); - let b_input = OutPoint::new(*regular.txid().as_ref(), 1); - let spend = transparent_fixture(vec![a_input, b_input], vec![output_b]); - let b_receivers_before = db.get_transparent_receivers(b, true, true).unwrap().len(); - store_account_transaction(&mut db, a, &spend, height + 1, None).unwrap(); - assert!(spendable(&db, &address_a).is_empty()); - assert_eq!(spendable(&db, &address_b).len(), 1); - assert_eq!( - db.get_transparent_receivers(b, true, true).unwrap().len(), - b_receivers_before - ); - assert!(db - .get_unspent_transparent_output( - &OutPoint::new(*spend.txid().as_ref(), 0), - (height + 401).into() - ) - .unwrap() - .is_none()); - } - - #[cfg(not(target_arch = "wasm32"))] - #[tokio::test] - async fn transparent_spend_checks_acknowledge_only_complete_ranges() { - use ::transparent::bundle::{OutPoint, TxOut}; - use zcash_client_backend::data_api::{ - Account as _, AccountBirthday, AccountPurpose, InputSource, - }; - use zcash_client_backend::wallet::WalletTransparentOutput; - use zcash_primitives::block::BlockHash; - use zcash_protocol::value::Zatoshis; - let mut db = crate::wallet::open_and_migrate("main", ":memory:").unwrap(); - let height = BlockHeight::from_u32(2_000_000); - let birthday = - AccountBirthday::from_parts(ChainState::empty(height - 1, BlockHash([0; 32])), None); - let owner = db - .import_account_ufvk( - "active", - &test_ufvk(&Network::MainNetwork, 61), - &birthday, - AccountPurpose::ViewOnly, - None, - ) - .unwrap() - .id(); - db.update_chain_tip(height + 200).unwrap(); - let address = *db - .get_transparent_receivers(owner, true, true) - .unwrap() - .keys() - .next() - .unwrap(); - let txout = TxOut::new(Zatoshis::from_u64(50_000).unwrap(), address.script().into()); - let parent = transparent_fixture(vec![OutPoint::new([3; 32], 0)], vec![txout.clone()]); - store_account_transaction(&mut db, owner, &parent, height, None).unwrap(); - let outpoint = OutPoint::new(*parent.txid().as_ref(), 0); - db.put_received_transparent_utxo( - &WalletTransparentOutput::from_parts( - outpoint.clone(), - txout.clone(), - Some(height), - Some(owner), - None, - None, - ) - .unwrap(), - ) - .unwrap(); - let request_for = |db: &Db| { - db.transaction_data_requests() - .unwrap() - .into_iter() - .find_map(|request| match request { - TransactionDataRequest::TransactionsInvolvingAddress(request) - if request.address() == address => - { - Some(request) - } - _ => None, - }) - .unwrap() - }; - store_account_transaction(&mut db, owner, &parent, height, None).unwrap(); - db.update_chain_tip(height + 400).unwrap(); - let initial = request_for(&db); - let error_stream = futures_util::stream::iter(vec![Err::( - net_err("testStream", "interrupted"), - )]); - assert!( - complete_transparent_spend_check(&mut db, owner, initial.clone(), error_stream) - .await - .is_err() - ); - assert_eq!( - request_for(&db).block_range_start(), - initial.block_range_start() - ); - let empty_stream = - futures_util::stream::iter(Vec::>::new()); - complete_transparent_spend_check(&mut db, owner, initial.clone(), empty_stream) - .await - .unwrap(); - assert_eq!( - request_for(&db).block_range_start(), - initial.block_range_end().unwrap() - ); - assert!(db - .get_unspent_transparent_output(&outpoint, (height + 401).into()) - .unwrap() - .is_some()); - - let next = request_for(&db); - let mut data = vec![]; - parent.write(&mut data).unwrap(); - let outside_range = - futures_util::stream::iter(vec![Ok::<_, RuntimeError>(service::RawTransaction { - data, - height: u64::from(next.block_range_end().unwrap()), - })]); - assert!( - complete_transparent_spend_check(&mut db, owner, next.clone(), outside_range) - .await - .is_err() - ); - assert_eq!( - request_for(&db).block_range_start(), - next.block_range_start() - ); - - let spend = transparent_fixture(vec![outpoint.clone()], vec![txout]); - let mut data = vec![]; - spend.write(&mut data).unwrap(); - let partial_stream = futures_util::stream::iter(vec![ - Ok(service::RawTransaction { - data, - height: u64::from(next.block_range_start()), - }), - Err(net_err("testStream", "interrupted after transaction")), - ]); - assert!( - complete_transparent_spend_check(&mut db, owner, next, partial_stream) - .await - .is_err() - ); - // A positively observed spend remains valid even when later stream data - // fails; missing entries alone never changed spentness above. - assert!(db - .get_unspent_transparent_output(&outpoint, (height + 401).into()) - .unwrap() - .is_none()); + fn only_a_contiguous_prefix_of_the_range_is_accepted() { + assert!(check_block_sequence(10, 13, [10u64, 11, 12].into_iter()).is_ok()); + assert!(check_block_sequence(10, 13, [10u64, 11].into_iter()).is_ok()); + assert!(check_block_sequence(10, 13, [11u64].into_iter()).is_err()); + assert!(check_block_sequence(10, 13, [10u64, 10].into_iter()).is_err()); + assert!(check_block_sequence(10, 13, [10u64, 12].into_iter()).is_err()); + assert!(check_block_sequence(10, 12, [10u64, 11, 12].into_iter()).is_err()); } fn selected_ufvks_for( diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs index bbeb8d530..bcb0758da 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs @@ -101,7 +101,7 @@ pub fn insert_finalized( FROM v_tx_outputs output WHERE output.txid = ?1 AND output.from_account_uuid = ?2 - AND output.to_account_uuid IS NULL + AND (output.to_account_uuid IS NULL OR output.to_account_uuid <> ?2) AND COALESCE(output.is_change, 0) = 0 LIMIT 1), 'pending' @@ -275,6 +275,83 @@ pub fn remove_account_rows(ext: &ExtensionTransaction<'_>, account_uuid: &str) - #[cfg(test)] mod tests { use super::*; + use crate::clock::HostClock; + use rand::SeedableRng; + use rand_chacha::ChaCha20Rng; + use zcash_client_sqlite::WalletDb; + use zcash_protocol::consensus::Network; + + #[test] + fn finalized_recipient_is_external_to_the_sending_account() { + let mut conn = rusqlite::Connection::open_in_memory().unwrap(); + conn.execute_batch( + "CREATE TABLE ext_onekey_tx_state ( + txid BLOB PRIMARY KEY NOT NULL, + account_uuid BLOB NOT NULL, + reservation_id TEXT UNIQUE, + recipient TEXT, + broadcast_state TEXT NOT NULL, + rejection_code INTEGER, + rejection_reason TEXT + ); + CREATE TABLE v_tx_outputs ( + txid BLOB NOT NULL, + from_account_uuid BLOB, + to_account_uuid BLOB, + to_address TEXT, + is_change INTEGER + );", + ) + .unwrap(); + let sender = Uuid::from_u128(1); + let receiver = Uuid::from_u128(2); + let cases = [ + (Some(receiver), false, Some("synthetic-recipient")), + (None, false, Some("synthetic-recipient")), + (Some(sender), false, None), + (Some(sender), true, None), + ]; + for (index, (to_account, is_change, expected_recipient)) in cases.into_iter().enumerate() { + let txid = vec![index as u8; 32]; + conn.execute( + "INSERT INTO v_tx_outputs ( + txid, from_account_uuid, to_account_uuid, to_address, is_change + ) VALUES (?1, ?2, ?3, 'synthetic-recipient', ?4)", + params![ + txid, + sender.as_bytes().as_slice(), + to_account.map(|account| account.as_bytes().to_vec()), + is_change + ], + ) + .unwrap(); + { + let mut db = WalletDb::from_connection( + &mut conn, + Network::TestNetwork, + HostClock, + ChaCha20Rng::from_seed([7; 32]), + ); + db.transactionally_with_extension(|_wallet, ext| { + insert_finalized( + ext, + &hex_display_order(&txid), + &sender.to_string(), + &format!("reservation-{index}"), + ) + }) + .unwrap(); + } + let recipient: Option = conn + .query_row( + "SELECT recipient FROM ext_onekey_tx_state WHERE txid = ?1", + [txid], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(recipient.as_deref(), expected_recipient); + } + } #[test] fn only_runtime_owned_active_intents_are_unresolved_and_rebroadcastable() { diff --git a/chain-runtimes/zcash/scripts/build-wasm.sh b/chain-runtimes/zcash/scripts/build-wasm.sh index 6bb420176..224c59269 100755 --- a/chain-runtimes/zcash/scripts/build-wasm.sh +++ b/chain-runtimes/zcash/scripts/build-wasm.sh @@ -52,6 +52,13 @@ export AR_wasm32_unknown_unknown="${AR_wasm32_unknown_unknown:-$(dirname "${CLAN bash "${ROOT}/scripts/vendor-deps.sh" "$@" +# --mode no-install 找不到 wasm-opt 只会打一行 INFO 然后跳过:产物不报错地胖一倍 +#(函数名段不剥、不做 -O)。release 必须有它。 +if [ "${PROFILE}" = "release" ] && ! command -v wasm-opt >/dev/null 2>&1; then + echo "✗ 找不到 wasm-opt(Binaryen),release 产物会不经优化直接输出" >&2 + exit 1 +fi + echo "==> wasm-pack build (${PROFILE})" cd "${ROOT}/crates/zcash-runtime" case "${PROFILE}" in From e6c570154655fe64401a455aba067b28d92336b7 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 16:56:12 +0800 Subject: [PATCH 12/97] feat(monero): bind signing to a reviewed request and claim inputs before signing - add review.rs: verify recipients, amount, fee and change of a signable transaction against the approved request before signing - mark a reservation signed atomically before the host obtains a signature; signed reservations no longer expire with the unsigned TTL - reuse one RingCT output distribution per prepare --- .../crates/monero-runtime/src/bindgen.rs | 23 +- .../monero/crates/monero-runtime/src/lib.rs | 1 + .../crates/monero-runtime/src/network.rs | 14 +- .../monero/crates/monero-runtime/src/query.rs | 4 +- .../crates/monero-runtime/src/review.rs | 325 ++++++++++++++++++ .../monero/crates/monero-runtime/src/spend.rs | 138 ++++++-- .../monero/crates/monero-runtime/src/sync.rs | 10 +- 7 files changed, 468 insertions(+), 47 deletions(-) create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/review.rs diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs index 79ccf4ee7..1a2193745 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs @@ -282,10 +282,13 @@ pub fn validate_address(network: &str, address: &str) -> std::result::Result std::result::Result { - let n = runtime::with_db(|db| spend::mark_signed(db, reservation_id))?; +pub fn mark_reservation_signed( + reservation_id: &str, + expected_inputs: u32, +) -> std::result::Result { + let n = runtime::with_db(|db| spend::mark_signed(db, reservation_id, expected_inputs))?; json(serde_json::json!({ "marked": n })) } @@ -437,9 +440,21 @@ pub async fn prepare_transaction( pub fn sign_transaction( signable_hex: &str, spend_private_key_hex: &str, + review_json: &str, ) -> std::result::Result { let spend = Zeroizing::new(decode_hex(spend_private_key_hex, "spendPrivateKeyHex")?); - json(spend::sign_for_host(signable_hex, &spend)?) + json(spend::sign_for_host(signable_hex, &spend, review_json)?) +} + +/// Validate actual payment effects before the host presents its confirmation. +#[wasm_bindgen(js_name = verifyTransaction)] +pub fn verify_transaction( + signable_hex: &str, + review_json: &str, +) -> std::result::Result<(), JsValue> { + let request = crate::review::parse_request(review_json)?; + crate::review::verify(signable_hex, &request, None)?; + Ok(()) } /// 广播一笔已签名的交易。**不可逆。** diff --git a/chain-runtimes/monero/crates/monero-runtime/src/lib.rs b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs index f969d011b..50b94e0e5 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/lib.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs @@ -22,6 +22,7 @@ pub mod network; pub mod perf; pub mod pool; pub mod query; +pub mod review; pub mod runtime; pub mod scan; pub mod schema; diff --git a/chain-runtimes/monero/crates/monero-runtime/src/network.rs b/chain-runtimes/monero/crates/monero-runtime/src/network.rs index f5d02a9f6..2db388ab7 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/network.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/network.rs @@ -182,6 +182,11 @@ fn describe_js(value: &wasm_bindgen::JsValue) -> String { #[cfg(target_arch = "wasm32")] const REQUEST_TIMEOUT_MS: u32 = 45_000; +// The host enforces a per-chunk idle limit. Its backstop must allow a large +// response to keep progressing on a slow link, matching the Worker relay. +#[cfg(target_arch = "wasm32")] +const HOST_REQUEST_TIMEOUT_MS: u32 = 10 * 60 * 1000; + /// 浏览器载体里的传输实现,基于 `fetch`。 #[cfg(target_arch = "wasm32")] #[derive(Clone, Debug)] @@ -209,12 +214,17 @@ impl FetchTransport { let url = format!("{base_url}/{}", route.trim_start_matches('/')); let request = Box::pin(Self::post_untimed(base_url, route, body, limit)); - let timeout = gloo_timers::future::TimeoutFuture::new(REQUEST_TIMEOUT_MS); + let timeout_ms = if host_handler().is_some() { + HOST_REQUEST_TIMEOUT_MS + } else { + REQUEST_TIMEOUT_MS + }; + let timeout = gloo_timers::future::TimeoutFuture::new(timeout_ms); match select(request, timeout).await { Either::Left((result, _)) => result, Either::Right(_) => Err(InterfaceError::InterfaceError(format!( "{url}: {} 秒没有响应", - REQUEST_TIMEOUT_MS / 1000 + timeout_ms / 1000 ))), } } diff --git a/chain-runtimes/monero/crates/monero-runtime/src/query.rs b/chain-runtimes/monero/crates/monero-runtime/src/query.rs index 21f20d386..b9f931ae2 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/query.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs @@ -62,7 +62,7 @@ pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result ?2 + LEFT JOIN locked_outputs l ON l.output_id = o.id AND (l.locked_at > ?2 OR l.signed_at IS NOT NULL) WHERE o.identity_id = ?1 AND o.spent_at_height IS NULL", ) .map_err(|e| db_err("balanceQuery", e))?; @@ -173,7 +173,7 @@ pub fn spendable_rows(db: &Db, identity_id: i64, chain_tip: u64) -> Result ?2 + LEFT JOIN locked_outputs l ON l.output_id = o.id AND (l.locked_at > ?2 OR l.signed_at IS NOT NULL) WHERE o.identity_id = ?1 AND o.spent_at_height IS NULL AND o.key_image IS NOT NULL diff --git a/chain-runtimes/monero/crates/monero-runtime/src/review.rs b/chain-runtimes/monero/crates/monero-runtime/src/review.rs new file mode 100644 index 000000000..d67557f14 --- /dev/null +++ b/chain-runtimes/monero/crates/monero-runtime/src/review.rs @@ -0,0 +1,325 @@ +use monero_wallet::{ + address::MoneroAddress, + ed25519::{CompressedPoint, Point, Scalar}, + io::{read_byte, read_bytes, read_u32, read_u64, read_vec}, + send::SignableTransaction, + OutputWithDecoys, +}; +use serde::Deserialize; +use zeroize::Zeroizing; + +use crate::{ + error::{ErrorCode, Result, RuntimeError}, + keys, +}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewRequest { + pub network: String, + pub from_address: String, + pub to_address: String, + pub amount_atomic: String, + pub fee_atomic: String, + pub change_atomic: String, + pub is_max_send: bool, +} + +fn mismatch(field: &str) -> RuntimeError { + RuntimeError::with( + ErrorCode::InvalidRequest, + serde_json::json!({"field": field, "reason": "transactionDoesNotMatchReview"}), + ) +} + +fn amount(value: &str) -> Result { + let parsed = value.parse::().map_err(|_| mismatch("amount"))?; + if parsed.to_string() != value { + return Err(mismatch("amount")); + } + Ok(parsed) +} + +pub fn parse_request(json: &str) -> Result { + serde_json::from_str(json).map_err(|_| mismatch("reviewRequest")) +} + +/// Read the pinned monero-wallet 0.2 serialization after its own strict validator. +/// Its payment fields are private, so inspection uses its public wire readers. +pub fn verify( + signable_hex: &str, + request: &ReviewRequest, + spend_key: Option<&[u8]>, +) -> Result { + if signable_hex.len() > 8 * 1024 * 1024 { + return Err(mismatch("signableSize")); + } + let bytes = Zeroizing::new(hex::decode(signable_hex).map_err(|_| mismatch("signableHex"))?); + let mut reader = bytes.as_slice(); + let signable = SignableTransaction::read(&mut reader).map_err(|_| mismatch("signableHex"))?; + if !reader.is_empty() { + return Err(mismatch("trailingBytes")); + } + let network = keys::parse_network(&request.network)?; + let expected_recipient = keys::parse_address(network, &request.to_address, "toAddress")?; + let expected_sender = keys::parse_address(network, &request.from_address, "fromAddress")?; + let expected_amount = amount(&request.amount_atomic)?; + let expected_fee = amount(&request.fee_atomic)?; + let expected_change = amount(&request.change_atomic)?; + let inspect = || -> std::io::Result<(u64, u64)> { + let mut reader = bytes.as_slice(); + read_byte(&mut reader)?; + let _outgoing_view_key = Zeroizing::new(read_bytes::<_, 32>(&mut reader)?); + let inputs = read_vec(OutputWithDecoys::read, Some(1024), &mut reader)?; + let total = inputs.iter().try_fold(0u64, |sum, input| { + sum.checked_add(input.commitment().amount) + .ok_or_else(|| std::io::Error::other("input amount overflow")) + })?; + let mut paid = None; + let mut change_seen = false; + read_vec( + |reader| { + match read_byte(reader)? { + 0 => { + let address_bytes = + read_vec(read_byte, Some(MoneroAddress::SIZE_UPPER_BOUND.0), reader)?; + let address = + String::from_utf8(address_bytes).map_err(std::io::Error::other)?; + let address = MoneroAddress::from_str(network, &address) + .map_err(std::io::Error::other)?; + let value = read_u64(reader)?; + if paid.is_some() + || address != expected_recipient + || value != expected_amount + || value == 0 + { + return Err(std::io::Error::other("unapproved recipient or amount")); + } + paid = Some(value); + } + 2 => { + let spend = CompressedPoint::read(reader)?.to_bytes(); + let view = Zeroizing::new(read_bytes::<_, 32>(reader)?); + let pair = keys::view_pair_from_bytes(&spend, view.as_ref()) + .map_err(|_| std::io::Error::other("invalid change keys"))?; + if change_seen + || read_u32(reader)? != 0 + || read_u32(reader)? != 0 + || pair.legacy_address(network) != expected_sender + { + return Err(std::io::Error::other("unapproved change")); + } + if let Some(key) = spend_key { + let scalar = Zeroizing::new(Scalar::read(&mut key.as_ref())?); + let public = Point::from( + (*scalar).into() + * curve25519_dalek::constants::ED25519_BASEPOINT_POINT, + ); + let private_view = + Zeroizing::new(Scalar::hash(<[u8; 32]>::from(*scalar))); + if public.compress().to_bytes() != spend + || <[u8; 32]>::from(*private_view) != *view + { + return Err(std::io::Error::other("change is not owned by signer")); + } + } + change_seen = true; + } + _ => return Err(std::io::Error::other("unsupported change type")), + } + Ok(()) + }, + Some(16), + &mut reader, + )?; + if !change_seen || paid.is_none() { + return Err(std::io::Error::other("missing payment or change")); + } + let data = read_vec( + |reader| read_vec(read_byte, Some(255), reader), + Some(255), + &mut reader, + )?; + if !data.is_empty() { + return Err(std::io::Error::other("unapproved transaction extra")); + } + Ok((total, paid.expect("checked above"))) + }; + let (inputs, paid) = inspect().map_err(|_| mismatch("paymentOrChange"))?; + let actual_fee = signable.necessary_fee(); + let change = inputs + .checked_sub(paid) + .and_then(|value| value.checked_sub(actual_fee)) + .ok_or_else(|| mismatch("amounts"))?; + if actual_fee != expected_fee + || change != expected_change + || (request.is_max_send && change != 0) + { + return Err(mismatch("feeOrChange")); + } + Ok(signable) +} + +#[cfg(test)] +mod tests { + use super::*; + use monero_wallet::{ + address::Network, + ed25519::Commitment, + interface::FeeRate, + ringct::{clsag::Decoys, RctType}, + send::Change, + ViewPair, + }; + + const RECIPIENT: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge"; + const OTHER: &str = "44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft3XjrpDtQGv7SqSsaBYBb98uNbr2VBBEt7f2wfn3RVGQBEP3A"; + const INPUT_AMOUNT: u64 = 2_000_000_000_000; + const PAYMENT_AMOUNT: u64 = 1_000_000_000_000; + + fn scalar(value: u8) -> Scalar { + let mut bytes = [0u8; 32]; + bytes[0] = value; + Scalar::read(&mut bytes.as_slice()).unwrap() + } + + // Public, deterministic test keys and invented outputs; no node or funds. + fn fixture(extra: Vec>) -> (Vec, ReviewRequest, [u8; 32]) { + let mut public_bytes = [0x66u8; 32]; + public_bytes[0] = 0x58; + let public = CompressedPoint::from(public_bytes).decompress().unwrap(); + let commitment = Commitment::new(scalar(1), INPUT_AMOUNT); + let mut input_bytes = Vec::new(); + input_bytes.extend(public_bytes); + scalar(0).write(&mut input_bytes).unwrap(); + commitment.write(&mut input_bytes).unwrap(); + let members = (0..16) + .map(|index| { + if index == 0 { + [public, commitment.commit()] + } else { + [ + Point::biased_hash([index; 32]), + Point::biased_hash([index + 100; 32]), + ] + } + }) + .collect(); + Decoys::new(vec![1; 16], 0, members) + .unwrap() + .write(&mut input_bytes) + .unwrap(); + let input = OutputWithDecoys::read(&mut input_bytes.as_slice()).unwrap(); + let spend_bytes = <[u8; 32]>::from(scalar(1)); + let pair = ViewPair::new(public, Zeroizing::new(Scalar::hash(spend_bytes))).unwrap(); + let sender = pair.legacy_address(Network::Mainnet).to_string(); + let tx = SignableTransaction::new( + RctType::ClsagBulletproofPlus, + Zeroizing::new([7; 32]), + vec![input], + vec![( + MoneroAddress::from_str(Network::Mainnet, RECIPIENT).unwrap(), + PAYMENT_AMOUNT, + )], + Change::new(pair, None), + extra, + FeeRate::new(20_000, 1).unwrap(), + ) + .unwrap(); + let fee = tx.necessary_fee(); + let review = ReviewRequest { + network: "mainnet".into(), + from_address: sender, + to_address: RECIPIENT.into(), + amount_atomic: PAYMENT_AMOUNT.to_string(), + fee_atomic: fee.to_string(), + change_atomic: (INPUT_AMOUNT - PAYMENT_AMOUNT - fee).to_string(), + is_max_send: false, + }; + (tx.serialize(), review, spend_bytes) + } + + #[test] + fn approved_transaction_is_verified_and_signed() { + let (bytes, review, spend) = fixture(vec![]); + let encoded = hex::encode(bytes); + verify(&encoded, &review, None).unwrap(); + let json = serde_json::json!({ + "network": review.network, "fromAddress": review.from_address, + "toAddress": review.to_address, "amountAtomic": review.amount_atomic, + "feeAtomic": review.fee_atomic, "changeAtomic": review.change_atomic, + "isMaxSend": review.is_max_send, + }) + .to_string(); + let signed = crate::spend::sign_for_host(&encoded, &spend, &json).unwrap(); + assert_eq!(signed["txid"].as_str().unwrap().len(), 64); + assert!(!signed["rawHex"].as_str().unwrap().is_empty()); + } + + #[test] + fn replacing_actual_recipient_is_rejected_with_unchanged_review() { + let (mut bytes, review, spend) = fixture(vec![]); + let position = bytes + .windows(RECIPIENT.len()) + .position(|part| part == RECIPIENT.as_bytes()) + .unwrap(); + bytes[position..position + RECIPIENT.len()].copy_from_slice(OTHER.as_bytes()); + assert!(verify(&hex::encode(bytes), &review, Some(&spend)).is_err()); + } + + #[test] + fn amount_fee_change_max_sender_and_network_must_match() { + for field in [ + "amount", + "fee", + "change", + "max", + "sender", + "network", + "recipient", + ] { + let (bytes, mut review, spend) = fixture(vec![]); + match field { + "amount" => review.amount_atomic = "999999999999".into(), + "fee" => { + review.fee_atomic = (review.fee_atomic.parse::().unwrap() + 1).to_string() + } + "change" => review.change_atomic = "0".into(), + "max" => review.is_max_send = true, + "sender" => review.from_address = OTHER.into(), + "network" => review.network = "testnet".into(), + "recipient" => review.to_address = OTHER.into(), + _ => unreachable!(), + } + assert!( + verify(&hex::encode(bytes), &review, Some(&spend)).is_err(), + "{field}" + ); + } + } + + #[test] + fn another_spend_key_cannot_authorize_the_change() { + let (bytes, review, _) = fixture(vec![]); + assert!(verify( + &hex::encode(bytes), + &review, + Some(&<[u8; 32]>::from(scalar(2))) + ) + .is_err()); + } + + #[test] + fn suffix_extra_and_noncanonical_amounts_are_rejected() { + let (mut bytes, review, spend) = fixture(vec![]); + bytes.push(0); + assert!(verify(&hex::encode(bytes), &review, Some(&spend)).is_err()); + let (bytes, review, spend) = fixture(vec![vec![1, 2, 3]]); + assert!(verify(&hex::encode(bytes), &review, Some(&spend)).is_err()); + for bad in ["01", "-1", "1e12", "18446744073709551616"] { + let (bytes, mut review, spend) = fixture(vec![]); + review.amount_atomic = bad.into(); + assert!(verify(&hex::encode(bytes), &review, Some(&spend)).is_err()); + } + } +} diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs index 619ea371f..492cd4e01 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs @@ -257,10 +257,7 @@ pub fn select_inputs( }) } -/// 预留多久没广播就作废。Monero 交易没有过期高度,只能按时间。 -/// -/// 作废之后再广播也不会丢记账(广播按交易里的 key image 标记已花),最坏是 -/// 期间另一笔选中同样的输出、其中一笔被节点拒收。 +/// Unsigned review reservations expire; signed inputs remain held until resolved. pub const RESERVATION_TTL_SECS: i64 = 60 * 60; /// 仍然有效的预留的下限时间:`locked_at` 大于它才算数。 @@ -280,7 +277,7 @@ pub fn reserve(db: &mut Db, reservation_id: &str, output_ids: &[i64]) -> Result< .map_err(|e| db_err("beginReserve", e))?; // 用户在确认页退出不会通知这里,作废的预留只能在这时清掉。 tx.execute( - "DELETE FROM locked_outputs WHERE locked_at <= ?1", + "DELETE FROM locked_outputs WHERE locked_at <= ?1 AND signed_at IS NULL", [now - RESERVATION_TTL_SECS], ) .map_err(|e| db_err("expireReservations", e))?; @@ -301,14 +298,49 @@ pub fn reserve(db: &mut Db, reservation_id: &str, output_ids: &[i64]) -> Result< tx.commit().map_err(|e| db_err("commitReserve", e)) } -/// 宿主签好名了:这笔预留不再算作被放弃的。 -pub fn mark_signed(db: &Db, reservation_id: &str) -> Result { - db.conn() +/// Atomically claim every live input before the host obtains a spend signature. +pub fn mark_signed(db: &mut Db, reservation_id: &str, expected_inputs: u32) -> Result { + let stale = || { + RuntimeError::with( + ErrorCode::InvalidRequest, + json!({"reason": "staleReservation"}), + ) + }; + if expected_inputs == 0 || expected_inputs > 1024 { + return Err(stale()); + } + let tx = db + .conn_mut() + .transaction() + .map_err(|e| db_err("beginSignReservation", e))?; + let count: u32 = tx + .query_row( + "SELECT count(*) FROM locked_outputs WHERE reservation_id = ?1", + [reservation_id], + |row| row.get(0), + ) + .map_err(|e| db_err("readSignReservation", e))?; + if count != expected_inputs { + return Err(stale()); + } + let marked = tx .execute( - "UPDATE locked_outputs SET signed_at = ?2 WHERE reservation_id = ?1", - params![reservation_id, crate::wallet::now_secs()], + "UPDATE locked_outputs SET signed_at = ?2 + WHERE reservation_id = ?1 AND signed_at IS NULL AND locked_at > ?3 + AND output_id IN (SELECT id FROM outputs WHERE spent_at_height IS NULL)", + params![ + reservation_id, + crate::wallet::now_secs(), + reservation_cutoff() + ], ) - .map_err(|e| db_err("markReservationSigned", e)) + .map_err(|e| db_err("markReservationSigned", e))?; + if u32::try_from(marked).map_err(|_| stale())? != expected_inputs { + return Err(stale()); + } + tx.commit() + .map_err(|e| db_err("commitSignReservation", e))?; + Ok(marked) } /// 放掉本身份所有没签名的预留。 @@ -882,17 +914,17 @@ mod tests { assert_eq!(left, 0, "有了 key image 的输出不再需要可能花费记录"); } - /// 签名入口不碰网络也不碰库,所以它唯一能出的错就是入参形状。 - /// 这里盯的是「坏输入必须报错」——静默接受会让一笔垃圾交易一路走到广播。 + // Invalid transaction bytes must fail before signing, even with a review attached. #[test] fn signing_rejects_a_blob_that_is_not_a_signable_transaction() { - let e = sign_for_host("zz", &[0u8; 32]).unwrap_err(); + let review = r#"{"network":"mainnet","fromAddress":"unused","toAddress":"unused","amountAtomic":"1","feeAtomic":"1","changeAtomic":"0","isMaxSend":false}"#; + let e = sign_for_host("zz", &[0u8; 32], review).unwrap_err(); assert_eq!(e.code, ErrorCode::InvalidRequest); - assert_eq!(e.params["reason"], "notHex"); + assert_eq!(e.params["reason"], "transactionDoesNotMatchReview"); - let e = sign_for_host("00010203", &[0u8; 32]).unwrap_err(); + let e = sign_for_host("00010203", &[0u8; 32], review).unwrap_err(); assert_eq!(e.code, ErrorCode::InvalidRequest); - assert_eq!(e.params["reason"], "notASignableTransaction"); + assert_eq!(e.params["reason"], "transactionDoesNotMatchReview"); } /// 金额相加溢出必须报错而不是回绕。回绕会让一笔「收款方总额 0」的交易 @@ -993,7 +1025,7 @@ mod tests { let signed = add_output(&db, id, 400, 11, true); reserve(&mut db, "abandoned", &[abandoned]).unwrap(); reserve(&mut db, "signed", &[signed]).unwrap(); - mark_signed(&db, "signed").unwrap(); + mark_signed(&mut db, "signed", 1).unwrap(); assert_eq!(release_unsigned(&db, id).unwrap(), 1); @@ -1008,6 +1040,59 @@ mod tests { assert_eq!(left, vec!["signed".to_string()]); } + #[test] + fn signing_rejects_expired_partial_or_replayed_reservations_atomically() { + let (mut db, id) = db_with_identity(); + let first = add_output(&db, id, 500, 10, true); + let second = add_output(&db, id, 400, 11, true); + reserve(&mut db, "review", &[first, second]).unwrap(); + assert!(mark_signed(&mut db, "review", 1).is_err()); + db.conn() + .execute( + "UPDATE locked_outputs SET locked_at = ?1 WHERE output_id = ?2", + params![reservation_cutoff(), second], + ) + .unwrap(); + assert!(mark_signed(&mut db, "review", 2).is_err()); + let marked: i64 = db + .conn() + .query_row( + "SELECT count(*) FROM locked_outputs WHERE signed_at IS NOT NULL", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(marked, 0, "partial claims must roll back"); + db.conn() + .execute("DELETE FROM locked_outputs WHERE output_id = ?1", [second]) + .unwrap(); + assert!(mark_signed(&mut db, "review", 2).is_err()); + mark_signed(&mut db, "review", 1).unwrap(); + assert!(mark_signed(&mut db, "review", 1).is_err()); + } + + #[test] + fn signed_reservations_stay_unspendable_after_the_unsigned_ttl() { + let (mut db, id) = db_with_identity(); + let input = add_output(&db, id, 500, 10, true); + reserve(&mut db, "signed", &[input]).unwrap(); + mark_signed(&mut db, "signed", 1).unwrap(); + db.conn() + .execute( + "UPDATE locked_outputs SET locked_at = ?1", + [reservation_cutoff() - 1], + ) + .unwrap(); + assert!(query::spendable_rows(&db, id, 100).unwrap().is_empty()); + assert_eq!( + query::balance(&db, id, Some(100)) + .unwrap() + .locked_by_reservation_atomic, + 500 + ); + assert!(reserve(&mut db, "replacement", &[input]).is_err()); + } + /// wallet2 同款:待确认发送的找零计入总余额(锁定),不计入可用;判失败后不再计。 #[test] fn pending_change_counts_in_total_until_the_send_fails() { @@ -1280,20 +1365,9 @@ pub async fn prepare_for_host( } /// 签名一笔已构造的交易。**不碰网络、不碰数据库。** -pub fn sign_for_host(signable_hex: &str, spend_private: &[u8]) -> Result { - let bytes = hex::decode(signable_hex).map_err(|_| { - RuntimeError::with( - ErrorCode::InvalidRequest, - json!({ "field": "signableHex", "reason": "notHex" }), - ) - })?; - let signable = SignableTransaction::read(&mut bytes.as_slice()).map_err(|e| { - RuntimeError::with( - ErrorCode::InvalidRequest, - json!({ "field": "signableHex", "reason": "notASignableTransaction" }), - ) - .detail(format!("{e:?}")) - })?; +pub fn sign_for_host(signable_hex: &str, spend_private: &[u8], review_json: &str) -> Result { + let request = crate::review::parse_request(review_json)?; + let signable = crate::review::verify(signable_hex, &request, Some(spend_private))?; let mut rng = rand_core::OsRng; let (raw, txid) = sign_prepared(signable, &mut rng, spend_private)?; Ok(json!({ diff --git a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs index 90f0790c3..f803c0f2a 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs @@ -28,13 +28,9 @@ use crate::wallet::Db; /// 且中途无法中断。真正的批量由宿主按实测吞吐决定。 pub const MAX_BLOCKS_PER_CALL: u64 = 1_000; -/// 同时在途的取块请求数。 -/// -/// 取块是**延迟**型而不是带宽型:一块要 3~4 次往返(区块、交易、输出索引), -/// 每次 130~230 ms,实测串行时 ~1.36 s/块。块与块之间没有依赖,并发 N 个 -/// 就把墙钟时间压到约 1/N。取 6 是因为浏览器、插件后台、RN 的 HTTP 栈对 -/// 同一 host 的连接上限都在这个量级,再高只会排队,还更容易被公共节点限流。 -pub const FETCH_CONCURRENCY: usize = 6; +/// Limit per-block fallback requests to three, leaving the host's fourth +/// stream slot available for a chain-tip probe or another privacy chain. +pub const FETCH_CONCURRENCY: usize = 3; /// 问链尖。**不碰钱包库** —— 建账户时需要它来定 birthday,而那一刻库还没建。 pub async fn chain_tip(daemon: &Daemon) -> Result { From e4dde24e7b4ebb0696b7c94bcde204e4d6583d34 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 16:56:12 +0800 Subject: [PATCH 13/97] feat(zcash): review PCZTs before signing and route lightwalletd through the host - add keys review.rs: check every spend and output of a PCZT against the approved request before signing with the seed - add circuit_keys.rs and pick the Orchard circuit by the transaction's branch - vendor tonic-web-wasm-client with a host fetch handler patch - harden transparent send and shielding request validation --- chain-runtimes/zcash/Cargo.lock | 3 +- chain-runtimes/zcash/Cargo.toml | 2 + .../crates/zcash-keys-runtime/src/bindgen.rs | 10 +- .../crates/zcash-keys-runtime/src/lib.rs | 1 + .../crates/zcash-keys-runtime/src/review.rs | 467 ++++++++++++++++++ .../src/transparent_send.rs | 29 +- .../src/transparent_send/shielding.rs | 36 +- .../zcash/crates/zcash-runtime/Cargo.toml | 1 + .../zcash/crates/zcash-runtime/src/bindgen.rs | 28 +- .../crates/zcash-runtime/src/circuit_keys.rs | 79 +++ .../zcash/crates/zcash-runtime/src/history.rs | 181 ++++++- .../zcash/crates/zcash-runtime/src/lib.rs | 1 + .../zcash/crates/zcash-runtime/src/network.rs | 18 +- .../zcash/crates/zcash-runtime/src/send.rs | 368 +++++++++----- .../zcash/crates/zcash-runtime/src/sync.rs | 211 +++++++- .../crates/zcash-runtime/src/tx_state.rs | 12 +- chain-runtimes/zcash/patches/manifest.json | 6 + ...nic-web-wasm-client-0.9.1-host-fetch.patch | 47 ++ 18 files changed, 1356 insertions(+), 144 deletions(-) create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/circuit_keys.rs create mode 100644 chain-runtimes/zcash/patches/tonic-web-wasm-client-0.9.1-host-fetch.patch diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock index fb53d016c..e3a22c816 100644 --- a/chain-runtimes/zcash/Cargo.lock +++ b/chain-runtimes/zcash/Cargo.lock @@ -1687,6 +1687,7 @@ dependencies = [ name = "onekey-zcash-runtime" version = "0.1.0-rc.1" dependencies = [ + "blake2b_simd", "console_error_panic_hook", "futures", "futures-util", @@ -2932,8 +2933,6 @@ dependencies = [ [[package]] name = "tonic-web-wasm-client" version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c0469c353de5f665c95f898074b5b004b500c6722214c3249f1dc79c0a2a3f6" dependencies = [ "base64", "byteorder", diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml index 316334a8f..fce978a00 100644 --- a/chain-runtimes/zcash/Cargo.toml +++ b/chain-runtimes/zcash/Cargo.toml @@ -23,6 +23,7 @@ rust-version = "1.85" # 那个 feature 会在构建期编译 SQLite 的 C 源码,而 wasm32 没有 libc sysroot。 # Zcash Rust 源码零改动。VFS 的持久化补丁另见 patches/manifest.json。 [workspace.dependencies] +blake2b_simd = "1" zcash_client_backend = { version = "0.24.0", default-features = false, features = ["orchard", "transparent-inputs", "lightwalletd-tonic", "sync", "pczt"] } # serde: create_pczt_from_proposal 要求 AccountId: Serialize zcash_client_sqlite = { version = "0.22.0", default-features = false, features = ["orchard", "transparent-inputs", "serde"] } @@ -77,6 +78,7 @@ tonic-web-wasm-client = "0.9.1" # 先跑 `bash scripts/vendor-deps.sh` 生成 vendor/ 目录。 [patch.crates-io] zcash_client_sqlite = { path = "vendor/zcash_client_sqlite-0.22.0" } +tonic-web-wasm-client = { path = "vendor/tonic-web-wasm-client-0.9.1" } [profile.release] # "s" 是量过的选择,不是省事的默认:opt-level = 3 在主网扫描上快不出 diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs index 3b887660c..fa9db7953 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs @@ -5,7 +5,7 @@ use wasm_bindgen::prelude::*; use zeroize::Zeroizing; -use crate::{keys, sign, transparent_prevouts, transparent_send}; +use crate::{keys, review, sign, transparent_prevouts, transparent_send}; /// Check recipient encoding, network, and supported receivers locally. #[wasm_bindgen(js_name = validateAddress)] @@ -51,9 +51,11 @@ pub fn pczt_sign_with_seed( seed: Vec, account_index: u32, pczt_bytes: Vec, + review_json: &str, ) -> Result, JsValue> { let seed = Zeroizing::new(seed); let params = keys::parse_network(network)?; + review::verify_signer(params, &seed, account_index, &pczt_bytes, review_json)?; Ok(sign::sign_pczt_with_seed( params, &seed, @@ -62,6 +64,12 @@ pub fn pczt_sign_with_seed( )?) } +/// Verify a private payment before showing its confirmation or contacting a signer. +#[wasm_bindgen(js_name = pcztVerifyReview)] +pub fn pczt_verify_review(pczt_bytes: Vec, review_json: &str) -> Result<(), JsValue> { + Ok(review::verify_json(&pczt_bytes, review_json)?) +} + /// 从 UFVK 取透明收款地址(t 地址)。离线可算,不需要钱包库。 #[wasm_bindgen(js_name = transparentAddressFromUfvk)] pub fn transparent_address_from_ufvk(network: &str, ufvk: &str) -> Result { diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs index 5ccdcb1af..f4387ed28 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs @@ -16,6 +16,7 @@ pub mod error; pub mod keys; +pub mod review; pub mod sign; pub mod transparent_prevouts; pub mod transparent_send; diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs new file mode 100644 index 000000000..d595c3116 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs @@ -0,0 +1,467 @@ +use pczt::roles::verifier::{OrchardError, Verifier}; +use serde::Deserialize; +use zcash_keys::{address::Address, keys::UnifiedFullViewingKey}; +use zcash_note_encryption::Domain; +use zcash_protocol::{consensus::Network, memo::MemoBytes}; +use zcash_script::script::Evaluable; +use zip32::Scope; + +use crate::{ + error::{ErrorCode, KeysError, Result}, + keys, +}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewRequest { + pub network: String, + pub ufvk: String, + pub to_address: String, + pub amount_zat: String, + pub fee_zat: String, + pub spend_source: String, + pub is_max_send: bool, + pub memo_hex: Option, +} + +fn mismatch(field: &str) -> KeysError { + KeysError::with( + ErrorCode::InvalidTransactionRequest, + serde_json::json!({"field": field, "reason": "transactionDoesNotMatchReview"}), + ) +} + +fn amount(value: &str) -> Result { + let parsed = value.parse::().map_err(|_| mismatch("amount"))?; + if parsed.to_string() != value || parsed > 2_100_000_000_000_000 { + return Err(mismatch("amount")); + } + Ok(parsed) +} + +pub fn parse_request(json: &str) -> Result { + serde_json::from_str(json).map_err(|_| mismatch("reviewRequest")) +} + +/// Inspect actual effects and note ciphertexts; UI metadata is not authoritative. +pub fn verify(pczt_bytes: &[u8], request: &ReviewRequest) -> Result<()> { + if pczt_bytes.len() > 8 * 1024 * 1024 { + return Err(mismatch("pcztSize")); + } + let params = keys::parse_network(&request.network)?; + let ufvk = + UnifiedFullViewingKey::decode(¶ms, &request.ufvk).map_err(|_| mismatch("ufvk"))?; + let fvk = ufvk.orchard().ok_or_else(|| mismatch("ufvk"))?; + let recipient = keys::supported_recipient(¶ms, &request.to_address) + .ok_or_else(|| mismatch("recipient"))?; + let recipient_orchard = match &recipient { + Address::Unified(address) => address.orchard().copied(), + _ => None, + }; + let recipient_transparent = match recipient { + Address::Transparent(address) => Some(address), + // TEX recipients require transparent inputs, which this private path forbids. + _ => None, + }; + let expected_amount = amount(&request.amount_zat)?; + let expected_fee = amount(&request.fee_zat)?; + let expected_memo = super::transparent_send::parse_memo_hex(request.memo_hex.as_deref())?; + if request.memo_hex.is_some() && recipient_orchard.is_none() { + return Err(mismatch("memoRecipient")); + } + if expected_amount == 0 || !matches!(request.spend_source.as_str(), "orchard" | "ironwood") { + return Err(mismatch("spendSourceOrAmount")); + } + let pczt = pczt::Pczt::parse(pczt_bytes).map_err(|_| mismatch("pczt"))?; + if pczt.clone().serialize().map_err(|_| mismatch("pczt"))? != pczt_bytes { + return Err(mismatch("nonCanonicalPczt")); + } + if !pczt.transparent().inputs().is_empty() + || !pczt.sapling().spends().is_empty() + || !pczt.sapling().outputs().is_empty() + { + return Err(mismatch("unsupportedInputs")); + } + let mut paid = 0u64; + let mut fee = 0i128; + for output in pczt.transparent().outputs() { + let address = recipient_transparent.ok_or_else(|| mismatch("transparentOutput"))?; + if *output.script_pubkey() != address.script().to_bytes() { + return Err(mismatch("transparentRecipient")); + } + paid = paid + .checked_add(*output.value()) + .ok_or_else(|| mismatch("amount"))?; + fee -= i128::from(*output.value()); + } + let mut real_spends = 0usize; + let mut check_bundle = |bundle: &orchard::pczt::Bundle, + pool: &str| + -> std::result::Result<(), OrchardError> { + let custom = |field| OrchardError::Custom(mismatch(field)); + let (magnitude, sign) = bundle.value_sum().magnitude_sign(); + let value_sum = match sign { + orchard::value::Sign::Positive => i128::from(magnitude), + orchard::value::Sign::Negative => -i128::from(magnitude), + }; + let mut actual_value_sum = 0i128; + bundle.verify_cross_address_restriction()?; + for action in bundle.actions() { + let spend = action.spend(); + let output = action.output(); + let spend_value = spend.value().ok_or_else(|| custom("spendValue"))?; + if spend_value.inner() != 0 { + if pool != request.spend_source || spend.dummy_sk().is_some() { + return Err(custom("spendSource")); + } + real_spends += 1; + spend.verify_nullifier(Some(fvk))?; + spend.verify_rk(Some(fvk))?; + } + action.verify_cv_net()?; + output.verify_note_commitment(spend)?; + let value = output.value().ok_or_else(|| custom("outputValue"))?; + actual_value_sum += i128::from(spend_value.inner()) - i128::from(value.inner()); + if value.inner() == 0 { + continue; + } + let address = output + .recipient() + .ok_or_else(|| custom("outputRecipient"))?; + let is_recipient = Some(address) == recipient_orchard; + if is_recipient { + if pool != "ironwood" { + return Err(custom("recipientOutputPool")); + } + paid = paid + .checked_add(value.inner()) + .ok_or_else(|| custom("amount"))?; + } else if request.is_max_send + || fvk.scope_for_address(&address) != Some(Scope::Internal) + || (pool == "orchard" && request.spend_source != "orchard") + { + return Err(custom("changeOwnership")); + } + let note = orchard::Note::from_parts( + address, + value, + orchard::note::Rho::from_bytes(&spend.nullifier().to_bytes()) + .into_option() + .ok_or_else(|| custom("rho"))?, + output.rseed().ok_or_else(|| custom("rseed"))?, + *output.note_version(), + ) + .into_option() + .ok_or_else(|| custom("note"))?; + // Bind the approved memo to recipient ciphertext; change retains an empty memo. + let memo = if is_recipient { + *expected_memo.as_array() + } else { + *MemoBytes::empty().as_array() + }; + let (ciphertext, epk) = if pool == "ironwood" { + let encryptor = + orchard::note_encryption::IronwoodNoteEncryption::new(None, note, memo); + ( + encryptor.encrypt_note_plaintext(), + orchard::note_encryption::IronwoodDomain::epk_bytes(encryptor.epk()).0, + ) + } else { + let encryptor = + orchard::note_encryption::OrchardNoteEncryption::new(None, note, memo); + ( + encryptor.encrypt_note_plaintext(), + orchard::note_encryption::OrchardDomain::epk_bytes(encryptor.epk()).0, + ) + }; + if ciphertext != output.encrypted_note().enc_ciphertext + || epk != output.encrypted_note().epk_bytes + { + return Err(custom("outputCiphertext")); + } + } + if actual_value_sum != value_sum { + return Err(custom("bundleValueSum")); + } + fee += actual_value_sum; + Ok(()) + }; + Verifier::new(pczt) + .with_orchard(|bundle| check_bundle(bundle, "orchard")) + .and_then(|verifier| verifier.with_ironwood(|bundle| check_bundle(bundle, "ironwood"))) + .map_err(|_| mismatch("shieldedEffects"))?; + if real_spends == 0 || paid != expected_amount || fee != i128::from(expected_fee) { + return Err(mismatch("amountOrFee")); + } + Ok(()) +} + +pub fn verify_json(pczt_bytes: &[u8], json: &str) -> Result<()> { + verify(pczt_bytes, &parse_request(json)?) +} + +pub fn verify_signer( + params: Network, + seed: &[u8], + account_index: u32, + pczt_bytes: &[u8], + json: &str, +) -> Result<()> { + let request = parse_request(json)?; + if keys::parse_network(&request.network)? != params + || keys::ufvk_from_seed_bytes(params, seed, account_index)? != request.ufvk + { + return Err(mismatch("signerAccount")); + } + verify(pczt_bytes, &request) +} + +#[cfg(test)] +mod tests { + use super::*; + use pczt::roles::creator::Creator; + use zcash_primitives::transaction::{ + builder::{BuildConfig, Builder, BundlePadding}, + fees::fixed::FeeRule, + }; + use zcash_protocol::value::Zatoshis; + + fn fixture(source: &str, max: bool, foreign_change: bool) -> (Vec, ReviewRequest) { + fixture_with_memo(source, max, foreign_change, None) + } + + fn fixture_with_memo( + source: &str, + max: bool, + foreign_change: bool, + memo_hex: Option, + ) -> (Vec, ReviewRequest) { + let ufvk_string = keys::ufvk_from_seed_bytes(Network::MainNetwork, &[7; 32], 0).unwrap(); + let ufvk = UnifiedFullViewingKey::decode(&Network::MainNetwork, &ufvk_string).unwrap(); + let fvk = ufvk.orchard().unwrap().clone(); + let other = keys::ufvk_from_seed_bytes(Network::MainNetwork, &[8; 32], 0).unwrap(); + let other = UnifiedFullViewingKey::decode(&Network::MainNetwork, &other).unwrap(); + let receiver = other.orchard().unwrap().address_at(0u32, Scope::External); + let to_address = + keys::unified_address_with("main", &other.encode(&Network::MainNetwork), "orchard") + .unwrap(); + let rho = orchard::note::Rho::from_bytes(&[1; 32]).unwrap(); + let rseed = (0u8..=255) + .find_map(|byte| orchard::note::RandomSeed::from_bytes([byte; 32], &rho).into_option()) + .unwrap(); + let note = orchard::Note::from_parts( + fvk.address_at(0u32, Scope::External), + orchard::value::NoteValue::from_raw(100_000), + rho, + rseed, + if source == "ironwood" { + orchard::note::NoteVersion::V3 + } else { + orchard::note::NoteVersion::V2 + }, + ) + .unwrap(); + let zero = orchard::tree::MerkleHashOrchard::from_bytes(&[0; 32]).unwrap(); + let path = orchard::tree::MerklePath::from_parts(0, [zero; 32]); + let anchor = path.root(note.commitment().into()); + let mut builder = Builder::new( + Network::MainNetwork, + 3_500_000u32.into(), + BuildConfig::Standard { + sapling_anchor: None, + orchard_anchor: (source == "orchard").then_some(anchor), + ironwood_anchor: Some(if source == "ironwood" { + anchor + } else { + orchard::Anchor::empty_tree() + }), + orchard_padding: BundlePadding::DEFAULT, + ironwood_padding: BundlePadding::DEFAULT, + }, + ); + if source == "orchard" { + builder + .add_orchard_spend::(fvk.clone(), note, path) + .unwrap(); + } else { + builder + .add_ironwood_spend::(fvk.clone(), note, path) + .unwrap(); + } + let amount = if max { 80_000 } else { 50_000 }; + builder + .add_ironwood_output::( + None, + receiver, + Zatoshis::const_from_u64(amount), + super::super::transparent_send::parse_memo_hex(memo_hex.as_deref()).unwrap(), + ) + .unwrap(); + if !max { + let change_fvk = if foreign_change { + other.orchard().unwrap().clone() + } else { + fvk + }; + let address = change_fvk.address_at(0u32, Scope::Internal); + if source == "orchard" { + builder + .add_orchard_change_output::( + change_fvk, + None, + address, + Zatoshis::const_from_u64(30_000), + MemoBytes::empty(), + ) + .unwrap(); + } else { + builder + .add_ironwood_output::( + None, + address, + Zatoshis::const_from_u64(30_000), + MemoBytes::empty(), + ) + .unwrap(); + } + } + let built = builder + .build_for_pczt( + rand::rngs::OsRng, + &FeeRule::non_standard(Zatoshis::const_from_u64(20_000)), + ) + .unwrap(); + let pczt = Creator::build_from_parts(built.pczt_parts) + .unwrap() + .serialize() + .unwrap(); + ( + pczt, + ReviewRequest { + network: "main".into(), + ufvk: ufvk_string, + to_address, + amount_zat: amount.to_string(), + fee_zat: "20000".into(), + spend_source: source.into(), + is_max_send: max, + memo_hex, + }, + ) + } + + #[test] + fn text_and_binary_memo_must_match_recipient_ciphertext() { + for source in ["orchard", "ironwood"] { + for max in [false, true] { + for prefix in ["e4b8ade6968720f09f9982", "ff000102"] { + let memo = format!("{prefix}{}", "00".repeat(512 - prefix.len() / 2)); + let (bytes, mut request) = fixture_with_memo(source, max, false, Some(memo)); + verify(&bytes, &request).unwrap(); + request.memo_hex = None; + assert!(verify(&bytes, &request).is_err()); + request.memo_hex = Some(format!("ff99{}", "00".repeat(510))); + assert!(verify(&bytes, &request).is_err()); + } + } + } + } + + #[test] + fn both_pools_and_max_verify_with_owned_change() { + for source in ["orchard", "ironwood"] { + for max in [false, true] { + let (bytes, request) = fixture(source, max, false); + verify(&bytes, &request).unwrap(); + } + } + } + + #[test] + fn display_intent_cannot_replace_actual_effects() { + for field in [ + "recipient", + "amount", + "fee", + "source", + "max", + "ufvk", + "network", + ] { + let (bytes, mut request) = fixture("orchard", false, false); + match field { + "recipient" => { + request.to_address = + keys::unified_address_with("main", &request.ufvk, "orchard").unwrap() + } + "amount" => request.amount_zat = "49999".into(), + "fee" => request.fee_zat = "19999".into(), + "source" => request.spend_source = "ironwood".into(), + "max" => request.is_max_send = true, + "ufvk" => { + request.ufvk = + keys::ufvk_from_seed_bytes(Network::MainNetwork, &[9; 32], 0).unwrap() + } + "network" => request.network = "test".into(), + _ => unreachable!(), + } + assert!(verify(&bytes, &request).is_err(), "{field}"); + } + } + + #[test] + fn change_cannot_be_redirected_to_another_wallet() { + for source in ["orchard", "ironwood"] { + let (bytes, request) = fixture(source, false, true); + assert!(verify(&bytes, &request).is_err()); + } + } + + #[test] + fn suffix_and_noncanonical_amounts_are_rejected() { + let (mut bytes, request) = fixture("ironwood", true, false); + bytes.push(0); + assert!(verify(&bytes, &request).is_err()); + for invalid in ["080000", "-1", "8e4", "2100000000000001"] { + let (bytes, mut request) = fixture("ironwood", true, false); + request.amount_zat = invalid.into(); + assert!(verify(&bytes, &request).is_err()); + } + } + + #[test] + fn signer_must_own_the_reviewed_ufvk() { + let (bytes, request) = fixture("orchard", false, false); + let json = serde_json::json!({"network":request.network,"ufvk":request.ufvk,"toAddress":request.to_address,"amountZat":request.amount_zat,"feeZat":request.fee_zat,"spendSource":request.spend_source,"isMaxSend":request.is_max_send}).to_string(); + verify_signer(Network::MainNetwork, &[7; 32], 0, &bytes, &json).unwrap(); + assert!(verify_signer(Network::MainNetwork, &[8; 32], 0, &bytes, &json).is_err()); + assert!(verify_signer(Network::MainNetwork, &[7; 32], 1, &bytes, &json).is_err()); + } + + #[test] + fn altered_recipient_ciphertext_is_rejected_even_with_unchanged_metadata() { + let (mut bytes, request) = fixture("ironwood", true, false); + let mut ciphertext = None; + Verifier::new(pczt::Pczt::parse(&bytes).unwrap()) + .with_ironwood::(|bundle| { + ciphertext = bundle + .actions() + .iter() + .find(|action| action.output().value().unwrap().inner() > 0) + .map(|action| action.output().encrypted_note().enc_ciphertext); + Ok(()) + }) + .unwrap(); + let ciphertext = ciphertext.unwrap(); + let position = bytes + .windows(ciphertext.len()) + .position(|part| part == ciphertext) + .unwrap(); + bytes[position] ^= 1; + assert!( + pczt::Pczt::parse(&bytes).is_ok(), + "attack retains a structurally valid PCZT" + ); + assert!(verify(&bytes, &request).is_err()); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs index 9c004d28c..15ee37f0b 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs @@ -80,6 +80,7 @@ pub struct OutpointRef { pub struct TransparentRecipient { pub address: String, pub amount_zat: Option, + pub memo_hex: Option, } #[derive(Clone, Debug, Deserialize)] @@ -136,6 +137,7 @@ enum RecipientAddress { struct PlannedOutput { address: RecipientAddress, user_address: String, + memo: zcash_protocol::memo::MemoBytes, value: Zatoshis, } @@ -232,6 +234,20 @@ impl TransactionPlan { } } +pub(crate) fn parse_memo_hex(hex: Option<&str>) -> Result { + match hex { + None => Ok(zcash_protocol::memo::MemoBytes::empty()), + Some(hex) => { + let invalid = || KeysError::new(ErrorCode::InvalidTransactionRequest); + if hex.len() != 1024 { + return Err(invalid()); + } + let bytes = hex::decode(hex).map_err(|_| invalid())?; + zcash_protocol::memo::MemoBytes::from_bytes(&bytes).map_err(|_| invalid()) + } + } +} + fn plan_transaction(request: TransparentTxRequest) -> Result { if request.network != "main" { return Err(KeysError::with( @@ -310,6 +326,10 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { .into_iter() .map(|recipient| { let address = parse_recipient_address(&recipient.address)?; + let memo = parse_memo_hex(recipient.memo_hex.as_deref())?; + if recipient.memo_hex.is_some() && matches!(address, RecipientAddress::Transparent(_)) { + return Err(KeysError::new(ErrorCode::InvalidTransactionRequest)); + } if request.send_max { if recipient.amount_zat.is_some() { return Err(KeysError::with( @@ -317,7 +337,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { serde_json::json!({ "field": "amountZat", "reason": "mustBeOmittedForSendMax" }), )); } - Ok((address, None, recipient.address)) + Ok((address, None, recipient.address, memo)) } else { let amount = recipient.amount_zat.as_deref().ok_or_else(|| { KeysError::with( @@ -326,7 +346,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { ) })?; let value = parse_positive_zatoshis(amount, "recipient.amountZat")?; - Ok((address, Some(value), recipient.address)) + Ok((address, Some(value), recipient.address, memo)) } }) .collect::>>()?; @@ -346,6 +366,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { recipients: vec![PlannedOutput { address, user_address: parsed_recipients[0].2.clone(), + memo: parsed_recipients[0].3.clone(), value: send_amount, }], change: None, @@ -357,7 +378,8 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { let recipients = parsed_recipients .into_iter() - .map(|(address, value, user_address)| PlannedOutput { + .map(|(address, value, user_address, memo)| PlannedOutput { + memo, address, user_address, value: value.expect("non-send-max recipients were checked above"), @@ -450,6 +472,7 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { PlannedOutput { address: RecipientAddress::Transparent(change_address), user_address: change_request.address, + memo: zcash_protocol::memo::MemoBytes::empty(), value: change_value, }, change_path, diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs index 39dabff58..a86f94b26 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs @@ -86,7 +86,7 @@ fn create_with_public_key(plan: &TransactionPlan, key: &AccountPubKey) -> Result None, address, output.value, - MemoBytes::empty(), + output.memo.clone(), ) .map_err(failure)?, } @@ -320,11 +320,13 @@ fn validate_ironwood(bundle: &orchard::pczt::Bundle, plan: &TransactionPlan) -> .recipients .iter() .filter_map(|output| match output.address { - RecipientAddress::Ironwood(address) => Some((address, u64::from(output.value))), + RecipientAddress::Ironwood(address) => { + Some((address, u64::from(output.value), output.memo.clone())) + } RecipientAddress::Transparent(_) => None, }) .collect::>(); - let total = expected.iter().map(|(_, value)| value).sum::(); + let total = expected.iter().map(|(_, value, _)| value).sum::(); let action_count = if expected.is_empty() { 0 } else { @@ -360,12 +362,13 @@ fn validate_ironwood(bundle: &orchard::pczt::Bundle, plan: &TransactionPlan) -> output.verify_note_commitment(spend).map_err(failure)?; let recipient = output.recipient().ok_or_else(mismatch)?; let value = output.value().ok_or_else(mismatch)?; + let mut approved_memo = MemoBytes::empty(); if value.inner() != 0 { let index = expected .iter() - .position(|entry| *entry == (recipient, value.inner())) + .position(|entry| entry.0 == recipient && entry.1 == value.inner()) .ok_or_else(mismatch)?; - expected.remove(index); + approved_memo = expected.remove(index).2; } // A matching commitment alone does not ensure the recipient can decrypt the note. // Dummy output ciphertexts may be randomized by the upstream builder. @@ -384,7 +387,7 @@ fn validate_ironwood(bundle: &orchard::pczt::Bundle, plan: &TransactionPlan) -> let encryptor = orchard::note_encryption::IronwoodNoteEncryption::new( None, note, - *MemoBytes::empty().as_array(), + *approved_memo.as_array(), ); if encryptor.encrypt_note_plaintext() != output.encrypted_note().enc_ciphertext || orchard::note_encryption::IronwoodDomain::epk_bytes(encryptor.epk()).0 @@ -859,6 +862,27 @@ mod tests { .serialize() } + #[test] + fn shielding_memo_is_bound_to_the_approved_request() { + for max in [false, true] { + for prefix in ["e4b8ade6968720f09f9982", "ff000102"] { + let mut approved = request(max); + approved["recipients"][0]["memoHex"] = + Value::String(format!("{prefix}{}", "00".repeat(512 - prefix.len() / 2))); + let original = create(&approved.to_string(), &SEED).unwrap(); + sign(&approved.to_string(), &SEED, &original, &original).unwrap(); + approved["recipients"][0]["memoHex"] = + Value::String(format!("ff99{}", "00".repeat(510))); + assert!(sign(&approved.to_string(), &SEED, &original, &original).is_err()); + approved["recipients"][0] + .as_object_mut() + .unwrap() + .remove("memoHex"); + assert!(sign(&approved.to_string(), &SEED, &original, &original).is_err()); + } + } + } + #[test] fn signs_fixed_and_max_shielding_with_matching_request() { for send_max in [false, true] { diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml index 8058c55f9..a3a6d70b5 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml @@ -10,6 +10,7 @@ description = "OneKey Zcash Runtime — 官方 librustzcash 之上的最薄 wasm crate-type = ["cdylib", "rlib"] [dependencies] +blake2b_simd.workspace = true zcash_client_backend.workspace = true zcash_client_sqlite.workspace = true zcash_keys.workspace = true diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs index a6ff22633..f03fd3ba6 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs @@ -26,6 +26,12 @@ use crate::{ guard, history, network, runtime, send, storage, sync, tx_state, wallet, }; +/// Inject a Fetch-compatible host transport; None retains browser Fetch. +#[wasm_bindgen(js_name = setRequestHandler)] +pub fn set_request_handler(handler: Option) { + network::set_request_handler(handler); +} + // ── 生命周期 ──────────────────────────────────────────────────────────── /// 安装存储层。必须在其他任何调用之前 await 一次。幂等。 @@ -161,7 +167,7 @@ pub fn close_wallet() -> Result<(), JsValue> { /// 配置 lightwalletd 端点,形如 `https://host:port`。 /// /// 端点由宿主决定 —— 本 runtime 不硬编码任何服务器地址。 -/// 注意该端点必须支持 gRPC-web 与 CORS,否则浏览器侧会以网络错误失败。 +/// The endpoint must support gRPC-web. CORS is required only without a host transport. #[wasm_bindgen(js_name = setLightwalletdUrl)] pub fn set_lightwalletd_url(base_url: &str) -> Result<(), JsValue> { runtime::set_client(network::connect(base_url)?); @@ -379,6 +385,7 @@ pub fn pczt_quote( pad_orchard_bundle: bool, allow_zero_conf_shielding: Option, spend_source: Option, + memo_hex: Option, ) -> Result { // 与 `pcztCreate` 同一个构造入口,参数顺序也刻意对齐:报价用的选币规则 // 只要有一个字段和真正发送不同,报出来的费用就不是实付的费用。 @@ -396,7 +403,7 @@ pub fn pczt_quote( &account_uuid, &to_address, amount_zat, - memo.as_deref(), + send::parse_memo(memo.as_deref(), memo_hex.as_deref())?.as_ref(), policy, ) })?) @@ -542,6 +549,7 @@ pub fn pczt_create( reservation_id: Option, allow_zero_conf_shielding: Option, spend_source: Option, + memo_hex: Option, ) -> Result { let policy = send::parse_send_policy( trusted, @@ -557,7 +565,7 @@ pub fn pczt_create( &account_uuid, &to_address, amount_zat, - memo.as_deref(), + send::parse_memo(memo.as_deref(), memo_hex.as_deref())?.as_ref(), policy, lock_for_blocks, reservation_id.as_deref(), @@ -874,6 +882,16 @@ pub fn self_check(network_name: &str, db_name: &str) -> Result .to_string()) } +/// Builds only public circuit parameters without opening wallet storage. +#[wasm_bindgen(js_name = prewarmPczt)] +pub fn prewarm_pczt(network_name: &str, target_height: u32) -> Result<(), JsValue> { + install_panic_hook(); + Ok(send::prewarm_pczt( + &wallet::parse_network(network_name)?, + target_height.into(), + )?) +} + /// Proves a locally constructed PCZT without opening a wallet or initializing storage. #[wasm_bindgen(js_name = pcztProveAtHeight)] pub fn pczt_prove_at_height(target_height: u32, pczt_bytes: Vec) -> Result, JsValue> { @@ -891,9 +909,7 @@ pub fn pczt_extract_stateless(pczt_bytes: Vec) -> Result { install_panic_hook(); let failure = |error: String| RuntimeError::new(ErrorCode::PcztError).detail(error); let pczt = pczt::Pczt::parse(&pczt_bytes).map_err(|e| failure(format!("{e:?}")))?; - let tx = pczt::roles::tx_extractor::TransactionExtractor::new(pczt) - .extract() - .map_err(|e| failure(format!("{e:?}")))?; + let tx = send::extract_pczt(pczt)?; let mut bytes = Vec::new(); tx.write(&mut bytes) .map_err(|e| failure(format!("{e:?}")))?; diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/circuit_keys.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/circuit_keys.rs new file mode 100644 index 000000000..76de18d97 --- /dev/null +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/circuit_keys.rs @@ -0,0 +1,79 @@ +//! Immutable public circuit parameters, shared by proving and extraction. + +use std::sync::OnceLock; + +use orchard::circuit::{OrchardCircuitVersion, ProvingKey, VerifyingKey}; +use zcash_primitives::transaction::builder::cached_orchard_proving_key; + +use crate::error::{ErrorCode, Result, RuntimeError}; + +// Each WASM instance owns its cache. Native callers share these thread-safe +// public parameters; wallet data, witnesses, and spending keys never enter it. +static HISTORICAL_VERIFYING: OnceLock = OnceLock::new(); +static FIXED_VERIFYING: OnceLock = OnceLock::new(); +static CURRENT_VERIFYING: OnceLock = OnceLock::new(); + +pub fn proving_key(version: OrchardCircuitVersion) -> Result<&'static ProvingKey> { + match version { + OrchardCircuitVersion::FixedPostNu6_2 | OrchardCircuitVersion::PostNu6_3 => {} + OrchardCircuitVersion::InsecurePreNu6_2 => { + return Err(RuntimeError::new(ErrorCode::Unimplemented) + .detail("Historical insecure circuits are verification-only")); + } + } + Ok(cached_orchard_proving_key(version)) +} + +pub fn verifying_key(version: OrchardCircuitVersion) -> &'static VerifyingKey { + let slot = match version { + OrchardCircuitVersion::InsecurePreNu6_2 => &HISTORICAL_VERIFYING, + OrchardCircuitVersion::FixedPostNu6_2 => &FIXED_VERIFYING, + OrchardCircuitVersion::PostNu6_3 => &CURRENT_VERIFYING, + }; + slot.get_or_init(|| VerifyingKey::build(version)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn public_parameters_are_shared_and_isolated_by_circuit_version() { + for version in [ + OrchardCircuitVersion::FixedPostNu6_2, + OrchardCircuitVersion::PostNu6_3, + ] { + let proving = proving_key(version).unwrap(); + let verifying = verifying_key(version); + assert!(std::ptr::eq(proving, cached_orchard_proving_key(version))); + assert_eq!(proving.circuit_version(), version); + assert_eq!(verifying.circuit_version(), version); + std::thread::scope(|scope| { + for _ in 0..4 { + scope.spawn(move || { + assert!(std::ptr::eq(proving, proving_key(version).unwrap())); + assert!(std::ptr::eq(verifying, verifying_key(version))); + }); + } + }); + } + assert!(!std::ptr::eq( + proving_key(OrchardCircuitVersion::FixedPostNu6_2).unwrap(), + proving_key(OrchardCircuitVersion::PostNu6_3).unwrap(), + )); + assert!(!std::ptr::eq( + verifying_key(OrchardCircuitVersion::FixedPostNu6_2), + verifying_key(OrchardCircuitVersion::PostNu6_3), + )); + } + + #[test] + fn insecure_historical_circuit_cannot_be_used_for_proving() { + assert_eq!( + proving_key(OrchardCircuitVersion::InsecurePreNu6_2) + .unwrap_err() + .code, + ErrorCode::Unimplemented, + ); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs index d787a083c..d36aefb2a 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs @@ -346,16 +346,23 @@ pub fn details_outputs( } if to_acct.as_deref() == Some(me.as_slice()) { + let (memo_text, memo_binary) = + memo.as_deref().map(memo_details).unwrap_or((None, None)); received.push(json!({ "valueZat": value, "pool": pool, "poolName": pool_name(pool), "isChange": is_change, - "memo": memo.as_deref().and_then(decode_memo), + "memo": memo_text, + "memoBinary": memo_binary, "address": address, })); } else if from_acct.as_deref() == Some(me.as_slice()) { + let (memo_text, memo_binary) = + memo.as_deref().map(memo_details).unwrap_or((None, None)); external.push(json!({ + "memo": memo_text, + "memoBinary": memo_binary, "valueZat": value, "pool": pool, "poolName": pool_name(pool), @@ -420,13 +427,63 @@ fn pool_name(pool: i64) -> &'static str { } } -/// memo 里全零表示「没有 memo」,0xF6 开头是协议保留,都不该当文本给出去。 -fn decode_memo(bytes: &[u8]) -> Option { - if bytes.is_empty() || bytes.iter().all(|b| *b == 0) || bytes[0] == 0xF6 { - return None; +#[derive(Debug, PartialEq)] +enum DecodedMemo { + None, + Text(String), + /// `hex`: the field without its zero padding. `hash`: BLAKE2b-256 of the + /// whole 512-byte field, hex. + Binary { + hex: String, + hash: String, + }, +} + +/// Classified per ZIP 302: text is shown as is; arbitrary-data and +/// future-format memos cannot be, so they are identified by a hash. +fn decode_memo(bytes: &[u8]) -> DecodedMemo { + use zcash_protocol::memo::{Memo, MemoBytes}; + let Ok(memo_bytes) = MemoBytes::from_bytes(bytes) else { + return DecodedMemo::None; + }; + match Memo::try_from(&memo_bytes) { + Ok(Memo::Empty) => DecodedMemo::None, + // All zeroes decodes as empty text; it means no memo too. + Ok(Memo::Text(text)) if text.is_empty() => DecodedMemo::None, + Ok(Memo::Text(text)) => DecodedMemo::Text(String::from(text)), + // Invalid UTF-8 in the text range is still data the sender put there. + Ok(Memo::Future(_)) | Ok(Memo::Arbitrary(_)) | Err(_) => { + let hash = blake2b_simd::Params::new() + .hash_length(32) + .hash(memo_bytes.as_array()); + DecodedMemo::Binary { + hex: hex::encode(memo_bytes.as_slice()), + hash: hex::encode(hash.as_bytes()), + } + } } - let end = bytes.iter().rposition(|b| *b != 0).map_or(0, |i| i + 1); - String::from_utf8(bytes[..end].to_vec()).ok() +} + +/// Preserve the exact padded field for both text and binary memo displays. +fn memo_details(bytes: &[u8]) -> (Option, Option) { + let text = match decode_memo(bytes) { + DecodedMemo::None => return (None, None), + DecodedMemo::Text(text) => Some(text), + DecodedMemo::Binary { .. } => None, + }; + let Ok(field) = zcash_protocol::memo::MemoBytes::from_bytes(bytes) else { + return (None, None); + }; + let hash = blake2b_simd::Params::new() + .hash_length(32) + .hash(field.as_array()); + ( + text, + Some(json!({ + "hex": hex::encode(field.as_array()), + "hash": hex::encode(hash.as_bytes()), + })), + ) } /// 显示序(大端 hex)→ 内部序(小端字节)。 @@ -463,6 +520,62 @@ mod tests { use super::*; use crate::clock::HostClock; + // Expected hashes from Python: hashlib.blake2b(field, digest_size=32), + // where field is the memo padded with zeroes to 512 bytes. + #[test] + fn memos_are_classified_per_zip_302() { + assert_eq!(decode_memo(b"hello"), DecodedMemo::Text("hello".into())); + assert_eq!(decode_memo(&[0xF6]), DecodedMemo::None); + assert_eq!(decode_memo(&[0u8; 512]), DecodedMemo::None); + assert_eq!( + decode_memo(&[0xFF, 1, 2, 3]), + DecodedMemo::Binary { + hex: "ff010203".into(), + hash: "65f2f3b6161331db680c67819cb0419fbebc46d460926cb5b2251300be0bab19".into(), + } + ); + assert_eq!( + decode_memo(&[0xF5, 9]), + DecodedMemo::Binary { + hex: "f509".into(), + hash: "0e72c1749d69b52a0360b93c9d8598c99c03ff333a1b011504f35a9983560f73".into(), + } + ); + assert_eq!( + decode_memo(&[0xC3, 0x28]), + DecodedMemo::Binary { + hex: "c328".into(), + hash: "e839917e76e97f37720fabe711e787adf8819788647c7407363819b8e4bf80ae".into(), + } + ); + } + + #[test] + fn memo_details_preserve_full_text_and_binary_fields() { + let (text, raw) = memo_details(" 中文\n🙂 ".as_bytes()); + assert_eq!(text.as_deref(), Some(" 中文\n🙂 ")); + let raw = raw.unwrap(); + assert_eq!(raw["hex"].as_str().unwrap().len(), 1024); + assert!(raw["hex"] + .as_str() + .unwrap() + .starts_with("2020e4b8ade696870af09f99822020")); + assert_eq!( + raw["hash"], + "8ddea12a10d4fba7353a20aff34eb4a0a4e9533eabc637a5fca9e6e90ab7eeef" + ); + let (text, raw) = memo_details(&[0xff, 1, 2, 3]); + assert_eq!(text, None); + let raw = raw.unwrap(); + assert_eq!(raw["hex"], format!("ff010203{}", "00".repeat(508))); + assert_eq!( + raw["hash"], + "65f2f3b6161331db680c67819cb0419fbebc46d460926cb5b2251300be0bab19" + ); + assert_eq!(memo_details(&[0xf6]), (None, None)); + assert_eq!(memo_details(&[0; 512]), (None, None)); + } + #[test] fn a_non_ascii_txid_is_rejected_not_a_panic() { // Four bytes, but byte 2 falls inside "é": slicing there panics. @@ -675,6 +788,60 @@ mod tests { json!({ "3": "-100", "4": "99" }) ); } + #[test] + fn decrypted_memos_are_visible_only_to_the_output_sender_or_receiver() { + let conn = history_fixture(); + conn.execute_batch( + "ALTER TABLE v_tx_outputs ADD COLUMN output_pool INTEGER DEFAULT 4; + ALTER TABLE v_tx_outputs ADD COLUMN value INTEGER DEFAULT 10000; + ALTER TABLE v_tx_outputs ADD COLUMN memo BLOB; + ALTER TABLE v_received_outputs ADD COLUMN address_id INTEGER; + CREATE TABLE addresses (id INTEGER PRIMARY KEY, address TEXT);", + ) + .unwrap(); + let sender = uuid::Uuid::from_u128(1); + let receiver = uuid::Uuid::from_u128(2); + let stranger = uuid::Uuid::from_u128(3); + let txid = [7u8; 32]; + let text = " 中文\n🙂 "; + conn.execute( + "INSERT INTO v_tx_outputs + (txid, from_account_uuid, to_account_uuid, to_address, is_change, memo) + VALUES (?1, ?2, ?3, 'synthetic-recipient', 0, ?4)", + rusqlite::params![ + txid.as_slice(), + sender.as_bytes().as_slice(), + receiver.as_bytes().as_slice(), + text.as_bytes(), + ], + ) + .unwrap(); + for (account, field) in [(sender, "external"), (receiver, "received")] { + let output: serde_json::Value = serde_json::from_str( + &details_outputs(&conn, &account.to_string(), &hex_display_order(&txid)).unwrap(), + ) + .unwrap(); + assert_eq!(output[field][0]["memo"], text); + assert_eq!( + output[field][0]["memoBinary"]["hex"] + .as_str() + .unwrap() + .len(), + 1024 + ); + assert_eq!( + output[field][0]["memoBinary"]["hash"], + "8ddea12a10d4fba7353a20aff34eb4a0a4e9533eabc637a5fca9e6e90ab7eeef" + ); + } + let output: serde_json::Value = serde_json::from_str( + &details_outputs(&conn, &stranger.to_string(), &hex_display_order(&txid)).unwrap(), + ) + .unwrap(); + assert_eq!(output["external"], json!([])); + assert_eq!(output["received"], json!([])); + } + #[test] fn outgoing_outputs_are_external_relative_to_the_current_account() { let conn = history_fixture(); diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs index d717894b3..dd9285fa6 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs @@ -24,6 +24,7 @@ // 也就是说移动端**可以**跑完整的钱包逻辑,不必退化成 keys-only。 pub mod account; pub mod blockcache; +mod circuit_keys; pub mod clock; pub mod error; pub mod guard; diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs index 36d81361d..76a0cb896 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs @@ -13,6 +13,17 @@ use zcash_client_backend::proto::service::{ use crate::error::{ErrorCode, Result, RuntimeError}; use serde_json::json; +#[cfg(target_arch = "wasm32")] +thread_local! { + static REQUEST_HANDLER: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// The handler belongs to this WASM instance, and is installed before networking. +#[cfg(target_arch = "wasm32")] +pub fn set_request_handler(handler: Option) { + REQUEST_HANDLER.with(|slot| *slot.borrow_mut() = handler); +} + // 浏览器走 gRPC-web(没有原生 HTTP/2 裸连接),原生目标走 tonic 自带 transport。 // 上层的 `LightClient` 签名在两边一致,`chain_tip` / `tree_state` 等函数不用分叉。 #[cfg(target_arch = "wasm32")] @@ -95,8 +106,13 @@ pub fn connect(base_url: &str) -> Result { json!({ "reason": "httpsRequired" }), )); } + let mut options = tonic_web_wasm_client::options::FetchOptions::new(); + options.fetch = REQUEST_HANDLER.with(|slot| slot.borrow().clone()); Ok(CompactTxStreamerClient::new( - tonic_web_wasm_client::Client::new(base_url.to_owned()), + tonic_web_wasm_client::Client::new_with_options( + base_url.trim_end_matches('/').to_owned(), + options, + ), )) } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs index 8efdbdaaf..46d98ee33 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs @@ -242,12 +242,33 @@ fn recipient_is_tex( ) } +// Keep the legacy text argument compatible; new hosts pass the exact ZIP 302 field. +pub fn parse_memo(text: Option<&str>, hex: Option<&str>) -> Result> { + let invalid = || RuntimeError::new(ErrorCode::InvalidMemo); + match (text, hex) { + (Some(_), Some(_)) => Err(invalid()), + (_, Some(hex)) => { + if hex.len() != 1024 { + return Err(invalid()); + } + let bytes = hex::decode(hex).map_err(|_| invalid())?; + Ok(Some(MemoBytes::from_bytes(&bytes).map_err(|_| invalid())?)) + } + (Some(text), None) => { + let memo = + zcash_protocol::memo::Memo::from_bytes(text.as_bytes()).map_err(|_| invalid())?; + Ok(Some(MemoBytes::from(&memo))) + } + (None, None) => Ok(None), + } +} + fn build_proposal( db: &mut Db, account_uuid: &str, to_address: &str, amount_zat: u64, - memo: Option<&str>, + memo: Option<&MemoBytes>, policy: SendPolicy, lock: Option, ) -> Result { @@ -283,18 +304,8 @@ fn build_proposal( )); } - let memo_bytes = match memo { - None => None, - Some(m) => { - let parsed = zcash_protocol::memo::Memo::from_bytes(m.as_bytes()).map_err(|e| { - RuntimeError::with(ErrorCode::InvalidMemo, json!({ "byteLen": m.len() })).detail(e) - })?; - Some(MemoBytes::from(&parsed)) - } - }; - // Payment::new 会自己校验「透明地址不能带 memo」这类约束。 - let payment = zip321::Payment::new(recipient, Some(amount), memo_bytes, None, None, vec![]) + let payment = zip321::Payment::new(recipient, Some(amount), memo.cloned(), None, None, vec![]) .map_err(|e| { RuntimeError::with(ErrorCode::InvalidMemo, json!({ "reason": "payment" })) .detail(format!("{e:?}")) @@ -371,7 +382,7 @@ pub fn quote( account_uuid: &str, to_address: &str, amount_zat: u64, - memo: Option<&str>, + memo: Option<&MemoBytes>, policy: SendPolicy, ) -> Result { let proposal = build_proposal(db, account_uuid, to_address, amount_zat, memo, policy, None)?; @@ -403,7 +414,7 @@ pub fn quote( // 提案本身要留在内存里:`unlock_proposal_inputs` 需要提案才知道该解锁哪些 note。 thread_local! { static RESERVATIONS: std::cell::RefCell< - std::collections::HashMap, + std::collections::HashMap)>, > = std::cell::RefCell::new(std::collections::HashMap::new()); } @@ -442,20 +453,22 @@ pub fn release_reservation(db: &mut Db, reservation_id: &str) -> Result { // selected notes. In that state release must only discard the in-memory // proposal; unlocking its inputs would make spent notes selectable again. let finalized_txid = db.transactionally_with_extension(|_wallet, ext| { - tx_state::existing_txid_for_reservation(ext, reservation_id) + tx_state::existing_txid_for_reservation(ext, reservation_id, None) })?; if finalized_txid.is_some() { forget_reservation(reservation_id); return Ok(false); } - if let Some((account_uuid, proposal)) = + if let Some((account_uuid, proposal, approved_pczt)) = RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id)) { if let Err(e) = unlock_proposal_inputs(db, &proposal, owner) { RESERVATIONS.with(|r| { - r.borrow_mut() - .insert(reservation_id.to_owned(), (account_uuid, proposal)); + r.borrow_mut().insert( + reservation_id.to_owned(), + (account_uuid, proposal, approved_pczt), + ); }); return Err(build_err("unlockProposalInputs", format!("{e:?}"))); } @@ -481,7 +494,7 @@ fn release_persisted_reservation( use zcash_protocol::PoolType; db.transactionally_with_extension(|wallet, ext| { - if tx_state::existing_txid_for_reservation(ext, reservation_id)?.is_some() { + if tx_state::existing_txid_for_reservation(ext, reservation_id, None)?.is_some() { return Ok(false); } let mut released = false; @@ -553,7 +566,7 @@ pub fn forget_reservation(reservation_id: &str) { pub fn forget_account_reservations(account_uuid: &str) { RESERVATIONS.with(|r| { r.borrow_mut() - .retain(|_, (owner_uuid, _)| owner_uuid.as_str() != account_uuid) + .retain(|_, (owner_uuid, _, _)| owner_uuid.as_str() != account_uuid) }); } @@ -576,7 +589,7 @@ pub fn create_pczt( account_uuid: &str, to_address: &str, amount_zat: u64, - memo: Option<&str>, + memo: Option<&MemoBytes>, policy: SendPolicy, lock_for_blocks: u32, reservation_id: Option<&str>, @@ -645,8 +658,10 @@ pub fn create_pczt( // 提案要留着:解锁时需要它才知道该放开哪些 note。 RESERVATIONS.with(|r| { - r.borrow_mut() - .insert(reservation_id.clone(), (account_uuid.to_owned(), proposal)); + r.borrow_mut().insert( + reservation_id.clone(), + (account_uuid.to_owned(), proposal, bytes.clone()), + ); }); Ok((bytes, reservation_id, fee_zat)) } @@ -810,6 +825,44 @@ pub fn prove_pczt(db: &Db, pczt_bytes: &[u8]) -> Result> { prove_pczt_at_height(¶ms, chain_tip, pczt_bytes) } +/// Builds only public parameters, without a wallet, proposal, or spending key. +pub fn prewarm_pczt( + params: &zcash_protocol::consensus::Network, + target_height: zcash_protocol::consensus::BlockHeight, +) -> Result<()> { + let version = circuit_version_for(params, target_height); + crate::circuit_keys::proving_key(version)?; + crate::circuit_keys::verifying_key(version); + Ok(()) +} + +/// Retains upstream proof/signature validation while reusing public parameters. +pub fn extract_pczt(pczt: pczt::Pczt) -> Result { + use orchard::circuit::OrchardCircuitVersion; + use zcash_protocol::consensus::{BranchId, OrchardProtocolRevision}; + + let version = BranchId::try_from(*pczt.global().consensus_branch_id()) + .ok() + .and_then(|branch| branch.orchard_protocol_revision()) + .map(|revision| match revision { + OrchardProtocolRevision::InsecureV1 => OrchardCircuitVersion::InsecurePreNu6_2, + OrchardProtocolRevision::V2 => OrchardCircuitVersion::FixedPostNu6_2, + OrchardProtocolRevision::V3 => OrchardCircuitVersion::PostNu6_3, + }); + let has_shielded_bundle = + !pczt.orchard().actions().is_empty() || !pczt.ironwood().actions().is_empty(); + let extractor = pczt::roles::tx_extractor::TransactionExtractor::new(pczt); + let extractor = match version.filter(|_| has_shielded_bundle) { + Some(version) => extractor.with_orchard(crate::circuit_keys::verifying_key(version)), + // Let upstream report unsupported branches and malformed bundles. + None => extractor, + }; + extractor.extract().map_err(|error| { + RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "extract" })) + .detail(format!("{error:?}")) + }) +} + /// Pure proving: no wallet, database, scan, or storage initialization. pub fn prove_pczt_at_height( params: &zcash_protocol::consensus::Network, @@ -825,13 +878,11 @@ pub fn prove_pczt_at_height( let prover = pczt::roles::prover::Prover::new(pczt); let prover = if prover.requires_ironwood_proof() { - let proving_key = orchard::circuit::ProvingKey::build(version); - prover - .create_ironwood_proof(&proving_key) - .map_err(|error| { - RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "ironwoodProof" })) - .detail(format!("{error:?}")) - })? + let proving_key = crate::circuit_keys::proving_key(version)?; + prover.create_ironwood_proof(proving_key).map_err(|error| { + RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "ironwoodProof" })) + .detail(format!("{error:?}")) + })? } else { prover }; @@ -844,8 +895,8 @@ pub fn prove_pczt_at_height( } let prover = if prover.requires_orchard_proof() { - let proving_key = orchard::circuit::ProvingKey::build(version); - prover.create_orchard_proof(&proving_key).map_err(|error| { + let proving_key = crate::circuit_keys::proving_key(version)?; + prover.create_orchard_proof(proving_key).map_err(|error| { RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "orchardProof" })) .detail(format!("{error:?}")) })? @@ -887,7 +938,7 @@ pub enum SubmitOutcome { Accepted { txid: String, }, - /// 节点明确拒收:没落库,note 已放回。 + /// The trusted node rejected it; keep the durable record until chain expiry. Rejected { txid: String, error: RuntimeError, @@ -899,24 +950,33 @@ pub enum SubmitOutcome { }, } -/// 首次提交时这笔交易从没发出过:节点回「输入已花」只能是别的交易花了它们, -/// 不是它自己已被打包 —— 按拒绝处理。`Ok` 是拒绝,`Err` 原样是其他错误。 +// A spent-input/duplicate-nullifier reply can refer to this transaction itself. fn first_submit_rejection(error: RuntimeError) -> std::result::Result { - match error.code { - ErrorCode::BroadcastRejected | ErrorCode::BroadcastOutcomeUnknown => Ok(RuntimeError { - code: ErrorCode::BroadcastRejected, - ..error - }), - _ => Err(error), + if error.code == ErrorCode::BroadcastRejected { + Ok(error) + } else { + Err(error) } } -/// 提交签好名的 PCZT:先提取交易并广播,再按结局决定落不落库。 -/// -/// 先落库再广播的话,上游从落库那一刻起就把 note 算作已花,只有交易过期才放 -/// 回来;节点明确拒收的交易会把钱冻上几十个块。这里反过来:明确拒收就不落库, -/// 直接放回 note。结局未知仍然落库 —— 交易可能已经传开,放回 note 会让用户重发 -/// 出第二笔。广播成功后落库失败按 FINALIZE_OUTCOME_UNKNOWN 报,由宿主查历史。 +fn record_submit_outcome(db: &mut Db, txid: String, result: Result<()>) -> SubmitOutcome { + match result { + Ok(()) => match tx_state::mark_accepted(db, &txid) { + Ok(()) => SubmitOutcome::Accepted { txid }, + Err(error) => SubmitOutcome::Unknown { txid, error }, + }, + Err(error) => match first_submit_rejection(error) { + Ok(error) => match tx_state::mark_rejected(db, &txid, &error) { + Ok(()) => SubmitOutcome::Rejected { txid, error }, + Err(error) => SubmitOutcome::Unknown { txid, error }, + }, + Err(error) => SubmitOutcome::Unknown { txid, error }, + }, + } +} + +/// Persist the exact authorized transaction before any external broadcast. +/// Retries and crash recovery always rebroadcast the stored bytes. pub async fn submit_signed_pczt( db: &mut Db, client: &mut crate::network::LightClient, @@ -924,24 +984,42 @@ pub async fn submit_signed_pczt( pczt_bytes: &[u8], reservation_id: &str, ) -> Result { - use pczt::roles::{spend_finalizer::SpendFinalizer, tx_extractor::TransactionExtractor}; - // 上次提交已经落库(宿主没拿到回包就重试):重播那一笔,不再提取第二次。 let stored = db.transactionally_with_extension(|_wallet, ext| { - tx_state::existing_txid_for_reservation(ext, reservation_id) + tx_state::existing_txid_for_reservation(ext, reservation_id, Some(account_uuid)) })?; if let Some(txid) = stored { - let raw = raw_transaction(db, &txid)?; - return Ok(match crate::network::broadcast(client, raw).await { - Ok(()) => { - tx_state::mark_accepted(db, &txid)?; - SubmitOutcome::Accepted { txid } - } - Err(error) => SubmitOutcome::Unknown { txid, error }, - }); + if let Err(error) = tx_state::assert_broadcastable(db, &txid) { + return Ok(if error.code == ErrorCode::BroadcastRejected { + SubmitOutcome::Rejected { txid, error } + } else { + SubmitOutcome::Unknown { txid, error } + }); + } + let raw = match raw_transaction(db, &txid) { + Ok(raw) => raw, + Err(error) => return Ok(SubmitOutcome::Unknown { txid, error }), + }; + let result = crate::network::broadcast(client, raw).await; + return Ok(record_submit_outcome(db, txid, result)); } - let pczt = pczt::Pczt::parse(pczt_bytes).map_err(|e| { + let approved_pczt = RESERVATIONS + .with(|reservations| { + reservations + .borrow() + .get(reservation_id) + .filter(|(owner, _, _)| owner == account_uuid) + .map(|(_, _, pczt)| pczt.clone()) + }) + .ok_or_else(|| { + RuntimeError::with( + ErrorCode::InvalidReservationId, + json!({ "reason": "missingOrWrongAccount" }), + ) + })?; + let bound_pczt = combine_pczt(&approved_pczt, pczt_bytes)?; + let pczt = pczt::Pczt::parse(&bound_pczt).map_err(|e| { RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "parse" })) .detail(format!("{e:?}")) })?; @@ -952,55 +1030,25 @@ pub async fn submit_signed_pczt( .ok_or_else(|| RuntimeError::new(ErrorCode::NotSynced))?; let version = circuit_version_for_branch(¶ms, *pczt.global().consensus_branch_id(), chain_tip); - // 构建一次,提取和落库共用:每次现场构建都要好几秒。 - let orchard_vk = orchard::circuit::VerifyingKey::build(version); - - let finalized = SpendFinalizer::new(pczt.clone()) - .finalize_spends() - .map_err(|e| build_err("finalizeSpends", format!("{e:?}")))?; - let tx = TransactionExtractor::new(finalized) - .with_orchard(&orchard_vk) - .extract() - .map_err(|e| build_err("extractTransaction", format!("{e:?}")))?; - let txid = tx.txid().to_string(); - let mut raw = Vec::new(); - tx.write(&mut raw) - .map_err(|e| build_err("serializeTransaction", e))?; - - let broadcast = match crate::network::broadcast(client, raw).await { - Err(error) => match first_submit_rejection(error) { - Ok(error) => { - release_reservation(db, reservation_id)?; - return Ok(SubmitOutcome::Rejected { txid, error }); - } - Err(error) => Err(error), - }, - Ok(()) => Ok(()), - }; + let orchard_vk = crate::circuit_keys::verifying_key(version); - let stored = store_signed_pczt(db, account_uuid, pczt, &orchard_vk, reservation_id).and_then( - |stored_txid| { - if broadcast.is_ok() { - tx_state::mark_accepted(db, &stored_txid)?; - } - Ok(stored_txid) - }, - ); + // This transaction atomically stores raw bytes and the reservation/txid association. + // If it fails, nothing has been sent and the caller can safely abandon the proposal. + let stored_txid = store_signed_pczt(db, account_uuid, pczt, orchard_vk, reservation_id)?; forget_reservation(reservation_id); - let stored_txid = stored.map_err(|error| { - RuntimeError::with( - ErrorCode::FinalizeOutcomeUnknown, - json!({ "txid": txid, "broadcast": if broadcast.is_ok() { "accepted" } else { "unknown" } }), - ) - .detail(format!("{error:?}")) - })?; - Ok(match broadcast { - Ok(()) => SubmitOutcome::Accepted { txid: stored_txid }, - Err(error) => SubmitOutcome::Unknown { - txid: stored_txid, - error, - }, - }) + // Extraction randomizes binding signatures. Broadcast only the stored bytes, + // so the first attempt and every recovery attempt use identical authorizations. + let raw = match raw_transaction(db, &stored_txid) { + Ok(raw) => raw, + Err(error) => { + return Ok(SubmitOutcome::Unknown { + txid: stored_txid, + error, + }) + } + }; + let result = crate::network::broadcast(client, raw).await; + Ok(record_submit_outcome(db, stored_txid, result)) } /// 从钱包库取出已落库交易的原始字节,供重播使用。 @@ -1054,7 +1102,7 @@ pub fn clear_locked_outputs(db: &mut Db, account_uuid: &str) -> Result { RESERVATIONS.with(|r| { r.borrow_mut() - .retain(|_, (owner_account_uuid, _)| owner_account_uuid != account_uuid); + .retain(|_, (owner_account_uuid, _, _)| owner_account_uuid != account_uuid); }); Ok(n as u32) } @@ -1077,6 +1125,79 @@ mod reservation_recovery_tests { ) } + fn outcome_wallet(fail_update: bool) -> (Db, String) { + let conn = Connection::open_in_memory().unwrap(); + conn.execute_batch("CREATE TABLE ext_onekey_tx_state (txid BLOB PRIMARY KEY, account_uuid BLOB, reservation_id TEXT, broadcast_state TEXT, rejection_code INTEGER, rejection_reason TEXT);").unwrap(); + conn.execute("INSERT INTO ext_onekey_tx_state (txid,account_uuid,reservation_id,broadcast_state) VALUES (?1,?2,'review','pending')", rusqlite::params![[1u8;32].as_slice(), uuid::Uuid::from_u128(1).as_bytes().as_slice()]).unwrap(); + if fail_update { + conn.execute_batch("CREATE TRIGGER fail_state BEFORE UPDATE ON ext_onekey_tx_state BEGIN SELECT RAISE(ABORT,'synthetic write failure'); END;").unwrap(); + } + (wallet(conn), "01".repeat(32)) + } + + #[test] + fn both_first_and_retried_broadcasts_record_definitive_node_outcomes() { + let (mut db, txid) = outcome_wallet(false); + assert!(matches!( + record_submit_outcome(&mut db, txid.clone(), Ok(())), + SubmitOutcome::Accepted { .. } + )); + let rejected = RuntimeError::new(ErrorCode::BroadcastRejected).detail("bad-txns-expired"); + assert!(matches!( + record_submit_outcome(&mut db, txid.clone(), Err(rejected)), + SubmitOutcome::Rejected { .. } + )); + assert_eq!( + tx_state::assert_broadcastable(&mut db, &txid) + .unwrap_err() + .code, + ErrorCode::BroadcastRejected + ); + } + + #[test] + fn accepted_broadcast_with_failed_state_write_keeps_its_known_txid() { + let (mut db, txid) = outcome_wallet(true); + match record_submit_outcome(&mut db, txid.clone(), Ok(())) { + SubmitOutcome::Unknown { txid: retained, .. } => assert_eq!(retained, txid), + _ => panic!("an accepted transaction must not become a signing failure"), + } + tx_state::assert_broadcastable(&mut db, &txid).unwrap(); + } + + #[test] + fn duplicate_spend_or_network_failure_keeps_the_persisted_send_pending() { + for code in [ErrorCode::BroadcastOutcomeUnknown, ErrorCode::NetworkError] { + let (mut db, txid) = outcome_wallet(false); + assert!(matches!( + record_submit_outcome(&mut db, txid.clone(), Err(RuntimeError::new(code))), + SubmitOutcome::Unknown { .. } + )); + tx_state::assert_broadcastable(&mut db, &txid).unwrap(); + } + } + + #[test] + fn retry_cannot_use_another_accounts_reservation() { + let (mut db, txid) = outcome_wallet(false); + let owner = uuid::Uuid::from_u128(1).to_string(); + let other = uuid::Uuid::from_u128(2).to_string(); + db.transactionally_with_extension(|_, ext| { + assert_eq!( + tx_state::existing_txid_for_reservation(ext, "review", Some(&owner))?, + Some(txid) + ); + assert_eq!( + tx_state::existing_txid_for_reservation(ext, "review", Some(&other)) + .unwrap_err() + .code, + ErrorCode::InvalidReservationId + ); + Ok::<(), RuntimeError>(()) + }) + .unwrap(); + } + #[test] fn restart_cancellation_releases_only_its_owner_and_preserves_finalized_locks() { let path = @@ -1086,7 +1207,7 @@ mod reservation_recovery_tests { let conn = Connection::open(&path).unwrap(); conn.execute_batch( "CREATE TABLE transactions (id_tx INTEGER PRIMARY KEY, txid BLOB); - CREATE TABLE ext_onekey_tx_state (txid BLOB, reservation_id TEXT);", + CREATE TABLE ext_onekey_tx_state (txid BLOB, reservation_id TEXT, account_uuid BLOB);", ) .unwrap(); conn.execute("INSERT INTO transactions VALUES (1, ?1)", [[3_u8; 32]]) @@ -1127,8 +1248,8 @@ mod reservation_recovery_tests { assert_eq!(released, 1); } conn.execute( - "INSERT INTO ext_onekey_tx_state VALUES (?1, ?2)", - rusqlite::params![[4_u8; 32], hex32(&other_owner)], + "INSERT INTO ext_onekey_tx_state (txid, reservation_id, account_uuid) VALUES (?1, ?2, ?3)", + rusqlite::params![[4_u8; 32], hex32(&other_owner), uuid::Uuid::from_u128(1).as_bytes()], ) .unwrap(); assert!(!release_reservation(&mut db, &hex32(&other_owner)).unwrap()); @@ -1395,14 +1516,14 @@ mod submit_tests { use super::*; #[test] - fn first_submit_treats_spent_inputs_as_rejection() { + fn first_submit_keeps_spent_inputs_unknown() { let spent = RuntimeError::with( ErrorCode::BroadcastOutcomeUnknown, json!({ "errorCode": -26 }), ) .detail("bad-txns-inputs-spent".to_string()); - let rejection = first_submit_rejection(spent).unwrap(); - assert_eq!(rejection.code, ErrorCode::BroadcastRejected); + let rejection = first_submit_rejection(spent).unwrap_err(); + assert_eq!(rejection.code, ErrorCode::BroadcastOutcomeUnknown); assert_eq!(rejection.params["errorCode"], -26); assert_eq!(rejection.detail.as_deref(), Some("bad-txns-inputs-spent")); } @@ -1416,3 +1537,24 @@ mod submit_tests { ); } } + +#[cfg(test)] +mod memo_tests { + use super::*; + #[test] + fn text_and_hex_fields_preserve_bytes_and_reject_ambiguous_input() { + let text = parse_memo(Some(" 中文\n🙂 "), None).unwrap().unwrap(); + let hex = hex::encode(text.as_array()); + assert_eq!(parse_memo(None, Some(&hex)).unwrap().unwrap(), text); + let binary = format!("ff000102{}", "00".repeat(508)); + assert_eq!( + hex::encode(parse_memo(None, Some(&binary)).unwrap().unwrap().as_array()), + binary + ); + assert!(parse_memo(Some("text"), Some(&hex)).is_err()); + assert!(parse_memo(None, Some("ff00")).is_err()); + assert!(parse_memo(None, Some(&"zz".repeat(512))).is_err()); + assert!(parse_memo(Some(&"🙂".repeat(129)), None).is_err()); + assert!(parse_memo(None, None).unwrap().is_none()); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs index d7702dc25..305145798 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs @@ -25,12 +25,17 @@ use zcash_address::unified::{Container, Encoding, Fvk, Ufvk}; use zcash_client_backend::data_api::chain::error::Error as ChainError; use zcash_client_backend::data_api::chain::{BlockSource, ChainState, CommitmentTreeRoot}; use zcash_client_backend::data_api::scanning::{ScanPriority, ScanRange}; -use zcash_client_backend::data_api::{WalletCommitmentTrees, WalletRead, WalletWrite}; +use zcash_client_backend::data_api::{ + TransactionDataRequest, TransactionStatus, WalletCommitmentTrees, WalletRead, WalletWrite, +}; +use zcash_client_backend::decrypt_transaction; use zcash_client_backend::proto::service; use zcash_client_backend::scanning::{scan_block, Nullifiers, ScanningKeys}; +use zcash_client_sqlite::AccountUuid; use zcash_keys::keys::UnifiedFullViewingKey; use zcash_primitives::merkle_tree::HashSer; -use zcash_protocol::consensus::{BlockHeight, NetworkUpgrade, Parameters}; +use zcash_primitives::transaction::{Transaction, TxId}; +use zcash_protocol::consensus::{BlockHeight, BranchId, NetworkUpgrade, Parameters}; use crate::blockcache::MemoryBlockCache; use crate::error::{ErrorCode, Result, RuntimeError}; @@ -375,6 +380,16 @@ pub async fn step( batches_done += 1; } + // Compact blocks cannot supply full outgoing amounts, fees or memos. + // Bound the optional enrichment work independently of the scan lanes. + // The host visits several scan lanes per turn; enrich only on historic + // steps, or standalone steps, to keep the network budget bounded. + let enhancement = if preferred.is_none() || preferred == Some(ScanPriority::Historic) { + enhance_transactions(db, client, active_ufvks).await + } else { + Ok(0) + }; + // 扫完之后重新问一次,把剩余量报给宿主做进度条。 let remaining = db .suggest_scan_ranges() @@ -383,6 +398,8 @@ pub async fn step( Ok(json!({ "done": remaining_blocks == 0, + "transactionsEnhanced": enhancement.as_ref().copied().unwrap_or(0), + "enhancementError": enhancement.err().map(|error| error.to_string()), "activeAccounts": active_account_count, "batchesDone": batches_done, "blocksScanned": blocks_scanned, @@ -399,6 +416,143 @@ pub async fn step( .to_string()) } +// Use the official decrypt/store APIs with only explicitly enabled identities. +// The convenience decrypt_and_store_transaction helper would try every stored +// UFVK, including accounts whose Privacy Mode has been switched off. + +async fn enhance_transactions( + db: &mut Db, + client: &mut LightClient, + active_ufvks: &[String], +) -> Result { + let params = *db.params(); + let active: HashSet<&str> = active_ufvks.iter().map(String::as_str).collect(); + let keys = db + .get_unified_full_viewing_keys() + .map_err(|error| db_err("enhancementKeys", error))? + .into_iter() + .filter(|(_, key)| active.contains(key.encode(¶ms).as_str())) + .collect::>(); + if keys.is_empty() { + return Ok(0); + } + let requests = db + .transaction_data_requests() + .map_err(|error| db_err("transactionDataRequests", error))?; + let mut txids = requests + .into_iter() + .filter_map(|request| match request { + TransactionDataRequest::Enhancement(txid) => Some((0, txid)), + TransactionDataRequest::GetStatus(txid) => Some((1, txid)), + // Public address discovery remains owned by the transparent indexer. + _ => None, + }) + .collect::>(); + // Never disclose a paused account's transaction ID to the sync endpoint. + txids = select_enhancement_requests(db, &keys.keys().copied().collect::>(), txids)?; + txids.sort_by_key(|(priority, txid)| (*priority, txid.to_string())); + txids.dedup_by_key(|(_, txid)| *txid); + // Advance even after a failed fetch so one missing transaction cannot + // permanently starve the rest. This scalar belongs to the runtime instance. + thread_local! { static ENHANCEMENT_CURSOR: std::cell::Cell = const { std::cell::Cell::new(0) }; } + if !txids.is_empty() { + let offset = ENHANCEMENT_CURSOR.with(|cursor| { + let value = cursor.get(); + cursor.set(value.wrapping_add(1)); + value % txids.len() + }); + txids.rotate_left(offset); + } + let mut enhanced = 0; + for (_, txid) in txids.into_iter().take(2) { + let response = crate::network::with_timeout( + async { + match client + .get_transaction(service::TxFilter { + hash: txid.as_ref().to_vec(), + ..Default::default() + }) + .await + { + Ok(response) => Ok(Some(response.into_inner())), + Err(status) if status.code() == tonic::Code::NotFound => Ok(None), + Err(error) => Err(net_err("enhanceTransaction", error)), + } + }, + 5_000, + "enhanceTransaction", + ) + .await?; + let Some(raw) = response else { + db.set_transaction_status(txid, TransactionStatus::TxidNotRecognized) + .map_err(|error| db_err("enhancementStatus", error))?; + continue; + }; + let mined_height = match raw.height { + 0 | u64::MAX => None, + height => Some(BlockHeight::from_u32(u32::try_from(height).map_err( + |error| RuntimeError::new(ErrorCode::InvalidBlockHeight).detail(error), + )?)), + }; + let tip = db + .chain_height() + .map_err(|error| db_err("enhancementChainHeight", error))?; + let branch = BranchId::for_height( + ¶ms, + mined_height.or(tip).unwrap_or(BlockHeight::from_u32(0)), + ); + let tx = parse_enhancement(&raw.data, branch, txid)?; + let height = mined_height.or(db + .get_tx_height(txid) + .map_err(|error| db_err("enhancementTxHeight", error))?); + db.store_decrypted_tx(decrypt_transaction(¶ms, height, tip, &tx, &keys)) + .map_err(|error| db_err("storeEnhancedTransaction", error))?; + db.set_transaction_status( + txid, + mined_height + .map(TransactionStatus::Mined) + .unwrap_or(TransactionStatus::NotInMainChain), + ) + .map_err(|error| db_err("enhancementStatus", error))?; + enhanced += 1; + } + Ok(enhanced) +} + +fn select_enhancement_requests( + db: &mut Db, + active_accounts: &[AccountUuid], + requests: Vec<(u8, TxId)>, +) -> Result> { + db.transactionally_with_extension(|_, ext| { + let mut selected = Vec::new(); + for request in requests { + for account in active_accounts { + let visible: bool = ext.query_row( + "SELECT EXISTS(SELECT 1 FROM v_transactions WHERE txid = ?1 AND account_uuid = ?2)", + rusqlite::params![request.1.as_ref(), account.expose_uuid()], + |row| row.get(0), + )?; + if visible { selected.push(request); break; } + } + } + Ok::<_, rusqlite::Error>(selected) + }).map_err(|error| db_err("enhancementOwnership", error)) +} + +fn parse_enhancement(data: &[u8], branch: BranchId, expected: TxId) -> Result { + let mut reader = std::io::Cursor::new(data); + let tx = Transaction::read(&mut reader, branch) + .map_err(|error| net_err("parseEnhancedTransaction", error))?; + if reader.position() != data.len() as u64 || tx.txid() != expected { + return Err(net_err( + "parseEnhancedTransaction", + "transaction identity or length mismatch", + )); + } + Ok(tx) +} + /// 就地扫描一批区块并落库。**不使用上游的 `scan_cached_blocks`。** /// /// ## 为什么不能用 `scan_cached_blocks` @@ -733,6 +887,7 @@ const DOWNLOAD_SOFT_BUDGET_MS: f64 = 30_000.0; /// 每条流消息各自套 DEFAULT_TIMEOUT_MS 的**停滞**超时:只有一颗块都没 /// 收到过的停滞才向上抛错(交给调用方重试/对半);已有收获的停滞和 /// 预算超线一样,截断收工。 + async fn download_batch( client: &mut LightClient, cache: &MemoryBlockCache, @@ -886,6 +1041,58 @@ mod tests { use zcash_keys::keys::UnifiedSpendingKey; use zcash_protocol::consensus::Network; + #[test] + fn enhancement_only_requests_transactions_owned_by_enabled_accounts() { + use rand::SeedableRng; + let conn = rusqlite::Connection::open_in_memory().unwrap(); + conn.execute_batch("CREATE TABLE v_transactions (txid BLOB, account_uuid BLOB)") + .unwrap(); + let active = AccountUuid::from_uuid(uuid::Uuid::from_bytes([1; 16])); + let paused = AccountUuid::from_uuid(uuid::Uuid::from_bytes([2; 16])); + let active_tx = TxId::from_bytes([3; 32]); + let paused_tx = TxId::from_bytes([4; 32]); + for (account, txid) in [(active, active_tx), (paused, paused_tx)] { + conn.execute( + "INSERT INTO v_transactions VALUES (?1, ?2)", + rusqlite::params![txid.as_ref(), account.expose_uuid()], + ) + .unwrap(); + } + let mut db = zcash_client_sqlite::WalletDb::from_connection( + conn, + Network::TestNetwork, + crate::clock::HostClock, + rand_chacha::ChaCha20Rng::from_seed([7; 32]), + ); + assert_eq!( + select_enhancement_requests(&mut db, &[active], vec![(0, active_tx), (0, paused_tx)]) + .unwrap(), + vec![(0, active_tx)] + ); + assert!( + select_enhancement_requests(&mut db, &[], vec![(0, active_tx)]) + .unwrap() + .is_empty() + ); + } + + #[test] + fn enhancement_validates_identity_and_complete_serialization() { + let fixture: serde_json::Value = serde_json::from_str(include_str!( + "../../zcash-keys-runtime/tests/fixtures/previous-transactions.json" + )) + .unwrap(); + let entry = &fixture["transactions"][0]; + let raw = hex::decode(entry["rawTx"].as_str().unwrap()).unwrap(); + let expected = Transaction::read(&raw[..], BranchId::Nu6_2).unwrap().txid(); + assert!(parse_enhancement(&raw, BranchId::Nu6_2, expected).is_ok()); + assert!(parse_enhancement(&raw, BranchId::Nu6_2, TxId::from_bytes([0; 32])).is_err()); + assert!(parse_enhancement(&raw[..4], BranchId::Nu6_2, expected).is_err()); + let mut trailing = raw; + trailing.push(0); + assert!(parse_enhancement(&trailing, BranchId::Nu6_2, expected).is_err()); + } + fn test_ufvk(network: &Network, seed_byte: u8) -> UnifiedFullViewingKey { UnifiedSpendingKey::from_seed( network, diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs index bcb0758da..028d44089 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs @@ -70,16 +70,22 @@ fn db_err(operation: &'static str, error: impl std::fmt::Display) -> RuntimeErro pub fn existing_txid_for_reservation( ext: &ExtensionTransaction<'_>, reservation_id: &str, + expected_account_uuid: Option<&str>, ) -> Result> { let txid = ext .query_row( - &format!("SELECT txid FROM {TABLE} WHERE reservation_id = ?1"), + &format!("SELECT txid, account_uuid FROM {TABLE} WHERE reservation_id = ?1"), [reservation_id], - |row| row.get::<_, Vec>(0), + |row| Ok((row.get::<_, Vec>(0)?, row.get::<_, Vec>(1)?)), ) .optional() .map_err(|error| db_err("findBroadcastIntent", error))?; - Ok(txid.map(|bytes| hex_display_order(&bytes))) + if let (Some((_, owner)), Some(expected)) = (&txid, expected_account_uuid) { + if *owner != uuid_blob(expected)? { + return Err(RuntimeError::new(ErrorCode::InvalidReservationId)); + } + } + Ok(txid.map(|(bytes, _)| hex_display_order(&bytes))) } pub fn insert_finalized( diff --git a/chain-runtimes/zcash/patches/manifest.json b/chain-runtimes/zcash/patches/manifest.json index 2d534ca1e..9af7c348f 100644 --- a/chain-runtimes/zcash/patches/manifest.json +++ b/chain-runtimes/zcash/patches/manifest.json @@ -10,5 +10,11 @@ "version": "0.2.0", "sha256": "7f7a5c9ac229421d577bb5a9bb59048838509958b218dd4e0b3c1214a87c361e", "patch": "sqlite-wasm-vfs-0.2.0-opfs-durability.patch" + }, + { + "name": "tonic-web-wasm-client", + "version": "0.9.1", + "sha256": "3c0469c353de5f665c95f898074b5b004b500c6722214c3249f1dc79c0a2a3f6", + "patch": "tonic-web-wasm-client-0.9.1-host-fetch.patch" } ] diff --git a/chain-runtimes/zcash/patches/tonic-web-wasm-client-0.9.1-host-fetch.patch b/chain-runtimes/zcash/patches/tonic-web-wasm-client-0.9.1-host-fetch.patch new file mode 100644 index 000000000..50d0c0059 --- /dev/null +++ b/chain-runtimes/zcash/patches/tonic-web-wasm-client-0.9.1-host-fetch.patch @@ -0,0 +1,47 @@ +diff --git a/src/call.rs b/src/call.rs +index f46e5aa..c343eeb 100644 +--- a/src/call.rs ++++ b/src/call.rs +@@ -23,7 +23,7 @@ pub async fn call( + + let request = prepare_request(&base_url, headers, body)?; + let (init, abort) = options.request_init()?; +- let response = fetch(&request, &init).await?; ++ let response = fetch(&request, &init, options.fetch.as_ref()).await?; + + let result = Response::builder().status(response.status()); + let (result, content_type) = set_response_headers(result, &response)?; +diff --git a/src/fetch.rs b/src/fetch.rs +index af70088..59929fb 100644 +--- a/src/fetch.rs ++++ b/src/fetch.rs +@@ -23,8 +23,13 @@ fn js_fetch(request: &Request, init: &RequestInit) -> Promise { + } + } + +-pub async fn fetch(request: &Request, init: &RequestInit) -> Result { +- let js_response = JsFuture::from(js_fetch(request, init)) ++pub async fn fetch(request: &Request, init: &RequestInit, handler: Option<&js_sys::Function>) -> Result { ++ // OneKey patch: keep the upstream response/trailer parser and abort guard. ++ let promise = match handler { ++ Some(handler) => Promise::resolve(&handler.call2(&JsValue::NULL, request, init).map_err(Error::js_error)?), ++ None => js_fetch(request, init), ++ }; ++ let js_response = JsFuture::from(promise) + .await + .map_err(Error::js_error)?; + +diff --git a/src/options/mod.rs b/src/options/mod.rs +index 8d4868c..798c5b4 100644 +--- a/src/options/mod.rs ++++ b/src/options/mod.rs +@@ -18,6 +18,9 @@ use web_sys::RequestInit; + /// Options for underlying `fetch` call + #[derive(Debug, Clone, Default)] + pub struct FetchOptions { ++ /// OneKey patch: per-client host transport, without replacing global fetch. ++ pub fetch: Option, ++ + /// Request's cache mode + pub cache: Option, + From faa6cd73181bee584fbedc825935f9aaa80ff03d Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 17:12:42 +0800 Subject: [PATCH 14/97] fix(zcash): never report an uncertain broadcast as rejected - treat only consensus-invalid or expired node replies as a rejection; any other broadcast error is an unknown outcome that stays pending and is rebroadcast, so the host never invites a resend that could pay twice - run the durability barrier after a rejection too, since its state is written - drop the Sapling receiver from every unified address policy; this runtime cannot spend Sapling notes - check that the birthday tree state is for the requested block and network - refuse to build under a reservation id that already has a stored transaction - correct submit, spend source and lock documentation --- .../crates/zcash-keys-runtime/src/keys.rs | 54 +++++++++++++++-- .../zcash/crates/zcash-runtime/src/account.rs | 60 +++++++++++++++++++ .../zcash/crates/zcash-runtime/src/bindgen.rs | 26 ++++---- .../zcash/crates/zcash-runtime/src/error.rs | 13 ++-- .../zcash/crates/zcash-runtime/src/network.rs | 56 +++++++++++++++-- .../zcash/crates/zcash-runtime/src/send.rs | 38 +++++++++--- 6 files changed, 212 insertions(+), 35 deletions(-) diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs index 194f5c5cc..0639d0fa7 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs @@ -96,15 +96,19 @@ pub fn ufvk_from_seed_bytes(params: Network, seed: &[u8], account_index: u32) -> /// 也决定了这个地址会不会把你的透明活动和屏蔽活动关联起来。所以由宿主指定。 /// /// Runtime 只负责校验组合在协议上是否成立。 +/// +/// **任何取值都不含 Sapling receiver。** 本 runtime 不能花 Sapling(不带它的 +/// prover),地址里放一个 Sapling receiver,只认 Sapling 的付款方就会把钱打 +/// 进一个这里花不出去的池子。`"shielded"` 因此与 `"orchard"` 相同,保留这个 +/// 取值只为不打断已有的调用方。 fn receiver_policy(name: &str) -> Result { - use zcash_keys::keys::UnifiedAddressRequest as R; + use zcash_keys::keys::{ReceiverRequirement::*, UnifiedAddressRequest as R}; match name { // 空串不再当作 `"all"`。缺省最省事的那个取值恰好是隐私上最贵的一个: // 带 transparent receiver 的 UA 会把用户的透明活动和屏蔽活动绑在 // 同一个字符串里,而调用方什么都没写,也就什么都没同意。 - "all" => Ok(R::ALLOW_ALL), - "shielded" => Ok(R::SHIELDED), - "orchard" => Ok(R::ORCHARD), + "all" => Ok(R::unsafe_custom(Require, Omit, Allow)), + "shielded" | "orchard" => Ok(R::ORCHARD), other => Err(KeysError::with( ErrorCode::InvalidUfvk, json!({ "stage": "receiverPolicy", "value": other }), @@ -136,8 +140,9 @@ pub fn transparent_address(network: &str, ufvk_str: &str) -> Result { let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str) .map_err(|e| KeysError::new(ErrorCode::InvalidUfvk).detail(e))?; + // 与 `"all"` 取同一个地址,保证这里的 t 地址就是 UA 里的透明 receiver。 let (addr, _) = ufvk - .default_address(zcash_keys::keys::UnifiedAddressRequest::ALLOW_ALL) + .default_address(receiver_policy("all")?) .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?; let t = addr.transparent().ok_or_else(|| { @@ -209,6 +214,45 @@ mod tests { assert_ne!(t, ua, "t 地址与 UA 是两种呈现,不该相同"); } + #[test] + fn no_address_policy_includes_a_sapling_receiver() { + use zcash_address::unified::{Address, Container, Encoding, Receiver}; + + for network in ["main", "test"] { + let ufvk = ufvk_from_mnemonic(network, TEST_MNEMONIC, 0).unwrap(); + for policy in ["all", "shielded", "orchard"] { + let ua = unified_address_with(network, &ufvk, policy).unwrap(); + let (_, address) = Address::decode(&ua).unwrap(); + let receivers = address.items(); + assert!( + !receivers.iter().any(|r| matches!(r, Receiver::Sapling(_))), + "{network}/{policy} 不能含 Sapling receiver" + ); + assert!(receivers.iter().any(|r| matches!(r, Receiver::Orchard(_)))); + assert_eq!( + receivers.iter().any(|r| matches!(r, Receiver::P2pkh(_))), + policy == "all", + "{network}/{policy}" + ); + } + // 「all」里的透明 receiver 必须就是单独给出的那个 t 地址(/0/0)。 + let params = parse_network(network).unwrap(); + let all = unified_address_with(network, &ufvk, "all").unwrap(); + let Some(zcash_keys::address::Address::Unified(all)) = + zcash_keys::address::Address::decode(¶ms, &all) + else { + panic!("{network}: 应解析为 UA"); + }; + assert_eq!( + zcash_keys::encoding::encode_transparent_address_p( + ¶ms, + all.transparent().unwrap() + ), + transparent_address(network, &ufvk).unwrap() + ); + } + } + // 公开测试向量,切勿用于真实资金。 const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs index 0ffa92330..904c16488 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs @@ -45,6 +45,7 @@ pub async fn import_ufvk( // 所以需要「birthday 之前」的树状态作为锚点。 let anchor_height = birthday_height.saturating_sub(1); let treestate = network::tree_state(client, anchor_height).await?; + check_birthday_tree_state(&treestate, anchor_height, ¶ms)?; let birthday = AccountBirthday::from_treestate(treestate, None).map_err(|e| { RuntimeError::with( @@ -275,3 +276,62 @@ pub fn confirmations_policy( let u = std::num::NonZeroU32::new(untrusted).ok_or_else(bad)?; ConfirmationsPolicy::new(t, u, allow_zero_conf_shielding).map_err(|e| bad().detail(e)) } + +/// 生日取自服务端给的树状态:上游按它报的高度 + 1 定生日,不核对是不是 +/// 我们要的那一块。报高了,生日之前那段收款永远不扫;报错了网络,整个账户 +/// 都在别的链上。所以高度必须正好是请求的那一块,网络(服务端给了的话) +/// 必须是钱包的网络。 +fn check_birthday_tree_state( + treestate: &zcash_client_backend::proto::service::TreeState, + anchor_height: u32, + params: &zcash_protocol::consensus::Network, +) -> Result<()> { + use zcash_protocol::consensus::Network; + let expected_network = match params { + Network::MainNetwork => "main", + Network::TestNetwork => "test", + }; + let network_ok = treestate.network.is_empty() || treestate.network == expected_network; + if treestate.height != u64::from(anchor_height) || !network_ok { + return Err(RuntimeError::with( + ErrorCode::InvalidBlockHeight, + json!({ + "stage": "birthdayTreeState", + "requestedHeight": anchor_height, + "returnedHeight": treestate.height, + "returnedNetwork": treestate.network, + }), + )); + } + Ok(()) +} + +#[cfg(test)] +mod birthday_tests { + use super::check_birthday_tree_state; + use zcash_client_backend::proto::service::TreeState; + use zcash_protocol::consensus::Network; + + fn state(network: &str, height: u64) -> TreeState { + TreeState { + network: network.to_owned(), + height, + ..Default::default() + } + } + + #[test] + fn the_birthday_tree_state_must_be_the_requested_block_on_our_network() { + let main = Network::MainNetwork; + check_birthday_tree_state(&state("main", 3_000_000), 3_000_000, &main).unwrap(); + check_birthday_tree_state(&state("", 3_000_000), 3_000_000, &main).unwrap(); + for bad in [ + state("main", 3_000_001), + state("main", 2_999_999), + state("test", 3_000_000), + ] { + assert!(check_birthday_tree_state(&bad, 3_000_000, &main).is_err()); + } + check_birthday_tree_state(&state("test", 10), 10, &Network::TestNetwork).unwrap(); + } +} diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs index f03fd3ba6..a79049c10 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs @@ -644,10 +644,13 @@ async fn barrier_after_irreversible(params: serde_json::Value) -> Result<(), cra }) } -/// 提交已证明且已签名的 PCZT:提取交易、广播,再按结局决定落不落库。 +/// 提交已证明且已签名的 PCZT:提取交易、先落库、再广播。 /// /// 返回 `{ txid, broadcast: "accepted" | "rejected" | "unknown", error? }`。 -/// 节点明确拒收时交易不落库、note 立即放回;结局未知时已落库,同步会重播。 +/// - `rejected`:节点明确判定共识无效或已过期,永远上不了链。交易仍在库里, +/// 它花的 note 要到过期高度才回来。 +/// - `unknown`:不能确定节点收没收到。交易保持待确认、同步时重播,宿主**不得** +/// 当作发送失败。 #[wasm_bindgen(js_name = pcztSubmit)] pub async fn pczt_submit( account_uuid: String, @@ -670,15 +673,11 @@ pub async fn pczt_submit( send::SubmitOutcome::Accepted { txid } => { serde_json::json!({ "txid": txid, "broadcast": "accepted" }) } - send::SubmitOutcome::Rejected { txid, error } => { - // 没落库,也就没有需要落盘屏障的东西。 - return Ok(serde_json::json!({ - "txid": txid, - "broadcast": "rejected", - "error": error.to_json(), - }) - .to_string()); - } + send::SubmitOutcome::Rejected { txid, error } => serde_json::json!({ + "txid": txid, + "broadcast": "rejected", + "error": error.to_json(), + }), send::SubmitOutcome::Unknown { txid, error } => serde_json::json!({ "txid": txid, "broadcast": "unknown", @@ -719,8 +718,9 @@ pub fn rebroadcastable_txids(account_uuid: String) -> Result { /// 重播已落库、结局未知的交易(同步时调用)。**不可逆。** /// -/// 节点拒绝抛 `BROADCAST_REJECTED`(不要重试,先查原因); -/// 网络本身出错抛 `NETWORK_ERROR`(可以重试,交易已在本地库里)。 +/// 节点明确判定无效抛 `BROADCAST_REJECTED`(不要重试,先查原因); +/// 节点回了错误但不能确定上不了链时抛 `BROADCAST_OUTCOME_UNKNOWN`,网络本身出错 +/// 抛 `NETWORK_ERROR` —— 这两种交易都仍待确认,下次同步照常重播。 #[wasm_bindgen(js_name = broadcastTransaction)] pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> { let result = runtime::with_db_and_client(move |mut db, mut client| async move { diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs index e9b6d8c6e..cf85c8b64 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs @@ -109,15 +109,16 @@ pub enum ErrorCode { PcztError, /// 交易构造失败(选币、费用、anchor 等)。参数:`{ stage }` TransactionBuildError, - /// 交易已提交但被节点拒绝。参数:`{ errorCode }`,`detail` 里是节点原文。 + /// 节点明确判定这笔交易共识上无效或已过期,永远上不了链。 + /// 参数:`{ errorCode }`,`detail` 里是节点原文。 /// /// 与 `NETWORK_ERROR` 分开:网络错误可以原样重试,被拒绝**不能** —— - /// 重发同一笔只会再被拒一次。宿主该做的是查明原因(费用不足、双花、 - /// 共识分支不对),而不是退避重试。 + /// 重发同一笔只会再被拒一次。交易已落库,它花的 note 要到过期高度才回来。 BroadcastRejected, - /// 节点回了拒绝,但原因同样可能是「这笔交易已经上链/在池里」(双花、重复 - /// nullifier、找不到输入)。不能判拒绝:交易保持待确认,由扫链见到上链或过期来定。 - /// 参数:`{ errorCode }`,`detail` 里是节点原文。 + /// 节点回了错误,但不能确定这笔交易上不了链:可能已经上链/在池里(双花、 + /// 重复 nullifier、找不到输入),也可能只是节点暂时不收(忙、内存池满、 + /// 同步落后)。交易保持待确认、同步时重播,由扫链见到上链或过期来定。 + /// 宿主**不得**把它当作发送失败。参数:`{ errorCode }`,`detail` 里是节点原文。 BroadcastOutcomeUnknown, /// 本地交易没有持久化的广播授权。参数:`{ txid }`。 BroadcastIntentNotFound, diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs index 76a0cb896..49b55c532 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs @@ -197,10 +197,10 @@ pub async fn broadcast(client: &mut LightClient, tx_bytes: Vec) -> Result<() if broadcast_already_known(&resp.error_message) { return Ok(()); } - let code = if broadcast_outcome_ambiguous(&resp.error_message) { - ErrorCode::BroadcastOutcomeUnknown - } else { + let code = if broadcast_definitely_invalid(&resp.error_message) { ErrorCode::BroadcastRejected + } else { + ErrorCode::BroadcastOutcomeUnknown }; return Err(RuntimeError::with( code, @@ -235,6 +235,26 @@ fn broadcast_outcome_ambiguous(message: &str) -> bool { .any(|needle| message.contains(needle)) } +/// 只有能确定这份字节**永远上不了链**的回复才算拒收。 +/// +/// 拒收会让宿主显示失败、不再把它当在途交易,用户随之重发;而原交易占着的 +/// note 要到过期高度才回来,重发只能换一批 note 去花。原交易若其实已经传播 +/// 出去(上一次超时其实发出去了,或节点一边转发一边回错),两笔都会上链。 +/// 所以这里是白名单:共识上无效(证明、签名、金额、分支不对)或已过期。 +/// 节点忙、内存池满、同步落后、非标准这类临时或策略性回复都不算 —— 记成 +/// 结局未知,同步时重播,过期后自然了结。 +fn broadcast_definitely_invalid(message: &str) -> bool { + if broadcast_outcome_ambiguous(message) { + return false; + } + let message = message.to_lowercase(); + // zcashd: main.cpp 的共识检查拒因。`tx-expiring-soon` 是策略(还剩几块 + // 才过期,别的节点仍可能打包),不在其列。 + ["bad-txns-", "bad-tx-", "tx-overwinter-expired"] + .iter() + .any(|needle| message.contains(needle)) +} + fn broadcast_already_known(message: &str) -> bool { let message = message.to_lowercase(); [ @@ -348,7 +368,10 @@ pub async fn tree_state(client: &mut LightClient, height: u32) -> Result Result { } } -/// 解析宿主传来的「只从这个池子花」。`None` 表示不限制(见 -/// `SendPolicy::spend_source`)。 +/// 解析宿主传来的「只从这个池子花」。构造与报价都要求给出(见 +/// `build_proposal`),`None` 在那里会被拒绝。 /// /// Orchard remains a valid spend source, but cannot receive new change. /// Sapling spending is unsupported because this runtime does not ship its prover. @@ -154,7 +153,7 @@ pub struct SendPolicy { /// 曾经硬编码 `false`,而余额读取那头却是参数 —— 宿主想跟进 ZIP-315 /// 就会造出「余额显示可花、选币拒花」的错配。读和花必须同源。 pub allow_zero_conf_shielding: bool, - /// 只从这一个屏蔽池选 note。`None` = 本方案能花的全部池子。 + /// 只从这一个屏蔽池选 note。必填:`None` 会在构造时被拒绝。 /// /// 存在的理由有两个,都不是可选的: /// @@ -570,14 +569,29 @@ pub fn forget_account_reservations(account_uuid: &str) { }); } +/// 一个 reservation 只对应一笔交易。已经落库过的 id 再拿来构造,会在同一个 +/// owner 下再锁一批 note,而提交只会重播旧的那笔:新锁既用不上也解不开。 +fn refuse_submitted_reservation(db: &mut Db, reservation_id: &str) -> Result<()> { + let submitted = db.transactionally_with_extension(|_wallet, ext| { + tx_state::existing_txid_for_reservation(ext, reservation_id, None) + })?; + match submitted { + Some(txid) => Err(RuntimeError::with( + ErrorCode::InvalidReservationId, + json!({ "reason": "alreadySubmitted", "txid": txid }), + )), + None => Ok(()), + } +} + /// 构造一笔转账的 PCZT(未签名),并**锁住选中的 note**。 /// /// 返回 `{ pcztHex, reservationId }`:`reservationId` 是这批 note 的占用凭证, /// 调用方必须一直带着它,直到交易提交(`pcztSubmit`)或用户取消(`releaseReservation`)。 /// 不释放也不会永久卡死 —— 锁有按区块高度的过期时间,但那是兜底,不是正常路径。 /// -/// `lock_for_blocks` 由宿主决定,但必须长过交易的过期高度:广播后、落库前崩溃时, -/// 只有这把锁防止同一批 note 被再花一次。 +/// `lock_for_blocks` 由宿主决定,但必须长过交易的过期高度。提交时交易先落库 +/// 再广播,落库之后由交易本身占住这批 note;锁管的是从构造到落库这一段。 /// /// `reservation_id` 可由调用方传入(64 位 hex)。上游的设计意图就是**调用方持有 /// 这个 token**:先生成、先持久化,再来构造。这样即使中途崩溃,恢复后仍然知道 @@ -602,6 +616,7 @@ pub fn create_pczt( None => LockOwner::random(&mut rand::rngs::OsRng), }; let reservation_id = hex32(owner.as_bytes()); + refuse_submitted_reservation(db, &reservation_id)?; let proposal = build_proposal( db, account_uuid, @@ -1177,6 +1192,15 @@ mod reservation_recovery_tests { } } + #[test] + fn a_reservation_that_already_has_a_stored_transaction_cannot_build_again() { + let (mut db, txid) = outcome_wallet(false); + let e = refuse_submitted_reservation(&mut db, "review").unwrap_err(); + assert_eq!(e.code, ErrorCode::InvalidReservationId); + assert_eq!(e.params["txid"], txid); + refuse_submitted_reservation(&mut db, &"ab".repeat(32)).unwrap(); + } + #[test] fn retry_cannot_use_another_accounts_reservation() { let (mut db, txid) = outcome_wallet(false); From facad65c7887362fb8561043b9ef3d965556eed7 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 17:12:43 +0800 Subject: [PATCH 15/97] fix(monero): record sends before broadcasting and validate node fees and network - record a send as pending, with its inputs marked spent, before broadcasting; undo only a fresh record after an explicit rejection, so an interrupted broadcast can never push the next send onto other inputs - keep the wallet's own sends pending on a reorg rewind instead of deleting them and releasing their inputs - expire signed reservations that never reached broadcast after a day - cap the fee rate per priority (5x current mainnet values; the old flat cap refused the highest priority) and require the protocol quantization mask of 10,000 - identify the node's network by its genesis hash on connect and refuse wallet operations against a node on another network --- .../crates/monero-runtime/src/bindgen.rs | 12 +- .../monero/crates/monero-runtime/src/error.rs | 4 + .../crates/monero-runtime/src/network.rs | 61 +++- .../monero/crates/monero-runtime/src/query.rs | 16 +- .../crates/monero-runtime/src/runtime.rs | 46 ++- .../monero/crates/monero-runtime/src/scan.rs | 64 ++++- .../monero/crates/monero-runtime/src/spend.rs | 265 +++++++++++++++--- 7 files changed, 419 insertions(+), 49 deletions(-) diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs index 1a2193745..1dc471257 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs @@ -64,13 +64,16 @@ pub async fn set_node_url(url: &str) -> std::result::Result<(), JsValue> { if url.trim().is_empty() { return Ok(()); } - let daemon = network::connect(url).await?; - runtime::set_daemon(daemon); + let (daemon, node_network) = network::connect(url).await?; + runtime::set_daemon(daemon, node_network); Ok(()) } /// 问链尖。**不要求钱包库已打开** —— 建账户时要用它定 birthday, /// 而那一刻库还没建。 +/// +/// 返回 `{ height, network }`:`network` 是节点所在的链(按创世块认定)。 +/// 这一步还没有钱包库可比对,宿主定 birthday 前须确认它与要建的钱包一致。 #[wasm_bindgen(js_name = chainTip)] pub async fn chain_tip() -> std::result::Result { let tip: u64 = runtime::with_daemon(|daemon| async move { @@ -78,7 +81,10 @@ pub async fn chain_tip() -> std::result::Result { (daemon, r) }) .await?; - json(serde_json::json!({ "height": tip })) + json(serde_json::json!({ + "height": tip, + "network": runtime::daemon_network().map(crate::keys::network_name), + })) } /// 注册一个身份(观察密钥对)。 diff --git a/chain-runtimes/monero/crates/monero-runtime/src/error.rs b/chain-runtimes/monero/crates/monero-runtime/src/error.rs index c0890a502..72402a553 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/error.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/error.rs @@ -50,6 +50,9 @@ pub enum ErrorCode { // ── 外部世界 ──────────────────────────────────────────────────────── /// 节点地址没配。 NodeNotConfigured, + /// 节点不在钱包所属的网络上(按创世块判断),或认不出它在哪条链上。 + /// 参数:`{ nodeNetwork, walletNetwork }` 或 `{ nodeGenesis }` + NodeNetworkMismatch, /// 网络请求失败或超时。参数:`{ operation }` NetworkError, /// 节点返回的数据解不开(epee/JSON 格式不对)。参数:`{ operation }` @@ -86,6 +89,7 @@ impl ErrorCode { RingCtIndexMismatch => "RINGCT_INDEX_MISMATCH", ScanFailed => "SCAN_FAILED", NodeNotConfigured => "NODE_NOT_CONFIGURED", + NodeNetworkMismatch => "NODE_NETWORK_MISMATCH", NetworkError => "NETWORK_ERROR", MalformedNodeResponse => "MALFORMED_NODE_RESPONSE", BroadcastRejected => "BROADCAST_REJECTED", diff --git a/chain-runtimes/monero/crates/monero-runtime/src/network.rs b/chain-runtimes/monero/crates/monero-runtime/src/network.rs index 2db388ab7..1f2456dff 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/network.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/network.rs @@ -428,7 +428,7 @@ pub type Daemon = MoneroDaemon; /// /// 节点地址**由宿主给**,这里没有内置默认值 —— 内置一个默认节点等于替用户 /// 决定把自己的 IP 和查询交给谁,那是隐私决策,不该藏在 runtime 里。 -pub async fn connect(base_url: &str) -> Result { +pub async fn connect(base_url: &str) -> Result<(Daemon, monero_wallet::address::Network)> { if base_url.trim().is_empty() { return Err(RuntimeError::new(ErrorCode::NodeNotConfigured)); } @@ -441,8 +441,54 @@ pub async fn connect(base_url: &str) -> Result { let daemon = MoneroDaemon::new(Transport::new(base_url)) .await .map_err(|e| net_err("connect", format!("{e:?}")))?; + let network = node_network(&daemon).await?; CURRENT_NODE_URL.with(|c| *c.borrow_mut() = Some(base_url.to_owned())); - Ok(daemon) + Ok((daemon, network)) +} + +/// 各网络的创世块哈希。 +/// +/// 同一套密钥在三个网络上推出同样的输出密钥:测试网钱包连上主网节点, +/// 扫到的就是真 XMR,按测试网地址发出去的也是真 XMR。只看地址前缀挡不住, +/// 必须确认节点所在的链。 +const GENESIS_HASHES: [(monero_wallet::address::Network, &str); 3] = [ + ( + monero_wallet::address::Network::Mainnet, + "418015bb9ae982a1975da7d79277c2705727a56894ba0fb246adaabb1f4632e3", + ), + ( + monero_wallet::address::Network::Testnet, + "48ca7cd3c8de5b6a4d53d2861fbdaedca141553559f9be9520068053cda8430b", + ), + ( + monero_wallet::address::Network::Stagenet, + "76ee3cc98646292206cd3e86f74d88b4dcc1d937088645e9b0cbca84b7ce74eb", + ), +]; + +pub(crate) fn network_for_genesis(hash: &[u8; 32]) -> Option { + let hash = hex::encode(hash); + GENESIS_HASHES + .iter() + .find(|(_, genesis)| *genesis == hash) + .map(|(network, _)| *network) +} + +/// 按创世块认出节点在哪条链上。认不出就不连:宁可没有节点,也不要一个 +/// 不知道在哪条链上的节点。 +async fn node_network(daemon: &Daemon) -> Result { + use monero_daemon_rpc::prelude::*; + + let genesis = daemon + .block_hash(0) + .await + .map_err(|e| net_err("genesisHash", format!("{e:?}")))?; + network_for_genesis(&genesis).ok_or_else(|| { + RuntimeError::with( + ErrorCode::NodeNetworkMismatch, + json!({ "nodeGenesis": hex::encode(genesis) }), + ) + }) } thread_local! { @@ -464,6 +510,17 @@ pub fn forget_node_url() { mod tests { use super::*; + #[test] + fn genesis_hashes_identify_each_network() { + use monero_wallet::address::Network; + for (network, genesis) in GENESIS_HASHES { + let bytes: [u8; 32] = hex::decode(genesis).unwrap().try_into().unwrap(); + assert_eq!(network_for_genesis(&bytes), Some(network)); + } + assert_eq!(network_for_genesis(&[0u8; 32]), None); + assert_ne!(Network::Mainnet, Network::Stagenet); + } + /// 不内置默认节点:内置一个等于替用户决定把 IP 和查询交给谁。 #[test] fn an_empty_node_url_is_refused_not_defaulted() { diff --git a/chain-runtimes/monero/crates/monero-runtime/src/query.rs b/chain-runtimes/monero/crates/monero-runtime/src/query.rs index b9f931ae2..fcf3e10c4 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/query.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs @@ -62,14 +62,18 @@ pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result ?2 OR l.signed_at IS NOT NULL) + LEFT JOIN locked_outputs l ON l.output_id = o.id AND (l.locked_at > ?2 OR l.signed_at > ?3) WHERE o.identity_id = ?1 AND o.spent_at_height IS NULL", ) .map_err(|e| db_err("balanceQuery", e))?; let rows = stmt .query_map( - params![identity_id, crate::spend::reservation_cutoff()], + params![ + identity_id, + crate::spend::reservation_cutoff(), + crate::spend::signed_reservation_cutoff() + ], |r| { Ok(( r.get::<_, i64>(0)? as u128, @@ -173,7 +177,7 @@ pub fn spendable_rows(db: &Db, identity_id: i64, chain_tip: u64) -> Result ?2 OR l.signed_at IS NOT NULL) + LEFT JOIN locked_outputs l ON l.output_id = o.id AND (l.locked_at > ?2 OR l.signed_at > ?3) WHERE o.identity_id = ?1 AND o.spent_at_height IS NULL AND o.key_image IS NOT NULL @@ -184,7 +188,11 @@ pub fn spendable_rows(db: &Db, identity_id: i64, chain_tip: u64) -> Result(0)?, diff --git a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs index a007b8f45..ee210763d 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs @@ -11,10 +11,13 @@ use std::cell::{Cell, RefCell}; use crate::error::{ErrorCode, Result, RuntimeError}; use crate::network::Daemon; use crate::wallet::Db; +use monero_wallet::address::Network; thread_local! { static DB: RefCell> = const { RefCell::new(None) }; static DAEMON: RefCell> = const { RefCell::new(None) }; + /// 当前节点所在的网络,连接时按创世块认定。与 DAEMON 同进同出。 + static DAEMON_NETWORK: Cell> = const { Cell::new(None) }; static DB_NAME: RefCell> = const { RefCell::new(None) }; // ── 并发防线 ──────────────────────────────────────────────────────── @@ -101,14 +104,36 @@ pub fn set_db(db: Db, db_name: &str) -> Result<()> { Ok(()) } -pub fn set_daemon(daemon: Daemon) { +pub fn set_daemon(daemon: Daemon, network: Network) { DAEMON.with(|c| *c.borrow_mut() = Some(daemon)); + DAEMON_NETWORK.with(|n| n.set(Some(network))); bump_daemon_generation(); } +/// 钱包库与节点必须在同一个网络上。不一致时什么都不做:测试网钱包连着主网 +/// 节点扫到的是真 XMR,发出去的也是。 +fn check_node_network(node: Option, wallet: Network) -> Result<()> { + if node == Some(wallet) { + return Ok(()); + } + Err(RuntimeError::with( + ErrorCode::NodeNetworkMismatch, + serde_json::json!({ + "nodeNetwork": node.map(crate::keys::network_name), + "walletNetwork": crate::keys::network_name(wallet), + }), + )) +} + +/// 当前节点所在的网络(连接时按创世块认定)。没有节点时为 `None`。 +pub fn daemon_network() -> Option { + DAEMON_NETWORK.with(Cell::get) +} + /// 断开当前节点。借出中的客户端放回时按世代号作废,不会复活。 pub fn clear_daemon() { DAEMON.with(|c| *c.borrow_mut() = None); + DAEMON_NETWORK.with(|n| n.set(None)); bump_daemon_generation(); } @@ -121,6 +146,7 @@ pub fn close() -> Result<()> { assert_idle("closeWallet")?; DB.with(|c| *c.borrow_mut() = None); DAEMON.with(|c| *c.borrow_mut() = None); + DAEMON_NETWORK.with(|n| n.set(None)); DB_NAME.with(|c| *c.borrow_mut() = None); bump_generation(); bump_daemon_generation(); @@ -167,6 +193,11 @@ where return Err(no_daemon()); } }; + if let Err(e) = check_node_network(DAEMON_NETWORK.with(Cell::get), db.network()) { + DB.with(|cell| *cell.borrow_mut() = Some(db)); + DAEMON.with(|cell| *cell.borrow_mut() = Some(daemon)); + return Err(e); + } let (db, daemon, out) = f(db, daemon).await; @@ -269,6 +300,19 @@ mod tests { with_db_read(|_| Ok(())).expect("库应当还在"); } + #[test] + fn a_node_on_another_network_is_refused() { + check_node_network(Some(Network::Mainnet), Network::Mainnet).unwrap(); + for (node, wallet) in [ + (Some(Network::Mainnet), Network::Stagenet), + (Some(Network::Testnet), Network::Mainnet), + (None, Network::Mainnet), + ] { + let e = check_node_network(node, wallet).unwrap_err(); + assert_eq!(e.code, ErrorCode::NodeNetworkMismatch); + } + } + /// 关库必须让在途的客户端借用作废。否则它结束时会把旧节点盖回去, /// 之后所有请求都发给上一个节点。 #[test] diff --git a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs index c10ffb1ef..7e8cca006 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs @@ -746,14 +746,24 @@ fn timelock_to_i64(timelock: monero_wallet::transaction::Timelock) -> i64 { /// 回退到指定高度:丢掉该高度**之上**的全部扫描结果。 /// -/// **破坏性。** 用于重组恢复。已广播的交易不受影响(它们在链上),但本地 -/// 未确认记录会丢。 +/// **破坏性。** 用于重组恢复。例外是自己广播过的交易:它所在的块被重组掉, +/// 交易通常回到交易池、稍后重新上链。删掉它会让它花的输入重新可选,用户 +/// 换一批输入再发一次,两笔都上链。所以它退回在途(高度清空),输入保持 +/// 已花,交给在途检查与扫描判定。 pub fn rewind_to(db: &mut Db, identity_id: i64, height: u64) -> Result<()> { let tx = db .conn_mut() .transaction() .map_err(|e| db_err("beginRewind", e))?; + // 放在撤销花费标记之前:下面那条按「在途交易」保留标记。 + tx.execute( + "UPDATE transactions SET height = NULL, failed = 0, pool_checked_at = NULL + WHERE identity_id = ?1 AND height > ?2 AND sent_at IS NOT NULL", + params![identity_id, height as i64], + ) + .map_err(|e| db_err("rewindOwnSends", e))?; + tx.execute( "DELETE FROM outputs WHERE identity_id = ?1 AND height > ?2", params![identity_id, height as i64], @@ -1101,6 +1111,56 @@ mod tests { assert_eq!(spent_in, Some(txid.to_vec())); } + /// 自己发出、已上链的交易所在块被重组掉:退回在途,输入不放回。 + #[test] + fn a_rewind_turns_our_confirmed_send_back_into_a_pending_one() { + let (mut db, id) = db_with_identity(); + let ours = [3u8; 32]; + let scanned = [4u8; 32]; + for (n, txid) in [(1u8, ours), (2u8, scanned)] { + db.conn() + .execute( + "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, + amount_atomic, height, key_image, spent_at_height, spent_in_txid) + VALUES (?1, x'00', ?2, ?3, 0, 700, 10, ?4, 500, ?5)", + params![id, [9u8 + n; 32].as_slice(), n, [n; 32].as_slice(), txid.as_slice()], + ) + .unwrap(); + } + db.conn() + .execute( + "INSERT INTO transactions (identity_id, txid, height, direction, sent_at) + VALUES (?1, ?2, 500, 'out', 1000), (?1, ?3, 500, 'out', NULL)", + params![id, ours.as_slice(), scanned.as_slice()], + ) + .unwrap(); + + rewind_to(&mut db, id, 490).unwrap(); + + let rows: Vec<(Vec, Option)> = db + .conn() + .prepare("SELECT txid, height FROM transactions") + .unwrap() + .query_map([], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!( + rows, + vec![(ours.to_vec(), None)], + "自己的退回在途,扫到的照删" + ); + let spent: Vec>> = db + .conn() + .prepare("SELECT spent_in_txid FROM outputs ORDER BY global_index") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(spent, vec![Some(ours.to_vec()), None]); + } + /// 空批次是合法的 no-op,不该报错也不该动任何状态。 #[test] fn an_empty_batch_is_a_harmless_no_op() { diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs index 492cd4e01..2fef01534 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs @@ -257,14 +257,27 @@ pub fn select_inputs( }) } -/// Unsigned review reservations expire; signed inputs remain held until resolved. +/// 未签名的预留一小时后作废:用户在确认页退出不会通知这里。 pub const RESERVATION_TTL_SECS: i64 = 60 * 60; +/// 已签名、但没走到广播的预留一天后作废。 +/// +/// 广播会在发出前把输入标已花、写在途记录,所以留到这里的签名从没发出去 +/// (设备上拒绝、取消、签完被杀)。永远锁着,下一笔就只能换一批输入花; +/// 那份旧签名万一之后又被广播,两笔都会上链。放开后同一批输入重新排在 +/// 选币的前面,两笔争同一批 key image,链上只会成一笔。 +pub const SIGNED_RESERVATION_TTL_SECS: i64 = 24 * 60 * 60; + /// 仍然有效的预留的下限时间:`locked_at` 大于它才算数。 pub fn reservation_cutoff() -> i64 { crate::wallet::now_secs() - RESERVATION_TTL_SECS } +/// 已签名预留的下限时间:`signed_at` 大于它才算数。 +pub fn signed_reservation_cutoff() -> i64 { + crate::wallet::now_secs() - SIGNED_RESERVATION_TTL_SECS +} + /// 预留选中的输出,防止被第二笔在途交易重复选中。 /// /// 不预留的后果很具体:两笔交易花同一个输出,第二笔必然被网络拒绝, @@ -277,8 +290,12 @@ pub fn reserve(db: &mut Db, reservation_id: &str, output_ids: &[i64]) -> Result< .map_err(|e| db_err("beginReserve", e))?; // 用户在确认页退出不会通知这里,作废的预留只能在这时清掉。 tx.execute( - "DELETE FROM locked_outputs WHERE locked_at <= ?1 AND signed_at IS NULL", - [now - RESERVATION_TTL_SECS], + "DELETE FROM locked_outputs + WHERE (signed_at IS NULL AND locked_at <= ?1) OR signed_at <= ?2", + params![ + now - RESERVATION_TTL_SECS, + now - SIGNED_RESERVATION_TTL_SECS + ], ) .map_err(|e| db_err("expireReservations", e))?; for id in output_ids { @@ -1071,6 +1088,28 @@ mod tests { assert!(mark_signed(&mut db, "review", 1).is_err()); } + #[test] + fn signed_reservations_that_never_broadcast_expire_after_a_day() { + let (mut db, id) = db_with_identity(); + let input = add_output(&db, id, 500, 10, true); + reserve(&mut db, "signed", &[input]).unwrap(); + mark_signed(&mut db, "signed", 1).unwrap(); + db.conn() + .execute( + "UPDATE locked_outputs SET locked_at = ?1, signed_at = ?1", + [signed_reservation_cutoff() - 1], + ) + .unwrap(); + assert_eq!(query::spendable_rows(&db, id, 100).unwrap().len(), 1); + assert_eq!( + query::balance(&db, id, Some(100)) + .unwrap() + .locked_by_reservation_atomic, + 0 + ); + reserve(&mut db, "replacement", &[input]).expect("过期的签名预留让位"); + } + #[test] fn signed_reservations_stay_unspendable_after_the_unsigned_ttl() { let (mut db, id) = db_with_identity(); @@ -1182,6 +1221,54 @@ mod tests { assert_eq!(outgoing.as_deref(), Some("123")); } + /// 记账在广播之前:被拒时只撤这一次新建的记录;重发同一笔不算新建。 + #[test] + fn a_rejected_first_broadcast_is_undone_but_a_retry_is_not_fresh() { + let (mut db, id) = db_with_identity(); + let a = add_output(&db, id, 500, 10, true); + reserve(&mut db, "r", &[a]).unwrap(); + let key_image: Vec = db + .conn() + .query_row("SELECT key_image FROM outputs WHERE id = ?1", [a], |r| { + r.get(0) + }) + .unwrap(); + let key_image = <[u8; 32]>::try_from(key_image.as_slice()).unwrap(); + let txid = [0x66u8; 32]; + let record = |db: &Db| { + record_broadcast( + db, + id, + &txid, + &[key_image], + "r", + 900, + SentAmounts::default(), + ) + .unwrap() + }; + + assert!(record(&db), "第一次是新建"); + assert!( + crate::query::spendable_rows(&db, id, 10_000) + .unwrap() + .is_empty(), + "广播前输入就已不可选" + ); + assert!(!record(&db), "同一笔再记一次不是新建"); + + undo_recorded_broadcast(&db, id, &txid).unwrap(); + assert_eq!( + crate::query::spendable_rows(&db, id, 10_000).unwrap().len(), + 1 + ); + let rows: i64 = db + .conn() + .query_row("SELECT count(*) FROM transactions", [], |r| r.get(0)) + .unwrap(); + assert_eq!(rows, 0, "被拒的交易不留在历史里"); + } + /// 同一笔输出不能被两个预留同时持有 —— 否则两笔交易花同一个输出, /// 第二笔必然被网络拒绝。 #[test] @@ -1228,15 +1315,54 @@ mod tests { // ── 端到端发送 ────────────────────────────────────────────────────────── -/// 手续费率的理智上限(piconero / weight)。 +/// 各优先级手续费率的上限(piconero / weight)。 /// /// 上游 `fee_rate` 强制要求给一个上限,理由很实在:**手续费率来自节点, /// 而节点可能撒谎**。报一个天价费率会让用户把余额全付成手续费。 /// -/// Monero 常规优先级的费率约在 20,000 piconero/weight 量级,最高优先级约 -/// 十倍。这里取 1,000,000 —— 比最高优先级还宽 5 倍,正常波动碰不到, -/// 但挡得住数量级级别的胡说。 -pub const MAX_FEE_PER_WEIGHT: u64 = 1_000_000; +/// monerod 的四档是基础费率的固定倍数,主网现值为 20,000 / 80,000 / +/// 320,000 / 4,000,000。基础费率随区块奖励与区块大小中位数算出:交易一多 +/// 区块变大,费率反而下降;尾部发行固定后奖励也不再变。所以各档按现值留 +/// 5 倍余量,正常波动碰不到,挡得住数量级级别的胡说。碰到上限的结果是这一档 +/// 发不出去,不会多付。 +pub fn max_fee_per_weight(priority: monero_wallet::interface::FeePriority) -> u64 { + use monero_wallet::interface::FeePriority; + match priority { + FeePriority::Unimportant => 100_000, + FeePriority::Normal => 400_000, + FeePriority::Elevated => 1_600_000, + FeePriority::Priority | FeePriority::Custom { .. } => 20_000_000, + } +} + +/// 手续费的取整单位(piconero)。 +/// +/// 这不是价格,是 monerod 写死的常量(`PER_KB_FEE_QUANTIZATION_DECIMALS = 8`, +/// 即 10^(12-8)),不随网络繁忙变化。上游拿节点给的值把手续费向上取整到它的 +/// 整数倍,不设上限 —— 节点报一个大 mask,手续费就跟着翻几百倍。所以只认这一个值。 +pub const FEE_QUANTIZATION_MASK: u64 = 10_000; + +/// 上游 `FeeRate` 不暴露 mask,只能从它的序列化里取:先 per_weight 后 mask, +/// 各 8 字节小端。布局由测试钉住,上游改了会先在测试里炸。 +fn fee_mask(rate: &monero_wallet::interface::FeeRate) -> Option { + let bytes = rate.serialize(); + Some(u64::from_le_bytes(bytes.get(8..16)?.try_into().ok()?)) +} + +fn check_fee_rate(rate: &monero_wallet::interface::FeeRate) -> Result<()> { + let mask = fee_mask(rate); + if mask != Some(FEE_QUANTIZATION_MASK) { + return Err(RuntimeError::with( + ErrorCode::NetworkError, + json!({ + "operation": "feeRate", + "reason": "unexpectedQuantizationMask", + "mask": mask.map(|m| m.to_string()), + }), + )); + } + Ok(()) +} /// 手续费优先级。字符串而非数字:数字跨边界时无从校验。 pub fn parse_priority(name: &str) -> Result { @@ -1292,12 +1418,13 @@ pub async fn prepare_for_host( let network = db.network(); let rate = daemon - .fee_rate(priority, MAX_FEE_PER_WEIGHT) + .fee_rate(priority, max_fee_per_weight(priority)) .await .map_err(|e| { RuntimeError::with(ErrorCode::NetworkError, json!({ "operation": "feeRate" })) .detail(format!("{e:?}")) })?; + check_fee_rate(&rate)?; // 当前共识:CLSAG + Bulletproofs+。跟着硬分叉走,由我们发版控制, // 不问节点 —— 节点说错了交易会被全网拒绝。 @@ -1377,7 +1504,6 @@ pub fn sign_for_host(signable_hex: &str, spend_private: &[u8], review_json: &str })) } -/// 广播成功后的记账:输入标已花、记一条在途转出、释放预留。一个事务。 /// 自己发出的一笔交易的金额(只有广播时知道)。 #[derive(Debug, Default, Clone, Copy)] pub struct SentAmounts { @@ -1387,6 +1513,10 @@ pub struct SentAmounts { pub change_atomic: Option, } +/// 广播前的记账:输入标已花、记一条在途转出、释放预留。一个事务。 +/// +/// 返回这条在途记录是不是这一次新建的。已有记录说明同一笔交易以前发过 +/// (重试同一份签名),那次的结局可能已经是「节点收下了」。 fn record_broadcast( db: &Db, identity_id: i64, @@ -1395,11 +1525,18 @@ fn record_broadcast( reservation_id: &str, chain_tip: u64, amounts: SentAmounts, -) -> Result<()> { +) -> Result { let tx_db = db .conn() .unchecked_transaction() .map_err(|e| db_err("beginRecordSend", e))?; + let existed: bool = tx_db + .query_row( + "SELECT EXISTS (SELECT 1 FROM transactions WHERE identity_id = ?1 AND txid = ?2)", + params![identity_id, txid.as_slice()], + |r| r.get(0), + ) + .map_err(|e| db_err("findRecordedSend", e))?; for key_image in key_images { tx_db .execute( @@ -1438,13 +1575,37 @@ fn record_broadcast( [reservation_id], ) .map_err(|e| db_err("releaseAfterBroadcast", e))?; - tx_db.commit().map_err(|e| db_err("commitRecordSend", e)) + tx_db.commit().map_err(|e| db_err("commitRecordSend", e))?; + Ok(!existed) +} + +/// 撤销这一次新建的在途记录:节点明确拒收,这笔不会上链,输入放回可用。 +fn undo_recorded_broadcast(db: &Db, identity_id: i64, txid: &[u8; 32]) -> Result<()> { + let tx_db = db + .conn() + .unchecked_transaction() + .map_err(|e| db_err("beginUndoSend", e))?; + tx_db + .execute( + "UPDATE outputs SET spent_at_height = NULL, spent_in_txid = NULL + WHERE identity_id = ?1 AND spent_in_txid = ?2", + params![identity_id, txid.as_slice()], + ) + .map_err(|e| db_err("releaseRejectedInputs", e))?; + tx_db + .execute( + "DELETE FROM transactions WHERE identity_id = ?1 AND txid = ?2 AND height IS NULL", + params![identity_id, txid.as_slice()], + ) + .map_err(|e| db_err("forgetRejectedSend", e))?; + tx_db.commit().map_err(|e| db_err("commitUndoSend", e)) } -/// 广播一笔已签名的交易,并记账。**不可逆。** +/// 记账,然后广播一笔已签名的交易。**不可逆。** /// -/// 广播成功后立刻把被花的输出标记掉:不标的话下一次选币会再选中它们, -/// 构出一笔必然被网络拒绝的交易。 +/// 先记账再广播:输入先标已花、先有一条在途记录,之后任何一刻被打断 +/// (Worker 被杀、回包丢失),重启后这笔都看得见,输入也不会被下一笔选中 +/// 而换一批去花 —— 换一批花,两笔都会上链,用户付两次。 pub async fn broadcast_signed( db: &Db, daemon: &crate::network::Daemon, @@ -1465,22 +1626,8 @@ pub async fn broadcast_signed( .map_err(|e| db_err("parseSignedTransaction", e))?; let txid = tx.hash(); - // 明确拒收说明这笔不会上链,输入放回可用。其余错误分不清节点收没收到: - // 照样记成在途交易,输入不会被重选(重发换一批输入就可能付两次); - // 节点真没收到的话,在途检查过了扩散期会判失败并放回输入。 - // 「双花」也可能是这笔自己早已上链(回包丢过、重试了同一份签名),同样当 - // 不确定处理:真是别人花的,扩散期后在途检查会判失败。 - let mut unknown = match broadcast(daemon, &raw).await { - Ok(()) => None, - Err(e) if e.code == ErrorCode::BroadcastRejected && !is_double_spend(&e) => { - release(db, reservation_id)?; - return Err(e); - } - Err(e) => Some(e), - }; - - // 广播已经发生,不可逆。立刻记账。按交易自己的 key image 标,不靠预留: - // 预留可能已经过期,或者签名失败释放后又拿同一份签名重发。 + // 按交易自己的 key image 标,不靠预留:预留可能已经过期,或者签名失败 + // 释放后又拿同一份签名重发。 let key_images: Vec<[u8; 32]> = tx .prefix() .inputs @@ -1492,9 +1639,8 @@ pub async fn broadcast_signed( _ => None, }) .collect(); - // 记账失败也不能报「发送失败」:交易可能已经在网上,报失败会引人重发。 - // 按不确定返回;扫链按 key image 会认出这笔。 - if let Err(e) = record_broadcast( + // 记不上账就不发:这时什么都还没发生,报错是真话。 + let fresh = record_broadcast( db, identity_id, &txid, @@ -1502,9 +1648,22 @@ pub async fn broadcast_signed( reservation_id, chain_tip, amounts, - ) { - unknown = Some(e); - } + )?; + + // 明确拒收说明这笔不会上链:这次新建的记录撤掉,输入放回可用。 + // 其余错误分不清节点收没收到:记录留着,输入不会被重选;节点真没收到的话, + // 在途检查过了扩散期会判失败并放回输入。 + // 「双花」也可能是这笔自己早已上链(回包丢过、重试了同一份签名),同样当 + // 不确定处理。以前发过的同一笔(`fresh` 为假)被拒也当不确定:上一次的 + // 结局可能是节点收下了。 + let unknown = match broadcast(daemon, &raw).await { + Ok(()) => None, + Err(e) if e.code == ErrorCode::BroadcastRejected && !is_double_spend(&e) && fresh => { + undo_recorded_broadcast(db, identity_id, &txid)?; + return Err(e); + } + Err(e) => Some(e), + }; Ok(json!({ "txid": hex::encode(txid), @@ -1570,6 +1729,38 @@ mod cached_decoys_tests { mod double_spend_tests { use super::*; + #[test] + fn only_the_protocol_quantization_mask_is_accepted() { + use monero_wallet::interface::FeeRate; + let rate = FeeRate::new(80_000, FEE_QUANTIZATION_MASK).unwrap(); + assert_eq!( + fee_mask(&rate), + Some(FEE_QUANTIZATION_MASK), + "序列化布局变了" + ); + check_fee_rate(&rate).unwrap(); + for mask in [1, 9_999, 10_001, 10_000_000_000] { + let rate = FeeRate::new(80_000, mask).unwrap(); + assert_eq!(fee_mask(&rate), Some(mask)); + let e = check_fee_rate(&rate).unwrap_err(); + assert_eq!(e.params["reason"], "unexpectedQuantizationMask"); + } + } + + /// 主网现值(2026-10)各档都要能发,且离上限至少 5 倍。 + #[test] + fn current_mainnet_fee_rates_fit_every_priority() { + use monero_wallet::interface::FeePriority; + for (priority, current) in [ + (FeePriority::Unimportant, 20_000), + (FeePriority::Normal, 80_000), + (FeePriority::Elevated, 320_000), + (FeePriority::Priority, 4_000_000), + ] { + assert!(current * 5 <= max_fee_per_weight(priority)); + } + } + #[test] fn a_double_spend_rejection_is_not_treated_as_final() { let spent = RuntimeError::new(ErrorCode::BroadcastRejected).detail("double spend"); From e5446b16b174150c6f2b68c7246369afe6f5cf96 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 17:12:43 +0800 Subject: [PATCH 16/97] docs: align chain runtime docs with current behavior - describe store-before-broadcast, rejection and unknown outcomes, receiver policies, fee and network checks as implemented - update the Zcash API list to the actual exports - remove stale experiment logs, local paths and process notes - require an explicit node for Monero live tests and scripts --- README.md | 5 +- chain-runtimes/README.md | 14 +- chain-runtimes/monero/CONTEXT.md | 98 +++---- chain-runtimes/monero/README.md | 15 +- .../crates/monero-runtime/tests/live_node.rs | 4 +- .../docs/hardware-and-offline-signing.md | 3 +- chain-runtimes/monero/rust-toolchain.toml | 14 +- chain-runtimes/monero/scripts/measure-scan.js | 6 +- chain-runtimes/zcash/CONTEXT.md | 10 +- chain-runtimes/zcash/IMPORT.md | 53 +--- chain-runtimes/zcash/README.md | 248 ++++++++---------- .../zcash-keys-runtime/TRANSPARENT_TX_API.md | 8 +- .../tests/fixtures/README.md | 5 +- chain-runtimes/zcash/docs/decisions.md | 136 +++------- 14 files changed, 235 insertions(+), 384 deletions(-) diff --git a/README.md b/README.md index 89267596f..d6f999caf 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,5 @@ The app-monorepo job checks the existing module-ID registry but does not regener ## Chain runtimes -Rust chain libraries live in [chain-runtimes](./chain-runtimes/README.md), separately -from React Native workspaces. Zcash is the first runtime; see its build and test -commands there. +Rust chain libraries (Zcash and Monero) live in [chain-runtimes](./chain-runtimes/README.md), +separately from React Native workspaces; see their build and test commands there. diff --git a/chain-runtimes/README.md b/chain-runtimes/README.md index 52950c40c..43ceb4137 100644 --- a/chain-runtimes/README.md +++ b/chain-runtimes/README.md @@ -7,7 +7,8 @@ workspaces or their shared version/publish commands. ## Zcash -See [zcash](./zcash/README.md) and its [import record](./zcash/IMPORT.md). +See [zcash](./zcash/README.md), its [import record](./zcash/IMPORT.md) and +[release process](./zcash/RELEASING.md). From the repository root: @@ -19,6 +20,11 @@ yarn zcash:build These convenience commands dispatch to the Rust project. The equivalent direct commands in the Zcash README do not require installing the root Node dependencies. -Generated WASM stays out of Git. The Zcash CI workflow builds -both runtime and keys packages together and stores them as one artifact; it does -not publish npm packages. +Generated WASM stays out of Git. The Zcash CI workflow builds both runtime and keys +packages together and stores them as one artifact; npm publishing is a separate, +manually triggered workflow described in the release process. + +## Monero + +See [monero](./monero/README.md). It is built and tested from its own directory +(`cargo test --workspace`, `bash scripts/build-wasm.sh`) and is not published yet. diff --git a/chain-runtimes/monero/CONTEXT.md b/chain-runtimes/monero/CONTEXT.md index 869dd5dc0..7b11ffeca 100644 --- a/chain-runtimes/monero/CONTEXT.md +++ b/chain-runtimes/monero/CONTEXT.md @@ -1,54 +1,40 @@ -# 交接上下文 +# 维护上下文 -写给接手的人(可能没有这个仓库的历史)。**这里只记不能从代码本身读出来的东西。** +**这里只记不能从代码本身读出来的东西。** -## 现在到哪了 - -Runtime 层扫链闭环 + 花费闭环已通,65 个测试,原生与 wasm32 两个目标零警告, -产物 3.92 MB / gzip 1.22 MB。 - -**没做的(按优先级):** - -1. **TS / app 层整个没动** —— `sdkMonero`、`Vault`、`Keyring`、四端载体接线。 - Zcash 那边这部分约 6,000 行。这是最大的一块缺口。 -2. **硬件签名** —— `OutputWithDecoys` 可序列化,天然支持「准备 / 签名」两阶段, - 但固件协议与 SDK 方法都还没有。 -3. **对真实节点的集成测试** —— 现在全是单元测试。扫描循环的三道校验、 - RingCT 索引推算,都只在构造的数据上验证过,没跑过主网。 -4. **内存池 / 未确认交易** —— `transactions.height` 允许 NULL 就是给它留的位, - 但没有拉取内存池的路径。 -5. **广播重试状态机** —— 广播后立刻记账,但没有「待广播 / 已拒绝」的生命周期 - 管理(Zcash 那边是 `tx_state.rs`)。 - -## 三件必须知道、代码里看不出来的事 +## 代码里看不出来的几件事 **一、扫描进度为什么在 `identities` 而不是从 `blocks` 推。** -`blocks` 表是全局的(块哈希是客观事实,各身份共享)。我一开始拿它的 -`max(height)` 当进度,结果是:一个追到链尖的身份会把另一个还在回补的身份的 -进度一起推到链尖,那段历史被永久跳过。已修,并有回归测试 -`two_identities_keep_independent_progress` 钉住。**别再改回去。** +`blocks` 表是全局的(块哈希是客观事实,各身份共享)。拿它的 `max(height)` 当进度, +会让一个追到链尖的身份把另一个还在回补的身份的进度一起推到链尖,那段历史被永久跳过。 +回归测试 `two_identities_keep_independent_progress` 钉住了这一点。**别改回去。** **二、为什么 `runtime.rs` 没有 wasm-only 门。** -Zcash 那边它是 `#[cfg(target_arch = "wasm32")]`,导致 `runtime.rs` 加两个 -`bindgen.rs` 共 1,377 行在原生 `cargo test` 里**根本不编译** —— 那是真实的覆盖 -漏洞,我们 review 时才发现。这里刻意不加那个门,所以并发防线(BUSY 守卫、 -世代号)是可测的,`runtime.rs` 里那 6 个测试就是。 +加了门,`runtime.rs` 与绑定层在原生 `cargo test` 里根本不编译,并发防线(BUSY 守卫、 +世代号)就测不到。这里刻意不加,`runtime.rs` 里的测试覆盖它们。 **三、`cargo check` 不链接。** -给 wasm 目标做验证时只跑 check 会漏掉链接期的问题。本工程踩过一次: -macOS 的 `/usr/bin/ar` 读不懂 wasm 目标文件,把 38 个编译好的 `.o` **静默** -打成 96 字节的空归档,编译阶段零报错,只有 `cargo build` 才暴露。归archiver -已由 `.cargo/config.toml` 固定成 llvm-ar。 +给 wasm 目标做验证时只跑 check 会漏掉链接期的问题。macOS 的 `/usr/bin/ar` 读不懂 +wasm 目标文件,会把编译好的 `.o` **静默**打成空归档,只有 `cargo build` 才暴露。 +归档器已由 `.cargo/config.toml` 固定成 llvm-ar。 + +## 发送的记账顺序 + +- 交易在**广播之前**就记为在途:输入按 key image 标为已花、写一条待确认记录。 + 广播结局未知(超时、Worker 被终止)时,这笔交易仍然可见、输入不会被重新选中, + 由在途检查(`pool.rs`)或扫链按 key image 认出来解决。只有节点明确拒收时才撤销。 +- 重组回退时,自己发出的交易改回待确认,而不是删除记录、放回输入。 +- 已签名但始终没有走到广播的预留 24 小时后过期(未签名的 1 小时)。过期后这批输入 + 重新排在选币前面,旧签名万一再被广播,两笔争同一批 key image,链上只成一笔。 ## 协议性的硬限制,不是实现问题 **观察钱包检测不到花费。** 需要 key image,而 key image 需要花费私钥。宿主必须 在解锁时调 `importKeyImages`,否则余额偏高。`balance` 返回的 -`unverifiableAtomic` 就是这部分,宿主应当据此提示用户。而且补齐只影响**之后** -扫的块 —— 补齐之前发生的花费要回退重扫才认得出来。 +`unverifiableAtomic` 就是这部分,宿主应当据此提示用户。 **节点声称的 RingCT 输出索引不可验证。** 上游文档明确要求客户端自己维护并比对。 `scan.rs` 实现了独立推算(按本块 v2 交易的输出总数推进游标),不一致报 @@ -57,39 +43,25 @@ macOS 的 `/usr/bin/ar` 读不懂 wasm 目标文件,把 38 个编译好的 `.o **时间戳形式的时间锁判不了。** 只有链高判得了块高形式的锁。时间戳形式的一律 按「仍锁定」处理 —— 让用户等,好过让他构一笔必然被拒的交易。 -## 刻意写死、不问节点的三个值 - -都写死是因为「节点说错了」的后果比「我们发版晚了」严重: - -- **环大小 16**(`spend::RING_LEN`)—— 说小了隐私被削弱且可能被拒 -- **RctType = ClsagBulletproofPlus** —— 说错了交易被全网拒绝 -- **手续费率上限 1,000,000 piconero/weight**(`spend::MAX_FEE_PER_WEIGHT`) - —— 没上限的话恶意节点报天价费率能让用户把余额全付成手续费 - -硬分叉时这三个都要跟着改,由我们发版控制。 - -## 与 Zcash runtime 的重复 - -只有一处:`crates/monero-runtime/build.rs`(SQLite 的 wasm 链接胶水,与链无关, -实测只差 8 行注释)。现在抽不了 —— 两条链在各自未合并的分支上,没有共同祖先 -能放共享 crate。**两条都落 main 之后第一件事就是抽它**,改一边记得同步另一边。 +## 不信节点的几个值 -`storage.rs`、`runtime.rs`、`error.rs` 的形状也高度相似但不完全相同, -等 Monero 这边稳定了再决定要不要一起抽 —— 从两个真实实现里抽, -比现在照着一个猜要靠谱。 +「节点说错了」的后果比「我们发版晚了」严重,所以这些由 runtime 写死或校验: -## 集成测试在本机沙箱里跑不了 +- **环大小 16**(`spend::RING_LEN`) +- **RctType = ClsagBulletproofPlus** —— 跟着硬分叉由我们发版控制 +- **手续费**:每档优先级各有费率上限(`spend::max_fee_per_weight`,按主网现值留 + 5 倍余量);节点给的取整单位(quantization mask)必须等于协议常量 + `spend::FEE_QUANTIZATION_MASK`(10,000)。不符就拒绝构造交易,宁可发不出去也不多付。 +- **网络**:连接节点时按创世块认出它在哪条链上,认不出就不连;钱包库与节点一起使用前 + 比对两边的网络,不一致报 `NODE_NETWORK_MISMATCH`。`chainTip` 在钱包库打开前调用, + 返回里带 `network`,宿主定 birthday 前须自行比对。 -`tests/live_node.rs` 对真实节点的那几条,在我的构建沙箱里连不上 —— 已判明是 -**沙箱不放行编译出来的测试进程的网络**,不是代码问题:同环境下 `curl` 拿得到 -200,而一个五行的裸 `reqwest` 调用同样失败。 +## 对真实节点的测试 -所以那几条**没有在真链上跑过**。你那边直接: +`tests/live_node.rs` 里联网的用例需要显式指定节点: ```bash -XMR_NODE=http://node.monerodevs.org:18089 \ - cargo test --test live_node -- --nocapture +XMR_NODE= cargo test --test live_node -- --nocapture ``` -它会打印链尖、扫描速度(块/秒)和余额三档。**扫描速度就是决定整条路线成立 -与否的那个数字** —— 单线程扫 Monero 在手机上能不能忍,到今天为止仍然没有答案。 +它会打印链尖、扫描速度(块/秒)和余额。 diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md index 0f6cb548e..391a078fa 100644 --- a/chain-runtimes/monero/README.md +++ b/chain-runtimes/monero/README.md @@ -5,7 +5,7 @@ monero-oxide 之上的钱包状态层。**它提供密码学、扫描器与交 ## 为什么是这条路 -三条路都量过(数据见 `development/research`): +三条路都量过: | | 我们要写 | 出厂体积 | 插件端 | 落盘 | |---|---|---|---|---| @@ -31,6 +31,8 @@ scan.rs 扫描循环 + 三道校验 + 落库 sync.rs 有界推进编排(拉块 → 扫描 → 记进度) query.rs 余额、历史、可花输出 spend.rs key image 导入、选币、预留、构造、签名、广播 +review.rs 签名前按用户确认的请求校验收款方、金额、手续费与找零 +pool.rs 自己广播、尚未上链的交易的存活检查 network.rs monerod 传输(浏览器 fetch / 原生 reqwest) runtime.rs 跨调用会话状态与并发防线 bindgen.rs wasm 边界 @@ -69,11 +71,8 @@ cargo check --workspace --target wasm32-unknown-unknown ## 与 Zcash runtime 的关系 -两条链各自独立的工作区,没有代码依赖。目前唯一的重复是 -`crates/monero-runtime/build.rs`(SQLite 的 wasm 链接胶水,与链无关,实测只差 -8 行注释)—— 抽不了,因为两条链还在各自未合并的分支上,没有共同祖先能放共享 -crate。**两条都落 main 之后第一件事就是抽它。** +两条链各自独立的工作区,没有代码依赖。`crates/monero-runtime/build.rs`(SQLite 的 +wasm 链接胶水,与链无关)与 Zcash 那边基本相同,改一边记得同步另一边。 -一个刻意的差异:`runtime.rs` 在这里**不加 wasm-only 门**。Zcash 那边它是 -`#[cfg(target_arch = "wasm32")]`,导致 1,377 行在原生 `cargo test` 里根本不编译 -——那是真实的覆盖漏洞,这里的并发防线因此是可测的。 +一个刻意的差异:`runtime.rs` 在这里**不加 wasm-only 门**,所以并发防线(BUSY 守卫、 +世代号)在原生 `cargo test` 里也能测。 diff --git a/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs index 2adbc56ba..365645d6c 100644 --- a/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs +++ b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs @@ -1,8 +1,8 @@ //! 对**真实节点**的集成测试。默认全部跳过。 //! //! ```bash -//! # 随便一个公共节点,或你自己的 -//! XMR_NODE=http://node.monerodevs.org:18089 cargo test --test live_node -- --nocapture +//! # 你自己的节点,或一个可信的公共节点(建议 https) +//! XMR_NODE= cargo test --test live_node -- --nocapture //! //! # 想扫自己的钱包(只需要观察密钥,不需要花费私钥) //! XMR_NODE=... \ diff --git a/chain-runtimes/monero/docs/hardware-and-offline-signing.md b/chain-runtimes/monero/docs/hardware-and-offline-signing.md index bde11c7c6..316b3b6fd 100644 --- a/chain-runtimes/monero/docs/hardware-and-offline-signing.md +++ b/chain-runtimes/monero/docs/hardware-and-offline-signing.md @@ -1,7 +1,6 @@ # Monero 硬件签名与离线签名:接缝在哪,什么已经做了 -2026-09-22。这份文档是为了让下一个人不用重做一遍调查。所有结论都注明了 -来源(上游源码行为 / 固件源码 / 实测),没有推测。 +记录于 2026-09-22。结论都注明了来源(上游源码行为 / 固件源码 / 实测)。 ## 一句话 diff --git a/chain-runtimes/monero/rust-toolchain.toml b/chain-runtimes/monero/rust-toolchain.toml index b8c2570ae..b79659373 100644 --- a/chain-runtimes/monero/rust-toolchain.toml +++ b/chain-runtimes/monero/rust-toolchain.toml @@ -1,18 +1,10 @@ # 跟当前 stable 走,不钉死版本号。 # # 这**不是** MSRV —— crate 声明的最低版本是 1.85(见 Cargo.toml 的 -# `rust-version`)。 +# `rust-version`)。若用 mise 等工具管理 Rust,请让它同样跟随 stable, +# 否则这里的声明与实际使用的工具链会不一致。 # -# 为什么不写具体版本:本机的 cargo/rustc 由 mise 接管 -# (`~/.config/mise/config.toml` 里是 `rust = latest`),`rust-toolchain.toml` -# 和 `RUSTUP_TOOLCHAIN` 在这台机器上都不生效。写死一个数字,等 mise 跟着 -# latest 往前走,这里就会变成一句和现实矛盾的声明 —— 曾经因为这种不一致 -# 白查过一小时(当时以为是代码或目录搬迁的问题,其实是工具链)。 -# -# 写 `stable` 则两边永远一致:mise 跟 latest stable,rustup 用户跟 stable。 -# -# 如果将来需要可复现的 wasm 产物(逐字节一致),再换成具体版本号, -# 并且**同时**改 mise 配置,两处必须一起动。 +# 如果将来需要可复现的 wasm 产物(逐字节一致),再换成具体版本号。 [toolchain] channel = "stable" profile = "minimal" diff --git a/chain-runtimes/monero/scripts/measure-scan.js b/chain-runtimes/monero/scripts/measure-scan.js index 3782e92a1..476a6abc0 100755 --- a/chain-runtimes/monero/scripts/measure-scan.js +++ b/chain-runtimes/monero/scripts/measure-scan.js @@ -10,7 +10,11 @@ * XMR_NODE=http://your-node:18081 node scripts/measure-scan.js */ (async () => { - await rt.setNodeUrl(process.env.XMR_NODE || 'http://node.monerodevs.org:18089'); + if (!process.env.XMR_NODE) { + console.error('Set XMR_NODE to a monerod RPC URL.'); + process.exit(1); + } + await rt.setNodeUrl(process.env.XMR_NODE); const tip = JSON.parse(await rt.chainTip()); const key = '0'.repeat(63) + '7'; const a = JSON.parse(rt.deriveAccount('mainnet', key)); diff --git a/chain-runtimes/zcash/CONTEXT.md b/chain-runtimes/zcash/CONTEXT.md index aef19c98e..06c12b14f 100644 --- a/chain-runtimes/zcash/CONTEXT.md +++ b/chain-runtimes/zcash/CONTEXT.md @@ -65,6 +65,7 @@ _Avoid_: Test seed、测试钱包助记词(两者都容易被误解为可以 另一次选币挑中同一批。 token 由**调用方持有**:先生成、先持久化、再构造,这样崩溃恢复后仍知道该释放哪一批。 +一个 token 只对应一笔交易:交易落库后,该 token 不能再用于构造新交易。 ## Capability(能力声明) @@ -94,9 +95,9 @@ _Avoid_: Ironwood 地址、最新池地址 ## Current Shielded Output Pool(当前私密输出池) -当前网络升级下,新私密输出、Shield All 目标和私密找零实际落入的池,当前为 -Ironwood。它与 Private Receive UA Policy、可花费来源池是三个不同维度;调用方不得 -各自写死池名。 +当前网络升级下,新私密输出和 Shield All 目标实际落入的池,当前为 Ironwood。 +私密找零不一定落在这里:从 Orchard 花费时,上游可能把找零留在 Orchard。它与 +Private Receive UA Policy、可花费来源池是三个不同维度;调用方不得各自写死池名。 _Avoid_: Current Receiving Pool、最新池、默认隐私池 @@ -119,8 +120,7 @@ _Avoid_: Shield、归集(单独使用时无法表达来源、目标和“全 一笔付款花哪部分资金,由发送页的来源选择决定:私密池只花该池,透明只花透明, 互不补足。 -_Avoid_: 优先使用透明资金(该账户偏好已移除,见 -[App ADR 0008](../../../app-monorepo/packages/kit-bg/src/vaults/impls/zcash/docs/adr/0008-payment-source-is-the-send-page-choice.md)) +_Avoid_: 优先使用透明资金(该账户偏好已移除,付款来源只由发送页决定) ## Transparent Mode(透明模式) diff --git a/chain-runtimes/zcash/IMPORT.md b/chain-runtimes/zcash/IMPORT.md index 514b6b750..b1c943c88 100644 --- a/chain-runtimes/zcash/IMPORT.md +++ b/chain-runtimes/zcash/IMPORT.md @@ -1,29 +1,27 @@ # Zcash source import -- Source: the local `onekey-zcash-runtime` repository. - Source revision: `c11be01b2f395b0c64321df2e2cab026008da6b5` (`feat: add zcash wallet and keys wasm runtime`). - Destination: `OneKeyHQ/app-modules`, `chain-runtimes/zcash`. - Imported files: the source repository's tracked Cargo workspace, Rust source, tests, documentation, patches, and build scripts. The runtime is OneKey's adapter over the versions of librustzcash pinned in -`Cargo.lock`, rather than a fork of the entire librustzcash repository. The -original local repository is retained. Generated packages, Cargo build caches, -browser experiments, logs, and local wallet data are not imported. +`Cargo.lock`, rather than a fork of the entire librustzcash repository. Generated +packages, Cargo build caches, browser experiments, logs, and local wallet data are +not imported. ## Vendor changes -The source checkout depended on two local vendor trees. Only one of their -patches was originally tracked. Both are now reconstructible from the upstream -crate archive checksums in `patches/manifest.json`: +Every vendored crate is reconstructed from the upstream crate archive checksum and +an exact patch listed in `patches/manifest.json`: 1. `zcash_client_sqlite 0.22.0`: disable rusqlite's `bundled` feature for WASM. Its Rust source is unchanged. -2. The import initially preserved the existing `relaxed_idb` durability barrier. - The subsequent unified Worker change replaces it with - `sqlite-wasm-vfs-0.2.0-opfs-durability.patch`: per-connection locks, durable - journal deletion, handle cleanup and fail-closed metadata I/O. All App - platforms use this same patch. The old IndexedDB patch is no longer applied. +2. `sqlite-wasm-vfs 0.2.0`: `sqlite-wasm-vfs-0.2.0-opfs-durability.patch` adds + per-connection locks, durable journal deletion, handle cleanup and fail-closed + metadata I/O for the OPFS SAH-pool. All App platforms use this same patch. +3. `tonic-web-wasm-client 0.9.1`: `tonic-web-wasm-client-0.9.1-host-fetch.patch` + lets the host supply the fetch handler used for lightwalletd requests. `scripts/vendor-deps.sh` verifies the archives, applies the exact patches, and rejects an existing vendor tree whose contents differ. No vendor source or @@ -31,30 +29,7 @@ prebuilt WASM is committed. ## Application handoff -During local development, `app-monorepo/packages/core/package.json` points its -two existing portal dependencies to this directory's `pkg` and `pkg-keys`. -Build both outputs before installing the app dependencies. Package names and -runtime interfaces are unchanged by this import. Registry publishing and a -versioned app dependency are a separate release step. - -## Source-import validation (before the OPFS change, 2026-09-08) - -- All first-party Rust source and `Cargo.lock` match the source checkout byte - for byte. Both reconstructed vendor trees match the source checkout's Rust - source and Cargo manifests, including its previously untracked VFS patch. -- Rust workspace: 52 tests passed; 9 opt-in network tests remained ignored. -- Vendor reconstruction guards: 6 tests passed (including checksum, drift, - offline, archive traversal, and archive link rejection). -- Release builds succeeded for runtime, keys, and storage benchmark. -- The app's installed runtime resolves to this directory and loads in Node; - its capability and dependency-version probes succeeded. -- The app's installed keys package passed address scheme v3 goldens and all - 5 synthetic-seed cleanup checks against the actual WASM. -- `app-monorepo` passed `yarn agent:check --profile commit`, including TypeScript - and the background API contract checks. - -The immutable app installation changed only the two portal locations. Its -repository-specific `afterInstall` hook still ran despite disabled package build -scripts and reported a `react-native-collapsible-tab-view` patch failure. That -package and patch are unchanged by this migration; the issue is not a Zcash -build failure. The GitHub workflow has been added but has not been run remotely. +During local development, the App's `packages/core/package.json` points its +portal dependencies to this directory's `pkg` and `pkg-keys`. Build both outputs +before installing the App dependencies. Registry publishing and a versioned App +dependency are a separate release step; see [RELEASING.md](./RELEASING.md). diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md index ca525274a..6cbc8d805 100644 --- a/chain-runtimes/zcash/README.md +++ b/chain-runtimes/zcash/README.md @@ -1,32 +1,24 @@ -> This project now lives in `app-modules/chain-runtimes/zcash`. See -> [IMPORT.md](./IMPORT.md) for the source revision and preserved vendor patches. > Build commands below run from this directory. Use Rust 1.93.0 (pinned in > `rust-toolchain.toml`), Python 3.11+, LLVM/Clang, and wasm-pack 0.15.0. > Install `wasm-bindgen-cli` at the `wasm-bindgen` version in `Cargo.lock` > and provide `wasm-opt` (Binaryen), or reuse the matching wasm-pack tool cache. > Builds use `--mode no-install` and never update `Cargo.lock`. -> The original standalone browser experiments were not imported; app integration -> checks remain in app-monorepo. +> See [IMPORT.md](./IMPORT.md) for the source revision and vendor patches. # OneKey Zcash Runtime 官方 `librustzcash` 之上的最薄 wasm 绑定层。**不依赖 WebZjs**。 - --- ## 这个项目为什么存在 -此前的实现建在 `ChainSafe/WebZjs` 的 fork 上,而那个仓库自 2026-04-16 起没有任何分支收到过推送。 -更要紧的是它使用 `zcash_client_memory` 作为存储后端 —— 那个 crate 从未发布到 crates.io, -2026-06-20 被从 librustzcash 切成独立仓库后只有 dependabot 在动。我们为它 vendor 了 -11,122 行代码并改动了 27 个源文件中的 22 个,且每次 `zcash_client_backend` 升版都要自己重迁一遍。 +此前的实现建在 `ChainSafe/WebZjs` 的 fork 上,使用 `zcash_client_memory` 作为存储后端。 +那个 crate 从未发布到 crates.io,维持它需要 vendor 大量代码,并在每次 +`zcash_client_backend` 升版时自行重迁。 本项目改用 `zcash_client_sqlite`:它就在 librustzcash 仓库里,与 `zcash_client_backend` -**同日发版**,是官方 Android / iOS SDK 与 ECC 自家钱包 `zallet` 的存储层 -(GitHub 上有 135 个 Cargo.toml 依赖它)。 - -换句话说:**大脑一直用的是官方的,只是存储层配了个孤儿。这个项目把它换回原厂件。** +**同日发版**,也是官方 Android / iOS SDK 与 `zallet` 的存储层。 --- @@ -40,16 +32,15 @@ WASM 产物,不是按平台维护的两套实现;Desktop、Web、扩展和 i 所有 App 载体均在 DedicatedWorker 执行公共 TypeScript SDK 和 WASM。 移动端由 WebEmbed 创建内联 Blob Worker;其他端创建 URL Worker。 Rust native 构建保留用于测试和诊断,不作为 App 的另一套生产后端。 -WASM 大小以当前构建产物及 App 压缩包检查为准,不沿用早期实验数字。 ## 硬约束 -1. **不 vendor、不 fork 任何 Zcash 存储实现。** 存储层必须来自 crates.io 上未修改的 - `zcash_client_sqlite`。唯一例外是一处 Cargo.toml 改动(下节),Rust 源码零改动。 +1. **不 fork 任何 Zcash 存储实现。** 存储层来自 crates.io 上的 `zcash_client_sqlite`, + Rust 源码零改动;唯一改动是一处 Cargo.toml feature(下节)。 2. **种子仅在授权的派生/签名调用中短暂传入 keys WASM。** Rust 清理秘密缓冲区; JS 字符串及跨桥复制不能宣称可可靠擦除。扫描器持有 UFVK,不保存种子。 -3. **接口动词少、数据简单。** 只传 string / number / boolean / JSON 字符串,不把 Rust - 对象句柄交给 JS 管生命周期。每次调用是一次完整往返。 +3. **接口动词少、数据简单。** 只传 string / number / boolean / bytes / JSON 字符串, + 不把 Rust 对象句柄交给 JS 管生命周期。每次调用是一次完整往返。 ## 边界:什么在 Rust,什么在 TS @@ -61,11 +52,11 @@ WASM 大小以当前构建产物及 App 压缩包检查为准,不沿用早期 | 密钥派生与签名 | 进度展示、错误处理、重试 | | 平台胶水(时钟、随机数、VFS) | 历史记录的展示模型 | -判据是三条:**密钥安全、跨边界数据量、共识正确性**。三条都不沾的,就该在 TS —— 那边改起来快、看得见、能打断点。 +判据是三条:**密钥安全、跨边界数据量、共识正确性**。三条都不沾的,就该在 TS。 --- -## 那一处 Cargo.toml 改动 +## Vendor 补丁 `zcash_client_sqlite` 给 `rusqlite` 开了 `bundled` feature,它会在构建期用 cc 编译 SQLite 的 C 源码。`wasm32-unknown-unknown` 没有 libc sysroot,会停在 @@ -73,9 +64,10 @@ WASM 大小以当前构建产物及 App 压缩包检查为准,不沿用早期 已启用的 feature,只能改它的 Cargo.toml。 处理方式是可审计的:`scripts/vendor-deps.sh` 下载官方发布版并施加 -`patches/zcash_client_sqlite-0.22.0-no-bundled.patch`(**1 行**)。VFS 的公共 OPFS 修复也记录在 `patches/manifest.json`:连接锁、日志删除持久化、 -句柄清理和元数据失败后停止 I/O。`scripts/prepare-vendor.py --offline` 根据校验过的 -官方归档与补丁重建并比较全部文件,拒绝未记录的 vendor 改动。 +`patches/manifest.json` 记录的补丁 —— `zcash_client_sqlite` 的 1 行 Cargo.toml 改动、 +`sqlite-wasm-vfs` 的 OPFS 持久化修复(连接锁、日志删除持久化、句柄清理和元数据失败后 +停止 I/O),以及 `tonic-web-wasm-client` 的宿主 fetch 注入。`scripts/prepare-vendor.py --offline` +根据校验过的官方归档与补丁重建并比较全部文件,拒绝未记录的 vendor 改动。 wasm 侧的 SQLite 由 `sqlite-wasm-rs` 提供(预编译,不在构建期编 C)。 `crates/zcash-runtime/build.rs` 自动把它的 `libwsqlite3.a` 按链接器要的名字接上, @@ -86,147 +78,118 @@ wasm 侧的 SQLite 由 `sqlite-wasm-rs` 提供(预编译,不在构建期编 ## 存储:数据存在哪 所有 App 端统一使用 `sqlite-wasm-vfs` 的 OPFS SAH-pool,目录为 `.onekey-zcash-opfs`。 -SQLite 按页直接读写同步访问句柄,不再把整库预载成 WASM 内存镜像。 +SQLite 按页直接读写同步访问句柄,不把整库预载成 WASM 内存镜像。 每个 origin 的池由一个 Worker 独占;第二个 Worker 不能静默改用其他数据库。 -默认预留六个文件句柄,网络数据库仍为 `zcash-main.db` / `zcash-test.db`。 +默认预留六个文件句柄,网络数据库为 `zcash-main.db` / `zcash-test.db`。 连接明确设置 `journal_mode=DELETE`、`synchronous=FULL`。提交和日志删除的 flush 错误必须传回宿主;元数据 I/O 失败后该 VFS 停止服务,需要重建 Worker。 不要求 SharedArrayBuffer、COOP/COEP 或 UI 线程上的同步文件访问。 OPFS 仍受浏览器 origin、配额和清理策略约束;App 内嵌页面的来源必须稳定。 -本次处于开发阶段,不提供旧 IndexedDB 库迁移。运行时的新交易持久化要求仍然保留。 - -## 先前版本的验证记录(不替代当前 OPFS 验收) - -以下是历史实验记录,含旧 IndexedDB 后端描述,不是当前发布验收清单。 -当前存储实现见上方 OPFS 章节;每个候选版本须按 RELEASING.md 验证实际产物。 - -> 状态:**runtime 的看账与发送链路已在 testnet 上真实上链验证,App 适配层已接入并通过 -> 类型、单元与浏览器 runtime 检查。** App 内的有资金发送闭环与主网真实交易仍需人工验收。 - -**已验证** - -- [x] `zcash_client_sqlite` 0.22.0 编进 wasm32 并链接(唯一改动是 1 行 Cargo.toml) -- [x] IndexedDB VFS,**完整 schema 迁移:44 表 / 17 视图 / 84 索引**,重载后仍在 -- [x] 三个 target 编译通过:`wasm32-unknown-unknown` / `aarch64-apple-ios` / macOS 原生 -- [x] 单测 27 个全过(另有 9 个联网用例,默认 ignore) -- [x] 浏览器错误契约 10 项断言:每个错误都带 `code` + `params` 对象 -- [x] 真实 testnet 端到端:`chainTip` → 4291075、`importAccountUfvk` -- [x] `syncStep` 有界返回(原 `syncAdvance` 会跑到同步完成才返回,已修,见 docs/D5) -- [x] 浏览器实测批量 10 / 25 / 60 / 100 / 200 / 500 全部正常(持久化 IndexedDB VFS): - 扫描阶段 12–70ms,总耗时由两次网络往返主导;batch 500 一次追平 203 块 -- [x] 清缓存→重建闭环(`examples/web/purge-rebuild.html`):擦后是全新库(账户为空、 - uuid 变化),用 ufvk+birthday 能完整重建。这条是「出问题能救回来」的保障 -- [x] 发送路径的**错误契约** 9 项(不需要资金即可跑,`examples/web/send-errors.html`): - txid 非法/不存在、找零池参数错、PCZT 垃圾字节、电路版本错、 - reservation 非法/不存在各有可判定错误码 -- [x] **付款来源由宿主指定**:私密付款只花宿主选定的那个私密池,不再混用透明 - 资金;透明付款由 keys runtime 无状态构造。`pcztQuote` 与 `pcztCreate` - 走同一条提案路径,报价即实付手续费。余额不够时抛 `INSUFFICIENT_FUNDS`, - 带 `shortfallZat` -- [x] **端到端发送并广播上链**(testnet):水龙头 0.1 TAZ 落 Ironwood 池 → - `pcztCreate` → `pcztProve`(Halo2 约 19s)→ `pcztSign` → 提交并广播, - 链上确认(当时是 `pcztSend` + `broadcastTransaction` 两步,现合并为 `pcztSubmit`)。逐笔手续费对账到 zatoshi -- [x] **透明 ↔ 屏蔽双向**:隐私→透明地址、透明→隐私(当时走 `pcztShield`,含**透明 - 输入签名**;该 API 已移除,屏蔽改由 keys runtime 无状态构造)、 - 透明→透明,全部链上确认 -- [x] **多账户共库**:acct0/1/2 同一个库,扫一遍服务全部账户 - -**未验证 —— 别把这些当成能用** - -- [ ] **App UI 内的有资金闭环尚未执行。** runtime + `examples/web` 已真实跑过 testnet - 双向发送;App 适配层已通过类型检查及 Token/History/发送状态相关单测,但这不能替代 - Desktop、Extension MV3、iOS、Android 四端的 UI 验收 -- [ ] **交易记录里的 `feeZat` 重扫后为 null。** 它来自 `transactions.fee`, - 只有钱包自己构造那笔时写入,或跑 transaction enhancement 时补上 —— - 运行时没有 enhancement。用户清一次缓存重扫,历史里的手续费会全部消失 -- [ ] 主网从未测过,全部实测都在 testnet -- [ ] 失去批量试解密的代价只在很空的 testnet 区块上量过(1.4–2 倍)。 - 主网稠密区块上差距可能大得多,未测。 -- [x] 以 Yarn portal 包接入 monorepo;正式发布仍需固定可追溯的 runtime 版本 -- [ ] 从现有 wasm blob 迁移存量用户数据 -- [ ] 原生目标的 lightwalletd transport(网络层目前只有浏览器 gRPC-web) - -**已知约束** - -- lightwalletd 端点**必须支持 gRPC-web + CORS**。实测 - `zcash-{mainnet,testnet}.chainsafe.dev` 可用;`zec.rocks` 只开原生 gRPC, - 浏览器里挂死在第一次请求上(`grpcurl` 反而通 —— 两者说的不是同一个协议, - 用命令行探活会得出相反的结论)。 + +## 已知约束 + +- lightwalletd 端点**必须支持 gRPC-web + CORS**。`zcash-{mainnet,testnet}.chainsafe.dev` + 可用;只开原生 gRPC 的端点在浏览器里会挂在第一次请求上(`grpcurl` 能通不代表 + gRPC-web 能通)。端点由宿主注入,runtime 不硬编码。 - **扫描不走上游的 `scan_cached_blocks`**,改用自己的 `scan_blocks_inline`。 上游把试解密交给 `rayon::spawn_fifo`,而 wasm32 单线程环境下 rayon 没有工作线程, - 任务永远不会执行,随后取结果时**永久堵死主线程**。根因与取证过程见 - `docs/decisions.md` D8。代价是失去批量试解密的摊销优化(原生实测扫描阶段慢 1.4–2 倍)。 - `batchSize` 没有上限约束;用 `syncPeek()` 的 `remainingBlocks` 画进度条。 -- `syncPrepare()` 要下载三个池的全部子树根 —— 实测 testnet 约 1.4 秒 - (6 sapling / 3 orchard / 0 ironwood 子树),并不慢。宿主仍应给它独立的 - 「准备中」状态,因为主网子树数量会大得多。 -- `relaxed-idb` 在插件 offscreen 与移动 WebView 里的表现尚未实测(浏览器页面已证)。 -- 产物:runtime 6.53 MB / keys 1.99 MB(均已过 `wasm-opt -Oz`)。PCZT 证明电路约占 1.6–2.0 MB。 + 任务永远不会执行,随后取结果时永久堵死主线程。见 `docs/decisions.md` D8。 + 代价是失去批量试解密的摊销优化。用 `syncPeek()` 的 `remainingBlocks` 画进度条。 +- `syncPrepare()` 要下载各池的全部子树根。宿主应给它独立的「准备中」状态, + 主网子树数量比 testnet 多得多。 +- Sapling 不在产品范围内:不作为收款 receiver、扫描身份或发送来源。 ## API -全部通过 JSON 字符串交互。失败抛 `Error`,其上挂 **`code`(稳定错误码)+ `params` +全部通过 JSON 字符串或字节交互。失败抛 `Error`,其上挂 **`code`(稳定错误码)+ `params` (结构化参数)+ `detail`(仅日志)**。Rust 侧不产出任何面向用户的文案 —— -文案与 i18n 归宿主。 +文案与 i18n 归宿主。`capabilities()` / `keysCapabilities()` 报告当前构建实际支持的能力。 -### `onekey-zcash-runtime`(Desktop / Web / 插件) +### `onekey-zcash-runtime` ``` init() 安装存储层,幂等,必须先调 -openWallet(network, dbName) 开库 + schema 迁移 -closeWallet() +setRequestHandler(handler) 宿主提供 lightwalletd 请求的 fetch +openWallet(network, dbName) / closeWallet() setLightwalletdUrl(baseUrl) 端点由宿主注入,不硬编码 +chainTip() / chainTipAt(baseUrl) -chainTip() 当前链尖高度 -importAccountUfvk(name, ufvk, birthday) 导入只读账户 → UUID -listAccounts() +importAccountUfvk(name, ufvk, birthday, seedFingerprintHex?, accountIndex?) + 导入账户 → UUID;服务器返回的树状态必须 + 正好是 birthday 前一块 +removeAccount(uuid) / removeDeletedAccount(uuid) +accountByUfvk(ufvk) / listAccounts() / accountSyncStatus(uuid) accountBalance(uuid, trusted, untrusted, allowZeroConfShielding) -syncPrepare() 一次性准备(子树根+链尖),慢,单独计时 +syncPrepare() / syncTip() / syncPeek() 准备(子树根 + 链尖)与只读进度 syncStep(batchSize, maxBatches, priority, activeUfvksJson) 仅为宿主显式启用的 UFVK 有界推进 queueRescanFrom(fromHeight) 非破坏性重排 [fromHeight, chainTip] rewindTo(height) 回退重扫(破坏性) transactionHistory(uuid, limit, offset) 分页历史,limit 上限 500 -transactionDetails(uuid, txid) 单笔详情,查不到返回 "null" -deleteWallet(dbName) 擦掉本地缓存库(可重建),最后一个账户移除/App 重置用 +transactionDetails(uuid, txid) / transactionOutputs(uuid, txid) +deleteWallet(dbName) 擦掉本地缓存库(可重建) +storageStats() pcztQuote(...) 只报价,不建交易、不锁 note pcztCreate(...) → { pcztHex, reservationId } 构造并锁住选中的 note releaseReservation(id) 用户取消时放开锁,幂等 -pcztProve(pczt, circuitVersion) → keys.pcztSign → pcztSubmit(uuid, pczt, reservationId) - 先广播;节点明确拒收则不落库、note 放回,否则落库 +clearLockedOutputs(uuid) 显式修复:清掉该账户全部锁(有未决广播时拒绝) +pcztProve(pczt) 生成证明 +pcztCombine(original, signed) 合并外部签名器回传的副本(只许补签名) +pcztSubmit(uuid, pczt, reservationId) 终结、落库、广播,返回 {txid, broadcast} +pendingBroadcastTxids(uuid) / broadcastRetryTxids(uuid) broadcastTransaction(txid) 重播已落库的交易(同步循环用) -selfCheck(network, dbName) / dependencyVersions() + +prewarmPczt(network, height) 预建证明参数,不开钱包 +pcztProveAtHeight(height, pczt) 无钱包证明(透明资金付给 UA 的路径) +pcztExtractStateless(pczt) 无钱包校验并提取最终交易 +dependencyVersions() / diag* 诊断 ``` -### `onekey-zcash-keys`(iOS / Android,也可与上面同用) +### `onekey-zcash-keys` ``` -ufvkFromSeed(network, seedBytes, accountIndex) ← 接进 app 的实际入口 -ufvkFromMnemonic(network, mnemonic, accountIndex) 测试/独立验证用 -unifiedAddress(network, ufvk) -pcztSignWithSeed(network, seedBytes, accountIndex, pcztBytes) ← 唯一接触花费密钥处 -pcztSign(network, mnemonic, accountIndex, pcztBytes) -keysDependencyVersions() +ufvkFromSeed(network, seedBytes, accountIndex) +unifiedAddress(network, ufvk, receiverPolicy) + "all" = Orchard + 透明;"shielded" / "orchard" + = 仅 Orchard。不含 Sapling receiver +transparentAddressFromUfvk(network, ufvk) / transparentAccountPubKeyFromUfvk(network, ufvk) +validateAddress(network, address) / seedFingerprint(seed) +pcztVerifyReview(pczt, reviewJson) 只校验,不签名 +pcztSignWithSeed(network, seed, accountIndex, pczt, reviewJson) + 唯一接触花费密钥处;先按 review 校验每个 + spend 与 output,不符即拒绝 +transparentTx* / transparentShield* 无状态透明交易,见 TRANSPARENT_TX_API.md +parseTransparentTransactions(requestJson) +keysCapabilities() / keysDependencyVersions() ``` ### 发送的完整流程 ``` -runtime.pcztCreate() 构造(要钱包 DB:选币、witness、anchor) -runtime.pcztProve() 零知识证明(慢,要建 halo2 电路) -keys.pcztSign() 签名(要种子;在另一个包里) -runtime.pcztSubmit() 终结 + 广播;未被拒才写回本地钱包,返回 {txid, broadcast} +runtime.pcztCreate() 构造(要钱包 DB:选币、witness、anchor),锁住 note +runtime.pcztProve() 零知识证明(慢,要建 halo2 电路) +keys.pcztSignWithSeed() 按 review 校验后签名(要种子;在另一个包里) +runtime.pcztSubmit() 与原件合并校验 → 提取 → 落库 → 广播 ``` **顺序不能换**:证明必须在签名之前 —— 上游 Signer 需要能验证证明覆盖的是正确数据。 -先广播后落库:节点明确拒收(含首次提交时的「输入已花」)返回 `rejected`, -什么都不记、note 立即放回;网络不确定返回 `unknown`,照样落库,由同步循环重播原字节。 -`already known` / `already in mempool` / `already in blockchain` 视为幂等成功;所有触网调用 -都有 30 秒上限,避免 gRPC-web 静默挂起。 + +**先落库后广播**:签好的交易字节与 reservation→txid 关联在广播前原子落库,之后的每次 +重试和崩溃恢复都广播同一份字节。广播结局: + +- `accepted`:节点接受。`already known` / `already in mempool` / `already in blockchain` + 视为幂等成功。 +- `rejected`:只有明确表示交易在共识上无效或已过期的回复才算拒收。交易仍保留在库中, + 它选中的 note 要到交易过期高度之后才会重新可用。 +- `unknown`:其余任何错误(超时、临时错误、无法判定的回复)。交易保持待确认, + 由同步循环重播原字节;宿主不得把它当作失败、引导用户重发。 + +同一个 `reservationId` 已有落库交易时,`pcztCreate` 拒绝再用它构造新交易; +`pcztSubmit` 对它只会重播已落库的那一笔。所有触网调用都有 30 秒上限。 --- @@ -249,8 +212,8 @@ cargo test --workspace --locked bash scripts/vendor-deps.sh --offline ``` -产物 `pkg/`、`pkg-keys/` 不入库。两者一起构建,供 app-monorepo 的本地 -portal 依赖或 CI artifact 使用。独立 npm 发布流程、版本规则与 App 切换步骤见 +产物 `pkg/`、`pkg-keys/` 不入库。两者一起构建,供 App 的本地 portal 依赖或 CI +artifact 使用。独立 npm 发布流程、版本规则与 App 切换步骤见 [RELEASING.md](./RELEASING.md)。 --- @@ -258,32 +221,33 @@ portal 依赖或 CI artifact 使用。独立 npm 发布流程、版本规则与 ## 目录 ``` -crates/zcash-runtime/ 绑定层本体 - src/clock.rs 宿主时钟(std 在 wasm32 上没有时间源) - src/error.rs 稳定错误码 + JS Error 映射 - src/storage.rs VFS 安装与连接打开 - src/wallet.rs WalletDb 组装与 schema 迁移 - src/bindgen.rs 面向 JS 的接口 - build.rs 自动接上 wasm 版 SQLite 静态库 -patches/ 固定上游校验值、Cargo feature 与 VFS 持久化补丁 -scripts/vendor-deps.sh 校验官方发布版并施加已记录的 patch -scripts/build-wasm.sh 构建 +crates/zcash-runtime/ 钱包、扫描、PCZT 构造/证明/提交 + src/bindgen.rs 面向 JS 的接口 + src/send.rs 提案、reservation、PCZT 生命周期 + src/tx_state.rs reservation→txid 关联与广播结局 + src/guard.rs 破坏性操作的持久化闸门 + src/sync.rs 有界扫描 + src/storage.rs VFS 安装、连接打开与落盘屏障 + build.rs 自动接上 wasm 版 SQLite 静态库 +crates/zcash-keys-runtime/ 派生、review 校验与签名、无状态透明交易 +crates/zcash-storage-benchmark/ 开发者合成数据测试 +patches/ 固定上游校验值与补丁 +scripts/vendor-deps.sh 校验官方发布版并施加已记录的 patch +scripts/build-wasm.sh 构建 ``` --- ## 参考实现(读,不依赖) -- `ChainSafe/WebZjs` —— grpc-web 接线、wasm 线程池初始化的踩坑经验。 - 注意它的 `tonic-web-wasm-client` 必须 ≥ 0.9.1(0.8.0 会丢 gRPC trailer)。 -- `zcash/zcash-android-wallet-sdk` 的 `backend-lib/` —— ECC 自己写的 Rust FFI 层, - 生产在跑。核心 `lib.rs` 4,076 行是「该暴露什么、按什么粒度」的权威参照 - (其余约 18,000 行是该 SDK 自己的历史 migration、投票、slipstream,我们不需要)。 - +- `ChainSafe/WebZjs` —— grpc-web 接线、wasm 线程池初始化的经验。 + 注意 `tonic-web-wasm-client` 必须 ≥ 0.9.1(0.8.0 会丢 gRPC trailer)。 +- `zcash/zcash-android-wallet-sdk` 的 `backend-lib/` —— ECC 的 Rust FFI 层, + 是「该暴露什么、按什么粒度」的参照。 ### Stateless transparent funding of Unified recipients -`transparentTxQuote` accepts mainnet t1/t3 recipients and Unified recipients with an +`transparentTxQuote` accepts mainnet t1/t3/tex recipients and Unified recipients with an Orchard receiver (an Ironwood output after NU6.3). It uses only the host-supplied confirmed, regular transparent UTXOs, explicit outpoints, target height, and transparent change address. Sapling/Sprout destinations and coinbase inputs remain @@ -309,5 +273,5 @@ pending broadcast records, and submission to its node. The recipient's wallet scans to discover and later spend the received shielded notes; the sender does not need to scan. Private inputs still use the existing stateful wallet/PCZT APIs. -The app's existing hardware Shield flow is separate; these new signing exports -are for software seed/account-xprv keyrings. +The App's hardware Shield flow is separate; these signing exports are for software +seed/account-xprv keyrings. diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md index 965b7535e..895224cee 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md @@ -56,11 +56,13 @@ Inputs must be confirmed, non-coinbase P2PKH coins controlled by their declared BIP-44 path. Recipients may be mainnet P2PKH (`t1`), P2SH (`t3`), a ZIP-320 TEX address (`tex1`, paid as P2PKH), or a Unified Address with an Orchard receiver, which is paid an Ironwood note; a Unified Address without one is rejected rather -than paid at a public receiver. Change must be an owned P2PKH address on internal scope `1`. +than paid at a public receiver. Change must be an owned P2PKH address on internal scope `1` with an address index below 40. For send-max, supply exactly one recipient and omit `amountZat` and `change`. The recipient receives -the selected input total minus the ZIP-317 fee. For a fixed amount, change below the standard 5,000 -zatoshi marginal fee is rejected instead of silently adding it to the fee. +the selected input total minus the ZIP-317 fee. For a fixed amount, a surplus too small to fund a +change output (below the 5,000 zatoshi marginal fee, or not enough to pay for the extra output) is +added to the fee and shown in the quote; the overpayment stays below about 0.0001 ZEC. +Any larger surplus requires a `change` entry. The target height must be on the mainnet NU6.3 branch. `expiryHeight` is mandatory and is supplied by the host's transaction policy. The crate validates that it is after the target height and no more diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md index a9adfbb63..9dae2c065 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md @@ -1,8 +1,7 @@ # Previous transaction fixtures -Public Zcash transactions fetched on 2026-09-20 through OneKey's test-environment -`POST /wallet/v1/network/raw-transaction/list` endpoint (`networkId: zec--0`). -The fixture records the raw transactions; their mined heights are listed below: +Public Zcash mainnet transactions, recorded on 2026-09-20. The fixture stores the +raw transactions; their mined heights are listed below: - `69ff03c1e3d19df98087396f86783addbc9f8ad615022efdeb5de10fe78597ae`: V4, height 3490000, output 0 is 100000000 zatoshi. - `70177881b2a62c93ed023725a24166362a5bd65cc93dbbd3b3a243ff5927d89c`: V6, height 3476066, output 0 is 1000 zatoshi. diff --git a/chain-runtimes/zcash/docs/decisions.md b/chain-runtimes/zcash/docs/decisions.md index 538237b2e..791214950 100644 --- a/chain-runtimes/zcash/docs/decisions.md +++ b/chain-runtimes/zcash/docs/decisions.md @@ -13,8 +13,8 @@ | | `zcash_client_memory` | `zcash_client_sqlite` | |---|---|---| | 发布到 crates.io | 从未 | 是,63 个正式版 | -| 所在仓库 | 2026-06-20 被切成独立仓库后停更 | 就在 librustzcash 里 | -| 近期活动 | 只有 dependabot | 与 `zcash_client_backend` 同日发版 | +| 所在仓库 | 已移出 librustzcash 主仓库 | 就在 librustzcash 里 | +| 发版节奏 | 独立 | 与 `zcash_client_backend` 同日发版 | | 生产使用 | 无 | 官方 Android/iOS SDK、zallet,135 个 Cargo.toml 依赖 | | 我们的改动量 | vendor 11,122 行,27 个文件改了 22 个 | 1 行 Cargo.toml | @@ -33,16 +33,16 @@ --- -## D2 — 浏览器存储用 IndexedDB VFS,不自己写 VFS(暂时) +## D2 — 浏览器存储:OPFS SAH-pool(取代早期的 IndexedDB VFS) -**决定**:先用 `sqlite-wasm-vfs` 现成的 `relaxed_idb`,不自己实现 VFS。 +**决定**:所有 App 端使用 `sqlite-wasm-vfs` 的 OPFS SAH-pool,并施加 +`patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch`(连接锁、日志删除持久化、句柄清理、 +元数据失败后停止 I/O)。早期使用的 `relaxed_idb`(IndexedDB)已不再使用。 -**依据**:VFS 只有五个方法(read/write/truncate/flush/size),自己写是可行的, -但现成实现已经处理了同步/异步这个真正困难的部分。先跑通、看清真实读写模式, -再决定要不要换成自己的实现(届时只是替换那五个方法,不影响上层)。 +**依据**:VFS 只有少数几个方法,现成实现已经处理了同步/异步这个真正困难的部分; +持久化语义上的缺口用可审计的补丁补上,而不是自己重写一个 VFS。 -**留给未来的口子**:需要加密、接 OneKey 自己的存储层、或移动端桥到原生存储时, -自己实现 VFS 是直接的路径。 +**留给未来的口子**:需要加密、或移动端桥到原生存储时,自己实现 VFS 是直接的路径。 --- @@ -90,11 +90,6 @@ rusqlite 调用(`execute` 335、`query_row` 205、`prepare` 139+84、params (即 `rand_core` 0.6 那条线)。用 0.9 会因为 `RngCore` trait 不是同一个而 无法满足 `init_wallet_db` 的泛型约束,报错信息不直观。 -**headless Chrome 的 `--virtual-time-budget` 配 `--dump-dom` 会卡死** -(虚拟时间与 IndexedDB 的异步 IO 冲突),且 Chrome 拿到结果后不会自行退出。 -`scripts/browser-check.py` 的做法是让页面把结果 fetch 回传给本地 server, -轮询到结果就主动结束进程。 - --- ## 运行期发现(2026-08-22 实测) @@ -121,21 +116,13 @@ rusqlite 调用(`execute` 335、`query_row` 205、`prepare` 139+84、params 因此本 runtime **不硬编码任何端点**,由宿主通过 `setLightwalletdUrl()` 注入; 换端点时必须先验证 gRPC-web 支持。 -### 首次同步不是一次快调用 - -`syncAdvance` 第一次调用要先 `update_subtree_roots`(下载全部子树根),实测在 testnet 上 -超过 15 分钟仍未返回。这不是错误路径,但有两个直接后果: - -1. **宿主必须给进度反馈**,不能把它当成一个普通的 await。 -2. `batch_size` 控制的是单批扫描量,**控制不了前置的 subtree roots 下载**。 - -如果这个耗时不可接受,方向是让 `sync::run` 的前置步骤可分段、可中断 —— 那需要不走 -`sync::run` 而自己驱动 `scan_cached_blocks`,属于后续工作,不要在没有实测数据前就动手。 - --- ## D3 — 移动端原生:分叉面有多大(实测) +> 已被取代:移动端改为在 WebEmbed Worker 中运行同一份 WASM(见 README), +> 不维护原生绑定。以下保留当时的测算,供将来重新评估。 + 担心「维护多套代码」是合理的,所以先量。当前 `crates/zcash-runtime/src` 的构成: | | 行数 | 说明 | @@ -187,21 +174,19 @@ Kotlin 与 Swift,把「JNI + Swift 两套」压成一套。注意 `equilibrium 构造 PCZT 需要钱包数据库(选币、witness、anchor),所以「构造 + 证明」包必须 自带完整的存储栈。那就意味着两个 wasm 模块各自持有一个 SQLite 实例, -同时读写同一份 IndexedDB —— 而我们用的 `relaxed-idb` VFS 明确标注 -**Multiple connections: ❌**。并发写同一个库会损坏数据。 +同时读写同一份数据库 —— 而存储池只允许单连接独占。并发写同一个库会损坏数据。 省 1.6 MB 不值得换来数据损坏风险。 -**替代的省体积方向**(未做,按性价比排序): +**替代的省体积方向**: -1. `wasm-opt -Oz`(wasm-pack 默认只跑 `-O`) -2. 证明改为可选加载:把 `pcztProve` 单独编成一个**不含数据库**的模块 —— - 它只吃 PCZT 字节、吐 PCZT 字节,不碰存储,因此没有多连接问题。 - 这条路可行,是真要省体积时的正解。 -3. 检查是否有未使用的 feature 还在拉代码 +1. `wasm-opt -Oz`(已采用)。 +2. 不含数据库的证明入口:`pcztProveAtHeight` 只吃 PCZT 字节、吐 PCZT 字节, + 不碰存储,因此没有多连接问题(已提供,供无钱包路径使用)。 +3. 检查是否有未使用的 feature 还在拉代码。 注意方案 2 与被否掉的方案不同:分界线在**是否需要数据库**, -不在「是不是 PCZT 相关」。`pcztCreate` 必须和钱包同包,`pcztProve` 不必。 +不在「是不是 PCZT 相关」。`pcztCreate` 必须和钱包同包,证明不必。 --- @@ -285,53 +270,28 @@ wasm 里挂死的调用**宿主无法取消** —— 没有线程可以中断, --- -## D7 — 「10 个区块能扫、25 个挂死」的排查记录 - -值得完整记下来,因为过程里我判断错了三次,每次都靠实测纠正。 +## D7 — 「小批量能扫、大批量挂死」:区块缓存的可重入死锁 ### 症状 -`syncStep(10, 1)` 591ms 正常返回;`syncStep(25, 1)` 永久不返回, -**页面完全无响应,没有任何错误信息,连 30 秒超时都不触发**。 - -超时不触发这一点本身就是关键线索:说明阻塞发生在**同步代码**里, -JS 事件循环被占住,定时器根本没机会开火。如果是 await 的网络调用挂住,超时会正常生效。 - -### 三次错误判断 - -1. **「卡在下载子树根」** —— 错。`syncPrepare` 实测 1.3–1.4 秒 - (testnet 6 sapling / 3 orchard / 0 ironwood 子树)。 -2. **「treestate 高度低于 Sapling 激活导致 gRPC 挂起」**(我们自己代码库记过这个坑) - —— 也错,因为 birthday 在链尖附近。**但这个钳位保留了**,它是真实陷阱。 -3. **「批量大就是慢」** —— 错。10 通过、25 挂死这种悬崖不是量级问题。 +`syncStep(10, 1)` 正常返回;`syncStep(25, 1)` 永久不返回,页面无响应、无错误, +**连 30 秒超时都不触发**。超时不触发说明阻塞发生在**同步代码**里 —— JS 事件循环被占住, +定时器没机会开火;如果是 await 的网络调用挂住,超时会正常生效。 -### 定位手段 - -- `syncPeek()` —— 只读待扫区间、不发网络。**0ms** 返回 - `{start, end, len: 201, priority: "ChainTip"}`,一下排除「区间异常巨大」。 -- `syncProbeDownload(n)` —— 只下载不扫描。**100 个区块下载仅 303ms**, - 网络这一半彻底洗清,问题锁定在 `scan_cached_blocks`。 -- 干净库跑 25 同样挂 —— 排除「累积状态」。 - -### 真正的原因:我自己写的缓存里有可重入死锁 - -`MemoryBlockCache::with_blocks` 原本在**整个遍历期间持有 `Mutex`**, -并在持锁状态下调用 `with_block` 回调 —— 而那个回调会写钱包库, -上游有可能在那条路径上再次读取本缓存。 +### 根因 -`std::sync::Mutex` 不可重入。wasm 是单线程,同一线程二次加锁 = **永久死锁**, -表现正是「页面卡死、无错误、定时器不响」。批量小时不触发那条二次读取路径, -所以 10 能过、25 挂死。 +`MemoryBlockCache::with_blocks` 原本在**整个遍历期间持有 `Mutex`**,并在持锁状态下调用 +回调 —— 而回调会写钱包库,上游可能在那条路径上再次读取本缓存。`std::sync::Mutex` +不可重入,wasm 单线程下同一线程二次加锁就是永久死锁。 **修法**:持锁时只把区块 `clone` 收集出来,**释放锁之后**才执行回调。 ### 教训 - 在持锁状态下调用外部回调,等于把锁的作用域交给了不受控的代码。 - 单线程环境下这不是「可能有竞争」,是「一定死锁」。 -- 「小批量能跑、大批量挂死」不要当成性能问题处理。真的性能问题是渐变的; - 陡峭悬崖几乎总是状态机或锁的问题。 -- 超时不触发是强信号,说明阻塞在同步代码里 —— 这个信息比超时本身更有价值。 +- 「小批量能跑、大批量挂死」这种陡峭悬崖几乎总是状态机或锁的问题,不是性能问题。 +- 排查工具:`syncPeek()`(只读待扫区间,不发网络)和 `syncProbeDownload(n)` + (只下载不扫描)能快速把问题切分到网络或扫描一侧。 --- @@ -350,11 +310,8 @@ batch=100 耗时 517ms blocksScanned=100 remainingBlocks=101 结论:**症结在 wasm 侧**。 -> ⚠️ 当时据此推断「嫌疑在 `relaxed-idb` 存储层」,**这个推断是错的** —— -> 换成内存 VFS 照样卡。而且这一节说「上游 `scan_cached_blocks` 没有问题」 -> 也不准确:它在 wasm 上确实有问题,只是原生跑不出来。 -> 真正的根因见 D8。这一节保留,是因为「原生对照」这个方法本身是对的, -> 只是当时的对照实验没控住变量(两端连的服务器不同、覆盖的高度区间也不同)。 +> 注:真正的根因见 D8。这里保留「原生对照」这个方法;对照时两端必须连同一个服务器、 +> 覆盖同一段高度,否则结论无效。 ### 顺带的收获 @@ -441,28 +398,11 @@ rayon 全局线程池没有任何工作线程 —— 任务被排进队列后永 扫描本身很便宜,耗时基本全在两次网络往返上。宿主要提速应该减少往返次数, 而不是调批量。 -### 排查过程里更值得记住的教训 - -**测量工具本身骗了我好几轮。** 页面用 `fetch` 往测试服务器回传日志, -于是「被测代码卡住」和「回传通道自己死了」在日志上完全一样 —— 都是 -「日志停在某一行」。据此得出过两个错误结论: - -1. 「batchSize ≥ 25 永久挂死」—— 写进了 README 当作阻塞发版的问题,实际是假的; -2. 「区块 4292846 有毒」—— 停止位置其实是被 tracing 自身拖慢造成的假象。 - -修法是把证据通道和被测对象彻底解耦:`scripts/cdp_console.py` 直接从 -Chrome DevTools 协议读 console,不经过页面网络。换上它之后, -第一轮就拿到了真实的停止位置。 - -顺带修掉的两个工具缺陷: +### 教训 -- `browser-check.py` 原来用串行 `TCPServer`,页面同时发上报和拉资源时会互相排队; - 已换成 `ThreadingHTTPServer`。 -- 判定「通过」只看「行数够且没有 FAIL」,页面卡在最后一步时照样报通过 —— - 真发生过。现在必须收到页面自己发的终止标记。 +**对照实验要控住所有变量。** 早期「原生正常」的结论一度无效:两端连的服务器不同, +原生跑的高度区间也没覆盖到出问题的区块。`network::block_summary`(返回编码长度 + +校验和)用来确认两端拿到的字节完全一致。 -**另一条:对照实验要控住所有变量。** 早期「原生正常」的结论其实无效 —— -原生连的是 `testnet.zec.rocks`、浏览器连的是 `zcash-testnet.chainsafe.dev`, -服务器都不是同一个;而且原生跑的高度区间根本没覆盖到出问题的区块。 -后来加了 `network::block_summary`(返回编码长度 + 校验和), -确认两端拿到的字节完全一致,对照才真正成立。 +**证据通道要与被测对象解耦。** 页面自己回传日志时,「被测代码卡住」和「回传通道自己死了」 +在日志上完全一样;从 DevTools 协议直接读 console 才能拿到真实的停止位置。 From a8041632b3e1d3af80b7da769b977c1a970ff320 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 17:16:46 +0800 Subject: [PATCH 17/97] test(monero): follow connect returning the node network in live tests --- .../monero/crates/monero-runtime/tests/live_node.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs index 365645d6c..e9b68a867 100644 --- a/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs +++ b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs @@ -41,7 +41,7 @@ fn connects_and_reads_the_chain_tip() { }; block_on(async { - let daemon = network::connect(&url).await.expect("连接节点"); + let (daemon, _) = network::connect(&url).await.expect("连接节点"); let tip = sync::chain_tip(&daemon).await.expect("取链尖"); println!("链尖 = {tip}"); assert!(tip > 3_000_000, "主网高度早就过 300 万了,{tip} 不合理"); @@ -65,7 +65,7 @@ fn scans_real_blocks_without_false_alarms() { }; block_on(async { - let daemon = network::connect(&url).await.expect("连接节点"); + let (daemon, _) = network::connect(&url).await.expect("连接节点"); let tip = sync::chain_tip(&daemon).await.expect("取链尖"); // 从链尖往回 200 块开始扫 40 块:足够覆盖有交易的块,又不至于太慢。 @@ -124,7 +124,7 @@ fn scans_a_real_wallet_if_view_keys_are_supplied() { let view = hex::decode(view_hex.trim()).expect("XMR_VIEW_PRIV 必须是 hex"); block_on(async { - let daemon = network::connect(&url).await.expect("连接节点"); + let (daemon, _) = network::connect(&url).await.expect("连接节点"); let tip = sync::chain_tip(&daemon).await.expect("取链尖"); let mut db = @@ -186,7 +186,7 @@ fn rewind_actually_rolls_back_and_requeues() { }; block_on(async { - let daemon = network::connect(&url).await.expect("连接节点"); + let (daemon, _) = network::connect(&url).await.expect("连接节点"); let tip = sync::chain_tip(&daemon).await.expect("取链尖"); let start = tip.saturating_sub(50); From 0b03e667b45218420bbc28fde0cfec099fc80850 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 17:32:17 +0800 Subject: [PATCH 18/97] chore: translate chain runtime comments to English Comments, test messages, log-only error details, script output and package descriptions are now concise English. Code is unchanged apart from dropping an unused `mut` in a test; misplaced doc comments are moved back onto their items and a stale fragment on NETWORK_ERROR is removed. Unicode test fixtures keep their non-ASCII text. --- chain-runtimes/monero/.cargo/config.toml | 9 +- chain-runtimes/monero/Cargo.toml | 31 +- .../monero/crates/monero-runtime/Cargo.toml | 16 +- .../monero/crates/monero-runtime/build.rs | 41 +- .../crates/monero-runtime/src/bindgen.rs | 156 ++++---- .../crates/monero-runtime/src/blocks_bin.rs | 180 +++++---- .../monero/crates/monero-runtime/src/error.rs | 99 ++--- .../monero/crates/monero-runtime/src/keys.rs | 128 +++--- .../monero/crates/monero-runtime/src/lib.rs | 21 +- .../crates/monero-runtime/src/network.rs | 208 +++++----- .../monero/crates/monero-runtime/src/perf.rs | 8 +- .../monero/crates/monero-runtime/src/pool.rs | 38 +- .../monero/crates/monero-runtime/src/query.rs | 129 +++--- .../crates/monero-runtime/src/runtime.rs | 119 +++--- .../monero/crates/monero-runtime/src/scan.rs | 311 ++++++++------- .../crates/monero-runtime/src/schema.rs | 244 ++++++------ .../monero/crates/monero-runtime/src/spend.rs | 364 ++++++++--------- .../crates/monero-runtime/src/storage.rs | 108 +++-- .../monero/crates/monero-runtime/src/sync.rs | 217 ++++++----- .../crates/monero-runtime/src/wallet.rs | 95 ++--- .../crates/monero-runtime/tests/live_node.rs | 165 ++++---- chain-runtimes/monero/rust-toolchain.toml | 9 +- .../monero/scripts/build-node-pkg.sh | 4 +- chain-runtimes/monero/scripts/build-wasm.sh | 27 +- chain-runtimes/monero/scripts/smoke.js | 88 ++--- chain-runtimes/zcash/.cargo/config.toml | 4 +- chain-runtimes/zcash/Cargo.toml | 48 ++- .../crates/zcash-keys-runtime/Cargo.toml | 27 +- .../crates/zcash-keys-runtime/src/bindgen.rs | 37 +- .../crates/zcash-keys-runtime/src/error.rs | 38 +- .../crates/zcash-keys-runtime/src/keys.rs | 178 ++++----- .../crates/zcash-keys-runtime/src/lib.rs | 22 +- .../crates/zcash-keys-runtime/src/sign.rs | 61 ++- .../src/transparent_send.rs | 41 +- .../src/transparent_send/shielding.rs | 28 +- .../zcash/crates/zcash-runtime/Cargo.toml | 33 +- .../zcash/crates/zcash-runtime/build.rs | 38 +- .../zcash/crates/zcash-runtime/src/account.rs | 71 ++-- .../zcash/crates/zcash-runtime/src/bindgen.rs | 368 +++++++++--------- .../crates/zcash-runtime/src/blockcache.rs | 70 ++-- .../zcash/crates/zcash-runtime/src/clock.rs | 18 +- .../zcash/crates/zcash-runtime/src/error.rs | 169 ++++---- .../zcash/crates/zcash-runtime/src/guard.rs | 58 ++- .../zcash/crates/zcash-runtime/src/history.rs | 100 ++--- .../zcash/crates/zcash-runtime/src/lib.rs | 38 +- .../zcash/crates/zcash-runtime/src/network.rs | 100 +++-- .../zcash/crates/zcash-runtime/src/perf.rs | 6 +- .../zcash/crates/zcash-runtime/src/runtime.rs | 126 +++--- .../zcash/crates/zcash-runtime/src/send.rs | 270 +++++++------ .../zcash/crates/zcash-runtime/src/stats.rs | 67 ++-- .../zcash/crates/zcash-runtime/src/sync.rs | 236 +++++------ .../zcash/crates/zcash-runtime/src/wallet.rs | 50 ++- .../crates/zcash-runtime/tests/scan_repro.rs | 185 +++++---- chain-runtimes/zcash/scripts/build-wasm.sh | 47 ++- 54 files changed, 2589 insertions(+), 2760 deletions(-) diff --git a/chain-runtimes/monero/.cargo/config.toml b/chain-runtimes/monero/.cargo/config.toml index 4e7902890..07d9ba901 100644 --- a/chain-runtimes/monero/.cargo/config.toml +++ b/chain-runtimes/monero/.cargo/config.toml @@ -1,8 +1,5 @@ -# macOS 上 /usr/bin/ar 读不懂 wasm 目标文件:38 个编译好的 .o 会被**静默**打成 -# 一个 96 字节的空归档,链接期表现为一串 `undefined symbol: sqlite3_*`, -# 而编译阶段不报任何错。 -# -# 排查提示:本机 clang 是能编 wasm32 的(别往编译器上查),坏的是归档器。 -# cc crate 读 AR_ 形式的环境变量。 +# macOS /usr/bin/ar cannot read wasm object files and silently writes an empty +# archive, which surfaces at link time as `undefined symbol: sqlite3_*`. +# Use LLVM's ar; the cc crate reads AR_. [env] AR_wasm32_unknown_unknown = "/opt/homebrew/opt/llvm/bin/llvm-ar" diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml index bc328d989..524cd9a81 100644 --- a/chain-runtimes/monero/Cargo.toml +++ b/chain-runtimes/monero/Cargo.toml @@ -8,29 +8,28 @@ edition = "2021" license = "Apache-2.0" rust-version = "1.85" -# ── monero-oxide:独立 Rust 实现,MIT,no_std ──────────────────────────── +# ── monero-oxide: independent Rust implementation, MIT, no_std ─────────── # -# 选它而不是 wallet2 的理由见 development/research。要点:四端统一 wasm、 -# 产物约 226 KB、不需要跨源隔离、不需要 C++ 交叉编译链。 +# Chosen over wallet2 (see development/research): one wasm build for all +# platforms, ~226 KB output, no cross-origin isolation, no C++ cross toolchain. # -# 代价是它**不提供任何存储层**:`Scanner` 是纯函数(register_subaddress + -# scan(block) -> outputs),钱包状态全部由我们自己落 SQLite。这个工作区存在 -# 的意义就是那一层。 +# It has no storage layer: `Scanner` is pure (register_subaddress + +# scan(block) -> outputs). This workspace persists wallet state to SQLite. [workspace.dependencies] monero-wallet = { version = "0.2", default-features = false, features = ["std"] } monero-address = { version = "0.1", default-features = false, features = ["std"] } monero-daemon-rpc = { version = "0.2", default-features = false, features = ["std"] } monero-interface = { version = "0.2", default-features = false, features = ["std"] } -# get_blocks.bin 的请求与解析(blocks_bin.rs)。与 monero-daemon-rpc 用同一个。 +# get_blocks.bin request and parsing (blocks_bin.rs); same version as monero-daemon-rpc uses. monero-epee = { version = "0.2", default-features = false } -# SQLite on wasm:与 Zcash runtime 同一套组合。rusqlite 不开 "bundled" -# (那会在构建期编译 SQLite 的 C 源码,而 wasm32 没有 libc sysroot), -# 改由 sqlite-wasm-rs 提供 sqlite3 符号。 +# SQLite on wasm, same setup as the Zcash runtime. rusqlite without "bundled" +# (wasm32 has no libc sysroot for SQLite's C sources); sqlite-wasm-rs provides +# the sqlite3 symbols. rusqlite = { version = "0.37", default-features = false } sqlite-wasm-rs = "0.5" -# OPFS 同步访问 VFS。Zcash runtime 那边 vendor 了一份带落盘屏障补丁的, -# 这里先用发布版;等两条链都落 main,VFS 与 build.rs 一起抽成共享件。 +# OPFS sync-access VFS. The Zcash runtime vendors a copy patched with a +# durability barrier; this uses the released crate. sqlite-wasm-vfs = "0.2" serde = { version = "1", features = ["derive"] } @@ -38,7 +37,7 @@ serde_json = "1" thiserror = "2" hex = "0.4" rand_core = { version = "0.6", features = ["getrandom"] } -# 必须与 monero-oxide 用的同一大版本,否则 Scalar/Point 类型对不上。 +# Must match monero-oxide's major version so Scalar/Point types line up. curve25519-dalek = { version = "4", default-features = false } zeroize = { version = "1", features = ["zeroize_derive"] } @@ -47,10 +46,10 @@ gloo-timers = { version = "0.3", features = ["futures"] } js-sys = "0.3" wasm-bindgen-futures = "0.4" web-sys = { version = "0.3", features = ["Request", "RequestInit", "Response", "Headers"] } -# 原生侧只用于本机诊断与集成测试,不进出厂产物 —— 用默认 feature 就好。 -# 关掉默认 feature 会让连接在传输层直接失败(实测:curl 通、它不通)。 +# Native-only (diagnostics and integration tests), not shipped. Keep default +# features: without them connections fail at the transport layer. reqwest = "0.12" futures-lite = "2" futures-util = { version = "0.3", default-features = false, features = ["alloc"] } -# 原生传输走 reqwest,它要 Tokio reactor;集成测试因此需要一个运行时。 +# reqwest needs a Tokio reactor, so native integration tests need a runtime. tokio = { version = "1", features = ["rt", "macros", "time"] } diff --git a/chain-runtimes/monero/crates/monero-runtime/Cargo.toml b/chain-runtimes/monero/crates/monero-runtime/Cargo.toml index 60f3ff553..8af5f0602 100644 --- a/chain-runtimes/monero/crates/monero-runtime/Cargo.toml +++ b/chain-runtimes/monero/crates/monero-runtime/Cargo.toml @@ -4,7 +4,7 @@ version.workspace = true edition.workspace = true license.workspace = true rust-version.workspace = true -description = "OneKey Monero Runtime — monero-oxide 之上的钱包状态层(SQLite 落盘)" +description = "OneKey Monero Runtime: wallet state over monero-oxide, persisted in SQLite" [lib] crate-type = ["cdylib", "rlib"] @@ -26,16 +26,15 @@ rand_core.workspace = true curve25519-dalek.workspace = true zeroize.workspace = true -# wasm32 专属:SQLite 的 wasm 实现与 JS 互操作。原生目标(本机调试与测试) -# 用系统 SQLite,不需要这些。 +# Native targets (local debugging and tests). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -# 原生传输:让浏览器里出的问题能在本机上真调试器复现。 +# Native transport, to reproduce browser issues under a native debugger. reqwest.workspace = true -# 原生侧的重试退避(blocks_bin::backoff)。reqwest 本就跑在 Tokio 上。 +# Native retry backoff (blocks_bin::backoff); reqwest already runs on Tokio. tokio.workspace = true [dev-dependencies] -# 集成测试要直接构造地址取公钥 +# Integration tests build addresses to extract public keys. monero-wallet.workspace = true futures-lite.workspace = true tokio.workspace = true @@ -48,7 +47,6 @@ gloo-timers.workspace = true js-sys.workspace = true wasm-bindgen-futures.workspace = true web-sys.workspace = true -# monero-oxide 整条链走 rand_core 0.6 → getrandom 0.2,而 0.2 在 -# wasm32-unknown-unknown 上必须显式打开旧式的 "js" feature 才能编译。 -# 这条依赖我们代码里一次都不直接用,纯粹是为了把 feature 打开。 +# Not used directly: enables the legacy "js" feature that getrandom 0.2 (via +# monero-oxide's rand_core 0.6) needs on wasm32-unknown-unknown. getrandom_02 = { package = "getrandom", version = "0.2", features = ["js"] } diff --git a/chain-runtimes/monero/crates/monero-runtime/build.rs b/chain-runtimes/monero/crates/monero-runtime/build.rs index 9f9321fd5..1331c740a 100644 --- a/chain-runtimes/monero/crates/monero-runtime/build.rs +++ b/chain-runtimes/monero/crates/monero-runtime/build.rs @@ -1,19 +1,11 @@ -//! 把 wasm 版 SQLite 接到链接器上。 +//! Links the wasm SQLite build. //! -//! 背景:我们用 `rusqlite` 但不开 `bundled` feature —— 那会在构建期编译 SQLite -//! 的 C 源码,而 wasm32 没有 libc sysroot。关掉之后 libsqlite3-sys 转而发出 -//! `-l sqlite3`,让链接器去找现成的库。 +//! `rusqlite` is used without `bundled` (wasm32 has no libc sysroot to compile +//! SQLite's C sources), so libsqlite3-sys emits `-l sqlite3`. On wasm32 the library +//! comes from `sqlite-wasm-rs` as `libwsqlite3.a`; this script copies it into +//! OUT_DIR as `libsqlite3.a` and adds that to the search path, so no RUSTFLAGS are needed. //! -//! **这份是 `chain-runtimes/zcash/crates/zcash-runtime/build.rs` 的副本**(实测 -//! 仅 8 行注释差异)。与链无关,本该抽成一个共享 crate —— 但两条链目前在各自 -//! 未合并的分支上,抽了没有共同祖先可放。**两条都落 main 之后第一件事就是抽它**, -//! 改这里记得同步改另一份。 -//! -//! 在 wasm32 上这份现成的库由 `sqlite-wasm-rs` 提供,但它产出的归档叫 -//! `libwsqlite3.a`(名字里有个 w)。本脚本把它按链接器要的名字复制一份到我们 -//! 自己的 OUT_DIR,并把该目录加进搜索路径。 -//! -//! 这样调用方不需要任何手工的 RUSTFLAGS —— `cargo build` 直接可用。 +//! Duplicate of `chain-runtimes/zcash/crates/zcash-runtime/build.rs`; keep them in sync. use std::path::{Path, PathBuf}; @@ -22,25 +14,25 @@ fn main() { let target = std::env::var("TARGET").unwrap_or_default(); if !target.starts_with("wasm32") { - // 原生目标用系统或 bundled 的 SQLite,无需干预。 + // Native targets use system or bundled SQLite. return; } - let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR 应由 cargo 提供")); + let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR is set by cargo")); let Some(src) = find_wasm_sqlite_archive(&out_dir) else { - // 不直接 panic:留一条可读的提示,让链接期的报错有据可查。 + // Warn instead of panicking so a later link error has context. println!( - "cargo::warning=未找到 sqlite-wasm-rs 的 libwsqlite3.a;\ - 若链接期报 `unable to find library -lsqlite3`,请确认 sqlite-wasm-rs \ - 在依赖图中且目标为 wasm32" + "cargo::warning=libwsqlite3.a from sqlite-wasm-rs not found; \ + if linking fails with `unable to find library -lsqlite3`, check that \ + sqlite-wasm-rs is in the dependency graph and the target is wasm32" ); return; }; let dst = out_dir.join("libsqlite3.a"); if let Err(e) = std::fs::copy(&src, &dst) { - println!("cargo::warning=复制 {} 失败: {e}", src.display()); + println!("cargo::warning=failed to copy {}: {e}", src.display()); return; } @@ -48,12 +40,11 @@ fn main() { println!("cargo::rerun-if-changed={}", src.display()); } -/// 从我们的 OUT_DIR 往上找到 `.../build/` 目录,再在里面定位 -/// `sqlite-wasm-rs-*/out/libwsqlite3.a`。 +/// Locate `sqlite-wasm-rs-*/out/libwsqlite3.a` under the `.../build/` directory above OUT_DIR. /// -/// 依赖的构建脚本先于依赖方运行,所以这个文件此刻必然已经存在。 +/// Dependency build scripts run first, so the archive already exists. fn find_wasm_sqlite_archive(out_dir: &Path) -> Option { - // OUT_DIR 形如 target///build/-/out + // OUT_DIR is target///build/-/out let build_root = out_dir.parent()?.parent()?; for entry in std::fs::read_dir(build_root).ok()? { let Ok(entry) = entry else { continue }; diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs index 1dc471257..54eff3a3a 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs @@ -1,17 +1,18 @@ -//! 面向宿主的 wasm 接口。 +//! Host-facing wasm interface. //! -//! ## 形状约定 +//! ## Conventions //! -//! - 返回值一律是 **JSON 字符串**,宿主 `JSON.parse` 即可。错误也是 JSON -//! (`{ code, params, detail }`),所以宿主不必区分 Error 与非 Error 两条路。 -//! - **金额一律用字符串**。piconero 的上限远超 JS 的 `Number.MAX_SAFE_INTEGER`, -//! 走数字会静默丢精度 —— 那是最坏的一类 bug,因为它不报错。 -//! - 密钥材料**只进不出**:种子与花费私钥可以传进来,绝不作为返回值出去。 +//! - Every return value is a JSON string for the host to `JSON.parse`. Errors are +//! JSON too (`{ code, params, detail }`), so the host needs no separate Error path. +//! - Amounts are always strings: piconero values exceed JS `Number.MAX_SAFE_INTEGER`, +//! and numbers would silently lose precision. +//! - Key material goes in, never out: seeds and spend keys may be passed in but are +//! never returned. //! -//! ## 调度不在这里 +//! ## No scheduling here //! -//! 什么时候扫、扫多少、失败怎么退避 —— 全归宿主。这里每个导出都是一次 -//! 完整的往返,绝不自己循环。 +//! When to scan, how much, and how to back off on failure belong to the host. Each +//! export is one complete round trip and never loops. use wasm_bindgen::prelude::*; @@ -24,20 +25,20 @@ fn json(value: serde_json::Value) -> std::result::Result { Ok(value.to_string()) } -/// 装上持久化存储。**必须在开任何库之前调用一次。** +/// Install persistent storage. Must be called once before opening any DB. #[wasm_bindgen(js_name = init)] pub async fn init() -> std::result::Result<(), JsValue> { storage::install_persistent_vfs().await?; Ok(()) } -/// 本 runtime 锁定的上游版本,供宿主自检与日志使用。 +/// Upstream versions pinned by this runtime, for host self-checks and logs. #[wasm_bindgen(js_name = dependencyVersions)] pub fn dependency_versions() -> String { crate::dependency_versions().to_string() } -/// 打开(或新建)一个钱包库。 +/// Open (or create) a wallet DB. #[wasm_bindgen(js_name = openWallet)] pub fn open_wallet(db_name: &str, network: &str) -> std::result::Result { let net = keys::parse_network(network)?; @@ -52,11 +53,11 @@ pub fn close_wallet() -> std::result::Result<(), JsValue> { Ok(()) } -/// 配置节点地址,空串表示停用。**没有内置默认值** —— 内置一个等于替用户决定 -/// 把 IP 和查询交给谁,那是隐私决策,不该藏在 runtime 里。 +/// Set the node URL; an empty string disables it. No built-in default: one would +/// decide for the user who sees their IP and queries. /// -/// 先断开旧节点再连新的:用户换掉或停用一个节点后,它不能再收到任何请求, -/// 哪怕新节点连不上 —— 那时就是没有节点。 +/// The old node is dropped before connecting the new one: a replaced or disabled +/// node must receive no further requests, even if the new one fails to connect. #[wasm_bindgen(js_name = setNodeUrl)] pub async fn set_node_url(url: &str) -> std::result::Result<(), JsValue> { runtime::clear_daemon(); @@ -69,11 +70,12 @@ pub async fn set_node_url(url: &str) -> std::result::Result<(), JsValue> { Ok(()) } -/// 问链尖。**不要求钱包库已打开** —— 建账户时要用它定 birthday, -/// 而那一刻库还没建。 +/// Fetch the chain tip. Does not require an open wallet DB: account creation needs +/// it for the birthday before the DB exists. /// -/// 返回 `{ height, network }`:`network` 是节点所在的链(按创世块认定)。 -/// 这一步还没有钱包库可比对,宿主定 birthday 前须确认它与要建的钱包一致。 +/// Returns `{ height, network }`, where `network` is the node's chain (by genesis +/// block). There is no wallet DB to compare against yet, so the host must check it +/// matches the wallet being created before setting the birthday. #[wasm_bindgen(js_name = chainTip)] pub async fn chain_tip() -> std::result::Result { let tip: u64 = runtime::with_daemon(|daemon| async move { @@ -87,10 +89,10 @@ pub async fn chain_tip() -> std::result::Result { })) } -/// 注册一个身份(观察密钥对)。 +/// Register an identity (view key pair). /// -/// `spendPublicKeyHex` 与 `viewPrivateKeyHex` 都是 32 字节的十六进制。 -/// **花费私钥不在这里** —— 它只在签名时传入,见 `signAndBroadcast`。 +/// `spendPublicKeyHex` and `viewPrivateKeyHex` are 32-byte hex. The spend private +/// key is not taken here; it is passed only for signing (see `signTransaction`). #[wasm_bindgen(js_name = addAccount)] pub fn add_account( uuid: &str, @@ -124,16 +126,17 @@ pub fn list_accounts() -> std::result::Result { json(serde_json::json!({ "items": items })) } -/// 删除一个身份连同它的全部数据。**不可逆。** +/// Delete an identity and all its data. Irreversible. #[wasm_bindgen(js_name = removeAccount)] pub fn remove_account(uuid: &str) -> std::result::Result { let removed = runtime::with_db(|db| db.remove_identity(uuid))?; json(serde_json::json!({ "removed": removed })) } -/// 删除整个钱包库文件(app 重置、存储重建)。**不可逆。** +/// Delete the whole wallet DB file (app reset, storage rebuild). Irreversible. /// -/// 不打开库:版本不认或已损坏的库也删得掉。删的是当前打开的库时先关掉它。 +/// Does not open the DB, so unsupported-version or corrupt DBs can still be deleted. +/// Closes the DB first if it is the one currently open. #[wasm_bindgen(js_name = deleteWallet)] pub async fn delete_wallet(db_name: String) -> std::result::Result { if runtime::open_db_name().as_deref() == Some(db_name.as_str()) { @@ -143,7 +146,7 @@ pub async fn delete_wallet(db_name: String) -> std::result::Result std::result::Result { runtime::with_db(|db| sync::update_chain_tip(db, account_id, tip))?; @@ -164,9 +167,9 @@ pub fn update_chain_tip(account_id: i64, tip: u64) -> std::result::Result std::result::Result { let progress = runtime::with_db_and_daemon(|mut db, daemon| async move { @@ -177,22 +180,22 @@ pub async fn sync_step(account_id: i64, max_blocks: u64) -> std::result::Result< json(progress) } -/// 只读:当前扫描进度,不发网络请求。同步卡住时用它确认到底想扫哪一段。 +/// Read-only scan progress; no network requests. Shows which ranges sync intends to scan. #[wasm_bindgen(js_name = syncPeek)] pub fn sync_peek(account_id: i64) -> std::result::Result { let v = runtime::with_db_read(|db| sync::peek(db, account_id))?; json(v) } -/// 重组恢复:回退到指定高度并把那之上的区间重新排队。**破坏性。** +/// Reorg recovery: rewind to `height` and requeue everything above it. Destructive. #[wasm_bindgen(js_name = rewindTo)] pub fn rewind_to(account_id: i64, height: u64, tip: u64) -> std::result::Result { let v = runtime::with_db(|db| sync::rewind_and_requeue(db, account_id, height, tip))?; json(v) } -/// 余额。`chainTip` 传 `null` 表示还不知道链尖 —— 此时可用余额一律按 0 报, -/// 宁可显示 0,也不要让用户去花一笔构不进环的钱。 +/// Balance. `chainTip` = `null` means the tip is unknown; spendable is then reported +/// as 0 rather than invite a spend that cannot be built. #[wasm_bindgen(js_name = balance)] pub fn balance(account_id: i64, chain_tip: Option) -> std::result::Result { let b = runtime::with_db_read(|db| query::balance(db, account_id, chain_tip))?; @@ -214,11 +217,11 @@ pub fn transaction_details( json(v) } -/// 补齐 key image,让花费检测能工作。 +/// Import key images so spend detection works. /// -/// **必须在解锁时尽早调用。** 补齐之前余额会偏高:已经被花掉的输出看起来还在, -/// 因为观察钱包在协议上无法独立判断花费。补齐只影响之后扫的块 —— 之前发生的 -/// 花费要靠回退重扫才能识别。 +/// Call as early as possible after unlock. Until then the balance is too high: a +/// view-only wallet cannot detect spends, so spent outputs still look unspent. This +/// only affects blocks scanned afterwards; earlier spends need a rewind and rescan. #[wasm_bindgen(js_name = importKeyImages)] pub fn import_key_images( account_id: i64, @@ -232,15 +235,14 @@ pub fn import_key_images( })) } -/// 从 BIP-32 派生出来的私钥造出 Monero 的观察材料与主地址。 +/// Derive Monero view material and the primary address from a BIP-32-derived private key. /// -/// **不需要开库、不需要节点** —— 纯派生。这正是「地址可以先建、扫链之后再 -/// 手动打开」那条产品路径的基础。 +/// Pure derivation: no DB, no node, so an address can exist before any scanning. /// -/// 约定与 OneKey V4 一致(`spend = sc_reduce32(key)`、`view = keccak(spend)`)。 -/// 换约定会让老用户导入同一套助记词后看到空钱包。 +/// Matches OneKey V4 (`spend = sc_reduce32(key)`, `view = keccak(spend)`). Changing +/// it would show existing users an empty wallet after importing the same mnemonic. /// -/// **不返回花费私钥** —— 它就是调用方传进来的那个,没必要再跨一次边界。 +/// Does not return the spend private key; the caller already has it. #[wasm_bindgen(js_name = deriveAccount)] pub fn derive_account( network: &str, @@ -256,7 +258,7 @@ pub fn derive_account( })) } -/// 从 BIP-32 私钥算出签名用的花费标量。与 `deriveAccount` 同一个约简。 +/// Spend scalar for signing, from a BIP-32 private key. Same reduction as `deriveAccount`. #[wasm_bindgen(js_name = spendScalar)] pub fn spend_scalar(bip32_private_key_hex: &str) -> std::result::Result { let raw = Zeroizing::new(decode_hex(bip32_private_key_hex, "bip32PrivateKeyHex")?); @@ -264,7 +266,7 @@ pub fn spend_scalar(bip32_private_key_hex: &str) -> std::result::Result std::result::Result { let net = keys::parse_network(network)?; @@ -298,29 +300,28 @@ pub fn mark_reservation_signed( json(serde_json::json!({ "marked": n })) } -/// 释放一次预留(用户取消,或构造失败)。 +/// Release a reservation (user cancelled or construction failed). #[wasm_bindgen(js_name = releaseReservation)] pub fn release_reservation(reservation_id: &str) -> std::result::Result { let n = runtime::with_db(|db| spend::release(db, reservation_id))?; json(serde_json::json!({ "released": n })) } -/// 把网络请求交给宿主去发,而不是在 wasm 里 `fetch`。 +/// Hand network requests to the host instead of `fetch`ing in wasm. /// -/// `handler` 形如 `(url, contentType, body: Uint8Array) => Promise`。 -/// 传 `undefined` 卸载。 +/// `handler` is `(url, contentType, body: Uint8Array) => Promise`; +/// `undefined` uninstalls it. /// -/// wasm 里的 fetch 受浏览器的混合内容与 CORS 管,而 monerod 默认不发 CORS 头 -/// —— 2026-09-22 实测 12 家公共节点只有 1 家可用。把请求交回宿主,插件的 -/// background、桌面主进程、移动端原生都不受那两条规则管,于是全网节点可用。 -/// -/// 和性能无关:纯扫描只占总耗时 0.4%,受限的是可达性不是速度。 +/// In-wasm fetch is bound by browser mixed-content and CORS rules, and monerod sends +/// no CORS headers by default, so few public nodes are reachable. The extension +/// background, desktop main process and mobile native code are not bound by those +/// rules, so any node is reachable through them. #[wasm_bindgen(js_name = setRequestHandler)] pub fn set_request_handler(handler: Option) { crate::network::set_host_handler(handler); } -/// 诊断:库是否健在、各表行数、逻辑大小。**不发网络请求。** +/// Diagnostics: DB health, per-table row counts, logical size. No network requests. #[wasm_bindgen(js_name = diagDatabase)] pub fn diag_database() -> std::result::Result { let v = runtime::with_db_read(|db| { @@ -371,21 +372,22 @@ fn decode_hex(value: &str, field: &str) -> Result> { }) } -// ── 花费路径 ──────────────────────────────────────────────────────────── +// ── Spend path ───────────────────────────────────────────────────────────── -/// 选币、构造、预留。**不需要花费私钥,不广播。** +/// Select inputs, build and reserve. Needs no spend private key; does not broadcast. /// -/// `recipientsJson` 形如 `[{ "address": "...", "amountAtomic": "1000000000000" }]`。 +/// `recipientsJson` is `[{ "address": "...", "amountAtomic": "1000000000000" }]`. /// -/// `maxSend` 为真时只接受一个收款方,金额由「当前可花总额 − 手续费」反算, -/// 传入的金额被忽略 —— 不能靠「不给找零」实现,那样余数会全部并进手续费。 +/// With `maxSend`, exactly one recipient is accepted and its amount is computed as +/// spendable total minus fee; the passed amount is ignored. Merely omitting change +/// would fold the remainder into the fee. /// -/// 返回 `{ reservationId, signableHex, feeAtomic, amountAtomic, changeAtomic, -/// inputsAtomic, inputCount }`。`feeAtomic` 和 `amountAtomic` 是这笔交易真正 -/// 会用的数:确认页显示它们,签名时不会再变。 +/// Returns `{ reservationId, signableHex, feeAtomic, amountAtomic, changeAtomic, +/// inputsAtomic, inputCount }`. `feeAtomic` and `amountAtomic` are what the +/// transaction will use: the confirmation page shows them and signing keeps them. /// -/// 失败不会留下预留。成功后必须走 `signTransaction` + `broadcastTransaction`, -/// 或者显式 `releaseReservation` —— 否则那些输出会一直锁着。 +/// Failure leaves no reservation. On success the host must call `signTransaction` + +/// `broadcastTransaction`, or `releaseReservation`; otherwise the inputs stay locked. #[wasm_bindgen(js_name = prepareTransaction)] pub async fn prepare_transaction( account_id: i64, @@ -437,11 +439,11 @@ pub async fn prepare_transaction( json(v) } -/// 签名一笔已构造的交易。**不碰网络、不碰数据库、不广播。** +/// Sign a prepared transaction. No network, no DB, no broadcast. /// -/// `spendPrivateKeyHex` 用完即擦,绝不落库、绝不返回。 -/// 返回 `{ txid, rawHex, sizeBytes }` —— txid 在签名这一刻就定下来了, -/// 宿主据此在广播之前就能建立待确认记录。 +/// `spendPrivateKeyHex` is wiped after use, never stored or returned. +/// Returns `{ txid, rawHex, sizeBytes }`; the txid is fixed at signing, so the host +/// can record the pending transaction before broadcasting. #[wasm_bindgen(js_name = signTransaction)] pub fn sign_transaction( signable_hex: &str, @@ -463,10 +465,11 @@ pub fn verify_transaction( Ok(()) } -/// 广播一笔已签名的交易。**不可逆。** +/// Broadcast a signed transaction. Irreversible. /// -/// 节点接受或结果不确定(网络错误)都记账:被花的输出标记掉,交易进在途, -/// 返回 `broadcast: accepted | unknown`。只有节点明确拒收才报错并放回输入。 +/// Accepted and uncertain (network error) outcomes are both recorded: spent outputs +/// are marked, the transaction goes in flight, and `broadcast: accepted | unknown` is +/// returned. Only an explicit node rejection errors and releases the inputs. #[wasm_bindgen(js_name = broadcastTransaction)] pub async fn broadcast_transaction( account_id: i64, @@ -478,7 +481,8 @@ pub async fn broadcast_transaction( ) -> std::result::Result { let raw = raw_hex.to_owned(); let reservation = reservation_id.to_owned(); - // 十进制串:u64 过不了宿主桥。只用于显示与余额,格式不对就当没给。 + // Decimal strings: u64 cannot cross the host bridge. Used only for display and + // balance; malformed values count as absent. let amounts = spend::SentAmounts { outgoing_atomic: outgoing_atomic.and_then(|a| a.parse::().ok()), change_atomic: change_atomic.and_then(|a| a.parse::().ok()), diff --git a/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs b/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs index bac1e5f12..5cfb26d37 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs @@ -1,28 +1,32 @@ -//! 批量取块:`get_blocks.bin`,按 wallet2 的信任模型。 +//! Batch block fetch via `get_blocks.bin`, using wallet2's trust model. //! -//! 一次请求拿回一整批块,连同块里的交易和扫描要用的输出索引 —— 逐块取要 -//! 3~4 次往返一块,这里是一次往返几十上百块。 +//! One request returns a whole batch of blocks with their transactions and the +//! output indices scanning needs, instead of 3-4 round trips per block. //! -//! ## 为什么不直接用 monero-oxide 自带的那条 +//! ## Why not monero-oxide's built-in path //! -//! 它也走 `get_blocks.bin`,但坚持**用交易内容反算哈希、再与区块头的交易哈希 -//! 清单比对**。剪枝交易要反算哈希得有节点给的 `prunable_hash`,而已发布的 -//! monerod(截至 v0.18.5.1)把它发成全零(monero-project/monero#10120,修复 -//! #10652 只在 master)。于是它每次都整批放弃,退回逐块 JSON。 +//! It also uses `get_blocks.bin` but recomputes transaction hashes from content and +//! checks them against the block header's hash list. Pruned transactions need the +//! node's `prunable_hash` for that, and released monerod (through v0.18.5.1) sends +//! it as all zeros (monero-project/monero#10120; fix #10652 is master-only), so it +//! always drops the batch and falls back to per-block JSON. //! -//! ## 这里的信任模型(与 wallet2、Cake、Feather 相同) +//! ## Trust model (same as wallet2, Cake, Feather) //! -//! 直接采用区块头里的交易哈希清单,不以交易内容反算去验证。代价:恶意节点 -//! 可以在真实哈希下塞假的交易内容,让余额显示失真(虚报或藏掉一笔到账); -//! 偷不走钱 —— 花费要私钥,拿假输出去花会被网络拒绝。wallet2 见 -//! `wallet2::process_new_blockchain_entry`,它用的就是 `b.tx_hashes[idx]`。 +//! The header's transaction hash list is trusted; content is not re-hashed against +//! it. Cost: a malicious node can serve fake transaction content under real hashes +//! and distort the displayed balance (inflate or hide an incoming payment). It +//! cannot steal funds: spending needs the private key, and the network rejects +//! spends of fake outputs. See `wallet2::process_new_blockchain_entry`, which uses +//! `b.tx_hashes[idx]`. //! -//! 仍然做的检查:交易数与区块头清单一致、每块的输出索引条数与交易输出数一致、 -//! 块高从请求起点连续。块与块之间的衔接(前驱哈希、RingCT 游标)照旧由 -//! `scan::scan_blocks` 校验。 +//! Still checked: transaction count matches the header list, each block's output +//! index lists match its transaction outputs, and heights are contiguous from the +//! requested start. Cross-block continuity (previous hash, RingCT cursor) is +//! checked by `scan::scan_blocks`. //! -//! 请求格式与解析骨架取自 monero-oxide 的 `monero-daemon-rpc` -//! (`src/bin_rpc/blocks_bin.rs`、`epee.rs`,MIT)。 +//! Request format and parser skeleton follow monero-oxide's `monero-daemon-rpc` +//! (`src/bin_rpc/blocks_bin.rs`, `epee.rs`, MIT). use std::{ cell::{Cell, RefCell}, @@ -42,13 +46,13 @@ use monero_wallet::{ use crate::network::{Transport, MAX_RESPONSE_BYTES}; use crate::perf::now_ms; -/// 批量路径的失败分两种,处理方式截然不同。 +/// Batch-path failures, handled differently. #[derive(Debug)] pub enum BlocksBinError { - /// 网络问题:这一步失败,下一轮重试。不能据此判定节点不支持。 + /// Network failure: this step fails and the next retries. Not evidence the node lacks support. Network(String), - /// 节点回的东西不对(不支持、格式不符、数量对不上):对这个节点不再走 - /// 批量路径,退回逐块。 + /// Bad node response (unsupported, malformed, count mismatch): stop using the batch + /// path for this node and fetch per block. Protocol(String), } @@ -60,30 +64,30 @@ fn epee_err(e: EpeeError) -> BlocksBinError { protocol(format!("epee: {e:?}")) } -// ── 批量大小:自适应,上限与 wallet2 相同 ───────────────────────────────── +// ── Batch size: adaptive, capped as in wallet2 ───────────────────────────── // -// wallet2 每次 `getblocks.bin` 不设上限,节点最多回 1000 块 / 2 万笔交易。在好 -// 网络上那是最快的;在翻墙、抖动的网络上一个十几 MB 的请求可能迟迟走不完。 -// 所以大小随实测调整:快就翻倍,一路涨到 1000;慢或失败就减半,最低 10 块。 -// 一步只发一个请求、拿到就扫、就落库 —— 块是一个请求一个请求地"滴"进来的, -// 前面拿到的不会因为后面的慢而作废。 +// wallet2 sends `getblocks.bin` uncapped; the node returns at most 1000 blocks / +// 20k transactions. That is fastest on a good link, but a multi-MB request may never +// finish on a tunneled or jittery one. So the size adapts: double when fast, up to +// 1000; halve when slow or failed, down to 10. Each step sends one request and scans +// and stores what it gets, so a slow later request never discards earlier blocks. -/// 与 wallet2 / monerod 的单次上限一致(`COMMAND_RPC_GET_BLOCKS_FAST_MAX_BLOCK_COUNT`)。 +/// Per-request cap of wallet2 / monerod (`COMMAND_RPC_GET_BLOCKS_FAST_MAX_BLOCK_COUNT`). pub const MAX_BATCH_BLOCKS: u64 = 1000; -/// 再慢的网络也至少这么多一批,否则往返开销压过数据本身。 +/// Floor even on slow links; below it round-trip overhead dominates. pub const MIN_BATCH_BLOCKS: u64 = 10; -/// 起步大小:不知道网络如何时,一个请求十秒内能走完的量级。 +/// Starting size on an unknown link: roughly what one request delivers within ten seconds. pub const INITIAL_BATCH_BLOCKS: u64 = 100; -/// 比这快就加倍。 +/// Double when faster than this. const GROW_BELOW_MS: f64 = 8_000.0; -/// 比这慢就减半。 +/// Halve when slower than this. const SHRINK_ABOVE_MS: f64 = 25_000.0; thread_local! { static BATCH_BLOCKS: Cell = const { Cell::new(INITIAL_BATCH_BLOCKS) }; } -/// 下一个请求要多少块。 +/// Block count for the next request. pub fn batch_blocks() -> u64 { BATCH_BLOCKS.with(Cell::get) } @@ -103,19 +107,18 @@ fn record_failure() { BATCH_BLOCKS.with(|size| size.set((size.get() / 2).max(MIN_BATCH_BLOCKS))); } -// ── 请求与流水线 ───────────────────────────────────────────────────────── +// ── Requests and pipelining ──────────────────────────────────────────────── // -// 一次只发一个请求,与 wallet2 相同。插件实测(2026-09-23,cakewallet 节点): -// 三路并发时每一步都是阶梯状 —— 第一个请求 1~4 s 回来,另外两个要 17~38 s: -// 节点在排队(monerod 生成 `get_blocks.bin` 要占区块链数据库的锁,公共节点也 -// 可能按 IP 限并发)。提速靠流水线(`prefetch`):扫这一批的同时,下一批已经 -// 在路上。 +// One request at a time, as in wallet2. Concurrent requests to a public node are +// served one after another (monerod holds the blockchain DB lock while building +// `get_blocks.bin`, and nodes may limit per-IP concurrency). The speedup comes from +// pipelining (`prefetch`): the next batch is in flight while this one is scanned. -/// 一个请求的结果,以及它从发出到完成用了多久(预取的从预取那一刻算起)。 +/// A request's result and its duration from send to completion (from send time for a prefetch). type RequestOutcome = (Result, BlocksBinError>, f64); type RequestFuture = Pin>>; -/// 已经发出、结果还没被取走的下一个请求。 +/// The next request, already sent, whose result has not been taken. struct Prefetch { url: String, start: u64, @@ -130,7 +133,7 @@ thread_local! { fn request_future(url: &str, start: u64, count: u64) -> RequestFuture { let url = url.to_owned(); Box::pin(async move { - // 第一次被 poll 时请求才真正发出,计时也从这里开始。 + // The request is sent, and timing starts, on first poll. let started = now_ms(); let transport = Transport::new(&url); let result = request_once(&transport, start, count).await; @@ -138,8 +141,8 @@ fn request_future(url: &str, start: u64, count: u64) -> RequestFuture { }) } -/// 取走与这一段完全吻合的预取结果。不吻合(换了节点、回退重扫、区间变了) -/// 就丢掉 —— 宁可重发,也不能拿错一段数据。 +/// Take the prefetched result only if it matches this span exactly. Otherwise (node +/// changed, rewind, range changed) drop it: refetching beats using the wrong data. fn take_prefetched(url: &str, start: u64, count: u64) -> Option { PREFETCH.with(|slot| match slot.borrow_mut().take() { Some(p) if p.url == url && p.start == start && p.count == count => Some(p.future), @@ -147,14 +150,15 @@ fn take_prefetched(url: &str, start: u64, count: u64) -> Option { }) } -/// 取回的块,以及它们是否来自上一步的预取。 +/// Fetched blocks, and whether they came from the previous step's prefetch. pub struct Fetched { pub blocks: Vec, pub prefetch_hit: bool, } -/// 网络失败时的重试退避(毫秒),长度即额外重试次数。每次重试把请求减半 —— -/// 一个在当前网络上走不完的大请求,拆小了往往就能走完。协议错误不重试。 +/// Backoff (ms) before retrying a network failure; the length is the number of extra +/// retries. Each retry halves the request, since a smaller one often completes where a +/// large one cannot. Protocol errors are not retried. const RETRY_BACKOFF_MS: [u32; 2] = [500, 1500]; async fn backoff(ms: u32) { @@ -164,11 +168,12 @@ async fn backoff(ms: u32) { tokio::time::sleep(std::time::Duration::from_millis(u64::from(ms))).await; } -/// 从 `start` 起取至多 `limit` 块,按高度排好。`start` 必须非零 —— monerod -/// 只在 `start_height` 非零时才认这个字段。 +/// Fetch up to `limit` blocks from `start`, ordered by height. `start` must be +/// nonzero: monerod ignores `start_height` when it is zero. /// -/// 只发**一个**请求(失败时以更小的请求重试),节点给多少就收多少:它可能因为 -/// 2 万笔交易的上限少给,剩下的由下一步接着要。 +/// Sends one request (retried smaller on failure) and accepts however many blocks +/// the node returns; it may return fewer due to the 20k-transaction cap, and the +/// next step requests the rest. pub async fn fetch(base_url: &str, start: u64, limit: u64) -> Result { if start == 0 { return Err(protocol("get_blocks.bin cannot start at the genesis block")); @@ -208,12 +213,14 @@ pub async fn fetch(base_url: &str, start: u64, limit: u64) -> Result Box::pin(futures_util::future::ready(outcome)), None => future, @@ -243,7 +250,8 @@ pub async fn prefetch(base_url: &str, start: u64, limit: u64) { }); } -/// 一个请求。节点多给(早于 0.18.4.3 不认 `max_block_count`)就截掉,少给就照收。 +/// One request. Extra blocks (nodes before 0.18.4.3 ignore `max_block_count`) are +/// truncated; fewer are accepted. async fn request_once( transport: &Transport, start: u64, @@ -274,7 +282,7 @@ fn build_request(start_height: u64, max_block_count: u64) -> Vec { let mut request = Vec::with_capacity(64); request.extend(HEADER); request.push(VERSION); - // 三个字段。epee 的 varint 低两位是长度标记,00 表示一字节。 + // Three fields. The low two bits of an epee varint mark its length; 00 means one byte. request.push(3 << 2); push_key(&mut request, "prune"); @@ -285,7 +293,7 @@ fn build_request(start_height: u64, max_block_count: u64) -> Vec { request.push(Type::Uint64 as u8); request.extend(start_height.to_le_bytes()); - // 0.18.4.3 起才有;更老的节点忽略它,由 `fetch` 截断。 + // Added in 0.18.4.3; older nodes ignore it and `fetch` truncates. push_key(&mut request, "max_block_count"); request.push(Type::Uint64 as u8); request.extend(max_block_count.to_le_bytes()); @@ -293,7 +301,7 @@ fn build_request(start_height: u64, max_block_count: u64) -> Vec { request } -/// 一块:区块本身、剪枝后的非矿工交易、以及每笔交易(矿工交易在前)的输出索引。 +/// One block: the block and its pruned non-miner transactions. struct RawBlock { block: Block, transactions: Vec>, @@ -322,7 +330,7 @@ fn read_block<'e>(entry: EpeeEntry<'e, '_, &'e [u8]>) -> Result::read(&mut encoding) @@ -347,7 +355,7 @@ fn read_block<'e>(entry: EpeeEntry<'e, '_, &'e [u8]>) -> Result transaction (miner first) -> global index of each output. fn read_output_indices<'e>( entry: EpeeEntry<'e, '_, &'e [u8]>, ) -> Result>>, BlocksBinError> { @@ -434,7 +442,7 @@ pub(crate) fn parse_response( "expected block {expected}, node sent {height}" ))); } - // 与区块头的交易哈希清单对数 —— 我们信任的正是那份清单。 + // Check against the header's transaction hash list, which is what we trust. if raw.transactions.len() != raw.block.transactions.len() { return Err(protocol(format!( "block {height}: header lists {} transactions, node sent {}", @@ -450,7 +458,8 @@ pub(crate) fn parse_response( ))); } - // 本块第一个 RingCT 输出的全局索引:第一笔非 V1 且有输出的交易的首个索引。 + // Global index of this block's first RingCT output: the first index of the first + // non-V1 transaction with outputs. let miner = raw.block.miner_transaction(); let mut first_ringct = None; let shapes = std::iter::once(( @@ -488,7 +497,7 @@ pub(crate) fn parse_response( mod tests { use super::*; - /// 请求字节必须与 monero-oxide 发出的逐字一致:它是经过节点验证的格式。 + /// Request bytes must match monero-oxide's byte for byte; nodes are known to accept that layout. #[test] fn the_request_matches_the_upstream_layout() { let request = build_request(3_000_000, 50); @@ -502,7 +511,7 @@ mod tests { assert!(request.ends_with(&50u64.to_le_bytes())); } - /// 快就加倍到 1000 封顶,慢或失败就减半到 10 保底。 + /// Doubles up to 1000 when fast; halves down to 10 when slow or failed. #[test] fn the_batch_grows_on_fast_requests_and_shrinks_on_slow_or_failed_ones() { BATCH_BLOCKS.with(|b| b.set(INITIAL_BATCH_BLOCKS)); @@ -511,7 +520,7 @@ mod tests { } assert_eq!(batch_blocks(), MAX_BATCH_BLOCKS); record_success(15_000.0); - assert_eq!(batch_blocks(), MAX_BATCH_BLOCKS, "中速不动"); + assert_eq!(batch_blocks(), MAX_BATCH_BLOCKS, "steady at medium speed"); record_success(40_000.0); assert_eq!(batch_blocks(), MAX_BATCH_BLOCKS / 2); for _ in 0..20 { @@ -521,7 +530,7 @@ mod tests { BATCH_BLOCKS.with(|b| b.set(INITIAL_BATCH_BLOCKS)); } - /// 预取只在完全吻合时被取走;不吻合的一律丢弃,槽位同时被清空。 + /// A prefetch is taken only by an exact match; a mismatch discards it and clears the slot. #[test] fn a_prefetch_is_taken_only_by_the_exact_same_request() { let park = |url: &str, start: u64, count: u64| { @@ -538,20 +547,20 @@ mod tests { assert!(take_prefetched("https://a", 100, 20).is_some()); assert!( take_prefetched("https://a", 100, 20).is_none(), - "取走即清空" + "taking clears the slot" ); park("https://a", 100, 20); - assert!(take_prefetched("https://b", 100, 20).is_none(), "换了节点"); + assert!(take_prefetched("https://b", 100, 20).is_none(), "new node"); park("https://a", 100, 20); assert!( take_prefetched("https://a", 101, 20).is_none(), - "起点变了(回退、部分前缀)" + "different start (rewind, partial prefix)" ); park("https://a", 100, 20); assert!( take_prefetched("https://a", 100, 7).is_none(), - "区间长度变了" + "different count" ); } @@ -563,13 +572,13 @@ mod tests { assert!(matches!(e, BlocksBinError::Protocol(_))); } - /// 真实节点的真实响应(xmr-node.cakewallet.com,2026-09-23, - /// start_height=3768621、max_block_count=2),经桌面主进程抓取。 - /// 验证的是整条解析:区块、剪枝交易、输出索引、首个 RingCT 索引。 + /// A real node response (xmr-node.cakewallet.com, 2026-09-23, start_height=3768621, + /// max_block_count=2), captured via the desktop main process. Covers the full parse: + /// blocks, pruned transactions, output indices, first RingCT index. #[test] fn parses_a_real_node_response() { let bytes = include_bytes!("../tests/fixtures/get_blocks_bin_3768621.bin"); - let blocks = parse_response(bytes, 3_768_621).expect("解析真实响应"); + let blocks = parse_response(bytes, 3_768_621).expect("parse real response"); eprintln!( "node returned {} blocks: {:?}", blocks.len(), @@ -586,14 +595,14 @@ mod tests { for (i, b) in blocks.iter().enumerate() { assert_eq!(b.block.number() as u64, 3_768_621 + i as u64); assert_eq!(b.transactions.len(), b.block.transactions.len()); - // 每块至少有矿工交易的输出,所以一定有首个 RingCT 索引。 + // Every block has miner outputs, so a first RingCT index always exists. assert!(b.output_index_for_first_ringct_output.is_some()); } - // 前驱哈希首尾相接:确认块真的是连续的一段。 + // Previous hashes chain: the blocks really are contiguous. for pair in blocks.windows(2) { assert_eq!(pair[1].block.header.previous, pair[0].block.hash()); } - // RingCT 游标首尾相接:下一块的首个索引 = 这一块首个索引 + 这一块的输出总数。 + // RingCT cursor chains: next first index = this first index + this block's output count. for pair in blocks.windows(2) { let outputs: u64 = std::iter::once(pair[0].block.miner_transaction().prefix().outputs.len()) @@ -614,7 +623,8 @@ mod tests { } } - /// 扫描耗时基准(原生,release 下更准)。夹具太大不入库,按需抓: + /// Scan cost benchmark (native; release is more accurate). The fixture is too large + /// to commit; capture it on demand: /// `XMR_BLOCKS_BIN=/path/to/get_blocks.bin XMR_BLOCKS_BIN_START=3767000 \ /// cargo test --release --lib scan_cost -- --nocapture` #[test] @@ -623,20 +633,20 @@ mod tests { std::env::var("XMR_BLOCKS_BIN"), std::env::var("XMR_BLOCKS_BIN_START"), ) else { - eprintln!("跳过:未设置 XMR_BLOCKS_BIN / XMR_BLOCKS_BIN_START"); + eprintln!("skipped: XMR_BLOCKS_BIN / XMR_BLOCKS_BIN_START not set"); return; }; let start: u64 = start.parse().unwrap(); let bytes = std::fs::read(path).unwrap(); let t0 = std::time::Instant::now(); - let blocks = parse_response(&bytes, start).expect("解析"); + let blocks = parse_response(&bytes, start).expect("parse"); let parse_ms = t0.elapsed().as_secs_f64() * 1000.0; let mut db = crate::wallet::testing::db(); let (spend, view) = crate::wallet::testing::key_bytes(); let id = db.add_identity("bench", &spend, &view, start).unwrap().id; let t1 = std::time::Instant::now(); - crate::scan::scan_blocks(&mut db, id, &blocks).expect("扫描"); + crate::scan::scan_blocks(&mut db, id, &blocks).expect("scan"); let scan_ms = t1.elapsed().as_secs_f64() * 1000.0; let txs: usize = blocks.iter().map(|b| b.transactions.len()).sum(); eprintln!( diff --git a/chain-runtimes/monero/crates/monero-runtime/src/error.rs b/chain-runtimes/monero/crates/monero-runtime/src/error.rs index 72402a553..fc6694bda 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/error.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/error.rs @@ -1,77 +1,80 @@ -//! 错误码:跨 wasm 边界的稳定契约。 +//! Error codes: a stable contract across the wasm boundary. //! -//! 宿主按 `code` 分支处理、按 `params` 填 i18n 占位符。`detail` 只进日志, -//! 不面向用户、不翻译 —— 它可能带上游库的原始文案。 +//! The host branches on `code` and fills i18n placeholders from `params`. +//! `detail` is log-only, not user-facing or translated; it may carry raw +//! upstream text. //! -//! **不要改动已有取值。** 宿主会按字符串比对。 +//! **Never change existing values.** The host compares them as strings. use serde_json::{json, Map, Value}; use std::fmt; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ErrorCode { - // ── 输入校验 ──────────────────────────────────────────────────────── - /// 网络名不是 mainnet/stagenet/testnet。参数:`{ value }` + // ── Input validation ──────────────────────────────────────────────────────── + /// Network name is not mainnet/stagenet/testnet. Params: `{ value }` InvalidNetwork, - /// 地址无法解析,或不属于该网络。参数:`{ field }` + /// Address does not parse or belongs to another network. Params: `{ field }` InvalidAddress, - /// 私钥/种子字节数不对。参数:`{ byteLen, expected }` + /// Key/seed has the wrong byte length. Params: `{ byteLen, expected }` InvalidKeyMaterial, - /// 子地址序号非法(主序号与次序号不可同时为 0,那是主地址)。 + /// Invalid subaddress index (major and minor cannot both be 0; that is the primary address). InvalidSubaddressIndex, - /// 高度区间不合法(起点大于终点,或终点超过链尖)。参数:`{ from, to }` + /// Invalid height range (from > to, or to is past the chain tip). Params: `{ from, to }` InvalidBlockRange, - /// 宿主传入的 JSON 结构不对。参数:`{ field, reason }` + /// Malformed JSON from the host. Params: `{ field, reason }` InvalidRequest, - // ── 生命周期 ──────────────────────────────────────────────────────── - /// 还没 `openWallet`。 + // ── Lifecycle ──────────────────────────────────────────────────────── + /// `openWallet` has not been called. WalletNotOpen, - /// 正在进行一次异步操作,此刻不接受切换钱包的调用。参数:`{ operation }` + /// An async operation is in flight; wallet-switching calls are refused. Params: `{ operation }` WalletBusy, - /// 存储层还没初始化(wasm 上是 VFS 未安装)。 + /// Storage not initialized (on wasm: VFS not installed). NotInitialized, - /// 该账户在库里不存在。参数:`{ accountId }` + /// Account not in the database. Params: `{ accountId }` AccountNotFound, - // ── 扫描 ──────────────────────────────────────────────────────────── - /// 节点返回的块与本地记录不连续 —— 重组,或节点在骗人。 - /// 参数:`{ atHeight, suggestedRewindHeight }` + // ── Scanning ──────────────────────────────────────────────────────────── + /// Node blocks do not chain onto local records: a reorg or a lying node. + /// Params: `{ atHeight, suggestedRewindHeight }` ReorgDetected, - /// **节点给的 RingCT 输出索引与本地推算不符。** + /// **Node-reported RingCT output index differs from the locally derived one.** /// - /// 上游明确警告这个字段不可验证,要求客户端自己维护索引并比对;不一致 - /// 意味着节点在提供虚假视图,应当断开而不是继续扫。 - /// 参数:`{ height, claimed, expected }` + /// Upstream warns this field is unverifiable and clients must track and + /// compare it themselves; a mismatch means the node serves a false view, + /// so disconnect rather than keep scanning. + /// Params: `{ height, claimed, expected }` RingCtIndexMismatch, - /// 扫描器拒绝了这个块(上游 `ScanError`)。参数:`{ height }` + /// Scanner rejected the block (upstream `ScanError`). Params: `{ height }` ScanFailed, - // ── 外部世界 ──────────────────────────────────────────────────────── - /// 节点地址没配。 + // ── External ──────────────────────────────────────────────────────── + /// No node URL configured. NodeNotConfigured, - /// 节点不在钱包所属的网络上(按创世块判断),或认不出它在哪条链上。 - /// 参数:`{ nodeNetwork, walletNetwork }` 或 `{ nodeGenesis }` + /// Node is on a different network than the wallet (by genesis block), or + /// its chain is unrecognized. + /// Params: `{ nodeNetwork, walletNetwork }` or `{ nodeGenesis }` NodeNetworkMismatch, - /// 网络请求失败或超时。参数:`{ operation }` + /// Network request failed or timed out. Params: `{ operation }` NetworkError, - /// 节点返回的数据解不开(epee/JSON 格式不对)。参数:`{ operation }` + /// Node response does not decode (bad epee/JSON). Params: `{ operation }` MalformedNodeResponse, - /// 节点明确拒收了这笔交易(双花、手续费不足……)。输入的预留已释放。 + /// Node explicitly rejected the transaction (double spend, low fee, ...). Input reservations are released. BroadcastRejected, - // ── 存储 ──────────────────────────────────────────────────────────── - /// SQLite 操作失败。参数:`{ operation }` + // ── Storage ──────────────────────────────────────────────────────────── + /// SQLite operation failed. Params: `{ operation }` DatabaseError, - /// 库名非法(空,或含路径分隔符)。参数:`{ value }` + /// Invalid database name (empty or contains a path separator). Params: `{ value }` InvalidDbName, - /// 该能力尚未实现。参数:`{ what }` + /// Capability not implemented yet. Params: `{ what }` Unimplemented, } impl ErrorCode { - /// 稳定字符串形式。**不要改动已有取值。** + /// Stable string form. **Never change existing values.** pub fn as_str(self) -> &'static str { use ErrorCode::*; match self { @@ -103,9 +106,9 @@ impl ErrorCode { #[derive(Debug)] pub struct RuntimeError { pub code: ErrorCode, - /// 结构化参数,供宿主填 i18n 占位符。**永远是一个 JSON 对象。** + /// Structured params for host i18n placeholders. **Always a JSON object.** pub params: Value, - /// 上游库的原始报错。**仅用于日志**,不面向用户,不做 i18n。 + /// Raw upstream error. **Log-only**; not user-facing, not translated. pub detail: Option, } @@ -156,7 +159,7 @@ impl From for RuntimeError { pub type Result = std::result::Result; -/// 给数据库操作贴上操作名,排查时能知道是哪一步挂的。 +/// Tags a database error with the operation that failed. pub fn db_err(operation: &str, e: impl fmt::Display) -> RuntimeError { RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": operation })).detail(e) } @@ -168,8 +171,8 @@ pub fn net_err(operation: &str, e: impl fmt::Display) -> RuntimeError { #[cfg(target_arch = "wasm32")] impl From for wasm_bindgen::JsValue { fn from(e: RuntimeError) -> Self { - // 用 JSON 字符串而不是 Error 对象:宿主那头统一 `JSON.parse` 就能拿到 - // 结构化的 code/params,不必区分 Error 与非 Error 两条路径。 + // A JSON string rather than an Error object: the host always + // `JSON.parse`s it to get code/params, with a single code path. wasm_bindgen::JsValue::from_str(&e.to_json().to_string()) } } @@ -179,8 +182,8 @@ mod tests { use super::*; use std::collections::HashSet; - /// 码值必须唯一且是 SCREAMING_SNAKE —— 宿主按字符串比对,复制粘贴出一个 - /// 重复值会让两类错误在宿主眼里变成同一个,而那种 bug 很难从现象反推。 + /// Codes must be unique SCREAMING_SNAKE: the host compares strings, so a + /// duplicate would merge two errors on the host side. #[test] fn codes_are_unique_and_screaming_snake() { use ErrorCode::*; @@ -209,17 +212,17 @@ mod tests { let mut seen = HashSet::new(); for code in all { let s = code.as_str(); - assert!(seen.insert(s), "码值重复: {s}"); + assert!(seen.insert(s), "duplicate code: {s}"); assert!( !s.is_empty() && s.chars() .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'), - "码值格式不对: {s}" + "malformed code: {s}" ); } } - /// `params` 永远是对象 —— 宿主直接取字段,不必先判类型。 + /// `params` is always an object, so the host can read fields without type checks. #[test] fn params_default_to_empty_object() { let e = RuntimeError::new(ErrorCode::WalletNotOpen); @@ -230,10 +233,10 @@ mod tests { #[test] fn json_shape_is_stable() { let e = RuntimeError::with(ErrorCode::InvalidBlockRange, json!({ "from": 5, "to": 1 })) - .detail("起点大于终点"); + .detail("from > to"); let v = e.to_json(); assert_eq!(v["code"], "INVALID_BLOCK_RANGE"); assert_eq!(v["params"]["from"], 5); - assert_eq!(v["detail"], "起点大于终点"); + assert_eq!(v["detail"], "from > to"); } } diff --git a/chain-runtimes/monero/crates/monero-runtime/src/keys.rs b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs index 85519ace6..8e2ed5fd2 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/keys.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs @@ -1,14 +1,10 @@ -//! 观察密钥与地址派生。 +//! View keys and address derivation. //! -//! ## 这里有什么、没有什么 +//! Holds the public spend key and private view key (monero-oxide `ViewPair`), +//! everything scanning needs; the Zcash UFVK equivalent. //! -//! **有**:花费公钥 + 私有观察密钥(即 monero-oxide 的 `ViewPair`),这是扫链 -//! 需要的全部材料,等价于 Zcash 的 UFVK。 -//! -//! **没有**:花费私钥。它永远不进这个 crate,也不落库 —— 签名走单独的路径, -//! 由宿主在需要时把种子传进签名函数,用完即弃。 -//! -//! 想审计「私钥去了哪」,看这个文件就够:它一次都没出现。 +//! The private spend key is never stored here or persisted. Signing takes the +//! seed from the host per call and drops it afterwards. use monero_wallet::{ address::{MoneroAddress, Network, SubaddressIndex}, @@ -20,8 +16,8 @@ use zeroize::Zeroizing; use crate::error::{ErrorCode, Result, RuntimeError}; -/// 解析网络名。**没有缺省值** —— 主网和测试网的地址互不通用,猜错了钱会发到 -/// 一个看起来合法、实际上无人持有的地址上。 +/// Parses a network name. **No default**: a wrong guess sends funds to a +/// valid-looking address nobody controls. pub fn parse_network(name: &str) -> Result { match name { "mainnet" | "main" => Ok(Network::Mainnet), @@ -51,10 +47,10 @@ fn expect_32(bytes: &[u8], field: &str) -> Result<[u8; 32]> { }) } -/// 从原始字节造观察密钥对。 +/// Builds a view pair from raw bytes. /// -/// `spend_public` 是压缩的 ed25519 点,`view_private` 是标准序的标量。 -/// 两者都来自宿主 —— 这个 crate 不做派生,只做使用。 +/// `spend_public` is a compressed ed25519 point, `view_private` a canonical +/// scalar. Both come from the host. pub fn view_pair_from_bytes(spend_public: &[u8], view_private: &[u8]) -> Result { let spend = CompressedPoint::from(expect_32(spend_public, "spendPublicKey")?) .decompress() @@ -73,8 +69,8 @@ pub fn view_pair_from_bytes(spend_public: &[u8], view_private: &[u8]) -> Result< ) })?; - // 上游拒绝带挠率的花费公钥(那种密钥能否花费存疑)。这是它的判断,不是 - // 我们的 —— 原样把拒绝理由传出去,不要吞掉。 + // Upstream rejects spend keys with torsion (spendability is doubtful). + // Pass its reason through unchanged. ViewPair::new(spend, Zeroizing::new(view)).map_err(|e| { RuntimeError::with( ErrorCode::InvalidKeyMaterial, @@ -84,13 +80,13 @@ pub fn view_pair_from_bytes(spend_public: &[u8], view_private: &[u8]) -> Result< }) } -/// 主地址(标准地址)。 +/// Primary (standard) address. pub fn primary_address(pair: &ViewPair, network: Network) -> String { pair.legacy_address(network).to_string() } -/// 子地址。`(0, 0)` 是主地址,不是子地址 —— 上游对它返回 `None`,这里也拒绝, -/// 否则会注册出一个扫描器永远不认的条目。 +/// Subaddress. `(0, 0)` is the primary address; upstream returns `None` and we +/// reject it too, or the registry would get an entry the scanner never matches. pub fn subaddress(pair: &ViewPair, network: Network, major: u32, minor: u32) -> Result { let index = SubaddressIndex::new(major, minor).ok_or_else(|| { RuntimeError::with( @@ -101,12 +97,12 @@ pub fn subaddress(pair: &ViewPair, network: Network, major: u32, minor: u32) -> Ok(pair.subaddress(network, index).to_string()) } -/// 校验一个收款地址:编码合法、且属于指定网络。 +/// Whether `encoded` is a valid address on `network`. pub fn validate_address(network: Network, encoded: &str) -> bool { MoneroAddress::from_str(network, encoded).is_ok() } -/// 解析收款地址,网络不符时明确报错而不是笼统的"地址无效"。 +/// Parses a recipient address; the error names the expected network. pub fn parse_address(network: Network, encoded: &str, field: &str) -> Result { MoneroAddress::from_str(network, encoded).map_err(|e| { RuntimeError::with( @@ -121,7 +117,7 @@ pub fn parse_address(network: Network, encoded: &str, field: &str) -> Result RuntimeError { match view_pair_from_bytes(spend, view) { - Ok(_) => panic!("本该被拒绝的密钥材料却通过了"), + Ok(_) => panic!("key material should have been rejected"), Err(e) => e, } } @@ -169,18 +165,17 @@ mod tests { assert_eq!(e.params["byteLen"], 31); } - /// 全零不是合法曲线点,必须在解压那一步就被挡住,而不是带着一个无效点 - /// 一路跑到扫描里去。 + /// An invalid point must be rejected at decompression, not reach scanning. #[test] fn non_curve_spend_key_is_rejected() { let mut not_a_point = [0u8; 32]; - not_a_point[0] = 2; // 刻意构造一个解压不出来的值 + not_a_point[0] = 2; // does not decompress let e = expect_key_error(¬_a_point, &[1u8; 32]); assert_eq!(e.code, ErrorCode::InvalidKeyMaterial); } - /// (0,0) 是主地址。允许它进子地址注册表会产出一个扫描器永远不认的条目, - /// 表现为「这个地址收到的钱永远扫不到」。 + /// (0,0) is the primary address. Registering it as a subaddress would + /// create an entry whose incoming funds are never scanned. #[test] fn subaddress_zero_zero_is_refused() { let pair = test_pair(); @@ -190,8 +185,8 @@ mod tests { assert!(subaddress(&pair, Network::Mainnet, 1, 0).is_ok()); } - /// 子地址必须与主地址不同,且不同序号之间互不相同 —— 派生错了会让不同 - /// 账户共用一个收款地址,是最坏的那类 bug。 + /// Subaddresses must differ from the primary and from each other; a + /// collision would make accounts share a receiving address. #[test] fn subaddresses_are_distinct_from_each_other_and_the_primary() { let pair = test_pair(); @@ -208,48 +203,45 @@ mod tests { } fn test_pair() -> ViewPair { - // 从一个已知合法地址取出它的公钥对,再配一个任意标量当观察私钥。 - // 这里不关心它们是否互相对应 —— 测的是派生与编码路径。 + // Spend key from a known address plus an arbitrary view scalar. They + // need not match; this tests derivation and encoding. let addr = MoneroAddress::from_str(Network::Mainnet, MAINNET_ADDR).unwrap(); let spend = addr.spend().compress().to_bytes(); let mut view = [0u8; 32]; - view[0] = 9; // 小标量,必然是标准序 + view[0] = 9; // small, hence canonical match view_pair_from_bytes(&spend, &view) { Ok(pair) => pair, - Err(e) => panic!("测试密钥对构造失败: {e}"), + Err(e) => panic!("failed to build test key pair: {e}"), } } } -// ── 从 BIP-39 / BIP-32 派生 Monero 密钥 ───────────────────────────────── +// ── Monero keys from BIP-39 / BIP-32 ───────────────────────────────── -/// 从 BIP-32 派生出来的 32 字节私钥造出 Monero 的密钥三元组。 -/// -/// ## 为什么是这个约定 +/// Derives Monero keys from a 32-byte BIP-32 private key. /// -/// Monero 原生用自己的 25 词助记词,而 OneKey 全链统一 BIP-39。业界(以及 -/// **OneKey V4 自己**)的做法是: +/// Monero natively uses its own 25-word mnemonic; OneKey uses BIP-39 for all +/// chains. The common convention, also used by **OneKey V4**, is: /// /// ```text /// spend_secret = sc_reduce32(bip32_private_key) /// view_secret = sc_reduce32(keccak256(spend_secret)) /// ``` /// -/// **这个约定不能改。** V4 用的就是它(`sdkXmr/helper.ts` 的 -/// `getKeyPairFromRawPrivatekey`:先 `scReduce32` 再 `hashToScalar`),换一个 -/// 会让老用户导入同一套助记词后看到一个空钱包 —— 钱还在链上,只是这个钱包 -/// 再也找不到它。 +/// **Do not change it.** V4 uses it (`getKeyPairFromRawPrivatekey` in +/// `sdkXmr/helper.ts`: `scReduce32` then `hashToScalar`); any other scheme shows +/// existing users an empty wallet for the same mnemonic. /// -/// 返回观察材料与主地址。**花费私钥不返回** —— 它就是调用方传进来的那个 -/// BIP-32 私钥,宿主本来就持有,没有理由让它再跨一次边界。 +/// Returns view material and the primary address. **The spend key is not +/// returned**: the host already holds the BIP-32 key it passed in. pub fn derive_from_bip32_key(network: Network, bip32_private_key: &[u8]) -> Result { use monero_wallet::ed25519::Point; let raw = expect_32(bip32_private_key, "bip32PrivateKey")?; - // sc_reduce32:把任意 32 字节约简到标量域内。 + // sc_reduce32: reduce 32 bytes into the scalar field. let spend = Scalar::from(curve25519_dalek::Scalar::from_bytes_mod_order(raw)); - // hash_to_scalar:keccak256 再约简。上游 `Scalar::hash` 正是这个。 + // hash_to_scalar: keccak256 then reduce; upstream `Scalar::hash`. let view = Scalar::hash(<[u8; 32]>::from(spend)); let spend_public = @@ -276,7 +268,7 @@ pub struct DerivedKeys { pub primary_address: String, } -/// 花费私钥的标量形式,签名时用。与 [`derive_from_bip32_key`] 同一个约简。 +/// Spend key scalar for signing; same reduction as [`derive_from_bip32_key`]. pub fn spend_scalar_from_bip32_key(bip32_private_key: &[u8]) -> Result<[u8; 32]> { let raw = expect_32(bip32_private_key, "bip32PrivateKey")?; let spend = Scalar::from(curve25519_dalek::Scalar::from_bytes_mod_order(raw)); @@ -287,22 +279,22 @@ pub fn spend_scalar_from_bip32_key(bip32_private_key: &[u8]) -> Result<[u8; 32]> mod derive_tests { use super::*; - /// 派生必须是确定性的,且同一把 BIP-32 私钥在不同网络上给出不同前缀的 - /// 地址(主网 4 / 测试网 9 / stagenet 5)。 + /// Derivation is deterministic, and the address prefix is per network + /// (mainnet 4 / testnet 9 / stagenet 5). #[test] fn derivation_is_deterministic_and_network_scoped() { let key = [3u8; 32]; - let a = derive_from_bip32_key(Network::Mainnet, &key).expect("派生"); - let b = derive_from_bip32_key(Network::Mainnet, &key).expect("派生"); + let a = derive_from_bip32_key(Network::Mainnet, &key).expect("derive"); + let b = derive_from_bip32_key(Network::Mainnet, &key).expect("derive"); assert_eq!(a.primary_address, b.primary_address); assert_eq!(a.spend_public_key, b.spend_public_key); assert!(a.primary_address.starts_with('4')); - let t = derive_from_bip32_key(Network::Testnet, &key).expect("派生"); + let t = derive_from_bip32_key(Network::Testnet, &key).expect("derive"); assert_ne!(t.primary_address, a.primary_address); } - /// 不同的 BIP-32 私钥必须给出不同的地址 —— 撞了就是灾难。 + /// Different BIP-32 keys must give different addresses. #[test] fn different_keys_give_different_addresses() { let a = derive_from_bip32_key(Network::Mainnet, &[1u8; 32]).unwrap(); @@ -311,20 +303,18 @@ mod derive_tests { assert_ne!(a.view_private_key, b.view_private_key); } - /// 观察密钥必须由花费密钥经 keccak 得出,而不是别的什么 —— 这条锁住 - /// 与 V4 的兼容性(`hashToScalar(privateSpendKey)`)。 - /// **V4 兼容性契约。** 这是从 OneKey V4 取的真实向量: - /// 助记词经 `m/44'/128'/0'` 派生出的 BIP-32 私钥,以及 V4 当时显示给用户的 - /// 那个主地址(见 app 仓 `CoreChainSoftware.test.ts` 的 fixture)。 + /// **V4 compatibility contract.** Real OneKey V4 vector: the BIP-32 key at + /// `m/44'/128'/0'` and the primary address V4 showed (fixture in the app + /// repo's `CoreChainSoftware.test.ts`). /// - /// 派生约定是 `spend = sc_reduce32(bip32_key)`、`view = keccak256(spend)`。 - /// 这条一旦改动,V4 用户导入同一助记词会看到**空钱包** —— 钱还在链上, - /// 只是这个钱包再也找不到它。所以用真实向量钉死,不是自己造一个。 + /// Pins `spend = sc_reduce32(bip32_key)`, `view = keccak256(spend)`; any + /// change shows V4 users an **empty wallet** for the same mnemonic. #[test] fn the_v4_derivation_vector_still_produces_the_v4_address() { let key = hex::decode("8b28f5749ec99464d5a9d6527125aa8778ea017dd9e5cffaa567d2f62f2c8cbc") .unwrap(); - let derived = derive_from_bip32_key(Network::Mainnet, &key).expect("派生应当成功"); + let derived = + derive_from_bip32_key(Network::Mainnet, &key).expect("derivation should succeed"); assert_eq!( derived.primary_address, "45vw7EY1nYs66nCedDxS9hYptSP2PnnQwezJ4WmGsNFFKAKXMDWSEspFUKBD6UCivUB5LGW2vXoX8D3DjzhrFuoZSoDcYPN" @@ -344,7 +334,7 @@ mod derive_tests { fn key_length_is_enforced() { let e = derive_from_bip32_key(Network::Mainnet, &[0u8; 31]) .err() - .expect("长度不对必须拒绝"); + .expect("wrong length must be rejected"); assert_eq!(e.code, ErrorCode::InvalidKeyMaterial); } } diff --git a/chain-runtimes/monero/crates/monero-runtime/src/lib.rs b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs index 50b94e0e5..27230fc79 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/lib.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs @@ -1,19 +1,18 @@ //! # OneKey Monero Runtime //! -//! monero-oxide 提供密码学、扫描器与交易构造;**它不提供任何存储**。 -//! 这个 crate 就是缺的那一层:把扫描产出的输出落进 SQLite,并支持查询。 +//! monero-oxide provides cryptography, scanning, and transaction construction but +//! no storage. This crate adds it: scanned outputs are persisted to SQLite and queryable. //! -//! ## 为什么不是 monero-ts +//! ## Why not monero-ts //! -//! 那条路把整个钱包放在 wasm 内存里,持久化只能 `getData()` 整块序列化再写出去 -//! —— 历史越长每次保存越贵,且写一半崩了丢的是全部。这里走增量写 + 事务, -//! 和 Zcash runtime 同一个模型。 +//! monero-ts keeps the whole wallet in wasm memory and persists by serializing it +//! all via `getData()`, so saves grow with history and a crash mid-write loses +//! everything. This crate uses incremental transactional writes, like the Zcash runtime. //! -//! ## 设计边界 +//! ## Boundary //! -//! 留在 Rust 这一侧的只有三类:密码学与协议、平台胶水(存储 VFS、时钟)、 -//! 形状转换(Rust 富类型 → JSON)。**调度不在这里** —— 什么时候扫、扫哪一段, -//! 由宿主 TS 决定。 +//! Rust owns cryptography and protocol, platform glue (storage VFS, clock), and +//! conversion to JSON. Scheduling (when and what range to scan) belongs to the host. pub mod blocks_bin; pub mod error; @@ -36,7 +35,7 @@ pub use error::{ErrorCode, Result, RuntimeError}; #[cfg(target_arch = "wasm32")] pub mod bindgen; -/// 本 runtime 锁定的上游版本,供宿主自检与日志使用。 +/// Pinned upstream versions, for host self-checks and logs. pub fn dependency_versions() -> serde_json::Value { serde_json::json!({ "monero-wallet": "0.2.0", diff --git a/chain-runtimes/monero/crates/monero-runtime/src/network.rs b/chain-runtimes/monero/crates/monero-runtime/src/network.rs index 1f2456dff..f2b64020a 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/network.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/network.rs @@ -1,17 +1,17 @@ -//! 连 monerod 的传输层。 +//! Transport to monerod. //! -//! 上游 `monero-daemon-rpc` 把网络抽象成一个 trait,只有一个方法: -//! `post(route, body, size_limit) -> Vec`。二进制 RPC 与 epee 解析全在 -//! 上游 —— 我们只要把字节搬进搬出。 +//! Upstream `monero-daemon-rpc` abstracts the network as a trait with one method, +//! `post(route, body, size_limit) -> Vec`. Binary RPC and epee parsing stay +//! upstream; this module only moves bytes. //! -//! ## `Send` 的问题 +//! ## `Send` //! -//! 上游签名要求 `post` 返回 `impl Send + Future`,而浏览器 `fetch` 产出的 -//! future **不是** `Send`(它持有 JS 值,JS 值绑在它所在的线程上)。 +//! Upstream requires `post` to return `impl Send + Future`, but a browser `fetch` +//! future is not `Send` (it holds JS values bound to their thread). //! -//! wasm32-unknown-unknown 在我们的构建下没有 atomics、没有线程,整个模块跑在 -//! 一个 Worker 里,`Send` 这个约束在那里**没有可被违反的语义**。所以用一层 -//! 断言包装是成立的 —— 但仅限这个目标,见 [`SingleThreaded`] 上的安全性说明。 +//! Our wasm32-unknown-unknown build has no atomics or threads and runs in a single +//! Worker, so `Send` has nothing to violate there. An asserting wrapper is sound on +//! that target only; see the safety note on [`SingleThreaded`]. use monero_daemon_rpc::{HttpTransport, MoneroDaemon}; use monero_interface::InterfaceError; @@ -19,20 +19,19 @@ use serde_json::json; use crate::error::{net_err, ErrorCode, Result, RuntimeError}; -/// 单次请求的默认超时。 +/// Default per-request timeout. /// -/// 这是**停滞**超时,不是整批的截止时间:块流只要还在推进就不判死。 +/// A stall timeout, not a whole-batch deadline: a block stream that keeps progressing survives. pub const DEFAULT_TIMEOUT_MS: u32 = 30_000; -/// 响应体上限,防一个恶意节点用超大响应把 wasm 堆撑爆。 -/// 取 32 MB —— spam 墙区段一批块可达几十 MB,留够余量但不无界。 +/// Response body cap, so a malicious node cannot exhaust the wasm heap with an +/// oversized response. 32 MB: a batch in the spam-wall range can reach tens of MB. pub const MAX_RESPONSE_BYTES: usize = 32 * 1024 * 1024; -/// monerod 按路由区分 Content-Type。 +/// monerod expects a Content-Type per route. /// -/// 我一开始给所有路由都发 `application/octet-stream` 并在注释里断言「JSON -/// 路由也接受」—— **那是错的**,`/json_rpc` 会直接拒掉,表现为连接阶段就 -/// 失败而看不出原因。二进制路由以 `.bin` 结尾,其余走 JSON。 +/// `/json_rpc` rejects `application/octet-stream`, which surfaces as an unexplained +/// connect failure. Binary routes end in `.bin`; the rest are JSON. fn content_type_for(route: &str) -> &'static str { if route.ends_with(".bin") { "application/octet-stream" @@ -41,21 +40,21 @@ fn content_type_for(route: &str) -> &'static str { } } -/// 把一个 `!Send` 的 future 断言成 `Send`。 +/// Asserts that a `!Send` future is `Send`. /// -/// # 安全性 +/// # Safety /// -/// **只在 wasm32 上编译。** 该目标在本工程的构建配置下没有 atomics、没有 -/// 线程:产物跑在单个 Worker 里,不存在第二个线程能观察到这个 future。 -/// `Send` 在那里不约束任何真实行为。 +/// Compiled only for wasm32. This project builds that target without atomics or +/// threads: the module runs in a single Worker, so no second thread can observe +/// the future and `Send` constrains nothing. /// -/// 哪天这个 crate 要支持 wasm 线程(atomics + SharedArrayBuffer),**这一层 -/// 必须先去掉**,否则就是真正的数据竞争。 +/// If this crate ever supports wasm threads (atomics + SharedArrayBuffer), this +/// wrapper must be removed first; otherwise it is a real data race. #[cfg(target_arch = "wasm32")] struct SingleThreaded(F); #[cfg(target_arch = "wasm32")] -// SAFETY: 见上方说明 —— 目标平台单线程,无第二个线程可观察。 +// SAFETY: see above; the target is single-threaded, so no other thread can observe it. unsafe impl Send for SingleThreaded {} #[cfg(target_arch = "wasm32")] @@ -65,15 +64,16 @@ impl core::future::Future for SingleThreaded { self: core::pin::Pin<&mut Self>, cx: &mut core::task::Context<'_>, ) -> core::task::Poll { - // SAFETY: 只是把 pin 投影到唯一字段上,不移动它。 + // SAFETY: pin projection onto the only field; it is never moved. unsafe { self.map_unchecked_mut(|s| &mut s.0).poll(cx) } } } -/// 响应体上限检查,宿主通道与 wasm 内 fetch 共用。 +/// Response size check shared by the host channel and in-wasm fetch. /// -/// 防一个恶意节点用超大响应把 wasm 堆撑爆。两条路都拿不到流式截断,只能收完 -/// 再判 —— 但至少不会把它交给解析器再翻一倍。 +/// Guards the wasm heap against oversized responses from a malicious node. Neither +/// path can truncate while streaming, so this runs after receipt, but before the +/// parser would double the footprint. #[cfg(target_arch = "wasm32")] fn cap_response( bytes: Vec, @@ -81,40 +81,36 @@ fn cap_response( ) -> std::result::Result, InterfaceError> { let cap = limit.unwrap_or(MAX_RESPONSE_BYTES).min(MAX_RESPONSE_BYTES); if bytes.len() > cap { - return Err(InterfaceError::InvalidInterface("响应超出大小上限".into())); + return Err(InterfaceError::InvalidInterface("response too big".into())); } Ok(bytes) } -// 宿主提供的请求处理器。 +// Request handler supplied by the host. // -// ## 为什么要把网络交给宿主 +// ## Why the host sends requests // -// 在 wasm 里 `fetch`,请求就是从浏览器上下文发出去的,于是受两条浏览器规则 -// 管:混合内容(明文 HTTP 节点直接被拦)和 CORS(monerod 默认不发 -// `Access-Control-Allow-Origin`,要运维自己加反代)。 +// In-wasm `fetch` runs in the browser context, so it is subject to mixed-content +// blocking (plain-HTTP nodes) and CORS (monerod sends no +// `Access-Control-Allow-Origin` by default). Few public nodes pass both, and +// routing every user through one third-party node hands that operator everyone's +// IP, scan ranges and broadcast timing. // -// 结果是全网几百个活着的公共节点里我们只能用个位数 —— 2026-09-22 实测 12 家, -// 只有 1 家同时满足。让一条隐私链的所有用户共用一个第三方节点,等于把用户 -// 来这里要的东西还回去:那个运营方看得见每个人的 IP、同步区间和广播时机。 +// This is about reachability, not speed (scanning is 0.4% of total time). The +// extension background (with `host_permissions`), the Electron main process and +// React Native native code are not bound by those rules. // -// **这和性能无关。** 纯扫描 153 块/秒、只占总耗时 0.4%。受限的是可达性不是 -// 速度,所以解法不是换原生,是把请求交出去。 -// -// 这两条规则只管浏览器上下文。插件的 background(配 `host_permissions`)、 -// 桌面的 Electron 主进程、移动端的 RN 原生都不受管。 -// -// 宿主不装时退回 wasm 内 fetch,行为与以前完全一致 —— 增量改动。 +// Without a host handler, requests fall back to in-wasm fetch. #[cfg(target_arch = "wasm32")] thread_local! { static HOST_HANDLER: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } -/// 装上宿主的请求处理器。传 `None` 卸载,退回 wasm 内 fetch。 +/// Install the host request handler; `None` uninstalls it and falls back to in-wasm fetch. /// -/// 处理器签名:`(url, contentType, body: Uint8Array) => Promise`。 -/// 抛出或 reject 都当作网络错误上报,原因原样带出。 +/// Signature: `(url, contentType, body: Uint8Array) => Promise`. +/// A throw or rejection is reported as a network error carrying its reason. #[cfg(target_arch = "wasm32")] pub fn set_host_handler(handler: Option) { HOST_HANDLER.with(|slot| *slot.borrow_mut() = handler); @@ -125,7 +121,7 @@ fn host_handler() -> Option { HOST_HANDLER.with(|slot| slot.borrow().clone()) } -/// 走宿主通道发一次请求。 +/// Send one request through the host channel. #[cfg(target_arch = "wasm32")] async fn post_via_host( handler: js_sys::Function, @@ -137,7 +133,7 @@ async fn post_via_host( use wasm_bindgen_futures::JsFuture; let fail = |stage: &str, detail: String| { - InterfaceError::InterfaceError(format!("{url}: 宿主通道 {stage}: {detail}")) + InterfaceError::InterfaceError(format!("{url}: host channel {stage}: {detail}")) }; let array = js_sys::Uint8Array::from(body); @@ -148,26 +144,26 @@ async fn post_via_host( &JsValue::from_str(content_type), &array, ) - .map_err(|e| fail("调用", describe_js(&e)))?; + .map_err(|e| fail("call", describe_js(&e)))?; - // 同步返回字节或返回 Promise 都接受 —— 宿主那边怎么写都行。 + // Accept bytes returned directly or via a Promise. let resolved = match returned.dyn_into::() { Ok(promise) => JsFuture::from(promise) .await - .map_err(|e| fail("等待响应", describe_js(&e)))?, + .map_err(|e| fail("await response", describe_js(&e)))?, Err(value) => value, }; let bytes = resolved .dyn_into::() - .map_err(|_| fail("返回值", "宿主必须回 Uint8Array".to_owned()))?; + .map_err(|_| fail("return value", "host must return a Uint8Array".to_owned()))?; Ok(bytes.to_vec()) } -/// 把一个 JS 侧的异常压成一句人能读的话。 +/// Reduce a JS exception to a readable message. /// -/// `JsValue` 的 Debug 输出对排障几乎没用,而 `Error.message` 恰恰是浏览器把 -/// 真实原因(DNS 失败、CORS 被拒、连接被重置)写进去的地方。 +/// `JsValue`'s Debug output is useless for diagnosis; `Error.message` is where the +/// browser puts the real cause (DNS failure, CORS rejection, connection reset). #[cfg(target_arch = "wasm32")] fn describe_js(value: &wasm_bindgen::JsValue) -> String { use wasm_bindgen::JsValue; @@ -178,7 +174,7 @@ fn describe_js(value: &wasm_bindgen::JsValue) -> String { .unwrap_or_else(|| format!("{value:?}")) } -/// 单次请求的上限。一整批块在慢节点上要十几秒,留足余量。 +/// Per-request cap. A full batch can take over ten seconds on a slow node. #[cfg(target_arch = "wasm32")] const REQUEST_TIMEOUT_MS: u32 = 45_000; @@ -187,7 +183,7 @@ const REQUEST_TIMEOUT_MS: u32 = 45_000; #[cfg(target_arch = "wasm32")] const HOST_REQUEST_TIMEOUT_MS: u32 = 10 * 60 * 1000; -/// 浏览器载体里的传输实现,基于 `fetch`。 +/// Browser transport based on `fetch`. #[cfg(target_arch = "wasm32")] #[derive(Clone, Debug)] pub struct FetchTransport { @@ -202,8 +198,8 @@ impl FetchTransport { } } - /// 有上限地等一次请求。卡住的请求会让这一步一直占着钱包库,之后的每次调用 - /// 都只能拿到 WALLET_BUSY;超时后放手,请求本身在后台自生自灭。 + /// Await one request with a cap. A stuck request holds the wallet DB, so every later + /// call gets WALLET_BUSY; on timeout it is abandoned to finish in the background. async fn post_inner( base_url: String, route: String, @@ -223,7 +219,7 @@ impl FetchTransport { match select(request, timeout).await { Either::Left((result, _)) => result, Either::Right(_) => Err(InterfaceError::InterfaceError(format!( - "{url}: {} 秒没有响应", + "{url}: no response in {} s", timeout_ms / 1000 ))), } @@ -241,16 +237,15 @@ impl FetchTransport { let url = format!("{base_url}/{}", route.trim_start_matches('/')); let content_type = content_type_for(&route); - // 宿主装了处理器就交给它 —— 那条路不受浏览器的混合内容与 CORS 限制, - // 因此能用全网任意节点。没装则退回下面的 wasm 内 fetch。 + // Prefer the host handler: it is not bound by mixed-content or CORS rules, so any + // node is usable. Otherwise fall back to in-wasm fetch below. if let Some(handler) = host_handler() { let bytes = post_via_host(handler, &url, content_type, &body).await?; return cap_response(bytes, limit); } - // 每一步都带上自己的原因。九个失败点共用一句「请求失败」,就是把 - // 「节点挂了」「节点没开 CORS」「地址写错了」「响应体读不动」压成 - // 同一条信息 —— 而这几种情况用户要做的事完全不同。 + // Tag each failure with its stage: a down node, missing CORS, a bad URL and an + // unreadable body need different fixes from the user. let fail = |stage: &str, detail: String| { InterfaceError::InterfaceError(format!("{url}: {stage}: {detail}")) }; @@ -261,7 +256,7 @@ impl FetchTransport { opts.set_body(&array); let request = web_sys::Request::new_with_str_and_init(&url, &opts) - .map_err(|e| fail("构造请求", describe_js(&e)))?; + .map_err(|e| fail("build request", describe_js(&e)))?; let _ = request.headers().set("Content-Type", content_type); let global = js_sys::global(); @@ -270,32 +265,32 @@ impl FetchTransport { .and_then(|f| f.dyn_into::().ok()) .ok_or_else(|| { fail( - "取 fetch", - "当前环境没有全局 fetch(载体没装好,不是节点的问题)".to_owned(), + "get fetch", + "no global fetch here (host environment issue, not the node)".to_owned(), ) })?; let promise = fetch .call1(&global, &request) - .map_err(|e| fail("发起请求", describe_js(&e)))? + .map_err(|e| fail("send request", describe_js(&e)))? .dyn_into::() - .map_err(|e| fail("发起请求", describe_js(&e)))?; + .map_err(|e| fail("send request", describe_js(&e)))?; let response = JsFuture::from(promise) .await - // 走到这里基本只有两种:网络不通,或者节点没回 CORS 头。浏览器 - // 出于安全不会告诉我们是哪种,所以把两种可能都写出来。 + // Usually the network is down or the node sent no CORS headers; the browser + // does not say which, so name both. .map_err(|e| { fail( - "等待响应", - format!("{}(节点不可达,或者没有返回 CORS 头)", describe_js(&e)), + "await response", + format!("{} (node unreachable or no CORS headers)", describe_js(&e)), ) })? .dyn_into::() - .map_err(|e| fail("解析响应", describe_js(&e)))?; + .map_err(|e| fail("parse response", describe_js(&e)))?; if !response.ok() { return Err(fail( - "节点拒绝", + "node rejected", format!("HTTP {} {}", response.status(), response.status_text()), )); } @@ -303,10 +298,10 @@ impl FetchTransport { let buffer = JsFuture::from( response .array_buffer() - .map_err(|e| fail("读取响应体", describe_js(&e)))?, + .map_err(|e| fail("read response body", describe_js(&e)))?, ) .await - .map_err(|e| fail("读取响应体", describe_js(&e)))?; + .map_err(|e| fail("read response body", describe_js(&e)))?; cap_response(js_sys::Uint8Array::new(&buffer).to_vec(), limit) } @@ -330,7 +325,7 @@ impl HttpTransport for FetchTransport { } } -/// 原生传输,用于本机测试与诊断 —— 浏览器里出的问题可以在这边上真调试器复现。 +/// Native transport for local tests and diagnostics; reproduces browser issues under a debugger. #[cfg(not(target_arch = "wasm32"))] #[derive(Clone, Debug)] pub struct NativeTransport { @@ -347,8 +342,8 @@ impl NativeTransport { let builder = reqwest::Client::builder().timeout(std::time::Duration::from_millis( u64::from(DEFAULT_TIMEOUT_MS), )); - // reqwest 默认读 macOS 系统代理,curl 与 Node 不读。本机真链测试里 - // 同一节点 curl 秒回、这里却次次卡满超时时,用它排除代理的影响。 + // reqwest uses the macOS system proxy by default; curl and Node do not. Set this + // to rule out the proxy when a node answers curl instantly but times out here. let builder = if std::env::var_os("XMR_NATIVE_NO_PROXY").is_some() { builder.no_proxy() } else { @@ -373,8 +368,7 @@ impl HttpTransport for NativeTransport { let content_type = content_type_for(route); let client = self.client.clone(); async move { - // 把真实原因带出来。一律吞成「请求失败」会让排查完全没有抓手 —— - // 连不上、404、超时、TLS 失败在现象上一模一样。 + // Keep the real cause: refused, 404, timeout and TLS failure otherwise look identical. let response = client .post(&url) .header("Content-Type", content_type) @@ -382,8 +376,8 @@ impl HttpTransport for NativeTransport { .send() .await .map_err(|e| { - // reqwest 的顶层文案只有 "error sending request",真正原因 - // (超时、TLS、连接被重置、DNS)在 source 链里。 + // reqwest's top-level message is just "error sending request"; the cause + // (timeout, TLS, reset, DNS) is in the source chain. let mut chain = e.to_string(); let mut source = std::error::Error::source(&e); while let Some(inner) = source { @@ -404,13 +398,13 @@ impl HttpTransport for NativeTransport { let bytes = response .bytes() .await - .map_err(|e| InterfaceError::InterfaceError(format!("读取 {url} 的响应体: {e}")))? + .map_err(|e| InterfaceError::InterfaceError(format!("read body of {url}: {e}")))? .to_vec(); let cap = response_size_limit .unwrap_or(MAX_RESPONSE_BYTES) .min(MAX_RESPONSE_BYTES); if bytes.len() > cap { - return Err(InterfaceError::InvalidInterface("响应超出大小上限".into())); + return Err(InterfaceError::InvalidInterface("response too big".into())); } Ok(bytes) } @@ -424,10 +418,10 @@ pub type Transport = NativeTransport; pub type Daemon = MoneroDaemon; -/// 连上一个 monerod 节点。 +/// Connect to a monerod node and return it with the network its genesis block identifies. /// -/// 节点地址**由宿主给**,这里没有内置默认值 —— 内置一个默认节点等于替用户 -/// 决定把自己的 IP 和查询交给谁,那是隐私决策,不该藏在 runtime 里。 +/// The host supplies the URL; there is no built-in default. A default would decide for +/// the user who sees their IP and queries, a privacy choice the runtime must not make. pub async fn connect(base_url: &str) -> Result<(Daemon, monero_wallet::address::Network)> { if base_url.trim().is_empty() { return Err(RuntimeError::new(ErrorCode::NodeNotConfigured)); @@ -446,11 +440,11 @@ pub async fn connect(base_url: &str) -> Result<(Daemon, monero_wallet::address:: Ok((daemon, network)) } -/// 各网络的创世块哈希。 +/// Genesis block hash per network. /// -/// 同一套密钥在三个网络上推出同样的输出密钥:测试网钱包连上主网节点, -/// 扫到的就是真 XMR,按测试网地址发出去的也是真 XMR。只看地址前缀挡不住, -/// 必须确认节点所在的链。 +/// The same keys derive the same output keys on all three networks: a testnet wallet +/// on a mainnet node would scan and send real XMR. Address prefixes cannot catch +/// this; the node's chain must be checked. const GENESIS_HASHES: [(monero_wallet::address::Network, &str); 3] = [ ( monero_wallet::address::Network::Mainnet, @@ -474,8 +468,8 @@ pub(crate) fn network_for_genesis(hash: &[u8; 32]) -> Option Result { use monero_daemon_rpc::prelude::*; @@ -492,8 +486,8 @@ async fn node_network(daemon: &Daemon) -> Result> = const { std::cell::RefCell::new(None) }; } @@ -521,7 +515,7 @@ mod tests { assert_ne!(Network::Mainnet, Network::Stagenet); } - /// 不内置默认节点:内置一个等于替用户决定把 IP 和查询交给谁。 + /// No built-in default node: it would decide for the user who sees their IP and queries. #[test] fn an_empty_node_url_is_refused_not_defaulted() { let e = futures_lite::future::block_on(connect("")).unwrap_err(); @@ -530,8 +524,8 @@ mod tests { assert_eq!(e.code, ErrorCode::NodeNotConfigured); } - /// 协议头必须显式。给个 `1.2.3.4:18081` 会被当成相对路径拼出乱七八糟的 - /// URL,错误现场离真正的原因很远。 + /// The scheme must be explicit: `1.2.3.4:18081` would be treated as a relative path + /// and yield a malformed URL that fails far from the cause. #[test] fn the_node_url_must_carry_a_scheme() { for bad in ["1.2.3.4:18081", "node.example.com", "ftp://x"] { @@ -540,8 +534,8 @@ mod tests { } } - /// 路由决定 Content-Type。发错会让 `/json_rpc` 在连接阶段就被拒, - /// 而错误现场离真正的原因很远 —— 这条踩过。 + /// The route decides Content-Type. The wrong one makes `/json_rpc` reject at + /// connect time, far from the cause. #[test] fn json_and_binary_routes_get_different_content_types() { assert_eq!(content_type_for("json_rpc"), "application/json"); @@ -555,7 +549,7 @@ mod tests { #[test] fn response_cap_never_exceeds_the_hard_limit() { - // 宿主传一个比硬上限还大的值时,以硬上限为准 + // A host value above the hard cap is clamped to it let requested = MAX_RESPONSE_BYTES * 4; assert_eq!(requested.min(MAX_RESPONSE_BYTES), MAX_RESPONSE_BYTES); } diff --git a/chain-runtimes/monero/crates/monero-runtime/src/perf.rs b/chain-runtimes/monero/crates/monero-runtime/src/perf.rs index 1436948b5..367d49d22 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/perf.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/perf.rs @@ -1,9 +1,7 @@ -//! 计时打点。 +//! Timing. //! -//! 扫得慢的时候,「慢在拉块还是慢在解密」是完全不同的两件事,而在浏览器里 -//! 两者的表现一模一样(界面不动)。实测公共节点单次 RPC 往返可达 490ms, -//! 不把两段分开量,就会把网络延迟误判成算力不足 —— 那会让整条技术路线的 -//! 结论反过来。 +//! Fetch and scan time are measured separately: public node RPC round trips can +//! reach ~490 ms, which would otherwise read as slow decryption. #[cfg(target_arch = "wasm32")] pub fn now_ms() -> f64 { diff --git a/chain-runtimes/monero/crates/monero-runtime/src/pool.rs b/chain-runtimes/monero/crates/monero-runtime/src/pool.rs index 4179f8aa4..11aa4de57 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/pool.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/pool.rs @@ -1,9 +1,11 @@ -//! 自己广播、还没上链的交易是否还活着。 +//! Liveness of our own broadcast, unconfirmed transactions. //! -//! 照 wallet2 `process_unconfirmed_transfer`:广播超过 [`TX_PROPAGATION_TIMEOUT_SECS`] -//! 仍然不在节点那里,判失败,把它花的输出放回可用。不放的话那笔钱永远锁着。 +//! Like wallet2 `process_unconfirmed_transfer`: a send still unknown to the node +//! [`TX_PROPAGATION_TIMEOUT_SECS`] after broadcast is marked failed and its inputs +//! are released, otherwise those funds stay locked. //! -//! 上链的不归这里管:扫描按 key image 认出来,交易行自然拿到高度(也会清掉失败标记)。 +//! Confirmed sends are handled by scanning via key images, which sets the height +//! and clears the failed flag. use rusqlite::params; use serde_json::Value; @@ -12,15 +14,15 @@ use crate::error::{db_err, Result}; use crate::network::Daemon; use crate::wallet::{now_secs, Db}; -/// wallet2 同值。短于 Dandelion++ 的扩散时间会把刚发的交易误判失败。 +/// Same as wallet2. Shorter than Dandelion++ propagation would fail fresh sends. pub const TX_PROPAGATION_TIMEOUT_SECS: i64 = 500; -/// 同一笔在途交易两次询问节点的最小间隔。扫链一步几秒一次,不能每步都问。 +/// Minimum interval between node checks of the same pending send; sync steps run every few seconds. const POOL_RECHECK_SECS: i64 = 60; const RESPONSE_SIZE_LIMIT: usize = 4 * 1024 * 1024; -/// 该问节点的在途交易:已过扩散期、没判过失败、最近没问过。 +/// Pending sends to check: past the propagation timeout, not failed, not checked recently. fn due_pending(db: &Db, identity_id: i64, now: i64) -> Result> { let mut stmt = db .conn() @@ -50,13 +52,14 @@ fn due_pending(db: &Db, identity_id: i64, now: i64) -> Result> { .collect()) } -/// 节点明确说不认识的交易。回包不像样就一个都不算 —— 宁可晚判,不可误判。 +/// Transactions the node explicitly reports missing. A malformed response counts +/// none, so a send is never failed on an unclear answer. fn missed_in(response: &str) -> Option> { let v: Value = serde_json::from_str(response).ok()?; if v.get("status").and_then(Value::as_str) != Some("OK") { return None; } - // epee 对空数组可能直接省略字段 + // epee may omit empty arrays. let Some(missed) = v.get("missed_tx") else { return Some(Vec::new()); }; @@ -82,10 +85,10 @@ fn mark_checked(db: &Db, identity_id: i64, txids: &[[u8; 32]], now: i64) -> Resu Ok(()) } -/// 判失败:交易留着(历史里显示失败),它花的输出放回可用。 +/// Mark a send failed: keep the transaction (shown as failed) and release its inputs. /// -/// `spent_in_txid` 保留:这条失败交易的金额还要靠它算;将来这笔输出被别的交易 -/// 花掉时会被覆盖。 +/// `spent_in_txid` is kept to compute the failed transaction's amount; a later +/// spend of the output overwrites it. pub(crate) fn mark_failed(db: &Db, identity_id: i64, txid: &[u8; 32]) -> Result<()> { let tx = db .conn() @@ -106,9 +109,10 @@ pub(crate) fn mark_failed(db: &Db, identity_id: i64, txid: &[u8; 32]) -> Result< tx.commit().map_err(|e| db_err("commitMarkFailed", e)) } -/// 问一次节点,把不在的判失败。返回判了几笔。 +/// Query the node once and mark missing sends failed; returns how many. /// -/// 节点不可达或回包异常时什么都不改:失败判定只能来自节点明确的「不认识」。 +/// Changes nothing if the node is unreachable or the response is malformed: only +/// an explicit "missing" fails a send. pub async fn check_pending(db: &Db, daemon: &Daemon, identity_id: i64) -> Result { let now = now_secs(); let due = due_pending(db, identity_id, now)?; @@ -175,7 +179,7 @@ mod tests { assert_eq!(due_pending(&db, id, now).unwrap(), vec![[2u8; 32]]); mark_checked(&db, id, &[[2u8; 32]], now).unwrap(); - assert!(due_pending(&db, id, now + 1).unwrap().is_empty(), "刚问过"); + assert!(due_pending(&db, id, now + 1).unwrap().is_empty(), "recent"); assert_eq!( due_pending(&db, id, now + POOL_RECHECK_SECS).unwrap(), vec![[2u8; 32]] @@ -207,10 +211,10 @@ mod tests { |r| r.get(0), ) .unwrap(); - assert_eq!(spent_at, None, "输出回到可用"); + assert_eq!(spent_at, None, "output released"); assert!( due_pending(&db, id, i64::MAX / 2).unwrap().is_empty(), - "判过就不再问" + "failed sends are not rechecked" ); } diff --git a/chain-runtimes/monero/crates/monero-runtime/src/query.rs b/chain-runtimes/monero/crates/monero-runtime/src/query.rs index fcf3e10c4..1d109e032 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/query.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs @@ -1,7 +1,7 @@ -//! 余额、历史与可花输出的查询。 +//! Balance, history and spendable-output queries. //! -//! 这一层是选 SQLite 而非内存方案的**直接兑现**:分页、按高度筛选、按子地址 -//! 聚合都是索引查询,不是在内存对象上过滤。历史再长也不需要把全部数据读进来。 +//! Paging, height filters and per-subaddress aggregation are indexed SQLite +//! queries, so long histories are never loaded into memory. use monero_wallet::WalletOutput; use rusqlite::{params, OptionalExtension}; @@ -10,34 +10,35 @@ use serde_json::{json, Value}; use crate::error::{db_err, ErrorCode, Result, RuntimeError}; use crate::wallet::Db; -/// Monero 协议对**所有**输出的固定锁定期:10 个确认。 +/// Consensus lock on **all** outputs: 10 confirmations. /// -/// 这不是我们的策略,是共识规则 —— 未满 10 块的输出构不进环,节点会拒。 -/// 额外时间锁(`additional_timelock`)是在这之上的附加约束。 +/// Younger outputs cannot be used in a ring; nodes reject them. +/// `additional_timelock` applies on top of this. pub const COINBASE_AND_STANDARD_LOCK: u64 = 10; #[derive(Debug, Default, Clone)] pub struct Balance { - /// 全部未花输出之和。 + /// Sum of all unspent outputs. pub total_atomic: u128, - /// 其中当前可花的部分(已过 10 块锁定且额外时间锁已满足,且未被预留)。 + /// Spendable now: past the 10-block lock and any extra timelock, and not reserved. pub unlocked_atomic: u128, - /// 被在途交易预留的部分。已计入 total,但不可再次选中。 + /// Reserved by in-flight sends. Counted in total, not selectable. pub locked_by_reservation_atomic: u128, - /// 待核实:还没有 key image、又出现在某个环里的输出金额。**这部分可能已经 - /// 被花掉**,要等宿主补算 key image 才知道;从没进过环的一定没花,不算在内。 + /// Outputs without a key image that appear in some ring. **May already be + /// spent** until the host supplies key images; outputs never seen in a ring + /// are certainly unspent and excluded. pub unverifiable_atomic: u128, - /// 自己发出、还没上链的交易的找零。已计入 total(锁定,不可花),wallet2 同款。 + /// Change from own unconfirmed sends. Counted in total but locked, as in wallet2. pub pending_change_atomic: u128, - /// 还没有 key image 的未花输出笔数。大于 0 时发送前要先补算 key image - /// (选币只选有 key image 的输出)。 + /// Unspent outputs lacking a key image. If > 0, compute key images before + /// sending (selection only uses outputs with one). pub outputs_without_key_image: u64, } impl Balance { pub fn to_json(&self) -> Value { - // 金额一律用字符串跨边界:piconero 的上限超过 JS 的 - // Number.MAX_SAFE_INTEGER,走数字会静默丢精度。 + // Amounts cross the boundary as strings: piconero values exceed JS + // Number.MAX_SAFE_INTEGER. json!({ "totalAtomic": self.total_atomic.to_string(), "unlockedAtomic": self.unlocked_atomic.to_string(), @@ -49,8 +50,8 @@ impl Balance { } } -/// 算余额。`chain_tip` 用于判断锁定期;给 `None` 表示还不知道链尖, -/// 此时一律按「未解锁」处理 —— 宁可显示 0 可用,也不要让用户去花一笔构不进环的钱。 +/// Computes the balance. `chain_tip` drives the lock check; `None` (tip unknown) +/// treats everything as locked rather than offer funds that cannot be spent. pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result { let mut stmt = db .conn() @@ -95,8 +96,8 @@ pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result) -> Result> = db .conn() .prepare( @@ -132,11 +133,11 @@ pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result bool { const MAX_BLOCK_NUMBER: u64 = 500_000_000; @@ -149,16 +150,15 @@ pub fn is_unlocked(height: u64, additional_timelock: u64, chain_tip: u64) -> boo if additional_timelock < MAX_BLOCK_NUMBER { chain_tip >= additional_timelock } else { - // 时间戳形式的锁没法只靠链高判断。保守处理:**当作仍锁定**。 - // 让用户等,比让他构一笔必然被拒的交易好。 + // Timestamp locks cannot be judged from height alone; treat as locked. false } } -/// 一笔可花输出的**元信息**,不含反序列化后的密码学对象。 +/// Spendable output **metadata**, without the deserialized crypto object. /// -/// 筛选与展示只需要这些列。把 blob 的反序列化推迟到真正要构造交易的那一刻, -/// 免得为了挑两个输出把五百个都解一遍 —— 那是内存方案的毛病,不该在这里复现。 +/// Enough for selection and display; blobs are deserialized only when building +/// the transaction. #[derive(Debug, Clone)] pub struct SpendableRow { pub id: i64, @@ -167,10 +167,10 @@ pub struct SpendableRow { pub height: u64, } -/// 取当前可花的输出元信息,金额降序(大额优先,减少输入数量从而降低手续费)。 +/// Currently spendable outputs, largest first (fewer inputs, lower fee). /// -/// 只返回**有 key image** 的输出:没有 key image 就无法确认它没被花掉, -/// 拿它构造交易有双花风险,节点会拒。 +/// Only outputs **with a key image**: without one we cannot tell whether it is +/// already spent, and the node would reject a double spend. pub fn spendable_rows(db: &Db, identity_id: i64, chain_tip: u64) -> Result> { let mut stmt = db .conn() @@ -222,13 +222,13 @@ pub fn spendable_rows(db: &Db, identity_id: i64, chain_tip: u64) -> Result Result { let blob: Vec = db .conn() @@ -247,15 +247,14 @@ pub fn load_output(db: &Db, output_id: i64) -> Result { WalletOutput::read(&mut blob.as_slice()).map_err(|e| { db_err( "deserializeOutput", - format!("输出 {output_id} 的 blob 读不回来: {e}"), + format!("cannot read blob of output {output_id}: {e}"), ) }) } -/// 交易历史,按高度倒序分页。 +/// Transaction history, paged, newest height first. pub fn history(db: &Db, identity_id: i64, limit: u32, offset: u32) -> Result { - // 限制上界:宿主传个巨大的 limit 会把整段历史读进内存,那正是我们选 - // SQLite 想避免的事。 + // Cap the page size so a huge limit cannot load the whole history. let limit = limit.clamp(1, 500); let mut stmt = db @@ -307,7 +306,7 @@ pub fn history(db: &Db, identity_id: i64, limit: u32, offset: u32) -> Result Result { let txid = hex::decode(txid_hex).map_err(|_| { RuntimeError::with( @@ -387,7 +386,7 @@ mod tests { ) -> i64 { let ki: Option> = with_key_image.then(|| { let mut k = vec![0u8; 32]; - // 每个输出一个不同的 key image,免得唯一性问题掩盖 bug + // Distinct key image per output so uniqueness issues do not mask bugs k[0] = (amount % 251) as u8; k[1] = (height % 251) as u8; k @@ -410,29 +409,28 @@ mod tests { db.conn().last_insert_rowid() } - /// 10 块锁定是共识规则,不是我们的策略 —— 未满 10 块的输出构不进环。 + /// The 10-block lock is consensus: younger outputs cannot be used in a ring. #[test] fn the_ten_block_lock_is_enforced() { - assert!(!is_unlocked(100, 0, 100), "同高度必然锁定"); - assert!(!is_unlocked(100, 0, 109), "差一块也是锁定"); - assert!(is_unlocked(100, 0, 110), "满 10 块解锁"); + assert!(!is_unlocked(100, 0, 100), "locked at the same height"); + assert!(!is_unlocked(100, 0, 109), "locked one block short"); + assert!(is_unlocked(100, 0, 110), "unlocked after 10 blocks"); } #[test] fn additional_block_timelock_is_honoured() { - // 额外锁到 200 块:即使过了 10 块锁也还不能花 + // Extra lock to height 200: still locked after the 10-block lock assert!(!is_unlocked(100, 200, 150)); assert!(is_unlocked(100, 200, 200)); } - /// 时间戳形式的时间锁光靠链高判断不了。保守当作仍锁定 —— 让用户等, - /// 好过让他构一笔必然被节点拒绝的交易。 + /// Timestamp timelocks cannot be judged from height; treat as locked. #[test] fn timestamp_timelocks_are_treated_as_locked() { assert!(!is_unlocked(100, 1_700_000_000, 999_999)); } - /// 不知道链尖时可用余额必须是 0,不能乐观放行。 + /// With an unknown chain tip the unlocked balance must be 0. #[test] fn unknown_chain_tip_means_nothing_is_spendable() { let (db, id) = db_with_identity(); @@ -442,8 +440,9 @@ mod tests { assert_eq!(b.unlocked_atomic, 0); } - /// 没 key image、又进过某个环的输出**可能已经被花掉**,必须单独报出来; - /// 从没进过环的一定没花(花它必然要把它放进环),不能算成待核实。 + /// Outputs without a key image seen in a ring **may be spent** and are + /// reported separately; never-ringed ones are certainly unspent (spending + /// requires a ring). #[test] fn only_outputs_seen_in_a_ring_are_pending_verification() { let (db, id) = db_with_identity(); @@ -461,11 +460,14 @@ mod tests { let b = balance(&db, id, Some(100)).unwrap(); assert_eq!(b.total_atomic, 1_200); assert_eq!(b.unverifiable_atomic, 200); - assert_eq!(b.unlocked_atomic, 1_000, "可能已花的不算可用"); + assert_eq!( + b.unlocked_atomic, 1_000, + "possibly spent outputs are not unlocked" + ); } - /// 被在途交易预留的输出仍计入总额,但不可再次选中 —— 不锁会让同一笔 - /// 输出被两笔交易同时花掉,第二笔必然被网络拒绝。 + /// Reserved outputs count toward total but are not selectable, so two + /// sends cannot spend the same output. #[test] fn reserved_outputs_are_excluded_from_unlocked_and_from_selection() { let (db, id) = db_with_identity(); @@ -484,11 +486,11 @@ mod tests { assert_eq!(b.unlocked_atomic, 400); let spendable = spendable_rows(&db, id, 100).unwrap(); - assert_eq!(spendable.len(), 1, "被预留的不能再被选中"); + assert_eq!(spendable.len(), 1, "reserved outputs must not be selected"); assert_eq!(spendable[0].amount_atomic, 400); } - /// 用户在确认页退出不会通知 runtime;过期的预留不能永远锁着钱。 + /// Abandoning the confirm screen does not notify the runtime; expired reservations must release funds. #[test] fn an_expired_reservation_no_longer_holds_its_outputs() { let (db, id) = db_with_identity(); @@ -506,7 +508,7 @@ mod tests { assert_eq!(spendable_rows(&db, id, 100).unwrap().len(), 1); } - /// 已花的输出不再计入任何口径。 + /// Spent outputs drop out of every balance figure. #[test] fn spent_outputs_leave_the_balance() { let (db, id) = db_with_identity(); @@ -518,8 +520,8 @@ mod tests { assert_eq!(b.total_atomic, 0); } - /// 自己广播还没上链的:时间取广播时间(不然每次读都是「现在」), - /// 金额取广播时记下的,失败要标出来。 + /// An unconfirmed own send reports its broadcast time (not "now"), the + /// recorded amount, and failure. #[test] fn a_pending_send_reports_its_broadcast_time_amount_and_failure() { let (db, id) = db_with_identity(); @@ -537,8 +539,7 @@ mod tests { assert_eq!(item["outgoingAtomic"], "1234"); } - /// 历史分页的上界必须有硬限制 —— 宿主传个巨大的 limit 会把整段历史读进 - /// 内存,那正是选 SQLite 要避免的。 + /// History page size has a hard cap. #[test] fn history_limit_is_clamped() { let (db, id) = db_with_identity(); diff --git a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs index ee210763d..03d509691 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs @@ -1,10 +1,8 @@ -//! 跨调用的会话状态。 +//! Session state across calls. //! -//! 按边界原则,wasm 侧**不持有会话状态** —— 唯一的例外是数据库连接和节点 -//! 客户端,因为每次调用都重开代价太高(重开要重跑一遍迁移检查)。 -//! -//! 除此之外没有缓存、没有定时器、没有后台任务。宿主每调一次,这里完整做完 -//! 一次并返回。 +//! The wasm side holds no session state except the database connection and +//! node client, which are too costly to reopen per call (migration checks). +//! No caches, timers or background tasks: each host call runs to completion. use std::cell::{Cell, RefCell}; @@ -16,26 +14,26 @@ use monero_wallet::address::Network; thread_local! { static DB: RefCell> = const { RefCell::new(None) }; static DAEMON: RefCell> = const { RefCell::new(None) }; - /// 当前节点所在的网络,连接时按创世块认定。与 DAEMON 同进同出。 + /// Network of the current node, from its genesis block at connect. Set and cleared with DAEMON. static DAEMON_NETWORK: Cell> = const { Cell::new(None) }; static DB_NAME: RefCell> = const { RefCell::new(None) }; - // ── 并发防线 ──────────────────────────────────────────────────────── + // ── Concurrency guards ────────────────────────────────────────────── // - // 异步操作会把 DB 从这里**取走**,跨 await 持有,结束后放回。这中间宿主 - // 完全可以再发起别的调用 —— wasm 是单线程,但 await 让重入变得可能。 + // Async operations take DB out of here across awaits and put it back + // after. wasm is single-threaded, but awaits allow re-entrant host calls. // - // 没有防线时的真实竞态: - // 1. A 在扫链,DB(A) 已被取走 - // 2. B 调 openWallet(B),DB_NAME 变成 B - // 3. A 结束,把 DB(A) 放回 —— 此刻 DB_NAME 说 B,实际却是 A - // 之后所有操作都在错误的库上进行,而且看不出来。 + // Race without guards: + // 1. A is scanning with DB(A) taken + // 2. B calls openWallet(B); DB_NAME becomes B + // 3. A finishes and puts DB(A) back, while DB_NAME says B + // Every later operation then silently hits the wrong database. static BUSY: Cell = const { Cell::new(false) }; static GENERATION: Cell = const { Cell::new(0) }; - // 节点客户端有**自己的**世代号。DB 那道防线盖不住它:换节点时不碰 DB, - // GENERATION 不动,于是一次在途的取链尖结束后会把旧节点原样盖回去, - // 之后所有请求都发给上一个节点。 + // The node client has its **own** generation. Switching nodes leaves DB + // and GENERATION untouched, so without it an in-flight tip fetch would + // restore the old node and route all later requests there. static DAEMON_GENERATION: Cell = const { Cell::new(0) }; } @@ -49,7 +47,7 @@ fn assert_idle(operation: &str) -> Result<()> { Ok(()) } -/// 持有期间标记 BUSY,析构时**一定**清除 —— 包括提前返回与 panic 展开。 +/// Sets BUSY while held; Drop **always** clears it, including early returns and panic unwinding. struct BusyGuard; impl BusyGuard { @@ -78,8 +76,8 @@ fn daemon_generation() -> u64 { DAEMON_GENERATION.with(Cell::get) } -/// 取走客户端前采样,放回前比对。不相等说明期间节点被换掉或关掉了, -/// 手上这个已经作废 —— 丢弃它,而不是覆盖当前的。 +/// `sampled` is taken before the client is borrowed. A mismatch means the node +/// was replaced or closed meanwhile, so drop the stale client instead. fn put_daemon_back(daemon: Daemon, sampled: u64) { if daemon_generation() == sampled { DAEMON.with(|c| *c.borrow_mut() = Some(daemon)); @@ -94,8 +92,8 @@ fn no_daemon() -> RuntimeError { RuntimeError::new(ErrorCode::NodeNotConfigured) } -/// 打开钱包。正在进行异步操作时会被拒绝 —— 中途换库会让那次操作把结果写到 -/// 错误的地方,而且没有任何迹象。 +/// Opens a wallet. Refused while an async operation is in flight, which would +/// otherwise silently write its results to the wrong database. pub fn set_db(db: Db, db_name: &str) -> Result<()> { assert_idle("openWallet")?; DB.with(|c| *c.borrow_mut() = Some(db)); @@ -110,8 +108,8 @@ pub fn set_daemon(daemon: Daemon, network: Network) { bump_daemon_generation(); } -/// 钱包库与节点必须在同一个网络上。不一致时什么都不做:测试网钱包连着主网 -/// 节点扫到的是真 XMR,发出去的也是。 +/// Wallet and node must be on the same network. A testnet wallet on a mainnet +/// node would scan and send real XMR. fn check_node_network(node: Option, wallet: Network) -> Result<()> { if node == Some(wallet) { return Ok(()); @@ -125,12 +123,12 @@ fn check_node_network(node: Option, wallet: Network) -> Result<()> { )) } -/// 当前节点所在的网络(连接时按创世块认定)。没有节点时为 `None`。 +/// Network of the current node (by genesis block at connect); `None` without a node. pub fn daemon_network() -> Option { DAEMON_NETWORK.with(Cell::get) } -/// 断开当前节点。借出中的客户端放回时按世代号作废,不会复活。 +/// Disconnects the node. A borrowed client is discarded on return via the generation check. pub fn clear_daemon() { DAEMON.with(|c| *c.borrow_mut() = None); DAEMON_NETWORK.with(|n| n.set(None)); @@ -141,7 +139,7 @@ pub fn open_db_name() -> Option { DB_NAME.with(|c| c.borrow().clone()) } -/// 关闭钱包,释放数据库与客户端。用于账户删除或切换网络。 +/// Closes the wallet, dropping the database and client. Used for account deletion or network switches. pub fn close() -> Result<()> { assert_idle("closeWallet")?; DB.with(|c| *c.borrow_mut() = None); @@ -153,7 +151,7 @@ pub fn close() -> Result<()> { Ok(()) } -/// 借出数据库做一次同步操作。 +/// Borrows the database for a synchronous operation. pub fn with_db(f: impl FnOnce(&mut Db) -> Result) -> Result { let _guard = BusyGuard::acquire("walletOperation")?; DB.with(|c| { @@ -163,7 +161,7 @@ pub fn with_db(f: impl FnOnce(&mut Db) -> Result) -> Result { }) } -/// 只读借出。 +/// Read-only borrow. pub fn with_db_read(f: impl FnOnce(&Db) -> Result) -> Result { DB.with(|c| { let slot = c.borrow(); @@ -172,10 +170,9 @@ pub fn with_db_read(f: impl FnOnce(&Db) -> Result) -> Result { }) } -/// 借出数据库与节点客户端做一次异步操作。 +/// Borrows the database and node client for an async operation. /// -/// 用「取出 → 使用 → 放回」而不是长期持有 `RefCell` 借用:异步过程中不持有 -/// 任何借用,这是在 wasm 单线程上跨 await 安全共享状态的关键。 +/// Take, use, put back: no `RefCell` borrow is held across awaits. pub async fn with_db_and_daemon(f: F) -> Result where F: FnOnce(Db, Daemon) -> Fut, @@ -201,8 +198,8 @@ where let (db, daemon, out) = f(db, daemon).await; - // 期间钱包被换掉/关掉时,**丢弃**手上这个而不是放回去。 - // 放回去等于让一个已经作废的钱包覆盖当前的,那正是串库的源头。 + // If the wallet was replaced or closed meanwhile, **drop** this one; + // putting it back would overwrite the current wallet. if GENERATION.with(Cell::get) != generation { drop(db); } else { @@ -213,9 +210,9 @@ where out } -/// 只借出节点客户端,**不要求钱包库已打开**。 +/// Borrows only the node client; **no wallet needs to be open**. /// -/// 建账户时链尖是先决条件:宿主要用它定 birthday,而那一刻库还没建。 +/// Account creation needs the chain tip for the birthday before the database exists. pub async fn with_daemon(f: F) -> Result where F: FnOnce(Daemon) -> Fut, @@ -235,11 +232,11 @@ mod tests { use super::*; use monero_wallet::address::Network; - // 测试各跑在自己的线程上,thread_local 天然隔离,互不干扰。 + // Each test runs on its own thread, so thread_locals are isolated. fn open_memory_db() { - let db = Db::open(":memory:", Network::Mainnet).expect("内存库"); - set_db(db, ":memory:").expect("开库"); + let db = Db::open(":memory:", Network::Mainnet).expect("in-memory db"); + set_db(db, ":memory:").expect("open db"); } #[test] @@ -260,33 +257,33 @@ mod tests { ); } - /// 借出期间不许换库。换了会让那次操作把结果写到错误的地方,而且没有 - /// 任何迹象 —— 这是最难查的一类 bug。 + /// The wallet cannot be switched while borrowed, or the operation would + /// silently write to the wrong database. #[test] fn switching_the_wallet_is_refused_while_an_operation_holds_it() { open_memory_db(); let result = with_db(|_| { - // 模拟「操作进行中,宿主又来开库」 - let db2 = Db::open(":memory:", Network::Mainnet).expect("第二个库"); + // Host opens a wallet while an operation is in progress + let db2 = Db::open(":memory:", Network::Mainnet).expect("second db"); Ok(set_db(db2, "other").map(|_| ()).unwrap_err().code) }) .unwrap(); assert_eq!(result, ErrorCode::WalletBusy); } - /// 守卫析构时一定清 BUSY —— 包括提前返回那条路。否则一次失败会把 - /// runtime 永久卡在 BUSY,表现为「之后什么都做不了」。 + /// The guard clears BUSY on the error path too; otherwise one failure + /// would wedge the runtime in BUSY forever. #[test] fn the_busy_flag_is_cleared_even_when_the_operation_fails() { open_memory_db(); let _ = with_db(|_| -> Result<()> { Err(RuntimeError::new(ErrorCode::InvalidRequest)) }); - assert!(!BUSY.with(Cell::get), "失败路径也必须清 BUSY"); - // 清干净了才能接着用 - with_db(|_| Ok(())).expect("失败之后应当还能继续操作"); + assert!(!BUSY.with(Cell::get), "BUSY must be cleared on failure"); + // Usable again afterwards + with_db(|_| Ok(())).expect("operations should work after a failure"); } - /// 没配节点时,要求节点的操作必须报 NODE_NOT_CONFIGURED, - /// 而不是笼统的网络错误 —— 两者的处置完全不同。 + /// Without a node, node operations report NODE_NOT_CONFIGURED rather than a + /// generic network error; the host handles them differently. #[test] fn daemon_operations_report_a_missing_node_distinctly() { open_memory_db(); @@ -295,9 +292,9 @@ mod tests { })) .unwrap_err(); assert_eq!(e.code, ErrorCode::NodeNotConfigured); - // 借不到客户端时 DB 必须被放回去,否则钱包就凭空关了 - assert!(open_db_name().is_some(), "失败不该顺手把库弄丢"); - with_db_read(|_| Ok(())).expect("库应当还在"); + // DB must be put back when no client is available, or the wallet silently closes + assert!(open_db_name().is_some(), "failure must not drop the db"); + with_db_read(|_| Ok(())).expect("db should still be open"); } #[test] @@ -313,17 +310,21 @@ mod tests { } } - /// 关库必须让在途的客户端借用作废。否则它结束时会把旧节点盖回去, - /// 之后所有请求都发给上一个节点。 + /// Closing invalidates an in-flight client borrow, so it cannot restore + /// the old node when it finishes. #[test] fn closing_invalidates_an_in_flight_daemon_borrow() { let sampled = daemon_generation(); - assert_eq!(daemon_generation(), sampled, "无事发生时采样应稳定"); - close().expect("空状态下关闭应当成功"); + assert_eq!( + daemon_generation(), + sampled, + "generation is stable when nothing happens" + ); + close().expect("close should succeed on empty state"); assert_ne!( daemon_generation(), sampled, - "close 之后在途借用必须被判作废" + "in-flight borrow must be invalid after close" ); } } diff --git a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs index 7e8cca006..8fd560285 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs @@ -1,34 +1,35 @@ -//! 扫描:把区块喂给 monero-oxide 的 `Scanner`,把产出落进 SQLite。 +//! Scanning: feeds blocks to the monero-oxide `Scanner` and persists results to SQLite. //! -//! ## 有界推进 +//! ## Bounded steps //! -//! 这里**永远不会**自己循环到同步完成。调用方给一批块、拿一个结果,要不要 -//! 接着扫由宿主决定 —— 这正是「调度归 TS」那条边界。理由和 Zcash 那边一样: -//! 跑到底的函数在浏览器和移动端上无法中断、无法看进度、无法让出主线程。 +//! Never loops to full sync. The caller passes a batch and gets one result; the +//! host decides whether to continue, since a run-to-completion call cannot be +//! interrupted, report progress, or yield the main thread on web and mobile. //! -//! ## 三道校验,每一道都有具体的失败故事 +//! ## Three checks //! -//! 1. **块连续性** —— `header.previous` 必须等于我们记录的上一块哈希。对不上 -//! 就是重组(或节点在骗人),向上报 `REORG_DETECTED` 带精确高度。 +//! 1. **Block continuity**: `header.previous` must equal the recorded previous +//! hash. A mismatch is a reorg (or a lying node), reported as +//! `REORG_DETECTED` with the exact height. //! -//! 2. **RingCT 输出索引** —— 上游 `ScannableBlock` 的文档明确写着 -//! `output_index_for_first_ringct_output` **无法验证**,并要求客户端自己维护 -//! 这个索引、与节点声称的比对,不一致应当断开。这里就是那个自己维护的实现: -//! 扫完一块后按「本块 v2 交易的输出总数」推进游标,下一块拿它对账。 -//! 索引错了的后果是构环时取错输出,交易被网络拒绝 —— 而且很难从现象反推。 +//! 2. **RingCT output index**: upstream `ScannableBlock` documents that +//! `output_index_for_first_ringct_output` cannot be verified and the client +//! must track and compare it. The cursor advances by the block's v2 output +//! count and the next block is checked against it. A wrong index picks the +//! wrong ring members and the transaction is rejected. //! -//! 3. **批内高度递增** —— 节点乱序返回时直接拒绝,不要试图自己排序: -//! 能乱序就说明对端不可信,排好序继续扫等于替它掩盖问题。 +//! 3. **Increasing heights within a batch**: out-of-order blocks are rejected, +//! not sorted, because an out-of-order peer is untrusted. //! -//! ## 花费检测的协议限制 +//! ## Spend detection limits //! -//! Monero 的观察钱包**无法独立判断自己的输出有没有被花掉** —— 判断需要 -//! key image,而 key image 需要花费私钥。这不是实现取舍,是协议性质。 +//! A view-only wallet cannot tell whether its outputs were spent: that needs +//! key images, which need the private spend key. This is a protocol property. //! -//! 所以这里的做法是:`outputs.key_image` 由宿主通过 [`crate::spend::import_key_images`] -//! 在解锁时补齐;扫描时拿已知的 key image 去撞链上交易的输入。没补齐 key image -//! 的输出**检测不到花费**,余额会偏高 —— 这一点必须让宿主知道,见 -//! [`ScanOutcome::outputs_without_key_image`]。 +//! The host fills `outputs.key_image` via [`crate::spend::import_key_images`] +//! on unlock; scanning matches known key images against transaction inputs. +//! Outputs without a key image cannot be detected as spent, so the balance may +//! be overstated; see [`ScanOutcome::outputs_without_key_image`]. use std::collections::{HashMap, HashSet}; @@ -45,10 +46,10 @@ use crate::error::{db_err, ErrorCode, Result, RuntimeError}; use crate::schema::REORG_WINDOW_BLOCKS; use crate::wallet::Db; -/// 检测到重组时建议回退多少块。 +/// Suggested rewind depth on a detected reorg. /// -/// Monero 的重组极少超过几块;退太多让用户重扫大段历史,退太少可能没退到 -/// 分叉点之前、下一轮继续撞同一个错。宿主在重复失败时应自行加大。 +/// Monero reorgs rarely exceed a few blocks. Too deep forces a long rescan; too +/// shallow may not pass the fork point. The host should increase it on repeated failures. pub const REORG_REWIND_BLOCKS: u64 = 10; #[derive(Debug, Default, Clone)] @@ -56,25 +57,25 @@ pub struct ScanOutcome { pub blocks_scanned: u64, pub outputs_found: usize, pub spends_detected: usize, - /// 本批记下的「可能的花费」条数(环里含我的、还不知道 key image 的输出)。 + /// Possible spends recorded in this batch (our outputs without a key image seen in a ring). pub possible_spends: usize, pub from_height: Option, pub to_height: Option, - /// 还没有 key image 的输出数。**大于 0 意味着余额可能偏高** —— - /// 这些输出即使已经被花掉,扫描也检测不出来。 + /// Outputs without a key image. Greater than 0 means the balance may be + /// overstated: spends of these outputs cannot be detected. pub outputs_without_key_image: i64, - /// 拉块耗时(毫秒)。与 `ms_scan` 分开报,因为「网络慢」和「解密慢」 - /// 在界面上长得一模一样,但结论完全相反。 + /// Block download time in ms. Reported apart from `ms_scan` to tell a slow + /// network from slow decryption. pub ms_download: u32, - /// 试解密与落库耗时(毫秒)。 + /// Trial decryption and persistence time in ms. pub ms_scan: u32, - /// 这一批块是怎么取来的:`blocksBin`(一次批量)或 `perBlock`(逐块并发)。 + /// How the batch was fetched: `blocksBin` (one bulk request) or `perBlock` (concurrent per block). pub fetched_via: &'static str, - /// 批量路径这一步被放弃的原因。只在放弃发生的那一步出现。 + /// Why the bulk path was abandoned; set only on the step where that happened. pub fetch_note: Option, - /// 这一步的第一批是否直接用上了上一步预取的请求。 + /// Whether this step's first batch used the request prefetched by the previous step. pub prefetch_hit: bool, - /// 这一步之后的批量大小(下一个请求要多少块)。 + /// Batch size after this step (blocks in the next request). pub batch_blocks: u64, } @@ -98,10 +99,10 @@ impl ScanOutcome { } } -/// 本块里 RingCT 输出的数量。 +/// Number of RingCT outputs in the block. /// -/// 只有 v2 交易能产出 RingCT 输出(v1 不能),矿工交易也算在内且排在最前。 -/// 这是我们**独立于节点**推算全局输出序号的依据 —— 上游要求客户端这么做。 +/// Only v2 transactions produce RingCT outputs; the miner transaction counts +/// and comes first. Used to derive global output indices independently of the node. fn ringct_output_count(block: &ScannableBlock) -> u64 { fn count(tx: &Transaction) -> u64 { match tx { @@ -112,17 +113,17 @@ fn ringct_output_count(block: &ScannableBlock) -> u64 { count(block.block.miner_transaction()) + block.transactions.iter().map(count).sum::() } -/// 本块所有交易输入里的 key image,连同它所属交易的 txid。 +/// Key images of all inputs in the block, with the txid of their transaction. /// -/// txid 取自 `block.block.transactions`(块头里的 txid 列表),它与 -/// `block.transactions`(交易体)一一对应且同序 —— 上游的 -/// `expand_to_scannable_block` 就是按这个列表去拉的交易体。 +/// Txids come from `block.block.transactions`, which matches +/// `block.transactions` one to one and in order (upstream +/// `expand_to_scannable_block` fetches bodies from that list). /// -/// **不能用 `Transaction::hash()`**:这里的交易是 `Pruned` 形态,V2 交易算 -/// 哈希需要 prunable hash,而裁剪掉的正是它。 +/// Not `Transaction::hash()`: these are `Pruned` transactions, and a V2 hash +/// needs the prunable hash that was pruned. /// -/// 两个列表长度对不上说明节点给的块自相矛盾,直接拒绝而不是凑合对齐 —— -/// 错位会把花费记到别人的交易上。 +/// A length mismatch means an inconsistent block and is rejected; misalignment +/// would attribute spends to the wrong transaction. fn key_images_in(block: &ScannableBlock) -> Result> { if block.block.transactions.len() != block.transactions.len() { return Err(RuntimeError::with( @@ -152,9 +153,9 @@ fn key_images_in(block: &ScannableBlock) -> Result> { Ok(out) } -/// 块里每个输入引用的环:`(key image, 所在交易, 金额类, 环成员的绝对全局序号)`。 +/// Rings referenced by each input: `(key image, txid, amount pool, absolute global member indices)`. /// -/// `key_offsets` 是相对差分:第一个是绝对序号,之后每个是与前一个的间隔。 +/// `key_offsets` are deltas: the first is absolute, each next is relative to the previous. fn ring_references_in(block: &ScannableBlock) -> Vec { let mut out = Vec::new(); for (txid, tx) in block @@ -188,7 +189,7 @@ fn ring_references_in(block: &ScannableBlock) -> Vec { out } -/// 一条可能的花费:我的某笔输出出现在某个输入的环里。 +/// A possible spend: one of our outputs appears in an input's ring. struct PossibleSpend { out_txid: [u8; 32], out_index: u64, @@ -201,13 +202,13 @@ struct PossibleSpend { struct RingReference { key_image: [u8; 32], spend_txid: [u8; 32], - /// `None`/`Some(0)`:RingCT 池;其余为老式按金额分池(2017 年前)。 + /// `None`/`Some(0)`: RingCT pool; otherwise a pre-2017 per-amount pool. amount: Option, members: Vec, } -/// 还没有 key image 的未花输出,按全局序号索引:`(txid, index_in_tx, 金额)`。 -/// 只有它们需要「可能的花费」—— 有 key image 的由正常的花费检测负责。 +/// Unspent outputs without a key image, by global index: `(txid, index_in_tx, amount)`. +/// Only these need possible spends; outputs with a key image use normal spend detection. type RingCandidates = HashMap>; fn load_ring_candidates(db: &Db, identity_id: i64) -> Result { @@ -239,8 +240,9 @@ fn load_ring_candidates(db: &Db, identity_id: i64) -> Result { Ok(map) } -/// 一个输入的环里含我的哪些输出。老式按金额分池的输出还要金额相同才算; -/// RingCT 输入只按序号 —— 多报只会多一条「可能」,漏报才会让花费认不出。 +/// Our outputs in an input's ring. Pre-RingCT inputs also require a matching +/// amount; RingCT inputs match by index only, since a false positive is +/// harmless and a miss hides a spend. fn ring_matches<'a>( candidates: &'a RingCandidates, reference: &'a RingReference, @@ -254,24 +256,22 @@ fn ring_matches<'a>( .filter(move |(_, _, amount)| pool.is_none_or(|p| p == *amount)) } -/// 每条交易的公钥:`(R, additional)`,按 txid 索引。 +/// Transaction public keys `(R, additional)` by txid. /// -/// ## 为什么要单独留一份 +/// ## Why kept separately /// -/// monero-oxide 把「R + 输出序号 + 子地址」整条推导折叠成 `WalletOutput` 上的 -/// 一个 `key_offset` 标量,**然后就把 R 丢了**。软件签名只要 -/// `spend + key_offset`,所以缺了也看不出来。 +/// monero-oxide folds the R + output index + subaddress derivation into a +/// `key_offset` scalar on `WalletOutput` and drops R. Software signing only +/// needs `spend + key_offset`. /// -/// 固件不接受 `key_offset`。它要 `real_out_tx_key` 自己推导一次性私钥和 -/// key image —— 接受宿主算好的偏移量,等于让一个恶意宿主指挥设备拿任意密钥 -/// 签名。所以硬件那条路必须有 R。 +/// Firmware does not accept `key_offset`; it derives the one-time key and key +/// image from `real_out_tx_key` itself, since accepting a host-computed offset +/// would let a malicious host make the device sign with any key. /// -/// 而 R 只在扫描这一刻手里有:事后要么全量重扫,要么拿 txid 去找节点要回那条 -/// 交易 —— 后者等于直接告诉节点「我对这笔感兴趣」,把扫全链换来的隐私当场 -/// 还回去。所以在这里留下来,哪怕现在还没有硬件可接。 +/// R is only available at scan time; recovering it later needs a full rescan +/// or asking the node for the transaction by txid, which leaks interest in it. fn tx_public_keys_in(block: &ScannableBlock) -> Vec<([u8; 32], Vec, Option>)> { - // 长度不齐的情况由 `key_images_in` 统一报错;这里取不到就跳过, - // 不重复报同一个错。 + // Length mismatches are reported by `key_images_in`; skip here. let mut out = Vec::new(); for (txid, tx) in block .block @@ -286,10 +286,10 @@ fn tx_public_keys_in(block: &ScannableBlock) -> Vec<([u8; 32], Vec, Option Option<(Vec, Option>)> { fn flatten(points: &[monero_wallet::ed25519::Point]) -> Vec { let mut out = Vec::with_capacity(points.len() * 32); @@ -304,9 +304,9 @@ fn tx_public_keys_from_extra(extra: &[u8]) -> Option<(Vec, Option>)> Some((flatten(&keys), additional.as_deref().map(flatten))) } -/// 扫描一批块并落库。**整批一个事务**:要么全成,要么一块都不留。 +/// Scans and persists a batch of blocks in one transaction: all or nothing. /// -/// 块必须按高度升序、且彼此连续。调用方(宿主)负责按区间取块。 +/// Blocks must be contiguous in ascending height. The host fetches them by range. pub fn scan_blocks( db: &mut Db, identity_id: i64, @@ -323,34 +323,34 @@ pub fn scan_blocks( let mut scanner = Scanner::new(identity.view_pair.clone()); for (major, minor) in &subaddresses { - // (0,0) 进不了库(schema 有 CHECK),所以这里 None 不可能发生; - // 真发生了说明有人绕过了约束直接写库,宁可跳过也不要 panic。 + // The schema CHECK excludes (0,0), so None means the constraint was + // bypassed; skip rather than panic. if let Some(index) = SubaddressIndex::new(*major, *minor) { scanner.register_subaddress(index); } } - // 我们自己维护的 key image 集合,用于花费检测。 + // Known key images, for spend detection. let known_key_images = load_key_images(db, identity_id)?; - // 还不知道 key image 的输出,用环成员比对记下「可能的花费」。 + // Outputs without a key image, matched against ring members as possible spends. let mut ring_candidates = load_ring_candidates(db, identity_id)?; let mut possible_spends: Vec = Vec::new(); let mut outcome = ScanOutcome::default(); let mut found: Vec<(u64, WalletOutput)> = Vec::new(); - // txid -> (R, additional)。只留我们真正收到输出的那些交易的。 + // txid -> (R, additional), only for transactions that paid us. let mut tx_pub_keys: HashMap<[u8; 32], (Vec, Option>)> = HashMap::new(); let mut spends: Vec<(u64, [u8; 32], [u8; 32])> = Vec::new(); // (height, key_image, txid) let mut block_rows: Vec<(u64, [u8; 32], Option, u64)> = Vec::new(); // (height, hash, ringct_next, ts) - // 批起点的前一块:用于连续性与 RingCT 游标对账。 + // Block before the batch start, for continuity and RingCT cursor checks. let first_height = blocks[0].block.number() as u64; let mut prev = previous_block_state(db, identity_id, first_height)?; for block in blocks { let height = block.block.number() as u64; - // ── 1. 批内必须严格递增且连续 ────────────────────────────────── + // ── 1. Heights must be strictly increasing and contiguous ───────── if let Some((prev_height, _, _)) = prev { if height != prev_height + 1 { return Err(RuntimeError::with( @@ -364,7 +364,7 @@ pub fn scan_blocks( } } - // ── 2. 前驱哈希对账 —— 重组检测 ──────────────────────────────── + // ── 2. Previous hash check: reorg detection ────────────────────── if let Some((_, prev_hash, _)) = prev { if block.block.header.previous != prev_hash { return Err(RuntimeError::with( @@ -377,7 +377,7 @@ pub fn scan_blocks( } } - // ── 3. RingCT 索引对账 —— 上游要求客户端独立维护并比对 ───────── + // ── 3. RingCT index check (upstream requires client-side tracking) ─ if let (Some((_, _, Some(expected_next))), Some(claimed)) = (prev, block.output_index_for_first_ringct_output) { @@ -399,19 +399,18 @@ pub fn scan_blocks( RuntimeError::with(ErrorCode::ScanFailed, json!({ "height": height })) .detail(format!("{e:?}")) })? - // 额外时间锁由查询层按当前链高判断,这里全部收下 —— - // 丢掉锁定中的输出会让它们永远不再出现(我们不会重扫这一段)。 + // Timelocks are evaluated by the query layer against the current + // height; dropping locked outputs here would lose them for good. .ignore_additional_timelock(); if !outputs.is_empty() { - // 只在这一块确实有我们的输出时才解析 extra —— 绝大多数块一个都 - // 没有,为它们全量解析是白花 CPU。 + // Parse extra only for blocks that paid us; most blocks do not. for (txid, keys, additional) in tx_public_keys_in(block) { tx_pub_keys.insert(txid, (keys, additional)); } } - // 先比对本块的输入,再把本块收到的钱加进候选:刚收到的钱至少锁 10 块, - // 不可能在同一块被花。 + // Match inputs before adding this block's outputs as candidates: new + // outputs are locked for at least 10 blocks and cannot be spent in the same block. for reference in ring_references_in(block) { if known_key_images.contains_key(&reference.key_image) { continue; @@ -441,15 +440,14 @@ pub fn scan_blocks( for (key_image, txid) in key_images_in(block)? { if known_key_images.contains_key(&key_image) { - // txid 必须是**花费这笔输出的那条交易**,不是块哈希 —— - // 记错了历史详情会指向一条不相干的交易。 + // The spending transaction's txid, not the block hash. spends.push((height, key_image, txid)); } } - // 游标的依据:优先用上一块推出来的,其次用节点声称的起点。 - // 两者都没有时**保持未知**,绝不退化成 0 —— 那会让下一块的对账 - // 拿真实序号去比 0,报出一个假的 RINGCT_INDEX_MISMATCH。 + // Cursor base: the previous block's cursor, else the node's claimed + // start. With neither, stay unknown; falling back to 0 would raise a + // false RINGCT_INDEX_MISMATCH on the next block. let next_ringct = prev .and_then(|(_, _, n)| n) .or(block.output_index_for_first_ringct_output) @@ -485,7 +483,7 @@ pub fn scan_blocks( Ok(outcome) } -/// 取某高度前一块的 (高度, 哈希, 扫完后的 RingCT 游标)。 +/// (height, hash, RingCT cursor after it) of the block before `height`. fn previous_block_state( db: &Db, identity_id: i64, @@ -509,13 +507,14 @@ fn previous_block_state( .map_err(|e| db_err("previousBlockState", e))? .map(|(h, hash, next)| { let hash = <[u8; 32]>::try_from(hash.as_slice()) - .map_err(|_| db_err("previousBlockState", "块哈希长度不是 32"))?; + .map_err(|_| db_err("previousBlockState", "block hash is not 32 bytes"))?; Ok((h, hash, next)) }) .transpose() } -/// 未花的,加上被自己广播、还没上链的交易花掉的:后者上链时要靠 key image 命中才能确认。 +/// Unspent outputs plus those spent by our own unconfirmed broadcasts, which +/// are confirmed by a key image match once mined. fn load_key_images(db: &Db, identity_id: i64) -> Result> { let mut stmt = db .conn() @@ -571,7 +570,8 @@ fn persist( .map_err(|e| db_err("beginScanCommit", e))?; let mut seen_txids: HashSet<[u8; 32]> = HashSet::new(); - // 交易时间跟交易行一起存:块表会裁剪到链尖附近,回补扫到的交易一旦所在块被裁,联表就拿不到时间。 + // Store the time on the transaction row: `blocks` is pruned near the tip, + // so backfilled transactions cannot join for it later. let block_time: HashMap = block_rows .iter() .map(|(h, _, _, ts)| (*h, *ts as i64)) @@ -590,8 +590,8 @@ fn persist( )? { continue; } - // `INSERT OR IGNORE`:重扫同一段区间必须幂等,否则余额翻倍。 - // 唯一约束是 (identity_id, txid, index_in_tx)。 + // `INSERT OR IGNORE`: rescans must be idempotent or balances double. + // Unique key is (identity_id, txid, index_in_tx). tx.execute( "INSERT OR IGNORE INTO outputs (identity_id, blob, txid, global_index, index_in_tx, amount_atomic, @@ -661,7 +661,7 @@ fn persist( .map_err(|e| db_err("insertOutgoingTransaction", e))?; } - // 幂等:重扫同一段会遇到同样的环引用。 + // Idempotent: rescans hit the same ring references. for ps in possible_spends { tx.execute( "INSERT OR IGNORE INTO possible_spends @@ -695,9 +695,7 @@ fn persist( .map_err(|e| db_err("insertBlock", e))?; } - // 裁剪块表:只留链尖往前 REORG_WINDOW_BLOCKS 块。 - // 不裁剪的话这张表会随链高无限增长 —— 那正是我们批评 wallet2 内存模型 - // 时说的那件事,自己不能犯。 + // Keep only REORG_WINDOW_BLOCKS below the tip so the table does not grow with the chain. if let Some((tip, _, _, _)) = block_rows.last() { let floor = tip.saturating_sub(REORG_WINDOW_BLOCKS); tx.execute( @@ -710,9 +708,9 @@ fn persist( tx.commit().map_err(|e| db_err("commitScan", e)) } -/// 燃烧 bug:同一个一次性公钥出现在另一笔输出里。它们只有一笔能花(花一笔就烧掉 -/// 其余),所以只认最先看到的那笔,后来的不入账 —— 宁可少算,不能把花不掉的钱 -/// 算进余额。同一笔输出重扫不算重复。 +/// Burning bug: the same one-time key in another output. Only one is spendable, +/// so only the first seen is counted, never overstating the balance. A rescan +/// of the same output is not a duplicate. fn is_burning_duplicate( conn: &rusqlite::Connection, identity_id: i64, @@ -744,19 +742,20 @@ fn timelock_to_i64(timelock: monero_wallet::transaction::Timelock) -> i64 { } } -/// 回退到指定高度:丢掉该高度**之上**的全部扫描结果。 +/// Rewinds to `height`, dropping all scan results above it. /// -/// **破坏性。** 用于重组恢复。例外是自己广播过的交易:它所在的块被重组掉, -/// 交易通常回到交易池、稍后重新上链。删掉它会让它花的输入重新可选,用户 -/// 换一批输入再发一次,两笔都上链。所以它退回在途(高度清空),输入保持 -/// 已花,交给在途检查与扫描判定。 +/// Destructive; used for reorg recovery. Our own broadcasts are kept: a +/// reorged-out send usually returns to the pool and is mined again, and +/// releasing its inputs could let a second send with other inputs also confirm. +/// They revert to pending (height cleared) with inputs still spent, left to +/// the pending check and scanning. pub fn rewind_to(db: &mut Db, identity_id: i64, height: u64) -> Result<()> { let tx = db .conn_mut() .transaction() .map_err(|e| db_err("beginRewind", e))?; - // 放在撤销花费标记之前:下面那条按「在途交易」保留标记。 + // Must run before clearing spend marks: that step keeps marks for pending transactions. tx.execute( "UPDATE transactions SET height = NULL, failed = 0, pool_checked_at = NULL WHERE identity_id = ?1 AND height > ?2 AND sent_at IS NOT NULL", @@ -770,8 +769,8 @@ pub fn rewind_to(db: &mut Db, identity_id: i64, height: u64) -> Result<()> { ) .map_err(|e| db_err("rewindOutputs", e))?; - // 花费标记也要撤销:那笔花费所在的块可能已经不在链上了。 - // 自己广播、还没上链的不撤:它的高度只是广播时的链尖,撤了会被再次选中。 + // Clear spend marks above the height, except for our pending sends: their + // height is only the tip at broadcast, and clearing would make the inputs selectable again. tx.execute( "UPDATE outputs SET spent_at_height = NULL, spent_in_txid = NULL WHERE identity_id = ?1 AND spent_at_height > ?2 @@ -807,33 +806,33 @@ mod tests { use super::*; use crate::wallet::testing::db_with_identity; - /// 用真实主网块验证环引用的换算:相对差分要累加成严格递增的绝对序号, - /// 当前共识环大小 16,全部是 RingCT 输入。 + /// On real mainnet blocks, ring offsets resolve to strictly increasing + /// absolute indices; ring size is 16 and all inputs are RingCT. #[test] fn ring_references_resolve_to_increasing_absolute_positions_on_real_blocks() { let blocks = crate::blocks_bin::parse_response( include_bytes!("../tests/fixtures/get_blocks_bin_3768621.bin"), 3_768_621, ) - .expect("解析真实响应"); + .expect("parse real response"); let references: Vec = blocks.iter().flat_map(ring_references_in).collect(); assert!(!references.is_empty()); let mut key_images = HashSet::new(); for reference in &references { assert_eq!(reference.members.len(), 16); assert!(reference.members.windows(2).all(|w| w[0] < w[1])); - assert_eq!(reference.amount.unwrap_or(0), 0, "RingCT 输入"); - assert!(key_images.insert(reference.key_image), "key image 不应重复"); + assert_eq!(reference.amount.unwrap_or(0), 0, "RingCT input"); + assert!(key_images.insert(reference.key_image), "unique key images"); } - // 我的一笔输出若恰好是某个环的成员,就被记为可能的花费。 + // An output of ours that is a ring member is a possible spend. let target = &references[0]; let mut candidates = RingCandidates::new(); candidates.insert(target.members[5], vec![([7; 32], 1, 12_345)]); assert_eq!(ring_matches(&candidates, target).count(), 1); } - /// 老式按金额分池的输入,序号只在同一金额池内有意义。 + /// Pre-RingCT input indices are only meaningful within the same amount pool. #[test] fn a_pre_ringct_input_matches_only_outputs_of_its_amount() { let reference = RingReference { @@ -850,15 +849,12 @@ mod tests { } use rusqlite::params; - /// 真实主网交易向量。 + /// Real mainnet vector. /// - /// 取自 mainnet 高度 3767756 的交易 - /// `097edcb40a4345c0e83c41e8631b9e71173389270694e7a7499d3c2fa17951bb`。 - /// 结构是 `01`(TxPublicKey) + 32 字节 R + `02 09 01`(Nonce/加密 payment id) - /// + 8 字节。 - /// - /// 用真数据而不是自己拼一个 extra:自己拼只会测到我们对格式的理解, - /// 而这里要证明的恰恰是对真实链上数据的理解没错。 + /// Transaction + /// `097edcb40a4345c0e83c41e8631b9e71173389270694e7a7499d3c2fa17951bb` + /// at mainnet height 3767756. Layout: `01` (TxPublicKey) + 32-byte R + + /// `02 09 01` (nonce / encrypted payment id) + 8 bytes. #[test] fn the_transaction_public_key_is_read_from_a_real_mainnet_extra() { let extra = hex::decode( @@ -867,32 +863,28 @@ mod tests { ) .unwrap(); - let (keys, additional) = tx_public_keys_from_extra(&extra).expect("应当解析出交易公钥"); + let (keys, additional) = tx_public_keys_from_extra(&extra).expect("parse tx public key"); assert_eq!( hex::encode(&keys), "d3c8b566d9fd0bff3f93448591ec257cc8bf813e1aaa808e97254a5c65ea1660" ); - assert_eq!(keys.len(), 32, "单个 R 就是 32 字节,不要多也不要少"); - // 这笔交易发给主地址,没有 additional keys。空 Vec 和 None 是两回事: - // 前者表示「有 0 个」,后者表示「没有这个字段」。 + assert_eq!(keys.len(), 32, "a single R is exactly 32 bytes"); + // Sent to a primary address, so no additional keys: None, not an empty Vec. assert_eq!(additional, None); } - /// 空 extra 不是错误,只是没有公钥 —— 不能 panic,也不能当成解析失败去 - /// 中断整批扫描。 + /// An empty extra has no keys; it must not panic or abort the batch. #[test] fn an_extra_without_keys_yields_nothing_rather_than_failing() { assert!(tx_public_keys_from_extra(&[]).is_none()); } - /// **回归测试。** RingCT 游标曾经在「没有依据」时退化成 0。 - /// - /// 触发路径:从链中段开始扫,而起始块恰好没有 RingCT 输出(节点因此给的 - /// `output_index_for_first_ringct_output` 是 None)。游标存成 0 之后, - /// 下一块拿真实序号(几千万)来比对 0,报出一个**假的** - /// `RINGCT_INDEX_MISMATCH` —— 把一个诚实的节点判成作恶,扫描直接卡死。 + /// An unknown RingCT cursor is stored as NULL, not 0. /// - /// 正确行为:没有依据就存 NULL,对账跳过,等拿到真实锚点再开始比。 + /// Starting mid-chain at a block without RingCT outputs leaves + /// `output_index_for_first_ringct_output` as None. Storing 0 would raise a + /// false `RINGCT_INDEX_MISMATCH` against an honest node on the next block; + /// NULL skips the check until a real anchor is known. #[test] fn an_unknown_ringct_cursor_is_stored_as_null_not_zero() { let (db, id) = db_with_identity(); @@ -902,16 +894,16 @@ mod tests { VALUES (?1, ?2, ?3, NULL, 0)", params![id, 3_000_000i64, &vec![7u8; 32]], ) - .expect("游标应当允许 NULL"); + .expect("cursor should allow NULL"); - let prev = previous_block_state(&db, id, 3_000_001).expect("读前一块"); - let (height, _, cursor) = prev.expect("前一块应当在"); + let prev = previous_block_state(&db, id, 3_000_001).expect("read previous block"); + let (height, _, cursor) = prev.expect("previous block should exist"); assert_eq!(height, 3_000_000); - assert_eq!(cursor, None, "未知必须是 None,不能是 Some(0)"); + assert_eq!(cursor, None, "unknown must be None, not Some(0)"); } - /// 一个身份回滚不能动另一个身份的锚点:否则另一个身份在新链上接着扫, - /// 看不出重组,孤块里的钱留在余额里。 + /// One identity's rewind must not touch another's anchors, or the other + /// would miss the reorg and keep orphaned funds in its balance. #[test] fn one_identity_rewinding_leaves_the_others_anchors_alone() { let (mut db, a) = db_with_identity(); @@ -956,12 +948,12 @@ mod tests { assert!(is_burning_duplicate(db.conn(), id, &key, &[2u8; 32], 0).unwrap()); assert!( !is_burning_duplicate(db.conn(), id, &key, &[1u8; 32], 0).unwrap(), - "同一笔重扫不算" + "rescanning the same output is not a duplicate" ); assert!(!is_burning_duplicate(db.conn(), id, &[5u8; 32], &[2u8; 32], 0).unwrap()); } - /// 有依据时游标正常推进。 + /// A known cursor round-trips. #[test] fn a_known_ringct_cursor_round_trips() { let (db, id) = db_with_identity(); @@ -976,7 +968,7 @@ mod tests { assert_eq!(cursor, Some(82_000_000)); } - /// 回补扫到的交易,所在块随后被裁出块表,时间也不能丢(否则界面显示 1970)。 + /// A backfilled transaction keeps its time after its block is pruned (otherwise the UI shows 1970). #[test] fn a_transaction_keeps_its_time_after_its_block_is_pruned() { let (mut db, id) = db_with_identity(); @@ -1008,14 +1000,14 @@ mod tests { |r| r.get(0), ) .unwrap(); - assert_eq!(pruned, 0, "块本身应当已被裁掉"); + assert_eq!(pruned, 0, "the block itself should be pruned"); let history = crate::query::history(&db, id, 10, 0).unwrap(); assert_eq!(history["items"][0]["timestamp"], 1_700_000_000); } - /// 自己广播的交易上链:输出早在广播时标了已花,扫到时仍要按 key image 认出来, - /// 把交易从待确认转成已确认,高度改成真实上链高度。 + /// Our broadcast is mined: outputs already marked spent at broadcast must + /// still match by key image, confirming the transaction at its mined height. #[test] fn our_broadcast_spend_is_confirmed_when_its_block_is_scanned() { let (mut db, id) = db_with_identity(); @@ -1043,7 +1035,7 @@ mod tests { assert_eq!( known.get(&key_image), Some(&output_id), - "待确认的花费也要参与比对" + "pending spends must be matched too" ); persist( @@ -1078,7 +1070,7 @@ mod tests { assert_eq!(spent_at, mined_at as i64); assert!( load_key_images(&db, id).unwrap().is_empty(), - "确认后不再参与比对" + "confirmed spends are no longer matched" ); } @@ -1111,7 +1103,7 @@ mod tests { assert_eq!(spent_in, Some(txid.to_vec())); } - /// 自己发出、已上链的交易所在块被重组掉:退回在途,输入不放回。 + /// Our confirmed send reorged out reverts to pending; inputs stay spent. #[test] fn a_rewind_turns_our_confirmed_send_back_into_a_pending_one() { let (mut db, id) = db_with_identity(); @@ -1148,7 +1140,7 @@ mod tests { assert_eq!( rows, vec![(ours.to_vec(), None)], - "自己的退回在途,扫到的照删" + "our send reverts to pending, scanned ones are deleted" ); let spent: Vec>> = db .conn() @@ -1161,11 +1153,12 @@ mod tests { assert_eq!(spent, vec![Some(ours.to_vec()), None]); } - /// 空批次是合法的 no-op,不该报错也不该动任何状态。 + /// An empty batch is a no-op: no error, no state change. #[test] fn an_empty_batch_is_a_harmless_no_op() { let (mut db, id) = db_with_identity(); - let outcome = scan_blocks(&mut db, id, &[]).expect("空批次"); + let outcome = scan_blocks(&mut db, id, &[]).expect("empty batch"); + assert_eq!(outcome.blocks_scanned, 0); assert_eq!(outcome.outputs_found, 0); assert!(outcome.from_height.is_none()); diff --git a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs index 20c181185..712ecb665 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs @@ -1,37 +1,37 @@ -//! 钱包库的表结构与迁移。 +//! Wallet database schema and migrations. //! -//! ## 为什么要自己写 +//! ## Why hand-written //! -//! monero-oxide 只给密码学与扫描器,**不提供任何存储**。Zcash 那边 -//! `zcash_client_sqlite` 白送的这一层,在 Monero 这边没有对应物。 +//! monero-oxide provides cryptography and a scanner but no storage; there is +//! no counterpart to `zcash_client_sqlite`. //! -//! ## 比 Zcash 少掉的东西 +//! ## Narrower than Zcash //! -//! Monero 只有一种输出类型(没有 sapling/orchard/ironwood 三池),FCMP++ -//! 之前**没有承诺树**、因此也没有 witness 与检查点,也没有透明池。Zcash 库里 -//! 最复杂的那几块这里根本不存在,所以这套表能做得很窄。 +//! Monero has a single output type (no sapling/orchard/ironwood pools), no +//! transparent pool, and before FCMP++ no commitment tree, so no witnesses or +//! checkpoints. The schema can stay small. //! -//! ## 落盘而不是内存 +//! ## On disk, not in memory //! -//! 这是选 monero-oxide 而非 monero-ts 的全部理由:后者把整个钱包放在 wasm -//! 内存里,持久化只能整块序列化重写,历史越长每次保存越贵,写一半崩了丢全部。 -//! 这里是增量写 + 事务。 +//! monero-ts keeps the whole wallet in wasm memory and can only persist by +//! reserializing all of it, which grows with history and loses everything on +//! a torn write. Here writes are incremental and transactional. use rusqlite::Connection; use crate::error::{db_err, Result}; -/// 当前 schema 版本。**改表结构必须同时加迁移并把这个数加一。** +/// Current schema version. Any schema change must add a migration and bump this. pub const SCHEMA_VERSION: i64 = 1; -/// 重组安全窗口:`blocks` 表只保留链尖往前这么多块的哈希。 +/// Reorg safety window: `blocks` keeps hashes only for this many blocks below the tip. /// -/// Monero 的重组极少超过几块,但节点作恶不受此限。留 720 块(约一天)既够 -/// 覆盖任何现实重组,又不会让这张表随链高无限增长 —— 这正是我们批评 -/// wallet2 内存模型时说的那件事,自己不能犯。 +/// Real Monero reorgs rarely exceed a few blocks, but a malicious node is not +/// bound by that. 720 blocks (about a day) covers any realistic reorg without +/// letting the table grow with chain height. pub const REORG_WINDOW_BLOCKS: u64 = 720; -/// 建表。幂等:可以在每次开库时调用。 +/// Creates the tables. Idempotent: safe to call on every open. pub fn migrate(conn: &Connection) -> Result<()> { let version: i64 = conn .query_row("PRAGMA user_version", [], |r| r.get(0)) @@ -41,13 +41,13 @@ pub fn migrate(conn: &Connection) -> Result<()> { return Err(db_err( "migrate", format!( - "库的 schema 版本 {version} 高于本 runtime 支持的 {SCHEMA_VERSION},拒绝降级打开" + "database schema version {version} is newer than supported {SCHEMA_VERSION}; refusing to open" ), )); } - // 整个迁移一个事务:中途失败(关页、断电)不能留下改了一半、版本号却没动的库, - // 否则下次开库会对已存在的列再 ALTER 一次而永远打不开。 + // One transaction for the whole migration: a partial migration with an + // unchanged version would re-run ALTERs on the next open and never succeed. let tx = conn .unchecked_transaction() .map_err(|e| db_err("beginMigrate", e))?; @@ -60,47 +60,48 @@ pub fn migrate(conn: &Connection) -> Result<()> { tx.commit().map_err(|e| db_err("commitMigrate", e)) } -/// 版本 1。 +/// Version 1. /// -/// 命名约定:金额一律 `*_atomic` 存 piconero(u64 存成 INTEGER,Monero 的 -/// 总量 1.8e19 超过 i64 上限,但单笔金额不会 —— 超了会在写入时报错而不是 -/// 静默截断,见 `outputs.amount_atomic` 的 CHECK)。 +/// Amounts are `*_atomic` in piconero. Total supply (1.8e19) exceeds i64, but a +/// single amount does not; an overflow fails on write rather than truncating +/// (see the CHECK on `outputs.amount_atomic`). const V1: &str = r#" PRAGMA foreign_keys = ON; --- 钱包级元数据。单行表,id 恒为 0。 +-- Wallet metadata. Single row, id is always 0. CREATE TABLE IF NOT EXISTS wallet_meta ( id INTEGER PRIMARY KEY CHECK (id = 0), network TEXT NOT NULL, created_at INTEGER NOT NULL ); --- 一个 identity = 一对观察密钥 = 宿主眼里的一个账户。 +-- One identity = one view key pair = one host account. -- --- 存的是**观察材料**:花费公钥 + 私有观察密钥,等价于 Zcash 的 UFVK。 --- 花费私钥永远不落库、不进这个 crate —— 签名走另一条路。 +-- Stores view material only (spend public key + private view key, like a +-- Zcash UFVK). The private spend key never reaches the database or this crate. CREATE TABLE IF NOT EXISTS identities ( id INTEGER PRIMARY KEY AUTOINCREMENT, - -- 宿主给的稳定标识,用来跨会话认人 + -- Stable host-provided identifier across sessions uuid TEXT NOT NULL UNIQUE, - -- 主地址(标准地址,非子地址),同时兼作人类可读的身份 + -- Primary (standard, non-sub) address; also the human-readable identity primary_address TEXT NOT NULL UNIQUE, spend_public_key BLOB NOT NULL CHECK (length(spend_public_key) = 32), view_private_key BLOB NOT NULL CHECK (length(view_private_key) = 32), - -- 从哪个高度开始扫。导入旧钱包时由宿主给。 + -- Height to start scanning from; provided by the host on import. birthday_height INTEGER NOT NULL CHECK (birthday_height >= 0), - -- 本身份已经连续扫到的高度(含)。NULL = 一块都没扫过。 + -- Highest height (inclusive) contiguously scanned for this identity. NULL = none. -- - -- **必须按身份记**:拿别的身份的进度推算,会让一个刚追到链尖的身份把 - -- 另一个还在回补的身份的进度"推"到链尖,那段历史就被永久跳过了。 + -- Must be per identity: deriving it from another identity's progress would + -- let a caught-up identity skip a backfilling identity's history for good. scanned_to_height INTEGER, created_at INTEGER NOT NULL ); --- 子地址注册表。扫描前要全部灌进 monero-oxide 的 Scanner —— 它只认注册过的。 +-- Subaddress registry. All entries are loaded into the monero-oxide Scanner, +-- which only recognises registered subaddresses. -- --- (major, minor) 同为 0 是主地址,不进这张表(上游 SubaddressIndex::new --- 对 (0,0) 返回 None)。 +-- (0, 0) is the primary address and is excluded (upstream +-- SubaddressIndex::new returns None for it). CREATE TABLE IF NOT EXISTS subaddresses ( identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, major INTEGER NOT NULL CHECK (major >= 0), @@ -112,40 +113,37 @@ CREATE TABLE IF NOT EXISTS subaddresses ( ); CREATE INDEX IF NOT EXISTS idx_subaddresses_address ON subaddresses(address); --- 已扫区块的哈希与 RingCT 输出游标,每个身份各存一份。 +-- Scanned block hashes and RingCT output cursors, per identity. -- --- 两个用途,都不可省: +-- 1. Reorg detection: a new block whose prev_hash does not match is a reorg. +-- 2. RingCT index check: upstream `ScannableBlock` warns that +-- `output_index_for_first_ringct_output` cannot be verified and the client +-- must track it itself; a mismatch means the node is serving a false view. +-- `ringct_next` is the global index of the next RingCT output after this block. -- --- 1. **重组检测** —— 拉到新块时比对 prev_hash,对不上就是重组。 --- 2. **RingCT 索引校验** —— 上游 `ScannableBlock` 的文档明确警告 --- `output_index_for_first_ringct_output` **无法验证**,要求客户端自己维护 --- 这个索引并与节点声称的比对,不一致应当判定节点提供了虚假视图并断开。 --- `ringct_next` 存的就是"扫完本块之后下一个 RingCT 输出的全局序号"。 +-- Not shared across identities: one identity's rollback or pruning would +-- remove anchors another identity still needs, hiding a reorg from it. -- --- 不能各身份共用:一个身份回滚会删掉另一个身份的锚点,另一个身份接着在新链 --- 上扫、看不出重组;追链尖的身份裁剪时也会裁掉还在回补的身份的锚点。 --- --- 只保留链尖往前 REORG_WINDOW_BLOCKS 块,不随链高无限增长。 +-- Only the last REORG_WINDOW_BLOCKS blocks below the tip are kept. CREATE TABLE IF NOT EXISTS blocks ( identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, height INTEGER NOT NULL, hash BLOB NOT NULL CHECK (length(hash) = 32), - -- 扫完本块之后下一个 RingCT 输出的全局序号。 + -- Global index of the next RingCT output after this block. -- - -- **允许 NULL**:从链中段开始扫、且起始块恰好没有 RingCT 输出时,我们 - -- 没有任何依据推算这个游标。此时必须存 NULL 而不是 0 —— 存 0 会让下一块 - -- 拿真实序号(几千万)来比对 0,报出一个**假的** RINGCT_INDEX_MISMATCH, - -- 把一个诚实的节点判成作恶。 + -- NULL when scanning starts mid-chain at a block with no RingCT outputs, so + -- the cursor is unknown. Storing 0 instead would raise a false + -- RINGCT_INDEX_MISMATCH against an honest node on the next block. ringct_next INTEGER CHECK (ringct_next IS NULL OR ringct_next >= 0), timestamp INTEGER NOT NULL, PRIMARY KEY (identity_id, height) ); --- 扫描进度。用区间而不是单个游标:导入旧钱包会产生"回补一段历史"与 --- "追链尖"两条互不相邻的待扫区间。 +-- Scan progress as ranges rather than one cursor: importing an old wallet +-- yields two disjoint pending ranges (history backfill and tip catch-up). -- --- Monero 没有承诺树,所以**不要求连续扫描**(Zcash 要求,因为 witness 必须 --- 沿着树增量维护)。这让这张表比 Zcash 的扫描队列简单一个量级。 +-- With no commitment tree, Monero does not require contiguous scanning +-- (Zcash does, to maintain witnesses). CREATE TABLE IF NOT EXISTS scan_ranges ( identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, start_height INTEGER NOT NULL, @@ -154,44 +152,44 @@ CREATE TABLE IF NOT EXISTS scan_ranges ( CHECK (end_height > start_height) ); --- 扫到的输出。 +-- Received outputs. -- --- `blob` 是 monero-oxide `WalletOutput::serialize()` 的原样字节,花费时用 --- `WalletOutput::read()` 读回 —— 这是整个落盘方案成立的关键 API。 --- 其余列是从中抽出来供 SQL 查询的,**不是另一份真相**:任何要参与密码学的 --- 地方都必须从 blob 反序列化,抽出来的列只用于筛选和展示。 +-- `blob` is monero-oxide `WalletOutput::serialize()` output, read back with +-- `WalletOutput::read()` when spending. The other columns are derived for +-- querying and display only; anything cryptographic must deserialize the blob. CREATE TABLE IF NOT EXISTS outputs ( id INTEGER PRIMARY KEY AUTOINCREMENT, identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, - -- monero-oxide 的原样序列化,花费时读回 + -- monero-oxide serialization, read back when spending blob BLOB NOT NULL, - -- ── 以下均为 blob 的派生列,仅供查询 ── + -- ── Columns below are derived from blob, for queries only ── txid BLOB NOT NULL CHECK (length(txid) = 32), - -- 该输出在链上的全局序号,构环时要用 + -- Global output index on chain, used for ring construction global_index INTEGER NOT NULL, index_in_tx INTEGER NOT NULL, amount_atomic INTEGER NOT NULL CHECK (amount_atomic >= 0), - -- 收进哪个子地址;主地址存 NULL + -- Receiving subaddress; NULL for the primary address subaddress_major INTEGER, subaddress_minor INTEGER, height INTEGER NOT NULL, - -- 额外时间锁(Monero 的 unlock_time),0 表示无 + -- Additional timelock (Monero unlock_time), 0 = none additional_timelock INTEGER NOT NULL DEFAULT 0, - -- 花费检测用。需要花费密钥才能算,所以可能为空(只读观察钱包)。 + -- For spend detection. Requires the spend key, so NULL in view-only wallets. key_image BLOB CHECK (key_image IS NULL OR length(key_image) = 32), - -- 花在哪个高度;未花为 NULL + -- Height spent at; NULL if unspent spent_at_height INTEGER, spent_in_txid BLOB, - -- 交易公钥 R,多个则 32 字节一个顺序拼接(通常只有一个)。 + -- Transaction public keys R, concatenated 32 bytes each (usually one). -- - -- monero-oxide 扫描时把 R 折叠进 `key_offset` 后丢掉,软件签名用不到它; - -- 硬件签名要(固件 `step_02_set_input.py` 自己推导一次性私钥,不接受宿主 - -- 算好的偏移)。扫过就没了,事后只能全量重扫或拿 txid 问节点(泄露隐私), - -- 所以扫描当下就得留。 + -- monero-oxide folds R into `key_offset` and drops it; software signing + -- does not need it, but hardware signing does (firmware + -- `step_02_set_input.py` derives the one-time key itself). Recovering it + -- later needs a full rescan or a txid query to the node (leaks privacy), + -- so it is kept at scan time. tx_pub_keys BLOB, - -- 子地址收款用的 additional keys,每个输出一个;没有则为 NULL。 + -- Additional keys for subaddress receives, one per output; NULL if none. tx_additional_pub_keys BLOB, - -- 输出的一次性公钥,查燃烧 bug 用(同一个公钥只有一笔能花) + -- One-time output public key, for burning-bug checks (only one output per key is spendable) output_key BLOB CHECK (output_key IS NULL OR length(output_key) = 32), UNIQUE (identity_id, txid, index_in_tx) ); @@ -202,55 +200,58 @@ CREATE INDEX IF NOT EXISTS idx_outputs_key_image ON outputs(key_image) WHERE key CREATE INDEX IF NOT EXISTS idx_outputs_global ON outputs(identity_id, global_index); CREATE INDEX IF NOT EXISTS idx_outputs_output_key ON outputs(identity_id, output_key); --- 交易索引。收款由扫描产出;花费由 key image 命中产出。 +-- Transaction index. Receives come from scanning; spends from key image matches. CREATE TABLE IF NOT EXISTS transactions ( identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, txid BLOB NOT NULL CHECK (length(txid) = 32), - height INTEGER, -- NULL = 还在内存池 + height INTEGER, -- NULL = in mempool timestamp INTEGER, - -- 'in' 收款 / 'out' 花费。一笔交易可能两者皆有(找零),此时记 'out'。 + -- 'in' receive / 'out' spend. A tx with both (change) is recorded as 'out'. direction TEXT NOT NULL CHECK (direction IN ('in', 'out')), - -- 以下是自己广播的交易的在途状态(wallet2 `process_unconfirmed_transfer` - -- 同款):迟迟不进内存池的判失败并放回它花的输出,否则那笔钱永远锁着。 + -- In-flight state of our own broadcasts (as wallet2 + -- `process_unconfirmed_transfer`): one that never reaches the pool is + -- marked failed and its inputs released, otherwise the funds stay locked. sent_at INTEGER, pool_checked_at INTEGER, failed INTEGER NOT NULL DEFAULT 0, - -- 付出去的总额(收款 + 手续费),piconero 十进制串。待确认期间只有广播时 - -- 知道(找零要上链扫到才有)。 + -- Total paid out (destinations + fee), piconero decimal string. Only known + -- from the broadcast while pending (change appears once scanned). outgoing_atomic TEXT, - -- 待确认期间的找零,piconero 十进制串。wallet2 把它算进总余额(锁定), - -- 上链扫到后它变成一笔普通输出,这里就不再计。 + -- Pending change, piconero decimal string. wallet2 counts it in the total + -- (locked) balance; once scanned it becomes a normal output and is not counted here. change_atomic TEXT, PRIMARY KEY (identity_id, txid) ); CREATE INDEX IF NOT EXISTS idx_transactions_height ON transactions(identity_id, height); --- 锁定中的输出:已被某笔待广播交易选中,不可再次选中。 +-- Outputs reserved by a pending transaction and not selectable again. -- --- 与 Zcash 同样的理由:不锁会导致同一个输出被两笔在途交易同时花掉, --- 第二笔必然被网络拒绝,而用户看到的是"莫名其妙失败"。 +-- Without this, two in-flight transactions could spend the same output and +-- the second would be rejected by the network. CREATE TABLE IF NOT EXISTS locked_outputs ( output_id INTEGER PRIMARY KEY REFERENCES outputs(id) ON DELETE CASCADE, reservation_id TEXT NOT NULL, locked_at INTEGER NOT NULL, - -- 宿主签好名的时间。没签名的预留在下一次准备发送时作废(用户离开了确认页); - -- 签了名的要等广播结果或过期。 + -- When the host signed. Unsigned reservations are dropped on the next + -- prepare (the user left the confirm screen); signed ones wait for the + -- broadcast result or expiry. signed_at INTEGER ); CREATE INDEX IF NOT EXISTS idx_locked_reservation ON locked_outputs(reservation_id); --- 可能的花费(monero-lws 的做法)。 +-- Possible spends (as in monero-lws). -- --- 观察钱包没有花费私钥,认不出自己的钱被花掉。但一笔钱被花时它必然出现在 --- 那个输入的环里,所以扫描时把「环里含我的钱」的输入连同它的 key image 记下; --- 等宿主凭密码(或硬件)补算出 key image,一比对就知道哪条是真的花费。 --- 从没出现在任何环里的钱一定没花。只按全局序号比对,不需要任何密钥。 +-- A view-only wallet cannot recognise its own spends, but a spent output must +-- appear in that input's ring. Scanning records inputs whose ring contains one +-- of our outputs, with their key image; once the host computes the real key +-- image (password or hardware), matching reveals the true spend. An output +-- never seen in any ring is unspent. Matching uses global indices only, no keys. CREATE TABLE IF NOT EXISTS possible_spends ( identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, - -- 被引用的是哪笔我的输出:(txid, index_in_tx),与 outputs 的唯一键一致 + -- Referenced output: (txid, index_in_tx), same as the outputs unique key out_txid BLOB NOT NULL CHECK (length(out_txid) = 32), out_index INTEGER NOT NULL, - -- 引用它的那个输入的 key image,以及那条交易 + -- Key image of the referencing input, and its transaction key_image BLOB NOT NULL CHECK (length(key_image) = 32), spend_txid BLOB NOT NULL CHECK (length(spend_txid) = 32), height INTEGER NOT NULL, @@ -265,18 +266,18 @@ mod tests { use super::*; fn db() -> Connection { - let conn = Connection::open_in_memory().expect("内存库"); - migrate(&conn).expect("建表"); + let conn = Connection::open_in_memory().expect("in-memory db"); + migrate(&conn).expect("migrate"); conn } - /// 交易公钥要能原样存进去、原样拿回来。 + /// Transaction public keys must round-trip byte for byte. /// - /// 硬件签名要的就是这串字节(固件拿它推导一次性私钥),存歪了不会报错, - /// 只会在将来某天让设备签出一笔花不掉的交易。 + /// Hardware signing derives the one-time key from these bytes; corruption + /// would not error, it would yield an unspendable signed transaction. /// - /// 复用 `db_with_identity`,不另起一份身份行的 fixture —— 那份会随表约束 - /// 变化而悄悄过期。 + /// Uses `db_with_identity` rather than a separate identity fixture that + /// could drift from the table constraints. #[test] fn transaction_public_keys_round_trip() { let (db, identity_id) = crate::wallet::testing::db_with_identity(); @@ -303,9 +304,8 @@ mod tests { assert_eq!(got_additional, Some(additional)); } - /// 没有 additional keys 的交易(发给主地址)存 NULL,不是空串。 - /// 空串会让读取方以为「有 0 个 additional key」,和「这笔交易没有这个字段」 - /// 是两回事。 + /// A transaction without additional keys (sent to a primary address) + /// stores NULL, not an empty blob: "zero keys" and "field absent" differ. #[test] fn an_output_without_additional_keys_stores_null() { let (db, identity_id) = crate::wallet::testing::db_with_identity(); @@ -330,7 +330,7 @@ mod tests { #[test] fn migrate_is_idempotent() { let conn = db(); - migrate(&conn).expect("重复迁移应当无害"); + migrate(&conn).expect("repeated migration must be harmless"); let v: i64 = conn .query_row("PRAGMA user_version", [], |r| r.get(0)) .unwrap(); @@ -341,7 +341,7 @@ mod tests { fn refuses_to_open_a_newer_database() { let conn = Connection::open_in_memory().unwrap(); conn.execute_batch("PRAGMA user_version = 999").unwrap(); - // 降级打开会让新版写入的数据被旧代码误读,宁可拒绝 + // Old code could misread data written by a newer version assert!(migrate(&conn).is_err()); } @@ -366,12 +366,13 @@ mod tests { |r| r.get(0), ) .unwrap(); - assert_eq!(n, 1, "缺表 {t}"); + assert_eq!(n, 1, "missing table {t}"); } } - /// (0,0) 是主地址,不该进子地址表 —— 上游 `SubaddressIndex::new(0,0)` - /// 返回 None,库里也要挡住,否则会注册出一个扫描器永远不认的条目。 + /// (0,0) is the primary address and must be rejected here too (upstream + /// `SubaddressIndex::new(0,0)` returns None), or the scanner would never + /// recognise the entry. #[test] fn subaddress_zero_zero_is_rejected() { let conn = db(); @@ -385,15 +386,16 @@ mod tests { "INSERT INTO subaddresses (identity_id, major, minor, address) VALUES (1, 0, 0, 'a')", [], ); - assert!(bad.is_err(), "(0,0) 必须被 CHECK 拦住"); + assert!(bad.is_err(), "(0,0) must be rejected by the CHECK"); conn.execute( "INSERT INTO subaddresses (identity_id, major, minor, address) VALUES (1, 0, 1, 'a')", [], ) - .expect("(0,1) 是合法子地址"); + .expect("(0,1) is a valid subaddress"); } - /// 同一个输出不能入库两次 —— 重扫同一段区间必须幂等,否则余额翻倍。 + /// The same output cannot be stored twice; rescanning a range must be + /// idempotent or balances double. #[test] fn the_same_output_cannot_be_inserted_twice() { let conn = db(); @@ -405,15 +407,15 @@ mod tests { .unwrap(); let insert = "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx, amount_atomic, height) VALUES (1, x'00', zeroblob(32), 7, 0, 100, 10)"; - conn.execute(insert, []).expect("首次写入"); + conn.execute(insert, []).expect("first insert"); assert!( conn.execute(insert, []).is_err(), - "同一 (identity, txid, index_in_tx) 必须被唯一约束拦住" + "duplicate (identity, txid, index_in_tx) must hit the unique constraint" ); } - /// 删除 identity 要连带清掉它的全部数据 —— 否则「删钱包」会留下可被后续 - /// 查询读到的孤儿行,那是隐私问题不只是脏数据。 + /// Deleting an identity cascades to all its data; orphan rows left behind + /// by "delete wallet" would be a privacy leak. #[test] fn deleting_an_identity_cascades() { let conn = db(); @@ -442,7 +444,7 @@ mod tests { let n: i64 = conn .query_row(&format!("SELECT count(*) FROM {t}"), [], |r| r.get(0)) .unwrap(); - assert_eq!(n, 0, "{t} 应当被级联清空"); + assert_eq!(n, 0, "{t} should be cleared by cascade"); } } } diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs index 2fef01534..4dfe6a8d1 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs @@ -1,18 +1,18 @@ -//! 花费路径:key image 导入、交易构造、签名、广播。 +//! Spend path: key image import, transaction construction, signing, broadcast. //! -//! ## 花费私钥在这里出现,且只在这里 +//! ## The private spend key appears only here //! -//! 它由宿主在每次调用时传进来,用完即擦,**永远不落库、不跨 wasm 边界返回**。 -//! 想审计「私钥去了哪」,看这一个文件。 +//! The host passes it per call; it is zeroized after use, never persisted, and +//! never returned across the wasm boundary. //! -//! ## 为什么需要导入 key image +//! ## Why key images are imported //! -//! Monero 的观察钱包无法独立判断自己的输出有没有被花掉 —— 判断需要 key image, -//! 而 key image = `(花费私钥 + 输出偏移) × H(输出公钥)`,绕不开花费私钥。 -//! 这是协议性质,不是实现取舍。 +//! A view-only wallet cannot tell whether its outputs were spent: that needs +//! the key image `(spend key + output offset) × H(output key)`, which requires +//! the private spend key. //! -//! 所以扫描只能记下输出,花费状态要等宿主在解锁时调一次 -//! [`import_key_images`] 才补得齐。补齐之前余额会**偏高**(已花的看起来还在)。 +//! Scanning records outputs only; spend state is complete once the host calls +//! [`import_key_images`] on unlock. Until then the balance may be overstated. use std::collections::HashMap; @@ -32,20 +32,19 @@ use crate::keys; use crate::query; use crate::wallet::Db; -/// 环大小。当前共识值是 16(含真实成员)。 +/// Ring size. Current consensus is 16, including the real member. /// -/// 写死而不是问节点:节点说小了会让交易在隐私上被削弱且可能被拒, -/// 这个值应当跟着硬分叉走,由我们发版控制。 +/// Hardcoded rather than asked of the node: a smaller value weakens privacy +/// and may be rejected. It changes with hard forks via our releases. pub const RING_LEN: u8 = 16; -/// 从花费私钥算出某笔输出的 key image。 +/// Computes an output's key image from the private spend key. /// -/// 公式与上游 `SignableTransaction::sign` 内部一致: -/// `key_image = (spend + key_offset) × biased_hash(output_key)`。 +/// Same formula as upstream `SignableTransaction::sign`: +/// `key_image = (spend + key_offset) × biased_hash(output_key)`. /// -/// 顺带校验了密钥是否真的对应这笔输出 —— 不对应就说明宿主传错了账户的种子, -/// 这时必须报错而不是算出一个无意义的 key image 存进库里(那会让花费检测 -/// 永远撞不上,表现为「这笔钱花了但钱包还显示在」)。 +/// Also checks that the key owns the output. A mismatch (wrong account seed) +/// errors instead of storing a meaningless key image that would never match a spend. fn key_image_for(output: &WalletOutput, spend: &Zeroizing) -> Result<[u8; 32]> { use core::ops::Deref; @@ -71,13 +70,12 @@ fn key_image_for(output: &WalletOutput, spend: &Zeroizing) -> Result<[u8 Ok(image.compress().to_bytes()) } -/// 给还没有 key image 的输出补齐 key image。 +/// Fills in key images for outputs that lack one, enabling spend detection. /// -/// 补齐之后花费检测才能工作。 -/// -/// 补齐之前已经发生的花费靠扫描时记下的「可能的花费」追认:一笔输出算出的 -/// key image 若出现在它的某条可能花费里,那条就是真的花费。之后的花费由正常 -/// 扫描识别,所以这笔输出的可能花费记录随即清掉。 +/// Earlier spends are confirmed from possible spends recorded while scanning: +/// if the computed key image appears in one of the output's possible spends, +/// that is the real spend. Later spends are caught by normal scanning, so the +/// output's possible spends are then cleared. pub fn import_key_images( db: &mut Db, identity_id: i64, @@ -105,14 +103,14 @@ pub fn import_key_images( let mut computed = Vec::with_capacity(pending.len()); for (id, blob, txid, index) in pending { let output = WalletOutput::read(&mut blob.as_slice()) - .map_err(|e| db_err("deserializeOutput", format!("输出 {id}: {e}")))?; + .map_err(|e| db_err("deserializeOutput", format!("output {id}: {e}")))?; computed.push((id, key_image_for(&output, &spend)?, txid, index)); } apply_key_images(db, identity_id, &computed) } -/// 写回算好的 key image,并用「可能的花费」追认早已发生的花费。 -/// 与计算分开,好让比对逻辑脱离真实输出单独测试。 +/// Stores computed key images and confirms earlier spends from possible spends. +/// Separate from computation so the matching can be tested without real outputs. fn apply_key_images( db: &mut Db, identity_id: i64, @@ -174,11 +172,11 @@ fn apply_key_images( }) } -/// `import_key_images` 的结果。 +/// Result of `import_key_images`. pub struct KeyImageImport { - /// 这次补算了几笔输出的 key image。 + /// Outputs whose key image was computed. pub imported: usize, - /// 其中几笔借「可能的花费」追认为早已花掉。 + /// Of those, outputs confirmed as already spent via possible spends. pub spends_found: usize, } @@ -198,24 +196,24 @@ fn parse_spend_key(bytes: &[u8]) -> Result> { Ok(Zeroizing::new(scalar)) } -/// 一笔待发交易的收款项。 +/// A payment in a pending transaction. #[derive(Debug, Clone)] pub struct Payment { pub address: MoneroAddress, pub amount_atomic: u64, } -/// 选币结果与预留。 +/// Input selection result. #[derive(Debug, Clone)] pub struct Selection { pub output_ids: Vec, pub total_atomic: u64, } -/// 选币:大额优先,凑够 `needed` 为止。 +/// Selects inputs largest first until `needed` is covered. /// -/// 大额优先的理由是手续费:Monero 按交易重量计费,输入越少越便宜。代价是 -/// 会更快把大额输出打碎 —— 这个取舍和 wallet2 的默认行为一致。 +/// Fees are by weight, so fewer inputs are cheaper, at the cost of breaking up +/// large outputs sooner; this matches wallet2's default. pub fn select_inputs( db: &Db, identity_id: i64, @@ -257,38 +255,40 @@ pub fn select_inputs( }) } -/// 未签名的预留一小时后作废:用户在确认页退出不会通知这里。 +/// Unsigned reservations expire after an hour; leaving the confirm screen is not reported here. pub const RESERVATION_TTL_SECS: i64 = 60 * 60; -/// 已签名、但没走到广播的预留一天后作废。 +/// Signed reservations that never reached broadcast expire after a day. /// -/// 广播会在发出前把输入标已花、写在途记录,所以留到这里的签名从没发出去 -/// (设备上拒绝、取消、签完被杀)。永远锁着,下一笔就只能换一批输入花; -/// 那份旧签名万一之后又被广播,两笔都会上链。放开后同一批输入重新排在 -/// 选币的前面,两笔争同一批 key image,链上只会成一笔。 +/// Broadcast marks inputs spent and records the send before publishing, so a +/// signed reservation left here was never sent (rejected on device, cancelled, +/// killed after signing). Locking it forever would push the next send onto +/// other inputs, and if the old signature were broadcast later both would +/// confirm. Released, the same inputs are selected first again, so both +/// transactions share key images and at most one can confirm. pub const SIGNED_RESERVATION_TTL_SECS: i64 = 24 * 60 * 60; -/// 仍然有效的预留的下限时间:`locked_at` 大于它才算数。 +/// Reservations with `locked_at` after this are live. pub fn reservation_cutoff() -> i64 { crate::wallet::now_secs() - RESERVATION_TTL_SECS } -/// 已签名预留的下限时间:`signed_at` 大于它才算数。 +/// Signed reservations with `signed_at` after this are live. pub fn signed_reservation_cutoff() -> i64 { crate::wallet::now_secs() - SIGNED_RESERVATION_TTL_SECS } -/// 预留选中的输出,防止被第二笔在途交易重复选中。 +/// Reserves selected outputs so a second in-flight transaction cannot select them. /// -/// 不预留的后果很具体:两笔交易花同一个输出,第二笔必然被网络拒绝, -/// 而用户看到的是「莫名其妙失败」。 +/// Otherwise two transactions could spend the same output and the second would +/// be rejected by the network. pub fn reserve(db: &mut Db, reservation_id: &str, output_ids: &[i64]) -> Result<()> { let now = crate::wallet::now_secs(); let tx = db .conn_mut() .transaction() .map_err(|e| db_err("beginReserve", e))?; - // 用户在确认页退出不会通知这里,作废的预留只能在这时清掉。 + // Leaving the confirm screen is not reported, so expired reservations are cleared here. tx.execute( "DELETE FROM locked_outputs WHERE (signed_at IS NULL AND locked_at <= ?1) OR signed_at <= ?2", @@ -299,8 +299,8 @@ pub fn reserve(db: &mut Db, reservation_id: &str, output_ids: &[i64]) -> Result< ) .map_err(|e| db_err("expireReservations", e))?; for id in output_ids { - // 已被别人预留时这里会因为主键冲突而失败 —— 那正是我们要的: - // 宁可这笔构造不出来,也不要构造出一笔注定被拒的交易。 + // Fails on primary key conflict if already reserved: better to fail + // here than build a transaction that will be rejected. tx.execute( "INSERT INTO locked_outputs (output_id, reservation_id, locked_at) VALUES (?1, ?2, ?3)", params![id, reservation_id, now], @@ -308,7 +308,7 @@ pub fn reserve(db: &mut Db, reservation_id: &str, output_ids: &[i64]) -> Result< .map_err(|e| { db_err( "reserveOutput", - format!("输出 {id} 可能已被另一笔在途交易预留: {e}"), + format!("output {id} may be reserved by another pending send: {e}"), ) })?; } @@ -360,10 +360,10 @@ pub fn mark_signed(db: &mut Db, reservation_id: &str, expected_inputs: u32) -> R Ok(marked) } -/// 放掉本身份所有没签名的预留。 +/// Releases all unsigned reservations of this identity. /// -/// 用户在确认页返回、改完再下一步时不会通知这里;新的一次准备就说明前一次 -/// 没签名的已经没人要了。签了名的不动:它可能正在广播。 +/// Going back from the confirm screen is not reported; a new prepare means the +/// earlier unsigned ones are abandoned. Signed ones stay: they may be broadcasting. fn release_unsigned(db: &Db, identity_id: i64) -> Result { db.conn() .execute( @@ -375,7 +375,7 @@ fn release_unsigned(db: &Db, identity_id: i64) -> Result { .map_err(|e| db_err("releaseUnsignedReservations", e)) } -/// 释放预留(用户取消,或构造失败)。 +/// Releases a reservation (user cancelled or construction failed). pub fn release(db: &Db, reservation_id: &str) -> Result { let n = db .conn() @@ -387,21 +387,17 @@ pub fn release(db: &Db, reservation_id: &str) -> Result { Ok(n) } -/// 一笔构造完成、等待签名的交易。 +/// A constructed transaction awaiting signature. pub struct Prepared { pub signable: SignableTransaction, pub output_ids: Vec, pub inputs_atomic: u64, - /// 收款方实际收到的总额。max-send 时这是反算出来的,不等于宿主传入的值。 + /// Total received by recipients. For max-send it is derived, not the host's input. pub amount_atomic: u64, pub fee_atomic: u64, } -/// 给一个输出取一环诱饵。 -/// -/// 诱饵必须在**当前**链高上选:用旧高度会让环成员分布偏离当下的链上分布, -/// 那是可被统计分析利用的指纹。 -/// monerod 的拒收原因按标志拼接,双花写作 "double spend"。 +/// monerod joins rejection reasons by flag; a double spend reads "double spend". fn is_double_spend(error: &RuntimeError) -> bool { error .detail @@ -409,10 +405,11 @@ fn is_double_spend(error: &RuntimeError) -> bool { .is_some_and(|reason| reason.to_lowercase().contains("double spend")) } -/// 一次构造里所有输入共用同一份 RingCT 输出分布。 +/// Shares one RingCT output distribution across all inputs of a construction. /// -/// 上游每选一组诱饵都向节点要一次整条链的分布(约 18MB),N 个输入就下 N 份, -/// 移动端经宿主转发很容易超时。范围相同就复用,节点只问一次。 +/// Upstream fetches the full-chain distribution (about 18MB) per decoy +/// selection, N times for N inputs, which easily times out when relayed through +/// the host on mobile. Same range is reused, so the node is asked once. struct CachedDecoys<'a, P> { inner: &'a P, distributions: @@ -492,6 +489,10 @@ impl } } +/// Picks a ring of decoys for one output. +/// +/// Decoys must be selected at the current height; a stale height skews the +/// ring distribution into a statistical fingerprint. async fn ring_for( db: &Db, decoy_source: &impl monero_wallet::interface::ProvidesDecoys, @@ -511,9 +512,9 @@ async fn ring_for( }) } -/// 取一组输出的环,已经取过的直接复用。 +/// Rings for a set of outputs, reusing ones already fetched. /// -/// 复用不是优化细节:每个输入要十几个诱饵,重取一轮就是十几个网络往返。 +/// Each ring costs a dozen or more network round trips. async fn rings_for( db: &Db, decoy_source: &impl monero_wallet::interface::ProvidesDecoys, @@ -533,7 +534,7 @@ async fn rings_for( Ok(inputs) } -/// 组装一笔 `SignableTransaction`。找零永远回到本账户主地址。 +/// Assembles a `SignableTransaction`. Change always goes to the account's primary address. fn assemble( identity: &crate::wallet::Identity, rng: &mut R, @@ -544,8 +545,8 @@ fn assemble( ) -> std::result::Result { let change = Change::new(identity.view_pair.clone(), None); - // `outgoing_view_key` 给这笔交易的确定性 RNG 做种子。**绝不能跨交易复用** - // —— 上游文档明写复用会导致临时秘密被重复使用。每次现取。 + // `outgoing_view_key` seeds this transaction's deterministic RNG. Never reuse + // it across transactions (upstream: reuse repeats ephemeral secrets). let mut ovk = Zeroizing::new([0u8; 32]); rng.fill_bytes(ovk.as_mut()); @@ -565,16 +566,16 @@ fn build_error(e: monero_wallet::send::SendError) -> RuntimeError { .detail(format!("{e:?}")) } -/// 选币 + 构造,**不需要花费私钥**。 +/// Selects inputs and constructs a transaction; no private spend key needed. /// -/// 返回的 `Prepared` 带着这笔交易真正要付的手续费,宿主据此在确认页上显示 —— -/// 显示的数就是会扣的数。在别处照抄一遍上游的重量公式只会让两个数慢慢分家。 +/// `Prepared` carries the actual fee, which the host shows on the confirm +/// screen, so the displayed fee is the one charged. /// -/// ## 为什么要迭代 +/// ## Why iterate /// -/// 手续费按交易重量算,重量取决于输入个数,而要凑几个输入又取决于手续费。 -/// 先按「只够付金额」选一轮,让上游把真实手续费算出来(`NotEnoughFunds` 里 -/// 带着它),不够就按新的目标再选。实测两轮收敛。 +/// The fee depends on weight, weight on input count, and input count on the +/// fee. The first round covers the amount only; upstream reports the real fee +/// in `NotEnoughFunds`, and selection repeats with the new target. Converges in two rounds in practice. #[allow(clippy::too_many_arguments)] pub async fn prepare( db: &Db, @@ -598,8 +599,8 @@ pub async fn prepare( let mut cache: HashMap = HashMap::new(); let mut needed = out_total; - // 三轮:第一轮不含手续费,第二轮按真实手续费重选,第三轮兜住「补的输入 - // 又把手续费抬上去了」。再不收敛就是钱确实不够。 + // Three rounds: without fee, with the real fee, and once more in case the + // added inputs raised the fee. Not converging means insufficient funds. for _ in 0..3 { let selection = select_inputs(db, identity_id, chain_tip, needed)?; let inputs = rings_for( @@ -635,10 +636,10 @@ pub async fn prepare( necessary_fee: Some(fee), .. }) => { - // 上游算出了真实手续费,按它重新定目标。 + // Retarget using the fee computed by upstream. let next = outputs.checked_add(fee).ok_or_else(overflow)?; if next <= needed { - // 目标没往上走却仍然构不出来:再循环也是同一个结果。 + // Target did not grow; another round would fail the same way. return Err(insufficient(selection.total_atomic, next)); } needed = next; @@ -650,13 +651,13 @@ pub async fn prepare( Err(insufficient(0, needed)) } -/// 把这个账户当前能花的**全部**输出发给一个地址。 +/// Sends all currently spendable outputs to one address. /// -/// 不能靠「不给找零输出」来实现 —— 上游明写那样会把余数全部并进手续费, -/// 等于白送矿工。正确做法是先拿到这笔交易真实的手续费,再反算金额。 +/// Omitting the change output would, per upstream, add the remainder to the +/// fee. Instead the real fee is obtained first and the amount derived. /// -/// 金额不影响交易重量(RingCT 的金额是定长密文),所以先用 1 piconero 试 -/// 构一次拿手续费,再用 `总额 - 手续费` 正式构造,两次重量一致。 +/// Amounts do not affect weight (RingCT amounts are fixed-size), so a probe +/// with 1 piconero gives the fee, then `total - fee` is built with the same weight. #[allow(clippy::too_many_arguments)] pub async fn prepare_max( db: &Db, @@ -688,8 +689,7 @@ pub async fn prepare_max( let mut cache: HashMap = HashMap::new(); let inputs = rings_for(db, decoy_source, rng, &output_ids, chain_tip, &mut cache).await?; - // 试构一次只为拿手续费。成功失败都给得出:成功读 `necessary_fee()`, - // 失败时 `NotEnoughFunds` 里也带着它。 + // Probe for the fee: `necessary_fee()` on success, or from `NotEnoughFunds`. let fee_atomic = match assemble( &identity, rng, @@ -759,9 +759,9 @@ fn insufficient(available: u64, needed: u64) -> RuntimeError { ) } -/// 签名一笔已构造的交易。**不碰网络,不碰数据库。** +/// Signs a constructed transaction. No network or database access. /// -/// `spend_private` 用完即擦。返回可直接广播的交易字节与 txid。 +/// `spend_private` is zeroized after use. Returns broadcastable bytes and the txid. pub fn sign_prepared( signable: SignableTransaction, rng: &mut R, @@ -776,7 +776,7 @@ pub fn sign_prepared( Ok((signed.serialize(), txid)) } -/// 广播。**不可逆。** +/// Broadcasts. Irreversible. pub async fn broadcast(daemon: &crate::network::Daemon, raw: &[u8]) -> Result<()> { use monero_daemon_rpc::prelude::*; @@ -794,7 +794,7 @@ pub async fn broadcast(daemon: &crate::network::Daemon, raw: &[u8]) -> Result<() }) } -/// 校验一个收款地址并解析金额,给宿主一个统一的入口。 +/// Validates a recipient address and parses the amount. pub fn parse_payment( network: monero_wallet::address::Network, address: &str, @@ -874,16 +874,16 @@ mod tests { .unwrap(); } - /// 补算出的 key image 若出现在这笔输出的某条可能花费里,那条就是真花费: - /// 标成已花、补一条出账记录。只是被别人当诱饵的(key image 对不上)不算。 + /// A computed key image found in the output's possible spends confirms that + /// spend (marked spent, outgoing record added). Use as someone else's decoy does not count. #[test] fn a_key_image_found_among_possible_spends_confirms_an_earlier_spend() { let (mut db, id) = db_with_identity(); let spent = add_output(&db, id, 700, 10, false); let decoyed = add_output(&db, id, 300, 11, false); - add_possible_spend(&db, id, 10, 0xAA, 0x51, 30); // 真的:key image 对得上 - add_possible_spend(&db, id, 10, 0xBB, 0x52, 31); // 别人拿它当诱饵 - add_possible_spend(&db, id, 11, 0xCC, 0x53, 32); // 别人拿它当诱饵 + add_possible_spend(&db, id, 10, 0xAA, 0x51, 30); // real: key image matches + add_possible_spend(&db, id, 10, 0xBB, 0x52, 31); // used as a decoy + add_possible_spend(&db, id, 11, 0xCC, 0x53, 32); // used as a decoy let result = apply_key_images( &mut db, @@ -913,7 +913,7 @@ mod tests { |r| r.get(0), ) .unwrap(); - assert_eq!(decoyed_spent, None, "只是被当诱饵,没花"); + assert_eq!(decoyed_spent, None, "only used as a decoy, not spent"); let (direction, out_height): (String, i64) = db .conn() @@ -928,7 +928,7 @@ mod tests { .conn() .query_row("SELECT count(*) FROM possible_spends", [], |r| r.get(0)) .unwrap(); - assert_eq!(left, 0, "有了 key image 的输出不再需要可能花费记录"); + assert_eq!(left, 0, "key-imaged outputs need no possible spends"); } // Invalid transaction bytes must fail before signing, even with a review attached. @@ -944,8 +944,8 @@ mod tests { assert_eq!(e.params["reason"], "transactionDoesNotMatchReview"); } - /// 金额相加溢出必须报错而不是回绕。回绕会让一笔「收款方总额 0」的交易 - /// 被当成合法请求构造出去。 + /// Amount overflow must error, not wrap; wrapping could build a transaction + /// paying a total of 0. #[test] fn payment_totals_do_not_wrap_on_overflow() { let address = keys::parse_address( @@ -975,7 +975,7 @@ mod tests { assert_eq!(e.params["byteLen"], 31); } - /// 大额优先:Monero 按重量计费,输入越少越便宜。 + /// Largest first: fees are by weight, so fewer inputs are cheaper. #[test] fn selection_prefers_large_outputs_and_stops_once_covered() { let (db, id) = db_with_identity(); @@ -984,7 +984,7 @@ mod tests { add_output(&db, id, 500, 12, true); let s = select_inputs(&db, id, 100, 1_000).unwrap(); - assert_eq!(s.total_atomic, 1_400, "900 + 500 就够了,不该再拿 100"); + assert_eq!(s.total_atomic, 1_400, "900 + 500 suffice; skip the 100"); assert_eq!(s.output_ids.len(), 2); } @@ -998,8 +998,7 @@ mod tests { assert_eq!(e.params["availableAtomic"], "100"); } - /// 没有 key image 的输出不能参与花费 —— 无法确认它没被花掉, - /// 拿它构造交易有双花风险。 + /// Outputs without a key image are never spent: their unspent status is unknown. #[test] fn outputs_without_key_images_are_never_selected() { let (db, id) = db_with_identity(); @@ -1008,15 +1007,15 @@ mod tests { assert_eq!(e.params["reason"], "insufficientUnlockedFunds"); } - /// 锁定期内的输出也不能选 —— 构不进环,节点会拒。 + /// Locked outputs are not selected; the node would reject them. #[test] fn locked_outputs_are_not_selected() { let (db, id) = db_with_identity(); add_output(&db, id, 5_000, 95, true); - // 链尖 100,输出在 95:差 5 块,未满 10 块锁定 + // Tip 100, output at 95: within the 10-block lock let e = select_inputs(&db, id, 100, 1_000).unwrap_err(); assert_eq!(e.params["reason"], "insufficientUnlockedFunds"); - // 到 105 就够了 + // Unlocked at 105 assert!(select_inputs(&db, id, 105, 1_000).is_ok()); } @@ -1030,11 +1029,10 @@ mod tests { params![a, reservation_cutoff() - 1], ) .unwrap(); - reserve(&mut db, "new", &[a]).expect("过期的预留不该挡路"); + reserve(&mut db, "new", &[a]).expect("expired reservation must not block"); } - /// 用户离开确认页后,下一次准备发送放掉没签名的预留;签了名的可能正在 - /// 广播,要留着。 + /// A new prepare releases unsigned reservations; signed ones may be broadcasting and stay. #[test] fn a_new_send_releases_only_unsigned_reservations() { let (mut db, id) = db_with_identity(); @@ -1107,7 +1105,7 @@ mod tests { .locked_by_reservation_atomic, 0 ); - reserve(&mut db, "replacement", &[input]).expect("过期的签名预留让位"); + reserve(&mut db, "replacement", &[input]).expect("expired signed reservation gives way"); } #[test] @@ -1132,7 +1130,7 @@ mod tests { assert!(reserve(&mut db, "replacement", &[input]).is_err()); } - /// wallet2 同款:待确认发送的找零计入总余额(锁定),不计入可用;判失败后不再计。 + /// As wallet2: pending change counts in the total (locked), not unlocked, until the send fails. #[test] fn pending_change_counts_in_total_until_the_send_fails() { let (db, id) = db_with_identity(); @@ -1172,7 +1170,7 @@ mod tests { assert_eq!(b.total_atomic, 500); } - /// 广播后按交易里的 key image 标已花:预留过期或被释放了也不能漏记。 + /// Broadcast marks inputs spent by the transaction's key images, even if the reservation is gone. #[test] fn a_broadcast_marks_its_inputs_by_key_image_without_a_reservation() { let (db, id) = db_with_identity(); @@ -1221,7 +1219,7 @@ mod tests { assert_eq!(outgoing.as_deref(), Some("123")); } - /// 记账在广播之前:被拒时只撤这一次新建的记录;重发同一笔不算新建。 + /// Recorded before broadcast: a rejection undoes only a fresh record; a retry is not fresh. #[test] fn a_rejected_first_broadcast_is_undone_but_a_retry_is_not_fresh() { let (mut db, id) = db_with_identity(); @@ -1248,14 +1246,14 @@ mod tests { .unwrap() }; - assert!(record(&db), "第一次是新建"); + assert!(record(&db), "first record is fresh"); assert!( crate::query::spendable_rows(&db, id, 10_000) .unwrap() .is_empty(), - "广播前输入就已不可选" + "inputs are unselectable before broadcast" ); - assert!(!record(&db), "同一笔再记一次不是新建"); + assert!(!record(&db), "recording the same tx again is not fresh"); undo_recorded_broadcast(&db, id, &txid).unwrap(); assert_eq!( @@ -1266,24 +1264,23 @@ mod tests { .conn() .query_row("SELECT count(*) FROM transactions", [], |r| r.get(0)) .unwrap(); - assert_eq!(rows, 0, "被拒的交易不留在历史里"); + assert_eq!(rows, 0, "rejected transaction is not kept in history"); } - /// 同一笔输出不能被两个预留同时持有 —— 否则两笔交易花同一个输出, - /// 第二笔必然被网络拒绝。 + /// An output cannot be held by two reservations at once. #[test] fn an_output_cannot_be_reserved_twice() { let (mut db, id) = db_with_identity(); let a = add_output(&db, id, 5_000, 10, true); reserve(&mut db, "r1", &[a]).unwrap(); - assert!(reserve(&mut db, "r2", &[a]).is_err(), "第二次预留必须失败"); + assert!(reserve(&mut db, "r2", &[a]).is_err(), "already reserved"); assert_eq!(release(&db, "r1").unwrap(), 1); - reserve(&mut db, "r2", &[a]).expect("释放后可以重新预留"); + reserve(&mut db, "r2", &[a]).expect("can reserve again after release"); } #[test] fn releasing_an_unknown_reservation_is_a_no_op() { - let (mut db, _) = db_with_identity(); + let (db, _) = db_with_identity(); assert_eq!(release(&db, "nope").unwrap(), 0); } @@ -1296,7 +1293,7 @@ mod tests { assert!(parse_payment(Network::Mainnet, addr, "1000").is_ok()); } - /// 金额走字符串跨边界:piconero 上限超过 JS 的 MAX_SAFE_INTEGER。 + /// Amounts cross the boundary as strings: piconero values exceed JS MAX_SAFE_INTEGER. #[test] fn large_amounts_survive_the_string_boundary() { let addr = crate::wallet::testing::ADDR; @@ -1313,18 +1310,18 @@ mod tests { } } -// ── 端到端发送 ────────────────────────────────────────────────────────── +// ── End-to-end send ───────────────────────────────────────────────────── -/// 各优先级手续费率的上限(piconero / weight)。 +/// Fee rate cap per priority (piconero / weight). /// -/// 上游 `fee_rate` 强制要求给一个上限,理由很实在:**手续费率来自节点, -/// 而节点可能撒谎**。报一个天价费率会让用户把余额全付成手续费。 +/// Upstream `fee_rate` requires a cap because the rate comes from the node, +/// which may lie; an absurd rate could spend the balance on fees. /// -/// monerod 的四档是基础费率的固定倍数,主网现值为 20,000 / 80,000 / -/// 320,000 / 4,000,000。基础费率随区块奖励与区块大小中位数算出:交易一多 -/// 区块变大,费率反而下降;尾部发行固定后奖励也不再变。所以各档按现值留 -/// 5 倍余量,正常波动碰不到,挡得住数量级级别的胡说。碰到上限的结果是这一档 -/// 发不出去,不会多付。 +/// monerod's four tiers are fixed multiples of the base fee, currently 20,000 / +/// 80,000 / 320,000 / 4,000,000 on mainnet. The base fee derives from block +/// reward and median block size: busier blocks lower it, and tail emission +/// fixes the reward. Caps leave 5x headroom over current values. Hitting a cap +/// fails the send at that tier; it never overpays. pub fn max_fee_per_weight(priority: monero_wallet::interface::FeePriority) -> u64 { use monero_wallet::interface::FeePriority; match priority { @@ -1335,15 +1332,16 @@ pub fn max_fee_per_weight(priority: monero_wallet::interface::FeePriority) -> u6 } } -/// 手续费的取整单位(piconero)。 +/// Fee quantization mask (piconero). /// -/// 这不是价格,是 monerod 写死的常量(`PER_KB_FEE_QUANTIZATION_DECIMALS = 8`, -/// 即 10^(12-8)),不随网络繁忙变化。上游拿节点给的值把手续费向上取整到它的 -/// 整数倍,不设上限 —— 节点报一个大 mask,手续费就跟着翻几百倍。所以只认这一个值。 +/// A monerod constant (`PER_KB_FEE_QUANTIZATION_DECIMALS = 8`, i.e. +/// 10^(12-8)), not a price. Upstream rounds the fee up to a multiple of the +/// node-supplied mask with no cap, so a large mask would multiply the fee; +/// only this value is accepted. pub const FEE_QUANTIZATION_MASK: u64 = 10_000; -/// 上游 `FeeRate` 不暴露 mask,只能从它的序列化里取:先 per_weight 后 mask, -/// 各 8 字节小端。布局由测试钉住,上游改了会先在测试里炸。 +/// Upstream `FeeRate` does not expose the mask; read it from the serialization +/// (per_weight then mask, 8 bytes LE each). The layout is pinned by a test. fn fee_mask(rate: &monero_wallet::interface::FeeRate) -> Option { let bytes = rate.serialize(); Some(u64::from_le_bytes(bytes.get(8..16)?.try_into().ok()?)) @@ -1364,7 +1362,7 @@ fn check_fee_rate(rate: &monero_wallet::interface::FeeRate) -> Result<()> { Ok(()) } -/// 手续费优先级。字符串而非数字:数字跨边界时无从校验。 +/// Fee priority, as a string so it can be validated across the boundary. pub fn parse_priority(name: &str) -> Result { use monero_wallet::interface::FeePriority; Ok(match name { @@ -1385,24 +1383,24 @@ pub fn parse_priority(name: &str) -> Result Result { let request = crate::review::parse_request(review_json)?; let signable = crate::review::verify(signable_hex, &request, Some(spend_private))?; @@ -1504,19 +1502,20 @@ pub fn sign_for_host(signable_hex: &str, spend_private: &[u8], review_json: &str })) } -/// 自己发出的一笔交易的金额(只有广播时知道)。 +/// Amounts of our own send, known only at broadcast. #[derive(Debug, Default, Clone, Copy)] pub struct SentAmounts { - /// 付出去的总额(收款 + 手续费)。 + /// Total paid out (destinations + fee). pub outgoing_atomic: Option, - /// 找零:上链前计入总余额(锁定),wallet2 同款。 + /// Change, counted in the total (locked) balance until mined, as wallet2. pub change_atomic: Option, } -/// 广播前的记账:输入标已花、记一条在途转出、释放预留。一个事务。 +/// Pre-broadcast bookkeeping in one transaction: mark inputs spent, record a +/// pending send, release the reservation. /// -/// 返回这条在途记录是不是这一次新建的。已有记录说明同一笔交易以前发过 -/// (重试同一份签名),那次的结局可能已经是「节点收下了」。 +/// Returns whether the record is fresh. An existing record means the same +/// transaction was sent before (a retry), which the node may have accepted. fn record_broadcast( db: &Db, identity_id: i64, @@ -1579,7 +1578,7 @@ fn record_broadcast( Ok(!existed) } -/// 撤销这一次新建的在途记录:节点明确拒收,这笔不会上链,输入放回可用。 +/// Undoes a fresh pending record after an explicit rejection; the inputs become spendable again. fn undo_recorded_broadcast(db: &Db, identity_id: i64, txid: &[u8; 32]) -> Result<()> { let tx_db = db .conn() @@ -1601,11 +1600,12 @@ fn undo_recorded_broadcast(db: &Db, identity_id: i64, txid: &[u8; 32]) -> Result tx_db.commit().map_err(|e| db_err("commitUndoSend", e)) } -/// 记账,然后广播一笔已签名的交易。**不可逆。** +/// Records, then broadcasts a signed transaction. Irreversible. /// -/// 先记账再广播:输入先标已花、先有一条在途记录,之后任何一刻被打断 -/// (Worker 被杀、回包丢失),重启后这笔都看得见,输入也不会被下一笔选中 -/// 而换一批去花 —— 换一批花,两笔都会上链,用户付两次。 +/// Recording first marks inputs spent and creates a pending record, so an +/// interruption (worker killed, response lost) leaves the send visible and its +/// inputs unselectable. Otherwise the next send could use other inputs and both +/// would confirm, paying twice. pub async fn broadcast_signed( db: &Db, daemon: &crate::network::Daemon, @@ -1626,8 +1626,8 @@ pub async fn broadcast_signed( .map_err(|e| db_err("parseSignedTransaction", e))?; let txid = tx.hash(); - // 按交易自己的 key image 标,不靠预留:预留可能已经过期,或者签名失败 - // 释放后又拿同一份签名重发。 + // Mark by the transaction's own key images, not the reservation, which may + // have expired or been released before the same signature is resent. let key_images: Vec<[u8; 32]> = tx .prefix() .inputs @@ -1639,7 +1639,7 @@ pub async fn broadcast_signed( _ => None, }) .collect(); - // 记不上账就不发:这时什么都还没发生,报错是真话。 + // If recording fails, do not send; nothing has happened yet. let fresh = record_broadcast( db, identity_id, @@ -1650,12 +1650,13 @@ pub async fn broadcast_signed( amounts, )?; - // 明确拒收说明这笔不会上链:这次新建的记录撤掉,输入放回可用。 - // 其余错误分不清节点收没收到:记录留着,输入不会被重选;节点真没收到的话, - // 在途检查过了扩散期会判失败并放回输入。 - // 「双花」也可能是这笔自己早已上链(回包丢过、重试了同一份签名),同样当 - // 不确定处理。以前发过的同一笔(`fresh` 为假)被拒也当不确定:上一次的 - // 结局可能是节点收下了。 + // An explicit rejection means it will not confirm: undo the fresh record + // and release the inputs. Other errors are uncertain: keep the record so the + // inputs are not reselected; the pending check fails it after the + // propagation window if the node never got it. + // "double spend" may be this transaction already mined (lost response, + // retried signature), so it is uncertain too, as is a rejection of a + // non-fresh record, which the node may have accepted earlier. let unknown = match broadcast(daemon, &raw).await { Ok(()) => None, Err(e) if e.code == ErrorCode::BroadcastRejected && !is_double_spend(&e) && fresh => { @@ -1736,7 +1737,7 @@ mod double_spend_tests { assert_eq!( fee_mask(&rate), Some(FEE_QUANTIZATION_MASK), - "序列化布局变了" + "serialization layout changed" ); check_fee_rate(&rate).unwrap(); for mask in [1, 9_999, 10_001, 10_000_000_000] { @@ -1747,7 +1748,8 @@ mod double_spend_tests { } } - /// 主网现值(2026-10)各档都要能发,且离上限至少 5 倍。 + /// Current mainnet rates (2026-10) fit every tier with at least 5x headroom. + #[test] fn current_mainnet_fee_rates_fit_every_priority() { use monero_wallet::interface::FeePriority; diff --git a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs index 2b4d108ca..06917a40b 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs @@ -1,19 +1,19 @@ -//! 各端共用的 SQLite 存储。 +//! SQLite storage shared by all platforms. //! -//! wasm 侧跑在独立 Worker 里,四端(桌面、Web、插件、移动 WebEmbed)都用同一套 -//! OPFS 同步访问 VFS —— SQLite 直接按页读写,而不是把整个库预载进 wasm 内存。 -//! **这正是选 monero-oxide 而不是 monero-ts 的理由**:后者只能整块序列化。 +//! The wasm side runs in a dedicated Worker; desktop, web, extension and mobile +//! WebEmbed all use the same OPFS sync-access VFS, so SQLite reads and writes +//! pages directly instead of preloading the database into wasm memory. This is +//! why monero-oxide was chosen over monero-ts, which serializes the whole wallet. //! -//! 原生构建保留,用于 Rust 测试与本机诊断。 +//! The native build is kept for Rust tests and local diagnostics. use rusqlite::Connection; use serde_json::json; use crate::error::{db_err, ErrorCode, Result, RuntimeError}; -// 强制链接:Rust 只链接代码里真正引用过的 crate。光在 Cargo.toml 里声明 -// sqlite-wasm-rs 不够 —— 它的归档会被找到却一个符号都不拉,链接期报一串 -// `undefined symbol: sqlite3_*`。 +// Force linking: an unreferenced crate is not linked, which would fail with +// `undefined symbol: sqlite3_*`. #[cfg(target_arch = "wasm32")] use sqlite_wasm_rs as _; @@ -23,14 +23,14 @@ use std::sync::atomic::{AtomicBool, Ordering}; #[cfg(target_arch = "wasm32")] static VFS_READY: AtomicBool = AtomicBool::new(false); -// 装好后的池句柄。删库要靠它:库打不开(版本不认、文件损坏)时也得能删掉。 +// Installed pool handle; lets us delete databases that cannot be opened (unknown version, corruption). #[cfg(target_arch = "wasm32")] thread_local! { static VFS_UTIL: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } -/// VFS 是否已就绪。原生目标恒为 true(用系统文件系统)。 +/// Whether the VFS is ready. Always true on native (system filesystem). pub fn is_ready() -> bool { #[cfg(target_arch = "wasm32")] { @@ -42,28 +42,20 @@ pub fn is_ready() -> bool { } } -/// 在浏览器载体里装上持久化 VFS。必须在开任何库之前调用一次。 +/// Installs the persistent VFS in the browser carrier. Call once before opening +/// any database. /// -/// 池会独占文件句柄直到它所在的 Worker 被终止 —— 所以同一个库不能被两个 -/// Worker 同时打开,宿主那侧要保证串行。 +/// The pool holds file handles exclusively until its Worker terminates, so two +/// Workers cannot open the same database; the host must serialize. /// -/// ## 为什么要自己起名,不用库的默认值 +/// A dedicated name instead of the default `.opfs-sahpool` keeps the pool from +/// sharing a directory and handles with other pools on the same origin (e.g. +/// Zcash's `.onekey-zcash-opfs`). /// -/// 默认是 `.opfs-sahpool`。同一个 origin 下 Zcash 的 runtime 也在装它自己的池 -/// (`.onekey-zcash-opfs`),将来任何一个依赖只要用默认配置装一次,就会和我们 -/// 共用同一个目录、抢同一批文件句柄。起个专属名字是一行的事,省掉的是一类 -/// 只在"两条链同时开着"时才出现、且看起来像存储损坏的故障。 -/// -/// ## 为什么要重试 -/// -/// 浏览器里 Worker 的终止是**异步**的:carrier 重置、页面刷新、开发时热更新, -/// 旧 Worker 在新的已经跑起来之后还会攥着 SAH 句柄一小会儿。这时 install 会拿 -/// 到 `NoModificationAllowedError`。不重试的话,用户看到的是刷新一下页面 -/// 钱包就打不开了。 -/// -/// 只对"上一个持有者正在释放"这一种错误重试,而且有界。真有另一个活着的持有 -/// 者时,等完这段窗口依然会失败 —— 那是对的,两个 Worker 同时写一个库比报错 -/// 严重得多。 +/// Worker termination is **asynchronous**: after a carrier reset, reload or hot +/// update, the old Worker briefly keeps its SAH handles and install fails with +/// `NoModificationAllowedError`. Only that error is retried, with a bound; a +/// live second holder still fails, which is correct. #[cfg(target_arch = "wasm32")] pub async fn install_persistent_vfs() -> Result<()> { use sqlite_wasm_vfs::sahpool::{install, OpfsSAHError, OpfsSAHPoolCfg}; @@ -75,16 +67,16 @@ pub async fn install_persistent_vfs() -> Result<()> { let cfg = OpfsSAHPoolCfg { vfs_name: "onekey-xmr-opfs".to_owned(), directory: ".onekey-xmr-opfs".to_owned(), - // 绝不能是 true:那会在每次启动时清空池,等于每次开 app 都要全链重扫。 + // Never true: it wipes the pool on every start, forcing a full rescan. clear_on_init: false, - // 一个网络一个库,加上回滚日志与富余句柄。 + // One database per network, plus rollback journals and spare handles. initial_capacity: 4, }; let mut retries = 20; loop { - // `WasmOsCallback` 是 sqlite-wasm-rs 提供的具体实现(VFS crate 本身只 - // 定义了 trait)。泛型参数必须显式给,否则推不出来。 + // `WasmOsCallback` is sqlite-wasm-rs's implementation of the VFS crate's + // trait; the type parameter cannot be inferred. match install::(&cfg, true).await { Ok(util) => { VFS_UTIL.with(|slot| *slot.borrow_mut() = Some(std::rc::Rc::new(util))); @@ -118,16 +110,16 @@ pub async fn install_persistent_vfs() -> Result<()> { } } -/// 原生目标不需要装 VFS。留同名函数让上层代码不必到处写 cfg。 +/// No VFS on native; same-named stub keeps callers cfg-free. #[cfg(not(target_arch = "wasm32"))] pub async fn install_persistent_vfs() -> Result<()> { Ok(()) } -/// 库名校验:不能为空,也不能含路径分隔符。 +/// Database name must be non-empty with no path separators. /// -/// **两个目标都要查**。wasm 上 db_name 是 VFS 里的不透明键,原生上它会直接 -/// 变成文件路径 —— 后者才是路径穿越真正有意义的地方,所以不能只在 wasm 上查。 +/// **Checked on every target**: on wasm the name is an opaque VFS key, but on +/// native it becomes a file path, where traversal actually matters. fn validate_db_name(db_name: &str) -> Result<()> { let bad = db_name.is_empty() || db_name.contains('/') @@ -142,13 +134,13 @@ fn validate_db_name(db_name: &str) -> Result<()> { Ok(()) } -/// 打开一条连接并设好 pragma。 +/// Opens a connection and sets pragmas. /// -/// `:memory:` 是测试专用的特例,跳过名字校验与持久化 pragma。 +/// `:memory:` is test-only and skips name validation and durability pragmas. pub fn open_connection(db_name: &str) -> Result { if db_name == ":memory:" { let conn = Connection::open_in_memory().map_err(|e| db_err("openInMemory", e))?; - // 外键与正式库一致,级联删除的测试才有意义 + // Match real databases so cascade-delete tests are meaningful conn.execute_batch("PRAGMA foreign_keys = ON;") .map_err(|e| db_err("pragmaForeignKeys", e))?; return Ok(conn); @@ -162,18 +154,18 @@ pub fn open_connection(db_name: &str) -> Result { let conn = Connection::open(db_name).map_err(|e| db_err("open", e))?; - // 外键必须显式打开(SQLite 默认关闭),否则 identities 的级联删除不生效, - // 「删钱包」会留下能被后续查询读到的孤儿行。 + // Foreign keys are off by default; without them identity cascades fail and + // deleting a wallet leaves readable orphan rows. conn.execute_batch("PRAGMA foreign_keys = ON;") .map_err(|e| db_err("pragmaForeignKeys", e))?; - // 删掉的行(观察私钥、收款记录)用零覆盖,不留在空闲页里等人读。 + // Zero deleted rows (view keys, receipts) instead of leaving them in free pages. conn.execute_batch("PRAGMA secure_delete = ON;") .map_err(|e| db_err("pragmaSecureDelete", e))?; #[cfg(target_arch = "wasm32")] { - // SAH 池用回滚日志,不做跨上下文的 WAL 协调。 - // **绝不为了扫描吞吐去弱化事务持久性。** + // SAH pool uses a rollback journal, no cross-context WAL. + // **Never weaken durability for scan throughput.** conn.execute_batch("PRAGMA journal_mode = DELETE; PRAGMA synchronous = FULL;") .map_err(|e| db_err("pragmaDurability", e))?; } @@ -181,8 +173,8 @@ pub fn open_connection(db_name: &str) -> Result { Ok(conn) } -/// 删掉一个已关闭的库,**不打开它**:打不开的库也要删得掉。 -/// 返回 `true` 表示删了,`false` 表示本来就不存在。 +/// Deletes a closed database **without opening it**, so unopenable ones can be deleted. +/// Returns `true` if deleted, `false` if it did not exist. #[cfg(target_arch = "wasm32")] pub async fn delete_database(db_name: &str) -> Result { validate_db_name(db_name)?; @@ -212,16 +204,16 @@ pub async fn delete_database(db_name: &str) -> Result { } } -/// 落盘屏障:确保此前提交的事务真的到了持久存储。 +/// Durability barrier: ensures committed transactions reached durable storage. /// -/// 在做完一件**不可逆**的事之后调用(比如广播了一笔交易)。屏障失败的含义是 -/// 「持久化是否到达耐久存储未知」,**不是**「那件事失败了」—— 调用方不能因此 -/// 把真实结局丢掉。 +/// Call after an **irreversible** action (e.g. a broadcast). Failure means +/// durability is unknown, **not** that the action failed; callers must keep +/// the real outcome. pub async fn durability_barrier() -> Result<()> { #[cfg(target_arch = "wasm32")] { - // SAH 池的写在 sqlite3 返回时已落到 OPFS 句柄上;这里给宿主一个 - // 明确的同步点,且保留将来换 VFS 时插入真正 flush 的位置。 + // SAH pool writes reach the OPFS handle before sqlite3 returns; this is + // an explicit sync point and the place for a real flush on another VFS. Ok(()) } #[cfg(not(target_arch = "wasm32"))] @@ -234,7 +226,7 @@ pub async fn durability_barrier() -> Result<()> { mod tests { use super::*; - // 删库不打开库:一个根本不是 SQLite 的文件也删得掉。 + // Deletion does not open the file, so even a non-SQLite file is deleted. #[test] fn deletes_a_database_it_cannot_open() { let name = format!("xmr-delete-test-{}.db", std::process::id()); @@ -249,12 +241,12 @@ mod tests { assert!(open_connection(":memory:").is_ok()); } - /// 路径穿越在**原生**目标上才真正危险(db_name 直接变文件路径), - /// 所以这条校验不能像某些实现那样只在 wasm 下生效。 + /// Path traversal is dangerous on **native** (the name becomes a file + /// path), so the check must not be wasm-only. #[test] fn path_separators_are_rejected_on_every_target() { for bad in ["", "a/b", "a\\b", "../escape", "x/../y"] { - let e = open_connection(bad).expect_err(&format!("{bad:?} 应被拒绝")); + let e = open_connection(bad).expect_err(&format!("{bad:?} should be rejected")); assert_eq!(e.code, ErrorCode::InvalidDbName); } } @@ -262,7 +254,7 @@ mod tests { #[test] fn foreign_keys_are_on() { let conn = open_connection(":memory:").unwrap(); - // 内存库走的是特例分支,这里显式开一次再验,确保 pragma 语句本身有效 + // The in-memory branch is special; set it explicitly to verify the pragma itself conn.execute_batch("PRAGMA foreign_keys = ON;").unwrap(); let on: i64 = conn .query_row("PRAGMA foreign_keys", [], |r| r.get(0)) diff --git a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs index f803c0f2a..a3fca938b 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs @@ -1,15 +1,14 @@ -//! 同步编排:拉块 → 扫描 → 记进度。**有界推进,永不跑到底。** +//! Sync orchestration: fetch blocks, scan, record progress. Bounded; never runs to completion. //! -//! 一次调用最多处理 `max_blocks` 个块,然后带进度返回。要不要接着调由宿主 -//! 决定 —— 这是「调度归 TS」那条边界。理由是具体的:跑到底的函数在浏览器和 -//! 移动端上无法中断、无法看进度、无法让出线程,页面直接冻住。 +//! One call processes at most `max_blocks` blocks and returns progress; the host +//! decides whether to call again. A run-to-completion call cannot be interrupted, +//! report progress, or yield on browsers and mobile, so the page would freeze. //! -//! ## 扫描进度按身份独立记账 +//! ## Scan progress is tracked per identity //! -//! `scan_ranges` 带 `identity_id`。这和 Zcash 那边不一样 —— 那边承诺树要求 -//! 全库连续扫描,于是「用 A 的密钥扫过的区间被标记为全库已扫」,暂停中的账户 -//! 会永久漏掉那一段,只能靠宿主保管的游标补救。Monero 没有承诺树、不要求 -//! 连续扫描,各身份各记各的,从根上没有这个坑。 +//! `scan_ranges` is keyed by `identity_id`. Unlike Zcash, Monero has no commitment +//! tree that forces wallet-wide contiguous scanning, so each identity tracks its +//! own progress and a paused account never loses a span scanned for another. use futures_util::stream::{self, StreamExt, TryStreamExt}; use monero_daemon_rpc::prelude::*; @@ -22,17 +21,18 @@ use crate::perf::now_ms; use crate::scan::{self, ScanOutcome}; use crate::wallet::Db; -/// 单次调用的块数上限。 +/// Per-call block cap. /// -/// 不是性能调优参数,是**卡死防线**:宿主传个巨大的值会让这次调用跑上几分钟 -/// 且中途无法中断。真正的批量由宿主按实测吞吐决定。 +/// A hang guard, not a tuning knob: a huge value would make one call run for +/// minutes with no way to interrupt it. The host sizes batches from measured throughput. pub const MAX_BLOCKS_PER_CALL: u64 = 1_000; /// Limit per-block fallback requests to three, leaving the host's fourth /// stream slot available for a chain-tip probe or another privacy chain. pub const FETCH_CONCURRENCY: usize = 3; -/// 问链尖。**不碰钱包库** —— 建账户时需要它来定 birthday,而那一刻库还没建。 +/// Fetch the chain tip without touching the wallet DB: account creation needs it +/// for the birthday before the DB exists. pub async fn chain_tip(daemon: &Daemon) -> Result { let n = daemon .latest_block_number() @@ -41,9 +41,9 @@ pub async fn chain_tip(daemon: &Daemon) -> Result { Ok(n as u64) } -/// 把链尖告诉某个身份:据此算出还要扫哪一段。 +/// Tell an identity the chain tip and queue the range it still needs to scan. /// -/// 新身份的待扫区间是 `[birthday, tip]`;已有进度的则是 `(已扫到, tip]`。 +/// A new identity queues `[birthday, tip]`; one with progress queues `(scanned_to, tip]`. pub fn update_chain_tip(db: &mut Db, identity_id: i64, tip: u64) -> Result<()> { let identity = db.identity_by_id(identity_id)?; let scanned_to = scanned_to_height(db, identity_id)?; @@ -52,7 +52,7 @@ pub fn update_chain_tip(db: &mut Db, identity_id: i64, tip: u64) -> Result<()> { .unwrap_or(identity.birthday_height); if start > tip { - return Ok(()); // 已经追上链尖,没有待扫区间 + return Ok(()); // Already at the tip; nothing to queue } db.conn() @@ -66,11 +66,11 @@ pub fn update_chain_tip(db: &mut Db, identity_id: i64, tip: u64) -> Result<()> { Ok(()) } -/// 该身份已经连续扫到哪个高度(含)。没扫过任何块时返回 `None`。 +/// Highest height this identity has scanned contiguously (inclusive); `None` if nothing scanned. /// -/// 读的是 `identities.scanned_to_height` 而**不是** `blocks` 表的 max —— 后者 -/// 是全局的,会让一个已追到链尖的身份把另一个还在回补的身份的进度推到链尖, -/// 那段历史就被永久跳过。 +/// Reads `identities.scanned_to_height`, not `max` over the global `blocks` table: +/// that would let a caught-up identity push a backfilling identity's progress to +/// the tip, permanently skipping that history. pub fn scanned_to_height(db: &Db, identity_id: i64) -> Result> { Ok(db .conn() @@ -85,7 +85,7 @@ pub fn scanned_to_height(db: &Db, identity_id: i64) -> Result> { .map(|h| h as u64)) } -/// 推进该身份的扫描进度。只进不退 —— 回退走 `rewind_and_requeue`。 +/// Advance this identity's scan progress. Monotonic; rewinds go through `rewind_and_requeue`. fn advance_scanned_to(db: &Db, identity_id: i64, height: u64) -> Result<()> { db.conn() .execute( @@ -98,7 +98,7 @@ fn advance_scanned_to(db: &Db, identity_id: i64, height: u64) -> Result<()> { Ok(()) } -/// 取当前最靠前的待扫区间。 +/// The lowest pending scan range. fn next_range(db: &Db, identity_id: i64) -> Result> { db.conn() .query_row( @@ -111,15 +111,16 @@ fn next_range(db: &Db, identity_id: i64) -> Result> { .map_err(|e| db_err("nextRange", e)) } -/// 把已扫完的 `[start, scanned_through]` 从待扫区间里销掉。 +/// Remove the scanned span `[start, scanned_through]` from the pending ranges. /// -/// 待扫区间**可能互相重叠**:重扫(`rewind_and_requeue`)会从回退高度重新排一段, -/// 而原来的尾部区间还在队列里。只处理"起点等于 `start`"的那一条、再把余下部分 -/// 普通 INSERT 回去,一旦余下的起点正好是另一条区间的起点就撞主键 —— 整步回滚, -/// 下一步从同一处开始、再撞,扫描永远原地踏步。 +/// Pending ranges can overlap: `rewind_and_requeue` queues a span from the rewind +/// height while the old tail range is still queued. Consuming only the range that +/// starts at `start` and re-inserting the remainder with a plain INSERT collides on +/// the primary key when the remainder starts where another range does; the step +/// rolls back and scanning never advances. /// -/// 所以这里对**每一条**与已扫段相交的区间都减去已扫段,余下部分以 upsert -/// 合并(同起点取更远的终点)。重叠在此被逐步消化,不再需要区间互不相交这个前提。 +/// So the scanned span is subtracted from every overlapping range and remainders +/// are upserted (same start keeps the farther end). Ranges need not be disjoint. fn consume_range(db: &mut Db, identity_id: i64, start: u64, scanned_through: u64) -> Result<()> { let tx = db .conn_mut() @@ -162,11 +163,11 @@ fn consume_range(db: &mut Db, identity_id: i64, start: u64, scanned_through: u64 params![identity_id, range_start], ) .map_err(|e| db_err("consumeRange", e))?; - // 已扫段之前的部分(按最低起点取区间时不会出现,保留以防万一)。 + // Part before the scanned span (unreachable when taking the lowest start; kept defensively). if range_start < scanned_from { upsert(range_start, scanned_from)?; } - // 已扫段之后的部分。 + // Part after the scanned span. if range_end > resume_at { upsert(resume_at, range_end)?; } @@ -176,12 +177,13 @@ fn consume_range(db: &mut Db, identity_id: i64, start: u64, scanned_through: u64 } thread_local! { - /// 批量路径对哪个节点、从什么时候起判定不可用。换节点即重新尝试。 + /// Node the batch path was judged unusable for, and since when. A different node is tried again. static BLOCKS_BIN_UNSUPPORTED_BY: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } -/// 判定不可用之后多久再试批量。一次截断或代理改写的回包不该让好节点整个会话都走慢路。 +/// Retry delay for the batch path. One truncated or proxy-rewritten response must +/// not keep a good node on the slow path all session. const BLOCKS_BIN_RETRY_AFTER_MS: f64 = 10.0 * 60.0 * 1000.0; fn blocks_bin_skipped_for(node: Option<&str>, now: f64) -> bool { @@ -191,11 +193,12 @@ fn blocks_bin_skipped_for(node: Option<&str>, now: f64) -> bool { }) } -/// 先走批量(`get_blocks.bin`,一次往返一整批),节点不配合时退回逐块并发。 +/// Try the batch path (`get_blocks.bin`, one round trip per batch) first; fall back +/// to concurrent per-block fetches if the node does not cooperate. /// -/// 只有**协议**层面的失败(节点不支持、格式不符、数量对不上)才会让这个节点 -/// 暂时跳过批量路径(见 `BLOCKS_BIN_RETRY_AFTER_MS`);网络失败照常上抛,这一步 -/// 失败、下一轮重试 —— 一次超时不能让一个好节点从此降级。 +/// Only protocol failures (unsupported, malformed, count mismatch) skip the batch +/// path for this node (see `BLOCKS_BIN_RETRY_AFTER_MS`). Network failures propagate +/// and the next step retries; one timeout must not downgrade a good node. async fn fetch_blocks( daemon: &Daemon, start: u64, @@ -217,7 +220,7 @@ async fn fetch_blocks( Err(crate::blocks_bin::BlocksBinError::Protocol(detail)) => { BLOCKS_BIN_UNSUPPORTED_BY .with(|c| *c.borrow_mut() = node.clone().map(|url| (url, now_ms()))); - // 放弃的原因随这一步的结果回给宿主,只报这一次。 + // Report why the batch path was abandoned with this step's result, once. let blocks = fetch_scannable_blocks(daemon, start, last).await?; return Ok(( blocks, @@ -236,21 +239,20 @@ async fn fetch_blocks( )) } -/// 取 `[start, last]` 的可扫描块,按高度排好。 +/// Fetch scannable blocks for `[start, last]`, ordered by height. /// -/// 批量路径(`blocks_bin`)不可用时的退路。 +/// Fallback when the batch path (`blocks_bin`) is unusable. /// -/// **不走** `contiguous_scannable_blocks`。它先试批量的 `get_blocks.bin`,但 -/// 已发布的 monerod(截至 v0.18.5.1)在 `prune=true` 时不回 `prunable_hash` -/// (monero-project/monero#10120,修复 #10652 只在 master),monero-oxide 为了 -/// 能校验交易哈希就整批放弃、回退逐块 JSON —— 于是每一步都**白下一整包再扔掉**, -/// 再串行地一块一块取。对今天的任何公共节点,那次批量尝试都注定失败。 -/// -/// 这里直接逐块取、N 路并发。每块仍经上游校验(编号正确、交易与区块的交易 -/// 列表一致);块与块之间的衔接(高度连续、前驱哈希、RingCT 游标)由 -/// `scan::scan_blocks` 独立校验,所以完整性保障一条不少。`buffered` 保持 -/// 提交顺序,结果天然按高度排列。 +/// Does not use `contiguous_scannable_blocks`: it tries `get_blocks.bin` first, but +/// released monerod (through v0.18.5.1) omits `prunable_hash` when `prune=true` +/// (monero-project/monero#10120; fix #10652 is master-only), so monero-oxide drops +/// the whole batch and falls back to serial per-block JSON, wasting a full download +/// every step. /// +/// Instead fetch per block with N-way concurrency. Upstream still validates each +/// block (number, transactions match the block's tx list); cross-block continuity +/// (heights, previous hash, RingCT cursor) is checked by `scan::scan_blocks`. +/// `buffered` preserves order, so results are sorted by height. async fn fetch_scannable_blocks( daemon: &Daemon, start: u64, @@ -268,10 +270,10 @@ async fn fetch_scannable_blocks( .await } -/// 一次有界推进。 +/// One bounded step. /// -/// 返回进度 JSON;`done` 表示已经没有待扫区间。**本函数永远不会自己循环到 -/// 同步完成** —— 宿主拿到进度后自己决定要不要接着调。 +/// Returns progress JSON; `done` means no pending ranges remain. Never loops to +/// completion; the host decides whether to call again. pub async fn step( db: &mut Db, daemon: &Daemon, @@ -294,26 +296,25 @@ pub async fn step( return Ok(v); }; - // 区间是左闭右开(end 是"第一个还没扫的高度之后"),上游要的是闭区间。 + // Ranges are half-open (`end` is exclusive); upstream takes a closed range. let last = (start + max_blocks - 1).min(end.saturating_sub(1)); if last < start { return Ok(progress(db, identity_id, &ScanOutcome::default(), true)?); } - // 分段打点。扫得慢的时候,「慢在拉块还是慢在解密」是完全不同的两件事, - // 而在浏览器里两者的表现一模一样(界面不动)—— 只能靠打点区分。 - // 公共节点单次往返可达几百毫秒,不分开量就会把网络延迟误判成算力不足。 + // Time download and scan separately: both look the same in a browser (a frozen + // UI), and public-node latency would otherwise be misread as CPU cost. let t0 = now_ms(); let (blocks, fetched_via, fetch_note, prefetch_hit) = fetch_blocks(daemon, start, last).await?; - // 流水线:扫这一批之前,先把下一批的请求发出去(wallet2 同款)。起点按实际 - // 拿到的块算 —— 只拿到部分前缀时,下一步从断点开始,预取也得从那里开始。 + // Pipeline: request the next batch before scanning this one (as wallet2 does). + // Start from the blocks actually received, since a partial prefix resumes there. if fetched_via == "blocksBin" { let next = start + blocks.len() as u64; if let (Some(url), true) = (crate::network::current_node_url(), next < end) { - // 与下一步的请求一致:同样受 max_blocks 与区间终点约束,大小取 - // 这一次请求之后调整过的批量。 + // Same bounds as the next step's request (max_blocks, range end), sized by the + // batch as adjusted after this request. crate::blocks_bin::prefetch(&url, next, (end - next).min(max_blocks)).await; } } @@ -321,8 +322,8 @@ pub async fn step( let t_downloaded = now_ms(); if blocks.is_empty() { - // 节点对一个非空区间返回了零个块 —— 它没有守协议。 - // **不能当成"扫完了"静默推进**,那会让这段高度被永远跳过。 + // Zero blocks for a non-empty range violates the protocol. Advancing as if + // scanned would skip this span forever. return Err(RuntimeError::with( ErrorCode::MalformedNodeResponse, json!({ "operation": "contiguousScannableBlocks", "from": start, "to": last }), @@ -331,8 +332,9 @@ pub async fn step( db.ensure_subaddress_lookahead(identity_id)?; let mut outcome = scan::scan_blocks(db, identity_id, &blocks)?; - // 收到钱的子地址靠近窗口末尾时窗口会扩大;用新窗口重扫同一批(块已在手, - // 落库幂等),这批里后面发给新登记子地址的钱才不会漏。 + // Funds near the end of the subaddress window grow it; rescan the same batch with + // the new window (blocks in hand, writes idempotent) so later funds to the newly + // registered subaddresses are not missed. while outcome.outputs_found > 0 && db.ensure_subaddress_lookahead(identity_id)? > 0 { outcome = scan::scan_blocks(db, identity_id, &blocks)?; } @@ -372,9 +374,9 @@ fn progress(db: &Db, identity_id: i64, outcome: &ScanOutcome, done: bool) -> Res Ok(v) } -/// 只读:当前的扫描进度,不发任何网络请求。 +/// Read-only scan progress; makes no network requests. /// -/// 同步卡住时用它确认 runtime 到底想扫哪一段 —— 不用猜。 +/// Shows which ranges the runtime intends to scan when sync appears stuck. pub fn peek(db: &Db, identity_id: i64) -> Result { let mut stmt = db .conn() @@ -397,17 +399,18 @@ pub fn peek(db: &Db, identity_id: i64) -> Result { Ok(json!({ "ranges": ranges, "scannedToHeight": scanned_to_height(db, identity_id)?, - // 回补起点以运行时为准:宿主存的生日可能与这里不一致(重新启用不会改已有身份的生日)。 + // The runtime's birthday is authoritative: the host's may differ (re-enabling + // keeps an existing identity's birthday). "birthdayHeight": db.identity_by_id(identity_id)?.birthday_height, })) } -/// 重组恢复:回退到指定高度,并把那之上的区间重新排进待扫队列。 +/// Reorg recovery: rewind to `height` and requeue everything above it. pub fn rewind_and_requeue(db: &mut Db, identity_id: i64, height: u64, tip: u64) -> Result { scan::rewind_to(db, identity_id, height)?; - // 进度也要退。不退的话下一轮会从一个已经被丢弃的高度接着扫, - // 中间那段永远不会被重新覆盖。一块都没扫过的保持 NULL:当成 0 会让 - // 下一次 update_chain_tip 从创世块排队。 + // Rewind progress too, or the next step resumes from a discarded height and the + // gap is never rescanned. Keep NULL if nothing was scanned: 0 would make the next + // `update_chain_tip` queue from genesis. db.conn() .execute( "UPDATE identities SET scanned_to_height = min(scanned_to_height, ?2) @@ -415,14 +418,15 @@ pub fn rewind_and_requeue(db: &mut Db, identity_id: i64, height: u64, tip: u64) params![identity_id, height as i64], ) .map_err(|e| db_err("rewindScannedTo", e))?; - // 往生日之前重扫(用户选了更早的日期):生日跟着提前,进度才有正确的起点。 + // Rescan before the birthday (user picked an earlier date): move the birthday + // back so progress starts there. db.conn() .execute( "UPDATE identities SET birthday_height = ?2 WHERE id = ?1 AND birthday_height > ?2", params![identity_id, (height + 1) as i64], ) .map_err(|e| db_err("rewindBirthday", e))?; - // 回退后那一段要重扫。直接排进队列,不依赖宿主记得再调一次 update_chain_tip。 + // Requeue the rewound span here instead of relying on the host to call `update_chain_tip`. if tip > height { db.conn() .execute( @@ -447,20 +451,20 @@ mod tests { assert!(next_range(&db, id).unwrap().is_none()); let p = peek(&db, id).unwrap(); assert_eq!(p["ranges"].as_array().unwrap().len(), 0); - assert_eq!(p["birthdayHeight"], 100, "进度的起点取运行时的生日"); + assert_eq!(p["birthdayHeight"], 100, "starts at the runtime's birthday"); } #[test] fn learning_the_tip_queues_the_backfill_range() { let (mut db, id) = db_with_identity(); // birthday = 100 update_chain_tip(&mut db, id, 150).unwrap(); - let (start, end) = next_range(&db, id).unwrap().expect("应当排上队"); - assert_eq!(start, 100, "从 birthday 起扫"); - assert_eq!(end, 151, "区间左闭右开"); + let (start, end) = next_range(&db, id).unwrap().expect("should be queued"); + assert_eq!(start, 100, "scans from the birthday"); + assert_eq!(end, 151, "ranges are half-open"); } - /// 链尖前进时只该抬高终点,不该产生第二条重叠区间 —— 重叠会导致同一段 - /// 被扫两遍,浪费带宽还让进度显示倒退。 + /// Advancing the tip extends the range end; a second overlapping range would + /// rescan the same span and make progress go backwards. #[test] fn advancing_the_tip_extends_rather_than_duplicates() { let (mut db, id) = db_with_identity(); @@ -468,11 +472,11 @@ mod tests { update_chain_tip(&mut db, id, 200).unwrap(); let ranges = peek(&db, id).unwrap(); let ranges = ranges["ranges"].as_array().unwrap(); - assert_eq!(ranges.len(), 1, "只该有一条区间"); + assert_eq!(ranges.len(), 1, "should have one range"); assert_eq!(ranges[0]["end"], 201); } - /// 链尖不动时重复调用必须幂等。 + /// Repeating the same tip is idempotent. #[test] fn the_same_tip_twice_changes_nothing() { let (mut db, id) = db_with_identity(); @@ -482,8 +486,9 @@ mod tests { assert_eq!(before, peek(&db, id).unwrap()); } - /// **回归**:重扫排进来的区间与旧的尾部区间重叠,余下部分的起点正好落在 - /// 另一条区间的起点上。旧实现撞主键、整步回滚,扫描原地踏步(插件实测)。 + /// Regression: a requeued range overlaps the old tail range and the remainder + /// starts exactly at another range's start. This used to collide on the primary + /// key and roll back the step, stalling the scan. #[test] fn consuming_across_overlapping_ranges_merges_instead_of_colliding() { let (mut db, id) = db_with_identity(); @@ -495,7 +500,7 @@ mod tests { ) .unwrap(); } - consume_range(&mut db, id, 100, 160).expect("不能再撞主键"); + consume_range(&mut db, id, 100, 160).expect("must not collide on the primary key"); let ranges: Vec<(i64, i64)> = db .conn() .prepare("SELECT start_height, end_height FROM scan_ranges WHERE identity_id = ?1 ORDER BY start_height") @@ -507,7 +512,7 @@ mod tests { assert_eq!(ranges, vec![(161, 250)]); } - /// 已扫段横跨一条完全被覆盖的区间:那条区间整条消失,不留下重复扫描。 + /// A range fully covered by the scanned span is removed, leaving no duplicate scan. #[test] fn a_range_fully_covered_by_the_scan_disappears() { let (mut db, id) = db_with_identity(); @@ -536,7 +541,7 @@ mod tests { let (mut db, id) = db_with_identity(); update_chain_tip(&mut db, id, 200).unwrap(); consume_range(&mut db, id, 100, 149).unwrap(); - let (start, end) = next_range(&db, id).unwrap().expect("剩余部分还在"); + let (start, end) = next_range(&db, id).unwrap().expect("remainder queued"); assert_eq!((start, end), (150, 201)); } @@ -548,31 +553,31 @@ mod tests { assert!(next_range(&db, id).unwrap().is_none()); } - /// 单次调用的块数有硬上限:宿主传个巨大的值会让这次调用跑上几分钟且 - /// 中途无法中断,页面直接冻住。 + /// The per-call block cap is hard: a huge value would run for minutes with no + /// way to interrupt it, freezing the page. #[test] fn max_blocks_is_clamped_and_zero_is_rejected() { assert_eq!(u64::MAX.min(MAX_BLOCKS_PER_CALL), MAX_BLOCKS_PER_CALL); - // 0 会让 `start + max_blocks - 1` 下溢,必须挡在入口 + // 0 would underflow `start + max_blocks - 1`; it is rejected at the entry assert!(MAX_BLOCKS_PER_CALL > 0); } - /// **回归测试。** 扫描进度曾经是从全局 `blocks` 表取 `max(height)` 的, - /// 而那张表所有身份共享 —— 一个追到链尖的身份会把另一个还在回补的身份的 - /// 进度一起"推"到链尖,那段历史就被永久跳过、再也不会重扫。 + /// Regression: progress used to be `max(height)` over the shared `blocks` table, + /// so a caught-up identity pushed a backfilling identity's progress to the tip + /// and that history was never scanned. #[test] fn two_identities_keep_independent_progress() { use crate::wallet::testing::key_bytes; let (mut db, a) = db_with_identity(); // birthday 100 let (spend, mut view) = key_bytes(); - view[1] = 3; // 换一个观察密钥,造出第二个不同的身份 + view[1] = 3; // Different view key for a distinct second identity let b = db.add_identity("acct-2", &spend, &view, 100).unwrap().id; update_chain_tip(&mut db, a, 1_000).unwrap(); update_chain_tip(&mut db, b, 1_000).unwrap(); - // A 一路扫到链尖,B 一块没扫 + // A scans to the tip; B scans nothing consume_range(&mut db, a, 100, 1_000).unwrap(); advance_scanned_to(&db, a, 1_000).unwrap(); @@ -580,12 +585,12 @@ mod tests { assert_eq!( scanned_to_height(&db, b).unwrap(), None, - "B 一块都没扫过,进度必须仍是 None" + "B scanned nothing, so its progress must stay None" ); - // B 的待扫区间必须原封不动,仍从它的 birthday 起 - let (start, _) = next_range(&db, b).unwrap().expect("B 的区间还在"); - assert_eq!(start, 100, "B 的起点不该被 A 的进度带跑"); + // B's pending range is untouched and still starts at its birthday + let (start, _) = next_range(&db, b).unwrap().expect("B's range still queued"); + assert_eq!(start, 100, "B's start must not follow A's progress"); } #[test] @@ -596,7 +601,7 @@ mod tests { assert!(next_range(&db, id).unwrap().is_none()); rewind_and_requeue(&mut db, id, 180, 200).unwrap(); - let (start, end) = next_range(&db, id).unwrap().expect("回退后应重新排队"); + let (start, end) = next_range(&db, id).unwrap().expect("rewind should requeue"); assert_eq!((start, end), (181, 201)); } @@ -611,25 +616,25 @@ mod tests { )); } - /// 一块都没扫过就重扫(清缓存、换起点):不能从创世块开始排队。 + /// Rescanning before any step (cache cleared, new start) must not queue from genesis. #[test] fn rewinding_before_the_first_step_does_not_queue_from_genesis() { - let (mut db, id) = db_with_identity(); // 生日 100 + let (mut db, id) = db_with_identity(); // birthday 100 rewind_and_requeue(&mut db, id, 100, 200).unwrap(); update_chain_tip(&mut db, id, 200).unwrap(); assert_eq!(scanned_to_height(&db, id).unwrap(), None); - let (start, _) = next_range(&db, id).unwrap().expect("有待扫区间"); + let (start, _) = next_range(&db, id).unwrap().expect("a range is pending"); assert_eq!(start, 100); } - /// 用户选了比生日更早的日期重扫:生日跟着提前,进度的起点才对。 + /// Rescanning from before the birthday moves the birthday back so progress starts there. #[test] fn rewinding_before_the_birthday_moves_the_birthday() { - let (mut db, id) = db_with_identity(); // 生日 100 + let (mut db, id) = db_with_identity(); // birthday 100 rewind_and_requeue(&mut db, id, 49, 200).unwrap(); assert_eq!(db.identity_by_id(id).unwrap().birthday_height, 50); - let (start, _) = next_range(&db, id).unwrap().expect("有待扫区间"); + let (start, _) = next_range(&db, id).unwrap().expect("a range is pending"); assert_eq!(start, 50); } } diff --git a/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs index 0425c4c34..a9f8f7901 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs @@ -1,12 +1,12 @@ -//! 钱包库句柄与身份管理。 +//! Wallet database handle and identity management. //! -//! 一个 identity = 一对观察密钥 = 宿主眼里的一个账户。库是**共享的**: -//! 多个 identity 共用一个 SQLite 文件,各自有独立的扫描进度。 +//! One identity = one view key pair = one host account. Identities **share** a +//! SQLite file, each with its own scan progress. //! -//! 这一点和 Zcash 有个关键差别:Zcash 的扫描队列是全库共享的(承诺树要求 -//! 连续扫描),所以「用 A 的 key 扫过的区间会被标记为全库已扫」,暂停的账户 -//! 会漏掉那段。Monero 没有承诺树、不要求连续扫描,**扫描进度按 identity 独立 -//! 记账**(`scan_ranges.identity_id`),从根上不存在那个坑。 +//! Unlike Zcash, whose scan queue is database-wide (the commitment tree needs +//! contiguous scanning), Monero has no commitment tree, so **scan progress is +//! per identity** (`scan_ranges.identity_id`) and a paused account never misses +//! ranges scanned for another. use monero_wallet::{address::Network, ViewPair}; use rusqlite::{params, Connection, OptionalExtension}; @@ -16,7 +16,7 @@ use crate::error::{db_err, ErrorCode, Result, RuntimeError}; use crate::keys::{self, network_name}; use crate::schema; -/// 账户 0 下,收过钱的最大子地址之后保持登记的空闲子地址数(同比特币的 gap limit)。 +/// Unused subaddresses kept registered past the highest used one in account 0 (like Bitcoin's gap limit). pub const SUBADDRESS_LOOKAHEAD: u32 = 20; pub struct Db { @@ -24,7 +24,7 @@ pub struct Db { network: Network, } -/// 库里的一个身份。 +/// An identity in the database. pub struct Identity { pub id: i64, pub uuid: String, @@ -34,13 +34,13 @@ pub struct Identity { } impl Db { - /// 打开(或新建)一个钱包库并跑迁移。 + /// Opens (or creates) a wallet database and runs migrations. pub fn open(db_name: &str, network: Network) -> Result { let conn = crate::storage::open_connection(db_name)?; schema::migrate(&conn)?; - // 网络是库级不变量:同一个文件里混两个网络的身份,扫描会把 - // stagenet 的块喂给 mainnet 的密钥,表现为「怎么扫都扫不到钱」。 + // Network is a per-database invariant; mixing networks would feed one + // network's blocks to another's keys and silently find nothing. let existing: Option = conn .query_row("SELECT network FROM wallet_meta WHERE id = 0", [], |r| { r.get(0) @@ -84,10 +84,10 @@ impl Db { &mut self.conn } - /// 注册一个身份。已存在时按 uuid 幂等返回原有的那个。 + /// Registers an identity; idempotent by uuid. /// - /// `birthday_height` 决定回补起点。宿主给不出来时应当给链尖而不是 0 —— - /// 给 0 会让新钱包从创世块扫起,那是几天而不是几秒。 + /// `birthday_height` is where backfill starts. Without one the host should + /// pass the chain tip, not 0, which would scan from genesis. pub fn add_identity( &mut self, uuid: &str, @@ -111,12 +111,13 @@ impl Db { if address == primary { return self.identity_by_id(id); } - // 同一个账户标识换了密钥(重置后新建的钱包沿用了旧标识):旧数据属于一个 - // 已经不在的钱包,留着会被当成新钱包的,删掉。 + // Same account id with new keys (a reset wallet reused the id): the + // old data belongs to a gone wallet and would be attributed to the + // new one, so delete it. self.remove_identity(uuid)?; } - // 同一套密钥换了标识(删掉钱包后重新导入):扫描数据仍然有效,改挂到新标识下。 + // Same keys under a new id (deleted and reimported): keep the scan data under the new id. let by_address: Option = self .conn .query_row( @@ -158,9 +159,9 @@ impl Db { .map_err(|e| db_err("insertIdentity", e))?; let id = tx.last_insert_rowid(); - // 新身份的初始待扫区间:从 birthday 到 birthday(空区间), - // 真正的终点由 `update_chain_tip` 在拿到链尖后补上。这样 - // 「还没问过链尖」和「已经扫完」在库里是两种不同的状态。 + // Initial scan range is empty (birthday..birthday); `update_chain_tip` + // extends it once the tip is known, so "tip never fetched" and + // "fully scanned" stay distinct states. tx.commit().map_err(|e| db_err("commitAddIdentity", e))?; id } @@ -230,10 +231,10 @@ impl Db { .map_err(|e| db_err("listIdentities", e)) } - /// 删除一个身份连同它的全部数据。**不可逆。** + /// Deletes an identity and all its data. **Irreversible.** /// - /// 级联由外键负责(`PRAGMA foreign_keys = ON` 在 open_connection 里开)。 - /// 留下孤儿行不只是脏数据,是隐私问题 —— 「删钱包」必须真的删干净。 + /// Foreign-key cascades do the work (`PRAGMA foreign_keys = ON` in + /// open_connection). Orphan rows would be a privacy leak. pub fn remove_identity(&mut self, uuid: &str) -> Result { let n = self .conn @@ -242,7 +243,7 @@ impl Db { Ok(n > 0) } - /// 登记一个子地址。扫描前这些会被灌进 Scanner —— **没登记的收不到**。 + /// Registers a subaddress. These are fed to the Scanner; **unregistered ones receive nothing**. pub fn register_subaddress( &mut self, identity_id: i64, @@ -262,9 +263,9 @@ impl Db { Ok(address) } - /// 保证账户 0 下「收过钱的最大子地址序号 + SUBADDRESS_LOOKAHEAD」以内都已登记。 - /// 返回新登记了几个。扫描只认登记过的子地址;成本只在登记时(每个一次标量乘), - /// 扫描是反推公钥后查表,不随数量增长。 + /// Ensures account 0 has subaddresses registered up to the highest used minor + /// + SUBADDRESS_LOOKAHEAD; returns how many were added. Cost is one scalar + /// multiplication per registration; scanning is a table lookup. pub fn ensure_subaddress_lookahead(&mut self, identity_id: i64) -> Result { let (highest_used, highest_registered): (i64, i64) = self .conn @@ -287,7 +288,7 @@ impl Db { Ok(added) } - /// 取该身份已登记的全部子地址序号。 + /// All registered subaddress indices of the identity. pub fn subaddress_indices(&self, identity_id: i64) -> Result> { let mut stmt = self .conn @@ -325,7 +326,7 @@ pub(crate) mod testing { pub const ADDR: &str = "44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft3XjrpDtQGv7SqSsaBYBb98uNbr2VBBEt7f2wfn3RVGQBEP3A"; - /// 一对能用的测试密钥:花费公钥取自已知地址,观察私钥用小标量。 + /// Test keys: spend key from a known address, a small scalar as view key. pub fn key_bytes() -> ([u8; 32], [u8; 32]) { use monero_wallet::address::MoneroAddress; let addr = MoneroAddress::from_str(Network::Mainnet, ADDR).unwrap(); @@ -336,7 +337,7 @@ pub(crate) mod testing { } pub fn db() -> Db { - Db::open(":memory:", Network::Mainnet).expect("内存库") + Db::open(":memory:", Network::Mainnet).expect("in-memory db") } pub fn db_with_identity() -> (Db, i64) { @@ -344,7 +345,7 @@ pub(crate) mod testing { let (spend, view) = key_bytes(); let id = db .add_identity("acct-1", &spend, &view, 100) - .expect("建身份") + .expect("add identity") .id; (db, id) } @@ -389,7 +390,7 @@ mod tests { assert_eq!( db.ensure_subaddress_lookahead(id).unwrap(), 0, - "已够就不再登记" + "no registration once the window is full" ); } @@ -423,8 +424,8 @@ mod tests { assert_eq!(outputs, 0); } - /// 删了钱包又导入同一套助记词:新标识、同密钥,扫描数据照用,不能因为主地址 - /// 唯一约束而建不出来。 + /// Reimport after deletion (new id, same keys) reuses the scan data and must + /// not trip the primary-address unique constraint. #[test] fn the_same_keys_under_a_new_account_id_keep_their_scan() { let (mut db, old) = db_with_identity(); @@ -442,13 +443,15 @@ mod tests { let (spend, view) = key_bytes(); let a = db.add_identity("acct-1", &spend, &view, 100).unwrap(); let b = db.add_identity("acct-1", &spend, &view, 999).unwrap(); - assert_eq!(a.id, b.id, "同一 uuid 必须复用同一行"); - assert_eq!(b.birthday_height, 100, "重复注册不应改写已有的 birthday"); + assert_eq!(a.id, b.id, "same uuid must reuse the row"); + assert_eq!( + b.birthday_height, 100, + "re-registration must not overwrite the birthday" + ); assert_eq!(db.list_identities().unwrap().len(), 1); } - /// 库级网络不变量:同一个文件混两个网络会让扫描静默失效 - /// (拿 stagenet 的块喂 mainnet 的密钥,表现为「怎么扫都扫不到」)。 + /// Per-database network invariant: mixing networks silently breaks scanning. #[test] fn a_database_refuses_a_different_network() { let conn = crate::storage::open_connection(":memory:").unwrap(); @@ -458,7 +461,7 @@ mod tests { [], ) .unwrap(); - // 用同一条连接模拟「已有库」,再以 mainnet 打开应当被拒 + // Simulate an existing testnet database; opening it as mainnet must fail let recorded: String = conn .query_row("SELECT network FROM wallet_meta WHERE id = 0", [], |r| { r.get(0) @@ -477,17 +480,17 @@ mod tests { assert_eq!(by_id.primary_address, by_uuid.primary_address); assert!( by_id.primary_address.starts_with('4'), - "主网主地址以 4 开头" + "mainnet primary address starts with 4" ); } #[test] fn missing_identity_is_account_not_found_not_a_database_error() { let db = db(); - // Identity 内含 ViewPair,上游刻意不实现 Debug(免得密钥被打进日志), - // 所以这里不能用 unwrap_err —— 那要求 Ok 类型可 Debug。 + // Identity holds a ViewPair, which deliberately lacks Debug (keeps keys + // out of logs), so unwrap_err is unavailable. match db.identity_by_uuid("nope") { - Ok(_) => panic!("不存在的身份不该查得到"), + Ok(_) => panic!("missing identity must not be found"), Err(e) => assert_eq!(e.code, ErrorCode::AccountNotFound), } } @@ -499,7 +502,7 @@ mod tests { let b = db.register_subaddress(id, 1, 0, None).unwrap(); assert_ne!(a, b); assert_eq!(db.subaddress_indices(id).unwrap(), vec![(0, 1), (1, 0)]); - // 重复登记同一个序号是幂等的,不该产生第二行 + // Re-registering an index is idempotent db.register_subaddress(id, 0, 1, Some("改个标签")).unwrap(); assert_eq!(db.subaddress_indices(id).unwrap().len(), 2); } @@ -512,7 +515,7 @@ mod tests { assert!(db.subaddress_indices(id).unwrap().is_empty()); assert!( !db.remove_identity("acct-1").unwrap(), - "删第二次应当返回 false" + "second delete should return false" ); } } diff --git a/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs index e9b68a867..0dc93e7d6 100644 --- a/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs +++ b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs @@ -1,18 +1,18 @@ -//! 对**真实节点**的集成测试。默认全部跳过。 +//! Integration tests against a **real node**. All skipped by default. //! //! ```bash -//! # 你自己的节点,或一个可信的公共节点(建议 https) +//! # Your own node, or a trusted public one (https recommended) //! XMR_NODE= cargo test --test live_node -- --nocapture //! -//! # 想扫自己的钱包(只需要观察密钥,不需要花费私钥) +//! # Scan your own wallet (view keys only, no spend key) //! XMR_NODE=... \ -//! XMR_SPEND_PUB=<64位hex> XMR_VIEW_PRIV=<64位hex> XMR_BIRTHDAY=3000000 \ +//! XMR_SPEND_PUB=<64 hex chars> XMR_VIEW_PRIV=<64 hex chars> XMR_BIRTHDAY=3000000 \ //! cargo test --test live_node -- --nocapture //! ``` //! -//! 为什么要有这个:单元测试用的是构造出来的数据,**扫描循环的三道校验和 -//! RingCT 索引推算从没在真实链上跑过**。那些校验一旦写错,表现是「扫不到钱」 -//! 或者「一直报重组」,而不是编译错误。 +//! Unit tests use synthetic data; these exercise the scan loop checks and +//! RingCT index derivation on the real chain, where bugs show up as missing +//! funds or spurious reorgs rather than compile errors. use onekey_monero_runtime::{keys, network, scan, sync, wallet}; @@ -22,70 +22,73 @@ fn node() -> Option { .filter(|s| !s.trim().is_empty()) } -/// 原生传输走 `reqwest`,它需要 Tokio 的 reactor —— 用 `futures_lite::block_on` -/// 会在第一次发请求时 panic「there is no reactor running」。 +/// Native transport uses `reqwest`, which needs a Tokio reactor; +/// `futures_lite::block_on` panics with "there is no reactor running". fn block_on(f: F) -> F::Output { tokio::runtime::Builder::new_current_thread() .enable_all() .build() - .expect("Tokio 运行时") + .expect("Tokio runtime") .block_on(f) } -/// 最基本的连通性:能连上、能问到链尖。 +/// Basic connectivity: connect and read the chain tip. #[test] fn connects_and_reads_the_chain_tip() { let Some(url) = node() else { - eprintln!("跳过:未设置 XMR_NODE"); + eprintln!("skipped: XMR_NODE not set"); return; }; block_on(async { - let (daemon, _) = network::connect(&url).await.expect("连接节点"); - let tip = sync::chain_tip(&daemon).await.expect("取链尖"); - println!("链尖 = {tip}"); - assert!(tip > 3_000_000, "主网高度早就过 300 万了,{tip} 不合理"); + let (daemon, _) = network::connect(&url).await.expect("connect to node"); + let tip = sync::chain_tip(&daemon).await.expect("fetch chain tip"); + println!("chain tip = {tip}"); + assert!( + tip > 3_000_000, + "mainnet is well past height 3M; {tip} is implausible" + ); }); } -/// **这条是真正要跑的。** 扫一小段真实区块,验证: +/// **The key live test.** Scans a short range of real blocks and checks: /// -/// - 块能拉下来并被上游接受为 `ScannableBlock` -/// - 我们的连续性校验不会对合法链误报重组 -/// - 我们独立推算的 RingCT 游标与节点声称的一致 +/// - blocks download and upstream accepts them as `ScannableBlock` +/// - continuity checks raise no false reorgs on a valid chain +/// - our independently derived RingCT cursor matches the node's claim /// -/// 最后一条是重点:上游明说这个字段不可验证、要求客户端自己算并比对。 -/// 如果我们的推算逻辑错了,这里会报 `RINGCT_INDEX_MISMATCH` —— 那说明是 -/// **我们**错了,不是节点在作恶。 +/// Upstream says the last field is unverifiable and clients must compute and +/// compare it. A `RINGCT_INDEX_MISMATCH` here means **our** derivation is +/// wrong, not a malicious node. #[test] fn scans_real_blocks_without_false_alarms() { let Some(url) = node() else { - eprintln!("跳过:未设置 XMR_NODE"); + eprintln!("skipped: XMR_NODE not set"); return; }; block_on(async { - let (daemon, _) = network::connect(&url).await.expect("连接节点"); - let tip = sync::chain_tip(&daemon).await.expect("取链尖"); + let (daemon, _) = network::connect(&url).await.expect("connect to node"); + let tip = sync::chain_tip(&daemon).await.expect("fetch chain tip"); - // 从链尖往回 200 块开始扫 40 块:足够覆盖有交易的块,又不至于太慢。 + // Start 200 blocks below the tip: enough to hit transactions, still fast. let start = tip.saturating_sub(200); let count = 40u64; - let mut db = - wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap()).expect("内存库"); + let mut db = wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap()) + .expect("in-memory db"); let (spend, view) = throwaway_keys(); let identity = db .add_identity("live", &spend, &view, start) - .expect("建身份"); + .expect("add identity"); - sync::update_chain_tip(&mut db, identity.id, tip).expect("告知链尖"); + sync::update_chain_tip(&mut db, identity.id, tip).expect("update chain tip"); let mut scanned = 0u64; for _ in 0..count { let progress = sync::step(&mut db, &daemon, identity.id, 10) .await - .expect("扫描不该失败 —— 失败意味着我们的校验逻辑对合法链误报了"); + .expect("scan must not fail; a failure means our checks flagged a valid chain"); let n = progress["blocksScanned"].as_u64().unwrap_or(0); if n == 0 { break; @@ -96,15 +99,18 @@ fn scans_real_blocks_without_false_alarms() { } } - println!("扫了 {scanned} 块,从 {start} 起"); - assert!(scanned > 0, "一块都没扫到,说明拉块或扫描路径断了"); + println!("scanned {scanned} blocks from {start}"); + assert!( + scanned > 0, + "no blocks scanned; fetch or scan path is broken" + ); }); } -/// 用你自己的观察密钥扫一段,看能不能扫到输出。 +/// Scans a range with your own view keys to check outputs are found. /// -/// 需要 `XMR_SPEND_PUB` / `XMR_VIEW_PRIV` / `XMR_BIRTHDAY`。 -/// **只要观察密钥,不需要花费私钥** —— 这条测试本身就是那个边界的证明。 +/// Needs `XMR_SPEND_PUB` / `XMR_VIEW_PRIV` / `XMR_BIRTHDAY`. +/// **View keys only, no spend key.** #[test] fn scans_a_real_wallet_if_view_keys_are_supplied() { let (Some(url), Ok(spend_hex), Ok(view_hex)) = ( @@ -112,7 +118,7 @@ fn scans_a_real_wallet_if_view_keys_are_supplied() { std::env::var("XMR_SPEND_PUB"), std::env::var("XMR_VIEW_PRIV"), ) else { - eprintln!("跳过:未设置 XMR_NODE / XMR_SPEND_PUB / XMR_VIEW_PRIV"); + eprintln!("skipped: XMR_NODE / XMR_SPEND_PUB / XMR_VIEW_PRIV not set"); return; }; @@ -120,27 +126,27 @@ fn scans_a_real_wallet_if_view_keys_are_supplied() { .ok() .and_then(|s| s.parse().ok()) .unwrap_or(0); - let spend = hex::decode(spend_hex.trim()).expect("XMR_SPEND_PUB 必须是 hex"); - let view = hex::decode(view_hex.trim()).expect("XMR_VIEW_PRIV 必须是 hex"); + let spend = hex::decode(spend_hex.trim()).expect("XMR_SPEND_PUB must be hex"); + let view = hex::decode(view_hex.trim()).expect("XMR_VIEW_PRIV must be hex"); block_on(async { - let (daemon, _) = network::connect(&url).await.expect("连接节点"); - let tip = sync::chain_tip(&daemon).await.expect("取链尖"); + let (daemon, _) = network::connect(&url).await.expect("connect to node"); + let tip = sync::chain_tip(&daemon).await.expect("fetch chain tip"); - let mut db = - wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap()).expect("内存库"); + let mut db = wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap()) + .expect("in-memory db"); let identity = db .add_identity("live-wallet", &spend, &view, birthday) - .expect("建身份"); - println!("主地址 = {}", identity.primary_address); + .expect("add identity"); + println!("primary address = {}", identity.primary_address); - // 常用的几个子地址也登记上 —— 没登记的收不到。 + // Register common subaddresses; unregistered ones receive nothing. for minor in 1..=5 { db.register_subaddress(identity.id, 0, minor, None) - .expect("登记子地址"); + .expect("register subaddress"); } - sync::update_chain_tip(&mut db, identity.id, tip).expect("告知链尖"); + sync::update_chain_tip(&mut db, identity.id, tip).expect("update chain tip"); let budget_blocks = std::env::var("XMR_SCAN_BLOCKS") .ok() @@ -152,7 +158,7 @@ fn scans_a_real_wallet_if_view_keys_are_supplied() { while scanned < budget_blocks { let progress = sync::step(&mut db, &daemon, identity.id, 100) .await - .expect("扫描"); + .expect("scan"); let n = progress["blocksScanned"].as_u64().unwrap_or(0); if n == 0 || progress["done"].as_bool().unwrap_or(false) { break; @@ -161,65 +167,67 @@ fn scans_a_real_wallet_if_view_keys_are_supplied() { } let elapsed = started.elapsed(); - // 这就是明天要看的那个数字。 + // Scan throughput. println!( - "扫了 {scanned} 块,耗时 {:.1}s,{:.1} 块/秒", + "scanned {scanned} blocks in {:.1}s, {:.1} blocks/s", elapsed.as_secs_f64(), scanned as f64 / elapsed.as_secs_f64().max(0.001) ); let balance = - onekey_monero_runtime::query::balance(&db, identity.id, Some(tip)).expect("算余额"); + onekey_monero_runtime::query::balance(&db, identity.id, Some(tip)).expect("balance"); println!( - "总额 {} / 可用 {} / 不可验证 {}", + "total {} / unlocked {} / unverifiable {}", balance.total_atomic, balance.unlocked_atomic, balance.unverifiable_atomic ); }); } -/// 回退必须真的把那一段清掉并重新排队。 +/// Rewind must actually clear the range and requeue it. #[test] fn rewind_actually_rolls_back_and_requeues() { let Some(url) = node() else { - eprintln!("跳过:未设置 XMR_NODE"); + eprintln!("skipped: XMR_NODE not set"); return; }; block_on(async { - let (daemon, _) = network::connect(&url).await.expect("连接节点"); - let tip = sync::chain_tip(&daemon).await.expect("取链尖"); + let (daemon, _) = network::connect(&url).await.expect("connect to node"); + let tip = sync::chain_tip(&daemon).await.expect("fetch chain tip"); let start = tip.saturating_sub(50); - let mut db = - wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap()).expect("内存库"); + let mut db = wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap()) + .expect("in-memory db"); let (spend, view) = throwaway_keys(); - let identity = db.add_identity("rw", &spend, &view, start).expect("建身份"); - sync::update_chain_tip(&mut db, identity.id, tip).expect("告知链尖"); + let identity = db + .add_identity("rw", &spend, &view, start) + .expect("add identity"); + sync::update_chain_tip(&mut db, identity.id, tip).expect("update chain tip"); sync::step(&mut db, &daemon, identity.id, 20) .await - .expect("先扫一段"); - let before = sync::scanned_to_height(&db, identity.id).expect("进度"); - assert!(before.is_some(), "应当已经有进度"); + .expect("initial scan"); + let before = sync::scanned_to_height(&db, identity.id).expect("progress"); + assert!(before.is_some(), "progress should exist"); let target = start + 5; - sync::rewind_and_requeue(&mut db, identity.id, target, tip).expect("回退"); + sync::rewind_and_requeue(&mut db, identity.id, target, tip).expect("rewind"); - let after = sync::scanned_to_height(&db, identity.id).expect("进度"); + let after = sync::scanned_to_height(&db, identity.id).expect("progress"); assert!( after.unwrap_or(0) <= target, - "回退之后进度必须不高于目标高度,否则中间那段永远不会重扫" + "progress must not exceed the target after rewind, or the gap is never rescanned" ); - let peek = sync::peek(&db, identity.id).expect("看队列"); + let peek = sync::peek(&db, identity.id).expect("peek queue"); assert!( !peek["ranges"].as_array().unwrap().is_empty(), - "回退之后必须有待扫区间" + "ranges must be queued after rewind" ); }); } -/// 一对不对应任何真实钱包的观察密钥,用来测扫描机制本身。 +/// View keys matching no real wallet, for testing the scan machinery. fn throwaway_keys() -> ([u8; 32], [u8; 32]) { use monero_wallet::address::{MoneroAddress, Network}; const ADDR: &str = "44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft3XjrpDtQGv7SqSsaBYBb98uNbr2VBBEt7f2wfn3RVGQBEP3A"; @@ -231,13 +239,16 @@ fn throwaway_keys() -> ([u8; 32], [u8; 32]) { #[test] fn reorg_detection_rejects_a_gap() { - // 这条不需要网络:构造一个跳号的场景,确认我们报的是重组而不是静默跳过。 - let mut db = - wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap()).expect("内存库"); + // Offline: a gap must be reported as a reorg, not silently skipped. + let mut db = wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap()) + .expect("in-memory db"); let (spend, view) = throwaway_keys(); - let identity = db.add_identity("gap", &spend, &view, 0).expect("建身份"); + let identity = db + .add_identity("gap", &spend, &view, 0) + .expect("add identity"); - // 空批次是合法的 no-op,不该报错 - let outcome = scan::scan_blocks(&mut db, identity.id, &[]).expect("空批次应当无害"); + // An empty batch is a valid no-op + let outcome = + scan::scan_blocks(&mut db, identity.id, &[]).expect("empty batch should be harmless"); assert_eq!(outcome.blocks_scanned, 0); } diff --git a/chain-runtimes/monero/rust-toolchain.toml b/chain-runtimes/monero/rust-toolchain.toml index b79659373..9495f83fb 100644 --- a/chain-runtimes/monero/rust-toolchain.toml +++ b/chain-runtimes/monero/rust-toolchain.toml @@ -1,10 +1,5 @@ -# 跟当前 stable 走,不钉死版本号。 -# -# 这**不是** MSRV —— crate 声明的最低版本是 1.85(见 Cargo.toml 的 -# `rust-version`)。若用 mise 等工具管理 Rust,请让它同样跟随 stable, -# 否则这里的声明与实际使用的工具链会不一致。 -# -# 如果将来需要可复现的 wasm 产物(逐字节一致),再换成具体版本号。 +# Tracks current stable. This is not the MSRV, which is `rust-version` in +# Cargo.toml (1.85). Pin a version if byte-reproducible wasm builds are needed. [toolchain] channel = "stable" profile = "minimal" diff --git a/chain-runtimes/monero/scripts/build-node-pkg.sh b/chain-runtimes/monero/scripts/build-node-pkg.sh index 980bffbaa..c57a93ea8 100755 --- a/chain-runtimes/monero/scripts/build-node-pkg.sh +++ b/chain-runtimes/monero/scripts/build-node-pkg.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -# 出一个 nodejs target 的包,只用于本机冒烟(scripts/smoke.js)。 -# 出厂用的是 build-wasm.sh 的 web target。 +# Build a nodejs-target package for local smoke tests (scripts/smoke.js) only. +# Shipped builds use the web target from build-wasm.sh. set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" cd "${ROOT}/crates/monero-runtime" diff --git a/chain-runtimes/monero/scripts/build-wasm.sh b/chain-runtimes/monero/scripts/build-wasm.sh index 8980d885c..e5cb9c210 100755 --- a/chain-runtimes/monero/scripts/build-wasm.sh +++ b/chain-runtimes/monero/scripts/build-wasm.sh @@ -1,13 +1,12 @@ #!/usr/bin/env bash # -# 构建 wasm 产物到 pkg/。 +# Build the wasm package into pkg/. # -# 前置: -# 1. rustup(toolchain 由 rust-toolchain.toml 锁定) -# 2. wasm-pack:cargo install wasm-pack -# 3. **llvm-ar** —— macOS 自带的 /usr/bin/ar 读不懂 wasm 目标文件,会把编译好 -# 的 .o 静默打成空归档,链接期报一串 `undefined symbol: sqlite3_*`。 -# 归档器由 .cargo/config.toml 指定,这里只做存在性检查给出可读提示。 +# Requires: +# 1. rustup (toolchain set by rust-toolchain.toml) +# 2. wasm-pack: cargo install wasm-pack +# 3. llvm-ar, configured in .cargo/config.toml. macOS /usr/bin/ar silently +# writes empty archives for wasm objects (`undefined symbol: sqlite3_*`). set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" @@ -16,16 +15,16 @@ OUT="${ROOT}/pkg" AR="$(sed -n 's/^AR_wasm32_unknown_unknown = "\(.*\)"/\1/p' "${ROOT}/.cargo/config.toml")" if [[ -n "${AR}" && ! -x "${AR}" ]]; then - echo "✗ 找不到 ${AR}" >&2 - echo " wasm 目标需要 llvm-ar;系统自带的 ar 会静默产出空归档。" >&2 - echo " 装一个:brew install llvm" >&2 + echo "✗ ${AR} not found" >&2 + echo " wasm targets need llvm-ar; the system ar silently writes empty archives." >&2 + echo " install it: brew install llvm" >&2 exit 1 fi -# --mode no-install 找不到 wasm-opt 只会打一行 INFO 然后跳过:产物不报错地胖 -#(函数名段不剥、不做 -O)。release 必须有它。 +# With --mode no-install, a missing wasm-opt is only logged and skipped, leaving +# an unoptimized output. Release builds require it. if [ "${PROFILE}" = "release" ] && ! command -v wasm-opt >/dev/null 2>&1; then - echo "✗ 找不到 wasm-opt(Binaryen),release 产物会不经优化直接输出" >&2 + echo "✗ wasm-opt (Binaryen) not found; the release build would be unoptimized" >&2 exit 1 fi @@ -37,5 +36,5 @@ case "${PROFILE}" in *) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --dev ;; esac -echo "==> 产物" +echo "==> output" du -h "${OUT}"/*.wasm diff --git a/chain-runtimes/monero/scripts/smoke.js b/chain-runtimes/monero/scripts/smoke.js index 7cdba2191..981e4c79c 100755 --- a/chain-runtimes/monero/scripts/smoke.js +++ b/chain-runtimes/monero/scripts/smoke.js @@ -1,9 +1,9 @@ #!/usr/bin/env node /** - * 端到端冒烟:派生 → 开库 → 建账户 → 子地址 → 余额 → 扫描队列 → 选币。 + * End-to-end smoke test against the real wasm build: derive -> open DB -> + * add account -> subaddress -> balance -> scan queue -> coin selection. * - * 不需要节点、不需要网络。跑的是真实 wasm,不是 mock —— 这条脚本存在的意义 - * 是「编译通过」和「真的能用」之间那道坎。 + * Offline by default; set XMR_NODE_URL to also run the node checks. * * ./scripts/build-node-pkg.sh && node scripts/smoke.js */ @@ -15,93 +15,91 @@ let failures = 0; function check(label, actual, expected) { const ok = actual === expected; if (!ok) failures += 1; - console.log(`${ok ? '✓' : '✗'} ${label}${ok ? '' : ` 期望 ${expected},实际 ${actual}`}`); + console.log(`${ok ? '✓' : '✗'} ${label}${ok ? '' : ` expected ${expected}, got ${actual}`}`); } -// 固定私钥:派生必须是确定性的,换一次运行结果不能变 +// Fixed key: derivation must be deterministic across runs. const key = '0'.repeat(63) + '7'; const a = JSON.parse(rt.deriveAccount('mainnet', key)); const b = JSON.parse(rt.deriveAccount('mainnet', key)); -check('派生是确定性的', a.primaryAddress, b.primaryAddress); -check('主网主地址长度 95', a.primaryAddress.length, 95); -check('主网主地址以 4 开头', a.primaryAddress[0], '4'); -check('自己的地址自己认', rt.validateAddress('mainnet', a.primaryAddress), true); -check('主网地址在测试网被拒', rt.validateAddress('testnet', a.primaryAddress), false); +check('derivation is deterministic', a.primaryAddress, b.primaryAddress); +check('mainnet primary address length is 95', a.primaryAddress.length, 95); +check('mainnet primary address starts with 4', a.primaryAddress[0], '4'); +check('own address validates', rt.validateAddress('mainnet', a.primaryAddress), true); +check('mainnet address rejected on testnet', rt.validateAddress('testnet', a.primaryAddress), false); const sub = JSON.parse( rt.deriveSubaddress('mainnet', a.spendPublicKeyHex, a.viewPrivateKeyHex, 0, 1), ); -check('子地址以 8 开头', sub.address[0], '8'); -check('子地址不等于主地址', sub.address !== a.primaryAddress, true); +check('subaddress starts with 8', sub.address[0], '8'); +check('subaddress differs from primary address', sub.address !== a.primaryAddress, true); -// SQLite 路径。`:memory:` 走特例分支,不需要 OPFS。 +// SQLite path. `:memory:` is special-cased and needs no OPFS. rt.openWallet(':memory:', 'mainnet'); const added = JSON.parse( rt.addAccount('smoke', a.spendPublicKeyHex, a.viewPrivateKeyHex, 3700000n), ); -check('落库地址与纯派生一致', added.primaryAddress, a.primaryAddress); +check('stored address matches derivation', added.primaryAddress, a.primaryAddress); const id = BigInt(added.accountId); rt.registerSubaddress(id, 0, 1); const balance = JSON.parse(rt.balance(id, undefined)); -check('空钱包总额为 0', balance.totalAtomic, '0'); -// 不知道链尖时可用余额必须是 0,不能乐观放行 -check('不知链尖则可用为 0', balance.unlockedAtomic, '0'); +check('empty wallet total is 0', balance.totalAtomic, '0'); +// Unlocked balance must be 0 while the chain tip is unknown. +check('unlocked is 0 without a chain tip', balance.unlockedAtomic, '0'); rt.updateChainTip(id, 3700100n); const peek = JSON.parse(rt.syncPeek(id)); -check('待扫区间从 birthday 起', peek.ranges[0].start, 3700000); -check('待扫区间到链尖+1', peek.ranges[0].end, 3700101); -check('尚未扫过任何块', peek.scannedToHeight, null); +check('pending range starts at birthday', peek.ranges[0].start, 3700000); +check('pending range ends at tip + 1', peek.ranges[0].end, 3700101); +check('no blocks scanned yet', peek.scannedToHeight, null); const diag = JSON.parse(rt.diagDatabase()); -check('身份入库', diag.counts.identities, 1); -check('子地址入库', diag.counts.subaddresses, 1); +check('identity stored', diag.counts.identities, 1); +check('subaddress stored', diag.counts.subaddresses, 1); -// 签名入口是纯计算,不碰网络也不碰库。坏输入必须报错 —— 静默接受会让一笔 -// 垃圾交易一路走到广播。 +// Signing is pure computation. Bad input must be rejected, never passed on to broadcast. for (const [label, hex, reason] of [ - ['非十六进制', 'zz', 'notHex'], - ['不是可签名交易', '00010203', 'notASignableTransaction'], + ['non-hex input', 'zz', 'notHex'], + ['an unsignable transaction', '00010203', 'notASignableTransaction'], ]) { try { rt.signTransaction(hex, '00'.repeat(32)); - check(`签名拒绝${label}`, 'succeeded', 'failed'); + check(`signing rejects ${label}`, 'succeeded', 'failed'); } catch (e) { const err = JSON.parse(e.message ?? e); - check(`签名拒绝${label}`, err.params.reason, reason); + check(`signing rejects ${label}`, err.params.reason, reason); } } -// 需要节点的部分。没给 XMR_NODE_URL 就跳过,这样这条脚本在离线环境里依然 -// 是绿的 —— 把「没测」和「测失败」混成一个结果是最糟的。 +// Node checks; skipped (and reported as skipped) without XMR_NODE_URL. async function online() { const url = process.env.XMR_NODE_URL; if (!url) { - console.log('\n(跳过联网检查:未设置 XMR_NODE_URL)'); + console.log('\n(skipping node checks: XMR_NODE_URL not set)'); return; } - console.log(`\n联网检查 ${url}`); + console.log(`\nnode checks against ${url}`); await rt.setNodeUrl(url); const tip = JSON.parse(await rt.chainTip()); - check('链尖是正整数', Number.isInteger(tip.height) && tip.height > 0, true); - console.log(` 链尖 ${tip.height}`); + check('chain tip is a positive integer', Number.isInteger(tip.height) && tip.height > 0, true); + console.log(` chain tip ${tip.height}`); - // 真正扫一段。走的是二进制路由(get_blocks_by_height.bin),它和 JSON 路由 - // 的 Content-Type 不同 —— 这一步同时验证了那个分支。 + // Scan a real range over the binary route (get_blocks_by_height.bin), which + // uses a different Content-Type from the JSON routes. rt.updateChainTip(id, BigInt(tip.height)); rt.rewindTo(id, BigInt(tip.height - 20), BigInt(tip.height)); const step = JSON.parse(await rt.syncStep(id, 20n)); - check('扫到了块', step.blocksScanned > 0, true); + check('blocks scanned', step.blocksScanned > 0, true); console.log( - ` 扫了 ${step.blocksScanned} 块,下载 ${step.msDownload}ms / 扫描 ${step.msScan}ms`, + ` scanned ${step.blocksScanned} blocks, download ${step.msDownload}ms / scan ${step.msScan}ms`, ); - // 空钱包构造交易必须报「余额不足」。这条同时证明了取手续费率的往返是通的 - // —— 手续费率在选币之前就要问节点。 + // An empty wallet must fail with insufficient funds. The fee rate is fetched + // before coin selection, so this also covers that round trip. try { await rt.prepareTransaction( id, @@ -111,23 +109,23 @@ async function online() { BigInt(tip.height), 'normal', ); - check('空钱包构造应当失败', 'succeeded', 'failed'); + check('empty wallet build fails', 'succeeded', 'failed'); } catch (e) { const err = JSON.parse(e.message ?? e); - check('空钱包构造报余额不足', err.params.reason, 'insufficientUnlockedFunds'); + check('empty wallet build reports insufficient funds', err.params.reason, 'insufficientUnlockedFunds'); } const released = JSON.parse(rt.releaseReservation('smoke-r1')); - check('失败的构造没有留下预留', released.released, 0); + check('failed build leaves no reservation', released.released, 0); } online() .catch((e) => { failures += 1; - console.log(`✗ 联网检查抛错: ${e.message ?? e}`); + console.log(`✗ node checks threw: ${e.message ?? e}`); }) .then(() => { rt.closeWallet(); - console.log(failures === 0 ? '\n全部通过' : `\n${failures} 项失败`); + console.log(failures === 0 ? '\nall passed' : `\n${failures} failed`); process.exit(failures === 0 ? 0 : 1); }); diff --git a/chain-runtimes/zcash/.cargo/config.toml b/chain-runtimes/zcash/.cargo/config.toml index 79febffe2..031c7fde5 100644 --- a/chain-runtimes/zcash/.cargo/config.toml +++ b/chain-runtimes/zcash/.cargo/config.toml @@ -1,4 +1,4 @@ -# getrandom 0.4 在 wasm32-unknown-unknown 上必须显式指定后端, -# 否则编译期报 "the wasm* targets are not supported by default"。 +# getrandom 0.4 needs an explicit backend on wasm32-unknown-unknown, otherwise +# it fails with "the wasm* targets are not supported by default". [target.wasm32-unknown-unknown] rustflags = ['--cfg', 'getrandom_backend="wasm_js"'] diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml index fce978a00..4f5bbb55f 100644 --- a/chain-runtimes/zcash/Cargo.toml +++ b/chain-runtimes/zcash/Cargo.toml @@ -13,30 +13,29 @@ edition = "2021" license = "Apache-2.0" rust-version = "1.85" -# ── Zcash 依赖:官方稳定发布线 ─────────────────────────────────────────── +# ── Zcash dependencies: official stable releases ───────────────────────── # -# 硬约束:存储层必须来自 crates.io 上未修改的官方发布版。 -# 我们不 vendor、不 fork 任何 zcash 存储实现。 +# Hard rule: the storage layer comes from unmodified crates.io releases; no +# vendored or forked zcash storage code. # -# Zcash 存储层仅有 zcash_client_sqlite 的一处 Cargo.toml 改动(见 -# scripts/vendor-deps.sh 与 patches/),它取消 rusqlite 的 "bundled" feature — -# 那个 feature 会在构建期编译 SQLite 的 C 源码,而 wasm32 没有 libc sysroot。 -# Zcash Rust 源码零改动。VFS 的持久化补丁另见 patches/manifest.json。 +# The only change is one Cargo.toml edit to zcash_client_sqlite (see +# scripts/vendor-deps.sh and patches/) that drops rusqlite's "bundled" feature, +# which compiles SQLite's C sources and needs a libc sysroot wasm32 lacks. +# No Zcash Rust source is modified. VFS persistence patches: patches/manifest.json. [workspace.dependencies] blake2b_simd = "1" zcash_client_backend = { version = "0.24.0", default-features = false, features = ["orchard", "transparent-inputs", "lightwalletd-tonic", "sync", "pczt"] } -# serde: create_pczt_from_proposal 要求 AccountId: Serialize +# serde: create_pczt_from_proposal requires AccountId: Serialize. zcash_client_sqlite = { version = "0.22.0", default-features = false, features = ["orchard", "transparent-inputs", "serde"] } zcash_keys = { version = "0.16.1", features = ["orchard", "sapling", "transparent-inputs"] } zcash_protocol = "0.10" -# default-features = false 关键:默认带 multicore,而 wasm32 无 atomics 时 -# halo2_proofs 会直接 compile_error。 +# default-features = false is required: the default multicore feature makes +# halo2_proofs compile_error on wasm32 without atomics. zcash_primitives = { version = "0.30", default-features = false } transparent = { package = "zcash_transparent", version = "0.10" } zcash_address = "0.13" zip321 = "0.9.0" -# 与 zcash_client_backend 完全一致的配置:默认 feature 全关。 -# 开着默认 feature 会拉到已 yank 的 core2 0.3。 +# Same as zcash_client_backend: default features off. They pull the yanked core2 0.3. pczt = { version = "0.9.3", default-features = false } orchard = { version = "0.15", default-features = false } @@ -52,8 +51,8 @@ tracing = "0.1" tracing-wasm = "0.2" tracing-subscriber = { version = "0.3", default-features = false, features = ["registry", "std"] } -# 必须与 zcash_client_sqlite 的 rand_core 保持同一大版本(0.6 线), -# 否则 RngCore trait 对不上,init_wallet_db 的泛型约束不满足。 +# Must match zcash_client_sqlite's rand_core major (0.6), or RngCore does not +# unify and init_wallet_db's bounds fail. rand = "0.8" rand_chacha = "0.3" serde = { version = "1", features = ["derive"] } @@ -66,30 +65,27 @@ schemerz-rusqlite = "0.370" futures-util = { version = "0.3", default-features = false } sapling = { package = "sapling-crypto", version = "0.7", default-features = false } -# lightwalletd 走 gRPC-web:浏览器里跑不了原生 gRPC。 -# tonic-web-wasm-client 必须 >= 0.9.1 —— 0.8.0 会丢 gRPC trailer(上游已修)。 +# lightwalletd uses gRPC-web; browsers cannot speak native gRPC. +# tonic-web-wasm-client must be >= 0.9.1: 0.8.0 drops gRPC trailers. hex = "0.4" prost = "0.14" tonic = { version = "0.14", default-features = false, features = ["codegen"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] } tonic-web-wasm-client = "0.9.1" -# zcash_client_sqlite 的官方发布版 + 单行 no-bundled patch。 -# 先跑 `bash scripts/vendor-deps.sh` 生成 vendor/ 目录。 +# Official zcash_client_sqlite release plus the one-line no-bundled patch. +# Run `bash scripts/vendor-deps.sh` first to create vendor/. [patch.crates-io] zcash_client_sqlite = { path = "vendor/zcash_client_sqlite-0.22.0" } tonic-web-wasm-client = { path = "vendor/tonic-web-wasm-client-0.9.1" } [profile.release] -# "s" 是量过的选择,不是省事的默认:opt-level = 3 在主网扫描上快不出 -# 噪声(msScan 7350-8805 vs 8064-8218 / 1000 块),wasm 却大 31%(6.8→8.9MB)。 +# Measured: opt-level = 3 is no faster on mainnet scans (msScan 7350-8805 vs +# 8064-8218 per 1000 blocks) but makes the wasm 31% larger (6.8 -> 8.9 MB). opt-level = "s" lto = true codegen-units = 1 -# 不要用 panic = "abort"。 -# -# 在 wasm 上 abort 会直接杀死实例:没有 JS 异常、没有 Promise reject、 -# 没有任何日志 —— 调用方看到的是一个永远不 settle 的 Promise, -# 表现和「卡死」完全一样,无法区分也无法排查。 -# unwind 则会变成一条带 message 的 JS 异常,宿主能 catch、能上报。 +# Do not use panic = "abort": on wasm it kills the instance silently and the +# caller sees a Promise that never settles. unwind surfaces as a JS exception +# with a message that the host can catch and report. panic = "unwind" diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml index 034670e5e..2c614da14 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml @@ -4,16 +4,14 @@ version.workspace = true edition.workspace = true license.workspace = true rust-version.workspace = true -description = "OneKey Zcash — 仅密钥派生与签名。不含存储、扫链与网络。" +description = "OneKey Zcash keys: derivation and signing only, no storage, scanning or network" [lib] crate-type = ["cdylib", "rlib"] -# 刻意保持极小的依赖面:这个 crate 会被移动端打包, -# 每多一个依赖都是 iOS/Android 包体的直接成本。 -# -# 明确**不**依赖:zcash_client_backend、zcash_client_sqlite、rusqlite、 -# sqlite-wasm-rs、tonic —— 那些属于 onekey-zcash-runtime。 +# Minimal dependencies: this crate ships in mobile bundles. Deliberately excludes +# zcash_client_backend, zcash_client_sqlite, rusqlite, sqlite-wasm-rs, and tonic, +# which belong to onekey-zcash-runtime. [dependencies] zcash_keys.workspace = true zcash_protocol.workspace = true @@ -29,17 +27,16 @@ serde_json.workspace = true hex.workspace = true secp256k1 = { version = "0.29", features = ["alloc"], default-features = false } zcash_script = { version = "0.4.3", default-features = false } -# signer + orchard:本包唯一的职责就是给 PCZT 的 Orchard 花费签名。 -# 不开 prover/tx-extractor —— 那些属于 runtime 包。 -# transparent:屏蔽(transparent → shielded)必须签透明输入,否则打进 t 地址的钱 -# 出不来。它会连带拉入 zcash_script(0.4 起是纯 Rust,能上 wasm32)。 +# signer + orchard: sign PCZT Orchard spends. prover/tx-extractor belong to the runtime crate. +# transparent: shielding must sign transparent inputs. Pulls in zcash_script (pure Rust +# since 0.4, builds for wasm32). pczt = { workspace = true, features = ["signer", "orchard", "transparent", "zcp-builder", "spend-finalizer", "io-finalizer"] } transparent = { workspace = true, features = ["transparent-inputs"] } orchard = { version = "0.15", default-features = false } sapling.workspace = true thiserror.workspace = true -# bip0039 只在测试里出现:出厂产物不收助记词,宿主传种子字节。 +# bip0039 is test-only: shipped builds take seed bytes, never a mnemonic. [dev-dependencies] bip0039 = { version = "0.12", features = ["all-languages"] } @@ -47,11 +44,11 @@ bip0039 = { version = "0.12", features = ["all-languages"] } wasm-bindgen.workspace = true js-sys.workspace = true getrandom = { workspace = true, features = ["wasm_js"] } -# 依赖树里同时存在 getrandom 0.2(被老一些的 crate 拉入),它需要旧式的 "js" -# feature 才能在 wasm32-unknown-unknown 上编译。两个都要显式打开。 +# Older crates also pull in getrandom 0.2, which needs the legacy "js" feature on +# wasm32-unknown-unknown. getrandom_02 = { package = "getrandom", version = "0.2", features = ["js"] } -# wasm-pack 默认跑 `wasm-opt -O`;-Oz 更激进地压体积。 -# 代价是构建慢一些,运行时性能差异对我们这类 IO 密集的负载可忽略。 +# -Oz instead of wasm-pack's default -O: smaller output; slower builds, negligible +# runtime cost for this IO-bound workload. [package.metadata.wasm-pack.profile.release] wasm-opt = ["-Oz", "--enable-bulk-memory", "--enable-nontrapping-float-to-int"] diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs index fa9db7953..ba3518ee3 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs @@ -1,6 +1,6 @@ -//! 面向宿主的密钥接口。 +//! Host-facing key API. //! -//! 出口只有 UFVK 与地址 —— 种子和花费密钥永远不跨这条边界。 +//! Seeds and spending keys never cross this boundary outward. use wasm_bindgen::prelude::*; use zeroize::Zeroizing; @@ -13,13 +13,11 @@ pub fn validate_address(network: &str, address: &str) -> Result { Ok(keys::validate_address(network, address)?) } -/// 从 UFVK 取统一地址。纯公开材料,不涉及私钥。 +/// Derive the Unified Address from a UFVK. Public material only. /// -/// `receiverPolicy` 决定 UA 里包含哪些 receiver:`"all"` / `"shielded"` / -/// `"orchard"`。**这是隐私策略,由宿主决定,没有缺省值** —— 带 transparent -/// receiver 的地址别人可以用公开方式付给你,代价是把你的透明与屏蔽活动关联 -/// 起来。省略这个参数曾经等于选中 `"all"`,也就是那个代价最大的取值:调用方 -/// 什么都没写,却替用户做了这个决定。 +/// `receiverPolicy` selects the receivers: `"all"` / `"shielded"` / `"orchard"`. +/// It is a host privacy decision with no default: a transparent receiver links +/// the user's transparent and shielded activity. #[wasm_bindgen(js_name = unifiedAddress)] pub fn unified_address( network: &str, @@ -29,9 +27,7 @@ pub fn unified_address( Ok(keys::unified_address_with(network, ufvk, receiver_policy)?) } -/// 从**种子字节**派生 UFVK。 -/// -/// 助记词只在解密那一刻出现一次,之后全程传种子 —— 本边界不收助记词。 +/// Derive a UFVK from seed bytes. This boundary never accepts a mnemonic. #[wasm_bindgen(js_name = ufvkFromSeed)] pub fn ufvk_from_seed(network: &str, seed: Vec, account_index: u32) -> Result { // Own and wipe the original bindgen allocation, including on validation errors. @@ -41,10 +37,10 @@ pub fn ufvk_from_seed(network: &str, seed: Vec, account_index: u32) -> Resul Ok(keys::ufvk_from_seed_bytes(params, &seed, account_index)?) } -/// 用**种子字节**给 PCZT 签名。整个方案里唯一接触花费密钥的接口之一。 +/// Sign a PCZT with seed bytes after verifying it against the reviewed payment. /// -/// 花费密钥在 Rust 侧从种子现场派生、用完即弃,不跨边界返回。 -/// 调用方负责擦除自己那份种子 —— 这一侧擦不了 JS 堆上的副本。 +/// Spending keys are derived in Rust and never returned. The caller wipes its +/// own seed copy; this side cannot wipe the JS heap. #[wasm_bindgen(js_name = pcztSignWithSeed)] pub fn pczt_sign_with_seed( network: &str, @@ -70,20 +66,19 @@ pub fn pczt_verify_review(pczt_bytes: Vec, review_json: &str) -> Result<(), Ok(review::verify_json(&pczt_bytes, review_json)?) } -/// 从 UFVK 取透明收款地址(t 地址)。离线可算,不需要钱包库。 +/// Derive the transparent receiving address (t-address) from a UFVK, offline. #[wasm_bindgen(js_name = transparentAddressFromUfvk)] pub fn transparent_address_from_ufvk(network: &str, ufvk: &str) -> Result { Ok(keys::transparent_address(network, ufvk)?) } -/// UFVK 的透明账户公钥(chain code || 压缩公钥,hex)。见 keys::transparent_account_pubkey。 +/// Transparent account pubkey (chain code || compressed key, hex). See `keys::transparent_account_pubkey`. #[wasm_bindgen(js_name = transparentAccountPubKeyFromUfvk)] pub fn transparent_account_pubkey_from_ufvk(network: &str, ufvk: &str) -> Result { Ok(keys::transparent_account_pubkey(network, ufvk)?) } -/// 种子指纹(ZIP-32 标准值)。宿主拿它当账户身份持久化, -/// 所以必须与标准一致 —— 不能另发明一套哈希。 +/// Standard ZIP-32 seed fingerprint, persisted by the host as account identity. #[wasm_bindgen(js_name = seedFingerprint)] pub fn seed_fingerprint(seed: Vec) -> Result { let seed = Zeroizing::new(seed); @@ -125,8 +120,8 @@ pub fn transparent_tx_build_with_account_xprv( )?) } -/// keys 侧**实际**能签什么。与 runtime 的 `capabilities()` 合并后才是完整判断: -/// 一笔交易要能发出去,证明和签名两边都得支持同一种 bundle。 +/// What the keys side can sign. Combine with the runtime's `capabilities()`: +/// a bundle is usable only if both proving and signing support it. #[wasm_bindgen(js_name = keysCapabilities)] pub fn keys_capabilities() -> String { serde_json::json!({ @@ -185,7 +180,7 @@ pub fn transparent_tx_combine_hardware_signed( )?) } -/// 本 crate 锁定的官方依赖版本。 +/// Pinned upstream dependency versions. #[wasm_bindgen(js_name = keysDependencyVersions)] pub fn dependency_versions() -> String { crate::dependency_versions().to_string() diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs index 835faf9d2..7e863dc4e 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs @@ -1,29 +1,29 @@ -//! 错误契约。与 `onekey-zcash-runtime` 完全同构: -//! **稳定错误码 + 结构化参数,Rust 侧不产出面向用户的文案。** +//! Error contract, same shape as `onekey-zcash-runtime`: stable error codes plus +//! structured params. Rust never produces user-facing text. //! -//! 两个包的错误码取值空间不重叠,宿主可以用同一套 catch 逻辑处理。 +//! The two crates' code sets do not overlap, so hosts can share one handler. use serde_json::{json, Map, Value}; use std::fmt; -/// 稳定错误码。只允许追加,不允许改动已有取值的含义。 +/// Stable error codes. Append only; never change the meaning of an existing code. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ErrorCode { - /// 网络名不是 "main" / "test"。参数:`{ value }` + /// Network is not "main" / "test". Params: `{ value }` InvalidNetwork, - /// 助记词无法解析。 + /// Mnemonic cannot be parsed. InvalidMnemonic, - /// 种子过短。参数:`{ byteLen, min }` + /// Seed is too short. Params: `{ byteLen, min }` InvalidSeed, - /// 账户序号越界。参数:`{ value }` + /// Account index out of range. Params: `{ value }` InvalidAccountIndex, - /// UFVK 无法解析。 + /// UFVK cannot be parsed. InvalidUfvk, - /// 密钥派生失败。 + /// Key derivation failed. DeriveFailed, - /// PCZT 解析失败。 + /// PCZT cannot be parsed. PcztParseFailed, - /// PCZT 签名失败。参数:`{ orchardActions }`(能取到时) + /// PCZT signing failed. Params: `{ orchardActions }` when available. PcztSignFailed, /// The stateless transparent transaction request is malformed. InvalidTransactionRequest, @@ -97,12 +97,12 @@ impl ErrorCode { #[derive(Debug)] pub struct KeysError { pub code: ErrorCode, - /// 结构化参数,供宿主填 i18n 占位符。永远是 JSON 对象。 + /// Structured params for host i18n placeholders. Always a JSON object. pub params: Value, - /// 上游原始报错,**仅用于日志**。 + /// Raw upstream error, for logs only. /// - /// 注意:本包处理密钥材料,任何 detail 都不得包含种子、USK 或其派生物。 - /// 上游库的错误只描述结构问题,不回显输入,所以直接透传是安全的。 + /// Must never contain seeds, USKs, or anything derived from them. Upstream + /// errors describe structure and do not echo input, so passing them through is safe. pub detail: Option, } @@ -147,7 +147,7 @@ impl std::error::Error for KeysError {} pub type Result = std::result::Result; -/// 抛给 JS:`Error` 上挂 `code` / `params` / `detail`。 +/// Thrown to JS as an `Error` carrying `code` / `params` / `detail`. #[cfg(target_arch = "wasm32")] impl From for wasm_bindgen::JsValue { fn from(e: KeysError) -> Self { @@ -212,10 +212,10 @@ mod tests { let mut seen = std::collections::HashSet::new(); for c in all { let s = c.as_str(); - assert!(seen.insert(s), "错误码重复: {s}"); + assert!(seen.insert(s), "duplicate error code: {s}"); assert!( s.chars().all(|ch| ch.is_ascii_uppercase() || ch == '_'), - "格式不对: {s}" + "malformed error code: {s}" ); } } diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs index 0639d0fa7..a1d3059f3 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs @@ -1,7 +1,7 @@ -//! 密钥派生。 +//! Key derivation. //! -//! 种子和 USK 的生命周期严格控制在本模块内:入口接收字节、出口只给 -//! UFVK 与地址,中间副本用完即 `zeroize`。 +//! Seeds and USKs never leave this module: input is seed bytes, output is only +//! UFVKs and addresses. use zcash_keys::keys::{UnifiedFullViewingKey, UnifiedSpendingKey}; use zcash_protocol::consensus::Network; @@ -46,10 +46,9 @@ pub fn validate_address(network: &str, encoded: &str) -> Result { Ok(supported_recipient(¶ms, encoded).is_some()) } -/// 测试专用:从助记词派生 UFVK。 +/// Test-only: derive a UFVK from a mnemonic. /// -/// 出厂产物不收助记词 —— 宿主只传种子字节。留着它是为了让金标向量测试 -/// 能直接喂参考实现用的助记词。 +/// Shipped builds never take a mnemonic; the host passes seed bytes only. #[cfg(test)] pub(crate) fn ufvk_from_mnemonic( network: &str, @@ -63,10 +62,11 @@ pub(crate) fn ufvk_from_mnemonic( ufvk_from_seed_bytes(params, seed.as_ref(), account_index) } -/// 从原始种子字节派生 UFVK。 +/// Derive a UFVK from raw seed bytes. /// -/// 调用方给的切片本 crate 不持有。注意中间的 `UnifiedSpendingKey` 上游没有 -/// `ZeroizeOnDrop`,析构后仍留在线性内存里 —— 擦除责任在宿主那一侧。 +/// The seed slice is borrowed, not retained. Upstream `UnifiedSpendingKey` is not +/// `ZeroizeOnDrop`, so the intermediate USK stays in linear memory after drop; +/// wiping is the host's responsibility. pub fn ufvk_from_seed_bytes(params: Network, seed: &[u8], account_index: u32) -> Result { if seed.len() < 32 { return Err(KeysError::with( @@ -91,22 +91,17 @@ pub fn ufvk_from_seed_bytes(params: Network, seed: &[u8], account_index: u32) -> Ok(ufvk.encode(¶ms)) } -/// UA 里包含哪些 receiver。**这是隐私策略,不是协议事实** —— -/// 带不带 transparent receiver 决定了对方能不能用公开方式付给你, -/// 也决定了这个地址会不会把你的透明活动和屏蔽活动关联起来。所以由宿主指定。 +/// Receivers to include in a UA. This is a privacy policy chosen by the host: +/// a transparent receiver links the user's transparent and shielded activity. +/// The runtime only checks that the combination is valid. /// -/// Runtime 只负责校验组合在协议上是否成立。 -/// -/// **任何取值都不含 Sapling receiver。** 本 runtime 不能花 Sapling(不带它的 -/// prover),地址里放一个 Sapling receiver,只认 Sapling 的付款方就会把钱打 -/// 进一个这里花不出去的池子。`"shielded"` 因此与 `"orchard"` 相同,保留这个 -/// 取值只为不打断已有的调用方。 +/// No policy includes a Sapling receiver: this runtime cannot spend Sapling, so +/// Sapling-only senders would pay into an unspendable pool. `"shielded"` is +/// therefore an alias of `"orchard"`, kept for existing callers. fn receiver_policy(name: &str) -> Result { use zcash_keys::keys::{ReceiverRequirement::*, UnifiedAddressRequest as R}; match name { - // 空串不再当作 `"all"`。缺省最省事的那个取值恰好是隐私上最贵的一个: - // 带 transparent receiver 的 UA 会把用户的透明活动和屏蔽活动绑在 - // 同一个字符串里,而调用方什么都没写,也就什么都没同意。 + // No default: an empty policy must not silently select the least private option. "all" => Ok(R::unsafe_custom(Require, Omit, Allow)), "shielded" | "orchard" => Ok(R::ORCHARD), other => Err(KeysError::with( @@ -116,9 +111,9 @@ fn receiver_policy(name: &str) -> Result Result { let params = parse_network(network)?; let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str) @@ -131,16 +126,17 @@ pub fn unified_address_with(network: &str, ufvk_str: &str, policy: &str) -> Resu Ok(addr.encode(¶ms)) } -/// 从 UFVK 取透明收款地址(t 地址)。不涉及任何私钥、不需要钱包库。 +/// Derive the transparent receiving address (t-address) from a UFVK. No +/// spending key or wallet database involved. /// -/// 与 UA 是同一份 UFVK 的两种呈现:UA 是包含多个 receiver 的统一地址, -/// 这里取出其中的透明 receiver 单独编码。交易所之类只认 t 地址的场合要用它。 +/// This is the transparent receiver of the `"all"` UA, encoded on its own for +/// counterparties that only accept t-addresses. pub fn transparent_address(network: &str, ufvk_str: &str) -> Result { let params = parse_network(network)?; let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str) .map_err(|e| KeysError::new(ErrorCode::InvalidUfvk).detail(e))?; - // 与 `"all"` 取同一个地址,保证这里的 t 地址就是 UA 里的透明 receiver。 + // Same address as `"all"`, so this matches the UA's transparent receiver. let (addr, _) = ufvk .default_address(receiver_policy("all")?) .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?; @@ -157,9 +153,9 @@ pub fn transparent_address(network: &str, ufvk_str: &str) -> Result { )) } -/// UFVK 里的透明账户公钥,BIP32 账户层(m/44'/133'/account'): -/// 32 字节 chain code || 33 字节压缩公钥,hex。宿主据此拼 xpub, -/// 硬件账户无需再向设备额外要一次透明 xpub。 +/// Transparent account public key from the UFVK at the BIP32 account level +/// (m/44'/133'/account'), hex of 32-byte chain code || 33-byte compressed key. +/// The host builds the xpub from it without asking a hardware device again. pub fn transparent_account_pubkey(network: &str, ufvk_str: &str) -> Result { let params = parse_network(network)?; let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str) @@ -190,17 +186,17 @@ pub fn seed_fingerprint(seed: &[u8]) -> Result { mod tests { use super::*; - /// 指纹是**标准值**且被宿主持久化当账户身份。这条测试锁死它: - /// 实现哪天漂了,存量账户会全部失配,而那种故障很难从现象反推。 + /// The fingerprint is a standard value persisted as account identity; any + /// drift would orphan existing accounts. #[test] fn seed_fingerprint_is_stable() { let seed = [0x42u8; 64]; let fp = seed_fingerprint(&seed).unwrap(); - assert_eq!(fp.len(), 64, "32 字节 → 64 位 hex"); - assert_eq!(fp, seed_fingerprint(&seed).unwrap(), "同一种子必须同一指纹"); - // 换一个种子必须变 + assert_eq!(fp.len(), 64, "32 bytes -> 64 hex chars"); + assert_eq!(fp, seed_fingerprint(&seed).unwrap(), "must be stable"); + // A different seed must change it. assert_ne!(fp, seed_fingerprint(&[0x43u8; 64]).unwrap()); - // 长度不足要拒绝,而不是算出一个看似合理的值 + // Short seeds are rejected rather than fingerprinted. assert!(seed_fingerprint(&[0u8; 16]).is_err()); } @@ -208,10 +204,10 @@ mod tests { fn transparent_address_from_ufvk_is_t_prefixed() { let ufvk = ufvk_from_mnemonic("test", TEST_MNEMONIC, 0).unwrap(); let t = transparent_address("test", &ufvk).unwrap(); - assert!(t.starts_with("tm"), "testnet t 地址前缀应为 tm,实际 {t}"); + assert!(t.starts_with("tm"), "expected a tm t-address, got {t}"); let ua = unified_address_with("test", &ufvk, "all").unwrap(); - assert!(ua.starts_with("utest"), "UA 前缀应为 utest"); - assert_ne!(t, ua, "t 地址与 UA 是两种呈现,不该相同"); + assert!(ua.starts_with("utest"), "UA must start with utest"); + assert_ne!(t, ua, "t-address and UA must differ"); } #[test] @@ -226,7 +222,7 @@ mod tests { let receivers = address.items(); assert!( !receivers.iter().any(|r| matches!(r, Receiver::Sapling(_))), - "{network}/{policy} 不能含 Sapling receiver" + "{network}/{policy} must not contain a Sapling receiver" ); assert!(receivers.iter().any(|r| matches!(r, Receiver::Orchard(_)))); assert_eq!( @@ -235,13 +231,13 @@ mod tests { "{network}/{policy}" ); } - // 「all」里的透明 receiver 必须就是单独给出的那个 t 地址(/0/0)。 + // The transparent receiver in "all" must be the standalone t-address (/0/0). let params = parse_network(network).unwrap(); let all = unified_address_with(network, &ufvk, "all").unwrap(); let Some(zcash_keys::address::Address::Unified(all)) = zcash_keys::address::Address::decode(¶ms, &all) else { - panic!("{network}: 应解析为 UA"); + panic!("{network}: expected a UA"); }; assert_eq!( zcash_keys::encoding::encode_transparent_address_p( @@ -253,7 +249,7 @@ mod tests { } } - // 公开测试向量,切勿用于真实资金。 + // Public test vector; never use for real funds. const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; @@ -298,12 +294,11 @@ mod tests { let tag = &hex_key[64..66]; assert!( tag == "02" || tag == "03", - "压缩公钥前缀应为 02/03,实际 {tag}" + "compressed key prefix must be 02/03, got {tag}" ); } - /// 省略 / 留空 receiver 策略曾经等于选中 `"all"` —— 那是隐私上最贵的取值, - /// 而调用方什么都没写,也就什么都没同意。 + /// An omitted or empty receiver policy must not default to `"all"`. #[test] fn receiver_policy_has_no_default() { assert!(receiver_policy("all").is_ok()); @@ -325,21 +320,21 @@ mod tests { #[test] fn short_seed_is_rejected() { let err = ufvk_from_seed_bytes(Network::TestNetwork, &[0u8; 16], 0); - assert!(err.is_err(), "过短的种子必须拒绝"); + assert!(err.is_err(), "short seed must be rejected"); } #[test] fn derives_ufvk_and_address() { - let ufvk = ufvk_from_mnemonic("test", TEST_MNEMONIC, 0).expect("应能派生"); + let ufvk = ufvk_from_mnemonic("test", TEST_MNEMONIC, 0).expect("derive UFVK"); assert!( ufvk.starts_with("uview"), - "testnet UFVK 前缀应为 uview,实际 {ufvk}" + "testnet UFVK must start with uview, got {ufvk}" ); - let addr = unified_address_with("test", &ufvk, "all").expect("应能取地址"); + let addr = unified_address_with("test", &ufvk, "all").expect("derive address"); assert!( addr.starts_with("utest"), - "testnet UA 前缀应为 utest,实际 {addr}" + "testnet UA must start with utest, got {addr}" ); } @@ -347,15 +342,16 @@ mod tests { fn different_accounts_differ() { let a = ufvk_from_mnemonic("test", TEST_MNEMONIC, 0).unwrap(); let b = ufvk_from_mnemonic("test", TEST_MNEMONIC, 1).unwrap(); - assert_ne!(a, b, "不同账户序号必须派生出不同的 UFVK"); + assert_ne!(a, b, "different accounts must derive different UFVKs"); } - /// 与硬件固件的互通向量(2026-08-25 对齐),路径 m/32'/133'/account'。 + /// Parity vectors from the independent hardware firmware implementation, + /// path m/32'/133'/account'. /// - /// 硬件侧向量是固件独立实现产出的:UFVK 不含 sapling 项、UA 为 - /// orchard+p2pkh 组合,所以**不比整串,比同名项的字节** —— 指纹、 - /// orchard FVK(96B)、transparent 公钥(65B)、两个 receiver。任何一侧 - /// 的路径、币种或 diversifier 策略漂移都会在这里炸。 + /// The firmware UFVK has no Sapling item and its UA is orchard+p2pkh, so this + /// compares item bytes rather than whole strings: fingerprint, Orchard FVK + /// (96B), transparent pubkey (65B), and both receivers. Drift in path, coin + /// type, or diversifier policy on either side fails here. #[test] fn hardware_parity_vectors() { use zcash_address::unified::{Container, Encoding, Fvk, Receiver, Ufvk}; @@ -376,17 +372,17 @@ mod tests { ), ]; - let parsed = bip0039::Mnemonic::::from_phrase(MNEMONIC).expect("助记词"); + let parsed = bip0039::Mnemonic::::from_phrase(MNEMONIC).expect("BIP39"); let seed = parsed.to_seed(""); assert_eq!( seed_fingerprint(seed.as_ref()).unwrap(), FINGERPRINT, - "种子指纹与硬件不一致" + "seed fingerprint differs from hardware" ); - // UFVK 里的 orchard / transparent 项字节。 + // Orchard / transparent item bytes of a UFVK. let fvk_items = |s: &str| { - let (_, u) = Ufvk::decode(s).expect("解析 UFVK"); + let (_, u) = Ufvk::decode(s).expect("decode UFVK"); let mut orchard = None; let mut p2pkh = None; for item in u.items() { @@ -396,11 +392,11 @@ mod tests { _ => {} } } - (orchard.expect("缺 orchard 项"), p2pkh.expect("缺 p2pkh 项")) + (orchard.expect("orchard item"), p2pkh.expect("p2pkh item")) }; - // UA 里的 orchard / p2pkh receiver 字节。 + // Orchard / p2pkh receiver bytes of a UA. let ua_receivers = |s: &str| { - let (_, a) = zcash_address::unified::Address::decode(s).expect("解析 UA"); + let (_, a) = zcash_address::unified::Address::decode(s).expect("decode UA"); let mut orchard = None; let mut p2pkh = None; for item in a.items() { @@ -411,24 +407,24 @@ mod tests { } } ( - orchard.expect("缺 orchard receiver"), - p2pkh.expect("缺 p2pkh receiver"), + orchard.expect("missing orchard receiver"), + p2pkh.expect("missing p2pkh receiver"), ) }; for (account, hw_ufvk, hw_ua) in HW { - let ours = ufvk_from_mnemonic("main", MNEMONIC, account).expect("派生 UFVK"); + let ours = ufvk_from_mnemonic("main", MNEMONIC, account).expect("derive UFVK"); assert_eq!( fvk_items(&ours), fvk_items(hw_ufvk), - "account {account}: FVK 项字节与硬件不一致" + "account {account}: FVK item bytes differ from hardware" ); - // 我们带 p2pkh receiver 的组装是 "all";只取它的 receiver 字节比对。 + // "all" is our policy with a p2pkh receiver; compare receiver bytes only. let our_ua = unified_address_with("main", &ours, "all").expect("UA"); assert_eq!( ua_receivers(&our_ua), ua_receivers(hw_ua), - "account {account}: 地址 receiver 字节与硬件不一致" + "account {account}: address receiver bytes differ from hardware" ); } } @@ -438,7 +434,7 @@ mod tests { mod ua_inspect { fn receivers(ua: &str) -> Vec { use zcash_address::unified::{Container, Encoding}; - let (_, parsed) = zcash_address::unified::Address::decode(ua).expect("解析 UA"); + let (_, parsed) = zcash_address::unified::Address::decode(ua).expect("decode UA"); parsed .items() .iter() @@ -452,11 +448,11 @@ mod ua_inspect { .collect() } - /// 打印某助记词的收款地址,供本机手工测试(要水龙头的币)用。 - /// 需要 `ZR_MNEMONIC`,未设置时直接跳过,所以常规 `cargo test` 不受影响。 + /// Print receiving addresses for a mnemonic, for manual testing (e.g. faucet + /// funds). Skipped unless `ZR_MNEMONIC` is set. /// - /// 同时打印每种 policy 的 receiver 组成 —— 收款地址里混进不可花的 receiver - /// 会让打进来的钱永远取不出来,这条是唯一能提前看见它的地方。 + /// Also prints each policy's receivers, since an unspendable receiver in a + /// receiving address would strand incoming funds. #[test] fn print_receiving_addresses() { let mnemonic = std::env::var("ZR_MNEMONIC").unwrap_or_default(); @@ -469,22 +465,21 @@ mod ua_inspect { .and_then(|v| v.parse().ok()) .unwrap_or(0); let ufvk = - super::ufvk_from_mnemonic(&network, mnemonic.trim(), account).expect("派生 UFVK"); + super::ufvk_from_mnemonic(&network, mnemonic.trim(), account).expect("derive UFVK"); - // 与硬件对向量用的完整三元组:指纹 → UFVK → 地址,粗到细, - // 哪一级先岔开,问题就在那一级对应的派生步骤里。 + // Fingerprint -> UFVK -> address, for comparing against hardware level by level. let parsed = - bip0039::Mnemonic::::from_phrase(mnemonic.trim()).expect("助记词"); + bip0039::Mnemonic::::from_phrase(mnemonic.trim()).expect("mnemonic"); let seed = parsed.to_seed(""); println!("network {network} account {account}"); println!( "fingerprint {}", - super::seed_fingerprint(seed.as_ref()).expect("指纹") + super::seed_fingerprint(seed.as_ref()).expect("fingerprint") ); println!("ufvk {ufvk}"); println!( "t-addr {}", - super::transparent_address(&network, &ufvk).expect("t 地址") + super::transparent_address(&network, &ufvk).expect("t-address") ); for policy in ["all", "shielded", "orchard"] { let ua = super::unified_address_with(&network, &ufvk, policy).expect("UA"); @@ -493,9 +488,9 @@ mod ua_inspect { } } - /// 解析一个 UFVK(uview…),列出它包含哪些密钥项。 - /// 与硬件对派生时用:整串不等先看项集合 —— 项集合不同是组装差异, - /// 项集合相同而字节不同才是真正的派生差异。 + /// Decode a UFVK (uview...) and list its key items. Differing item sets mean + /// an encoding difference; same items with different bytes mean a derivation + /// difference. #[test] fn inspect_external_ufvk() { let s = std::env::var("ZR_UFVK").unwrap_or_default(); @@ -504,20 +499,19 @@ mod ua_inspect { } use zcash_address::unified::{Container, Encoding, Fvk, Ufvk}; let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::(); - let (net, parsed) = Ufvk::decode(&s).expect("解析 UFVK"); - println!("网络: {net:?}"); + let (net, parsed) = Ufvk::decode(&s).expect("decode UFVK"); + println!("network: {net:?}"); for item in parsed.items() { match &item { Fvk::Orchard(d) => println!(" orchard {}", hex(d)), Fvk::Sapling(d) => println!(" sapling {}", hex(d)), Fvk::P2pkh(d) => println!(" transparent-p2pkh {}", hex(d)), - other => println!(" 其他密钥项: {other:?}"), + other => println!(" other key item: {other:?}"), } } } - /// 解析一个 UA,列出它包含哪些 receiver。 - /// 用来看别的钱包实际给用户的收款地址里放了什么。 + /// Decode a UA and list its receivers, e.g. to inspect other wallets' addresses. #[test] fn inspect_external_ua() { let ua = std::env::var("ZR_UA").unwrap_or_default(); @@ -526,8 +520,8 @@ mod ua_inspect { } use zcash_address::unified::{Container, Encoding}; let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::(); - let (net, parsed) = zcash_address::unified::Address::decode(&ua).expect("解析 UA"); - println!("网络: {net:?}"); + let (net, parsed) = zcash_address::unified::Address::decode(&ua).expect("decode UA"); + println!("network: {net:?}"); for item in parsed.items() { match &item { zcash_address::unified::Receiver::Orchard(d) => { @@ -542,7 +536,7 @@ mod ua_inspect { zcash_address::unified::Receiver::P2sh(d) => { println!(" transparent-p2sh {}", hex(d)); } - other => println!(" 其他 receiver: {other:?}"), + other => println!(" other receiver: {other:?}"), } } } diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs index f4387ed28..284fb63d4 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs @@ -1,18 +1,16 @@ //! # OneKey Zcash Keys //! -//! 只做两件事:从种子派生密钥、导出可公开的观察材料(UFVK / 地址)。 +//! Key derivation, signing, and export of public viewing material (UFVK / +//! addresses). No storage, chain scanning, or network, so mobile builds avoid +//! SQLite and the scan engine. //! -//! **不含存储、不含扫链、不含网络。** 这是刻意的:移动端只需要这一半, -//! 不该为了派生一个地址就把 SQLite 和整个扫链引擎打进包里。 +//! ## Key handling //! -//! ## 密钥纪律 -//! -//! - 种子与花费密钥(USK)**只在本 crate 内部存在**,不跨 wasm 边界。 -//! - JS 侧永远只拿到 UFVK 和地址;出厂边界不收助记词,只收种子字节。 -//! - 种子(含调用方传进来的那份)用 `Zeroizing` 包裹,用完即擦。 -//! - **但派生出的密钥擦不掉**:`UnifiedSpendingKey`、`AccountPrivKey`、 -//! `secp256k1::SecretKey` 上游都没有 `ZeroizeOnDrop`,析构后仍留在 wasm -//! 线性内存里。别把这一条读成「全链路擦干净」—— 它不是。 +//! - Seeds and spending keys (USK) stay inside this crate and never cross the wasm boundary. +//! - JS receives only UFVKs and addresses; the boundary takes seed bytes, never a mnemonic. +//! - Seeds, including the caller's copy, are wrapped in `Zeroizing` and wiped after use. +//! - Derived keys are not wiped: upstream `UnifiedSpendingKey`, `AccountPrivKey`, and +//! `secp256k1::SecretKey` lack `ZeroizeOnDrop` and remain in wasm linear memory. pub mod error; pub mod keys; @@ -26,7 +24,7 @@ pub mod bindgen; pub use error::{ErrorCode, KeysError, Result}; -/// 本 crate 锁定的官方依赖版本。 +/// Pinned upstream dependency versions. pub fn dependency_versions() -> serde_json::Value { serde_json::json!({ "zcash_keys": "0.16.1", diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs index 04b89c877..3ecd65b67 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs @@ -12,36 +12,31 @@ use zip32::AccountId; use crate::error::{ErrorCode, KeysError, Result}; -/// 透明输入的签名是否盖住全部输出。 +/// Whether a transparent input's signature commits to all outputs. /// -/// 非 `SIGHASH_ALL` 的签名盖不住输出,拿到已签交易的人能改写收款地址。四处 -/// 签名/校验路径共用这一个判定,别在调用点各写各的 —— 写岔一处就是一个洞。 +/// A non-`SIGHASH_ALL` signature lets anyone holding the signed transaction +/// rewrite the recipients. All signing and verification paths share this check. pub(crate) fn is_sighash_all(input: &transparent::pczt::Input) -> bool { *input.sighash_type() == SighashType::ALL } -/// 本 crate 当前实际能签的 bundle 类型。定义在实现旁边,翻转时必然改到实现。 +/// Bundle types this crate can sign. Kept next to the implementation so they change together. pub const SIGN_ORCHARD: bool = true; pub const SIGN_SAPLING: bool = false; pub const SIGN_TRANSPARENT: bool = true; pub const SIGN_IRONWOOD: bool = true; -/// 试签透明输入时扫多少个地址序号。 +/// Address indices to try when signing transparent inputs. /// -/// PCZT 里每个透明输入都带着自己的 BIP-32 派生路径,但 `pczt` 没有把那个字段 -/// 公开出来,所以只能按序号逐个试。上游 `sign` 会从私钥反推 pubkey 并核对 -/// `script_pubkey`,不匹配就报错 —— 所以试签不会静默产出错误签名。 +/// `pczt` does not expose each input's BIP-32 derivation path, so indices are +/// tried in order. Upstream `sign` checks the derived pubkey against +/// `script_pubkey`, so a wrong key fails instead of producing a bad signature. /// -/// 取值要覆盖钱包的 gap limit(默认 20),留一倍余量。 -/// -/// 这个上限同时约束**找零地址的序号**(见 `transparent_send`):找零落在扫描 -/// 范围之外,就是一笔钥匙还在、钱包却再也签不出来的钱。 +/// Covers twice the default gap limit (20). It also bounds change address +/// indices (see `transparent_send`): change beyond this range could not be signed. pub(crate) const TRANSPARENT_SCAN_GAP: u32 = 40; -/// 给全部透明输入签名,返回 (签上了几个, 最后一次失败原因)。 -/// -/// 透明输入是屏蔽(transparent → shielded)这条路的必经之处:不签它,打进 -/// t 地址的钱就永远出不来。 +/// Sign all transparent inputs; returns (signed count, last failure). fn sign_transparent_inputs( signer: &mut Signer, usk: &UnifiedSpendingKey, @@ -55,7 +50,7 @@ fn sign_transparent_inputs( for index in 0..input_count { let mut done = false; - // 找零走 internal scope,收款走 external,两个都要试。 + // Receiving uses the external scope and change the internal one; try both. for scope in [TransparentKeyScope::EXTERNAL, TransparentKeyScope::INTERNAL] { for i in 0..TRANSPARENT_SCAN_GAP { let Some(child) = NonHardenedChildIndex::from_index(i) else { @@ -82,10 +77,10 @@ fn sign_transparent_inputs( (signed, last_err) } -/// 用种子派生出的花费密钥给 PCZT 签名。调用方负责擦除自己那份种子。 +/// Sign a PCZT with spending keys derived from the seed. The caller wipes its seed copy. /// -/// 只签 Orchard/Ironwood 花费与透明输入 —— 不支持 Sapling 花费 -/// (Groth16 证明参数约 50 MB,不随包分发;新收到的资金也不落在 Sapling 池)。 +/// Signs Orchard/Ironwood spends and transparent inputs only. Sapling spends are +/// unsupported (the ~50 MB Groth16 parameters are not shipped). pub fn sign_pczt_with_seed( params: Network, seed: &[u8], @@ -112,11 +107,8 @@ pub fn sign_pczt_with_seed( let pczt = pczt::Pczt::parse(pczt_bytes) .map_err(|e| KeysError::new(ErrorCode::PcztParseFailed).detail(format!("{e:?}")))?; - // 签名前的闸门。上游 `Signer::sign_*` 的文档明写:语义校验是调用方的责任。 - // - // 这里守住最要命的一条:签名必须盖住全部输出。`SIGHASH_ALL` 之外的类型 - // (`NONE`、`SINGLE|ANYONECANPAY` 等)签出来的透明输入,拿到已签交易的人 - // 可以改写收款地址。姊妹模块 shielding.rs 三处都查了这一条,这条路漏了。 + // Upstream `Signer::sign_*` leaves semantic checks to the caller. Require + // `SIGHASH_ALL` on every transparent input so signatures commit to all outputs. let pczt = Verifier::new(pczt) .with_transparent(|bundle| { match bundle @@ -140,20 +132,18 @@ pub fn sign_pczt_with_seed( let mut signer = Signer::new(pczt) .map_err(|e| KeysError::new(ErrorCode::PcztSignFailed).detail(format!("{e:?}")))?; - // Orchard 花费授权密钥由花费密钥派生。 + // Orchard spend authorizing key, derived from the spending key. let ask = orchard::keys::SpendAuthorizingKey::from(usk.orchard()); - // 逐个 action 尝试签名:不属于本账户的 action 会被上游拒绝, - // 这里按「签得上就签」处理,两个池都签不上才算错误。 - // - // 两个池都要签:NU6.3 之后新的花费走 Ironwood,而从 Orchard 迁出(那个池 - // 现在只出不进)走 Orchard。一笔迁移交易可能两边都有 action。 + // Shielded actions are signed best-effort: upstream rejects actions not owned + // by this account, and it is an error only if nothing is signed. Both pools are + // signed: post-NU6.3 spends use Ironwood, while migrations out of Orchard use + // Orchard, and one transaction can have both. let (orchard_count, ironwood_count, transparent_count) = bundle_counts(pczt_bytes)?; let mut signed_any = false; let mut last_err: Option = None; - // 透明输入必须**全部**签上。少签一个,交易就是无效的 —— 屏蔽这条路上 - // 所有输入都是透明的,漏一个等于整笔作废,所以这里是硬要求而非尽力而为。 + // Every transparent input must be signed; one missing signature invalidates the transaction. let (transparent_signed, transparent_err) = sign_transparent_inputs(&mut signer, &usk, transparent_count); if transparent_signed < transparent_count { @@ -201,10 +191,9 @@ pub fn sign_pczt_with_seed( .map_err(|e| KeysError::new(ErrorCode::PcztSignFailed).detail(format!("{e:?}"))) } -/// 数出这份 PCZT 里各 bundle 有多少东西要签:(orchard, ironwood, transparent)。 +/// Count signable items per bundle: (orchard, ironwood, transparent). /// -/// Ironwood 的 note 与 Orchard 是同一个 Rust 类型,只靠 `ValuePool` 标签区分, -/// 但 PCZT 里是两个独立的 bundle,所以必须分别数、分别签。 +/// Ironwood and Orchard share Rust types but are separate PCZT bundles. fn bundle_counts(pczt_bytes: &[u8]) -> Result<(usize, usize, usize)> { let pczt = pczt::Pczt::parse(pczt_bytes) .map_err(|e| KeysError::new(ErrorCode::PcztParseFailed).detail(format!("{e:?}")))?; diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs index 15ee37f0b..dd667ae83 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs @@ -427,10 +427,8 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { serde_json::json!({ "field": "change.derivationPath", "reason": "internalScopeRequired" }), )); } - // 找零序号必须落在签名时的扫描范围内。PCZT 不把派生路径交给 - // `sign_transparent_inputs`,那边只能按序号试到 `TRANSPARENT_SCAN_GAP`; - // 序号更大的找零是「钥匙还在、钱包再也签不出来」的钱。宿主当前把找零 - // 固定在 .../1/0,这条只是把那个事实钉成契约。 + // The change index must be within the signer's scan range + // (`TRANSPARENT_SCAN_GAP`); change beyond it could never be signed. if change_path.index >= crate::sign::TRANSPARENT_SCAN_GAP { return Err(KeysError::with( ErrorCode::InvalidDerivationPath, @@ -450,16 +448,12 @@ fn plan_transaction(request: TransparentTxRequest) -> Result { .ok_or_else(|| amount_error("recipientTotal"))?; let change_raw = input_total_raw.saturating_sub(needed_with_change); - // 找零养不起自己时,把这点零头并进手续费、发一笔无找零的交易。 + // If change cannot pay for its own output, add it to the fee and send + // without change (like upstream `DustAction::AddDustToFee`). // - // 这里原本有两条失败路:找零 < MARGINAL_FEE 抛 DustChange,钱不够再加 - // 一个输出抛 InsufficientFunds。后者是假话 —— 钱是够的,只是不够养一个 - // 找零输出;而「零头进手续费」的无找零交易完全成立。上游屏蔽路径的 - // `DustAction::AddDustToFee` 就是这个做法,透明这边缺了。 - // - // 走到这里已经确定 input_total > send_total + fee_without_change,所以 - // 减法不会下溢,付出的手续费也一定不低于最低要求。多付的上限是 - // fee_with_change + MARGINAL_FEE,量级在万分之一 ZEC 以内。 + // input_total > send_total + fee_without_change holds here, so the + // subtraction cannot underflow and the fee meets the minimum. Overpayment + // is bounded by fee_with_change + MARGINAL_FEE. if input_total_raw < needed_with_change || change_raw < MARGINAL_FEE.into_u64() { let fee_raw = input_total_raw - send_total_raw; (parse_zatoshis_u64(fee_raw, "fee")?, None) @@ -1060,11 +1054,11 @@ mod tests { assert_eq!(built.spent_outpoints, quote.spent_outpoints); } - /// 找零够不上 dust 门槛时,零头并进手续费发无找零交易 —— 不是拒绝。 + /// Sub-dust change is added to the fee instead of failing. /// - /// 100,000 的 UTXO 发 88,000:有找零和无找零的手续费都是 10,000(ZIP-317 - /// 1-in 两档都落在 grace 2),富余 2,000 养不起一个找零输出。改之前这里 - /// 直接抛 DustChange,用户只能改金额 —— 而这笔交易本身完全成立。 + /// Sending 88,000 from a 100,000 UTXO: the fee is 10,000 with or without + /// change (ZIP-317, 1-in stays within grace 2), and the 2,000 surplus cannot + /// fund a change output. #[test] fn sub_dust_change_goes_into_the_fee_instead_of_failing() { let mut request: serde_json::Value = @@ -1075,18 +1069,17 @@ mod tests { let quote: TransparentQuote = serde_json::from_str("e_json(&request).unwrap()).unwrap(); assert_eq!(quote.send_amount_zat, "88000"); assert_eq!(quote.change_zat, "0"); - assert_eq!(quote.fee_zat, "12000", "富余应全部进手续费"); + assert_eq!(quote.fee_zat, "12000", "surplus must all go to the fee"); let built: TransparentBuildResult = serde_json::from_str(&build_with_seed_json(&request, &seed()).unwrap()).unwrap(); assert_eq!(built.fee_zat, "12000"); } - /// 同一个死区的另一半,改之前报的是**假的「余额不足」**。 + /// A surplus between the two fee tiers is not insufficient funds. /// - /// 1-in/3-out 时 fee_without_change=15,000、fee_with_change=20,000。富余 - /// 17,000 落在两者之间:加不起找零输出,但无找零的交易成立。旧代码在 - /// `checked_sub` 上下溢,直接告诉用户钱不够。 + /// 1-in/3-out: fee_without_change=15,000, fee_with_change=20,000. A 17,000 + /// surplus cannot fund change, but the no-change transaction is valid. #[test] fn surplus_between_the_two_fee_tiers_is_not_reported_as_insufficient_funds() { let mut request: serde_json::Value = @@ -1104,7 +1097,7 @@ mod tests { assert_eq!(quote.fee_zat, "17000"); } - /// 找零序号必须落在签名端的扫描范围内,否则找零变成签不出来的钱。 + /// The change index must be within the signer's scan range. #[test] fn rejects_change_index_outside_the_signing_scan_range() { let mut request: serde_json::Value = @@ -1113,7 +1106,7 @@ mod tests { let e = quote_json(&request.to_string()).unwrap_err(); assert_eq!(e.code, ErrorCode::InvalidDerivationPath); - // 范围内的仍然放行 + // In range is still accepted. request["change"]["derivationPath"] = "m/44'/133'/0'/1/39".into(); assert!(quote_json(&request.to_string()).is_ok()); } diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs index a86f94b26..a051896e4 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs @@ -14,11 +14,10 @@ use zcash_primitives::transaction::builder::{BuildConfig, Builder, BundlePadding use zcash_primitives::transaction::fees::fixed::FeeRule as FixedFeeRule; use zcash_protocol::memo::MemoBytes; -/// 本模块实际提供的入口。定义在实现旁边,删改实现必然改到这里。 +/// Entry points this module provides, kept next to the implementation. /// -/// 宿主必须先查能力再调:这四个函数是后加的,装到旧 wasm 时缺的是导出本身, -/// 直接调只会得到 `undefined is not a function` —— 那看起来像 app 崩了, -/// 而不是一次「本版本不支持」。 +/// Hosts must check these capabilities before calling: older wasm builds lack +/// the exports entirely, so a direct call fails with `undefined is not a function`. pub const SHIELD_CREATE_WITH_SEED: bool = true; pub const SHIELD_CREATE_WITH_ACCOUNT_XPRV: bool = true; pub const SHIELD_SIGN_WITH_SEED: bool = true; @@ -688,12 +687,12 @@ mod tests { let request = request.to_string(); let quote: Value = serde_json::from_str("e_json(&request).unwrap()).unwrap(); let folded = 100_000 - amount.parse::().unwrap(); - assert_eq!(quote["feeZat"], folded.to_string(), "零头应当并进手续费"); + assert_eq!(quote["feeZat"], folded.to_string(), "surplus goes to fee"); if hardware { create_with_account_xpub(&request, &account_xpub(), &fingerprint) - .expect("硬件路径按报价的手续费构造"); + .expect("hardware path builds with the quoted fee"); } else { - create(&request, &SEED).expect("软件路径按报价的手续费构造"); + create(&request, &SEED).expect("software path builds with the quoted fee"); } } } @@ -924,12 +923,11 @@ mod tests { } } - /// `pcztSignWithSeed` 是通用签名入口,PCZT 从宿主传进来。上游 `Signer` 的 - /// 文档把语义校验的责任明确留给调用方,所以那一侧必须自己守 `SIGHASH_ALL`: - /// 非 ALL 的签名盖不住输出,拿到已签交易的人能改收款地址。 + /// `pcztSignWithSeed` signs host-supplied PCZTs, and upstream `Signer` leaves + /// semantic checks to the caller, so it must enforce `SIGHASH_ALL` itself. /// - /// 正向用例同时钉住另一件事:屏蔽 PCZT 的 ironwood action 只有输出、 - /// 没有可签的 spend,**部分池签不上是正常的**,不能改成「每池全签」。 + /// The positive case also pins that a pool with nothing signable is fine: the + /// shielding PCZT's Ironwood actions are outputs only. #[test] fn generic_signer_requires_sighash_all_on_transparent_inputs() { use zcash_protocol::consensus::Network; @@ -938,17 +936,17 @@ mod tests { let original = create(&request, &SEED).unwrap(); crate::sign::sign_pczt_with_seed(Network::MainNetwork, &SEED, 0, &original) - .expect("未改动的屏蔽 PCZT 应当能签"); + .expect("unmodified shielding PCZT must sign"); let modified = mutate(&original, |value| { value["transparent"]["inputs"][0]["sighash_type"] = 2.into(); }); let e = crate::sign::sign_pczt_with_seed(Network::MainNetwork, &SEED, 0, &modified) - .expect_err("sighash_type 不是 ALL 必须拒签"); + .expect_err("non-ALL sighash_type must be rejected"); assert_eq!(e.code, ErrorCode::PcztSignFailed); assert!( format!("{:?}", e.detail).contains("transparentInputSighashNotAll"), - "应指出是 sighash 策略问题,实际 {e:?}" + "expected a sighash policy error, got {e:?}" ); } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml index a3a6d70b5..6a5861929 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml +++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml @@ -4,7 +4,7 @@ version.workspace = true edition.workspace = true license.workspace = true rust-version.workspace = true -description = "OneKey Zcash Runtime — 官方 librustzcash 之上的最薄 wasm 绑定层" +description = "OneKey Zcash Runtime: a thin wasm binding over librustzcash" [lib] crate-type = ["cdylib", "rlib"] @@ -41,11 +41,8 @@ futures-util.workspace = true sapling.workspace = true uuid.workspace = true -# wasm32 专属:SQLite 的 wasm 实现与 IndexedDB VFS,以及 JS 互操作。 -# 非 wasm 目标(原生桌面/移动/测试)不需要这些 —— 那里 rusqlite 直接用 -# 系统或 bundled 的 SQLite 即可。 -# 原生目标:给同一个 tonic 追加 transport(feature 是并集,wasm 侧不受影响)。 -# 有了它就能在本机复现浏览器里的问题 —— 原生环境可以上真调试器。 +# Native targets: add tonic transport (features are additive; wasm is unaffected) +# so browser issues can be reproduced natively under a debugger. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] tonic = { workspace = true, features = ["transport", "tls-ring", "tls-webpki-roots"] } tokio = { workspace = true } @@ -69,28 +66,28 @@ tracing-wasm = { workspace = true, optional = true } tracing-subscriber = { workspace = true, optional = true } getrandom = { workspace = true, features = ["wasm_js"] } tonic-web-wasm-client.workspace = true -# 本 crate 不直接用 time —— 打开它只为传递 feature。zcash_client_backend 记 -# `created` 时绕过注入的 Clock,直接调 time::OffsetDateTime::now_utc();不开这个 -# feature 它就落到 SystemTime::now(),而 wasm32-unknown-unknown 上 std 没有时间源, -# 于是 pcztSubmit 落库时 panic("time not implemented on this platform")。 +# Not used directly; only enables the feature. zcash_client_backend records +# `created` via time::OffsetDateTime::now_utc(), bypassing the injected Clock. +# Without wasm-bindgen it falls back to SystemTime::now(), which panics on +# wasm32-unknown-unknown ("time not implemented on this platform") in pcztSubmit. time = { version = "0.3", features = ["wasm-bindgen"] } [dev-dependencies] futures = "0.3" -# wasm-pack 默认跑 `wasm-opt -O`;-Oz 更激进地压体积。 -# 代价是构建慢一些,运行时性能差异对我们这类 IO 密集的负载可忽略。 +# wasm-pack defaults to `wasm-opt -O`; -Oz shrinks further at the cost of build +# time, with negligible runtime impact on this IO-bound workload. [package.metadata.wasm-pack.profile.release] -# 不开 --enable-simd:实测(decrypt-share.html,主网 500 块×2 轮)SIMD128 只快 -# ~2%(曲线库无专门 SIMD 路径,自动向量化吃不到),却抬高老 WebView 的兼容门槛。 +# No --enable-simd: measured ~2% faster on mainnet (decrypt-share.html, 500 +# blocks x2) since the curve libraries have no SIMD paths, and it breaks old WebViews. wasm-opt = ["-Oz", "--enable-bulk-memory", "--enable-nontrapping-float-to-int"] -# 排查用档:保持 cargo 的优化(否则 Halo2 证明慢到不可用),但不跑 wasm-opt —— -# 它会剥掉 name 段,而 wasm 的 panic 栈只有函数序号,没有名字就无从下手。 +# Debug profile: keep cargo optimizations (Halo2 proving is unusable without +# them) but skip wasm-opt, which strips the name section panic stacks need. [package.metadata.wasm-pack.profile.profiling] wasm-opt = false [features] -# 把 zcash_client_backend 的 tracing 事件转到浏览器 console。 -# 只在排查时开 —— 日志量很大,且会显著拖慢扫描。 +# Forward zcash_client_backend tracing events to the browser console. +# Debugging only: very verbose and slows scanning noticeably. debug-tracing = ["dep:tracing-wasm", "dep:tracing-subscriber"] diff --git a/chain-runtimes/zcash/crates/zcash-runtime/build.rs b/chain-runtimes/zcash/crates/zcash-runtime/build.rs index f6d86ddaa..9bf5ef819 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/build.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/build.rs @@ -1,14 +1,10 @@ -//! 把 wasm 版 SQLite 接到链接器上。 +//! Links the wasm SQLite build. //! -//! 背景:`zcash_client_sqlite` 依赖 `rusqlite` → `libsqlite3-sys`。我们取消了 -//! `bundled` feature(见 scripts/vendor-deps.sh),所以 libsqlite3-sys 不再在 -//! 构建期编译 C 源码,转而发出 `-l sqlite3` 让链接器去找现成的库。 -//! -//! 在 wasm32 上这份现成的库由 `sqlite-wasm-rs` 提供,但它产出的归档叫 -//! `libwsqlite3.a`(名字里有个 w)。本脚本把它按链接器要的名字复制一份到我们 -//! 自己的 OUT_DIR,并把该目录加进搜索路径。 -//! -//! 这样调用方不需要任何手工的 RUSTFLAGS —— `cargo build` 直接可用。 +//! With rusqlite's `bundled` feature removed (see scripts/vendor-deps.sh), +//! `libsqlite3-sys` emits `-l sqlite3` instead of compiling C sources. On wasm32 +//! the library comes from `sqlite-wasm-rs` as `libwsqlite3.a`; this script copies +//! it to OUT_DIR as `libsqlite3.a` and adds that to the search path, so no manual +//! RUSTFLAGS are needed. use std::path::{Path, PathBuf}; @@ -17,25 +13,25 @@ fn main() { let target = std::env::var("TARGET").unwrap_or_default(); if !target.starts_with("wasm32") { - // 原生目标用系统或 bundled 的 SQLite,无需干预。 + // Native targets use system or bundled SQLite. return; } - let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR 应由 cargo 提供")); + let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR is set by cargo")); let Some(src) = find_wasm_sqlite_archive(&out_dir) else { - // 不直接 panic:留一条可读的提示,让链接期的报错有据可查。 + // Warn instead of panicking so a later link error has context. println!( - "cargo::warning=未找到 sqlite-wasm-rs 的 libwsqlite3.a;\ - 若链接期报 `unable to find library -lsqlite3`,请确认 sqlite-wasm-rs \ - 在依赖图中且目标为 wasm32" + "cargo::warning=sqlite-wasm-rs libwsqlite3.a not found; \ + if linking fails with `unable to find library -lsqlite3`, check that \ + sqlite-wasm-rs is in the dependency graph and the target is wasm32" ); return; }; let dst = out_dir.join("libsqlite3.a"); if let Err(e) = std::fs::copy(&src, &dst) { - println!("cargo::warning=复制 {} 失败: {e}", src.display()); + println!("cargo::warning=failed to copy {}: {e}", src.display()); return; } @@ -43,12 +39,10 @@ fn main() { println!("cargo::rerun-if-changed={}", src.display()); } -/// 从我们的 OUT_DIR 往上找到 `.../build/` 目录,再在里面定位 -/// `sqlite-wasm-rs-*/out/libwsqlite3.a`。 -/// -/// 依赖的构建脚本先于依赖方运行,所以这个文件此刻必然已经存在。 +/// Finds `sqlite-wasm-rs-*/out/libwsqlite3.a` under the `build/` directory +/// above OUT_DIR. Dependency build scripts run first, so it already exists. fn find_wasm_sqlite_archive(out_dir: &Path) -> Option { - // OUT_DIR 形如 target///build/-/out + // OUT_DIR is target///build/-/out let build_root = out_dir.parent()?.parent()?; for entry in std::fs::read_dir(build_root).ok()? { let Ok(entry) = entry else { continue }; diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs index 904c16488..b78eb5718 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs @@ -1,6 +1,5 @@ -//! 账户导入与读取。 -//! -//! 只做「看账」所需:导入 UFVK、读余额。私钥、地址派生与签名不在这条路径上。 +//! Account import and reads: UFVK import and balances. No private keys, +//! address derivation or signing on this path. use zcash_client_backend::data_api::wallet::ConfirmationsPolicy; use zcash_client_backend::data_api::{ @@ -13,12 +12,10 @@ use crate::network::{self, LightClient}; use crate::wallet::Db; use serde_json::json; -/// 导入一个只读账户(UFVK)。 +/// Imports an account from a UFVK. /// -/// `birthday_height` 是「这个账户最早可能收到 note 的高度」。它决定扫描起点, -/// 也决定首次同步要花多久 —— 设成当天的链尖高度,新建账户就几乎不用扫历史。 -/// -/// 需要一次网络往返取 birthday 前一个区块的 treestate。 +/// `birthday_height` is the earliest height the account can have received a +/// note; scanning starts there. Fetches the tree state of the block before it. pub async fn import_ufvk( db: &mut Db, client: &mut LightClient, @@ -32,8 +29,9 @@ pub async fn import_ufvk( let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str) .map_err(|e| RuntimeError::new(ErrorCode::InvalidUfvk).detail(e))?; - // 宿主知道种子指纹 + 账户序号时,账户按「可花费」导入:PCZT 里的 change 输出 - // 会带上 zip32_derivation,签名器(软件/硬件)据此确认找零回到自己。 + // With a seed fingerprint and account index the account is imported as + // spending, so PCZT change outputs carry zip32_derivation and signers can + // verify change returns to the wallet. let purpose = match derivation { Some((fingerprint_hex, account_index)) => AccountPurpose::Spending { derivation: Some(parse_zip32_derivation(fingerprint_hex, account_index)?), @@ -41,8 +39,7 @@ pub async fn import_ufvk( None => AccountPurpose::ViewOnly, }; - // treestate 取的是 birthday 的前一个区块:账户从 birthday 起开始观察, - // 所以需要「birthday 之前」的树状态作为锚点。 + // The account starts at the birthday, so the anchor is the tree state just before it. let anchor_height = birthday_height.saturating_sub(1); let treestate = network::tree_state(client, anchor_height).await?; check_birthday_tree_state(&treestate, anchor_height, ¶ms)?; @@ -94,7 +91,7 @@ fn parse_zip32_derivation(fingerprint_hex: &str, account_index: u32) -> Result Result { let account_id = parse_account_id(db, account_uuid)?; @@ -106,8 +103,8 @@ pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) -> .detail(e) })?; - // 还没扫到任何区块时没有摘要。这是一个明确的状态,用错误码表达, - // 不要在返回值里塞中文原因 —— 那是宿主的文案。 + // No summary before any block is scanned; reported as an error code, with + // user-facing text left to the host. let Some(summary) = summary else { return Err(RuntimeError::new(ErrorCode::NotSynced)); }; @@ -119,20 +116,15 @@ pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) -> ) })?; - // 每个池各自报全五个量,**不做任何跨池合并**。 - // - // 合并是产品决策,不是事实。比如「可花的屏蔽余额」在本钱包等于 - // orchard + ironwood(sapling 因为裁掉了证明参数只读),但那是钱包当下的 - // 策略,不是链上的性质 —— 焊进 runtime 就意味着策略一变 runtime 就在说谎。 - // 而且合并会抹掉「钱在哪个池」,那恰恰是池明细 UI 要展示的东西。 - // - // 宿主要什么口径的合计,自己加。 + // Each pool reports all five values with no cross-pool merging: which pools + // count as spendable is wallet policy, not chain fact, and per-pool detail is + // shown in the UI. The host computes any totals it needs. let pool = |b: &zcash_client_backend::data_api::Balance| { serde_json::json!({ "spendable": u64::from(b.spendable_value()), "pendingChange": u64::from(b.change_pending_confirmation()), "pendingSpendable": u64::from(b.value_pending_spendability()), - // 被某个 PCZT 提案占住的部分(见 send.rs 的 reservation) + // Reserved by a PCZT proposal (see the reservation in send.rs). "locked": u64::from(b.locked_value()), "total": u64::from(b.total()), }) @@ -156,9 +148,8 @@ pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) -> "orchard": pool(balances.orchard_balance()), "ironwood": pool(balances.ironwood_balance()), - // 透明余额也分开报:coinbase 有不同的成熟规则,而且只能走 - // `propose_shielding_coinbase` 屏蔽,宿主的屏蔽路径碰不到它。 - // 并成一个数就看不出这个差别了。 + // Coinbase is reported separately: it has its own maturity rules and can + // only be shielded via `propose_shielding_coinbase`. "transparentRegular": pool(balances.unshielded_regular_balance()), "transparentCoinbase": pool(balances.unshielded_coinbase_balance()), @@ -168,10 +159,8 @@ pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) -> .to_string()) } -/// 从共享库里移除单个账户。 -/// -/// 共享库下删除**不能**是删库 —— 那会连累其他钱包的账户。库只在最后一个账户 -/// 也被删掉之后才该丢弃,那由宿主判断。 +/// Removes one account from the shared database. Deleting the database would +/// remove other wallets' accounts; the host drops it after the last account. pub fn remove_account(db: &mut Db, account_uuid: &str) -> Result<()> { let account_id = parse_account_id(db, account_uuid)?; db.transactionally_with_extension(|wallet, ext| { @@ -186,11 +175,11 @@ pub fn remove_account(db: &mut Db, account_uuid: &str) -> Result<()> { }) } -/// 按 UFVK 查这个库里的账户,找不到返回 `"null"`。 +/// Finds the account with this UFVK, or returns `"null"`. /// -/// 共享库下这是**定位账户的唯一正确方式**:一份库装着全部钱包的全部账户, -/// 不能假设第一个就是要找的那个;而 runtime 的 UUID 在 purge 之后会变, -/// 也不能缓存。UFVK 是宿主手上稳定且唯一的键。 +/// This is how to locate an account in the shared database: it holds every +/// wallet's accounts, and runtime UUIDs change after a purge. The UFVK is the +/// host's stable unique key. pub fn account_by_ufvk(db: &Db, ufvk_str: &str) -> Result { let params = *db.params(); let target = UnifiedFullViewingKey::decode(¶ms, ufvk_str) @@ -221,7 +210,7 @@ pub fn account_by_ufvk(db: &Db, ufvk_str: &str) -> Result { Ok("null".to_string()) } -/// 列出本地已有账户,JSON 数组。 +/// Local account UUIDs as a JSON array. pub fn list_accounts_json(db: &Db) -> Result { let ids = db.get_account_ids().map_err(|e| { RuntimeError::with( @@ -260,7 +249,7 @@ fn uuid_from_str(s: &str) -> Result { }) } -/// 构造确认数策略。两个门槛都必须 >= 1,且 trusted <= untrusted。 +/// Builds a confirmations policy. Both thresholds must be >= 1 and trusted <= untrusted. pub fn confirmations_policy( trusted: u32, untrusted: u32, @@ -277,10 +266,10 @@ pub fn confirmations_policy( ConfirmationsPolicy::new(t, u, allow_zero_conf_shielding).map_err(|e| bad().detail(e)) } -/// 生日取自服务端给的树状态:上游按它报的高度 + 1 定生日,不核对是不是 -/// 我们要的那一块。报高了,生日之前那段收款永远不扫;报错了网络,整个账户 -/// 都在别的链上。所以高度必须正好是请求的那一块,网络(服务端给了的话) -/// 必须是钱包的网络。 +/// Upstream sets the birthday to the server's reported tree state height + 1 +/// without checking it. A height too high skips earlier receipts forever and a +/// wrong network puts the account on another chain, so the height must equal +/// the request and the network (if given) must match the wallet. fn check_birthday_tree_state( treestate: &zcash_client_backend::proto::service::TreeState, anchor_height: u32, diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs index a79049c10..c5775da87 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs @@ -1,21 +1,20 @@ -//! 面向宿主 JS/TS 的接口。 +//! Host-facing JS/TS interface. //! -//! ## 约定 +//! ## Conventions //! -//! - 入参与返回值只用 string / number / boolean / JSON 字符串。 -//! - 不把 Rust 对象句柄交给 JS 管生命周期。 -//! - **失败抛的 `Error` 上挂 `code` / `params` / `detail`。** -//! `code` 是稳定错误码,用它做分支;`params` 是结构化参数,用它填 i18n 占位符; -//! `detail` 只用于日志。**这里不产出任何面向用户的文案** —— 文案属于宿主。 -//! - 每个调用都是一次完整往返,不留后台任务、不留定时器。 - -// ── 稳定契约 vs 诊断 ──────────────────────────────────────────────────── +//! - Parameters and return values are only string / number / boolean / JSON string. +//! - No Rust object handles are handed to JS for lifetime management. +//! - A thrown `Error` carries `code` / `params` / `detail`. +//! Branch on `code` (stable error code); fill i18n placeholders from `params`; +//! `detail` is for logs only. No user-facing text is produced here; that belongs to the host. +//! - Every call is a complete round trip: no background tasks, no timers. + +// ── Stable contract vs diagnostics ────────────────────────────────────── // -// `diag*` 前缀的方法是**排障工具,不是稳定契约**:它们随时可能改签名或消失。 -// 分开命名是为了让依赖它们这件事在调用点就看得见 —— 否则宿主很容易顺手用上, -// 将来想删就变成破坏性升级。 +// `diag*` methods are debugging tools, not a stable contract: their signatures may +// change or they may disappear. The prefix makes dependence on them visible at the call site. // -// 其余方法构成钱包契约,改动需要走版本。 +// All other methods form the wallet contract; changes require a version bump. use wasm_bindgen::prelude::*; @@ -32,9 +31,9 @@ pub fn set_request_handler(handler: Option) { network::set_request_handler(handler); } -// ── 生命周期 ──────────────────────────────────────────────────────────── +// ── Lifecycle ─────────────────────────────────────────────────────────── -/// 安装存储层。必须在其他任何调用之前 await 一次。幂等。 +/// Installs the storage layer. Must be awaited once before any other call. Idempotent. #[wasm_bindgen(js_name = init)] pub async fn init() -> Result<(), JsValue> { install_panic_hook(); @@ -48,20 +47,19 @@ pub fn storage_requires_worker_restart() -> bool { storage::requires_worker_restart() } -/// panic 变成带堆栈的 console 错误,而不是一个永远不 settle 的 Promise。 +/// Turns a panic into a console error with a stack trace instead of a Promise that never settles. /// -/// 必须在**每个**入口都装。曾经只装在 `init()` 里,于是走 `initMemoryStorage()` -/// 的排查路径上 panic 完全静默 —— 排查工具本身反而看不见错误。 +/// Must be installed at every entry point, including `diagInitMemoryStorage()`. fn install_panic_hook() { console_error_panic_hook::set_once(); } -/// 打开 tracing 输出到浏览器 console(需 `debug-tracing` feature)。 +/// Enables tracing output to the browser console (requires the `debug-tracing` feature). /// -/// 上游 `zcash_client_backend` 全程用 `tracing` 打点。同步卡住时, -/// console 里的**最后一条**日志就指出它停在哪一步 —— 比反复猜快得多。 +/// Upstream `zcash_client_backend` is instrumented with `tracing`; when sync stalls, +/// the last console entry shows the step it stopped at. /// -/// 日志量很大且会拖慢扫描,只在排查时用。 +/// Very verbose and slows scanning; use only for debugging. #[wasm_bindgen(js_name = diagEnableTracing)] pub fn enable_debug_tracing() { #[cfg(feature = "debug-tracing")] @@ -73,12 +71,11 @@ pub fn enable_debug_tracing() { } } -/// 改用**内存存储**:不安装持久化 VFS,数据只活在本页面生命周期内。 +/// Uses in-memory storage: no persistent VFS; data lives only for the page lifetime. /// -/// 用途:临时/一次性钱包;以及排查时把存储层从纯计算里摘出来 —— -/// 同样的扫描在内存 VFS 上跑一遍,就知道瓶颈在哪一半。 +/// For ephemeral wallets, and for isolating storage from computation when profiling. /// -/// 必须替代 `init()` 调用,不能两个都调。 +/// Call instead of `init()`, never both. #[wasm_bindgen(js_name = diagInitMemoryStorage)] pub fn init_memory_storage() { install_panic_hook(); @@ -87,8 +84,8 @@ pub fn init_memory_storage() { /// The capabilities of this version-locked wallet and keys package set. /// -/// 存在的理由:发送失败得太晚代价很高 —— 提案已经锁了 note,用户已经输过密码, -/// 却在证明阶段才炸。与其让流水线中途失败,不如让按钮一开始就不出现。 +/// Lets the host hide unsupported actions up front instead of failing at proving time, +/// after notes are locked and the user has entered a password. /// #[wasm_bindgen(js_name = capabilities)] pub fn capabilities() -> String { @@ -105,26 +102,25 @@ pub fn capabilities() -> String { // The host must combine both packages' capabilities. "proveShielding": true, "notes": { - // 说明为什么不通,宿主可以据此给用户不同的提示 - "sapling": "Sapling 不在产品支持范围:不扫描、不展示、不收款、不花费;\ - 证明参数(约 50MB)也不随包分发", - "transparent": "透明输入的签名在 keys 包,本包只负责提案与证明;\ - 「能否屏蔽」要两边的标志同时为真", + // Why a capability is unavailable, so the host can show different hints. + "sapling": "Sapling is out of scope: not scanned, shown, received or spent; \ + its ~50MB proving parameters are not shipped", + "transparent": "Transparent inputs are signed by the keys package; this package \ + only proposes and proves. Shielding needs both packages' flags", }, }) .to_string() } -/// 本 runtime 锁定的官方依赖版本,JSON 字符串。 +/// Official dependency versions pinned by this runtime, as a JSON string. #[wasm_bindgen(js_name = dependencyVersions)] pub fn dependency_versions() -> String { crate::dependency_versions().to_string() } -/// 诊断:取单个区块的结构摘要。不扫描、不写库、不改任何状态。 +/// Diagnostic: structural summary of a single block. No scanning, no writes, no state change. /// -/// 用来确认浏览器(gRPC-web 代理)与原生(真 gRPC)拿到的是不是同一份数据 —— -/// 两边行为不一致时,先排除「数据本来就不同」再谈计算差异。 +/// Confirms whether browser (gRPC-web proxy) and native (gRPC) clients receive the same data. #[wasm_bindgen(js_name = diagBlockSummary)] pub async fn block_summary(height: u32) -> Result { Ok( @@ -143,30 +139,29 @@ pub async fn open_wallet(network_name: String, db_name: String) -> Result Result<(), JsValue> { Ok(runtime::close()?) } -/// 配置 lightwalletd 端点,形如 `https://host:port`。 +/// Configures the lightwalletd endpoint, e.g. `https://host:port`. /// -/// 端点由宿主决定 —— 本 runtime 不硬编码任何服务器地址。 +/// The host chooses the endpoint; this runtime hardcodes no server address. /// The endpoint must support gRPC-web. CORS is required only without a host transport. #[wasm_bindgen(js_name = setLightwalletdUrl)] pub fn set_lightwalletd_url(base_url: &str) -> Result<(), JsValue> { @@ -174,12 +169,12 @@ pub fn set_lightwalletd_url(base_url: &str) -> Result<(), JsValue> { Ok(()) } -// ── 链信息 ────────────────────────────────────────────────────────────── +// ── Chain info ────────────────────────────────────────────────────────── -/// 当前链尖高度。**不需要先打开钱包库** —— 只需要先 `setLightwalletdUrl`。 +/// Current chain tip height. Requires only `setLightwalletdUrl`, not an open wallet. /// -/// 建账户时宿主要靠它定 birthday,而那一刻库还不存在;若要求先开库, -/// 这一步必然失败,birthday 就会退回 Sapling 激活高度,新助记词也要全量扫。 +/// The host uses it to pick a new account's birthday before the database exists; +/// otherwise the birthday falls back to Sapling activation and a full scan. #[wasm_bindgen(js_name = chainTip)] pub async fn chain_tip() -> Result { Ok(runtime::with_client(|mut client| async move { @@ -199,12 +194,12 @@ pub async fn chain_tip_at(base_url: String) -> Result { Ok(network::chain_tip(&mut client).await?) } -// ── 账户 ──────────────────────────────────────────────────────────────── +// ── Accounts ──────────────────────────────────────────────────────────── -/// 导入一个只读账户(UFVK),返回账户 UUID。 +/// Imports a view-only account (UFVK) and returns its UUID. /// -/// `birthdayHeight` 决定扫描起点。新建账户传当前链尖高度,首次同步几乎不用扫历史; -/// 恢复钱包必须传足够早的高度,否则会漏掉历史资金 —— **这个决策属于宿主**。 +/// `birthdayHeight` is the scan start. New accounts pass the current tip; restores must pass +/// a height early enough not to miss historical funds. This decision belongs to the host. #[wasm_bindgen(js_name = importAccountUfvk)] pub async fn import_account_ufvk( account_name: String, @@ -231,7 +226,7 @@ pub async fn import_account_ufvk( ) } -/// 从共享库里移除单个账户。**不删库** —— 库还装着其他钱包的账户。 +/// Removes one account from the shared database. Does not delete the database, which holds other wallets' accounts. #[wasm_bindgen(js_name = removeAccount)] pub async fn remove_account(account_uuid: String) -> Result<(), JsValue> { runtime::with_read_conn(|conn| { @@ -247,10 +242,10 @@ pub async fn remove_account(account_uuid: String) -> Result<(), JsValue> { Ok(()) } -/// 宿主已经删掉这个账户:有没有在途交易都清掉,不做 `removeAccount` 的空闲检查。 +/// The host already deleted this account: removes it regardless of in-flight transactions, +/// skipping `removeAccount`'s idle check. /// -/// 钱在链上、助记词在用户手里,重新导入扫链就能找回;在途交易留着只会让一个 -/// 已删的账户继续占着库。 +/// Funds are on chain and the seed is with the user, so a re-import and rescan recovers them. #[wasm_bindgen(js_name = removeDeletedAccount)] pub async fn remove_deleted_account(account_uuid: String) -> Result<(), JsValue> { runtime::with_db(|db| account::remove_account(db, &account_uuid))?; @@ -259,24 +254,23 @@ pub async fn remove_deleted_account(account_uuid: String) -> Result<(), JsValue> Ok(()) } -/// 按 UFVK 定位这个库里的账户,返回 `{ uuid }`,找不到返回 `"null"`。 +/// Finds the account for a UFVK, returning `{ uuid }` or `"null"` if absent. /// -/// 共享库(每 network 一份,装全部钱包的全部账户)下,这是定位账户的唯一 -/// 正确方式:不能假设第一个就是要找的那个,UUID 又会在 purge 后变化。 +/// The only correct lookup in the shared per-network database: the first account is not +/// necessarily the one wanted, and UUIDs change after a purge. #[wasm_bindgen(js_name = accountByUfvk)] pub fn account_by_ufvk(ufvk: String) -> Result { let _perf = perf::span("accountByUfvk"); Ok(runtime::with_db(|db| account::account_by_ufvk(db, &ufvk))?) } -/// 每个账户各自的同步完成度,从「该账户 birthday + 全库剩余待扫区间」推导。 +/// Per-account sync status, derived from the account birthday and the database's remaining scan ranges. /// -/// 共享库下全局进度会误导:新加一个账户会让**所有**账户看起来都没同步完。 -/// 官方 schema 没有 per-account 游标,也不该为此改 schema(见 D15), -/// 所以这里只读推导,零 schema 改动。 +/// Global progress misleads in a shared database: adding an account makes all accounts look unsynced. +/// The official schema has no per-account cursor and is not changed for this (see D15); this is read-only. /// -/// 返回纯块高,不给百分比 —— 进度比例的分母是移动窗口里的 note 数, -/// 永远到不了 100%,显示出来像坏了。 +/// Returns block heights, not a percentage: the upstream progress ratio is over notes in a moving +/// window and never reaches 100%. #[wasm_bindgen(js_name = accountSyncStatus)] pub fn account_sync_status(account_uuid: String) -> Result { Ok(runtime::with_db(|db| { @@ -284,17 +278,17 @@ pub fn account_sync_status(account_uuid: String) -> Result { })?) } -/// 列出本地账户的 UUID,JSON 数组。 +/// Lists local account UUIDs as a JSON array. #[wasm_bindgen(js_name = listAccounts)] pub fn list_accounts() -> Result { Ok(runtime::with_db(|db| account::list_accounts_json(db))?) } -/// 账户余额,JSON。 +/// Account balance as JSON. /// -/// `trusted` / `untrusted` 是确认数门槛(均 >= 1,且 trusted <= untrusted): -/// 自己找零的 note 可以宽松,外来的应更保守。具体取值是产品决策,由宿主传。 -/// 尚未同步到任何区块时抛 `NOT_SYNCED`。 +/// `trusted` / `untrusted` are confirmation thresholds (both >= 1, trusted <= untrusted): +/// own change can be looser, external notes stricter. Values are a product decision passed by the host. +/// Throws `NOT_SYNCED` before any block has been synced. #[wasm_bindgen(js_name = accountBalance)] pub fn account_balance( account_uuid: String, @@ -309,15 +303,15 @@ pub fn account_balance( })?) } -// ── 扫链 ──────────────────────────────────────────────────────────────── +// ── Scanning ──────────────────────────────────────────────────────────── -/// 同步前的一次性准备:下载三个池的子树根、更新链尖。 +/// One-time sync preparation: downloads subtree roots for all three pools and updates the chain tip. /// -/// **这是首次同步最慢的一步**,与 batchSize 无关。单独暴露是为了让宿主 -/// 能给出「正在准备」的独立进度,而不是干等一个不返回的调用。 +/// The slowest step of a first sync, independent of batchSize; exposed separately so the host +/// can show a distinct "preparing" state. /// -/// 返回 `{ chainTip, saplingSubtrees, orchardSubtrees, ironwoodSubtrees }`。 -/// 每轮同步开始时调一次即可。 +/// Returns `{ chainTip, saplingSubtrees, orchardSubtrees, ironwoodSubtrees }`. +/// Call once at the start of a sync round. #[wasm_bindgen(js_name = syncPrepare)] pub async fn sync_prepare() -> Result { let _perf = perf::span("syncPrepare"); @@ -330,10 +324,10 @@ pub async fn sync_prepare() -> Result { ) } -/// 只更新链尖(一个 unary 调用,主网实测 ~270ms)。返回 `{ chainTip }`。 +/// Updates only the chain tip (one unary call, ~270ms on mainnet). Returns `{ chainTip }`. /// -/// 每轮同步用它;子树根走 `syncPrepare`,开库后一次即可 —— 那 1900 条根 -/// 是凝固的历史,每轮重下就是主网每轮多出 7 秒的来源。 +/// Use every sync round; subtree roots go through `syncPrepare` once per open, since +/// re-downloading the ~1900 immutable roots costs ~7s per round on mainnet. #[wasm_bindgen(js_name = syncTip)] pub async fn sync_tip() -> Result { Ok( @@ -345,19 +339,18 @@ pub async fn sync_tip() -> Result { ) } -/// 只读查看待扫区间,**不发网络请求**。返回 -/// `{ ranges: [{ start, end, len, priority }], totalBlocks }`。 +/// Read-only view of pending scan ranges; no network requests. Returns +/// `{ ranges: [{ start, end, len, priority }], totalBlocks }`. /// -/// 给宿主做进度条用;同步异常时也用它确认钱包想扫哪一段。 +/// For host progress bars and for checking which range the wallet wants to scan. #[wasm_bindgen(js_name = syncPeek)] pub fn sync_peek() -> Result { Ok(runtime::with_db(|db| sync::peek(db))?) } -/// 诊断:只下载不扫描,返回各阶段耗时。**不改变钱包状态。** +/// Diagnostic: downloads without scanning and returns per-phase timings. Does not change wallet state. /// -/// 同步在浏览器里卡住时,网络挂和扫描挂的表现一样(页面无响应), -/// 但成因不同。先用这个确认网络这一半是好的,再去查扫描。 +/// Separates network stalls from scan stalls, which look the same in the browser. #[wasm_bindgen(js_name = diagProbeDownload)] pub async fn sync_probe_download(batch_size: u32) -> Result { Ok( @@ -369,10 +362,10 @@ pub async fn sync_probe_download(batch_size: u32) -> Result { ) } -/// 只报价、不构造交易、不锁定 note。返回 `{ feeZat, steps }`。 +/// Quotes only: no transaction built, no notes locked. Returns `{ feeZat, steps }`. /// -/// 与 `pcztCreate` 共用同一条提案路径,所以报出来的费用就是实付的费用。 -/// 余额不足同样抛 `INSUFFICIENT_FUNDS`(带 shortfallZat),宿主可据此提示。 +/// Shares the proposal path with `pcztCreate`, so the quoted fee is the fee paid. +/// Insufficient balance throws `INSUFFICIENT_FUNDS` (with shortfallZat). #[wasm_bindgen(js_name = pcztQuote)] pub fn pczt_quote( account_uuid: String, @@ -387,8 +380,8 @@ pub fn pczt_quote( spend_source: Option, memo_hex: Option, ) -> Result { - // 与 `pcztCreate` 同一个构造入口,参数顺序也刻意对齐:报价用的选币规则 - // 只要有一个字段和真正发送不同,报出来的费用就不是实付的费用。 + // Same constructor and parameter order as `pcztCreate`: any differing selection + // field would make the quoted fee differ from the fee paid. let policy = send::parse_send_policy( trusted, untrusted, @@ -409,8 +402,8 @@ pub fn pczt_quote( })?) } -/// 单笔交易详情,JSON。钱包里没有这笔时返回 `"null"` 而不是报错 —— -/// 「不在钱包里」是正常状态(外部 txid、被回滚的交易),不是故障。 +/// Single transaction details as JSON. Returns `"null"` rather than an error when the wallet +/// lacks the transaction (external txid, rolled-back transaction); that is a normal state. #[wasm_bindgen(js_name = transactionDetails)] pub fn transaction_details(account_uuid: String, txid: String) -> Result { let _perf = perf::span("transactionDetails"); @@ -419,11 +412,10 @@ pub fn transaction_details(account_uuid: String, txid: String) -> Result Result { Ok(runtime::with_read_conn(|conn| { @@ -431,21 +423,22 @@ pub fn transaction_outputs(account_uuid: String, txid: String) -> Result Result { - // 刻意**没有**空闲闸门。这不是用户可选的破坏性操作,而是重组发生时钱包 - // 跟上链的唯一手段(唯一调用方是 syncWallet 的重组分支)。在这里因为 - // 「有笔交易还没落块」而拒绝,正好挑中最该回退的时刻把账户钉死在一条 - // 已被放弃的链上,之后再也扫不过去。 + // Deliberately no idle gate: this is how the wallet follows a reorg (sole caller is + // syncWallet's reorg branch). Refusing because a transaction is unmined would pin the + // account to an abandoned chain. // - // 用户触发的重扫走 `queueRescanFrom`:它只重排扫描区间,不丢数据。 + // User-triggered rescans use `queueRescanFrom`, which only requeues ranges. Ok(runtime::with_db(|db| sync::rewind_to(db, height))?) } @@ -524,17 +516,17 @@ pub fn queue_rescan_from(from_height: u32) -> Result { })?) } -// ── 发送 ──────────────────────────────────────────────────────────────── +// ── Send ──────────────────────────────────────────────────────────────── // -// 完整流程:pcztCreate → pcztProve → (keys 包)pcztSign → pcztSubmit +// Flow: pcztCreate → pcztProve → (keys package) pcztSign → pcztSubmit // -// 证明在签名之前还是之后都可以(两者作用于 PCZT 的不同部分), -// 但**都必须在 pcztSubmit 之前完成**,否则交易无效。 +// Proving and signing may happen in either order (they touch different PCZT parts), +// but both must finish before pcztSubmit or the transaction is invalid. -/// 构造一笔转账的 PCZT(未证明、未签名),返回字节。 +/// Builds an unproven, unsigned PCZT for a transfer and returns its bytes. /// -/// `fallbackChangePool`: 当前产品固定传 `"ironwood"`,交易找零进入最新隐私池。 -/// `padOrchardBundle`: 是否填充 Orchard bundle 隐藏真实 action 数(更大、费更高)。 +/// `fallbackChangePool`: the product currently always passes `"ironwood"`, so change goes to the newest shielded pool. +/// `padOrchardBundle`: pads the Orchard bundle to hide the real action count (larger, higher fee). #[wasm_bindgen(js_name = pcztCreate)] pub fn pczt_create( account_uuid: String, @@ -579,33 +571,33 @@ pub fn pczt_create( })?) } -/// 生成 Orchard / Ironwood 零知识证明。**必须在 pcztSubmit 之前做**。 +/// Creates Orchard / Ironwood zero-knowledge proofs. Must run before pcztSubmit. #[wasm_bindgen(js_name = pcztProve)] pub fn pczt_prove(pczt_bytes: Vec) -> Result, JsValue> { Ok(runtime::with_db(|db| send::prove_pczt(db, &pczt_bytes))?) } -/// 把外部签名器(硬件)返回的脱敏 PCZT 合并回本地的完整 PCZT。 +/// Merges a redacted PCZT returned by an external (hardware) signer back into the full local PCZT. /// -/// 硬件只回传签名等公开字段,私有字段(rseed、witness 等)以 None 回来; -/// Combiner 逐字段取「有值」的一方,所以本地副本 + 签名副本 = 可证明可提取的 PCZT。 -/// 不需要钱包数据库。 +/// Hardware returns only public fields such as signatures; private fields (rseed, witness, etc.) +/// come back as None. The Combiner takes whichever side has a value, so local + signed copies +/// yield a provable, extractable PCZT. Needs no wallet database. #[wasm_bindgen(js_name = pcztCombine)] pub fn pczt_combine(original: Vec, signed: Vec) -> Result, JsValue> { Ok(send::combine_pczt(&original, &signed)?) } -/// 释放该账户**全部**被锁的 note,返回解锁数量。 +/// Releases all locked notes of the account; returns the number unlocked. /// -/// 崩溃恢复用:`releaseReservation` 靠内存里的提案表定位,app / offscreen 重启后 -/// 那张表没了,旧 token 既解不开也不知道锁了什么。 +/// For crash recovery: `releaseReservation` relies on the in-memory proposal table, which is +/// lost when the app / offscreen restarts. /// -/// **会连带放开进行中的提案**,所以只能由用户主动触发的「修复」动作调用, -/// 不要放进正常流程。 +/// Also releases in-progress proposals, so call only from a user-triggered repair action, +/// never from the normal flow. #[wasm_bindgen(js_name = clearLockedOutputs)] pub fn clear_locked_outputs(account_uuid: String) -> Result { - // 锁本身不算「忙」—— 它正是这里要清的东西。但已经发出去的交易算:解锁 - // 一批正在被一笔待广播交易花掉的 note,等于把它们放回可选池去双花。 + // Locks are not "busy" (they are what this clears), but sent transactions are: unlocking + // notes spent by a pending broadcast would return them to selection and allow a double spend. runtime::with_read_conn(|conn| { guard::assert_idle( conn, @@ -619,10 +611,10 @@ pub fn clear_locked_outputs(account_uuid: String) -> Result { })?) } -/// 释放一次 reservation 占用的 note(用户取消发送时调)。 +/// Releases the notes held by a reservation (called when the user cancels a send). /// -/// 幂等:id 已发送 / 已释放 / 从未存在时返回 `false` 而不报错 —— -/// 取消路径上重复调用是常态,不该因此给用户弹错误。 +/// Idempotent: returns `false` instead of an error when the id was sent, already released, +/// or never existed; repeated calls on the cancel path are normal. #[wasm_bindgen(js_name = releaseReservation)] pub fn release_reservation(reservation_id: String) -> Result { Ok(runtime::with_db(|db| { @@ -630,27 +622,27 @@ pub fn release_reservation(reservation_id: String) -> Result { })?) } -/// 在一件**已经不可逆地发生了**的事情之后做落盘屏障。 +/// Durability barrier after an irreversible step. /// -/// 屏障失败的含义是「持久化有没有到达耐久存储未知」,不是「这件事失败了」。 -/// 两个调用点都已越过不可逆点 —— `pcztSubmit` 已提交交易并交出 note, -/// `broadcastTransaction` 已把交易发上网。把真实结局换成一个泛化的存储错误, -/// 宿主就会去重试、或者把一笔已上链的交易显示成「未知失败」。 +/// A barrier failure means "unknown whether persistence reached durable storage", not that +/// the step failed. Both callers are past the point of no return (`pcztSubmit` committed the +/// transaction, `broadcastTransaction` sent it), so the real outcome must not be replaced by a +/// generic storage error that would make the host retry or show an on-chain tx as failed. /// -/// 调用方自己写 params(各自的结局形状不同),错误码与 detail 由这里统一。 +/// Callers supply `params` (outcome shapes differ); the error code and detail are set here. async fn barrier_after_irreversible(params: serde_json::Value) -> Result<(), crate::RuntimeError> { storage::durability_barrier().await.map_err(|error| { crate::RuntimeError::with(crate::ErrorCode::FinalizeOutcomeUnknown, params).detail(error) }) } -/// 提交已证明且已签名的 PCZT:提取交易、先落库、再广播。 +/// Submits a proven and signed PCZT: extracts the transaction, persists it, then broadcasts. /// -/// 返回 `{ txid, broadcast: "accepted" | "rejected" | "unknown", error? }`。 -/// - `rejected`:节点明确判定共识无效或已过期,永远上不了链。交易仍在库里, -/// 它花的 note 要到过期高度才回来。 -/// - `unknown`:不能确定节点收没收到。交易保持待确认、同步时重播,宿主**不得** -/// 当作发送失败。 +/// Returns `{ txid, broadcast: "accepted" | "rejected" | "unknown", error? }`. +/// - `rejected`: the node definitively judged it consensus-invalid or expired; it can never be +/// mined. The transaction stays stored and its notes return only at expiry height. +/// - `unknown`: delivery to the node is uncertain. The transaction stays pending and is +/// rebroadcast on sync; the host must not treat it as a failed send. #[wasm_bindgen(js_name = pcztSubmit)] pub async fn pczt_submit( account_uuid: String, @@ -716,11 +708,12 @@ pub fn rebroadcastable_txids(account_uuid: String) -> Result { })?) } -/// 重播已落库、结局未知的交易(同步时调用)。**不可逆。** +/// Rebroadcasts a stored transaction with an unknown outcome (called during sync). Irreversible. /// -/// 节点明确判定无效抛 `BROADCAST_REJECTED`(不要重试,先查原因); -/// 节点回了错误但不能确定上不了链时抛 `BROADCAST_OUTCOME_UNKNOWN`,网络本身出错 -/// 抛 `NETWORK_ERROR` —— 这两种交易都仍待确认,下次同步照常重播。 +/// Throws `BROADCAST_REJECTED` when the node definitively rejects it (do not retry); +/// `BROADCAST_OUTCOME_UNKNOWN` when the node errored without proving it can never be mined; +/// `NETWORK_ERROR` on transport failure. In the latter two cases the transaction stays pending +/// and is rebroadcast on the next sync. #[wasm_bindgen(js_name = broadcastTransaction)] pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> { let result = runtime::with_db_and_client(move |mut db, mut client| async move { @@ -733,9 +726,8 @@ pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> { let r = match r { Ok(()) => tx_state::mark_accepted(&mut db, &txid), Err(e) if e.code == crate::ErrorCode::BroadcastRejected => { - // 落库失败也要把**节点给的拒绝原因**交回宿主:那才是用户能据以 - // 行动的信息,而重试这笔广播只会被同样地拒。落库本身的失败作为 - // detail 附上,不顶替结论。 + // Even if persisting fails, return the node's rejection reason: it is what the + // user can act on. The persistence failure is attached as detail. match tx_state::mark_rejected(&mut db, &txid, &e) { Ok(()) => Err(e), Err(persist_error) => { @@ -753,7 +745,7 @@ pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> { .as_ref() .is_err_and(|error| error.code == crate::ErrorCode::BroadcastRejected); if changed_lifecycle { - // 广播已经发生,生命周期也已写进事务 —— 结局必须原样带给宿主。 + // The broadcast happened and the lifecycle is committed; the outcome must reach the host unchanged. let outcome = match &result { Ok(()) => serde_json::json!({ "broadcast": "accepted" }), Err(rejection) => serde_json::json!({ @@ -769,18 +761,18 @@ pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> { Ok(result?) } -// ── 自检 ──────────────────────────────────────────────────────────────── +// ── Self-check ────────────────────────────────────────────────────────── -/// 删除一个钱包库(连同 IndexedDB 里的字节)。**不可逆。** +/// Deletes a wallet database (including its bytes in IndexedDB). Irreversible. /// -/// 库是纯派生缓存:UFVK 与 birthday 由宿主保管,不在库里,所以删掉只是要重扫。 -/// 用途一是最后一个账户移除后删文件,用途二是 App 重置。 +/// The database is a derived cache: UFVKs and birthdays are kept by the host, so deleting +/// only forces a rescan. Used after the last account is removed and on app reset. /// -/// 不检查在途交易:两个用途都必须删成,交易本身已在链上或会过期。 -/// 需要等交易落定的操作(暂停、重置缓存)由宿主在调用前自己判断。 +/// Does not check in-flight transactions: both uses must succeed, and transactions are already +/// on chain or will expire. Operations that must wait for settlement are gated by the host. /// -/// 若删的正是当前打开的库,会先自动关闭 —— 底层要求删除前库必须已关闭。 -/// 返回 `true` 表示确实删掉了,`false` 表示本来就不存在(不算错误)。 +/// Closes the database first if it is the one currently open (required before deletion). +/// Returns `true` if deleted, `false` if it did not exist (not an error). #[wasm_bindgen(js_name = deleteWallet)] pub async fn delete_wallet(db_name: String) -> Result { if !storage::database_exists(&db_name).await? { @@ -792,15 +784,15 @@ pub async fn delete_wallet(db_name: String) -> Result { Ok(storage::delete_database(&db_name).await?) } -/// 当前钱包库的用量,按数据语义分组。**只读,不改任何数据。** +/// Usage of the open wallet database, grouped by data meaning. Read-only. /// -/// 这是**稳定契约**,不是 `diag*` —— 宿主要靠它做容量守卫(比如超过软阈值就 -/// 停掉 birthday 回填),那属于产品行为,不能建立在随时会消失的排障接口上。 +/// A stable contract, not `diag*`: the host uses it for capacity guards (e.g. stopping +/// birthday backfill above a soft threshold). /// -/// `logicalBytes` 是页数 × 页大小,**不等于 IndexedDB 的物理占用**:那边有写 -/// 放大、旧版本页和异步刷盘。两个数不该互相外推。 +/// `logicalBytes` is page count × page size, not IndexedDB physical usage (which includes +/// write amplification, stale pages and async flushes). Do not extrapolate one from the other. /// -/// 刻意不提供「执行任意 SQL」:一条写错的语句就能删掉仍待证明的 anchor。 +/// Arbitrary SQL is deliberately not offered: one bad statement could delete an anchor still needed for proving. #[wasm_bindgen(js_name = storageStats)] pub fn storage_stats() -> Result { let db_name = runtime::open_db_name() @@ -821,9 +813,9 @@ pub fn database_health() -> Result { Ok(runtime::with_read_conn(crate::stats::database_health)?) } -/// 诊断:数一份 PCZT 里各 bundle 有多少输入。 +/// Diagnostic: counts inputs per bundle in a PCZT. /// -/// 用来回答「这笔钱是从哪个池出去的」——费用差只能间接推断,输入个数是直接证据。 +/// Input counts are direct evidence of which pool funds left from; fee differences are only indirect. #[wasm_bindgen(js_name = diagPcztInputCounts)] pub fn pczt_input_counts(pczt_bytes: Vec) -> Result { let pczt = pczt::Pczt::parse(&pczt_bytes).map_err(|e| { @@ -831,19 +823,19 @@ pub fn pczt_input_counts(pczt_bytes: Vec) -> Result { crate::RuntimeError::new(crate::ErrorCode::PcztError).detail(format!("{e:?}")), ) })?; - // action 个数单独看会骗人:Orchard/Ironwood 的 action 是「花费+输出」成对的, - // 而且 bundle 会补 dummy 凑到最少 2 个。所以「有 2 个 action」既可能是真花了 - // 屏蔽 note,也可能只是找零输出加一个 dummy。 + // Action counts alone mislead: Orchard/Ironwood actions pair a spend with an output, and + // bundles are padded with dummies to at least 2. Two actions may be a real shielded spend + // or just a change output plus a dummy. // - // `valueSum` = 该池的花费减输出(负号单独给出)。为负说明净流入这个池 - // (只收了找零),为正才说明真的花了这个池里的 note。 + // `valueSum` = the pool's spends minus outputs (sign given separately). Negative means net + // inflow (change only); positive means notes from this pool were actually spent. let sum = |b: &pczt::orchard::Bundle| { let (magnitude, negative) = *b.value_sum(); serde_json::json!({ "magnitude": magnitude, "negative": negative }) }; - // 透明输入的**金额**才是判断有没有混合的可靠依据: - // 屏蔽花费额 = 付款额 + 手续费 − 透明输入额。`valueSum` 只给净流向, - // 净流入为负并不等于零花费 —— 一笔交易完全可以既有真实屏蔽花费又净流入。 + // The transparent input value is the reliable mixing indicator: + // shielded spend = payment + fee − transparent input. `valueSum` gives only net flow, and a + // net inflow does not imply zero shielded spend. let transparent_value: u64 = pczt.transparent().inputs().iter().map(|i| *i.value()).sum(); Ok(serde_json::json!({ @@ -858,7 +850,7 @@ pub fn pczt_input_counts(pczt_bytes: Vec) -> Result { .to_string()) } -/// 自检:打开库、跑完迁移,回报建出来的表 / 视图 / 索引数量。 +/// Self-check: opens the database, runs migrations, and reports table / view / index counts. #[wasm_bindgen(js_name = diagSelfCheck)] pub fn self_check(network_name: &str, db_name: &str) -> Result { drop(wallet::open_and_migrate(network_name, db_name)?); diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs index ac307a53f..471594e65 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs @@ -1,13 +1,9 @@ -//! 内存版 compact block 缓存。 +//! In-memory compact block cache. //! -//! `zcash_client_backend::sync::run` 需要一个 `BlockCache`,官方在 -//! `zcash_client_sqlite` 里提供的是文件系统版(`FsBlockDb`),浏览器用不了。 -//! -//! 这里用内存实现,理由是 compact block 是**过程性数据**:下载 → 扫描 → 用完即弃。 -//! 真正需要持久化的是扫描结果(note、witness、承诺树),那些由 `zcash_client_sqlite` -//! 写进 SQLite,已经落在 IndexedDB 上。 -//! -//! 内存占用受 `sync::run` 的 `batch_size` 约束:一次只保留正在扫的那一批。 +//! `zcash_client_backend::sync::run` needs a `BlockCache`; upstream's `FsBlockDb` +//! needs a filesystem. Compact blocks are transient (download, scan, discard); +//! scan results are persisted by `zcash_client_sqlite`. Memory is bounded by the +//! `sync::run` batch size. use std::collections::BTreeMap; use std::ops::Range; @@ -36,7 +32,7 @@ impl MemoryBlockCache { } } - /// 当前缓存的区块数量,供宿主观测内存占用。 + /// Number of cached blocks, for observing memory use. pub fn len(&self) -> usize { self.blocks.lock().map(|b| b.len()).unwrap_or(0) } @@ -49,18 +45,18 @@ impl MemoryBlockCache { let r = range.block_range(); u32::from(r.start)..u32::from(r.end) } - /// 写入一批区块。缓存是过程性数据,重复写入同一高度即覆盖。 + /// Inserts blocks; an existing height is overwritten. pub fn insert(&self, compact_blocks: Vec) -> Result<(), CacheError> { let mut blocks = self.blocks.lock().map_err(|_| poisoned())?; for b in compact_blocks { let h = u32::try_from(b.height) - .map_err(|_| CacheError(format!("区块高度超出范围: {}", b.height)))?; + .map_err(|_| CacheError(format!("block height out of range: {}", b.height)))?; blocks.insert(h, b); } Ok(()) } - /// 扫完即弃:删掉一段区间,把内存还回去。 + /// Drops a scanned range to free memory. pub fn delete(&self, range: &ScanRange) -> Result<(), CacheError> { let mut blocks = self.blocks.lock().map_err(|_| poisoned())?; let r = Self::range_of(range); @@ -72,7 +68,7 @@ impl MemoryBlockCache { } } -/// 缓存自身的错误。内存实现里唯一可能的失败是锁中毒。 +/// Cache error. In memory, the only failure is a poisoned lock. #[derive(Debug)] pub struct CacheError(pub String); @@ -85,7 +81,7 @@ impl std::fmt::Display for CacheError { impl std::error::Error for CacheError {} fn poisoned() -> CacheError { - CacheError("内部锁中毒(上一次持锁时发生了 panic)".into()) + CacheError("internal lock poisoned (a previous holder panicked)".into()) } impl BlockSource for MemoryBlockCache { @@ -100,16 +96,14 @@ impl BlockSource for MemoryBlockCache { where F: FnMut(CompactBlock) -> Result<(), error::Error>, { - // 交出去的必须是**从 from_height 起的连续前缀**,允许短读。 - // - // 这条契约不是形式主义:调用方拿 `prior` 的元数据去接续扫描,喂给它一段 - // 跳号的块会被上游判成 `BlockHeightDiscontinuity`,而那个错误 是 - // `is_continuity_error()` 的真值 —— 于是服务端漏块会被当成链重组,触发 - // 破坏性回退、重下、再撞同一个洞。宁可短读让下一轮重来。 + // Hand out only a contiguous prefix starting at from_height; short reads + // are allowed. A gap would surface upstream as `BlockHeightDiscontinuity`, + // which `is_continuity_error()` treats as a reorg, so a block missing on + // the server would trigger a destructive rewind that hits the same gap again. // - // 先在持锁时收集,再释放锁,最后才执行回调:回调会写钱包库,而上游有 - // 可能在那条路径上再次读取本缓存。`std::sync::Mutex` 不可重入,同一线程 - // 二次加锁在 wasm 单线程环境下就是永久死锁。 + // Collect under the lock and release it before calling back: the callback + // writes the wallet and upstream may read this cache again on that path. + // `std::sync::Mutex` is not reentrant, so that would deadlock on wasm. let selected: Vec = { let blocks = self .blocks @@ -135,18 +129,19 @@ impl BlockSource for MemoryBlockCache { expect = next; } - // 起点缺失时一块都不交,并且**报错而不是静默返回空**:静默空会让 - // 上游把空批当成功、队列不推进,调用方原地重下同一段直到批数耗尽。 + // A missing start is an error, not an empty batch: upstream treats an + // empty batch as success without advancing the queue, so the caller + // would re-download the same range until it runs out of batches. if out.is_empty() && cap > 0 && !blocks.is_empty() { return Err(error::Error::BlockSource(CacheError(format!( - "缓存缺少起点区块 {start},不能从后面的块接着扫" + "cache is missing start block {start}; cannot scan from later blocks" )))); } out - }; // 锁在这里释放 + }; // lock released here - // 逐块打点:把「卡在第几块的扫描里」和「所有块都扫完了、卡在之后的 - // 写库/承诺树里」分开。只在排查构建里编进来。 + // Per-block tracing separates a stall in scanning from one in the later + // database/tree writes. debug-tracing builds only. #[cfg(feature = "debug-tracing")] let total = selected.len(); // The index is consumed only by the debug-tracing build. @@ -154,7 +149,7 @@ impl BlockSource for MemoryBlockCache { for (_i, block) in selected.into_iter().enumerate() { #[cfg(feature = "debug-tracing")] crate::sync::trace(&format!( - "cache: 交出第 {}/{} 块 h={}", + "cache: handing out block {}/{} h={}", _i + 1, total, block.height @@ -162,7 +157,7 @@ impl BlockSource for MemoryBlockCache { with_block(block)?; } #[cfg(feature = "debug-tracing")] - crate::sync::trace("cache: 本批区块已全部交出,之后的时间都在上游写库/承诺树里"); + crate::sync::trace("cache: batch handed out; remaining time is upstream db/tree writes"); Ok(()) } } @@ -186,7 +181,7 @@ mod tests { ) } - /// 收集 `with_blocks` 实际交出来的高度 —— 这是扫描唯一走的那条路。 + /// Heights actually handed out by `with_blocks`, the path scanning uses. fn handed_out( c: &MemoryBlockCache, from: u32, @@ -222,7 +217,7 @@ mod tests { assert_eq!(handed_out(&c, 10, 2).unwrap(), vec![10, 11]); } - /// 缺口之后的区块不能被交出去,否则上游会把跳号判成链重组并触发破坏性回退。 + /// Blocks past a gap must not be handed out, or upstream sees a reorg and rewinds. #[test] fn hand_out_stops_at_gap() { let c = MemoryBlockCache::new(); @@ -230,12 +225,11 @@ mod tests { assert_eq!( handed_out(&c, 10, 4).unwrap(), vec![10, 11], - "高度 12 缺,就该停" + "must stop at missing height 12" ); } - /// 起点缺失要**报错**,不能静默返回空 —— 静默空会被当成扫描成功, - /// 队列不推进,调用方原地重下同一段。 + /// A missing start must error; an empty batch would read as a successful scan. #[test] fn missing_start_is_an_error_not_an_empty_batch() { let c = MemoryBlockCache::new(); @@ -243,7 +237,7 @@ mod tests { let e = handed_out(&c, 10, 2).unwrap_err(); assert!( matches!(e, error::Error::BlockSource(CacheError(ref m)) if m.contains("10")), - "起点缺失应报 BlockSource 错误,实际 {e:?}" + "missing start should be a BlockSource error, got {e:?}" ); } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs index 0d9260597..4e2f4b8b8 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs @@ -1,15 +1,13 @@ -//! 时钟。 +//! Clock. //! -//! `zcash_client_sqlite` 需要一个 `Clock` 来给数据库记录时间戳,官方提供的 -//! `SystemClock` 走 `std::time::SystemTime::now()`。在 wasm32-unknown-unknown 上 -//! 那个调用会 panic(std 没有该平台的时间源),所以浏览器侧必须自己接。 -//! -//! 这是本 crate 存在的典型理由之一:一小块平台胶水,不是业务逻辑。 +//! `zcash_client_sqlite` timestamps records through a `Clock`. The upstream +//! `SystemClock` calls `std::time::SystemTime::now()`, which panics on +//! wasm32-unknown-unknown, so the browser needs its own. use std::time::{Duration, SystemTime}; use zcash_client_sqlite::util::Clock; -/// 由宿主 JS 的 `Date.now()` 驱动的时钟。 +/// Clock backed by the host's JS `Date.now()`. #[derive(Clone, Copy, Default)] pub struct HostClock; @@ -21,7 +19,7 @@ impl Clock for HostClock { #[cfg(target_arch = "wasm32")] fn now_millis() -> u64 { - // js_sys::Date::now() 返回自 epoch 的毫秒数(f64)。 + // Milliseconds since the epoch, as f64. let ms = js_sys::Date::now(); if ms.is_finite() && ms > 0.0 { ms as u64 @@ -47,8 +45,8 @@ mod tests { let t = HostClock .now() .duration_since(SystemTime::UNIX_EPOCH) - .expect("时钟不应早于 epoch"); - // 2020-01-01 的毫秒数,确保我们拿到的是真实时间而不是 0。 + .expect("clock must not be before the epoch"); + // 2020-01-01 in ms: a real time, not 0. assert!(t.as_millis() > 1_577_836_800_000); } } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs index cf85c8b64..079d9243a 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs @@ -1,22 +1,19 @@ -//! 错误契约。 +//! Error contract. //! -//! ## 原则 +//! The Rust side produces no user-facing text. The host receives a stable error +//! code plus structured params and renders copy and i18n from the code. Text baked +//! into wasm would need a rebuild and release (and an app-store review on mobile) +//! for every wording change. //! -//! **Rust 侧不产出面向用户的文案。** 抛给宿主的是「稳定错误码 + 结构化参数」, -//! 文案与 i18n 全部由 monorepo 那边根据错误码渲染。 -//! -//! 这不只是分层洁癖:文案编进 wasm 意味着改一句提示语就要重编、重发包、 -//! (移动端还要)过应用商店。错误码和参数是契约,文案是产品。 -//! -//! ## 宿主怎么用 +//! ## Host usage //! //! ```js //! try { //! await rt.syncAdvance(1000); //! } catch (e) { -//! // e.code 稳定错误码,用它做分支 -//! // e.params 结构化参数,用它填 i18n 占位符 -//! // e.detail 上游库的原始报错,只用于日志,不要展示 +//! // e.code stable error code; branch on it +//! // e.params structured params; fill i18n placeholders +//! // e.detail raw upstream error; logs only, never display //! switch (e.code) { //! case 'INSUFFICIENT_FUNDS': //! toast(t('zcash.insufficient', { need: e.params.requiredZat })); @@ -25,114 +22,115 @@ //! } //! ``` //! -//! ## 演进规则 +//! ## Evolution //! -//! 错误码只允许**追加**,不允许改动已有取值的含义或删除 —— 宿主的分支依赖它。 -//! 参数字段同理:可以加,不可以改语义。 +//! Error codes and param fields are append-only: never change the meaning of or +//! remove an existing one, since host branching depends on them. use serde_json::{json, Map, Value}; use std::fmt; -/// 稳定错误码。宿主按此做分支,不要去匹配 `detail` 的文本。 +/// Stable error code. Hosts branch on this, never on `detail` text. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ErrorCode { - // ── 生命周期 ── - /// 尚未 `init()`,存储层未安装。 + // ── Lifecycle ── + /// `init()` not called; storage layer not installed. NotInitialized, - /// 尚未 `openWallet()`。 + /// `openWallet()` not called. WalletNotOpen, - /// 尚未 `setLightwalletdUrl()`。 + /// `setLightwalletdUrl()` not called. LightwalletdNotConfigured, - // ── 入参校验 ── - /// 网络名不是 "main" / "test"。参数:`{ value }` + // ── Input validation ── + /// Network name is not "main" / "test". Params: `{ value }` InvalidNetwork, - /// 数据库名为空或含路径分隔符。参数:`{ value }` + /// Database name is empty or contains a path separator. Params: `{ value }` InvalidDbName, - /// 收款地址无法解析。参数:`{ value }` + /// Recipient address cannot be parsed. Params: `{ value }` InvalidAddress, - /// UFVK 无法解析。 + /// UFVK cannot be parsed. InvalidUfvk, - /// memo 非法(如超长,或给了透明地址)。参数:`{ byteLen }` + /// Invalid memo (too long, or sent to a transparent address). Params: `{ byteLen }` InvalidMemo, - /// 账户 id 不是合法 UUID。参数:`{ value }` + /// Account id is not a valid UUID. Params: `{ value }` InvalidAccountId, - /// 金额超出 Zatoshis 范围。参数:`{ valueZat }` + /// Amount outside the Zatoshis range. Params: `{ valueZat }` AmountOutOfRange, - /// 确认数策略不合法(须 >= 1 且 trusted <= untrusted)。 - /// 参数:`{ trusted, untrusted }` + /// Invalid confirmations policy (requires >= 1 and trusted <= untrusted). + /// Params: `{ trusted, untrusted }` InvalidConfirmationsPolicy, - /// 批大小为 0 或越界。参数:`{ value }` + /// Batch size is 0 or out of range. Params: `{ value }` InvalidBatchSize, - /// 区块高度越界。参数:`{ value }` + /// Block height out of range. Params: `{ value }` InvalidBlockHeight, - // ── 业务状态 ── - /// 找不到该账户。参数:`{ accountId }` + // ── Wallet state ── + /// Account not found. Params: `{ accountId }` AccountNotFound, - /// 尚未同步任何区块,读不到钱包摘要。 + /// No blocks synced yet; wallet summary unavailable. NotSynced, - /// 余额不足。参数:`{ requiredZat, availableZat }`(能取到时) + /// Insufficient funds. Params: `{ requiredZat, availableZat }` (when available) InsufficientFunds, - /// 屏蔽余额不足,但透明余额本可补上 —— 钱在,只是在透明池里。 - /// - /// 与 `InsufficientFunds` 分开,是因为对用户来说这两件事完全不同: - // ── 外部依赖 ── - /// lightwalletd 网络错误。参数:`{ operation }` + // ── External dependencies ── + /// lightwalletd network error. Params: `{ operation }` NetworkError, - /// 钱包数据库错误(含 schema 迁移失败)。参数:`{ operation }` + /// Wallet database error (including schema migration failure). Params: `{ operation }` DatabaseError, - /// 检测到链重组。参数:`{ atHeight, suggestedRewindHeight }` + /// Chain reorg detected. Params: `{ atHeight, suggestedRewindHeight }` /// - /// **不是故障,是正常事件** —— 链尖几个块被替换了。宿主应当调 `rewindTo` - /// 到建议高度然后继续同步。压成 `DATABASE_ERROR` 会让宿主无从判断该重试 - /// 还是该回退、更不知道退到哪里。 + /// A normal event, not a failure: blocks near the tip were replaced. The host + /// should `rewindTo` the suggested height and resume syncing. ReorgDetected, - /// 正在进行一次异步操作,此刻不能切换/关闭钱包。参数:`{ operation }` + /// An async operation is in flight; the wallet cannot be switched or closed now. + /// Params: `{ operation }` /// - /// 这不是内部错误而是**并发保护**:中途换库会让进行中的操作把结果写到 - /// 错误的库上,且没有任何迹象。宿主应当序列化对同一 runtime 的调用, - /// 或等当前操作结束后重试。 + /// Concurrency guard: swapping databases mid-operation would silently write + /// results to the wrong wallet. Hosts should serialize calls to one runtime or + /// retry after the current operation finishes. WalletBusy, - /// 扫描优先级名称不合法。参数:`{ value }` + /// Invalid scan priority name. Params: `{ value }` InvalidScanPriority, /// No privacy identity was explicitly enabled for this scan. /// /// An empty active set must never fall back to every UFVK stored in the runtime database. NoActiveAccounts, - /// reservationId 不是 64 位 hex。参数:`{ value }` + /// reservationId is not 64 hex chars. Params: `{ value }` InvalidReservationId, - /// txid 格式不合法(不是 64 位 hex)。参数:`{ value }` 或 `{ value, byteLen }` + /// Malformed txid (not 64 hex chars). Params: `{ value }` or `{ value, byteLen }` InvalidTxid, - /// PCZT 解析或序列化失败。参数:`{ stage }` + /// PCZT parse or serialization failed. Params: `{ stage }` PcztError, - /// 交易构造失败(选币、费用、anchor 等)。参数:`{ stage }` + /// Transaction construction failed (note selection, fee, anchor, etc.). Params: `{ stage }` TransactionBuildError, - /// 节点明确判定这笔交易共识上无效或已过期,永远上不了链。 - /// 参数:`{ errorCode }`,`detail` 里是节点原文。 + /// The node definitively judged the transaction consensus-invalid or expired; it + /// can never be mined. Params: `{ errorCode }`; `detail` holds the node's message. /// - /// 与 `NETWORK_ERROR` 分开:网络错误可以原样重试,被拒绝**不能** —— - /// 重发同一笔只会再被拒一次。交易已落库,它花的 note 要到过期高度才回来。 + /// Unlike `NETWORK_ERROR`, this must not be retried as-is. The transaction is + /// already stored; its spent notes return only at the expiry height. BroadcastRejected, - /// 节点回了错误,但不能确定这笔交易上不了链:可能已经上链/在池里(双花、 - /// 重复 nullifier、找不到输入),也可能只是节点暂时不收(忙、内存池满、 - /// 同步落后)。交易保持待确认、同步时重播,由扫链见到上链或过期来定。 - /// 宿主**不得**把它当作发送失败。参数:`{ errorCode }`,`detail` 里是节点原文。 + /// The node returned an error that does not prove the transaction can never be + /// mined: it may already be mined or in the mempool (double spend, duplicate + /// nullifier, missing inputs), or the node may be temporarily refusing (busy, + /// mempool full, lagging). The transaction stays pending and is rebroadcast + /// during sync; scanning resolves it as mined or expired. Hosts must not treat + /// this as a failed send. Params: `{ errorCode }`; `detail` holds the node's message. BroadcastOutcomeUnknown, - /// 本地交易没有持久化的广播授权。参数:`{ txid }`。 + /// No persisted broadcast intent for this local transaction. Params: `{ txid }`. BroadcastIntentNotFound, - /// 广播授权存在,但当前状态不允许广播。参数:`{ txid, state }`。 + /// Broadcast intent exists but its state does not allow broadcasting. + /// Params: `{ txid, state }`. BroadcastIntentNotReady, - /// 交易可能已写入内存钱包,但持久化结果无法确认。不得解锁或重建交易。 + /// The transaction may be in the in-memory wallet but persistence is unconfirmed. + /// Do not unlock or rebuild the transaction. FinalizeOutcomeUnknown, - /// 该能力尚未实现。参数:`{ what }` + /// Capability not implemented. Params: `{ what }` Unimplemented, } impl ErrorCode { - /// 稳定字符串形式。**不要改动已有取值。** + /// Stable string form. Never change existing values. pub fn as_str(self) -> &'static str { use ErrorCode::*; match self { @@ -175,9 +173,9 @@ impl ErrorCode { #[derive(Debug)] pub struct RuntimeError { pub code: ErrorCode, - /// 结构化参数,供宿主填 i18n 占位符。永远是一个 JSON 对象。 + /// Structured params for host i18n placeholders. Always a JSON object. pub params: Value, - /// 上游库的原始报错。**仅用于日志**,不面向用户,不做 i18n。 + /// Raw upstream error. Logs only; not user-facing, not localized. pub detail: Option, } @@ -190,7 +188,7 @@ impl RuntimeError { } } - /// 带结构化参数。`params` 应当是一个 JSON 对象。 + /// With structured params. `params` should be a JSON object. pub fn with(code: ErrorCode, params: Value) -> Self { Self { code, @@ -199,13 +197,13 @@ impl RuntimeError { } } - /// 附上游原始报错,仅供日志。 + /// Attach the raw upstream error, for logs only. pub fn detail(mut self, d: impl fmt::Display) -> Self { self.detail = Some(d.to_string()); self } - /// 序列化成宿主能直接消费的 JSON。 + /// Serialize to JSON the host can consume directly. pub fn to_json(&self) -> Value { json!({ "code": self.code.as_str(), @@ -217,7 +215,7 @@ impl RuntimeError { impl fmt::Display for RuntimeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - // 面向日志,不面向用户。 + // For logs, not users. write!(f, "{} {}", self.code.as_str(), self.params)?; if let Some(d) = &self.detail { write!(f, " :: {d}")?; @@ -236,10 +234,10 @@ impl From for RuntimeError { pub type Result = std::result::Result; -/// 抛给 JS 的形状:`Error` 对象上挂 `code` / `params` / `detail`。 +/// JS shape: an `Error` carrying `code` / `params` / `detail`. /// -/// `message` 故意只放错误码 —— 它不是给用户看的文案, -/// 宿主拿 `code` 去查自己的 i18n 表。 +/// `message` is just the error code; it is not user-facing text. Hosts map `code` +/// through their own i18n table. #[cfg(target_arch = "wasm32")] impl From for wasm_bindgen::JsValue { fn from(e: RuntimeError) -> Self { @@ -262,15 +260,12 @@ impl From for wasm_bindgen::JsValue { set("detail", wasm_bindgen::JsValue::from_str(d)); } - // 同一份内容再放进 `payload`。 - // - // 宿主把错误跨进程/跨 WebView 传递时,序列化器只转发一份**固定的**字段 - // 名单,`params` 与 `detail` 不在其中 —— 平铺的那几个字段只有直接调用 - // (不跨载体)时才到得了对面,跨载体就只剩 `code`。`payload` 在名单里, - // 所以结构化参数必须搭这班车。 + // Duplicate the same fields under `payload`. // - // 两份都留:平铺的是本 crate 的契约,宿主直接调时读它;`payload` 是给 - // 跨载体那条路用的。内容相同,不存在哪份更新的问题。 + // When the host forwards errors across processes or WebViews, its serializer + // only passes a fixed field allowlist that includes `payload` but not `params` + // or `detail`. The flat fields are this crate's contract for direct calls; + // `payload` carries them across that boundary. let payload = js_sys::Object::new(); let pset = |k: &str, v: wasm_bindgen::JsValue| { let _ = js_sys::Reflect::set(&payload, &wasm_bindgen::JsValue::from_str(k), &v); @@ -330,10 +325,10 @@ mod tests { let mut seen = std::collections::HashSet::new(); for c in all { let s = c.as_str(); - assert!(seen.insert(s), "错误码重复: {s}"); + assert!(seen.insert(s), "duplicate error code: {s}"); assert!( s.chars().all(|ch| ch.is_ascii_uppercase() || ch == '_'), - "错误码必须是 SCREAMING_SNAKE_CASE: {s}" + "error code must be SCREAMING_SNAKE_CASE: {s}" ); } } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/guard.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/guard.rs index 86d8d85f8..cbdc40856 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/guard.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/guard.rs @@ -1,29 +1,27 @@ -//! 破坏性操作前的统一闸门。 +//! Shared gate for destructive operations. //! -//! 这些操作会丢掉扫描结果、账户或整个库。它们共用一个判断:钱包现在是不是 -//! 「闲着」—— 没有在途提案、没有未落块的花费、没有未确认结局的广播。 +//! Operations that drop scan results, accounts or the whole database require +//! the wallet to be idle: no in-flight proposals, no unmined spends, no +//! broadcasts with an unknown outcome. //! -//! ## 为什么问库而不是问进程 -//! -//! 原来「有没有在途提案」问的是 `send` 里的进程内 map。Worker 一重启它就是 -//! 空的,闸门于是静默放行,而锁本身还在 SQLite 里 —— 正是「用户刷新了页面, -//! 然后点了删除」这条路。锁是持久化的,判断也必须是。 +//! The check reads the database, not process memory: output locks persist in +//! SQLite and survive a Worker restart, so the check must as well. use serde_json::json; use crate::error::{ErrorCode, Result, RuntimeError}; use crate::history::uuid_blob; -/// 输出锁算不算「忙」。 +/// Whether output locks count as busy. #[derive(Clone, Copy, PartialEq, Eq)] pub enum LockPolicy { - /// 未过期的锁就拒绝:可能有人正在证明或签名这批 note。 + /// Refuse on any unexpired lock: those notes may be being proven or signed. Blocking, - /// 锁正是这个操作要清的东西,拿它当拒绝理由等于让修复按钮永远点不动。 + /// The operation clears the locks itself, so they cannot block it. Ignored, } -/// 带锁的四张表。上游按池分表,锁列在每张表上各有一份。 +/// Tables with lock columns; upstream keeps one per pool. const LOCKABLE_TABLES: [&str; 4] = [ "sapling_received_notes", "orchard_received_notes", @@ -35,7 +33,7 @@ fn db_err(operation: &str, error: impl std::fmt::Display) -> RuntimeError { RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": operation })).detail(error) } -/// 链尖。与上游 `chain_tip_height` 同源:扫描区间是右开的,所以减一。 +/// Chain tip, as upstream `chain_tip_height`: scan ranges are end-exclusive, hence -1. fn chain_tip(conn: &rusqlite::Connection) -> Result> { conn.query_row("SELECT MAX(block_range_end) FROM scan_queue", [], |row| { row.get::<_, Option>(0) @@ -44,10 +42,10 @@ fn chain_tip(conn: &rusqlite::Connection) -> Result> { .map_err(|e| db_err("walletIdleChainTip", e)) } -/// 这个账户(`None` = 整个库)名下还有没有未过期的输出锁。 +/// Whether the account (`None` = whole database) has unexpired output locks. fn has_live_locks(conn: &rusqlite::Connection, account_uuid: Option<&str>) -> Result { - // 链尖未知时不做过期判断:宁可报忙,也不要因为读不到高度就把一批 - // 正在签名的 note 判成空闲。 + // With an unknown tip, treat every lock as live: report busy rather than + // free notes that may be mid-signing. let tip = chain_tip(conn)?; let account_filter = account_uuid .map(|uuid| uuid_blob(uuid).map(Some)) @@ -76,7 +74,8 @@ fn has_live_locks(conn: &rusqlite::Connection, account_uuid: Option<&str>) -> Re Ok(false) } -/// 已花出去但还没落块、也还没过期的交易。回退或删除会把它的记录一起丢掉。 +/// Spending transactions that are neither mined nor expired; a rewind or delete +/// would lose their records. fn has_unsettled_outgoing(conn: &rusqlite::Connection, account_uuid: Option<&str>) -> Result { let account_filter = account_uuid .map(|uuid| uuid_blob(uuid).map(Some)) @@ -97,7 +96,7 @@ fn has_unsettled_outgoing(conn: &rusqlite::Connection, account_uuid: Option<&str .map_err(|e| db_err("walletIdleOutgoing", e)) } -/// 已授权广播、结局还没确定的交易。这份状态不是可重建的扫描缓存。 +/// Authorized broadcasts with no known outcome. This state cannot be rebuilt by rescanning. fn has_unresolved_broadcast( conn: &rusqlite::Connection, account_uuid: Option<&str>, @@ -126,8 +125,8 @@ fn has_unresolved_broadcast( .map_err(|e| db_err("walletIdleBroadcast", e)) } -/// 钱包不空闲就拒绝。`account_uuid` 为 `None` 时判整个库 —— 回退和删库影响 -/// 的是共享库里的每一个账户,只看当前这个会漏掉别人的在途交易。 +/// Errors with `WalletBusy` unless the wallet is idle. Pass `None` for operations +/// that affect every account in the shared database (rewind, delete). pub fn assert_idle( conn: &rusqlite::Connection, account_uuid: Option<&str>, @@ -159,9 +158,8 @@ mod tests { use super::*; use rusqlite::Connection; - /// 在真实迁移出来的库上跑一遍。目的不是看结果,是证明**每条 SQL 的表名和 - /// 列名都真实存在** —— 写错的话 SQLite 在这里就报错,而不是等到线上把 - /// 「读不出来」当成「钱包空闲」然后删库。 + /// Runs against a migrated database to prove every table and column in the + /// SQL exists, so a typo fails here rather than reading as "idle". #[test] fn every_query_matches_the_real_schema() { let path = @@ -213,7 +211,7 @@ mod tests { } } - /// 这是整个改动的理由:锁在库里,进程内那张表重启就空了。 + /// Locks persist in the database, so they block after a restart. #[test] fn a_persisted_lock_blocks_the_account_that_holds_it() { let conn = Connection::open_in_memory().unwrap(); @@ -221,7 +219,7 @@ mod tests { let owner = uuid::Uuid::from_u128(1).to_string(); let other = uuid::Uuid::from_u128(2).to_string(); - // 还没有锁:谁都空闲。 + // No locks yet: idle. assert!(assert_idle(&conn, Some(&owner), "removeAccount", LockPolicy::Blocking).is_ok()); conn.execute( @@ -236,11 +234,11 @@ mod tests { assert_eq!(err.params["activeReservation"], true); assert_eq!(err.params["operation"], "removeAccount"); - // 别人的账户不受影响;整库判则看得见。 + // Other accounts are unaffected; the whole-database check sees it. assert!(assert_idle(&conn, Some(&other), "removeAccount", LockPolicy::Blocking).is_ok()); assert!(assert_idle(&conn, None, "rewindTo", LockPolicy::Blocking).is_err()); - // clearLockedOutputs 清的就是它,不能拿它当拒绝理由。 + // clearLockedOutputs clears this lock, so it must not be refused. assert!(assert_idle( &conn, Some(&owner), @@ -255,7 +253,7 @@ mod tests { let conn = Connection::open_in_memory().unwrap(); fixture(&conn); let owner = uuid::Uuid::from_u128(1).to_string(); - // 链尖 1000(scan_queue 右开),过期高度 900 已经过去了。 + // Tip is 1000 (scan_queue is end-exclusive); expiry 900 has passed. conn.execute( "INSERT INTO orchard_received_notes VALUES (1, ?1, 900)", rusqlite::params![[7_u8; 32]], @@ -264,8 +262,8 @@ mod tests { assert!(assert_idle(&conn, Some(&owner), "removeAccount", LockPolicy::Blocking).is_ok()); } - /// 广播还没有结局的时候,连「修复」按钮也不能动锁 —— 解锁等于把正在被 - /// 一笔待确认交易花掉的 note 放回可选池。 + /// With an unresolved broadcast even the repair path must not unlock: that + /// would return notes spent by a pending transaction to the selectable pool. #[test] fn an_unresolved_broadcast_blocks_even_the_repair_path() { let conn = Connection::open_in_memory().unwrap(); diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs index d36aefb2a..8d129035b 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs @@ -1,37 +1,24 @@ -//! 交易历史。 +//! Transaction history. //! -//! ## 为什么直接查视图 +//! Upstream `WalletRead::get_tx_history` is test-only (its return type lives in +//! `testing`), so this reads the `v_transactions` view maintained by +//! `zcash_client_sqlite`, as the official Android / iOS SDKs do. //! -//! `zcash_client_backend` 的 `WalletRead::get_tx_history` 上游明确标注为 **test-only** -//! (「production use could return a very large number of results; either pagination or a -//! streaming design will be necessary to stabilize this feature」),返回类型还在 -//! `testing` 模块下。不能拿它做生产接口。 +//! Column names are not checked at compile time: run the `history_smoke` test +//! after upgrading `zcash_client_sqlite`. Failures are `DATABASE_ERROR` with +//! `params.operation = "history"`. //! -//! 所以走 `zcash_client_sqlite` 维护的 `v_transactions` 视图 —— 这也是官方 -//! Android / iOS SDK 的做法。视图由上游随 schema 一起演进,我们只读不改。 -//! -//! ## 耦合风险 -//! -//! 直接查视图意味着依赖它的列名。升级 `zcash_client_sqlite` 时列可能变化, -//! 而那**不会**在 Rust 编译期报错,只会在运行时查询失败。因此: -//! -//! - 本模块的查询列表集中在一处,升级时先跑一次 `history_smoke` 测试; -//! - 出错时抛 `DATABASE_ERROR` 且 `params.operation = "history"`,便于定位。 -//! -//! ## 边界 -//! -//! 这里只做**取数与分页**,不做展示模型 —— 「这笔算收入还是支出」「显示成什么文案」 -//! 属于宿主。返回的是中性事实:金额增量、是否找零、note 计数、时间戳。 +//! Returns neutral facts (deltas, change, note counts, timestamps); classifying +//! and labelling transactions is up to the host. use serde_json::json; use crate::error::{ErrorCode, Result, RuntimeError}; -/// 账户 UUID 在官方 schema 里是 **BLOB**(16 字节原始值),不是文本。 +/// Account UUIDs are 16-byte BLOBs in the upstream schema, not text. /// -/// 用 36 字符的连字符形式去绑定,SQLite 不会报错,只会**一行都匹配不上** —— -/// 于是历史、计数、详情全部恒空,而且看起来像「还没同步出数据」。 -/// 这个坑代价很高:坏查询和空钱包的返回值完全一样,测试很容易假绿。 +/// Binding the hyphenated string matches no rows without any error, which is +/// indistinguishable from an empty wallet. pub(crate) fn uuid_blob(account_uuid: &str) -> Result> { uuid::Uuid::parse_str(account_uuid) .map(|u| u.as_bytes().to_vec()) @@ -43,7 +30,7 @@ pub(crate) fn uuid_blob(account_uuid: &str) -> Result> { }) } -/// 每页最多返回多少条,防止宿主一次拉爆内存。 +/// Maximum rows per page. pub const MAX_PAGE_SIZE: u32 = 500; fn db_err(e: impl std::fmt::Display) -> RuntimeError { @@ -147,10 +134,9 @@ const NON_SAPLING_ACTIVITY: &str = "( ) )"; -/// 分页读取某账户的交易历史,返回 JSON 数组。 +/// A page of an account's transaction history as a JSON array. /// -/// 排序:未上链的排在最前(`mined_height IS NULL`),其余按高度倒序。 -/// 这样用户刚发出的交易立刻可见。 +/// Unmined transactions come first, then by height descending. pub fn list( conn: &rusqlite::Connection, account_uuid: &str, @@ -190,7 +176,7 @@ pub fn list( serde_json::to_string(&out).map_err(db_err) } -/// 一行 `v_transactions` → JSON。列表与详情共用,保证两处字段完全一致。 +/// A `v_transactions` row as JSON; shared by list and details so fields match. fn row_to_json(row: &rusqlite::Row<'_>) -> rusqlite::Result { let txid: Vec = row.get(0)?; let per_pool_entries = row @@ -231,7 +217,7 @@ fn row_to_json(row: &rusqlite::Row<'_>) -> rusqlite::Result { .map(|(pool, delta)| (pool.to_string(), serde_json::Value::String(delta))) .collect::>(); Ok(json!({ - // txid 以显示序(大端)给出,与区块浏览器一致。 + // Display (big-endian) order, as block explorers show it. "txid": hex_display_order(&txid), "minedHeight": row.get::<_, Option>(1)?, "blockTime": row.get::<_, Option>(2)?, @@ -244,10 +230,9 @@ fn row_to_json(row: &rusqlite::Row<'_>) -> rusqlite::Result { "receivedNoteCount": row.get::<_, Option>(9)?.unwrap_or(0), "memoCount": row.get::<_, Option>(10)?.unwrap_or(0), "isShielding": row.get::<_, Option>(11)?.unwrap_or(false), - // 本账户在这笔交易里的方向性金额(视图现成列)。宿主用它们分类与 - // 显示:sent 的显示金额 = spent - received - fee(不含手续费的净额), - // 自转/屏蔽的显示金额 = received —— 直接用 balance_delta 会把屏蔽 - // 显示成一笔「手续费大小」的交易。 + // Account-side amounts. Hosts show sends as spent - received - fee and + // self-transfers/shielding as received; balance_delta would show a + // shielding transaction as just its fee. "totalSpentZat": row.get::<_, Option>(12)?, "totalReceivedZat": row.get::<_, Option>(13)?, // Preserve exact upstream pool identifiers. The host may aggregate @@ -259,17 +244,17 @@ fn row_to_json(row: &rusqlite::Row<'_>) -> rusqlite::Result { "perPoolBalanceDeltaZat": per_pool_balance_delta_zat, "broadcastState": row.get::<_, Option>(15)?, "recipient": row.get::<_, Option>(16)?, - // 本账户发出、且不属于本账户任何地址的输出数。为 0 且有花费 = 内部 - // 转移(屏蔽 / 提到自己的透明地址 / 池间搬家),与 fee 是否已知无关 —— - // fee 未知时靠 spent-received 判方向会把自转误判成外发。 + // Outputs sent to addresses outside this account. Zero with spends means + // an internal transfer, whether or not the fee is known; inferring from + // spent - received misreads self-transfers as sends when the fee is unknown. "externalOutputCount": row.get::<_, i64>(17)?, })) } -/// 单笔交易详情。查不到返回 `null`(JSON),不抛错 —— -/// 「这笔不在钱包里」是正常状态,不是故障:外部 txid、已被回滚的交易都会走到这里。 +/// One transaction's details, or JSON `null` if it is not in the wallet +/// (foreign txid, rolled back); that is not an error. pub fn details(conn: &rusqlite::Connection, account_uuid: &str, txid: &str) -> Result { - // 库里 txid 存的是内部序(小端),入参是显示序(大端),先翻回去。 + // Stored in internal (little-endian) order; the input is display order. let internal = display_order_to_internal(txid)?; let sql = format!( @@ -294,20 +279,19 @@ pub fn details(conn: &rusqlite::Connection, account_uuid: &str, txid: &str) -> R } } -/// 单笔交易的**逐笔明细**:本账户被花掉的、收到的,以及发给外部的输出。 +/// Per-output breakdown of one transaction: outputs this account spent, +/// received, and sent externally. /// -/// 数据来自 `v_tx_outputs` —— `zcash_client_sqlite` 维护的每输出一行的视图, -/// 官方 SDK 取交易详情走的也是它。三段的判定规则: +/// Reads `v_tx_outputs`, the per-output view the official SDKs also use: /// -/// - `received`:`to_account_uuid` 是本账户(`is_change` 区分找零与真收款) +/// - `received`: `to_account_uuid` is this account (`is_change` marks change) /// - `external`: sent by this account to an unknown or different account, /// including another account registered in this wallet database. -/// **只有自己发的交易才看得到收款地址**, -/// 别人发给别人的输出我们既解不开也不该出现在这里 -/// - `spent`:本账户在更早交易里收到、且被这笔花掉的输出,走 `v_received_output_spends` +/// Recipient addresses are only known for our own sends. +/// - `spent`: outputs received earlier and spent here, via `v_received_output_spends` /// -/// 池号沿用上游编码:0=transparent, 2=sapling, 3=orchard, 4=ironwood。 -/// 这里原样透出数字并附字符串名,宿主不必自己记这套映射。 +/// Pools use upstream codes (0=transparent, 2=sapling, 3=orchard, 4=ironwood), +/// returned with their names. pub fn details_outputs( conn: &rusqlite::Connection, account_uuid: &str, @@ -337,7 +321,7 @@ pub fn details_outputs( .unwrap_or(false); let memo: Option> = row.get(3).map_err(db_err)?; let address: Option = row.get(4).map_err(db_err)?; - // 同理:读出来也是 BLOB,按 String 读会直接报列类型错误 + // Account UUIDs are BLOBs; reading them as String fails. let to_acct: Option> = row.get(5).map_err(db_err)?; let from_acct: Option> = row.get(6).map_err(db_err)?; @@ -374,9 +358,9 @@ pub fn details_outputs( let mut spent = Vec::new(); { - // 本账户收到的输出中,被这笔交易花掉的那些。 - // 连接键是 (pool, id_within_pool_table) ↔ (pool, received_output_id)。 - // `v_received_output_spends` 里没有 output_index,别拿它当连接键。 + // This account's received outputs spent by this transaction. Join on + // (pool, id_within_pool_table) = (pool, received_output_id); + // `v_received_output_spends` has no output_index. let mut stmt = conn .prepare( "SELECT ro.pool, ro.value, addr.address @@ -416,7 +400,7 @@ pub fn details_outputs( .map_err(db_err) } -/// 上游的池编码。数字是存储层的事实,名字是给宿主省一次查表。 +/// Name for an upstream pool code. fn pool_name(pool: i64) -> &'static str { match pool { 0 => "transparent", @@ -486,7 +470,7 @@ fn memo_details(bytes: &[u8]) -> (Option, Option) { ) } -/// 显示序(大端 hex)→ 内部序(小端字节)。 +/// Display order (big-endian hex) to internal order (little-endian bytes). pub(crate) fn display_order_to_internal(txid: &str) -> Result> { let bytes = hex_decode(txid) .ok_or_else(|| RuntimeError::with(ErrorCode::InvalidTxid, json!({ "value": txid })))?; @@ -505,7 +489,7 @@ fn hex_decode(s: &str) -> Option> { hex::decode(s).ok() } -/// txid 在库里以内部序(小端)存储,浏览器展示用大端。翻转后转 hex。 +/// Stored (little-endian) txid to display-order hex. pub(crate) fn hex_display_order(txid_le: &[u8]) -> String { txid_le.iter().rev().map(|b| format!("{b:02x}")).collect() } @@ -590,7 +574,7 @@ mod tests { #[test] fn rejects_bad_page_size() { - // 用一个内存库即可,查询根本不会执行到。 + // Validation fails before any query runs. let conn = rusqlite::Connection::open_in_memory().unwrap(); for bad in [0, MAX_PAGE_SIZE + 1] { let e = list(&conn, "whatever", bad, 0).unwrap_err(); diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs index dd9285fa6..e5373bf16 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs @@ -1,27 +1,28 @@ //! # OneKey Zcash Runtime //! -//! 官方 `librustzcash` 之上的最薄绑定层。 +//! A thin binding layer over the official `librustzcash`. //! -//! ## 设计边界 +//! ## Scope //! -//! 留在这一侧(wasm / Rust)的只有三类东西: +//! Only three things live on this side: //! -//! 1. **密码学与协议** —— 扫链的 trial decryption、witness 与承诺树维护、 -//! 交易构造与选币。这些跨边界成本高、且错了会丢钱,必须留在原地。 -//! 2. **平台胶水** —— 时钟、随机数、存储 VFS。std 在 wasm32 上不提供的那些。 -//! 3. **形状转换** —— 把 Rust 的富类型转成 JSON 交给宿主。 +//! 1. **Cryptography and protocol**: trial decryption, witness and commitment +//! tree maintenance, transaction building and note selection. Costly to move +//! across the boundary, and mistakes lose funds. +//! 2. **Platform glue**: clock, randomness, storage VFS, which std lacks on wasm32. +//! 3. **Shape conversion**: Rust types to JSON for the host. //! -//! 明确**不**放在这一侧的:调度(什么时候扫、扫哪段)、账户与 birthday 管理、 -//! 缓存策略、进度展示、错误重试。那些属于宿主 TS,改起来快、看得见、能打断点。 +//! Scheduling, account and birthday management, caching, progress and retries +//! belong to the host. //! -//! ## 接口形状 +//! ## Interface //! -//! 动词少、数据简单。每次调用是一次完整往返,wasm 不持有跨调用的会话状态 -//! (数据库除外)。这样宿主侧出问题永远能自己修,wasm 侧只在协议变化时才动。 +//! Few verbs, simple data. Each call is a full round trip; apart from the +//! database, wasm holds no state across calls. -// ── 全平台:钱包核心 ──────────────────────────────────────────────────── -// 这几个模块在 wasm32、aarch64-apple-ios、Android 上都编译。 -// 也就是说移动端**可以**跑完整的钱包逻辑,不必退化成 keys-only。 +// ── All platforms: wallet core ───────────────────────────────────────── +// Builds on wasm32, aarch64-apple-ios and Android, so mobile can run the full +// wallet, not just keys. pub mod account; pub mod blockcache; mod circuit_keys; @@ -35,13 +36,12 @@ pub mod storage; pub mod tx_state; pub mod wallet; -// 网络与扫链现在是全平台的:浏览器走 gRPC-web,原生走 tonic transport。 -// 这也让我们能在本机原生环境复现浏览器里的问题 —— 那边可以上真调试器。 +// Network and sync: gRPC-web in browsers, tonic transport natively. pub mod network; pub mod perf; pub mod sync; -// 跨调用状态用 thread_local,只在单线程的 wasm 宿主里成立。 +// Cross-call state uses thread_local, valid only in the single-threaded wasm host. #[cfg(target_arch = "wasm32")] pub mod runtime; @@ -50,7 +50,7 @@ pub mod bindgen; pub use error::{ErrorCode, Result, RuntimeError}; -/// 本 runtime 依赖的官方 crate 版本,供宿主自检与日志使用。 +/// Upstream crate versions this runtime is built on, for host checks and logs. pub fn dependency_versions() -> serde_json::Value { serde_json::json!({ "zcash_client_backend": "0.24.0", diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs index 49b55c532..ee61a6c9d 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs @@ -1,10 +1,10 @@ -//! lightwalletd 网络层。 +//! lightwalletd network layer. //! -//! 浏览器里跑不了原生 gRPC(没有 HTTP/2 裸连接),所以走 gRPC-web: -//! `tonic-web-wasm-client` 把 tonic 生成的客户端接到 fetch 上。 +//! Browsers have no raw HTTP/2, so wasm uses gRPC-web: `tonic-web-wasm-client` +//! runs the tonic-generated client over fetch. //! -//! 版本约束:`tonic-web-wasm-client` 必须 >= 0.9.1。0.8.0 在流结束时不转发 -//! gRPC trailer,会让 `get_block_range` 这类流式调用永远等不到结束标志。 +//! Requires `tonic-web-wasm-client` >= 0.9.1; 0.8.0 drops gRPC trailers at stream +//! end, so streaming calls like `get_block_range` never complete. use zcash_client_backend::proto::service::{ compact_tx_streamer_client::CompactTxStreamerClient, BlockId, ChainSpec, TreeState, @@ -24,8 +24,8 @@ pub fn set_request_handler(handler: Option) { REQUEST_HANDLER.with(|slot| *slot.borrow_mut() = handler); } -// 浏览器走 gRPC-web(没有原生 HTTP/2 裸连接),原生目标走 tonic 自带 transport。 -// 上层的 `LightClient` 签名在两边一致,`chain_tip` / `tree_state` 等函数不用分叉。 +// wasm uses gRPC-web; native uses tonic's own transport. `LightClient` has the +// same signature on both, so `chain_tip` / `tree_state` etc. need no cfg split. #[cfg(target_arch = "wasm32")] pub type Transport = tonic_web_wasm_client::Client; @@ -34,18 +34,16 @@ pub type Transport = tonic::transport::Channel; pub type LightClient = CompactTxStreamerClient; -/// `operation` 是稳定的机器可读标识(不是文案),宿主可据此区分是哪一步失败。 +/// `operation` is a stable machine-readable id (not text) naming the failed step. fn net_err(operation: &str, e: impl std::fmt::Display) -> RuntimeError { RuntimeError::with(ErrorCode::NetworkError, json!({ "operation": operation })).detail(e) } -/// 把一个网络 future 套上超时。 +/// Wrap a network future in a timeout. /// -/// **为什么必须有**:wasm 里挂死的调用宿主无法取消 —— 没有线程可以中断, -/// Promise 也不会自己 reject。一个不返回的 gRPC 调用会让整个钱包永久卡住, -/// 而且没有任何错误信息。加超时把「挂死」变成「可处理的错误」。 -/// -/// 实测踩过:`get_block_range` 在某些情况下不返回也不报错。 +/// In wasm the host cannot cancel a hung call (no thread to interrupt, the +/// Promise never rejects), so a gRPC call that never returns would wedge the +/// wallet silently. `get_block_range` can hang this way. #[cfg(target_arch = "wasm32")] pub async fn with_timeout( fut: impl std::future::Future>, @@ -63,7 +61,7 @@ pub async fn with_timeout( } } -/// 原生目标用 tokio 的定时器。 +/// Native targets use the tokio timer. #[cfg(not(target_arch = "wasm32"))] pub async fn with_timeout( fut: impl std::future::Future>, @@ -83,12 +81,12 @@ fn timeout_err(operation: &str, timeout_ms: u32) -> RuntimeError { ) } -/// 默认网络超时。单次 gRPC 调用超过这个时长基本可以判定为挂死。 +/// Default network timeout; a single gRPC call exceeding it is treated as hung. pub const DEFAULT_TIMEOUT_MS: u32 = 30_000; -/// 建立一个 lightwalletd 客户端。`base_url` 形如 `https://host:port`。 +/// Build a lightwalletd client. `base_url` looks like `https://host:port`. /// -/// 不做网络往返 —— 真正的连接发生在第一次调用时。 +/// No network round trip; the connection happens on the first call. #[cfg(target_arch = "wasm32")] pub fn connect(base_url: &str) -> Result { if base_url.is_empty() { @@ -97,9 +95,9 @@ pub fn connect(base_url: &str) -> Result { json!({ "reason": "emptyUrl" }), )); } - // 明文会把「这个钱包在查哪些地址」直接暴露给链路上的任何人。原生那条路 - // 靠 `https://` 前缀决定要不要配 TLS,浏览器这条路之前什么都收 —— 补齐, - // 免得哪天开放自定义节点或某个备用地址写错时静默降级。 + // Plaintext would expose which addresses this wallet queries to anyone on the + // path. Require https so a custom node or mistyped fallback URL cannot + // silently downgrade. if !base_url.starts_with("https://") { return Err(RuntimeError::with( ErrorCode::LightwalletdNotConfigured, @@ -116,7 +114,7 @@ pub fn connect(base_url: &str) -> Result { )) } -/// 原生目标的连接。与 wasm 版不同,这里会真的建链接,所以是 async。 +/// Native connect. Unlike wasm this actually opens the connection, hence async. #[cfg(not(target_arch = "wasm32"))] pub async fn connect_native(base_url: &str) -> Result { if base_url.is_empty() { @@ -125,7 +123,7 @@ pub async fn connect_native(base_url: &str) -> Result { json!({ "reason": "emptyUrl" }), )); } - // https 端点必须显式配 TLS —— tonic 0.14 不会自动启用根证书。 + // https endpoints need explicit TLS; tonic 0.14 does not enable root certs by default. let mut endpoint = tonic::transport::Channel::from_shared(base_url.to_owned()) .map_err(|e| net_err("parseEndpoint", e))?; if base_url.starts_with("https://") { @@ -140,7 +138,7 @@ pub async fn connect_native(base_url: &str) -> Result { Ok(CompactTxStreamerClient::new(channel)) } -/// 当前链尖高度。 +/// Current chain tip height. pub async fn chain_tip(client: &mut LightClient) -> Result { let block = with_timeout( async { @@ -162,13 +160,14 @@ pub async fn chain_tip(client: &mut LightClient) -> Result { }) } -/// 把已签名的交易提交给 lightwalletd。 +/// Submit a signed transaction to lightwalletd. /// -/// lightwalletd 的 `SendTransaction` **不用 gRPC 错误表示业务失败** —— 调用成功返回, -/// 但 `SendResponse.error_code != 0` 表示节点拒绝了这笔交易。只看 `Result::Ok` -/// 会把「被拒绝」当成「已广播」,这是这条链路上最容易漏的一步。 +/// `SendTransaction` does not signal node errors via gRPC status: the call +/// succeeds but `SendResponse.error_code != 0` means the node did not accept the +/// transaction. /// -/// 拒绝抛 `BROADCAST_REJECTED`(不可重试),网络本身出错才抛 `NETWORK_ERROR`。 +/// Definite rejections return `BROADCAST_REJECTED` (not retryable), other node +/// errors `BROADCAST_OUTCOME_UNKNOWN`, transport failures `NETWORK_ERROR`. pub async fn broadcast(client: &mut LightClient, tx_bytes: Vec) -> Result<()> { use zcash_client_backend::proto::service::RawTransaction; @@ -177,7 +176,7 @@ pub async fn broadcast(client: &mut LightClient, tx_bytes: Vec) -> Result<() client .send_transaction(RawTransaction { data: tx_bytes, - // 广播时高度未知;lightwalletd 忽略该字段。 + // Height is unknown at broadcast; lightwalletd ignores it. height: 0, }) .await @@ -235,21 +234,21 @@ fn broadcast_outcome_ambiguous(message: &str) -> bool { .any(|needle| message.contains(needle)) } -/// 只有能确定这份字节**永远上不了链**的回复才算拒收。 +/// Only replies proving these bytes can never be mined count as a rejection. /// -/// 拒收会让宿主显示失败、不再把它当在途交易,用户随之重发;而原交易占着的 -/// note 要到过期高度才回来,重发只能换一批 note 去花。原交易若其实已经传播 -/// 出去(上一次超时其实发出去了,或节点一边转发一边回错),两笔都会上链。 -/// 所以这里是白名单:共识上无效(证明、签名、金额、分支不对)或已过期。 -/// 节点忙、内存池满、同步落后、非标准这类临时或策略性回复都不算 —— 记成 -/// 结局未知,同步时重播,过期后自然了结。 +/// A rejection makes the host show a failure and the user resend with other +/// notes (the original's notes stay locked until expiry). If the original +/// actually propagated, both would be mined. So this is an allowlist: +/// consensus-invalid (proof, signature, value, branch) or expired. Transient or +/// policy replies (busy, mempool full, lagging, non-standard) are an unknown +/// outcome, rebroadcast during sync until mined or expired. fn broadcast_definitely_invalid(message: &str) -> bool { if broadcast_outcome_ambiguous(message) { return false; } let message = message.to_lowercase(); - // zcashd: main.cpp 的共识检查拒因。`tx-expiring-soon` 是策略(还剩几块 - // 才过期,别的节点仍可能打包),不在其列。 + // zcashd: consensus reject reasons from main.cpp. `tx-expiring-soon` is policy + // (other nodes may still mine it) and is excluded. ["bad-txns-", "bad-tx-", "tx-overwinter-expired"] .iter() .any(|needle| message.contains(needle)) @@ -271,13 +270,11 @@ fn broadcast_already_known(message: &str) -> bool { .any(|needle| message.contains(needle)) } -/// 诊断:取单个区块并给出结构摘要,不做任何扫描、不写库。 -/// -/// 存在的理由:浏览器走 gRPC-web 代理、原生走真 gRPC,**两边可能根本不是同一个 -/// 服务端**,返回的 compact block 未必一致。排查「同一高度在 wasm 上出问题、 -/// 在原生上正常」时,必须先确认两边拿到的数据是不是同一份,否则一切对比都不成立。 +/// Diagnostic: fetch one block and return a structural summary. No scanning, no writes. /// -/// 摘要里带上各池的计数:某个池只在一边出现,就说明是服务端差异而非计算差异。 +/// wasm (gRPC-web proxy) and native (gRPC) may hit different servers returning +/// different compact blocks; compare summaries before comparing behavior. Per-pool +/// counts show whether a difference comes from the server rather than computation. pub async fn block_summary(client: &mut LightClient, height: u32) -> Result { use futures_util::TryStreamExt; use zcash_client_backend::proto::service::BlockRange; @@ -321,7 +318,7 @@ pub async fn block_summary(client: &mut LightClient, height: u32) -> Result Result String { let mut h: u64 = 0xcbf2_9ce4_8422_2325; for b in bytes { @@ -343,10 +340,10 @@ fn fnv1a(bytes: &[u8]) -> String { format!("{h:016x}") } -/// 取指定高度的 treestate。 +/// Fetch the treestate at `height`. /// -/// 导入账户时需要它:`AccountBirthday` 要知道 birthday 高度之前的承诺树状态, -/// 否则新账户无法为之后收到的 note 计算 witness。 +/// Needed for account import: `AccountBirthday` requires the commitment tree state +/// preceding the birthday height to compute witnesses for notes received later. pub async fn tree_state(client: &mut LightClient, height: u32) -> Result { let ts = with_timeout( async { @@ -399,7 +396,8 @@ mod tests { } } - // 拒收是白名单:没把握的回复一律是「结局未知」,交易留在途、继续重播。 + // Rejection is an allowlist: any uncertain reply is an unknown outcome and + // the tx stays pending for rebroadcast. #[test] fn only_consensus_invalid_or_expired_replies_count_as_a_rejection() { for message in [ diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs index b064df0c1..167aac548 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs @@ -1,5 +1,5 @@ -//! 临时性能打点:宿主打开开关后,每个重导出的耗时打到 console。 -//! 与宿主侧 `[PRIV-PERF]` 同前缀,一个过滤器看全链路。 +//! Temporary perf tracing: when enabled by the host, logs each export's duration +//! to the console. Shares the host's `[PRIV-PERF]` prefix so one filter covers both. use std::sync::atomic::{AtomicBool, Ordering}; @@ -13,7 +13,7 @@ pub fn is_enabled() -> bool { ENABLED.load(Ordering::Relaxed) } -/// 作用域结束(含跨 await 的 async 函数返回)时打一条耗时。 +/// Logs the elapsed time when dropped, including across awaits in async fns. pub struct Span { name: &'static str, started_ms: f64, diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs index 17752032e..31815a5d8 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs @@ -1,10 +1,8 @@ -//! 跨调用的运行时状态。 +//! Cross-call runtime state. //! -//! 按边界原则,wasm 侧**不持有会话状态** —— 唯一的例外是那个数据库连接和 -//! lightwalletd 客户端,因为每次调用都重开代价太高(重开要重跑一遍迁移检查)。 -//! -//! 除此之外没有任何缓存、没有定时器、没有后台任务。宿主 TS 每调一次, -//! 这里就完整做完一次并返回。 +//! Only the database connection and the lightwalletd client are kept, since +//! reopening per call would rerun migration checks. No caches, timers or +//! background tasks. use std::cell::{Cell, RefCell}; @@ -15,37 +13,34 @@ use crate::wallet::Db; thread_local! { static DB: RefCell> = const { RefCell::new(None) }; static CLIENT: RefCell> = const { RefCell::new(None) }; - // 历史查询走 v_transactions 视图,而 WalletDb 不对外暴露内部连接, - // 所以记住库名,需要时另开一条只读连接(同 VFS、同库名 = 同一份数据)。 + // WalletDb does not expose its connection, so history queries on + // v_transactions open a separate read connection by name (same VFS, same data). static DB_NAME: RefCell> = const { RefCell::new(None) }; - // ── 并发防线 ──────────────────────────────────────────────────────── - // - // 异步操作会把 DB 从这里**取走**,跨 await 持有,结束后放回。这中间宿主 - // 完全可以再发起别的调用 —— wasm 是单线程,但 await 让重入变得可能。 + // ── Reentrancy guard ──────────────────────────────────────────────── // - // 没有防线时的真实竞态: - // 1. A 在 syncStep,DB(A) 已被取走 - // 2. B 调 openWallet(B),DB_NAME 变成 B - // 3. A 结束,把 DB(A) 放回 —— 此刻 DB_NAME 说 B,实际却是 A - // 之后所有操作都在错误的库上进行,而且看不出来:历史串库、余额串库、 - // 甚至可能用 A 的 note 去发 B 的交易。 + // Async operations take DB out, hold it across awaits and put it back; the + // host can call in meanwhile. Unguarded race: + // 1. A is in syncStep with DB(A) taken + // 2. B calls openWallet(B); DB_NAME becomes B + // 3. A finishes and puts DB(A) back while DB_NAME says B + // Every later call then silently hits the wrong wallet, possibly spending + // A's notes in B's transactions. // - // 防线主力是 BUSY:它在期间拒绝一切会切换钱包的操作。GENERATION 是它后面 - // 的兜底,但**当前不可达** —— 采样发生在置位 BUSY 之后,而 set_db/close 都 - // 被 BUSY 挡住,世代号在守卫存活期间不可能变。留着是为了将来出现「跨 await - // 却不持 BUSY」的路径时仍有第二道,不要据此认为现在有两道独立防线。 + // BUSY is the real guard: it refuses wallet switches meanwhile. GENERATION is + // a fallback that is currently unreachable (it is sampled after BUSY is set + // and set_db/close are blocked by BUSY); it covers future paths that await + // without holding BUSY. It is not a second independent guard today. static BUSY: Cell = const { Cell::new(false) }; static GENERATION: Cell = const { Cell::new(0) }; - // 客户端有自己的世代号。DB 的那道防线盖不住它:`setLightwalletdUrl` 换端点 - // 时**不**碰 DB,GENERATION 不动,于是一次在途的 `getChainTip` 结束后会把 - // 旧端点原样盖回去,之后所有同步都在跟上一个网络的 lightwalletd 说话。 + // The client has its own generation: `setLightwalletdUrl` does not touch DB, + // so without it an in-flight `getChainTip` would restore the old endpoint. static CLIENT_GENERATION: Cell = const { Cell::new(0) }; } -/// 取走客户端前采样;放回前比对。不相等说明期间端点被换掉或关掉了,手上这个 -/// 已经作废 —— 丢弃它,而不是覆盖当前的。 +/// Sampled before taking the client and compared before putting it back; a +/// mismatch means the endpoint changed or closed, so the stale client is dropped. fn client_generation() -> u64 { CLIENT_GENERATION.with(Cell::get) } @@ -56,7 +51,7 @@ fn put_client_back(client: LightClient, sampled: u64) { } } -/// 正在进行一次异步操作时,任何切换钱包的调用都必须被拒绝。 +/// Refuses wallet-switching calls while an async operation is running. fn assert_idle(operation: &str) -> Result<()> { if BUSY.with(Cell::get) { return Err(RuntimeError::with( @@ -67,22 +62,20 @@ fn assert_idle(operation: &str) -> Result<()> { Ok(()) } -/// 持有期间标记 BUSY,析构时**一定**清除 —— 包括提前返回和 panic 展开。 -/// -/// ## 它覆盖哪个窗口,不覆盖哪个 +/// Sets BUSY while held and always clears it on drop, including early returns +/// and panic unwinds. /// -/// wasm-bindgen 的 `async fn` 返回的 Promise 是排进微任务队列的,函数体要等 -/// 当前同步块结束才开始跑。所以存在两个不同的窗口: +/// A wasm-bindgen `async fn` body starts only after the current synchronous +/// block, so there are two windows: /// -/// - **调用之后、函数体开始之前**:此时还没取走任何东西,`openWallet` 会成功, -/// 随后那次操作作用在新库上。这是调用方的时序错误,由宿主侧的租约 -/// (`withWalletLease`)负责序列化,runtime 这里拦不住 —— 拦得住的唯一办法是 -/// 把导出改成同步返回 Promise,代价是所有返回值退化成 `any`,不值得。 -/// - **函数体开始之后、await 期间**:DB 已被取走,此时切库/关库才是真正危险的, -/// 这个窗口由 BUSY 拦住。 +/// - **After the call, before the body runs**: nothing is taken yet, so +/// `openWallet` succeeds and the operation runs on the new wallet. The host's +/// `withWalletLease` serializes this; the runtime cannot without making exports +/// return Promises synchronously (typing every result as `any`). +/// - **During awaits in the body**: DB is taken; BUSY blocks switching or closing. /// -/// 不变量则由 generation 独立保证:无论哪个窗口,异步返回时都不会用一个 -/// 已经作废的钱包覆盖当前的。 +/// Generation ensures that in either window a stale wallet never overwrites the +/// current one. struct BusyGuard { generation: u64, } @@ -92,13 +85,13 @@ impl BusyGuard { assert_idle(operation)?; BUSY.with(|b| b.set(true)); Ok(Self { - // 采样点就是「取走 DB 的那一刻」—— 早于此的切库不算陈旧, - // 那只是这次操作作用在了新库上;晚于此的才是。 + // Sampled when DB is taken: a switch before this is not stale (the + // operation just runs on the new wallet); one after is. generation: GENERATION.with(Cell::get), }) } - /// 这次操作开始之后,钱包有没有被换掉/关掉。 + /// Whether the wallet was switched or closed since the operation started. fn stale(&self) -> bool { self.generation != GENERATION.with(Cell::get) } @@ -122,8 +115,8 @@ fn not_open() -> RuntimeError { RuntimeError::new(ErrorCode::WalletNotOpen) } -/// 库不在手上时说清楚是哪种:被一次异步操作借走(稍后重试即可)还是真没开 -/// (宿主要重开)。混成 NOT_OPEN 会让宿主在扫链途中把一个好好的钱包重开一遍。 +/// Distinguishes a DB borrowed by an async operation (retry later) from one +/// not open (host must reopen), so the host does not reopen a wallet mid-sync. fn db_unavailable(operation: &str) -> RuntimeError { if BUSY.with(Cell::get) { RuntimeError::with( @@ -139,8 +132,8 @@ fn no_client() -> RuntimeError { RuntimeError::new(ErrorCode::LightwalletdNotConfigured) } -/// 打开钱包。正在进行异步操作时会被拒绝 —— 中途换库会让那次操作把结果写到 -/// 错误的地方,而且没有任何迹象。 +/// Opens a wallet. Refused during an async operation, which would otherwise +/// silently write its results to the wrong wallet. pub fn set_db(db: Db, db_name: &str) -> Result<()> { assert_idle("openWallet")?; DB.with(|c| *c.borrow_mut() = Some(db)); @@ -149,7 +142,7 @@ pub fn set_db(db: Db, db_name: &str) -> Result<()> { Ok(()) } -/// 另开一条连接做只读查询(历史等)。 +/// Opens a separate connection for read-only queries such as history. pub fn with_read_conn(f: impl FnOnce(&rusqlite::Connection) -> Result) -> Result { let name = DB_NAME.with(|c| c.borrow().clone()).ok_or_else(not_open)?; let conn = crate::storage::open_connection(&name)?; @@ -161,10 +154,10 @@ pub fn set_client(client: LightClient) { bump_client_generation(); } -/// 借出数据库做一次同步操作。 +/// Lends the database for a synchronous operation. /// -/// 用「取出 → 使用 → 放回」而不是长期持有 `RefCell` 借用, -/// 这样即便 `f` 里再次进入本模块也不会 panic。 +/// Take, use, put back rather than holding a `RefCell` borrow, so reentry from +/// `f` does not panic. pub fn with_db(f: impl FnOnce(&mut Db) -> Result) -> Result { let mut db = DB .with(|c| c.borrow_mut().take()) @@ -174,17 +167,16 @@ pub fn with_db(f: impl FnOnce(&mut Db) -> Result) -> Result { out } -/// 借出数据库与网络客户端做一次异步操作(扫链、导入账户)。 +/// Lends the database and client for an async operation (sync, account import). /// -/// 同样是取出再放回 —— 异步过程中不持有任何 `RefCell` 借用, -/// 这是在 wasm 单线程上跨 await 安全共享状态的关键。 +/// No `RefCell` borrow is held across awaits. pub async fn with_db_and_client(f: F) -> Result where F: FnOnce(Db, LightClient) -> Fut, Fut: std::future::Future)>, { - // 先拿锁再取 DB,两者之间没有 await,所以 generation 的采样点与取走 DB - // 是同一时刻 —— 这正是「陈旧」判定成立的前提。 + // No await between acquiring the guard and taking DB, so the generation is + // sampled at the moment DB is taken; staleness relies on this. let guard = BusyGuard::acquire("walletOperation")?; let client_gen = client_generation(); let db = DB.with(|c| c.borrow_mut().take()).ok_or_else(not_open)?; @@ -198,8 +190,8 @@ where let (db, client, out) = f(db, client).await; - // 期间钱包被换掉/关掉时,**丢弃**手上这个而不是放回去。 - // 放回去等于让一个已经作废的钱包覆盖当前的,那正是串库的源头。 + // If the wallet was switched or closed meanwhile, drop this one rather than + // overwrite the current wallet with a stale one. if guard.stale() { drop(db); } else { @@ -209,11 +201,11 @@ where out } -/// 只借出网络客户端,**不要求钱包库已打开**。 +/// Lends only the client; no wallet needs to be open. /// -/// 建新账户时链尖是先决条件:宿主要用它定 birthday,而那一刻库还没建。 -/// 如果取链尖也要求先开库,这条路必然失败、失败又被吞成 null, -/// 结果 birthday 退回 Sapling 激活高度,新助记词也要从头扫。 +/// New accounts need the chain tip for their birthday before the database +/// exists. Requiring an open wallet here would fall back to the Sapling +/// activation birthday and force a full scan. pub async fn with_client(f: F) -> Result where F: FnOnce(LightClient) -> Fut, @@ -228,15 +220,15 @@ where result } -/// 当前打开的库名。删除库前要用它判断是不是正在用的那个。 +/// Name of the open database, checked before deleting a database. pub fn open_db_name() -> Option { DB_NAME.with(|c| c.borrow().clone()) } -/// 关闭钱包,释放数据库与客户端。用于账户删除或切换网络。 +/// Closes the wallet, releasing the database and client (account removal, +/// network switch). /// -/// 异步操作进行中会被拒绝:那次操作手上还握着 DB,此时清空只会让它结束后 -/// 把一个本该消失的钱包放回来。 +/// Refused during an async operation, which holds DB and would put it back. pub fn close() -> Result<()> { assert_idle("closeWallet")?; DB.with(|c| *c.borrow_mut() = None); diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs index 49815c3d0..3dafa95e9 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs @@ -1,27 +1,29 @@ -//! 发送:PCZT 的构造与广播。 +//! Sending: PCZT construction and broadcast. //! -//! 拆成四段是刻意的 —— **签名那一段不在本 crate**: +//! Four stages; signing is not in this crate: //! //! ```text -//! runtime.pcztCreate() 构造(要钱包状态:选币、witness、anchor) -//! runtime.pcztProve() 证明,纯计算,不碰私钥 -//! keys.pcztSign() 签名(要花费密钥,在 onekey-zcash-keys 里) -//! runtime.pcztSubmit() 提取、先落库、再广播(重试只重播落库的那份字节) +//! runtime.pcztCreate() build (needs wallet state: note selection, witness, anchor) +//! runtime.pcztProve() prove; pure computation, no private keys +//! keys.pcztSign() sign (needs the spending key; in onekey-zcash-keys) +//! runtime.pcztSubmit() extract, store, broadcast (retries resend the stored bytes) //! ``` //! -//! 证明必须排在签名之前:上游 Signer 角色的文档写明,它需要足以「验证证明覆盖的是 -//! 正确数据」的信息,也就是签名时证明必须已经在 PCZT 里。 +//! Proving precedes signing: the upstream Signer role needs enough information +//! to verify the proofs cover the right data, so proofs must already be in the PCZT. //! -//! 这条缝是密钥纪律的体现:构造和广播需要钱包数据库,签名需要种子, -//! 两者永远不在同一个 crate 里同时出现。 +//! Key separation: build and broadcast need the wallet database, signing needs +//! the seed; the two never live in the same crate. //! -//! ## 为什么这些留在 Rust +//! ## Why this stays in Rust //! -//! 选币、ZIP-317 费用、anchor 选择、witness —— 这些是**共识相关**的。 -//! 选错 anchor 交易会被拒,算错费可能丢钱。所以机制留在上游实现里。 +//! Note selection, ZIP-317 fees, anchor choice and witnesses are consensus-relevant: +//! a wrong anchor gets the transaction rejected, a wrong fee can lose funds. The +//! mechanism stays in the upstream implementation. //! -//! 但**策略旋钮全部由宿主传入**(找零池、dust 策略、OVK 策略、确认数、 -//! bundle padding),本 crate 不替宿主做产品决策,也不藏默认值。 +//! Policy knobs (change pool, dust policy, OVK policy, confirmations, bundle +//! padding) all come from the host; this crate makes no product decisions and +//! hides no defaults. use zcash_client_backend::data_api::locking::LockOwner; use zcash_client_backend::data_api::wallet::{ @@ -40,24 +42,21 @@ use crate::error::{ErrorCode, Result, RuntimeError}; use crate::{tx_state, wallet::Db}; use serde_json::json; -/// `stage` 是稳定标识,宿主据此知道卡在构造的哪一段。 +/// `stage` is a stable identifier telling the host which build step failed. fn build_err(stage: &str, e: impl std::fmt::Display) -> RuntimeError { RuntimeError::with(ErrorCode::TransactionBuildError, json!({ "stage": stage })).detail(e) } -/// 把提案阶段的失败翻译成宿主能分支处理的错误码。 +/// Maps proposal failures to error codes the host can branch on. /// -/// 「余额不足」是发送最常见的失败,宿主要据此提示还差多少、要不要减额重试; -/// 「需要先同步」则是让用户等扫描追平后再试。这两种都**不该**被折叠成泛化的 -/// `TRANSACTION_BUILD_ERROR` —— 那样宿主只能拿到一句没法判定的字符串。 +/// `INSUFFICIENT_FUNDS` (with the shortfall) and `NOT_SYNCED` must not collapse +/// into a generic `TRANSACTION_BUILD_ERROR`. /// -/// **注意上游有两个不同的「余额不足」出处**,两个都要接住: +/// Upstream reports insufficient funds from two places; both are handled: /// -/// - `Error::InsufficientFunds` —— 选币阶段就凑不够(转账走这条) -/// - `Error::Change(ChangeError::InsufficientFunds)` —— 选币过了,但算上找零和 -/// 手续费之后不够(屏蔽零余额走这条) -/// -/// 只接第一个的话,屏蔽路径会退化成泛化错误 —— 实测踩过。 +/// - `Error::InsufficientFunds`: selection cannot cover the amount (transfers) +/// - `Error::Change(ChangeError::InsufficientFunds)`: selection succeeded but +/// change plus fee does not fit (shielding) fn propose_err( stage: &str, e: zcash_client_backend::data_api::error::Error, @@ -80,7 +79,7 @@ where json!({ "availableZat": have, "requiredZat": need, - // 直接给差额,省得宿主自己减(还容易减错方向) + // Precomputed so the host does not subtract in the wrong direction. "shortfallZat": need.saturating_sub(have), "stage": stage, }), @@ -103,15 +102,13 @@ where } } -/// 解析宿主传来的找零池名。构造与报价共用,避免两处各写一份而写歪。 +/// Parses the host's change pool name. Shared by build and quote so they cannot diverge. pub fn parse_change_pool(name: &str) -> Result { match name { // NU6.3 makes Orchard spend-only; new change must enter Ironwood. "ironwood" => Ok(ShieldedPool::Ironwood), - // Sapling 不是合法的找零去处,理由和 `parse_spend_source` 拒它一样, - // 而且更硬:本方案裁掉了 Sapling 的 Groth16 证明参数,建不出 Sapling - // 输出。就算建得出,那笔找零也进了一个本钱包只读不可花的池子 —— - // 用户的找零会当场变成取不回来的钱。 + // Sapling is rejected: this runtime ships no Sapling Groth16 parameters, + // and change there would land in a pool this wallet cannot spend. other => Err(RuntimeError::with( ErrorCode::TransactionBuildError, json!({ "stage": "fallbackChangePool", "value": other }), @@ -119,8 +116,8 @@ pub fn parse_change_pool(name: &str) -> Result { } } -/// 解析宿主传来的「只从这个池子花」。构造与报价都要求给出(见 -/// `build_proposal`),`None` 在那里会被拒绝。 +/// Parses the host's spend-source pool. Build and quote both require it; +/// `None` is rejected in `build_proposal`. /// /// Orchard remains a valid spend source, but cannot receive new change. /// Sapling spending is unsupported because this runtime does not ship its prover. @@ -136,38 +133,34 @@ pub fn parse_spend_source(name: Option<&str>) -> Result> { } } -/// 宿主可调的发送策略。全部显式传入,本 crate 不藏默认值。 +/// Host-controlled send policy. Every field is explicit; no hidden defaults. #[derive(Debug, Clone, Copy)] pub struct SendPolicy { - /// 可信 note 的确认数门槛(>= 1)。 + /// Confirmations required for trusted notes (>= 1). pub trusted: u32, - /// 外来 note 的确认数门槛(>= trusted)。 + /// Confirmations required for untrusted notes (>= trusted). pub untrusted: u32, - /// 交易全透明时,找零回落到哪个屏蔽池。 + /// Shielded pool for change when the transaction is fully transparent. pub fallback_change_pool: ShieldedPool, - /// 是否给 Orchard bundle 填充到固定 action 数(隐藏真实 action 数量, - /// 代价是交易更大、费用更高)。 + /// Pad the Orchard bundle to a fixed action count (hides the real count at + /// the cost of a larger transaction and higher fee). pub pad_orchard_bundle: bool, - /// 零确认的自家屏蔽产出允不允许立刻再花(ZIP-315 建议允许)。 + /// Allow spending zero-conf outputs of our own shielding (ZIP-315 recommends it). /// - /// 曾经硬编码 `false`,而余额读取那头却是参数 —— 宿主想跟进 ZIP-315 - /// 就会造出「余额显示可花、选币拒花」的错配。读和花必须同源。 + /// Must match the balance query's setting, or the balance shows funds that + /// selection refuses to spend. pub allow_zero_conf_shielding: bool, - /// 只从这一个屏蔽池选 note。必填:`None` 会在构造时被拒绝。 - /// - /// 存在的理由有两个,都不是可选的: + /// Select notes only from this shielded pool. Required: `None` is rejected at build. /// - /// 1. **Sapling 必须排除。** 上游 `SpendPolicy::default()` 允许 sapling, - /// 而选币是「最老的合格 note 优先」—— 一个恢复了 2022 年前历史的账户, - /// 每一笔转账都会先挑中 sapling note,然后在证明阶段撞上 - /// `PROVE_SAPLING = false`。那笔钱花不了是事实,但因此**整个账户发不出 - /// 任何交易**不是。默认集合把它挡在选币之外,用户就能正常花其他池子。 + /// 1. Excludes Sapling. Upstream `SpendPolicy::default()` allows it and + /// selection prefers the oldest eligible note, so an account with pre-2022 + /// history would pick Sapling notes and fail at proving (`PROVE_SAPLING = false`), + /// blocking every send. + /// 2. Enables per-pool withdrawal, e.g. moving old Orchard funds to a + /// transparent address without spending Ironwood funds the user wants kept private. /// - /// 2. **按池子提取需要它。** 「把旧 Orchard 余额转到透明地址」这个动作, - /// 没有它就只是一笔普通转账,选币可能去花 Ironwood —— 把用户还想留在 - /// 私密池里的钱搬到了链上公开的地址。上游文档给的例子正是这个用法。 - /// - /// 指定一个池子时,凑不够就是 `InsufficientFunds`,上游保证不会越池。 + /// If the pool cannot cover the amount the result is `InsufficientFunds`; + /// upstream never crosses pools. pub spend_source: Option, } @@ -185,13 +178,11 @@ impl SendPolicy { } } -/// 从宿主传来的原始参数造一份发送策略。 +/// Builds a send policy from the host's raw arguments. /// -/// **报价和真正构造必须走这一个入口。** 两边各拼一次 `SendPolicy`,迟早会出现 -/// 某个字段只在一边接上:`pad_orchard_bundle` 就是这样 —— 报价那边曾经固定写 -/// `false`,而它会改变 Orchard bundle 的大小、进而改变 ZIP-317 手续费。当时 -/// 宿主的常量也是 `false`,所以对得上;等哪天真去打开这个产品开关,报出来的 -/// 费用就会比实付的低,而且没有任何东西会报错。 +/// Quote and build must both use this entry point. Fields such as +/// `pad_orchard_bundle` change the bundle size and therefore the ZIP-317 fee; +/// wiring them separately lets the quoted fee silently drift from the paid fee. #[allow(clippy::too_many_arguments)] pub fn parse_send_policy( trusted: u32, @@ -211,13 +202,14 @@ pub fn parse_send_policy( }) } -/// 一次转账提案。`create_pczt` 与 `quote` 共用 —— 两者的选币、费率、找零策略 -/// 必须完全一致,否则报价和实际构造会对不上,用户看到的费用就是假的。 +/// A transfer proposal, shared by `create_pczt` and `quote` so selection, fee +/// and change strategy are identical and the quoted fee is the real one. type TransferProposal = zcash_client_backend::proposal::Proposal; -/// 收款只能落在 Sapling:Sapling 证明参数没随包发布(体积),这种交易必然在 -/// 证明阶段失败 —— 那时用户已经点了确认。在构造前就拒绝。 +/// Recipient can only receive into Sapling. Sapling proving parameters are not +/// shipped, so such a transaction would fail at proving after the user confirmed; +/// refuse before building. fn recipient_needs_sapling_output( params: &zcash_protocol::consensus::Network, recipient: &zcash_address::ZcashAddress, @@ -230,7 +222,7 @@ fn recipient_needs_sapling_output( } } -/// ZIP-320 TEX 地址只收透明输入;私密付款花的是屏蔽池,付不了它。 +/// ZIP-320 TEX addresses accept only transparent inputs; a shielded spend cannot pay them. fn recipient_is_tex( params: &zcash_protocol::consensus::Network, recipient: &zcash_address::ZcashAddress, @@ -274,7 +266,8 @@ fn build_proposal( let params = *db.params(); let account_id = account::parse_account_id(db, account_uuid)?; - // 零值:上游只对透明收款方拒绝,屏蔽收款方会建出一笔只付手续费的交易。 + // Zero amount: upstream rejects it only for transparent recipients; a shielded + // recipient would yield a fee-only transaction. let amount = Zatoshis::from_u64(amount_zat) .ok() .filter(|a| !a.is_zero()) @@ -303,7 +296,7 @@ fn build_proposal( )); } - // Payment::new 会自己校验「透明地址不能带 memo」这类约束。 + // Payment::new enforces constraints such as no memo for transparent recipients. let payment = zip321::Payment::new(recipient, Some(amount), memo.cloned(), None, None, vec![]) .map_err(|e| { RuntimeError::with(ErrorCode::InvalidMemo, json!({ "reason": "payment" })) @@ -319,12 +312,12 @@ fn build_proposal( policy.allow_zero_conf_shielding, )?; - // 花费来源策略:只花所选的屏蔽池,一个透明 UTXO 都不花(与上游默认一致)。 + // Spend only the selected shielded pool, never transparent UTXOs (as upstream's default). let spend_policy = { use zcash_client_backend::data_api::wallet::input_selection::SpendPolicy; - // 不用 SpendPolicy::default():它允许 sapling。见 SendPolicy::spend_source。 - // 屏蔽池之间永不并池(docs/08),而"当前池"只在宿主一处定义 - // (ZCASH_CURRENT_SHIELDED_POOL):这里不藏缺省,缺参直接拒绝。 + // Not SpendPolicy::default(): it allows Sapling. See SendPolicy::spend_source. + // Shielded pools are never combined (docs/08), and the current pool is defined + // only by the host (ZCASH_CURRENT_SHIELDED_POOL): no default here, missing is rejected. let pool = policy.spend_source.ok_or_else(|| { RuntimeError::with( ErrorCode::TransactionBuildError, @@ -354,7 +347,7 @@ fn build_proposal( DustOutputPolicy::default(), ); - // 显式标注 commitment-tree 错误类型:这一处泛型推不出来。 + // The commitment-tree error type cannot be inferred here. let proposal = propose_transfer::( db, @@ -372,10 +365,9 @@ fn build_proposal( proposal.map_err(|e| propose_err("proposeTransfer", e)) } -/// 只出费用,不构造 PCZT、不锁定 note。 +/// Returns the fee only; builds no PCZT and locks no notes. /// -/// 用途是发送前给用户看手续费。**必须与 `create_pczt` 走同一条提案路径**, -/// 否则报价与实付不符 —— 那是最难被发现、也最不该发生的一类 bug。 +/// Must use the same proposal path as `create_pczt` so the quote matches the fee paid. pub fn quote( db: &mut Db, account_uuid: &str, @@ -398,19 +390,17 @@ pub fn quote( .to_string()) } -// ── note 锁定(宿主契约里的 reservation) ──────────────────────────────── -// -// 屏蔽池里的钱是一个个 note,性质像 UTXO:整个花掉,花时公布 nullifier, -// 同一个 note 被两笔交易花,第二笔必被节点拒绝。 +// ── Note locking (the host contract's "reservation") ──────────────────── // -// 而发送流水线中间有一段「已选币、未花掉」的窗口: -// 选币 → 审核页 → 输密码 → 签名 → 广播 -// 用户在审核页停着又发起第二笔(或点了 shield),选币器会把同一批 note 再选一遍。 +// Notes behave like UTXOs: spent whole, revealing a nullifier; a second +// transaction spending the same note is rejected by the node. // -// 锁定就是在选币时把这批 note 标记为已被某个操作占用,别的选币跳过; -// 用户取消就 release 还回去。上游还带按区块高度的过期时间,兜住「app 中途崩了」。 +// Between selection and broadcast (select -> review -> password -> sign -> broadcast) +// a second send or shield would reselect the same notes. Locking marks them as +// held by one operation so other selections skip them; cancel releases them. +// Upstream locks also expire by block height, covering an app crash. // -// 提案本身要留在内存里:`unlock_proposal_inputs` 需要提案才知道该解锁哪些 note。 +// The proposal stays in memory: `unlock_proposal_inputs` needs it to know which notes to unlock. thread_local! { static RESERVATIONS: std::cell::RefCell< std::collections::HashMap)>, @@ -439,10 +429,10 @@ fn parse_owner(reservation_id: &str) -> Result { Ok(LockOwner::new(out)) } -/// 释放一次 reservation 占用的 note。 +/// Releases the notes held by a reservation. /// -/// 幂等:id 不存在(已发送、已释放、或本来就没锁过)返回 `false` 而不报错 —— -/// 取消路径上重复调用是常态,不该因此弹错误给用户。 +/// Idempotent: an unknown id (sent, already released, or never locked) returns +/// `false`, not an error. pub fn release_reservation(db: &mut Db, reservation_id: &str) -> Result { let owner = parse_owner(reservation_id)?; @@ -553,15 +543,15 @@ fn release_persisted_reservation( }) } -/// 交易已落库后丢弃 reservation 记录。 +/// Drops the reservation record once the transaction is stored. /// -/// 此时锁已由花费本身接管(note 真的被花掉了),不需要也不应该再解锁 —— -/// 解锁会把已经花出去的 note 重新放回可选池。 +/// The stored spend now holds the notes; unlocking would make spent notes +/// selectable again. pub fn forget_reservation(reservation_id: &str) { RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id)); } -/// 账户被删掉时,它还在内存里的提案一并丢弃:那些 note 已经随账户删了。 +/// Drops in-memory proposals of a deleted account; its notes are gone with it. pub fn forget_account_reservations(account_uuid: &str) { RESERVATIONS.with(|r| { r.borrow_mut() @@ -569,8 +559,9 @@ pub fn forget_account_reservations(account_uuid: &str) { }); } -/// 一个 reservation 只对应一笔交易。已经落库过的 id 再拿来构造,会在同一个 -/// owner 下再锁一批 note,而提交只会重播旧的那笔:新锁既用不上也解不开。 +/// A reservation maps to one transaction. Rebuilding under a stored id would lock +/// a second set under the same owner while submit only replays the old one, so +/// the new locks could be neither used nor released. fn refuse_submitted_reservation(db: &mut Db, reservation_id: &str) -> Result<()> { let submitted = db.transactionally_with_extension(|_wallet, ext| { tx_state::existing_txid_for_reservation(ext, reservation_id, None) @@ -584,18 +575,19 @@ fn refuse_submitted_reservation(db: &mut Db, reservation_id: &str) -> Result<()> } } -/// 构造一笔转账的 PCZT(未签名),并**锁住选中的 note**。 +/// Builds an unsigned transfer PCZT and locks the selected notes. /// -/// 返回 `{ pcztHex, reservationId }`:`reservationId` 是这批 note 的占用凭证, -/// 调用方必须一直带着它,直到交易提交(`pcztSubmit`)或用户取消(`releaseReservation`)。 -/// 不释放也不会永久卡死 —— 锁有按区块高度的过期时间,但那是兜底,不是正常路径。 +/// Returns `{ pcztHex, reservationId }`. The caller must keep `reservationId` +/// until submit (`pcztSubmit`) or cancel (`releaseReservation`). Locks also +/// expire by block height, but only as a fallback. /// -/// `lock_for_blocks` 由宿主决定,但必须长过交易的过期高度。提交时交易先落库 -/// 再广播,落库之后由交易本身占住这批 note;锁管的是从构造到落库这一段。 +/// `lock_for_blocks` is host-chosen and must outlast the transaction's expiry +/// height. The lock covers build until storage; after that the stored +/// transaction holds the notes. /// -/// `reservation_id` 可由调用方传入(64 位 hex)。上游的设计意图就是**调用方持有 -/// 这个 token**:先生成、先持久化,再来构造。这样即使中途崩溃,恢复后仍然知道 -/// 该释放哪一批 note,或者重新锁住自己那批。不传则由这里随机生成。 +/// `reservation_id` may be supplied (64 hex chars) so the caller can generate +/// and persist it before building, and after a crash still release or relock +/// its notes. Otherwise one is generated randomly. // The public binding keeps proposal policy explicit at the call boundary. #[allow(clippy::too_many_arguments)] pub fn create_pczt( @@ -632,10 +624,9 @@ pub fn create_pczt( .map(|step| u64::from(step.balance().fee_required())) .sum(); - // 同理:InputsErrT / ChangeErrT 只出现在 Err 分支,推不出来。 - // 提案已经锁住了 note。从这里往下任何失败都必须**先解锁再返回** —— - // 否则调用方拿不到 reservationId(我们还没返回它),就永远没法释放, - // 那批 note 会一直冻到锁自然过期。 + // InputsErrT / ChangeErrT appear only in the Err branch and cannot be inferred. + // The notes are already locked: any failure below must unlock before returning, + // since the caller has no reservationId yet and could not release them. let built = (|| -> Result> { let pczt = create_pczt_from_proposal::< Db, @@ -664,14 +655,13 @@ pub fn create_pczt( let bytes = match built { Ok(b) => b, Err(e) => { - // 尽力解锁。解锁本身再失败也只能吞掉 —— 真正的错误是上面那个, - // 不该被一个清理动作的错误盖掉;锁还有过期时间兜底。 + // Best effort: keep the original error; lock expiry covers an unlock failure. let _ = unlock_proposal_inputs(db, &proposal, owner); return Err(e); } }; - // 提案要留着:解锁时需要它才知道该放开哪些 note。 + // Keep the proposal: unlocking needs it to know which notes to release. RESERVATIONS.with(|r| { r.borrow_mut().insert( reservation_id.clone(), @@ -681,10 +671,11 @@ pub fn create_pczt( Ok((bytes, reservation_id, fee_zat)) } -/// 用哪个电路版本证明,由**共识分支**决定,不是产品选项。 +/// The proving circuit version is set by the consensus branch, not a product option. /// -/// `height` 是交易所属分支的起始高度:过了 NU6.3 激活高度就用 PostNu6_3, -/// 否则用 FixedPostNu6_2。`InsecurePreNu6_2` 永远不用于证明(上游明确标注)。 +/// `height` is the start of the transaction's branch: PostNu6_3 at or after NU6.3 +/// activation, otherwise FixedPostNu6_2. `InsecurePreNu6_2` is never used for +/// proving (marked so upstream). fn circuit_version_for( params: &zcash_protocol::consensus::Network, height: zcash_protocol::consensus::BlockHeight, @@ -713,20 +704,20 @@ fn circuit_version_for_branch( circuit_version_for(params, branch_start.unwrap_or(chain_tip)) } -/// 给 PCZT 生成 Orchard / Ironwood 零知识证明。 -/// 合并两份同一笔交易的 PCZT(本地完整副本 + 外部签名器返回的脱敏副本)。 -/// 合并硬件回传的签名副本。**只许补签名,不许改交易。** +/// Merges the signed copy returned by an external signer (hardware) into the +/// local original PCZT. It may add signatures only, never change the transaction. /// -/// 别指望后面那一步兜底:`TransactionExtractor` 是拿**合并后**的交易重算 sighash -/// 再验签名,它只回答「这笔交易自洽吗」,不知道用户批准过什么。 +/// `TransactionExtractor` cannot catch this later: it recomputes the sighash of +/// the merged transaction, so it only checks self-consistency, not what the user approved. /// -/// 裸 `Combiner` 目前挡得住换交易,但那是两条上游性质的副作用,不是本 crate 的 -/// 声明:一是我们构造的 PCZT `tx_modifiable == 0`,不可增删输入/输出/action; -/// 二是效果字段全部已填,冲突会被逐字段查出来。两条都属于上游,升级就可能变。 +/// The bare `Combiner` currently blocks substitution only as a side effect of +/// upstream behaviour (our PCZTs have `tx_modifiable == 0`, and all effect fields +/// are set so conflicts are detected), which an upgrade could change. /// -/// 所以把不变量写在这里:合并前后 sighash 必须逐字节相同,且 `scriptSig` 必须仍为 -/// 空 —— 它不进 sighash,又恰好是原件里为 `None`、会被 `merge_optional` 直接采纳的 -/// 字段,是这层唯一真正漏着的口子。失败发生在昂贵的证明之前,错误带 `field`。 +/// Invariant enforced here: sighashes must be byte-identical before and after, +/// and `scriptSig` must stay empty (it is outside the sighash, `None` in the +/// original, and adopted as-is by `merge_optional`). Fails before proving; +/// errors carry `field`. pub fn combine_pczt(original: &[u8], signed: &[u8]) -> Result> { use pczt::roles::signer::Signer; use pczt::roles::verifier::{TransparentError, Verifier}; @@ -798,10 +789,10 @@ pub fn combine_pczt(original: &[u8], signed: &[u8]) -> Result> { return Err(mismatch("transparentSighash")); } } - // sighash 不覆盖 scriptSig,而它正是合并里唯一能被对方无中生有填上的字段 - // (原件恒为 None,merge_optional 会直接采纳)。我们自己从不填:提取时 - // SpendFinalizer 才从 partial_signatures 拼出来。 - // 在副本上查 —— Verifier 会把 bundle 解析再序列化回去,不能动待序列化的那份。 + // scriptSig is outside the sighash and is the one field the other side can + // inject (always None in our original; merge_optional adopts it). We never set + // it; SpendFinalizer builds it from partial_signatures at extraction. + // Check a clone: Verifier reparses and reserializes the bundle. if transparent_inputs > 0 { Verifier::new(combined.clone()) .with_transparent(|bundle| { @@ -925,7 +916,7 @@ pub fn prove_pczt_at_height( }) } -/// 把签好名的 PCZT 落进钱包库:从这一刻起它花掉的 note 由这笔交易持有。 +/// Stores the signed PCZT in the wallet; from now on this transaction holds its spent notes. fn store_signed_pczt( db: &mut Db, account_uuid: &str, @@ -948,7 +939,7 @@ fn store_signed_pczt( }) } -/// 一次提交的结局。 +/// Outcome of a submit. pub enum SubmitOutcome { Accepted { txid: String, @@ -958,7 +949,7 @@ pub enum SubmitOutcome { txid: String, error: RuntimeError, }, - /// 不知道节点收没收到:已落库,交易持有 note,同步时会重播。 + /// Unknown whether the node received it: stored, holds its notes, rebroadcast on sync. Unknown { txid: String, error: RuntimeError, @@ -999,7 +990,7 @@ pub async fn submit_signed_pczt( pczt_bytes: &[u8], reservation_id: &str, ) -> Result { - // 上次提交已经落库(宿主没拿到回包就重试):重播那一笔,不再提取第二次。 + // Already stored by an earlier submit (host retried): rebroadcast it, never extract again. let stored = db.transactionally_with_extension(|_wallet, ext| { tx_state::existing_txid_for_reservation(ext, reservation_id, Some(account_uuid)) })?; @@ -1066,7 +1057,7 @@ pub async fn submit_signed_pczt( Ok(record_submit_outcome(db, stored_txid, result)) } -/// 从钱包库取出已落库交易的原始字节,供重播使用。 +/// Reads a stored transaction's raw bytes from the wallet for rebroadcast. pub fn raw_transaction(db: &Db, txid: &str) -> Result> { use zcash_primitives::transaction::TxId; @@ -1076,7 +1067,7 @@ pub fn raw_transaction(db: &Db, txid: &str) -> Result> { .ok_or_else(|| { RuntimeError::with(ErrorCode::TransactionBuildError, json!({ "stage": "txid" })) })?; - // txid 字符串是显示序(大端),内部表示是小端。 + // The txid string is in display order (big-endian); the internal form is little-endian. let mut internal = [0u8; 32]; for (i, b) in bytes.iter().rev().enumerate() { internal[i] = *b; @@ -1295,8 +1286,8 @@ mod reservation_recovery_tests { mod policy_tests { use super::*; - /// Sapling 在这两处都不是合法取值,理由不同但结论一样:证明建不出来, - /// 而且找零会落进一个只读不可花的池子。 + /// Sapling is invalid in both places: it cannot be proven, and change would + /// land in a pool this wallet cannot spend. #[test] fn sapling_is_not_a_spendable_source_nor_a_change_destination() { assert!(parse_change_pool("ironwood").is_ok()); @@ -1305,7 +1296,8 @@ mod policy_tests { assert!(parse_spend_source(Some("sapling")).is_err()); } - /// 升级前后几块:本地链尖还在旧分支,交易已按新分支构造(或反过来)。 + /// Around an upgrade the local tip can be on the old branch while the + /// transaction targets the new one, or vice versa. #[test] fn the_proving_circuit_follows_the_transactions_branch_not_the_tip() { use orchard::circuit::OrchardCircuitVersion; diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs index bc52ff08a..cffee92c7 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs @@ -1,14 +1,12 @@ -//! 存储用量统计。**只读,固定 SQL,不改任何数据。** +//! Storage usage stats. Read-only, fixed SQL. //! -//! 存在的理由:`diagSelfCheck` 只能报出表 / 视图 / 索引的**数量**,答不了 -//! 「哪一组数据占了多少字节」。没有这个数,任何裁剪都是盲改 —— 先量再改。 +//! Reports bytes per data group, which `diagSelfCheck` (object counts only) cannot. //! -//! 刻意**不**提供「执行任意 SQL」的接口:那等于把数据库交给宿主, -//! 一条写错的语句就能删掉仍待证明的 anchor。这里的每条查询都是写死的。 +//! There is deliberately no arbitrary-SQL entry point: one bad statement could +//! delete anchors still needed for proving. //! -//! 所有 SQL 里的表名与列名都来自 `wallet.rs::tests::dump_schema` 的实测输出, -//! 不是照文档抄的 —— 表名写错时 SQLite 会报错而不是安静返回 0,但列名写错 -//! 在某些聚合下会返回 NULL,所以两者都必须对着真实 schema 核过。 +//! Table and column names come from `wallet.rs::tests::dump_schema`. A wrong +//! column name can yield NULL under some aggregates instead of an error. use crate::error::{ErrorCode, Result, RuntimeError}; use rusqlite::Connection; @@ -24,7 +22,7 @@ fn count(conn: &Connection, sql: &str, op: &str) -> Result { .map_err(|e| db_err(op, e)) } -/// `SUM` 在空表上返回 NULL,直接 `get::` 会失败 —— 用 Option 接住并归零。 +/// `SUM` over an empty table is NULL; map it to 0. fn sum(conn: &Connection, sql: &str, op: &str) -> Result { conn.query_row(sql, [], |r| r.get::<_, Option>(0)) .map(|v| v.unwrap_or(0)) @@ -37,11 +35,11 @@ fn opt_i64(conn: &Connection, sql: &str, op: &str) -> Result { .map_err(|e| db_err(op, e)) } -/// 一棵树的用量。三个池的表名只差前缀,所以共用这一段。 +/// Usage for one pool's tree; pool tables differ only by prefix. fn tree_stats(conn: &Connection, prefix: &str) -> Result { Ok(json!({ "shards": count(conn, &format!("SELECT COUNT(*) FROM {prefix}_tree_shards"), "shards")?, - // shard_data 是聚合后的树分片,通常是数据库里最大的 BLOB 列。 + // shard_data is usually the largest BLOB column in the database. "shardBytes": sum( conn, &format!("SELECT SUM(LENGTH(shard_data)) FROM {prefix}_tree_shards"), @@ -52,9 +50,8 @@ fn tree_stats(conn: &Connection, prefix: &str) -> Result { &format!("SELECT COUNT(*) FROM {prefix}_tree_checkpoints"), "checkpoints", )?, - // ZIP-318 的 durable anchor。它们**不受**普通 100 深度上限约束, - // 而 runtime 目前没有任何回收路径,所以这个数只会单调增长 —— - // 这正是需要先量出来的东西。 + // ZIP-318 durable anchors. Not bound by the 100-checkpoint limit and + // never pruned by the runtime, so this only grows. "retained": count( conn, &format!("SELECT COUNT(*) FROM {prefix}_tree_retained_checkpoints"), @@ -68,9 +65,9 @@ fn tree_stats(conn: &Connection, prefix: &str) -> Result { })) } -/// 分组统计当前钱包库的用量,JSON 字符串。 +/// Storage usage of the wallet database by group, as a JSON string. pub fn storage_stats(conn: &Connection) -> Result { - // 总量走 PRAGMA:`dbstat` 虚拟表未必编进当前 SQLite,PRAGMA 一定在。 + // Totals use PRAGMA; the `dbstat` virtual table may not be compiled in. let page_size = count(conn, "PRAGMA page_size", "pageSize")?; let page_count = count(conn, "PRAGMA page_count", "pageCount")?; let free_pages = count(conn, "PRAGMA freelist_count", "freelistCount")?; @@ -80,16 +77,15 @@ pub fn storage_stats(conn: &Connection) -> Result { "pageSize": page_size, "pageCount": page_count, "freePages": free_pages, - // 页数 × 页大小。这是**逻辑**大小,不等于 IndexedDB 的物理占用 —— - // 那边有写放大、旧版本页和异步刷盘,两个数不该互相外推。 + // Logical size only; IndexedDB physical usage differs (write + // amplification, stale pages, async flushes). "logicalBytes": page_size * page_count, }, "scan": { "minHeight": opt_i64(conn, "SELECT MIN(height) FROM blocks", "minHeight")?, "maxHeight": opt_i64(conn, "SELECT MAX(height) FROM blocks", "maxHeight")?, - // 严格随「已扫块数」线性增长,是最明确的线性项。 - // 注意:它不是 compact block 本身,每行只有 height/hash/time 和三池的 - // 树大小与 action 计数。 + // Grows linearly with scanned blocks. Rows hold height/hash/time and + // per-pool tree sizes and action counts, not compact blocks. "blockRows": count(conn, "SELECT COUNT(*) FROM blocks", "blockRows")?, "rangeRows": count(conn, "SELECT COUNT(*) FROM scan_queue", "rangeRows")?, }, @@ -102,7 +98,7 @@ pub fn storage_stats(conn: &Connection) -> Result { "accounts": count(conn, "SELECT COUNT(*) FROM accounts", "accounts")?, "addresses": count(conn, "SELECT COUNT(*) FROM addresses", "addresses")?, "transactions": count(conn, "SELECT COUNT(*) FROM transactions", "transactions")?, - // 完整交易字节,只在本钱包构造或做过 enhancement 后才有。 + // Full transaction bytes, present only for own or enhanced transactions. "rawTxBytes": sum(conn, "SELECT SUM(LENGTH(raw)) FROM transactions", "rawTxBytes")?, "notes": count( conn, @@ -125,8 +121,8 @@ pub fn storage_stats(conn: &Connection) -> Result { "transparentOutputs", )?, }, - // 有界或有删除路径的几组。官方把 nullifier_map 裁到最近 100 块, - // 所以这里的数**不该**随链头无限增长 —— 长了说明裁剪没生效。 + // Bounded or pruned groups. Upstream prunes nullifier_map to the last + // 100 blocks, so steady growth here means pruning is not working. "transient": { "nullifiers": count(conn, "SELECT COUNT(*) FROM nullifier_map", "nullifiers")?, "locators": count(conn, "SELECT COUNT(*) FROM tx_locator_map", "locators")?, @@ -152,7 +148,7 @@ pub fn storage_stats(conn: &Connection) -> Result { "SELECT COUNT(*) FROM orchard_ironwood_migration_transactions", "migrationTxs", )?, - // 在途 migration 的 PCZT 可能不小,且按次数单调增长。 + // In-flight migration PCZTs can be large and grow with each run. "pcztBytes": sum( conn, "SELECT SUM(LENGTH(pczt)) FROM orchard_ironwood_migration_transactions", @@ -211,20 +207,19 @@ pub fn database_health(conn: &Connection) -> Result { mod tests { use super::*; - /// 空库上跑一遍。目的不是看数字,是证明**每条 SQL 的表名和列名都真实存在** —— - /// 写错的话 SQLite 会在这里报错,而不是等到线上安静地返回 0。 + /// Runs on an empty database to prove every table and column in the SQL exists. #[test] fn every_query_matches_the_real_schema() { let path = std::env::temp_dir().join("zr-stats-schema-check.sqlite"); let _ = std::fs::remove_file(&path); - let db = crate::wallet::open_and_migrate("test", path.to_str().unwrap()).expect("迁移"); + let db = crate::wallet::open_and_migrate("test", path.to_str().unwrap()).expect("migrate"); drop(db); - let conn = crate::storage::open_connection(path.to_str().unwrap()).expect("开连接"); - let out = storage_stats(&conn).expect("统计不应失败"); - let v: Value = serde_json::from_str(&out).expect("应是合法 JSON"); + let conn = crate::storage::open_connection(path.to_str().unwrap()).expect("open"); + let out = storage_stats(&conn).expect("storage stats"); + let v: Value = serde_json::from_str(&out).expect("valid JSON"); - // 空库也必须报出结构,而不是缺字段。 + // An empty database still reports every field. for group in [ "sqlite", "scan", @@ -233,7 +228,7 @@ mod tests { "transient", "poolMigration", ] { - assert!(v.get(group).is_some(), "缺少分组 {group}"); + assert!(v.get(group).is_some(), "missing group {group}"); } for pool in ["sapling", "orchard", "ironwood"] { let t = &v["trees"][pool]; @@ -244,13 +239,13 @@ mod tests { "retained", "marksRemoved", ] { - assert!(t.get(k).is_some(), "{pool} 缺少 {k}"); + assert!(t.get(k).is_some(), "{pool} missing {k}"); } } - // 空库没有扫过块,高度必须是 null 而不是 0 —— 0 会被误读成「扫到创世块」。 + // Unscanned heights are null, not 0, which would read as genesis. assert!(v["scan"]["minHeight"].is_null()); assert!(v["scan"]["maxHeight"].is_null()); - // 页大小必须是真数,否则 logicalBytes 没有意义。 + // A real page size, or logicalBytes is meaningless. assert!(v["sqlite"]["pageSize"].as_i64().unwrap_or(0) > 0); assert!(v["sqlite"]["logicalBytes"].as_i64().unwrap_or(0) > 0); diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs index 305145798..a5207e4b9 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs @@ -1,19 +1,13 @@ -//! 扫链:**真正有界**的推进。 +//! Chain scanning with bounded progress. //! -//! ## 为什么不用 `zcash_client_backend::sync::run` +//! `zcash_client_backend::sync::run` loops until fully synced (`batch_size` only +//! sizes each batch), so callers cannot interrupt, observe progress, or yield the +//! main thread. This module drives the upstream public APIs in two parts: //! -//! 上游那个函数内部是 `while running(...) {}` —— 它跑到**完全同步为止**。 -//! `batch_size` 只控制单批区块数,不控制批数。也就是说它不是「推进一步」, -//! 而是「同步到底」:调用方无法中断、无法看进度、无法在中途让出主线程。 +//! - [`prepare`]: one-off setup (subtree roots, chain tip). Slow; once per sync. +//! - [`step`]: scans at most `max_batches` batches, then returns progress. //! -//! 实测在 testnet 上一次调用 900 秒未返回。对浏览器和移动端都不可接受。 -//! -//! 所以这里自己驱动上游的公开 API,拆成两段: -//! -//! - [`prepare`] —— 一次性准备(下载子树根、更新链尖)。慢,但每轮同步只做一次。 -//! - [`step`] —— 有界推进:最多扫 `max_batches` 批,然后带进度返回。 -//! -//! 宿主拿到进度后自己决定要不要接着调 —— 这正是「调度归 TS」那条边界。 +//! The host decides whether to call again; scheduling belongs to TS. use std::collections::{HashMap, HashSet}; use std::hash::Hash; @@ -42,11 +36,11 @@ use crate::error::{ErrorCode, Result, RuntimeError}; use crate::network::LightClient; use crate::wallet::Db; -/// 在上游建议的区间里按优先级挑一个。 +/// Pick a range from the upstream suggestions by priority. /// -/// `None` 表示「随便,按上游给的顺序」—— 上游本就把 ChainTip 排在 Historic 前面。 -/// 指定优先级时只在同优先级里挑;挑不到就返回 None,让调用方知道这条 lane 空了, -/// 而不是悄悄去扫另一条 lane(那会让宿主的进度显示和实际发生的事对不上)。 +/// `None` means any, in upstream order (ChainTip before Historic). With a priority, +/// only that lane is considered; `None` is returned when it is empty rather than +/// silently scanning another lane, which would desync host progress reporting. fn pick_range(suggested: &[ScanRange], preferred: Option) -> Option { suggested .iter() @@ -54,7 +48,7 @@ fn pick_range(suggested: &[ScanRange], preferred: Option) -> Optio .cloned() } -/// 宿主可以指定的优先级。字符串而非数字:数字在跨边界时无从校验。 +/// Host-selectable priority. Strings, not numbers, so values are checkable across the boundary. pub fn parse_priority(name: &str) -> Result> { Ok(match name { "" | "any" => None, @@ -72,10 +66,10 @@ pub fn parse_priority(name: &str) -> Result> { }) } -/// 检测到重组时建议回退多少块。 +/// Suggested rewind depth on reorg. /// -/// Zcash 的最终性很快,深重组极罕见;退太多会让用户重扫大段历史,退太少则可能 -/// 没退到分叉点之前、下一轮继续撞连续性错误。宿主可以在重复失败时自行加大。 +/// Deep reorgs are rare on Zcash; too deep forces a long rescan, too shallow may +/// not pass the fork point. Hosts may increase it on repeated failures. const REORG_REWIND_BLOCKS: u32 = 10; fn net_err(operation: &str, e: impl std::fmt::Display) -> RuntimeError { @@ -86,7 +80,7 @@ fn db_err(operation: &str, e: impl std::fmt::Display) -> RuntimeError { RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": operation })).detail(e) } -/// 拉取某个池的全部子树根。 +/// Fetch all subtree roots for one pool. async fn subtree_roots( client: &mut LightClient, protocol: service::ShieldedProtocol, @@ -131,13 +125,12 @@ async fn subtree_roots( Ok(roots) } -/// 一次性准备:把三个池的子树根灌进钱包,并更新链尖。 +/// One-off setup: load subtree roots for all three pools and update the chain tip. /// -/// **这是首次同步最慢的一步**(要下载全部子树根),且与 `batch_size` 无关 —— -/// 这正是之前 `syncAdvance` 看起来「卡住」的原因。把它单独暴露出来, -/// 宿主就能给出「正在准备」这样的独立进度,而不是干等一个不返回的调用。 +/// The slowest step of a first sync (downloads every subtree root), independent of +/// `batch_size`; exposed separately so the host can report it as its own phase. /// -/// 每轮同步开始时调一次即可。重复调用是幂等的,但会重新下载,没必要。 +/// Idempotent, but each call re-downloads everything. pub async fn prepare(db: &mut Db, client: &mut LightClient) -> Result { let sapling: Vec> = subtree_roots( client, @@ -182,11 +175,11 @@ pub async fn prepare(db: &mut Db, client: &mut LightClient) -> Result { .to_string()) } -/// 只更新链尖,不碰子树根。 +/// Update only the chain tip, leaving subtree roots untouched. /// -/// 子树根是凝固的历史(新分片几天才完成一个),`prepare` 却每次从索引 0 -/// 全量重下约 1900 条 —— 主网实测 7.4s。每轮同步真正的新信息只有链尖, -/// 一个 unary 调用。`prepare` 留给开库后的第一次。 +/// Subtree roots change rarely (a new shard every few days) while `prepare` +/// refetches all ~1900 from index 0 (~7.4s on mainnet). Use `prepare` once after +/// opening the wallet and this unary call for later syncs. pub async fn tip(db: &mut Db, client: &mut LightClient) -> Result { let tip = crate::network::chain_tip(client).await?; db.update_chain_tip(BlockHeight::from_u32(tip)) @@ -194,10 +187,10 @@ pub async fn tip(db: &mut Db, client: &mut LightClient) -> Result { Ok(json!({ "chainTip": tip }).to_string()) } -/// 有界推进:最多处理 `max_batches` 批,每批 `batch_size` 个区块。 +/// Bounded progress: at most `max_batches` batches of `batch_size` blocks. /// -/// 返回进度 JSON,`done` 表示「已经没有待扫区间」。宿主据此决定是否继续调 —— -/// 本函数**永远不会**自己循环到同步完成。 +/// Returns progress JSON; `done` means no ranges remain. Never loops to full sync; +/// the host decides whether to call again. pub async fn step( db: &mut Db, client: &mut LightClient, @@ -224,8 +217,7 @@ pub async fn step( let mut batches_done = 0u32; let mut blocks_scanned = 0u64; - // 分阶段累计耗时。扫描慢的时候,「慢在下载还是慢在扫描」是完全不同的两件事, - // 而在浏览器里两者的表现一模一样(页面不动),只能靠打点区分。 + // Per-phase timings: in the browser slow download and slow scan look identical. let (mut ms_download, mut ms_treestate, mut ms_scan) = (0.0f64, 0.0f64, 0.0f64); let (mut scanned_from, mut scanned_to) = (None::, None::); let mut scanned_priority: Option = None; @@ -235,14 +227,14 @@ pub async fn step( .suggest_scan_ranges() .map_err(|e| db_err("suggestScanRanges", e))?; - // 按宿主给的优先级挑区间。**选择权在宿主,但候选只能来自上游建议** —— - // 这样「先追链尖还是先回填历史」这类调度决策回到 App,而 - // 「哪些区间扫了才是安全的」仍由协议实现说了算,宿主没法乱指高度。 + // The host picks the priority, but candidates come only from upstream + // suggestions: scheduling stays with the app, while which ranges are safe + // to scan stays with the protocol implementation. let Some(range) = pick_range(&suggested, preferred) else { - break; // 该优先级下没有待扫区间 + break; // no pending ranges at this priority }; - // 只取这一批,剩下的留给下一次调用 —— 这就是「有界」的全部含义。 + // Take only this batch; the rest is left for later calls. let start = range.block_range().start; if scanned_from.is_none() { scanned_from = Some(u32::from(start)); @@ -251,15 +243,14 @@ pub async fn step( let t_start = now_ms(); - // 下载:失败先原批重试一次,再对半收缩,地板 32 块。 + // Download: on failure retry the same batch once, then halve, down to 32 blocks. // - // 2022 spam 墙区段(约 171 万~195 万高度)一批 500 块可达几十 MB, - // 固定超时在慢链路上永远下不完 —— 不收缩的重试是原地撞墙,换端点 - // 也一样(哪台服务器这段都这么大)。成功的批量跨调用记忆(下方 - // thread_local):不记忆时每轮都从常规值重爬梯子,在墙里等于每轮 - // 白烧两次超时;记住上次成功值、成功后再倍增回去,梯子只爬一次, - // 出墙后几轮内自动恢复常规批量。wasm 单线程,thread_local 即会话级; - // 载体重启后回到常规值,自愈。 + // In the 2022 spam range (heights ~1.71M-1.95M) a 500-block batch can be + // tens of MB and never finishes on slow links under a fixed timeout, on any + // server. The successful size is remembered across calls (thread_local + // below, session-scoped on single-threaded wasm) and doubled back up after + // successes, so the shrink happens once and normal size recovers after the + // spam range. const MIN_DOWNLOAD_BATCH: u32 = 32; thread_local! { static DOWNLOAD_BATCH_HINT: std::cell::Cell = @@ -280,10 +271,10 @@ pub async fn step( let candidate = ScanRange::from_parts(start..attempt_end, range.priority()); let candidate_len = candidate.len(); trace(&format!( - "step: 下载 {candidate_len} 块 @{}", + "step: download {candidate_len} blocks @{}", u32::from(start) )); - // 超时在 download_batch 内部按「停滞」判定;这里只兜真失败。 + // download_batch times out on stalls; only real failures reach here. let _ = candidate_len; match download_batch(client, &cache, &candidate).await { Ok(got) => break (candidate, got), @@ -293,20 +284,20 @@ pub async fn step( } if same_size_retry > 0 { same_size_retry -= 1; - trace("step: 下载失败,原批重试"); + trace("step: download failed, retrying same batch"); continue; } if attempt_len <= MIN_DOWNLOAD_BATCH { return Err(e); } attempt_len = std::cmp::max(MIN_DOWNLOAD_BATCH, attempt_len / 2); - trace(&format!("step: 下载超时,批量对半 -> {attempt_len}")); + trace(&format!("step: download timeout, halving -> {attempt_len}")); } } }; - // 缩过就记住缩后的值并清空连胜;**整批**(非链尖小批)在记忆值上 - // 连胜三次才向上探一档 —— 小批成功或单次侥幸都不算数,否则记忆值 - // 被顶回超时区来回震荡,每隔一轮就白烧一次探测超时。 + // After shrinking, remember the size and reset the streak. Grow one step only + // after three consecutive full batches at the remembered size (small tip + // batches do not count), so the hint does not oscillate back into timeouts. if attempt_len < initial_len { DOWNLOAD_BATCH_HINT.with(|h| h.set(attempt_len)); DOWNLOAD_BATCH_STREAK.with(|s| s.set(0)); @@ -320,20 +311,18 @@ pub async fn step( let grown = std::cmp::min(batch_size, attempt_len.saturating_mul(2)); DOWNLOAD_BATCH_HINT.with(|h| h.set(grown)); DOWNLOAD_BATCH_STREAK.with(|s| s.set(0)); - trace(&format!("step: 批量上探 -> {grown}")); + trace(&format!("step: growing batch -> {grown}")); } } - // 预算截断时实际入库的可能少于请求区间,扫描终点以实收为准。 + // A budget cut may store fewer blocks than requested; scan only what arrived. let _ = &batch; scanned_to = Some(u32::from(start) + batch_len as u32); let t_downloaded = now_ms(); ms_download += t_downloaded - t_start; - // 钳位到 Sapling 激活高度之后。 - // - // lightwalletd 在 Sapling 激活之前**没有 treestate**,而它对这种请求的 - // 错误响应会让 wasm 侧的 gRPC 调用**永久挂起** —— 不是报错,是不返回。 - // 这个坑我们自己的代码库早有记录(zcashWebSdk.ts 的 birthday 钳位)。 + // Clamp to Sapling activation: lightwalletd has no treestate before it, and its + // error reply hangs the wasm gRPC call forever (see the birthday clamp in + // zcashWebSdk.ts). let anchor = anchor_height(¶ms, start); let chain_state = crate::network::with_timeout( @@ -356,10 +345,9 @@ pub async fn step( let t_treestate = now_ms(); ms_treestate += t_treestate - t_downloaded; - trace(&format!("step: 开始扫描 {batch_len} 块")); + trace(&format!("step: scanning {batch_len} blocks")); - // 重组在 scan_blocks_inline 内部按**类型**分类成 REORG_DETECTED - // (带精确 atHeight)—— 这里不再做字符串嗅探。 + // scan_blocks_inline maps reorgs to REORG_DETECTED by error type (exact atHeight). scan_blocks_inline( ¶ms, &cache, @@ -371,7 +359,7 @@ pub async fn step( )?; ms_scan += now_ms() - t_treestate; - trace(&format!("step: 扫描完成,累计 {ms_scan:.0}ms")); + trace(&format!("step: scan done, total {ms_scan:.0}ms")); blocks_scanned += batch_len as u64; @@ -390,7 +378,7 @@ pub async fn step( Ok(0) }; - // 扫完之后重新问一次,把剩余量报给宿主做进度条。 + // Re-query to report remaining work for the host progress bar. let remaining = db .suggest_scan_ranges() .map_err(|e| db_err("suggestScanRanges", e))?; @@ -405,7 +393,7 @@ pub async fn step( "blocksScanned": blocks_scanned, "remainingBlocks": remaining_blocks, "remainingRanges": remaining.len(), - // 这次实际扫的是哪一段、什么优先级 —— 宿主据此把进度归到正确的 lane + // Range and priority actually scanned, so the host attributes progress to the right lane "scannedFrom": scanned_from, "scannedTo": scanned_to, "scannedPriority": scanned_priority, @@ -553,28 +541,22 @@ fn parse_enhancement(data: &[u8], branch: BranchId, expected: TxId) -> Result rayon::spawn_fifo(|| task.run()) /// ``` /// -/// 而 `scan_cached_blocks` 用的正是 `Tasks for ()`,该实现只覆写了 `add_task`, -/// **没有覆写 `run_task`**,于是仍然走 rayon。wasm32 单线程环境下 rayon 全局线程池 -/// 没有工作线程,任务被排队但永远不会执行;随后 `BatchReceiver::into_results()` -/// 在通道上等一个永远不来的结果,**把主线程彻底堵死**。 -/// -/// 表现极具迷惑性:空区块不会产生批次,所以扫描一路正常,直到遇到**第一个含 -/// 屏蔽输出的区块**才卡住 —— 看起来像「批量大到某个阈值就挂」,实际与批量无关。 -/// 页面无响应、无错误、超时定时器不触发,连 CDP 都服务不了。 +/// Its `Tasks for ()` overrides `add_task` but not `run_task`, so tasks still go to +/// rayon. On single-threaded wasm32 the rayon pool has no workers, and +/// `BatchReceiver::into_results()` blocks the main thread forever at the first +/// block with shielded outputs. /// -/// 这里改用公开的 `scanning::scan_block`(它等价于 `runners = None`), -/// 试解密就地完成,不碰 rayon。代价是失去批量试解密的摊销优化(批量求逆), -/// 换来的是在单线程目标上能正确工作,且**不需要 fork 上游**。 +/// `scanning::scan_block` (equivalent to `runners = None`) decrypts inline without +/// rayon, at the cost of batched-inversion amortization and without forking upstream. fn scan_blocks_inline( params: &zcash_protocol::consensus::Network, cache: &MemoryBlockCache, @@ -607,10 +589,9 @@ where Ok(()) }) .map_err(|e| match &e { - // 链重组:上游的**类型化**判定(和参考循环同一个谓词)。这里是错误 - // 还带着类型的最后一刻 —— 一旦 format 成字符串再去嗅探变体名,就是 - // 上一个 bug 的形状:匹配串写错,重组识别静默失效,钱包在同一高度 - // 死循环整夜。at_height 也因此是精确值,不再用批起点估。 + // Reorg: classify by the typed upstream predicate (same as the reference + // loop) while the error is still typed; string matching can silently + // miss it. This also gives an exact at_height. ChainError::Scan(scan_err) if scan_err.is_continuity_error() => { let at = u32::from(scan_err.at_height()); RuntimeError::with( @@ -696,13 +677,11 @@ fn orchard_only_ufvk( .map_err(|e| RuntimeError::new(ErrorCode::InvalidUfvk).detail(e)) } -/// 单个账户的同步完成度。**不发网络请求。** +/// Sync completeness for a single account. No network requests. /// -/// 共享库里所有账户共用一条扫描队列,所以「全库剩余多少」对单个账户是误导的: -/// 刚加进来的账户会把全库进度拉回去,让早就扫完的账户看起来也没好。 -/// -/// 这里的判据是:**高于该账户 birthday 的待扫区间**才与它有关。低于 birthday -/// 的区间是别的账户的历史,与它无关。 +/// All accounts in a shared database share one scan queue, so whole-database +/// progress is misleading per account. Only pending ranges above this account's +/// birthday count; ranges below it belong to other accounts' history. pub fn account_status(db: &Db, account_uuid: &str) -> Result { let account_id = crate::account::parse_account_id(db, account_uuid)?; let birthday = u32::from( @@ -714,7 +693,7 @@ pub fn account_status(db: &Db, account_uuid: &str) -> Result { .suggest_scan_ranges() .map_err(|e| db_err("suggestScanRanges", e))?; - // 只算与这个账户有关的那部分 + // Count only the part relevant to this account let mut remaining: u64 = 0; let mut lowest_pending: Option = None; for r in &ranges { @@ -732,7 +711,7 @@ pub fn account_status(db: &Db, account_uuid: &str) -> Result { .map_err(|e| db_err("walletSummary", e))?; let chain_tip = summary.as_ref().map(|s| u32::from(s.chain_tip_height())); - // 扫到哪了 = 与本账户相关的最低待扫高度;没有待扫就是已追到链尖。 + // Scanned height = lowest pending height for this account, else the chain tip. let scanned_to = lowest_pending.or(chain_tip); Ok(json!({ @@ -745,10 +724,9 @@ pub fn account_status(db: &Db, account_uuid: &str) -> Result { .to_string()) } -/// 只读:钱包当前建议扫描哪些区间。**不发任何网络请求。** +/// Read-only: the ranges the wallet currently suggests scanning. No network requests. /// -/// 用途有二:给宿主做进度条;以及在同步卡住时确认它到底想扫哪一段 —— -/// 不用猜,直接看。 +/// For host progress bars and for inspecting what a stuck sync is trying to scan. pub fn peek(db: &Db) -> Result { let ranges = db .suggest_scan_ranges() @@ -770,12 +748,10 @@ pub fn peek(db: &Db) -> Result { Ok(json!({ "ranges": items, "totalBlocks": total }).to_string()) } -/// 诊断探针:只做**下载**,不扫描、不写库。返回各阶段耗时。 -/// -/// 用来把「网络慢/挂」与「扫描慢/挂」分开 —— 这两者在浏览器里的表现完全一样 -/// (都是页面无响应),但成因和修法完全不同。 +/// Diagnostic probe: download only, no scan, no writes. Returns per-phase timings. /// -/// 也可以当网络健康检查用:它不改变任何钱包状态。 +/// Separates a slow or hung network from a slow or hung scan, which look the same +/// in the browser. Also usable as a network health check; no wallet state changes. pub async fn probe_download(db: &Db, client: &mut LightClient, batch_size: u32) -> Result { let t0 = now_ms(); @@ -842,8 +818,7 @@ fn now_ms() -> f64 { .unwrap_or(0.0) } -/// 阶段打点。一次调用要跑很久时,最后一条打点就指出它停在哪个阶段 —— -/// 浏览器里除此之外看不到任何东西。 +/// Phase trace. When a call runs long, the last trace shows which phase it is in. #[cfg(target_arch = "wasm32")] pub(crate) fn trace(msg: &str) { #[wasm_bindgen::prelude::wasm_bindgen] @@ -864,10 +839,10 @@ pub(crate) fn trace(msg: &str) { } } -/// 取 `start - 1` 作为锚点,但不低于 Sapling 激活高度。 +/// Anchor at `start - 1`, but not below Sapling activation. /// -/// 低于该高度时 lightwalletd 没有 treestate,其错误响应会让 wasm 的 gRPC -/// 调用永久挂起(不是返回错误),所以必须在发请求前钳住。 +/// lightwalletd has no treestate below it, and its error reply hangs the wasm +/// gRPC call forever instead of failing, so clamp before requesting. fn anchor_height(params: &zcash_protocol::consensus::Network, start: BlockHeight) -> u32 { let sapling = params .activation_height(NetworkUpgrade::Sapling) @@ -876,17 +851,17 @@ fn anchor_height(params: &zcash_protocol::consensus::Network, start: BlockHeight u32::from(start).saturating_sub(1).max(sapling) } -/// 软预算:块还在到达时不判死,但总时长过线后**把已到手的连续前缀拿去扫**, -/// 不再等剩余的块。超时语义因此从「总时长一刀切」变成「停滞才是死」—— -/// 一个健康推进的大批(spam 墙里 500 块几十 MB)不再被硬杀重下; -/// 慢链路的每一秒都变成已入库的块,批量大小由实际吞吐逐秒决定。 +/// Soft download budget. Past it, scan the contiguous prefix received so far +/// instead of waiting for the rest; only a stall is fatal. A large but progressing +/// batch (500 spam-range blocks, tens of MB) is not killed and refetched. const DOWNLOAD_SOFT_BUDGET_MS: f64 = 30_000.0; -/// 流式下载一段区块并写入缓存,返回**实际入库的块数**(连续前缀)。 +/// Stream a block range into the cache; returns the number of blocks stored +/// (a contiguous prefix). /// -/// 每条流消息各自套 DEFAULT_TIMEOUT_MS 的**停滞**超时:只有一颗块都没 -/// 收到过的停滞才向上抛错(交给调用方重试/对半);已有收获的停滞和 -/// 预算超线一样,截断收工。 +/// Each stream item has its own DEFAULT_TIMEOUT_MS stall timeout. A stall before +/// any block arrives is an error (caller retries or halves); a later stall, like +/// the budget, truncates. async fn download_batch( client: &mut LightClient, @@ -923,7 +898,7 @@ async fn download_batch( let mut blocks = Vec::new(); loop { if !blocks.is_empty() && now_ms() - started > DOWNLOAD_SOFT_BUDGET_MS { - trace(&format!("step: 下载达预算,截断扫已获 {} 块", blocks.len())); + trace(&format!("step: over budget, scan {} blocks", blocks.len())); break; } let next = crate::network::with_timeout( @@ -939,12 +914,12 @@ async fn download_batch( .await; match next { Ok(Some(block)) => blocks.push(block), - Ok(None) => break, // 流正常结束(整批到齐) + Ok(None) => break, // stream ended normally (full batch) Err(e) => { if blocks.is_empty() { - return Err(e); // 真停滞且颗粒无收 + return Err(e); // stalled with nothing received } - trace(&format!("step: 下载停滞,截断扫已获 {} 块", blocks.len())); + trace(&format!("step: stalled, scan {} blocks", blocks.len())); break; } } @@ -963,8 +938,9 @@ async fn download_batch( Ok(got) } -/// 节点回的块必须从区间起点开始、逐块连续、不越过终点(右开)。截断的前缀 -/// 是合法的(下载有预算);乱序、重复、跳号或区间外的块不能进缓存。 +/// Blocks must start at the range start, be contiguous, and stay below the +/// exclusive end. A truncated prefix is valid (download budget); out-of-order, +/// duplicate, skipped, or out-of-range blocks must not enter the cache. fn check_block_sequence( start: u32, end_exclusive: u32, @@ -984,12 +960,14 @@ fn check_block_sequence( Ok(()) } -/// 回退钱包到指定高度,让之后的同步重扫这段区间。 +/// Rewind the wallet to `height` so later syncs rescan above it. /// -/// **破坏性**:该高度之上的扫描结果(note、witness、承诺树检查点)会被丢弃。 -/// 已广播的交易不受影响(它们在链上),但本地未确认记录可能丢失。 +/// Destructive: scan results above the height (notes, witnesses, commitment tree +/// checkpoints) are discarded. Broadcast transactions are unaffected on chain, +/// but local unconfirmed records may be lost. /// -/// 返回实际回退到的高度:上游可能因承诺树检查点位置退得比请求的更靠前。 +/// Returns the actual height, which may be lower than requested because of +/// checkpoint positions. pub fn rewind_to(db: &mut Db, height: u32) -> Result { let target = BlockHeight::from_u32(height); let actual = db @@ -1125,10 +1103,10 @@ mod tests { fn anchor_never_precedes_sapling_activation() { for net in [Network::MainNetwork, Network::TestNetwork] { let sapling = u32::from(net.activation_height(NetworkUpgrade::Sapling).unwrap()); - // 请求高度远早于 Sapling —— 必须被抬到激活高度,否则 gRPC 会挂死 + // Far below Sapling: must clamp to activation or gRPC hangs assert_eq!(anchor_height(&net, BlockHeight::from_u32(1)), sapling); assert_eq!(anchor_height(&net, BlockHeight::from_u32(sapling)), sapling); - // 正常情况取 start - 1 + // Normally start - 1 let h = sapling + 1000; assert_eq!(anchor_height(&net, BlockHeight::from_u32(h)), h - 1); } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs index e71786938..2ffb4c622 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs @@ -1,8 +1,7 @@ -//! 钱包数据库的打开与初始化。 +//! Opening and initializing the wallet database. //! -//! 这里只做三件事:接上存储、组装 `WalletDb`、跑 schema 迁移。 -//! 钱包的协议逻辑全部来自 `zcash_client_sqlite` / `zcash_client_backend`, -//! 本 crate 不实现任何 Zcash 语义。 +//! Connects storage, builds the `WalletDb` and runs schema migrations. All +//! wallet protocol logic comes from `zcash_client_sqlite` / `zcash_client_backend`. use rand::SeedableRng; use rand_chacha::ChaCha20Rng; @@ -14,10 +13,10 @@ use crate::error::{ErrorCode, Result, RuntimeError}; use crate::storage; use serde_json::json; -/// 本 runtime 使用的具体 `WalletDb` 组合。 +/// The concrete `WalletDb` used by this runtime. pub type Db = WalletDb; -/// 网络选择。跨 wasm 边界时用字符串,不暴露 Rust 枚举形状。 +/// Parses the network name passed across the wasm boundary. pub fn parse_network(s: &str) -> Result { match s { "main" => Ok(Network::MainNetwork), @@ -29,17 +28,14 @@ pub fn parse_network(s: &str) -> Result { } } -/// 打开(必要时创建)钱包数据库,并把 schema 迁移到当前库版本。 -/// -/// `init_wallet_db` 是幂等的:每次打开都跑一遍是安全且推荐的做法。 -/// 它会跑完 `zcash_client_sqlite` 的全部 migration —— 这也是我们验证 -/// SQL 方言与存储层是否真的可用的最强证据。 +/// Opens (creating if needed) the wallet database and migrates it to the +/// current schema. Migration is idempotent and runs on every open. pub fn open_and_migrate(network: &str, db_name: &str) -> Result { let params = parse_network(network)?; let conn = storage::open_connection(db_name)?; - // RNG 只用于库内部的非密钥用途(如 migration id、临时值)。 - // 密钥材料不经过它,也不经过本 crate 的任何路径。 + // Used only for non-key purposes inside the library (migration ids, nonces). + // No key material passes through it or through this crate. let rng = ChaCha20Rng::from_seed(random_seed()?); let mut db = WalletDb::from_connection(conn, params, HostClock, rng); @@ -55,7 +51,7 @@ pub fn open_and_migrate(network: &str, db_name: &str) -> Result { Ok(db) } -/// 32 字节随机种子。wasm 上走宿主的 crypto.getRandomValues。 +/// 32-byte random seed; on wasm this uses the host's crypto.getRandomValues. fn random_seed() -> Result<[u8; 32]> { let mut seed = [0u8; 32]; getrandom::fill(&mut seed).map_err(|e| { @@ -83,13 +79,13 @@ mod tests { #[test] fn seed_is_not_all_zero() { - let s = random_seed().expect("应能取到随机数"); + let s = random_seed().expect("random bytes available"); assert_ne!(s, [0u8; 32]); } - /// 打印迁移后的真实 schema。`storageStats` 的 SQL 必须照着这份写 —— - /// 表名靠记忆或靠外部文档写,出错时只会安静地返回 0,而不是报错。 - /// 需要 `ZR_DUMP_SCHEMA=1`,未设置时直接跳过。 + /// Prints the migrated schema. `storageStats` SQL must follow it: a wrong + /// table name silently returns 0 instead of failing. Runs only with + /// `ZR_DUMP_SCHEMA=1`. #[test] fn dump_schema() { if std::env::var("ZR_DUMP_SCHEMA") @@ -100,19 +96,19 @@ mod tests { } let path = std::env::temp_dir().join("zr-schema-dump.sqlite"); let _ = std::fs::remove_file(&path); - let db = open_and_migrate("test", path.to_str().unwrap()).expect("迁移"); + let db = open_and_migrate("test", path.to_str().unwrap()).expect("migrate"); drop(db); - let conn = crate::storage::open_connection(path.to_str().unwrap()).expect("开连接"); + let conn = crate::storage::open_connection(path.to_str().unwrap()).expect("open"); let mut stmt = conn .prepare("SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name") - .expect("查 sqlite_master"); + .expect("query sqlite_master"); let rows: Vec<(String, String)> = stmt .query_map([], |r| Ok((r.get(0)?, r.get(1)?))) - .expect("遍历") - .map(|r| r.expect("行")) + .expect("iterate rows") + .map(|r| r.expect("row")) .collect(); - // 统计要按 BLOB 列求和,所以列名也得是实测的。 + // Stats sum BLOB columns, so column names must come from the real schema. for t in [ "blocks", "transactions", @@ -130,11 +126,11 @@ mod tests { ] { let mut s = conn .prepare(&format!("PRAGMA table_info({t})")) - .expect("列"); + .expect("table_info"); let cols: Vec = s .query_map([], |r| r.get::<_, String>(1)) - .expect("遍历列") - .map(|r| r.expect("列名")) + .expect("iterate columns") + .map(|r| r.expect("column name")) .collect(); println!("-- {t}: {}", cols.join(", ")); } diff --git a/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs b/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs index e0dcb2bde..5bda99a23 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs @@ -1,51 +1,46 @@ -//! 原生复现:在本机跑与浏览器完全相同的扫描流程。 +//! Runs the browser scan flow natively, where a debugger and `sample` are available. //! -//! 目的是把「batchSize ≥ 25 挂死」从 wasm 里搬到原生环境 —— 那边能上真调试器、 -//! 能看堆栈、能 `sample` 采样,而在浏览器里只能看到页面无响应。 -//! -//! 需要联网,所以默认 `#[ignore]`。跑法: +//! Needs network, so `#[ignore]` by default. Run with: //! //! ```bash //! cargo test -p onekey-zcash-runtime --test scan_repro -- --ignored --nocapture -//! # 卡住时另开一个终端: +//! # If it hangs, from another terminal: //! # sample 5 -f /tmp/scan.txt # macOS //! ``` use onekey_zcash_runtime::{account, network, sync, wallet}; -// 原生 gRPC 端点(与浏览器用的 gRPC-web 端点不同)。 -// chainsafe 那个是 gRPC-web 代理,原生连不上;zec.rocks 反过来。 +// Native gRPC endpoint. The chainsafe endpoint is a gRPC-web proxy that native +// clients cannot use; zec.rocks is the reverse. const LWD: &str = "https://testnet.zec.rocks:443"; -/// Alice 的 testnet UFVK —— 公开测试向量,切勿用于真实资金。 +/// Alice's testnet UFVK, a public test vector. Never use for real funds. const ALICE_UFVK: &str = "uviewtest1eacc7lytmvgp0sshwjjv4qsg9fnewq00s6zye8hqwndpdsg0tum2ft4k96t86eapddpq56exfycnxnlds75vvpydv8fgj4cecczkmt3rjat8qjfqrk2cdlm9alep2z04785sx6yekqjk6wywkttlthld4c3xmg8fvneg4p97vzxwu9xtuh0xrgfy90p6uuxf8cwl8nxfq6hlte0nnylk59xceldrkx9vge3k4utkue2txu5kpp60aw07q0f0jgp0pv2c0gr7jdm6273uxyskt72jehte5jf2dg94d84le08h2t5rhd93j2d98ja59h46est69f3a7rav7k6744p2u8dxasc7nr9p2k95x7uaknahj0kw7mu5zq9nllj7x2qswq3jswsuzwms7shv7dhxz9s4yudatwu3u3v3wqznkhu6jt7xt8whjh3dkzvsf28p6mj8tya009gwzgszz2at8alquu8y0fmqt7klayrjx7n3ulml5q00fgdr"; async fn scan_with_batch(batch_size: u32) { let db_name = format!("/tmp/zcash-repro-{batch_size}.sqlite"); let _ = std::fs::remove_file(&db_name); - let mut db = wallet::open_and_migrate("test", &db_name).expect("开库应成功"); + let mut db = wallet::open_and_migrate("test", &db_name).expect("open wallet"); let mut client = network::connect_native(LWD) .await - .expect("应能连上 lightwalletd"); + .expect("connect to lightwalletd"); - let tip = network::chain_tip(&mut client).await.expect("应能取链尖"); - println!("链尖 = {tip}"); + let tip = network::chain_tip(&mut client).await.expect("chain tip"); + println!("tip = {tip}"); let uuid = account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 200, None) .await - .expect("导入账户应成功"); - println!("账户 = {uuid}"); + .expect("import account"); + println!("account = {uuid}"); - let prep = sync::prepare(&mut db, &mut client) - .await - .expect("准备应成功"); + let prep = sync::prepare(&mut db, &mut client).await.expect("prepare"); println!("prepare = {prep}"); - println!("peek = {}", sync::peek(&db).expect("peek 应成功")); + println!("peek = {}", sync::peek(&db).expect("peek")); let t0 = std::time::Instant::now(); - println!("开始 syncStep(batch_size={batch_size}, max_batches=1) …"); + println!("starting syncStep(batch_size={batch_size}, max_batches=1) …"); let out = sync::step( &mut db, &mut client, @@ -55,40 +50,39 @@ async fn scan_with_batch(batch_size: u32) { &[ALICE_UFVK.to_owned()], ) .await - .expect("扫描应成功"); - println!("耗时 {:?} 结果 {out}", t0.elapsed()); + .expect("scan"); + println!("elapsed {:?} result {out}", t0.elapsed()); } #[tokio::test(flavor = "multi_thread")] -#[ignore = "需要联网"] +#[ignore = "requires network"] async fn scan_batch_10() { scan_with_batch(10).await; } -/// 浏览器里这个批量会永久挂死。原生跑一遍就能区分: -/// 若这里也挂 → 是上游扫描逻辑;若这里正常 → 是 wasm / 存储层特有的问题。 +/// Hung in the browser. A native hang points at upstream scanning; a pass +/// points at wasm or the storage layer. #[tokio::test(flavor = "multi_thread")] -#[ignore = "需要联网"] +#[ignore = "requires network"] async fn scan_batch_25() { scan_with_batch(25).await; } #[tokio::test(flavor = "multi_thread")] -#[ignore = "需要联网"] +#[ignore = "requires network"] async fn scan_batch_100() { scan_with_batch(100).await; } -/// 扫描指定高度区间。浏览器里 trace 显示扫描停在某个具体高度上, -/// 而之前的原生测试都从 tip-200 / tip-2000 起步,**根本没覆盖到那一段**。 +/// Scans from a given height (the other tests start at tip-200 / tip-2000). /// -/// 用法(高度和批量都可覆盖): +/// Usage (height and batch size are overridable): /// ```bash /// ZR_FROM=4292840 ZR_BATCH=20 cargo test -p onekey-zcash-runtime \ /// --test scan_repro scan_from_height -- --ignored --nocapture /// ``` #[tokio::test(flavor = "multi_thread")] -#[ignore = "需要联网"] +#[ignore = "requires network"] async fn scan_from_height() { let from: u32 = std::env::var("ZR_FROM") .ok() @@ -102,20 +96,18 @@ async fn scan_from_height() { let db_name = format!("/tmp/zcash-from-{from}.sqlite"); let _ = std::fs::remove_file(&db_name); - let mut db = wallet::open_and_migrate("test", &db_name).expect("开库应成功"); + let mut db = wallet::open_and_migrate("test", &db_name).expect("open wallet"); let mut client = network::connect_native(LWD) .await - .expect("应能连上 lightwalletd"); - let tip = network::chain_tip(&mut client).await.expect("应能取链尖"); - println!("链尖 = {tip},从 {from} 起扫 {batch} 块"); + .expect("connect to lightwalletd"); + let tip = network::chain_tip(&mut client).await.expect("chain tip"); + println!("tip = {tip}, scanning {batch} blocks from {from}"); account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, from, None) .await - .expect("导入账户应成功"); - sync::prepare(&mut db, &mut client) - .await - .expect("准备应成功"); - println!("peek = {}", sync::peek(&db).expect("peek 应成功")); + .expect("import account"); + sync::prepare(&mut db, &mut client).await.expect("prepare"); + println!("peek = {}", sync::peek(&db).expect("peek")); let t0 = std::time::Instant::now(); let out = sync::step( @@ -127,32 +119,29 @@ async fn scan_from_height() { &[ALICE_UFVK.to_owned()], ) .await - .expect("扫描应成功"); - println!("耗时 {:?} 结果 {out}", t0.elapsed()); + .expect("scan"); + println!("elapsed {:?} result {out}", t0.elapsed()); } -/// 原生侧的批量耗时曲线。浏览器上批量越大越不成比例地慢,先确认原生是不是也这样: -/// 若原生也非线性 → 是算法问题,可以在原生上用采样分析器直接定位; -/// 若原生始终线性 → 非线性是 wasm 特有的,与上游无关。 +/// Native scan time by batch size. Nonlinear here means an algorithmic issue to +/// profile natively; linear means the browser slowdown is wasm-specific. #[tokio::test(flavor = "multi_thread")] -#[ignore = "需要联网"] +#[ignore = "requires network"] async fn scan_batch_curve() { for batch in [25u32, 100, 400, 1000] { let db_name = format!("/tmp/zcash-curve-{batch}.sqlite"); let _ = std::fs::remove_file(&db_name); - let mut db = wallet::open_and_migrate("test", &db_name).expect("开库应成功"); + let mut db = wallet::open_and_migrate("test", &db_name).expect("open wallet"); let mut client = network::connect_native(LWD) .await - .expect("应能连上 lightwalletd"); - let tip = network::chain_tip(&mut client).await.expect("应能取链尖"); + .expect("connect to lightwalletd"); + let tip = network::chain_tip(&mut client).await.expect("chain tip"); account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 2000, None) .await - .expect("导入账户应成功"); - sync::prepare(&mut db, &mut client) - .await - .expect("准备应成功"); + .expect("import account"); + sync::prepare(&mut db, &mut client).await.expect("prepare"); let t0 = std::time::Instant::now(); let out = sync::step( @@ -164,55 +153,51 @@ async fn scan_batch_curve() { &[ALICE_UFVK.to_owned()], ) .await - .expect("扫描应成功"); - println!("批量 {batch:>5} 总计 {:>10?} {out}", t0.elapsed()); + .expect("scan"); + println!("batch {batch:>5} total {:>10?} {out}", t0.elapsed()); } } -/// 与浏览器 `bisect.html` 完全同构:逐块推进 40 次。 -/// -/// 浏览器在第 7 块停住。如果原生也停在某个高度 → 是那个区块的内容; -/// 如果原生一路跑完 → 与区块无关,是 wasm 侧特有的。 +/// Mirrors the browser `bisect.html`: advances one block at a time, 40 times. +/// A native stall points at block content; a full run points at wasm. #[tokio::test(flavor = "multi_thread")] -#[ignore = "需要联网"] +#[ignore = "requires network"] async fn scan_one_by_one() { let db_name = "/tmp/zcash-repro-onebyone.sqlite"; let _ = std::fs::remove_file(db_name); - let mut db = wallet::open_and_migrate("test", db_name).expect("开库应成功"); + let mut db = wallet::open_and_migrate("test", db_name).expect("open wallet"); let mut client = network::connect_native(LWD) .await - .expect("应能连上 lightwalletd"); - let tip = network::chain_tip(&mut client).await.expect("应能取链尖"); - println!("链尖 = {tip}"); + .expect("connect to lightwalletd"); + let tip = network::chain_tip(&mut client).await.expect("chain tip"); + println!("tip = {tip}"); account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 200, None) .await - .expect("导入账户应成功"); - sync::prepare(&mut db, &mut client) - .await - .expect("准备应成功"); + .expect("import account"); + sync::prepare(&mut db, &mut client).await.expect("prepare"); for i in 0..40 { let peek: serde_json::Value = - serde_json::from_str(&sync::peek(&db).expect("peek 应成功")).unwrap(); + serde_json::from_str(&sync::peek(&db).expect("peek")).unwrap(); let height = peek["ranges"][0]["start"].as_u64(); let t0 = std::time::Instant::now(); let out = sync::step(&mut db, &mut client, 1, 1, None, &[ALICE_UFVK.to_owned()]) .await - .expect("扫描应成功"); + .expect("scan"); println!("#{i} h={height:?} {:?} {out}", t0.elapsed()); } } -/// 打印某个高度区块的结构摘要,用于和浏览器侧逐字段比对。 +/// Prints block structure summaries for field-by-field comparison with the browser. /// /// ```bash /// ZR_FROM=4292845 ZR_SPAN=3 cargo test -p onekey-zcash-runtime \ /// --test scan_repro block_summary_at -- --ignored --nocapture /// ``` #[tokio::test(flavor = "multi_thread")] -#[ignore = "需要联网"] +#[ignore = "requires network"] async fn block_summary_at() { let from: u32 = std::env::var("ZR_FROM") .ok() @@ -225,7 +210,7 @@ async fn block_summary_at() { let mut client = network::connect_native(LWD) .await - .expect("应能连上 lightwalletd"); + .expect("connect to lightwalletd"); for h in from..from + span { match network::block_summary(&mut client, h).await { Ok(s) => println!("{s}"), @@ -234,24 +219,24 @@ async fn block_summary_at() { } } -/// 审查报告称 `accounts.uuid` 是 BLOB,而 history.rs 用字符串绑定, -/// 导致历史查询恒为空。这条测试实测两种绑定的匹配数,不靠读 schema 推断。 +/// `accounts.uuid` is a BLOB: measures how many rows a string and a BLOB +/// binding match. #[tokio::test(flavor = "multi_thread")] -#[ignore = "需要联网"] +#[ignore = "requires network"] async fn uuid_binding_string_vs_blob() { let db_name = "/tmp/zcash-uuid-binding.sqlite"; let _ = std::fs::remove_file(db_name); - let mut db = wallet::open_and_migrate("test", db_name).expect("开库应成功"); - let mut client = network::connect_native(LWD).await.expect("应能连上"); - let tip = network::chain_tip(&mut client).await.expect("取链尖"); + let mut db = wallet::open_and_migrate("test", db_name).expect("open wallet"); + let mut client = network::connect_native(LWD).await.expect("connect"); + let tip = network::chain_tip(&mut client).await.expect("chain tip"); let uuid_str = account::import_ufvk(&mut db, &mut client, "a", ALICE_UFVK, tip - 10, None) .await - .expect("导入账户"); - println!("listAccounts 给出的形式: {uuid_str}"); + .expect("import account"); + println!("listAccounts form: {uuid_str}"); drop(db); - let conn = rusqlite::Connection::open(db_name).expect("直接打开同一个库"); + let conn = rusqlite::Connection::open(db_name).expect("open the same database directly"); let as_text: i64 = conn .query_row( "SELECT COUNT(*) FROM accounts WHERE uuid = ?1", @@ -271,32 +256,36 @@ async fn uuid_binding_string_vs_blob() { .query_row("SELECT COUNT(*) FROM accounts", [], |r| r.get(0)) .unwrap(); - println!("accounts 总数={total} 字符串绑定匹配={as_text} BLOB 绑定匹配={as_blob}"); - assert_eq!(total, 1, "应当只有一个账户"); - assert_eq!(as_blob, 1, "BLOB 绑定必须匹配到"); - assert_eq!(as_text, 0, "字符串绑定匹配不到 —— 这正是历史恒空的原因"); + println!( + "accounts total={total} string binding matched={as_text} BLOB binding matched={as_blob}" + ); + assert_eq!(total, 1, "exactly one account"); + assert_eq!(as_blob, 1, "BLOB binding must match"); + assert_eq!( + as_text, 0, + "string binding matches nothing, which leaves history empty" + ); } -/// 回归:历史查询必须真的能匹配到账户。 +/// Regression: history must actually match the account. /// -/// 之前这里报过假绿 —— 查询用文本绑定 BLOB 列,一行都匹配不上, -/// 而「空结果」和「空钱包」返回值一样,看不出坏。所以这条测试**不看返回内容**, -/// 只验证「用同一个 uuid 能在 v_transactions 上匹配到与直接查库一致的条数」。 +/// An empty result looks like an empty wallet, so this compares the row count +/// from history() with a direct v_transactions query instead of the content. #[tokio::test(flavor = "multi_thread")] -#[ignore = "需要联网"] +#[ignore = "requires network"] async fn history_uuid_actually_matches() { let db_name = "/tmp/zcash-history-uuid.sqlite"; let _ = std::fs::remove_file(db_name); - let mut db = wallet::open_and_migrate("test", db_name).expect("开库"); - let mut client = network::connect_native(LWD).await.expect("连上"); - let tip = network::chain_tip(&mut client).await.expect("链尖"); + let mut db = wallet::open_and_migrate("test", db_name).expect("open wallet"); + let mut client = network::connect_native(LWD).await.expect("connect"); + let tip = network::chain_tip(&mut client).await.expect("chain tip"); let uuid = account::import_ufvk(&mut db, &mut client, "a", ALICE_UFVK, tip - 10, None) .await - .expect("导入"); + .expect("import account"); drop(db); - let conn = rusqlite::Connection::open(db_name).expect("直接开库"); + let conn = rusqlite::Connection::open(db_name).expect("open database directly"); let via_join: i64 = conn .query_row( "SELECT COUNT(*) FROM v_transactions v @@ -310,9 +299,9 @@ async fn history_uuid_actually_matches() { let via_api = serde_json::from_str::>(&history) .expect("history JSON") .len(); - println!("直接查={via_join} history() 给出={via_api}"); + println!("direct={via_join} history()={via_api}"); assert_eq!( via_api as i64, via_join, - "history() 必须与直接查一致,而不是恒空" + "history() must match the direct query" ); } diff --git a/chain-runtimes/zcash/scripts/build-wasm.sh b/chain-runtimes/zcash/scripts/build-wasm.sh index 224c59269..4a0754c06 100755 --- a/chain-runtimes/zcash/scripts/build-wasm.sh +++ b/chain-runtimes/zcash/scripts/build-wasm.sh @@ -1,15 +1,14 @@ #!/usr/bin/env bash -# 构建浏览器可用的 wasm 包。 +# Build the browser wasm packages. # -# 前置条件: -# 1. wasm32-unknown-unknown target:rustup target add wasm32-unknown-unknown -# 2. 支持 wasm32 的 clang。macOS 自带的 Apple clang **不支持**,会报 -# "No available targets are compatible with triple wasm32-unknown-unknown"。 -# 用 Homebrew 的:brew install llvm -# (secp256k1-sys 自带 wasm sysroot,只是需要一个能产 wasm 的 clang。) -# 3. wasm-pack:cargo install wasm-pack +# Prerequisites: +# 1. wasm32-unknown-unknown target: rustup target add wasm32-unknown-unknown +# 2. A clang that targets wasm32. Apple clang does not ("No available targets +# are compatible with triple wasm32-unknown-unknown"); use brew install llvm. +# (secp256k1-sys ships its own wasm sysroot; it only needs the compiler.) +# 3. wasm-pack: cargo install wasm-pack # -# 用法: +# Usage: # bash scripts/build-wasm.sh # release # PROFILE=dev bash scripts/build-wasm.sh @@ -26,7 +25,7 @@ fi RUST_TOOLCHAIN="$(python3 -c 'import sys, tomllib; print(tomllib.load(open(sys.argv[1], "rb"))["toolchain"]["channel"])' "${ROOT}/rust-toolchain.toml")" rustup run "${RUST_TOOLCHAIN}" rustc --version -# 找一个能编 wasm32 的 clang +# Find a clang that can compile for wasm32. pick_clang() { for c in "${CC_wasm32_unknown_unknown:-}" \ /opt/homebrew/opt/llvm/bin/clang \ @@ -41,21 +40,21 @@ pick_clang() { } if ! CLANG="$(pick_clang)"; then - echo "错误:找不到支持 wasm32 的 clang。" >&2 - echo " macOS 请先 brew install llvm(Apple clang 不支持 wasm32 目标)。" >&2 + echo "Error: no clang with wasm32 support found." >&2 + echo " On macOS run brew install llvm (Apple clang lacks the wasm32 target)." >&2 exit 1 fi -echo "==> 使用 clang: ${CLANG}" +echo "==> Using clang: ${CLANG}" export CC_wasm32_unknown_unknown="${CLANG}" export AR_wasm32_unknown_unknown="${AR_wasm32_unknown_unknown:-$(dirname "${CLANG}")/llvm-ar}" bash "${ROOT}/scripts/vendor-deps.sh" "$@" -# --mode no-install 找不到 wasm-opt 只会打一行 INFO 然后跳过:产物不报错地胖一倍 -#(函数名段不剥、不做 -O)。release 必须有它。 +# With --mode no-install a missing wasm-opt is only an INFO line and the output +# silently doubles in size. Release requires it. if [ "${PROFILE}" = "release" ] && ! command -v wasm-opt >/dev/null 2>&1; then - echo "✗ 找不到 wasm-opt(Binaryen),release 产物会不经优化直接输出" >&2 + echo "✗ wasm-opt (Binaryen) not found; release output would be unoptimized" >&2 exit 1 fi @@ -63,24 +62,24 @@ echo "==> wasm-pack build (${PROFILE})" cd "${ROOT}/crates/zcash-runtime" case "${PROFILE}" in release) rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --release ;; - # 优化照旧,但保留名字段。wasm 里的 panic 只给函数序号,没有它就只能靠 - # 通读依赖去猜是谁调的 —— 而 --dev 会让 Halo2 证明慢到不可用。 + # Optimized but keeps the name section, which wasm panic stacks need. + # --dev would make Halo2 proving unusably slow. profiling) rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --profiling ;; *) rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --dev ;; esac -echo "==> 产物" +echo "==> Artifacts" ls -lh "${OUT}"/*.wasm | awk '{print " ", $9, $5}' -echo "==> 构建 storage benchmark" +echo "==> Building storage benchmark" (cd "${ROOT}/crates/zcash-storage-benchmark" && \ rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${ROOT}/pkg/storage-benchmark" --release) -# keys 包必须一起构建。只建 runtime 会让宿主用到过期的 keys 产物, -# 而那种不一致极难从现象反推(接口存在、行为却是旧的)。 -echo "==> 构建 onekey-zcash-keys" +# Always rebuild the keys package too, so the host never pairs a fresh runtime +# with a stale keys build. +echo "==> Building onekey-zcash-keys" (cd "${ROOT}/crates/zcash-keys-runtime" && rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${ROOT}/pkg-keys" --release) -echo "产物:$(du -h "${ROOT}"/pkg/*.wasm "${ROOT}"/pkg-keys/*.wasm "${ROOT}"/pkg/storage-benchmark/*.wasm | tr '\n' ' ')" +echo "Artifacts: $(du -h "${ROOT}"/pkg/*.wasm "${ROOT}"/pkg-keys/*.wasm "${ROOT}"/pkg/storage-benchmark/*.wasm | tr '\n' ' ')" if [ "${OUT}" = "${ROOT}/pkg" ]; then python3 "${ROOT}/scripts/package-release.py" prepare From 5d65850ca4db1877457122328d615bec2313c603 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 17:32:17 +0800 Subject: [PATCH 19/97] fix(monero): load the runtime package in measure-scan --- chain-runtimes/monero/scripts/measure-scan.js | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/chain-runtimes/monero/scripts/measure-scan.js b/chain-runtimes/monero/scripts/measure-scan.js index 476a6abc0..888ddfbab 100755 --- a/chain-runtimes/monero/scripts/measure-scan.js +++ b/chain-runtimes/monero/scripts/measure-scan.js @@ -1,14 +1,17 @@ #!/usr/bin/env node /** - * 量「拉块」与「扫描」各占多少。 - * - * 这条脚本存在的理由:0.6 块/秒这个端到端数字**没有意义**,除非知道它是 - * 网络慢还是解密慢 —— 两者的结论完全相反。实测(Mac,公共节点,单观察密钥): - * 拉块 99.6%、扫描 0.4%,纯扫描 153 块/秒。 + * Split sync time into block fetching and scanning, since an end-to-end + * blocks/sec figure cannot tell network latency from decryption cost. + * Measured (Mac, public node, one view key): fetch 99.6%, scan 0.4%, + * scan-only 153 blocks/sec. * * ./scripts/build-node-pkg.sh * XMR_NODE=http://your-node:18081 node scripts/measure-scan.js */ +const path = require('path'); +const pkg = process.env.XMR_NODE_PKG || path.join(__dirname, '..', 'pkg-node'); +const rt = require(path.join(pkg, 'onekey_monero_runtime.js')); + (async () => { if (!process.env.XMR_NODE) { console.error('Set XMR_NODE to a monerod RPC URL.'); @@ -28,10 +31,10 @@ const p = JSON.parse(await rt.syncStep(id, 10n)); if (!p.blocksScanned) break; dl += p.msDownload; sc += p.msScan; n += p.blocksScanned; - console.log(` ${p.blocksScanned}块: 拉块 ${p.msDownload}ms / 扫描 ${p.msScan}ms`); + console.log(` ${p.blocksScanned} blocks: fetch ${p.msDownload}ms / scan ${p.msScan}ms`); if (p.done) break; } - console.log(`\n合计 ${n} 块: 拉块 ${dl}ms (${(dl*100/(dl+sc)).toFixed(0)}%) / 扫描 ${sc}ms (${(sc*100/(dl+sc)).toFixed(0)}%)`); - console.log(`纯扫描速率: ${(n/(sc/1000)).toFixed(0)} 块/秒`); - console.log(`端到端速率: ${(n/((dl+sc)/1000)).toFixed(1)} 块/秒`); + console.log(`\ntotal ${n} blocks: fetch ${dl}ms (${(dl*100/(dl+sc)).toFixed(0)}%) / scan ${sc}ms (${(sc*100/(dl+sc)).toFixed(0)}%)`); + console.log(`scan-only rate: ${(n/(sc/1000)).toFixed(0)} blocks/sec`); + console.log(`end-to-end rate: ${(n/((dl+sc)/1000)).toFixed(1)} blocks/sec`); })(); From 7d4ca5fe36d1d25d85176e9700df7c036851fa4e Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 17:42:36 +0800 Subject: [PATCH 20/97] docs: keep only the docs needed to build, integrate and release Drop the import record, decision log, glossary context files and the Monero hardware-signing research note; README, RELEASING and the transparent tx API remain. Host contracts that lived only in the Monero context file (node network check, unknown broadcast outcome) move into its README. Remove references to the dropped files. --- chain-runtimes/README.md | 3 +- chain-runtimes/monero/CONTEXT.md | 67 --- chain-runtimes/monero/README.md | 9 +- .../docs/hardware-and-offline-signing.md | 132 ------ chain-runtimes/zcash/CONTEXT.md | 160 ------- chain-runtimes/zcash/IMPORT.md | 35 -- chain-runtimes/zcash/README.md | 3 +- .../zcash/crates/zcash-runtime/src/bindgen.rs | 2 +- .../zcash/crates/zcash-runtime/src/send.rs | 2 +- chain-runtimes/zcash/docs/decisions.md | 408 ------------------ 10 files changed, 12 insertions(+), 809 deletions(-) delete mode 100644 chain-runtimes/monero/CONTEXT.md delete mode 100644 chain-runtimes/monero/docs/hardware-and-offline-signing.md delete mode 100644 chain-runtimes/zcash/CONTEXT.md delete mode 100644 chain-runtimes/zcash/IMPORT.md delete mode 100644 chain-runtimes/zcash/docs/decisions.md diff --git a/chain-runtimes/README.md b/chain-runtimes/README.md index 43ceb4137..8e5ae5303 100644 --- a/chain-runtimes/README.md +++ b/chain-runtimes/README.md @@ -7,8 +7,7 @@ workspaces or their shared version/publish commands. ## Zcash -See [zcash](./zcash/README.md), its [import record](./zcash/IMPORT.md) and -[release process](./zcash/RELEASING.md). +See [zcash](./zcash/README.md) and its [release process](./zcash/RELEASING.md). From the repository root: diff --git a/chain-runtimes/monero/CONTEXT.md b/chain-runtimes/monero/CONTEXT.md deleted file mode 100644 index 7b11ffeca..000000000 --- a/chain-runtimes/monero/CONTEXT.md +++ /dev/null @@ -1,67 +0,0 @@ -# 维护上下文 - -**这里只记不能从代码本身读出来的东西。** - -## 代码里看不出来的几件事 - -**一、扫描进度为什么在 `identities` 而不是从 `blocks` 推。** - -`blocks` 表是全局的(块哈希是客观事实,各身份共享)。拿它的 `max(height)` 当进度, -会让一个追到链尖的身份把另一个还在回补的身份的进度一起推到链尖,那段历史被永久跳过。 -回归测试 `two_identities_keep_independent_progress` 钉住了这一点。**别改回去。** - -**二、为什么 `runtime.rs` 没有 wasm-only 门。** - -加了门,`runtime.rs` 与绑定层在原生 `cargo test` 里根本不编译,并发防线(BUSY 守卫、 -世代号)就测不到。这里刻意不加,`runtime.rs` 里的测试覆盖它们。 - -**三、`cargo check` 不链接。** - -给 wasm 目标做验证时只跑 check 会漏掉链接期的问题。macOS 的 `/usr/bin/ar` 读不懂 -wasm 目标文件,会把编译好的 `.o` **静默**打成空归档,只有 `cargo build` 才暴露。 -归档器已由 `.cargo/config.toml` 固定成 llvm-ar。 - -## 发送的记账顺序 - -- 交易在**广播之前**就记为在途:输入按 key image 标为已花、写一条待确认记录。 - 广播结局未知(超时、Worker 被终止)时,这笔交易仍然可见、输入不会被重新选中, - 由在途检查(`pool.rs`)或扫链按 key image 认出来解决。只有节点明确拒收时才撤销。 -- 重组回退时,自己发出的交易改回待确认,而不是删除记录、放回输入。 -- 已签名但始终没有走到广播的预留 24 小时后过期(未签名的 1 小时)。过期后这批输入 - 重新排在选币前面,旧签名万一再被广播,两笔争同一批 key image,链上只成一笔。 - -## 协议性的硬限制,不是实现问题 - -**观察钱包检测不到花费。** 需要 key image,而 key image 需要花费私钥。宿主必须 -在解锁时调 `importKeyImages`,否则余额偏高。`balance` 返回的 -`unverifiableAtomic` 就是这部分,宿主应当据此提示用户。 - -**节点声称的 RingCT 输出索引不可验证。** 上游文档明确要求客户端自己维护并比对。 -`scan.rs` 实现了独立推算(按本块 v2 交易的输出总数推进游标),不一致报 -`RINGCT_INDEX_MISMATCH`。索引错了的后果是构环取错输出、交易被全网拒绝。 - -**时间戳形式的时间锁判不了。** 只有链高判得了块高形式的锁。时间戳形式的一律 -按「仍锁定」处理 —— 让用户等,好过让他构一笔必然被拒的交易。 - -## 不信节点的几个值 - -「节点说错了」的后果比「我们发版晚了」严重,所以这些由 runtime 写死或校验: - -- **环大小 16**(`spend::RING_LEN`) -- **RctType = ClsagBulletproofPlus** —— 跟着硬分叉由我们发版控制 -- **手续费**:每档优先级各有费率上限(`spend::max_fee_per_weight`,按主网现值留 - 5 倍余量);节点给的取整单位(quantization mask)必须等于协议常量 - `spend::FEE_QUANTIZATION_MASK`(10,000)。不符就拒绝构造交易,宁可发不出去也不多付。 -- **网络**:连接节点时按创世块认出它在哪条链上,认不出就不连;钱包库与节点一起使用前 - 比对两边的网络,不一致报 `NODE_NETWORK_MISMATCH`。`chainTip` 在钱包库打开前调用, - 返回里带 `network`,宿主定 birthday 前须自行比对。 - -## 对真实节点的测试 - -`tests/live_node.rs` 里联网的用例需要显式指定节点: - -```bash -XMR_NODE= cargo test --test live_node -- --nocapture -``` - -它会打印链尖、扫描速度(块/秒)和余额。 diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md index 391a078fa..40de30854 100644 --- a/chain-runtimes/monero/README.md +++ b/chain-runtimes/monero/README.md @@ -38,7 +38,7 @@ runtime.rs 跨调用会话状态与并发防线 bindgen.rs wasm 边界 ``` -## 三件必须知道的事 +## 必须知道的事 **一、观察钱包检测不到花费。** Monero 的花费检测需要 key image,而 key image 需要花费私钥。这是协议性质不是实现取舍。所以宿主必须在解锁时调一次 @@ -53,6 +53,13 @@ bindgen.rs wasm 边界 **三、调度归宿主。** `syncStep` 一次最多扫 `maxBlocks` 个块就返回,**永远不会 自己循环到同步完成**。什么时候扫、扫多少、失败怎么退避全由宿主 TS 决定。 +**四、节点必须和钱包在同一个网络上。** 连接时按创世块认出节点所在的链,钱包库与 +节点网络不一致时报 `NODE_NETWORK_MISMATCH`。`chainTip` 在开库前调用,返回里带 +`network`,宿主定 birthday 前须自行比对。 + +**五、广播结局 `unknown` 不是失败。** 交易在广播前已记为在途、输入已标已花; +结局不确定时由在途检查或扫链判定。宿主不得据此提示失败、引导重发。 + ## 构建 ```bash diff --git a/chain-runtimes/monero/docs/hardware-and-offline-signing.md b/chain-runtimes/monero/docs/hardware-and-offline-signing.md deleted file mode 100644 index 316b3b6fd..000000000 --- a/chain-runtimes/monero/docs/hardware-and-offline-signing.md +++ /dev/null @@ -1,132 +0,0 @@ -# Monero 硬件签名与离线签名:接缝在哪,什么已经做了 - -记录于 2026-09-22。结论都注明了来源(上游源码行为 / 固件源码 / 实测)。 - -## 一句话 - -软件签名已经通了。硬件签名接不上的地方**只有一个是不可逆的**,已经修掉; -其余都能在真正接硬件时再补,不会丢数据。 - ---- - -## 1. 三方各自给什么 - -### monero-oxide(我们用的密码学库) - -签名只有两条路: - -| 路径 | 入参 | 适用 | -|---|---|---| -| `SignableTransaction::sign(rng, spend_key)` | 花费私钥 | 软件钱包(我们现在走这条) | -| `SignableTransaction::multisig(ThresholdKeys)` | FROST 门限密钥 | 门限多签,**不是**硬件 | - -没有「外部签名者」回调。`multisig` 是 FROST,和固件那套分步协议是两回事。 - -`SignableTransaction` 的公开访问器只有: -`fee_rate()` / `necessary_fee()` / `serialize()` / `read()` / -`unsigned_transaction(key_images)` / `sign()`。 - -**它不公开 `inputs()` 也不公开 `payments()`** —— 序列化出来的 blob 从外面 -拆不开。要拿里面的东西,只能在 `prepare` 那一刻、东西还在手里时留下来。 - -有用的是 `unsigned_transaction(key_images: Vec)`: -这是上游留的两段式接缝 —— key image 从外面给(设备算的),它给出未签名交易。 - -### 固件(`firmware/core/src/apps/monero/`) - -实现的是 Trezor 那套分步协议,step 01–10: -init → set_input → inputs_permutation → input_vini → all_inputs_set → -set_output → all_outputs_set → sign_input → sign_final。 - -**设备自己构造并签名整笔交易**,宿主只是喂数据。 - -每个输入要一个 `MoneroTransactionSourceEntry`(见 -`signing/step_02_set_input.py`): - -- `outputs[]` —— 整个环,每项 `{ idx(全局序号), key.dest, key.mask }` -- `real_output` —— 环里哪一个是我们的 -- `real_out_tx_key` —— **创建这笔输出的那条交易的公钥 R** -- `real_out_additional_tx_keys` —— 子地址收款时的 additional keys -- `real_output_in_tx_index` —— 我们的输出在那条交易里的序号 -- `amount` / `subaddr_minor` / `rct` - -关键一点,别想绕:设备用 `real_out_tx_key` + `real_output_in_tx_index` + -子地址**自己推导**一次性私钥和 key image。它不接受宿主算好的偏移量 —— -接受了就等于让一个恶意宿主指挥设备拿任意密钥签名。 - -### hd-core(`@onekeyfe/hd-core@1.2.4`,实测) - -48 个 `Monero*` protobuf **类型**,**0 个可调用方法**。 -`CoreApi` 上没有任何 `moneroXxx()`。SDK 现在驱动不了签名会话。 - ---- - -## 2. 差在哪:一个不可逆,其余可逆 - -### 不可逆(已修):交易公钥 R - -monero-oxide 扫描时把「R + 输出序号 + 子地址」整条推导**折叠成一个 -`key_offset` 标量**(`WalletOutput` 只存 `key_offset: Scalar`), -然后把 R 丢掉。软件签名只要 `spend + key_offset`,所以一直没暴露出来。 - -固件要 R。而 R 只在扫描那一刻手里有,事后只有两条路: - -1. 全量重扫(每个已有用户一次) -2. 拿 txid 去问节点要回那条交易 —— 等于直接告诉节点「我对这笔感兴趣」, - 把扫全链换来的隐私当场还回去 - -所以**必须在发版前就开始存**。已做: - -- schema V2:`outputs.tx_pub_keys` + `outputs.tx_additional_pub_keys` - (32 字节一个顺序拼接;没有 additional 时存 NULL 而不是空串 —— - 「有 0 个」和「没有这个字段」是两回事) -- `scan.rs::tx_public_keys_from_extra()` 在扫描当下从 `Extra` 取 -- 只在这一块确实有我们的输出时才解析(绝大多数块一个都没有) -- 测试:真实主网向量(高度 3767756,交易 - `097edcb4…51bb`)+ 迁移测试(v1 库就地升 v2)+ 空 extra 不 panic - -### 可逆(不急):环成员与诱饵 - -`Decoys` 公开了 `offsets()` / `positions()`(绝对全局序号)/ -`signer_index()`(= `real_output`)/ `ring()`(= `[dest, commitment]`), -全都够用。 - -但它们只活在 `SignableTransaction` 里,而那个类型不公开 `inputs()`。 - -**不要紧**:诱饵每次 `prepare` 都重新选(必须如此 —— 用旧链高选的环, -成员分布会偏离当下的链上分布,那是可被统计分析利用的指纹)。 -所以什么都没丢,接硬件那天让 `prepare` 顺手多返回一份就行。 - -真接的时候改这里:`spend.rs::prepare()` 里 `inputs` 那个 Vec 还在手上, -在它被 move 进 `SignableTransaction::new` 之前把每项的 -`decoys().positions()` / `ring()` / `signer_index()` 取出来。 - ---- - -## 3. 一条硬约束:`signableHex` 等价于 view key - -上游把整个 viewing pair 写进找零输出: -`ChangeEnum::Standard { view_pair, .. }`, -`write()` 里是 `view_pair.spend().compress().write(w)` 后面紧跟 -`view_pair.view.write(w)` —— **私有 view key 明明白白在里面**。 - -原因是 Monero 的钱包协议按「发送方能看到自己的找零」来优化。 -不带 view key 的变体是 `Change::fingerprintable`,上游自带警告 -「You MUST assume this will harm your privacy」,所以不能为了躲这个去换。 - -**对离线签名设计的直接后果**:那份「未签名交易」不是无害的。 -谁拿到它,谁就能看见这个账户收到过的每一笔钱。它只能在 view key -本来就可以去的地方流动。做气隙签名(二维码 / U 盘)之前必须先想清这一条。 - ---- - -## 4. 接硬件时的动作清单 - -1. 等 hd-core 暴露 Monero 方法(现在是 0 个)。没有这个前面都白搭。 -2. `prepare` 增补返回每个输入的环数据(见 §2「可逆」那段,改一处)。 -3. 写 `KeyringHardware`,按固件 step 01–10 驱动。 - 接缝已经在位:vault 的发送路径按 keyring 分流, - `IEncodedTxXmr` 带着未签名产物,软件签名走 `CoreChainSoftware`, - 硬件那条只要在同一个位置插进去。 -4. key image 从设备来,用 - `SignableTransaction::unsigned_transaction(key_images)` 合回去。 diff --git a/chain-runtimes/zcash/CONTEXT.md b/chain-runtimes/zcash/CONTEXT.md deleted file mode 100644 index 06c12b14f..000000000 --- a/chain-runtimes/zcash/CONTEXT.md +++ /dev/null @@ -1,160 +0,0 @@ -# Zcash Runtime — 领域词汇 - -本文件只定义**术语**,不放实现细节、不放待办。设计决策见 `docs/decisions.md`。 - ---- - -## Wallet(钱包库) - -一份 SQLite 数据库,由 `zcash_client_sqlite` 管理其 schema。 - -**一个 wallet 对应一个 network,而不是一个种子或一个账户。** 宿主为同一网络上的 -所有 Account 注册 UFVK,数据库一次下载和扫描即可试解密全部账户。wallet 的身份只有 -`network`,**不包含 lightwalletd 端点**:同一条链上不同端点提供同一份数据,换端点 -不能导致全量重扫。 - -wallet 是**纯派生缓存**。SQLite 会保存已注册 UFVK、birthday 和扫描结果,以便重载后 -继续工作;但这些不是唯一副本。宿主账户元数据仍是 UFVK 与 birthday 的权威来源, -所以删除数据库只会触发重新注册和重扫,不会丢失不可再生材料。 - -## Account(账户) - -wallet 内的一个 UFVK 及其派生地址。对应 OneKey 的一个链上账户(一个 `hdIndex`)。 - -在 runtime 内以 UUID 标识。**该 UUID 不稳定**:Purge 后重建会得到新的 UUID, -所以宿主不能缓存它,每次从 UFVK 重新解析。 - -## Seed Fingerprint(种子指纹) - -ZIP-32 定义的种子标识。**是标准值,不是任意哈希** —— 宿主持久化它作为账户身份, -自行发明的哈希会让存量账户全部失配。 - -## Public Test Mnemonic(公开测试助记词) - -专用于可重复测试、已公开且不承载真实资产的助记词夹具。当前允许记录的是标准 -`abandon` 开头、`about` 结尾的 12 词测试向量;任何真实钱包或非公开测试钱包的 -助记词都不属于此概念,禁止进入文档、日志、截图或测试产物。 - -_Avoid_: Test seed、测试钱包助记词(两者都容易被误解为可以记录任意测试账户密钥) - -## Purge(清缓存) - -丢弃已扫结果、保留重建所需材料的操作。因为 wallet 是纯派生缓存,Purge 只是 -"要重扫一遍",不丢任何不可再生的数据。 - -两种用途:出问题时的手动重置;删账户时清除已解密的屏蔽交易历史——后者是隐私要求, -那份历史正是 Zcash 存在的意义所要隐藏的东西。 - -## Lane(同步车道) - -扫描进度分两条逻辑车道,回答不同问题: - -- **Tip lane**:余额新不新。用户当下看的是它。 -- **Birthday lane**:这个钱包是否已经知道自己的全部历史。**它才决定余额可不可信**—— - 回填未完成时余额可能偏低,因为更早的收款还没被发现。 - -两条车道由宿主调度,runtime 只按宿主指定的优先级推进一段,且候选区间只能来自 -上游的建议集合。 - -## Reservation(占用凭证) - -一次交易提案对所选 note 的占用,以 32 字节 owner token 标识。 - -存在的理由:屏蔽 note 形如 UTXO,同一个 note 被两笔交易花,第二笔必被拒。而 -"选好币"到"真的花掉"之间隔着审核页、密码、证明、签名,这段窗口内必须防止 -另一次选币挑中同一批。 - -token 由**调用方持有**:先生成、先持久化、再构造,这样崩溃恢复后仍知道该释放哪一批。 -一个 token 只对应一笔交易:交易落库后,该 token 不能再用于构造新交易。 - -## Capability(能力声明) - -runtime 当下**实际**能做什么。宿主据此提前隐藏做不到的操作。 - -每个标志定义在限制它的那段代码旁边,且与运行时的拒绝分支一一对应——不会出现 -"声称支持其实不支持"。发送失败得晚代价很高:提案已锁 note、用户已输密码。 - -## 池(Pool) - -- **transparent**:公开,与比特币同构。再分 regular 与 coinbase,后者成熟规则不同 - 且只能经由专门的 shielding 路径转出。 -- **sapling**:本产品不支持的历史屏蔽池。不得作为收款 receiver、余额或历史的 - 产品数据源,也不得作为发送来源;“不支持”不是“显示但只读”。 -- **orchard**:屏蔽。保留历史余额并支持迁出;NU6.3 后不再是新收款目标。 -- **ironwood**:NU6.3 引入的当前屏蔽池;向 UA 的新付款默认落在这里。 - -跨池合计是产品口径,不是链上事实,因此由宿主计算;runtime 只逐池报事实。 - -## Private Receive UA Policy(私密收款地址策略) - -App 对外展示的私密 Unified Address 所包含的 receiver 集合,当前仅包含 Orchard -receiver。Ironwood 没有独立的 UA receiver typecode;“地址含 Orchard receiver”不代表 -新收到的资金会进入 Orchard。 - -_Avoid_: Ironwood 地址、最新池地址 - -## Current Shielded Output Pool(当前私密输出池) - -当前网络升级下,新私密输出和 Shield All 目标实际落入的池,当前为 Ironwood。 -私密找零不一定落在这里:从 Orchard 花费时,上游可能把找零留在 Orchard。它与 -Private Receive UA Policy、可花费来源池是三个不同维度;调用方不得各自写死池名。 - -_Avoid_: Current Receiving Pool、最新池、默认隐私池 - -## Spendable Shielded Sources(可花费私密来源池) - -普通发送允许消费的私密来源池集合,当前为 Orchard 和 Ironwood。指定来源池时必须 -严格隔离,不得因透明花费测试开关而追加其他池的输入。 - -_Avoid_: Current Shielded Output Pool(它描述输出目标,不描述可花费来源) - -## Shield All(全部屏蔽) - -把账户中全部符合条件的 regular transparent UTXO 扣除手续费后,转入自己的 -Current Shielded Output Pool。它不消费任何已有私密池,也不消费 Coinbase UTXO。 - -_Avoid_: Shield、归集(单独使用时无法表达来源、目标和“全部”语义) - -## Payment Source(付款来源) - -一笔付款花哪部分资金,由发送页的来源选择决定:私密池只花该池,透明只花透明, -互不补足。 - -_Avoid_: 优先使用透明资金(该账户偏好已移除,付款来源只由发送页决定) - -## Transparent Mode(透明模式) - -账户展示透明资金与活动,并使用透明来源付款,不启用私密资金发现或扫描。付款可以 -面向透明地址或受支持的 Unified Address;私密收款目标不改变付款来源的公开属性。 - -_Avoid_: Privacy disabled(容易把产品模式误解为一次临时暂停) - -## Privacy Mode(隐私模式) - -账户选择启用受支持私密资金与活动的发现和展示。启用不等于历史发现已经完成; -支持的账户、设备及发送组合由产品契约规定,不能由该模式名称自行推导。 - -## Privacy Pause(暂停隐私处理) - -把 UFVK 标为 inactive,停止后续扫描并隐藏私密余额、历史、收款和发送入口,同时保留 -runtime 缓存与 birthday。它不会移动链上资金,也不是删除本地隐私数据。 - -## Active UFVK Set(当前启用的隐私身份集) - -宿主每次调用扫描时显式传入的 UFVK 去重集合。Runtime 只用这些身份的 -Orchard key 试解密 Orchard/Ironwood,不在 Rust DB 持久化产品开关;空集合是错误, -不得解释为“扫描全部账户”。 - -_Avoid_: Registered UFVK Set(数据库已注册身份不等于产品已启用身份) - -## Privacy Resume Cursor(隐私恢复游标) - -宿主在 Privacy Pause 时保存的区块高度。同 network wallet 的 scan queue 是全局的, -其他 Active UFVK 在暂停期间会继续推进它;因此重新启用前,宿主必须加入重组安全余量, -再用 `queueRescanFrom` 把缺失区间重新排队。该游标属于宿主产品状态,不属于 runtime DB。 - -## Delete Local Privacy Data(删除本地隐私数据) - -用户明确触发的破坏性本地操作:删除账户的 runtime 派生缓存和本地 UFVK/UA 元数据, -但保留 birthday。重新开启 Privacy Mode 时重新派生观察材料,并从保留的 birthday -重扫。该操作不得与普通模式开关合并。 diff --git a/chain-runtimes/zcash/IMPORT.md b/chain-runtimes/zcash/IMPORT.md deleted file mode 100644 index b1c943c88..000000000 --- a/chain-runtimes/zcash/IMPORT.md +++ /dev/null @@ -1,35 +0,0 @@ -# Zcash source import - -- Source revision: `c11be01b2f395b0c64321df2e2cab026008da6b5` (`feat: add zcash wallet and keys wasm runtime`). -- Destination: `OneKeyHQ/app-modules`, `chain-runtimes/zcash`. -- Imported files: the source repository's tracked Cargo workspace, Rust source, - tests, documentation, patches, and build scripts. - -The runtime is OneKey's adapter over the versions of librustzcash pinned in -`Cargo.lock`, rather than a fork of the entire librustzcash repository. Generated -packages, Cargo build caches, browser experiments, logs, and local wallet data are -not imported. - -## Vendor changes - -Every vendored crate is reconstructed from the upstream crate archive checksum and -an exact patch listed in `patches/manifest.json`: - -1. `zcash_client_sqlite 0.22.0`: disable rusqlite's `bundled` feature for WASM. - Its Rust source is unchanged. -2. `sqlite-wasm-vfs 0.2.0`: `sqlite-wasm-vfs-0.2.0-opfs-durability.patch` adds - per-connection locks, durable journal deletion, handle cleanup and fail-closed - metadata I/O for the OPFS SAH-pool. All App platforms use this same patch. -3. `tonic-web-wasm-client 0.9.1`: `tonic-web-wasm-client-0.9.1-host-fetch.patch` - lets the host supply the fetch handler used for lightwalletd requests. - -`scripts/vendor-deps.sh` verifies the archives, applies the exact patches, and -rejects an existing vendor tree whose contents differ. No vendor source or -prebuilt WASM is committed. - -## Application handoff - -During local development, the App's `packages/core/package.json` points its -portal dependencies to this directory's `pkg` and `pkg-keys`. Build both outputs -before installing the App dependencies. Registry publishing and a versioned App -dependency are a separate release step; see [RELEASING.md](./RELEASING.md). diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md index 6cbc8d805..a92a8ed45 100644 --- a/chain-runtimes/zcash/README.md +++ b/chain-runtimes/zcash/README.md @@ -3,7 +3,6 @@ > Install `wasm-bindgen-cli` at the `wasm-bindgen` version in `Cargo.lock` > and provide `wasm-opt` (Binaryen), or reuse the matching wasm-pack tool cache. > Builds use `--mode no-install` and never update `Cargo.lock`. -> See [IMPORT.md](./IMPORT.md) for the source revision and vendor patches. # OneKey Zcash Runtime @@ -94,7 +93,7 @@ OPFS 仍受浏览器 origin、配额和清理策略约束;App 内嵌页面的 gRPC-web 能通)。端点由宿主注入,runtime 不硬编码。 - **扫描不走上游的 `scan_cached_blocks`**,改用自己的 `scan_blocks_inline`。 上游把试解密交给 `rayon::spawn_fifo`,而 wasm32 单线程环境下 rayon 没有工作线程, - 任务永远不会执行,随后取结果时永久堵死主线程。见 `docs/decisions.md` D8。 + 任务永远不会执行,随后取结果时永久堵死主线程。 代价是失去批量试解密的摊销优化。用 `syncPeek()` 的 `remainingBlocks` 画进度条。 - `syncPrepare()` 要下载各池的全部子树根。宿主应给它独立的「准备中」状态, 主网子树数量比 testnet 多得多。 diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs index c5775da87..b4b9320f1 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs @@ -267,7 +267,7 @@ pub fn account_by_ufvk(ufvk: String) -> Result { /// Per-account sync status, derived from the account birthday and the database's remaining scan ranges. /// /// Global progress misleads in a shared database: adding an account makes all accounts look unsynced. -/// The official schema has no per-account cursor and is not changed for this (see D15); this is read-only. +/// The official schema has no per-account cursor and is not changed for this; this is read-only. /// /// Returns block heights, not a percentage: the upstream progress ratio is over notes in a moving /// window and never reaches 100%. diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs index 3dafa95e9..372d1d2a3 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs @@ -316,7 +316,7 @@ fn build_proposal( let spend_policy = { use zcash_client_backend::data_api::wallet::input_selection::SpendPolicy; // Not SpendPolicy::default(): it allows Sapling. See SendPolicy::spend_source. - // Shielded pools are never combined (docs/08), and the current pool is defined + // Shielded pools are never combined, and the current pool is defined // only by the host (ZCASH_CURRENT_SHIELDED_POOL): no default here, missing is rejected. let pool = policy.spend_source.ok_or_else(|| { RuntimeError::with( diff --git a/chain-runtimes/zcash/docs/decisions.md b/chain-runtimes/zcash/docs/decisions.md deleted file mode 100644 index 791214950..000000000 --- a/chain-runtimes/zcash/docs/decisions.md +++ /dev/null @@ -1,408 +0,0 @@ -# 设计决策与已排除的方案 - -记录「为什么这样」以及「哪些路走过发现不通」,避免以后重走。 - ---- - -## D1 — 存储层用 `zcash_client_sqlite`,不用 `zcash_client_memory` - -**决定**:存储后端使用 crates.io 上未修改的 `zcash_client_sqlite`。 - -**依据**: - -| | `zcash_client_memory` | `zcash_client_sqlite` | -|---|---|---| -| 发布到 crates.io | 从未 | 是,63 个正式版 | -| 所在仓库 | 已移出 librustzcash 主仓库 | 就在 librustzcash 里 | -| 发版节奏 | 独立 | 与 `zcash_client_backend` 同日发版 | -| 生产使用 | 无 | 官方 Android/iOS SDK、zallet,135 个 Cargo.toml 依赖 | -| 我们的改动量 | vendor 11,122 行,27 个文件改了 22 个 | 1 行 Cargo.toml | - -关键点:`zcash_client_sqlite` 与 `zcash_client_backend` **同日发版** -(2026-08-19 / 06-03 / 04-28 / 03-10 四次全对得上)。采用它不新增升级跑步机 —— -我们已经在这趟车上,只是把 storage 层的移植工作从自己这边转给 ECC。 - -**推论**:旧实现里为 memory 后端做的那些修复**应当丢弃,而非迁移**。原因是那些 bug -本就是我们手工打补丁打出来的;上游文档记载,它们正是拿 `zcash_client_sqlite` -当参考实现对 diff 找出来的。具体地: - -- 输入锁 —— `zcash_client_sqlite` 有 `src/wallet/locking.rs`,1,319 行第一方实现, - 带 Sapling / Orchard 双池测试。我们手写的 192 行该丢。 -- Ironwood 适配 —— sqlite 有十几个 ironwood migration 与完整迁池套件,第一方维护。 -- 手动序列化 —— SQLite 自己按页管持久化,整块不需要。 - ---- - -## D2 — 浏览器存储:OPFS SAH-pool(取代早期的 IndexedDB VFS) - -**决定**:所有 App 端使用 `sqlite-wasm-vfs` 的 OPFS SAH-pool,并施加 -`patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch`(连接锁、日志删除持久化、句柄清理、 -元数据失败后停止 I/O)。早期使用的 `relaxed_idb`(IndexedDB)已不再使用。 - -**依据**:VFS 只有少数几个方法,现成实现已经处理了同步/异步这个真正困难的部分; -持久化语义上的缺口用可审计的补丁补上,而不是自己重写一个 VFS。 - -**留给未来的口子**:需要加密、或移动端桥到原生存储时,自己实现 VFS 是直接的路径。 - ---- - -## 已排除的方案 - -### ✗ 升 `rusqlite` 到 0.40 用 `ffi-sqlite-wasm-rs` feature - -`zcash_client_sqlite 0.22` 依赖 `rusqlite ^0.37`。强升 0.40 产生 **83 个编译错误** -(`u64: FromSql` 等 API 破坏),且 `schemerz-rusqlite` 最高只有 `0.370.0`, -没有 0.40 对应版本 —— 要连带 fork 第二个 crate。 - -### ✗ 换用 turso(纯 Rust 的 SQLite 实现) - -可行但不必要。turso 没有 rusqlite 兼容层,而 `zcash_client_sqlite` 有约 1,240 处 -rusqlite 调用(`execute` 335、`query_row` 205、`prepare` 139+84、params 宏 751 等), -需要写一整层 shim;且它仍是 `0.8.0-pre`,未到 1.0。 - -### ✗ 自己把 SQLite 的 C 源码编到 wasm - -不需要。`sqlite-wasm-rs` 已提供预编译产物。自行编译还要处理 wasm sysroot -(`stdio.h` 缺失),得不偿失。expo-sqlite 的做法也印证了这一点 —— 它给 Web 端 -直接 vendor 了一个编好的 624 KB wasm,不在用户机器上编 C。 - -### ✗ 靠 wasm 符号差分判断某个 Rust 修复是否包含在内 - -实测无效:`get_legacy_transparent_address`、`get_transparent_address_metadata`、 -`AddressNotRecognized`、`transparent_receivers`、`ironwood` 这些探针在不同构建里 -出现次数完全一致,区分不出来。判断版本要靠版本号与字节数,不要靠符号。 - ---- - -## 构建环境的坑 - -**Apple clang 不支持 wasm32**,会报 -`No available targets are compatible with triple wasm32-unknown-unknown`。 -必须用 Homebrew LLVM(`/opt/homebrew/opt/llvm/bin/clang`)。 -`secp256k1-sys` 自带 wasm sysroot,只是需要一个能产 wasm 的 clang。 -`scripts/build-wasm.sh` 会自动探测并给出可读的报错。 - -**`getrandom` 0.4 在 wasm32-unknown-unknown 上必须显式选后端**, -否则编译期直接失败。已在 `.cargo/config.toml` 里配好 -`--cfg getrandom_backend="wasm_js"`。 - -**`rand` 版本必须跟 `zcash_client_sqlite` 对齐到 0.8 / `rand_chacha` 0.3** -(即 `rand_core` 0.6 那条线)。用 0.9 会因为 `RngCore` trait 不是同一个而 -无法满足 `init_wallet_db` 的泛型约束,报错信息不直观。 - ---- - -## 运行期发现(2026-08-22 实测) - -### lightwalletd 端点必须支持 gRPC-web + CORS - -浏览器里跑的是 gRPC-web,不是原生 gRPC,所以端点必须: - -1. 接受 `content-type: application/grpc-web+proto` -2. 对 OPTIONS 预检返回 CORS 头(`access-control-allow-{origin,methods,headers}`) - -实测: - -| 端点 | gRPC-web + CORS | -|---|---| -| `zcash-mainnet.chainsafe.dev` | ✅ | -| `zcash-testnet.chainsafe.dev` | ✅ | -| `testnet.zec.rocks` | ❌ OPTIONS 返回 404 | -| `mainnet.zec.rocks` | ❌ 连不上 | - -不支持时浏览器侧的报错是 `TypeError: Failed to fetch` —— 这个信息**不会**告诉你是 CORS 问题, -排查时先用 curl 打一次 OPTIONS 预检确认。 - -因此本 runtime **不硬编码任何端点**,由宿主通过 `setLightwalletdUrl()` 注入; -换端点时必须先验证 gRPC-web 支持。 - ---- - -## D3 — 移动端原生:分叉面有多大(实测) - -> 已被取代:移动端改为在 WebEmbed Worker 中运行同一份 WASM(见 README), -> 不维护原生绑定。以下保留当时的测算,供将来重新评估。 - -担心「维护多套代码」是合理的,所以先量。当前 `crates/zcash-runtime/src` 的构成: - -| | 行数 | 说明 | -|---|---|---| -| **全平台共享** | **662** | `wallet` / `account` / `storage` / `blockcache` / `clock` / `error`,wasm32 与 aarch64-apple-ios 均已编译通过 | -| wasm 专属 | 361 | `bindgen` 177、`runtime` 85、`network` 61、`sync` 38 | - -wasm 专属那 361 行里,真正**必须写第二份**的只有绑定层: - -- `bindgen.rs`(177 行)—— wasm-bindgen 对 JS,移动端要 JNI / Swift 的等价物。 -- `network.rs`(61 行)—— 只是把 gRPC-web transport 换成 tonic 原生 transport, - 逻辑与 `LightClient` 签名都不变,是一个 cfg 分支。 -- `sync.rs` / `runtime.rs` —— 现在因为依赖 `network` 才一起 cfg, - 本身没有平台特异性,接上原生 transport 后可直接共享。 - -**结论:第二份大约 180–250 行,不是「多套代码」。** - -可以进一步降低:**UniFFI**(0.32.0,1100 万下载,活跃)能从一份 Rust 定义同时生成 -Kotlin 与 Swift,把「JNI + Swift 两套」压成一套。注意 `equilibriumco/uniffi-zcash-lib` -(把 librustzcash 做 UniFFI 封装的现成项目)最后更新在 2024-08,**不要直接依赖**, -但它证明这条路可行。 - -### 但有三个真实成本,不要低估 - -1. **构建矩阵变大**:wasm-pack 之外多出 4 个移动架构组合(arm64/x86_64 × iOS/Android), - CI 时长与产物管理都变复杂。 -2. **调试变难**:移动端原生出问题,没有浏览器 devtools 可用。 -3. **发布节奏耦合**:Rust 改一次,移动端就要重新出包、过应用商店。 - -第 3 条最实在,也直接决定了边界该怎么划:**放进 Rust 的逻辑越少,移动端被迫发版的频率越低。** -这正是「调度、birthday、进度、重试放 TS」这条原则的现实价值 —— 它不只是开发体验问题。 - -### 建议:分阶段,现在不要做 - -先把 Web / Desktop 这条线跑通并稳定,移动端维持 keys-only(与现状一致,不构成倒退)。 -等 Rust 侧的接口经过实战、改动频率降下来,再上移动端原生 —— 那时候第二套绑定的 -维护成本才是可预测的,而不是在接口还在变的时候就把它复制一份。 - ---- - -## D4 — 不拆第三个包(实测后的结论) - -考虑过把 PCZT 的构造与证明拆成独立包,让日常「扫链 + 看余额」不背证明电路的体积。 - -**实测代价**:去掉全部 PCZT 相关代码后 wasm 从 6.73 MB 降到 **4.70 MB**, -即证明电路(`orchard/circuit` → halo2)约值 **1.6–2.0 MB**。 - -**但拆不了,原因是数据库**: - -构造 PCZT 需要钱包数据库(选币、witness、anchor),所以「构造 + 证明」包必须 -自带完整的存储栈。那就意味着两个 wasm 模块各自持有一个 SQLite 实例, -同时读写同一份数据库 —— 而存储池只允许单连接独占。并发写同一个库会损坏数据。 - -省 1.6 MB 不值得换来数据损坏风险。 - -**替代的省体积方向**: - -1. `wasm-opt -Oz`(已采用)。 -2. 不含数据库的证明入口:`pcztProveAtHeight` 只吃 PCZT 字节、吐 PCZT 字节, - 不碰存储,因此没有多连接问题(已提供,供无钱包路径使用)。 -3. 检查是否有未使用的 feature 还在拉代码。 - -注意方案 2 与被否掉的方案不同:分界线在**是否需要数据库**, -不在「是不是 PCZT 相关」。`pcztCreate` 必须和钱包同包,证明不必。 - ---- - -## D5 — 不用 `sync::run`,自己驱动有界扫描 - -**症状**:`syncAdvance(batchSize)` 在 testnet 上一次调用 900 秒未返回。 - -**根因**:`zcash_client_backend::sync::run` 内部是 - -```rust -update_subtree_roots(client, db_data).await?; -while running(client, params, db_cache, db_data, batch_size).await? {} -``` - -`batch_size` 只控制**单批区块数**,不控制批数 —— 这个函数的语义是「同步到底」, -不是「推进一步」。调用方无法中断、无法看进度、无法在中途让出主线程。 - -我们原先的接口文档写着「有界推进」,实现却是跑到尾。**是接口契约与实现不符, -不是性能问题。** - -**修法**:自己驱动上游的公开 API,拆成两段: - -- `syncPrepare()` —— 一次性准备:下载三个池的子树根 + 更新链尖。 - 这是首次同步最慢的一步,且与 batchSize 无关。单独暴露,宿主才能给出 - 「正在准备」的独立进度,而不是干等一个不返回的调用。 -- `syncStep(batchSize, maxBatches, priority, activeUfvksJson)` —— 最多扫 - `maxBatches` 批就返回,且只为宿主显式传入的 UFVK 试解密; - 空集合报 `NO_ACTIVE_ACCOUNTS`,绝不回退到数据库中全部账户。 - 带 `{ done, batchesDone, blocksScanned, remainingBlocks, remainingRanges }`。 - **永远不自己循环到完成。** -- `queueRescanFrom(fromHeight)` —— 非破坏性地把 - `[fromHeight, chainTip]` 重新排为 historic 扫描。宿主在恢复曾暂停的 UFVK 时调用, - 因为上游 scan queue 是 network wallet 全局的,其他 active UFVK 可能已经把它推进到链尖。 - -Sapling 仍保留上游 schema、承诺树和 subtree root 兼容逻辑,但不会进入 ownership -scanning keys。Runtime 用官方 ZIP-316 API 临时构造只含 Orchard component 的 UFVK, -再交给官方 scanner;没有 fork 或修改 `zcash_client_backend`。 - -上游的 `download_subtree_roots` / `download_blocks` / `download_chain_state` / -`scan_blocks` 全是私有函数,所以这四段逻辑在 `sync.rs` 里重新实现了一遍 —— -但用的都是公开 API(`get_subtree_roots` / `get_block_range` / `get_tree_state` / -`scan_cached_blocks` / `put_*_subtree_roots` / `suggest_scan_ranges`), -没有复制任何协议逻辑。 - -**教训**:上游函数名叫 `run` 而不是 `step`,语义在文档里也写了。 -接口契约要以**实测行为**为准,不能以我们希望它是什么为准 —— -这个 bug 在写文档时就该被发现,而不是等到 900 秒超时。 - ---- - -## D6 — 所有网络调用必须有超时 - -**为什么是硬性要求,不是「最好有」**: - -wasm 里挂死的调用**宿主无法取消** —— 没有线程可以中断,Promise 也不会自己 reject。 -一个不返回的 gRPC 调用会让整个钱包永久卡住,而且不产生任何错误信息, -连日志都没有。用户看到的是「转圈永远不停」。 - -实测踩到过:`syncStep` 只需要扫 201 个区块(`syncPeek` 0ms 就返回了区间 -`{start: 4292265, end: 4292466, priority: ChainTip}`),却几分钟不返回。 -区间这么小说明不是计算量问题,是某个网络调用挂住了。 - -**做法**:`network::with_timeout(fut, ms, operation)` 用 `gloo-timers` 的 -`TimeoutFuture` 与目标 future 竞速,超时抛 -`NETWORK_ERROR` 且 `params = { operation, timeoutMs }`。 -`operation` 是稳定标识,宿主和排查者都能一眼看出是哪一步。 - -默认 30 秒(`DEFAULT_TIMEOUT_MS`)—— 单次 gRPC 调用超过这个时长基本可判定为挂死。 - -**顺带的价值**:超时把「挂死」变成「可定位的错误」。上面那个卡住的问题, -加上超时后一次运行就能指出是 `getBlockRange` 还是 `getTreeState`, -不用再靠猜和二分。 - -## 排查这类问题的手段:`syncPeek()` - -`syncPeek()` 只读钱包建议的扫描区间,**不发任何网络请求**,返回 -`{ ranges: [{ start, end, len, priority }], totalBlocks }`。 - -它同时是宿主的进度条数据源,和「同步卡住时先确认它想扫哪一段」的诊断入口 —— -先用它排除「区间异常巨大」这种可能,再去查网络层,比直接猜快得多。 - ---- - -## D7 — 「小批量能扫、大批量挂死」:区块缓存的可重入死锁 - -### 症状 - -`syncStep(10, 1)` 正常返回;`syncStep(25, 1)` 永久不返回,页面无响应、无错误, -**连 30 秒超时都不触发**。超时不触发说明阻塞发生在**同步代码**里 —— JS 事件循环被占住, -定时器没机会开火;如果是 await 的网络调用挂住,超时会正常生效。 - -### 根因 - -`MemoryBlockCache::with_blocks` 原本在**整个遍历期间持有 `Mutex`**,并在持锁状态下调用 -回调 —— 而回调会写钱包库,上游可能在那条路径上再次读取本缓存。`std::sync::Mutex` -不可重入,wasm 单线程下同一线程二次加锁就是永久死锁。 - -**修法**:持锁时只把区块 `clone` 收集出来,**释放锁之后**才执行回调。 - -### 教训 - -- 在持锁状态下调用外部回调,等于把锁的作用域交给了不受控的代码。 -- 「小批量能跑、大批量挂死」这种陡峭悬崖几乎总是状态机或锁的问题,不是性能问题。 -- 排查工具:`syncPeek()`(只读待扫区间,不发网络)和 `syncProbeDownload(n)` - (只下载不扫描)能快速把问题切分到网络或扫描一侧。 - ---- - -## D7 补充 — 原生复现证明问题在 wasm 侧,不在扫描逻辑 - -浏览器里 `batchSize ≥ 25` 挂死。为了排除「上游扫描逻辑本身有问题」, -给网络层补了**原生 transport**(tonic + TLS),在本机跑完全相同的流程: - -``` -batch=25 耗时 513ms blocksScanned=25 remainingBlocks=176 -batch=100 耗时 517ms blocksScanned=100 remainingBlocks=101 -``` - -**原生环境完全正常,而且 25 与 100 耗时几乎相同**(513 vs 517ms)—— -说明扫描本身根本不是瓶颈,耗时由固定开销主导。 - -结论:**症结在 wasm 侧**。 - -> 注:真正的根因见 D8。这里保留「原生对照」这个方法;对照时两端必须连同一个服务器、 -> 覆盖同一段高度,否则结论无效。 - -### 顺带的收获 - -这次为复现而加的原生 transport **本身就是移动端要用的东西** -(见 D3 关于移动端原生 runtime 的讨论)。现在 `network` 与 `sync` 模块 -已是全平台的,只有 `runtime`(thread_local 状态)仍限 wasm。 - -`crates/zcash-runtime/tests/scan_repro.rs` 保留为可复现的回归用例, -默认 `#[ignore]`(需要联网)。跑法: - -```bash -cargo test -p onekey-zcash-runtime --test scan_repro -- --ignored --nocapture -``` - -注意端点不通用:浏览器要 gRPC-web + CORS(`zcash-*.chainsafe.dev`), -原生要真 gRPC(`testnet.zec.rocks:443`)。两边端点互不相通, -配错的表现都是「连不上」但原因完全不同。 - ---- - -## D8 — 扫描不走上游 `scan_cached_blocks`:wasm 上它会永久堵死主线程 - -### 症状 - -浏览器里扫描随机卡死:页面无响应、无报错、超时定时器不触发,连 Chrome -DevTools 协议都服务不了(`Profiler.enable` 超时)。原生跑同一段完全正常。 - -### 根因 - -`zcash_client_backend` 把试解密交给批量 runner,而 `Tasks` trait 的**默认** -`run_task` 是: - -```rust -fn run_task(&self, item: Item) { - let task = self.add_task(item); - rayon::spawn_fifo(|| task.run()); -} -``` - -`scan_cached_blocks` 用的 `Tasks for ()` 只覆写了 `add_task`,**没有覆写 -`run_task`**,所以仍然走 rayon。wasm32-unknown-unknown 是单线程、无 atomics, -rayon 全局线程池没有任何工作线程 —— 任务被排进队列后永远不会执行。 - -随后第二遍扫描调 `BatchReceiver::into_results()`,它的文档写得很直白: -「Blocks until the results of the batch are ready」。结果永远不来, -主线程就永久阻塞在通道上。 - -### 为什么表现得像「批量大到某个阈值就挂」 - -空区块不产生批次。测试用的 testnet 区间里绝大多数是空块(93 字节 / 0 交易), -只有 4292845 一个区块有内容(6 sapling spend / 2 output / 2 ironwood action)。 -批量越大越容易把它圈进去,于是看起来像「批量超过某个值就挂」—— -实际与批量毫无关系,只与**这一批里有没有含屏蔽输出的区块**有关。 - -### 解法 - -用公开 API `scanning::scan_block` 自己写扫描循环(`sync::scan_blocks_inline`)。 -`scan_block` 内部等价于 `scan_block_with_runners(..., runners = None)`, -试解密就地完成,不碰 rayon。 - -- **不需要 fork 上游**:`scan_block` / `ScanningKeys::from_account_ufvks` / - `Nullifiers::unspent` / `ScannedBlock::to_block_metadata` 全是公开项。 -- 代价:失去批量试解密的摊销优化(批量求逆)。原生实测扫描阶段耗时: - 1000 块 45ms → 88ms,约 1.4–2 倍。这段 testnet 区块很空, - 主网稠密区块上的差距会更大,届时可重新评估。 -- 备选方案(未采用):vendor `zcash_client_backend` 并把 `run_task` 在 wasm 上 - 改成就地执行 —— 能保住批量优化,但要多 fork 一个大 crate。 - rayon 在整个依赖图里只有 `zcash_client_backend` 一个使用者, - 所以「patch rayon 成单线程 shim」也可行,同样因为增加 fork 面而未选。 - -这是上游在单线程目标上的真实缺陷,值得反馈给 librustzcash。 - -### 实测(修复后,持久化 IndexedDB VFS,testnet) - -| batchSize | 总耗时 | 下载 | treestate | 扫描 | -|---|---|---|---|---| -| 10 | 853ms | 523 | 255 | 70 | -| 25 | 533ms | 258 | 257 | 17 | -| 60 | 549ms | 279 | 257 | 12 | -| 100 | 567ms | 287 | 255 | 24 | -| 200 | 633ms | 351 | 254 | 26 | -| 500 | 614ms | 333 | 255 | 25(203 块,追平) | - -扫描本身很便宜,耗时基本全在两次网络往返上。宿主要提速应该减少往返次数, -而不是调批量。 - -### 教训 - -**对照实验要控住所有变量。** 早期「原生正常」的结论一度无效:两端连的服务器不同, -原生跑的高度区间也没覆盖到出问题的区块。`network::block_summary`(返回编码长度 + -校验和)用来确认两端拿到的字节完全一致。 - -**证据通道要与被测对象解耦。** 页面自己回传日志时,「被测代码卡住」和「回传通道自己死了」 -在日志上完全一样;从 DevTools 协议直接读 console 才能拿到真实的停止位置。 From 72221e4f8c908db3dfefce417faa209dd53e1e07 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 19:05:37 +0800 Subject: [PATCH 21/97] docs: drop design history and release-candidate checklists from chain runtime docs Also move the one-off scan measurement script out of the repo and update the Monero wasm smoke test for review-bound signing. --- chain-runtimes/monero/README.md | 17 +------- chain-runtimes/monero/scripts/measure-scan.js | 40 ------------------- chain-runtimes/monero/scripts/smoke.js | 28 ++++++++----- chain-runtimes/zcash/README.md | 22 +--------- chain-runtimes/zcash/RELEASING.md | 18 ++------- 5 files changed, 24 insertions(+), 101 deletions(-) delete mode 100755 chain-runtimes/monero/scripts/measure-scan.js diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md index 40de30854..a2a35bc31 100644 --- a/chain-runtimes/monero/README.md +++ b/chain-runtimes/monero/README.md @@ -3,22 +3,6 @@ monero-oxide 之上的钱包状态层。**它提供密码学、扫描器与交易构造;存储这一层 是我们自己写的,因为上游不提供。** -## 为什么是这条路 - -三条路都量过: - -| | 我们要写 | 出厂体积 | 插件端 | 落盘 | -|---|---|---|---|---| -| monero-ts(wallet2 编 wasm) | 最少 | 6.2 MB JS | 可以 | ✗ 整块序列化 | -| wallet2 + monero_c | 1.5–2.5k 行 | — | **不行**(零 wasm 支持) | ✓ | -| **monero-oxide + SQLite** | 6–8.5k 行 | **3.37 MB / gzip 1.06 MB** | 可以 | **✓ 增量写** | - -决定性的是最后一列。monero-ts 把整个钱包放在 wasm 内存里,持久化只能 -`getData()` 整块序列化再写出去 —— 历史越长每次保存越贵,写一半崩了丢全部。 -这里是增量写 + 事务,和 Zcash runtime 同一个模型。 - -代价写在明面上:多出来的六到八千行**正确性归我们自己**,上游不兜底。 - ## 结构 ``` @@ -66,6 +50,7 @@ bindgen.rs wasm 边界 ./scripts/build-wasm.sh # release 到 pkg/ cargo test --workspace # 原生测试 cargo check --workspace --target wasm32-unknown-unknown +./scripts/build-node-pkg.sh && node scripts/smoke.js # wasm 端到端冒烟 ``` **macOS 上必须有 llvm-ar**(`brew install llvm`)。系统自带的 `/usr/bin/ar` diff --git a/chain-runtimes/monero/scripts/measure-scan.js b/chain-runtimes/monero/scripts/measure-scan.js deleted file mode 100755 index 888ddfbab..000000000 --- a/chain-runtimes/monero/scripts/measure-scan.js +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env node -/** - * Split sync time into block fetching and scanning, since an end-to-end - * blocks/sec figure cannot tell network latency from decryption cost. - * Measured (Mac, public node, one view key): fetch 99.6%, scan 0.4%, - * scan-only 153 blocks/sec. - * - * ./scripts/build-node-pkg.sh - * XMR_NODE=http://your-node:18081 node scripts/measure-scan.js - */ -const path = require('path'); -const pkg = process.env.XMR_NODE_PKG || path.join(__dirname, '..', 'pkg-node'); -const rt = require(path.join(pkg, 'onekey_monero_runtime.js')); - -(async () => { - if (!process.env.XMR_NODE) { - console.error('Set XMR_NODE to a monerod RPC URL.'); - process.exit(1); - } - await rt.setNodeUrl(process.env.XMR_NODE); - const tip = JSON.parse(await rt.chainTip()); - const key = '0'.repeat(63) + '7'; - const a = JSON.parse(rt.deriveAccount('mainnet', key)); - rt.openWallet(':memory:', 'mainnet'); - const added = JSON.parse(rt.addAccount('m', a.spendPublicKeyHex, a.viewPrivateKeyHex, BigInt(tip.height - 40))); - const id = BigInt(added.accountId); - rt.updateChainTip(id, BigInt(tip.height)); - - let dl = 0, sc = 0, n = 0; - for (let i = 0; i < 4; i += 1) { - const p = JSON.parse(await rt.syncStep(id, 10n)); - if (!p.blocksScanned) break; - dl += p.msDownload; sc += p.msScan; n += p.blocksScanned; - console.log(` ${p.blocksScanned} blocks: fetch ${p.msDownload}ms / scan ${p.msScan}ms`); - if (p.done) break; - } - console.log(`\ntotal ${n} blocks: fetch ${dl}ms (${(dl*100/(dl+sc)).toFixed(0)}%) / scan ${sc}ms (${(sc*100/(dl+sc)).toFixed(0)}%)`); - console.log(`scan-only rate: ${(n/(sc/1000)).toFixed(0)} blocks/sec`); - console.log(`end-to-end rate: ${(n/((dl+sc)/1000)).toFixed(1)} blocks/sec`); -})(); diff --git a/chain-runtimes/monero/scripts/smoke.js b/chain-runtimes/monero/scripts/smoke.js index 981e4c79c..9c087be8d 100755 --- a/chain-runtimes/monero/scripts/smoke.js +++ b/chain-runtimes/monero/scripts/smoke.js @@ -3,7 +3,7 @@ * End-to-end smoke test against the real wasm build: derive -> open DB -> * add account -> subaddress -> balance -> scan queue -> coin selection. * - * Offline by default; set XMR_NODE_URL to also run the node checks. + * Offline by default; set XMR_NODE to also run the node checks. * * ./scripts/build-node-pkg.sh && node scripts/smoke.js */ @@ -61,24 +61,34 @@ check('identity stored', diag.counts.identities, 1); check('subaddress stored', diag.counts.subaddresses, 1); // Signing is pure computation. Bad input must be rejected, never passed on to broadcast. -for (const [label, hex, reason] of [ - ['non-hex input', 'zz', 'notHex'], - ['an unsignable transaction', '00010203', 'notASignableTransaction'], +const review = JSON.stringify({ + network: 'mainnet', + fromAddress: a.primaryAddress, + toAddress: a.primaryAddress, + amountAtomic: '1000', + feeAtomic: '0', + changeAtomic: '0', + isMaxSend: false, +}); +for (const [label, hex, req, field] of [ + ['non-hex input', 'zz', review, 'signableHex'], + ['an unsignable transaction', '00010203', review, 'signableHex'], + ['a malformed review', '00010203', '{}', 'reviewRequest'], ]) { try { - rt.signTransaction(hex, '00'.repeat(32)); + rt.signTransaction(hex, '00'.repeat(32), req); check(`signing rejects ${label}`, 'succeeded', 'failed'); } catch (e) { const err = JSON.parse(e.message ?? e); - check(`signing rejects ${label}`, err.params.reason, reason); + check(`signing rejects ${label}`, err.params.field, field); } } -// Node checks; skipped (and reported as skipped) without XMR_NODE_URL. +// Node checks; skipped (and reported as skipped) without XMR_NODE. async function online() { - const url = process.env.XMR_NODE_URL; + const url = process.env.XMR_NODE; if (!url) { - console.log('\n(skipping node checks: XMR_NODE_URL not set)'); + console.log('\n(skipping node checks: XMR_NODE not set)'); return; } console.log(`\nnode checks against ${url}`); diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md index a92a8ed45..d62657156 100644 --- a/chain-runtimes/zcash/README.md +++ b/chain-runtimes/zcash/README.md @@ -10,17 +10,6 @@ --- -## 这个项目为什么存在 - -此前的实现建在 `ChainSafe/WebZjs` 的 fork 上,使用 `zcash_client_memory` 作为存储后端。 -那个 crate 从未发布到 crates.io,维持它需要 vendor 大量代码,并在每次 -`zcash_client_backend` 升版时自行重迁。 - -本项目改用 `zcash_client_sqlite`:它就在 librustzcash 仓库里,与 `zcash_client_backend` -**同日发版**,也是官方 Android / iOS SDK 与 `zallet` 的存储层。 - ---- - ## 同一套 Rust / WASM,所有 App 端共用 `onekey-zcash-keys` 负责派生和签名,不依赖 SQLite、网络、扫描器或 prover。 @@ -235,16 +224,7 @@ scripts/vendor-deps.sh 校验官方发布版并施加已记录的 patch scripts/build-wasm.sh 构建 ``` ---- - -## 参考实现(读,不依赖) - -- `ChainSafe/WebZjs` —— grpc-web 接线、wasm 线程池初始化的经验。 - 注意 `tonic-web-wasm-client` 必须 ≥ 0.9.1(0.8.0 会丢 gRPC trailer)。 -- `zcash/zcash-android-wallet-sdk` 的 `backend-lib/` —— ECC 的 Rust FFI 层, - 是「该暴露什么、按什么粒度」的参照。 - -### Stateless transparent funding of Unified recipients +## Stateless transparent funding of Unified recipients `transparentTxQuote` accepts mainnet t1/t3/tex recipients and Unified recipients with an Orchard receiver (an Ironwood output after NU6.3). It uses only the host-supplied diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md index 7ad585299..d7fda3db6 100644 --- a/chain-runtimes/zcash/RELEASING.md +++ b/chain-runtimes/zcash/RELEASING.md @@ -10,8 +10,8 @@ it, and wasm-pack generates the npm versions from those crates. Update the three workspace entries in `Cargo.lock` with `cargo check --workspace --offline` and review the lockfile diff; dependency upgrades are a separate change. -The first candidate is `0.1.0-rc.1` on the npm `rc` tag. After acceptance, release -`0.1.0` on `latest`; subsequent compatible fixes can use `0.1.1`. Runtime and keys +Release candidates use `X.Y.Z-rc.N` on the npm `rc` tag; final releases use +`latest`. Runtime and keys always share a version and source commit. The benchmark is shipped as a runtime subdirectory to preserve the App developer tools' existing import path; it is not a third published package and production App bundles still exclude it. @@ -51,21 +51,9 @@ other fails, do not consume the version until both exist. Restore the exact verified artifact from that workflow run and publish only the missing package; never overwrite an existing version or rebuild different bytes under that version. -## App cutover and acceptance +## App cutover Until the pair exists on npm, keep the App's local `portal:` dependencies. Once both packages have been published, replace both entries in `packages/core/package.json` with the same exact version and update `yarn.lock` through the App repository's dependency workflow. Do not use a version range. - -Validate the actual packed/published files, rather than the larger portal folder: - -- The worker can resolve JS, types and WASM for both packages, and the developer - storage benchmark import resolves from the runtime package. -- Desktop and Extension: start, scan, restart and restore progress. -- iOS and Android: foreground scan, pause/resume and relaunch recovery. -- Exercise the supported receive/send paths, including transparent shielding and - interrupted broadcast recovery, using the same candidate artifacts. - -Native Rust tests do not replace wasm32 OPFS durability tests or four-platform -acceptance. The candidate's mainnet/real-funds scope must be recorded explicitly. From 8e0d4c8259c104b47aad750705f53265251ef1d6 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 19:16:57 +0800 Subject: [PATCH 22/97] docs: rewrite chain runtime READMEs in English against the current API List every export, add the hardware transparent signing path, the storage restart signal and FINALIZE_OUTCOME_UNKNOWN handling, and state the Monero send order and host contract. --- chain-runtimes/monero/README.md | 146 ++++--- chain-runtimes/zcash/README.md | 371 +++++++++--------- chain-runtimes/zcash/RELEASING.md | 7 +- .../zcash-keys-runtime/TRANSPARENT_TX_API.md | 7 + 4 files changed, 290 insertions(+), 241 deletions(-) diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md index a2a35bc31..60e971ad1 100644 --- a/chain-runtimes/monero/README.md +++ b/chain-runtimes/monero/README.md @@ -1,70 +1,114 @@ # OneKey Monero Runtime -monero-oxide 之上的钱包状态层。**它提供密码学、扫描器与交易构造;存储这一层 -是我们自己写的,因为上游不提供。** +Wallet state layer over monero-oxide. monero-oxide provides cryptography, scanning +and transaction construction; this crate adds the storage it lacks: SQLite with +incremental, transactional writes. -## 结构 +## Build -``` -error.rs 错误码契约(跨 wasm 边界稳定) -storage.rs SQLite 连接、OPFS VFS、落盘屏障 -schema.rs 表结构与迁移 -keys.rs 观察密钥对、地址、子地址派生 -wallet.rs 库句柄、身份管理、子地址注册表 -scan.rs 扫描循环 + 三道校验 + 落库 -sync.rs 有界推进编排(拉块 → 扫描 → 记进度) -query.rs 余额、历史、可花输出 -spend.rs key image 导入、选币、预留、构造、签名、广播 -review.rs 签名前按用户确认的请求校验收款方、金额、手续费与找零 -pool.rs 自己广播、尚未上链的交易的存活检查 -network.rs monerod 传输(浏览器 fetch / 原生 reqwest) -runtime.rs 跨调用会话状态与并发防线 -bindgen.rs wasm 边界 +```bash +cargo test --workspace # native tests +cargo check --workspace --target wasm32-unknown-unknown +./scripts/build-wasm.sh # release build to pkg/ +./scripts/build-node-pkg.sh && node scripts/smoke.js # wasm end-to-end smoke test ``` -## 必须知道的事 +`smoke.js` runs offline; set `XMR_NODE=` to add node checks. +Builds need the `wasm-bindgen-cli` version pinned in `Cargo.lock`. -**一、观察钱包检测不到花费。** Monero 的花费检测需要 key image,而 key image -需要花费私钥。这是协议性质不是实现取舍。所以宿主必须在解锁时调一次 -`importKeyImages`,否则余额会**偏高**(已花的看起来还在)。余额查询里的 -`unverifiableAtomic` 就是这部分的金额,宿主应当据此提示用户。 +**macOS needs `llvm-ar`** (`brew install llvm`). `/usr/bin/ar` cannot read wasm +objects and silently writes an empty archive; linking then fails with +`undefined symbol: sqlite3_*`. `cargo check` does not link, so it never shows this. +The archiver is set in `.cargo/config.toml`. -**二、节点声称的 RingCT 输出索引不可验证。** 上游文档明确要求客户端自己维护 -这个索引并比对,不一致应当断开。`scan.rs` 实现了这个独立推算,不一致时报 -`RINGCT_INDEX_MISMATCH`。索引错了的后果是构环时取错输出、交易被网络拒绝, -而且很难从现象反推。 +## Host contract -**三、调度归宿主。** `syncStep` 一次最多扫 `maxBlocks` 个块就返回,**永远不会 -自己循环到同步完成**。什么时候扫、扫多少、失败怎么退避全由宿主 TS 决定。 +1. **Import key images on unlock.** A view-only wallet cannot detect spends, so the + balance stays too high until `importKeyImages` is called. It covers only blocks + scanned afterwards; earlier spends need a rewind and rescan. `balance` reports the + unverified part as `unverifiableAtomic`. +2. **The node must be on the wallet's network.** The node's chain is identified by its + genesis block; a mismatch fails with `NODE_NETWORK_MISMATCH`. `chainTip` works + without an open wallet and returns `network`; compare it before picking a birthday. +3. **An `unknown` broadcast is not a failure.** The send is recorded and its inputs + marked spent before broadcasting; pool checks and scanning settle it. Never report + it as failed or prompt a resend. +4. **The host schedules sync.** `syncStep` scans at most `maxBlocks` and returns; it + never loops to completion. Timing, batch size and backoff belong to the host. +5. **Register subaddresses before use.** Funds to unregistered subaddresses go + undetected. -**四、节点必须和钱包在同一个网络上。** 连接时按创世块认出节点所在的链,钱包库与 -节点网络不一致时报 `NODE_NETWORK_MISMATCH`。`chainTip` 在开库前调用,返回里带 -`network`,宿主定 birthday 前须自行比对。 +The scanner derives RingCT output indexes itself and fails with +`RINGCT_INDEX_MISMATCH` when the node's claim differs. -**五、广播结局 `unknown` 不是失败。** 交易在广播前已记为在途、输入已标已花; -结局不确定时由在途检查或扫链判定。宿主不得据此提示失败、引导重发。 +## API -## 构建 +Values cross the boundary as strings, numbers, booleans, bytes or JSON strings. +Errors carry a stable `code` and structured `params`; user-facing text belongs to the host. -```bash -./scripts/build-wasm.sh # release 到 pkg/ -cargo test --workspace # 原生测试 -cargo check --workspace --target wasm32-unknown-unknown -./scripts/build-node-pkg.sh && node scripts/smoke.js # wasm 端到端冒烟 +``` +init() / dependencyVersions() +openWallet(dbName, network) / closeWallet() / deleteWallet(dbName) +setNodeUrl(url) / setRequestHandler(handler) no default node +chainTip() { height, network } + +deriveAccount(network, bip32PrivateKeyHex) / spendScalar(bip32PrivateKeyHex) +deriveSubaddress(network, spendPub, viewPriv, major, minor) +validateAddress(network, address) +addAccount(uuid, spendPub, viewPriv, birthday) / listAccounts() / removeAccount(uuid) +registerSubaddress(accountId, major, minor, label?) +importKeyImages(accountId, spendPrivateKeyHex) + +updateChainTip(accountId, tip) / syncStep(accountId, maxBlocks) / syncPeek(accountId) +rewindTo(accountId, height, tip) destructive +balance(accountId, chainTip?) / history(accountId, limit, offset) +transactionDetails(accountId, txid) + +prepareTransaction(accountId, recipientsJson, maxSend, reservationId, chainTip, priority) +verifyTransaction(signableHex, reviewJson) +markReservationSigned(reservationId, expectedInputs) +signTransaction(signableHex, spendPrivateKeyHex, reviewJson) +broadcastTransaction(accountId, rawHex, reservationId, chainTip, outgoingAtomic?, changeAtomic?) +releaseReservation(reservationId) +diagDatabase() ``` -**macOS 上必须有 llvm-ar**(`brew install llvm`)。系统自带的 `/usr/bin/ar` -读不懂 wasm 目标文件,会把编译好的 `.o` **静默**打成一个 96 字节的空归档, -链接期报一串 `undefined symbol: sqlite3_*`,而编译阶段不报任何错。归档器由 -`.cargo/config.toml` 指定。 +### Sending -排查提示:本机 clang 是能编 wasm32 的,别往编译器上查。 -另外 `cargo check` **不链接**,这个坑在 check 下完全看不见。 +``` +prepareTransaction select and reserve inputs, build; no spend key +verifyTransaction check recipient, amount, fee and change against the review +markReservationSigned claim the reserved inputs for this review +signTransaction verify again, then sign; no network, no DB +broadcastTransaction record, then broadcast → { txid, broadcast: accepted | unknown } +``` + +`BROADCAST_REJECTED` is thrown only when the node explicitly rejects a first +broadcast for a reason other than double spend; the record is then undone and the +inputs released. Unsigned reservations expire after 1 hour, signed ones after 24 +hours. Call `releaseReservation` when the user cancels. -## 与 Zcash runtime 的关系 +## Layout + +``` +error.rs error codes (stable across the wasm boundary) +storage.rs SQLite connection, OPFS VFS, durability barrier +schema.rs tables and migrations +keys.rs view keys, addresses, subaddress derivation +wallet.rs DB handle, identities, subaddress registry +scan.rs scan loop, output checks, persistence +sync.rs bounded sync (fetch → scan → record progress) +query.rs balance, history, spendable outputs +spend.rs key images, selection, reservation, build, sign, broadcast +review.rs pre-signing check of recipient, amount, fee and change +pool.rs liveness check of our unconfirmed sends +network.rs monerod transport and node network check +runtime.rs session state and concurrency guards +bindgen.rs wasm boundary +``` -两条链各自独立的工作区,没有代码依赖。`crates/monero-runtime/build.rs`(SQLite 的 -wasm 链接胶水,与链无关)与 Zcash 那边基本相同,改一边记得同步另一边。 +## Relation to the Zcash runtime -一个刻意的差异:`runtime.rs` 在这里**不加 wasm-only 门**,所以并发防线(BUSY 守卫、 -世代号)在原生 `cargo test` 里也能测。 +Separate workspaces with no code dependency. `crates/monero-runtime/build.rs` (wasm +SQLite link glue) mirrors the Zcash one; keep them in sync. Unlike Zcash, `runtime.rs` +is not wasm-only, so its concurrency guards are covered by native tests. diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md index d62657156..182cc6f3f 100644 --- a/chain-runtimes/zcash/README.md +++ b/chain-runtimes/zcash/README.md @@ -1,140 +1,160 @@ -> Build commands below run from this directory. Use Rust 1.93.0 (pinned in -> `rust-toolchain.toml`), Python 3.11+, LLVM/Clang, and wasm-pack 0.15.0. -> Install `wasm-bindgen-cli` at the `wasm-bindgen` version in `Cargo.lock` -> and provide `wasm-opt` (Binaryen), or reuse the matching wasm-pack tool cache. -> Builds use `--mode no-install` and never update `Cargo.lock`. - # OneKey Zcash Runtime -官方 `librustzcash` 之上的最薄 wasm 绑定层。**不依赖 WebZjs**。 - ---- - -## 同一套 Rust / WASM,所有 App 端共用 - -`onekey-zcash-keys` 负责派生和签名,不依赖 SQLite、网络、扫描器或 prover。 -`onekey-zcash-runtime` 负责钱包、扫描、SQLite 和 PCZT 证明。它们是按功能拆分的两个 -WASM 产物,不是按平台维护的两套实现;Desktop、Web、扩展和 iOS/Android 都使用它们。 -`zcash-storage-benchmark` 仅用于开发者合成数据测试。 - -所有 App 载体均在 DedicatedWorker 执行公共 TypeScript SDK 和 WASM。 -移动端由 WebEmbed 创建内联 Blob Worker;其他端创建 URL Worker。 -Rust native 构建保留用于测试和诊断,不作为 App 的另一套生产后端。 - -## 硬约束 - -1. **不 fork 任何 Zcash 存储实现。** 存储层来自 crates.io 上的 `zcash_client_sqlite`, - Rust 源码零改动;唯一改动是一处 Cargo.toml feature(下节)。 -2. **种子仅在授权的派生/签名调用中短暂传入 keys WASM。** Rust 清理秘密缓冲区; - JS 字符串及跨桥复制不能宣称可可靠擦除。扫描器持有 UFVK,不保存种子。 -3. **接口动词少、数据简单。** 只传 string / number / boolean / bytes / JSON 字符串, - 不把 Rust 对象句柄交给 JS 管生命周期。每次调用是一次完整往返。 +Thin wasm bindings over the official `librustzcash`, with `zcash_client_sqlite` as +the wallet store. Does not depend on WebZjs. -## 边界:什么在 Rust,什么在 TS +Two packages built from one source, used by every App platform (Desktop, Web, +Extension, iOS, Android): -| 留在 Rust(wasm) | 放在宿主 TS | -|---|---| -| 扫链的 trial decryption | 何时扫、扫哪段、扫多少(调度) | -| witness / 承诺树维护 | 账户与 birthday 管理 | -| 交易构造与选币(共识正确性) | 缓存与持久化策略 | -| 密钥派生与签名 | 进度展示、错误处理、重试 | -| 平台胶水(时钟、随机数、VFS) | 历史记录的展示模型 | - -判据是三条:**密钥安全、跨边界数据量、共识正确性**。三条都不沾的,就该在 TS。 +- `onekey-zcash-keys`: derivation, review checks and signing. No SQLite, network, + scanner or prover. +- `onekey-zcash-runtime`: wallet, scanning, SQLite and PCZT proving. ---- +Both run inside a DedicatedWorker (an inline Blob Worker from WebEmbed on mobile, a +URL Worker elsewhere). Native Rust builds are for tests and diagnostics only. +`zcash-storage-benchmark` is a developer tool for synthetic storage tests. -## Vendor 补丁 +## Build -`zcash_client_sqlite` 给 `rusqlite` 开了 `bundled` feature,它会在构建期用 cc 编译 SQLite -的 C 源码。`wasm32-unknown-unknown` 没有 libc sysroot,会停在 -`fatal error: 'stdio.h' file not found`。Cargo 的 feature 是并集语义,下游无法取消上游 -已启用的 feature,只能改它的 Cargo.toml。 +Run from this directory. Requires Rust 1.93.0 (pinned in `rust-toolchain.toml`), +Python 3.11+, LLVM/Clang with wasm32 support, wasm-pack 0.15.0, `wasm-bindgen-cli` +at the version in `Cargo.lock`, and `wasm-opt` (Binaryen). Builds use +`--mode no-install` and never update `Cargo.lock`. -处理方式是可审计的:`scripts/vendor-deps.sh` 下载官方发布版并施加 -`patches/manifest.json` 记录的补丁 —— `zcash_client_sqlite` 的 1 行 Cargo.toml 改动、 -`sqlite-wasm-vfs` 的 OPFS 持久化修复(连接锁、日志删除持久化、句柄清理和元数据失败后 -停止 I/O),以及 `tonic-web-wasm-client` 的宿主 fetch 注入。`scripts/prepare-vendor.py --offline` -根据校验过的官方归档与补丁重建并比较全部文件,拒绝未记录的 vendor 改动。 +```bash +rustup target add wasm32-unknown-unknown +brew install llvm # Apple clang cannot target wasm32 -wasm 侧的 SQLite 由 `sqlite-wasm-rs` 提供(预编译,不在构建期编 C)。 -`crates/zcash-runtime/build.rs` 自动把它的 `libwsqlite3.a` 按链接器要的名字接上, -**调用方不需要任何手工 RUSTFLAGS**。 +bash scripts/build-wasm.sh # builds pkg/ and pkg-keys/ (prepares vendor first) ---- +bash scripts/vendor-deps.sh # once before native tests +cargo test --workspace --locked -## 存储:数据存在哪 +bash scripts/vendor-deps.sh --offline # verify vendor against recorded upstream + patches +``` -所有 App 端统一使用 `sqlite-wasm-vfs` 的 OPFS SAH-pool,目录为 `.onekey-zcash-opfs`。 -SQLite 按页直接读写同步访问句柄,不把整库预载成 WASM 内存镜像。 -每个 origin 的池由一个 Worker 独占;第二个 Worker 不能静默改用其他数据库。 -默认预留六个文件句柄,网络数据库为 `zcash-main.db` / `zcash-test.db`。 +`pkg/` and `pkg-keys/` are not committed; they are built together for the App's +local `portal:` dependencies or CI artifacts. Publishing is in [RELEASING.md](./RELEASING.md). -连接明确设置 `journal_mode=DELETE`、`synchronous=FULL`。提交和日志删除的 flush -错误必须传回宿主;元数据 I/O 失败后该 VFS 停止服务,需要重建 Worker。 -不要求 SharedArrayBuffer、COOP/COEP 或 UI 线程上的同步文件访问。 -OPFS 仍受浏览器 origin、配额和清理策略约束;App 内嵌页面的来源必须稳定。 +## Design rules -## 已知约束 +1. **No forked Zcash storage.** `zcash_client_sqlite` comes from crates.io with no + Rust source changes; the only change is one Cargo.toml feature (see Vendor patches). +2. **Seeds enter only the keys wasm, only for an authorized derive or sign call.** Rust + wipes its secret buffers; JS strings and cross-bridge copies cannot be reliably + wiped. The scanner holds the UFVK, never the seed. +3. **Few verbs, plain data.** Only strings, numbers, booleans, bytes and JSON strings + cross the boundary; no Rust object handles are given to JS. -- lightwalletd 端点**必须支持 gRPC-web + CORS**。`zcash-{mainnet,testnet}.chainsafe.dev` - 可用;只开原生 gRPC 的端点在浏览器里会挂在第一次请求上(`grpcurl` 能通不代表 - gRPC-web 能通)。端点由宿主注入,runtime 不硬编码。 -- **扫描不走上游的 `scan_cached_blocks`**,改用自己的 `scan_blocks_inline`。 - 上游把试解密交给 `rayon::spawn_fifo`,而 wasm32 单线程环境下 rayon 没有工作线程, - 任务永远不会执行,随后取结果时永久堵死主线程。 - 代价是失去批量试解密的摊销优化。用 `syncPeek()` 的 `remainingBlocks` 画进度条。 -- `syncPrepare()` 要下载各池的全部子树根。宿主应给它独立的「准备中」状态, - 主网子树数量比 testnet 多得多。 -- Sapling 不在产品范围内:不作为收款 receiver、扫描身份或发送来源。 +| Rust (wasm) | Host TS | +|---|---| +| Trial decryption | When and how much to scan | +| Witness and commitment trees | Accounts and birthdays | +| Transaction construction and note selection | Caching and persistence policy | +| Key derivation and signing | Progress, error handling, retries | +| Platform glue (clock, RNG, VFS) | History display model | + +Code belongs in Rust only if it touches key security, large cross-boundary data or +consensus correctness. + +## Vendor patches + +`zcash_client_sqlite` enables `rusqlite`'s `bundled` feature, which compiles SQLite's +C source with cc. `wasm32-unknown-unknown` has no libc sysroot and stops at +`fatal error: 'stdio.h' file not found`. Cargo features are additive, so a downstream +crate cannot disable it; only the upstream Cargo.toml can. + +`scripts/vendor-deps.sh` downloads the official releases and applies the patches +recorded in `patches/manifest.json`: + +- `zcash_client_sqlite`: the one-line Cargo.toml change. +- `sqlite-wasm-vfs`: OPFS durability fixes (connection lock, durable journal deletion, + handle cleanup, stop I/O after a metadata failure). +- `tonic-web-wasm-client`: host fetch injection. + +`scripts/prepare-vendor.py --offline` rebuilds and compares every file from the +verified archives and patches, and rejects unrecorded vendor changes. + +The wasm SQLite comes precompiled from `sqlite-wasm-rs`; `crates/zcash-runtime/build.rs` +links its `libwsqlite3.a` under the name the linker expects. No manual RUSTFLAGS. + +## Storage + +All platforms use the `sqlite-wasm-vfs` OPFS SAH pool in `.onekey-zcash-opfs`, with +six file handles reserved by default. Databases are `zcash-main.db` / `zcash-test.db`. +SQLite reads and writes pages through sync access handles; the database is never +preloaded into wasm memory. One Worker owns each origin's pool; a second Worker must +not silently switch to another database. + +Connections use `journal_mode=DELETE` and `synchronous=FULL`. Flush errors on commit +and journal deletion reach the host. After a metadata I/O failure the VFS stops +serving and `storageRequiresWorkerRestart()` returns true: keep the failed call's +result and restart the Worker. No SharedArrayBuffer, COOP/COEP or UI-thread sync file +access is needed. OPFS is still subject to origin, quota and eviction rules, so the +App's embedded page origin must be stable. + +## Known constraints + +- The lightwalletd endpoint **must support gRPC-web** (and CORS without a host + transport). A native-gRPC-only endpoint hangs on the first browser request even if + `grpcurl` works. The host supplies the endpoint; none is hardcoded. +- **Scanning does not use upstream `scan_cached_blocks`** but `scan_blocks_inline`. + Upstream hands trial decryption to `rayon::spawn_fifo`; single-threaded wasm has no + worker threads, so the task never runs and the main thread blocks forever. This + loses batched trial decryption. Use `syncPeek()` for progress. +- `syncPrepare()` downloads every pool's subtree roots, many more on mainnet; give it + its own "preparing" state. +- Sapling is out of scope: not a receiver, scan identity or send source. ## API -全部通过 JSON 字符串或字节交互。失败抛 `Error`,其上挂 **`code`(稳定错误码)+ `params` -(结构化参数)+ `detail`(仅日志)**。Rust 侧不产出任何面向用户的文案 —— -文案与 i18n 归宿主。`capabilities()` / `keysCapabilities()` 报告当前构建实际支持的能力。 +Failures throw an `Error` with a stable `code`, structured `params`, and a log-only +`detail`. Rust produces no user-facing text. `capabilities()` / `keysCapabilities()` +report what the build supports. ### `onekey-zcash-runtime` ``` -init() 安装存储层,幂等,必须先调 -setRequestHandler(handler) 宿主提供 lightwalletd 请求的 fetch +init() install storage; idempotent; call first +storageRequiresWorkerRestart() true after a VFS failure +setRequestHandler(handler) host fetch for lightwalletd openWallet(network, dbName) / closeWallet() -setLightwalletdUrl(baseUrl) 端点由宿主注入,不硬编码 +setLightwalletdUrl(baseUrl) chainTip() / chainTipAt(baseUrl) importAccountUfvk(name, ufvk, birthday, seedFingerprintHex?, accountIndex?) - 导入账户 → UUID;服务器返回的树状态必须 - 正好是 birthday 前一块 + → UUID; the server's tree state must be + exactly the block before birthday removeAccount(uuid) / removeDeletedAccount(uuid) accountByUfvk(ufvk) / listAccounts() / accountSyncStatus(uuid) accountBalance(uuid, trusted, untrusted, allowZeroConfShielding) -syncPrepare() / syncTip() / syncPeek() 准备(子树根 + 链尖)与只读进度 +syncPrepare() / syncTip() / syncPeek() prepare (subtree roots + tip), read-only progress syncStep(batchSize, maxBatches, priority, activeUfvksJson) - 仅为宿主显式启用的 UFVK 有界推进 -queueRescanFrom(fromHeight) 非破坏性重排 [fromHeight, chainTip] -rewindTo(height) 回退重扫(破坏性) + bounded step, only for UFVKs the host enabled +queueRescanFrom(fromHeight) non-destructive requeue of [fromHeight, tip] +rewindTo(height) destructive -transactionHistory(uuid, limit, offset) 分页历史,limit 上限 500 +transactionHistory(uuid, limit, offset) limit ≤ 500 transactionDetails(uuid, txid) / transactionOutputs(uuid, txid) -deleteWallet(dbName) 擦掉本地缓存库(可重建) +deleteWallet(dbName) deletes the local cache (rebuildable) storageStats() -pcztQuote(...) 只报价,不建交易、不锁 note -pcztCreate(...) → { pcztHex, reservationId } 构造并锁住选中的 note -releaseReservation(id) 用户取消时放开锁,幂等 -clearLockedOutputs(uuid) 显式修复:清掉该账户全部锁(有未决广播时拒绝) -pcztProve(pczt) 生成证明 -pcztCombine(original, signed) 合并外部签名器回传的副本(只许补签名) -pcztSubmit(uuid, pczt, reservationId) 终结、落库、广播,返回 {txid, broadcast} +pcztQuote(...) quote only; builds nothing, locks nothing +pcztCreate(...) → { pcztHex, reservationId } build and lock the selected notes +releaseReservation(id) user cancel; idempotent +clearLockedOutputs(uuid) repair: clear the account's locks; refused + while broadcasts are pending +pcztProve(pczt) +pcztCombine(original, signed) merge an external signer's copy (signatures only) +pcztSubmit(uuid, pczt, reservationId) → { txid, broadcast } pendingBroadcastTxids(uuid) / broadcastRetryTxids(uuid) -broadcastTransaction(txid) 重播已落库的交易(同步循环用) +broadcastTransaction(txid) rebroadcast a stored transaction -prewarmPczt(network, height) 预建证明参数,不开钱包 -pcztProveAtHeight(height, pczt) 无钱包证明(透明资金付给 UA 的路径) -pcztExtractStateless(pczt) 无钱包校验并提取最终交易 -dependencyVersions() / diag* 诊断 +prewarmPczt(network, height) build proving parameters; no wallet +pcztProveAtHeight(height, pczt) prove without a wallet +pcztExtractStateless(pczt) verify and extract without a wallet +dependencyVersions() / setPerfTrace(enabled) / diag* ``` ### `onekey-zcash-keys` @@ -142,115 +162,94 @@ dependencyVersions() / diag* 诊断 ``` ufvkFromSeed(network, seedBytes, accountIndex) unifiedAddress(network, ufvk, receiverPolicy) - "all" = Orchard + 透明;"shielded" / "orchard" - = 仅 Orchard。不含 Sapling receiver + "all" = Orchard + transparent; + "shielded" / "orchard" = Orchard only; never Sapling transparentAddressFromUfvk(network, ufvk) / transparentAccountPubKeyFromUfvk(network, ufvk) validateAddress(network, address) / seedFingerprint(seed) -pcztVerifyReview(pczt, reviewJson) 只校验,不签名 +pcztVerifyReview(pczt, reviewJson) check only, no signing pcztSignWithSeed(network, seed, accountIndex, pczt, reviewJson) - 唯一接触花费密钥处;先按 review 校验每个 - spend 与 output,不符即拒绝 -transparentTx* / transparentShield* 无状态透明交易,见 TRANSPARENT_TX_API.md + only place spend keys are used; checks every + spend and output against the review first +transparentTx* / transparentShield* stateless transparent sends, see + crates/zcash-keys-runtime/TRANSPARENT_TX_API.md parseTransparentTransactions(requestJson) keysCapabilities() / keysDependencyVersions() ``` -### 发送的完整流程 +### Sending ``` -runtime.pcztCreate() 构造(要钱包 DB:选币、witness、anchor),锁住 note -runtime.pcztProve() 零知识证明(慢,要建 halo2 电路) -keys.pcztSignWithSeed() 按 review 校验后签名(要种子;在另一个包里) -runtime.pcztSubmit() 与原件合并校验 → 提取 → 落库 → 广播 +runtime.pcztCreate() build (needs wallet DB: selection, witness, anchor), lock notes +runtime.pcztProve() zero-knowledge proofs (slow) +keys.pcztSignWithSeed() check against the review, then sign (needs the seed) +runtime.pcztSubmit() combine check → extract → store → broadcast ``` -**顺序不能换**:证明必须在签名之前 —— 上游 Signer 需要能验证证明覆盖的是正确数据。 +Prove before signing: the upstream Signer must be able to verify what the proofs cover. -**先落库后广播**:签好的交易字节与 reservation→txid 关联在广播前原子落库,之后的每次 -重试和崩溃恢复都广播同一份字节。广播结局: +The signed bytes and the reservation→txid link are stored atomically before +broadcast; every retry and crash recovery sends the same bytes. Outcomes: -- `accepted`:节点接受。`already known` / `already in mempool` / `already in blockchain` - 视为幂等成功。 -- `rejected`:只有明确表示交易在共识上无效或已过期的回复才算拒收。交易仍保留在库中, - 它选中的 note 要到交易过期高度之后才会重新可用。 -- `unknown`:其余任何错误(超时、临时错误、无法判定的回复)。交易保持待确认, - 由同步循环重播原字节;宿主不得把它当作失败、引导用户重发。 +- `accepted`: the node took it. `already known`, `already in mempool` and + `already in blockchain` count as success. +- `rejected`: only a reply that the transaction is consensus-invalid or expired. It + stays stored; its notes return only after its expiry height. +- `unknown`: anything else (timeout, transient error, unclear reply). It stays pending + and sync rebroadcasts the same bytes. The host must not show it as failed or + prompt a resend, and must check `pendingBroadcastTxids` before building another + payment. -同一个 `reservationId` 已有落库交易时,`pcztCreate` 拒绝再用它构造新交易; -`pcztSubmit` 对它只会重播已落库的那一笔。所有触网调用都有 30 秒上限。 +`FINALIZE_OUTCOME_UNKNOWN` from `pcztSubmit` or `broadcastTransaction` means the +step went through but persistence is unconfirmed. Treat it like `unknown`: do not +unlock notes or rebuild the transaction. ---- +A `reservationId` with a stored transaction cannot build again: `pcztCreate` refuses +it and `pcztSubmit` only rebroadcasts the stored one. Network calls time out after +30 seconds. -## 用法 +### Stateless transparent sends to Unified Addresses -```bash -# 一次性:装 wasm target 和能编 wasm 的 clang -rustup target add wasm32-unknown-unknown -brew install llvm # macOS 自带的 Apple clang 不支持 wasm32 -cargo install wasm-pack +`transparentTxQuote` accepts mainnet t1/t3/tex recipients and Unified Addresses with +an Orchard receiver (paid as an Ironwood output after NU6.3). It uses only the +host-supplied confirmed, non-coinbase transparent UTXOs, explicit outpoints, target +height and transparent change address. No wallet, database, scan or network call. +Sapling/Sprout destinations and coinbase inputs are unsupported. -# 构建(自动跑 vendor-deps.sh) -bash scripts/build-wasm.sh +Software keys (seed or account xprv): -# 原生单测(首次运行前先准备 vendor) -bash scripts/vendor-deps.sh -cargo test --workspace --locked +1. `keys.transparentShieldCreateWithSeed` / `WithAccountXprv` builds a PCZT from the + request used for the quote. +2. `runtime.pcztProveAtHeight` proves it. +3. `keys.transparentShieldSignWithSeed` / `WithAccountXprv` checks the request, the + original PCZT and the proved PCZT, then signs. +4. `runtime.pcztExtractStateless` verifies and extracts the final transaction. -# 校验缓存中的 vendor 与记录的上游/补丁完全一致 -bash scripts/vendor-deps.sh --offline -``` +Hardware: `keys.transparentTxCreateWithAccountXpub` → device signs → +`keys.transparentTxCombineHardwareSigned` (verifies every signature against the +request) → `runtime.pcztProveAtHeight` → `runtime.pcztExtractStateless`. -产物 `pkg/`、`pkg-keys/` 不入库。两者一起构建,供 App 的本地 portal 依赖或 CI -artifact 使用。独立 npm 发布流程、版本规则与 App 切换步骤见 -[RELEASING.md](./RELEASING.md)。 +`parseTransparentTransactions` verifies raw previous transactions against their +txids and returns output values, scripts and coinbase status; the host checks each +UTXO's index and value against it. ---- +The host owns outpoint reservations, UTXO revalidation at signing time, pending +broadcast records and submission. The recipient scans to find the shielded notes; +the sender does not need to scan. -## 目录 +## Layout ``` -crates/zcash-runtime/ 钱包、扫描、PCZT 构造/证明/提交 - src/bindgen.rs 面向 JS 的接口 - src/send.rs 提案、reservation、PCZT 生命周期 - src/tx_state.rs reservation→txid 关联与广播结局 - src/guard.rs 破坏性操作的持久化闸门 - src/sync.rs 有界扫描 - src/storage.rs VFS 安装、连接打开与落盘屏障 - build.rs 自动接上 wasm 版 SQLite 静态库 -crates/zcash-keys-runtime/ 派生、review 校验与签名、无状态透明交易 -crates/zcash-storage-benchmark/ 开发者合成数据测试 -patches/ 固定上游校验值与补丁 -scripts/vendor-deps.sh 校验官方发布版并施加已记录的 patch -scripts/build-wasm.sh 构建 +crates/zcash-runtime/ wallet, scanning, PCZT build/prove/submit + src/bindgen.rs JS interface + src/send.rs proposals, reservations, PCZT lifecycle + src/tx_state.rs reservation→txid link and broadcast outcomes + src/guard.rs persistent gate for destructive operations + src/sync.rs bounded scanning + src/storage.rs VFS install, connections, durability barrier + build.rs links the wasm SQLite static library +crates/zcash-keys-runtime/ derivation, review checks, signing, stateless transparent sends +crates/zcash-storage-benchmark/ synthetic storage tests +patches/ pinned upstream checksums and patches +scripts/vendor-deps.sh verify official releases and apply recorded patches +scripts/build-wasm.sh build ``` - -## Stateless transparent funding of Unified recipients - -`transparentTxQuote` accepts mainnet t1/t3/tex recipients and Unified recipients with an -Orchard receiver (an Ironwood output after NU6.3). It uses only the host-supplied -confirmed, regular transparent UTXOs, explicit outpoints, target height, and -transparent change address. Sapling/Sprout destinations and coinbase inputs remain -unsupported. No wallet registration, database, scan, or network call is required. - -Software keyrings use this sequence for Unified recipients: - -1. `keys.transparentShieldCreateWithSeed` (or `WithAccountXprv`) constructs a PCZT - from the same validated request used for the quote. -2. `runtime.pcztProveAtHeight` proves it without calling `init` or opening a wallet. -3. `keys.transparentShieldSignWithSeed` (or `WithAccountXprv`) checks the original - request, all effects of the original PCZT, and the proved PCZT before signing. -4. `runtime.pcztExtractStateless` verifies and extracts the final transaction. - -`parseTransparentTransactions` verifies raw previous transactions against their -requested transaction IDs and returns transparent output values, scripts, and -coinbase status. It only needs transaction IDs and raw bytes; the host must check -each UTXO's output index and value against the result. -This API uses only the keys module; no wallet database or scan is required. - -The host owns transparent outpoint reservations, signature-time UTXO revalidation, -pending broadcast records, and submission to its node. The recipient's wallet -scans to discover and later spend the received shielded notes; the sender does not -need to scan. Private inputs still use the existing stateful wallet/PCZT APIs. - -The App's hardware Shield flow is separate; these signing exports are for software -seed/account-xprv keyrings. diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md index d7fda3db6..5688193fe 100644 --- a/chain-runtimes/zcash/RELEASING.md +++ b/chain-runtimes/zcash/RELEASING.md @@ -11,10 +11,9 @@ workspace entries in `Cargo.lock` with `cargo check --workspace --offline` and review the lockfile diff; dependency upgrades are a separate change. Release candidates use `X.Y.Z-rc.N` on the npm `rc` tag; final releases use -`latest`. Runtime and keys -always share a version and source commit. The benchmark is shipped as a runtime -subdirectory to preserve the App developer tools' existing import path; it is -not a third published package and production App bundles still exclude it. +`latest`. Runtime and keys always share a version and source commit. The +benchmark ships as a runtime subdirectory to keep the App developer tools' import +path; it is not a third package, and production App bundles exclude it. ## Prepare and verify diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md index 895224cee..3baac33e8 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md @@ -9,6 +9,13 @@ status reconciliation. - `transparentTxQuote(requestJson)` - `transparentTxBuildWithSeed(requestJson, seed)` - `transparentTxBuildWithAccountXprv(requestJson, accountXprv)` +- `transparentShield{Create,Sign}With{Seed,AccountXprv}`: Unified Address recipients + through a proved PCZT +- `transparentTxCreateWithAccountXpub(requestJson, accountXpub, seedFingerprintHex)` and + `transparentTxCombineHardwareSigned(requestJson, accountXpub, original, signed)`: hardware + signing + +The PCZT call sequences are in the Zcash README. All entry points take the same request. The xprv entry point accepts an account-level BIP-44 xprv. Its required derivation path is `m/44'/133'/account'`. An account xprv cannot attest its ancestors, so the crate verifies its depth From fc7e5c1652d8c3cf1693668c243dcaa85a9d0180 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 20:21:13 +0800 Subject: [PATCH 23/97] fix(zcash): treat shielded-requirements-not-met as an unknown broadcast outcome --- chain-runtimes/zcash/crates/zcash-runtime/src/network.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs index ee61a6c9d..46568b9e7 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs @@ -229,6 +229,9 @@ fn broadcast_outcome_ambiguous(message: &str) -> bool { "bad-txns-inputs-missingorspent", "txn-mempool-conflict", "missing inputs", + // REJECT_DUPLICATE for a fully shielded tx whose nullifiers are already + // spent, including by this tx once mined. + "bad-txns-shielded-requirements-not-met", ] .iter() .any(|needle| message.contains(needle)) @@ -383,6 +386,7 @@ mod tests { "any transaction with the same effects will be rejected from the mempool until the next chain tip block: ..", "bad-txns-inputs-spent", "txn-mempool-conflict", + "18: bad-txns-shielded-requirements-not-met", ] { assert!(broadcast_outcome_ambiguous(message), "{message}"); assert!(!broadcast_already_known(message), "{message}"); @@ -411,6 +415,7 @@ mod tests { for message in [ "bad-txns-inputs-spent", "bad-txns-inputs-missingorspent", + "bad-txns-shielded-requirements-not-met", "tx-expiring-soon", "transaction is non-standard", "transaction dropped because the queue is full", From f6d68a3e3b86f0fadfde5eb64bcc4740217694ef Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 20:21:14 +0800 Subject: [PATCH 24/97] fix(monero): keep only reorgable own sends pending on rewind --- .../monero/crates/monero-runtime/src/scan.rs | 50 +++++++++++++++---- .../monero/crates/monero-runtime/src/sync.rs | 2 +- 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs index 8fd560285..7abee15a9 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs @@ -744,22 +744,25 @@ fn timelock_to_i64(timelock: monero_wallet::transaction::Timelock) -> i64 { /// Rewinds to `height`, dropping all scan results above it. /// -/// Destructive; used for reorg recovery. Our own broadcasts are kept: a -/// reorged-out send usually returns to the pool and is mined again, and -/// releasing its inputs could let a second send with other inputs also confirm. -/// They revert to pending (height cleared) with inputs still spent, left to -/// the pending check and scanning. -pub fn rewind_to(db: &mut Db, identity_id: i64, height: u64) -> Result<()> { +/// Destructive; used for reorg recovery and user rescans. Our own broadcasts +/// within the reorg window of `tip` are kept: a reorged-out send usually +/// returns to the pool and is mined again, and releasing its inputs could let +/// a second send with other inputs also confirm. They revert to pending +/// (height cleared) with inputs still spent, left to the pending check and +/// scanning. Deeper sends cannot be reorged out; they are dropped and found +/// again by the rescan, so a rescan does not turn old history pending. +pub fn rewind_to(db: &mut Db, identity_id: i64, height: u64, tip: u64) -> Result<()> { let tx = db .conn_mut() .transaction() .map_err(|e| db_err("beginRewind", e))?; // Must run before clearing spend marks: that step keeps marks for pending transactions. + let reorgable_above = height.max(tip.saturating_sub(REORG_WINDOW_BLOCKS)); tx.execute( "UPDATE transactions SET height = NULL, failed = 0, pool_checked_at = NULL WHERE identity_id = ?1 AND height > ?2 AND sent_at IS NOT NULL", - params![identity_id, height as i64], + params![identity_id, reorgable_above as i64], ) .map_err(|e| db_err("rewindOwnSends", e))?; @@ -926,7 +929,7 @@ mod tests { .unwrap(); } - rewind_to(&mut db, a, 50).unwrap(); + rewind_to(&mut db, a, 50, 60).unwrap(); assert!(previous_block_state(&db, a, 101).unwrap().is_none()); assert!(previous_block_state(&db, b, 101).unwrap().is_some()); @@ -1094,7 +1097,7 @@ mod tests { ) .unwrap(); - rewind_to(&mut db, id, 490).unwrap(); + rewind_to(&mut db, id, 490, 505).unwrap(); let spent_in: Option> = db .conn() @@ -1103,6 +1106,33 @@ mod tests { assert_eq!(spent_in, Some(txid.to_vec())); } + /// A rescan far below the reorg window drops our old send instead of + /// turning it pending; scanning finds it again. + #[test] + fn a_deep_rewind_does_not_turn_old_sends_pending() { + let (mut db, id) = db_with_identity(); + let ours = [3u8; 32]; + db.conn() + .execute( + "INSERT INTO transactions (identity_id, txid, height, direction, sent_at) + VALUES (?1, ?2, 500, 'out', 1000)", + params![id, ours.as_slice()], + ) + .unwrap(); + + rewind_to(&mut db, id, 490, 500 + REORG_WINDOW_BLOCKS + 10).unwrap(); + + let pending: i64 = db + .conn() + .query_row( + "SELECT count(*) FROM transactions WHERE height IS NULL", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(pending, 0); + } + /// Our confirmed send reorged out reverts to pending; inputs stay spent. #[test] fn a_rewind_turns_our_confirmed_send_back_into_a_pending_one() { @@ -1127,7 +1157,7 @@ mod tests { ) .unwrap(); - rewind_to(&mut db, id, 490).unwrap(); + rewind_to(&mut db, id, 490, 505).unwrap(); let rows: Vec<(Vec, Option)> = db .conn() diff --git a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs index a3fca938b..0300133b0 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs @@ -407,7 +407,7 @@ pub fn peek(db: &Db, identity_id: i64) -> Result { /// Reorg recovery: rewind to `height` and requeue everything above it. pub fn rewind_and_requeue(db: &mut Db, identity_id: i64, height: u64, tip: u64) -> Result { - scan::rewind_to(db, identity_id, height)?; + scan::rewind_to(db, identity_id, height, tip)?; // Rewind progress too, or the next step resumes from a discarded height and the // gap is never rescanned. Keep NULL if nothing was scanned: 0 would make the next // `update_chain_tip` queue from genesis. From 1aedcc6571ecac2ddf55ab7d1c2346dd8b937748 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 20:33:09 +0800 Subject: [PATCH 25/97] chore: version zcash and monero runtimes 0.1.0-alpha.1 --- chain-runtimes/monero/Cargo.lock | 2 +- chain-runtimes/monero/Cargo.toml | 2 +- chain-runtimes/zcash/Cargo.lock | 6 +++--- chain-runtimes/zcash/Cargo.toml | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock index f8ff09bcd..6c7772605 100644 --- a/chain-runtimes/monero/Cargo.lock +++ b/chain-runtimes/monero/Cargo.lock @@ -1259,7 +1259,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "onekey-monero-runtime" -version = "0.0.1-spike.0" +version = "0.1.0-alpha.1" dependencies = [ "curve25519-dalek", "futures-lite", diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml index 524cd9a81..ec87836ed 100644 --- a/chain-runtimes/monero/Cargo.toml +++ b/chain-runtimes/monero/Cargo.toml @@ -3,7 +3,7 @@ resolver = "2" members = ["crates/monero-runtime"] [workspace.package] -version = "0.0.1-spike.0" +version = "0.1.0-alpha.1" edition = "2021" license = "Apache-2.0" rust-version = "1.85" diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock index e3a22c816..04c16cb45 100644 --- a/chain-runtimes/zcash/Cargo.lock +++ b/chain-runtimes/zcash/Cargo.lock @@ -1655,7 +1655,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "onekey-zcash-keys" -version = "0.1.0-rc.1" +version = "0.1.0-alpha.1" dependencies = [ "bip0039", "bs58", @@ -1685,7 +1685,7 @@ dependencies = [ [[package]] name = "onekey-zcash-runtime" -version = "0.1.0-rc.1" +version = "0.1.0-alpha.1" dependencies = [ "blake2b_simd", "console_error_panic_hook", @@ -1733,7 +1733,7 @@ dependencies = [ [[package]] name = "onekey-zcash-storage-benchmark" -version = "0.1.0-rc.1" +version = "0.1.0-alpha.1" dependencies = [ "console_error_panic_hook", "js-sys", diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml index 4f5bbb55f..16b908fb2 100644 --- a/chain-runtimes/zcash/Cargo.toml +++ b/chain-runtimes/zcash/Cargo.toml @@ -8,7 +8,7 @@ members = [ exclude = ["vendor/sqlite-wasm-vfs-0.2.0"] [workspace.package] -version = "0.1.0-rc.1" +version = "0.1.0-alpha.1" edition = "2021" license = "Apache-2.0" rust-version = "1.85" From 6e41a5746095c10ca19150699c5a00cc8c2e98ca Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 20:33:09 +0800 Subject: [PATCH 26/97] ci(zcash): allow alpha releases from any branch --- .github/workflows/zcash-publish.yml | 10 ++++++---- .github/workflows/zcash-runtime.yml | 1 + chain-runtimes/zcash/RELEASING.md | 12 +++++++----- chain-runtimes/zcash/scripts/package-release.py | 7 ++++--- chain-runtimes/zcash/scripts/test_package_release.py | 6 ++++++ 5 files changed, 24 insertions(+), 12 deletions(-) diff --git a/.github/workflows/zcash-publish.yml b/.github/workflows/zcash-publish.yml index 7f1ce9783..fcdd63798 100644 --- a/.github/workflows/zcash-publish.yml +++ b/.github/workflows/zcash-publish.yml @@ -4,14 +4,14 @@ on: workflow_dispatch: inputs: version: - description: Exact workspace version (for example 0.1.0-rc.1) + description: Exact workspace version (for example 0.1.0-alpha.1) required: true type: string tag: description: npm dist-tag required: true type: choice - options: [rc, latest] + options: [alpha, rc, latest] permissions: contents: read @@ -25,12 +25,14 @@ jobs: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v6 - - name: Require main and the exact release version + - name: Require the exact release version (rc and latest only from main) env: RELEASE_VERSION: ${{ inputs.version }} RELEASE_TAG: ${{ inputs.tag }} run: | - test "$GITHUB_REF" = refs/heads/main + if [ "$RELEASE_TAG" != alpha ]; then + test "$GITHUB_REF" = refs/heads/main + fi python3 - <<'PY' import importlib.util, os from pathlib import Path diff --git a/.github/workflows/zcash-runtime.yml b/.github/workflows/zcash-runtime.yml index e432df24a..1bdb9c42b 100644 --- a/.github/workflows/zcash-runtime.yml +++ b/.github/workflows/zcash-runtime.yml @@ -56,6 +56,7 @@ jobs: VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') TAG=latest if [[ "$VERSION" == *-rc.* ]]; then TAG=rc; fi + if [[ "$VERSION" == *-alpha.* ]]; then TAG=alpha; fi python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$GITHUB_SHA" - uses: actions/upload-artifact@v4 with: diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md index 5688193fe..4a0a41375 100644 --- a/chain-runtimes/zcash/RELEASING.md +++ b/chain-runtimes/zcash/RELEASING.md @@ -10,8 +10,9 @@ it, and wasm-pack generates the npm versions from those crates. Update the three workspace entries in `Cargo.lock` with `cargo check --workspace --offline` and review the lockfile diff; dependency upgrades are a separate change. -Release candidates use `X.Y.Z-rc.N` on the npm `rc` tag; final releases use -`latest`. Runtime and keys always share a version and source commit. The +Development builds use `X.Y.Z-alpha.N` on the npm `alpha` tag and may be +published from any branch. Release candidates use `X.Y.Z-rc.N` on the npm `rc` +tag; final releases use `latest`. Runtime and keys always share a version and source commit. The benchmark ships as a runtime subdirectory to keep the App developer tools' import path; it is not a third package, and production App bundles exclude it. @@ -34,9 +35,10 @@ archives or manually rewrite the manifest to make an old artifact pass. ## Publish -Merge the release changes to `main` first. The **Publish Zcash runtime** workflow -is manual, accepts the exact version and `rc`/`latest` tag, and refuses other -branches. It reuses the build/test workflow, verifies the downloaded artifact +For `rc` and `latest`, merge the release changes to `main` first; the +**Publish Zcash runtime** workflow refuses other branches for those tags. An +`alpha` can be published from any branch. The workflow is manual, accepts the +exact version and `alpha`/`rc`/`latest` tag, reuses the build/test workflow, verifies the downloaded artifact again, and publishes only these two npm packages. The native-module publish workflow is unchanged. diff --git a/chain-runtimes/zcash/scripts/package-release.py b/chain-runtimes/zcash/scripts/package-release.py index 0be895ec4..8c5bfdfa9 100644 --- a/chain-runtimes/zcash/scripts/package-release.py +++ b/chain-runtimes/zcash/scripts/package-release.py @@ -21,9 +21,10 @@ def version(root): def check_version(value, expected, tag): - if value != expected or not re.fullmatch(r"\d+\.\d+\.\d+(?:-rc\.\d+)?", value): + match = re.fullmatch(r"\d+\.\d+\.\d+(?:-(alpha|rc)\.\d+)?", value) + if value != expected or not match: raise ValueError("Release version must exactly match the workspace version") - required_tag = "rc" if "-rc." in value else "latest" + required_tag = match.group(1) or "latest" if tag != required_tag: raise ValueError(f"Version {value} requires npm dist-tag {required_tag}") @@ -106,7 +107,7 @@ def pack(root, expected, tag, revision, allow_dirty=False): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("operation", choices=("prepare", "pack")) parser.add_argument("--version") - parser.add_argument("--tag", choices=("rc", "latest")) + parser.add_argument("--tag", choices=("alpha", "rc", "latest")) parser.add_argument("--revision") parser.add_argument("--allow-dirty", action="store_true", help="Local pack checks only; never publish these archives") args = parser.parse_args() diff --git a/chain-runtimes/zcash/scripts/test_package_release.py b/chain-runtimes/zcash/scripts/test_package_release.py index 4a767c7fa..7261e1d27 100644 --- a/chain-runtimes/zcash/scripts/test_package_release.py +++ b/chain-runtimes/zcash/scripts/test_package_release.py @@ -36,11 +36,17 @@ def test_prepare_preserves_benchmark_and_rejects_mixed_versions(self): release.prepare(root) def test_prereleases_cannot_update_latest(self): + release.check_version("0.1.0-alpha.1", "0.1.0-alpha.1", "alpha") release.check_version("0.1.0-rc.1", "0.1.0-rc.1", "rc") release.check_version("0.1.0", "0.1.0", "latest") for expected, tag in (("0.1.0-rc.1", "latest"), ("0.1.0-rc.2", "rc")): with self.assertRaises(ValueError): release.check_version("0.1.0-rc.1", expected, tag) + for tag in ("rc", "latest"): + with self.assertRaises(ValueError): + release.check_version("0.1.0-alpha.1", "0.1.0-alpha.1", tag) + with self.assertRaises(ValueError): + release.check_version("0.1.0-beta.1", "0.1.0-beta.1", "rc") def test_missing_benchmark_and_changed_bytes_are_rejected(self): with tempfile.TemporaryDirectory() as directory: From 1ffe792cb517f1aa40e736545168d24be6d29ba7 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 20:33:09 +0800 Subject: [PATCH 27/97] ci(monero): add build and npm publish workflows --- .github/workflows/monero-publish.yml | 66 ++++++ .github/workflows/monero-runtime.yml | 59 +++++ chain-runtimes/monero/LICENSE | 202 ++++++++++++++++++ chain-runtimes/monero/scripts/build-wasm.sh | 3 +- .../monero/scripts/package-release.py | 71 ++++++ 5 files changed, 400 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/monero-publish.yml create mode 100644 .github/workflows/monero-runtime.yml create mode 100644 chain-runtimes/monero/LICENSE create mode 100644 chain-runtimes/monero/scripts/package-release.py diff --git a/.github/workflows/monero-publish.yml b/.github/workflows/monero-publish.yml new file mode 100644 index 000000000..8eafb63e3 --- /dev/null +++ b/.github/workflows/monero-publish.yml @@ -0,0 +1,66 @@ +name: Publish Monero runtime + +on: + workflow_dispatch: + inputs: + version: + description: Exact workspace version (for example 0.1.0-alpha.1) + required: true + type: string + tag: + description: npm dist-tag + required: true + type: choice + options: [alpha, rc, latest] + +permissions: + contents: read + +concurrency: + group: monero-npm-publish + cancel-in-progress: false + +jobs: + validate: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + - name: Require the exact release version (rc and latest only from main) + env: + RELEASE_VERSION: ${{ inputs.version }} + RELEASE_TAG: ${{ inputs.tag }} + run: | + if [ "$RELEASE_TAG" != alpha ]; then + test "$GITHUB_REF" = refs/heads/main + fi + python3 - <<'PY' + import importlib.util, os + from pathlib import Path + path = Path('chain-runtimes/monero/scripts/package-release.py') + spec = importlib.util.spec_from_file_location('release', path) + release = importlib.util.module_from_spec(spec) + spec.loader.exec_module(release) + release.check_version(release.workspace_version(), os.environ['RELEASE_VERSION'], os.environ['RELEASE_TAG']) + PY + build: + needs: validate + uses: ./.github/workflows/monero-runtime.yml + publish: + needs: build + runs-on: ubuntu-24.04 + environment: npm-monero + steps: + - uses: actions/setup-node@v6 + with: + node-version: '24.x' + registry-url: https://registry.npmjs.org + - uses: actions/download-artifact@v4 + with: + name: monero-npm-${{ github.sha }} + path: dist + - name: Publish the runtime + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + RELEASE_VERSION: ${{ inputs.version }} + RELEASE_TAG: ${{ inputs.tag }} + run: npm publish "dist/onekey-monero-runtime-${RELEASE_VERSION}.tgz" --ignore-scripts --access public --tag "$RELEASE_TAG" diff --git a/.github/workflows/monero-runtime.yml b/.github/workflows/monero-runtime.yml new file mode 100644 index 000000000..f25983c43 --- /dev/null +++ b/.github/workflows/monero-runtime.yml @@ -0,0 +1,59 @@ +name: Monero runtime + +on: + pull_request: + paths: + - 'chain-runtimes/monero/**' + - '.github/workflows/monero-runtime.yml' + - '.github/workflows/monero-publish.yml' + push: + branches: [main] + paths: + - 'chain-runtimes/monero/**' + - '.github/workflows/monero-runtime.yml' + - '.github/workflows/monero-publish.yml' + workflow_dispatch: + workflow_call: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-24.04 + timeout-minutes: 45 + defaults: + run: + working-directory: chain-runtimes/monero + steps: + - uses: actions/checkout@v6 + - name: Install build tools + run: | + sudo apt-get update + sudo apt-get install -y clang llvm binaryen libsqlite3-dev pkg-config + rustup toolchain install + cargo install wasm-pack --version 0.15.0 --locked + WASM_BINDGEN_VERSION=$(python3 -c 'import tomllib; print(next(p["version"] for p in tomllib.load(open("Cargo.lock", "rb"))["package"] if p["name"] == "wasm-bindgen"))') + cargo install wasm-bindgen-cli --version "$WASM_BINDGEN_VERSION" --locked + - name: Test Rust workspace + run: cargo test --workspace --locked + - name: Build runtime + env: + CC_wasm32_unknown_unknown: /usr/bin/clang + AR_wasm32_unknown_unknown: /usr/bin/llvm-ar + run: bash scripts/build-wasm.sh release + - uses: actions/setup-node@v6 + with: + node-version: '24.x' + - name: Pack npm archive + run: | + VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') + TAG=latest + if [[ "$VERSION" == *-rc.* ]]; then TAG=rc; fi + if [[ "$VERSION" == *-alpha.* ]]; then TAG=alpha; fi + python3 scripts/package-release.py --version "$VERSION" --tag "$TAG" + - uses: actions/upload-artifact@v4 + with: + name: monero-npm-${{ github.sha }} + if-no-files-found: error + path: chain-runtimes/monero/dist/ diff --git a/chain-runtimes/monero/LICENSE b/chain-runtimes/monero/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/chain-runtimes/monero/LICENSE @@ -0,0 +1,202 @@ + + 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/chain-runtimes/monero/scripts/build-wasm.sh b/chain-runtimes/monero/scripts/build-wasm.sh index e5cb9c210..e35487b07 100755 --- a/chain-runtimes/monero/scripts/build-wasm.sh +++ b/chain-runtimes/monero/scripts/build-wasm.sh @@ -13,7 +13,8 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd)" PROFILE="${1:-release}" OUT="${ROOT}/pkg" -AR="$(sed -n 's/^AR_wasm32_unknown_unknown = "\(.*\)"/\1/p' "${ROOT}/.cargo/config.toml")" +# CI sets AR_wasm32_unknown_unknown itself; cargo's [env] does not override it. +AR="${AR_wasm32_unknown_unknown:-$(sed -n 's/^AR_wasm32_unknown_unknown = "\(.*\)"/\1/p' "${ROOT}/.cargo/config.toml")}" if [[ -n "${AR}" && ! -x "${AR}" ]]; then echo "✗ ${AR} not found" >&2 echo " wasm targets need llvm-ar; the system ar silently writes empty archives." >&2 diff --git a/chain-runtimes/monero/scripts/package-release.py b/chain-runtimes/monero/scripts/package-release.py new file mode 100644 index 000000000..329b95e86 --- /dev/null +++ b/chain-runtimes/monero/scripts/package-release.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Pack the Monero runtime npm archive from a wasm-pack build. + +Usage: python3 scripts/package-release.py --version 0.1.0-alpha.1 --tag alpha +""" + +import argparse +import json +import re +import shutil +import subprocess +import tomllib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +NAME = "onekey-monero-runtime" + + +def workspace_version(root=ROOT): + with open(root / "Cargo.toml", "rb") as f: + return tomllib.load(f)["workspace"]["package"]["version"] + + +def check_version(value, expected, tag): + match = re.fullmatch(r"\d+\.\d+\.\d+(?:-(alpha|rc)\.\d+)?", value) + if value != expected or not match: + raise ValueError("Release version must exactly match the workspace version") + required_tag = match.group(1) or "latest" + if tag != required_tag: + raise ValueError(f"Version {value} requires npm dist-tag {required_tag}") + + +def prepare(root=ROOT): + pkg = root / "pkg" + path = pkg / "package.json" + package = json.loads(path.read_text()) + if package["name"] != NAME or package["version"] != workspace_version(root): + raise ValueError("Rebuild the wasm package: pkg version mismatch") + module = NAME.replace("-", "_") + package["files"] = [f"{module}.js", f"{module}.d.ts", f"{module}_bg.wasm", "LICENSE"] + if (pkg / "snippets").exists(): + package["files"].append("snippets") + package["repository"] = { + "type": "git", + "url": "git+https://github.com/OneKeyHQ/app-modules.git", + "directory": "chain-runtimes/monero/crates/monero-runtime", + } + path.write_text(json.dumps(package, indent=2) + "\n") + shutil.copyfile(root / "LICENSE", pkg / "LICENSE") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--version", required=True) + parser.add_argument("--tag", required=True, choices=["alpha", "rc", "latest"]) + args = parser.parse_args() + check_version(args.version, workspace_version(), args.tag) + prepare() + dist = ROOT / "dist" + dist.mkdir(exist_ok=True) + subprocess.run( + ["npm", "pack", "--pack-destination", str(dist)], cwd=ROOT / "pkg", check=True + ) + archive = dist / f"{NAME}-{args.version}.tgz" + if not archive.exists(): + raise SystemExit(f"missing {archive}") + print(archive) + + +if __name__ == "__main__": + main() From 79b23894503902a82b3cee916c7f6629f5fcb80a Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 21:07:19 +0800 Subject: [PATCH 28/97] build: share one toolchain across the zcash and monero runtimes - pin Monero to Rust 1.93.0 and wasm-bindgen 0.2.127, matching Zcash - find Homebrew clang and llvm-ar on Apple Silicon and Intel; route the node smoke build through build-wasm.sh - install Binaryen 133 with a checksum in CI instead of Ubuntu's 108 - install OpenSSL headers for Monero's native tests --- .github/workflows/monero-runtime.yml | 14 ++++- .github/workflows/zcash-runtime.yml | 14 ++++- chain-runtimes/monero/Cargo.lock | 30 +++++------ chain-runtimes/monero/README.md | 7 ++- chain-runtimes/monero/rust-toolchain.toml | 6 +-- .../monero/scripts/build-node-pkg.sh | 4 +- chain-runtimes/monero/scripts/build-wasm.sh | 51 ++++++++++++++----- 7 files changed, 89 insertions(+), 37 deletions(-) diff --git a/.github/workflows/monero-runtime.yml b/.github/workflows/monero-runtime.yml index f25983c43..81412f5dc 100644 --- a/.github/workflows/monero-runtime.yml +++ b/.github/workflows/monero-runtime.yml @@ -27,10 +27,22 @@ jobs: working-directory: chain-runtimes/monero steps: - uses: actions/checkout@v6 + - name: Install Binaryen 133 (same wasm-opt as local builds) + run: | + BINARYEN=version_133 + case "$(uname -m)" in + x86_64) ARCH=x86_64 SHA=2dc9c7813f5375db93d96ead4b78222fcc3e2677bbb832297af4797782a37489 ;; + aarch64) ARCH=aarch64 SHA=89c07ea56faf38d0fbecf36ca8ec0721756716185f265b568e133d427f299bf8 ;; + *) echo "unsupported architecture $(uname -m)" >&2; exit 1 ;; + esac + curl -sSfL -o /tmp/binaryen.tgz "https://github.com/WebAssembly/binaryen/releases/download/${BINARYEN}/binaryen-${BINARYEN}-${ARCH}-linux.tar.gz" + echo "${SHA} /tmp/binaryen.tgz" | sha256sum -c - + sudo tar xzf /tmp/binaryen.tgz -C /opt + echo "/opt/binaryen-${BINARYEN}/bin" >> "$GITHUB_PATH" - name: Install build tools run: | sudo apt-get update - sudo apt-get install -y clang llvm binaryen libsqlite3-dev pkg-config + sudo apt-get install -y clang llvm libsqlite3-dev libssl-dev pkg-config rustup toolchain install cargo install wasm-pack --version 0.15.0 --locked WASM_BINDGEN_VERSION=$(python3 -c 'import tomllib; print(next(p["version"] for p in tomllib.load(open("Cargo.lock", "rb"))["package"] if p["name"] == "wasm-bindgen"))') diff --git a/.github/workflows/zcash-runtime.yml b/.github/workflows/zcash-runtime.yml index 1bdb9c42b..6315dc97f 100644 --- a/.github/workflows/zcash-runtime.yml +++ b/.github/workflows/zcash-runtime.yml @@ -27,10 +27,22 @@ jobs: working-directory: chain-runtimes/zcash steps: - uses: actions/checkout@v6 + - name: Install Binaryen 133 (same wasm-opt as local builds) + run: | + BINARYEN=version_133 + case "$(uname -m)" in + x86_64) ARCH=x86_64 SHA=2dc9c7813f5375db93d96ead4b78222fcc3e2677bbb832297af4797782a37489 ;; + aarch64) ARCH=aarch64 SHA=89c07ea56faf38d0fbecf36ca8ec0721756716185f265b568e133d427f299bf8 ;; + *) echo "unsupported architecture $(uname -m)" >&2; exit 1 ;; + esac + curl -sSfL -o /tmp/binaryen.tgz "https://github.com/WebAssembly/binaryen/releases/download/${BINARYEN}/binaryen-${BINARYEN}-${ARCH}-linux.tar.gz" + echo "${SHA} /tmp/binaryen.tgz" | sha256sum -c - + sudo tar xzf /tmp/binaryen.tgz -C /opt + echo "/opt/binaryen-${BINARYEN}/bin" >> "$GITHUB_PATH" - name: Install build tools run: | sudo apt-get update - sudo apt-get install -y clang llvm binaryen libsqlite3-dev pkg-config + sudo apt-get install -y clang llvm libsqlite3-dev pkg-config rustup toolchain install 1.93.0 --profile minimal --target wasm32-unknown-unknown cargo install wasm-pack --version 0.15.0 --locked WASM_BINDGEN_VERSION=$(python3 -c 'import tomllib; print(next(p["version"] for p in tomllib.load(open("Cargo.lock", "rb"))["package"] if p["name"] == "wasm-bindgen"))') diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock index 6c7772605..cf1a41914 100644 --- a/chain-runtimes/monero/Cargo.lock +++ b/chain-runtimes/monero/Cargo.lock @@ -811,9 +811,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "js-sys" -version = "0.3.105" +version = "0.3.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" dependencies = [ "cfg-if", "futures-util", @@ -2111,9 +2111,9 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasm-bindgen" -version = "0.2.128" +version = "0.2.127" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" dependencies = [ "cfg-if", "once_cell", @@ -2124,9 +2124,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.78" +version = "0.4.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" +checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950" dependencies = [ "js-sys", "wasm-bindgen", @@ -2134,9 +2134,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.128" +version = "0.2.127" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2144,31 +2144,31 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.128" +version = "0.2.127" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.6", + "syn 2.0.119", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.128" +version = "0.2.127" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" dependencies = [ "unicode-ident", ] [[package]] name = "web-sys" -version = "0.3.105" +version = "0.3.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" +checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" dependencies = [ "js-sys", "wasm-bindgen", diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md index 60e971ad1..359470ad8 100644 --- a/chain-runtimes/monero/README.md +++ b/chain-runtimes/monero/README.md @@ -14,12 +14,15 @@ cargo check --workspace --target wasm32-unknown-unknown ``` `smoke.js` runs offline; set `XMR_NODE=` to add node checks. -Builds need the `wasm-bindgen-cli` version pinned in `Cargo.lock`. +The toolchain matches the Zcash runtime, so one install builds both: Rust 1.93.0 +(pinned in `rust-toolchain.toml`), wasm-pack 0.15.0, `wasm-bindgen-cli` at the +version in `Cargo.lock`, and `wasm-opt` (Binaryen 133 in CI). **macOS needs `llvm-ar`** (`brew install llvm`). `/usr/bin/ar` cannot read wasm objects and silently writes an empty archive; linking then fails with `undefined symbol: sqlite3_*`. `cargo check` does not link, so it never shows this. -The archiver is set in `.cargo/config.toml`. +`build-wasm.sh` finds Homebrew's clang and `llvm-ar` on Apple Silicon and Intel; +`.cargo/config.toml` sets the Apple Silicon archiver for direct `cargo` builds. ## Host contract diff --git a/chain-runtimes/monero/rust-toolchain.toml b/chain-runtimes/monero/rust-toolchain.toml index 9495f83fb..f7fb285f3 100644 --- a/chain-runtimes/monero/rust-toolchain.toml +++ b/chain-runtimes/monero/rust-toolchain.toml @@ -1,6 +1,6 @@ -# Tracks current stable. This is not the MSRV, which is `rust-version` in -# Cargo.toml (1.85). Pin a version if byte-reproducible wasm builds are needed. +# Same toolchain as the Zcash runtime, so one install builds both. Pinned for +# reproducible wasm; this is not the MSRV (`rust-version` in Cargo.toml). [toolchain] -channel = "stable" +channel = "1.93.0" profile = "minimal" targets = ["wasm32-unknown-unknown"] diff --git a/chain-runtimes/monero/scripts/build-node-pkg.sh b/chain-runtimes/monero/scripts/build-node-pkg.sh index c57a93ea8..49b7aa539 100755 --- a/chain-runtimes/monero/scripts/build-node-pkg.sh +++ b/chain-runtimes/monero/scripts/build-node-pkg.sh @@ -3,6 +3,4 @@ # Shipped builds use the web target from build-wasm.sh. set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" -cd "${ROOT}/crates/monero-runtime" -wasm-pack build --mode no-install --locked --target nodejs \ - --out-dir "${ROOT}/pkg-node" --release +WASM_PACK_TARGET=nodejs OUT="${ROOT}/pkg-node" exec bash "${ROOT}/scripts/build-wasm.sh" release diff --git a/chain-runtimes/monero/scripts/build-wasm.sh b/chain-runtimes/monero/scripts/build-wasm.sh index e35487b07..0270e0d88 100755 --- a/chain-runtimes/monero/scripts/build-wasm.sh +++ b/chain-runtimes/monero/scripts/build-wasm.sh @@ -3,24 +3,51 @@ # Build the wasm package into pkg/. # # Requires: -# 1. rustup (toolchain set by rust-toolchain.toml) +# 1. rustup with the toolchain pinned in rust-toolchain.toml # 2. wasm-pack: cargo install wasm-pack -# 3. llvm-ar, configured in .cargo/config.toml. macOS /usr/bin/ar silently -# writes empty archives for wasm objects (`undefined symbol: sqlite3_*`). +# 3. wasm-bindgen-cli matching Cargo.lock +# 4. A clang with wasm32 support and its llvm-ar (brew install llvm on macOS). +# macOS /usr/bin/ar silently writes empty archives for wasm objects +# (`undefined symbol: sqlite3_*`). +# 5. wasm-opt (Binaryen) for release builds set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" PROFILE="${1:-release}" -OUT="${ROOT}/pkg" +OUT="${OUT:-${ROOT}/pkg}" +# web for the App; build-node-pkg.sh passes nodejs for the smoke test. +TARGET="${WASM_PACK_TARGET:-web}" -# CI sets AR_wasm32_unknown_unknown itself; cargo's [env] does not override it. -AR="${AR_wasm32_unknown_unknown:-$(sed -n 's/^AR_wasm32_unknown_unknown = "\(.*\)"/\1/p' "${ROOT}/.cargo/config.toml")}" -if [[ -n "${AR}" && ! -x "${AR}" ]]; then - echo "✗ ${AR} not found" >&2 +# rustup run pins the toolchain even where a version manager overrides +# rust-toolchain.toml. +RUST_TOOLCHAIN="$(python3 -c 'import sys, tomllib; print(tomllib.load(open(sys.argv[1], "rb"))["toolchain"]["channel"])' "${ROOT}/rust-toolchain.toml")" +rustup run "${RUST_TOOLCHAIN}" rustc --version + +pick_clang() { + for c in "${CC_wasm32_unknown_unknown:-}" \ + /opt/homebrew/opt/llvm/bin/clang \ + /usr/local/opt/llvm/bin/clang "$(command -v clang || true)"; do + [ -n "$c" ] && [ -x "$c" ] || continue + if echo 'int main(void){return 0;}' > /tmp/_wasmprobe.c 2>/dev/null && + "$c" --target=wasm32-unknown-unknown -nostdlib -c /tmp/_wasmprobe.c -o /tmp/_wasmprobe.o 2>/dev/null; then + echo "$c"; return 0 + fi + done + return 1 +} +if ! CLANG="$(pick_clang)"; then + echo "✗ no clang with wasm32 support found; on macOS run brew install llvm" >&2 + exit 1 +fi +export CC_wasm32_unknown_unknown="${CLANG}" +# An exported value wins over .cargo/config.toml's [env] default. +export AR_wasm32_unknown_unknown="${AR_wasm32_unknown_unknown:-$(dirname "${CLANG}")/llvm-ar}" +if [[ ! -x "${AR_wasm32_unknown_unknown}" ]]; then + echo "✗ ${AR_wasm32_unknown_unknown} not found" >&2 echo " wasm targets need llvm-ar; the system ar silently writes empty archives." >&2 - echo " install it: brew install llvm" >&2 exit 1 fi +echo "==> Using clang: ${CLANG}" # With --mode no-install, a missing wasm-opt is only logged and skipped, leaving # an unoptimized output. Release builds require it. @@ -32,9 +59,9 @@ fi echo "==> wasm-pack build (${PROFILE})" cd "${ROOT}/crates/monero-runtime" case "${PROFILE}" in - release) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --release ;; - profiling) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --profiling ;; - *) wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --dev ;; + release) rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target "${TARGET}" --out-dir "${OUT}" --release ;; + profiling) rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target "${TARGET}" --out-dir "${OUT}" --profiling ;; + *) rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target "${TARGET}" --out-dir "${OUT}" --dev ;; esac echo "==> output" From b7740d5a14fb5473eb424d9d19fa096e6bc5042a Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 21:36:10 +0800 Subject: [PATCH 29/97] ci: publish alpha manually and rc/latest only from main - manual runs publish X.Y.Z-alpha.N from any branch and refuse other versions - a Cargo.toml version change merged to main publishes rc/latest, skipping alpha versions and versions already on npm - build workflows run on runtime code changes only, so the workflow files can land on main before the runtimes --- .github/workflows/monero-publish.yml | 70 ++++++++++++++++++-------- .github/workflows/monero-runtime.yml | 6 +-- .github/workflows/zcash-publish.yml | 74 +++++++++++++++++++--------- .github/workflows/zcash-runtime.yml | 6 +-- chain-runtimes/monero/README.md | 8 +++ chain-runtimes/zcash/RELEASING.md | 17 ++++--- 6 files changed, 125 insertions(+), 56 deletions(-) diff --git a/.github/workflows/monero-publish.yml b/.github/workflows/monero-publish.yml index 8eafb63e3..75b9cdc47 100644 --- a/.github/workflows/monero-publish.yml +++ b/.github/workflows/monero-publish.yml @@ -1,17 +1,19 @@ name: Publish Monero runtime +# Manual runs publish alpha builds only, from any branch. rc and latest are +# published only when a version change in chain-runtimes/monero/Cargo.toml is +# merged to main. on: workflow_dispatch: inputs: version: - description: Exact workspace version (for example 0.1.0-alpha.1) + description: Exact workspace alpha version (for example 0.1.0-alpha.1) required: true type: string - tag: - description: npm dist-tag - required: true - type: choice - options: [alpha, rc, latest] + push: + branches: [main] + paths: + - 'chain-runtimes/monero/Cargo.toml' permissions: contents: read @@ -23,30 +25,58 @@ concurrency: jobs: validate: runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.plan.outputs.version }} + tag: ${{ steps.plan.outputs.tag }} + publish: ${{ steps.plan.outputs.publish }} steps: - uses: actions/checkout@v6 - - name: Require the exact release version (rc and latest only from main) + - uses: actions/setup-node@v6 + with: + node-version: '24.x' + - name: Decide what to publish + id: plan env: - RELEASE_VERSION: ${{ inputs.version }} - RELEASE_TAG: ${{ inputs.tag }} + EVENT_NAME: ${{ github.event_name }} + INPUT_VERSION: ${{ inputs.version }} run: | - if [ "$RELEASE_TAG" != alpha ]; then - test "$GITHUB_REF" = refs/heads/main + VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("chain-runtimes/monero/Cargo.toml", "rb"))["workspace"]["package"]["version"])') + case "$VERSION" in + *-alpha.*) TAG=alpha ;; + *-rc.*) TAG=rc ;; + *) TAG=latest ;; + esac + if [ "$EVENT_NAME" = workflow_dispatch ]; then + test "$INPUT_VERSION" = "$VERSION" || { echo "Input $INPUT_VERSION does not match workspace $VERSION" >&2; exit 1; } + test "$TAG" = alpha || { echo "Manual runs publish alpha only; merge $VERSION to main instead" >&2; exit 1; } + elif [ "$TAG" = alpha ]; then + echo "Alpha versions are published manually; nothing to do on main" >> "$GITHUB_STEP_SUMMARY" + echo "publish=false" >> "$GITHUB_OUTPUT"; exit 0 fi - python3 - <<'PY' - import importlib.util, os - from pathlib import Path - path = Path('chain-runtimes/monero/scripts/package-release.py') - spec = importlib.util.spec_from_file_location('release', path) + python3 - "$VERSION" "$TAG" <<'PY' + import importlib.util, sys + spec = importlib.util.spec_from_file_location('release', 'chain-runtimes/monero/scripts/package-release.py') release = importlib.util.module_from_spec(spec) spec.loader.exec_module(release) - release.check_version(release.workspace_version(), os.environ['RELEASE_VERSION'], os.environ['RELEASE_TAG']) + release.check_version(sys.argv[1], sys.argv[1], sys.argv[2]) PY + if npm view "onekey-monero-runtime@$VERSION" version >/dev/null 2>&1; then + echo "onekey-monero-runtime@$VERSION is already on npm" >> "$GITHUB_STEP_SUMMARY" + test "$EVENT_NAME" = push || exit 1 + echo "publish=false" >> "$GITHUB_OUTPUT"; exit 0 + fi + { + echo "version=$VERSION" + echo "tag=$TAG" + echo "publish=true" + } >> "$GITHUB_OUTPUT" build: needs: validate + if: needs.validate.outputs.publish == 'true' uses: ./.github/workflows/monero-runtime.yml publish: - needs: build + needs: [validate, build] + if: needs.validate.outputs.publish == 'true' runs-on: ubuntu-24.04 environment: npm-monero steps: @@ -61,6 +91,6 @@ jobs: - name: Publish the runtime env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - RELEASE_VERSION: ${{ inputs.version }} - RELEASE_TAG: ${{ inputs.tag }} + RELEASE_VERSION: ${{ needs.validate.outputs.version }} + RELEASE_TAG: ${{ needs.validate.outputs.tag }} run: npm publish "dist/onekey-monero-runtime-${RELEASE_VERSION}.tgz" --ignore-scripts --access public --tag "$RELEASE_TAG" diff --git a/.github/workflows/monero-runtime.yml b/.github/workflows/monero-runtime.yml index 81412f5dc..94de6e289 100644 --- a/.github/workflows/monero-runtime.yml +++ b/.github/workflows/monero-runtime.yml @@ -1,17 +1,15 @@ name: Monero runtime +# Runs when runtime code changes. Edits to these workflow files alone do not +# trigger it (main may not carry the runtime yet); run it manually instead. on: pull_request: paths: - 'chain-runtimes/monero/**' - - '.github/workflows/monero-runtime.yml' - - '.github/workflows/monero-publish.yml' push: branches: [main] paths: - 'chain-runtimes/monero/**' - - '.github/workflows/monero-runtime.yml' - - '.github/workflows/monero-publish.yml' workflow_dispatch: workflow_call: diff --git a/.github/workflows/zcash-publish.yml b/.github/workflows/zcash-publish.yml index fcdd63798..0edc9f919 100644 --- a/.github/workflows/zcash-publish.yml +++ b/.github/workflows/zcash-publish.yml @@ -1,17 +1,19 @@ name: Publish Zcash runtime +# Manual runs publish alpha builds only, from any branch. rc and latest are +# published only when a version change in chain-runtimes/zcash/Cargo.toml is +# merged to main. on: workflow_dispatch: inputs: version: - description: Exact workspace version (for example 0.1.0-alpha.1) + description: Exact workspace alpha version (for example 0.1.0-alpha.1) required: true type: string - tag: - description: npm dist-tag - required: true - type: choice - options: [alpha, rc, latest] + push: + branches: [main] + paths: + - 'chain-runtimes/zcash/Cargo.toml' permissions: contents: read @@ -23,30 +25,58 @@ concurrency: jobs: validate: runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.plan.outputs.version }} + tag: ${{ steps.plan.outputs.tag }} + publish: ${{ steps.plan.outputs.publish }} steps: - uses: actions/checkout@v6 - - name: Require the exact release version (rc and latest only from main) + - uses: actions/setup-node@v6 + with: + node-version: '24.x' + - name: Decide what to publish + id: plan env: - RELEASE_VERSION: ${{ inputs.version }} - RELEASE_TAG: ${{ inputs.tag }} + EVENT_NAME: ${{ github.event_name }} + INPUT_VERSION: ${{ inputs.version }} run: | - if [ "$RELEASE_TAG" != alpha ]; then - test "$GITHUB_REF" = refs/heads/main + VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("chain-runtimes/zcash/Cargo.toml", "rb"))["workspace"]["package"]["version"])') + case "$VERSION" in + *-alpha.*) TAG=alpha ;; + *-rc.*) TAG=rc ;; + *) TAG=latest ;; + esac + if [ "$EVENT_NAME" = workflow_dispatch ]; then + test "$INPUT_VERSION" = "$VERSION" || { echo "Input $INPUT_VERSION does not match workspace $VERSION" >&2; exit 1; } + test "$TAG" = alpha || { echo "Manual runs publish alpha only; merge $VERSION to main instead" >&2; exit 1; } + elif [ "$TAG" = alpha ]; then + echo "Alpha versions are published manually; nothing to do on main" >> "$GITHUB_STEP_SUMMARY" + echo "publish=false" >> "$GITHUB_OUTPUT"; exit 0 fi - python3 - <<'PY' - import importlib.util, os - from pathlib import Path - path = Path('chain-runtimes/zcash/scripts/package-release.py') - spec = importlib.util.spec_from_file_location('release', path) + python3 - "$VERSION" "$TAG" <<'PY' + import importlib.util, sys + spec = importlib.util.spec_from_file_location('release', 'chain-runtimes/zcash/scripts/package-release.py') release = importlib.util.module_from_spec(spec) spec.loader.exec_module(release) - release.check_version(release.version(release.ROOT), os.environ['RELEASE_VERSION'], os.environ['RELEASE_TAG']) + release.check_version(sys.argv[1], sys.argv[1], sys.argv[2]) PY + if npm view "onekey-zcash-runtime@$VERSION" version >/dev/null 2>&1; then + echo "onekey-zcash-runtime@$VERSION is already on npm" >> "$GITHUB_STEP_SUMMARY" + test "$EVENT_NAME" = push || exit 1 + echo "publish=false" >> "$GITHUB_OUTPUT"; exit 0 + fi + { + echo "version=$VERSION" + echo "tag=$TAG" + echo "publish=true" + } >> "$GITHUB_OUTPUT" build: needs: validate + if: needs.validate.outputs.publish == 'true' uses: ./.github/workflows/zcash-runtime.yml publish: - needs: build + needs: [validate, build] + if: needs.validate.outputs.publish == 'true' runs-on: ubuntu-24.04 environment: npm-zcash steps: @@ -62,15 +92,15 @@ jobs: - name: Recheck and pack the verified build working-directory: chain-runtimes/zcash env: - RELEASE_VERSION: ${{ inputs.version }} - RELEASE_TAG: ${{ inputs.tag }} + RELEASE_VERSION: ${{ needs.validate.outputs.version }} + RELEASE_TAG: ${{ needs.validate.outputs.tag }} run: python3 scripts/package-release.py pack --version "$RELEASE_VERSION" --tag "$RELEASE_TAG" --revision "$GITHUB_SHA" - name: Publish the runtime and keys pair working-directory: chain-runtimes/zcash env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - RELEASE_VERSION: ${{ inputs.version }} - RELEASE_TAG: ${{ inputs.tag }} + RELEASE_VERSION: ${{ needs.validate.outputs.version }} + RELEASE_TAG: ${{ needs.validate.outputs.tag }} run: | npm publish "dist/onekey-zcash-runtime-${RELEASE_VERSION}.tgz" --ignore-scripts --access public --tag "$RELEASE_TAG" npm publish "dist/onekey-zcash-keys-${RELEASE_VERSION}.tgz" --ignore-scripts --access public --tag "$RELEASE_TAG" diff --git a/.github/workflows/zcash-runtime.yml b/.github/workflows/zcash-runtime.yml index 6315dc97f..22153154e 100644 --- a/.github/workflows/zcash-runtime.yml +++ b/.github/workflows/zcash-runtime.yml @@ -1,17 +1,15 @@ name: Zcash runtime +# Runs when runtime code changes. Edits to these workflow files alone do not +# trigger it (main may not carry the runtime yet); run it manually instead. on: pull_request: paths: - 'chain-runtimes/zcash/**' - - '.github/workflows/zcash-runtime.yml' - - '.github/workflows/zcash-publish.yml' push: branches: [main] paths: - 'chain-runtimes/zcash/**' - - '.github/workflows/zcash-runtime.yml' - - '.github/workflows/zcash-publish.yml' workflow_dispatch: workflow_call: diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md index 359470ad8..a865fa8fd 100644 --- a/chain-runtimes/monero/README.md +++ b/chain-runtimes/monero/README.md @@ -24,6 +24,14 @@ objects and silently writes an empty archive; linking then fails with `build-wasm.sh` finds Homebrew's clang and `llvm-ar` on Apple Silicon and Intel; `.cargo/config.toml` sets the Apple Silicon archiver for direct `cargo` builds. +## Release + +`onekey-monero-runtime` follows the Zcash runtime's release rules: a manual +**Publish Monero runtime** run publishes `X.Y.Z-alpha.N` from any branch, and +`rc`/`latest` versions publish only when a `Cargo.toml` version change is merged +to `main`. Locally, `python3 scripts/package-release.py --version --tag ` +packs the archive into `dist/` without publishing. + ## Host contract 1. **Import key images on unlock.** A view-only wallet cannot detect spends, so the diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md index 4a0a41375..8096b2edf 100644 --- a/chain-runtimes/zcash/RELEASING.md +++ b/chain-runtimes/zcash/RELEASING.md @@ -35,12 +35,17 @@ archives or manually rewrite the manifest to make an old artifact pass. ## Publish -For `rc` and `latest`, merge the release changes to `main` first; the -**Publish Zcash runtime** workflow refuses other branches for those tags. An -`alpha` can be published from any branch. The workflow is manual, accepts the -exact version and `alpha`/`rc`/`latest` tag, reuses the build/test workflow, verifies the downloaded artifact -again, and publishes only these two npm packages. The native-module publish -workflow is unchanged. +The **Publish Zcash runtime** workflow has two triggers: + +- **Manual run, alpha only.** Run it from any branch with the exact workspace + version (`X.Y.Z-alpha.N`). Any other version is refused. +- **Merge to `main`, rc and latest only.** When a change to `Cargo.toml` lands + on `main` with an `X.Y.Z-rc.N` or `X.Y.Z` version not yet on npm, it publishes + with the matching `rc` or `latest` tag. Alpha versions on `main` are skipped. + +Both reuse the build/test workflow, verify the downloaded artifact again, and +publish only these two npm packages. The native-module publish workflow is +unchanged. Repository maintainers must configure `NPM_TOKEN` with permission to publish `onekey-zcash-runtime` and `onekey-zcash-keys`. Configure required reviewers for From ada587b34d4b7e60a4799dfe5648a8a24e622538 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 22:29:03 +0800 Subject: [PATCH 30/97] ci: publish runtime alphas to npm next like the native previews --- .github/workflows/monero-publish.yml | 9 +++++---- .github/workflows/monero-runtime.yml | 2 +- .github/workflows/zcash-publish.yml | 9 +++++---- .github/workflows/zcash-runtime.yml | 2 +- chain-runtimes/monero/README.md | 2 +- chain-runtimes/monero/scripts/package-release.py | 6 +++--- chain-runtimes/zcash/RELEASING.md | 3 ++- chain-runtimes/zcash/scripts/package-release.py | 4 ++-- chain-runtimes/zcash/scripts/test_package_release.py | 2 +- 9 files changed, 21 insertions(+), 18 deletions(-) diff --git a/.github/workflows/monero-publish.yml b/.github/workflows/monero-publish.yml index 75b9cdc47..aa595aa16 100644 --- a/.github/workflows/monero-publish.yml +++ b/.github/workflows/monero-publish.yml @@ -1,6 +1,7 @@ name: Publish Monero runtime -# Manual runs publish alpha builds only, from any branch. rc and latest are +# Manual runs publish alpha builds (npm `next`, like the native previews) +# only, from any branch. rc and latest are # published only when a version change in chain-runtimes/monero/Cargo.toml is # merged to main. on: @@ -42,14 +43,14 @@ jobs: run: | VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("chain-runtimes/monero/Cargo.toml", "rb"))["workspace"]["package"]["version"])') case "$VERSION" in - *-alpha.*) TAG=alpha ;; + *-alpha.*) TAG=next ;; *-rc.*) TAG=rc ;; *) TAG=latest ;; esac if [ "$EVENT_NAME" = workflow_dispatch ]; then test "$INPUT_VERSION" = "$VERSION" || { echo "Input $INPUT_VERSION does not match workspace $VERSION" >&2; exit 1; } - test "$TAG" = alpha || { echo "Manual runs publish alpha only; merge $VERSION to main instead" >&2; exit 1; } - elif [ "$TAG" = alpha ]; then + test "$TAG" = next || { echo "Manual runs publish alpha only; merge $VERSION to main instead" >&2; exit 1; } + elif [ "$TAG" = next ]; then echo "Alpha versions are published manually; nothing to do on main" >> "$GITHUB_STEP_SUMMARY" echo "publish=false" >> "$GITHUB_OUTPUT"; exit 0 fi diff --git a/.github/workflows/monero-runtime.yml b/.github/workflows/monero-runtime.yml index 94de6e289..b780912e9 100644 --- a/.github/workflows/monero-runtime.yml +++ b/.github/workflows/monero-runtime.yml @@ -60,7 +60,7 @@ jobs: VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') TAG=latest if [[ "$VERSION" == *-rc.* ]]; then TAG=rc; fi - if [[ "$VERSION" == *-alpha.* ]]; then TAG=alpha; fi + if [[ "$VERSION" == *-alpha.* ]]; then TAG=next; fi python3 scripts/package-release.py --version "$VERSION" --tag "$TAG" - uses: actions/upload-artifact@v4 with: diff --git a/.github/workflows/zcash-publish.yml b/.github/workflows/zcash-publish.yml index 0edc9f919..d41ddbb5b 100644 --- a/.github/workflows/zcash-publish.yml +++ b/.github/workflows/zcash-publish.yml @@ -1,6 +1,7 @@ name: Publish Zcash runtime -# Manual runs publish alpha builds only, from any branch. rc and latest are +# Manual runs publish alpha builds (npm `next`, like the native previews) +# only, from any branch. rc and latest are # published only when a version change in chain-runtimes/zcash/Cargo.toml is # merged to main. on: @@ -42,14 +43,14 @@ jobs: run: | VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("chain-runtimes/zcash/Cargo.toml", "rb"))["workspace"]["package"]["version"])') case "$VERSION" in - *-alpha.*) TAG=alpha ;; + *-alpha.*) TAG=next ;; *-rc.*) TAG=rc ;; *) TAG=latest ;; esac if [ "$EVENT_NAME" = workflow_dispatch ]; then test "$INPUT_VERSION" = "$VERSION" || { echo "Input $INPUT_VERSION does not match workspace $VERSION" >&2; exit 1; } - test "$TAG" = alpha || { echo "Manual runs publish alpha only; merge $VERSION to main instead" >&2; exit 1; } - elif [ "$TAG" = alpha ]; then + test "$TAG" = next || { echo "Manual runs publish alpha only; merge $VERSION to main instead" >&2; exit 1; } + elif [ "$TAG" = next ]; then echo "Alpha versions are published manually; nothing to do on main" >> "$GITHUB_STEP_SUMMARY" echo "publish=false" >> "$GITHUB_OUTPUT"; exit 0 fi diff --git a/.github/workflows/zcash-runtime.yml b/.github/workflows/zcash-runtime.yml index 22153154e..9772fc74a 100644 --- a/.github/workflows/zcash-runtime.yml +++ b/.github/workflows/zcash-runtime.yml @@ -66,7 +66,7 @@ jobs: VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') TAG=latest if [[ "$VERSION" == *-rc.* ]]; then TAG=rc; fi - if [[ "$VERSION" == *-alpha.* ]]; then TAG=alpha; fi + if [[ "$VERSION" == *-alpha.* ]]; then TAG=next; fi python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$GITHUB_SHA" - uses: actions/upload-artifact@v4 with: diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md index a865fa8fd..bc012c51e 100644 --- a/chain-runtimes/monero/README.md +++ b/chain-runtimes/monero/README.md @@ -27,7 +27,7 @@ objects and silently writes an empty archive; linking then fails with ## Release `onekey-monero-runtime` follows the Zcash runtime's release rules: a manual -**Publish Monero runtime** run publishes `X.Y.Z-alpha.N` from any branch, and +**Publish Monero runtime** run publishes `X.Y.Z-alpha.N` to the npm `next` tag from any branch, and `rc`/`latest` versions publish only when a `Cargo.toml` version change is merged to `main`. Locally, `python3 scripts/package-release.py --version --tag ` packs the archive into `dist/` without publishing. diff --git a/chain-runtimes/monero/scripts/package-release.py b/chain-runtimes/monero/scripts/package-release.py index 329b95e86..e18b303cb 100644 --- a/chain-runtimes/monero/scripts/package-release.py +++ b/chain-runtimes/monero/scripts/package-release.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Pack the Monero runtime npm archive from a wasm-pack build. -Usage: python3 scripts/package-release.py --version 0.1.0-alpha.1 --tag alpha +Usage: python3 scripts/package-release.py --version 0.1.0-alpha.1 --tag next """ import argparse @@ -25,7 +25,7 @@ def check_version(value, expected, tag): match = re.fullmatch(r"\d+\.\d+\.\d+(?:-(alpha|rc)\.\d+)?", value) if value != expected or not match: raise ValueError("Release version must exactly match the workspace version") - required_tag = match.group(1) or "latest" + required_tag = {"alpha": "next", "rc": "rc"}.get(match.group(1), "latest") if tag != required_tag: raise ValueError(f"Version {value} requires npm dist-tag {required_tag}") @@ -52,7 +52,7 @@ def prepare(root=ROOT): def main(): parser = argparse.ArgumentParser() parser.add_argument("--version", required=True) - parser.add_argument("--tag", required=True, choices=["alpha", "rc", "latest"]) + parser.add_argument("--tag", required=True, choices=["next", "rc", "latest"]) args = parser.parse_args() check_version(args.version, workspace_version(), args.tag) prepare() diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md index 8096b2edf..caf257366 100644 --- a/chain-runtimes/zcash/RELEASING.md +++ b/chain-runtimes/zcash/RELEASING.md @@ -10,7 +10,8 @@ it, and wasm-pack generates the npm versions from those crates. Update the three workspace entries in `Cargo.lock` with `cargo check --workspace --offline` and review the lockfile diff; dependency upgrades are a separate change. -Development builds use `X.Y.Z-alpha.N` on the npm `alpha` tag and may be +Development builds use `X.Y.Z-alpha.N` on the npm `next` tag (as the native +modules' previews do) and may be published from any branch. Release candidates use `X.Y.Z-rc.N` on the npm `rc` tag; final releases use `latest`. Runtime and keys always share a version and source commit. The benchmark ships as a runtime subdirectory to keep the App developer tools' import diff --git a/chain-runtimes/zcash/scripts/package-release.py b/chain-runtimes/zcash/scripts/package-release.py index 8c5bfdfa9..4ef07a85c 100644 --- a/chain-runtimes/zcash/scripts/package-release.py +++ b/chain-runtimes/zcash/scripts/package-release.py @@ -24,7 +24,7 @@ def check_version(value, expected, tag): match = re.fullmatch(r"\d+\.\d+\.\d+(?:-(alpha|rc)\.\d+)?", value) if value != expected or not match: raise ValueError("Release version must exactly match the workspace version") - required_tag = match.group(1) or "latest" + required_tag = {"alpha": "next", "rc": "rc"}.get(match.group(1), "latest") if tag != required_tag: raise ValueError(f"Version {value} requires npm dist-tag {required_tag}") @@ -107,7 +107,7 @@ def pack(root, expected, tag, revision, allow_dirty=False): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("operation", choices=("prepare", "pack")) parser.add_argument("--version") - parser.add_argument("--tag", choices=("alpha", "rc", "latest")) + parser.add_argument("--tag", choices=("next", "rc", "latest")) parser.add_argument("--revision") parser.add_argument("--allow-dirty", action="store_true", help="Local pack checks only; never publish these archives") args = parser.parse_args() diff --git a/chain-runtimes/zcash/scripts/test_package_release.py b/chain-runtimes/zcash/scripts/test_package_release.py index 7261e1d27..ee1feb873 100644 --- a/chain-runtimes/zcash/scripts/test_package_release.py +++ b/chain-runtimes/zcash/scripts/test_package_release.py @@ -36,7 +36,7 @@ def test_prepare_preserves_benchmark_and_rejects_mixed_versions(self): release.prepare(root) def test_prereleases_cannot_update_latest(self): - release.check_version("0.1.0-alpha.1", "0.1.0-alpha.1", "alpha") + release.check_version("0.1.0-alpha.1", "0.1.0-alpha.1", "next") release.check_version("0.1.0-rc.1", "0.1.0-rc.1", "rc") release.check_version("0.1.0", "0.1.0", "latest") for expected, tag in (("0.1.0-rc.1", "latest"), ("0.1.0-rc.2", "rc")): From 8aed7cf9de32338cbabd58ef207bb7cdf90ee564 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 22:55:43 +0800 Subject: [PATCH 31/97] ci: publish from the runtime workflows like package-publish Each runtime workflow now selects the npm channel, packs and publishes with NPM_TOKEN in one job, as package-publish does. The separate publish workflows, their environments and the reusable-build hop are gone. A manual run publishes the branch's alpha to npm next; a push to main publishes new rc/latest. --- .github/workflows/monero-publish.yml | 97 ------------------------ .github/workflows/monero-runtime.yml | 61 +++++++++++---- .github/workflows/zcash-publish.yml | 107 --------------------------- .github/workflows/zcash-runtime.yml | 70 ++++++++++++------ chain-runtimes/monero/README.md | 10 +-- chain-runtimes/zcash/RELEASING.md | 27 +++---- 6 files changed, 109 insertions(+), 263 deletions(-) delete mode 100644 .github/workflows/monero-publish.yml delete mode 100644 .github/workflows/zcash-publish.yml diff --git a/.github/workflows/monero-publish.yml b/.github/workflows/monero-publish.yml deleted file mode 100644 index aa595aa16..000000000 --- a/.github/workflows/monero-publish.yml +++ /dev/null @@ -1,97 +0,0 @@ -name: Publish Monero runtime - -# Manual runs publish alpha builds (npm `next`, like the native previews) -# only, from any branch. rc and latest are -# published only when a version change in chain-runtimes/monero/Cargo.toml is -# merged to main. -on: - workflow_dispatch: - inputs: - version: - description: Exact workspace alpha version (for example 0.1.0-alpha.1) - required: true - type: string - push: - branches: [main] - paths: - - 'chain-runtimes/monero/Cargo.toml' - -permissions: - contents: read - -concurrency: - group: monero-npm-publish - cancel-in-progress: false - -jobs: - validate: - runs-on: ubuntu-24.04 - outputs: - version: ${{ steps.plan.outputs.version }} - tag: ${{ steps.plan.outputs.tag }} - publish: ${{ steps.plan.outputs.publish }} - steps: - - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 - with: - node-version: '24.x' - - name: Decide what to publish - id: plan - env: - EVENT_NAME: ${{ github.event_name }} - INPUT_VERSION: ${{ inputs.version }} - run: | - VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("chain-runtimes/monero/Cargo.toml", "rb"))["workspace"]["package"]["version"])') - case "$VERSION" in - *-alpha.*) TAG=next ;; - *-rc.*) TAG=rc ;; - *) TAG=latest ;; - esac - if [ "$EVENT_NAME" = workflow_dispatch ]; then - test "$INPUT_VERSION" = "$VERSION" || { echo "Input $INPUT_VERSION does not match workspace $VERSION" >&2; exit 1; } - test "$TAG" = next || { echo "Manual runs publish alpha only; merge $VERSION to main instead" >&2; exit 1; } - elif [ "$TAG" = next ]; then - echo "Alpha versions are published manually; nothing to do on main" >> "$GITHUB_STEP_SUMMARY" - echo "publish=false" >> "$GITHUB_OUTPUT"; exit 0 - fi - python3 - "$VERSION" "$TAG" <<'PY' - import importlib.util, sys - spec = importlib.util.spec_from_file_location('release', 'chain-runtimes/monero/scripts/package-release.py') - release = importlib.util.module_from_spec(spec) - spec.loader.exec_module(release) - release.check_version(sys.argv[1], sys.argv[1], sys.argv[2]) - PY - if npm view "onekey-monero-runtime@$VERSION" version >/dev/null 2>&1; then - echo "onekey-monero-runtime@$VERSION is already on npm" >> "$GITHUB_STEP_SUMMARY" - test "$EVENT_NAME" = push || exit 1 - echo "publish=false" >> "$GITHUB_OUTPUT"; exit 0 - fi - { - echo "version=$VERSION" - echo "tag=$TAG" - echo "publish=true" - } >> "$GITHUB_OUTPUT" - build: - needs: validate - if: needs.validate.outputs.publish == 'true' - uses: ./.github/workflows/monero-runtime.yml - publish: - needs: [validate, build] - if: needs.validate.outputs.publish == 'true' - runs-on: ubuntu-24.04 - environment: npm-monero - steps: - - uses: actions/setup-node@v6 - with: - node-version: '24.x' - registry-url: https://registry.npmjs.org - - uses: actions/download-artifact@v4 - with: - name: monero-npm-${{ github.sha }} - path: dist - - name: Publish the runtime - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - RELEASE_VERSION: ${{ needs.validate.outputs.version }} - RELEASE_TAG: ${{ needs.validate.outputs.tag }} - run: npm publish "dist/onekey-monero-runtime-${RELEASE_VERSION}.tgz" --ignore-scripts --access public --tag "$RELEASE_TAG" diff --git a/.github/workflows/monero-runtime.yml b/.github/workflows/monero-runtime.yml index b780912e9..e51e7b8f5 100644 --- a/.github/workflows/monero-runtime.yml +++ b/.github/workflows/monero-runtime.yml @@ -1,7 +1,7 @@ name: Monero runtime -# Runs when runtime code changes. Edits to these workflow files alone do not -# trigger it (main may not carry the runtime yet); run it manually instead. +# Builds and tests on runtime changes. A manual run also publishes the branch's +# alpha version; a push to main publishes a new rc or latest version. on: pull_request: paths: @@ -11,7 +11,6 @@ on: paths: - 'chain-runtimes/monero/**' workflow_dispatch: - workflow_call: permissions: contents: read @@ -25,6 +24,38 @@ jobs: working-directory: chain-runtimes/monero steps: - uses: actions/checkout@v6 + - uses: actions/setup-node@v6 + with: + node-version: '24.x' + registry-url: https://registry.npmjs.org + # Manual runs publish the branch's alpha version to npm next; rc and + # latest versions publish only when merged to main. + - name: Select release channel + id: channel + env: + EVENT_NAME: ${{ github.event_name }} + run: | + VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') + case "$VERSION" in + *-alpha.*) TAG=next ;; + *-rc.*) TAG=rc ;; + *) TAG=latest ;; + esac + PUBLISH=false + if [ "$EVENT_NAME" = workflow_dispatch ]; then + test "$TAG" = next || { echo "Manual runs publish alpha versions only; merge $VERSION to main instead" >&2; exit 1; } + PUBLISH=true + elif [ "$EVENT_NAME" = push ] && [ "$TAG" != next ]; then + PUBLISH=true + fi + if [ "$PUBLISH" = true ] && npm view "onekey-monero-runtime@$VERSION" version >/dev/null 2>&1; then + test "$EVENT_NAME" = push || { echo "onekey-monero-runtime@$VERSION is already on npm" >&2; exit 1; } + PUBLISH=false + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "tag=$TAG" >> "$GITHUB_OUTPUT" + echo "publish=$PUBLISH" >> "$GITHUB_OUTPUT" + echo "Version $VERSION, npm dist-tag $TAG, publish: $PUBLISH" >> "$GITHUB_STEP_SUMMARY" - name: Install Binaryen 133 (same wasm-opt as local builds) run: | BINARYEN=version_133 @@ -52,18 +83,16 @@ jobs: CC_wasm32_unknown_unknown: /usr/bin/clang AR_wasm32_unknown_unknown: /usr/bin/llvm-ar run: bash scripts/build-wasm.sh release - - uses: actions/setup-node@v6 - with: - node-version: '24.x' - name: Pack npm archive + env: + VERSION: ${{ steps.channel.outputs.version }} + TAG: ${{ steps.channel.outputs.tag }} + run: python3 scripts/package-release.py --version "$VERSION" --tag "$TAG" + - name: Publish runtime + if: steps.channel.outputs.publish == 'true' + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + VERSION: ${{ steps.channel.outputs.version }} + TAG: ${{ steps.channel.outputs.tag }} run: | - VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') - TAG=latest - if [[ "$VERSION" == *-rc.* ]]; then TAG=rc; fi - if [[ "$VERSION" == *-alpha.* ]]; then TAG=next; fi - python3 scripts/package-release.py --version "$VERSION" --tag "$TAG" - - uses: actions/upload-artifact@v4 - with: - name: monero-npm-${{ github.sha }} - if-no-files-found: error - path: chain-runtimes/monero/dist/ + npm publish "dist/onekey-monero-runtime-${VERSION}.tgz" --ignore-scripts --access public --tag "$TAG" diff --git a/.github/workflows/zcash-publish.yml b/.github/workflows/zcash-publish.yml deleted file mode 100644 index d41ddbb5b..000000000 --- a/.github/workflows/zcash-publish.yml +++ /dev/null @@ -1,107 +0,0 @@ -name: Publish Zcash runtime - -# Manual runs publish alpha builds (npm `next`, like the native previews) -# only, from any branch. rc and latest are -# published only when a version change in chain-runtimes/zcash/Cargo.toml is -# merged to main. -on: - workflow_dispatch: - inputs: - version: - description: Exact workspace alpha version (for example 0.1.0-alpha.1) - required: true - type: string - push: - branches: [main] - paths: - - 'chain-runtimes/zcash/Cargo.toml' - -permissions: - contents: read - -concurrency: - group: zcash-npm-publish - cancel-in-progress: false - -jobs: - validate: - runs-on: ubuntu-24.04 - outputs: - version: ${{ steps.plan.outputs.version }} - tag: ${{ steps.plan.outputs.tag }} - publish: ${{ steps.plan.outputs.publish }} - steps: - - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 - with: - node-version: '24.x' - - name: Decide what to publish - id: plan - env: - EVENT_NAME: ${{ github.event_name }} - INPUT_VERSION: ${{ inputs.version }} - run: | - VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("chain-runtimes/zcash/Cargo.toml", "rb"))["workspace"]["package"]["version"])') - case "$VERSION" in - *-alpha.*) TAG=next ;; - *-rc.*) TAG=rc ;; - *) TAG=latest ;; - esac - if [ "$EVENT_NAME" = workflow_dispatch ]; then - test "$INPUT_VERSION" = "$VERSION" || { echo "Input $INPUT_VERSION does not match workspace $VERSION" >&2; exit 1; } - test "$TAG" = next || { echo "Manual runs publish alpha only; merge $VERSION to main instead" >&2; exit 1; } - elif [ "$TAG" = next ]; then - echo "Alpha versions are published manually; nothing to do on main" >> "$GITHUB_STEP_SUMMARY" - echo "publish=false" >> "$GITHUB_OUTPUT"; exit 0 - fi - python3 - "$VERSION" "$TAG" <<'PY' - import importlib.util, sys - spec = importlib.util.spec_from_file_location('release', 'chain-runtimes/zcash/scripts/package-release.py') - release = importlib.util.module_from_spec(spec) - spec.loader.exec_module(release) - release.check_version(sys.argv[1], sys.argv[1], sys.argv[2]) - PY - if npm view "onekey-zcash-runtime@$VERSION" version >/dev/null 2>&1; then - echo "onekey-zcash-runtime@$VERSION is already on npm" >> "$GITHUB_STEP_SUMMARY" - test "$EVENT_NAME" = push || exit 1 - echo "publish=false" >> "$GITHUB_OUTPUT"; exit 0 - fi - { - echo "version=$VERSION" - echo "tag=$TAG" - echo "publish=true" - } >> "$GITHUB_OUTPUT" - build: - needs: validate - if: needs.validate.outputs.publish == 'true' - uses: ./.github/workflows/zcash-runtime.yml - publish: - needs: [validate, build] - if: needs.validate.outputs.publish == 'true' - runs-on: ubuntu-24.04 - environment: npm-zcash - steps: - - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 - with: - node-version: '24.x' - registry-url: https://registry.npmjs.org - - uses: actions/download-artifact@v4 - with: - name: zcash-wasm-${{ github.sha }} - path: chain-runtimes/zcash - - name: Recheck and pack the verified build - working-directory: chain-runtimes/zcash - env: - RELEASE_VERSION: ${{ needs.validate.outputs.version }} - RELEASE_TAG: ${{ needs.validate.outputs.tag }} - run: python3 scripts/package-release.py pack --version "$RELEASE_VERSION" --tag "$RELEASE_TAG" --revision "$GITHUB_SHA" - - name: Publish the runtime and keys pair - working-directory: chain-runtimes/zcash - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - RELEASE_VERSION: ${{ needs.validate.outputs.version }} - RELEASE_TAG: ${{ needs.validate.outputs.tag }} - run: | - npm publish "dist/onekey-zcash-runtime-${RELEASE_VERSION}.tgz" --ignore-scripts --access public --tag "$RELEASE_TAG" - npm publish "dist/onekey-zcash-keys-${RELEASE_VERSION}.tgz" --ignore-scripts --access public --tag "$RELEASE_TAG" diff --git a/.github/workflows/zcash-runtime.yml b/.github/workflows/zcash-runtime.yml index 9772fc74a..0f4435c80 100644 --- a/.github/workflows/zcash-runtime.yml +++ b/.github/workflows/zcash-runtime.yml @@ -1,7 +1,7 @@ name: Zcash runtime -# Runs when runtime code changes. Edits to these workflow files alone do not -# trigger it (main may not carry the runtime yet); run it manually instead. +# Builds and tests on runtime changes. A manual run also publishes the branch's +# alpha version; a push to main publishes a new rc or latest version. on: pull_request: paths: @@ -11,7 +11,6 @@ on: paths: - 'chain-runtimes/zcash/**' workflow_dispatch: - workflow_call: permissions: contents: read @@ -25,6 +24,38 @@ jobs: working-directory: chain-runtimes/zcash steps: - uses: actions/checkout@v6 + - uses: actions/setup-node@v6 + with: + node-version: '24.x' + registry-url: https://registry.npmjs.org + # Manual runs publish the branch's alpha version to npm next; rc and + # latest versions publish only when merged to main. + - name: Select release channel + id: channel + env: + EVENT_NAME: ${{ github.event_name }} + run: | + VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') + case "$VERSION" in + *-alpha.*) TAG=next ;; + *-rc.*) TAG=rc ;; + *) TAG=latest ;; + esac + PUBLISH=false + if [ "$EVENT_NAME" = workflow_dispatch ]; then + test "$TAG" = next || { echo "Manual runs publish alpha versions only; merge $VERSION to main instead" >&2; exit 1; } + PUBLISH=true + elif [ "$EVENT_NAME" = push ] && [ "$TAG" != next ]; then + PUBLISH=true + fi + if [ "$PUBLISH" = true ] && npm view "onekey-zcash-runtime@$VERSION" version >/dev/null 2>&1; then + test "$EVENT_NAME" = push || { echo "onekey-zcash-runtime@$VERSION is already on npm" >&2; exit 1; } + PUBLISH=false + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "tag=$TAG" >> "$GITHUB_OUTPUT" + echo "publish=$PUBLISH" >> "$GITHUB_OUTPUT" + echo "Version $VERSION, npm dist-tag $TAG, publish: $PUBLISH" >> "$GITHUB_STEP_SUMMARY" - name: Install Binaryen 133 (same wasm-opt as local builds) run: | BINARYEN=version_133 @@ -58,26 +89,23 @@ jobs: run: bash scripts/build-wasm.sh --offline - name: Verify complete artifact provenance run: python3 scripts/artifact-manifest.py verify --expected-revision "${{ github.sha }}" - - uses: actions/setup-node@v6 - with: - node-version: '24.x' - - name: Verify npm archives - run: | - VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') - TAG=latest - if [[ "$VERSION" == *-rc.* ]]; then TAG=rc; fi - if [[ "$VERSION" == *-alpha.* ]]; then TAG=next; fi - python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$GITHUB_SHA" - - uses: actions/upload-artifact@v4 - with: - name: zcash-wasm-${{ github.sha }} - if-no-files-found: error - path: | - chain-runtimes/zcash/pkg/ - chain-runtimes/zcash/pkg-keys/ - chain-runtimes/zcash/zcash-wasm-manifest.json + - name: Pack and verify npm archives + env: + VERSION: ${{ steps.channel.outputs.version }} + TAG: ${{ steps.channel.outputs.tag }} + run: python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$GITHUB_SHA" + # Kept so a half-finished publish can be completed from the same bytes. - uses: actions/upload-artifact@v4 with: name: zcash-npm-${{ github.sha }} if-no-files-found: error path: chain-runtimes/zcash/dist/ + - name: Publish runtime and keys + if: steps.channel.outputs.publish == 'true' + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + VERSION: ${{ steps.channel.outputs.version }} + TAG: ${{ steps.channel.outputs.tag }} + run: | + npm publish "dist/onekey-zcash-runtime-${VERSION}.tgz" --ignore-scripts --access public --tag "$TAG" + npm publish "dist/onekey-zcash-keys-${VERSION}.tgz" --ignore-scripts --access public --tag "$TAG" diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md index bc012c51e..96f62ed19 100644 --- a/chain-runtimes/monero/README.md +++ b/chain-runtimes/monero/README.md @@ -26,11 +26,11 @@ objects and silently writes an empty archive; linking then fails with ## Release -`onekey-monero-runtime` follows the Zcash runtime's release rules: a manual -**Publish Monero runtime** run publishes `X.Y.Z-alpha.N` to the npm `next` tag from any branch, and -`rc`/`latest` versions publish only when a `Cargo.toml` version change is merged -to `main`. Locally, `python3 scripts/package-release.py --version --tag ` -packs the archive into `dist/` without publishing. +The **Monero runtime** workflow follows the Zcash runtime's rules: a manual run +publishes the branch's `X.Y.Z-alpha.N` version to the npm `next` tag, and `rc` or +`latest` versions publish only when merged to `main`. Locally, +`python3 scripts/package-release.py --version --tag ` packs the archive +into `dist/` without publishing. ## Host contract diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md index caf257366..929cc7043 100644 --- a/chain-runtimes/zcash/RELEASING.md +++ b/chain-runtimes/zcash/RELEASING.md @@ -36,26 +36,19 @@ archives or manually rewrite the manifest to make an old artifact pass. ## Publish -The **Publish Zcash runtime** workflow has two triggers: +The **Zcash runtime** workflow builds, tests and packs on every runtime change, +and publishes the two npm packages with the repository's `NPM_TOKEN`, like the +native modules' `package-publish`: -- **Manual run, alpha only.** Run it from any branch with the exact workspace - version (`X.Y.Z-alpha.N`). Any other version is refused. -- **Merge to `main`, rc and latest only.** When a change to `Cargo.toml` lands - on `main` with an `X.Y.Z-rc.N` or `X.Y.Z` version not yet on npm, it publishes - with the matching `rc` or `latest` tag. Alpha versions on `main` are skipped. - -Both reuse the build/test workflow, verify the downloaded artifact again, and -publish only these two npm packages. The native-module publish workflow is -unchanged. - -Repository maintainers must configure `NPM_TOKEN` with permission to publish -`onekey-zcash-runtime` and `onekey-zcash-keys`. Configure required reviewers for -the `npm-zcash` GitHub environment if a separate release approval is desired. -The environment name alone does not enable approval protection. +- **Manual run: alpha only.** Running it on a branch publishes that branch's + `X.Y.Z-alpha.N` version to the npm `next` tag. Any other version is refused. +- **Merge to `main`: rc and latest only.** A push to `main` whose version is + `X.Y.Z-rc.N` or `X.Y.Z` and not yet on npm publishes it with the `rc` or + `latest` tag. Alpha versions on `main` are not published. npm cannot publish two packages atomically. If publishing one succeeds and the -other fails, do not consume the version until both exist. Restore the exact -verified artifact from that workflow run and publish only the missing package; +other fails, do not consume the version until both exist. Download the +`zcash-npm-` artifact from that run and publish only the missing package; never overwrite an existing version or rebuild different bytes under that version. ## App cutover From 7b9dab959f1b6f44ab00ba101a49176397162c12 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Tue, 13 Oct 2026 23:09:22 +0800 Subject: [PATCH 32/97] ci: build, pack and publish on manual runs only Drop the release-channel step and automatic publishing. A manual run publishes prereleases to npm next and release versions (from main only) to latest; npm requires a tag for prereleases. --- .github/workflows/monero-runtime.yml | 60 ++++++------------ .github/workflows/zcash-runtime.yml | 62 ++++++------------- chain-runtimes/monero/README.md | 10 +-- .../monero/scripts/package-release.py | 4 +- chain-runtimes/zcash/RELEASING.md | 21 +++---- .../zcash/scripts/package-release.py | 4 +- .../zcash/scripts/test_package_release.py | 11 ++-- 7 files changed, 57 insertions(+), 115 deletions(-) diff --git a/.github/workflows/monero-runtime.yml b/.github/workflows/monero-runtime.yml index e51e7b8f5..c69dd1e17 100644 --- a/.github/workflows/monero-runtime.yml +++ b/.github/workflows/monero-runtime.yml @@ -1,7 +1,7 @@ name: Monero runtime -# Builds and tests on runtime changes. A manual run also publishes the branch's -# alpha version; a push to main publishes a new rc or latest version. +# Builds and tests on runtime changes. A manual run also publishes to npm: +# prerelease versions to `next`, release versions (from main only) to `latest`. on: pull_request: paths: @@ -24,38 +24,6 @@ jobs: working-directory: chain-runtimes/monero steps: - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 - with: - node-version: '24.x' - registry-url: https://registry.npmjs.org - # Manual runs publish the branch's alpha version to npm next; rc and - # latest versions publish only when merged to main. - - name: Select release channel - id: channel - env: - EVENT_NAME: ${{ github.event_name }} - run: | - VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') - case "$VERSION" in - *-alpha.*) TAG=next ;; - *-rc.*) TAG=rc ;; - *) TAG=latest ;; - esac - PUBLISH=false - if [ "$EVENT_NAME" = workflow_dispatch ]; then - test "$TAG" = next || { echo "Manual runs publish alpha versions only; merge $VERSION to main instead" >&2; exit 1; } - PUBLISH=true - elif [ "$EVENT_NAME" = push ] && [ "$TAG" != next ]; then - PUBLISH=true - fi - if [ "$PUBLISH" = true ] && npm view "onekey-monero-runtime@$VERSION" version >/dev/null 2>&1; then - test "$EVENT_NAME" = push || { echo "onekey-monero-runtime@$VERSION is already on npm" >&2; exit 1; } - PUBLISH=false - fi - echo "version=$VERSION" >> "$GITHUB_OUTPUT" - echo "tag=$TAG" >> "$GITHUB_OUTPUT" - echo "publish=$PUBLISH" >> "$GITHUB_OUTPUT" - echo "Version $VERSION, npm dist-tag $TAG, publish: $PUBLISH" >> "$GITHUB_STEP_SUMMARY" - name: Install Binaryen 133 (same wasm-opt as local builds) run: | BINARYEN=version_133 @@ -83,16 +51,24 @@ jobs: CC_wasm32_unknown_unknown: /usr/bin/clang AR_wasm32_unknown_unknown: /usr/bin/llvm-ar run: bash scripts/build-wasm.sh release + - uses: actions/setup-node@v6 + with: + node-version: '24.x' + registry-url: https://registry.npmjs.org - name: Pack npm archive - env: - VERSION: ${{ steps.channel.outputs.version }} - TAG: ${{ steps.channel.outputs.tag }} - run: python3 scripts/package-release.py --version "$VERSION" --tag "$TAG" - - name: Publish runtime - if: steps.channel.outputs.publish == 'true' + run: | + VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') + TAG=latest + if [[ "$VERSION" == *-* ]]; then TAG=next; fi + echo "VERSION=$VERSION" >> "$GITHUB_ENV" + echo "TAG=$TAG" >> "$GITHUB_ENV" + python3 scripts/package-release.py --version "$VERSION" --tag "$TAG" + - name: Publish + if: github.event_name == 'workflow_dispatch' env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - VERSION: ${{ steps.channel.outputs.version }} - TAG: ${{ steps.channel.outputs.tag }} run: | + if [ "$TAG" = latest ] && [ "$GITHUB_REF" != refs/heads/main ]; then + echo "Release versions publish from main only" >&2; exit 1 + fi npm publish "dist/onekey-monero-runtime-${VERSION}.tgz" --ignore-scripts --access public --tag "$TAG" diff --git a/.github/workflows/zcash-runtime.yml b/.github/workflows/zcash-runtime.yml index 0f4435c80..e09f48b32 100644 --- a/.github/workflows/zcash-runtime.yml +++ b/.github/workflows/zcash-runtime.yml @@ -1,7 +1,7 @@ name: Zcash runtime -# Builds and tests on runtime changes. A manual run also publishes the branch's -# alpha version; a push to main publishes a new rc or latest version. +# Builds and tests on runtime changes. A manual run also publishes to npm: +# prerelease versions to `next`, release versions (from main only) to `latest`. on: pull_request: paths: @@ -24,38 +24,6 @@ jobs: working-directory: chain-runtimes/zcash steps: - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 - with: - node-version: '24.x' - registry-url: https://registry.npmjs.org - # Manual runs publish the branch's alpha version to npm next; rc and - # latest versions publish only when merged to main. - - name: Select release channel - id: channel - env: - EVENT_NAME: ${{ github.event_name }} - run: | - VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') - case "$VERSION" in - *-alpha.*) TAG=next ;; - *-rc.*) TAG=rc ;; - *) TAG=latest ;; - esac - PUBLISH=false - if [ "$EVENT_NAME" = workflow_dispatch ]; then - test "$TAG" = next || { echo "Manual runs publish alpha versions only; merge $VERSION to main instead" >&2; exit 1; } - PUBLISH=true - elif [ "$EVENT_NAME" = push ] && [ "$TAG" != next ]; then - PUBLISH=true - fi - if [ "$PUBLISH" = true ] && npm view "onekey-zcash-runtime@$VERSION" version >/dev/null 2>&1; then - test "$EVENT_NAME" = push || { echo "onekey-zcash-runtime@$VERSION is already on npm" >&2; exit 1; } - PUBLISH=false - fi - echo "version=$VERSION" >> "$GITHUB_OUTPUT" - echo "tag=$TAG" >> "$GITHUB_OUTPUT" - echo "publish=$PUBLISH" >> "$GITHUB_OUTPUT" - echo "Version $VERSION, npm dist-tag $TAG, publish: $PUBLISH" >> "$GITHUB_STEP_SUMMARY" - name: Install Binaryen 133 (same wasm-opt as local builds) run: | BINARYEN=version_133 @@ -89,23 +57,31 @@ jobs: run: bash scripts/build-wasm.sh --offline - name: Verify complete artifact provenance run: python3 scripts/artifact-manifest.py verify --expected-revision "${{ github.sha }}" - - name: Pack and verify npm archives - env: - VERSION: ${{ steps.channel.outputs.version }} - TAG: ${{ steps.channel.outputs.tag }} - run: python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$GITHUB_SHA" + - uses: actions/setup-node@v6 + with: + node-version: '24.x' + registry-url: https://registry.npmjs.org + - name: Pack npm archives + run: | + VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') + TAG=latest + if [[ "$VERSION" == *-* ]]; then TAG=next; fi + echo "VERSION=$VERSION" >> "$GITHUB_ENV" + echo "TAG=$TAG" >> "$GITHUB_ENV" + python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$GITHUB_SHA" # Kept so a half-finished publish can be completed from the same bytes. - uses: actions/upload-artifact@v4 with: name: zcash-npm-${{ github.sha }} if-no-files-found: error path: chain-runtimes/zcash/dist/ - - name: Publish runtime and keys - if: steps.channel.outputs.publish == 'true' + - name: Publish + if: github.event_name == 'workflow_dispatch' env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - VERSION: ${{ steps.channel.outputs.version }} - TAG: ${{ steps.channel.outputs.tag }} run: | + if [ "$TAG" = latest ] && [ "$GITHUB_REF" != refs/heads/main ]; then + echo "Release versions publish from main only" >&2; exit 1 + fi npm publish "dist/onekey-zcash-runtime-${VERSION}.tgz" --ignore-scripts --access public --tag "$TAG" npm publish "dist/onekey-zcash-keys-${VERSION}.tgz" --ignore-scripts --access public --tag "$TAG" diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md index 96f62ed19..9ebd9be78 100644 --- a/chain-runtimes/monero/README.md +++ b/chain-runtimes/monero/README.md @@ -26,11 +26,11 @@ objects and silently writes an empty archive; linking then fails with ## Release -The **Monero runtime** workflow follows the Zcash runtime's rules: a manual run -publishes the branch's `X.Y.Z-alpha.N` version to the npm `next` tag, and `rc` or -`latest` versions publish only when merged to `main`. Locally, -`python3 scripts/package-release.py --version --tag ` packs the archive -into `dist/` without publishing. +Run the **Monero runtime** workflow manually to build, test and publish +`onekey-monero-runtime`: prereleases to npm `next` from any branch, release +versions to `latest` from `main` only. Locally, +`python3 scripts/package-release.py --version --tag ` packs the +archive into `dist/` without publishing. ## Host contract diff --git a/chain-runtimes/monero/scripts/package-release.py b/chain-runtimes/monero/scripts/package-release.py index e18b303cb..df01d8019 100644 --- a/chain-runtimes/monero/scripts/package-release.py +++ b/chain-runtimes/monero/scripts/package-release.py @@ -25,7 +25,7 @@ def check_version(value, expected, tag): match = re.fullmatch(r"\d+\.\d+\.\d+(?:-(alpha|rc)\.\d+)?", value) if value != expected or not match: raise ValueError("Release version must exactly match the workspace version") - required_tag = {"alpha": "next", "rc": "rc"}.get(match.group(1), "latest") + required_tag = "next" if match.group(1) else "latest" if tag != required_tag: raise ValueError(f"Version {value} requires npm dist-tag {required_tag}") @@ -52,7 +52,7 @@ def prepare(root=ROOT): def main(): parser = argparse.ArgumentParser() parser.add_argument("--version", required=True) - parser.add_argument("--tag", required=True, choices=["next", "rc", "latest"]) + parser.add_argument("--tag", required=True, choices=["next", "latest"]) args = parser.parse_args() check_version(args.version, workspace_version(), args.tag) prepare() diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md index 929cc7043..330f4b6f6 100644 --- a/chain-runtimes/zcash/RELEASING.md +++ b/chain-runtimes/zcash/RELEASING.md @@ -10,10 +10,8 @@ it, and wasm-pack generates the npm versions from those crates. Update the three workspace entries in `Cargo.lock` with `cargo check --workspace --offline` and review the lockfile diff; dependency upgrades are a separate change. -Development builds use `X.Y.Z-alpha.N` on the npm `next` tag (as the native -modules' previews do) and may be -published from any branch. Release candidates use `X.Y.Z-rc.N` on the npm `rc` -tag; final releases use `latest`. Runtime and keys always share a version and source commit. The +Prerelease versions (`X.Y.Z-alpha.N`, `X.Y.Z-rc.N`) go to the npm `next` tag, +release versions to `latest`. Runtime and keys always share a version and source commit. The benchmark ships as a runtime subdirectory to keep the App developer tools' import path; it is not a third package, and production App bundles exclude it. @@ -26,7 +24,7 @@ Use Python 3.11+ and the pinned Rust/WASM tools described in README.md. 2. Commit the release changes. A release build must come from a clean checkout. 3. Run `bash scripts/build-wasm.sh --offline`. This builds all three WASM artifacts, prepares npm metadata and LICENSE, and writes the source manifest. -4. Run `python3 scripts/package-release.py pack --version 0.1.0-rc.1 --tag rc +4. Run `python3 scripts/package-release.py pack --version 0.1.0-rc.1 --tag next --revision ` (as one command). It checks clean-source provenance, Cargo.lock, all artifact hashes, versions, and npm archive contents. `dist/` contains the two verified tarballs and source manifest. @@ -36,15 +34,10 @@ archives or manually rewrite the manifest to make an old artifact pass. ## Publish -The **Zcash runtime** workflow builds, tests and packs on every runtime change, -and publishes the two npm packages with the repository's `NPM_TOKEN`, like the -native modules' `package-publish`: - -- **Manual run: alpha only.** Running it on a branch publishes that branch's - `X.Y.Z-alpha.N` version to the npm `next` tag. Any other version is refused. -- **Merge to `main`: rc and latest only.** A push to `main` whose version is - `X.Y.Z-rc.N` or `X.Y.Z` and not yet on npm publishes it with the `rc` or - `latest` tag. Alpha versions on `main` are not published. +Run the **Zcash runtime** workflow manually. It builds, tests, packs and +publishes both npm packages with the repository's `NPM_TOKEN`, like the native +modules' `package-publish`. Prereleases can be published from any branch; +release versions only from `main`. npm cannot publish two packages atomically. If publishing one succeeds and the other fails, do not consume the version until both exist. Download the diff --git a/chain-runtimes/zcash/scripts/package-release.py b/chain-runtimes/zcash/scripts/package-release.py index 4ef07a85c..ec5b7a68f 100644 --- a/chain-runtimes/zcash/scripts/package-release.py +++ b/chain-runtimes/zcash/scripts/package-release.py @@ -24,7 +24,7 @@ def check_version(value, expected, tag): match = re.fullmatch(r"\d+\.\d+\.\d+(?:-(alpha|rc)\.\d+)?", value) if value != expected or not match: raise ValueError("Release version must exactly match the workspace version") - required_tag = {"alpha": "next", "rc": "rc"}.get(match.group(1), "latest") + required_tag = "next" if match.group(1) else "latest" if tag != required_tag: raise ValueError(f"Version {value} requires npm dist-tag {required_tag}") @@ -107,7 +107,7 @@ def pack(root, expected, tag, revision, allow_dirty=False): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("operation", choices=("prepare", "pack")) parser.add_argument("--version") - parser.add_argument("--tag", choices=("next", "rc", "latest")) + parser.add_argument("--tag", choices=("next", "latest")) parser.add_argument("--revision") parser.add_argument("--allow-dirty", action="store_true", help="Local pack checks only; never publish these archives") args = parser.parse_args() diff --git a/chain-runtimes/zcash/scripts/test_package_release.py b/chain-runtimes/zcash/scripts/test_package_release.py index ee1feb873..c83f5e65f 100644 --- a/chain-runtimes/zcash/scripts/test_package_release.py +++ b/chain-runtimes/zcash/scripts/test_package_release.py @@ -37,16 +37,13 @@ def test_prepare_preserves_benchmark_and_rejects_mixed_versions(self): def test_prereleases_cannot_update_latest(self): release.check_version("0.1.0-alpha.1", "0.1.0-alpha.1", "next") - release.check_version("0.1.0-rc.1", "0.1.0-rc.1", "rc") + release.check_version("0.1.0-rc.1", "0.1.0-rc.1", "next") release.check_version("0.1.0", "0.1.0", "latest") - for expected, tag in (("0.1.0-rc.1", "latest"), ("0.1.0-rc.2", "rc")): + for value, tag in (("0.1.0-alpha.1", "latest"), ("0.1.0", "next")): with self.assertRaises(ValueError): - release.check_version("0.1.0-rc.1", expected, tag) - for tag in ("rc", "latest"): - with self.assertRaises(ValueError): - release.check_version("0.1.0-alpha.1", "0.1.0-alpha.1", tag) + release.check_version(value, value, tag) with self.assertRaises(ValueError): - release.check_version("0.1.0-beta.1", "0.1.0-beta.1", "rc") + release.check_version("0.1.0-rc.1", "0.1.0-rc.2", "next") def test_missing_benchmark_and_changed_bytes_are_rejected(self): with tempfile.TemporaryDirectory() as directory: From 32cf763b88f0b7b80b3d32a6818722f11a21a306 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Wed, 14 Oct 2026 10:06:02 +0800 Subject: [PATCH 33/97] fix(monero): bind broadcast records to the sending account and accept one recipient A first broadcast now requires every input to be an unspent output of the given account, so a wrong accountId can no longer record the send elsewhere and free the real account's reserved inputs. The reservation release is scoped to that account. Preparation accepts exactly one recipient, matching the review. --- chain-runtimes/monero/README.md | 4 + .../monero/crates/monero-runtime/src/spend.rs | 117 ++++++++++++++++-- chain-runtimes/monero/scripts/smoke.js | 19 +++ 3 files changed, 130 insertions(+), 10 deletions(-) diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md index 9ebd9be78..085226d85 100644 --- a/chain-runtimes/monero/README.md +++ b/chain-runtimes/monero/README.md @@ -94,6 +94,10 @@ signTransaction verify again, then sign; no network, no DB broadcastTransaction record, then broadcast → { txid, broadcast: accepted | unknown } ``` +`prepareTransaction` takes exactly one recipient. A first `broadcastTransaction` +whose inputs are not this account's, or are already spent by another transaction, +is refused with `INVALID_REQUEST` before anything is recorded or sent. + `BROADCAST_REJECTED` is thrown only when the node explicitly rejects a first broadcast for a reason other than double spend; the record is then undone and the inputs released. Unsigned reservations expire after 1 hour, signed ones after 24 diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs index 4dfe6a8d1..a6e7eddad 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs @@ -1267,6 +1267,60 @@ mod tests { assert_eq!(rows, 0, "rejected transaction is not kept in history"); } + /// A send passed with the wrong account records nothing and leaves the + /// source account's reservation and inputs as they were. + #[test] + fn a_broadcast_under_another_account_is_refused_before_sending() { + let (mut db, source) = db_with_identity(); + let (spend, mut view) = crate::wallet::testing::key_bytes(); + view[0] = 10; + let other = db.add_identity("acct-2", &spend, &view, 100).unwrap().id; + let a = add_output(&db, source, 500, 10, true); + reserve(&mut db, "r", &[a]).unwrap(); + let key_image: Vec = db + .conn() + .query_row("SELECT key_image FROM outputs WHERE id = ?1", [a], |r| { + r.get(0) + }) + .unwrap(); + let key_image = <[u8; 32]>::try_from(key_image.as_slice()).unwrap(); + let record = |db: &Db, identity, txid: &[u8; 32]| { + record_broadcast( + db, + identity, + txid, + &[key_image], + "r", + 900, + SentAmounts::default(), + ) + }; + + let err = record(&db, other, &[0x66; 32]).unwrap_err(); + assert_eq!(err.params["reason"], "inputNotOwnedByAccount"); + let rows: i64 = db + .conn() + .query_row("SELECT count(*) FROM transactions", [], |r| r.get(0)) + .unwrap(); + assert_eq!(rows, 0); + let locked: i64 = db + .conn() + .query_row("SELECT count(*) FROM locked_outputs", [], |r| r.get(0)) + .unwrap(); + assert_eq!(locked, 1, "the source reservation is kept"); + + assert!(record(&db, source, &[0x66; 32]).unwrap()); + let err = record(&db, source, &[0x77; 32]).unwrap_err(); + assert_eq!( + err.params["reason"], "inputAlreadySpent", + "a second transaction over the same inputs is not recorded" + ); + assert!( + !record(&db, source, &[0x66; 32]).unwrap(), + "a retry is still accepted" + ); + } + /// An output cannot be held by two reservations at once. #[test] fn an_output_cannot_be_reserved_twice() { @@ -1396,8 +1450,9 @@ pub fn parse_priority(name: &str) -> Result Result { use monero_daemon_rpc::prelude::*; + if recipients.len() != 1 { + return Err(RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "recipientsJson", "reason": "exactlyOneRecipient" }), + )); + } let network = db.network(); let rate = daemon .fee_rate(priority, max_fee_per_weight(priority)) @@ -1434,12 +1495,6 @@ pub async fn prepare_for_host( let decoys = CachedDecoys::new(daemon); let prepared = if max_send { - if recipients.len() != 1 { - return Err(RuntimeError::with( - ErrorCode::InvalidRequest, - json!({ "field": "recipientsJson", "reason": "maxSendNeedsExactlyOneRecipient" }), - )); - } let address = keys::parse_address(network, recipients[0].0, "recipient.address")?; prepare_max( db, @@ -1516,6 +1571,9 @@ pub struct SentAmounts { /// /// Returns whether the record is fresh. An existing record means the same /// transaction was sent before (a retry), which the node may have accepted. +/// +/// A fresh record must spend only this account's outputs that no other +/// transaction spent; otherwise nothing is recorded and nothing is sent. fn record_broadcast( db: &Db, identity_id: i64, @@ -1536,6 +1594,9 @@ fn record_broadcast( |r| r.get(0), ) .map_err(|e| db_err("findRecordedSend", e))?; + if !existed { + check_inputs_owned(&tx_db, identity_id, txid, key_images)?; + } for key_image in key_images { tx_db .execute( @@ -1570,14 +1631,50 @@ fn record_broadcast( .map_err(|e| db_err("recordOutgoing", e))?; tx_db .execute( - "DELETE FROM locked_outputs WHERE reservation_id = ?1", - [reservation_id], + "DELETE FROM locked_outputs WHERE reservation_id = ?1 + AND output_id IN (SELECT id FROM outputs WHERE identity_id = ?2)", + params![reservation_id, identity_id], ) .map_err(|e| db_err("releaseAfterBroadcast", e))?; tx_db.commit().map_err(|e| db_err("commitRecordSend", e))?; Ok(!existed) } +/// Every input must be an output of `identity_id` not spent by another transaction. +fn check_inputs_owned( + db: &rusqlite::Connection, + identity_id: i64, + txid: &[u8; 32], + key_images: &[[u8; 32]], +) -> Result<()> { + if key_images.is_empty() { + return Err(RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "rawHex", "reason": "noInputs" }), + )); + } + for key_image in key_images { + let spent_in: Option>> = db + .query_row( + "SELECT spent_in_txid FROM outputs WHERE identity_id = ?1 AND key_image = ?2", + params![identity_id, key_image.as_slice()], + |r| r.get(0), + ) + .optional() + .map_err(|e| db_err("checkInputOwner", e))?; + let reason = match spent_in { + None => "inputNotOwnedByAccount", + Some(Some(other)) if other.as_slice() != txid.as_slice() => "inputAlreadySpent", + Some(_) => continue, + }; + return Err(RuntimeError::with( + ErrorCode::InvalidRequest, + json!({ "field": "rawHex", "reason": reason }), + )); + } + Ok(()) +} + /// Undoes a fresh pending record after an explicit rejection; the inputs become spendable again. fn undo_recorded_broadcast(db: &Db, identity_id: i64, txid: &[u8; 32]) -> Result<()> { let tx_db = db diff --git a/chain-runtimes/monero/scripts/smoke.js b/chain-runtimes/monero/scripts/smoke.js index 9c087be8d..2ed5b8fca 100755 --- a/chain-runtimes/monero/scripts/smoke.js +++ b/chain-runtimes/monero/scripts/smoke.js @@ -125,6 +125,25 @@ async function online() { check('empty wallet build reports insufficient funds', err.params.reason, 'insufficientUnlockedFunds'); } + // The review covers one recipient, so preparation refuses more. + try { + await rt.prepareTransaction( + id, + JSON.stringify([ + { address: a.primaryAddress, amountAtomic: '1000' }, + { address: sub.address, amountAtomic: '1000' }, + ]), + false, + 'smoke-r2', + BigInt(tip.height), + 'normal', + ); + check('two-recipient build fails', 'succeeded', 'failed'); + } catch (e) { + const err = JSON.parse(e.message ?? e); + check('two-recipient build is refused', err.params.reason, 'exactlyOneRecipient'); + } + const released = JSON.parse(rt.releaseReservation('smoke-r1')); check('failed build leaves no reservation', released.released, 0); } From 89486d1d89bd24dcfa334fcb28852e8c82d4308b Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Wed, 14 Oct 2026 10:22:00 +0800 Subject: [PATCH 34/97] test(monero): change to an own subaddress or another account is refused --- .../crates/monero-runtime/src/review.rs | 43 ++++++++++++++++++- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/chain-runtimes/monero/crates/monero-runtime/src/review.rs b/chain-runtimes/monero/crates/monero-runtime/src/review.rs index d67557f14..d67d05b75 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/review.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/review.rs @@ -183,8 +183,24 @@ mod tests { Scalar::read(&mut bytes.as_slice()).unwrap() } - // Public, deterministic test keys and invented outputs; no node or funds. fn fixture(extra: Vec>) -> (Vec, ReviewRequest, [u8; 32]) { + fixture_with(extra, |pair| Change::new(pair, None)) + } + + /// A view pair for another account: spend key `value`, view key derived as OneKey does. + fn other_account(value: u8) -> ViewPair { + let bytes = <[u8; 32]>::from(scalar(value)); + let spend: curve25519_dalek::Scalar = scalar(value).into(); + let public = Point::from(spend * curve25519_dalek::constants::ED25519_BASEPOINT_POINT); + ViewPair::new(public, Zeroizing::new(Scalar::hash(bytes))).unwrap() + } + + // Public, deterministic test keys and invented outputs; no node or funds. + // `change` picks the change destination from the sender's view pair. + fn fixture_with( + extra: Vec>, + change: impl FnOnce(ViewPair) -> Change, + ) -> (Vec, ReviewRequest, [u8; 32]) { let mut public_bytes = [0x66u8; 32]; public_bytes[0] = 0x58; let public = CompressedPoint::from(public_bytes).decompress().unwrap(); @@ -221,7 +237,7 @@ mod tests { MoneroAddress::from_str(Network::Mainnet, RECIPIENT).unwrap(), PAYMENT_AMOUNT, )], - Change::new(pair, None), + change(pair), extra, FeeRate::new(20_000, 1).unwrap(), ) @@ -309,6 +325,29 @@ mod tests { .is_err()); } + /// Change must return to the signer's primary address: not one of its + /// subaddresses, not another account of the same wallet. + #[test] + fn change_to_any_other_own_address_is_rejected() { + let to_subaddress = |pair| { + Change::new( + pair, + Some(monero_wallet::address::SubaddressIndex::new(0, 1).unwrap()), + ) + }; + let to_other_account = |_| Change::new(other_account(3), None); + let cases: [(&str, Box Change>); 2] = [ + ("subaddress", Box::new(to_subaddress)), + ("other account", Box::new(to_other_account)), + ]; + for (label, change) in cases { + let (bytes, review, spend) = fixture_with(vec![], change); + let encoded = hex::encode(bytes); + assert!(verify(&encoded, &review, None).is_err(), "{label}"); + assert!(verify(&encoded, &review, Some(&spend)).is_err(), "{label}"); + } + } + #[test] fn suffix_extra_and_noncanonical_amounts_are_rejected() { let (mut bytes, review, spend) = fixture(vec![]); From 0a61dbf4b484e4f262163880c53deabe1ea1634a Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Wed, 14 Oct 2026 16:06:12 +0800 Subject: [PATCH 35/97] ci: merge runtime workflows into publish-runtime-packages --- .github/workflows/monero-runtime.yml | 74 ---------------- .../workflows/publish-runtime-packages.yml | 80 +++++++++++++++++ .github/workflows/zcash-runtime.yml | 87 ------------------- chain-runtimes/monero/README.md | 6 +- chain-runtimes/zcash/RELEASING.md | 17 ++-- 5 files changed, 91 insertions(+), 173 deletions(-) delete mode 100644 .github/workflows/monero-runtime.yml create mode 100644 .github/workflows/publish-runtime-packages.yml delete mode 100644 .github/workflows/zcash-runtime.yml diff --git a/.github/workflows/monero-runtime.yml b/.github/workflows/monero-runtime.yml deleted file mode 100644 index c69dd1e17..000000000 --- a/.github/workflows/monero-runtime.yml +++ /dev/null @@ -1,74 +0,0 @@ -name: Monero runtime - -# Builds and tests on runtime changes. A manual run also publishes to npm: -# prerelease versions to `next`, release versions (from main only) to `latest`. -on: - pull_request: - paths: - - 'chain-runtimes/monero/**' - push: - branches: [main] - paths: - - 'chain-runtimes/monero/**' - workflow_dispatch: - -permissions: - contents: read - -jobs: - build: - runs-on: ubuntu-24.04 - timeout-minutes: 45 - defaults: - run: - working-directory: chain-runtimes/monero - steps: - - uses: actions/checkout@v6 - - name: Install Binaryen 133 (same wasm-opt as local builds) - run: | - BINARYEN=version_133 - case "$(uname -m)" in - x86_64) ARCH=x86_64 SHA=2dc9c7813f5375db93d96ead4b78222fcc3e2677bbb832297af4797782a37489 ;; - aarch64) ARCH=aarch64 SHA=89c07ea56faf38d0fbecf36ca8ec0721756716185f265b568e133d427f299bf8 ;; - *) echo "unsupported architecture $(uname -m)" >&2; exit 1 ;; - esac - curl -sSfL -o /tmp/binaryen.tgz "https://github.com/WebAssembly/binaryen/releases/download/${BINARYEN}/binaryen-${BINARYEN}-${ARCH}-linux.tar.gz" - echo "${SHA} /tmp/binaryen.tgz" | sha256sum -c - - sudo tar xzf /tmp/binaryen.tgz -C /opt - echo "/opt/binaryen-${BINARYEN}/bin" >> "$GITHUB_PATH" - - name: Install build tools - run: | - sudo apt-get update - sudo apt-get install -y clang llvm libsqlite3-dev libssl-dev pkg-config - rustup toolchain install - cargo install wasm-pack --version 0.15.0 --locked - WASM_BINDGEN_VERSION=$(python3 -c 'import tomllib; print(next(p["version"] for p in tomllib.load(open("Cargo.lock", "rb"))["package"] if p["name"] == "wasm-bindgen"))') - cargo install wasm-bindgen-cli --version "$WASM_BINDGEN_VERSION" --locked - - name: Test Rust workspace - run: cargo test --workspace --locked - - name: Build runtime - env: - CC_wasm32_unknown_unknown: /usr/bin/clang - AR_wasm32_unknown_unknown: /usr/bin/llvm-ar - run: bash scripts/build-wasm.sh release - - uses: actions/setup-node@v6 - with: - node-version: '24.x' - registry-url: https://registry.npmjs.org - - name: Pack npm archive - run: | - VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') - TAG=latest - if [[ "$VERSION" == *-* ]]; then TAG=next; fi - echo "VERSION=$VERSION" >> "$GITHUB_ENV" - echo "TAG=$TAG" >> "$GITHUB_ENV" - python3 scripts/package-release.py --version "$VERSION" --tag "$TAG" - - name: Publish - if: github.event_name == 'workflow_dispatch' - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - run: | - if [ "$TAG" = latest ] && [ "$GITHUB_REF" != refs/heads/main ]; then - echo "Release versions publish from main only" >&2; exit 1 - fi - npm publish "dist/onekey-monero-runtime-${VERSION}.tgz" --ignore-scripts --access public --tag "$TAG" diff --git a/.github/workflows/publish-runtime-packages.yml b/.github/workflows/publish-runtime-packages.yml new file mode 100644 index 000000000..179108c2e --- /dev/null +++ b/.github/workflows/publish-runtime-packages.yml @@ -0,0 +1,80 @@ +name: publish-runtime-packages + +# Builds and tests the chain runtimes on change. A manual run also publishes +# each package whose version is not on npm yet. +on: + pull_request: + paths: + - 'chain-runtimes/**' + workflow_dispatch: + +permissions: + contents: read + +jobs: + publish-runtime-packages: + strategy: + fail-fast: false + matrix: + include: + - runtime: zcash + packages: onekey-zcash-runtime onekey-zcash-keys + build: | + bash scripts/vendor-deps.sh + python3 -m unittest discover -s scripts -p 'test_*.py' + cargo test --workspace --locked + bash scripts/build-wasm.sh --offline + python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$GITHUB_SHA" + - runtime: monero + packages: onekey-monero-runtime + build: | + cargo test --workspace --locked + bash scripts/build-wasm.sh release + python3 scripts/package-release.py --version "$VERSION" --tag "$TAG" + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: chain-runtimes/${{ matrix.runtime }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: actions/setup-node@v6 + with: + node-version: '24.x' + registry-url: https://registry.npmjs.org + - name: Install build tools + run: | + curl -sSfL -o /tmp/binaryen.tgz https://github.com/WebAssembly/binaryen/releases/download/version_133/binaryen-version_133-x86_64-linux.tar.gz + echo "2dc9c7813f5375db93d96ead4b78222fcc3e2677bbb832297af4797782a37489 /tmp/binaryen.tgz" | sha256sum -c - + sudo tar xzf /tmp/binaryen.tgz -C /opt + echo /opt/binaryen-version_133/bin >> "$GITHUB_PATH" + sudo apt-get update + sudo apt-get install -y clang llvm libsqlite3-dev libssl-dev pkg-config + rustup toolchain install + cargo install wasm-pack --version 0.15.0 --locked + WASM_BINDGEN_VERSION=$(python3 -c 'import tomllib; print(next(p["version"] for p in tomllib.load(open("Cargo.lock", "rb"))["package"] if p["name"] == "wasm-bindgen"))') + cargo install wasm-bindgen-cli --version "$WASM_BINDGEN_VERSION" --locked + - name: Test, build and pack + env: + CC_wasm32_unknown_unknown: /usr/bin/clang + AR_wasm32_unknown_unknown: /usr/bin/llvm-ar + run: | + VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') + TAG=latest + if [[ "$VERSION" == *-* ]]; then TAG=next; fi + echo "VERSION=$VERSION" >> "$GITHUB_ENV" + echo "TAG=$TAG" >> "$GITHUB_ENV" + ${{ matrix.build }} + - name: Publish versions missing from npm + if: github.event_name == 'workflow_dispatch' + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: | + for pkg in ${{ matrix.packages }}; do + if npm view "$pkg@$VERSION" version >/dev/null 2>&1; then + echo "$pkg@$VERSION already published" + continue + fi + npm publish "dist/$pkg-$VERSION.tgz" --tag "$TAG" + done diff --git a/.github/workflows/zcash-runtime.yml b/.github/workflows/zcash-runtime.yml deleted file mode 100644 index e09f48b32..000000000 --- a/.github/workflows/zcash-runtime.yml +++ /dev/null @@ -1,87 +0,0 @@ -name: Zcash runtime - -# Builds and tests on runtime changes. A manual run also publishes to npm: -# prerelease versions to `next`, release versions (from main only) to `latest`. -on: - pull_request: - paths: - - 'chain-runtimes/zcash/**' - push: - branches: [main] - paths: - - 'chain-runtimes/zcash/**' - workflow_dispatch: - -permissions: - contents: read - -jobs: - build: - runs-on: ubuntu-24.04 - timeout-minutes: 45 - defaults: - run: - working-directory: chain-runtimes/zcash - steps: - - uses: actions/checkout@v6 - - name: Install Binaryen 133 (same wasm-opt as local builds) - run: | - BINARYEN=version_133 - case "$(uname -m)" in - x86_64) ARCH=x86_64 SHA=2dc9c7813f5375db93d96ead4b78222fcc3e2677bbb832297af4797782a37489 ;; - aarch64) ARCH=aarch64 SHA=89c07ea56faf38d0fbecf36ca8ec0721756716185f265b568e133d427f299bf8 ;; - *) echo "unsupported architecture $(uname -m)" >&2; exit 1 ;; - esac - curl -sSfL -o /tmp/binaryen.tgz "https://github.com/WebAssembly/binaryen/releases/download/${BINARYEN}/binaryen-${BINARYEN}-${ARCH}-linux.tar.gz" - echo "${SHA} /tmp/binaryen.tgz" | sha256sum -c - - sudo tar xzf /tmp/binaryen.tgz -C /opt - echo "/opt/binaryen-${BINARYEN}/bin" >> "$GITHUB_PATH" - - name: Install build tools - run: | - sudo apt-get update - sudo apt-get install -y clang llvm libsqlite3-dev pkg-config - rustup toolchain install 1.93.0 --profile minimal --target wasm32-unknown-unknown - cargo install wasm-pack --version 0.15.0 --locked - WASM_BINDGEN_VERSION=$(python3 -c 'import tomllib; print(next(p["version"] for p in tomllib.load(open("Cargo.lock", "rb"))["package"] if p["name"] == "wasm-bindgen"))') - cargo install wasm-bindgen-cli --version "$WASM_BINDGEN_VERSION" --locked - - name: Restore pinned vendor sources - run: bash scripts/vendor-deps.sh - - name: Test vendor reconstruction guards - run: python3 -m unittest discover -s scripts -p 'test_*.py' - - name: Test Rust workspace - run: cargo test --workspace --locked - - name: Build runtime and keys together - env: - CC_wasm32_unknown_unknown: /usr/bin/clang - AR_wasm32_unknown_unknown: /usr/bin/llvm-ar - run: bash scripts/build-wasm.sh --offline - - name: Verify complete artifact provenance - run: python3 scripts/artifact-manifest.py verify --expected-revision "${{ github.sha }}" - - uses: actions/setup-node@v6 - with: - node-version: '24.x' - registry-url: https://registry.npmjs.org - - name: Pack npm archives - run: | - VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') - TAG=latest - if [[ "$VERSION" == *-* ]]; then TAG=next; fi - echo "VERSION=$VERSION" >> "$GITHUB_ENV" - echo "TAG=$TAG" >> "$GITHUB_ENV" - python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$GITHUB_SHA" - # Kept so a half-finished publish can be completed from the same bytes. - - uses: actions/upload-artifact@v4 - with: - name: zcash-npm-${{ github.sha }} - if-no-files-found: error - path: chain-runtimes/zcash/dist/ - - name: Publish - if: github.event_name == 'workflow_dispatch' - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - run: | - if [ "$TAG" = latest ] && [ "$GITHUB_REF" != refs/heads/main ]; then - echo "Release versions publish from main only" >&2; exit 1 - fi - npm publish "dist/onekey-zcash-runtime-${VERSION}.tgz" --ignore-scripts --access public --tag "$TAG" - npm publish "dist/onekey-zcash-keys-${VERSION}.tgz" --ignore-scripts --access public --tag "$TAG" diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md index 085226d85..8041ce1ce 100644 --- a/chain-runtimes/monero/README.md +++ b/chain-runtimes/monero/README.md @@ -26,9 +26,9 @@ objects and silently writes an empty archive; linking then fails with ## Release -Run the **Monero runtime** workflow manually to build, test and publish -`onekey-monero-runtime`: prereleases to npm `next` from any branch, release -versions to `latest` from `main` only. Locally, +Run the **publish-runtime-packages** workflow manually to build, test and publish +`onekey-monero-runtime` (skipped if its version is already on npm): prereleases to npm `next`, release +versions to `latest`. Locally, `python3 scripts/package-release.py --version --tag ` packs the archive into `dist/` without publishing. diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md index 330f4b6f6..423e988b1 100644 --- a/chain-runtimes/zcash/RELEASING.md +++ b/chain-runtimes/zcash/RELEASING.md @@ -34,15 +34,14 @@ archives or manually rewrite the manifest to make an old artifact pass. ## Publish -Run the **Zcash runtime** workflow manually. It builds, tests, packs and -publishes both npm packages with the repository's `NPM_TOKEN`, like the native -modules' `package-publish`. Prereleases can be published from any branch; -release versions only from `main`. - -npm cannot publish two packages atomically. If publishing one succeeds and the -other fails, do not consume the version until both exist. Download the -`zcash-npm-` artifact from that run and publish only the missing package; -never overwrite an existing version or rebuild different bytes under that version. +Run the **publish-runtime-packages** workflow manually. It builds, tests and packs +every runtime, then publishes each package whose version is not on npm yet, with +the repository's `NPM_TOKEN`. Prereleases go to `next`, release versions to `latest`. + +npm cannot publish two packages atomically. If one of the pair fails, do not +consume the version until both exist: re-run that same run, which skips the +package already published. Do not dispatch a new run from another commit for the +same version, or runtime and keys would come from different sources. ## App cutover From 6382ac54ed0205f6f8eab10503065cded43df6a4 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Wed, 14 Oct 2026 16:14:06 +0800 Subject: [PATCH 36/97] ci: publish runtime packages from a separate job with pinned actions --- .../workflows/publish-runtime-packages.yml | 48 +++++++++++++------ 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/.github/workflows/publish-runtime-packages.yml b/.github/workflows/publish-runtime-packages.yml index 179108c2e..fd864d998 100644 --- a/.github/workflows/publish-runtime-packages.yml +++ b/.github/workflows/publish-runtime-packages.yml @@ -12,13 +12,11 @@ permissions: contents: read jobs: - publish-runtime-packages: + build: strategy: - fail-fast: false matrix: include: - runtime: zcash - packages: onekey-zcash-runtime onekey-zcash-keys build: | bash scripts/vendor-deps.sh python3 -m unittest discover -s scripts -p 'test_*.py' @@ -26,7 +24,6 @@ jobs: bash scripts/build-wasm.sh --offline python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$GITHUB_SHA" - runtime: monero - packages: onekey-monero-runtime build: | cargo test --workspace --locked bash scripts/build-wasm.sh release @@ -36,13 +33,12 @@ jobs: run: working-directory: chain-runtimes/${{ matrix.runtime }} steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: persist-credentials: false - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 with: - node-version: '24.x' - registry-url: https://registry.npmjs.org + node-version: 24.21.0 - name: Install build tools run: | curl -sSfL -o /tmp/binaryen.tgz https://github.com/WebAssembly/binaryen/releases/download/version_133/binaryen-version_133-x86_64-linux.tar.gz @@ -63,18 +59,40 @@ jobs: VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') TAG=latest if [[ "$VERSION" == *-* ]]; then TAG=next; fi - echo "VERSION=$VERSION" >> "$GITHUB_ENV" - echo "TAG=$TAG" >> "$GITHUB_ENV" ${{ matrix.build }} + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: runtime-${{ matrix.runtime }} + path: chain-runtimes/${{ matrix.runtime }}/dist/*.tgz + if-no-files-found: error + + # Separate job so the npm token never shares a runner with build code, + # which can rewrite PATH and env for later steps of the same job. + publish: + needs: build + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-24.04 + steps: + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version: 24.21.0 + registry-url: https://registry.npmjs.org + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: runtime-* + merge-multiple: true + path: dist - name: Publish versions missing from npm - if: github.event_name == 'workflow_dispatch' env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} run: | - for pkg in ${{ matrix.packages }}; do - if npm view "$pkg@$VERSION" version >/dev/null 2>&1; then - echo "$pkg@$VERSION already published" + for tgz in dist/*.tgz; do + pkg=$(tar -xOzf "$tgz" package/package.json | node -p 'const p = JSON.parse(require("fs").readFileSync(0)); `${p.name}@${p.version}`') + if npm view "$pkg" version >/dev/null 2>&1; then + echo "$pkg already published" continue fi - npm publish "dist/$pkg-$VERSION.tgz" --tag "$TAG" + TAG=latest + if [[ "${pkg##*@}" == *-* ]]; then TAG=next; fi + npm publish "$tgz" --tag "$TAG" done From b262e71d106c369569b5f557d42a85c9299f2086 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Wed, 14 Oct 2026 17:44:31 +0800 Subject: [PATCH 37/97] fix(zcash): derive the UFVK without Sapling Seed-derived UFVKs now hold only the transparent and Orchard items, the same ones the OneKey firmware returns, so a software account and a device on one seed share a UFVK. This runtime can neither scan for nor spend Sapling, and the firmware rejects PCZTs that carry it. Ironwood keys derive from the Orchard item. Every seed derivation and the pre-sign review check go through ufvk_from_seed_bytes, so they stay consistent. --- .../crates/zcash-keys-runtime/src/keys.rs | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs index a1d3059f3..b60894691 100644 --- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs +++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs @@ -64,6 +64,12 @@ pub(crate) fn ufvk_from_mnemonic( /// Derive a UFVK from raw seed bytes. /// +/// Transparent + Orchard only, the same items the OneKey firmware returns, so a +/// software account and a device holding the same seed share one UFVK. Sapling +/// is left out: this runtime can neither scan for nor spend it, and the +/// firmware rejects PCZTs that carry it. Ironwood keys derive from the Orchard +/// item. +/// /// The seed slice is borrowed, not retained. Upstream `UnifiedSpendingKey` is not /// `ZeroizeOnDrop`, so the intermediate USK stays in linear memory after drop; /// wiping is the host's responsibility. @@ -88,7 +94,21 @@ pub fn ufvk_from_seed_bytes(params: Network, seed: &[u8], account_index: u32) -> usk.to_unified_full_viewing_key() }; - Ok(ufvk.encode(¶ms)) + without_sapling(params, &ufvk) +} + +fn without_sapling(params: Network, ufvk: &UnifiedFullViewingKey) -> Result { + use zcash_address::unified::{Container, Encoding, Fvk, Ufvk}; + let (network, container) = Ufvk::decode(&ufvk.encode(¶ms)) + .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?; + let items = container + .items() + .into_iter() + .filter(|item| matches!(item, Fvk::P2pkh(_) | Fvk::Orchard(_))) + .collect::>(); + let container = Ufvk::try_from_items(items) + .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?; + Ok(container.encode(&network)) } /// Receivers to include in a UA. This is a privacy policy chosen by the host: @@ -186,6 +206,28 @@ pub fn seed_fingerprint(seed: &[u8]) -> Result { mod tests { use super::*; + /// Same items as the firmware's UFVK, so a device and a software account on + /// one seed agree; a Sapling item would also make the firmware reject PCZTs. + #[test] + fn ufvk_holds_only_transparent_and_orchard() { + use zcash_address::unified::{Container, Encoding, Fvk, Ufvk}; + let encoded = ufvk_from_seed_bytes(Network::MainNetwork, &[0x42u8; 64], 0).unwrap(); + let (_, container) = Ufvk::decode(&encoded).unwrap(); + let mut kinds = container + .items() + .into_iter() + .map(|item| match item { + Fvk::P2pkh(_) => "p2pkh", + Fvk::Orchard(_) => "orchard", + Fvk::Sapling(_) => "sapling", + _ => "other", + }) + .collect::>(); + kinds.sort_unstable(); + assert_eq!(kinds, vec!["orchard", "p2pkh"]); + assert!(UnifiedFullViewingKey::decode(&Network::MainNetwork, &encoded).is_ok()); + } + /// The fingerprint is a standard value persisted as account identity; any /// drift would orphan existing accounts. #[test] From c5ffe7152a461505af9e32fb3e418883ef854dee Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Wed, 14 Oct 2026 18:47:24 +0800 Subject: [PATCH 38/97] ci: build chain runtimes through a per-runtime ci.sh hook --- .../workflows/publish-runtime-packages.yml | 41 ++++++++++--------- chain-runtimes/monero/scripts/ci.sh | 12 ++++++ chain-runtimes/zcash/scripts/ci.sh | 14 +++++++ 3 files changed, 47 insertions(+), 20 deletions(-) create mode 100644 chain-runtimes/monero/scripts/ci.sh create mode 100644 chain-runtimes/zcash/scripts/ci.sh diff --git a/.github/workflows/publish-runtime-packages.yml b/.github/workflows/publish-runtime-packages.yml index fd864d998..36238e696 100644 --- a/.github/workflows/publish-runtime-packages.yml +++ b/.github/workflows/publish-runtime-packages.yml @@ -1,7 +1,9 @@ name: publish-runtime-packages -# Builds and tests the chain runtimes on change. A manual run also publishes -# each package whose version is not on npm yet. +# Builds and tests every chain runtime that provides the CI hook +# chain-runtimes//scripts/ci.sh, which tests, builds and packs its +# npm tarballs into dist/. A manual run also publishes each package whose +# version is not on npm yet. on: pull_request: paths: @@ -12,22 +14,25 @@ permissions: contents: read jobs: + runtimes: + runs-on: ubuntu-24.04 + outputs: + list: ${{ steps.find.outputs.list }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - id: find + run: | + list=$(find chain-runtimes -mindepth 3 -maxdepth 3 -path '*/scripts/ci.sh' 2>/dev/null | cut -d/ -f2 | sort | jq -Rnc '[inputs]') + echo "list=$list" >> "$GITHUB_OUTPUT" + build: + needs: runtimes + if: needs.runtimes.outputs.list != '[]' strategy: matrix: - include: - - runtime: zcash - build: | - bash scripts/vendor-deps.sh - python3 -m unittest discover -s scripts -p 'test_*.py' - cargo test --workspace --locked - bash scripts/build-wasm.sh --offline - python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$GITHUB_SHA" - - runtime: monero - build: | - cargo test --workspace --locked - bash scripts/build-wasm.sh release - python3 scripts/package-release.py --version "$VERSION" --tag "$TAG" + runtime: ${{ fromJSON(needs.runtimes.outputs.list) }} runs-on: ubuntu-24.04 defaults: run: @@ -55,11 +60,7 @@ jobs: env: CC_wasm32_unknown_unknown: /usr/bin/clang AR_wasm32_unknown_unknown: /usr/bin/llvm-ar - run: | - VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') - TAG=latest - if [[ "$VERSION" == *-* ]]; then TAG=next; fi - ${{ matrix.build }} + run: bash scripts/ci.sh - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: runtime-${{ matrix.runtime }} diff --git a/chain-runtimes/monero/scripts/ci.sh b/chain-runtimes/monero/scripts/ci.sh new file mode 100644 index 000000000..508136619 --- /dev/null +++ b/chain-runtimes/monero/scripts/ci.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# CI hook: test, build and pack the npm tarball into dist/. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') +TAG=latest +if [[ "$VERSION" == *-* ]]; then TAG=next; fi + +cargo test --workspace --locked +bash scripts/build-wasm.sh release +python3 scripts/package-release.py --version "$VERSION" --tag "$TAG" diff --git a/chain-runtimes/zcash/scripts/ci.sh b/chain-runtimes/zcash/scripts/ci.sh new file mode 100644 index 000000000..ddde1689b --- /dev/null +++ b/chain-runtimes/zcash/scripts/ci.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# CI hook: test, build and pack the npm tarballs into dist/. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])') +TAG=latest +if [[ "$VERSION" == *-* ]]; then TAG=next; fi + +bash scripts/vendor-deps.sh +python3 -m unittest discover -s scripts -p 'test_*.py' +cargo test --workspace --locked +bash scripts/build-wasm.sh --offline +python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$(git rev-parse HEAD)" From 1a9213dabfe241ebc1bbd63542949c7d20bff8ae Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Wed, 14 Oct 2026 21:18:26 +0800 Subject: [PATCH 39/97] ci: limit runtime publishing to own packages and alpha off main --- .../workflows/publish-runtime-packages.yml | 47 +++++++++++++++---- chain-runtimes/monero/README.md | 2 +- chain-runtimes/zcash/RELEASING.md | 6 ++- 3 files changed, 43 insertions(+), 12 deletions(-) diff --git a/.github/workflows/publish-runtime-packages.yml b/.github/workflows/publish-runtime-packages.yml index 36238e696..9cd23a600 100644 --- a/.github/workflows/publish-runtime-packages.yml +++ b/.github/workflows/publish-runtime-packages.yml @@ -3,19 +3,25 @@ name: publish-runtime-packages # Builds and tests every chain runtime that provides the CI hook # chain-runtimes//scripts/ci.sh, which tests, builds and packs its # npm tarballs into dist/. A manual run also publishes each package whose -# version is not on npm yet. +# version is not on npm yet; a runtime may only publish onekey--*, and +# branches other than main publish alpha versions only. +# Pull requests never reach the publish job or its credentials. npm prefers +# trusted publishing (OIDC) once a package has it configured and falls back to +# NPM_TOKEN otherwise; reviewers on the runtime-npm-publish environment, when +# configured, gate every publish. on: pull_request: paths: - 'chain-runtimes/**' workflow_dispatch: -permissions: - contents: read +permissions: {} jobs: runtimes: runs-on: ubuntu-24.04 + permissions: + contents: read outputs: list: ${{ steps.find.outputs.list }} steps: @@ -24,7 +30,7 @@ jobs: persist-credentials: false - id: find run: | - list=$(find chain-runtimes -mindepth 3 -maxdepth 3 -path '*/scripts/ci.sh' 2>/dev/null | cut -d/ -f2 | sort | jq -Rnc '[inputs]') + list=$(find chain-runtimes -mindepth 3 -maxdepth 3 -path '*/scripts/ci.sh' 2>/dev/null | cut -d/ -f2 | grep -xE '[a-z0-9-]+' | sort | jq -Rnc '[inputs]') echo "list=$list" >> "$GITHUB_OUTPUT" build: @@ -34,6 +40,8 @@ jobs: matrix: runtime: ${{ fromJSON(needs.runtimes.outputs.list) }} runs-on: ubuntu-24.04 + permissions: + contents: read defaults: run: working-directory: chain-runtimes/${{ matrix.runtime }} @@ -67,12 +75,15 @@ jobs: path: chain-runtimes/${{ matrix.runtime }}/dist/*.tgz if-no-files-found: error - # Separate job so the npm token never shares a runner with build code, - # which can rewrite PATH and env for later steps of the same job. + # Separate job so the publish identity never shares a runner with build + # code, which can rewrite PATH and env for later steps of the same job. publish: needs: build if: github.event_name == 'workflow_dispatch' runs-on: ubuntu-24.04 + environment: runtime-npm-publish + permissions: + id-token: write steps: - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 with: @@ -81,14 +92,32 @@ jobs: - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: pattern: runtime-* - merge-multiple: true path: dist - name: Publish versions missing from npm env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} run: | - for tgz in dist/*.tgz; do - pkg=$(tar -xOzf "$tgz" package/package.json | node -p 'const p = JSON.parse(require("fs").readFileSync(0)); `${p.name}@${p.version}`') + package_of() { + tar -xOzf "$1" package/package.json | node -p 'const p = JSON.parse(require("fs").readFileSync(0)); `${p.name}@${p.version}`' + } + # Check every tarball before publishing any of them. + for tgz in dist/runtime-*/*.tgz; do + runtime=$(basename "$(dirname "$tgz")") + runtime=${runtime#runtime-} + pkg=$(package_of "$tgz") + if [[ "$pkg" != "onekey-$runtime-"* ]]; then + echo "::error::$tgz is $pkg; a runtime may only publish onekey-$runtime-* packages" >&2 + exit 1 + fi + if [ "$GITHUB_REF" != refs/heads/main ]; then + if [[ "${pkg##*@}" != *-alpha.* ]]; then + echo "::error::$pkg: branches other than main publish alpha versions only" >&2 + exit 1 + fi + fi + done + for tgz in dist/runtime-*/*.tgz; do + pkg=$(package_of "$tgz") if npm view "$pkg" version >/dev/null 2>&1; then echo "$pkg already published" continue diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md index 8041ce1ce..ea7365eb1 100644 --- a/chain-runtimes/monero/README.md +++ b/chain-runtimes/monero/README.md @@ -28,7 +28,7 @@ objects and silently writes an empty archive; linking then fails with Run the **publish-runtime-packages** workflow manually to build, test and publish `onekey-monero-runtime` (skipped if its version is already on npm): prereleases to npm `next`, release -versions to `latest`. Locally, +versions to `latest`. Branches other than `main` can publish alpha versions only. Locally, `python3 scripts/package-release.py --version --tag ` packs the archive into `dist/` without publishing. diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md index 423e988b1..d30efedfe 100644 --- a/chain-runtimes/zcash/RELEASING.md +++ b/chain-runtimes/zcash/RELEASING.md @@ -35,8 +35,10 @@ archives or manually rewrite the manifest to make an old artifact pass. ## Publish Run the **publish-runtime-packages** workflow manually. It builds, tests and packs -every runtime, then publishes each package whose version is not on npm yet, with -the repository's `NPM_TOKEN`. Prereleases go to `next`, release versions to `latest`. +every runtime, then publishes each package whose version is not on npm yet. +Prereleases go to `next`, release versions to `latest`. Branches other than +`main` can publish alpha versions only. npm uses trusted publishing once it is +configured for a package and the repository's `NPM_TOKEN` until then. npm cannot publish two packages atomically. If one of the pair fails, do not consume the version until both exist: re-run that same run, which skips the From affda0ad425b3d1580ee795fd5c011fedbb69a44 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Wed, 14 Oct 2026 22:19:17 +0800 Subject: [PATCH 40/97] ci: publish only discovered runtimes with NPM_TOKEN --- .../workflows/publish-runtime-packages.yml | 52 +++++++++---------- chain-runtimes/zcash/RELEASING.md | 4 +- 2 files changed, 26 insertions(+), 30 deletions(-) diff --git a/.github/workflows/publish-runtime-packages.yml b/.github/workflows/publish-runtime-packages.yml index 9cd23a600..8f045e031 100644 --- a/.github/workflows/publish-runtime-packages.yml +++ b/.github/workflows/publish-runtime-packages.yml @@ -1,14 +1,8 @@ name: publish-runtime-packages -# Builds and tests every chain runtime that provides the CI hook -# chain-runtimes//scripts/ci.sh, which tests, builds and packs its -# npm tarballs into dist/. A manual run also publishes each package whose -# version is not on npm yet; a runtime may only publish onekey--*, and -# branches other than main publish alpha versions only. -# Pull requests never reach the publish job or its credentials. npm prefers -# trusted publishing (OIDC) once a package has it configured and falls back to -# NPM_TOKEN otherwise; reviewers on the runtime-npm-publish environment, when -# configured, gate every publish. +# Every chain-runtimes//scripts/ci.sh tests, builds and packs its npm +# tarballs into dist/. A manual run publishes versions missing from npm: only +# onekey--* packages, and only alpha versions off main. on: pull_request: paths: @@ -75,15 +69,13 @@ jobs: path: chain-runtimes/${{ matrix.runtime }}/dist/*.tgz if-no-files-found: error - # Separate job so the publish identity never shares a runner with build - # code, which can rewrite PATH and env for later steps of the same job. + # Separate job so the npm token never shares a runner with build code, + # which can rewrite PATH and env for later steps of the same job. publish: - needs: build + needs: [runtimes, build] if: github.event_name == 'workflow_dispatch' runs-on: ubuntu-24.04 environment: runtime-npm-publish - permissions: - id-token: write steps: - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 with: @@ -96,27 +88,31 @@ jobs: - name: Publish versions missing from npm env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + RUNTIMES: ${{ needs.runtimes.outputs.list }} run: | package_of() { tar -xOzf "$1" package/package.json | node -p 'const p = JSON.parse(require("fs").readFileSync(0)); `${p.name}@${p.version}`' } - # Check every tarball before publishing any of them. - for tgz in dist/runtime-*/*.tgz; do - runtime=$(basename "$(dirname "$tgz")") - runtime=${runtime#runtime-} - pkg=$(package_of "$tgz") - if [[ "$pkg" != "onekey-$runtime-"* ]]; then - echo "::error::$tgz is $pkg; a runtime may only publish onekey-$runtime-* packages" >&2 - exit 1 - fi - if [ "$GITHUB_REF" != refs/heads/main ]; then - if [[ "${pkg##*@}" != *-alpha.* ]]; then - echo "::error::$pkg: branches other than main publish alpha versions only" >&2 + # Check every tarball before publishing any of them; artifacts from + # runtimes outside the discovered list are ignored. + tarballs=() + for runtime in $(jq -r '.[]' <<<"$RUNTIMES"); do + for tgz in "dist/runtime-$runtime"/*.tgz; do + pkg=$(package_of "$tgz") + if [[ "$pkg" != "onekey-$runtime-"* ]]; then + echo "::error::$tgz is $pkg; a runtime may only publish onekey-$runtime-* packages" >&2 exit 1 fi - fi + if [ "$GITHUB_REF" != refs/heads/main ]; then + if [[ "${pkg##*@}" != *-alpha.* ]]; then + echo "::error::$pkg: branches other than main publish alpha versions only" >&2 + exit 1 + fi + fi + tarballs+=("$tgz") + done done - for tgz in dist/runtime-*/*.tgz; do + for tgz in "${tarballs[@]}"; do pkg=$(package_of "$tgz") if npm view "$pkg" version >/dev/null 2>&1; then echo "$pkg already published" diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md index d30efedfe..8f8518c5f 100644 --- a/chain-runtimes/zcash/RELEASING.md +++ b/chain-runtimes/zcash/RELEASING.md @@ -37,8 +37,8 @@ archives or manually rewrite the manifest to make an old artifact pass. Run the **publish-runtime-packages** workflow manually. It builds, tests and packs every runtime, then publishes each package whose version is not on npm yet. Prereleases go to `next`, release versions to `latest`. Branches other than -`main` can publish alpha versions only. npm uses trusted publishing once it is -configured for a package and the repository's `NPM_TOKEN` until then. +`main` can publish alpha versions only. Publishing uses the repository's +`NPM_TOKEN`. npm cannot publish two packages atomically. If one of the pair fails, do not consume the version until both exist: re-run that same run, which skips the From 2cd705cef1d961598f68e64eb9de7177bb98669a Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Thu, 15 Oct 2026 12:24:24 +0800 Subject: [PATCH 41/97] ci: run runtime publishing manually only and verify published versions --- .../workflows/publish-runtime-packages.yml | 30 +++++++++++++------ 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/.github/workflows/publish-runtime-packages.yml b/.github/workflows/publish-runtime-packages.yml index 8f045e031..5c01749a4 100644 --- a/.github/workflows/publish-runtime-packages.yml +++ b/.github/workflows/publish-runtime-packages.yml @@ -1,12 +1,9 @@ name: publish-runtime-packages -# Every chain-runtimes//scripts/ci.sh tests, builds and packs its npm -# tarballs into dist/. A manual run publishes versions missing from npm: only -# onekey--* packages, and only alpha versions off main. +# Manual only. Every chain-runtimes//scripts/ci.sh tests, builds and +# packs its npm tarballs into dist/; the run then publishes versions missing +# from npm: only onekey--* packages, and only alpha versions off main. on: - pull_request: - paths: - - 'chain-runtimes/**' workflow_dispatch: permissions: {} @@ -73,7 +70,6 @@ jobs: # which can rewrite PATH and env for later steps of the same job. publish: needs: [runtimes, build] - if: github.event_name == 'workflow_dispatch' runs-on: ubuntu-24.04 environment: runtime-npm-publish steps: @@ -112,13 +108,29 @@ jobs: tarballs+=("$tgz") done done + # ?write=true skips npm's CDN, whose package documents can be hours stale. + has_version() { + curl -sf "https://registry.npmjs.org/$1?write=true" | jq -e --arg v "$2" '.versions[$v]' >/dev/null + } for tgz in "${tarballs[@]}"; do pkg=$(package_of "$tgz") - if npm view "$pkg" version >/dev/null 2>&1; then + name=${pkg%@*} + version=${pkg##*@} + if has_version "$name" "$version"; then echo "$pkg already published" continue fi TAG=latest - if [[ "${pkg##*@}" == *-* ]]; then TAG=next; fi + if [[ "$version" == *-* ]]; then TAG=next; fi npm publish "$tgz" --tag "$TAG" + # npm can accept a tarball that never becomes downloadable. + attempt=1 + until has_version "$name" "$version"; do + if [ "$attempt" -ge 10 ]; then + echo "::error::npm accepted $pkg but it never became available" >&2 + exit 1 + fi + attempt=$((attempt + 1)) + sleep 30 + done done From b7225a903b33f7e06fb146a60ff2066e58ce1b22 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Thu, 15 Oct 2026 12:41:57 +0800 Subject: [PATCH 42/97] feat(runtime): reclaim free database pages and report unsupported storage --- .../crates/monero-runtime/src/bindgen.rs | 15 +- .../monero/crates/monero-runtime/src/error.rs | 6 + .../crates/monero-runtime/src/storage.rs | 124 +++++++++++++ .../crates/monero-runtime/src/wallet.rs | 6 + .../zcash/crates/zcash-runtime/src/bindgen.rs | 36 ++-- .../zcash/crates/zcash-runtime/src/error.rs | 5 + .../zcash/crates/zcash-runtime/src/runtime.rs | 9 + .../zcash/crates/zcash-runtime/src/storage.rs | 167 ++++++++++++++++++ 8 files changed, 350 insertions(+), 18 deletions(-) diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs index 54eff3a3a..ebd48c250 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs @@ -129,7 +129,11 @@ pub fn list_accounts() -> std::result::Result { /// Delete an identity and all its data. Irreversible. #[wasm_bindgen(js_name = removeAccount)] pub fn remove_account(uuid: &str) -> std::result::Result { - let removed = runtime::with_db(|db| db.remove_identity(uuid))?; + let removed = runtime::with_db(|db| { + let removed = db.remove_identity(uuid)?; + db.reclaim_storage(storage::RECLAIM_PAGES_AFTER_DELETE); + Ok(removed) + })?; json(serde_json::json!({ "removed": removed })) } @@ -174,6 +178,9 @@ pub fn update_chain_tip(account_id: i64, tip: u64) -> std::result::Result std::result::Result { let progress = runtime::with_db_and_daemon(|mut db, daemon| async move { let r = sync::step(&mut db, &daemon, account_id, max_blocks).await; + if r.is_ok() { + db.reclaim_storage(storage::RECLAIM_PAGES_PER_STEP); + } (db, daemon, r) }) .await?; @@ -190,7 +197,11 @@ pub fn sync_peek(account_id: i64) -> std::result::Result { /// Reorg recovery: rewind to `height` and requeue everything above it. Destructive. #[wasm_bindgen(js_name = rewindTo)] pub fn rewind_to(account_id: i64, height: u64, tip: u64) -> std::result::Result { - let v = runtime::with_db(|db| sync::rewind_and_requeue(db, account_id, height, tip))?; + let v = runtime::with_db(|db| { + let v = sync::rewind_and_requeue(db, account_id, height, tip)?; + db.reclaim_storage(storage::RECLAIM_PAGES_AFTER_DELETE); + Ok(v) + })?; json(v) } diff --git a/chain-runtimes/monero/crates/monero-runtime/src/error.rs b/chain-runtimes/monero/crates/monero-runtime/src/error.rs index fc6694bda..cedb98ec7 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/error.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/error.rs @@ -32,6 +32,10 @@ pub enum ErrorCode { WalletBusy, /// Storage not initialized (on wasm: VFS not installed). NotInitialized, + /// The browser lacks the OPFS API the storage needs (an outdated WebView, + /// or a context with no usable origin). Retrying cannot help. + /// Params: `{ missing }` + StorageUnsupported, /// Account not in the database. Params: `{ accountId }` AccountNotFound, @@ -87,6 +91,7 @@ impl ErrorCode { WalletNotOpen => "WALLET_NOT_OPEN", WalletBusy => "WALLET_BUSY", NotInitialized => "NOT_INITIALIZED", + StorageUnsupported => "STORAGE_UNSUPPORTED", AccountNotFound => "ACCOUNT_NOT_FOUND", ReorgDetected => "REORG_DETECTED", RingCtIndexMismatch => "RINGCT_INDEX_MISMATCH", @@ -197,6 +202,7 @@ mod tests { WalletNotOpen, WalletBusy, NotInitialized, + StorageUnsupported, AccountNotFound, ReorgDetected, RingCtIndexMismatch, diff --git a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs index 06917a40b..941cc3519 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs @@ -63,6 +63,12 @@ pub async fn install_persistent_vfs() -> Result<()> { if is_ready() { return Ok(()); } + if let Some(missing) = missing_opfs_api() { + return Err(RuntimeError::with( + ErrorCode::StorageUnsupported, + json!({ "missing": missing }), + )); + } let cfg = OpfsSAHPoolCfg { vfs_name: "onekey-xmr-opfs".to_owned(), @@ -96,6 +102,13 @@ pub async fn install_persistent_vfs() -> Result<()> { .as_deref() == Some("NoModificationAllowedError") ); + if matches!(&error, OpfsSAHError::GetDirHandle(value) if is_security_error(value)) { + return Err(RuntimeError::with( + ErrorCode::StorageUnsupported, + json!({ "missing": "origin" }), + ) + .detail(format!("{error:?}"))); + } if !owner_is_releasing || retries == 0 { return Err(RuntimeError::with( ErrorCode::NotInitialized, @@ -110,6 +123,45 @@ pub async fn install_persistent_vfs() -> Result<()> { } } +/// The OPFS API the pool needs, checked before installing it: on an outdated +/// WebView the install would otherwise throw a bare TypeError from inside the +/// bindings, which the host cannot tell apart from any other failure. +#[cfg(target_arch = "wasm32")] +fn missing_opfs_api() -> Option<&'static str> { + use wasm_bindgen::JsValue; + let get = |target: &JsValue, key: &str| { + js_sys::Reflect::get(target, &JsValue::from_str(key)) + .ok() + .filter(|value| !value.is_undefined() && !value.is_null()) + }; + let global: JsValue = js_sys::global().into(); + let has_get_directory = get(&global, "navigator") + .and_then(|navigator| get(&navigator, "storage")) + .and_then(|storage| get(&storage, "getDirectory")) + .is_some(); + if !has_get_directory { + return Some("getDirectory"); + } + let has_sync_access_handle = get(&global, "FileSystemFileHandle") + .and_then(|handle| get(&handle, "prototype")) + .and_then(|prototype| get(&prototype, "createSyncAccessHandle")) + .is_some(); + if !has_sync_access_handle { + return Some("createSyncAccessHandle"); + } + None +} + +/// An opaque origin (a file:// page) has the API but refuses to use it. +#[cfg(target_arch = "wasm32")] +fn is_security_error(value: &wasm_bindgen::JsValue) -> bool { + js_sys::Reflect::get(value, &wasm_bindgen::JsValue::from_str("name")) + .ok() + .and_then(|name| name.as_string()) + .as_deref() + == Some("SecurityError") +} + /// No VFS on native; same-named stub keeps callers cfg-free. #[cfg(not(target_arch = "wasm32"))] pub async fn install_persistent_vfs() -> Result<()> { @@ -154,6 +206,11 @@ pub fn open_connection(db_name: &str) -> Result { let conn = Connection::open(db_name).map_err(|e| db_err("open", e))?; + // Only takes effect before the first table exists, so every database + // created from here on can hand freed pages back; see reclaim_free_pages. + conn.execute_batch("PRAGMA auto_vacuum = INCREMENTAL;") + .map_err(|e| db_err("pragmaAutoVacuum", e))?; + // Foreign keys are off by default; without them identity cascades fail and // deleting a wallet leaves readable orphan rows. conn.execute_batch("PRAGMA foreign_keys = ON;") @@ -173,6 +230,43 @@ pub fn open_connection(db_name: &str) -> Result { Ok(conn) } +/// Free pages below which a reclaim is not worth its write transaction. +const RECLAIM_MIN_FREE_PAGES: i64 = 256; +/// Per sync step: small enough never to hold the step up noticeably. +pub const RECLAIM_PAGES_PER_STEP: u32 = 512; +/// After removing or rewinding an identity; later steps take the rest. +pub const RECLAIM_PAGES_AFTER_DELETE: u32 = 4096; + +/// Hands up to `max_pages` free pages back to the file system and returns how +/// many it reclaimed. Rewinds and removals otherwise leave a file that only +/// grows. Databases created before auto_vacuum was set report 0. +pub fn reclaim_free_pages(conn: &Connection, max_pages: u32) -> Result { + let read = |sql: &str| -> Result { + conn.query_row(sql, [], |r| r.get(0)) + .map_err(|e| db_err("reclaimFreePages", e)) + }; + // 2 = INCREMENTAL. + if read("PRAGMA auto_vacuum")? != 2 { + return Ok(0); + } + let before = read("PRAGMA freelist_count")?; + if before < RECLAIM_MIN_FREE_PAGES { + return Ok(0); + } + // Each step frees one page; a single execute would stop after the first. + let mut stmt = conn + .prepare(&format!("PRAGMA incremental_vacuum({max_pages})")) + .map_err(|e| db_err("reclaimFreePages", e))?; + let mut rows = stmt.query([]).map_err(|e| db_err("reclaimFreePages", e))?; + while rows + .next() + .map_err(|e| db_err("reclaimFreePages", e))? + .is_some() + {} + let after = read("PRAGMA freelist_count")?; + Ok(u32::try_from(before - after).unwrap_or(0)) +} + /// Deletes a closed database **without opening it**, so unopenable ones can be deleted. /// Returns `true` if deleted, `false` if it did not exist. #[cfg(target_arch = "wasm32")] @@ -226,6 +320,36 @@ pub async fn durability_barrier() -> Result<()> { mod tests { use super::*; + fn free_pages(conn: &Connection) -> i64 { + conn.query_row("PRAGMA freelist_count", [], |r| r.get(0)) + .unwrap() + } + + // A rewind or removal frees pages that only a reclaim gives back. + #[test] + fn reclaims_freed_pages_in_bounded_batches() { + let name = format!("xmr-reclaim-test-{}.db", std::process::id()); + let _ = std::fs::remove_file(&name); + let conn = open_connection(&name).unwrap(); + conn.execute_batch( + "CREATE TABLE blob (id INTEGER PRIMARY KEY, data BLOB NOT NULL); + WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000) + INSERT INTO blob (data) SELECT zeroblob(4000) FROM n; + DELETE FROM blob;", + ) + .unwrap(); + let before = free_pages(&conn); + assert!(before > 1000, "expected many free pages, got {before}"); + + assert_eq!(reclaim_free_pages(&conn, 300).unwrap(), 300); + assert_eq!(free_pages(&conn), before - 300); + reclaim_free_pages(&conn, u32::MAX).unwrap(); + assert_eq!(free_pages(&conn), 0); + + drop(conn); + let _ = std::fs::remove_file(&name); + } + // Deletion does not open the file, so even a non-SQLite file is deleted. #[test] fn deletes_a_database_it_cannot_open() { diff --git a/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs index a9f8f7901..f5a6fbee5 100644 --- a/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs +++ b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs @@ -34,6 +34,12 @@ pub struct Identity { } impl Db { + /// Best effort: a failed reclaim only means the file stays larger until + /// the next one, so it never fails the caller. + pub fn reclaim_storage(&self, max_pages: u32) { + let _ = crate::storage::reclaim_free_pages(&self.conn, max_pages); + } + /// Opens (or creates) a wallet database and runs migrations. pub fn open(db_name: &str, network: Network) -> Result { let conn = crate::storage::open_connection(db_name)?; diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs index b4b9320f1..f8b9c35d6 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs @@ -239,6 +239,7 @@ pub async fn remove_account(account_uuid: String) -> Result<(), JsValue> { })?; runtime::with_db(|db| account::remove_account(db, &account_uuid))?; storage::durability_barrier().await?; + runtime::reclaim_storage(storage::RECLAIM_PAGES_AFTER_DELETE); Ok(()) } @@ -251,6 +252,7 @@ pub async fn remove_deleted_account(account_uuid: String) -> Result<(), JsValue> runtime::with_db(|db| account::remove_account(db, &account_uuid))?; send::forget_account_reservations(&account_uuid); storage::durability_barrier().await?; + runtime::reclaim_storage(storage::RECLAIM_PAGES_AFTER_DELETE); Ok(()) } @@ -451,21 +453,21 @@ pub async fn sync_step( let active_ufvks: Vec = serde_json::from_str(&active_ufvks_json).map_err(|e| { RuntimeError::new(ErrorCode::InvalidUfvk).detail(format!("activeUfvksJson: {e}")) })?; - Ok( - runtime::with_db_and_client(move |mut db, mut client| async move { - let r = sync::step( - &mut db, - &mut client, - batch_size, - max_batches, - preferred, - &active_ufvks, - ) - .await; - (db, client, r) - }) - .await?, - ) + let progress = runtime::with_db_and_client(move |mut db, mut client| async move { + let r = sync::step( + &mut db, + &mut client, + batch_size, + max_batches, + preferred, + &active_ufvks, + ) + .await; + (db, client, r) + }) + .await?; + runtime::reclaim_storage(storage::RECLAIM_PAGES_PER_STEP); + Ok(progress) } // ── Transaction history ───────────────────────────────────────────────── @@ -501,7 +503,9 @@ pub fn rewind_to(height: u32) -> Result { // account to an abandoned chain. // // User-triggered rescans use `queueRescanFrom`, which only requeues ranges. - Ok(runtime::with_db(|db| sync::rewind_to(db, height))?) + let rewound = runtime::with_db(|db| sync::rewind_to(db, height))?; + runtime::reclaim_storage(storage::RECLAIM_PAGES_AFTER_DELETE); + Ok(rewound) } /// Re-queue `[fromHeight, chainTip]` as historic work without deleting cached notes or history. diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs index 079d9243a..d477db42e 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs @@ -36,6 +36,10 @@ pub enum ErrorCode { // ── Lifecycle ── /// `init()` not called; storage layer not installed. NotInitialized, + /// The browser lacks the OPFS API the storage needs (an outdated WebView, + /// or a context with no usable origin). Retrying cannot help. + /// Params: `{ missing }` + StorageUnsupported, /// `openWallet()` not called. WalletNotOpen, /// `setLightwalletdUrl()` not called. @@ -135,6 +139,7 @@ impl ErrorCode { use ErrorCode::*; match self { NotInitialized => "NOT_INITIALIZED", + StorageUnsupported => "STORAGE_UNSUPPORTED", WalletNotOpen => "WALLET_NOT_OPEN", LightwalletdNotConfigured => "LIGHTWALLETD_NOT_CONFIGURED", InvalidNetwork => "INVALID_NETWORK", diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs index 31815a5d8..044b2e9eb 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs @@ -149,6 +149,15 @@ pub fn with_read_conn(f: impl FnOnce(&rusqlite::Connection) -> Result) -> f(&conn) } +/// Best effort on its own connection: a failed reclaim only means the file +/// stays larger until the next one, so it never fails the caller. +pub fn reclaim_storage(max_pages: u32) { + if let Some(name) = DB_NAME.with(|c| c.borrow().clone()) { + let _ = crate::storage::open_connection(&name) + .and_then(|conn| crate::storage::reclaim_free_pages(&conn, max_pages)); + } +} + pub fn set_client(client: LightClient) { CLIENT.with(|c| *c.borrow_mut() = Some(client)); bump_client_generation(); diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs index 400888b87..7f842d36c 100644 --- a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs +++ b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs @@ -34,6 +34,45 @@ fn persistent_vfs() -> Result Option<&'static str> { + use wasm_bindgen::JsValue; + let get = |target: &JsValue, key: &str| { + js_sys::Reflect::get(target, &JsValue::from_str(key)) + .ok() + .filter(|value| !value.is_undefined() && !value.is_null()) + }; + let global: JsValue = js_sys::global().into(); + let has_get_directory = get(&global, "navigator") + .and_then(|navigator| get(&navigator, "storage")) + .and_then(|storage| get(&storage, "getDirectory")) + .is_some(); + if !has_get_directory { + return Some("getDirectory"); + } + let has_sync_access_handle = get(&global, "FileSystemFileHandle") + .and_then(|handle| get(&handle, "prototype")) + .and_then(|prototype| get(&prototype, "createSyncAccessHandle")) + .is_some(); + if !has_sync_access_handle { + return Some("createSyncAccessHandle"); + } + None +} + +/// An opaque origin (a file:// page) has the API but refuses to use it. +#[cfg(target_arch = "wasm32")] +fn is_security_error(value: &wasm_bindgen::JsValue) -> bool { + js_sys::Reflect::get(value, &wasm_bindgen::JsValue::from_str("name")) + .ok() + .and_then(|name| name.as_string()) + .as_deref() + == Some("SecurityError") +} + /// Install the same page-backed VFS in every browser carrier. /// The pool owns exclusive file handles until its Worker is terminated. #[cfg(target_arch = "wasm32")] @@ -44,6 +83,12 @@ pub async fn install_persistent_vfs() -> Result<()> { if is_ready() { return Ok(()); } + if let Some(missing) = missing_opfs_api() { + return Err(RuntimeError::with( + ErrorCode::StorageUnsupported, + json!({ "missing": missing }), + )); + } let cfg = OpfsSAHPoolCfg { vfs_name: "onekey-zcash-opfs".to_owned(), directory: ".onekey-zcash-opfs".to_owned(), @@ -69,6 +114,13 @@ pub async fn install_persistent_vfs() -> Result<()> { } _ => false, }; + if matches!(&error, OpfsSAHError::GetDirHandle(value) if is_security_error(value)) { + return Err(RuntimeError::with( + ErrorCode::StorageUnsupported, + json!({ "missing": "origin" }), + ) + .detail(format!("{error:?}"))); + } if !owner_releasing || retries == 0 { return Err( RuntimeError::new(ErrorCode::NotInitialized).detail(format!("{error:?}")) @@ -165,6 +217,9 @@ pub fn open_connection(db_name: &str) -> Result { )); } let conn = rusqlite::Connection::open(db_name)?; + // Only takes effect before the first table exists, so every database + // created from here on can hand freed pages back; see reclaim_free_pages. + conn.execute_batch("PRAGMA auto_vacuum = INCREMENTAL;")?; #[cfg(target_arch = "wasm32")] if !memory_mode() { // SAH-pool uses rollback journals, not cross-context WAL coordination. @@ -175,6 +230,34 @@ pub fn open_connection(db_name: &str) -> Result { Ok(conn) } +/// Free pages below which a reclaim is not worth its write transaction. +const RECLAIM_MIN_FREE_PAGES: i64 = 256; +/// Per sync step: small enough never to hold the step up noticeably. +pub const RECLAIM_PAGES_PER_STEP: u32 = 512; +/// After removing or rewinding an account; later steps take the rest. +pub const RECLAIM_PAGES_AFTER_DELETE: u32 = 4096; + +/// Hands up to `max_pages` free pages back to the file system and returns how +/// many it reclaimed. Rescans and removals otherwise leave a file that only +/// grows. Databases created before auto_vacuum was set report 0. +pub fn reclaim_free_pages(conn: &rusqlite::Connection, max_pages: u32) -> Result { + let mode: i64 = conn.query_row("PRAGMA auto_vacuum", [], |r| r.get(0))?; + // 2 = INCREMENTAL. + if mode != 2 { + return Ok(0); + } + let before: i64 = conn.query_row("PRAGMA freelist_count", [], |r| r.get(0))?; + if before < RECLAIM_MIN_FREE_PAGES { + return Ok(0); + } + // Each step frees one page; a single execute would stop after the first. + let mut stmt = conn.prepare(&format!("PRAGMA incremental_vacuum({max_pages})"))?; + let mut rows = stmt.query([])?; + while rows.next()?.is_some() {} + let after: i64 = conn.query_row("PRAGMA freelist_count", [], |r| r.get(0))?; + Ok(u32::try_from(before - after).unwrap_or(0)) +} + /// Inspect the pool's file table without opening or creating a database. #[cfg(target_arch = "wasm32")] pub async fn database_exists(db_name: &str) -> Result { @@ -224,3 +307,87 @@ fn db_storage_err(operation: &str, db_name: &str, error: impl std::fmt::Debug) - ) .detail(format!("{error:?}")) } + +#[cfg(test)] +mod tests { + use super::*; + + fn page_counts(conn: &rusqlite::Connection) -> (i64, i64) { + let pages = conn + .query_row("PRAGMA page_count", [], |r| r.get(0)) + .unwrap(); + let free = conn + .query_row("PRAGMA freelist_count", [], |r| r.get(0)) + .unwrap(); + (pages, free) + } + + /// A rescan or removal frees pages that only a reclaim gives back. + #[test] + fn reclaims_freed_pages_in_bounded_batches() { + let path = std::env::temp_dir().join("zr-reclaim-free-pages.sqlite"); + let _ = std::fs::remove_file(&path); + let conn = open_connection(path.to_str().unwrap()).expect("open"); + conn.execute_batch( + "CREATE TABLE blob (id INTEGER PRIMARY KEY, data BLOB NOT NULL); + WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000) + INSERT INTO blob (data) SELECT zeroblob(4000) FROM n; + DELETE FROM blob;", + ) + .unwrap(); + let (pages_before, free_before) = page_counts(&conn); + assert!( + free_before > 1000, + "expected many free pages, got {free_before}" + ); + + assert_eq!(reclaim_free_pages(&conn, 300).unwrap(), 300); + assert_eq!(page_counts(&conn).0, pages_before - 300); + + reclaim_free_pages(&conn, u32::MAX).unwrap(); + let (_, free_after) = page_counts(&conn); + assert_eq!(free_after, 0); + let _ = std::fs::remove_file(&path); + } + + /// Too few free pages to be worth a write transaction. + #[test] + fn leaves_a_small_freelist_alone() { + let path = std::env::temp_dir().join("zr-reclaim-small-freelist.sqlite"); + let _ = std::fs::remove_file(&path); + let conn = open_connection(path.to_str().unwrap()).expect("open"); + conn.execute_batch( + "CREATE TABLE blob (id INTEGER PRIMARY KEY, data BLOB NOT NULL); + INSERT INTO blob (data) VALUES (zeroblob(40000)); + DELETE FROM blob;", + ) + .unwrap(); + assert!(page_counts(&conn).1 > 0); + assert_eq!(reclaim_free_pages(&conn, u32::MAX).unwrap(), 0); + let _ = std::fs::remove_file(&path); + } + + /// auto_vacuum is fixed when the first table is created; an older file + /// keeps its mode and is never touched. + #[test] + fn leaves_databases_without_incremental_vacuum_alone() { + let path = std::env::temp_dir().join("zr-reclaim-legacy.sqlite"); + let _ = std::fs::remove_file(&path); + { + let legacy = rusqlite::Connection::open(&path).unwrap(); + legacy + .execute_batch( + "CREATE TABLE blob (id INTEGER PRIMARY KEY, data BLOB NOT NULL); + WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000) + INSERT INTO blob (data) SELECT zeroblob(4000) FROM n; + DELETE FROM blob;", + ) + .unwrap(); + } + let conn = open_connection(path.to_str().unwrap()).expect("open"); + let free = page_counts(&conn).1; + assert_eq!(reclaim_free_pages(&conn, u32::MAX).unwrap(), 0); + assert_eq!(page_counts(&conn).1, free); + let _ = std::fs::remove_file(&path); + } +} From 9a602440d5d486cf5ed4d0c7846000758479bff6 Mon Sep 17 00:00:00 2001 From: ByteZhang Date: Thu, 15 Oct 2026 17:00:34 +0800 Subject: [PATCH 43/97] ci: publish a fixed list of runtime packages --- .../workflows/publish-runtime-packages.yml | 109 ++++++------------ chain-runtimes/monero/scripts/ci.sh | 5 +- chain-runtimes/zcash/scripts/ci.sh | 6 +- 3 files changed, 46 insertions(+), 74 deletions(-) diff --git a/.github/workflows/publish-runtime-packages.yml b/.github/workflows/publish-runtime-packages.yml index 5c01749a4..b76055706 100644 --- a/.github/workflows/publish-runtime-packages.yml +++ b/.github/workflows/publish-runtime-packages.yml @@ -1,35 +1,17 @@ name: publish-runtime-packages -# Manual only. Every chain-runtimes//scripts/ci.sh tests, builds and -# packs its npm tarballs into dist/; the run then publishes versions missing -# from npm: only onekey--* packages, and only alpha versions off main. +# Manual only. Builds each runtime with chain-runtimes//scripts/ci.sh +# and publishes exactly the packages listed in the publish step. on: workflow_dispatch: permissions: {} jobs: - runtimes: - runs-on: ubuntu-24.04 - permissions: - contents: read - outputs: - list: ${{ steps.find.outputs.list }} - steps: - - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - with: - persist-credentials: false - - id: find - run: | - list=$(find chain-runtimes -mindepth 3 -maxdepth 3 -path '*/scripts/ci.sh' 2>/dev/null | cut -d/ -f2 | grep -xE '[a-z0-9-]+' | sort | jq -Rnc '[inputs]') - echo "list=$list" >> "$GITHUB_OUTPUT" - build: - needs: runtimes - if: needs.runtimes.outputs.list != '[]' strategy: matrix: - runtime: ${{ fromJSON(needs.runtimes.outputs.list) }} + runtime: [zcash, monero] runs-on: ubuntu-24.04 permissions: contents: read @@ -53,8 +35,8 @@ jobs: sudo apt-get install -y clang llvm libsqlite3-dev libssl-dev pkg-config rustup toolchain install cargo install wasm-pack --version 0.15.0 --locked - WASM_BINDGEN_VERSION=$(python3 -c 'import tomllib; print(next(p["version"] for p in tomllib.load(open("Cargo.lock", "rb"))["package"] if p["name"] == "wasm-bindgen"))') - cargo install wasm-bindgen-cli --version "$WASM_BINDGEN_VERSION" --locked + # Must match wasm-bindgen in both runtimes' Cargo.lock. + cargo install wasm-bindgen-cli --version 0.2.127 --locked - name: Test, build and pack env: CC_wasm32_unknown_unknown: /usr/bin/clang @@ -62,14 +44,14 @@ jobs: run: bash scripts/ci.sh - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: runtime-${{ matrix.runtime }} - path: chain-runtimes/${{ matrix.runtime }}/dist/*.tgz + name: ${{ matrix.runtime }} + path: chain-runtimes/${{ matrix.runtime }}/dist/ if-no-files-found: error # Separate job so the npm token never shares a runner with build code, # which can rewrite PATH and env for later steps of the same job. publish: - needs: [runtimes, build] + needs: build runs-on: ubuntu-24.04 environment: runtime-npm-publish steps: @@ -77,60 +59,43 @@ jobs: with: node-version: 24.21.0 registry-url: https://registry.npmjs.org + # Each artifact lands in dist//. - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - pattern: runtime-* path: dist - name: Publish versions missing from npm env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - RUNTIMES: ${{ needs.runtimes.outputs.list }} run: | - package_of() { - tar -xOzf "$1" package/package.json | node -p 'const p = JSON.parse(require("fs").readFileSync(0)); `${p.name}@${p.version}`' - } - # Check every tarball before publishing any of them; artifacts from - # runtimes outside the discovered list are ignored. - tarballs=() - for runtime in $(jq -r '.[]' <<<"$RUNTIMES"); do - for tgz in "dist/runtime-$runtime"/*.tgz; do - pkg=$(package_of "$tgz") - if [[ "$pkg" != "onekey-$runtime-"* ]]; then - echo "::error::$tgz is $pkg; a runtime may only publish onekey-$runtime-* packages" >&2 - exit 1 - fi - if [ "$GITHUB_REF" != refs/heads/main ]; then - if [[ "${pkg##*@}" != *-alpha.* ]]; then - echo "::error::$pkg: branches other than main publish alpha versions only" >&2 - exit 1 - fi - fi - tarballs+=("$tgz") - done + # The only packages this workflow publishes, as /. + packages='zcash/onekey-zcash-keys zcash/onekey-zcash-runtime monero/onekey-monero-runtime' + # main publishes x.y.z or x.y.z-
.n; other branches only x.y.z-alpha.n.
+          versions='^[0-9]+\.[0-9]+\.[0-9]+(-[a-z]+\.[0-9]+)?$'
+          if [ "$GITHUB_REF" != refs/heads/main ]; then
+            versions='^[0-9]+\.[0-9]+\.[0-9]+-alpha\.[0-9]+$'
+          fi
+          field() { tar -xOzf "dist/$1.tgz" package/package.json | jq -r ".$2"; }
+
+          # Check every package before publishing any.
+          for pkg in $packages; do
+            if [ "$(field "$pkg" name)" != "$(basename "$pkg")" ]; then
+              echo "::error::dist/$pkg.tgz is missing or is not $(basename "$pkg")"
+              exit 1
+            fi
+            if [[ ! "$(field "$pkg" version)" =~ $versions ]]; then
+              echo "::error::$pkg: version not allowed on $GITHUB_REF"
+              exit 1
+            fi
           done
-          # ?write=true skips npm's CDN, whose package documents can be hours stale.
-          has_version() {
-            curl -sf "https://registry.npmjs.org/$1?write=true" | jq -e --arg v "$2" '.versions[$v]' >/dev/null
-          }
-          for tgz in "${tarballs[@]}"; do
-            pkg=$(package_of "$tgz")
-            name=${pkg%@*}
-            version=${pkg##*@}
-            if has_version "$name" "$version"; then
-              echo "$pkg already published"
+
+          for pkg in $packages; do
+            name=$(basename "$pkg")
+            version=$(field "$pkg" version)
+            if [ -n "$(npm view "$name@$version" version 2>/dev/null)" ]; then
+              echo "$name@$version already published"
               continue
             fi
-            TAG=latest
-            if [[ "$version" == *-* ]]; then TAG=next; fi
-            npm publish "$tgz" --tag "$TAG"
-            # npm can accept a tarball that never becomes downloadable.
-            attempt=1
-            until has_version "$name" "$version"; do
-              if [ "$attempt" -ge 10 ]; then
-                echo "::error::npm accepted $pkg but it never became available" >&2
-                exit 1
-              fi
-              attempt=$((attempt + 1))
-              sleep 30
-            done
+            tag=latest
+            if [[ "$version" =~ - ]]; then tag=next; fi
+            npm publish "dist/$pkg.tgz" --tag "$tag"
           done
diff --git a/chain-runtimes/monero/scripts/ci.sh b/chain-runtimes/monero/scripts/ci.sh
index 508136619..518fc74df 100644
--- a/chain-runtimes/monero/scripts/ci.sh
+++ b/chain-runtimes/monero/scripts/ci.sh
@@ -5,8 +5,11 @@ cd "$(dirname "${BASH_SOURCE[0]}")/.."
 
 VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])')
 TAG=latest
-if [[ "$VERSION" == *-* ]]; then TAG=next; fi
+if [[ "$VERSION" =~ - ]]; then TAG=next; fi
 
 cargo test --workspace --locked
 bash scripts/build-wasm.sh release
 python3 scripts/package-release.py --version "$VERSION" --tag "$TAG"
+
+# Fixed file names for the publish workflow.
+mv "dist/onekey-monero-runtime-$VERSION.tgz" dist/onekey-monero-runtime.tgz
diff --git a/chain-runtimes/zcash/scripts/ci.sh b/chain-runtimes/zcash/scripts/ci.sh
index ddde1689b..829a333bc 100644
--- a/chain-runtimes/zcash/scripts/ci.sh
+++ b/chain-runtimes/zcash/scripts/ci.sh
@@ -5,10 +5,14 @@ cd "$(dirname "${BASH_SOURCE[0]}")/.."
 
 VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"])')
 TAG=latest
-if [[ "$VERSION" == *-* ]]; then TAG=next; fi
+if [[ "$VERSION" =~ - ]]; then TAG=next; fi
 
 bash scripts/vendor-deps.sh
 python3 -m unittest discover -s scripts -p 'test_*.py'
 cargo test --workspace --locked
 bash scripts/build-wasm.sh --offline
 python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$(git rev-parse HEAD)"
+
+# Fixed file names for the publish workflow.
+mv "dist/onekey-zcash-keys-$VERSION.tgz" dist/onekey-zcash-keys.tgz
+mv "dist/onekey-zcash-runtime-$VERSION.tgz" dist/onekey-zcash-runtime.tgz

From 77fdcec4ff7a815914a0616adafb0441590c92dc Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Thu, 15 Oct 2026 17:51:29 +0800
Subject: [PATCH 44/97] fix(zcash): send hardware signers a copy without
 Sapling or proving fields

The OneKey firmware rejects any Sapling data and any proving fields. The IO
Finalizer always sets the Sapling bsk, even on an empty bundle, and the
Orchard-protocol bsk, so every PCZT we built was refused.

pcztRedactForHardwareSigner returns the copy to send: it clears the Sapling
bsk and, for Orchard and Ironwood, bsk, zkproof, spend witnesses and dummy
keys, as upstream redact_pczt_for_signer does. The host keeps the original
and combines the device's result into it; tests check the combined PCZT is
identical to signing the original.
---
 .../crates/zcash-keys-runtime/src/bindgen.rs  |  6 +++
 .../crates/zcash-keys-runtime/src/sign.rs     | 27 ++++++++++++
 .../src/transparent_send/shielding.rs         | 42 +++++++++++++++++++
 .../zcash/crates/zcash-runtime/src/send.rs    | 18 ++++++++
 4 files changed, 93 insertions(+)

diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
index ba3518ee3..cfbe3a5f0 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
@@ -60,6 +60,12 @@ pub fn pczt_sign_with_seed(
     )?)
 }
 
+/// The copy of a PCZT to send to a hardware signer; keep the original for combining.
+#[wasm_bindgen(js_name = pcztRedactForHardwareSigner)]
+pub fn pczt_redact_for_hardware_signer(pczt_bytes: Vec) -> Result, JsValue> {
+    Ok(sign::redact_for_hardware_signer(&pczt_bytes)?)
+}
+
 /// Verify a private payment before showing its confirmation or contacting a signer.
 #[wasm_bindgen(js_name = pcztVerifyReview)]
 pub fn pczt_verify_review(pczt_bytes: Vec, review_json: &str) -> Result<(), JsValue> {
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
index 3ecd65b67..368d02d6d 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
@@ -191,6 +191,33 @@ pub fn sign_pczt_with_seed(
         .map_err(|e| KeysError::new(ErrorCode::PcztSignFailed).detail(format!("{e:?}")))
 }
 
+/// The copy of a PCZT sent to a hardware signer.
+///
+/// The firmware rejects any Sapling data (the IO Finalizer sets `bsk` even on
+/// an empty bundle) and any proving fields (witnesses, dummy keys, proofs,
+/// binding keys). Signing needs none of them; the host keeps the original and
+/// combines the device's result into it, so proving and extraction still have
+/// them. Upstream `redact_pczt_for_signer` (compact view) clears the same.
+pub fn redact_for_hardware_signer(pczt_bytes: &[u8]) -> Result> {
+    fn redact_orchard_protocol(mut bundle: pczt::roles::redactor::orchard::OrchardRedactor<'_>) {
+        bundle.clear_zkproof();
+        bundle.clear_bsk();
+        bundle.redact_actions(|mut action| {
+            action.clear_spend_witness();
+            action.clear_spend_dummy_sk();
+        });
+    }
+    let pczt = pczt::Pczt::parse(pczt_bytes)
+        .map_err(|e| KeysError::new(ErrorCode::PcztParseFailed).detail(format!("{e:?}")))?;
+    pczt::roles::redactor::Redactor::new(pczt)
+        .redact_sapling_with(|mut sapling| sapling.clear_bsk())
+        .redact_orchard_with(redact_orchard_protocol)
+        .redact_ironwood_with(redact_orchard_protocol)
+        .finish()
+        .serialize()
+        .map_err(|e| KeysError::new(ErrorCode::PcztParseFailed).detail(format!("{e:?}")))
+}
+
 /// Count signable items per bundle: (orchard, ironwood, transparent).
 ///
 /// Ironwood and Orchard share Rust types but are separate PCZT bundles.
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
index a051896e4..bc2976d09 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
@@ -852,6 +852,48 @@ mod tests {
         }
     }
 
+    // The firmware (firmware-pro2 `signer_parse.rs`) rejects any Sapling data,
+    // including the `bsk` the IO Finalizer sets on the empty bundle, and any
+    // proving fields. The device signs a copy without them; combining its
+    // result into the original gives the same transaction.
+    #[test]
+    fn hardware_signs_a_copy_without_sapling_or_proving_fields() {
+        for transparent_destination in [false, true] {
+            let mut request = request(false);
+            if transparent_destination {
+                request["recipients"][0]["address"] = transparent_address(0, 9)
+                    .to_zcash_address(NetworkType::Main)
+                    .to_string()
+                    .into();
+            }
+            let request_json = request.to_string();
+            let original =
+                create_with_account_xpub(&request_json, &account_xpub(), &"01".repeat(32)).unwrap();
+            let redacted = crate::sign::redact_for_hardware_signer(&original).unwrap();
+            assert!(redacted.len() < original.len());
+            assert_eq!(
+                crate::sign::redact_for_hardware_signer(&redacted).unwrap(),
+                redacted
+            );
+
+            let from_original = combine_hardware_signed(
+                &request_json,
+                &account_xpub(),
+                &original,
+                &simulated_device_signature(&original),
+            )
+            .unwrap();
+            let from_redacted = combine_hardware_signed(
+                &request_json,
+                &account_xpub(),
+                &original,
+                &simulated_device_signature(&redacted),
+            )
+            .unwrap();
+            assert_eq!(from_redacted, from_original);
+        }
+    }
+
     fn mutate(bytes: &[u8], change: impl FnOnce(&mut Value)) -> Vec {
         let wire = pczt::v2::Pczt::try_from(pczt::Pczt::parse(bytes).unwrap()).unwrap();
         let mut value = serde_json::to_value(wire).unwrap();
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
index 372d1d2a3..a8b06be36 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
@@ -1525,6 +1525,24 @@ mod combine_tests {
             reason(&error)
         );
     }
+
+    // Hardware signers get a copy without the Sapling `bsk` (see the keys
+    // runtime's `redact_for_hardware_signer`); the original keeps it.
+    #[test]
+    fn combine_restores_sapling_bsk_from_the_original() {
+        let original = transparent_pczt(90_000, 0xaa, false);
+        let device_copy =
+            pczt::roles::redactor::Redactor::new(pczt::Pczt::parse(&original).unwrap())
+                .redact_sapling_with(|mut sapling| sapling.clear_bsk())
+                .finish()
+                .serialize()
+                .unwrap();
+        assert!(device_copy.len() < original.len());
+        assert_eq!(
+            combine_pczt(&original, &signed_copy(&device_copy)).unwrap(),
+            combine_pczt(&original, &signed_copy(&original)).unwrap(),
+        );
+    }
 }
 
 #[cfg(all(test, not(target_arch = "wasm32")))]

From 387e47c336d14110e33222c76894a05948314e95 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Thu, 15 Oct 2026 22:05:40 +0800
Subject: [PATCH 45/97] fix(monero): use the patched OPFS VFS and check storage
 before broadcasting

Monero used the released sqlite-wasm-vfs, whose durability barrier is a no-op,
so a metadata I/O failure around journal deletion could leave the pending send
and input locks undurable while the transaction still went out.

Monero now rebuilds the VFS from the Zcash runtime's patch (vendor-deps.sh,
prepare-vendor.py gains --root), and broadcast_signed runs the durability
barrier after recording the send: a poisoned pool stops the broadcast before
anything is sent.
---
 chain-runtimes/monero/Cargo.lock              |  2 -
 chain-runtimes/monero/Cargo.toml              |  7 ++--
 chain-runtimes/monero/README.md               |  9 +++--
 .../monero/crates/monero-runtime/src/spend.rs |  3 ++
 .../crates/monero-runtime/src/storage.rs      | 40 +++++++++++++------
 chain-runtimes/monero/patches/manifest.json   |  8 ++++
 chain-runtimes/monero/scripts/build-wasm.sh   |  2 +
 chain-runtimes/monero/scripts/ci.sh           |  1 +
 chain-runtimes/monero/scripts/vendor-deps.sh  |  6 +++
 .../zcash/scripts/prepare-vendor.py           | 14 ++++---
 10 files changed, 67 insertions(+), 25 deletions(-)
 create mode 100644 chain-runtimes/monero/patches/manifest.json
 create mode 100755 chain-runtimes/monero/scripts/vendor-deps.sh

diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock
index cf1a41914..7e2a96c81 100644
--- a/chain-runtimes/monero/Cargo.lock
+++ b/chain-runtimes/monero/Cargo.lock
@@ -1768,8 +1768,6 @@ dependencies = [
 [[package]]
 name = "sqlite-wasm-vfs"
 version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7f7a5c9ac229421d577bb5a9bb59048838509958b218dd4e0b3c1214a87c361e"
 dependencies = [
  "indexed_db_futures",
  "js-sys",
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index ec87836ed..5f147032a 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -1,6 +1,7 @@
 [workspace]
 resolver = "2"
 members = ["crates/monero-runtime"]
+exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
 version = "0.1.0-alpha.1"
@@ -28,9 +29,9 @@ monero-epee = { version = "0.2", default-features = false }
 # the sqlite3 symbols.
 rusqlite = { version = "0.37", default-features = false }
 sqlite-wasm-rs = "0.5"
-# OPFS sync-access VFS. The Zcash runtime vendors a copy patched with a
-# durability barrier; this uses the released crate.
-sqlite-wasm-vfs = "0.2"
+# OPFS sync-access VFS, patched with the Zcash runtime's patch (see
+# scripts/vendor-deps.sh): metadata I/O failures surface instead of passing.
+sqlite-wasm-vfs = { version = "0.2", path = "vendor/sqlite-wasm-vfs-0.2.0" }
 
 serde = { version = "1", features = ["derive"] }
 serde_json = "1"
diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md
index ea7365eb1..3140877db 100644
--- a/chain-runtimes/monero/README.md
+++ b/chain-runtimes/monero/README.md
@@ -7,9 +7,10 @@ incremental, transactional writes.
 ## Build
 
 ```bash
+bash scripts/vendor-deps.sh                               # once, before any cargo command
 cargo test --workspace                                    # native tests
 cargo check --workspace --target wasm32-unknown-unknown
-./scripts/build-wasm.sh                                   # release build to pkg/
+./scripts/build-wasm.sh                                   # release build to pkg/ (prepares vendor first)
 ./scripts/build-node-pkg.sh && node scripts/smoke.js      # wasm end-to-end smoke test
 ```
 
@@ -124,6 +125,8 @@ bindgen.rs   wasm boundary
 
 ## Relation to the Zcash runtime
 
-Separate workspaces with no code dependency. `crates/monero-runtime/build.rs` (wasm
-SQLite link glue) mirrors the Zcash one; keep them in sync. Unlike Zcash, `runtime.rs`
+Separate workspaces with no code dependency, but one storage layer: `vendor-deps.sh`
+rebuilds `sqlite-wasm-vfs` with the Zcash runtime's patch, using its
+`prepare-vendor.py`, so a VFS fix lands in both. `crates/monero-runtime/build.rs`
+(wasm SQLite link glue) mirrors the Zcash one; keep them in sync. Unlike Zcash, `runtime.rs`
 is not wasm-only, so its concurrency guards are covered by native tests.
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
index a6e7eddad..6cfa13299 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -1746,6 +1746,9 @@ pub async fn broadcast_signed(
         chain_tip,
         amounts,
     )?;
+    // Same for a record that may not be durable: a restart could make its
+    // inputs selectable again while the transaction is in flight.
+    crate::storage::durability_barrier().await?;
 
     // An explicit rejection means it will not confirm: undo the fresh record
     // and release the inputs. Other errors are uncertain: keep the record so the
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
index 941cc3519..678d72987 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
@@ -298,22 +298,38 @@ pub async fn delete_database(db_name: &str) -> Result {
     }
 }
 
-/// Durability barrier: ensures committed transactions reached durable storage.
+/// Durability barrier: fails if committed transactions may not have reached
+/// durable storage.
 ///
-/// Call after an **irreversible** action (e.g. a broadcast). Failure means
-/// durability is unknown, **not** that the action failed; callers must keep
-/// the real outcome.
+/// SQLite commits synchronously through the VFS, so commit errors already
+/// surface from the statement. This catches the rest: a metadata I/O failure
+/// (e.g. deleting the rollback journal) poisons the patched pool, and nothing
+/// written since can be trusted until the Worker restarts.
 pub async fn durability_barrier() -> Result<()> {
-    #[cfg(target_arch = "wasm32")]
-    {
-        // SAH pool writes reach the OPFS handle before sqlite3 returns; this is
-        // an explicit sync point and the place for a real flush on another VFS.
-        Ok(())
+    if requires_worker_restart() {
+        return Err(RuntimeError::with(
+            ErrorCode::DatabaseError,
+            json!({ "reason": "storageRequiresWorkerRestart" }),
+        ));
     }
-    #[cfg(not(target_arch = "wasm32"))]
-    {
-        Ok(())
+    if !is_ready() {
+        return Err(RuntimeError::new(ErrorCode::NotInitialized));
     }
+    Ok(())
+}
+
+#[cfg(target_arch = "wasm32")]
+fn requires_worker_restart() -> bool {
+    VFS_UTIL.with(|slot| {
+        slot.borrow()
+            .as_ref()
+            .is_some_and(|util| util.is_poisoned())
+    })
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn requires_worker_restart() -> bool {
+    false
 }
 
 #[cfg(test)]
diff --git a/chain-runtimes/monero/patches/manifest.json b/chain-runtimes/monero/patches/manifest.json
new file mode 100644
index 000000000..2eab828a0
--- /dev/null
+++ b/chain-runtimes/monero/patches/manifest.json
@@ -0,0 +1,8 @@
+[
+  {
+    "name": "sqlite-wasm-vfs",
+    "version": "0.2.0",
+    "sha256": "7f7a5c9ac229421d577bb5a9bb59048838509958b218dd4e0b3c1214a87c361e",
+    "patch": "../../zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch"
+  }
+]
diff --git a/chain-runtimes/monero/scripts/build-wasm.sh b/chain-runtimes/monero/scripts/build-wasm.sh
index 0270e0d88..dcb7fb9ad 100755
--- a/chain-runtimes/monero/scripts/build-wasm.sh
+++ b/chain-runtimes/monero/scripts/build-wasm.sh
@@ -49,6 +49,8 @@ if [[ ! -x "${AR_wasm32_unknown_unknown}" ]]; then
 fi
 echo "==> Using clang: ${CLANG}"
 
+bash "${ROOT}/scripts/vendor-deps.sh"
+
 # With --mode no-install, a missing wasm-opt is only logged and skipped, leaving
 # an unoptimized output. Release builds require it.
 if [ "${PROFILE}" = "release" ] && ! command -v wasm-opt >/dev/null 2>&1; then
diff --git a/chain-runtimes/monero/scripts/ci.sh b/chain-runtimes/monero/scripts/ci.sh
index 518fc74df..ab0d1d094 100644
--- a/chain-runtimes/monero/scripts/ci.sh
+++ b/chain-runtimes/monero/scripts/ci.sh
@@ -7,6 +7,7 @@ VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"
 TAG=latest
 if [[ "$VERSION" =~ - ]]; then TAG=next; fi
 
+bash scripts/vendor-deps.sh
 cargo test --workspace --locked
 bash scripts/build-wasm.sh release
 python3 scripts/package-release.py --version "$VERSION" --tag "$TAG"
diff --git a/chain-runtimes/monero/scripts/vendor-deps.sh b/chain-runtimes/monero/scripts/vendor-deps.sh
new file mode 100755
index 000000000..7776a7fec
--- /dev/null
+++ b/chain-runtimes/monero/scripts/vendor-deps.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Reconstruct the patched OPFS VFS from upstream and the Zcash runtime's patch,
+# so both runtimes run the same storage layer.
+set -euo pipefail
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+exec python3 "${ROOT}/../zcash/scripts/prepare-vendor.py" --root "${ROOT}" "$@"
diff --git a/chain-runtimes/zcash/scripts/prepare-vendor.py b/chain-runtimes/zcash/scripts/prepare-vendor.py
index c7c3fa10c..ac79137be 100644
--- a/chain-runtimes/zcash/scripts/prepare-vendor.py
+++ b/chain-runtimes/zcash/scripts/prepare-vendor.py
@@ -42,12 +42,14 @@ def extract_crate(archive, temporary, identity):
                 raise RuntimeError(f"Unsupported crate archive entry: {member.name}")
 
 
-def prepare(offline):
-    vendor = ROOT / "vendor"
+def prepare(offline, root=None):
+    # Another runtime (Monero) reuses this script and the patches with its own root.
+    root = root or ROOT
+    vendor = root / "vendor"
     archives = vendor / ".archives"
     archives.mkdir(parents=True, exist_ok=True)
     cargo_home = Path(os.environ.get("CARGO_HOME", Path.home() / ".cargo"))
-    manifest = json.loads((ROOT / "patches/manifest.json").read_text())
+    manifest = json.loads((root / "patches/manifest.json").read_text())
     for entry in manifest:
         identity = f"{entry['name']}-{entry['version']}"
         archive = archives / f"{identity}.crate"
@@ -74,7 +76,7 @@ def prepare(offline):
             extract_crate(archive, temporary, identity)
             source = Path(temporary) / identity
             subprocess.run(
-                ["patch", "--batch", "--forward", "-F", "0", "-p1", "-i", str(ROOT / "patches" / entry["patch"])],
+                ["patch", "--batch", "--forward", "-F", "0", "-p1", "-i", str(root / "patches" / entry["patch"])],
                 cwd=source,
                 check=True,
             )
@@ -90,4 +92,6 @@ def prepare(offline):
 if __name__ == "__main__":
     parser = argparse.ArgumentParser(description=__doc__)
     parser.add_argument("--offline", action="store_true", help="Use cached crate archives only")
-    prepare(parser.parse_args().offline)
+    parser.add_argument("--root", type=Path, help="Runtime directory holding patches/ and vendor/")
+    args = parser.parse_args()
+    prepare(args.offline, args.root.resolve() if args.root else None)

From 997f6a704e412e6a4b28d4070ab3a3aa8c66f33d Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Fri, 16 Oct 2026 18:27:39 +0800
Subject: [PATCH 46/97] feat(zcash): sign with account keys instead of the seed
 and mark change for hardware signers

---
 chain-runtimes/zcash/Cargo.lock               |   9 +-
 chain-runtimes/zcash/Cargo.toml               |   2 +-
 .../crates/zcash-keys-runtime/Cargo.toml      |   7 +-
 .../zcash-keys-runtime/src/account_keys.rs    | 562 ++++++++++++++++++
 .../crates/zcash-keys-runtime/src/bindgen.rs  | 107 ++--
 .../crates/zcash-keys-runtime/src/error.rs    |  11 +-
 .../crates/zcash-keys-runtime/src/keys.rs     | 168 +-----
 .../crates/zcash-keys-runtime/src/lib.rs      |  17 +-
 .../crates/zcash-keys-runtime/src/review.rs   | 177 +++++-
 .../crates/zcash-keys-runtime/src/sign.rs     |  62 +-
 .../src/transparent_send.rs                   |  87 ++-
 .../src/transparent_send/shielding.rs         | 181 ++++--
 .../zcash/crates/zcash-runtime/Cargo.toml     |   2 +
 .../zcash/crates/zcash-runtime/src/account.rs |   5 +-
 .../zcash/crates/zcash-runtime/src/send.rs    | 520 +++++++++++++++-
 15 files changed, 1520 insertions(+), 397 deletions(-)
 create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs

diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index 04c16cb45..17004b508 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1655,9 +1655,11 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-zcash-keys"
-version = "0.1.0-alpha.1"
+version = "0.1.0-alpha.2"
 dependencies = [
  "bip0039",
+ "bip32",
+ "blake2b_simd",
  "bs58",
  "getrandom 0.2.17",
  "getrandom 0.4.3",
@@ -1685,7 +1687,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-runtime"
-version = "0.1.0-alpha.1"
+version = "0.1.0-alpha.2"
 dependencies = [
  "blake2b_simd",
  "console_error_panic_hook",
@@ -1724,6 +1726,7 @@ dependencies = [
  "zcash_client_backend",
  "zcash_client_sqlite",
  "zcash_keys",
+ "zcash_note_encryption",
  "zcash_primitives",
  "zcash_protocol",
  "zcash_transparent",
@@ -1733,7 +1736,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-storage-benchmark"
-version = "0.1.0-alpha.1"
+version = "0.1.0-alpha.2"
 dependencies = [
  "console_error_panic_hook",
  "js-sys",
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index 16b908fb2..dea5c9773 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -8,7 +8,7 @@ members = [
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.1"
+version = "0.1.0-alpha.2"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml
index 2c614da14..7ad6e24db 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml
@@ -26,6 +26,9 @@ serde.workspace = true
 serde_json.workspace = true
 hex.workspace = true
 secp256k1 = { version = "0.29", features = ["alloc"], default-features = false }
+# Same pinned version as zcash_transparent: parses the account xprv without upstream
+# `AccountPrivKey::from_bytes`, which re-encodes it into an unwiped heap string.
+bip32 = { version = "=0.6.0-pre.1", default-features = false, features = ["secp256k1-ffi"] }
 zcash_script = { version = "0.4.3", default-features = false }
 # signer + orchard: sign PCZT Orchard spends. prover/tx-extractor belong to the runtime crate.
 # transparent: shielding must sign transparent inputs. Pulls in zcash_script (pure Rust
@@ -36,9 +39,11 @@ orchard = { version = "0.15", default-features = false }
 sapling.workspace = true
 thiserror.workspace = true
 
-# bip0039 is test-only: shipped builds take seed bytes, never a mnemonic.
+# Test-only: shipped builds never take a seed or mnemonic. bip0039 and blake2b_simd
+# derive account keys from seeds for parity tests against upstream.
 [dev-dependencies]
 bip0039 = { version = "0.12", features = ["all-languages"] }
+blake2b_simd.workspace = true
 
 [target.'cfg(target_arch = "wasm32")'.dependencies]
 wasm-bindgen.workspace = true
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
new file mode 100644
index 000000000..c83c9f5b4
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
@@ -0,0 +1,562 @@
+//! Account-scoped software keys supplied by the host.
+//!
+//! The host derives the ZIP-32 Orchard account spending key (`m/32'/133'/account'`)
+//! and the BIP-44 transparent account key (`m/44'/133'/account'`) from its seed;
+//! no seed or mnemonic crosses this boundary. Mainnet only.
+
+use std::ops::Deref;
+
+use orchard::keys::{FullViewingKey, SpendingKey};
+use serde_json::json;
+use transparent::keys::{AccountPrivKey, AccountPubKey};
+use zcash_protocol::consensus::{Network, Parameters};
+use zeroize::Zeroizing;
+use zip32::AccountId;
+
+use crate::{
+    error::{ErrorCode, KeysError, Result},
+    keys, review, sign, transparent_send,
+};
+
+/// Upstream key types that can be wiped in place.
+///
+/// # Safety
+///
+/// Implementors must be flat: no drop glue, pointers, or niches, so all-zero bytes
+/// are a valid value. `SpendingKey` is `[u8; 32]`; `AccountPrivKey` is a bip32
+/// `ExtendedPrivateKey` of `secp256k1::SecretKey([u8; 32])` and plain attributes.
+pub(crate) unsafe trait FlatKey {}
+unsafe impl FlatKey for SpendingKey {}
+unsafe impl FlatKey for AccountPrivKey {}
+
+/// Wipes an upstream key that lacks `ZeroizeOnDrop` when dropped. Copies the
+/// compiler leaves in moved-from stack slots are outside its reach.
+pub(crate) struct Wiped(T);
+
+impl Wiped {
+    pub(crate) fn new(key: T) -> Self {
+        const { assert!(!std::mem::needs_drop::()) };
+        Self(key)
+    }
+}
+
+impl Deref for Wiped {
+    type Target = T;
+
+    fn deref(&self) -> &T {
+        &self.0
+    }
+}
+
+impl Drop for Wiped {
+    fn drop(&mut self) {
+        // SAFETY: `FlatKey` types are flat, and `new` rejects drop glue.
+        unsafe { zeroize::zeroize_flat_type(&mut self.0) }
+    }
+}
+
+/// Spending keys for one account, wiped on drop. Only the xprv carries account
+/// metadata; `review::verify_signer` binds both keys to the reviewed UFVK.
+pub struct AccountSigningKeys {
+    params: Network,
+    orchard: Wiped,
+    transparent: Wiped,
+}
+
+impl AccountSigningKeys {
+    pub fn parse(
+        network: &str,
+        orchard_sk: &[u8],
+        account_xprv: &str,
+        account_index: u32,
+    ) -> Result {
+        let params = parse_mainnet(network)?;
+        account_id(account_index)?;
+        let orchard = parse_orchard_sk(orchard_sk)?;
+        let transparent = transparent_send::parse_account_xprv(account_xprv, account_index)?;
+        Ok(Self {
+            params,
+            orchard,
+            transparent,
+        })
+    }
+
+    pub fn params(&self) -> Network {
+        self.params
+    }
+
+    pub(crate) fn orchard(&self) -> &SpendingKey {
+        &self.orchard
+    }
+
+    pub(crate) fn transparent(&self) -> &AccountPrivKey {
+        &self.transparent
+    }
+
+    /// The UFVK these keys control, encoded exactly like `ufvkFromAccountKeys`.
+    pub fn ufvk(&self) -> Result {
+        ufvk_from_parts(
+            self.params,
+            &FullViewingKey::from(&*self.orchard),
+            &self.transparent.to_account_pubkey(),
+        )
+    }
+}
+
+/// The account-key APIs reject testnet.
+fn parse_mainnet(network: &str) -> Result {
+    match keys::parse_network(network)? {
+        Network::MainNetwork => Ok(Network::MainNetwork),
+        Network::TestNetwork => Err(KeysError::with(
+            ErrorCode::InvalidNetwork,
+            json!({ "value": network, "supported": ["main"] }),
+        )),
+    }
+}
+
+fn account_id(account_index: u32) -> Result {
+    AccountId::try_from(account_index).map_err(|_| {
+        KeysError::with(
+            ErrorCode::InvalidAccountIndex,
+            json!({ "value": account_index }),
+        )
+    })
+}
+
+/// Parse a raw 32-byte Orchard spending key, rejecting keys upstream deems invalid.
+pub(crate) fn parse_orchard_sk(bytes: &[u8]) -> Result> {
+    let bytes: Zeroizing<[u8; 32]> = Zeroizing::new(bytes.try_into().map_err(|_| {
+        KeysError::with(
+            ErrorCode::InvalidSpendingKey,
+            json!({ "byteLen": bytes.len(), "expected": 32 }),
+        )
+    })?);
+    Option::from(SpendingKey::from_bytes(*bytes))
+        .map(Wiped::new)
+        .ok_or_else(|| KeysError::new(ErrorCode::InvalidSpendingKey))
+}
+
+/// Transparent + Orchard UFVK, the same items the OneKey firmware returns.
+///
+/// Sapling is left out: this runtime can neither scan for nor spend it, and the
+/// firmware rejects PCZTs that carry it. Ironwood keys derive from the Orchard item.
+pub(crate) fn ufvk_from_parts(
+    params: Network,
+    fvk: &FullViewingKey,
+    account: &AccountPubKey,
+) -> Result {
+    use zcash_address::unified::{Encoding, Fvk, Ufvk};
+    let p2pkh: [u8; 65] = account
+        .serialize()
+        .try_into()
+        .map_err(|_| KeysError::new(ErrorCode::DeriveFailed))?;
+    let container = Ufvk::try_from_items(vec![Fvk::P2pkh(p2pkh), Fvk::Orchard(fvk.to_bytes())])
+        .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?;
+    Ok(container.encode(¶ms.network_type()))
+}
+
+/// UFVK from the Orchard account spending key and the transparent account xpub.
+///
+/// Account setup needs no transparent secret: the xpub is public account material.
+pub fn ufvk_from_account_keys(
+    network: &str,
+    orchard_sk: &[u8],
+    account_xpub: &str,
+    account_index: u32,
+) -> Result {
+    let params = parse_mainnet(network)?;
+    account_id(account_index)?;
+    let orchard = parse_orchard_sk(orchard_sk)?;
+    let transparent = transparent_send::parse_account_xpub(account_xpub, account_index)?;
+    ufvk_from_parts(params, &FullViewingKey::from(&*orchard), &transparent)
+}
+
+/// Verify a PCZT against the reviewed payment and the signer's own UFVK, then sign it.
+pub fn sign_reviewed_pczt(
+    network: &str,
+    orchard_sk: &[u8],
+    account_xprv: &str,
+    account_index: u32,
+    pczt_bytes: &[u8],
+    review_json: &str,
+) -> Result> {
+    let keys = AccountSigningKeys::parse(network, orchard_sk, account_xprv, account_index)?;
+    review::verify_signer(&keys, pczt_bytes, review_json)?;
+    sign::sign_pczt_with_account_keys(&keys, pczt_bytes)
+}
+
+/// Test-only key material derived from a seed, mirroring the host derivation.
+#[cfg(test)]
+pub(crate) mod test_keys {
+    use super::*;
+    use zcash_keys::keys::UnifiedSpendingKey;
+    use zcash_protocol::consensus::MAIN_NETWORK;
+
+    const XPRV_VERSION: [u8; 4] = [0x04, 0x88, 0xad, 0xe4];
+    const XPUB_VERSION: [u8; 4] = [0x04, 0x88, 0xb2, 0x1e];
+
+    fn blake2b_512(personal: &[u8; 16], parts: &[&[u8]]) -> [u8; 64] {
+        let mut state = blake2b_simd::Params::new()
+            .hash_length(64)
+            .personal(personal)
+            .to_state();
+        for part in parts {
+            state.update(part);
+        }
+        state.finalize().as_bytes().try_into().unwrap()
+    }
+
+    /// ZIP-32 Orchard hardened derivation, written out the way the host computes it.
+    pub(crate) fn orchard_sk_at(seed: &[u8], path: &[u32]) -> [u8; 32] {
+        let i = blake2b_512(b"ZcashIP32Orchard", &[seed]);
+        let (mut sk, mut chain): ([u8; 32], [u8; 32]) =
+            (i[..32].try_into().unwrap(), i[32..].try_into().unwrap());
+        for &index in path {
+            let child = (index | (1 << 31)).to_le_bytes();
+            let i = blake2b_512(b"Zcash_ExpandSeed", &[&chain, &[0x81], &sk, &child]);
+            sk = i[..32].try_into().unwrap();
+            chain = i[32..].try_into().unwrap();
+        }
+        sk
+    }
+
+    /// `m/32'/133'/account'`.
+    pub(crate) fn orchard_sk(seed: &[u8], account: u32) -> [u8; 32] {
+        orchard_sk_at(seed, &[32, 133, account])
+    }
+
+    pub(crate) fn account_priv_key(seed: &[u8], account: u32) -> AccountPrivKey {
+        AccountPrivKey::from_seed(&MAIN_NETWORK, seed, AccountId::try_from(account).unwrap())
+            .unwrap()
+    }
+
+    pub(crate) fn encode_xprv(key: &AccountPrivKey) -> String {
+        let mut payload = XPRV_VERSION.to_vec();
+        payload.extend(key.to_bytes());
+        bs58::encode(payload).with_check().into_string()
+    }
+
+    pub(crate) fn account_xprv(seed: &[u8], account: u32) -> String {
+        encode_xprv(&account_priv_key(seed, account))
+    }
+
+    pub(crate) fn account_xpub(seed: &[u8], account: u32) -> String {
+        let key = account_priv_key(seed, account);
+        // depth || parent fingerprint || child number, then chain code || pubkey.
+        let header = key.to_bytes()[..9].to_vec();
+        let mut payload = XPUB_VERSION.to_vec();
+        payload.extend(header);
+        payload.extend(key.to_account_pubkey().serialize());
+        bs58::encode(payload).with_check().into_string()
+    }
+
+    /// Oracle: the upstream seed-based USK this crate no longer accepts.
+    pub(crate) fn usk(seed: &[u8], account: u32) -> UnifiedSpendingKey {
+        UnifiedSpendingKey::from_seed(&MAIN_NETWORK, seed, AccountId::try_from(account).unwrap())
+            .unwrap()
+    }
+
+    pub(crate) fn signing_keys(seed: &[u8], account: u32) -> AccountSigningKeys {
+        AccountSigningKeys::parse(
+            "main",
+            &orchard_sk(seed, account),
+            &account_xprv(seed, account),
+            account,
+        )
+        .unwrap()
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::test_keys::*;
+    use super::*;
+    use orchard::keys::{SpendAuthorizingKey, SpendValidatingKey};
+
+    const ABANDON_MNEMONIC: &str =
+        "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
+
+    fn abandon_seed() -> Vec {
+        bip0039::Mnemonic::::from_phrase(ABANDON_MNEMONIC)
+            .unwrap()
+            .to_seed("")
+            .to_vec()
+    }
+
+    /// Deterministic seeds of both lengths the transparent and Orchard derivations accept.
+    fn deterministic_seeds(count: u32) -> Vec> {
+        (0..count)
+            .map(|i| {
+                // BIP-32 (transparent) accepts 16, 32 or 64 bytes; BIP-39 seeds are 64.
+                let len = [64usize, 32][i as usize % 2];
+                let mut seed = Vec::new();
+                let mut block = 0u32;
+                while seed.len() < len {
+                    let hash = blake2b_simd::Params::new()
+                        .hash_length(64)
+                        .personal(b"OneKeyZcashSeeds")
+                        .to_state()
+                        .update(&i.to_le_bytes())
+                        .update(&block.to_le_bytes())
+                        .finalize();
+                    seed.extend_from_slice(hash.as_bytes());
+                    block += 1;
+                }
+                seed.truncate(len);
+                seed
+            })
+            .collect()
+    }
+
+    fn assert_parity(seed: &[u8], account: u32) {
+        let oracle = usk(seed, account);
+        let oracle_ufvk = oracle.to_unified_full_viewing_key();
+        let sk = orchard_sk(seed, account);
+        assert_eq!(
+            &sk,
+            oracle.orchard().to_bytes(),
+            "orchard sk, account {account}"
+        );
+
+        let keys = signing_keys(seed, account);
+        let new_ufvk = keys.ufvk().unwrap();
+        assert_eq!(
+            new_ufvk,
+            keys::without_sapling(Network::MainNetwork, &oracle_ufvk).unwrap(),
+            "UFVK, account {account}"
+        );
+        assert_eq!(
+            ufvk_from_account_keys("main", &sk, &account_xpub(seed, account), account).unwrap(),
+            new_ufvk
+        );
+
+        let new_fvk = FullViewingKey::from(keys.orchard());
+        let oracle_fvk = oracle_ufvk.orchard().unwrap().clone();
+        assert_eq!(new_fvk.to_bytes(), oracle_fvk.to_bytes(), "FVK bytes");
+        // ak, the SpendValidatingKey encoding, is the first 32 bytes of the FVK encoding.
+        assert_eq!(new_fvk.to_bytes()[..32], oracle_fvk.to_bytes()[..32]);
+        assert_eq!(
+            SpendValidatingKey::from(&SpendAuthorizingKey::from(keys.orchard())),
+            SpendValidatingKey::from(&SpendAuthorizingKey::from(oracle.orchard())),
+            "SpendValidatingKey, account {account}"
+        );
+        assert_eq!(
+            SpendValidatingKey::from(new_fvk),
+            SpendValidatingKey::from(oracle_fvk)
+        );
+        assert_eq!(
+            keys.transparent().to_account_pubkey().serialize(),
+            oracle.transparent().to_account_pubkey().serialize()
+        );
+    }
+
+    #[test]
+    fn account_keys_match_the_seed_oracle_for_fixed_seeds() {
+        for seed in [vec![7u8; 32], vec![0x42u8; 64], abandon_seed()] {
+            for account in [0, 1, (1 << 31) - 1] {
+                assert_parity(&seed, account);
+                assert_eq!(
+                    signing_keys(&seed, account).ufvk().unwrap(),
+                    keys::ufvk_from_seed_bytes(Network::MainNetwork, &seed, account).unwrap()
+                );
+            }
+        }
+    }
+
+    #[test]
+    fn account_keys_match_the_seed_oracle_for_deterministic_seeds() {
+        let seeds = deterministic_seeds(100);
+        let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
+        std::thread::scope(|scope| {
+            for chunk in seeds.chunks(seeds.len().div_ceil(threads)) {
+                scope.spawn(move || {
+                    for seed in chunk {
+                        for account in [0, 1, (1 << 31) - 1] {
+                            assert_parity(seed, account);
+                        }
+                    }
+                });
+            }
+        });
+    }
+
+    /// ZIP-32 Orchard test vectors (orchard `test_vectors::zip32`, seed 0x00..0x1f):
+    /// pin the hand-written derivation the host mirrors.
+    #[test]
+    fn orchard_derivation_matches_zip32_vectors() {
+        let seed = (0u8..32).collect::>();
+        assert_eq!(
+            hex::encode(orchard_sk_at(&seed, &[])),
+            "7eee3c1017870990a3dd6891b82f80be8976c1e7dc20d60817a5e88e8b2cd4b8"
+        );
+        assert_eq!(
+            hex::encode(orchard_sk_at(&seed, &[1, 2, 3])),
+            "96439ea348a4b2ce4ec7beb4543c70274c8f76495d60c5fa5f018b68f3c32367"
+        );
+    }
+
+    #[test]
+    fn rejects_testnet_and_malformed_keys() {
+        let seed = [7u8; 32];
+        let sk = orchard_sk(&seed, 0);
+        let xpub = account_xpub(&seed, 0);
+        let xprv = account_xprv(&seed, 0);
+
+        let e = ufvk_from_account_keys("test", &sk, &xpub, 0).unwrap_err();
+        assert_eq!(e.code, ErrorCode::InvalidNetwork);
+        let e = AccountSigningKeys::parse("test", &sk, &xprv, 0)
+            .err()
+            .unwrap();
+        assert_eq!(e.code, ErrorCode::InvalidNetwork);
+        let e = sign_reviewed_pczt("test", &sk, &xprv, 0, &[], "{}").unwrap_err();
+        assert_eq!(e.code, ErrorCode::InvalidNetwork);
+
+        for len in [0usize, 31, 33, 64] {
+            let e = ufvk_from_account_keys("main", &vec![1u8; len], &xpub, 0).unwrap_err();
+            assert_eq!(e.code, ErrorCode::InvalidSpendingKey);
+            assert_eq!(e.params["byteLen"], len);
+        }
+
+        // The xpub/xprv metadata must name the requested account.
+        let e = ufvk_from_account_keys("main", &sk, &xpub, 1).unwrap_err();
+        assert_eq!(e.code, ErrorCode::InvalidAccountXpub);
+        let e = AccountSigningKeys::parse("main", &sk, &xprv, 1)
+            .err()
+            .unwrap();
+        assert_eq!(e.code, ErrorCode::InvalidAccountXprv);
+        let e = ufvk_from_account_keys("main", &sk, &xprv, 0).unwrap_err();
+        assert_eq!(e.code, ErrorCode::InvalidAccountXpub);
+        let e = AccountSigningKeys::parse("main", &sk, &xpub, 0)
+            .err()
+            .unwrap();
+        assert_eq!(e.code, ErrorCode::InvalidAccountXprv);
+
+        let e = ufvk_from_account_keys("main", &sk, &xpub, 1 << 31).unwrap_err();
+        assert_eq!(e.code, ErrorCode::InvalidAccountIndex);
+    }
+
+    #[test]
+    fn xprv_parse_matches_upstream_decoding() {
+        for account in [0, 1, (1 << 31) - 1] {
+            let seed = [7u8; 32];
+            let parsed =
+                transparent_send::parse_account_xprv(&account_xprv(&seed, account), account)
+                    .unwrap();
+            assert_eq!(
+                parsed.to_bytes(),
+                account_priv_key(&seed, account).to_bytes()
+            );
+        }
+    }
+
+    #[test]
+    fn parsed_keys_are_wiped_on_drop() {
+        let mut keys = std::mem::ManuallyDrop::new(signing_keys(&[7u8; 32], 0));
+        // SAFETY: dropped once; the fields are flat, so their bytes stay readable.
+        unsafe { std::mem::ManuallyDrop::drop(&mut keys) };
+        assert_eq!(keys.orchard().to_bytes(), &[0u8; 32]);
+        assert!(keys.transparent().to_bytes().iter().all(|&b| b == 0));
+    }
+
+    #[test]
+    fn errors_never_carry_key_material() {
+        let seed = [7u8; 32];
+        let sk = orchard_sk(&seed, 0);
+        let xprv = account_xprv(&seed, 0);
+        let mut bad_checksum = xprv.clone();
+        bad_checksum.pop();
+        bad_checksum.push(if xprv.ends_with('1') { '2' } else { '1' });
+        let secrets = [
+            xprv.clone(),
+            hex::encode(sk),
+            hex::encode(account_priv_key(&seed, 0).to_bytes()),
+        ];
+        let errors = [
+            sign_reviewed_pczt("main", &sk, &xprv, 0, &[], "{}").unwrap_err(),
+            sign_reviewed_pczt("main", &sk, &xprv, 0, &[], "not json").unwrap_err(),
+            sign_reviewed_pczt("main", &sk, &xprv, 1, &[], "{}").unwrap_err(),
+            sign_reviewed_pczt("main", &sk, &bad_checksum, 0, &[], "{}").unwrap_err(),
+            sign_reviewed_pczt("main", &sk[..31], &xprv, 0, &[], "{}").unwrap_err(),
+            transparent_send::build_with_account_xprv_json("{}", &xprv).unwrap_err(),
+        ];
+        for e in errors {
+            let rendered = format!("{e} {}", e.to_json());
+            for secret in &secrets {
+                assert!(!rendered.contains(secret.as_str()), "{rendered}");
+            }
+        }
+    }
+
+    /// Hardware parity vectors from the independent firmware implementation:
+    /// fingerprint, Orchard FVK (96B), transparent pubkey (65B), and both receivers.
+    #[test]
+    fn hardware_parity_vectors() {
+        use zcash_address::unified::{Container, Encoding, Fvk, Receiver, Ufvk};
+
+        const FINGERPRINT: &str =
+            "21ed3d7882c7e37fe012b54a6408048048cb09782d4b2938617da793ccd27815";
+        const HW: [(u32, &str, &str); 2] = [
+            (
+                0,
+                "uview1s8x5c6zq8pllw2v8ywmcp0fm46d5dk0er8gwwraz2l2s6g0cvq0jlyar820w9z6sh5l285d2ctzcukr2j2fn6cl7nyapa235fxkcmf7xkg4e3pc0phu7e95mukwx3j8t96p7yzuuxhdl9u28letaxay3gyscd9s4tr59dxg4uulsdxjxmy64ls4sy36n8p03j7f0d9w4ycjullvp5lqgslc4agjlgxzk53wnwkcm4andl5xqgs2afa7ewkkfl9fcyw7s5kknzlmn55m6sz93yvqpx78shy0uausk3avw",
+                "u1wzxtkul0j9he76y7m87agwd4z3vrkauchag9kwrzng07mkm2ntmc687mg45m4rjr979zhyjkn80ml4vkaty3ej20sc7hk65n0yr42chn7hw6ysdgwpu5l38ttxzhyldaa2unx7u4j8c",
+            ),
+            (
+                1,
+                "uview1anf6l9jhehdpktvfw4xur3emcrx7yeh6tczezfks6jmgujakhny45uqu6tc0un9ewqlk7uh5eq5fxfacwhgu3pw94yr5khdqdfl660ypxl2xryyqm6hamwwukn5dygk2hkl8lutx3ck5qy9zched9rny0ckz7rezx65um0rj0l0lcxsry8nzjakx9ftz6lecjjnym76pz5eury9yvh7rnk4pn8l76nc092h5l0x38vnxxgkwngdk0lguqjjy3sa2vzr5vay65p04zh0nqev5wvy5ypv7u060usd8yhqs",
+                "u1w969tctgrxzjplcpjape6al3wdqfzap4v82zhc6spfz24erd5jaea8w0rg649vknphqp30kgsahnupznu6faasvxwr700xxld9ttwermpgghrk7lxvxydmzku6vw3gwnkgac53c2v3h",
+            ),
+        ];
+
+        let seed = abandon_seed();
+        let fingerprint = zip32::fingerprint::SeedFingerprint::from_seed(&seed).unwrap();
+        assert_eq!(hex::encode(fingerprint.to_bytes()), FINGERPRINT);
+
+        let fvk_items = |s: &str| {
+            let (_, u) = Ufvk::decode(s).expect("decode UFVK");
+            let mut orchard = None;
+            let mut p2pkh = None;
+            for item in u.items() {
+                match item {
+                    Fvk::Orchard(d) => orchard = Some(d.to_vec()),
+                    Fvk::P2pkh(d) => p2pkh = Some(d.to_vec()),
+                    _ => {}
+                }
+            }
+            (orchard.expect("orchard item"), p2pkh.expect("p2pkh item"))
+        };
+        let ua_receivers = |s: &str| {
+            let (_, a) = zcash_address::unified::Address::decode(s).expect("decode UA");
+            let mut orchard = None;
+            let mut p2pkh = None;
+            for item in a.items() {
+                match item {
+                    Receiver::Orchard(d) => orchard = Some(d.to_vec()),
+                    Receiver::P2pkh(d) => p2pkh = Some(d.to_vec()),
+                    _ => {}
+                }
+            }
+            (
+                orchard.expect("orchard receiver"),
+                p2pkh.expect("p2pkh receiver"),
+            )
+        };
+
+        for (account, hw_ufvk, hw_ua) in HW {
+            let ours = ufvk_from_account_keys(
+                "main",
+                &orchard_sk(&seed, account),
+                &account_xpub(&seed, account),
+                account,
+            )
+            .unwrap();
+            assert_eq!(fvk_items(&ours), fvk_items(hw_ufvk), "account {account}");
+            let our_ua = keys::unified_address_with("main", &ours, "all").unwrap();
+            assert_eq!(
+                ua_receivers(&our_ua),
+                ua_receivers(hw_ua),
+                "account {account}"
+            );
+        }
+    }
+}
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
index cfbe3a5f0..bcc4a1928 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
@@ -1,11 +1,12 @@
 //! Host-facing key API.
 //!
-//! Seeds and spending keys never cross this boundary outward.
+//! No seed or mnemonic crosses this boundary. Spending keys enter only as
+//! account-scoped inputs and never cross it outward.
 
 use wasm_bindgen::prelude::*;
 use zeroize::Zeroizing;
 
-use crate::{keys, review, sign, transparent_prevouts, transparent_send};
+use crate::{account_keys, keys, review, sign, transparent_prevouts, transparent_send};
 
 /// Check recipient encoding, network, and supported receivers locally.
 #[wasm_bindgen(js_name = validateAddress)]
@@ -27,36 +28,48 @@ pub fn unified_address(
     Ok(keys::unified_address_with(network, ufvk, receiver_policy)?)
 }
 
-/// Derive a UFVK from seed bytes. This boundary never accepts a mnemonic.
-#[wasm_bindgen(js_name = ufvkFromSeed)]
-pub fn ufvk_from_seed(network: &str, seed: Vec, account_index: u32) -> Result {
+/// Derive a mainnet UFVK from the 32-byte Orchard account spending key
+/// (`m/32'/133'/account'`) and the transparent account xpub (`m/44'/133'/account'`).
+#[wasm_bindgen(js_name = ufvkFromAccountKeys)]
+pub fn ufvk_from_account_keys(
+    network: &str,
+    orchard_sk: Vec,
+    account_xpub: &str,
+    account_index: u32,
+) -> Result {
     // Own and wipe the original bindgen allocation, including on validation errors.
     // Wiping another copy would leave the JS-to-WASM input in freed linear memory.
-    let seed = Zeroizing::new(seed);
-    let params = keys::parse_network(network)?;
-    Ok(keys::ufvk_from_seed_bytes(params, &seed, account_index)?)
+    let orchard_sk = Zeroizing::new(orchard_sk);
+    Ok(account_keys::ufvk_from_account_keys(
+        network,
+        &orchard_sk,
+        account_xpub,
+        account_index,
+    )?)
 }
 
-/// Sign a PCZT with seed bytes after verifying it against the reviewed payment.
-///
-/// Spending keys are derived in Rust and never returned. The caller wipes its
-/// own seed copy; this side cannot wipe the JS heap.
-#[wasm_bindgen(js_name = pcztSignWithSeed)]
-pub fn pczt_sign_with_seed(
+/// Sign a mainnet PCZT with the Orchard account spending key and the transparent
+/// account xprv, after checking that they control the reviewed UFVK and that the
+/// PCZT matches the reviewed payment. The caller wipes its own copies; this side
+/// cannot wipe the JS heap.
+#[wasm_bindgen(js_name = pcztSignWithAccountKeys)]
+pub fn pczt_sign_with_account_keys(
     network: &str,
-    seed: Vec,
+    orchard_sk: Vec,
+    account_xprv: String,
     account_index: u32,
     pczt_bytes: Vec,
     review_json: &str,
 ) -> Result, JsValue> {
-    let seed = Zeroizing::new(seed);
-    let params = keys::parse_network(network)?;
-    review::verify_signer(params, &seed, account_index, &pczt_bytes, review_json)?;
-    Ok(sign::sign_pczt_with_seed(
-        params,
-        &seed,
+    let orchard_sk = Zeroizing::new(orchard_sk);
+    let account_xprv = Zeroizing::new(account_xprv);
+    Ok(account_keys::sign_reviewed_pczt(
+        network,
+        &orchard_sk,
+        &account_xprv,
         account_index,
         &pczt_bytes,
+        review_json,
     )?)
 }
 
@@ -84,13 +97,6 @@ pub fn transparent_account_pubkey_from_ufvk(network: &str, ufvk: &str) -> Result
     Ok(keys::transparent_account_pubkey(network, ufvk)?)
 }
 
-/// Standard ZIP-32 seed fingerprint, persisted by the host as account identity.
-#[wasm_bindgen(js_name = seedFingerprint)]
-pub fn seed_fingerprint(seed: Vec) -> Result {
-    let seed = Zeroizing::new(seed);
-    Ok(keys::seed_fingerprint(&seed)?)
-}
-
 /// Parses and verifies previous transactions without loading wallet state.
 #[wasm_bindgen(js_name = parseTransparentTransactions)]
 pub fn parse_transparent_transactions(request_json: &str) -> Result {
@@ -103,16 +109,6 @@ pub fn transparent_tx_quote(request_json: &str) -> Result {
     Ok(transparent_send::quote_json(request_json)?)
 }
 
-/// Builds and signs a mainnet V6 transparent transaction from a software-wallet seed.
-#[wasm_bindgen(js_name = transparentTxBuildWithSeed)]
-pub fn transparent_tx_build_with_seed(
-    request_json: &str,
-    seed: Vec,
-) -> Result {
-    let seed = Zeroizing::new(seed);
-    Ok(transparent_send::build_with_seed_json(request_json, &seed)?)
-}
-
 /// Builds and signs using an account xprv at `m/44'/133'/account'`.
 #[wasm_bindgen(js_name = transparentTxBuildWithAccountXprv)]
 pub fn transparent_tx_build_with_account_xprv(
@@ -137,19 +133,21 @@ pub fn keys_capabilities() -> String {
             "transparent": sign::SIGN_TRANSPARENT,
             "ironwood": sign::SIGN_IRONWOOD,
         },
+        "accountKeys": {
+            "network": "main",
+            "ufvk": true,
+            "pcztSign": true,
+        },
         "transparentTx": {
             "network": "main",
             "version": 6,
             "quote": true,
-            "buildWithSeed": true,
             "buildWithAccountXprv": true,
             "createWithAccountXpub": true,
             "combineHardwareSigned": true,
         },
         "transparentShield": {
-            "createWithSeed": transparent_send::shielding::SHIELD_CREATE_WITH_SEED,
             "createWithAccountXprv": transparent_send::shielding::SHIELD_CREATE_WITH_ACCOUNT_XPRV,
-            "signWithSeed": transparent_send::shielding::SHIELD_SIGN_WITH_SEED,
             "signWithAccountXprv": transparent_send::shielding::SHIELD_SIGN_WITH_ACCOUNT_XPRV,
         },
     })
@@ -192,33 +190,6 @@ pub fn dependency_versions() -> String {
     crate::dependency_versions().to_string()
 }
 
-/// Creates a shielding PCZT using only host-supplied transparent inputs.
-#[wasm_bindgen(js_name = transparentShieldCreateWithSeed)]
-pub fn transparent_shield_create_with_seed(
-    request_json: &str,
-    seed: Vec,
-) -> Result, JsValue> {
-    let seed = Zeroizing::new(seed);
-    Ok(transparent_send::shielding::create(request_json, &seed)?)
-}
-
-/// Signs the locally created, proved shielding PCZT.
-#[wasm_bindgen(js_name = transparentShieldSignWithSeed)]
-pub fn transparent_shield_sign_with_seed(
-    request_json: &str,
-    seed: Vec,
-    original: Vec,
-    pczt: Vec,
-) -> Result, JsValue> {
-    let seed = Zeroizing::new(seed);
-    Ok(transparent_send::shielding::sign(
-        request_json,
-        &seed,
-        &original,
-        &pczt,
-    )?)
-}
-
 /// Creates a shielding PCZT with an account-level transparent key.
 #[wasm_bindgen(js_name = transparentShieldCreateWithAccountXprv)]
 pub fn transparent_shield_create_with_account_xprv(
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs
index 7e863dc4e..56fde100a 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs
@@ -11,9 +11,9 @@ use std::fmt;
 pub enum ErrorCode {
     /// Network is not "main" / "test". Params: `{ value }`
     InvalidNetwork,
-    /// Mnemonic cannot be parsed.
+    /// Mnemonic cannot be parsed. Retired: no shipped API takes a mnemonic.
     InvalidMnemonic,
-    /// Seed is too short. Params: `{ byteLen, min }`
+    /// Seed is too short. Retired: no shipped API takes a seed.
     InvalidSeed,
     /// Account index out of range. Params: `{ value }`
     InvalidAccountIndex,
@@ -59,6 +59,9 @@ pub enum ErrorCode {
     TransactionBuildFailed,
     /// The signed transaction could not be serialized.
     TransactionSerializeFailed,
+    /// An Orchard spending key is not 32 bytes or is rejected by ZIP-32 validity rules.
+    /// Params: `{ byteLen, expected }` for a length error.
+    InvalidSpendingKey,
 }
 
 impl ErrorCode {
@@ -90,6 +93,7 @@ impl ErrorCode {
             InvalidAccountXpub => "INVALID_ACCOUNT_XPUB",
             TransactionBuildFailed => "TRANSACTION_BUILD_FAILED",
             TransactionSerializeFailed => "TRANSACTION_SERIALIZE_FAILED",
+            InvalidSpendingKey => "INVALID_SPENDING_KEY",
         }
     }
 }
@@ -101,7 +105,7 @@ pub struct KeysError {
     pub params: Value,
     /// Raw upstream error, for logs only.
     ///
-    /// Must never contain seeds, USKs, or anything derived from them. Upstream
+    /// Must never contain seeds, spending keys, or anything derived from them. Upstream
     /// errors describe structure and do not echo input, so passing them through is safe.
     pub detail: Option,
 }
@@ -208,6 +212,7 @@ mod tests {
             InvalidAccountXpub,
             TransactionBuildFailed,
             TransactionSerializeFailed,
+            InvalidSpendingKey,
         ];
         let mut seen = std::collections::HashSet::new();
         for c in all {
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
index b60894691..c8690ced5 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
@@ -1,12 +1,14 @@
-//! Key derivation.
+//! Public key material: networks, recipients, UFVK-derived addresses.
 //!
-//! Seeds and USKs never leave this module: input is seed bytes, output is only
-//! UFVKs and addresses.
+//! Account UFVKs are built from host-supplied account keys in `account_keys`.
 
-use zcash_keys::keys::{UnifiedFullViewingKey, UnifiedSpendingKey};
+use zcash_keys::keys::UnifiedFullViewingKey;
+#[cfg(test)]
+use zcash_keys::keys::UnifiedSpendingKey;
 use zcash_protocol::consensus::Network;
 #[cfg(test)]
 use zeroize::Zeroizing;
+#[cfg(test)]
 use zip32::AccountId;
 
 use crate::error::{ErrorCode, KeysError, Result};
@@ -48,7 +50,7 @@ pub fn validate_address(network: &str, encoded: &str) -> Result {
 
 /// Test-only: derive a UFVK from a mnemonic.
 ///
-/// Shipped builds never take a mnemonic; the host passes seed bytes only.
+/// Shipped builds never take a mnemonic or seed.
 #[cfg(test)]
 pub(crate) fn ufvk_from_mnemonic(
     network: &str,
@@ -62,18 +64,14 @@ pub(crate) fn ufvk_from_mnemonic(
     ufvk_from_seed_bytes(params, seed.as_ref(), account_index)
 }
 
-/// Derive a UFVK from raw seed bytes.
-///
-/// Transparent + Orchard only, the same items the OneKey firmware returns, so a
-/// software account and a device holding the same seed share one UFVK. Sapling
-/// is left out: this runtime can neither scan for nor spend it, and the
-/// firmware rejects PCZTs that carry it. Ironwood keys derive from the Orchard
-/// item.
-///
-/// The seed slice is borrowed, not retained. Upstream `UnifiedSpendingKey` is not
-/// `ZeroizeOnDrop`, so the intermediate USK stays in linear memory after drop;
-/// wiping is the host's responsibility.
-pub fn ufvk_from_seed_bytes(params: Network, seed: &[u8], account_index: u32) -> Result {
+/// Test-only oracle: the upstream seed-based UFVK, reduced to the transparent and
+/// Orchard items. Parity tests compare `account_keys` against it.
+#[cfg(test)]
+pub(crate) fn ufvk_from_seed_bytes(
+    params: Network,
+    seed: &[u8],
+    account_index: u32,
+) -> Result {
     if seed.len() < 32 {
         return Err(KeysError::with(
             ErrorCode::InvalidSeed,
@@ -97,7 +95,8 @@ pub fn ufvk_from_seed_bytes(params: Network, seed: &[u8], account_index: u32) ->
     without_sapling(params, &ufvk)
 }
 
-fn without_sapling(params: Network, ufvk: &UnifiedFullViewingKey) -> Result {
+#[cfg(test)]
+pub(crate) fn without_sapling(params: Network, ufvk: &UnifiedFullViewingKey) -> Result {
     use zcash_address::unified::{Container, Encoding, Fvk, Ufvk};
     let (network, container) = Ufvk::decode(&ufvk.encode(¶ms))
         .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?;
@@ -189,19 +188,6 @@ pub fn transparent_account_pubkey(network: &str, ufvk_str: &str) -> Result Result {
-    if seed.len() < 32 {
-        return Err(KeysError::with(
-            ErrorCode::InvalidSeed,
-            json!({ "byteLen": seed.len(), "min": 32 }),
-        ));
-    }
-    let fp = zip32::fingerprint::SeedFingerprint::from_seed(seed)
-        .ok_or_else(|| KeysError::with(ErrorCode::InvalidSeed, json!({ "byteLen": seed.len() })))?;
-    Ok(fp.to_bytes().iter().map(|b| format!("{b:02x}")).collect())
-}
-
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -210,8 +196,16 @@ mod tests {
     /// one seed agree; a Sapling item would also make the firmware reject PCZTs.
     #[test]
     fn ufvk_holds_only_transparent_and_orchard() {
+        use crate::account_keys::{test_keys, ufvk_from_account_keys};
         use zcash_address::unified::{Container, Encoding, Fvk, Ufvk};
-        let encoded = ufvk_from_seed_bytes(Network::MainNetwork, &[0x42u8; 64], 0).unwrap();
+        let seed = [0x42u8; 64];
+        let encoded = ufvk_from_account_keys(
+            "main",
+            &test_keys::orchard_sk(&seed, 0),
+            &test_keys::account_xpub(&seed, 0),
+            0,
+        )
+        .unwrap();
         let (_, container) = Ufvk::decode(&encoded).unwrap();
         let mut kinds = container
             .items()
@@ -228,20 +222,6 @@ mod tests {
         assert!(UnifiedFullViewingKey::decode(&Network::MainNetwork, &encoded).is_ok());
     }
 
-    /// The fingerprint is a standard value persisted as account identity; any
-    /// drift would orphan existing accounts.
-    #[test]
-    fn seed_fingerprint_is_stable() {
-        let seed = [0x42u8; 64];
-        let fp = seed_fingerprint(&seed).unwrap();
-        assert_eq!(fp.len(), 64, "32 bytes -> 64 hex chars");
-        assert_eq!(fp, seed_fingerprint(&seed).unwrap(), "must be stable");
-        // A different seed must change it.
-        assert_ne!(fp, seed_fingerprint(&[0x43u8; 64]).unwrap());
-        // Short seeds are rejected rather than fingerprinted.
-        assert!(seed_fingerprint(&[0u8; 16]).is_err());
-    }
-
     #[test]
     fn transparent_address_from_ufvk_is_t_prefixed() {
         let ufvk = ufvk_from_mnemonic("test", TEST_MNEMONIC, 0).unwrap();
@@ -359,12 +339,6 @@ mod tests {
         assert!(parse_network("testnet").is_err());
     }
 
-    #[test]
-    fn short_seed_is_rejected() {
-        let err = ufvk_from_seed_bytes(Network::TestNetwork, &[0u8; 16], 0);
-        assert!(err.is_err(), "short seed must be rejected");
-    }
-
     #[test]
     fn derives_ufvk_and_address() {
         let ufvk = ufvk_from_mnemonic("test", TEST_MNEMONIC, 0).expect("derive UFVK");
@@ -386,90 +360,6 @@ mod tests {
         let b = ufvk_from_mnemonic("test", TEST_MNEMONIC, 1).unwrap();
         assert_ne!(a, b, "different accounts must derive different UFVKs");
     }
-
-    /// Parity vectors from the independent hardware firmware implementation,
-    /// path m/32'/133'/account'.
-    ///
-    /// The firmware UFVK has no Sapling item and its UA is orchard+p2pkh, so this
-    /// compares item bytes rather than whole strings: fingerprint, Orchard FVK
-    /// (96B), transparent pubkey (65B), and both receivers. Drift in path, coin
-    /// type, or diversifier policy on either side fails here.
-    #[test]
-    fn hardware_parity_vectors() {
-        use zcash_address::unified::{Container, Encoding, Fvk, Receiver, Ufvk};
-
-        const MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
-        const FINGERPRINT: &str =
-            "21ed3d7882c7e37fe012b54a6408048048cb09782d4b2938617da793ccd27815";
-        const HW: [(u32, &str, &str); 2] = [
-            (
-                0,
-                "uview1s8x5c6zq8pllw2v8ywmcp0fm46d5dk0er8gwwraz2l2s6g0cvq0jlyar820w9z6sh5l285d2ctzcukr2j2fn6cl7nyapa235fxkcmf7xkg4e3pc0phu7e95mukwx3j8t96p7yzuuxhdl9u28letaxay3gyscd9s4tr59dxg4uulsdxjxmy64ls4sy36n8p03j7f0d9w4ycjullvp5lqgslc4agjlgxzk53wnwkcm4andl5xqgs2afa7ewkkfl9fcyw7s5kknzlmn55m6sz93yvqpx78shy0uausk3avw",
-                "u1wzxtkul0j9he76y7m87agwd4z3vrkauchag9kwrzng07mkm2ntmc687mg45m4rjr979zhyjkn80ml4vkaty3ej20sc7hk65n0yr42chn7hw6ysdgwpu5l38ttxzhyldaa2unx7u4j8c",
-            ),
-            (
-                1,
-                "uview1anf6l9jhehdpktvfw4xur3emcrx7yeh6tczezfks6jmgujakhny45uqu6tc0un9ewqlk7uh5eq5fxfacwhgu3pw94yr5khdqdfl660ypxl2xryyqm6hamwwukn5dygk2hkl8lutx3ck5qy9zched9rny0ckz7rezx65um0rj0l0lcxsry8nzjakx9ftz6lecjjnym76pz5eury9yvh7rnk4pn8l76nc092h5l0x38vnxxgkwngdk0lguqjjy3sa2vzr5vay65p04zh0nqev5wvy5ypv7u060usd8yhqs",
-                "u1w969tctgrxzjplcpjape6al3wdqfzap4v82zhc6spfz24erd5jaea8w0rg649vknphqp30kgsahnupznu6faasvxwr700xxld9ttwermpgghrk7lxvxydmzku6vw3gwnkgac53c2v3h",
-            ),
-        ];
-
-        let parsed = bip0039::Mnemonic::::from_phrase(MNEMONIC).expect("BIP39");
-        let seed = parsed.to_seed("");
-        assert_eq!(
-            seed_fingerprint(seed.as_ref()).unwrap(),
-            FINGERPRINT,
-            "seed fingerprint differs from hardware"
-        );
-
-        // Orchard / transparent item bytes of a UFVK.
-        let fvk_items = |s: &str| {
-            let (_, u) = Ufvk::decode(s).expect("decode UFVK");
-            let mut orchard = None;
-            let mut p2pkh = None;
-            for item in u.items() {
-                match item {
-                    Fvk::Orchard(d) => orchard = Some(d.to_vec()),
-                    Fvk::P2pkh(d) => p2pkh = Some(d.to_vec()),
-                    _ => {}
-                }
-            }
-            (orchard.expect("orchard item"), p2pkh.expect("p2pkh item"))
-        };
-        // Orchard / p2pkh receiver bytes of a UA.
-        let ua_receivers = |s: &str| {
-            let (_, a) = zcash_address::unified::Address::decode(s).expect("decode UA");
-            let mut orchard = None;
-            let mut p2pkh = None;
-            for item in a.items() {
-                match item {
-                    Receiver::Orchard(d) => orchard = Some(d.to_vec()),
-                    Receiver::P2pkh(d) => p2pkh = Some(d.to_vec()),
-                    _ => {}
-                }
-            }
-            (
-                orchard.expect("missing orchard receiver"),
-                p2pkh.expect("missing p2pkh receiver"),
-            )
-        };
-
-        for (account, hw_ufvk, hw_ua) in HW {
-            let ours = ufvk_from_mnemonic("main", MNEMONIC, account).expect("derive UFVK");
-            assert_eq!(
-                fvk_items(&ours),
-                fvk_items(hw_ufvk),
-                "account {account}: FVK item bytes differ from hardware"
-            );
-            // "all" is our policy with a p2pkh receiver; compare receiver bytes only.
-            let our_ua = unified_address_with("main", &ours, "all").expect("UA");
-            assert_eq!(
-                ua_receivers(&our_ua),
-                ua_receivers(hw_ua),
-                "account {account}: address receiver bytes differ from hardware"
-            );
-        }
-    }
 }
 
 #[cfg(test)]
@@ -516,7 +406,11 @@ mod ua_inspect {
         println!("network      {network}  account {account}");
         println!(
             "fingerprint  {}",
-            super::seed_fingerprint(seed.as_ref()).expect("fingerprint")
+            hex::encode(
+                zip32::fingerprint::SeedFingerprint::from_seed(seed.as_ref())
+                    .expect("fingerprint")
+                    .to_bytes()
+            )
         );
         println!("ufvk         {ufvk}");
         println!(
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs
index 284fb63d4..bf6df47b6 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs
@@ -6,12 +6,19 @@
 //!
 //! ## Key handling
 //!
-//! - Seeds and spending keys (USK) stay inside this crate and never cross the wasm boundary.
-//! - JS receives only UFVKs and addresses; the boundary takes seed bytes, never a mnemonic.
-//! - Seeds, including the caller's copy, are wrapped in `Zeroizing` and wiped after use.
-//! - Derived keys are not wiped: upstream `UnifiedSpendingKey`, `AccountPrivKey`, and
-//!   `secp256k1::SecretKey` lack `ZeroizeOnDrop` and remain in wasm linear memory.
+//! - No seed or mnemonic crosses the wasm boundary. Software signing takes only
+//!   account-scoped keys: the 32-byte Orchard spending key (`m/32'/133'/account'`)
+//!   and the transparent account xprv (`m/44'/133'/account'`). Mainnet only.
+//! - Spending keys never cross the boundary outward; JS receives UFVKs, addresses,
+//!   and signed transactions.
+//! - Secret inputs, including the bindgen copies, are wrapped in `Zeroizing` and wiped after use.
+//! - The xprv is parsed without heap copies, and the parsed account keys are wiped on
+//!   drop (`account_keys::Wiped`). Known limit: upstream `SpendingKey`, `AccountPrivKey`,
+//!   and `secp256k1::SecretKey` lack `ZeroizeOnDrop`, so keys derived from them inside
+//!   upstream code (child secret keys, spend authorizing keys) and moved-from stack
+//!   copies are not wiped here; the host wipes the wasm stack after each call.
 
+pub mod account_keys;
 pub mod error;
 pub mod keys;
 pub mod review;
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs
index d595c3116..3d0821822 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs
@@ -2,11 +2,12 @@ use pczt::roles::verifier::{OrchardError, Verifier};
 use serde::Deserialize;
 use zcash_keys::{address::Address, keys::UnifiedFullViewingKey};
 use zcash_note_encryption::Domain;
-use zcash_protocol::{consensus::Network, memo::MemoBytes};
+use zcash_protocol::memo::MemoBytes;
 use zcash_script::script::Evaluable;
 use zip32::Scope;
 
 use crate::{
+    account_keys::AccountSigningKeys,
     error::{ErrorCode, KeysError, Result},
     keys,
 };
@@ -200,17 +201,10 @@ pub fn verify_json(pczt_bytes: &[u8], json: &str) -> Result<()> {
     verify(pczt_bytes, &parse_request(json)?)
 }
 
-pub fn verify_signer(
-    params: Network,
-    seed: &[u8],
-    account_index: u32,
-    pczt_bytes: &[u8],
-    json: &str,
-) -> Result<()> {
+/// The reviewed UFVK must be the one the signing keys control, rebuilt from those keys.
+pub fn verify_signer(keys: &AccountSigningKeys, pczt_bytes: &[u8], json: &str) -> Result<()> {
     let request = parse_request(json)?;
-    if keys::parse_network(&request.network)? != params
-        || keys::ufvk_from_seed_bytes(params, seed, account_index)? != request.ufvk
-    {
+    if keys::parse_network(&request.network)? != keys.params() || keys.ufvk()? != request.ufvk {
         return Err(mismatch("signerAccount"));
     }
     verify(pczt_bytes, &request)
@@ -219,11 +213,16 @@ pub fn verify_signer(
 #[cfg(test)]
 mod tests {
     use super::*;
-    use pczt::roles::creator::Creator;
+    use crate::account_keys::{self, test_keys};
+    use pczt::roles::{
+        creator::Creator,
+        signer::{extract_orchard_spend_auth_signatures, Signer},
+    };
     use zcash_primitives::transaction::{
         builder::{BuildConfig, Builder, BundlePadding},
         fees::fixed::FeeRule,
     };
+    use zcash_protocol::consensus::Network;
     use zcash_protocol::value::Zatoshis;
 
     fn fixture(source: &str, max: bool, foreign_change: bool) -> (Vec, ReviewRequest) {
@@ -236,10 +235,10 @@ mod tests {
         foreign_change: bool,
         memo_hex: Option,
     ) -> (Vec, ReviewRequest) {
-        let ufvk_string = keys::ufvk_from_seed_bytes(Network::MainNetwork, &[7; 32], 0).unwrap();
+        let ufvk_string = test_keys::signing_keys(&[7; 32], 0).ufvk().unwrap();
         let ufvk = UnifiedFullViewingKey::decode(&Network::MainNetwork, &ufvk_string).unwrap();
         let fvk = ufvk.orchard().unwrap().clone();
-        let other = keys::ufvk_from_seed_bytes(Network::MainNetwork, &[8; 32], 0).unwrap();
+        let other = test_keys::signing_keys(&[8; 32], 0).ufvk().unwrap();
         let other = UnifiedFullViewingKey::decode(&Network::MainNetwork, &other).unwrap();
         let receiver = other.orchard().unwrap().address_at(0u32, Scope::External);
         let to_address =
@@ -398,10 +397,7 @@ mod tests {
                 "fee" => request.fee_zat = "19999".into(),
                 "source" => request.spend_source = "ironwood".into(),
                 "max" => request.is_max_send = true,
-                "ufvk" => {
-                    request.ufvk =
-                        keys::ufvk_from_seed_bytes(Network::MainNetwork, &[9; 32], 0).unwrap()
-                }
+                "ufvk" => request.ufvk = test_keys::signing_keys(&[9; 32], 0).ufvk().unwrap(),
                 "network" => request.network = "test".into(),
                 _ => unreachable!(),
             }
@@ -429,13 +425,150 @@ mod tests {
         }
     }
 
+    fn request_json(request: &ReviewRequest) -> String {
+        serde_json::json!({"network":request.network,"ufvk":request.ufvk,"toAddress":request.to_address,"amountZat":request.amount_zat,"feeZat":request.fee_zat,"spendSource":request.spend_source,"isMaxSend":request.is_max_send,"memoHex":request.memo_hex}).to_string()
+    }
+
+    fn sign_with(seed: &[u8], account: u32, bytes: &[u8], json: &str) -> Result> {
+        account_keys::sign_reviewed_pczt(
+            "main",
+            &test_keys::orchard_sk(seed, account),
+            &test_keys::account_xprv(seed, account),
+            account,
+            bytes,
+            json,
+        )
+    }
+
+    fn signer_account_mismatch(result: Result>) -> bool {
+        matches!(result, Err(e) if e.params["field"] == "signerAccount")
+    }
+
     #[test]
     fn signer_must_own_the_reviewed_ufvk() {
         let (bytes, request) = fixture("orchard", false, false);
-        let json = serde_json::json!({"network":request.network,"ufvk":request.ufvk,"toAddress":request.to_address,"amountZat":request.amount_zat,"feeZat":request.fee_zat,"spendSource":request.spend_source,"isMaxSend":request.is_max_send}).to_string();
-        verify_signer(Network::MainNetwork, &[7; 32], 0, &bytes, &json).unwrap();
-        assert!(verify_signer(Network::MainNetwork, &[8; 32], 0, &bytes, &json).is_err());
-        assert!(verify_signer(Network::MainNetwork, &[7; 32], 1, &bytes, &json).is_err());
+        let json = request_json(&request);
+        let seed = [7u8; 32];
+        verify_signer(&test_keys::signing_keys(&seed, 0), &bytes, &json).unwrap();
+        assert!(verify_signer(&test_keys::signing_keys(&[8; 32], 0), &bytes, &json).is_err());
+        assert!(verify_signer(&test_keys::signing_keys(&seed, 1), &bytes, &json).is_err());
+
+        assert!(signer_account_mismatch(sign_with(
+            &[8; 32], 0, &bytes, &json
+        )));
+        // Wrong-account keys, each self-consistent with their own account index.
+        for account in [1, (1 << 31) - 1] {
+            assert!(signer_account_mismatch(sign_with(
+                &seed, account, &bytes, &json
+            )));
+        }
+        // Mixed accounts: the Orchard key of account 0 with the transparent key of account 1.
+        for (orchard_account, transparent_account) in [(0, 1), (1, 0)] {
+            let mixed = account_keys::AccountSigningKeys::parse(
+                "main",
+                &test_keys::orchard_sk(&seed, orchard_account),
+                &test_keys::account_xprv(&seed, transparent_account),
+                transparent_account,
+            )
+            .unwrap();
+            assert!(verify_signer(&mixed, &bytes, &json).is_err());
+        }
+        // Another wallet's Orchard key paired with this wallet's transparent key.
+        let foreign = account_keys::AccountSigningKeys::parse(
+            "main",
+            &test_keys::orchard_sk(&[8; 32], 0),
+            &test_keys::account_xprv(&seed, 0),
+            0,
+        )
+        .unwrap();
+        assert!(verify_signer(&foreign, &bytes, &json).is_err());
+    }
+
+    #[test]
+    fn signer_rejects_testnet_keys_and_reviews() {
+        let (bytes, request) = fixture("orchard", false, false);
+        let seed = [7u8; 32];
+        let e = account_keys::sign_reviewed_pczt(
+            "test",
+            &test_keys::orchard_sk(&seed, 0),
+            &test_keys::account_xprv(&seed, 0),
+            0,
+            &bytes,
+            &request_json(&request),
+        )
+        .unwrap_err();
+        assert_eq!(e.code, ErrorCode::InvalidNetwork);
+
+        let mut testnet = request;
+        testnet.network = "test".into();
+        assert!(signer_account_mismatch(sign_with(
+            &seed,
+            0,
+            &bytes,
+            &request_json(&testnet)
+        )));
+    }
+
+    /// Re-applies each spend authorization signature to the unsigned PCZT, where
+    /// upstream verifies it against the action's randomized key `rk`. Returns the
+    /// signed (pool, action) positions.
+    fn verified_signatures(unsigned: &[u8], signed: &pczt::Pczt) -> Vec<(bool, usize)> {
+        let signatures = extract_orchard_spend_auth_signatures(signed);
+        let mut signer = Signer::new(pczt::Pczt::parse(unsigned).unwrap()).unwrap();
+        for signature in &signatures {
+            signer
+                .apply_orchard_spend_auth_signature(signature)
+                .expect("signature verifies under rk");
+        }
+        signatures
+            .iter()
+            .map(|s| {
+                (
+                    s.value_pool() == orchard::ValuePool::Ironwood,
+                    s.action_index(),
+                )
+            })
+            .collect()
+    }
+
+    /// Account keys and the upstream seed-derived USK authorize the same spends.
+    #[test]
+    fn account_keys_and_seed_oracle_sign_the_same_reviewed_pczt() {
+        let seed = [7u8; 32];
+        for source in ["orchard", "ironwood"] {
+            for max in [false, true] {
+                let (bytes, request) = fixture(source, max, false);
+                let json = request_json(&request);
+
+                let signed =
+                    pczt::Pczt::parse(&sign_with(&seed, 0, &bytes, &json).unwrap()).unwrap();
+                let by_account_keys = verified_signatures(&bytes, &signed);
+                assert!(!by_account_keys.is_empty());
+                assert!(by_account_keys
+                    .iter()
+                    .all(|(ironwood, _)| *ironwood == (source == "ironwood")));
+
+                let oracle = test_keys::usk(&seed, 0);
+                let ask = orchard::keys::SpendAuthorizingKey::from(oracle.orchard());
+                let unsigned = pczt::Pczt::parse(&bytes).unwrap();
+                let (orchard_actions, ironwood_actions) = (
+                    unsigned.orchard().actions().len(),
+                    unsigned.ironwood().actions().len(),
+                );
+                let mut signer = Signer::new(unsigned).unwrap();
+                for index in 0..orchard_actions {
+                    let _ = signer.sign_orchard(index, &ask);
+                }
+                for index in 0..ironwood_actions {
+                    let _ = signer.sign_ironwood(index, &ask);
+                }
+                assert_eq!(
+                    verified_signatures(&bytes, &signer.finish()),
+                    by_account_keys,
+                    "{source} max={max}"
+                );
+            }
+        }
     }
 
     #[test]
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
index 368d02d6d..57345210d 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
@@ -1,16 +1,16 @@
-//! PCZT signing with keys derived from caller-provided seed bytes.
+//! PCZT signing with host-supplied account keys.
 //!
-//! This crate also handles spending keys in `keys` and `transparent_send`.
+//! This crate also handles spending keys in `account_keys` and `transparent_send`.
 //! See the crate documentation for the limits of derived-key zeroization.
 
 use pczt::roles::signer::Signer;
 use pczt::roles::verifier::{TransparentError, Verifier};
-use transparent::sighash::SighashType;
-use zcash_keys::keys::UnifiedSpendingKey;
-use zcash_protocol::consensus::Network;
-use zip32::AccountId;
+use transparent::{keys::AccountPrivKey, sighash::SighashType};
 
-use crate::error::{ErrorCode, KeysError, Result};
+use crate::{
+    account_keys::AccountSigningKeys,
+    error::{ErrorCode, KeysError, Result},
+};
 
 /// Whether a transparent input's signature commits to all outputs.
 ///
@@ -39,12 +39,11 @@ pub(crate) const TRANSPARENT_SCAN_GAP: u32 = 40;
 /// Sign all transparent inputs; returns (signed count, last failure).
 fn sign_transparent_inputs(
     signer: &mut Signer,
-    usk: &UnifiedSpendingKey,
+    account_key: &AccountPrivKey,
     input_count: usize,
 ) -> (usize, Option) {
     use transparent::keys::{NonHardenedChildIndex, TransparentKeyScope};
 
-    let account_key = usk.transparent();
     let mut signed = 0usize;
     let mut last_err = None;
 
@@ -77,33 +76,15 @@ fn sign_transparent_inputs(
     (signed, last_err)
 }
 
-/// Sign a PCZT with spending keys derived from the seed. The caller wipes its seed copy.
+/// Sign a PCZT with the account's Orchard spending key and transparent account key.
 ///
 /// Signs Orchard/Ironwood spends and transparent inputs only. Sapling spends are
-/// unsupported (the ~50 MB Groth16 parameters are not shipped).
-pub fn sign_pczt_with_seed(
-    params: Network,
-    seed: &[u8],
-    account_index: u32,
+/// unsupported (the ~50 MB Groth16 parameters are not shipped). Callers verify the
+/// PCZT against the reviewed payment first (`account_keys::sign_reviewed_pczt`).
+pub fn sign_pczt_with_account_keys(
+    keys: &AccountSigningKeys,
     pczt_bytes: &[u8],
 ) -> Result> {
-    if seed.len() < 32 {
-        return Err(KeysError::with(
-            ErrorCode::InvalidSeed,
-            serde_json::json!({ "byteLen": seed.len(), "min": 32 }),
-        ));
-    }
-
-    let account = AccountId::try_from(account_index).map_err(|_| {
-        KeysError::with(
-            ErrorCode::InvalidAccountIndex,
-            serde_json::json!({ "value": account_index }),
-        )
-    })?;
-
-    let usk = UnifiedSpendingKey::from_seed(¶ms, seed, account)
-        .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?;
-
     let pczt = pczt::Pczt::parse(pczt_bytes)
         .map_err(|e| KeysError::new(ErrorCode::PcztParseFailed).detail(format!("{e:?}")))?;
 
@@ -133,7 +114,7 @@ pub fn sign_pczt_with_seed(
         .map_err(|e| KeysError::new(ErrorCode::PcztSignFailed).detail(format!("{e:?}")))?;
 
     // Orchard spend authorizing key, derived from the spending key.
-    let ask = orchard::keys::SpendAuthorizingKey::from(usk.orchard());
+    let ask = orchard::keys::SpendAuthorizingKey::from(keys.orchard());
 
     // Shielded actions are signed best-effort: upstream rejects actions not owned
     // by this account, and it is an error only if nothing is signed. Both pools are
@@ -145,7 +126,7 @@ pub fn sign_pczt_with_seed(
 
     // Every transparent input must be signed; one missing signature invalidates the transaction.
     let (transparent_signed, transparent_err) =
-        sign_transparent_inputs(&mut signer, &usk, transparent_count);
+        sign_transparent_inputs(&mut signer, keys.transparent(), transparent_count);
     if transparent_signed < transparent_count {
         return Err(KeysError::with(
             ErrorCode::PcztSignFailed,
@@ -234,19 +215,12 @@ fn bundle_counts(pczt_bytes: &[u8]) -> Result<(usize, usize, usize)> {
 #[cfg(test)]
 mod tests {
     use super::*;
-
-    const SEED: [u8; 32] = [7u8; 32];
-
-    #[test]
-    fn rejects_short_seed() {
-        let e = sign_pczt_with_seed(Network::TestNetwork, &[0u8; 8], 0, &[]).unwrap_err();
-        assert_eq!(e.code, ErrorCode::InvalidSeed);
-        assert_eq!(e.params["byteLen"], 8);
-    }
+    use crate::account_keys::test_keys;
 
     #[test]
     fn rejects_garbage_pczt() {
-        let e = sign_pczt_with_seed(Network::TestNetwork, &SEED, 0, b"not a pczt").unwrap_err();
+        let keys = test_keys::signing_keys(&[7u8; 32], 0);
+        let e = sign_pczt_with_account_keys(&keys, b"not a pczt").unwrap_err();
         assert_eq!(e.code, ErrorCode::PcztParseFailed);
     }
 }
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
index dd667ae83..5fcf33e55 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
@@ -33,10 +33,12 @@ use zcash_protocol::{
     TxId,
 };
 use zcash_script::script::Evaluable;
-use zeroize::Zeroizing;
 use zip32::AccountId;
 
-use crate::error::{ErrorCode, KeysError, Result};
+use crate::{
+    account_keys::Wiped,
+    error::{ErrorCode, KeysError, Result},
+};
 
 const MAX_EXPIRY_DELTA: u32 = 100;
 const XPRV_VERSION: [u8; 4] = [0x04, 0x88, 0xad, 0xe4];
@@ -173,21 +175,6 @@ pub fn quote_json(request_json: &str) -> Result {
         .map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e))
 }
 
-pub fn build_with_seed_json(request_json: &str, seed: &[u8]) -> Result {
-    if seed.len() < 32 {
-        return Err(KeysError::with(
-            ErrorCode::InvalidSeed,
-            serde_json::json!({ "byteLen": seed.len(), "min": 32 }),
-        ));
-    }
-
-    let request = parse_request(request_json)?;
-    let plan = plan_transaction(request)?;
-    let account_key = AccountPrivKey::from_seed(&MAIN_NETWORK, seed, plan.account_index)
-        .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(e))?;
-    serialize_build_result(build_transaction(plan, &account_key)?)
-}
-
 /// Builds with an account-level BIP-44 xprv at `m/44'/133'/account'`.
 ///
 /// An account xprv cannot prove its ancestor path. The encoded key metadata is therefore checked
@@ -764,7 +751,7 @@ fn derive_public_key(
         .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(e))
 }
 
-fn parse_account_xpub(encoded: &str, expected_account: u32) -> Result {
+pub(crate) fn parse_account_xpub(encoded: &str, expected_account: u32) -> Result {
     let invalid = || KeysError::new(ErrorCode::InvalidAccountXpub);
     let decoded = bs58::decode(encoded)
         .with_check(None)
@@ -781,31 +768,35 @@ fn parse_account_xpub(encoded: &str, expected_account: u32) -> Result Result {
-    let decoded = Zeroizing::new(
-        bs58::decode(encoded)
-            .with_check(None)
-            .into_vec()
-            .map_err(|_| KeysError::new(ErrorCode::InvalidAccountXprv))?,
-    );
-    if decoded.len() != 78 || decoded[..4] != XPRV_VERSION || decoded[4] != ACCOUNT_XPRV_DEPTH {
-        return Err(KeysError::new(ErrorCode::InvalidAccountXprv));
+/// Parses straight from the base58 string: bip32 decodes into a stack buffer it wipes, and
+/// `ExtendedKey` wipes its key bytes on drop. Upstream `AccountPrivKey::from_bytes` is avoided
+/// because it re-encodes the key into a heap string and buffer that are freed unwiped.
+pub(crate) fn parse_account_xprv(
+    encoded: &str,
+    expected_account: u32,
+) -> Result> {
+    let invalid = || KeysError::new(ErrorCode::InvalidAccountXprv);
+    let key: bip32::ExtendedKey = encoded.parse().map_err(|_| invalid())?;
+    if key.prefix.version() != u32::from_be_bytes(XPRV_VERSION)
+        || key.attrs.depth != ACCOUNT_XPRV_DEPTH
+    {
+        return Err(invalid());
     }
-    let child = u32::from_be_bytes(decoded[9..13].try_into().expect("fixed slice length"));
     let expected_child = expected_account.checked_add(1 << 31).ok_or_else(|| {
         KeysError::with(
             ErrorCode::InvalidAccountIndex,
             serde_json::json!({ "value": expected_account }),
         )
     })?;
-    if child != expected_child {
+    if u32::from(key.attrs.child_number) != expected_child {
         return Err(KeysError::with(
             ErrorCode::InvalidAccountXprv,
             serde_json::json!({ "reason": "accountIndexMismatch" }),
         ));
     }
-    AccountPrivKey::from_bytes(&decoded[4..])
-        .ok_or_else(|| KeysError::new(ErrorCode::InvalidAccountXprv))
+    bip32::ExtendedPrivateKey::::try_from(key)
+        .map(|key| Wiped::new(AccountPrivKey::from_extended_privkey(key)))
+        .map_err(|_| invalid())
 }
 
 fn parse_derivation_path(path: &str, expected_account: u32) -> Result {
@@ -931,6 +922,10 @@ mod tests {
             .to_vec()
     }
 
+    fn xprv() -> String {
+        crate::account_keys::test_keys::account_xprv(&seed(), 0)
+    }
+
     fn account_key(seed: &[u8], account: u32) -> AccountPrivKey {
         AccountPrivKey::from_seed(&MAIN_NETWORK, seed, AccountId::try_from(account).unwrap())
             .unwrap()
@@ -1027,7 +1022,7 @@ mod tests {
                 quote.send_amount_zat,
                 if send_max { "85000" } else { "50000" }
             );
-            let created = shielding::create(&request, &seed()).unwrap();
+            let created = shielding::create_with_account_xprv(&request, &xprv()).unwrap();
             let pczt = pczt::Pczt::parse(&created).unwrap();
             assert_eq!(pczt.transparent().inputs().len(), 1);
             assert_eq!(pczt.transparent().outputs().len(), usize::from(!send_max));
@@ -1049,7 +1044,8 @@ mod tests {
         assert_eq!(quote.spent_outpoints.len(), 3);
 
         let built: TransparentBuildResult =
-            serde_json::from_str(&build_with_seed_json(&request, &seed()).unwrap()).unwrap();
+            serde_json::from_str(&build_with_account_xprv_json(&request, &xprv()).unwrap())
+                .unwrap();
         assert_eq!(built.fee_zat, "15000");
         assert_eq!(built.spent_outpoints, quote.spent_outpoints);
     }
@@ -1072,7 +1068,8 @@ mod tests {
         assert_eq!(quote.fee_zat, "12000", "surplus must all go to the fee");
 
         let built: TransparentBuildResult =
-            serde_json::from_str(&build_with_seed_json(&request, &seed()).unwrap()).unwrap();
+            serde_json::from_str(&build_with_account_xprv_json(&request, &xprv()).unwrap())
+                .unwrap();
         assert_eq!(built.fee_zat, "12000");
     }
 
@@ -1148,9 +1145,9 @@ mod tests {
         let error = quote_json(&request.to_string()).unwrap_err();
         assert_eq!(error.code, ErrorCode::UnsupportedInputScript);
 
-        let other_seed = vec![0x42; 64];
+        let other_xprv = crate::account_keys::test_keys::account_xprv(&[0x42; 64], 0);
         request = serde_json::from_str(&request_json(&[100_000], true)).unwrap();
-        let error = build_with_seed_json(&request.to_string(), &other_seed).unwrap_err();
+        let error = build_with_account_xprv_json(&request.to_string(), &other_xprv).unwrap_err();
         assert_eq!(error.code, ErrorCode::KeyMismatch);
     }
 
@@ -1191,14 +1188,16 @@ mod tests {
             .to_string()
             .into();
 
-        let account_key = account_key(&seed, 0);
         let mut encoded = XPRV_VERSION.to_vec();
-        encoded.extend(account_key.to_bytes());
+        encoded.extend(account_key(&seed, 0).to_bytes());
         let account_xprv = bs58::encode(encoded).with_check().into_string();
+        assert_eq!(account_xprv, xprv());
 
-        let from_seed = build_with_seed_json(&request.to_string(), &seed).unwrap();
-        let from_xprv = build_with_account_xprv_json(&request.to_string(), &account_xprv).unwrap();
-        assert_eq!(from_xprv, from_seed);
+        let built: TransparentBuildResult = serde_json::from_str(
+            &build_with_account_xprv_json(&request.to_string(), &account_xprv).unwrap(),
+        )
+        .unwrap();
+        assert_eq!(built.fee_zat, "10000");
 
         request["accountIndex"] = 1.into();
         let error = build_with_account_xprv_json(&request.to_string(), &account_xprv).unwrap_err();
@@ -1214,7 +1213,7 @@ mod tests {
             .to_zcash_address(NetworkType::Main)
             .to_string()
             .into();
-        let via_t1 = build_with_seed_json(&request.to_string(), &seed()).unwrap();
+        let via_t1 = build_with_account_xprv_json(&request.to_string(), &xprv()).unwrap();
         request["recipients"][0]["address"] =
             ::from_tex(
                 NetworkType::Main,
@@ -1222,13 +1221,13 @@ mod tests {
             )
             .encode()
             .into();
-        let via_tex = build_with_seed_json(&request.to_string(), &seed()).unwrap();
+        let via_tex = build_with_account_xprv_json(&request.to_string(), &xprv()).unwrap();
         assert_eq!(via_tex, via_t1);
     }
 
     #[test]
     fn builds_deterministic_v6_transaction() {
-        let raw = build_with_seed_json(&request_json(&[100_000], true), &seed()).unwrap();
+        let raw = build_with_account_xprv_json(&request_json(&[100_000], true), &xprv()).unwrap();
         let result: TransparentBuildResult = serde_json::from_str(&raw).unwrap();
         assert_eq!(result.fee_zat, "10000");
         assert_eq!(result.expiry_height, 3_500_020);
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
index bc2976d09..4a8609e52 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
@@ -18,25 +18,13 @@ use zcash_protocol::memo::MemoBytes;
 ///
 /// Hosts must check these capabilities before calling: older wasm builds lack
 /// the exports entirely, so a direct call fails with `undefined is not a function`.
-pub const SHIELD_CREATE_WITH_SEED: bool = true;
 pub const SHIELD_CREATE_WITH_ACCOUNT_XPRV: bool = true;
-pub const SHIELD_SIGN_WITH_SEED: bool = true;
 pub const SHIELD_SIGN_WITH_ACCOUNT_XPRV: bool = true;
 
 fn failure(error: impl std::fmt::Debug) -> KeysError {
     KeysError::new(ErrorCode::TransactionBuildFailed).detail(format!("{error:?}"))
 }
 
-pub fn create(request_json: &str, seed: &[u8]) -> Result> {
-    if seed.len() < 32 {
-        return Err(KeysError::new(ErrorCode::InvalidSeed));
-    }
-    let plan = plan_transaction(parse_request(request_json)?)?;
-    let key =
-        AccountPrivKey::from_seed(&MAIN_NETWORK, seed, plan.account_index).map_err(failure)?;
-    create_with_public_key(&plan, &key.to_account_pubkey())
-}
-
 pub fn create_with_account_xprv(request_json: &str, account_xprv: &str) -> Result> {
     let plan = plan_transaction(parse_request(request_json)?)?;
     let key = parse_account_xprv(account_xprv, u32::from(plan.account_index))?;
@@ -495,16 +483,6 @@ fn validate_original(
     Ok(verified.finish())
 }
 
-pub fn sign(request_json: &str, seed: &[u8], original: &[u8], pczt: &[u8]) -> Result> {
-    if seed.len() < 32 {
-        return Err(KeysError::new(ErrorCode::InvalidSeed));
-    }
-    let plan = plan_transaction(parse_request(request_json)?)?;
-    let key =
-        AccountPrivKey::from_seed(&MAIN_NETWORK, seed, plan.account_index).map_err(failure)?;
-    sign_with_key(&plan, &key, original, pczt)
-}
-
 pub fn sign_with_account_xprv(
     request_json: &str,
     account_xprv: &str,
@@ -578,8 +556,20 @@ mod tests {
 
     const SEED: [u8; 64] = [7; 64];
 
+    fn xprv() -> String {
+        crate::account_keys::test_keys::account_xprv(&SEED, 0)
+    }
+
+    fn create(request_json: &str) -> Result> {
+        create_with_account_xprv(request_json, &xprv())
+    }
+
+    fn sign(request_json: &str, original: &[u8], pczt: &[u8]) -> Result> {
+        sign_with_account_xprv(request_json, &xprv(), original, pczt)
+    }
+
     fn transparent_address(scope: u32, index: u32) -> TransparentAddress {
-        let key = AccountPrivKey::from_seed(&MAIN_NETWORK, &SEED, AccountId::ZERO).unwrap();
+        let key = crate::account_keys::test_keys::account_priv_key(&SEED, 0);
         let secret = derive_secret_key(
             &key,
             DerivationPath {
@@ -625,7 +615,7 @@ mod tests {
     }
 
     fn account_xpub() -> String {
-        let key = AccountPrivKey::from_seed(&MAIN_NETWORK, &SEED, AccountId::ZERO).unwrap();
+        let key = crate::account_keys::test_keys::account_priv_key(&SEED, 0);
         let mut payload = vec![0x04, 0x88, 0xb2, 0x1e, 3, 0, 0, 0, 0];
         payload.extend_from_slice(&(1_u32 << 31).to_be_bytes());
         payload.extend_from_slice(&key.to_account_pubkey().serialize());
@@ -637,7 +627,7 @@ mod tests {
     }
 
     fn simulated_device_signatures(original: &[u8], input_count: usize) -> Vec {
-        let key = AccountPrivKey::from_seed(&MAIN_NETWORK, &SEED, AccountId::ZERO).unwrap();
+        let key = crate::account_keys::test_keys::account_priv_key(&SEED, 0);
         let mut signer = Signer::new(pczt::Pczt::parse(original).unwrap()).unwrap();
         for index in 0..input_count {
             signer
@@ -692,7 +682,7 @@ mod tests {
                 create_with_account_xpub(&request, &account_xpub(), &fingerprint)
                     .expect("hardware path builds with the quoted fee");
             } else {
-                create(&request, &SEED).expect("software path builds with the quoted fee");
+                create(&request).expect("software path builds with the quoted fee");
             }
         }
     }
@@ -831,9 +821,8 @@ mod tests {
                     .unwrap();
                 let mut changed_request = request.clone();
                 changed_request["expiryHeight"] = 3_500_021.into();
-                let changed = simulated_device_signature(
-                    &create(&changed_request.to_string(), &SEED).unwrap(),
-                );
+                let changed =
+                    simulated_device_signature(&create(&changed_request.to_string()).unwrap());
                 assert!(combine_hardware_signed(
                     &request_json,
                     &account_xpub(),
@@ -910,16 +899,16 @@ mod tests {
                 let mut approved = request(max);
                 approved["recipients"][0]["memoHex"] =
                     Value::String(format!("{prefix}{}", "00".repeat(512 - prefix.len() / 2)));
-                let original = create(&approved.to_string(), &SEED).unwrap();
-                sign(&approved.to_string(), &SEED, &original, &original).unwrap();
+                let original = create(&approved.to_string()).unwrap();
+                sign(&approved.to_string(), &original, &original).unwrap();
                 approved["recipients"][0]["memoHex"] =
                     Value::String(format!("ff99{}", "00".repeat(510)));
-                assert!(sign(&approved.to_string(), &SEED, &original, &original).is_err());
+                assert!(sign(&approved.to_string(), &original, &original).is_err());
                 approved["recipients"][0]
                     .as_object_mut()
                     .unwrap()
                     .remove("memoHex");
-                assert!(sign(&approved.to_string(), &SEED, &original, &original).is_err());
+                assert!(sign(&approved.to_string(), &original, &original).is_err());
             }
         }
     }
@@ -928,16 +917,16 @@ mod tests {
     fn signs_fixed_and_max_shielding_with_matching_request() {
         for send_max in [false, true] {
             let request = request(send_max).to_string();
-            let original = create(&request, &SEED).unwrap();
+            let original = create(&request).unwrap();
             // Proof generation is independent of the transparent signing authorization.
-            sign(&request, &SEED, &original, &original).unwrap();
+            sign(&request, &original, &original).unwrap();
         }
     }
 
     #[test]
     fn rejects_substitution_of_a_different_approved_request() {
         let request = request(false);
-        let original = create(&request.to_string(), &SEED).unwrap();
+        let original = create(&request.to_string()).unwrap();
         for field in ["recipient", "amount", "input", "value", "change", "expiry"] {
             let mut changed = request.clone();
             match field {
@@ -959,31 +948,30 @@ mod tests {
                 _ => unreachable!(),
             }
             assert!(
-                sign(&changed.to_string(), &SEED, &original, &original).is_err(),
+                sign(&changed.to_string(), &original, &original).is_err(),
                 "{field}"
             );
         }
     }
 
-    /// `pcztSignWithSeed` signs host-supplied PCZTs, and upstream `Signer` leaves
-    /// semantic checks to the caller, so it must enforce `SIGHASH_ALL` itself.
+    /// `pcztSignWithAccountKeys` signs host-supplied PCZTs, and upstream `Signer`
+    /// leaves semantic checks to the caller, so it must enforce `SIGHASH_ALL` itself.
     ///
     /// The positive case also pins that a pool with nothing signable is fine: the
     /// shielding PCZT's Ironwood actions are outputs only.
     #[test]
     fn generic_signer_requires_sighash_all_on_transparent_inputs() {
-        use zcash_protocol::consensus::Network;
-
+        let keys = crate::account_keys::test_keys::signing_keys(&SEED, 0);
         let request = request(false).to_string();
-        let original = create(&request, &SEED).unwrap();
+        let original = create(&request).unwrap();
 
-        crate::sign::sign_pczt_with_seed(Network::MainNetwork, &SEED, 0, &original)
+        crate::sign::sign_pczt_with_account_keys(&keys, &original)
             .expect("unmodified shielding PCZT must sign");
 
         let modified = mutate(&original, |value| {
             value["transparent"]["inputs"][0]["sighash_type"] = 2.into();
         });
-        let e = crate::sign::sign_pczt_with_seed(Network::MainNetwork, &SEED, 0, &modified)
+        let e = crate::sign::sign_pczt_with_account_keys(&keys, &modified)
             .expect_err("non-ALL sighash_type must be rejected");
         assert_eq!(e.code, ErrorCode::PcztSignFailed);
         assert!(
@@ -992,10 +980,82 @@ mod tests {
         );
     }
 
+    fn partial_signatures(pczt: &[u8]) -> Vec, Vec)>> {
+        let mut all = Vec::new();
+        Verifier::new(pczt::Pczt::parse(pczt).unwrap())
+            .with_transparent::(|bundle| {
+                for input in bundle.inputs() {
+                    all.push(
+                        input
+                            .partial_signatures()
+                            .iter()
+                            .map(|(k, v)| (k.to_vec(), v.clone()))
+                            .collect(),
+                    );
+                }
+                Ok(())
+            })
+            .unwrap();
+        all
+    }
+
+    /// The xprv path and the seed-derived USK produce identical transparent
+    /// signatures (RFC 6979), each valid for its input's sighash.
+    #[test]
+    fn account_keys_and_seed_oracle_sign_the_same_transparent_inputs() {
+        use crate::account_keys::test_keys;
+
+        let mut request = request(false);
+        let mut second = request["utxos"][0].clone();
+        second["vout"] = 1.into();
+        request["utxos"].as_array_mut().unwrap().push(second);
+        request["selectedOutpoints"]
+            .as_array_mut()
+            .unwrap()
+            .push(json!({ "txid": format!("{:064x}", 1), "vout": 1 }));
+        let original = create(&request.to_string()).unwrap();
+
+        let signed =
+            crate::sign::sign_pczt_with_account_keys(&test_keys::signing_keys(&SEED, 0), &original)
+                .unwrap();
+
+        let oracle = test_keys::usk(&SEED, 0);
+        let secret = oracle
+            .transparent()
+            .derive_secret_key(
+                TransparentKeyScope::EXTERNAL,
+                NonHardenedChildIndex::from_index(0).unwrap(),
+            )
+            .unwrap();
+        let mut signer = Signer::new(pczt::Pczt::parse(&original).unwrap()).unwrap();
+        for index in 0..2 {
+            signer.sign_transparent(index, &secret).unwrap();
+        }
+        let by_oracle = signer.finish().serialize().unwrap();
+
+        let signatures = partial_signatures(&signed);
+        assert_eq!(signatures.len(), 2);
+        assert!(signatures.iter().all(|input| input.len() == 1));
+        assert_eq!(signatures, partial_signatures(&by_oracle));
+
+        let secp = secp256k1::Secp256k1::verification_only();
+        let checker = Signer::new(pczt::Pczt::parse(&original).unwrap()).unwrap();
+        for (index, input) in signatures.iter().enumerate() {
+            let (public, signature) = &input[0];
+            assert_eq!(signature.last(), Some(&1), "SIGHASH_ALL");
+            secp.verify_ecdsa(
+                &secp256k1::Message::from_digest(checker.transparent_sighash(index).unwrap()),
+                &secp256k1::ecdsa::Signature::from_der(&signature[..signature.len() - 1]).unwrap(),
+                &secp256k1::PublicKey::from_slice(public).unwrap(),
+            )
+            .unwrap();
+        }
+    }
+
     #[test]
     fn rejects_modified_transparent_effects_and_sighash_policy() {
         let request = request(false).to_string();
-        let original = create(&request, &SEED).unwrap();
+        let original = create(&request).unwrap();
         for field in ["prevout_index", "value", "sighash_type", "sequence"] {
             let modified = mutate(&original, |value| {
                 value["transparent"]["inputs"][0][field] = match field {
@@ -1005,26 +1065,23 @@ mod tests {
                     _ => 1.into(),
                 };
             });
+            assert!(sign(&request, &modified, &modified).is_err(), "{field}");
             assert!(
-                sign(&request, &SEED, &modified, &modified).is_err(),
-                "{field}"
-            );
-            assert!(
-                sign(&request, &SEED, &original, &modified).is_err(),
+                sign(&request, &original, &modified).is_err(),
                 "prover {field}"
             );
         }
         let modified = mutate(&original, |value| {
             value["transparent"]["outputs"][0]["value"] = 1.into()
         });
-        assert!(sign(&request, &SEED, &modified, &modified).is_err());
-        assert!(sign(&request, &SEED, &original, &modified).is_err());
+        assert!(sign(&request, &modified, &modified).is_err());
+        assert!(sign(&request, &original, &modified).is_err());
     }
 
     #[test]
     fn rejects_unreviewed_ironwood_actions_and_ciphertexts() {
         let request = request(false).to_string();
-        let original = create(&request, &SEED).unwrap();
+        let original = create(&request).unwrap();
         for field in [
             "anchor",
             "value_sum",
@@ -1062,13 +1119,10 @@ mod tests {
                     }
                 }
             });
-            assert!(
-                sign(&request, &SEED, &modified, &modified).is_err(),
-                "{field}"
-            );
+            assert!(sign(&request, &modified, &modified).is_err(), "{field}");
             if field != "real_spend" && field != "output_value" {
                 assert!(
-                    sign(&request, &SEED, &original, &modified).is_err(),
+                    sign(&request, &original, &modified).is_err(),
                     "prover {field}"
                 );
             }
@@ -1078,10 +1132,7 @@ mod tests {
     #[test]
     fn account_xprv_has_the_same_authorization_checks() {
         let request = request(false).to_string();
-        let key = AccountPrivKey::from_seed(&MAIN_NETWORK, &SEED, AccountId::ZERO).unwrap();
-        let mut encoded = XPRV_VERSION.to_vec();
-        encoded.extend_from_slice(&key.to_bytes());
-        let xprv = bs58::encode(encoded).with_check().into_string();
+        let xprv = xprv();
         let original = create_with_account_xprv(&request, &xprv).unwrap();
         sign_with_account_xprv(&request, &xprv, &original, &original).unwrap();
         let mut changed: Value = serde_json::from_str(&request).unwrap();
@@ -1099,8 +1150,8 @@ mod tests {
             { "address": transparent_address(0, 2).to_zcash_address(NetworkType::Main).to_string(), "amountZat": "10000" },
         ]);
         let request = request.to_string();
-        let original = create(&request, &SEED).unwrap();
-        sign(&request, &SEED, &original, &original).unwrap();
+        let original = create(&request).unwrap();
+        sign(&request, &original, &original).unwrap();
         let modified = mutate(&original, |value| {
             let output = value["transparent"]["outputs"][0].clone();
             value["transparent"]["outputs"]
@@ -1108,6 +1159,6 @@ mod tests {
                 .unwrap()
                 .push(output);
         });
-        assert!(sign(&request, &SEED, &modified, &modified).is_err());
+        assert!(sign(&request, &modified, &modified).is_err());
     }
 }
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
index 6a5861929..1dbebfb4d 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
+++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
@@ -23,6 +23,8 @@ zip32 = "0.2"
 pczt.workspace = true
 # circuit: Orchard and Ironwood proving. This is the main WASM size cost.
 orchard = { workspace = true, features = ["circuit"] }
+# Trial-decrypts PCZT outputs to tell real change from randomized fabricated outputs.
+zcash_note_encryption = "0.4"
 
 rusqlite.workspace = true
 serde.workspace = true
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
index b78eb5718..0d79ec347 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
@@ -30,8 +30,9 @@ pub async fn import_ufvk(
         .map_err(|e| RuntimeError::new(ErrorCode::InvalidUfvk).detail(e))?;
 
     // With a seed fingerprint and account index the account is imported as
-    // spending, so PCZT change outputs carry zip32_derivation and signers can
-    // verify change returns to the wallet.
+    // spending: upstream then puts zip32_derivation on PCZT spends, and
+    // send::mark_wallet_outputs puts it on change outputs (upstream does not),
+    // so signers can find the key and verify change returns to the wallet.
     let purpose = match derivation {
         Some((fingerprint_hex, account_index)) => AccountPurpose::Spending {
             derivation: Some(parse_zip32_derivation(fingerprint_hex, account_index)?),
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
index a8b06be36..fe3db088a 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
@@ -5,7 +5,7 @@
 //! ```text
 //!   runtime.pcztCreate()          build (needs wallet state: note selection, witness, anchor)
 //!   runtime.pcztProve()           prove; pure computation, no private keys
-//!   keys.pcztSign()               sign (needs the spending key; in onekey-zcash-keys)
+//!   keys.pcztSignWithAccountKeys() sign (needs the spending keys; in onekey-zcash-keys)
 //!   runtime.pcztSubmit()          extract, store, broadcast (retries resend the stored bytes)
 //! ```
 //!
@@ -13,7 +13,7 @@
 //! to verify the proofs cover the right data, so proofs must already be in the PCZT.
 //!
 //! Key separation: build and broadcast need the wallet database, signing needs
-//! the seed; the two never live in the same crate.
+//! the spending keys; the two never live in the same crate.
 //!
 //! ## Why this stays in Rust
 //!
@@ -645,6 +645,7 @@ pub fn create_pczt(
             policy.padding(),
         )
         .map_err(|e| build_err("createPczt", format!("{e:?}")))?;
+        let pczt = mark_wallet_outputs(db, account_id, pczt)?;
 
         pczt.serialize().map_err(|e| {
             RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "serialize" }))
@@ -671,6 +672,109 @@ pub fn create_pczt(
     Ok((bytes, reservation_id, fee_zat))
 }
 
+/// Adds the account's ZIP 32 path to every Orchard/Ironwood output that pays
+/// this account (change), so a hardware signer can verify it as its own instead
+/// of rejecting it for having no `user_address`. Upstream sets only the spend
+/// paths. View-only accounts (no derivation) are left unchanged.
+fn mark_wallet_outputs(
+    db: &Db,
+    account_id: ::AccountId,
+    pczt: pczt::Pczt,
+) -> Result {
+    use zcash_client_backend::data_api::Account as _;
+    use zcash_protocol::consensus::{NetworkConstants as _, Parameters as _};
+
+    let account = db
+        .get_account(account_id)
+        .map_err(|e| {
+            RuntimeError::with(
+                ErrorCode::DatabaseError,
+                json!({ "operation": "getAccount" }),
+            )
+            .detail(e)
+        })?
+        .ok_or_else(|| RuntimeError::new(ErrorCode::AccountNotFound))?;
+    let (Some(derivation), Some(fvk)) = (
+        account.source().key_derivation(),
+        account.ufvk().and_then(|ufvk| ufvk.orchard()),
+    ) else {
+        return Ok(pczt);
+    };
+    mark_owned_outputs(
+        pczt,
+        fvk,
+        derivation,
+        db.params().network_type().coin_type(),
+    )
+    .map_err(|e| build_err("markWalletOutputs", format!("{e:?}")))
+}
+
+/// Sets `zip32_derivation` on each output whose recipient `fvk` owns (either
+/// scope) and whose note decrypts under that scope's IVK. Outputs that already
+/// name a `user_address` (real recipients) are left alone, as are outputs we do
+/// not own (padding). Undecryptable owned outputs are the zero-valued outputs
+/// the post-NU6.3 Orchard builder pairs with external-scope spends, with a
+/// randomized ciphertext: the firmware rejects those if they carry a path.
+fn mark_owned_outputs(
+    pczt: pczt::Pczt,
+    fvk: &orchard::keys::FullViewingKey,
+    derivation: &zcash_client_backend::data_api::Zip32Derivation,
+    coin_type: u32,
+) -> std::result::Result {
+    use orchard::keys::PreparedIncomingViewingKey;
+    use orchard::note_encryption::{IronwoodDomain, OrchardDomain};
+    use orchard::pczt::{Action, Bundle, Updater, UpdaterError, Zip32Derivation};
+    use zcash_note_encryption::try_note_decryption;
+
+    type Decrypts = fn(&Action, &PreparedIncomingViewingKey) -> bool;
+
+    let seed_fingerprint = derivation.seed_fingerprint().to_bytes();
+    let path = [
+        zip32::ChildIndex::hardened(32).index(),
+        zip32::ChildIndex::hardened(coin_type).index(),
+        zip32::ChildIndex::hardened(u32::from(derivation.account_index())).index(),
+    ];
+    let owned_actions = |bundle: &Bundle, decrypts: Decrypts| -> Vec {
+        let owned = |action: &Action| {
+            let output = action.output();
+            if output.user_address().is_some() {
+                return false;
+            }
+            let Some(scope) = output
+                .recipient()
+                .as_ref()
+                .and_then(|recipient| fvk.scope_for_address(recipient))
+            else {
+                return false;
+            };
+            decrypts(action, &PreparedIncomingViewingKey::new(&fvk.to_ivk(scope)))
+        };
+        let actions = bundle.actions().iter().enumerate();
+        actions.filter(|(_, a)| owned(a)).map(|(i, _)| i).collect()
+    };
+    let mark = |mut updater: Updater<'_>, decrypts: Decrypts| {
+        for index in owned_actions(updater.bundle(), decrypts) {
+            updater.update_action_with(index, |mut action| {
+                let derivation = Zip32Derivation::parse(seed_fingerprint, path.to_vec())
+                    .expect("hardened ZIP 32 indices");
+                action.set_output_zip32_derivation(derivation);
+                Ok::<_, UpdaterError>(())
+            })?;
+        }
+        Ok(())
+    };
+    let orchard_decrypts: Decrypts = |action, ivk| {
+        try_note_decryption(&OrchardDomain::for_pczt_action(action), ivk, action).is_some()
+    };
+    let ironwood_decrypts: Decrypts = |action, ivk| {
+        try_note_decryption(&IronwoodDomain::for_pczt_action(action), ivk, action).is_some()
+    };
+    Ok(pczt::roles::updater::Updater::new(pczt)
+        .update_orchard_with(|updater| mark(updater, orchard_decrypts))?
+        .update_ironwood_with(|updater| mark(updater, ironwood_decrypts))?
+        .finish())
+}
+
 /// The proving circuit version is set by the consensus branch, not a product option.
 ///
 /// `height` is the start of the transaction's branch: PostNu6_3 at or after NU6.3
@@ -1592,3 +1696,415 @@ mod memo_tests {
         assert!(parse_memo(None, None).unwrap().is_none());
     }
 }
+
+#[cfg(all(test, not(target_arch = "wasm32")))]
+mod owned_output_tests {
+    use super::*;
+    use orchard::keys::{FullViewingKey, Scope, SpendAuthorizingKey, SpendingKey};
+    use orchard::note::{NoteVersion, RandomSeed, Rho};
+    use orchard::note_encryption::{IronwoodDomain, OrchardDomain};
+    use orchard::pczt::{Action, Bundle};
+    use orchard::tree::{MerkleHashOrchard, MerklePath};
+    use orchard::value::NoteValue;
+    use orchard::{Address, Anchor, Note};
+    use pczt::roles::{creator::Creator, io_finalizer::IoFinalizer, signer::Signer};
+    use zcash_client_backend::data_api::Zip32Derivation;
+    use zcash_note_encryption::{try_output_recovery_with_pkd_esk, Domain};
+    use zcash_primitives::transaction::builder::{BuildConfig, Builder};
+    use zcash_protocol::consensus::{BlockHeight, Network};
+
+    const SEED: [u8; 32] = [7; 32];
+    const ACCOUNT: u32 = 5;
+    const SEND: u64 = 60_000;
+    const INPUT: u64 = 200_000;
+
+    fn spending_key(seed: &[u8], account: u32) -> SpendingKey {
+        SpendingKey::from_zip32_seed(seed, 133, zip32::AccountId::try_from(account).unwrap())
+            .unwrap()
+    }
+
+    fn ours() -> FullViewingKey {
+        FullViewingKey::from(&spending_key(&SEED, ACCOUNT))
+    }
+
+    fn fingerprint() -> [u8; 32] {
+        zip32::fingerprint::SeedFingerprint::from_seed(&SEED)
+            .unwrap()
+            .to_bytes()
+    }
+
+    fn derivation() -> Zip32Derivation {
+        Zip32Derivation::new(
+            zip32::fingerprint::SeedFingerprint::from_bytes(fingerprint()),
+            zip32::AccountId::try_from(ACCOUNT).unwrap(),
+        )
+    }
+
+    fn expected_path() -> Vec {
+        [32, 133, ACCOUNT].map(|i| i | (1 << 31)).to_vec()
+    }
+
+    fn note(recipient: Address, value: u64, version: NoteVersion) -> Note {
+        (1u8..)
+            .find_map(|b| {
+                let rho = Rho::from_bytes(&[b; 32]).into_option()?;
+                let rseed = RandomSeed::from_bytes([b.wrapping_add(1); 32], &rho).into_option()?;
+                Note::from_parts(recipient, NoteValue::from_raw(value), rho, rseed, version)
+                    .into_option()
+            })
+            .unwrap()
+    }
+
+    fn witness(note: &Note) -> (MerklePath, Anchor) {
+        let leaf = MerkleHashOrchard::from_bytes(&[0; 32]).unwrap();
+        let path = MerklePath::from_parts(0, [leaf; 32]);
+        let anchor = path.root(note.commitment().into());
+        (path, anchor)
+    }
+
+    struct Built {
+        pczt: pczt::Pczt,
+        orchard_change: Option,
+        ironwood_recipient: usize,
+        ironwood_change: Option,
+    }
+
+    /// A post-NU6.3 shielded spend of one Orchard note: the payment goes to a
+    /// foreign Ironwood address, change goes to our internal address, in
+    /// Ironwood or (when `orchard_change`) in Orchard. The external recipient
+    /// gets `user_address` as `create_pczt_from_proposal` sets it.
+    fn spend(spent_scope: Scope, orchard_change: bool) -> Built {
+        let fvk = ours();
+        let foreign = FullViewingKey::from(&spending_key(&[9; 32], 0));
+        let recipient = foreign.address_at(0u32, Scope::External);
+        let change_address = fvk.address_at(0u32, Scope::Internal);
+        let spent = note(fvk.address_at(0u32, spent_scope), INPUT, NoteVersion::V2);
+        let (path, anchor) = witness(&spent);
+
+        let builder = |change: u64| {
+            let mut b = Builder::new(
+                Network::MainNetwork,
+                BlockHeight::from_u32(3_500_000),
+                BuildConfig::Standard {
+                    sapling_anchor: None,
+                    orchard_anchor: Some(anchor),
+                    ironwood_anchor: Some(Anchor::empty_tree()),
+                    orchard_padding: BundlePadding::DEFAULT,
+                    ironwood_padding: BundlePadding::DEFAULT,
+                },
+            );
+            b.add_orchard_spend::(fvk.clone(), spent, path.clone())
+                .unwrap();
+            b.add_ironwood_output::(
+                None,
+                recipient,
+                Zatoshis::const_from_u64(SEND),
+                MemoBytes::empty(),
+            )
+            .unwrap();
+            let change = Zatoshis::const_from_u64(change);
+            if orchard_change {
+                b.add_orchard_change_output::(
+                    fvk.clone(),
+                    Some(fvk.to_ovk(Scope::Internal)),
+                    change_address,
+                    change,
+                    MemoBytes::empty(),
+                )
+                .unwrap();
+            } else {
+                b.add_ironwood_output::(
+                    Some(fvk.to_ovk(Scope::Internal)),
+                    change_address,
+                    change,
+                    MemoBytes::empty(),
+                )
+                .unwrap();
+            }
+            b
+        };
+        let fee_rule = Zip317FeeRule::standard();
+        let fee = u64::from(builder(1).get_fee(&fee_rule).unwrap());
+        let result = builder(INPUT - SEND - fee)
+            .build_for_pczt(rand::rngs::OsRng, &fee_rule)
+            .unwrap();
+        let ironwood_recipient = result.ironwood_meta.output_action_index(0).unwrap();
+        let (orchard_change, ironwood_change) = if orchard_change {
+            (result.orchard_meta.output_action_index(0), None)
+        } else {
+            (None, result.ironwood_meta.output_action_index(1))
+        };
+        let pczt = IoFinalizer::new(Creator::build_from_parts(result.pczt_parts).unwrap())
+            .finalize_io()
+            .unwrap();
+        let pczt = pczt::roles::updater::Updater::new(pczt)
+            .update_ironwood_with(|mut updater| {
+                updater.update_action_with(ironwood_recipient, |mut action| {
+                    action.set_output_user_address("recipient-ua".into());
+                    Ok(())
+                })
+            })
+            .unwrap()
+            .finish();
+        Built {
+            pczt,
+            orchard_change,
+            ironwood_recipient,
+            ironwood_change,
+        }
+    }
+
+    /// Runs `f` on the parsed Orchard (or Ironwood) bundle of `pczt`.
+    fn inspect(pczt: &pczt::Pczt, ironwood: bool, f: impl FnOnce(&Bundle) -> T) -> T {
+        let mut out = None;
+        let verifier = pczt::roles::verifier::Verifier::new(pczt.clone());
+        let run = |bundle: &Bundle| {
+            out = Some(f(bundle));
+            Ok::<_, pczt::roles::verifier::OrchardError<()>>(())
+        };
+        if ironwood {
+            verifier.with_ironwood(run).unwrap();
+        } else {
+            verifier.with_orchard(run).unwrap();
+        }
+        out.unwrap()
+    }
+
+    fn mark(pczt: pczt::Pczt) -> pczt::Pczt {
+        mark_owned_outputs(pczt, &ours(), &derivation(), 133).unwrap()
+    }
+
+    /// Mirrors the firmware's per-output acceptance (firmware-pro2
+    /// app/zcash/sign_pczt.py `_validate_orchard_protocol_outputs` and
+    /// signer_parse.rs): an output is accepted if it is an unrecoverable
+    /// fabricated zero output with nothing attached, carries a path whose
+    /// fingerprint/schema match and whose recipient the account FVK owns, carries
+    /// a `user_address`, or is a zero-valued output with no ock and no memo.
+    fn firmware_rejection(bundle: &Bundle, ironwood: bool) -> Option {
+        let fvk = ours();
+        for (index, action) in bundle.actions().iter().enumerate() {
+            let output = action.output();
+            let value = output.value().unwrap().inner();
+            let memo = recover_memo(action, ironwood);
+            let Some(memo) = memo else {
+                if bundle.flags().cross_address_enabled()
+                    || value != 0
+                    || output.ock().is_some()
+                    || output.zip32_derivation().is_some()
+                    || output.user_address().is_some()
+                {
+                    return Some(format!("{index}: invalid fabricated output"));
+                }
+                continue;
+            };
+            if let Some(derivation) = output.zip32_derivation() {
+                let path: Vec = derivation
+                    .derivation_path()
+                    .iter()
+                    .map(|i| i.index())
+                    .collect();
+                if derivation.seed_fingerprint() != &fingerprint() || path != expected_path() {
+                    return Some(format!("{index}: path/fingerprint mismatch"));
+                }
+                if fvk
+                    .scope_for_address(&output.recipient().unwrap())
+                    .is_none()
+                {
+                    return Some(format!("{index}: recipient not owned"));
+                }
+                continue;
+            }
+            if output.user_address().is_some() {
+                continue;
+            }
+            let empty_memo = memo.iter().all(|b| *b == 0)
+                || (memo[0] == 0xF6 && memo[1..].iter().all(|b| *b == 0));
+            if !(value == 0 && output.ock().is_none() && empty_memo) {
+                return Some(format!("{index}: Missing Orchard output address"));
+            }
+        }
+        None
+    }
+
+    /// Sender-side recovery as the firmware does it (no ock in our PCZTs, so
+    /// via pk_d and esk derived from the note).
+    fn recover_memo(action: &Action, ironwood: bool) -> Option<[u8; 512]> {
+        let output = action.output();
+        let rho = Rho::from_bytes(&action.spend().nullifier().to_bytes()).unwrap();
+        let note = Note::from_parts(
+            output.recipient().unwrap(),
+            output.value().unwrap(),
+            rho,
+            output.rseed().unwrap(),
+            *output.note_version(),
+        )
+        .unwrap();
+        if ironwood {
+            let domain = IronwoodDomain::for_pczt_action(action);
+            let esk = IronwoodDomain::derive_esk(¬e)?;
+            try_output_recovery_with_pkd_esk(&domain, IronwoodDomain::get_pk_d(¬e), esk, action)
+                .map(|(_, _, memo)| memo)
+        } else {
+            let domain = OrchardDomain::for_pczt_action(action);
+            let esk = OrchardDomain::derive_esk(¬e)?;
+            try_output_recovery_with_pkd_esk(&domain, OrchardDomain::get_pk_d(¬e), esk, action)
+                .map(|(_, _, memo)| memo)
+        }
+    }
+
+    fn has_our_path(action: &Action) -> bool {
+        action
+            .output()
+            .zip32_derivation()
+            .as_ref()
+            .is_some_and(|d| {
+                d.seed_fingerprint() == &fingerprint()
+                    && d.derivation_path()
+                        .iter()
+                        .map(|i| i.index())
+                        .collect::>()
+                        == expected_path()
+            })
+    }
+
+    fn assert_only_marked(bundle: &Bundle, marked: &[usize]) {
+        for (index, action) in bundle.actions().iter().enumerate() {
+            assert_eq!(
+                action.output().zip32_derivation().is_some(),
+                marked.contains(&index),
+                "action {index}"
+            );
+            if marked.contains(&index) {
+                assert!(has_our_path(action), "action {index}");
+                assert!(action.output().user_address().is_none(), "action {index}");
+            }
+        }
+    }
+
+    fn owned_by_us(action: &Action) -> Option {
+        ours().scope_for_address(&action.output().recipient().unwrap())
+    }
+
+    /// Has a zero-valued output to an address that is not ours.
+    fn is_padded(bundle: &Bundle) -> bool {
+        bundle.actions().iter().any(|a| {
+            owned_by_us(a).is_none()
+                && a.output().value().unwrap().inner() == 0
+                && a.output().user_address().is_none()
+        })
+    }
+
+    #[test]
+    fn unmarked_change_is_what_the_firmware_rejected() {
+        let built = spend(Scope::External, false);
+        assert_eq!(
+            inspect(&built.pczt, true, |b| firmware_rejection(b, true)),
+            Some(format!(
+                "{}: Missing Orchard output address",
+                built.ironwood_change.unwrap()
+            ))
+        );
+    }
+
+    #[test]
+    fn ironwood_change_gets_the_account_path_and_the_recipient_keeps_its_address() {
+        let built = spend(Scope::External, false);
+        let change = built.ironwood_change.unwrap();
+        let pczt = mark(built.pczt);
+
+        inspect(&pczt, true, |bundle| {
+            assert_only_marked(bundle, &[change]);
+            let recipient = bundle.actions()[built.ironwood_recipient].output();
+            assert_eq!(recipient.user_address().as_deref(), Some("recipient-ua"));
+            assert_eq!(firmware_rejection(bundle, true), None);
+        });
+        // The Orchard bundle holds the real spend's fabricated zero output (to
+        // our external address, randomized ciphertext) and padding: untouched.
+        inspect(&pczt, false, |bundle| {
+            assert_only_marked(bundle, &[]);
+            assert!(bundle
+                .actions()
+                .iter()
+                .any(|a| owned_by_us(a) == Some(Scope::External)));
+            assert!(is_padded(bundle));
+            assert_eq!(firmware_rejection(bundle, false), None);
+        });
+    }
+
+    #[test]
+    fn orchard_change_gets_the_account_path() {
+        let built = spend(Scope::Internal, true);
+        let change = built.orchard_change.unwrap();
+        let pczt = mark(built.pczt);
+
+        inspect(&pczt, false, |bundle| {
+            assert!(has_our_path(&bundle.actions()[change]));
+            // Internal-scope spends get a decryptable fabricated zero output to
+            // our own address; it is ours and carries the path too.
+            let owned: Vec = (0..bundle.actions().len())
+                .filter(|&i| owned_by_us(&bundle.actions()[i]).is_some())
+                .collect();
+            assert_eq!(owned.len(), 2);
+            assert_only_marked(bundle, &owned);
+            assert_eq!(firmware_rejection(bundle, false), None);
+        });
+        inspect(&pczt, true, |bundle| {
+            assert!(is_padded(bundle));
+            assert_only_marked(bundle, &[]);
+            assert_eq!(firmware_rejection(bundle, true), None);
+        });
+    }
+
+    #[test]
+    fn marked_pczt_round_trips_and_still_signs_in_software() {
+        for (scope, orchard_change) in [(Scope::External, false), (Scope::Internal, true)] {
+            let bytes = mark(spend(scope, orchard_change).pczt).serialize().unwrap();
+            let parsed = pczt::Pczt::parse(&bytes).unwrap();
+            assert_eq!(parsed.clone().serialize().unwrap(), bytes);
+
+            // Same loop as zcash-keys-runtime sign_pczt_with_account_keys.
+            let ask = SpendAuthorizingKey::from(&spending_key(&SEED, ACCOUNT));
+            let actions = parsed.orchard().actions().len();
+            let mut signer = Signer::new(parsed).unwrap();
+            let signed = (0..actions)
+                .filter(|&i| signer.sign_orchard(i, &ask).is_ok())
+                .count();
+            assert!(signed >= 1);
+        }
+    }
+
+    #[test]
+    fn marking_the_randomized_fabricated_output_would_be_rejected() {
+        let pczt = spend(Scope::External, false).pczt;
+        let fabricated = inspect(&pczt, false, |bundle| {
+            (0..bundle.actions().len())
+                .find(|&i| owned_by_us(&bundle.actions()[i]) == Some(Scope::External))
+                .unwrap()
+        });
+        let pczt = pczt::roles::updater::Updater::new(pczt)
+            .update_orchard_with(|mut updater| {
+                updater.update_action_with(fabricated, |mut action| {
+                    let path = expected_path();
+                    let derivation =
+                        orchard::pczt::Zip32Derivation::parse(fingerprint(), path).unwrap();
+                    action.set_output_zip32_derivation(derivation);
+                    Ok(())
+                })
+            })
+            .unwrap()
+            .finish();
+        assert_eq!(
+            inspect(&pczt, false, |b| firmware_rejection(b, false)),
+            Some(format!("{fabricated}: invalid fabricated output"))
+        );
+    }
+
+    #[test]
+    fn foreign_keys_mark_nothing() {
+        let built = spend(Scope::External, false);
+        let foreign = FullViewingKey::from(&spending_key(&[3; 32], 0));
+        let pczt = mark_owned_outputs(built.pczt, &foreign, &derivation(), 133).unwrap();
+        inspect(&pczt, false, |b| assert_only_marked(b, &[]));
+        inspect(&pczt, true, |b| assert_only_marked(b, &[]));
+    }
+}

From aa67a39bb292e26f102988ed11ff1b1b6cc9a96a Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Fri, 16 Oct 2026 18:27:40 +0800
Subject: [PATCH 47/97] docs: trim chain runtime docs to usage, design reasons
 and pitfalls

---
 chain-runtimes/README.md                      |  26 +-
 chain-runtimes/monero/README.md               |  90 +++----
 chain-runtimes/zcash/README.md                | 230 ++++++------------
 .../zcash-keys-runtime/TRANSPARENT_TX_API.md  |  94 ++++---
 .../tests/fixtures/README.md                  |   9 +-
 5 files changed, 181 insertions(+), 268 deletions(-)

diff --git a/chain-runtimes/README.md b/chain-runtimes/README.md
index 8e5ae5303..e7bf9b7af 100644
--- a/chain-runtimes/README.md
+++ b/chain-runtimes/README.md
@@ -1,15 +1,13 @@
 # Chain runtimes
 
-Chain execution libraries live here alongside the React Native modules and views.
-Each chain owns its Cargo workspace, lockfile, toolchain, patches, and build outputs.
-These directories are not React Native packages and are not part of the root Yarn
-workspaces or their shared version/publish commands.
+Rust chain libraries compiled to wasm. Each chain owns its Cargo workspace,
+lockfile, toolchain, patches and build outputs. These are not React Native packages
+and are not part of the root Yarn workspaces or their version/publish commands.
 
-## Zcash
+- [Zcash](./zcash/README.md) ([release process](./zcash/RELEASING.md))
+- [Monero](./monero/README.md)
 
-See [zcash](./zcash/README.md) and its [release process](./zcash/RELEASING.md).
-
-From the repository root:
+Root shortcuts for Zcash (the direct commands in its README need no Node install):
 
 ```sh
 yarn zcash:prepare
@@ -17,13 +15,5 @@ yarn zcash:test
 yarn zcash:build
 ```
 
-These convenience commands dispatch to the Rust project. The equivalent direct
-commands in the Zcash README do not require installing the root Node dependencies.
-Generated WASM stays out of Git. The Zcash CI workflow builds both runtime and keys
-packages together and stores them as one artifact; npm publishing is a separate,
-manually triggered workflow described in the release process.
-
-## Monero
-
-See [monero](./monero/README.md). It is built and tested from its own directory
-(`cargo test --workspace`, `bash scripts/build-wasm.sh`) and is not published yet.
+Generated wasm stays out of Git. Both runtimes are built, tested and published to
+npm by the manually triggered **publish-runtime-packages** workflow.
diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md
index 3140877db..6333632ef 100644
--- a/chain-runtimes/monero/README.md
+++ b/chain-runtimes/monero/README.md
@@ -1,8 +1,8 @@
 # OneKey Monero Runtime
 
-Wallet state layer over monero-oxide. monero-oxide provides cryptography, scanning
-and transaction construction; this crate adds the storage it lacks: SQLite with
-incremental, transactional writes.
+Wallet state layer over monero-oxide, published as `onekey-monero-runtime`.
+monero-oxide provides cryptography, scanning and transaction construction; this
+crate adds the storage it lacks: SQLite with incremental, transactional writes.
 
 ## Build
 
@@ -14,24 +14,23 @@ cargo check --workspace --target wasm32-unknown-unknown
 ./scripts/build-node-pkg.sh && node scripts/smoke.js      # wasm end-to-end smoke test
 ```
 
-`smoke.js` runs offline; set `XMR_NODE=` to add node checks.
-The toolchain matches the Zcash runtime, so one install builds both: Rust 1.93.0
-(pinned in `rust-toolchain.toml`), wasm-pack 0.15.0, `wasm-bindgen-cli` at the
-version in `Cargo.lock`, and `wasm-opt` (Binaryen 133 in CI).
+`smoke.js` runs offline; set `XMR_NODE=` to add node checks. The
+toolchain matches the Zcash runtime: Rust 1.93.0 (pinned in `rust-toolchain.toml`),
+wasm-pack 0.15.0, `wasm-bindgen-cli` at the version in `Cargo.lock`, and `wasm-opt`
+(Binaryen).
 
 **macOS needs `llvm-ar`** (`brew install llvm`). `/usr/bin/ar` cannot read wasm
 objects and silently writes an empty archive; linking then fails with
-`undefined symbol: sqlite3_*`. `cargo check` does not link, so it never shows this.
-`build-wasm.sh` finds Homebrew's clang and `llvm-ar` on Apple Silicon and Intel;
-`.cargo/config.toml` sets the Apple Silicon archiver for direct `cargo` builds.
+`undefined symbol: sqlite3_*`, which `cargo check` never shows. `build-wasm.sh` and
+`.cargo/config.toml` pick up Homebrew's toolchain.
 
 ## Release
 
-Run the **publish-runtime-packages** workflow manually to build, test and publish
-`onekey-monero-runtime` (skipped if its version is already on npm): prereleases to npm `next`, release
-versions to `latest`. Branches other than `main` can publish alpha versions only. Locally,
-`python3 scripts/package-release.py --version  --tag ` packs the
-archive into `dist/` without publishing.
+Run the **publish-runtime-packages** workflow manually. It builds, tests and
+publishes the package unless its version is already on npm: prereleases to `next`,
+releases to `latest`. Branches other than `main` can publish alpha versions only.
+`python3 scripts/package-release.py --version  --tag ` packs into
+`dist/` locally without publishing.
 
 ## Host contract
 
@@ -39,24 +38,21 @@ archive into `dist/` without publishing.
    balance stays too high until `importKeyImages` is called. It covers only blocks
    scanned afterwards; earlier spends need a rewind and rescan. `balance` reports the
    unverified part as `unverifiableAtomic`.
-2. **The node must be on the wallet's network.** The node's chain is identified by its
-   genesis block; a mismatch fails with `NODE_NETWORK_MISMATCH`. `chainTip` works
-   without an open wallet and returns `network`; compare it before picking a birthday.
+2. **The node must be on the wallet's network.** It is identified by its genesis
+   block; a mismatch fails with `NODE_NETWORK_MISMATCH`. `chainTip` works without an
+   open wallet and returns `network`; check it before picking a birthday.
 3. **An `unknown` broadcast is not a failure.** The send is recorded and its inputs
    marked spent before broadcasting; pool checks and scanning settle it. Never report
    it as failed or prompt a resend.
-4. **The host schedules sync.** `syncStep` scans at most `maxBlocks` and returns; it
-   never loops to completion. Timing, batch size and backoff belong to the host.
+4. **The host schedules sync.** `syncStep` scans at most `maxBlocks` and returns.
 5. **Register subaddresses before use.** Funds to unregistered subaddresses go
    undetected.
 
-The scanner derives RingCT output indexes itself and fails with
-`RINGCT_INDEX_MISMATCH` when the node's claim differs.
-
 ## API
 
 Values cross the boundary as strings, numbers, booleans, bytes or JSON strings.
-Errors carry a stable `code` and structured `params`; user-facing text belongs to the host.
+Errors carry a stable `code` and structured `params`; user-facing text belongs to
+the host.
 
 ```
 init() / dependencyVersions()
@@ -95,38 +91,20 @@ signTransaction         verify again, then sign; no network, no DB
 broadcastTransaction    record, then broadcast → { txid, broadcast: accepted | unknown }
 ```
 
-`prepareTransaction` takes exactly one recipient. A first `broadcastTransaction`
-whose inputs are not this account's, or are already spent by another transaction,
-is refused with `INVALID_REQUEST` before anything is recorded or sent.
-
-`BROADCAST_REJECTED` is thrown only when the node explicitly rejects a first
-broadcast for a reason other than double spend; the record is then undone and the
-inputs released. Unsigned reservations expire after 1 hour, signed ones after 24
-hours. Call `releaseReservation` when the user cancels.
-
-## Layout
-
-```
-error.rs     error codes (stable across the wasm boundary)
-storage.rs   SQLite connection, OPFS VFS, durability barrier
-schema.rs    tables and migrations
-keys.rs      view keys, addresses, subaddress derivation
-wallet.rs    DB handle, identities, subaddress registry
-scan.rs      scan loop, output checks, persistence
-sync.rs      bounded sync (fetch → scan → record progress)
-query.rs     balance, history, spendable outputs
-spend.rs     key images, selection, reservation, build, sign, broadcast
-review.rs    pre-signing check of recipient, amount, fee and change
-pool.rs      liveness check of our unconfirmed sends
-network.rs   monerod transport and node network check
-runtime.rs   session state and concurrency guards
-bindgen.rs   wasm boundary
-```
+- `prepareTransaction` takes exactly one recipient.
+- A first `broadcastTransaction` whose inputs are not this account's, or are already
+  spent elsewhere, is refused with `INVALID_REQUEST` before anything is recorded.
+- `BROADCAST_REJECTED` is thrown only when the node explicitly rejects a first
+  broadcast for a reason other than double spend; the record is undone and the
+  inputs released.
+- Unsigned reservations expire after 1 hour, signed ones after 24 hours. Call
+  `releaseReservation` when the user cancels.
+- The scanner derives RingCT output indexes itself and fails with
+  `RINGCT_INDEX_MISMATCH` when the node's claim differs.
 
 ## Relation to the Zcash runtime
 
-Separate workspaces with no code dependency, but one storage layer: `vendor-deps.sh`
-rebuilds `sqlite-wasm-vfs` with the Zcash runtime's patch, using its
-`prepare-vendor.py`, so a VFS fix lands in both. `crates/monero-runtime/build.rs`
-(wasm SQLite link glue) mirrors the Zcash one; keep them in sync. Unlike Zcash, `runtime.rs`
-is not wasm-only, so its concurrency guards are covered by native tests.
+No code dependency, but one storage layer: `vendor-deps.sh` rebuilds
+`sqlite-wasm-vfs` with the Zcash patch via its `prepare-vendor.py`, so a VFS fix
+lands in both. `crates/monero-runtime/build.rs` mirrors the Zcash wasm SQLite link
+glue; keep them in sync.
diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md
index 182cc6f3f..2f6c91a22 100644
--- a/chain-runtimes/zcash/README.md
+++ b/chain-runtimes/zcash/README.md
@@ -1,110 +1,48 @@
 # OneKey Zcash Runtime
 
 Thin wasm bindings over the official `librustzcash`, with `zcash_client_sqlite` as
-the wallet store. Does not depend on WebZjs.
-
-Two packages built from one source, used by every App platform (Desktop, Web,
-Extension, iOS, Android):
+the wallet store. Two packages built from one source, used on every App platform:
 
 - `onekey-zcash-keys`: derivation, review checks and signing. No SQLite, network,
   scanner or prover.
 - `onekey-zcash-runtime`: wallet, scanning, SQLite and PCZT proving.
 
-Both run inside a DedicatedWorker (an inline Blob Worker from WebEmbed on mobile, a
-URL Worker elsewhere). Native Rust builds are for tests and diagnostics only.
-`zcash-storage-benchmark` is a developer tool for synthetic storage tests.
+Both run inside a DedicatedWorker. Native Rust builds are for tests and diagnostics
+only. `zcash-storage-benchmark` is a developer tool for synthetic storage tests.
 
 ## Build
 
 Run from this directory. Requires Rust 1.93.0 (pinned in `rust-toolchain.toml`),
 Python 3.11+, LLVM/Clang with wasm32 support, wasm-pack 0.15.0, `wasm-bindgen-cli`
-at the version in `Cargo.lock`, and `wasm-opt` (Binaryen). Builds use
-`--mode no-install` and never update `Cargo.lock`.
+at the version in `Cargo.lock`, and `wasm-opt` (Binaryen). Builds never update
+`Cargo.lock`.
 
 ```bash
 rustup target add wasm32-unknown-unknown
-brew install llvm                    # Apple clang cannot target wasm32
+brew install llvm                       # Apple clang cannot target wasm32
 
-bash scripts/build-wasm.sh           # builds pkg/ and pkg-keys/ (prepares vendor first)
+bash scripts/build-wasm.sh              # builds pkg/ and pkg-keys/ (prepares vendor first)
 
-bash scripts/vendor-deps.sh          # once before native tests
+bash scripts/vendor-deps.sh             # once before native tests
 cargo test --workspace --locked
 
 bash scripts/vendor-deps.sh --offline   # verify vendor against recorded upstream + patches
 ```
 
-`pkg/` and `pkg-keys/` are not committed; they are built together for the App's
-local `portal:` dependencies or CI artifacts. Publishing is in [RELEASING.md](./RELEASING.md).
+`pkg/` and `pkg-keys/` are build outputs and are not committed. Publishing is in
+[RELEASING.md](./RELEASING.md).
 
 ## Design rules
 
-1. **No forked Zcash storage.** `zcash_client_sqlite` comes from crates.io with no
-   Rust source changes; the only change is one Cargo.toml feature (see Vendor patches).
-2. **Seeds enter only the keys wasm, only for an authorized derive or sign call.** Rust
-   wipes its secret buffers; JS strings and cross-bridge copies cannot be reliably
-   wiped. The scanner holds the UFVK, never the seed.
-3. **Few verbs, plain data.** Only strings, numbers, booleans, bytes and JSON strings
-   cross the boundary; no Rust object handles are given to JS.
-
-| Rust (wasm) | Host TS |
-|---|---|
-| Trial decryption | When and how much to scan |
-| Witness and commitment trees | Accounts and birthdays |
-| Transaction construction and note selection | Caching and persistence policy |
-| Key derivation and signing | Progress, error handling, retries |
-| Platform glue (clock, RNG, VFS) | History display model |
-
-Code belongs in Rust only if it touches key security, large cross-boundary data or
-consensus correctness.
-
-## Vendor patches
-
-`zcash_client_sqlite` enables `rusqlite`'s `bundled` feature, which compiles SQLite's
-C source with cc. `wasm32-unknown-unknown` has no libc sysroot and stops at
-`fatal error: 'stdio.h' file not found`. Cargo features are additive, so a downstream
-crate cannot disable it; only the upstream Cargo.toml can.
-
-`scripts/vendor-deps.sh` downloads the official releases and applies the patches
-recorded in `patches/manifest.json`:
-
-- `zcash_client_sqlite`: the one-line Cargo.toml change.
-- `sqlite-wasm-vfs`: OPFS durability fixes (connection lock, durable journal deletion,
-  handle cleanup, stop I/O after a metadata failure).
-- `tonic-web-wasm-client`: host fetch injection.
-
-`scripts/prepare-vendor.py --offline` rebuilds and compares every file from the
-verified archives and patches, and rejects unrecorded vendor changes.
-
-The wasm SQLite comes precompiled from `sqlite-wasm-rs`; `crates/zcash-runtime/build.rs`
-links its `libwsqlite3.a` under the name the linker expects. No manual RUSTFLAGS.
-
-## Storage
-
-All platforms use the `sqlite-wasm-vfs` OPFS SAH pool in `.onekey-zcash-opfs`, with
-six file handles reserved by default. Databases are `zcash-main.db` / `zcash-test.db`.
-SQLite reads and writes pages through sync access handles; the database is never
-preloaded into wasm memory. One Worker owns each origin's pool; a second Worker must
-not silently switch to another database.
-
-Connections use `journal_mode=DELETE` and `synchronous=FULL`. Flush errors on commit
-and journal deletion reach the host. After a metadata I/O failure the VFS stops
-serving and `storageRequiresWorkerRestart()` returns true: keep the failed call's
-result and restart the Worker. No SharedArrayBuffer, COOP/COEP or UI-thread sync file
-access is needed. OPFS is still subject to origin, quota and eviction rules, so the
-App's embedded page origin must be stable.
-
-## Known constraints
-
-- The lightwalletd endpoint **must support gRPC-web** (and CORS without a host
-  transport). A native-gRPC-only endpoint hangs on the first browser request even if
-  `grpcurl` works. The host supplies the endpoint; none is hardcoded.
-- **Scanning does not use upstream `scan_cached_blocks`** but `scan_blocks_inline`.
-  Upstream hands trial decryption to `rayon::spawn_fifo`; single-threaded wasm has no
-  worker threads, so the task never runs and the main thread blocks forever. This
-  loses batched trial decryption. Use `syncPeek()` for progress.
-- `syncPrepare()` downloads every pool's subtree roots, many more on mainnet; give it
-  its own "preparing" state.
-- Sapling is out of scope: not a receiver, scan identity or send source.
+1. **No forked Zcash storage.** `zcash_client_sqlite` is used unmodified except for
+   one Cargo.toml feature (see Pitfalls).
+2. **No seed or mnemonic enters any wasm.** The host passes only account-scoped keys
+   (Orchard `m/32'/133'/account'`, transparent `m/44'/133'/account'`), only for a
+   derive or sign call. The scanner holds the UFVK, never a spending key.
+3. **Plain data across the boundary.** Strings, numbers, booleans, bytes and JSON
+   strings only; no Rust object handles reach JS.
+4. **Rust owns key security, large data and consensus correctness;** the host owns
+   scheduling, accounts, persistence policy, retries and display.
 
 ## API
 
@@ -143,8 +81,7 @@ storageStats()
 pcztQuote(...)                           quote only; builds nothing, locks nothing
 pcztCreate(...) → { pcztHex, reservationId }   build and lock the selected notes
 releaseReservation(id)                   user cancel; idempotent
-clearLockedOutputs(uuid)                 repair: clear the account's locks; refused
-                                         while broadcasts are pending
+clearLockedOutputs(uuid)                 repair; refused while broadcasts are pending
 pcztProve(pczt)
 pcztCombine(original, signed)            merge an external signer's copy (signatures only)
 pcztSubmit(uuid, pczt, reservationId)    → { txid, broadcast }
@@ -160,96 +97,83 @@ dependencyVersions() / setPerfTrace(enabled) / diag*
 ### `onekey-zcash-keys`
 
 ```
-ufvkFromSeed(network, seedBytes, accountIndex)
+ufvkFromAccountKeys(network, orchardSk, accountXpub, accountIndex)
+                                         mainnet only; orchardSk is the 32-byte Orchard key
 unifiedAddress(network, ufvk, receiverPolicy)
                                          "all" = Orchard + transparent;
                                          "shielded" / "orchard" = Orchard only; never Sapling
 transparentAddressFromUfvk(network, ufvk) / transparentAccountPubKeyFromUfvk(network, ufvk)
-validateAddress(network, address) / seedFingerprint(seed)
+validateAddress(network, address)
 pcztVerifyReview(pczt, reviewJson)       check only, no signing
-pcztSignWithSeed(network, seed, accountIndex, pczt, reviewJson)
-                                         only place spend keys are used; checks every
-                                         spend and output against the review first
+pcztSignWithAccountKeys(network, orchardSk, accountXprv, accountIndex, pczt, reviewJson)
+                                         mainnet only; requires the keys to rebuild the
+                                         reviewed UFVK, then checks every spend and output
+pcztRedactForHardwareSigner(pczt)        copy to send to a device; keep the original
 transparentTx* / transparentShield*      stateless transparent sends, see
-                                         crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
-parseTransparentTransactions(requestJson)
+parseTransparentTransactions(requestJson)  crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
 keysCapabilities() / keysDependencyVersions()
 ```
 
 ### Sending
 
 ```
-runtime.pcztCreate()      build (needs wallet DB: selection, witness, anchor), lock notes
-runtime.pcztProve()       zero-knowledge proofs (slow)
-keys.pcztSignWithSeed()   check against the review, then sign (needs the seed)
-runtime.pcztSubmit()      combine check → extract → store → broadcast
+runtime.pcztCreate()             build (selection, witness, anchor) and lock notes
+runtime.pcztProve()              zero-knowledge proofs (slow)
+keys.pcztSignWithAccountKeys()   check against the review, then sign
+  or hardware: keys.pcztRedactForHardwareSigner() → device → runtime.pcztCombine()
+runtime.pcztSubmit()             combine check → extract → store → broadcast
 ```
 
-Prove before signing: the upstream Signer must be able to verify what the proofs cover.
-
-The signed bytes and the reservation→txid link are stored atomically before
-broadcast; every retry and crash recovery sends the same bytes. Outcomes:
-
-- `accepted`: the node took it. `already known`, `already in mempool` and
-  `already in blockchain` count as success.
-- `rejected`: only a reply that the transaction is consensus-invalid or expired. It
-  stays stored; its notes return only after its expiry height.
-- `unknown`: anything else (timeout, transient error, unclear reply). It stays pending
-  and sync rebroadcasts the same bytes. The host must not show it as failed or
-  prompt a resend, and must check `pendingBroadcastTxids` before building another
-  payment.
-
-`FINALIZE_OUTCOME_UNKNOWN` from `pcztSubmit` or `broadcastTransaction` means the
-step went through but persistence is unconfirmed. Treat it like `unknown`: do not
-unlock notes or rebuild the transaction.
-
-A `reservationId` with a stored transaction cannot build again: `pcztCreate` refuses
-it and `pcztSubmit` only rebroadcasts the stored one. Network calls time out after
-30 seconds.
-
-### Stateless transparent sends to Unified Addresses
-
-`transparentTxQuote` accepts mainnet t1/t3/tex recipients and Unified Addresses with
-an Orchard receiver (paid as an Ironwood output after NU6.3). It uses only the
-host-supplied confirmed, non-coinbase transparent UTXOs, explicit outpoints, target
-height and transparent change address. No wallet, database, scan or network call.
-Sapling/Sprout destinations and coinbase inputs are unsupported.
-
-Software keys (seed or account xprv):
-
-1. `keys.transparentShieldCreateWithSeed` / `WithAccountXprv` builds a PCZT from the
-   request used for the quote.
-2. `runtime.pcztProveAtHeight` proves it.
-3. `keys.transparentShieldSignWithSeed` / `WithAccountXprv` checks the request, the
-   original PCZT and the proved PCZT, then signs.
-4. `runtime.pcztExtractStateless` verifies and extracts the final transaction.
-
-Hardware: `keys.transparentTxCreateWithAccountXpub` → device signs →
-`keys.transparentTxCombineHardwareSigned` (verifies every signature against the
-request) → `runtime.pcztProveAtHeight` → `runtime.pcztExtractStateless`.
-
-`parseTransparentTransactions` verifies raw previous transactions against their
-txids and returns output values, scripts and coinbase status; the host checks each
-UTXO's index and value against it.
-
-The host owns outpoint reservations, UTXO revalidation at signing time, pending
-broadcast records and submission. The recipient scans to find the shielded notes;
-the sender does not need to scan.
+Prove before signing: the upstream Signer must be able to verify what the proofs
+cover. The signed bytes and the reservation→txid link are stored before broadcast,
+so every retry and crash recovery sends the same bytes. Broadcast outcomes:
+
+- `accepted`: the node took it (`already known` / `in mempool` / `in blockchain`
+  count as success).
+- `rejected`: only an explicit consensus-invalid or expired reply. The transaction
+  stays stored; its notes return after its expiry height.
+- `unknown`: anything else. It stays pending and sync rebroadcasts the same bytes.
+  Never show it as failed or prompt a resend; check `pendingBroadcastTxids` before
+  building another payment.
+
+`FINALIZE_OUTCOME_UNKNOWN` means persistence is unconfirmed: treat it like `unknown`
+and do not unlock notes or rebuild. A `reservationId` with a stored transaction
+cannot build again. Network calls time out after 30 seconds.
+
+Transparent-only sends (t-address or Unified Address recipients, no wallet or scan)
+use the stateless API in
+[TRANSPARENT_TX_API.md](./crates/zcash-keys-runtime/TRANSPARENT_TX_API.md).
+
+## Pitfalls
+
+- **The lightwalletd endpoint must support gRPC-web** (and CORS without a host
+  transport). A native-gRPC-only endpoint hangs on the first browser request even
+  if `grpcurl` works. No endpoint is hardcoded.
+- **Scanning does not use upstream `scan_cached_blocks`.** It hands trial decryption
+  to `rayon::spawn_fifo`, which never runs in single-threaded wasm and blocks the
+  thread forever. `scan_blocks_inline` replaces it; use `syncPeek()` for progress.
+- **`rusqlite`'s `bundled` feature breaks wasm32** (`'stdio.h' file not found`) and
+  Cargo features cannot be disabled downstream, so `scripts/vendor-deps.sh` patches
+  `zcash_client_sqlite`'s Cargo.toml. It also applies OPFS durability fixes to
+  `sqlite-wasm-vfs` and host fetch injection to `tonic-web-wasm-client`. All patches
+  are recorded in `patches/manifest.json`; `--offline` rejects unrecorded vendor
+  changes. The precompiled wasm SQLite is linked by `crates/zcash-runtime/build.rs`.
+- **Storage is OPFS** (SAH pool in `.onekey-zcash-opfs`, `zcash-main.db` /
+  `zcash-test.db`), with `journal_mode=DELETE` and `synchronous=FULL`. One Worker
+  owns each origin's pool. OPFS is per-origin and subject to quota and eviction, so
+  the embedding page's origin must be stable. When `storageRequiresWorkerRestart()`
+  is true after an I/O failure, keep the failed call's result and restart the
+  Worker. No SharedArrayBuffer or COOP/COEP is needed.
+- `syncPrepare()` downloads every pool's subtree roots (many on mainnet); give it its
+  own "preparing" state.
+- Sapling is out of scope: not a receiver, scan identity or send source.
 
 ## Layout
 
 ```
 crates/zcash-runtime/            wallet, scanning, PCZT build/prove/submit
-  src/bindgen.rs                 JS interface
-  src/send.rs                    proposals, reservations, PCZT lifecycle
-  src/tx_state.rs                reservation→txid link and broadcast outcomes
-  src/guard.rs                   persistent gate for destructive operations
-  src/sync.rs                    bounded scanning
-  src/storage.rs                 VFS install, connections, durability barrier
-  build.rs                       links the wasm SQLite static library
 crates/zcash-keys-runtime/       derivation, review checks, signing, stateless transparent sends
 crates/zcash-storage-benchmark/  synthetic storage tests
 patches/                         pinned upstream checksums and patches
-scripts/vendor-deps.sh           verify official releases and apply recorded patches
-scripts/build-wasm.sh            build
+scripts/                         vendor-deps.sh, build-wasm.sh, package-release.py
 ```
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
index 3baac33e8..2f78f062a 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
@@ -1,30 +1,51 @@
 # Stateless transparent transaction API
 
-This crate can quote and sign a mainnet transaction that spends transparent funds without a
-`WalletDb`, scanner, or network client. The host owns UTXO discovery, reservation, broadcast, and
-status reconciliation.
+`onekey-zcash-keys` can quote and sign a mainnet transaction that spends transparent
+funds without a wallet database, scanner or network client. The host owns UTXO
+discovery, outpoint reservation, revalidation at signing time, broadcast and status
+reconciliation. Recipients find shielded outputs by scanning; the sender does not scan.
 
 ## Exports
 
 - `transparentTxQuote(requestJson)`
-- `transparentTxBuildWithSeed(requestJson, seed)`
-- `transparentTxBuildWithAccountXprv(requestJson, accountXprv)`
-- `transparentShield{Create,Sign}With{Seed,AccountXprv}`: Unified Address recipients
-  through a proved PCZT
+- `transparentTxBuildWithAccountXprv(requestJson, accountXprv)`: transparent recipients
+- `transparentShieldCreateWithAccountXprv(requestJson, accountXprv)` and
+  `transparentShieldSignWithAccountXprv(requestJson, accountXprv, original, proved)`:
+  Unified Address recipients through a proved PCZT
 - `transparentTxCreateWithAccountXpub(requestJson, accountXpub, seedFingerprintHex)` and
-  `transparentTxCombineHardwareSigned(requestJson, accountXpub, original, signed)`: hardware
-  signing
+  `transparentTxCombineHardwareSigned(requestJson, accountXpub, original, signed)`:
+  hardware signing
+- `parseTransparentTransactions(requestJson)`: verifies raw previous transactions
+  against their txids and returns output values, scripts and coinbase status; the
+  host checks each UTXO's index and value against it
 
-The PCZT call sequences are in the Zcash README. All entry points take the same request.
+All entry points take the same request. No entry point takes a seed or mnemonic.
+`seedFingerprintHex` is the 32-byte ZIP-32 seed fingerprint written into the PCZT's
+derivation metadata for the device; it is an identifier, not key material.
 
-The xprv entry point accepts an account-level BIP-44 xprv. Its required derivation path is
-`m/44'/133'/account'`. An account xprv cannot attest its ancestors, so the crate verifies its depth
-and hardened account child metadata while the host remains responsible for deriving the account
-xprv from the exact purpose and coin-type path.
+The xprv entry points take the account-level BIP-44 xprv at `m/44'/133'/account'`.
+An account xprv cannot attest its ancestors, so the crate checks its depth and
+hardened account child; deriving it from the right purpose and coin type is the
+host's job.
+
+## Call sequences
+
+Unified Address recipient, software key:
+
+1. `keys.transparentShieldCreateWithAccountXprv` builds a PCZT from the quoted request.
+2. `runtime.pcztProveAtHeight` proves it.
+3. `keys.transparentShieldSignWithAccountXprv` checks the request, the original PCZT
+   and the proved PCZT, then signs.
+4. `runtime.pcztExtractStateless` verifies and extracts the final transaction.
+
+Hardware: `keys.transparentTxCreateWithAccountXpub` → device signs →
+`keys.transparentTxCombineHardwareSigned` (verifies every signature against the
+request) → `runtime.pcztProveAtHeight` → `runtime.pcztExtractStateless`.
 
 ## Request
 
-Amounts are decimal strings because JavaScript numbers cannot represent every valid zatoshi value.
+Amounts are decimal strings because JavaScript numbers cannot represent every valid
+zatoshi value.
 
 ```json
 {
@@ -58,26 +79,27 @@ Amounts are decimal strings because JavaScript numbers cannot represent every va
 }
 ```
 
-Only selected outpoints are spent. Every selection must resolve to exactly one supplied UTXO.
-Inputs must be confirmed, non-coinbase P2PKH coins controlled by their declared external or internal
-BIP-44 path. Recipients may be mainnet P2PKH (`t1`), P2SH (`t3`), a ZIP-320 TEX address (`tex1`,
-paid as P2PKH), or a Unified Address with an
-Orchard receiver, which is paid an Ironwood note; a Unified Address without one is rejected rather
-than paid at a public receiver. Change must be an owned P2PKH address on internal scope `1` with an address index below 40.
-
-For send-max, supply exactly one recipient and omit `amountZat` and `change`. The recipient receives
-the selected input total minus the ZIP-317 fee. For a fixed amount, a surplus too small to fund a
-change output (below the 5,000 zatoshi marginal fee, or not enough to pay for the extra output) is
-added to the fee and shown in the quote; the overpayment stays below about 0.0001 ZEC.
-Any larger surplus requires a `change` entry.
-
-The target height must be on the mainnet NU6.3 branch. `expiryHeight` is mandatory and is supplied
-by the host's transaction policy. The crate validates that it is after the target height and no more
-than 100 blocks later; it does not choose a product expiry policy. The resulting transaction is V6.
+- Only selected outpoints are spent; each must resolve to exactly one supplied UTXO.
+- Inputs must be confirmed, non-coinbase P2PKH coins controlled by their declared
+  external or internal BIP-44 path.
+- Recipients may be `t1` (P2PKH), `t3` (P2SH), ZIP-320 `tex1` (paid as P2PKH), or a
+  Unified Address with an Orchard receiver (paid as an Ironwood note). A Unified
+  Address without one is rejected rather than paid at a public receiver.
+  Sapling/Sprout destinations are unsupported.
+- Change must be an owned P2PKH address on internal scope `1` with an address index
+  below 40.
+- Send-max: exactly one recipient, no `amountZat` and no `change`; the recipient gets
+  the selected total minus the ZIP-317 fee.
+- Fixed amount: a surplus too small to fund a change output (below the 5,000 zatoshi
+  marginal fee, or not enough to pay for the extra output) is added to the fee and shown in the quote, so the overpayment stays
+  below about 0.0001 ZEC. A larger surplus requires `change`.
+- `targetHeight` must be on the mainnet NU6.3 branch. `expiryHeight` is mandatory,
+  comes from the host's policy, and must be after the target height and at most 100
+  blocks later. The result is a V6 transaction.
 
 ## Results
 
-Quote result:
+Quote:
 
 ```json
 {
@@ -90,7 +112,7 @@ Quote result:
 }
 ```
 
-Build result:
+Build:
 
 ```json
 {
@@ -102,6 +124,6 @@ Build result:
 }
 ```
 
-The build entry points recompute the quote and fail closed if any input script or change address does
-not match the derived key. The host must reserve every returned outpoint before broadcast and retain
-the exact raw transaction for ambiguous broadcast recovery.
+Build entry points recompute the quote and fail closed if any input script or change
+address does not match the derived key. Reserve every returned outpoint before
+broadcast and keep the exact raw transaction for ambiguous broadcast recovery.
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md
index 9dae2c065..16c10789a 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md
@@ -1,12 +1,11 @@
 # Previous transaction fixtures
 
-Public Zcash mainnet transactions, recorded on 2026-09-20. The fixture stores the
-raw transactions; their mined heights are listed below:
+Raw public Zcash mainnet transactions:
 
 - `69ff03c1e3d19df98087396f86783addbc9f8ad615022efdeb5de10fe78597ae`: V4, height 3490000, output 0 is 100000000 zatoshi.
 - `70177881b2a62c93ed023725a24166362a5bd65cc93dbbd3b3a243ff5927d89c`: V6, height 3476066, output 0 is 1000 zatoshi.
 
 These are public chain data, not spendable test credentials. Tests verify the
-transaction IDs from the bytes before using the outputs. The coinbase test
-mutates the V4 input into a synthetic coinbase outpoint and recomputes its ID;
-it does not represent a mined transaction.
+transaction IDs from the bytes before using the outputs. The coinbase test mutates
+the V4 input into a synthetic coinbase outpoint and recomputes its ID; it does not
+represent a mined transaction.

From 0b4b0dcac44a81f422749995c7827957942d269a Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Sat, 17 Oct 2026 11:22:05 +0800
Subject: [PATCH 48/97] fix(zcash): stop copying the device PCZT size limit
 into the runtime

---
 .../zcash-keys-runtime/src/account_keys.rs      |  4 ++--
 .../zcash/crates/zcash-keys-runtime/src/keys.rs |  2 +-
 .../zcash/crates/zcash-keys-runtime/src/sign.rs | 10 +++++-----
 .../src/transparent_send/shielding.rs           | 17 ++++-------------
 .../zcash/crates/zcash-runtime/src/send.rs      |  3 ++-
 5 files changed, 14 insertions(+), 22 deletions(-)

diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
index c83c9f5b4..6ca50a29f 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
@@ -138,8 +138,8 @@ pub(crate) fn parse_orchard_sk(bytes: &[u8]) -> Result> {
 
 /// Transparent + Orchard UFVK, the same items the OneKey firmware returns.
 ///
-/// Sapling is left out: this runtime can neither scan for nor spend it, and the
-/// firmware rejects PCZTs that carry it. Ironwood keys derive from the Orchard item.
+/// Sapling is left out: this runtime can neither scan for nor spend it.
+/// Ironwood keys derive from the Orchard item.
 pub(crate) fn ufvk_from_parts(
     params: Network,
     fvk: &FullViewingKey,
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
index c8690ced5..7bfeb0d6f 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
@@ -193,7 +193,7 @@ mod tests {
     use super::*;
 
     /// Same items as the firmware's UFVK, so a device and a software account on
-    /// one seed agree; a Sapling item would also make the firmware reject PCZTs.
+    /// one seed agree.
     #[test]
     fn ufvk_holds_only_transparent_and_orchard() {
         use crate::account_keys::{test_keys, ufvk_from_account_keys};
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
index 57345210d..25ef937d6 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
@@ -174,11 +174,11 @@ pub fn sign_pczt_with_account_keys(
 
 /// The copy of a PCZT sent to a hardware signer.
 ///
-/// The firmware rejects any Sapling data (the IO Finalizer sets `bsk` even on
-/// an empty bundle) and any proving fields (witnesses, dummy keys, proofs,
-/// binding keys). Signing needs none of them; the host keeps the original and
-/// combines the device's result into it, so proving and extraction still have
-/// them. Upstream `redact_pczt_for_signer` (compact view) clears the same.
+/// Drops what a signer doesn't need: Sapling `bsk` (the IO Finalizer sets it
+/// even on an empty bundle) and proving fields (witnesses, dummy keys, proofs,
+/// binding keys), matching upstream `redact_pczt_for_signer` (compact view).
+/// The host keeps the original and combines the device's result into it, so
+/// proving and extraction still have them.
 pub fn redact_for_hardware_signer(pczt_bytes: &[u8]) -> Result> {
     fn redact_orchard_protocol(mut bundle: pczt::roles::redactor::orchard::OrchardRedactor<'_>) {
         bundle.clear_zkproof();
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
index 4a8609e52..24e173d0b 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
@@ -216,15 +216,7 @@ pub fn create_with_account_xpub(
         })
         .map_err(failure)?
         .finish();
-    // Keep device RAM bounds explicit before asking the user to confirm.
-    let serialized = updated.serialize().map_err(failure)?;
-    if serialized.len() > 24 * 1024 {
-        return Err(KeysError::with(
-            ErrorCode::TransactionBuildFailed,
-            serde_json::json!({ "reason": "hardwarePcztTooLarge", "maxBytes": 24 * 1024 }),
-        ));
-    }
-    Ok(serialized)
+    updated.serialize().map_err(failure)
 }
 
 /// Combines a device's redacted signatures with the approved original, verifies
@@ -841,10 +833,9 @@ mod tests {
         }
     }
 
-    // The firmware (firmware-pro2 `signer_parse.rs`) rejects any Sapling data,
-    // including the `bsk` the IO Finalizer sets on the empty bundle, and any
-    // proving fields. The device signs a copy without them; combining its
-    // result into the original gives the same transaction.
+    // The device signs a copy without Sapling `bsk` (set by the IO Finalizer
+    // even on the empty bundle) or proving fields, which signing doesn't need;
+    // combining its result into the original gives the same transaction.
     #[test]
     fn hardware_signs_a_copy_without_sapling_or_proving_fields() {
         for transparent_destination in [false, true] {
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
index fe3db088a..16543fb58 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
@@ -714,7 +714,8 @@ fn mark_wallet_outputs(
 /// name a `user_address` (real recipients) are left alone, as are outputs we do
 /// not own (padding). Undecryptable owned outputs are the zero-valued outputs
 /// the post-NU6.3 Orchard builder pairs with external-scope spends, with a
-/// randomized ciphertext: the firmware rejects those if they carry a path.
+/// randomized ciphertext: no one can decrypt them, so like padding they get no
+/// path claiming them as wallet outputs.
 fn mark_owned_outputs(
     pczt: pczt::Pczt,
     fvk: &orchard::keys::FullViewingKey,

From f7e7cc68d6302e83bc871113c829447e25ef8652 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Sat, 17 Oct 2026 20:54:22 +0800
Subject: [PATCH 49/97] fix(monero): follow wallet2 unlock rules, keep the
 latest node selection and signal storage restarts

---
 chain-runtimes/monero/Cargo.lock              |   2 +-
 chain-runtimes/monero/Cargo.toml              |   2 +-
 chain-runtimes/monero/README.md               |   1 +
 .../crates/monero-runtime/src/bindgen.rs      |  17 +-
 .../crates/monero-runtime/src/network.rs      |   6 +-
 .../monero/crates/monero-runtime/src/query.rs | 306 ++++++++++++++++--
 .../crates/monero-runtime/src/runtime.rs      | 150 ++++++++-
 .../crates/monero-runtime/src/storage.rs      |  13 +-
 .../crates/monero-runtime/tests/live_node.rs  |   7 +
 9 files changed, 461 insertions(+), 43 deletions(-)

diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock
index 7e2a96c81..709c4a709 100644
--- a/chain-runtimes/monero/Cargo.lock
+++ b/chain-runtimes/monero/Cargo.lock
@@ -1259,7 +1259,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-monero-runtime"
-version = "0.1.0-alpha.1"
+version = "0.1.0-alpha.2"
 dependencies = [
  "curve25519-dalek",
  "futures-lite",
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index 5f147032a..78bc44a25 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/monero-runtime"]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.1"
+version = "0.1.0-alpha.2"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md
index 6333632ef..102393329 100644
--- a/chain-runtimes/monero/README.md
+++ b/chain-runtimes/monero/README.md
@@ -56,6 +56,7 @@ the host.
 
 ```
 init() / dependencyVersions()
+storageRequiresWorkerRestart()                  true after a VFS failure
 openWallet(dbName, network) / closeWallet() / deleteWallet(dbName)
 setNodeUrl(url) / setRequestHandler(handler)    no default node
 chainTip()                                      { height, network }
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
index ebd48c250..57c041a90 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -19,7 +19,7 @@ use wasm_bindgen::prelude::*;
 use crate::error::{ErrorCode, Result, RuntimeError};
 use zeroize::Zeroizing;
 
-use crate::{keys, network, query, runtime, spend, storage, sync, wallet};
+use crate::{keys, query, runtime, spend, storage, sync, wallet};
 
 fn json(value: serde_json::Value) -> std::result::Result {
     Ok(value.to_string())
@@ -32,6 +32,12 @@ pub async fn init() -> std::result::Result<(), JsValue> {
     Ok(())
 }
 
+/// Preserve a failed call's result, then retire its poisoned storage owner.
+#[wasm_bindgen(js_name = storageRequiresWorkerRestart)]
+pub fn storage_requires_worker_restart() -> bool {
+    storage::requires_worker_restart()
+}
+
 /// Upstream versions pinned by this runtime, for host self-checks and logs.
 #[wasm_bindgen(js_name = dependencyVersions)]
 pub fn dependency_versions() -> String {
@@ -58,15 +64,10 @@ pub fn close_wallet() -> std::result::Result<(), JsValue> {
 ///
 /// The old node is dropped before connecting the new one: a replaced or disabled
 /// node must receive no further requests, even if the new one fails to connect.
+/// If calls overlap, the last one wins.
 #[wasm_bindgen(js_name = setNodeUrl)]
 pub async fn set_node_url(url: &str) -> std::result::Result<(), JsValue> {
-    runtime::clear_daemon();
-    network::forget_node_url();
-    if url.trim().is_empty() {
-        return Ok(());
-    }
-    let (daemon, node_network) = network::connect(url).await?;
-    runtime::set_daemon(daemon, node_network);
+    runtime::select_node(url).await?;
     Ok(())
 }
 
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/network.rs b/chain-runtimes/monero/crates/monero-runtime/src/network.rs
index f2b64020a..4c8039744 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/network.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/network.rs
@@ -436,7 +436,6 @@ pub async fn connect(base_url: &str) -> Result<(Daemon, monero_wallet::address::
         .await
         .map_err(|e| net_err("connect", format!("{e:?}")))?;
     let network = node_network(&daemon).await?;
-    CURRENT_NODE_URL.with(|c| *c.borrow_mut() = Some(base_url.to_owned()));
     Ok((daemon, network))
 }
 
@@ -496,6 +495,11 @@ pub fn current_node_url() -> Option {
     CURRENT_NODE_URL.with(|c| c.borrow().clone())
 }
 
+/// Set only with the matching daemon (`runtime::select_node`), so a stale connect cannot win.
+pub fn remember_node_url(url: &str) {
+    CURRENT_NODE_URL.with(|c| *c.borrow_mut() = Some(url.to_owned()));
+}
+
 pub fn forget_node_url() {
     CURRENT_NODE_URL.with(|c| *c.borrow_mut() = None);
 }
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/query.rs b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
index 1d109e032..5ef9435fd 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/query.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
@@ -3,6 +3,7 @@
 //! Paging, height filters and per-subaddress aggregation are indexed SQLite
 //! queries, so long histories are never loaded into memory.
 
+use monero_wallet::address::Network;
 use monero_wallet::WalletOutput;
 use rusqlite::{params, OptionalExtension};
 use serde_json::{json, Value};
@@ -16,6 +17,16 @@ use crate::wallet::Db;
 /// `additional_timelock` applies on top of this.
 pub const COINBASE_AND_STANDARD_LOCK: u64 = 10;
 
+/// `CRYPTONOTE_MAX_BLOCK_NUMBER`: unlock values at or above it are Unix timestamps.
+const MAX_BLOCK_NUMBER: u64 = 500_000_000;
+/// `BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW`.
+const TIMESTAMP_CHECK_WINDOW: usize = 60;
+/// `CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS`: leeway on height-based unlock times.
+const LOCKED_TX_ALLOWED_DELTA_BLOCKS: u64 = 1;
+/// `DIFFICULTY_TARGET_V1` / `DIFFICULTY_TARGET_V2`, in seconds.
+const TARGET_SECONDS_V1: u64 = 60;
+const TARGET_SECONDS_V2: u64 = 120;
+
 #[derive(Debug, Default, Clone)]
 pub struct Balance {
     /// Sum of all unspent outputs.
@@ -53,6 +64,8 @@ impl Balance {
 /// Computes the balance. `chain_tip` drives the lock check; `None` (tip unknown)
 /// treats everything as locked rather than offer funds that cannot be spent.
 pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result {
+    let now = adjusted_time(db, identity_id)?;
+    let network = db.network();
     let mut stmt = db
         .conn()
         .prepare(
@@ -107,7 +120,7 @@ pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result) -> Result bool {
-    const MAX_BLOCK_NUMBER: u64 = 500_000_000;
-
-    if chain_tip < height + COINBASE_AND_STANDARD_LOCK {
+/// `chain_tip` is the top block number. `additional_timelock` is raw: below 500M
+/// it is a height, otherwise a Unix timestamp compared against `now` (see
+/// `adjusted_time`); with no chain time (`None`) timestamp locks stay locked.
+pub fn is_unlocked(
+    height: u64,
+    additional_timelock: u64,
+    chain_tip: u64,
+    now: Option,
+    network: Network,
+) -> bool {
+    // wallet2 compares against get_blockchain_current_height(): the chain length, i.e. tip + 1.
+    let current_height = chain_tip.saturating_add(1);
+    if height + COINBASE_AND_STANDARD_LOCK > current_height {
         return false;
     }
     if additional_timelock == 0 {
         return true;
     }
     if additional_timelock < MAX_BLOCK_NUMBER {
-        chain_tip >= additional_timelock
+        current_height - 1 + LOCKED_TX_ALLOWED_DELTA_BLOCKS >= additional_timelock
+    } else {
+        // wallet2::is_tx_spendtime_unlocked: one block of leeway past the timestamp.
+        now.is_some_and(|now| {
+            now.saturating_add(timestamp_lock_leeway(network, height)) >= additional_timelock
+        })
+    }
+}
+
+/// `CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V1/_V2`, picked by the output's
+/// height against the v2 fork heights wallet2 hard-codes.
+fn timestamp_lock_leeway(network: Network, height: u64) -> u64 {
+    let v2_height = match network {
+        Network::Testnet => 624_634,
+        Network::Stagenet => 32_000,
+        _ => 1_009_827,
+    };
+    if height < v2_height {
+        TARGET_SECONDS_V1
     } else {
-        // Timestamp locks cannot be judged from height alone; treat as locked.
-        false
+        TARGET_SECONDS_V2
+    }
+}
+
+/// "Now" for timestamp locks.
+///
+/// wallet2 uses the node's `get_info.adjusted_time`; this recomputes it from the
+/// identity's latest stored block timestamps. With fewer than 60 stored there is
+/// no chain time (`None`): the local clock is never trusted for an unlock.
+pub fn adjusted_time(db: &Db, identity_id: i64) -> Result> {
+    let mut timestamps: Vec = db
+        .conn()
+        .prepare(
+            "SELECT timestamp FROM blocks WHERE identity_id = ?1 ORDER BY height DESC LIMIT ?2",
+        )
+        .and_then(|mut stmt| {
+            stmt.query_map(params![identity_id, TIMESTAMP_CHECK_WINDOW as i64], |r| {
+                r.get::<_, i64>(0)
+            })?
+            .map(|t| t.map(|t| t.max(0) as u64))
+            .collect::>>()
+        })
+        .map_err(|e| db_err("adjustedTime", e))?;
+    if timestamps.len() < TIMESTAMP_CHECK_WINDOW {
+        return Ok(None);
     }
+    Ok(Some(daemon_adjusted_time(&mut timestamps)))
+}
+
+/// monerod's `Blockchain::get_adjusted_time` over the last 60 block timestamps.
+fn daemon_adjusted_time(timestamps: &mut [u64]) -> u64 {
+    // epee median sorts in place, so the "top" timestamp upstream reads is the maximum.
+    timestamps.sort_unstable();
+    let n = timestamps.len() / 2;
+    let median = if timestamps.len() % 2 == 1 {
+        timestamps[n]
+    } else {
+        let (a, b) = (timestamps[n - 1], timestamps[n]);
+        a / 2 + b / 2 + (a % 2 + b % 2) / 2
+    };
+    let median_ts =
+        median.saturating_add((TIMESTAMP_CHECK_WINDOW as u64 + 1) * TARGET_SECONDS_V2 / 2);
+    let current_ts = timestamps[timestamps.len() - 1].saturating_add(TARGET_SECONDS_V2);
+    current_ts.min(median_ts)
 }
 
 /// Spendable output **metadata**, without the deserialized crypto object.
@@ -172,6 +251,8 @@ pub struct SpendableRow {
 /// Only outputs **with a key image**: without one we cannot tell whether it is
 /// already spent, and the node would reject a double spend.
 pub fn spendable_rows(db: &Db, identity_id: i64, chain_tip: u64) -> Result> {
+    let now = adjusted_time(db, identity_id)?;
+    let network = db.network();
     let mut stmt = db
         .conn()
         .prepare(
@@ -209,7 +290,7 @@ pub fn spendable_rows(db: &Db, identity_id: i64, chain_tip: u64) -> Result current_height`,
+    /// where current_height is the chain length (tip + 1).
     #[test]
     fn the_ten_block_lock_is_enforced() {
-        assert!(!is_unlocked(100, 0, 100), "locked at the same height");
-        assert!(!is_unlocked(100, 0, 109), "locked one block short");
-        assert!(is_unlocked(100, 0, 110), "unlocked after 10 blocks");
+        assert!(
+            !is_unlocked(100, 0, 100, None, MAIN),
+            "locked at the same height"
+        );
+        assert!(
+            !is_unlocked(100, 0, 108, None, MAIN),
+            "locked one block before wallet2's unlock height"
+        );
+        assert!(
+            is_unlocked(100, 0, 109, None, MAIN),
+            "unlocked once the chain length reaches height + 10"
+        );
+        assert!(is_unlocked(100, 0, 110, None, MAIN));
     }
 
+    /// wallet2::is_tx_spendtime_unlocked: unlocked once
+    /// `current_height - 1 + 1 >= unlock_time`, i.e. tip + 1 >= unlock_time.
     #[test]
     fn additional_block_timelock_is_honoured() {
-        // Extra lock to height 200: still locked after the 10-block lock
-        assert!(!is_unlocked(100, 200, 150));
-        assert!(is_unlocked(100, 200, 200));
+        assert!(!is_unlocked(100, 200, 150, None, MAIN));
+        assert!(
+            !is_unlocked(100, 200, 198, None, MAIN),
+            "locked one block before wallet2's unlock height"
+        );
+        assert!(
+            is_unlocked(100, 200, 199, None, MAIN),
+            "unlocked at wallet2's unlock height"
+        );
+        assert!(is_unlocked(100, 200, 200, None, MAIN));
+        // Height locks ignore the clock
+        assert!(!is_unlocked(100, 200, 198, Some(u64::MAX), MAIN));
+        // The 10-block lock still applies when the height lock is already past
+        assert!(!is_unlocked(100, 50, 108, None, MAIN));
+        assert!(is_unlocked(100, 50, 109, None, MAIN));
+    }
+
+    /// wallet2::is_tx_spendtime_unlocked: `now + leeway >= unlock_time`, with a
+    /// 120 s leeway after the v2 fork and 60 s before it.
+    #[test]
+    fn timestamp_timelocks_unlock_at_the_leeway_boundary() {
+        let t = 1_700_000_000;
+        let h = 3_000_000;
+        assert!(
+            !is_unlocked(h, t, h + 10, Some(t - 121), MAIN),
+            "before expiry"
+        );
+        assert!(
+            is_unlocked(h, t, h + 10, Some(t - 120), MAIN),
+            "at the tolerance boundary"
+        );
+        assert!(is_unlocked(h, t, h + 10, Some(t + 1), MAIN), "after expiry");
+        assert!(
+            !is_unlocked(500, t, 510, Some(t - 61), MAIN),
+            "v1 era leeway is 60 s"
+        );
+        assert!(is_unlocked(500, t, 510, Some(t - 60), MAIN));
+        assert!(!is_unlocked(
+            31_999,
+            t,
+            32_009,
+            Some(t - 61),
+            Network::Stagenet
+        ));
+        assert!(is_unlocked(
+            32_000,
+            t,
+            32_010,
+            Some(t - 120),
+            Network::Stagenet
+        ));
+        assert!(is_unlocked(
+            624_634,
+            t,
+            624_644,
+            Some(t - 120),
+            Network::Testnet
+        ));
+        // The 10-block lock still applies to an expired timestamp lock
+        assert!(!is_unlocked(h, t, h + 8, Some(t + 1), MAIN));
+        assert!(is_unlocked(h, t, h + 9, Some(t + 1), MAIN));
+        // Timestamp boundary is unchanged at wallet2's first unlocked tip
+        assert!(!is_unlocked(h, t, h + 9, Some(t - 121), MAIN));
+        assert!(is_unlocked(h, t, h + 9, Some(t - 120), MAIN));
+        // Without chain time a timestamp lock stays locked, however old
+        assert!(!is_unlocked(h, 500_000_000, h + 10, None, MAIN));
+    }
+
+    /// Matches monerod's `get_adjusted_time`: min(max ts + 120, median + 3660).
+    #[test]
+    fn adjusted_time_follows_monerod() {
+        // Regular 120 s blocks: the max-timestamp projection wins
+        let mut regular: Vec = (0..60).map(|i| 1_000_000 + i * 120).collect();
+        assert_eq!(
+            daemon_adjusted_time(&mut regular),
+            1_000_000 + 59 * 120 + 120
+        );
+        // A far-future outlier is capped by the median projection
+        let mut outlier: Vec = (0..60).map(|i| 1_000_000 + i * 120).collect();
+        outlier[59] = 9_000_000;
+        let median = (1_000_000 + 29 * 120) / 2 + (1_000_000 + 30 * 120) / 2;
+        assert_eq!(daemon_adjusted_time(&mut outlier), median + 3_660);
+    }
+
+    fn add_block(db: &Db, identity_id: i64, height: u64, timestamp: u64) {
+        db.conn()
+            .execute(
+                "INSERT INTO blocks (identity_id, height, hash, ringct_next, timestamp)
+                 VALUES (?1, ?2, ?3, NULL, ?4)",
+                params![
+                    identity_id,
+                    height as i64,
+                    vec![(height % 251) as u8; 32],
+                    timestamp as i64
+                ],
+            )
+            .unwrap();
+    }
+
+    /// Stores `count` blocks from height 1_000 at 120 s spacing, ending at `last_timestamp`.
+    fn add_blocks(db: &Db, identity_id: i64, count: u64, last_timestamp: u64) {
+        for i in 0..count {
+            add_block(
+                db,
+                identity_id,
+                1_000 + i,
+                last_timestamp - (count - 1 - i) * 120,
+            );
+        }
+    }
+
+    /// Too few stored blocks for a median: no chain time, and no local clock.
+    #[test]
+    fn adjusted_time_needs_sixty_stored_blocks() {
+        let (db, id) = db_with_identity();
+        add_blocks(&db, id, 59, 1_000_000);
+        assert_eq!(adjusted_time(&db, id).unwrap(), None);
+        add_block(&db, id, 1_059, 1_000_120);
+        assert_eq!(adjusted_time(&db, id).unwrap(), Some(1_000_240));
+    }
+
+    /// Fewer than 60 stored blocks: a long-expired timestamp lock stays locked
+    /// in balance and selection, while height locks still unlock.
+    #[test]
+    fn timestamp_locked_outputs_stay_locked_without_chain_time() {
+        let (db, id) = db_with_identity();
+        let timestamp_locked = add_output(&db, id, 800, 1_000, true);
+        let height_locked = add_output(&db, id, 50, 1_001, true);
+        add_blocks(&db, id, 59, 2_000_000_000);
+        db.conn()
+            .execute(
+                "UPDATE outputs SET additional_timelock = ?1 WHERE id = ?2",
+                params![500_000_000i64, timestamp_locked],
+            )
+            .unwrap();
+        db.conn()
+            .execute(
+                "UPDATE outputs SET additional_timelock = ?1 WHERE id = ?2",
+                params![1_050i64, height_locked],
+            )
+            .unwrap();
+        assert_eq!(balance(&db, id, Some(1_100)).unwrap().unlocked_atomic, 50);
+        let rows = spendable_rows(&db, id, 1_100).unwrap();
+        assert_eq!(rows.len(), 1);
+        assert_eq!(rows[0].id, height_locked);
+
+        add_block(&db, id, 1_059, 2_000_000_120);
+        assert_eq!(balance(&db, id, Some(1_100)).unwrap().unlocked_atomic, 850);
+        assert_eq!(spendable_rows(&db, id, 1_100).unwrap().len(), 2);
     }
 
-    /// Timestamp timelocks cannot be judged from height; treat as locked.
+    /// Balance and selection judge timestamp locks against the chain's adjusted time.
     #[test]
-    fn timestamp_timelocks_are_treated_as_locked() {
-        assert!(!is_unlocked(100, 1_700_000_000, 999_999));
+    fn timestamp_locked_outputs_unlock_in_balance_and_selection() {
+        let (db, id) = db_with_identity();
+        let o = add_output(&db, id, 800, 1_000, true);
+        add_blocks(&db, id, 60, 2_000_000_000);
+        // Adjusted time = 2_000_000_120; leeway 60 s (height 1_000 predates v2)
+        db.conn()
+            .execute(
+                "UPDATE outputs SET additional_timelock = ?1 WHERE id = ?2",
+                params![2_000_000_181i64, o],
+            )
+            .unwrap();
+        assert_eq!(balance(&db, id, Some(1_100)).unwrap().unlocked_atomic, 0);
+        assert!(spendable_rows(&db, id, 1_100).unwrap().is_empty());
+
+        db.conn()
+            .execute(
+                "UPDATE outputs SET additional_timelock = ?1 WHERE id = ?2",
+                params![2_000_000_180i64, o],
+            )
+            .unwrap();
+        assert_eq!(balance(&db, id, Some(1_100)).unwrap().unlocked_atomic, 800);
+        assert_eq!(spendable_rows(&db, id, 1_100).unwrap().len(), 1);
     }
 
     /// With an unknown chain tip the unlocked balance must be 0.
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
index 03d509691..05e340784 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
@@ -102,10 +102,26 @@ pub fn set_db(db: Db, db_name: &str) -> Result<()> {
     Ok(())
 }
 
-pub fn set_daemon(daemon: Daemon, network: Network) {
-    DAEMON.with(|c| *c.borrow_mut() = Some(daemon));
-    DAEMON_NETWORK.with(|n| n.set(Some(network)));
-    bump_daemon_generation();
+/// Selects the node; an empty URL disables it.
+///
+/// The old node is dropped before connecting, so a replaced or disabled node gets
+/// no further requests even if the new one fails. Last selection wins, as with
+/// wallet2::set_daemon: a slower earlier connect that finishes after a later
+/// selection or clear is discarded.
+pub async fn select_node(url: &str) -> Result<()> {
+    clear_daemon();
+    if url.trim().is_empty() {
+        return Ok(());
+    }
+    let selection = daemon_generation();
+    let (daemon, network) = crate::network::connect(url).await?;
+    if daemon_generation() == selection {
+        DAEMON.with(|c| *c.borrow_mut() = Some(daemon));
+        DAEMON_NETWORK.with(|n| n.set(Some(network)));
+        crate::network::remember_node_url(url);
+        bump_daemon_generation();
+    }
+    Ok(())
 }
 
 /// Wallet and node must be on the same network. A testnet wallet on a mainnet
@@ -129,9 +145,11 @@ pub fn daemon_network() -> Option {
 }
 
 /// Disconnects the node. A borrowed client is discarded on return via the generation check.
+/// Also invalidates a pending `select_node`.
 pub fn clear_daemon() {
     DAEMON.with(|c| *c.borrow_mut() = None);
     DAEMON_NETWORK.with(|n| n.set(None));
+    crate::network::forget_node_url();
     bump_daemon_generation();
 }
 
@@ -143,11 +161,9 @@ pub fn open_db_name() -> Option {
 pub fn close() -> Result<()> {
     assert_idle("closeWallet")?;
     DB.with(|c| *c.borrow_mut() = None);
-    DAEMON.with(|c| *c.borrow_mut() = None);
-    DAEMON_NETWORK.with(|n| n.set(None));
     DB_NAME.with(|c| *c.borrow_mut() = None);
     bump_generation();
-    bump_daemon_generation();
+    clear_daemon();
     Ok(())
 }
 
@@ -162,10 +178,16 @@ pub fn with_db(f: impl FnOnce(&mut Db) -> Result) -> Result {
 }
 
 /// Read-only borrow.
+///
+/// While an async operation has the database checked out, reports WALLET_BUSY,
+/// not WALLET_NOT_OPEN: the host treats the latter as lost state and reopens.
 pub fn with_db_read(f: impl FnOnce(&Db) -> Result) -> Result {
     DB.with(|c| {
         let slot = c.borrow();
-        let db = slot.as_ref().ok_or_else(not_open)?;
+        let Some(db) = slot.as_ref() else {
+            assert_idle("walletRead")?;
+            return Err(not_open());
+        };
         f(db)
     })
 }
@@ -310,6 +332,118 @@ mod tests {
         }
     }
 
+    /// reqwest needs a Tokio reactor; current-thread keeps the thread_locals shared.
+    fn block_on(f: F) -> F::Output {
+        tokio::runtime::Builder::new_current_thread()
+            .enable_all()
+            .build()
+            .expect("Tokio runtime")
+            .block_on(f)
+    }
+
+    /// Minimal mainnet node: every JSON-RPC call gets the genesis hash, after `delay`.
+    fn fake_node(delay: std::time::Duration) -> String {
+        use std::io::{Read, Write};
+        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
+        let url = format!("http://{}", listener.local_addr().unwrap());
+        std::thread::spawn(move || {
+            for stream in listener.incoming() {
+                let Ok(mut stream) = stream else { continue };
+                let mut request = Vec::new();
+                let mut buf = [0u8; 4096];
+                // Read the headers, then the body by Content-Length.
+                let body_len = loop {
+                    let Ok(n) = stream.read(&mut buf) else {
+                        break None;
+                    };
+                    if n == 0 {
+                        break None;
+                    }
+                    request.extend_from_slice(&buf[..n]);
+                    let text = String::from_utf8_lossy(&request).to_lowercase();
+                    if let Some(end) = text.find("\r\n\r\n") {
+                        let len = text
+                            .lines()
+                            .find_map(|l| l.strip_prefix("content-length:"))
+                            .and_then(|v| v.trim().parse::().ok())
+                            .unwrap_or(0);
+                        break Some(end + 4 + len);
+                    }
+                };
+                let Some(total) = body_len else { continue };
+                while request.len() < total {
+                    match stream.read(&mut buf) {
+                        Ok(0) | Err(_) => break,
+                        Ok(n) => request.extend_from_slice(&buf[..n]),
+                    }
+                }
+                std::thread::sleep(delay);
+                let body = r#"{"jsonrpc":"2.0","id":0,"result":"418015bb9ae982a1975da7d79277c2705727a56894ba0fb246adaabb1f4632e3"}"#;
+                let _ = write!(
+                    stream,
+                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+                    body.len()
+                );
+            }
+        });
+        url
+    }
+
+    /// Last selection wins, as with wallet2::set_daemon: an earlier connect
+    /// finishing after a later one must not install its node.
+    #[test]
+    fn a_slower_earlier_node_selection_does_not_win() {
+        let slow = fake_node(std::time::Duration::from_millis(400));
+        let fast = fake_node(std::time::Duration::ZERO);
+        block_on(async {
+            let later = async {
+                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+                select_node(&fast).await
+            };
+            let (a, b) = tokio::join!(select_node(&slow), later);
+            a.expect("slow connect");
+            b.expect("fast connect");
+        });
+        assert_eq!(crate::network::current_node_url(), Some(fast));
+        assert_eq!(daemon_network(), Some(Network::Mainnet));
+        assert!(DAEMON.with(|c| c.borrow().is_some()));
+    }
+
+    /// Disabling the node while a connect is pending keeps it disabled.
+    #[test]
+    fn clearing_the_node_cancels_a_pending_selection() {
+        let slow = fake_node(std::time::Duration::from_millis(300));
+        block_on(async {
+            let clear = async {
+                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+                clear_daemon();
+            };
+            let (r, ()) = tokio::join!(select_node(&slow), clear);
+            r.expect("connect");
+        });
+        assert!(crate::network::current_node_url().is_none());
+        assert!(daemon_network().is_none());
+        assert!(DAEMON.with(|c| c.borrow().is_none()));
+    }
+
+    /// A read during an async step is BUSY, not NOT_OPEN; the host reopens on the latter.
+    #[test]
+    fn reads_during_an_async_operation_report_busy() {
+        open_memory_db();
+        let node = fake_node(std::time::Duration::ZERO);
+        block_on(async {
+            select_node(&node).await.expect("connect");
+            let code = with_db_and_daemon(|db, daemon| async move {
+                let code = with_db_read(|_| Ok(())).unwrap_err().code;
+                (db, daemon, Ok(code))
+            })
+            .await
+            .expect("operation");
+            assert_eq!(code, ErrorCode::WalletBusy);
+        });
+        with_db_read(|_| Ok(())).expect("readable after the operation");
+    }
+
     /// Closing invalidates an in-flight client borrow, so it cannot restore
     /// the old node when it finishes.
     #[test]
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
index 678d72987..e7dd67faa 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
@@ -318,8 +318,9 @@ pub async fn durability_barrier() -> Result<()> {
     Ok(())
 }
 
+/// Poisoned pool: only a fresh Worker can reopen storage.
 #[cfg(target_arch = "wasm32")]
-fn requires_worker_restart() -> bool {
+pub fn requires_worker_restart() -> bool {
     VFS_UTIL.with(|slot| {
         slot.borrow()
             .as_ref()
@@ -328,7 +329,7 @@ fn requires_worker_restart() -> bool {
 }
 
 #[cfg(not(target_arch = "wasm32"))]
-fn requires_worker_restart() -> bool {
+pub fn requires_worker_restart() -> bool {
     false
 }
 
@@ -376,6 +377,14 @@ mod tests {
         assert!(!delete().unwrap());
     }
 
+    // Native storage has no pool to poison, so the restart signal stays clear
+    // and the barrier passes.
+    #[test]
+    fn healthy_storage_needs_no_worker_restart() {
+        assert!(!requires_worker_restart());
+        assert!(futures_lite::future::block_on(durability_barrier()).is_ok());
+    }
+
     #[test]
     fn memory_database_always_opens() {
         assert!(open_connection(":memory:").is_ok());
diff --git a/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs
index 0dc93e7d6..838d0b2c9 100644
--- a/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs
@@ -22,6 +22,9 @@ fn node() -> Option {
         .filter(|s| !s.trim().is_empty())
 }
 
+// `network::remember_node_url` after `connect` enables the batch block fetch, as
+// `runtime::select_node` does.
+
 /// Native transport uses `reqwest`, which needs a Tokio reactor;
 /// `futures_lite::block_on` panics with "there is no reactor running".
 fn block_on(f: F) -> F::Output {
@@ -42,6 +45,7 @@ fn connects_and_reads_the_chain_tip() {
 
     block_on(async {
         let (daemon, _) = network::connect(&url).await.expect("connect to node");
+        network::remember_node_url(&url);
         let tip = sync::chain_tip(&daemon).await.expect("fetch chain tip");
         println!("chain tip = {tip}");
         assert!(
@@ -69,6 +73,7 @@ fn scans_real_blocks_without_false_alarms() {
 
     block_on(async {
         let (daemon, _) = network::connect(&url).await.expect("connect to node");
+        network::remember_node_url(&url);
         let tip = sync::chain_tip(&daemon).await.expect("fetch chain tip");
 
         // Start 200 blocks below the tip: enough to hit transactions, still fast.
@@ -131,6 +136,7 @@ fn scans_a_real_wallet_if_view_keys_are_supplied() {
 
     block_on(async {
         let (daemon, _) = network::connect(&url).await.expect("connect to node");
+        network::remember_node_url(&url);
         let tip = sync::chain_tip(&daemon).await.expect("fetch chain tip");
 
         let mut db = wallet::Db::open(":memory:", keys::parse_network("mainnet").unwrap())
@@ -193,6 +199,7 @@ fn rewind_actually_rolls_back_and_requeues() {
 
     block_on(async {
         let (daemon, _) = network::connect(&url).await.expect("connect to node");
+        network::remember_node_url(&url);
         let tip = sync::chain_tip(&daemon).await.expect("fetch chain tip");
         let start = tip.saturating_sub(50);
 

From 208bd65d56d75b128e3fb3d0d92c130305be28fa Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Sat, 17 Oct 2026 20:54:23 +0800
Subject: [PATCH 50/97] docs(zcash): describe signer redaction and accepted
 outputs accurately

---
 .../zcash/crates/zcash-keys-runtime/src/sign.rs    |  7 ++++---
 .../zcash/crates/zcash-runtime/src/send.rs         | 14 ++++++++------
 2 files changed, 12 insertions(+), 9 deletions(-)

diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
index 25ef937d6..65c0b28e9 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
@@ -174,9 +174,10 @@ pub fn sign_pczt_with_account_keys(
 
 /// The copy of a PCZT sent to a hardware signer.
 ///
-/// Drops what a signer doesn't need: Sapling `bsk` (the IO Finalizer sets it
-/// even on an empty bundle) and proving fields (witnesses, dummy keys, proofs,
-/// binding keys), matching upstream `redact_pczt_for_signer` (compact view).
+/// A subset of upstream `redact_pczt_for_signer`'s compact-view redaction:
+/// clears the Sapling `bsk` (the IO Finalizer sets it even on an empty bundle)
+/// and, in Orchard and Ironwood, the proof, `bsk`, spend witnesses and dummy
+/// spend keys. Wallet metadata, anchors and resolvable fields are kept as is.
 /// The host keeps the original and combines the device's result into it, so
 /// proving and extraction still have them.
 pub fn redact_for_hardware_signer(pczt_bytes: &[u8]) -> Result> {
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
index 16543fb58..98abe030b 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
@@ -1875,12 +1875,14 @@ mod owned_output_tests {
         mark_owned_outputs(pczt, &ours(), &derivation(), 133).unwrap()
     }
 
-    /// Mirrors the firmware's per-output acceptance (firmware-pro2
-    /// app/zcash/sign_pczt.py `_validate_orchard_protocol_outputs` and
-    /// signer_parse.rs): an output is accepted if it is an unrecoverable
-    /// fabricated zero output with nothing attached, carries a path whose
-    /// fingerprint/schema match and whose recipient the account FVK owns, carries
-    /// a `user_address`, or is a zero-valued output with no ock and no memo.
+    /// What a hardware signer needs to accept each Orchard-protocol output:
+    /// - a padding output the sender cannot recover must be zero-valued, in a
+    ///   bundle without cross-address, with no ock, ZIP-32 derivation or
+    ///   `user_address`;
+    /// - a wallet-owned output carries a ZIP-32 derivation matching the
+    ///   account's seed fingerprint and path, to a recipient its FVK owns;
+    /// - a payment carries a `user_address`;
+    /// - otherwise only a zero-valued output with no ock and an empty memo.
     fn firmware_rejection(bundle: &Bundle, ironwood: bool) -> Option {
         let fvk = ours();
         for (index, action) in bundle.actions().iter().enumerate() {

From 10fae0b925185a795aa11a3ae250e65bec767170 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Mon, 19 Oct 2026 02:48:23 +0800
Subject: [PATCH 51/97] fix: simplify privacy runtimes and preserve transaction
 identity

---
 chain-runtimes/monero/README.md               |  29 +-
 .../crates/monero-runtime/src/bindgen.rs      |  48 +-
 .../monero/crates/monero-runtime/src/error.rs |   2 +-
 .../monero/crates/monero-runtime/src/pool.rs  | 350 ++++++--
 .../monero/crates/monero-runtime/src/query.rs | 108 +--
 .../monero/crates/monero-runtime/src/scan.rs  |  11 +-
 .../crates/monero-runtime/src/schema.rs       |  16 -
 .../monero/crates/monero-runtime/src/spend.rs | 387 ++-------
 .../monero/crates/monero-runtime/src/sync.rs  |  71 +-
 chain-runtimes/monero/scripts/smoke.js        |   5 -
 chain-runtimes/zcash/README.md                |  39 +-
 .../zcash/crates/zcash-runtime/src/account.rs |   4 +-
 .../zcash/crates/zcash-runtime/src/bindgen.rs | 144 +---
 .../zcash/crates/zcash-runtime/src/error.rs   |  13 -
 .../zcash/crates/zcash-runtime/src/guard.rs   | 288 -------
 .../zcash/crates/zcash-runtime/src/history.rs |  35 +-
 .../zcash/crates/zcash-runtime/src/lib.rs     |   1 -
 .../zcash/crates/zcash-runtime/src/network.rs |   2 +-
 .../zcash/crates/zcash-runtime/src/send.rs    | 789 +++++++-----------
 .../crates/zcash-runtime/src/tx_state.rs      | 528 ++++++------
 .../zcash/crates/zcash-runtime/src/wallet.rs  |   2 +-
 21 files changed, 1112 insertions(+), 1760 deletions(-)
 delete mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/guard.rs

diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md
index 102393329..8b84ba870 100644
--- a/chain-runtimes/monero/README.md
+++ b/chain-runtimes/monero/README.md
@@ -42,11 +42,18 @@ releases to `latest`. Branches other than `main` can publish alpha versions only
    block; a mismatch fails with `NODE_NETWORK_MISMATCH`. `chainTip` works without an
    open wallet and returns `network`; check it before picking a birthday.
 3. **An `unknown` broadcast is not a failure.** The send is recorded and its inputs
-   marked spent before broadcasting; pool checks and scanning settle it. Never report
-   it as failed or prompt a resend.
+   marked spent before broadcasting; pool checks and scanning settle it. Do not
+   translate an unclear broadcast result into a failure or prompt a resend.
 4. **The host schedules sync.** `syncStep` scans at most `maxBlocks` and returns.
+   Its existing pool refresh includes previously failed own sends. A matching
+   transaction seen in the pool restores the record and released inputs in one
+   SQLite transaction, unless a later local spend already owns an input.
+   `sendsRestored` reports those changes so the host can refresh balances/history.
 5. **Register subaddresses before use.** Funds to unregistered subaddresses go
    undetected.
+6. **Local management does not require a live tip.** Deletion needs only the local
+   database. For `rewindTo`, pass the last locally observed tip; normal sync fetches
+   a fresh one later. Rewind, cursor updates and range requeue commit together.
 
 ## API
 
@@ -73,21 +80,18 @@ rewindTo(accountId, height, tip)                destructive
 balance(accountId, chainTip?) / history(accountId, limit, offset)
 transactionDetails(accountId, txid)
 
-prepareTransaction(accountId, recipientsJson, maxSend, reservationId, chainTip, priority)
+prepareTransaction(accountId, recipientsJson, maxSend, chainTip, priority)
 verifyTransaction(signableHex, reviewJson)
-markReservationSigned(reservationId, expectedInputs)
 signTransaction(signableHex, spendPrivateKeyHex, reviewJson)
-broadcastTransaction(accountId, rawHex, reservationId, chainTip, outgoingAtomic?, changeAtomic?)
-releaseReservation(reservationId)
+broadcastTransaction(accountId, rawHex, chainTip, outgoingAtomic?, changeAtomic?)
 diagDatabase()
 ```
 
 ### Sending
 
 ```
-prepareTransaction      select and reserve inputs, build; no spend key
+prepareTransaction      select inputs, build; no spend key
 verifyTransaction       check recipient, amount, fee and change against the review
-markReservationSigned   claim the reserved inputs for this review
 signTransaction         verify again, then sign; no network, no DB
 broadcastTransaction    record, then broadcast → { txid, broadcast: accepted | unknown }
 ```
@@ -98,8 +102,13 @@ broadcastTransaction    record, then broadcast → { txid, broadcast: accepted |
 - `BROADCAST_REJECTED` is thrown only when the node explicitly rejects a first
   broadcast for a reason other than double spend; the record is undone and the
   inputs released.
-- Unsigned reservations expire after 1 hour, signed ones after 24 hours. Call
-  `releaseReservation` when the user cancels.
+- Inputs are not reserved between prepare and broadcast. Two sends built from
+  the same inputs both sign, but only the first broadcast is recorded; the second
+  is refused with `inputAlreadySpent`. Inputs of a send the node never received
+  are released after the propagation timeout and an explicit missing response,
+  and can be spent again. Failed sends remain eligible for normal pool refresh;
+  response transaction hashes are checked against their serialized bodies before
+  updating local input ownership.
 - The scanner derives RingCT output indexes itself and fails with
   `RINGCT_INDEX_MISMATCH` when the node's claim differs.
 
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
index 57c041a90..7a1f4b58d 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -302,23 +302,6 @@ pub fn validate_address(network: &str, address: &str) -> std::result::Result std::result::Result {
-    let n = runtime::with_db(|db| spend::mark_signed(db, reservation_id, expected_inputs))?;
-    json(serde_json::json!({ "marked": n }))
-}
-
-/// Release a reservation (user cancelled or construction failed).
-#[wasm_bindgen(js_name = releaseReservation)]
-pub fn release_reservation(reservation_id: &str) -> std::result::Result {
-    let n = runtime::with_db(|db| spend::release(db, reservation_id))?;
-    json(serde_json::json!({ "released": n }))
-}
-
 /// Hand network requests to the host instead of `fetch`ing in wasm.
 ///
 /// `handler` is `(url, contentType, body: Uint8Array) => Promise`;
@@ -345,7 +328,6 @@ pub fn diag_database() -> std::result::Result {
             "transactions",
             "blocks",
             "scan_ranges",
-            "locked_outputs",
             "possible_spends",
         ] {
             let n: i64 = db
@@ -386,7 +368,7 @@ fn decode_hex(value: &str, field: &str) -> Result> {
 
 // ── Spend path ─────────────────────────────────────────────────────────────
 
-/// Select inputs, build and reserve. Needs no spend private key; does not broadcast.
+/// Select inputs and build. Needs no spend private key; does not broadcast.
 ///
 /// `recipientsJson` is `[{ "address": "...", "amountAtomic": "1000000000000" }]`.
 ///
@@ -394,18 +376,17 @@ fn decode_hex(value: &str, field: &str) -> Result> {
 /// spendable total minus fee; the passed amount is ignored. Merely omitting change
 /// would fold the remainder into the fee.
 ///
-/// Returns `{ reservationId, signableHex, feeAtomic, amountAtomic, changeAtomic,
-/// inputsAtomic, inputCount }`. `feeAtomic` and `amountAtomic` are what the
+/// Returns `{ signableHex, feeAtomic, amountAtomic, changeAtomic, inputsAtomic,
+/// inputCount }`. `feeAtomic` and `amountAtomic` are what the
 /// transaction will use: the confirmation page shows them and signing keeps them.
 ///
-/// Failure leaves no reservation. On success the host must call `signTransaction` +
-/// `broadcastTransaction`, or `releaseReservation`; otherwise the inputs stay locked.
+/// Inputs are not reserved: a second prepare before broadcast may select the same
+/// ones, and broadcast then refuses the later transaction as `inputAlreadySpent`.
 #[wasm_bindgen(js_name = prepareTransaction)]
 pub async fn prepare_transaction(
     account_id: i64,
     recipients_json: &str,
     max_send: bool,
-    reservation_id: &str,
     chain_tip: u64,
     priority: &str,
 ) -> std::result::Result {
@@ -427,11 +408,10 @@ pub async fn prepare_transaction(
     }
 
     let fee_priority = spend::parse_priority(priority)?;
-    let reservation = reservation_id.to_owned();
 
-    let v = runtime::with_db_and_daemon(move |mut db, daemon| async move {
+    let v = runtime::with_db_and_daemon(move |db, daemon| async move {
         let r = spend::prepare_for_host(
-            &mut db,
+            &db,
             &daemon,
             account_id,
             &recipients
@@ -439,7 +419,6 @@ pub async fn prepare_transaction(
                 .map(|r| (r.address.as_str(), r.amount_atomic.as_str()))
                 .collect::>(),
             max_send,
-            &reservation,
             chain_tip,
             fee_priority,
         )
@@ -486,13 +465,11 @@ pub fn verify_transaction(
 pub async fn broadcast_transaction(
     account_id: i64,
     raw_hex: &str,
-    reservation_id: &str,
     chain_tip: u64,
     outgoing_atomic: Option,
     change_atomic: Option,
 ) -> std::result::Result {
     let raw = raw_hex.to_owned();
-    let reservation = reservation_id.to_owned();
     // Decimal strings: u64 cannot cross the host bridge. Used only for display and
     // balance; malformed values count as absent.
     let amounts = spend::SentAmounts {
@@ -500,16 +477,7 @@ pub async fn broadcast_transaction(
         change_atomic: change_atomic.and_then(|a| a.parse::().ok()),
     };
     let v = runtime::with_db_and_daemon(move |db, daemon| async move {
-        let r = spend::broadcast_signed(
-            &db,
-            &daemon,
-            account_id,
-            &raw,
-            &reservation,
-            chain_tip,
-            amounts,
-        )
-        .await;
+        let r = spend::broadcast_signed(&db, &daemon, account_id, &raw, chain_tip, amounts).await;
         (db, daemon, r)
     })
     .await?;
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/error.rs b/chain-runtimes/monero/crates/monero-runtime/src/error.rs
index cedb98ec7..d7ae5ee02 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/error.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/error.rs
@@ -64,7 +64,7 @@ pub enum ErrorCode {
     NetworkError,
     /// Node response does not decode (bad epee/JSON). Params: `{ operation }`
     MalformedNodeResponse,
-    /// Node explicitly rejected the transaction (double spend, low fee, ...). Input reservations are released.
+    /// Node explicitly rejected the transaction (double spend, low fee, ...). The fresh record is undone and its inputs released.
     BroadcastRejected,
 
     // ── Storage ────────────────────────────────────────────────────────────
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/pool.rs b/chain-runtimes/monero/crates/monero-runtime/src/pool.rs
index 11aa4de57..5a0071793 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/pool.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/pool.rs
@@ -7,10 +7,11 @@
 //! Confirmed sends are handled by scanning via key images, which sets the height
 //! and clears the failed flag.
 
+use monero_wallet::transaction::{Input, Transaction};
 use rusqlite::params;
 use serde_json::Value;
 
-use crate::error::{db_err, Result};
+use crate::error::{db_err, ErrorCode, Result};
 use crate::network::Daemon;
 use crate::wallet::{now_secs, Db};
 
@@ -22,13 +23,13 @@ const POOL_RECHECK_SECS: i64 = 60;
 
 const RESPONSE_SIZE_LIMIT: usize = 4 * 1024 * 1024;
 
-/// Pending sends to check: past the propagation timeout, not failed, not checked recently.
+/// Own unconfirmed sends, including previously failed ones, due for the normal pool refresh.
 fn due_pending(db: &Db, identity_id: i64, now: i64) -> Result> {
     let mut stmt = db
         .conn()
         .prepare(
             "SELECT txid FROM transactions
-             WHERE identity_id = ?1 AND height IS NULL AND failed = 0
+             WHERE identity_id = ?1 AND height IS NULL AND direction = 'out'
                AND sent_at IS NOT NULL AND sent_at + ?2 <= ?3
                AND (pool_checked_at IS NULL OR pool_checked_at + ?4 <= ?3)",
         )
@@ -52,25 +53,62 @@ fn due_pending(db: &Db, identity_id: i64, now: i64) -> Result> {
         .collect())
 }
 
-/// Transactions the node explicitly reports missing. A malformed response counts
-/// none, so a send is never failed on an unclear answer.
-fn missed_in(response: &str) -> Option> {
-    let v: Value = serde_json::from_str(response).ok()?;
-    if v.get("status").and_then(Value::as_str) != Some("OK") {
+struct PooledTransaction {
+    txid: [u8; 32],
+    key_images: Vec<[u8; 32]>,
+}
+
+struct PoolStatus {
+    missed: Vec<[u8; 32]>,
+    pooled: Vec,
+}
+
+// Validate transaction identities before applying the node's pool observations.
+fn read_pool_status(response: &str) -> Option {
+    let value: Value = serde_json::from_str(response).ok()?;
+    if value.get("status")?.as_str()? != "OK" {
         return None;
     }
-    // epee may omit empty arrays.
-    let Some(missed) = v.get("missed_tx") else {
-        return Some(Vec::new());
+    let hash = |value: &Value| {
+        let bytes = hex::decode(value.as_str()?).ok()?;
+        <[u8; 32]>::try_from(bytes.as_slice()).ok()
     };
-    missed
-        .as_array()?
-        .iter()
-        .map(|h| {
-            let bytes = hex::decode(h.as_str()?).ok()?;
-            <[u8; 32]>::try_from(bytes.as_slice()).ok()
-        })
-        .collect()
+    let mut missed = Vec::new();
+    if let Some(items) = value.get("missed_tx") {
+        for item in items.as_array()? {
+            missed.push(hash(item)?);
+        }
+    }
+    let mut pooled = Vec::new();
+    if let Some(items) = value.get("txs") {
+        for item in items.as_array()? {
+            // Mined transactions are reconciled by the block scanner.
+            if item.get("in_pool").and_then(Value::as_bool) != Some(true) {
+                continue;
+            }
+            let txid = hash(item.get("tx_hash")?)?;
+            let raw = hex::decode(item.get("as_hex")?.as_str()?).ok()?;
+            let mut remaining = raw.as_slice();
+            let tx = Transaction::read(&mut remaining).ok()?;
+            if !remaining.is_empty() || tx.hash() != txid || missed.contains(&txid) {
+                return None;
+            }
+            let key_images = tx
+                .prefix()
+                .inputs
+                .iter()
+                .filter_map(|input| match input {
+                    Input::ToKey { key_image, .. } => Some(key_image.to_bytes()),
+                    _ => None,
+                })
+                .collect::>();
+            if key_images.is_empty() {
+                return None;
+            }
+            pooled.push(PooledTransaction { txid, key_images });
+        }
+    }
+    Some(PoolStatus { missed, pooled })
 }
 
 fn mark_checked(db: &Db, identity_id: i64, txids: &[[u8; 32]], now: i64) -> Result<()> {
@@ -89,54 +127,119 @@ fn mark_checked(db: &Db, identity_id: i64, txids: &[[u8; 32]], now: i64) -> Resu
 ///
 /// `spent_in_txid` is kept to compute the failed transaction's amount; a later
 /// spend of the output overwrites it.
-pub(crate) fn mark_failed(db: &Db, identity_id: i64, txid: &[u8; 32]) -> Result<()> {
+pub(crate) fn mark_failed(db: &Db, identity_id: i64, txid: &[u8; 32]) -> Result {
     let tx = db
         .conn()
         .unchecked_transaction()
         .map_err(|e| db_err("beginMarkFailed", e))?;
-    tx.execute(
-        "UPDATE transactions SET failed = 1
-         WHERE identity_id = ?1 AND txid = ?2 AND height IS NULL",
-        params![identity_id, txid.as_slice()],
-    )
-    .map_err(|e| db_err("markSendFailed", e))?;
+    let changed = tx
+        .execute(
+            "UPDATE transactions SET failed = 1
+         WHERE identity_id = ?1 AND txid = ?2 AND height IS NULL AND failed = 0",
+            params![identity_id, txid.as_slice()],
+        )
+        .map_err(|e| db_err("markSendFailed", e))?;
+    if changed == 0 {
+        return Ok(false);
+    }
     tx.execute(
         "UPDATE outputs SET spent_at_height = NULL
          WHERE identity_id = ?1 AND spent_in_txid = ?2",
         params![identity_id, txid.as_slice()],
     )
     .map_err(|e| db_err("releaseFailedInputs", e))?;
-    tx.commit().map_err(|e| db_err("commitMarkFailed", e))
+    tx.commit().map_err(|e| db_err("commitMarkFailed", e))?;
+    Ok(true)
 }
 
-/// Query the node once and mark missing sends failed; returns how many.
-///
-/// Changes nothing if the node is unreachable or the response is malformed: only
-/// an explicit "missing" fails a send.
-pub async fn check_pending(db: &Db, daemon: &Daemon, identity_id: i64) -> Result {
+// Restore the existing record and its inputs atomically. A later local spend
+// retains ownership until normal scanning resolves the conflict.
+fn restore_pending(db: &Db, identity_id: i64, pooled: &PooledTransaction) -> Result {
+    let tx = db
+        .conn()
+        .unchecked_transaction()
+        .map_err(|e| db_err("beginRestorePending", e))?;
+    let exists: bool = tx
+        .query_row(
+            "SELECT EXISTS(SELECT 1 FROM transactions
+         WHERE identity_id = ?1 AND txid = ?2 AND height IS NULL AND sent_at IS NOT NULL)",
+            params![identity_id, pooled.txid.as_slice()],
+            |row| row.get(0),
+        )
+        .map_err(|e| db_err("findPendingSend", e))?;
+    if !exists {
+        return Ok(false);
+    }
+    if let Err(error) =
+        crate::spend::check_inputs_owned(&tx, identity_id, &pooled.txid, &pooled.key_images)
+    {
+        if error.code == ErrorCode::InvalidRequest {
+            return Ok(false);
+        }
+        return Err(error);
+    }
+    let mut changed = tx
+        .execute(
+            "UPDATE transactions SET failed = 0
+         WHERE identity_id = ?1 AND txid = ?2 AND failed <> 0",
+            params![identity_id, pooled.txid.as_slice()],
+        )
+        .map_err(|e| db_err("restorePendingSend", e))?;
+    for key_image in &pooled.key_images {
+        changed += tx
+            .execute(
+                "UPDATE outputs SET spent_at_height = 0, spent_in_txid = ?2
+             WHERE identity_id = ?1 AND key_image = ?3 AND spent_at_height IS NULL",
+                params![identity_id, pooled.txid.as_slice(), key_image.as_slice()],
+            )
+            .map_err(|e| db_err("restorePendingInput", e))?;
+    }
+    tx.commit().map_err(|e| db_err("commitRestorePending", e))?;
+    Ok(changed > 0)
+}
+
+fn apply_pool_response(
+    db: &Db,
+    identity_id: i64,
+    due: &[[u8; 32]],
+    response: &str,
+    now: i64,
+) -> Result<(usize, usize)> {
+    let Some(status) = read_pool_status(response) else {
+        return Ok((0, 0));
+    };
+    let mut failed = 0;
+    let mut restored = 0;
+    for txid in status.missed.iter().filter(|txid| due.contains(txid)) {
+        failed += usize::from(mark_failed(db, identity_id, txid)?);
+    }
+    for pooled in status.pooled.iter().filter(|tx| due.contains(&tx.txid)) {
+        restored += usize::from(restore_pending(db, identity_id, pooled)?);
+    }
+    mark_checked(db, identity_id, due, now)?;
+    Ok((failed, restored))
+}
+
+/// Refresh own unconfirmed sends, returning (newly failed, restored).
+/// Unreachable nodes and malformed responses leave local transaction data unchanged.
+pub async fn check_pending(db: &Db, daemon: &Daemon, identity_id: i64) -> Result<(usize, usize)> {
     let now = now_secs();
     let due = due_pending(db, identity_id, now)?;
     if due.is_empty() {
-        return Ok(0);
+        return Ok((0, 0));
     }
     let hashes: Vec = due.iter().map(hex::encode).collect();
-    let request = serde_json::json!({ "txs_hashes": hashes, "prune": true }).to_string();
+    // Full transactions let the upstream parser verify txids and recover the
+    // exact key images without adding another persistent input index.
+    let request =
+        serde_json::json!({ "txs_hashes": hashes, "prune": false, "split": false }).to_string();
     let Ok(response) = daemon
         .rpc_call("get_transactions", Some(request), RESPONSE_SIZE_LIMIT)
         .await
     else {
-        return Ok(0);
-    };
-    let Some(missed) = missed_in(&response) else {
-        return Ok(0);
+        return Ok((0, 0));
     };
-    mark_checked(db, identity_id, &due, now)?;
-    let mut failed = 0;
-    for txid in missed.iter().filter(|t| due.contains(t)) {
-        mark_failed(db, identity_id, txid)?;
-        failed += 1;
-    }
-    Ok(failed)
+    apply_pool_response(db, identity_id, &due, &response, now)
 }
 
 #[cfg(test)]
@@ -212,9 +315,10 @@ mod tests {
             )
             .unwrap();
         assert_eq!(spent_at, None, "output released");
-        assert!(
-            due_pending(&db, id, i64::MAX / 2).unwrap().is_empty(),
-            "failed sends are not rechecked"
+        assert_eq!(
+            due_pending(&db, id, i64::MAX / 2).unwrap(),
+            vec![txid],
+            "failed sends remain eligible for the normal pool refresh"
         );
     }
 
@@ -222,15 +326,151 @@ mod tests {
     fn only_a_clear_answer_from_the_node_counts() {
         let tx = hex::encode([2u8; 32]);
         assert_eq!(
-            missed_in(&format!(r#"{{"status":"OK","missed_tx":["{tx}"]}}"#)),
-            Some(vec![[2u8; 32]])
+            read_pool_status(&format!(r#"{{"status":"OK","missed_tx":["{tx}"]}}"#))
+                .unwrap()
+                .missed,
+            vec![[2u8; 32]]
+        );
+        for response in [
+            r#"{"status":"BUSY","missed_tx":[]}"#,
+            "not json",
+            r#"{"status":"OK","missed_tx":["zz"]}"#,
+            r#"{"status":"OK","txs":[{"in_pool":true}]}"#,
+        ] {
+            assert!(read_pool_status(response).is_none());
+        }
+    }
+
+    fn pooled_send() -> (Db, i64, [u8; 32], String) {
+        use curve25519_dalek::constants::ED25519_BASEPOINT_POINT;
+        use monero_wallet::transaction::{Timelock, TransactionPrefix};
+
+        let tx = Transaction::V2 {
+            prefix: TransactionPrefix {
+                additional_timelock: Timelock::None,
+                inputs: vec![Input::ToKey {
+                    amount: None,
+                    key_offsets: vec![1],
+                    key_image: ED25519_BASEPOINT_POINT.compress().to_bytes().into(),
+                }],
+                outputs: vec![],
+                extra: vec![],
+            },
+            proofs: None,
+        };
+        let txid = tx.hash();
+        let (db, id) = db_with_identity();
+        let output = add_pending_send(&db, id, txid, 0);
+        db.conn()
+            .execute(
+                "UPDATE outputs SET key_image = ?1 WHERE id = ?2",
+                params![ED25519_BASEPOINT_POINT.compress().as_bytes(), output],
+            )
+            .unwrap();
+        db.conn()
+            .execute(
+                "UPDATE transactions SET change_atomic = '35' WHERE txid = ?1",
+                [txid.as_slice()],
+            )
+            .unwrap();
+        let response = serde_json::json!({ "status": "OK", "txs": [{
+            "tx_hash": hex::encode(txid), "in_pool": true, "as_hex": hex::encode(tx.serialize()),
+        }] })
+        .to_string();
+        (db, id, txid, response)
+    }
+
+    fn failed(db: &Db, txid: &[u8; 32]) -> bool {
+        db.conn()
+            .query_row(
+                "SELECT failed FROM transactions WHERE txid = ?1",
+                [txid.as_slice()],
+                |row| row.get(0),
+            )
+            .unwrap()
+    }
+
+    #[test]
+    fn a_failed_send_seen_again_restores_inputs_and_pending_change_together() {
+        let (db, id, txid, response) = pooled_send();
+        mark_failed(&db, id, &txid).unwrap();
+        assert_eq!(
+            crate::query::balance(&db, id, Some(1000))
+                .unwrap()
+                .total_atomic,
+            700
+        );
+        assert_eq!(
+            apply_pool_response(&db, id, &[txid], &response, 10_000).unwrap(),
+            (0, 1)
+        );
+        assert!(!failed(&db, &txid));
+        let balance = crate::query::balance(&db, id, Some(1000)).unwrap();
+        assert_eq!((balance.total_atomic, balance.unlocked_atomic), (35, 0));
+        assert_eq!(balance.pending_change_atomic, 35);
+        assert_eq!(
+            apply_pool_response(&db, id, &[txid], &response, 10_060).unwrap(),
+            (0, 0)
+        );
+    }
+
+    #[test]
+    fn pool_refresh_does_not_overwrite_a_later_input_owner() {
+        let (db, id, txid, response) = pooled_send();
+        mark_failed(&db, id, &txid).unwrap();
+        db.conn()
+            .execute(
+                "UPDATE outputs SET spent_at_height = 900, spent_in_txid = ?1",
+                [[9u8; 32].as_slice()],
+            )
+            .unwrap();
+        assert_eq!(
+            apply_pool_response(&db, id, &[txid], &response, 10_000).unwrap(),
+            (0, 0)
         );
+        assert!(failed(&db, &txid));
+        let owner: Vec = db
+            .conn()
+            .query_row("SELECT spent_in_txid FROM outputs", [], |row| row.get(0))
+            .unwrap();
+        assert_eq!(owner, [9u8; 32]);
+    }
+
+    #[test]
+    fn malformed_or_unrequested_pool_transactions_do_not_restore_a_send() {
+        let (db, id, txid, response) = pooled_send();
+        mark_failed(&db, id, &txid).unwrap();
+        let mut value: Value = serde_json::from_str(&response).unwrap();
+        value["txs"][0]["tx_hash"] = serde_json::json!(hex::encode([9u8; 32]));
+        assert_eq!(
+            apply_pool_response(&db, id, &[txid], &value.to_string(), 10_000).unwrap(),
+            (0, 0)
+        );
+        assert!(failed(&db, &txid));
+        assert_eq!(
+            apply_pool_response(&db, id, &[[8u8; 32]], &response, 10_000).unwrap(),
+            (0, 0)
+        );
+        assert!(failed(&db, &txid));
+    }
+
+    #[test]
+    fn a_failed_input_write_rolls_back_the_transaction_status() {
+        let (db, id, txid, response) = pooled_send();
+        mark_failed(&db, id, &txid).unwrap();
+        db.conn()
+            .execute_batch(
+                "CREATE TRIGGER refuse_input BEFORE UPDATE OF spent_at_height ON outputs
+            BEGIN SELECT RAISE(ABORT, 'synthetic write failure'); END;",
+            )
+            .unwrap();
+        assert!(apply_pool_response(&db, id, &[txid], &response, 10_000).is_err());
+        assert!(failed(&db, &txid));
         assert_eq!(
-            missed_in(r#"{"status":"OK","txs":[{"in_pool":true}]}"#),
-            Some(vec![])
+            crate::query::balance(&db, id, Some(1000))
+                .unwrap()
+                .total_atomic,
+            700
         );
-        assert_eq!(missed_in(r#"{"status":"BUSY","missed_tx":[]}"#), None);
-        assert_eq!(missed_in("not json"), None);
-        assert_eq!(missed_in(r#"{"status":"OK","missed_tx":["zz"]}"#), None);
     }
 }
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/query.rs b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
index 5ef9435fd..93452decb 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/query.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
@@ -31,10 +31,8 @@ const TARGET_SECONDS_V2: u64 = 120;
 pub struct Balance {
     /// Sum of all unspent outputs.
     pub total_atomic: u128,
-    /// Spendable now: past the 10-block lock and any extra timelock, and not reserved.
+    /// Spendable now: past the 10-block lock and any extra timelock.
     pub unlocked_atomic: u128,
-    /// Reserved by in-flight sends. Counted in total, not selectable.
-    pub locked_by_reservation_atomic: u128,
     /// Outputs without a key image that appear in some ring. **May already be
     /// spent** until the host supplies key images; outputs never seen in a ring
     /// are certainly unspent and excluded.
@@ -53,7 +51,6 @@ impl Balance {
         json!({
             "totalAtomic": self.total_atomic.to_string(),
             "unlockedAtomic": self.unlocked_atomic.to_string(),
-            "lockedByReservationAtomic": self.locked_by_reservation_atomic.to_string(),
             "unverifiableAtomic": self.unverifiable_atomic.to_string(),
             "pendingChangeAtomic": self.pending_change_atomic.to_string(),
             "outputsWithoutKeyImage": self.outputs_without_key_image,
@@ -71,39 +68,29 @@ pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result ?2 OR l.signed_at > ?3)
              WHERE o.identity_id = ?1 AND o.spent_at_height IS NULL",
         )
         .map_err(|e| db_err("balanceQuery", e))?;
 
     let rows = stmt
-        .query_map(
-            params![
-                identity_id,
-                crate::spend::reservation_cutoff(),
-                crate::spend::signed_reservation_cutoff()
-            ],
-            |r| {
-                Ok((
-                    r.get::<_, i64>(0)? as u128,
-                    r.get::<_, i64>(1)? as u64,
-                    r.get::<_, i64>(2)? as u64,
-                    r.get::<_, bool>(3)?,
-                    r.get::<_, bool>(4)?,
-                    r.get::<_, bool>(5)?,
-                ))
-            },
-        )
+        .query_map([identity_id], |r| {
+            Ok((
+                r.get::<_, i64>(0)? as u128,
+                r.get::<_, i64>(1)? as u64,
+                r.get::<_, i64>(2)? as u64,
+                r.get::<_, bool>(3)?,
+                r.get::<_, bool>(4)?,
+            ))
+        })
         .map_err(|e| db_err("balanceQuery", e))?;
 
     let mut b = Balance::default();
     for row in rows {
-        let (amount, height, timelock, no_key_image, reserved, maybe_spent) =
+        let (amount, height, timelock, no_key_image, maybe_spent) =
             row.map_err(|e| db_err("balanceQuery", e))?;
         b.total_atomic += amount;
         if no_key_image {
@@ -115,10 +102,6 @@ pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result Result ?2 OR l.signed_at > ?3)
              WHERE o.identity_id = ?1
                AND o.spent_at_height IS NULL
                AND o.key_image IS NOT NULL
-               AND l.output_id IS NULL
              ORDER BY o.amount_atomic DESC",
         )
         .map_err(|e| db_err("spendableRows", e))?;
 
     let rows = stmt
-        .query_map(
-            params![
-                identity_id,
-                crate::spend::reservation_cutoff(),
-                crate::spend::signed_reservation_cutoff()
-            ],
-            |r| {
-                Ok((
-                    r.get::<_, i64>(0)?,
-                    r.get::<_, i64>(1)? as u64,
-                    r.get::<_, i64>(2)? as u64,
-                    r.get::<_, i64>(3)? as u64,
-                    r.get::<_, i64>(4)? as u64,
-                ))
-            },
-        )
+        .query_map([identity_id], |r| {
+            Ok((
+                r.get::<_, i64>(0)?,
+                r.get::<_, i64>(1)? as u64,
+                r.get::<_, i64>(2)? as u64,
+                r.get::<_, i64>(3)? as u64,
+                r.get::<_, i64>(4)? as u64,
+            ))
+        })
         .map_err(|e| db_err("spendableRows", e))?;
 
     let mut out = Vec::new();
@@ -728,48 +702,6 @@ mod tests {
         );
     }
 
-    /// Reserved outputs count toward total but are not selectable, so two
-    /// sends cannot spend the same output.
-    #[test]
-    fn reserved_outputs_are_excluded_from_unlocked_and_from_selection() {
-        let (db, id) = db_with_identity();
-        let a = add_output(&db, id, 500, 10, true);
-        add_output(&db, id, 400, 11, true);
-        db.conn()
-            .execute(
-                "INSERT INTO locked_outputs (output_id, reservation_id, locked_at) VALUES (?1, 'r', ?2)",
-                params![a, crate::wallet::now_secs()],
-            )
-            .unwrap();
-
-        let b = balance(&db, id, Some(100)).unwrap();
-        assert_eq!(b.total_atomic, 900);
-        assert_eq!(b.locked_by_reservation_atomic, 500);
-        assert_eq!(b.unlocked_atomic, 400);
-
-        let spendable = spendable_rows(&db, id, 100).unwrap();
-        assert_eq!(spendable.len(), 1, "reserved outputs must not be selected");
-        assert_eq!(spendable[0].amount_atomic, 400);
-    }
-
-    /// Abandoning the confirm screen does not notify the runtime; expired reservations must release funds.
-    #[test]
-    fn an_expired_reservation_no_longer_holds_its_outputs() {
-        let (db, id) = db_with_identity();
-        let a = add_output(&db, id, 500, 10, true);
-        db.conn()
-            .execute(
-                "INSERT INTO locked_outputs (output_id, reservation_id, locked_at) VALUES (?1, 'r', ?2)",
-                params![a, crate::spend::reservation_cutoff() - 1],
-            )
-            .unwrap();
-
-        let b = balance(&db, id, Some(100)).unwrap();
-        assert_eq!(b.locked_by_reservation_atomic, 0);
-        assert_eq!(b.unlocked_atomic, 500);
-        assert_eq!(spendable_rows(&db, id, 100).unwrap().len(), 1);
-    }
-
     /// Spent outputs drop out of every balance figure.
     #[test]
     fn spent_outputs_leave_the_balance() {
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
index 7abee15a9..adedaca8e 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
@@ -756,7 +756,16 @@ pub fn rewind_to(db: &mut Db, identity_id: i64, height: u64, tip: u64) -> Result
         .conn_mut()
         .transaction()
         .map_err(|e| db_err("beginRewind", e))?;
+    rewind_in_transaction(&tx, identity_id, height, tip)?;
+    tx.commit().map_err(|e| db_err("commitRewind", e))
+}
 
+pub(crate) fn rewind_in_transaction(
+    tx: &rusqlite::Transaction<'_>,
+    identity_id: i64,
+    height: u64,
+    tip: u64,
+) -> Result<()> {
     // Must run before clearing spend marks: that step keeps marks for pending transactions.
     let reorgable_above = height.max(tip.saturating_sub(REORG_WINDOW_BLOCKS));
     tx.execute(
@@ -801,7 +810,7 @@ pub fn rewind_to(db: &mut Db, identity_id: i64, height: u64, tip: u64) -> Result
     )
     .map_err(|e| db_err("rewindBlocks", e))?;
 
-    tx.commit().map_err(|e| db_err("commitRewind", e))
+    Ok(())
 }
 
 #[cfg(test)]
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
index 712ecb665..572045369 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
@@ -224,21 +224,6 @@ CREATE TABLE IF NOT EXISTS transactions (
 );
 CREATE INDEX IF NOT EXISTS idx_transactions_height ON transactions(identity_id, height);
 
--- Outputs reserved by a pending transaction and not selectable again.
---
--- Without this, two in-flight transactions could spend the same output and
--- the second would be rejected by the network.
-CREATE TABLE IF NOT EXISTS locked_outputs (
-    output_id       INTEGER PRIMARY KEY REFERENCES outputs(id) ON DELETE CASCADE,
-    reservation_id  TEXT    NOT NULL,
-    locked_at       INTEGER NOT NULL,
-    -- When the host signed. Unsigned reservations are dropped on the next
-    -- prepare (the user left the confirm screen); signed ones wait for the
-    -- broadcast result or expiry.
-    signed_at       INTEGER
-);
-CREATE INDEX IF NOT EXISTS idx_locked_reservation ON locked_outputs(reservation_id);
-
 -- Possible spends (as in monero-lws).
 --
 -- A view-only wallet cannot recognise its own spends, but a spent output must
@@ -356,7 +341,6 @@ mod tests {
             "scan_ranges",
             "outputs",
             "transactions",
-            "locked_outputs",
             "possible_spends",
         ] {
             let n: i64 = conn
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
index 6cfa13299..f3ef0807d 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -255,138 +255,6 @@ pub fn select_inputs(
     })
 }
 
-/// Unsigned reservations expire after an hour; leaving the confirm screen is not reported here.
-pub const RESERVATION_TTL_SECS: i64 = 60 * 60;
-
-/// Signed reservations that never reached broadcast expire after a day.
-///
-/// Broadcast marks inputs spent and records the send before publishing, so a
-/// signed reservation left here was never sent (rejected on device, cancelled,
-/// killed after signing). Locking it forever would push the next send onto
-/// other inputs, and if the old signature were broadcast later both would
-/// confirm. Released, the same inputs are selected first again, so both
-/// transactions share key images and at most one can confirm.
-pub const SIGNED_RESERVATION_TTL_SECS: i64 = 24 * 60 * 60;
-
-/// Reservations with `locked_at` after this are live.
-pub fn reservation_cutoff() -> i64 {
-    crate::wallet::now_secs() - RESERVATION_TTL_SECS
-}
-
-/// Signed reservations with `signed_at` after this are live.
-pub fn signed_reservation_cutoff() -> i64 {
-    crate::wallet::now_secs() - SIGNED_RESERVATION_TTL_SECS
-}
-
-/// Reserves selected outputs so a second in-flight transaction cannot select them.
-///
-/// Otherwise two transactions could spend the same output and the second would
-/// be rejected by the network.
-pub fn reserve(db: &mut Db, reservation_id: &str, output_ids: &[i64]) -> Result<()> {
-    let now = crate::wallet::now_secs();
-    let tx = db
-        .conn_mut()
-        .transaction()
-        .map_err(|e| db_err("beginReserve", e))?;
-    // Leaving the confirm screen is not reported, so expired reservations are cleared here.
-    tx.execute(
-        "DELETE FROM locked_outputs
-         WHERE (signed_at IS NULL AND locked_at <= ?1) OR signed_at <= ?2",
-        params![
-            now - RESERVATION_TTL_SECS,
-            now - SIGNED_RESERVATION_TTL_SECS
-        ],
-    )
-    .map_err(|e| db_err("expireReservations", e))?;
-    for id in output_ids {
-        // Fails on primary key conflict if already reserved: better to fail
-        // here than build a transaction that will be rejected.
-        tx.execute(
-            "INSERT INTO locked_outputs (output_id, reservation_id, locked_at) VALUES (?1, ?2, ?3)",
-            params![id, reservation_id, now],
-        )
-        .map_err(|e| {
-            db_err(
-                "reserveOutput",
-                format!("output {id} may be reserved by another pending send: {e}"),
-            )
-        })?;
-    }
-    tx.commit().map_err(|e| db_err("commitReserve", e))
-}
-
-/// Atomically claim every live input before the host obtains a spend signature.
-pub fn mark_signed(db: &mut Db, reservation_id: &str, expected_inputs: u32) -> Result {
-    let stale = || {
-        RuntimeError::with(
-            ErrorCode::InvalidRequest,
-            json!({"reason": "staleReservation"}),
-        )
-    };
-    if expected_inputs == 0 || expected_inputs > 1024 {
-        return Err(stale());
-    }
-    let tx = db
-        .conn_mut()
-        .transaction()
-        .map_err(|e| db_err("beginSignReservation", e))?;
-    let count: u32 = tx
-        .query_row(
-            "SELECT count(*) FROM locked_outputs WHERE reservation_id = ?1",
-            [reservation_id],
-            |row| row.get(0),
-        )
-        .map_err(|e| db_err("readSignReservation", e))?;
-    if count != expected_inputs {
-        return Err(stale());
-    }
-    let marked = tx
-        .execute(
-            "UPDATE locked_outputs SET signed_at = ?2
-         WHERE reservation_id = ?1 AND signed_at IS NULL AND locked_at > ?3
-           AND output_id IN (SELECT id FROM outputs WHERE spent_at_height IS NULL)",
-            params![
-                reservation_id,
-                crate::wallet::now_secs(),
-                reservation_cutoff()
-            ],
-        )
-        .map_err(|e| db_err("markReservationSigned", e))?;
-    if u32::try_from(marked).map_err(|_| stale())? != expected_inputs {
-        return Err(stale());
-    }
-    tx.commit()
-        .map_err(|e| db_err("commitSignReservation", e))?;
-    Ok(marked)
-}
-
-/// Releases all unsigned reservations of this identity.
-///
-/// Going back from the confirm screen is not reported; a new prepare means the
-/// earlier unsigned ones are abandoned. Signed ones stay: they may be broadcasting.
-fn release_unsigned(db: &Db, identity_id: i64) -> Result {
-    db.conn()
-        .execute(
-            "DELETE FROM locked_outputs
-             WHERE signed_at IS NULL
-               AND output_id IN (SELECT id FROM outputs WHERE identity_id = ?1)",
-            [identity_id],
-        )
-        .map_err(|e| db_err("releaseUnsignedReservations", e))
-}
-
-/// Releases a reservation (user cancelled or construction failed).
-pub fn release(db: &Db, reservation_id: &str) -> Result {
-    let n = db
-        .conn()
-        .execute(
-            "DELETE FROM locked_outputs WHERE reservation_id = ?1",
-            [reservation_id],
-        )
-        .map_err(|e| db_err("release", e))?;
-    Ok(n)
-}
-
 /// A constructed transaction awaiting signature.
 pub struct Prepared {
     pub signable: SignableTransaction,
@@ -1019,117 +887,6 @@ mod tests {
         assert!(select_inputs(&db, id, 105, 1_000).is_ok());
     }
 
-    #[test]
-    fn an_expired_reservation_gives_way_to_a_new_one() {
-        let (mut db, id) = db_with_identity();
-        let a = add_output(&db, id, 500, 10, true);
-        db.conn()
-            .execute(
-                "INSERT INTO locked_outputs (output_id, reservation_id, locked_at) VALUES (?1, 'old', ?2)",
-                params![a, reservation_cutoff() - 1],
-            )
-            .unwrap();
-        reserve(&mut db, "new", &[a]).expect("expired reservation must not block");
-    }
-
-    /// A new prepare releases unsigned reservations; signed ones may be broadcasting and stay.
-    #[test]
-    fn a_new_send_releases_only_unsigned_reservations() {
-        let (mut db, id) = db_with_identity();
-        let abandoned = add_output(&db, id, 500, 10, true);
-        let signed = add_output(&db, id, 400, 11, true);
-        reserve(&mut db, "abandoned", &[abandoned]).unwrap();
-        reserve(&mut db, "signed", &[signed]).unwrap();
-        mark_signed(&mut db, "signed", 1).unwrap();
-
-        assert_eq!(release_unsigned(&db, id).unwrap(), 1);
-
-        let left: Vec = db
-            .conn()
-            .prepare("SELECT reservation_id FROM locked_outputs")
-            .unwrap()
-            .query_map([], |r| r.get(0))
-            .unwrap()
-            .collect::>()
-            .unwrap();
-        assert_eq!(left, vec!["signed".to_string()]);
-    }
-
-    #[test]
-    fn signing_rejects_expired_partial_or_replayed_reservations_atomically() {
-        let (mut db, id) = db_with_identity();
-        let first = add_output(&db, id, 500, 10, true);
-        let second = add_output(&db, id, 400, 11, true);
-        reserve(&mut db, "review", &[first, second]).unwrap();
-        assert!(mark_signed(&mut db, "review", 1).is_err());
-        db.conn()
-            .execute(
-                "UPDATE locked_outputs SET locked_at = ?1 WHERE output_id = ?2",
-                params![reservation_cutoff(), second],
-            )
-            .unwrap();
-        assert!(mark_signed(&mut db, "review", 2).is_err());
-        let marked: i64 = db
-            .conn()
-            .query_row(
-                "SELECT count(*) FROM locked_outputs WHERE signed_at IS NOT NULL",
-                [],
-                |row| row.get(0),
-            )
-            .unwrap();
-        assert_eq!(marked, 0, "partial claims must roll back");
-        db.conn()
-            .execute("DELETE FROM locked_outputs WHERE output_id = ?1", [second])
-            .unwrap();
-        assert!(mark_signed(&mut db, "review", 2).is_err());
-        mark_signed(&mut db, "review", 1).unwrap();
-        assert!(mark_signed(&mut db, "review", 1).is_err());
-    }
-
-    #[test]
-    fn signed_reservations_that_never_broadcast_expire_after_a_day() {
-        let (mut db, id) = db_with_identity();
-        let input = add_output(&db, id, 500, 10, true);
-        reserve(&mut db, "signed", &[input]).unwrap();
-        mark_signed(&mut db, "signed", 1).unwrap();
-        db.conn()
-            .execute(
-                "UPDATE locked_outputs SET locked_at = ?1, signed_at = ?1",
-                [signed_reservation_cutoff() - 1],
-            )
-            .unwrap();
-        assert_eq!(query::spendable_rows(&db, id, 100).unwrap().len(), 1);
-        assert_eq!(
-            query::balance(&db, id, Some(100))
-                .unwrap()
-                .locked_by_reservation_atomic,
-            0
-        );
-        reserve(&mut db, "replacement", &[input]).expect("expired signed reservation gives way");
-    }
-
-    #[test]
-    fn signed_reservations_stay_unspendable_after_the_unsigned_ttl() {
-        let (mut db, id) = db_with_identity();
-        let input = add_output(&db, id, 500, 10, true);
-        reserve(&mut db, "signed", &[input]).unwrap();
-        mark_signed(&mut db, "signed", 1).unwrap();
-        db.conn()
-            .execute(
-                "UPDATE locked_outputs SET locked_at = ?1",
-                [reservation_cutoff() - 1],
-            )
-            .unwrap();
-        assert!(query::spendable_rows(&db, id, 100).unwrap().is_empty());
-        assert_eq!(
-            query::balance(&db, id, Some(100))
-                .unwrap()
-                .locked_by_reservation_atomic,
-            500
-        );
-        assert!(reserve(&mut db, "replacement", &[input]).is_err());
-    }
-
     /// As wallet2: pending change counts in the total (locked), not unlocked, until the send fails.
     #[test]
     fn pending_change_counts_in_total_until_the_send_fails() {
@@ -1150,7 +907,6 @@ mod tests {
             id,
             &txid,
             &[key_image],
-            "r",
             900,
             SentAmounts {
                 outgoing_atomic: Some(200),
@@ -1170,9 +926,9 @@ mod tests {
         assert_eq!(b.total_atomic, 500);
     }
 
-    /// Broadcast marks inputs spent by the transaction's key images, even if the reservation is gone.
+    /// Broadcast marks inputs spent by the transaction's key images.
     #[test]
-    fn a_broadcast_marks_its_inputs_by_key_image_without_a_reservation() {
+    fn a_broadcast_marks_its_inputs_by_key_image() {
         let (db, id) = db_with_identity();
         let a = add_output(&db, id, 500, 10, true);
         let untouched = add_output(&db, id, 400, 11, true);
@@ -1190,7 +946,6 @@ mod tests {
             id,
             &txid,
             &[key_image],
-            "gone",
             900,
             SentAmounts {
                 outgoing_atomic: Some(123),
@@ -1222,9 +977,8 @@ mod tests {
     /// Recorded before broadcast: a rejection undoes only a fresh record; a retry is not fresh.
     #[test]
     fn a_rejected_first_broadcast_is_undone_but_a_retry_is_not_fresh() {
-        let (mut db, id) = db_with_identity();
+        let (db, id) = db_with_identity();
         let a = add_output(&db, id, 500, 10, true);
-        reserve(&mut db, "r", &[a]).unwrap();
         let key_image: Vec = db
             .conn()
             .query_row("SELECT key_image FROM outputs WHERE id = ?1", [a], |r| {
@@ -1234,16 +988,7 @@ mod tests {
         let key_image = <[u8; 32]>::try_from(key_image.as_slice()).unwrap();
         let txid = [0x66u8; 32];
         let record = |db: &Db| {
-            record_broadcast(
-                db,
-                id,
-                &txid,
-                &[key_image],
-                "r",
-                900,
-                SentAmounts::default(),
-            )
-            .unwrap()
+            record_broadcast(db, id, &txid, &[key_image], 900, SentAmounts::default()).unwrap()
         };
 
         assert!(record(&db), "first record is fresh");
@@ -1268,7 +1013,7 @@ mod tests {
     }
 
     /// A send passed with the wrong account records nothing and leaves the
-    /// source account's reservation and inputs as they were.
+    /// source account's inputs as they were.
     #[test]
     fn a_broadcast_under_another_account_is_refused_before_sending() {
         let (mut db, source) = db_with_identity();
@@ -1276,7 +1021,6 @@ mod tests {
         view[0] = 10;
         let other = db.add_identity("acct-2", &spend, &view, 100).unwrap().id;
         let a = add_output(&db, source, 500, 10, true);
-        reserve(&mut db, "r", &[a]).unwrap();
         let key_image: Vec = db
             .conn()
             .query_row("SELECT key_image FROM outputs WHERE id = ?1", [a], |r| {
@@ -1290,7 +1034,6 @@ mod tests {
                 identity,
                 txid,
                 &[key_image],
-                "r",
                 900,
                 SentAmounts::default(),
             )
@@ -1303,11 +1046,13 @@ mod tests {
             .query_row("SELECT count(*) FROM transactions", [], |r| r.get(0))
             .unwrap();
         assert_eq!(rows, 0);
-        let locked: i64 = db
-            .conn()
-            .query_row("SELECT count(*) FROM locked_outputs", [], |r| r.get(0))
-            .unwrap();
-        assert_eq!(locked, 1, "the source reservation is kept");
+        assert_eq!(
+            crate::query::spendable_rows(&db, source, 10_000)
+                .unwrap()
+                .len(),
+            1,
+            "the source inputs stay spendable"
+        );
 
         assert!(record(&db, source, &[0x66; 32]).unwrap());
         let err = record(&db, source, &[0x77; 32]).unwrap_err();
@@ -1321,21 +1066,55 @@ mod tests {
         );
     }
 
-    /// An output cannot be held by two reservations at once.
+    /// A send failed by the pending check releases its inputs; a new
+    /// transaction over the same inputs must be recordable again.
     #[test]
-    fn an_output_cannot_be_reserved_twice() {
-        let (mut db, id) = db_with_identity();
-        let a = add_output(&db, id, 5_000, 10, true);
-        reserve(&mut db, "r1", &[a]).unwrap();
-        assert!(reserve(&mut db, "r2", &[a]).is_err(), "already reserved");
-        assert_eq!(release(&db, "r1").unwrap(), 1);
-        reserve(&mut db, "r2", &[a]).expect("can reserve again after release");
-    }
+    fn an_input_released_by_a_failed_send_can_be_spent_again() {
+        let (db, id) = db_with_identity();
+        let a = add_output(&db, id, 500, 10, true);
+        let key_image: Vec = db
+            .conn()
+            .query_row("SELECT key_image FROM outputs WHERE id = ?1", [a], |r| {
+                r.get(0)
+            })
+            .unwrap();
+        let key_image = <[u8; 32]>::try_from(key_image.as_slice()).unwrap();
+        let failed = [0x66u8; 32];
+        let retry = [0x77u8; 32];
+        let record = |txid: &[u8; 32]| {
+            record_broadcast(&db, id, txid, &[key_image], 900, SentAmounts::default())
+        };
 
-    #[test]
-    fn releasing_an_unknown_reservation_is_a_no_op() {
-        let (db, _) = db_with_identity();
-        assert_eq!(release(&db, "nope").unwrap(), 0);
+        assert!(record(&failed).unwrap());
+        crate::pool::mark_failed(&db, id, &failed).unwrap();
+        assert_eq!(
+            crate::query::spendable_rows(&db, id, 10_000).unwrap().len(),
+            1,
+            "the failed send released its input"
+        );
+
+        assert!(record(&retry).expect("a released input is not already spent"));
+        let (spent_at, spent_in): (Option, Option>) = db
+            .conn()
+            .query_row(
+                "SELECT spent_at_height, spent_in_txid FROM outputs WHERE id = ?1",
+                [a],
+                |r| Ok((r.get(0)?, r.get(1)?)),
+            )
+            .unwrap();
+        assert_eq!((spent_at, spent_in), (Some(900), Some(retry.to_vec())));
+        assert!(crate::query::spendable_rows(&db, id, 10_000)
+            .unwrap()
+            .is_empty());
+        let failed_kept: i64 = db
+            .conn()
+            .query_row(
+                "SELECT failed FROM transactions WHERE txid = ?1",
+                [failed.as_slice()],
+                |r| r.get(0),
+            )
+            .unwrap();
+        assert_eq!(failed_kept, 1, "the failed send stays in history");
     }
 
     #[test]
@@ -1437,8 +1216,8 @@ pub fn parse_priority(name: &str) -> Result Result Result {
@@ -1489,9 +1267,6 @@ pub async fn prepare_for_host(
     // fork, not by the node; a wrong type is rejected network-wide.
     let rct_type = monero_wallet::ringct::RctType::ClsagBulletproofPlus;
     let mut rng = rand_core::OsRng;
-
-    // Before selection, so outputs held by abandoned reservations can be selected.
-    release_unsigned(db, identity_id)?;
     let decoys = CachedDecoys::new(daemon);
 
     let prepared = if max_send {
@@ -1530,11 +1305,7 @@ pub async fn prepare_for_host(
         .saturating_sub(prepared.amount_atomic)
         .saturating_sub(prepared.fee_atomic);
 
-    // Reserve last so an earlier failure leaves no outputs locked.
-    reserve(db, reservation_id, &prepared.output_ids)?;
-
     Ok(json!({
-        "reservationId": reservation_id,
         "signableHex": hex::encode(prepared.signable.serialize()),
         "feeAtomic": prepared.fee_atomic.to_string(),
         "amountAtomic": prepared.amount_atomic.to_string(),
@@ -1566,8 +1337,8 @@ pub struct SentAmounts {
     pub change_atomic: Option,
 }
 
-/// Pre-broadcast bookkeeping in one transaction: mark inputs spent, record a
-/// pending send, release the reservation.
+/// Pre-broadcast bookkeeping in one transaction: mark inputs spent and record a
+/// pending send.
 ///
 /// Returns whether the record is fresh. An existing record means the same
 /// transaction was sent before (a retry), which the node may have accepted.
@@ -1579,7 +1350,6 @@ fn record_broadcast(
     identity_id: i64,
     txid: &[u8; 32],
     key_images: &[[u8; 32]],
-    reservation_id: &str,
     chain_tip: u64,
     amounts: SentAmounts,
 ) -> Result {
@@ -1629,19 +1399,15 @@ fn record_broadcast(
             ],
         )
         .map_err(|e| db_err("recordOutgoing", e))?;
-    tx_db
-        .execute(
-            "DELETE FROM locked_outputs WHERE reservation_id = ?1
-               AND output_id IN (SELECT id FROM outputs WHERE identity_id = ?2)",
-            params![reservation_id, identity_id],
-        )
-        .map_err(|e| db_err("releaseAfterBroadcast", e))?;
     tx_db.commit().map_err(|e| db_err("commitRecordSend", e))?;
     Ok(!existed)
 }
 
 /// Every input must be an output of `identity_id` not spent by another transaction.
-fn check_inputs_owned(
+///
+/// A failed send releases its inputs (`spent_at_height` cleared) but keeps
+/// `spent_in_txid` for its history; such an input is spendable again.
+pub(crate) fn check_inputs_owned(
     db: &rusqlite::Connection,
     identity_id: i64,
     txid: &[u8; 32],
@@ -1656,7 +1422,8 @@ fn check_inputs_owned(
     for key_image in key_images {
         let spent_in: Option>> = db
             .query_row(
-                "SELECT spent_in_txid FROM outputs WHERE identity_id = ?1 AND key_image = ?2",
+                "SELECT CASE WHEN spent_at_height IS NULL THEN NULL ELSE spent_in_txid END
+                 FROM outputs WHERE identity_id = ?1 AND key_image = ?2",
                 params![identity_id, key_image.as_slice()],
                 |r| r.get(0),
             )
@@ -1708,7 +1475,6 @@ pub async fn broadcast_signed(
     daemon: &crate::network::Daemon,
     identity_id: i64,
     raw_hex: &str,
-    reservation_id: &str,
     chain_tip: u64,
     amounts: SentAmounts,
 ) -> Result {
@@ -1723,8 +1489,7 @@ pub async fn broadcast_signed(
         .map_err(|e| db_err("parseSignedTransaction", e))?;
     let txid = tx.hash();
 
-    // Mark by the transaction's own key images, not the reservation, which may
-    // have expired or been released before the same signature is resent.
+    // Mark by the transaction's own key images.
     let key_images: Vec<[u8; 32]> = tx
         .prefix()
         .inputs
@@ -1737,15 +1502,7 @@ pub async fn broadcast_signed(
         })
         .collect();
     // If recording fails, do not send; nothing has happened yet.
-    let fresh = record_broadcast(
-        db,
-        identity_id,
-        &txid,
-        &key_images,
-        reservation_id,
-        chain_tip,
-        amounts,
-    )?;
+    let fresh = record_broadcast(db, identity_id, &txid, &key_images, chain_tip, amounts)?;
     // Same for a record that may not be durable: a restart could make its
     // inputs selectable again while the transaction is in flight.
     crate::storage::durability_barrier().await?;
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
index 0300133b0..bdf07877a 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
@@ -288,11 +288,13 @@ pub async fn step(
     }
     let max_blocks = max_blocks.min(MAX_BLOCKS_PER_CALL);
 
-    let sends_failed = crate::pool::check_pending(db, daemon, identity_id).await?;
+    let (sends_failed, sends_restored) =
+        crate::pool::check_pending(db, daemon, identity_id).await?;
 
     let Some((start, end)) = next_range(db, identity_id)? else {
         let mut v = progress(db, identity_id, &ScanOutcome::default(), true)?;
         v["sendsFailed"] = json!(sends_failed);
+        v["sendsRestored"] = json!(sends_restored);
         return Ok(v);
     };
 
@@ -354,6 +356,7 @@ pub async fn step(
     let done = next_range(db, identity_id)?.is_none();
     let mut v = progress(db, identity_id, &outcome, done)?;
     v["sendsFailed"] = json!(sends_failed);
+    v["sendsRestored"] = json!(sends_restored);
     Ok(v)
 }
 
@@ -407,29 +410,30 @@ pub fn peek(db: &Db, identity_id: i64) -> Result {
 
 /// Reorg recovery: rewind to `height` and requeue everything above it.
 pub fn rewind_and_requeue(db: &mut Db, identity_id: i64, height: u64, tip: u64) -> Result {
-    scan::rewind_to(db, identity_id, height, tip)?;
+    let tx = db
+        .conn_mut()
+        .transaction()
+        .map_err(|e| db_err("beginRewindAndRequeue", e))?;
+    scan::rewind_in_transaction(&tx, identity_id, height, tip)?;
     // Rewind progress too, or the next step resumes from a discarded height and the
     // gap is never rescanned. Keep NULL if nothing was scanned: 0 would make the next
     // `update_chain_tip` queue from genesis.
-    db.conn()
-        .execute(
-            "UPDATE identities SET scanned_to_height = min(scanned_to_height, ?2)
+    tx.execute(
+        "UPDATE identities SET scanned_to_height = min(scanned_to_height, ?2)
              WHERE id = ?1 AND scanned_to_height IS NOT NULL",
-            params![identity_id, height as i64],
-        )
-        .map_err(|e| db_err("rewindScannedTo", e))?;
+        params![identity_id, height as i64],
+    )
+    .map_err(|e| db_err("rewindScannedTo", e))?;
     // Rescan before the birthday (user picked an earlier date): move the birthday
     // back so progress starts there.
-    db.conn()
-        .execute(
-            "UPDATE identities SET birthday_height = ?2 WHERE id = ?1 AND birthday_height > ?2",
-            params![identity_id, (height + 1) as i64],
-        )
-        .map_err(|e| db_err("rewindBirthday", e))?;
+    tx.execute(
+        "UPDATE identities SET birthday_height = ?2 WHERE id = ?1 AND birthday_height > ?2",
+        params![identity_id, (height + 1) as i64],
+    )
+    .map_err(|e| db_err("rewindBirthday", e))?;
     // Requeue the rewound span here instead of relying on the host to call `update_chain_tip`.
     if tip > height {
-        db.conn()
-            .execute(
+        tx.execute(
                 "INSERT INTO scan_ranges (identity_id, start_height, end_height)
                  VALUES (?1, ?2, ?3)
                  ON CONFLICT (identity_id, start_height) DO UPDATE SET end_height = max(end_height, ?3)",
@@ -437,6 +441,8 @@ pub fn rewind_and_requeue(db: &mut Db, identity_id: i64, height: u64, tip: u64)
             )
             .map_err(|e| db_err("requeueAfterRewind", e))?;
     }
+    tx.commit()
+        .map_err(|e| db_err("commitRewindAndRequeue", e))?;
     Ok(json!({ "rewoundTo": height, "requeuedTo": tip }))
 }
 
@@ -605,6 +611,39 @@ mod tests {
         assert_eq!((start, end), (181, 201));
     }
 
+    #[test]
+    fn a_failed_rewind_cursor_write_keeps_the_scan_data_intact() {
+        let (mut db, id) = db_with_identity();
+        update_chain_tip(&mut db, id, 200).unwrap();
+        advance_scanned_to(&db, id, 200).unwrap();
+        consume_range(&mut db, id, 100, 200).unwrap();
+        db.conn()
+            .execute(
+                "INSERT INTO blocks (identity_id, height, hash, timestamp) VALUES (?1, 190, ?2, 1)",
+                params![id, [1u8; 32].as_slice()],
+            )
+            .unwrap();
+        db.conn()
+            .execute_batch(
+                "CREATE TRIGGER refuse_cursor BEFORE UPDATE OF scanned_to_height ON identities
+            BEGIN SELECT RAISE(ABORT, 'synthetic cursor failure'); END;",
+            )
+            .unwrap();
+
+        assert!(rewind_and_requeue(&mut db, id, 180, 200).is_err());
+        let blocks: i64 = db
+            .conn()
+            .query_row(
+                "SELECT COUNT(*) FROM blocks WHERE identity_id = ?1",
+                [id],
+                |row| row.get(0),
+            )
+            .unwrap();
+        assert_eq!(blocks, 1);
+        assert_eq!(scanned_to_height(&db, id).unwrap(), Some(200));
+        assert!(next_range(&db, id).unwrap().is_none());
+    }
+
     #[test]
     fn a_node_that_failed_the_batch_path_gets_another_try_later() {
         BLOCKS_BIN_UNSUPPORTED_BY.with(|c| *c.borrow_mut() = Some(("http://n".into(), 1_000.0)));
diff --git a/chain-runtimes/monero/scripts/smoke.js b/chain-runtimes/monero/scripts/smoke.js
index 2ed5b8fca..8bad853a5 100755
--- a/chain-runtimes/monero/scripts/smoke.js
+++ b/chain-runtimes/monero/scripts/smoke.js
@@ -115,7 +115,6 @@ async function online() {
       id,
       JSON.stringify([{ address: a.primaryAddress, amountAtomic: '1000' }]),
       false,
-      'smoke-r1',
       BigInt(tip.height),
       'normal',
     );
@@ -134,7 +133,6 @@ async function online() {
         { address: sub.address, amountAtomic: '1000' },
       ]),
       false,
-      'smoke-r2',
       BigInt(tip.height),
       'normal',
     );
@@ -143,9 +141,6 @@ async function online() {
     const err = JSON.parse(e.message ?? e);
     check('two-recipient build is refused', err.params.reason, 'exactlyOneRecipient');
   }
-
-  const released = JSON.parse(rt.releaseReservation('smoke-r1'));
-  check('failed build leaves no reservation', released.released, 0);
 }
 
 online()
diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md
index 2f6c91a22..4b21bc25b 100644
--- a/chain-runtimes/zcash/README.md
+++ b/chain-runtimes/zcash/README.md
@@ -63,7 +63,8 @@ chainTip() / chainTipAt(baseUrl)
 importAccountUfvk(name, ufvk, birthday, seedFingerprintHex?, accountIndex?)
                                          → UUID; the server's tree state must be
                                          exactly the block before birthday
-removeAccount(uuid) / removeDeletedAccount(uuid)
+removeAccount(uuid)                     pending transactions do not block removal
+removeDeletedAccount(uuid)              compatibility alias for removeAccount
 accountByUfvk(ufvk) / listAccounts() / accountSyncStatus(uuid)
 accountBalance(uuid, trusted, untrusted, allowZeroConfShielding)
 
@@ -78,14 +79,12 @@ transactionDetails(uuid, txid) / transactionOutputs(uuid, txid)
 deleteWallet(dbName)                     deletes the local cache (rebuildable)
 storageStats()
 
-pcztQuote(...)                           quote only; builds nothing, locks nothing
-pcztCreate(...) → { pcztHex, reservationId }   build and lock the selected notes
-releaseReservation(id)                   user cancel; idempotent
-clearLockedOutputs(uuid)                 repair; refused while broadcasts are pending
+pcztQuote(...)                           quote only; builds nothing
+pcztCreate(...) → { pcztHex, feeZat }    build; locks no notes
 pcztProve(pczt)
 pcztCombine(original, signed)            merge an external signer's copy (signatures only)
-pcztSubmit(uuid, pczt, reservationId)    → { txid, broadcast }
-pendingBroadcastTxids(uuid) / broadcastRetryTxids(uuid)
+pcztSubmit(uuid, pczt)                   → { txid, broadcast }
+pendingBroadcastTxids(uuid)              stored, unmined, unexpired, not rejected
 broadcastTransaction(txid)               rebroadcast a stored transaction
 
 prewarmPczt(network, height)             build proving parameters; no wallet
@@ -117,28 +116,34 @@ keysCapabilities() / keysDependencyVersions()
 ### Sending
 
 ```
-runtime.pcztCreate()             build (selection, witness, anchor) and lock notes
+runtime.pcztCreate()             build (selection, witness, anchor)
 runtime.pcztProve()              zero-knowledge proofs (slow)
 keys.pcztSignWithAccountKeys()   check against the review, then sign
   or hardware: keys.pcztRedactForHardwareSigner() → device → runtime.pcztCombine()
-runtime.pcztSubmit()             combine check → extract → store → broadcast
+runtime.pcztSubmit()             extract → store → broadcast
 ```
 
 Prove before signing: the upstream Signer must be able to verify what the proofs
-cover. The signed bytes and the reservation→txid link are stored before broadcast,
-so every retry and crash recovery sends the same bytes. Broadcast outcomes:
+cover. Building locks no notes: the signed transaction is stored before broadcast
+and from then on holds its notes until mined or expired. Storing is refused when
+another stored, unexpired transaction already spends one of the same notes (two
+reviews opened at once). Sync rebroadcasts the stored bytes. Broadcast outcomes:
 
 - `accepted`: the node took it (`already known` / `in mempool` / `in blockchain`
   count as success).
-- `rejected`: only an explicit consensus-invalid or expired reply. The transaction
-  stays stored; its notes return after its expiry height.
+- `rejected`: only an explicit consensus-invalid or expired reply, recorded in
+  `ext_onekey_tx_state` (the only rows it holds). The transaction stays stored;
+  its notes return after its expiry height.
 - `unknown`: anything else. It stays pending and sync rebroadcasts the same bytes.
-  Never show it as failed or prompt a resend; check `pendingBroadcastTxids` before
-  building another payment.
+  Pending transactions do not block another payment or user-requested local-data
+  deletion, reset or rescan.
+
+Submission always extracts and stores the current signed transaction, including
+on retry. A shared nullifier identifies an input conflict; it never authorizes
+returning or broadcasting a different stored transaction in its place.
 
 `FINALIZE_OUTCOME_UNKNOWN` means persistence is unconfirmed: treat it like `unknown`
-and do not unlock notes or rebuild. A `reservationId` with a stored transaction
-cannot build again. Network calls time out after 30 seconds.
+and do not rebuild. Network calls time out after 30 seconds.
 
 Transparent-only sends (t-address or Unified Address recipients, no wallet or scan)
 use the stateless API in
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
index 0d79ec347..8475256ea 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
@@ -125,7 +125,7 @@ pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) ->
             "spendable": u64::from(b.spendable_value()),
             "pendingChange": u64::from(b.change_pending_confirmation()),
             "pendingSpendable": u64::from(b.value_pending_spendability()),
-            // Reserved by a PCZT proposal (see the reservation in send.rs).
+            // Held by an unexpired upstream output lock; this runtime's sends take none.
             "locked": u64::from(b.locked_value()),
             "total": u64::from(b.total()),
         })
@@ -172,7 +172,7 @@ pub fn remove_account(db: &mut Db, account_uuid: &str) -> Result<()> {
             )
             .detail(e)
         })?;
-        crate::tx_state::remove_account_rows(ext, account_uuid)
+        crate::tx_state::prune_orphaned_rows(ext)
     })
 }
 
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
index f8b9c35d6..f44489bfc 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
@@ -22,7 +22,7 @@ use crate::perf;
 use crate::{
     account,
     error::{ErrorCode, RuntimeError},
-    guard, history, network, runtime, send, storage, sync, tx_state, wallet,
+    history, network, runtime, send, storage, sync, tx_state, wallet,
 };
 
 /// Inject a Fetch-compatible host transport; None retains browser Fetch.
@@ -85,7 +85,7 @@ pub fn init_memory_storage() {
 /// The capabilities of this version-locked wallet and keys package set.
 ///
 /// Lets the host hide unsupported actions up front instead of failing at proving time,
-/// after notes are locked and the user has entered a password.
+/// after the user has reviewed the send and entered a password.
 ///
 #[wasm_bindgen(js_name = capabilities)]
 pub fn capabilities() -> String {
@@ -229,31 +229,16 @@ pub async fn import_account_ufvk(
 /// Removes one account from the shared database. Does not delete the database, which holds other wallets' accounts.
 #[wasm_bindgen(js_name = removeAccount)]
 pub async fn remove_account(account_uuid: String) -> Result<(), JsValue> {
-    runtime::with_read_conn(|conn| {
-        guard::assert_idle(
-            conn,
-            Some(&account_uuid),
-            "removeAccount",
-            guard::LockPolicy::Blocking,
-        )
-    })?;
     runtime::with_db(|db| account::remove_account(db, &account_uuid))?;
     storage::durability_barrier().await?;
     runtime::reclaim_storage(storage::RECLAIM_PAGES_AFTER_DELETE);
     Ok(())
 }
 
-/// The host already deleted this account: removes it regardless of in-flight transactions,
-/// skipping `removeAccount`'s idle check.
-///
-/// Funds are on chain and the seed is with the user, so a re-import and rescan recovers them.
+/// Compatibility alias for hosts that distinguish app-account removal.
 #[wasm_bindgen(js_name = removeDeletedAccount)]
 pub async fn remove_deleted_account(account_uuid: String) -> Result<(), JsValue> {
-    runtime::with_db(|db| account::remove_account(db, &account_uuid))?;
-    send::forget_account_reservations(&account_uuid);
-    storage::durability_barrier().await?;
-    runtime::reclaim_storage(storage::RECLAIM_PAGES_AFTER_DELETE);
-    Ok(())
+    remove_account(account_uuid).await
 }
 
 /// Finds the account for a UFVK, returning `{ uuid }` or `"null"` if absent.
@@ -364,7 +349,7 @@ pub async fn sync_probe_download(batch_size: u32) -> Result {
     )
 }
 
-/// Quotes only: no transaction built, no notes locked. Returns `{ feeZat, steps }`.
+/// Quotes only: no transaction built. Returns `{ feeZat, steps }`.
 ///
 /// Shares the proposal path with `pcztCreate`, so the quoted fee is the fee paid.
 /// Insufficient balance throws `INSUFFICIENT_FUNDS` (with shortfallZat).
@@ -541,8 +526,6 @@ pub fn pczt_create(
     untrusted: u32,
     fallback_change_pool: String,
     pad_orchard_bundle: bool,
-    lock_for_blocks: u32,
-    reservation_id: Option,
     allow_zero_conf_shielding: Option,
     spend_source: Option,
     memo_hex: Option,
@@ -556,19 +539,16 @@ pub fn pczt_create(
         spend_source.as_deref(),
     )?;
     Ok(runtime::with_db(|db| {
-        let (bytes, reservation_id, fee_zat) = send::create_pczt(
+        let (bytes, fee_zat) = send::create_pczt(
             db,
             &account_uuid,
             &to_address,
             amount_zat,
             send::parse_memo(memo.as_deref(), memo_hex.as_deref())?.as_ref(),
             policy,
-            lock_for_blocks,
-            reservation_id.as_deref(),
         )?;
         Ok(serde_json::json!({
             "pcztHex": bytes.iter().map(|b| format!("{b:02x}")).collect::(),
-            "reservationId": reservation_id,
             "feeZat": fee_zat,
         })
         .to_string())
@@ -591,41 +571,6 @@ pub fn pczt_combine(original: Vec, signed: Vec) -> Result, JsVal
     Ok(send::combine_pczt(&original, &signed)?)
 }
 
-/// Releases all locked notes of the account; returns the number unlocked.
-///
-/// For crash recovery: `releaseReservation` relies on the in-memory proposal table, which is
-/// lost when the app / offscreen restarts.
-///
-/// Also releases in-progress proposals, so call only from a user-triggered repair action,
-/// never from the normal flow.
-#[wasm_bindgen(js_name = clearLockedOutputs)]
-pub fn clear_locked_outputs(account_uuid: String) -> Result {
-    // Locks are not "busy" (they are what this clears), but sent transactions are: unlocking
-    // notes spent by a pending broadcast would return them to selection and allow a double spend.
-    runtime::with_read_conn(|conn| {
-        guard::assert_idle(
-            conn,
-            Some(&account_uuid),
-            "clearLockedOutputs",
-            guard::LockPolicy::Ignored,
-        )
-    })?;
-    Ok(runtime::with_db(|db| {
-        send::clear_locked_outputs(db, &account_uuid)
-    })?)
-}
-
-/// Releases the notes held by a reservation (called when the user cancels a send).
-///
-/// Idempotent: returns `false` instead of an error when the id was sent, already released,
-/// or never existed; repeated calls on the cancel path are normal.
-#[wasm_bindgen(js_name = releaseReservation)]
-pub fn release_reservation(reservation_id: String) -> Result {
-    Ok(runtime::with_db(|db| {
-        send::release_reservation(db, &reservation_id)
-    })?)
-}
-
 /// Durability barrier after an irreversible step.
 ///
 /// A barrier failure means "unknown whether persistence reached durable storage", not that
@@ -648,20 +593,9 @@ async fn barrier_after_irreversible(params: serde_json::Value) -> Result<(), cra
 /// - `unknown`: delivery to the node is uncertain. The transaction stays pending and is
 ///   rebroadcast on sync; the host must not treat it as a failed send.
 #[wasm_bindgen(js_name = pcztSubmit)]
-pub async fn pczt_submit(
-    account_uuid: String,
-    pczt_bytes: Vec,
-    reservation_id: String,
-) -> Result {
+pub async fn pczt_submit(account_uuid: String, pczt_bytes: Vec) -> Result {
     let outcome = runtime::with_db_and_client(move |mut db, mut client| async move {
-        let r = send::submit_signed_pczt(
-            &mut db,
-            &mut client,
-            &account_uuid,
-            &pczt_bytes,
-            &reservation_id,
-        )
-        .await;
+        let r = send::submit_signed_pczt(&mut db, &mut client, &account_uuid, &pczt_bytes).await;
         (db, client, r)
     })
     .await?;
@@ -684,12 +618,12 @@ pub async fn pczt_submit(
     Ok(json.to_string())
 }
 
-/// Runtime-owned unresolved broadcast intents for this account. The host uses
-/// this only to fail closed before constructing another payment; it does not
-/// persist or reinterpret the returned transaction IDs.
+/// Stored outgoing transactions of this account that are unmined, unexpired, and not
+/// rejected by the node. The host refuses to build another payment while any exist and
+/// rebroadcasts them on sync.
 #[wasm_bindgen(js_name = pendingBroadcastTxids)]
 pub fn pending_broadcast_txids(account_uuid: String) -> Result {
-    let txids = runtime::with_read_conn(|conn| tx_state::unresolved_txids(conn, &account_uuid))?;
+    let txids = runtime::with_read_conn(|conn| tx_state::pending_txids(conn, &account_uuid))?;
     Ok(serde_json::to_string(&txids).map_err(|error| {
         crate::RuntimeError::with(
             crate::ErrorCode::DatabaseError,
@@ -699,20 +633,7 @@ pub fn pending_broadcast_txids(account_uuid: String) -> Result
     })?)
 }
 
-#[wasm_bindgen(js_name = broadcastRetryTxids)]
-pub fn rebroadcastable_txids(account_uuid: String) -> Result {
-    let txids =
-        runtime::with_read_conn(|conn| tx_state::rebroadcastable_txids(conn, &account_uuid))?;
-    Ok(serde_json::to_string(&txids).map_err(|error| {
-        crate::RuntimeError::with(
-            crate::ErrorCode::DatabaseError,
-            serde_json::json!({ "operation": "serializeRebroadcastableTransactions" }),
-        )
-        .detail(error)
-    })?)
-}
-
-/// Rebroadcasts a stored transaction with an unknown outcome (called during sync). Irreversible.
+/// Rebroadcasts a stored pending transaction (called during sync). Irreversible.
 ///
 /// Throws `BROADCAST_REJECTED` when the node definitively rejects it (do not retry);
 /// `BROADCAST_OUTCOME_UNKNOWN` when the node errored without proving it can never be mined;
@@ -721,46 +642,41 @@ pub fn rebroadcastable_txids(account_uuid: String) -> Result {
 #[wasm_bindgen(js_name = broadcastTransaction)]
 pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> {
     let result = runtime::with_db_and_client(move |mut db, mut client| async move {
-        let r = match tx_state::assert_broadcastable(&mut db, &txid)
+        let r = match tx_state::assert_not_rejected(&mut db, &txid)
             .and_then(|_| send::raw_transaction(&db, &txid))
         {
             Ok(raw) => network::broadcast(&mut client, raw).await,
             Err(e) => Err(e),
         };
         let r = match r {
-            Ok(()) => tx_state::mark_accepted(&mut db, &txid),
             Err(e) if e.code == crate::ErrorCode::BroadcastRejected => {
                 // Even if persisting fails, return the node's rejection reason: it is what the
                 // user can act on. The persistence failure is attached as detail.
-                match tx_state::mark_rejected(&mut db, &txid, &e) {
+                let recorded =
+                    tx_state::account_uuid_for_txid(&mut db, &txid).and_then(|account_uuid| {
+                        tx_state::record_rejection(&mut db, &txid, &account_uuid, &e)
+                    });
+                match recorded {
                     Ok(()) => Err(e),
                     Err(persist_error) => {
-                        Err(e.detail(format!("mark_rejected failed: {persist_error}")))
+                        Err(e.detail(format!("record_rejection failed: {persist_error}")))
                     }
                 }
             }
-            Err(e) => Err(e),
+            r => r,
         };
         (db, client, r)
     })
     .await;
-    let changed_lifecycle = result.is_ok()
-        || result
-            .as_ref()
-            .is_err_and(|error| error.code == crate::ErrorCode::BroadcastRejected);
-    if changed_lifecycle {
-        // The broadcast happened and the lifecycle is committed; the outcome must reach the host unchanged.
-        let outcome = match &result {
-            Ok(()) => serde_json::json!({ "broadcast": "accepted" }),
-            Err(rejection) => serde_json::json!({
-                "broadcast": "rejected",
-                "rejection": rejection.to_json(),
-            }),
-        };
-        barrier_after_irreversible(
-            serde_json::json!({ "operation": "broadcastTransaction", "outcome": outcome }),
-        )
-        .await?;
+    if let Err(rejection) = &result {
+        if rejection.code == crate::ErrorCode::BroadcastRejected {
+            // The rejection is recorded; it must reach the host unchanged.
+            barrier_after_irreversible(serde_json::json!({
+                "operation": "broadcastTransaction",
+                "outcome": { "broadcast": "rejected", "rejection": rejection.to_json() },
+            }))
+            .await?;
+        }
     }
     Ok(result?)
 }
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
index d477db42e..57d7d3adf 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
@@ -99,8 +99,6 @@ pub enum ErrorCode {
     ///
     /// An empty active set must never fall back to every UFVK stored in the runtime database.
     NoActiveAccounts,
-    /// reservationId is not 64 hex chars. Params: `{ value }`
-    InvalidReservationId,
     /// Malformed txid (not 64 hex chars). Params: `{ value }` or `{ value, byteLen }`
     InvalidTxid,
     /// PCZT parse or serialization failed. Params: `{ stage }`
@@ -120,11 +118,6 @@ pub enum ErrorCode {
     /// during sync; scanning resolves it as mined or expired. Hosts must not treat
     /// this as a failed send. Params: `{ errorCode }`; `detail` holds the node's message.
     BroadcastOutcomeUnknown,
-    /// No persisted broadcast intent for this local transaction. Params: `{ txid }`.
-    BroadcastIntentNotFound,
-    /// Broadcast intent exists but its state does not allow broadcasting.
-    /// Params: `{ txid, state }`.
-    BroadcastIntentNotReady,
     /// The transaction may be in the in-memory wallet but persistence is unconfirmed.
     /// Do not unlock or rebuild the transaction.
     FinalizeOutcomeUnknown,
@@ -161,14 +154,11 @@ impl ErrorCode {
             WalletBusy => "WALLET_BUSY",
             InvalidScanPriority => "INVALID_SCAN_PRIORITY",
             NoActiveAccounts => "NO_ACTIVE_ACCOUNTS",
-            InvalidReservationId => "INVALID_RESERVATION_ID",
             InvalidTxid => "INVALID_TXID",
             PcztError => "PCZT_ERROR",
             TransactionBuildError => "TRANSACTION_BUILD_ERROR",
             BroadcastRejected => "BROADCAST_REJECTED",
             BroadcastOutcomeUnknown => "BROADCAST_OUTCOME_UNKNOWN",
-            BroadcastIntentNotFound => "BROADCAST_INTENT_NOT_FOUND",
-            BroadcastIntentNotReady => "BROADCAST_INTENT_NOT_READY",
             FinalizeOutcomeUnknown => "FINALIZE_OUTCOME_UNKNOWN",
             Unimplemented => "UNIMPLEMENTED",
         }
@@ -313,7 +303,6 @@ mod tests {
             InsufficientFunds,
             NetworkError,
             DatabaseError,
-            InvalidReservationId,
             InvalidTxid,
             PcztError,
             TransactionBuildError,
@@ -323,8 +312,6 @@ mod tests {
             ReorgDetected,
             WalletBusy,
             InvalidScanPriority,
-            BroadcastIntentNotFound,
-            BroadcastIntentNotReady,
             FinalizeOutcomeUnknown,
         ];
         let mut seen = std::collections::HashSet::new();
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/guard.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/guard.rs
deleted file mode 100644
index cbdc40856..000000000
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/guard.rs
+++ /dev/null
@@ -1,288 +0,0 @@
-//! Shared gate for destructive operations.
-//!
-//! Operations that drop scan results, accounts or the whole database require
-//! the wallet to be idle: no in-flight proposals, no unmined spends, no
-//! broadcasts with an unknown outcome.
-//!
-//! The check reads the database, not process memory: output locks persist in
-//! SQLite and survive a Worker restart, so the check must as well.
-
-use serde_json::json;
-
-use crate::error::{ErrorCode, Result, RuntimeError};
-use crate::history::uuid_blob;
-
-/// Whether output locks count as busy.
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub enum LockPolicy {
-    /// Refuse on any unexpired lock: those notes may be being proven or signed.
-    Blocking,
-    /// The operation clears the locks itself, so they cannot block it.
-    Ignored,
-}
-
-/// Tables with lock columns; upstream keeps one per pool.
-const LOCKABLE_TABLES: [&str; 4] = [
-    "sapling_received_notes",
-    "orchard_received_notes",
-    "ironwood_received_notes",
-    "transparent_received_outputs",
-];
-
-fn db_err(operation: &str, error: impl std::fmt::Display) -> RuntimeError {
-    RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": operation })).detail(error)
-}
-
-/// Chain tip, as upstream `chain_tip_height`: scan ranges are end-exclusive, hence -1.
-fn chain_tip(conn: &rusqlite::Connection) -> Result> {
-    conn.query_row("SELECT MAX(block_range_end) FROM scan_queue", [], |row| {
-        row.get::<_, Option>(0)
-    })
-    .map(|end| end.map(|h| h.saturating_sub(1)))
-    .map_err(|e| db_err("walletIdleChainTip", e))
-}
-
-/// Whether the account (`None` = whole database) has unexpired output locks.
-fn has_live_locks(conn: &rusqlite::Connection, account_uuid: Option<&str>) -> Result {
-    // With an unknown tip, treat every lock as live: report busy rather than
-    // free notes that may be mid-signing.
-    let tip = chain_tip(conn)?;
-    let account_filter = account_uuid
-        .map(|uuid| uuid_blob(uuid).map(Some))
-        .transpose()?
-        .flatten();
-    for table in LOCKABLE_TABLES {
-        let sql = format!(
-            "SELECT EXISTS(
-               SELECT 1
-               FROM {table} o
-               JOIN accounts a ON a.id = o.account_id
-               WHERE o.lock_owner IS NOT NULL
-                 AND (?1 IS NULL OR a.uuid = ?1)
-                 AND (?2 IS NULL OR o.lock_expiry_height IS NULL OR o.lock_expiry_height > ?2)
-             )"
-        );
-        let found: bool = conn
-            .query_row(&sql, rusqlite::params![account_filter, tip], |row| {
-                row.get(0)
-            })
-            .map_err(|e| db_err("walletIdleLocks", e))?;
-        if found {
-            return Ok(true);
-        }
-    }
-    Ok(false)
-}
-
-/// Spending transactions that are neither mined nor expired; a rewind or delete
-/// would lose their records.
-fn has_unsettled_outgoing(conn: &rusqlite::Connection, account_uuid: Option<&str>) -> Result {
-    let account_filter = account_uuid
-        .map(|uuid| uuid_blob(uuid).map(Some))
-        .transpose()?
-        .flatten();
-    conn.query_row(
-        "SELECT EXISTS(
-           SELECT 1
-           FROM v_transactions
-           WHERE (?1 IS NULL OR account_uuid = ?1)
-             AND mined_height IS NULL
-             AND expired_unmined = 0
-             AND COALESCE(total_spent, 0) > 0
-         )",
-        rusqlite::params![account_filter],
-        |row| row.get(0),
-    )
-    .map_err(|e| db_err("walletIdleOutgoing", e))
-}
-
-/// Authorized broadcasts with no known outcome. This state cannot be rebuilt by rescanning.
-fn has_unresolved_broadcast(
-    conn: &rusqlite::Connection,
-    account_uuid: Option<&str>,
-) -> Result {
-    let account_filter = account_uuid
-        .map(|uuid| uuid_blob(uuid).map(Some))
-        .transpose()?
-        .flatten();
-    conn.query_row(
-        &format!(
-            "SELECT EXISTS(
-               SELECT 1
-               FROM {table} state
-               LEFT JOIN v_transactions tx
-                 ON tx.txid = state.txid AND tx.account_uuid = state.account_uuid
-               WHERE (?1 IS NULL OR state.account_uuid = ?1)
-                 AND state.broadcast_state IN ('pending', 'accepted')
-                 AND tx.mined_height IS NULL
-                 AND COALESCE(tx.expired_unmined, 0) = 0
-             )",
-            table = crate::tx_state::TABLE,
-        ),
-        rusqlite::params![account_filter],
-        |row| row.get(0),
-    )
-    .map_err(|e| db_err("walletIdleBroadcast", e))
-}
-
-/// Errors with `WalletBusy` unless the wallet is idle. Pass `None` for operations
-/// that affect every account in the shared database (rewind, delete).
-pub fn assert_idle(
-    conn: &rusqlite::Connection,
-    account_uuid: Option<&str>,
-    operation: &str,
-    locks: LockPolicy,
-) -> Result<()> {
-    let active_reservation = match locks {
-        LockPolicy::Blocking => has_live_locks(conn, account_uuid)?,
-        LockPolicy::Ignored => false,
-    };
-    let unsettled_outgoing = has_unsettled_outgoing(conn, account_uuid)?;
-    let unresolved_broadcast = has_unresolved_broadcast(conn, account_uuid)?;
-    if !active_reservation && !unsettled_outgoing && !unresolved_broadcast {
-        return Ok(());
-    }
-    Err(RuntimeError::with(
-        ErrorCode::WalletBusy,
-        json!({
-            "operation": operation,
-            "activeReservation": active_reservation,
-            "unsettledOutgoing": unsettled_outgoing,
-            "unresolvedBroadcast": unresolved_broadcast,
-        }),
-    ))
-}
-
-#[cfg(all(test, not(target_arch = "wasm32")))]
-mod tests {
-    use super::*;
-    use rusqlite::Connection;
-
-    /// Runs against a migrated database to prove every table and column in the
-    /// SQL exists, so a typo fails here rather than reading as "idle".
-    #[test]
-    fn every_query_matches_the_real_schema() {
-        let path =
-            std::env::temp_dir().join(format!("zr-guard-schema-{}.sqlite", uuid::Uuid::new_v4()));
-        let _ = std::fs::remove_file(&path);
-        drop(crate::wallet::open_and_migrate("test", path.to_str().unwrap()).expect("migrate"));
-
-        let conn = crate::storage::open_connection(path.to_str().unwrap()).expect("open");
-        let nil = uuid::Uuid::nil().to_string();
-        for (account, locks) in [
-            (None, LockPolicy::Blocking),
-            (None, LockPolicy::Ignored),
-            (Some(nil.as_str()), LockPolicy::Blocking),
-            (Some(nil.as_str()), LockPolicy::Ignored),
-        ] {
-            assert!(assert_idle(&conn, account, "schemaCheck", locks).is_ok());
-        }
-        let _ = std::fs::remove_file(&path);
-    }
-
-    fn fixture(conn: &Connection) {
-        conn.execute_batch(
-            "CREATE TABLE accounts (id INTEGER PRIMARY KEY, uuid BLOB);
-             CREATE TABLE scan_queue (block_range_end INTEGER);
-             CREATE VIEW v_transactions AS
-               SELECT NULL AS account_uuid, NULL AS txid, NULL AS mined_height,
-                      0 AS expired_unmined, 0 AS total_spent WHERE 0;
-             CREATE TABLE ext_onekey_tx_state (
-               txid BLOB, account_uuid BLOB, broadcast_state TEXT
-             );",
-        )
-        .unwrap();
-        for table in LOCKABLE_TABLES {
-            conn.execute_batch(&format!(
-                "CREATE TABLE {table} (
-                   account_id INTEGER, lock_owner BLOB, lock_expiry_height INTEGER
-                 );"
-            ))
-            .unwrap();
-        }
-        conn.execute("INSERT INTO scan_queue VALUES (1001)", [])
-            .unwrap();
-        for (id, uuid) in [(1, uuid::Uuid::from_u128(1)), (2, uuid::Uuid::from_u128(2))] {
-            conn.execute(
-                "INSERT INTO accounts VALUES (?1, ?2)",
-                rusqlite::params![id, uuid.as_bytes().to_vec()],
-            )
-            .unwrap();
-        }
-    }
-
-    /// Locks persist in the database, so they block after a restart.
-    #[test]
-    fn a_persisted_lock_blocks_the_account_that_holds_it() {
-        let conn = Connection::open_in_memory().unwrap();
-        fixture(&conn);
-        let owner = uuid::Uuid::from_u128(1).to_string();
-        let other = uuid::Uuid::from_u128(2).to_string();
-
-        // No locks yet: idle.
-        assert!(assert_idle(&conn, Some(&owner), "removeAccount", LockPolicy::Blocking).is_ok());
-
-        conn.execute(
-            "INSERT INTO orchard_received_notes VALUES (1, ?1, 1500)",
-            rusqlite::params![[7_u8; 32]],
-        )
-        .unwrap();
-
-        let err = assert_idle(&conn, Some(&owner), "removeAccount", LockPolicy::Blocking)
-            .expect_err("a live lock must refuse a destructive operation");
-        assert_eq!(err.code, ErrorCode::WalletBusy);
-        assert_eq!(err.params["activeReservation"], true);
-        assert_eq!(err.params["operation"], "removeAccount");
-
-        // Other accounts are unaffected; the whole-database check sees it.
-        assert!(assert_idle(&conn, Some(&other), "removeAccount", LockPolicy::Blocking).is_ok());
-        assert!(assert_idle(&conn, None, "rewindTo", LockPolicy::Blocking).is_err());
-
-        // clearLockedOutputs clears this lock, so it must not be refused.
-        assert!(assert_idle(
-            &conn,
-            Some(&owner),
-            "clearLockedOutputs",
-            LockPolicy::Ignored
-        )
-        .is_ok());
-    }
-
-    #[test]
-    fn an_expired_lock_no_longer_blocks() {
-        let conn = Connection::open_in_memory().unwrap();
-        fixture(&conn);
-        let owner = uuid::Uuid::from_u128(1).to_string();
-        // Tip is 1000 (scan_queue is end-exclusive); expiry 900 has passed.
-        conn.execute(
-            "INSERT INTO orchard_received_notes VALUES (1, ?1, 900)",
-            rusqlite::params![[7_u8; 32]],
-        )
-        .unwrap();
-        assert!(assert_idle(&conn, Some(&owner), "removeAccount", LockPolicy::Blocking).is_ok());
-    }
-
-    /// With an unresolved broadcast even the repair path must not unlock: that
-    /// would return notes spent by a pending transaction to the selectable pool.
-    #[test]
-    fn an_unresolved_broadcast_blocks_even_the_repair_path() {
-        let conn = Connection::open_in_memory().unwrap();
-        fixture(&conn);
-        let owner = uuid::Uuid::from_u128(1).to_string();
-        conn.execute(
-            "INSERT INTO ext_onekey_tx_state VALUES (?1, ?2, 'pending')",
-            rusqlite::params![[9_u8; 32], uuid::Uuid::from_u128(1).as_bytes().to_vec()],
-        )
-        .unwrap();
-        let err = assert_idle(
-            &conn,
-            Some(&owner),
-            "clearLockedOutputs",
-            LockPolicy::Ignored,
-        )
-        .expect_err("an unresolved broadcast must refuse");
-        assert_eq!(err.code, ErrorCode::WalletBusy);
-        assert_eq!(err.params["unresolvedBroadcast"], true);
-        assert_eq!(err.params["activeReservation"], false);
-    }
-}
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
index 8d129035b..a6a03f936 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
@@ -89,18 +89,15 @@ const HISTORY_ROW_SELECT: &str = "SELECT
              ORDER BY activity.pool
            ) pool_delta
          ), '') AS per_pool_balance_deltas,
-         tx_state.broadcast_state,
-         COALESCE(
-           tx_state.recipient,
-           (SELECT output.to_address
-            FROM v_tx_outputs output
-            WHERE output.txid = tx_summary.txid
-              AND output.from_account_uuid = tx_summary.account_uuid
-              AND (output.to_account_uuid IS NULL
-                   OR output.to_account_uuid <> tx_summary.account_uuid)
-              AND COALESCE(output.is_change, 0) = 0
-            LIMIT 1)
-         ) AS recipient,
+         rejected.txid IS NOT NULL AS rejected,
+         (SELECT output.to_address
+          FROM v_tx_outputs output
+          WHERE output.txid = tx_summary.txid
+            AND output.from_account_uuid = tx_summary.account_uuid
+            AND (output.to_account_uuid IS NULL
+                 OR output.to_account_uuid <> tx_summary.account_uuid)
+            AND COALESCE(output.is_change, 0) = 0
+          LIMIT 1) AS recipient,
          (SELECT COUNT(*)
             FROM v_tx_outputs output
            WHERE output.txid = tx_summary.txid
@@ -111,9 +108,8 @@ const HISTORY_ROW_SELECT: &str = "SELECT
          ) AS external_output_count
      FROM v_transactions tx_summary
      JOIN transactions chain_tx ON chain_tx.txid = tx_summary.txid
-     LEFT JOIN ext_onekey_tx_state tx_state
-       ON tx_state.txid = tx_summary.txid
-      AND tx_state.account_uuid = tx_summary.account_uuid";
+     LEFT JOIN ext_onekey_tx_state rejected
+       ON rejected.txid = tx_summary.txid";
 
 const NON_SAPLING_ACTIVITY: &str = "(
   EXISTS (
@@ -242,7 +238,8 @@ fn row_to_json(row: &rusqlite::Row<'_>) -> rusqlite::Result {
         // Signed account-owned value change for each exact pool. This cannot be
         // recovered from the aggregate row after an Orchard-to-Ironwood move.
         "perPoolBalanceDeltaZat": per_pool_balance_delta_zat,
-        "broadcastState": row.get::<_, Option>(15)?,
+        // The trusted node definitively rejected it; it can never be mined.
+        "rejected": row.get::<_, bool>(15)?,
         "recipient": row.get::<_, Option>(16)?,
         // Outputs sent to addresses outside this account. Zero with spends means
         // an internal transfer, whether or not the fee is known; inferring from
@@ -591,7 +588,7 @@ mod tests {
             let rng = ChaCha20Rng::from_seed([7; 32]);
             let mut db = WalletDb::from_connection(&mut conn, Network::TestNetwork, HostClock, rng);
             WalletMigrator::new()
-                .with_external_migrations(vec![Box::new(crate::tx_state::Migration)])
+                .with_external_migrations(crate::tx_state::migrations())
                 .init_or_migrate(&mut db)
                 .unwrap();
         }
@@ -631,10 +628,6 @@ mod tests {
              );
              CREATE TABLE ext_onekey_tx_state (
                txid BLOB PRIMARY KEY NOT NULL,
-               account_uuid BLOB NOT NULL,
-               reservation_id TEXT UNIQUE,
-               recipient TEXT,
-               broadcast_state TEXT NOT NULL,
                rejection_code INTEGER,
                rejection_reason TEXT
              );
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs
index e5373bf16..778bcf60f 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs
@@ -28,7 +28,6 @@ pub mod blockcache;
 mod circuit_keys;
 pub mod clock;
 pub mod error;
-pub mod guard;
 pub mod history;
 pub mod send;
 pub mod stats;
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
index 46568b9e7..0a0b5aec3 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
@@ -240,7 +240,7 @@ fn broadcast_outcome_ambiguous(message: &str) -> bool {
 /// Only replies proving these bytes can never be mined count as a rejection.
 ///
 /// A rejection makes the host show a failure and the user resend with other
-/// notes (the original's notes stay locked until expiry). If the original
+/// notes (the stored original holds its notes until expiry). If the original
 /// actually propagated, both would be mined. So this is an allowlist:
 /// consensus-invalid (proof, signature, value, branch) or expired. Transient or
 /// policy replies (busy, mempool full, lagging, non-standard) are an unknown
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
index 98abe030b..fbf76ebe6 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
@@ -6,7 +6,7 @@
 //!   runtime.pcztCreate()          build (needs wallet state: note selection, witness, anchor)
 //!   runtime.pcztProve()           prove; pure computation, no private keys
 //!   keys.pcztSignWithAccountKeys() sign (needs the spending keys; in onekey-zcash-keys)
-//!   runtime.pcztSubmit()          extract, store, broadcast (retries resend the stored bytes)
+//!   runtime.pcztSubmit()          extract, store, broadcast (sync rebroadcasts the stored bytes)
 //! ```
 //!
 //! Proving precedes signing: the upstream Signer role needs enough information
@@ -25,10 +25,9 @@
 //! padding) all come from the host; this crate makes no product decisions and
 //! hides no defaults.
 
-use zcash_client_backend::data_api::locking::LockOwner;
 use zcash_client_backend::data_api::wallet::{
     create_pczt_from_proposal, extract_and_store_transaction_from_pczt,
-    input_selection::GreedyInputSelector, propose_transfer, unlock_proposal_inputs, LockRequest,
+    input_selection::GreedyInputSelector, propose_transfer,
 };
 use zcash_client_backend::data_api::WalletRead;
 use zcash_client_backend::fees::{zip317::SingleOutputChangeStrategy, DustOutputPolicy};
@@ -261,7 +260,6 @@ fn build_proposal(
     amount_zat: u64,
     memo: Option<&MemoBytes>,
     policy: SendPolicy,
-    lock: Option,
 ) -> Result {
     let params = *db.params();
     let account_id = account::parse_account_id(db, account_uuid)?;
@@ -324,19 +322,7 @@ fn build_proposal(
                 json!({ "stage": "spendSource", "reason": "required" }),
             )
         })?;
-        let mut base = SpendPolicy::shielded_pools([pool]);
-        // A retry under the same reservation id must reselect what that id
-        // already holds. The default policy excludes every lock, the caller's
-        // own included, so the retry would lock a second set and leave the
-        // first frozen until expiry. Only this owner's locks are admitted.
-        if let Some(lock) = &lock {
-            use zcash_client_backend::data_api::locking::LockedInputPolicy;
-            use zcash_client_backend::data_api::wallet::input_selection::NonEmptyBTreeSet;
-            base = base.with_locked_input_policy(LockedInputPolicy::PreferLocked(
-                NonEmptyBTreeSet::singleton(lock.owner()),
-            ));
-        }
-        base
+        SpendPolicy::shielded_pools([pool])
     };
 
     let selector = GreedyInputSelector::::new();
@@ -358,7 +344,7 @@ fn build_proposal(
             request,
             confirmations,
             &spend_policy,
-            lock,
+            None,
             None,
         );
 
@@ -376,7 +362,7 @@ pub fn quote(
     memo: Option<&MemoBytes>,
     policy: SendPolicy,
 ) -> Result {
-    let proposal = build_proposal(db, account_uuid, to_address, amount_zat, memo, policy, None)?;
+    let proposal = build_proposal(db, account_uuid, to_address, amount_zat, memo, policy)?;
     let fee: u64 = proposal
         .steps()
         .iter()
@@ -390,206 +376,12 @@ pub fn quote(
     .to_string())
 }
 
-// ── Note locking (the host contract's "reservation") ────────────────────
-//
-// Notes behave like UTXOs: spent whole, revealing a nullifier; a second
-// transaction spending the same note is rejected by the node.
-//
-// Between selection and broadcast (select -> review -> password -> sign -> broadcast)
-// a second send or shield would reselect the same notes. Locking marks them as
-// held by one operation so other selections skip them; cancel releases them.
-// Upstream locks also expire by block height, covering an app crash.
-//
-// The proposal stays in memory: `unlock_proposal_inputs` needs it to know which notes to unlock.
-thread_local! {
-    static RESERVATIONS: std::cell::RefCell<
-        std::collections::HashMap)>,
-    > = std::cell::RefCell::new(std::collections::HashMap::new());
-}
-
-fn hex32(bytes: &[u8; 32]) -> String {
-    bytes.iter().map(|b| format!("{b:02x}")).collect()
-}
-
-fn parse_owner(reservation_id: &str) -> Result {
-    let bad = || {
-        RuntimeError::with(
-            ErrorCode::InvalidReservationId,
-            json!({ "value": reservation_id }),
-        )
-    };
-    if reservation_id.len() != 64 {
-        return Err(bad());
-    }
-    let mut out = [0u8; 32];
-    for (i, chunk) in reservation_id.as_bytes().chunks(2).enumerate() {
-        let hex = std::str::from_utf8(chunk).map_err(|_| bad())?;
-        out[i] = u8::from_str_radix(hex, 16).map_err(|_| bad())?;
-    }
-    Ok(LockOwner::new(out))
-}
-
-/// Releases the notes held by a reservation.
+/// Builds an unsigned transfer PCZT for review. Returns `(pcztBytes, feeZat)`.
 ///
-/// Idempotent: an unknown id (sent, already released, or never locked) returns
-/// `false`, not an error.
-pub fn release_reservation(db: &mut Db, reservation_id: &str) -> Result {
-    let owner = parse_owner(reservation_id)?;
-
-    // Finalization is committed in the wallet database before the host can
-    // observe the txid. A durability/bridge failure can therefore leave the
-    // host holding a reservation id for a transaction that already spends the
-    // selected notes. In that state release must only discard the in-memory
-    // proposal; unlocking its inputs would make spent notes selectable again.
-    let finalized_txid = db.transactionally_with_extension(|_wallet, ext| {
-        tx_state::existing_txid_for_reservation(ext, reservation_id, None)
-    })?;
-    if finalized_txid.is_some() {
-        forget_reservation(reservation_id);
-        return Ok(false);
-    }
-
-    if let Some((account_uuid, proposal, approved_pczt)) =
-        RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id))
-    {
-        if let Err(e) = unlock_proposal_inputs(db, &proposal, owner) {
-            RESERVATIONS.with(|r| {
-                r.borrow_mut().insert(
-                    reservation_id.to_owned(),
-                    (account_uuid, proposal, approved_pczt),
-                );
-            });
-            return Err(build_err("unlockProposalInputs", format!("{e:?}")));
-        }
-        // Anything else this owner still holds (a set locked before a retry
-        // replaced the in-memory proposal) goes too.
-        release_persisted_reservation(db, reservation_id, owner)?;
-        return Ok(true);
-    }
-    release_persisted_reservation(db, reservation_id, owner)
-}
-
-// The proposal map is process-local, but the lock owner survives in SQLite.
-// Read the owner's exact output references and use the upstream lock API;
-// never clear another proposal's locks or write wallet-owned tables directly.
-fn release_persisted_reservation(
-    db: &mut Db,
-    reservation_id: &str,
-    owner: LockOwner,
-) -> Result {
-    use rusqlite::OptionalExtension;
-    use zcash_client_backend::{data_api::OutputLockStore, wallet::OutputRef};
-    use zcash_primitives::transaction::TxId;
-    use zcash_protocol::PoolType;
-
-    db.transactionally_with_extension(|wallet, ext| {
-        if tx_state::existing_txid_for_reservation(ext, reservation_id, None)?.is_some() {
-            return Ok(false);
-        }
-        let mut released = false;
-        for (table, index, pool) in [
-            (
-                "sapling_received_notes",
-                "output_index",
-                PoolType::Shielded(ShieldedPool::Sapling),
-            ),
-            (
-                "orchard_received_notes",
-                "action_index",
-                PoolType::Shielded(ShieldedPool::Orchard),
-            ),
-            (
-                "ironwood_received_notes",
-                "action_index",
-                PoolType::Shielded(ShieldedPool::Ironwood),
-            ),
-            (
-                "transparent_received_outputs",
-                "output_index",
-                PoolType::Transparent,
-            ),
-        ] {
-            loop {
-                let output = ext
-                    .query_row(
-                        &format!(
-                            "SELECT tx.txid, output.{index}
-                              FROM {table} output
-                              JOIN transactions tx ON tx.id_tx = output.transaction_id
-                              WHERE output.lock_owner = ?1 LIMIT 1"
-                        ),
-                        [owner.as_bytes()],
-                        |row| Ok((row.get::<_, [u8; 32]>(0)?, row.get::<_, u32>(1)?)),
-                    )
-                    .optional()
-                    .map_err(|e| build_err("readReservationLocks", e))?;
-                let Some((txid, output_index)) = output else {
-                    break;
-                };
-                let output = OutputRef::new(TxId::from_bytes(txid), pool, output_index);
-                if !wallet
-                    .unlock_output(&output, owner)
-                    .map_err(|e| build_err("releaseReservationLock", e))?
-                {
-                    return Err(build_err(
-                        "releaseReservationLock",
-                        "persisted lock was not released",
-                    ));
-                }
-                released = true;
-            }
-        }
-        Ok(released)
-    })
-}
-
-/// Drops the reservation record once the transaction is stored.
-///
-/// The stored spend now holds the notes; unlocking would make spent notes
-/// selectable again.
-pub fn forget_reservation(reservation_id: &str) {
-    RESERVATIONS.with(|r| r.borrow_mut().remove(reservation_id));
-}
-
-/// Drops in-memory proposals of a deleted account; its notes are gone with it.
-pub fn forget_account_reservations(account_uuid: &str) {
-    RESERVATIONS.with(|r| {
-        r.borrow_mut()
-            .retain(|_, (owner_uuid, _, _)| owner_uuid.as_str() != account_uuid)
-    });
-}
-
-/// A reservation maps to one transaction. Rebuilding under a stored id would lock
-/// a second set under the same owner while submit only replays the old one, so
-/// the new locks could be neither used nor released.
-fn refuse_submitted_reservation(db: &mut Db, reservation_id: &str) -> Result<()> {
-    let submitted = db.transactionally_with_extension(|_wallet, ext| {
-        tx_state::existing_txid_for_reservation(ext, reservation_id, None)
-    })?;
-    match submitted {
-        Some(txid) => Err(RuntimeError::with(
-            ErrorCode::InvalidReservationId,
-            json!({ "reason": "alreadySubmitted", "txid": txid }),
-        )),
-        None => Ok(()),
-    }
-}
-
-/// Builds an unsigned transfer PCZT and locks the selected notes.
-///
-/// Returns `{ pcztHex, reservationId }`. The caller must keep `reservationId`
-/// until submit (`pcztSubmit`) or cancel (`releaseReservation`). Locks also
-/// expire by block height, but only as a fallback.
-///
-/// `lock_for_blocks` is host-chosen and must outlast the transaction's expiry
-/// height. The lock covers build until storage; after that the stored
-/// transaction holds the notes.
-///
-/// `reservation_id` may be supplied (64 hex chars) so the caller can generate
-/// and persist it before building, and after a crash still release or relock
-/// its notes. Otherwise one is generated randomly.
-// The public binding keeps proposal policy explicit at the call boundary.
-#[allow(clippy::too_many_arguments)]
+/// Locks nothing: a review the user abandons, or an app killed on the review
+/// page, must leave the notes spendable. Notes are held from the moment
+/// `submit_signed_pczt` stores the signed transaction, until it is mined or
+/// expires.
 pub fn create_pczt(
     db: &mut Db,
     account_uuid: &str,
@@ -597,27 +389,10 @@ pub fn create_pczt(
     amount_zat: u64,
     memo: Option<&MemoBytes>,
     policy: SendPolicy,
-    lock_for_blocks: u32,
-    reservation_id: Option<&str>,
-) -> Result<(Vec, String, u64)> {
+) -> Result<(Vec, u64)> {
     let params = *db.params();
     let account_id = account::parse_account_id(db, account_uuid)?;
-
-    let owner = match reservation_id {
-        Some(id) => parse_owner(id)?,
-        None => LockOwner::random(&mut rand::rngs::OsRng),
-    };
-    let reservation_id = hex32(owner.as_bytes());
-    refuse_submitted_reservation(db, &reservation_id)?;
-    let proposal = build_proposal(
-        db,
-        account_uuid,
-        to_address,
-        amount_zat,
-        memo,
-        policy,
-        Some(LockRequest::new(owner, lock_for_blocks)),
-    )?;
+    let proposal = build_proposal(db, account_uuid, to_address, amount_zat, memo, policy)?;
     let fee_zat = proposal
         .steps()
         .iter()
@@ -625,51 +400,29 @@ pub fn create_pczt(
         .sum();
 
     // InputsErrT / ChangeErrT appear only in the Err branch and cannot be inferred.
-    // The notes are already locked: any failure below must unlock before returning,
-    // since the caller has no reservationId yet and could not release them.
-    let built = (|| -> Result> {
-        let pczt = create_pczt_from_proposal::<
-            Db,
-            _,
-            std::convert::Infallible,
-            _,
-            std::convert::Infallible,
-            _,
-        >(
-            db,
-            ¶ms,
-            account_id,
-            OvkPolicy::Sender,
-            &proposal,
-            None,
-            policy.padding(),
-        )
-        .map_err(|e| build_err("createPczt", format!("{e:?}")))?;
-        let pczt = mark_wallet_outputs(db, account_id, pczt)?;
-
-        pczt.serialize().map_err(|e| {
-            RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "serialize" }))
-                .detail(format!("{e:?}"))
-        })
-    })();
-
-    let bytes = match built {
-        Ok(b) => b,
-        Err(e) => {
-            // Best effort: keep the original error; lock expiry covers an unlock failure.
-            let _ = unlock_proposal_inputs(db, &proposal, owner);
-            return Err(e);
-        }
-    };
-
-    // Keep the proposal: unlocking needs it to know which notes to release.
-    RESERVATIONS.with(|r| {
-        r.borrow_mut().insert(
-            reservation_id.clone(),
-            (account_uuid.to_owned(), proposal, bytes.clone()),
-        );
-    });
-    Ok((bytes, reservation_id, fee_zat))
+    let pczt = create_pczt_from_proposal::<
+        Db,
+        _,
+        std::convert::Infallible,
+        _,
+        std::convert::Infallible,
+        _,
+    >(
+        db,
+        ¶ms,
+        account_id,
+        OvkPolicy::Sender,
+        &proposal,
+        None,
+        policy.padding(),
+    )
+    .map_err(|e| build_err("createPczt", format!("{e:?}")))?;
+    let pczt = mark_wallet_outputs(db, account_id, pczt)?;
+    let bytes = pczt.serialize().map_err(|e| {
+        RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "serialize" }))
+            .detail(format!("{e:?}"))
+    })?;
+    Ok((bytes, fee_zat))
 }
 
 /// Adds the account's ZIP 32 path to every Orchard/Ironwood output that pays
@@ -1021,13 +774,85 @@ pub fn prove_pczt_at_height(
     })
 }
 
-/// Stores the signed PCZT in the wallet; from now on this transaction holds its spent notes.
+/// Spend tables and their spent-output columns, one per pool.
+const SPEND_TABLES: [(&str, &str); 4] = [
+    ("sapling_received_note_spends", "sapling_received_note_id"),
+    ("orchard_received_note_spends", "orchard_received_note_id"),
+    ("ironwood_received_note_spends", "ironwood_received_note_id"),
+    (
+        "transparent_received_output_spends",
+        "transparent_received_output_id",
+    ),
+];
+
+/// Refuses a just-stored transaction that does not spend from `account_uuid`,
+/// or that spends an output another stored transaction still holds (mined, or
+/// unmined and unexpired). Reviews lock nothing, so two open at once can select
+/// the same notes; storing both would leave the second pending until expiry
+/// for a spend the node can never accept.
+fn assert_sole_spend(
+    ext: &zcash_client_sqlite::ExtensionTransaction<'_>,
+    txid: &str,
+    account_uuid: &str,
+) -> Result<()> {
+    let internal = crate::history::display_order_to_internal(txid)?;
+    let refuse = |reason: &str| {
+        RuntimeError::with(
+            ErrorCode::TransactionBuildError,
+            json!({ "stage": "storeSignedPczt", "reason": reason }),
+        )
+    };
+    let spends_from_account: bool = ext
+        .query_row(
+            "SELECT EXISTS(
+               SELECT 1 FROM v_transactions
+               WHERE txid = ?1 AND account_uuid = ?2 AND COALESCE(total_spent, 0) > 0
+             )",
+            rusqlite::params![internal, crate::history::uuid_blob(account_uuid)?],
+            |row| row.get(0),
+        )
+        .map_err(|e| build_err("readStoredSpend", e))?;
+    if !spends_from_account {
+        return Err(refuse("accountMismatch"));
+    }
+    for (table, output) in SPEND_TABLES {
+        let conflict: bool = ext
+            .query_row(
+                &format!(
+                    "SELECT EXISTS(
+                       SELECT 1
+                       FROM transactions own
+                       JOIN {table} own_spend ON own_spend.transaction_id = own.id_tx
+                       JOIN {table} other_spend
+                         ON other_spend.{output} = own_spend.{output}
+                        AND other_spend.transaction_id <> own.id_tx
+                       JOIN transactions other ON other.id_tx = other_spend.transaction_id
+                       WHERE own.txid = ?1
+                         AND (other.mined_height IS NOT NULL
+                              OR COALESCE(other.expiry_height, 0) = 0
+                              OR other.expiry_height
+                                 > COALESCE((SELECT MAX(height) FROM blocks), 0))
+                     )"
+                ),
+                [&internal],
+                |row| row.get(0),
+            )
+            .map_err(|e| build_err("readConflictingSpends", e))?;
+        if conflict {
+            return Err(refuse("inputsAlreadySpent"));
+        }
+    }
+    Ok(())
+}
+
+/// Stores the signed PCZT in the wallet; from now on this transaction holds its
+/// spent notes until it is mined or expires. Stored atomically with its checks:
+/// a refusal leaves the wallet unchanged.
 fn store_signed_pczt(
     db: &mut Db,
     account_uuid: &str,
     pczt: pczt::Pczt,
     orchard_vk: &orchard::circuit::VerifyingKey,
-    reservation_id: &str,
 ) -> Result {
     db.transactionally_with_extension(|wallet, ext| {
         let txid =
@@ -1039,7 +864,7 @@ fn store_signed_pczt(
             )
             .map_err(|e| build_err("extractAndStore", format!("{e:?}")))?
             .to_string();
-        tx_state::insert_finalized(ext, &txid, account_uuid, reservation_id)?;
+        assert_sole_spend(ext, &txid, account_uuid)?;
         Ok(txid)
     })
 }
@@ -1049,7 +874,7 @@ pub enum SubmitOutcome {
     Accepted {
         txid: String,
     },
-    /// The trusted node rejected it; keep the durable record until chain expiry.
+    /// The trusted node rejected it; the stored transaction holds its notes until chain expiry.
     Rejected {
         txid: String,
         error: RuntimeError,
@@ -1070,14 +895,16 @@ fn first_submit_rejection(error: RuntimeError) -> std::result::Result) -> SubmitOutcome {
+fn record_submit_outcome(
+    db: &mut Db,
+    account_uuid: &str,
+    txid: String,
+    result: Result<()>,
+) -> SubmitOutcome {
     match result {
-        Ok(()) => match tx_state::mark_accepted(db, &txid) {
-            Ok(()) => SubmitOutcome::Accepted { txid },
-            Err(error) => SubmitOutcome::Unknown { txid, error },
-        },
+        Ok(()) => SubmitOutcome::Accepted { txid },
         Err(error) => match first_submit_rejection(error) {
-            Ok(error) => match tx_state::mark_rejected(db, &txid, &error) {
+            Ok(error) => match tx_state::record_rejection(db, &txid, account_uuid, &error) {
                 Ok(()) => SubmitOutcome::Rejected { txid, error },
                 Err(error) => SubmitOutcome::Unknown { txid, error },
             },
@@ -1087,50 +914,17 @@ fn record_submit_outcome(db: &mut Db, txid: String, result: Result<()>) -> Submi
 }
 
 /// Persist the exact authorized transaction before any external broadcast.
-/// Retries and crash recovery always rebroadcast the stored bytes.
+///
+/// Submitting the same signed PCZT again stores the same txid again (upstream
+/// upserts it) and rebroadcasts; a transaction the node already rejected is
+/// not sent again.
 pub async fn submit_signed_pczt(
     db: &mut Db,
     client: &mut crate::network::LightClient,
     account_uuid: &str,
     pczt_bytes: &[u8],
-    reservation_id: &str,
 ) -> Result {
-    // Already stored by an earlier submit (host retried): rebroadcast it, never extract again.
-    let stored = db.transactionally_with_extension(|_wallet, ext| {
-        tx_state::existing_txid_for_reservation(ext, reservation_id, Some(account_uuid))
-    })?;
-    if let Some(txid) = stored {
-        if let Err(error) = tx_state::assert_broadcastable(db, &txid) {
-            return Ok(if error.code == ErrorCode::BroadcastRejected {
-                SubmitOutcome::Rejected { txid, error }
-            } else {
-                SubmitOutcome::Unknown { txid, error }
-            });
-        }
-        let raw = match raw_transaction(db, &txid) {
-            Ok(raw) => raw,
-            Err(error) => return Ok(SubmitOutcome::Unknown { txid, error }),
-        };
-        let result = crate::network::broadcast(client, raw).await;
-        return Ok(record_submit_outcome(db, txid, result));
-    }
-
-    let approved_pczt = RESERVATIONS
-        .with(|reservations| {
-            reservations
-                .borrow()
-                .get(reservation_id)
-                .filter(|(owner, _, _)| owner == account_uuid)
-                .map(|(_, _, pczt)| pczt.clone())
-        })
-        .ok_or_else(|| {
-            RuntimeError::with(
-                ErrorCode::InvalidReservationId,
-                json!({ "reason": "missingOrWrongAccount" }),
-            )
-        })?;
-    let bound_pczt = combine_pczt(&approved_pczt, pczt_bytes)?;
-    let pczt = pczt::Pczt::parse(&bound_pczt).map_err(|e| {
+    let pczt = pczt::Pczt::parse(pczt_bytes).map_err(|e| {
         RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "parse" }))
             .detail(format!("{e:?}"))
     })?;
@@ -1143,23 +937,19 @@ pub async fn submit_signed_pczt(
         circuit_version_for_branch(¶ms, *pczt.global().consensus_branch_id(), chain_tip);
     let orchard_vk = crate::circuit_keys::verifying_key(version);
 
-    // This transaction atomically stores raw bytes and the reservation/txid association.
-    // If it fails, nothing has been sent and the caller can safely abandon the proposal.
-    let stored_txid = store_signed_pczt(db, account_uuid, pczt, orchard_vk, reservation_id)?;
-    forget_reservation(reservation_id);
-    // Extraction randomizes binding signatures. Broadcast only the stored bytes,
-    // so the first attempt and every recovery attempt use identical authorizations.
-    let raw = match raw_transaction(db, &stored_txid) {
+    let txid = store_signed_pczt(db, account_uuid, pczt, orchard_vk)?;
+    if let Err(error) = tx_state::assert_not_rejected(db, &txid) {
+        return Ok(match error.code {
+            ErrorCode::BroadcastRejected => SubmitOutcome::Rejected { txid, error },
+            _ => SubmitOutcome::Unknown { txid, error },
+        });
+    }
+    let raw = match raw_transaction(db, &txid) {
         Ok(raw) => raw,
-        Err(error) => {
-            return Ok(SubmitOutcome::Unknown {
-                txid: stored_txid,
-                error,
-            })
-        }
+        Err(error) => return Ok(SubmitOutcome::Unknown { txid, error }),
     };
     let result = crate::network::broadcast(client, raw).await;
-    Ok(record_submit_outcome(db, stored_txid, result))
+    Ok(record_submit_outcome(db, account_uuid, txid, result))
 }
 
 /// Reads a stored transaction's raw bytes from the wallet for rebroadcast.
@@ -1199,27 +989,8 @@ pub const PROVE_ORCHARD: bool = true;
 pub const PROVE_SAPLING: bool = false;
 pub const PROVE_IRONWOOD: bool = true;
 
-/// Clears all advisory locks for an account during explicit state repair.
-/// Normal cancellation uses the durable owner-scoped `release_reservation`,
-/// including after restart. This broader operation also clears other proposals
-/// and must not be used as an automatic cancellation fallback.
-pub fn clear_locked_outputs(db: &mut Db, account_uuid: &str) -> Result {
-    use zcash_client_backend::data_api::OutputLockStore;
-
-    let account_id = account::parse_account_id(db, account_uuid)?;
-    let n = db
-        .clear_locked_outputs(account_id)
-        .map_err(|e| build_err("clearLockedOutputs", e))?;
-
-    RESERVATIONS.with(|r| {
-        r.borrow_mut()
-            .retain(|_, (owner_account_uuid, _, _)| owner_account_uuid != account_uuid);
-    });
-    Ok(n as u32)
-}
-
 #[cfg(all(test, not(target_arch = "wasm32")))]
-mod reservation_recovery_tests {
+mod submit_state_tests {
     use super::*;
     use rand::SeedableRng;
     use rand_chacha::ChaCha20Rng;
@@ -1236,30 +1007,44 @@ mod reservation_recovery_tests {
         )
     }
 
-    fn outcome_wallet(fail_update: bool) -> (Db, String) {
+    fn outcome_wallet(fail_write: bool) -> (Db, String) {
         let conn = Connection::open_in_memory().unwrap();
-        conn.execute_batch("CREATE TABLE ext_onekey_tx_state (txid BLOB PRIMARY KEY, account_uuid BLOB, reservation_id TEXT, broadcast_state TEXT, rejection_code INTEGER, rejection_reason TEXT);").unwrap();
-        conn.execute("INSERT INTO ext_onekey_tx_state (txid,account_uuid,reservation_id,broadcast_state) VALUES (?1,?2,'review','pending')", rusqlite::params![[1u8;32].as_slice(), uuid::Uuid::from_u128(1).as_bytes().as_slice()]).unwrap();
-        if fail_update {
-            conn.execute_batch("CREATE TRIGGER fail_state BEFORE UPDATE ON ext_onekey_tx_state BEGIN SELECT RAISE(ABORT,'synthetic write failure'); END;").unwrap();
+        conn.execute_batch(
+            "CREATE TABLE ext_onekey_tx_state (
+               txid BLOB PRIMARY KEY NOT NULL,
+               account_uuid BLOB NOT NULL,
+               rejection_code INTEGER,
+               rejection_reason TEXT
+             );",
+        )
+        .unwrap();
+        if fail_write {
+            conn.execute_batch(
+                "CREATE TRIGGER fail_state BEFORE INSERT ON ext_onekey_tx_state
+                 BEGIN SELECT RAISE(ABORT, 'synthetic write failure'); END;",
+            )
+            .unwrap();
         }
         (wallet(conn), "01".repeat(32))
     }
 
     #[test]
-    fn both_first_and_retried_broadcasts_record_definitive_node_outcomes() {
+    fn only_a_node_rejection_is_recorded() {
         let (mut db, txid) = outcome_wallet(false);
+        let account = uuid::Uuid::nil().to_string();
         assert!(matches!(
-            record_submit_outcome(&mut db, txid.clone(), Ok(())),
+            record_submit_outcome(&mut db, &account, txid.clone(), Ok(())),
             SubmitOutcome::Accepted { .. }
         ));
+        tx_state::assert_not_rejected(&mut db, &txid).unwrap();
+
         let rejected = RuntimeError::new(ErrorCode::BroadcastRejected).detail("bad-txns-expired");
         assert!(matches!(
-            record_submit_outcome(&mut db, txid.clone(), Err(rejected)),
+            record_submit_outcome(&mut db, &account, txid.clone(), Err(rejected)),
             SubmitOutcome::Rejected { .. }
         ));
         assert_eq!(
-            tx_state::assert_broadcastable(&mut db, &txid)
+            tx_state::assert_not_rejected(&mut db, &txid)
                 .unwrap_err()
                 .code,
             ErrorCode::BroadcastRejected
@@ -1267,126 +1052,103 @@ mod reservation_recovery_tests {
     }
 
     #[test]
-    fn accepted_broadcast_with_failed_state_write_keeps_its_known_txid() {
-        let (mut db, txid) = outcome_wallet(true);
-        match record_submit_outcome(&mut db, txid.clone(), Ok(())) {
-            SubmitOutcome::Unknown { txid: retained, .. } => assert_eq!(retained, txid),
-            _ => panic!("an accepted transaction must not become a signing failure"),
-        }
-        tx_state::assert_broadcastable(&mut db, &txid).unwrap();
-    }
-
-    #[test]
-    fn duplicate_spend_or_network_failure_keeps_the_persisted_send_pending() {
+    fn duplicate_spend_or_network_failure_keeps_the_stored_send_pending() {
         for code in [ErrorCode::BroadcastOutcomeUnknown, ErrorCode::NetworkError] {
             let (mut db, txid) = outcome_wallet(false);
             assert!(matches!(
-                record_submit_outcome(&mut db, txid.clone(), Err(RuntimeError::new(code))),
+                record_submit_outcome(
+                    &mut db,
+                    &uuid::Uuid::nil().to_string(),
+                    txid.clone(),
+                    Err(RuntimeError::new(code))
+                ),
                 SubmitOutcome::Unknown { .. }
             ));
-            tx_state::assert_broadcastable(&mut db, &txid).unwrap();
+            tx_state::assert_not_rejected(&mut db, &txid).unwrap();
         }
     }
 
     #[test]
-    fn a_reservation_that_already_has_a_stored_transaction_cannot_build_again() {
-        let (mut db, txid) = outcome_wallet(false);
-        let e = refuse_submitted_reservation(&mut db, "review").unwrap_err();
-        assert_eq!(e.code, ErrorCode::InvalidReservationId);
-        assert_eq!(e.params["txid"], txid);
-        refuse_submitted_reservation(&mut db, &"ab".repeat(32)).unwrap();
-    }
-
-    #[test]
-    fn retry_cannot_use_another_accounts_reservation() {
-        let (mut db, txid) = outcome_wallet(false);
-        let owner = uuid::Uuid::from_u128(1).to_string();
-        let other = uuid::Uuid::from_u128(2).to_string();
-        db.transactionally_with_extension(|_, ext| {
-            assert_eq!(
-                tx_state::existing_txid_for_reservation(ext, "review", Some(&owner))?,
-                Some(txid)
-            );
-            assert_eq!(
-                tx_state::existing_txid_for_reservation(ext, "review", Some(&other))
-                    .unwrap_err()
-                    .code,
-                ErrorCode::InvalidReservationId
-            );
-            Ok::<(), RuntimeError>(())
-        })
-        .unwrap();
+    fn a_rejection_that_cannot_be_recorded_stays_unknown() {
+        let (mut db, txid) = outcome_wallet(true);
+        let rejected = RuntimeError::new(ErrorCode::BroadcastRejected);
+        match record_submit_outcome(
+            &mut db,
+            &uuid::Uuid::nil().to_string(),
+            txid.clone(),
+            Err(rejected),
+        ) {
+            SubmitOutcome::Unknown { txid: retained, .. } => assert_eq!(retained, txid),
+            _ => panic!("an unrecorded rejection must not drop the stored transaction"),
+        }
     }
 
-    #[test]
-    fn restart_cancellation_releases_only_its_owner_and_preserves_finalized_locks() {
-        let path =
-            std::env::temp_dir().join(format!("zcash-reservation-{}.sqlite", uuid::Uuid::new_v4()));
-        let owner = [1_u8; 32];
-        let other_owner = [2_u8; 32];
-        let conn = Connection::open(&path).unwrap();
+    /// Transaction 1 is the one just stored; it spends orchard note 7.
+    fn spend_fixture(other: Option<(Option, Option)>) -> Db {
+        let conn = Connection::open_in_memory().unwrap();
         conn.execute_batch(
-            "CREATE TABLE transactions (id_tx INTEGER PRIMARY KEY, txid BLOB);
-                            CREATE TABLE ext_onekey_tx_state (txid BLOB, reservation_id TEXT, account_uuid BLOB);",
+            "CREATE TABLE transactions (
+               id_tx INTEGER PRIMARY KEY, txid BLOB, mined_height INTEGER, expiry_height INTEGER
+             );
+             CREATE TABLE blocks (height INTEGER);
+             INSERT INTO blocks VALUES (1000);
+             CREATE TABLE v_transactions (txid BLOB, account_uuid BLOB, total_spent INTEGER);",
         )
         .unwrap();
-        conn.execute("INSERT INTO transactions VALUES (1, ?1)", [[3_u8; 32]])
-            .unwrap();
-        for (table, index) in [
-            ("sapling_received_notes", "output_index"),
-            ("orchard_received_notes", "action_index"),
-            ("ironwood_received_notes", "action_index"),
-            ("transparent_received_outputs", "output_index"),
-        ] {
+        for (table, output) in SPEND_TABLES {
             conn.execute_batch(&format!(
-                "CREATE TABLE {table} (
-                transaction_id INTEGER, {index} INTEGER, lock_owner BLOB, lock_expiry_height INTEGER
-            );"
+                "CREATE TABLE {table} ({output} INTEGER, transaction_id INTEGER);"
             ))
             .unwrap();
-            conn.execute(
-                &format!("INSERT INTO {table} VALUES (1, 0, ?1, 1000), (1, 1, ?2, 1000)"),
-                rusqlite::params![owner, other_owner],
-            )
-            .unwrap();
-        }
-        drop(wallet(conn));
-
-        let mut db = wallet(Connection::open(&path).unwrap());
-        assert!(release_reservation(&mut db, &hex32(&owner)).unwrap());
-        assert!(!release_reservation(&mut db, &hex32(&owner)).unwrap());
-        let conn = Connection::open(&path).unwrap();
-        for table in [
-            "sapling_received_notes",
-            "orchard_received_notes",
-            "ironwood_received_notes",
-            "transparent_received_outputs",
-        ] {
-            let locks: u32 = conn.query_row(&format!("SELECT COUNT(*) FROM {table} WHERE lock_owner = ?1 AND lock_expiry_height = 1000"), [other_owner], |row| row.get(0)).unwrap();
-            assert_eq!(locks, 1);
-            let released: u32 = conn.query_row(&format!("SELECT COUNT(*) FROM {table} WHERE lock_owner IS NULL AND lock_expiry_height IS NULL"), [], |row| row.get(0)).unwrap();
-            assert_eq!(released, 1);
         }
         conn.execute(
-            "INSERT INTO ext_onekey_tx_state (txid, reservation_id, account_uuid) VALUES (?1, ?2, ?3)",
-            rusqlite::params![[4_u8; 32], hex32(&other_owner), uuid::Uuid::from_u128(1).as_bytes()],
+            "INSERT INTO transactions VALUES (1, ?1, NULL, 1040)",
+            [[1_u8; 32]],
         )
         .unwrap();
-        assert!(!release_reservation(&mut db, &hex32(&other_owner)).unwrap());
-        let locks: u32 = conn
-            .query_row(
-                "SELECT COUNT(*) FROM orchard_received_notes WHERE lock_owner = ?1",
-                [other_owner],
-                |row| row.get(0),
+        conn.execute(
+            "INSERT INTO v_transactions VALUES (?1, ?2, 10)",
+            rusqlite::params![[1_u8; 32], uuid::Uuid::from_u128(1).as_bytes().as_slice()],
+        )
+        .unwrap();
+        conn.execute("INSERT INTO orchard_received_note_spends VALUES (7, 1)", [])
+            .unwrap();
+        if let Some((mined_height, expiry_height)) = other {
+            conn.execute(
+                "INSERT INTO transactions VALUES (2, ?1, ?2, ?3)",
+                rusqlite::params![[2_u8; 32], mined_height, expiry_height],
             )
             .unwrap();
-        assert_eq!(locks, 1);
-        drop(conn);
-        drop(db);
-        std::fs::remove_file(path).unwrap();
+            conn.execute("INSERT INTO orchard_received_note_spends VALUES (7, 2)", [])
+                .unwrap();
+        }
+        wallet(conn)
+    }
+
+    fn check(db: &mut Db, account: u128) -> Result<()> {
+        let txid = crate::history::hex_display_order(&[1_u8; 32]);
+        let account = uuid::Uuid::from_u128(account).to_string();
+        db.transactionally_with_extension(|_, ext| assert_sole_spend(ext, &txid, &account))
+    }
+
+    #[test]
+    fn a_spend_already_held_by_another_stored_transaction_is_refused() {
+        check(&mut spend_fixture(None), 1).unwrap();
+        // Expired at 990, below the 1000 tip: its notes are free again.
+        check(&mut spend_fixture(Some((None, Some(990)))), 1).unwrap();
+        for held in [(None, Some(1040)), (None, None), (Some(900), Some(990))] {
+            let error = check(&mut spend_fixture(Some(held)), 1).unwrap_err();
+            assert_eq!(error.code, ErrorCode::TransactionBuildError);
+            assert_eq!(error.params["reason"], "inputsAlreadySpent");
+        }
     }
-}
 
+    #[test]
+    fn a_pczt_spending_from_another_account_is_refused() {
+        let error = check(&mut spend_fixture(None), 2).unwrap_err();
+        assert_eq!(error.params["reason"], "accountMismatch");
+    }
+}
 #[cfg(all(test, not(target_arch = "wasm32")))]
 mod policy_tests {
     use super::*;
@@ -1577,6 +1339,21 @@ mod combine_tests {
         assert_eq!(result.shielded_sighash(), approved.shielded_sighash());
     }
 
+    #[test]
+    fn transaction_identity_is_stable_on_retry_and_changes_with_the_recipient() {
+        let signed = signed_copy(&transparent_pczt(90_000, 0xaa, false));
+        let extract = |bytes: &[u8]| {
+            let finalized = SpendFinalizer::new(pczt::Pczt::parse(bytes).unwrap())
+                .finalize_spends()
+                .unwrap();
+            extract_pczt(finalized).unwrap()
+        };
+        let first = extract(&signed);
+        assert_eq!(first.txid(), extract(&signed).txid());
+        let other = extract(&signed_copy(&transparent_pczt(90_000, 0xbb, false)));
+        assert_ne!(first.txid(), other.txid());
+    }
+
     // Conflicting values on a field both sides carry: the bare Combiner already
     // refuses this one. Pinned so a future upstream bump cannot quietly relax it.
     #[test]
@@ -1775,8 +1552,12 @@ mod owned_output_tests {
     /// Ironwood or (when `orchard_change`) in Orchard. The external recipient
     /// gets `user_address` as `create_pczt_from_proposal` sets it.
     fn spend(spent_scope: Scope, orchard_change: bool) -> Built {
+        spend_to(spent_scope, orchard_change, 9)
+    }
+
+    fn spend_to(spent_scope: Scope, orchard_change: bool, recipient_seed: u8) -> Built {
         let fvk = ours();
-        let foreign = FullViewingKey::from(&spending_key(&[9; 32], 0));
+        let foreign = FullViewingKey::from(&spending_key(&[recipient_seed; 32], 0));
         let recipient = foreign.address_at(0u32, Scope::External);
         let change_address = fvk.address_at(0u32, Scope::Internal);
         let spent = note(fvk.address_at(0u32, spent_scope), INPUT, NoteVersion::V2);
@@ -1855,6 +1636,76 @@ mod owned_output_tests {
         }
     }
 
+    #[tokio::test]
+    async fn another_payment_with_a_shared_input_cannot_reuse_the_stored_transaction() {
+        use rand::SeedableRng;
+        use rand_chacha::ChaCha20Rng;
+
+        let first = spend_to(Scope::External, false, 9).pczt;
+        let other = spend_to(Scope::External, false, 10).pczt;
+        let common = first
+            .orchard()
+            .actions()
+            .iter()
+            .find_map(|action| {
+                let nf = action.spend().nullifier();
+                other
+                    .orchard()
+                    .actions()
+                    .iter()
+                    .any(|a| a.spend().nullifier() == nf)
+                    .then_some(*nf)
+            })
+            .expect("synthetic payments spend the same note");
+        let conn = rusqlite::Connection::open_in_memory().unwrap();
+        conn.execute_batch("CREATE TABLE scan_queue (block_range_end INTEGER);
+            INSERT INTO scan_queue VALUES (3500001);
+            CREATE TABLE blocks (height INTEGER);
+            INSERT INTO blocks VALUES (3500000);
+            CREATE TABLE transactions (id_tx INTEGER, txid BLOB, raw BLOB, mined_height INTEGER, expiry_height INTEGER);
+            CREATE TABLE orchard_received_notes (id INTEGER, nf BLOB);
+            CREATE TABLE orchard_received_note_spends (orchard_received_note_id INTEGER, transaction_id INTEGER);
+            CREATE TABLE ironwood_received_notes (id INTEGER, nf BLOB);
+            CREATE TABLE ironwood_received_note_spends (ironwood_received_note_id INTEGER, transaction_id INTEGER);
+            CREATE TABLE ext_onekey_tx_state (txid BLOB, account_uuid BLOB, rejection_code INTEGER, rejection_reason TEXT);")
+            .unwrap();
+        conn.execute(
+            "INSERT INTO transactions VALUES (1, ?1, x'00', NULL, 3500040)",
+            [[1u8; 32]],
+        )
+        .unwrap();
+        conn.execute(
+            "INSERT INTO orchard_received_notes VALUES (7, ?1)",
+            [common],
+        )
+        .unwrap();
+        conn.execute("INSERT INTO orchard_received_note_spends VALUES (7, 1)", [])
+            .unwrap();
+        let mut db = zcash_client_sqlite::WalletDb::from_connection(
+            conn,
+            Network::MainNetwork,
+            crate::clock::HostClock,
+            ChaCha20Rng::from_seed([0; 32]),
+        );
+        let mut client = crate::network::LightClient::new(
+            tonic::transport::Endpoint::from_static("http://127.0.0.1:1").connect_lazy(),
+        );
+
+        // The second payment has no proof or authorization. A stored shared
+        // input must never let it skip extraction and return the first txid.
+        match submit_signed_pczt(
+            &mut db,
+            &mut client,
+            &uuid::Uuid::nil().to_string(),
+            &other.serialize().unwrap(),
+        )
+        .await
+        {
+            Err(error) => assert_eq!(error.params["stage"], "extractAndStore"),
+            Ok(_) => panic!("a different payment must not reuse a stored transaction"),
+        }
+    }
+
     /// Runs `f` on the parsed Orchard (or Ironwood) bundle of `pczt`.
     fn inspect(pczt: &pczt::Pczt, ironwood: bool, f: impl FnOnce(&Bundle) -> T) -> T {
         let mut out = None;
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
index 028d44089..e0206cdaf 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
@@ -1,3 +1,12 @@
+//! OneKey-owned record of node rejections.
+//!
+//! Everything else about a sent transaction lives in `zcash_client_sqlite`:
+//! the signed transaction is stored before broadcast, and stays in
+//! `v_transactions` as unmined (holding its notes) until it is mined or
+//! expires. The one fact the wallet schema cannot hold is that the trusted node
+//! definitively rejected it; that must stop rebroadcasts and show the send as
+//! failed.
+
 use std::collections::HashSet;
 
 use rusqlite::{params, OptionalExtension};
@@ -12,14 +21,22 @@ use crate::error::{ErrorCode, Result, RuntimeError};
 use crate::history::{display_order_to_internal, hex_display_order, uuid_blob};
 use crate::wallet::Db;
 
-const MIGRATION_ID: Uuid = Uuid::from_u128(0x5be0af90_63f4_43ea_ae65_8207c84e46dd);
+const LIFECYCLE_MIGRATION_ID: Uuid = Uuid::from_u128(0x5be0af90_63f4_43ea_ae65_8207c84e46dd);
+const REJECTIONS_MIGRATION_ID: Uuid = Uuid::from_u128(0x0d3b6f2e_9a41_4c8e_b7d5_3e1f6a2c9b70);
 pub(crate) const TABLE: &str = "ext_onekey_tx_state";
 
-pub struct Migration;
+/// External migrations, in dependency order.
+pub fn migrations() -> Vec>> {
+    vec![Box::new(LifecycleMigration), Box::new(RejectionsMigration)]
+}
+
+/// The original lifecycle table. Kept so databases that already applied it
+/// keep a consistent migration graph; `RejectionsMigration` replaces it.
+struct LifecycleMigration;
 
-impl schemerz::Migration for Migration {
+impl schemerz::Migration for LifecycleMigration {
     fn id(&self) -> Uuid {
-        MIGRATION_ID
+        LIFECYCLE_MIGRATION_ID
     }
 
     fn dependencies(&self) -> HashSet {
@@ -31,7 +48,7 @@ impl schemerz::Migration for Migration {
     }
 }
 
-impl RusqliteMigration for Migration {
+impl RusqliteMigration for LifecycleMigration {
     type Error = WalletMigrationError;
 
     fn up(&self, transaction: &rusqlite::Transaction) -> std::result::Result<(), Self::Error> {
@@ -55,7 +72,53 @@ impl RusqliteMigration for Migration {
     }
 
     fn down(&self, _transaction: &rusqlite::Transaction) -> std::result::Result<(), Self::Error> {
-        Err(WalletMigrationError::CannotRevert(MIGRATION_ID))
+        Err(WalletMigrationError::CannotRevert(LIFECYCLE_MIGRATION_ID))
+    }
+}
+
+/// Keeps only node rejections. Pending/accepted rows are dropped: those
+/// transactions are already unmined rows in `v_transactions`.
+struct RejectionsMigration;
+
+impl schemerz::Migration for RejectionsMigration {
+    fn id(&self) -> Uuid {
+        REJECTIONS_MIGRATION_ID
+    }
+
+    fn dependencies(&self) -> HashSet {
+        HashSet::from([LIFECYCLE_MIGRATION_ID])
+    }
+
+    fn description(&self) -> &'static str {
+        "Reduces OneKey Zcash transaction state to node rejections."
+    }
+}
+
+impl RusqliteMigration for RejectionsMigration {
+    type Error = WalletMigrationError;
+
+    fn up(&self, transaction: &rusqlite::Transaction) -> std::result::Result<(), Self::Error> {
+        transaction.execute_batch(
+            "CREATE TABLE ext_onekey_tx_state_new (
+               txid BLOB PRIMARY KEY NOT NULL,
+               account_uuid BLOB NOT NULL,
+               rejection_code INTEGER,
+               rejection_reason TEXT
+             );
+             INSERT INTO ext_onekey_tx_state_new (
+               txid, account_uuid, rejection_code, rejection_reason
+             )
+               SELECT txid, account_uuid, rejection_code, rejection_reason
+               FROM ext_onekey_tx_state
+               WHERE broadcast_state = 'rejected';
+             DROP TABLE ext_onekey_tx_state;
+             ALTER TABLE ext_onekey_tx_state_new RENAME TO ext_onekey_tx_state;",
+        )?;
+        Ok(())
+    }
+
+    fn down(&self, _transaction: &rusqlite::Transaction) -> std::result::Result<(), Self::Error> {
+        Err(WalletMigrationError::CannotRevert(REJECTIONS_MIGRATION_ID))
     }
 }
 
@@ -67,214 +130,119 @@ fn db_err(operation: &'static str, error: impl std::fmt::Display) -> RuntimeErro
     .detail(error)
 }
 
-pub fn existing_txid_for_reservation(
-    ext: &ExtensionTransaction<'_>,
-    reservation_id: &str,
-    expected_account_uuid: Option<&str>,
-) -> Result> {
-    let txid = ext
-        .query_row(
-            &format!("SELECT txid, account_uuid FROM {TABLE} WHERE reservation_id = ?1"),
-            [reservation_id],
-            |row| Ok((row.get::<_, Vec>(0)?, row.get::<_, Vec>(1)?)),
+/// Account that sent this stored transaction, for a rejection row.
+pub fn account_uuid_for_txid(db: &mut Db, txid: &str) -> Result {
+    let txid = display_order_to_internal(txid)?;
+    let bytes = db.transactionally_with_extension(|_wallet, ext| {
+        ext.query_row(
+            "SELECT account_uuid
+             FROM v_transactions
+             WHERE txid = ?1 AND COALESCE(total_spent, 0) > 0
+             LIMIT 1",
+            [&txid],
+            |row| row.get::<_, Vec>(0),
         )
-        .optional()
-        .map_err(|error| db_err("findBroadcastIntent", error))?;
-    if let (Some((_, owner)), Some(expected)) = (&txid, expected_account_uuid) {
-        if *owner != uuid_blob(expected)? {
-            return Err(RuntimeError::new(ErrorCode::InvalidReservationId));
-        }
-    }
-    Ok(txid.map(|(bytes, _)| hex_display_order(&bytes)))
+        .map_err(|error| db_err("readAccountForTxid", error))
+    })?;
+    uuid::Uuid::from_slice(&bytes)
+        .map(|uuid| uuid.to_string())
+        .map_err(|error| db_err("parseAccountForTxid", error))
 }
 
-pub fn insert_finalized(
-    ext: &ExtensionTransaction<'_>,
+/// Records the node's definitive rejection of a stored transaction.
+pub fn record_rejection(
+    db: &mut Db,
     txid: &str,
     account_uuid: &str,
-    reservation_id: &str,
+    error: &RuntimeError,
 ) -> Result<()> {
     let txid = display_order_to_internal(txid)?;
     let account_uuid = uuid_blob(account_uuid)?;
-    ext.execute(
-        &format!(
-            "INSERT INTO {TABLE} (
-               txid, account_uuid, reservation_id, recipient, broadcast_state
-             )
-             VALUES (
-               ?1, ?2, ?3,
-               (SELECT output.to_address
-                FROM v_tx_outputs output
-                WHERE output.txid = ?1
-                  AND output.from_account_uuid = ?2
-                  AND (output.to_account_uuid IS NULL OR output.to_account_uuid <> ?2)
-                  AND COALESCE(output.is_change, 0) = 0
-                LIMIT 1),
-               'pending'
-             )
-             ON CONFLICT(txid) DO UPDATE SET
-               account_uuid = excluded.account_uuid,
-               reservation_id = excluded.reservation_id,
-               recipient = COALESCE(excluded.recipient, {TABLE}.recipient),
-               broadcast_state = 'pending',
-               rejection_code = NULL,
-               rejection_reason = NULL"
-        ),
-        params![txid, account_uuid, reservation_id],
-    )
-    .map_err(|error| db_err("saveBroadcastIntent", error))?;
-    Ok(())
-}
-
-pub fn assert_broadcastable(db: &mut Db, txid: &str) -> Result<()> {
-    let txid = display_order_to_internal(txid)?;
-    db.transactionally_with_extension(|_wallet, ext| {
-        let state = ext
-            .query_row(
-                &format!(
-                    "SELECT broadcast_state, rejection_code, rejection_reason
-                     FROM {TABLE}
-                     WHERE txid = ?1"
-                ),
-                [&txid],
-                |row| {
-                    Ok((
-                        row.get::<_, String>(0)?,
-                        row.get::<_, Option>(1)?,
-                        row.get::<_, Option>(2)?,
-                    ))
-                },
-            )
-            .optional()
-            .map_err(|error| db_err("readBroadcastIntent", error))?;
-        match state {
-            Some((state, _, _)) if state == "pending" || state == "accepted" => Ok(()),
-            Some((state, error_code, reason)) if state == "rejected" => {
-                let mut error = RuntimeError::with(
-                    ErrorCode::BroadcastRejected,
-                    serde_json::json!({ "errorCode": error_code }),
-                );
-                error.detail = reason;
-                Err(error)
-            }
-            Some((state, _, _)) => Err(RuntimeError::with(
-                ErrorCode::BroadcastIntentNotReady,
-                serde_json::json!({ "txid": hex_display_order(&txid), "state": state }),
-            )),
-            None => Err(RuntimeError::with(
-                ErrorCode::BroadcastIntentNotFound,
-                serde_json::json!({ "txid": hex_display_order(&txid) }),
-            )),
-        }
-    })
-}
-
-pub fn mark_accepted(db: &mut Db, txid: &str) -> Result<()> {
-    update_outcome(db, txid, "accepted", None)
-}
-
-pub fn mark_rejected(db: &mut Db, txid: &str, error: &RuntimeError) -> Result<()> {
-    let error_code = error
+    let rejection_code = error
         .params
         .get("errorCode")
         .and_then(serde_json::Value::as_i64);
-    update_outcome(
-        db,
-        txid,
-        "rejected",
-        Some((error_code, error.detail.as_deref())),
-    )
-}
-
-fn update_outcome(
-    db: &mut Db,
-    txid: &str,
-    state: &str,
-    rejection: Option<(Option, Option<&str>)>,
-) -> Result<()> {
-    let txid = display_order_to_internal(txid)?;
-    let (rejection_code, rejection_reason) = rejection.unwrap_or((None, None));
     db.transactionally_with_extension(|_wallet, ext| {
-        let changed = ext
-            .execute(
-                &format!(
-                    "UPDATE {TABLE}
-                     SET broadcast_state = ?2,
-                         rejection_code = ?3,
-                         rejection_reason = ?4
-                     WHERE txid = ?1"
-                ),
-                params![txid, state, rejection_code, rejection_reason],
-            )
-            .map_err(|error| db_err("updateBroadcastIntent", error))?;
-        if changed == 0 {
-            return Err(RuntimeError::with(
-                ErrorCode::BroadcastIntentNotFound,
-                serde_json::json!({ "txid": hex_display_order(&txid) }),
-            ));
-        }
+        ext.execute(
+            &format!(
+                "INSERT INTO {TABLE} (txid, account_uuid, rejection_code, rejection_reason)
+                 VALUES (?1, ?2, ?3, ?4)
+                 ON CONFLICT(txid) DO UPDATE SET
+                   account_uuid = excluded.account_uuid,
+                   rejection_code = excluded.rejection_code,
+                   rejection_reason = excluded.rejection_reason"
+            ),
+            params![txid, account_uuid, rejection_code, error.detail.as_deref()],
+        )
+        .map_err(|error| db_err("recordRejection", error))?;
         Ok(())
     })
 }
 
-pub fn unresolved_txids(conn: &rusqlite::Connection, account_uuid: &str) -> Result> {
-    let account_uuid = uuid_blob(account_uuid)?;
-    let mut stmt = conn
-        .prepare(&format!(
-            "SELECT state.txid
-             FROM {TABLE} state
-             LEFT JOIN v_transactions tx
-               ON tx.txid = state.txid AND tx.account_uuid = state.account_uuid
-             WHERE state.account_uuid = ?1
-               AND state.broadcast_state IN ('pending', 'accepted')
-               AND tx.mined_height IS NULL
-               AND COALESCE(tx.expired_unmined, 0) = 0"
-        ))
-        .map_err(|error| db_err("listUnresolvedBroadcasts", error))?;
-    let rows = stmt
-        .query_map([account_uuid], |row| row.get::<_, Vec>(0))
-        .map_err(|error| db_err("listUnresolvedBroadcasts", error))?;
-    rows.map(|row| {
-        row.map(|bytes| hex_display_order(&bytes))
-            .map_err(|error| db_err("listUnresolvedBroadcasts", error))
-    })
-    .collect()
+/// Fails with the recorded `BroadcastRejected` if the node already rejected this transaction.
+pub fn assert_not_rejected(db: &mut Db, txid: &str) -> Result<()> {
+    let txid = display_order_to_internal(txid)?;
+    let rejection = db.transactionally_with_extension(|_wallet, ext| {
+        ext.query_row(
+            &format!("SELECT rejection_code, rejection_reason FROM {TABLE} WHERE txid = ?1"),
+            [&txid],
+            |row| {
+                Ok((
+                    row.get::<_, Option>(0)?,
+                    row.get::<_, Option>(1)?,
+                ))
+            },
+        )
+        .optional()
+        .map_err(|error| db_err("readRejection", error))
+    })?;
+    match rejection {
+        None => Ok(()),
+        Some((error_code, reason)) => {
+            let mut error = RuntimeError::with(
+                ErrorCode::BroadcastRejected,
+                serde_json::json!({ "errorCode": error_code }),
+            );
+            error.detail = reason;
+            Err(error)
+        }
+    }
 }
 
-pub fn rebroadcastable_txids(
-    conn: &rusqlite::Connection,
-    account_uuid: &str,
-) -> Result> {
+/// This account's stored outgoing transactions that are neither mined, expired
+/// nor rejected: the ones a sync must rebroadcast.
+pub fn pending_txids(conn: &rusqlite::Connection, account_uuid: &str) -> Result> {
     let account_uuid = uuid_blob(account_uuid)?;
     let mut stmt = conn
         .prepare(&format!(
-            "SELECT state.txid
-             FROM {TABLE} state
-             JOIN v_transactions tx
-               ON tx.txid = state.txid AND tx.account_uuid = state.account_uuid
-             WHERE state.account_uuid = ?1
-               AND state.broadcast_state IN ('pending', 'accepted')
+            "SELECT tx.txid
+             FROM v_transactions tx
+             JOIN transactions chain_tx ON chain_tx.txid = tx.txid
+             WHERE tx.account_uuid = ?1
                AND tx.mined_height IS NULL
-               AND COALESCE(tx.expired_unmined, 0) = 0"
+               AND tx.expired_unmined = 0
+               AND COALESCE(tx.total_spent, 0) > 0
+               AND chain_tx.raw IS NOT NULL
+               AND NOT EXISTS (SELECT 1 FROM {TABLE} rejected WHERE rejected.txid = tx.txid)"
         ))
-        .map_err(|error| db_err("listRebroadcastableTransactions", error))?;
+        .map_err(|error| db_err("listPendingBroadcasts", error))?;
     let rows = stmt
         .query_map([account_uuid], |row| row.get::<_, Vec>(0))
-        .map_err(|error| db_err("listRebroadcastableTransactions", error))?;
+        .map_err(|error| db_err("listPendingBroadcasts", error))?;
     rows.map(|row| {
         row.map(|bytes| hex_display_order(&bytes))
-            .map_err(|error| db_err("listRebroadcastableTransactions", error))
+            .map_err(|error| db_err("listPendingBroadcasts", error))
     })
     .collect()
 }
 
-pub fn remove_account_rows(ext: &ExtensionTransaction<'_>, account_uuid: &str) -> Result<()> {
-    let account_uuid = uuid_blob(account_uuid)?;
+/// Drops rejections whose transaction left the wallet with a removed account.
+pub fn prune_orphaned_rows(ext: &ExtensionTransaction<'_>) -> Result<()> {
     ext.execute(
-        &format!("DELETE FROM {TABLE} WHERE account_uuid = ?1"),
-        [account_uuid],
+        &format!("DELETE FROM {TABLE} WHERE txid NOT IN (SELECT txid FROM transactions)"),
+        [],
     )
-    .map_err(|error| db_err("deleteAccountTransactionState", error))?;
+    .map_err(|error| db_err("pruneTransactionState", error))?;
     Ok(())
 }
 
@@ -287,144 +255,132 @@ mod tests {
     use zcash_client_sqlite::WalletDb;
     use zcash_protocol::consensus::Network;
 
+    fn wallet(conn: rusqlite::Connection) -> Db {
+        WalletDb::from_connection(
+            conn,
+            Network::TestNetwork,
+            HostClock,
+            ChaCha20Rng::from_seed([7; 32]),
+        )
+    }
+
     #[test]
-    fn finalized_recipient_is_external_to_the_sending_account() {
-        let mut conn = rusqlite::Connection::open_in_memory().unwrap();
+    fn the_rebuild_keeps_only_rejections() {
+        let conn = rusqlite::Connection::open_in_memory().unwrap();
+        let tx = conn.unchecked_transaction().unwrap();
+        LifecycleMigration.up(&tx).unwrap();
+        for (byte, state) in [(1_u8, "pending"), (2, "accepted"), (3, "rejected")] {
+            tx.execute(
+                "INSERT INTO ext_onekey_tx_state (
+                   txid, account_uuid, broadcast_state, rejection_code, rejection_reason
+                 ) VALUES (?1, ?2, ?3, -26, 'bad-txns')",
+                params![vec![byte; 32], Uuid::nil().as_bytes().to_vec(), state],
+            )
+            .unwrap();
+        }
+        RejectionsMigration.up(&tx).unwrap();
+        tx.commit().unwrap();
+
+        let rows: Vec<(Vec, Vec, i64, String)> = conn
+            .prepare(
+                "SELECT txid, account_uuid, rejection_code, rejection_reason
+                 FROM ext_onekey_tx_state",
+            )
+            .unwrap()
+            .query_map([], |row| {
+                Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
+            })
+            .unwrap()
+            .map(|row| row.unwrap())
+            .collect();
+        assert_eq!(
+            rows,
+            vec![(
+                vec![3_u8; 32],
+                Uuid::nil().as_bytes().to_vec(),
+                -26,
+                "bad-txns".to_owned()
+            )]
+        );
+    }
+
+    #[test]
+    fn a_recorded_rejection_is_returned_with_the_nodes_reason() {
+        let conn = rusqlite::Connection::open_in_memory().unwrap();
         conn.execute_batch(
             "CREATE TABLE ext_onekey_tx_state (
                txid BLOB PRIMARY KEY NOT NULL,
                account_uuid BLOB NOT NULL,
-               reservation_id TEXT UNIQUE,
-               recipient TEXT,
-               broadcast_state TEXT NOT NULL,
                rejection_code INTEGER,
                rejection_reason TEXT
-             );
-             CREATE TABLE v_tx_outputs (
-               txid BLOB NOT NULL,
-               from_account_uuid BLOB,
-               to_account_uuid BLOB,
-               to_address TEXT,
-               is_change INTEGER
              );",
         )
         .unwrap();
-        let sender = Uuid::from_u128(1);
-        let receiver = Uuid::from_u128(2);
-        let cases = [
-            (Some(receiver), false, Some("synthetic-recipient")),
-            (None, false, Some("synthetic-recipient")),
-            (Some(sender), false, None),
-            (Some(sender), true, None),
-        ];
-        for (index, (to_account, is_change, expected_recipient)) in cases.into_iter().enumerate() {
-            let txid = vec![index as u8; 32];
-            conn.execute(
-                "INSERT INTO v_tx_outputs (
-                   txid, from_account_uuid, to_account_uuid, to_address, is_change
-                 ) VALUES (?1, ?2, ?3, 'synthetic-recipient', ?4)",
-                params![
-                    txid,
-                    sender.as_bytes().as_slice(),
-                    to_account.map(|account| account.as_bytes().to_vec()),
-                    is_change
-                ],
-            )
-            .unwrap();
-            {
-                let mut db = WalletDb::from_connection(
-                    &mut conn,
-                    Network::TestNetwork,
-                    HostClock,
-                    ChaCha20Rng::from_seed([7; 32]),
-                );
-                db.transactionally_with_extension(|_wallet, ext| {
-                    insert_finalized(
-                        ext,
-                        &hex_display_order(&txid),
-                        &sender.to_string(),
-                        &format!("reservation-{index}"),
-                    )
-                })
-                .unwrap();
-            }
-            let recipient: Option = conn
-                .query_row(
-                    "SELECT recipient FROM ext_onekey_tx_state WHERE txid = ?1",
-                    [txid],
-                    |row| row.get(0),
-                )
-                .unwrap();
-            assert_eq!(recipient.as_deref(), expected_recipient);
-        }
+        let mut db = wallet(conn);
+        let txid = "01".repeat(32);
+        let account = Uuid::nil().to_string();
+        assert_not_rejected(&mut db, &txid).unwrap();
+
+        let rejected = RuntimeError::with(
+            ErrorCode::BroadcastRejected,
+            serde_json::json!({ "errorCode": 18 }),
+        )
+        .detail("bad-txns-expired");
+        record_rejection(&mut db, &txid, &account, &rejected).unwrap();
+        record_rejection(&mut db, &txid, &account, &rejected).unwrap();
+
+        let error = assert_not_rejected(&mut db, &txid).unwrap_err();
+        assert_eq!(error.code, ErrorCode::BroadcastRejected);
+        assert_eq!(error.params["errorCode"], 18);
+        assert_eq!(error.detail.as_deref(), Some("bad-txns-expired"));
     }
 
     #[test]
-    fn only_runtime_owned_active_intents_are_unresolved_and_rebroadcastable() {
+    fn only_unmined_unexpired_unrejected_outgoing_transactions_are_pending() {
         let conn = rusqlite::Connection::open_in_memory().unwrap();
         conn.execute_batch(
-            "CREATE TABLE ext_onekey_tx_state (
-               txid BLOB PRIMARY KEY NOT NULL,
-               account_uuid BLOB NOT NULL,
-               reservation_id TEXT UNIQUE,
-               recipient TEXT,
-               broadcast_state TEXT NOT NULL,
-               rejection_code INTEGER,
-               rejection_reason TEXT
-             );
+            "CREATE TABLE ext_onekey_tx_state (txid BLOB PRIMARY KEY NOT NULL);
+             CREATE TABLE transactions (txid BLOB NOT NULL, raw BLOB);
              CREATE TABLE v_transactions (
                txid BLOB NOT NULL,
                account_uuid BLOB NOT NULL,
                mined_height INTEGER,
-               expired_unmined INTEGER NOT NULL
+               expired_unmined INTEGER NOT NULL,
+               total_spent INTEGER
              );",
         )
         .unwrap();
         let account = Uuid::nil().as_bytes().to_vec();
+        // (txid byte, mined_height, expired_unmined, total_spent, has raw, rejected)
         let rows = [
-            (1_u8, "pending", Some((None, 0))),
-            (2, "accepted", Some((None, 0))),
-            (3, "observed", Some((None, 0))),
-            (4, "rejected", Some((None, 0))),
-            (5, "accepted", Some((Some(100), 0))),
-            (6, "accepted", Some((None, 1))),
+            (1_u8, None, 0, 10, true, false),
+            (2, Some(100), 0, 10, true, false),
+            (3, None, 1, 10, true, false),
+            (4, None, 0, 0, true, false),
+            (5, None, 0, 10, false, false),
+            (6, None, 0, 10, true, true),
         ];
-        for (byte, state, chain_state) in rows {
+        for (byte, mined_height, expired_unmined, total_spent, has_raw, rejected) in rows {
             let txid = vec![byte; 32];
             conn.execute(
-                "INSERT INTO ext_onekey_tx_state (
-                   txid, account_uuid, broadcast_state
-                 ) VALUES (?1, ?2, ?3)",
-                params![txid, account, state],
+                "INSERT INTO transactions (txid, raw) VALUES (?1, ?2)",
+                params![txid, has_raw.then(|| vec![0_u8])],
+            )
+            .unwrap();
+            conn.execute(
+                "INSERT INTO v_transactions VALUES (?1, ?2, ?3, ?4, ?5)",
+                params![txid, account, mined_height, expired_unmined, total_spent],
             )
             .unwrap();
-            if let Some((mined_height, expired_unmined)) = chain_state {
-                conn.execute(
-                    "INSERT INTO v_transactions (
-                       txid, account_uuid, mined_height, expired_unmined
-                     ) VALUES (?1, ?2, ?3, ?4)",
-                    params![txid, account, mined_height, expired_unmined],
-                )
-                .unwrap();
+            if rejected {
+                conn.execute("INSERT INTO ext_onekey_tx_state VALUES (?1)", [txid])
+                    .unwrap();
             }
         }
 
-        let mut unresolved = unresolved_txids(&conn, &Uuid::nil().to_string()).unwrap();
-        unresolved.sort();
-        assert_eq!(
-            unresolved,
-            [1_u8, 2]
-                .map(|byte| hex_display_order(&[byte; 32]))
-                .to_vec()
-        );
-
-        let mut rebroadcastable = rebroadcastable_txids(&conn, &Uuid::nil().to_string()).unwrap();
-        rebroadcastable.sort();
         assert_eq!(
-            rebroadcastable,
-            [1_u8, 2]
-                .map(|byte| hex_display_order(&[byte; 32]))
-                .to_vec()
+            pending_txids(&conn, &Uuid::nil().to_string()).unwrap(),
+            vec![hex_display_order(&[1_u8; 32])]
         );
     }
 }
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
index 2ffb4c622..6d12b5c51 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
@@ -41,7 +41,7 @@ pub fn open_and_migrate(network: &str, db_name: &str) -> Result {
     let mut db = WalletDb::from_connection(conn, params, HostClock, rng);
 
     WalletMigrator::new()
-        .with_external_migrations(vec![Box::new(crate::tx_state::Migration)])
+        .with_external_migrations(crate::tx_state::migrations())
         .init_or_migrate(&mut db)
         .map_err(|e| {
             RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": "migrate" }))

From 2c160319e1e21203e686a371c1c7300f628ef8d8 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Mon, 19 Oct 2026 10:22:06 +0800
Subject: [PATCH 52/97] chore: bump privacy runtimes to 0.1.0-alpha.3

---
 chain-runtimes/monero/Cargo.lock | 2 +-
 chain-runtimes/monero/Cargo.toml | 2 +-
 chain-runtimes/zcash/Cargo.lock  | 6 +++---
 chain-runtimes/zcash/Cargo.toml  | 2 +-
 4 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock
index 709c4a709..da9352219 100644
--- a/chain-runtimes/monero/Cargo.lock
+++ b/chain-runtimes/monero/Cargo.lock
@@ -1259,7 +1259,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-monero-runtime"
-version = "0.1.0-alpha.2"
+version = "0.1.0-alpha.3"
 dependencies = [
  "curve25519-dalek",
  "futures-lite",
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index 78bc44a25..9c5ec06cc 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/monero-runtime"]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.2"
+version = "0.1.0-alpha.3"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index 17004b508..5c57b55b3 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1655,7 +1655,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-zcash-keys"
-version = "0.1.0-alpha.2"
+version = "0.1.0-alpha.3"
 dependencies = [
  "bip0039",
  "bip32",
@@ -1687,7 +1687,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-runtime"
-version = "0.1.0-alpha.2"
+version = "0.1.0-alpha.3"
 dependencies = [
  "blake2b_simd",
  "console_error_panic_hook",
@@ -1736,7 +1736,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-storage-benchmark"
-version = "0.1.0-alpha.2"
+version = "0.1.0-alpha.3"
 dependencies = [
  "console_error_panic_hook",
  "js-sys",
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index dea5c9773..b01ff0d7d 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -8,7 +8,7 @@ members = [
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.2"
+version = "0.1.0-alpha.3"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"

From bb5af270daa33c616254c50082ef732a0d51ed6a Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Mon, 19 Oct 2026 11:21:05 +0800
Subject: [PATCH 53/97] test: avoid sensitive values in zcash assertion output

---
 .../zcash-keys-runtime/src/account_keys.rs    | 69 +++++++++++--------
 .../crates/zcash-keys-runtime/src/keys.rs     | 17 +----
 2 files changed, 42 insertions(+), 44 deletions(-)

diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
index 6ca50a29f..8e485ba21 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
@@ -312,41 +312,47 @@ mod tests {
         let oracle = usk(seed, account);
         let oracle_ufvk = oracle.to_unified_full_viewing_key();
         let sk = orchard_sk(seed, account);
-        assert_eq!(
-            &sk,
-            oracle.orchard().to_bytes(),
-            "orchard sk, account {account}"
+        assert!(
+            &sk == oracle.orchard().to_bytes(),
+            "Orchard spending key must match the seed oracle"
         );
 
         let keys = signing_keys(seed, account);
         let new_ufvk = keys.ufvk().unwrap();
-        assert_eq!(
-            new_ufvk,
-            keys::without_sapling(Network::MainNetwork, &oracle_ufvk).unwrap(),
-            "UFVK, account {account}"
+        assert!(
+            new_ufvk == keys::without_sapling(Network::MainNetwork, &oracle_ufvk).unwrap(),
+            "UFVK must match the seed oracle"
         );
-        assert_eq!(
-            ufvk_from_account_keys("main", &sk, &account_xpub(seed, account), account).unwrap(),
-            new_ufvk
+        assert!(
+            ufvk_from_account_keys("main", &sk, &account_xpub(seed, account), account).unwrap()
+                == new_ufvk,
+            "Account keys must derive the same UFVK"
         );
 
         let new_fvk = FullViewingKey::from(keys.orchard());
         let oracle_fvk = oracle_ufvk.orchard().unwrap().clone();
-        assert_eq!(new_fvk.to_bytes(), oracle_fvk.to_bytes(), "FVK bytes");
+        assert!(
+            new_fvk.to_bytes() == oracle_fvk.to_bytes(),
+            "Orchard full viewing key must match the seed oracle"
+        );
         // ak, the SpendValidatingKey encoding, is the first 32 bytes of the FVK encoding.
-        assert_eq!(new_fvk.to_bytes()[..32], oracle_fvk.to_bytes()[..32]);
-        assert_eq!(
-            SpendValidatingKey::from(&SpendAuthorizingKey::from(keys.orchard())),
-            SpendValidatingKey::from(&SpendAuthorizingKey::from(oracle.orchard())),
-            "SpendValidatingKey, account {account}"
+        assert!(
+            new_fvk.to_bytes()[..32] == oracle_fvk.to_bytes()[..32],
+            "Spend validating key encoding must match the seed oracle"
         );
-        assert_eq!(
-            SpendValidatingKey::from(new_fvk),
-            SpendValidatingKey::from(oracle_fvk)
+        assert!(
+            SpendValidatingKey::from(&SpendAuthorizingKey::from(keys.orchard()))
+                == SpendValidatingKey::from(&SpendAuthorizingKey::from(oracle.orchard())),
+            "Spend authorizing keys must derive the same spend validating key"
         );
-        assert_eq!(
-            keys.transparent().to_account_pubkey().serialize(),
-            oracle.transparent().to_account_pubkey().serialize()
+        assert!(
+            SpendValidatingKey::from(new_fvk) == SpendValidatingKey::from(oracle_fvk),
+            "Full viewing keys must derive the same spend validating key"
+        );
+        assert!(
+            keys.transparent().to_account_pubkey().serialize()
+                == oracle.transparent().to_account_pubkey().serialize(),
+            "Transparent account public key must match the seed oracle"
         );
     }
 
@@ -482,7 +488,10 @@ mod tests {
         for e in errors {
             let rendered = format!("{e} {}", e.to_json());
             for secret in &secrets {
-                assert!(!rendered.contains(secret.as_str()), "{rendered}");
+                assert!(
+                    !rendered.contains(secret.as_str()),
+                    "Error output must not contain key material"
+                );
             }
         }
     }
@@ -550,12 +559,14 @@ mod tests {
                 account,
             )
             .unwrap();
-            assert_eq!(fvk_items(&ours), fvk_items(hw_ufvk), "account {account}");
+            assert!(
+                fvk_items(&ours) == fvk_items(hw_ufvk),
+                "UFVK items must match the hardware vector"
+            );
             let our_ua = keys::unified_address_with("main", &ours, "all").unwrap();
-            assert_eq!(
-                ua_receivers(&our_ua),
-                ua_receivers(hw_ua),
-                "account {account}"
+            assert!(
+                ua_receivers(&our_ua) == ua_receivers(hw_ua),
+                "Unified address receivers must match the hardware vector"
             );
         }
     }
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
index 7bfeb0d6f..348829394 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
@@ -316,7 +316,7 @@ mod tests {
         let tag = &hex_key[64..66];
         assert!(
             tag == "02" || tag == "03",
-            "compressed key prefix must be 02/03, got {tag}"
+            "compressed key prefix must be 02/03"
         );
     }
 
@@ -399,20 +399,7 @@ mod ua_inspect {
         let ufvk =
             super::ufvk_from_mnemonic(&network, mnemonic.trim(), account).expect("derive UFVK");
 
-        // Fingerprint -> UFVK -> address, for comparing against hardware level by level.
-        let parsed =
-            bip0039::Mnemonic::::from_phrase(mnemonic.trim()).expect("mnemonic");
-        let seed = parsed.to_seed("");
-        println!("network      {network}  account {account}");
-        println!(
-            "fingerprint  {}",
-            hex::encode(
-                zip32::fingerprint::SeedFingerprint::from_seed(seed.as_ref())
-                    .expect("fingerprint")
-                    .to_bytes()
-            )
-        );
-        println!("ufvk         {ufvk}");
+        println!("network      {network}");
         println!(
             "t-addr       {}",
             super::transparent_address(&network, &ufvk).expect("t-address")

From eab53899ee6c1ebf96a381683ac1f113ab30afc9 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Mon, 19 Oct 2026 18:00:20 +0800
Subject: [PATCH 54/97] fix: bind monero broadcast amounts to reviewed outputs

---
 chain-runtimes/monero/Cargo.lock              |   2 +-
 chain-runtimes/monero/Cargo.toml              |   2 +-
 chain-runtimes/monero/README.md               |  19 +-
 .../crates/monero-runtime/src/bindgen.rs      |  40 ++-
 .../crates/monero-runtime/src/review.rs       | 304 +++++++++++++++---
 .../monero/crates/monero-runtime/src/spend.rs | 105 +++++-
 chain-runtimes/monero/scripts/smoke.js        |  30 +-
 7 files changed, 447 insertions(+), 55 deletions(-)

diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock
index da9352219..e945c9f17 100644
--- a/chain-runtimes/monero/Cargo.lock
+++ b/chain-runtimes/monero/Cargo.lock
@@ -1259,7 +1259,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-monero-runtime"
-version = "0.1.0-alpha.3"
+version = "0.1.0-alpha.4"
 dependencies = [
  "curve25519-dalek",
  "futures-lite",
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index 9c5ec06cc..5fb28a8a6 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/monero-runtime"]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.3"
+version = "0.1.0-alpha.4"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md
index 8b84ba870..4fe76b770 100644
--- a/chain-runtimes/monero/README.md
+++ b/chain-runtimes/monero/README.md
@@ -82,8 +82,9 @@ transactionDetails(accountId, txid)
 
 prepareTransaction(accountId, recipientsJson, maxSend, chainTip, priority)
 verifyTransaction(signableHex, reviewJson)
+verifySignedTransaction(signableHex, reviewJson, rawHex)
 signTransaction(signableHex, spendPrivateKeyHex, reviewJson)
-broadcastTransaction(accountId, rawHex, chainTip, outgoingAtomic?, changeAtomic?)
+broadcastTransaction(accountId, rawHex, chainTip, outgoingAtomic?, changeAtomic?, signableHex, reviewJson)
 diagDatabase()
 ```
 
@@ -97,7 +98,21 @@ broadcastTransaction    record, then broadcast → { txid, broadcast: accepted |
 ```
 
 - `prepareTransaction` takes exactly one recipient.
-- A first `broadcastTransaction` whose inputs are not this account's, or are already
+- Before broadcasting, the host verifies the signed transaction
+  against the same prepared transaction and review before broadcasting. The
+  broadcast boundary repeats that verification before touching the database or
+  node. Missing review evidence is rejected, including calls from older hosts.
+  The reviewed sender and network must match the local account before recording
+  a send, so another account's change cannot be credited to this account.
+- Pending outgoing and change amounts come from that verified review. Optional
+  host amount strings must be canonical unsigned integers equal to those values;
+  missing strings do not discard the amounts derived from the review. A retry
+  retains previously recorded amounts and fills only missing values.
+- `verifySignedTransaction` returns the signed transaction id. It uses the pinned
+  wallet library's output matching and the transaction's fee; it performs no
+  network request and persists no data. This matches outputs and the fee; it
+  does not replace the node's signature and consensus validation.
+- A `broadcastTransaction` whose inputs are not this account's, or are already
   spent elsewhere, is refused with `INVALID_REQUEST` before anything is recorded.
 - `BROADCAST_REJECTED` is thrown only when the node explicitly rejects a first
   broadcast for a reason other than double spend; the record is undone and the
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
index 7a1f4b58d..701027a20 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -456,6 +456,17 @@ pub fn verify_transaction(
     Ok(())
 }
 
+#[wasm_bindgen(js_name = verifySignedTransaction)]
+pub fn verify_signed_transaction(
+    signable_hex: &str,
+    review_json: &str,
+    raw_hex: &str,
+) -> std::result::Result {
+    let request = crate::review::parse_request(review_json)?;
+    let transaction = crate::review::verify_signed(signable_hex, &request, raw_hex)?;
+    Ok(hex::encode(transaction.hash()))
+}
+
 /// Broadcast a signed transaction. Irreversible.
 ///
 /// Accepted and uncertain (network error) outcomes are both recorded: spent outputs
@@ -468,16 +479,33 @@ pub async fn broadcast_transaction(
     chain_tip: u64,
     outgoing_atomic: Option,
     change_atomic: Option,
+    signable_hex: Option,
+    review_json: Option,
 ) -> std::result::Result {
     let raw = raw_hex.to_owned();
-    // Decimal strings: u64 cannot cross the host bridge. Used only for display and
-    // balance; malformed values count as absent.
-    let amounts = spend::SentAmounts {
-        outgoing_atomic: outgoing_atomic.and_then(|a| a.parse::().ok()),
-        change_atomic: change_atomic.and_then(|a| a.parse::().ok()),
+    let required = |value: Option, field: &str| {
+        value.ok_or_else(|| {
+            RuntimeError::with(
+                ErrorCode::InvalidRequest,
+                serde_json::json!({"field": field, "reason": "reviewRequired"}),
+            )
+        })
     };
+    let request = crate::review::parse_request(&required(review_json, "reviewJson")?)?;
+    let amounts = spend::reviewed_broadcast_amounts(
+        &required(signable_hex, "signableHex")?,
+        &request,
+        &raw,
+        outgoing_atomic.as_deref(),
+        change_atomic.as_deref(),
+    )?;
     let v = runtime::with_db_and_daemon(move |db, daemon| async move {
-        let r = spend::broadcast_signed(&db, &daemon, account_id, &raw, chain_tip, amounts).await;
+        let r = async {
+            let identity = db.identity_by_id(account_id)?;
+            crate::review::verify_sender(&request, &identity.view_pair, db.network())?;
+            spend::broadcast_signed(&db, &daemon, account_id, &raw, chain_tip, amounts).await
+        }
+        .await;
         (db, daemon, r)
     })
     .await?;
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/review.rs b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
index d67d05b75..4503ce044 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/review.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
@@ -2,7 +2,8 @@ use monero_wallet::{
     address::MoneroAddress,
     ed25519::{CompressedPoint, Point, Scalar},
     io::{read_byte, read_bytes, read_u32, read_u64, read_vec},
-    send::SignableTransaction,
+    send::{Eventuality, SignableTransaction},
+    transaction::Transaction,
     OutputWithDecoys,
 };
 use serde::Deserialize;
@@ -44,6 +45,19 @@ pub fn parse_request(json: &str) -> Result {
     serde_json::from_str(json).map_err(|_| mismatch("reviewRequest"))
 }
 
+pub fn verify_sender(
+    request: &ReviewRequest,
+    pair: &monero_wallet::ViewPair,
+    network: monero_wallet::address::Network,
+) -> Result<()> {
+    if keys::parse_network(&request.network)? != network
+        || request.from_address != keys::primary_address(pair, network)
+    {
+        return Err(mismatch("fromAddress"));
+    }
+    Ok(())
+}
+
 /// Read the pinned monero-wallet 0.2 serialization after its own strict validator.
 /// Its payment fields are private, so inspection uses its public wire readers.
 pub fn verify(
@@ -160,6 +174,39 @@ pub fn verify(
     Ok(signable)
 }
 
+/// Bind the reviewed outputs to the actual signed transaction without changing
+/// signing or scanning. Eventuality validates output keys, commitments and ciphertexts.
+pub fn verify_signed(
+    signable_hex: &str,
+    request: &ReviewRequest,
+    raw_hex: &str,
+) -> Result {
+    let signable = verify(signable_hex, request, None)?;
+    if raw_hex.len() > 8 * 1024 * 1024 {
+        return Err(mismatch("rawHex"));
+    }
+    let raw = hex::decode(raw_hex).map_err(|_| mismatch("rawHex"))?;
+    let mut reader = raw.as_slice();
+    let transaction: Transaction =
+        Transaction::read(&mut reader).map_err(|_| mismatch("rawHex"))?;
+    if !reader.is_empty() {
+        return Err(mismatch("trailingBytes"));
+    }
+    let Transaction::V2 {
+        proofs: Some(ref proofs),
+        ..
+    } = transaction
+    else {
+        return Err(mismatch("signedTransaction"));
+    };
+    if proofs.base.fee != amount(&request.fee_atomic)?
+        || !Eventuality::from(signable).matches(&transaction.clone().pruned_with_prunable().0)
+    {
+        return Err(mismatch("signedTransaction"));
+    }
+    Ok(transaction)
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -187,6 +234,147 @@ mod tests {
         fixture_with(extra, |pair| Change::new(pair, None))
     }
 
+    fn review_json(review: &ReviewRequest) -> String {
+        serde_json::json!({
+            "network": review.network, "fromAddress": review.from_address,
+            "toAddress": review.to_address, "amountAtomic": review.amount_atomic,
+            "feeAtomic": review.fee_atomic, "changeAtomic": review.change_atomic,
+            "isMaxSend": review.is_max_send,
+        })
+        .to_string()
+    }
+
+    fn signed_fixture() -> (String, ReviewRequest, String) {
+        let (bytes, review, spend) = fixture(vec![]);
+        let encoded = hex::encode(bytes);
+        let signed = crate::spend::sign_for_host(&encoded, &spend, &review_json(&review)).unwrap();
+        (
+            encoded,
+            review,
+            signed["rawHex"].as_str().unwrap().to_owned(),
+        )
+    }
+
+    #[test]
+    fn signed_outputs_and_fee_must_match_the_prepared_review() {
+        let (encoded, review, raw) = signed_fixture();
+        let transaction = verify_signed(&encoded, &review, &raw).unwrap();
+        let mut wrong_outputs = transaction.clone();
+        wrong_outputs.prefix_mut().outputs.swap(0, 1);
+        assert!(verify_signed(&encoded, &review, &hex::encode(wrong_outputs.serialize())).is_err());
+        let mut wrong_extra = transaction.clone();
+        wrong_extra.prefix_mut().extra.push(0);
+        assert!(verify_signed(&encoded, &review, &hex::encode(wrong_extra.serialize())).is_err());
+        let mut wrong_fee = transaction;
+        if let Transaction::V2 {
+            proofs: Some(ref mut proofs),
+            ..
+        } = wrong_fee
+        {
+            proofs.base.fee += 1;
+        }
+        assert!(verify_signed(&encoded, &review, &hex::encode(wrong_fee.serialize())).is_err());
+        assert!(verify_signed(&encoded, &review, &format!("{raw}00")).is_err());
+        assert!(verify_signed(&encoded, &review, "zz").is_err());
+    }
+
+    #[test]
+    fn signed_multiple_inputs_match_the_prepared_review() {
+        let (bytes, review, spend) = fixture_with_inputs(vec![], |pair| Change::new(pair, None), 3);
+        let encoded = hex::encode(bytes);
+        let signed = crate::spend::sign_for_host(&encoded, &spend, &review_json(&review)).unwrap();
+        assert!(verify_signed(&encoded, &review, signed["rawHex"].as_str().unwrap()).is_ok());
+    }
+
+    #[test]
+    fn broadcast_review_must_belong_to_the_local_account_and_network() {
+        let (_, review, _) = fixture(vec![]);
+        assert!(verify_sender(&review, &other_account(1), Network::Mainnet).is_ok());
+        assert!(verify_sender(&review, &other_account(2), Network::Mainnet).is_err());
+        assert!(verify_sender(&review, &other_account(1), Network::Testnet).is_err());
+    }
+
+    #[test]
+    fn signed_self_payments_and_max_sends_match_the_prepared_review() {
+        for (self_payment, max_send) in [(true, false), (false, true), (true, true)] {
+            let (bytes, review, spend) = fixture_with_options(
+                vec![],
+                |pair| Change::new(pair, None),
+                3,
+                self_payment,
+                max_send,
+            );
+            let encoded = hex::encode(bytes);
+            let signed =
+                crate::spend::sign_for_host(&encoded, &spend, &review_json(&review)).unwrap();
+            let amounts = crate::spend::reviewed_broadcast_amounts(
+                &encoded,
+                &review,
+                signed["rawHex"].as_str().unwrap(),
+                None,
+                None,
+            )
+            .unwrap();
+            assert_eq!(
+                amounts.change_atomic,
+                Some(review.change_atomic.parse::().unwrap())
+            );
+            if max_send {
+                assert_eq!(amounts.change_atomic, Some(0));
+                assert_eq!(amounts.outgoing_atomic, Some(INPUT_AMOUNT * 3));
+            }
+        }
+    }
+
+    #[test]
+    fn broadcast_amounts_are_derived_from_verified_outputs_not_optional_host_values() {
+        let (encoded, review, raw) = signed_fixture();
+        let expected = PAYMENT_AMOUNT + review.fee_atomic.parse::().unwrap();
+        let amounts =
+            crate::spend::reviewed_broadcast_amounts(&encoded, &review, &raw, None, None).unwrap();
+        assert_eq!(amounts.outgoing_atomic, Some(expected));
+        assert_eq!(
+            amounts.change_atomic,
+            Some(review.change_atomic.parse::().unwrap())
+        );
+        let outgoing = expected.to_string();
+        assert!(crate::spend::reviewed_broadcast_amounts(
+            &encoded,
+            &review,
+            &raw,
+            Some(&outgoing),
+            Some(&review.change_atomic)
+        )
+        .is_ok());
+        for bad in [
+            "",
+            "-1",
+            "+1",
+            "01",
+            "1.0",
+            "1e3",
+            "18446744073709551616",
+            "1",
+        ] {
+            assert!(crate::spend::reviewed_broadcast_amounts(
+                &encoded,
+                &review,
+                &raw,
+                None,
+                Some(bad)
+            )
+            .is_err());
+            assert!(crate::spend::reviewed_broadcast_amounts(
+                &encoded,
+                &review,
+                &raw,
+                Some(bad),
+                None
+            )
+            .is_err());
+        }
+    }
+
     /// A view pair for another account: spend key `value`, view key derived as OneKey does.
     fn other_account(value: u8) -> ViewPair {
         let bytes = <[u8; 32]>::from(scalar(value));
@@ -200,57 +388,95 @@ mod tests {
     fn fixture_with(
         extra: Vec>,
         change: impl FnOnce(ViewPair) -> Change,
+    ) -> (Vec, ReviewRequest, [u8; 32]) {
+        fixture_with_inputs(extra, change, 1)
+    }
+
+    fn fixture_with_inputs(
+        extra: Vec>,
+        change: impl FnOnce(ViewPair) -> Change,
+        input_count: u8,
+    ) -> (Vec, ReviewRequest, [u8; 32]) {
+        fixture_with_options(extra, change, input_count, false, false)
+    }
+
+    fn fixture_with_options(
+        extra: Vec>,
+        change: impl FnOnce(ViewPair) -> Change,
+        input_count: u8,
+        self_payment: bool,
+        max_send: bool,
     ) -> (Vec, ReviewRequest, [u8; 32]) {
         let mut public_bytes = [0x66u8; 32];
         public_bytes[0] = 0x58;
         let public = CompressedPoint::from(public_bytes).decompress().unwrap();
-        let commitment = Commitment::new(scalar(1), INPUT_AMOUNT);
-        let mut input_bytes = Vec::new();
-        input_bytes.extend(public_bytes);
-        scalar(0).write(&mut input_bytes).unwrap();
-        commitment.write(&mut input_bytes).unwrap();
-        let members = (0..16)
-            .map(|index| {
-                if index == 0 {
-                    [public, commitment.commit()]
-                } else {
-                    [
-                        Point::biased_hash([index; 32]),
-                        Point::biased_hash([index + 100; 32]),
-                    ]
-                }
+        let inputs: Vec = (0..input_count)
+            .map(|input_index| {
+                let private: curve25519_dalek::Scalar = scalar(input_index + 1).into();
+                let input_public =
+                    Point::from(private * curve25519_dalek::constants::ED25519_BASEPOINT_POINT);
+                let commitment = Commitment::new(scalar(input_index + 1), INPUT_AMOUNT);
+                let mut input_bytes = Vec::new();
+                input_public.compress().write(&mut input_bytes).unwrap();
+                scalar(input_index).write(&mut input_bytes).unwrap();
+                commitment.write(&mut input_bytes).unwrap();
+                let members = (0..16)
+                    .map(|index| {
+                        if index == 0 {
+                            [input_public, commitment.commit()]
+                        } else {
+                            [
+                                Point::biased_hash([index + input_index * 16; 32]),
+                                Point::biased_hash([index + 100 + input_index * 16; 32]),
+                            ]
+                        }
+                    })
+                    .collect();
+                Decoys::new(vec![1; 16], 0, members)
+                    .unwrap()
+                    .write(&mut input_bytes)
+                    .unwrap();
+                OutputWithDecoys::read(&mut input_bytes.as_slice()).unwrap()
             })
             .collect();
-        Decoys::new(vec![1; 16], 0, members)
-            .unwrap()
-            .write(&mut input_bytes)
-            .unwrap();
-        let input = OutputWithDecoys::read(&mut input_bytes.as_slice()).unwrap();
         let spend_bytes = <[u8; 32]>::from(scalar(1));
         let pair = ViewPair::new(public, Zeroizing::new(Scalar::hash(spend_bytes))).unwrap();
         let sender = pair.legacy_address(Network::Mainnet).to_string();
-        let tx = SignableTransaction::new(
-            RctType::ClsagBulletproofPlus,
-            Zeroizing::new([7; 32]),
-            vec![input],
-            vec![(
-                MoneroAddress::from_str(Network::Mainnet, RECIPIENT).unwrap(),
-                PAYMENT_AMOUNT,
-            )],
-            change(pair),
-            extra,
-            FeeRate::new(20_000, 1).unwrap(),
-        )
-        .unwrap();
+        let recipient = if self_payment { &sender } else { RECIPIENT };
+        let change = change(pair);
+        let build = |payment_amount| {
+            SignableTransaction::new(
+                RctType::ClsagBulletproofPlus,
+                Zeroizing::new([7; 32]),
+                inputs.clone(),
+                vec![(
+                    MoneroAddress::from_str(Network::Mainnet, recipient).unwrap(),
+                    payment_amount,
+                )],
+                change.clone(),
+                extra.clone(),
+                FeeRate::new(20_000, 1).unwrap(),
+            )
+            .unwrap()
+        };
+        let total = INPUT_AMOUNT * u64::from(input_count);
+        let mut tx = build(PAYMENT_AMOUNT);
+        let paid = if max_send {
+            let paid = total - tx.necessary_fee();
+            tx = build(paid);
+            paid
+        } else {
+            PAYMENT_AMOUNT
+        };
         let fee = tx.necessary_fee();
         let review = ReviewRequest {
             network: "mainnet".into(),
-            from_address: sender,
-            to_address: RECIPIENT.into(),
-            amount_atomic: PAYMENT_AMOUNT.to_string(),
+            from_address: sender.clone(),
+            to_address: recipient.into(),
+            amount_atomic: paid.to_string(),
             fee_atomic: fee.to_string(),
-            change_atomic: (INPUT_AMOUNT - PAYMENT_AMOUNT - fee).to_string(),
-            is_max_send: false,
+            change_atomic: (total - paid - fee).to_string(),
+            is_max_send: max_send,
         };
         (tx.serialize(), review, spend_bytes)
     }
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
index f3ef0807d..11c7064d8 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -920,12 +920,58 @@ mod tests {
         assert_eq!(b.pending_change_atomic, 300);
         assert_eq!(b.unlocked_atomic, 0);
 
+        record_broadcast(
+            &db,
+            id,
+            &txid,
+            &[key_image],
+            901,
+            SentAmounts {
+                outgoing_atomic: Some(499),
+                change_atomic: Some(1),
+            },
+        )
+        .unwrap();
+        let recorded: (String, String) = db.conn().query_row(
+            "SELECT outgoing_atomic, change_atomic FROM transactions WHERE identity_id = ?1 AND txid = ?2",
+            params![id, txid.as_slice()], |row| Ok((row.get(0)?, row.get(1)?)),
+        ).unwrap();
+        assert_eq!(recorded, ("200".to_owned(), "300".to_owned()));
+        assert_eq!(
+            crate::query::balance(&db, id, Some(10_000))
+                .unwrap()
+                .total_atomic,
+            300
+        );
+
         crate::pool::mark_failed(&db, id, &txid).unwrap();
         let b = crate::query::balance(&db, id, Some(10_000)).unwrap();
         assert_eq!(b.pending_change_atomic, 0);
         assert_eq!(b.total_atomic, 500);
     }
 
+    #[test]
+    fn a_known_incoming_transaction_cannot_bypass_input_ownership_on_rebroadcast() {
+        let (db, id) = db_with_identity();
+        let txid = [0x57u8; 32];
+        db.conn().execute(
+            "INSERT INTO transactions (identity_id, txid, height, direction) VALUES (?1, ?2, 90, 'in')",
+            params![id, txid.as_slice()],
+        ).unwrap();
+        assert!(
+            record_broadcast(&db, id, &txid, &[[0x99; 32]], 100, SentAmounts::default()).is_err()
+        );
+        let direction: String = db
+            .conn()
+            .query_row(
+                "SELECT direction FROM transactions WHERE identity_id = ?1 AND txid = ?2",
+                params![id, txid.as_slice()],
+                |row| row.get(0),
+            )
+            .unwrap();
+        assert_eq!(direction, "in");
+    }
+
     /// Broadcast marks inputs spent by the transaction's key images.
     #[test]
     fn a_broadcast_marks_its_inputs_by_key_image() {
@@ -1337,6 +1383,57 @@ pub struct SentAmounts {
     pub change_atomic: Option,
 }
 
+pub fn reviewed_broadcast_amounts(
+    signable_hex: &str,
+    request: &crate::review::ReviewRequest,
+    raw_hex: &str,
+    outgoing_atomic: Option<&str>,
+    change_atomic: Option<&str>,
+) -> Result {
+    crate::review::verify_signed(signable_hex, request, raw_hex)?;
+    let parse = |value: &str, field: &str| -> Result {
+        let parsed = value.parse::().map_err(|_| {
+            RuntimeError::with(
+                ErrorCode::InvalidRequest,
+                json!({"field": field, "reason": "invalidAmount"}),
+            )
+        })?;
+        if parsed.to_string() != value {
+            return Err(RuntimeError::with(
+                ErrorCode::InvalidRequest,
+                json!({"field": field, "reason": "invalidAmount"}),
+            ));
+        }
+        Ok(parsed)
+    };
+    let outgoing = parse(&request.amount_atomic, "amountAtomic")?
+        .checked_add(parse(&request.fee_atomic, "feeAtomic")?)
+        .ok_or_else(|| {
+            RuntimeError::with(
+                ErrorCode::InvalidRequest,
+                json!({"field": "outgoingAtomic", "reason": "amountOverflow"}),
+            )
+        })?;
+    let change = parse(&request.change_atomic, "changeAtomic")?;
+    for (supplied, expected, field) in [
+        (outgoing_atomic, outgoing, "outgoingAtomic"),
+        (change_atomic, change, "changeAtomic"),
+    ] {
+        if let Some(value) = supplied {
+            if parse(value, field)? != expected {
+                return Err(RuntimeError::with(
+                    ErrorCode::InvalidRequest,
+                    json!({"field": field, "reason": "transactionDoesNotMatchReview"}),
+                ));
+            }
+        }
+    }
+    Ok(SentAmounts {
+        outgoing_atomic: Some(outgoing),
+        change_atomic: Some(change),
+    })
+}
+
 /// Pre-broadcast bookkeeping in one transaction: mark inputs spent and record a
 /// pending send.
 ///
@@ -1364,9 +1461,7 @@ fn record_broadcast(
             |r| r.get(0),
         )
         .map_err(|e| db_err("findRecordedSend", e))?;
-    if !existed {
-        check_inputs_owned(&tx_db, identity_id, txid, key_images)?;
-    }
+    check_inputs_owned(&tx_db, identity_id, txid, key_images)?;
     for key_image in key_images {
         tx_db
             .execute(
@@ -1388,8 +1483,8 @@ fn record_broadcast(
              VALUES (?1, ?2, NULL, 'out', ?3, ?4, ?5)
              ON CONFLICT (identity_id, txid) DO UPDATE
                SET direction = 'out', sent_at = ?3, failed = 0,
-                   outgoing_atomic = COALESCE(?4, outgoing_atomic),
-                   change_atomic = COALESCE(?5, change_atomic)",
+                   outgoing_atomic = COALESCE(outgoing_atomic, ?4),
+                   change_atomic = COALESCE(change_atomic, ?5)",
             params![
                 identity_id,
                 txid.as_slice(),
diff --git a/chain-runtimes/monero/scripts/smoke.js b/chain-runtimes/monero/scripts/smoke.js
index 8bad853a5..0bc1527af 100755
--- a/chain-runtimes/monero/scripts/smoke.js
+++ b/chain-runtimes/monero/scripts/smoke.js
@@ -84,6 +84,33 @@ for (const [label, hex, req, field] of [
   }
 }
 
+check('signed transaction verifier is exported', typeof rt.verifySignedTransaction, 'function');
+try {
+  rt.verifySignedTransaction('zz', review, '00');
+  check('signed verification rejects malformed input', 'succeeded', 'failed');
+} catch (e) {
+  const err = JSON.parse(e.message ?? e);
+  check('signed verification rejects malformed input', err.params.field, 'signableHex');
+}
+
+async function broadcastReviewBoundaries() {
+  for (const [label, signable, req, field] of [
+    ['missing review', undefined, undefined, 'reviewJson'],
+    ['missing signable', undefined, review, 'signableHex'],
+    ['malformed signable', 'zz', review, 'signableHex'],
+  ]) {
+    try {
+      await rt.broadcastTransaction(id, '00', 3700100n, '1', '0', signable, req);
+      check(`broadcast rejects ${label}`, 'succeeded', 'failed');
+    } catch (e) {
+      const err = JSON.parse(e.message ?? e);
+      check(`broadcast rejects ${label}`, err.params.field, field);
+    }
+  }
+  const after = JSON.parse(rt.diagDatabase());
+  check('rejected broadcasts do not record transactions', after.counts.transactions, 0);
+}
+
 // Node checks; skipped (and reported as skipped) without XMR_NODE.
 async function online() {
   const url = process.env.XMR_NODE;
@@ -143,7 +170,8 @@ async function online() {
   }
 }
 
-online()
+broadcastReviewBoundaries()
+  .then(online)
   .catch((e) => {
     failures += 1;
     console.log(`✗ node checks threw: ${e.message ?? e}`);

From db4598f1bb85dc25265793458f56e25d6883dae2 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Mon, 19 Oct 2026 22:24:44 +0800
Subject: [PATCH 55/97] fix: distinguish zcash self payments from change

---
 chain-runtimes/zcash/Cargo.lock               |   6 +-
 chain-runtimes/zcash/Cargo.toml               |   2 +-
 chain-runtimes/zcash/README.md                |   5 +
 .../zcash/crates/zcash-runtime/src/history.rs | 110 +++++++++++++++++-
 4 files changed, 115 insertions(+), 8 deletions(-)

diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index 5c57b55b3..fb0c53b21 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1655,7 +1655,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-zcash-keys"
-version = "0.1.0-alpha.3"
+version = "0.1.0-alpha.4"
 dependencies = [
  "bip0039",
  "bip32",
@@ -1687,7 +1687,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-runtime"
-version = "0.1.0-alpha.3"
+version = "0.1.0-alpha.4"
 dependencies = [
  "blake2b_simd",
  "console_error_panic_hook",
@@ -1736,7 +1736,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-storage-benchmark"
-version = "0.1.0-alpha.3"
+version = "0.1.0-alpha.4"
 dependencies = [
  "console_error_panic_hook",
  "js-sys",
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index b01ff0d7d..fd0379f66 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -8,7 +8,7 @@ members = [
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.3"
+version = "0.1.0-alpha.4"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md
index 4b21bc25b..c2a8c063e 100644
--- a/chain-runtimes/zcash/README.md
+++ b/chain-runtimes/zcash/README.md
@@ -115,6 +115,11 @@ keysCapabilities() / keysDependencyVersions()
 
 ### Sending
 
+The transaction-output history API distinguishes recorded payment outputs from
+change using the exact transaction, pool and output index in `sent_notes`. Its
+`isChange` excludes explicit self-payments, which compact scanning also flags as
+change for wallet accounting. This read projection does not modify scan state.
+
 ```
 runtime.pcztCreate()             build (selection, witness, anchor)
 runtime.pcztProve()              zero-knowledge proofs (slow)
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
index a6a03f936..4628fb8b0 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
@@ -302,10 +302,16 @@ pub fn details_outputs(
     {
         let mut stmt = conn
             .prepare(
-                "SELECT output_pool, value, is_change, memo, to_address,
-                        to_account_uuid, from_account_uuid
-                 FROM v_tx_outputs
-                 WHERE txid = ?1",
+                "SELECT output.output_pool, output.value, output.is_change,
+                        output.memo, output.to_address,
+                        output.to_account_uuid, output.from_account_uuid,
+                        payment.to_address
+                 FROM v_tx_outputs output
+                 LEFT JOIN sent_notes payment
+                   ON payment.transaction_id = output.transaction_id
+                  AND payment.output_pool = output.output_pool
+                  AND payment.output_index = output.output_index
+                 WHERE output.txid = ?1",
             )
             .map_err(db_err)?;
         let mut rows = stmt.query(rusqlite::params![internal]).map_err(db_err)?;
@@ -321,6 +327,12 @@ pub fn details_outputs(
             // Account UUIDs are BLOBs; reading them as String fails.
             let to_acct: Option> = row.get(5).map_err(db_err)?;
             let from_acct: Option> = row.get(6).map_err(db_err)?;
+            let payment_address: Option = row.get(7).map_err(db_err)?;
+            // Compact scanning also marks explicit self-payments as change.
+            // A recorded shielded recipient identifies a payment; actual change
+            // has no sent-note recipient address. Keep the scan flags intact.
+            let is_change = is_change && (pool == 0 || payment_address.is_none());
+            let address = payment_address.or(address);
 
             if pool == 2 {
                 continue;
@@ -599,6 +611,10 @@ mod tests {
             details(&conn, &account_uuid, &"00".repeat(32)).unwrap(),
             "null"
         );
+        let outputs: serde_json::Value =
+            serde_json::from_str(&details_outputs(&conn, &account_uuid, &"00".repeat(32)).unwrap())
+                .unwrap();
+        assert_eq!(outputs["received"], json!([]));
     }
 
     fn history_fixture() -> rusqlite::Connection {
@@ -620,12 +636,20 @@ mod tests {
                received_output_id INTEGER NOT NULL
              );
              CREATE TABLE v_tx_outputs (
+               transaction_id INTEGER,
+               output_index INTEGER DEFAULT 0,
                txid BLOB NOT NULL,
                from_account_uuid BLOB,
                to_account_uuid BLOB,
                to_address TEXT,
                is_change INTEGER
              );
+             CREATE TABLE sent_notes (
+               transaction_id INTEGER,
+               output_pool INTEGER,
+               output_index INTEGER,
+               to_address TEXT
+             );
              CREATE TABLE ext_onekey_tx_state (
                txid BLOB PRIMARY KEY NOT NULL,
                rejection_code INTEGER,
@@ -819,6 +843,84 @@ mod tests {
         assert_eq!(output["received"], json!([]));
     }
 
+    #[test]
+    fn explicit_self_payment_is_not_displayed_as_change_after_scanning() {
+        let conn = history_fixture();
+        conn.execute_batch(
+            "ALTER TABLE v_tx_outputs ADD COLUMN output_pool INTEGER DEFAULT 4;
+             ALTER TABLE v_tx_outputs ADD COLUMN value INTEGER;
+             ALTER TABLE v_tx_outputs ADD COLUMN memo BLOB;
+             ALTER TABLE v_received_outputs ADD COLUMN address_id INTEGER;
+             CREATE TABLE addresses (id INTEGER PRIMARY KEY, address TEXT);",
+        )
+        .unwrap();
+        let account = uuid::Uuid::from_u128(1);
+        let txid = [7u8; 32];
+        let text = "  self payment\n\u{1f642}  ";
+        for (index, value, recipient, memo) in [
+            (0, 10_000, Some("synthetic-self-recipient"), Some(text)),
+            (1, 2_536_200, None, None),
+        ] {
+            conn.execute(
+                "INSERT INTO v_tx_outputs
+                 (transaction_id, output_index, txid, from_account_uuid,
+                  to_account_uuid, to_address, is_change, value, memo)
+                 VALUES (1, ?1, ?2, ?3, ?3, ?4, 1, ?5, ?6)",
+                rusqlite::params![
+                    index,
+                    txid.as_slice(),
+                    account.as_bytes().as_slice(),
+                    recipient,
+                    value,
+                    memo.map(str::as_bytes),
+                ],
+            )
+            .unwrap();
+            conn.execute(
+                "INSERT INTO sent_notes
+                 (transaction_id, output_pool, output_index, to_address)
+                 VALUES (1, 4, ?1, ?2)",
+                rusqlite::params![index, recipient],
+            )
+            .unwrap();
+        }
+        conn.execute_batch(
+            "INSERT INTO sent_notes
+             (transaction_id, output_pool, output_index, to_address) VALUES
+               (1, 3, 1, 'different-pool-payment'),
+               (2, 4, 1, 'different-transaction-payment');",
+        )
+        .unwrap();
+
+        let output: serde_json::Value = serde_json::from_str(
+            &details_outputs(&conn, &account.to_string(), &hex_display_order(&txid)).unwrap(),
+        )
+        .unwrap();
+        let received = output["received"].as_array().unwrap();
+        let payment = received
+            .iter()
+            .find(|row| row["valueZat"] == 10_000)
+            .unwrap();
+        let change = received
+            .iter()
+            .find(|row| row["valueZat"] == 2_536_200)
+            .unwrap();
+        assert_eq!(payment["isChange"], false);
+        assert_eq!(payment["memo"], text);
+        assert_eq!(payment["address"], "synthetic-self-recipient");
+        assert_eq!(change["isChange"], true);
+        assert_eq!(output["external"], json!([]));
+        // This is a read projection, not a rewrite of upstream wallet state.
+        let scanner_change_count: i64 = conn
+            .query_row(
+                "SELECT COUNT(*) FROM v_tx_outputs WHERE is_change = 1",
+                [],
+                |row| row.get(0),
+            )
+            .unwrap();
+        assert_eq!(scanner_change_count, 2);
+    }
+
     #[test]
     fn outgoing_outputs_are_external_relative_to_the_current_account() {
         let conn = history_fixture();

From 7106e1fb5bf12e52fa7cf3935cfbcd0df8a26f7f Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Tue, 20 Oct 2026 23:09:31 +0800
Subject: [PATCH 56/97] fix: allow zcash transparent change at the receive
 address

---
 .../zcash-keys-runtime/TRANSPARENT_TX_API.md  |  8 +-
 .../src/transparent_send.rs                   | 98 ++++++++++++++++++-
 .../src/transparent_send/shielding.rs         | 46 +++++++++
 3 files changed, 147 insertions(+), 5 deletions(-)

diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
index 2f78f062a..e2892f228 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
@@ -74,7 +74,7 @@ zatoshi value.
   "sendMax": false,
   "change": {
     "address": "t1...",
-    "derivationPath": "m/44'/133'/0'/1/0"
+    "derivationPath": "m/44'/133'/0'/0/0"
   }
 }
 ```
@@ -86,8 +86,10 @@ zatoshi value.
   Unified Address with an Orchard receiver (paid as an Ironwood note). A Unified
   Address without one is rejected rather than paid at a public receiver.
   Sapling/Sprout destinations are unsupported.
-- Change must be an owned P2PKH address on internal scope `1` with an address index
-  below 40.
+- Change must be an owned P2PKH address. The App reuses the account's default
+  receive address at `0/0`; internal scope `1` with an address index below 40
+  remains supported for previously prepared transactions. Both signing paths
+  verify that the address matches the declared path in the signing account.
 - Send-max: exactly one recipient, no `amountZat` and no `change`; the recipient gets
   the selected total minus the ZIP-317 fee.
 - Fixed amount: a surplus too small to fund a change output (below the 5,000 zatoshi
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
index 5fcf33e55..ea1d4d6d0 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
@@ -408,10 +408,11 @@ fn plan_transaction(request: TransparentTxRequest) -> Result {
         }
         let change_path =
             parse_derivation_path(&change_request.derivation_path, request.account_index)?;
-        if change_path.scope != 1 {
+        // Reuse the default receive address, while accepting legacy internal change.
+        if change_path.scope == 0 && change_path.index != 0 {
             return Err(KeysError::with(
                 ErrorCode::InvalidDerivationPath,
-                serde_json::json!({ "field": "change.derivationPath", "reason": "internalScopeRequired" }),
+                serde_json::json!({ "field": "change.derivationPath", "reason": "defaultReceiveAddressRequired" }),
             ));
         }
         // The change index must be within the signer's scan range
@@ -1050,6 +1051,99 @@ mod tests {
         assert_eq!(built.spent_outpoints, quote.spent_outpoints);
     }
 
+    #[test]
+    fn receive_address_and_legacy_internal_change_can_both_be_spent() {
+        for scope in [0, 1] {
+            let (change, script) = address_and_script(&seed(), 0, scope, 0);
+            let mut request: serde_json::Value =
+                serde_json::from_str(&request_json(&[100_000], false)).unwrap();
+            request["change"] = serde_json::json!({
+                "address": change,
+                "derivationPath": format!("m/44'/133'/0'/{scope}/0"),
+            });
+            let quote: TransparentQuote =
+                serde_json::from_str("e_json(&request.to_string()).unwrap()).unwrap();
+            assert_eq!(quote.send_amount_zat, "50000");
+            assert_eq!(quote.change_zat, "40000");
+            assert_eq!(quote.fee_zat, "10000");
+            let built: TransparentBuildResult = serde_json::from_str(
+                &build_with_account_xprv_json(&request.to_string(), &xprv()).unwrap(),
+            )
+            .unwrap();
+            let tx = zcash_primitives::transaction::Transaction::read(
+                hex::decode(&built.raw_tx).unwrap().as_slice(),
+                BranchId::Nu6_3,
+            )
+            .unwrap();
+            let outputs = &tx.transparent_bundle().unwrap().vout;
+            assert_eq!(outputs.len(), 2);
+            assert_eq!(u64::from(outputs[1].value()), 40_000);
+            assert_eq!(hex::encode(outputs[1].script_pubkey().0.to_bytes()), script);
+
+            let mut spend: serde_json::Value =
+                serde_json::from_str(&request_json(&[40_000], true)).unwrap();
+            spend["utxos"][0]["txid"] = built.txid.clone().into();
+            spend["utxos"][0]["vout"] = 1.into();
+            spend["utxos"][0]["scriptPubKey"] = script.into();
+            spend["utxos"][0]["derivationPath"] = format!("m/44'/133'/0'/{scope}/0").into();
+            spend["selectedOutpoints"][0] = serde_json::json!({ "txid": built.txid, "vout": 1 });
+            let spent: TransparentBuildResult = serde_json::from_str(
+                &build_with_account_xprv_json(&spend.to_string(), &xprv()).unwrap(),
+            )
+            .unwrap();
+            assert_eq!(spent.fee_zat, "10000");
+        }
+    }
+
+    #[test]
+    fn self_payment_and_change_keep_separate_amounts_at_the_receive_address() {
+        let (address, script) = address_and_script(&seed(), 0, 0, 0);
+        let mut request: serde_json::Value =
+            serde_json::from_str(&request_json(&[100_000], false)).unwrap();
+        request["recipients"][0]["address"] = address.clone().into();
+        request["change"] = serde_json::json!({
+            "address": address,
+            "derivationPath": "m/44'/133'/0'/0/0",
+        });
+        let built: TransparentBuildResult = serde_json::from_str(
+            &build_with_account_xprv_json(&request.to_string(), &xprv()).unwrap(),
+        )
+        .unwrap();
+        let tx = zcash_primitives::transaction::Transaction::read(
+            hex::decode(&built.raw_tx).unwrap().as_slice(),
+            BranchId::Nu6_3,
+        )
+        .unwrap();
+        let outputs = &tx.transparent_bundle().unwrap().vout;
+        assert_eq!(outputs.len(), 2);
+        assert_eq!(u64::from(outputs[0].value()), 50_000);
+        assert_eq!(u64::from(outputs[1].value()), 40_000);
+        assert!(outputs
+            .iter()
+            .all(|output| hex::encode(output.script_pubkey().0.to_bytes()) == script));
+    }
+
+    #[test]
+    fn receive_address_change_preserves_path_and_ownership_checks() {
+        let mut request: serde_json::Value =
+            serde_json::from_str(&request_json(&[100_000], false)).unwrap();
+        for path in ["m/44'/133'/0'/0/1", "m/44'/133'/1'/0/0"] {
+            request["change"]["derivationPath"] = path.into();
+            assert_eq!(
+                quote_json(&request.to_string()).unwrap_err().code,
+                ErrorCode::InvalidDerivationPath
+            );
+        }
+        request["change"]["derivationPath"] = "m/44'/133'/0'/0/0".into();
+        // The existing internal address is not the declared receive address.
+        assert_eq!(
+            build_with_account_xprv_json(&request.to_string(), &xprv())
+                .unwrap_err()
+                .code,
+            ErrorCode::KeyMismatch
+        );
+    }
+
     /// Sub-dust change is added to the fee instead of failing.
     ///
     /// Sending 88,000 from a 100,000 UTXO: the fee is 10,000 with or without
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
index 24e173d0b..b4a30da95 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
@@ -786,6 +786,52 @@ mod tests {
         assert!(create_with_account_xpub(&request, &account_xpub(), "01").is_err());
     }
 
+    #[test]
+    fn hardware_can_return_change_to_the_receive_address() {
+        let receive = transparent_address(0, 0)
+            .to_zcash_address(NetworkType::Main)
+            .to_string();
+        for (destination, change_zat) in [(recipient(0), 35_000), (receive.clone(), 40_000)] {
+            let mut request = request(false);
+            request["recipients"][0]["address"] = destination.into();
+            request["change"] = json!({
+                "address": receive,
+                "derivationPath": "m/44'/133'/0'/0/0",
+            });
+            let request_json = request.to_string();
+            let original =
+                create_with_account_xpub(&request_json, &account_xpub(), &"01".repeat(32)).unwrap();
+            let signed = simulated_device_signature(&original);
+            let finalized =
+                combine_hardware_signed(&request_json, &account_xpub(), &original, &signed)
+                    .unwrap();
+            Verifier::new(pczt::Pczt::parse(&finalized).unwrap())
+                .with_transparent::(|bundle| {
+                    let change = bundle.outputs().last().unwrap();
+                    assert_eq!(u64::from(*change.value()), change_zat);
+                    assert_eq!(
+                        change.script_pubkey().to_bytes(),
+                        transparent_address(0, 0).script().to_bytes()
+                    );
+                    assert_eq!(change.bip32_derivation().len(), 1);
+                    assert!(bundle.inputs()[0].script_sig().is_some());
+                    Ok(())
+                })
+                .unwrap();
+
+            request["change"]["address"] = transparent_address(1, 0)
+                .to_zcash_address(NetworkType::Main)
+                .to_string()
+                .into();
+            assert!(create_with_account_xpub(
+                &request.to_string(),
+                &account_xpub(),
+                &"01".repeat(32)
+            )
+            .is_err());
+        }
+    }
+
     #[test]
     fn hardware_public_construction_and_signature_validation_cover_both_destinations() {
         for transparent_destination in [false, true] {

From 1e10e4c3b7e25ee4650287921c7a608bf12c4ef6 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 07:14:14 +0800
Subject: [PATCH 57/97] fix: keep the monero spend key inside the runtime

---
 chain-runtimes/monero/README.md               |  20 +-
 .../crates/monero-runtime/src/bindgen.rs      |  74 +++---
 .../monero/crates/monero-runtime/src/keys.rs  |  95 ++++++-
 .../crates/monero-runtime/src/review.rs       |  74 ++++++
 .../monero/crates/monero-runtime/src/spend.rs | 247 +++++++++++++++++-
 chain-runtimes/monero/scripts/smoke.js        |  10 +-
 6 files changed, 471 insertions(+), 49 deletions(-)

diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md
index 4fe76b770..a3eb43557 100644
--- a/chain-runtimes/monero/README.md
+++ b/chain-runtimes/monero/README.md
@@ -35,9 +35,9 @@ releases to `latest`. Branches other than `main` can publish alpha versions only
 ## Host contract
 
 1. **Import key images on unlock.** A view-only wallet cannot detect spends, so the
-   balance stays too high until `importKeyImages` is called. It covers only blocks
-   scanned afterwards; earlier spends need a rewind and rescan. `balance` reports the
-   unverified part as `unverifiableAtomic`.
+   balance stays too high until `importKeyImagesWithBip32Key` is called. It covers
+   only blocks scanned afterwards; earlier spends need a rewind and rescan. `balance`
+   reports the unverified part as `unverifiableAtomic`.
 2. **The node must be on the wallet's network.** It is identified by its genesis
    block; a mismatch fails with `NODE_NETWORK_MISMATCH`. `chainTip` works without an
    open wallet and returns `network`; check it before picking a birthday.
@@ -68,12 +68,12 @@ openWallet(dbName, network) / closeWallet() / deleteWallet(dbName)
 setNodeUrl(url) / setRequestHandler(handler)    no default node
 chainTip()                                      { height, network }
 
-deriveAccount(network, bip32PrivateKeyHex) / spendScalar(bip32PrivateKeyHex)
+deriveAccount(network, bip32PrivateKeyHex)
 deriveSubaddress(network, spendPub, viewPriv, major, minor)
 validateAddress(network, address)
 addAccount(uuid, spendPub, viewPriv, birthday) / listAccounts() / removeAccount(uuid)
 registerSubaddress(accountId, major, minor, label?)
-importKeyImages(accountId, spendPrivateKeyHex)
+importKeyImagesWithBip32Key(accountId, bip32PrivateKeyHex)
 
 updateChainTip(accountId, tip) / syncStep(accountId, maxBlocks) / syncPeek(accountId)
 rewindTo(accountId, height, tip)                destructive
@@ -83,7 +83,7 @@ transactionDetails(accountId, txid)
 prepareTransaction(accountId, recipientsJson, maxSend, chainTip, priority)
 verifyTransaction(signableHex, reviewJson)
 verifySignedTransaction(signableHex, reviewJson, rawHex)
-signTransaction(signableHex, spendPrivateKeyHex, reviewJson)
+signTransactionWithBip32Key(signableHex, bip32PrivateKeyHex, reviewJson)
 broadcastTransaction(accountId, rawHex, chainTip, outgoingAtomic?, changeAtomic?, signableHex, reviewJson)
 diagDatabase()
 ```
@@ -91,10 +91,10 @@ diagDatabase()
 ### Sending
 
 ```
-prepareTransaction      select inputs, build; no spend key
-verifyTransaction       check recipient, amount, fee and change against the review
-signTransaction         verify again, then sign; no network, no DB
-broadcastTransaction    record, then broadcast → { txid, broadcast: accepted | unknown }
+prepareTransaction           select inputs, build; no spend key
+verifyTransaction            check recipient, amount, fee and change against the review
+signTransactionWithBip32Key  verify again, then sign; no network, no DB
+broadcastTransaction         record, then broadcast → { txid, broadcast: accepted | unknown }
 ```
 
 - `prepareTransaction` takes exactly one recipient.
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
index 701027a20..2b676c510 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -6,8 +6,11 @@
 //!   JSON too (`{ code, params, detail }`), so the host needs no separate Error path.
 //! - Amounts are always strings: piconero values exceed JS `Number.MAX_SAFE_INTEGER`,
 //!   and numbers would silently lose precision.
-//! - Key material goes in, never out: seeds and spend keys may be passed in but are
-//!   never returned.
+//! - Key material goes in, never out: the BIP-32 key and the view key may be
+//!   passed in but are never returned. The spend key is reduced from the BIP-32
+//!   key inside each export that needs it, so it never crosses this boundary.
+//! - Secret parameters are owned `String`s wrapped in `Zeroizing`, wiping the
+//!   bindgen allocation itself; a `&str` would leave the input in freed memory.
 //!
 //! ## No scheduling here
 //!
@@ -92,17 +95,18 @@ pub async fn chain_tip() -> std::result::Result {
 
 /// Register an identity (view key pair).
 ///
-/// `spendPublicKeyHex` and `viewPrivateKeyHex` are 32-byte hex. The spend private
-/// key is not taken here; it is passed only for signing (see `signTransaction`).
+/// `spendPublicKeyHex` and `viewPrivateKeyHex` are 32-byte hex. No spend secret
+/// is taken here; see `signTransactionWithBip32Key`.
 #[wasm_bindgen(js_name = addAccount)]
 pub fn add_account(
     uuid: &str,
     spend_public_key_hex: &str,
-    view_private_key_hex: &str,
+    view_private_key_hex: String,
     birthday_height: u64,
 ) -> std::result::Result {
+    let view_private_key_hex = Zeroizing::new(view_private_key_hex);
     let spend = decode_hex(spend_public_key_hex, "spendPublicKeyHex")?;
-    let view = Zeroizing::new(decode_hex(view_private_key_hex, "viewPrivateKeyHex")?);
+    let view = Zeroizing::new(decode_hex(&view_private_key_hex, "viewPrivateKeyHex")?);
     let result = runtime::with_db(|db| {
         let identity = db.add_identity(uuid, &spend, &view, birthday_height)?;
         Ok(serde_json::json!({
@@ -234,13 +238,17 @@ pub fn transaction_details(
 /// Call as early as possible after unlock. Until then the balance is too high: a
 /// view-only wallet cannot detect spends, so spent outputs still look unspent. This
 /// only affects blocks scanned afterwards; earlier spends need a rewind and rescan.
-#[wasm_bindgen(js_name = importKeyImages)]
-pub fn import_key_images(
+///
+/// Takes the account's BIP-32 key (as `deriveAccount`); the spend key is reduced
+/// here and wiped after use.
+#[wasm_bindgen(js_name = importKeyImagesWithBip32Key)]
+pub fn import_key_images_with_bip32_key(
     account_id: i64,
-    spend_private_key_hex: &str,
+    bip32_private_key_hex: String,
 ) -> std::result::Result {
-    let spend = Zeroizing::new(decode_hex(spend_private_key_hex, "spendPrivateKeyHex")?);
-    let result = runtime::with_db(|db| spend::import_key_images(db, account_id, &spend))?;
+    let raw = decode_secret_hex(bip32_private_key_hex, "bip32PrivateKeyHex")?;
+    let result =
+        runtime::with_db(|db| spend::import_key_images_with_bip32_key(db, account_id, &raw))?;
     json(serde_json::json!({
         "imported": result.imported,
         "spendsFound": result.spends_found,
@@ -254,14 +262,15 @@ pub fn import_key_images(
 /// Matches OneKey V4 (`spend = sc_reduce32(key)`, `view = keccak(spend)`). Changing
 /// it would show existing users an empty wallet after importing the same mnemonic.
 ///
-/// Does not return the spend private key; the caller already has it.
+/// Does not return the spend private key.
 #[wasm_bindgen(js_name = deriveAccount)]
 pub fn derive_account(
     network: &str,
-    bip32_private_key_hex: &str,
+    bip32_private_key_hex: String,
 ) -> std::result::Result {
+    let bip32_private_key_hex = Zeroizing::new(bip32_private_key_hex);
     let net = keys::parse_network(network)?;
-    let raw = Zeroizing::new(decode_hex(bip32_private_key_hex, "bip32PrivateKeyHex")?);
+    let raw = Zeroizing::new(decode_hex(&bip32_private_key_hex, "bip32PrivateKeyHex")?);
     let derived = keys::derive_from_bip32_key(net, &raw)?;
     json(serde_json::json!({
         "primaryAddress": derived.primary_address,
@@ -270,26 +279,19 @@ pub fn derive_account(
     }))
 }
 
-/// Spend scalar for signing, from a BIP-32 private key. Same reduction as `deriveAccount`.
-#[wasm_bindgen(js_name = spendScalar)]
-pub fn spend_scalar(bip32_private_key_hex: &str) -> std::result::Result {
-    let raw = Zeroizing::new(decode_hex(bip32_private_key_hex, "bip32PrivateKeyHex")?);
-    let scalar = Zeroizing::new(keys::spend_scalar_from_bip32_key(&raw)?);
-    Ok(hex::encode(*scalar))
-}
-
 /// Derive a subaddress. Pure derivation; no DB.
 #[wasm_bindgen(js_name = deriveSubaddress)]
 pub fn derive_subaddress(
     network: &str,
     spend_public_key_hex: &str,
-    view_private_key_hex: &str,
+    view_private_key_hex: String,
     major: u32,
     minor: u32,
 ) -> std::result::Result {
+    let view_private_key_hex = Zeroizing::new(view_private_key_hex);
     let net = keys::parse_network(network)?;
     let spend = decode_hex(spend_public_key_hex, "spendPublicKeyHex")?;
-    let view = Zeroizing::new(decode_hex(view_private_key_hex, "viewPrivateKeyHex")?);
+    let view = Zeroizing::new(decode_hex(&view_private_key_hex, "viewPrivateKeyHex")?);
     let pair = keys::view_pair_from_bytes(&spend, &view)?;
     let address = keys::subaddress(&pair, net, major, minor)?;
     json(serde_json::json!({ "address": address, "major": major, "minor": minor }))
@@ -366,6 +368,13 @@ fn decode_hex(value: &str, field: &str) -> Result> {
     })
 }
 
+/// Takes ownership of a secret hex parameter so both it and the decoded bytes
+/// are wiped, including on errors.
+fn decode_secret_hex(value: String, field: &str) -> Result>> {
+    let value = Zeroizing::new(value);
+    Ok(Zeroizing::new(decode_hex(&value, field)?))
+}
+
 // ── Spend path ─────────────────────────────────────────────────────────────
 
 /// Select inputs and build. Needs no spend private key; does not broadcast.
@@ -432,17 +441,22 @@ pub async fn prepare_transaction(
 
 /// Sign a prepared transaction. No network, no DB, no broadcast.
 ///
-/// `spendPrivateKeyHex` is wiped after use, never stored or returned.
+/// Takes the account's BIP-32 key (as `deriveAccount`); the spend key is reduced
+/// here, and both are wiped after use, never stored or returned.
 /// Returns `{ txid, rawHex, sizeBytes }`; the txid is fixed at signing, so the host
 /// can record the pending transaction before broadcasting.
-#[wasm_bindgen(js_name = signTransaction)]
-pub fn sign_transaction(
+#[wasm_bindgen(js_name = signTransactionWithBip32Key)]
+pub fn sign_transaction_with_bip32_key(
     signable_hex: &str,
-    spend_private_key_hex: &str,
+    bip32_private_key_hex: String,
     review_json: &str,
 ) -> std::result::Result {
-    let spend = Zeroizing::new(decode_hex(spend_private_key_hex, "spendPrivateKeyHex")?);
-    json(spend::sign_for_host(signable_hex, &spend, review_json)?)
+    let raw = decode_secret_hex(bip32_private_key_hex, "bip32PrivateKeyHex")?;
+    json(spend::sign_for_host_with_bip32_key(
+        signable_hex,
+        &raw,
+        review_json,
+    )?)
 }
 
 /// Validate actual payment effects before the host presents its confirmation.
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/keys.rs b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
index 8e2ed5fd2..676e7ec3c 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
@@ -269,10 +269,28 @@ pub struct DerivedKeys {
 }
 
 /// Spend key scalar for signing; same reduction as [`derive_from_bip32_key`].
-pub fn spend_scalar_from_bip32_key(bip32_private_key: &[u8]) -> Result<[u8; 32]> {
-    let raw = expect_32(bip32_private_key, "bip32PrivateKey")?;
-    let spend = Scalar::from(curve25519_dalek::Scalar::from_bytes_mod_order(raw));
-    Ok(<[u8; 32]>::from(spend))
+///
+/// Stays inside the runtime: signing and key-image import take the BIP-32 key
+/// and call this, so the spend key never crosses the wasm boundary.
+pub fn spend_scalar_from_bip32_key(bip32_private_key: &[u8]) -> Result> {
+    let raw = secret_32(bip32_private_key, "bip32PrivateKey")?;
+    let spend = Zeroizing::new(Scalar::from(
+        curve25519_dalek::Scalar::from_bytes_mod_order(*raw),
+    ));
+    Ok(Zeroizing::new(<[u8; 32]>::from(*spend)))
+}
+
+/// [`expect_32`] into a buffer that is wiped on drop.
+fn secret_32(bytes: &[u8], field: &str) -> Result> {
+    if bytes.len() != 32 {
+        return Err(RuntimeError::with(
+            ErrorCode::InvalidKeyMaterial,
+            json!({ "field": field, "byteLen": bytes.len(), "expected": 32 }),
+        ));
+    }
+    let mut out = Zeroizing::new([0u8; 32]);
+    out.copy_from_slice(bytes);
+    Ok(out)
 }
 
 #[cfg(test)]
@@ -326,10 +344,77 @@ mod derive_tests {
         let key = [7u8; 32];
         let derived = derive_from_bip32_key(Network::Mainnet, &key).unwrap();
         let spend = spend_scalar_from_bip32_key(&key).unwrap();
-        let expected = <[u8; 32]>::from(Scalar::hash(spend));
+        let expected = <[u8; 32]>::from(Scalar::hash(*spend));
         assert_eq!(derived.view_private_key, expected);
     }
 
+    /// Pinned reduction outputs (`sc_reduce32`, little-endian mod l), checked
+    /// against an independent big-integer reference. Signing and key-image
+    /// import must reduce exactly as address derivation does.
+    #[test]
+    fn spend_scalar_reduction_is_pinned() {
+        for (input, expected) in [
+            // V4 vector (`m/44'/128'/0'`)
+            (
+                "8b28f5749ec99464d5a9d6527125aa8778ea017dd9e5cffaa567d2f62f2c8cbc",
+                "5c0d65767c87ca9b9fec3252e06815a277ea017dd9e5cffaa567d2f62f2c8c0c",
+            ),
+            (
+                "0000000000000000000000000000000000000000000000000000000000000000",
+                "0000000000000000000000000000000000000000000000000000000000000000",
+            ),
+            (
+                "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
+                "1c95988d7431ecd670cf7d73f45befc6feffffffffffffffffffffffffffff0f",
+            ),
+            // l - 1
+            (
+                "ecd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010",
+                "ecd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010",
+            ),
+            // l
+            (
+                "edd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010",
+                "0000000000000000000000000000000000000000000000000000000000000000",
+            ),
+            // l + 1
+            (
+                "eed3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010",
+                "0100000000000000000000000000000000000000000000000000000000000000",
+            ),
+        ] {
+            let scalar = spend_scalar_from_bip32_key(&hex::decode(input).unwrap()).unwrap();
+            assert_eq!(hex::encode(&scalar[..]), expected, "input {input}");
+        }
+    }
+
+    /// Signing and key-image import reduce exactly as the shipped reduction and
+    /// as address derivation: the reduced key's public point is the address's
+    /// spend key.
+    #[test]
+    fn spend_scalar_matches_the_reference_and_the_derived_address_for_random_keys() {
+        use rand_core::RngCore;
+        let mut rng = crate::spend::test_support::SeededRng::new(0x5eed);
+        for _ in 0..1000 {
+            let mut key = [0u8; 32];
+            rng.fill_bytes(&mut key);
+            let scalar = spend_scalar_from_bip32_key(&key).unwrap();
+            assert_eq!(
+                *scalar,
+                crate::spend::test_support::reference_spend_scalar(&key)
+            );
+            let dalek: curve25519_dalek::Scalar =
+                Scalar::read(&mut scalar.as_slice()).unwrap().into();
+            let public = dalek * curve25519_dalek::constants::ED25519_BASEPOINT_POINT;
+            assert_eq!(
+                public.compress().to_bytes(),
+                derive_from_bip32_key(Network::Mainnet, &key)
+                    .unwrap()
+                    .spend_public_key
+            );
+        }
+    }
+
     #[test]
     fn key_length_is_enforced() {
         let e = derive_from_bip32_key(Network::Mainnet, &[0u8; 31])
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/review.rs b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
index 4503ce044..75718040f 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/review.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
@@ -481,6 +481,80 @@ mod tests {
         (tx.serialize(), review, spend_bytes)
     }
 
+    /// Signing from the BIP-32 key produces the same transaction, byte for
+    /// byte under a fixed RNG, as signing from the spend key did. The txids were
+    /// recorded from the spend-key path before it left the wasm interface.
+    #[test]
+    fn signing_from_the_bip32_key_matches_the_spend_key_path() {
+        use crate::spend::test_support::{plus_group_order, SeededRng};
+        let change = |pair| Change::new(pair, None);
+        for (txid, (bytes, review, spend)) in [
+            (
+                "2d468af49a6d7fe0f591e6813a3b751e379dcd35f341ebf1258202c00a755c57",
+                fixture(vec![]),
+            ),
+            (
+                "47cf01a87459ab9ff041d29ff843bae47f7b4808b6743cf429bd4f0607238a8b",
+                fixture_with_inputs(vec![], change, 3),
+            ),
+            (
+                "c8ff2c3a62fd2552e49748c6fe8d749a50720da8632c7e0cc72fddd3f460d9e1",
+                fixture_with_options(vec![], change, 3, true, false),
+            ),
+            (
+                "e88d2717232572d5419be5ee7482b3986bc1fbf2b03a3f24f5c657b0c2bf6ea2",
+                fixture_with_options(vec![], change, 3, false, true),
+            ),
+            (
+                "c08e858375049f3c51d0290fc2fa7763a38d3ffd4882c678e5f918641dbf86cb",
+                fixture_with_options(vec![], change, 3, true, true),
+            ),
+        ] {
+            let encoded = hex::encode(bytes);
+            let json = review_json(&review);
+            let old = crate::spend::sign_for_host_with_rng(
+                &encoded,
+                &spend,
+                &json,
+                &mut SeededRng::new(42),
+            )
+            .unwrap();
+            assert_eq!(old["txid"], txid);
+            // A canonical key reduces to itself; `key + l` reduces to the key.
+            for bip32 in [spend, plus_group_order(&spend)] {
+                let new = crate::spend::sign_with_bip32_key_and_rng(
+                    &encoded,
+                    &bip32,
+                    &json,
+                    &mut SeededRng::new(42),
+                )
+                .unwrap();
+                assert_eq!(new, old);
+                verify_signed(&encoded, &review, new["rawHex"].as_str().unwrap()).unwrap();
+            }
+            let signed =
+                crate::spend::sign_for_host_with_bip32_key(&encoded, &spend, &json).unwrap();
+            verify_signed(&encoded, &review, signed["rawHex"].as_str().unwrap()).unwrap();
+        }
+    }
+
+    /// Another account's BIP-32 key cannot sign: the change check rejects it.
+    #[test]
+    fn signing_from_another_bip32_key_is_rejected() {
+        let (bytes, review, _) = fixture(vec![]);
+        let e = crate::spend::sign_for_host_with_bip32_key(
+            &hex::encode(bytes),
+            &[2u8; 32],
+            &review_json(&review),
+        )
+        .unwrap_err();
+        assert_eq!(e.code, crate::ErrorCode::InvalidRequest);
+        let e = crate::spend::sign_for_host_with_bip32_key("00", &[2u8; 31], &review_json(&review))
+            .unwrap_err();
+        assert_eq!(e.code, crate::ErrorCode::InvalidKeyMaterial);
+        assert_eq!(e.params["field"], "bip32PrivateKey");
+    }
+
     #[test]
     fn approved_transaction_is_verified_and_signed() {
         let (bytes, review, spend) = fixture(vec![]);
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
index 11c7064d8..8ad8a0edf 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -2,7 +2,8 @@
 //!
 //! ## The private spend key appears only here
 //!
-//! The host passes it per call; it is zeroized after use, never persisted, and
+//! The host passes the account's BIP-32 key per call and the spend key is
+//! reduced from it here; both are zeroized after use, never persisted, and
 //! never returned across the wasm boundary.
 //!
 //! ## Why key images are imported
@@ -696,6 +697,7 @@ pub fn selection_to_json(selection: &Selection) -> Value {
 
 #[cfg(test)]
 mod tests {
+    use super::test_support::{plus_group_order, reference_spend_scalar};
     use super::*;
     use crate::wallet::testing::db_with_identity;
     use monero_wallet::address::Network;
@@ -799,6 +801,128 @@ mod tests {
         assert_eq!(left, 0, "key-imaged outputs need no possible spends");
     }
 
+    /// A serialized `WalletOutput` owned by `spend` with the given offset.
+    fn owned_output_blob(spend: &[u8; 32], offset: u8, txid: [u8; 32]) -> (Vec, [u8; 32]) {
+        use monero_wallet::ed25519::Commitment;
+        let mut offset_bytes = [0u8; 32];
+        offset_bytes[0] = offset;
+        let offset = Scalar::read(&mut offset_bytes.as_slice()).unwrap();
+        let secret: curve25519_dalek::Scalar =
+            curve25519_dalek::Scalar::from_bytes_mod_order(*spend) + offset.into();
+        let key = Point::from(secret * curve25519_dalek::constants::ED25519_BASEPOINT_POINT);
+        let generator: curve25519_dalek::EdwardsPoint =
+            Point::biased_hash(key.compress().to_bytes()).into();
+        let image = Point::from(secret * generator);
+
+        let mut blob = Vec::new();
+        blob.extend_from_slice(&txid);
+        blob.extend_from_slice(&0u64.to_le_bytes()); // index in transaction
+        blob.extend_from_slice(&7u64.to_le_bytes()); // index on chain
+        key.compress().write(&mut blob).unwrap();
+        offset.write(&mut blob).unwrap();
+        Commitment::new(offset, 1_000).write(&mut blob).unwrap();
+        blob.extend_from_slice(&[0, 0, 0, 0]); // no timelock, subaddress, payment id, data
+        WalletOutput::read(&mut blob.as_slice()).expect("fixture must deserialize");
+        (blob, image.compress().to_bytes())
+    }
+
+    /// Outputs owned by `spend`; the first has a possible spend with its real key image.
+    fn db_with_owned_outputs(spend: &[u8; 32]) -> (Db, i64) {
+        let (db, id) = db_with_identity();
+        for n in 1..=3u8 {
+            let txid = [n; 32];
+            let (blob, image) = owned_output_blob(spend, n, txid);
+            db.conn()
+                .execute(
+                    "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx,
+                                          amount_atomic, height)
+                     VALUES (?1, ?2, ?3, ?4, 0, 1000, ?4)",
+                    params![id, blob, txid.to_vec(), i64::from(n) * 10],
+                )
+                .unwrap();
+            if n == 1 {
+                db.conn()
+                    .execute(
+                        "INSERT INTO possible_spends
+                           (identity_id, out_txid, out_index, key_image, spend_txid, height, timestamp)
+                         VALUES (?1, ?2, 0, ?3, ?4, 40, 1700000000)",
+                        params![id, txid.to_vec(), image.to_vec(), vec![0x51u8; 32]],
+                    )
+                    .unwrap();
+            }
+        }
+        (db, id)
+    }
+
+    type OutputRow = (i64, Option>, Option, Option>);
+
+    fn output_rows(db: &Db) -> Vec {
+        let mut stmt = db
+            .conn()
+            .prepare(
+                "SELECT id, key_image, spent_at_height, spent_in_txid FROM outputs ORDER BY id",
+            )
+            .unwrap();
+        stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))
+            .unwrap()
+            .collect::>>()
+            .unwrap()
+    }
+
+    /// Importing from the BIP-32 key stores exactly what the old spend-key path
+    /// stored, for canonical, reducible and non-canonical BIP-32 keys alike.
+    #[test]
+    fn key_image_import_from_the_bip32_key_matches_the_spend_key_path() {
+        let v4: [u8; 32] =
+            hex::decode("8b28f5749ec99464d5a9d6527125aa8778ea017dd9e5cffaa567d2f62f2c8cbc")
+                .unwrap()
+                .try_into()
+                .unwrap();
+        let mut rng = test_support::SeededRng::new(7);
+        let mut keys = vec![v4, [0xff; 32], [1; 32], plus_group_order(&[5; 32])];
+        for _ in 0..8 {
+            let mut key = [0u8; 32];
+            rng.fill_bytes(&mut key);
+            keys.push(key);
+        }
+        for bip32 in keys {
+            let spend = reference_spend_scalar(&bip32);
+
+            let (mut old_db, old_id) = db_with_owned_outputs(&spend);
+            let old = import_key_images(&mut old_db, old_id, &spend).unwrap();
+            let (mut new_db, new_id) = db_with_owned_outputs(&spend);
+            let new = import_key_images_with_bip32_key(&mut new_db, new_id, &bip32).unwrap();
+
+            assert_eq!((old.imported, old.spends_found), (3, 1));
+            assert_eq!(
+                (new.imported, new.spends_found),
+                (old.imported, old.spends_found)
+            );
+            let rows = output_rows(&new_db);
+            assert_eq!(rows, output_rows(&old_db));
+            assert!(rows.iter().all(|row| row.1.is_some()));
+            assert_eq!(rows[0].2, Some(40), "the real possible spend is confirmed");
+        }
+    }
+
+    /// A different account's key is still refused, not stored as a useless key image.
+    #[test]
+    fn key_image_import_from_another_bip32_key_is_refused() {
+        let (mut db, id) = db_with_owned_outputs(&reference_spend_scalar(&[3; 32]));
+        let e = match import_key_images_with_bip32_key(&mut db, id, &[4; 32]) {
+            Ok(_) => panic!("another key must not import"),
+            Err(e) => e,
+        };
+        assert_eq!(e.params["reason"], "doesNotMatchOutput");
+        assert!(output_rows(&db).iter().all(|row| row.1.is_none()));
+        let e = match import_key_images_with_bip32_key(&mut db, id, &[4; 31]) {
+            Ok(_) => panic!("short key must be refused"),
+            Err(e) => e,
+        };
+        assert_eq!(e.code, ErrorCode::InvalidKeyMaterial);
+        assert_eq!(e.params["field"], "bip32PrivateKey");
+    }
+
     // Invalid transaction bytes must fail before signing, even with a review attached.
     #[test]
     fn signing_rejects_a_blob_that_is_not_a_signable_transaction() {
@@ -1363,10 +1487,59 @@ pub async fn prepare_for_host(
 
 /// Signs a constructed transaction. No network or database access.
 pub fn sign_for_host(signable_hex: &str, spend_private: &[u8], review_json: &str) -> Result {
+    sign_for_host_with_rng(
+        signable_hex,
+        spend_private,
+        review_json,
+        &mut rand_core::OsRng,
+    )
+}
+
+/// [`sign_for_host`] from the BIP-32 key the account was derived from. The spend
+/// key is reduced here, with the same reduction as address derivation, so it
+/// never crosses the wasm boundary.
+pub fn sign_for_host_with_bip32_key(
+    signable_hex: &str,
+    bip32_private_key: &[u8],
+    review_json: &str,
+) -> Result {
+    sign_with_bip32_key_and_rng(
+        signable_hex,
+        bip32_private_key,
+        review_json,
+        &mut rand_core::OsRng,
+    )
+}
+
+/// [`import_key_images`] from the BIP-32 key; see [`sign_for_host_with_bip32_key`].
+pub fn import_key_images_with_bip32_key(
+    db: &mut Db,
+    identity_id: i64,
+    bip32_private_key: &[u8],
+) -> Result {
+    let spend = keys::spend_scalar_from_bip32_key(bip32_private_key)?;
+    import_key_images(db, identity_id, spend.as_slice())
+}
+
+pub(crate) fn sign_with_bip32_key_and_rng(
+    signable_hex: &str,
+    bip32_private_key: &[u8],
+    review_json: &str,
+    rng: &mut R,
+) -> Result {
+    let spend = keys::spend_scalar_from_bip32_key(bip32_private_key)?;
+    sign_for_host_with_rng(signable_hex, spend.as_slice(), review_json, rng)
+}
+
+pub(crate) fn sign_for_host_with_rng(
+    signable_hex: &str,
+    spend_private: &[u8],
+    review_json: &str,
+    rng: &mut R,
+) -> Result {
     let request = crate::review::parse_request(review_json)?;
     let signable = crate::review::verify(signable_hex, &request, Some(spend_private))?;
-    let mut rng = rand_core::OsRng;
-    let (raw, txid) = sign_prepared(signable, &mut rng, spend_private)?;
+    let (raw, txid) = sign_prepared(signable, rng, spend_private)?;
     Ok(json!({
         "txid": hex::encode(txid),
         "rawHex": hex::encode(&raw),
@@ -1723,3 +1896,71 @@ mod double_spend_tests {
         assert!(!is_double_spend(&other));
     }
 }
+
+/// Shared test fixtures for comparing the BIP-32-key paths with the old ones.
+#[cfg(test)]
+pub(crate) mod test_support {
+    use monero_wallet::ed25519::Scalar;
+    use rand_core::{CryptoRng, RngCore};
+
+    /// The scalar reduction as shipped before signing took the BIP-32 key,
+    /// frozen here as the reference for the old host-side path.
+    pub fn reference_spend_scalar(bip32: &[u8; 32]) -> [u8; 32] {
+        <[u8; 32]>::from(Scalar::from(
+            curve25519_dalek::Scalar::from_bytes_mod_order(*bip32),
+        ))
+    }
+
+    /// `bytes + l` (little-endian), a non-canonical encoding of the same scalar.
+    pub fn plus_group_order(bytes: &[u8; 32]) -> [u8; 32] {
+        let l = hex::decode("edd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010")
+            .unwrap();
+        let mut out = [0u8; 32];
+        let mut carry = 0u16;
+        for i in 0..32 {
+            let sum = u16::from(bytes[i]) + u16::from(l[i]) + carry;
+            out[i] = sum as u8;
+            carry = sum >> 8;
+        }
+        assert_eq!(carry, 0, "test key too large to add l");
+        out
+    }
+
+    /// Deterministic RNG so tests can compare signatures byte for byte.
+    /// SplitMix64. Not secure; tests only.
+    pub struct SeededRng(u64);
+
+    impl SeededRng {
+        pub fn new(seed: u64) -> Self {
+            Self(seed)
+        }
+    }
+
+    impl RngCore for SeededRng {
+        fn next_u32(&mut self) -> u32 {
+            self.next_u64() as u32
+        }
+
+        fn next_u64(&mut self) -> u64 {
+            self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
+            let mut z = self.0;
+            z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
+            z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
+            z ^ (z >> 31)
+        }
+
+        fn fill_bytes(&mut self, dest: &mut [u8]) {
+            for chunk in dest.chunks_mut(8) {
+                let bytes = self.next_u64().to_le_bytes();
+                chunk.copy_from_slice(&bytes[..chunk.len()]);
+            }
+        }
+
+        fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
+            self.fill_bytes(dest);
+            Ok(())
+        }
+    }
+
+    impl CryptoRng for SeededRng {}
+}
diff --git a/chain-runtimes/monero/scripts/smoke.js b/chain-runtimes/monero/scripts/smoke.js
index 0bc1527af..aa8c057fa 100755
--- a/chain-runtimes/monero/scripts/smoke.js
+++ b/chain-runtimes/monero/scripts/smoke.js
@@ -60,6 +60,14 @@ const diag = JSON.parse(rt.diagDatabase());
 check('identity stored', diag.counts.identities, 1);
 check('subaddress stored', diag.counts.subaddresses, 1);
 
+// Spend keys never cross the boundary: signing and key-image import take the
+// BIP-32 key and reduce it inside.
+for (const name of ['spendScalar', 'signTransaction', 'importKeyImages']) {
+  check(`${name} is not exported`, typeof rt[name], 'undefined');
+}
+const imported = JSON.parse(rt.importKeyImagesWithBip32Key(id, key));
+check('key-image import from the BIP-32 key on an empty wallet', imported.imported, 0);
+
 // Signing is pure computation. Bad input must be rejected, never passed on to broadcast.
 const review = JSON.stringify({
   network: 'mainnet',
@@ -76,7 +84,7 @@ for (const [label, hex, req, field] of [
   ['a malformed review', '00010203', '{}', 'reviewRequest'],
 ]) {
   try {
-    rt.signTransaction(hex, '00'.repeat(32), req);
+    rt.signTransactionWithBip32Key(hex, key, req);
     check(`signing rejects ${label}`, 'succeeded', 'failed');
   } catch (e) {
     const err = JSON.parse(e.message ?? e);

From 477f96f596efe308637863e35db400c99e2e7fa2 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 07:28:12 +0800
Subject: [PATCH 58/97] fix: wipe remaining monero key copies

---
 .../crates/monero-runtime/src/bindgen.rs      | 28 ++++--
 .../monero/crates/monero-runtime/src/keys.rs  | 94 +++++++++++++++++--
 .../monero/crates/monero-runtime/src/spend.rs | 46 +++++++--
 chain-runtimes/monero/scripts/smoke.js        | 17 ++++
 4 files changed, 159 insertions(+), 26 deletions(-)

diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
index 2b676c510..5a5ba1d80 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -106,7 +106,7 @@ pub fn add_account(
 ) -> std::result::Result {
     let view_private_key_hex = Zeroizing::new(view_private_key_hex);
     let spend = decode_hex(spend_public_key_hex, "spendPublicKeyHex")?;
-    let view = Zeroizing::new(decode_hex(&view_private_key_hex, "viewPrivateKeyHex")?);
+    let view = decode_secret_hex(&view_private_key_hex, "viewPrivateKeyHex")?;
     let result = runtime::with_db(|db| {
         let identity = db.add_identity(uuid, &spend, &view, birthday_height)?;
         Ok(serde_json::json!({
@@ -246,7 +246,8 @@ pub fn import_key_images_with_bip32_key(
     account_id: i64,
     bip32_private_key_hex: String,
 ) -> std::result::Result {
-    let raw = decode_secret_hex(bip32_private_key_hex, "bip32PrivateKeyHex")?;
+    let bip32_private_key_hex = Zeroizing::new(bip32_private_key_hex);
+    let raw = decode_secret_hex(&bip32_private_key_hex, "bip32PrivateKeyHex")?;
     let result =
         runtime::with_db(|db| spend::import_key_images_with_bip32_key(db, account_id, &raw))?;
     json(serde_json::json!({
@@ -270,7 +271,7 @@ pub fn derive_account(
 ) -> std::result::Result {
     let bip32_private_key_hex = Zeroizing::new(bip32_private_key_hex);
     let net = keys::parse_network(network)?;
-    let raw = Zeroizing::new(decode_hex(&bip32_private_key_hex, "bip32PrivateKeyHex")?);
+    let raw = decode_secret_hex(&bip32_private_key_hex, "bip32PrivateKeyHex")?;
     let derived = keys::derive_from_bip32_key(net, &raw)?;
     json(serde_json::json!({
         "primaryAddress": derived.primary_address,
@@ -291,7 +292,7 @@ pub fn derive_subaddress(
     let view_private_key_hex = Zeroizing::new(view_private_key_hex);
     let net = keys::parse_network(network)?;
     let spend = decode_hex(spend_public_key_hex, "spendPublicKeyHex")?;
-    let view = Zeroizing::new(decode_hex(&view_private_key_hex, "viewPrivateKeyHex")?);
+    let view = decode_secret_hex(&view_private_key_hex, "viewPrivateKeyHex")?;
     let pair = keys::view_pair_from_bytes(&spend, &view)?;
     let address = keys::subaddress(&pair, net, major, minor)?;
     json(serde_json::json!({ "address": address, "major": major, "minor": minor }))
@@ -368,11 +369,17 @@ fn decode_hex(value: &str, field: &str) -> Result> {
     })
 }
 
-/// Takes ownership of a secret hex parameter so both it and the decoded bytes
-/// are wiped, including on errors.
-fn decode_secret_hex(value: String, field: &str) -> Result>> {
-    let value = Zeroizing::new(value);
-    Ok(Zeroizing::new(decode_hex(&value, field)?))
+/// [`decode_hex`] into a buffer that is wiped on drop, including the bytes
+/// already decoded when the input turns out to be malformed.
+fn decode_secret_hex(value: &str, field: &str) -> Result>> {
+    let mut out = Zeroizing::new(vec![0u8; value.len() / 2]);
+    hex::decode_to_slice(value, out.as_mut_slice()).map_err(|_| {
+        RuntimeError::with(
+            ErrorCode::InvalidKeyMaterial,
+            serde_json::json!({ "field": field, "reason": "notHex" }),
+        )
+    })?;
+    Ok(out)
 }
 
 // ── Spend path ─────────────────────────────────────────────────────────────
@@ -451,7 +458,8 @@ pub fn sign_transaction_with_bip32_key(
     bip32_private_key_hex: String,
     review_json: &str,
 ) -> std::result::Result {
-    let raw = decode_secret_hex(bip32_private_key_hex, "bip32PrivateKeyHex")?;
+    let bip32_private_key_hex = Zeroizing::new(bip32_private_key_hex);
+    let raw = decode_secret_hex(&bip32_private_key_hex, "bip32PrivateKeyHex")?;
     json(spend::sign_for_host_with_bip32_key(
         signable_hex,
         &raw,
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/keys.rs b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
index 676e7ec3c..b1cf73cc5 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
@@ -12,7 +12,7 @@ use monero_wallet::{
     ViewPair,
 };
 use serde_json::json;
-use zeroize::Zeroizing;
+use zeroize::{Zeroize, Zeroizing};
 
 use crate::error::{ErrorCode, Result, RuntimeError};
 
@@ -235,19 +235,30 @@ mod tests {
 /// Returns view material and the primary address. **The spend key is not
 /// returned**: the host already holds the BIP-32 key it passed in.
 pub fn derive_from_bip32_key(network: Network, bip32_private_key: &[u8]) -> Result {
+    let derived = derive_keys_in_frame(network, bip32_private_key);
+    scrub_stack();
+    derived
+}
+
+// Separate frame so `scrub_stack` can overwrite it, including the by-value
+// key copies passed to the reductions.
+#[inline(never)]
+fn derive_keys_in_frame(network: Network, bip32_private_key: &[u8]) -> Result {
     use monero_wallet::ed25519::Point;
 
-    let raw = expect_32(bip32_private_key, "bip32PrivateKey")?;
+    let raw = secret_32(bip32_private_key, "bip32PrivateKey")?;
 
     // sc_reduce32: reduce 32 bytes into the scalar field.
-    let spend = Scalar::from(curve25519_dalek::Scalar::from_bytes_mod_order(raw));
+    let spend = Zeroizing::new(Scalar::from(
+        curve25519_dalek::Scalar::from_bytes_mod_order(*raw),
+    ));
     // hash_to_scalar: keccak256 then reduce; upstream `Scalar::hash`.
-    let view = Scalar::hash(<[u8; 32]>::from(spend));
+    let view = Zeroizing::new(Scalar::hash(<[u8; 32]>::from(*spend)));
 
     let spend_public =
-        Point::from(spend.into() * curve25519_dalek::constants::ED25519_BASEPOINT_POINT);
+        Point::from((*spend).into() * curve25519_dalek::constants::ED25519_BASEPOINT_POINT);
 
-    let pair = ViewPair::new(spend_public, Zeroizing::new(view)).map_err(|e| {
+    let pair = ViewPair::new(spend_public, Zeroizing::new(*view)).map_err(|e| {
         RuntimeError::with(
             ErrorCode::InvalidKeyMaterial,
             json!({ "field": "bip32PrivateKey" }),
@@ -257,7 +268,7 @@ pub fn derive_from_bip32_key(network: Network, bip32_private_key: &[u8]) -> Resu
 
     Ok(DerivedKeys {
         spend_public_key: spend_public.compress().to_bytes(),
-        view_private_key: <[u8; 32]>::from(view),
+        view_private_key: <[u8; 32]>::from(*view),
         primary_address: primary_address(&pair, network),
     })
 }
@@ -273,11 +284,22 @@ pub struct DerivedKeys {
 /// Stays inside the runtime: signing and key-image import take the BIP-32 key
 /// and call this, so the spend key never crosses the wasm boundary.
 pub fn spend_scalar_from_bip32_key(bip32_private_key: &[u8]) -> Result> {
+    let spend = reduce_spend_key_in_frame(bip32_private_key);
+    scrub_stack();
+    spend
+}
+
+#[inline(never)]
+fn reduce_spend_key_in_frame(bip32_private_key: &[u8]) -> Result> {
     let raw = secret_32(bip32_private_key, "bip32PrivateKey")?;
     let spend = Zeroizing::new(Scalar::from(
         curve25519_dalek::Scalar::from_bytes_mod_order(*raw),
     ));
-    Ok(Zeroizing::new(<[u8; 32]>::from(*spend)))
+    let mut out = Zeroizing::new([0u8; 32]);
+    spend
+        .write(&mut out.as_mut_slice())
+        .expect("a scalar is 32 bytes");
+    Ok(out)
 }
 
 /// [`expect_32`] into a buffer that is wiped on drop.
@@ -293,6 +315,21 @@ fn secret_32(bytes: &[u8], field: &str) -> Result> {
     Ok(out)
 }
 
+/// Stack overwritten by [`scrub_stack`]; more than the key derivation, key-image
+/// and signing call chains use below their entry frames.
+const STACK_SCRUB_BYTES: usize = 64 * 1024;
+
+/// Overwrites the stack just below the caller's frame, where the functions it
+/// just returned from kept their secret temporaries (by-value key copies,
+/// reduction intermediates) that `Zeroizing` cannot reach. Best effort: frames
+/// deeper than [`STACK_SCRUB_BYTES`] are not covered.
+#[inline(never)]
+pub(crate) fn scrub_stack() {
+    let mut area = [0u8; STACK_SCRUB_BYTES];
+    area.zeroize();
+    core::hint::black_box(&area);
+}
+
 #[cfg(test)]
 mod derive_tests {
     use super::*;
@@ -415,6 +452,47 @@ mod derive_tests {
         }
     }
 
+    /// The derivation as shipped before its secrets were wiped, frozen as the
+    /// reference: wiping must not change a single derived byte.
+    fn reference_derive(raw: [u8; 32]) -> ([u8; 32], [u8; 32], String) {
+        use monero_wallet::ed25519::Point;
+        let spend = Scalar::from(curve25519_dalek::Scalar::from_bytes_mod_order(raw));
+        let view = Scalar::hash(<[u8; 32]>::from(spend));
+        let spend_public =
+            Point::from(spend.into() * curve25519_dalek::constants::ED25519_BASEPOINT_POINT);
+        let pair = ViewPair::new(spend_public, Zeroizing::new(view)).unwrap();
+        (
+            spend_public.compress().to_bytes(),
+            <[u8; 32]>::from(view),
+            primary_address(&pair, Network::Mainnet),
+        )
+    }
+
+    #[test]
+    fn derivation_matches_the_reference_for_random_and_edge_keys() {
+        use rand_core::RngCore;
+        let mut rng = crate::spend::test_support::SeededRng::new(0xd3e1);
+        let mut inputs = vec![[0xffu8; 32], [1u8; 32]];
+        inputs.push(
+            hex::decode("8b28f5749ec99464d5a9d6527125aa8778ea017dd9e5cffaa567d2f62f2c8cbc")
+                .unwrap()
+                .try_into()
+                .unwrap(),
+        );
+        for _ in 0..300 {
+            let mut key = [0u8; 32];
+            rng.fill_bytes(&mut key);
+            inputs.push(key);
+        }
+        for key in inputs {
+            let derived = derive_from_bip32_key(Network::Mainnet, &key).unwrap();
+            let (spend_public, view, address) = reference_derive(key);
+            assert_eq!(derived.spend_public_key, spend_public);
+            assert_eq!(derived.view_private_key, view);
+            assert_eq!(derived.primary_address, address);
+        }
+    }
+
     #[test]
     fn key_length_is_enforced() {
         let e = derive_from_bip32_key(Network::Mainnet, &[0u8; 31])
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
index 8ad8a0edf..f91afba9d 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -49,9 +49,9 @@ pub const RING_LEN: u8 = 16;
 fn key_image_for(output: &WalletOutput, spend: &Zeroizing) -> Result<[u8; 32]> {
     use core::ops::Deref;
 
-    let spend_dalek: curve25519_dalek::Scalar = (**spend).into();
+    let spend_dalek: Zeroizing = Zeroizing::new((**spend).into());
     let offset: curve25519_dalek::Scalar = output.key_offset().into();
-    let input_key = Zeroizing::new(spend_dalek + offset);
+    let input_key = Zeroizing::new(*spend_dalek + offset);
 
     let derived =
         Point::from(input_key.deref() * curve25519_dalek::constants::ED25519_BASEPOINT_POINT);
@@ -101,13 +101,30 @@ pub fn import_key_images(
             .map_err(|e| db_err("listOutputsWithoutKeyImage", e))?
     };
 
+    let computed = compute_key_images(pending, &spend);
+    keys::scrub_stack();
+    apply_key_images(db, identity_id, &computed?)
+}
+
+/// `(output id, blob, txid, index in tx)` of an output lacking a key image.
+type PendingOutput = (i64, Vec, Vec, i64);
+/// `(output id, key image, txid, index in tx)`.
+type ComputedKeyImage = (i64, [u8; 32], Vec, i64);
+
+// Separate frame so `scrub_stack` can overwrite what the key-image math left
+// on the stack.
+#[inline(never)]
+fn compute_key_images(
+    pending: Vec,
+    spend: &Zeroizing,
+) -> Result> {
     let mut computed = Vec::with_capacity(pending.len());
     for (id, blob, txid, index) in pending {
         let output = WalletOutput::read(&mut blob.as_slice())
             .map_err(|e| db_err("deserializeOutput", format!("output {id}: {e}")))?;
-        computed.push((id, key_image_for(&output, &spend)?, txid, index));
+        computed.push((id, key_image_for(&output, spend)?, txid, index));
     }
-    apply_key_images(db, identity_id, &computed)
+    Ok(computed)
 }
 
 /// Stores computed key images and confirms earlier spends from possible spends.
@@ -182,12 +199,12 @@ pub struct KeyImageImport {
 }
 
 fn parse_spend_key(bytes: &[u8]) -> Result> {
-    let arr = <[u8; 32]>::try_from(bytes).map_err(|_| {
+    let arr = Zeroizing::new(<[u8; 32]>::try_from(bytes).map_err(|_| {
         RuntimeError::with(
             ErrorCode::InvalidKeyMaterial,
             json!({ "field": "spendPrivateKey", "byteLen": bytes.len(), "expected": 32 }),
         )
-    })?;
+    })?);
     let scalar = Scalar::read(&mut arr.as_slice()).map_err(|_| {
         RuntimeError::with(
             ErrorCode::InvalidKeyMaterial,
@@ -1538,8 +1555,9 @@ pub(crate) fn sign_for_host_with_rng(
     rng: &mut R,
 ) -> Result {
     let request = crate::review::parse_request(review_json)?;
-    let signable = crate::review::verify(signable_hex, &request, Some(spend_private))?;
-    let (raw, txid) = sign_prepared(signable, rng, spend_private)?;
+    let signed = verify_and_sign(signable_hex, &request, spend_private, rng);
+    keys::scrub_stack();
+    let (raw, txid) = signed?;
     Ok(json!({
         "txid": hex::encode(txid),
         "rawHex": hex::encode(&raw),
@@ -1547,6 +1565,18 @@ pub(crate) fn sign_for_host_with_rng(
     }))
 }
 
+// Separate frame so `scrub_stack` can overwrite what signing left on the stack.
+#[inline(never)]
+fn verify_and_sign(
+    signable_hex: &str,
+    request: &crate::review::ReviewRequest,
+    spend_private: &[u8],
+    rng: &mut R,
+) -> Result<(Vec, [u8; 32])> {
+    let signable = crate::review::verify(signable_hex, request, Some(spend_private))?;
+    sign_prepared(signable, rng, spend_private)
+}
+
 /// Amounts of our own send, known only at broadcast.
 #[derive(Debug, Default, Clone, Copy)]
 pub struct SentAmounts {
diff --git a/chain-runtimes/monero/scripts/smoke.js b/chain-runtimes/monero/scripts/smoke.js
index aa8c057fa..e0a2c3e26 100755
--- a/chain-runtimes/monero/scripts/smoke.js
+++ b/chain-runtimes/monero/scripts/smoke.js
@@ -78,6 +78,23 @@ const review = JSON.stringify({
   changeAtomic: '0',
   isMaxSend: false,
 });
+// Malformed secret hex is refused as notHex, never decoded partially.
+for (const [label, call] of [
+  ['deriveAccount', (bad) => rt.deriveAccount('mainnet', bad)],
+  ['signTransactionWithBip32Key', (bad) => rt.signTransactionWithBip32Key('00', bad, review)],
+  ['importKeyImagesWithBip32Key', (bad) => rt.importKeyImagesWithBip32Key(id, bad)],
+]) {
+  for (const bad of [`${key.slice(0, 62)}zz`, key.slice(1)]) {
+    try {
+      call(bad);
+      check(`${label} rejects malformed key hex`, 'succeeded', 'failed');
+    } catch (e) {
+      const err = JSON.parse(e.message ?? e);
+      check(`${label} rejects malformed key hex`, err.params.reason, 'notHex');
+    }
+  }
+}
+
 for (const [label, hex, req, field] of [
   ['non-hex input', 'zz', review, 'signableHex'],
   ['an unsignable transaction', '00010203', review, 'signableHex'],

From 422972dcb5f54d9e27473173ea1a0b0916aea863 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 07:28:12 +0800
Subject: [PATCH 59/97] docs: note that hosts never resubmit stored zcash sends

---
 chain-runtimes/zcash/README.md                     |  7 ++++---
 .../zcash/crates/zcash-runtime/src/bindgen.rs      | 14 ++++++++------
 .../zcash/crates/zcash-runtime/src/error.rs        |  4 ++--
 .../zcash/crates/zcash-runtime/src/network.rs      |  4 ++--
 .../zcash/crates/zcash-runtime/src/send.rs         |  7 ++++---
 .../zcash/crates/zcash-runtime/src/tx_state.rs     |  7 ++++---
 6 files changed, 24 insertions(+), 19 deletions(-)

diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md
index c2a8c063e..f29b38961 100644
--- a/chain-runtimes/zcash/README.md
+++ b/chain-runtimes/zcash/README.md
@@ -85,7 +85,7 @@ pcztProve(pczt)
 pcztCombine(original, signed)            merge an external signer's copy (signatures only)
 pcztSubmit(uuid, pczt)                   → { txid, broadcast }
 pendingBroadcastTxids(uuid)              stored, unmined, unexpired, not rejected
-broadcastTransaction(txid)               rebroadcast a stored transaction
+broadcastTransaction(txid)               resend a stored transaction; explicit user request only
 
 prewarmPczt(network, height)             build proving parameters; no wallet
 pcztProveAtHeight(height, pczt)          prove without a wallet
@@ -132,14 +132,15 @@ Prove before signing: the upstream Signer must be able to verify what the proofs
 cover. Building locks no notes: the signed transaction is stored before broadcast
 and from then on holds its notes until mined or expired. Storing is refused when
 another stored, unexpired transaction already spends one of the same notes (two
-reviews opened at once). Sync rebroadcasts the stored bytes. Broadcast outcomes:
+reviews opened at once). Sync does not rebroadcast it. Broadcast outcomes:
 
 - `accepted`: the node took it (`already known` / `in mempool` / `in blockchain`
   count as success).
 - `rejected`: only an explicit consensus-invalid or expired reply, recorded in
   `ext_onekey_tx_state` (the only rows it holds). The transaction stays stored;
   its notes return after its expiry height.
-- `unknown`: anything else. It stays pending and sync rebroadcasts the same bytes.
+- `unknown`: anything else. It stays pending until mined or expired; the host does
+  not resubmit it.
   Pending transactions do not block another payment or user-requested local-data
   deletion, reset or rescan.
 
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
index f44489bfc..1ccdfa069 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
@@ -590,8 +590,9 @@ async fn barrier_after_irreversible(params: serde_json::Value) -> Result<(), cra
 /// Returns `{ txid, broadcast: "accepted" | "rejected" | "unknown", error? }`.
 /// - `rejected`: the node definitively judged it consensus-invalid or expired; it can never be
 ///   mined. The transaction stays stored and its notes return only at expiry height.
-/// - `unknown`: delivery to the node is uncertain. The transaction stays pending and is
-///   rebroadcast on sync; the host must not treat it as a failed send.
+/// - `unknown`: delivery to the node is uncertain. The transaction stays pending until mined
+///   or expired and the host does not resubmit it; the host must not treat it as a failed
+///   send.
 #[wasm_bindgen(js_name = pcztSubmit)]
 pub async fn pczt_submit(account_uuid: String, pczt_bytes: Vec) -> Result {
     let outcome = runtime::with_db_and_client(move |mut db, mut client| async move {
@@ -619,8 +620,8 @@ pub async fn pczt_submit(account_uuid: String, pczt_bytes: Vec) -> Result Result {
     let txids = runtime::with_read_conn(|conn| tx_state::pending_txids(conn, &account_uuid))?;
@@ -633,12 +634,13 @@ pub fn pending_broadcast_txids(account_uuid: String) -> Result
     })?)
 }
 
-/// Rebroadcasts a stored pending transaction (called during sync). Irreversible.
+/// Resends a stored pending transaction. Irreversible. For an explicit user request only:
+/// sync does not call it, and an unmined send otherwise stays pending until mined or expired.
 ///
 /// Throws `BROADCAST_REJECTED` when the node definitively rejects it (do not retry);
 /// `BROADCAST_OUTCOME_UNKNOWN` when the node errored without proving it can never be mined;
 /// `NETWORK_ERROR` on transport failure. In the latter two cases the transaction stays pending
-/// and is rebroadcast on the next sync.
+/// until mined or expired.
 #[wasm_bindgen(js_name = broadcastTransaction)]
 pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> {
     let result = runtime::with_db_and_client(move |mut db, mut client| async move {
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
index 57d7d3adf..4535ef8cc 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
@@ -114,8 +114,8 @@ pub enum ErrorCode {
     /// The node returned an error that does not prove the transaction can never be
     /// mined: it may already be mined or in the mempool (double spend, duplicate
     /// nullifier, missing inputs), or the node may be temporarily refusing (busy,
-    /// mempool full, lagging). The transaction stays pending and is rebroadcast
-    /// during sync; scanning resolves it as mined or expired. Hosts must not treat
+    /// mempool full, lagging). The transaction stays pending and the host does not
+    /// resubmit it; scanning resolves it as mined or expired. Hosts must not treat
     /// this as a failed send. Params: `{ errorCode }`; `detail` holds the node's message.
     BroadcastOutcomeUnknown,
     /// The transaction may be in the in-memory wallet but persistence is unconfirmed.
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
index 0a0b5aec3..46462d162 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
@@ -244,7 +244,7 @@ fn broadcast_outcome_ambiguous(message: &str) -> bool {
 /// actually propagated, both would be mined. So this is an allowlist:
 /// consensus-invalid (proof, signature, value, branch) or expired. Transient or
 /// policy replies (busy, mempool full, lagging, non-standard) are an unknown
-/// outcome, rebroadcast during sync until mined or expired.
+/// outcome: the tx stays pending until mined or expired.
 fn broadcast_definitely_invalid(message: &str) -> bool {
     if broadcast_outcome_ambiguous(message) {
         return false;
@@ -401,7 +401,7 @@ mod tests {
     }
 
     // Rejection is an allowlist: any uncertain reply is an unknown outcome and
-    // the tx stays pending for rebroadcast.
+    // the tx stays pending until mined or expired.
     #[test]
     fn only_consensus_invalid_or_expired_replies_count_as_a_rejection() {
         for message in [
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
index fbf76ebe6..526eb56ce 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
@@ -6,7 +6,7 @@
 //!   runtime.pcztCreate()          build (needs wallet state: note selection, witness, anchor)
 //!   runtime.pcztProve()           prove; pure computation, no private keys
 //!   keys.pcztSignWithAccountKeys() sign (needs the spending keys; in onekey-zcash-keys)
-//!   runtime.pcztSubmit()          extract, store, broadcast (sync rebroadcasts the stored bytes)
+//!   runtime.pcztSubmit()          extract, store, broadcast once (sync does not rebroadcast)
 //! ```
 //!
 //! Proving precedes signing: the upstream Signer role needs enough information
@@ -879,7 +879,8 @@ pub enum SubmitOutcome {
         txid: String,
         error: RuntimeError,
     },
-    /// Unknown whether the node received it: stored, holds its notes, rebroadcast on sync.
+    /// Unknown whether the node received it: stored, holds its notes, and stays pending
+    /// until mined or expired; the host does not resubmit it.
     Unknown {
         txid: String,
         error: RuntimeError,
@@ -952,7 +953,7 @@ pub async fn submit_signed_pczt(
     Ok(record_submit_outcome(db, account_uuid, txid, result))
 }
 
-/// Reads a stored transaction's raw bytes from the wallet for rebroadcast.
+/// Reads a stored transaction's raw bytes from the wallet for broadcast.
 pub fn raw_transaction(db: &Db, txid: &str) -> Result> {
     use zcash_primitives::transaction::TxId;
 
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
index e0206cdaf..cbd9359d7 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
@@ -4,8 +4,9 @@
 //! the signed transaction is stored before broadcast, and stays in
 //! `v_transactions` as unmined (holding its notes) until it is mined or
 //! expires. The one fact the wallet schema cannot hold is that the trusted node
-//! definitively rejected it; that must stop rebroadcasts and show the send as
-//! failed.
+//! definitively rejected it; that must stop any resend and show the send as
+//! failed. An unmined send that was not rejected stays pending until mined or
+//! expired; the host does not resubmit it.
 
 use std::collections::HashSet;
 
@@ -210,7 +211,7 @@ pub fn assert_not_rejected(db: &mut Db, txid: &str) -> Result<()> {
 }
 
 /// This account's stored outgoing transactions that are neither mined, expired
-/// nor rejected: the ones a sync must rebroadcast.
+/// nor rejected: still pending. The host does not resubmit them.
 pub fn pending_txids(conn: &rusqlite::Connection, account_uuid: &str) -> Result> {
     let account_uuid = uuid_blob(account_uuid)?;
     let mut stmt = conn

From 2b5da9ece59d962336543495dd668f86d180dd29 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 08:53:26 +0800
Subject: [PATCH 60/97] fix: enable secure delete on every zcash wallet
 connection

---
 .../zcash/crates/zcash-runtime/src/storage.rs | 88 +++++++++++++++++++
 1 file changed, 88 insertions(+)

diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
index 7f842d36c..4e0edb720 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
@@ -220,6 +220,9 @@ pub fn open_connection(db_name: &str) -> Result {
     // Only takes effect before the first table exists, so every database
     // created from here on can hand freed pages back; see reclaim_free_pages.
     conn.execute_batch("PRAGMA auto_vacuum = INCREMENTAL;")?;
+    // Zero deleted rows (viewing keys, notes, memos) instead of leaving them
+    // in free pages; per connection, so every open needs it.
+    conn.execute_batch("PRAGMA secure_delete = ON;")?;
     #[cfg(target_arch = "wasm32")]
     if !memory_mode() {
         // SAH-pool uses rollback journals, not cross-context WAL coordination.
@@ -310,7 +313,13 @@ fn db_storage_err(operation: &str, db_name: &str, error: impl std::fmt::Debug) -
 
 #[cfg(test)]
 mod tests {
+    use rand::SeedableRng;
+    use rand_chacha::ChaCha20Rng;
+    use zcash_client_sqlite::{wallet::init::WalletMigrator, WalletDb};
+    use zcash_protocol::consensus::Network;
+
     use super::*;
+    use crate::clock::HostClock;
 
     fn page_counts(conn: &rusqlite::Connection) -> (i64, i64) {
         let pages = conn
@@ -367,6 +376,85 @@ mod tests {
         let _ = std::fs::remove_file(&path);
     }
 
+    fn secure_delete(conn: &rusqlite::Connection) -> i64 {
+        conn.query_row("PRAGMA secure_delete", [], |r| r.get(0))
+            .unwrap()
+    }
+
+    /// The pragma is per connection: the wallet's own, the separate read and
+    /// reclaim connections, and every reopen after a migration.
+    #[test]
+    fn every_connection_turns_on_secure_delete() {
+        let path = std::env::temp_dir().join("zr-secure-delete-connections.sqlite");
+        let _ = std::fs::remove_file(&path);
+        let name = path.to_str().unwrap();
+
+        // Same steps as wallet::open_and_migrate, keeping the connection so it
+        // can be asked afterwards: migrations must not turn the pragma off.
+        for _ in 0..2 {
+            let mut conn = open_connection(name).expect("open");
+            {
+                let rng = ChaCha20Rng::from_seed([7; 32]);
+                let mut db =
+                    WalletDb::from_connection(&mut conn, Network::TestNetwork, HostClock, rng);
+                WalletMigrator::new()
+                    .with_external_migrations(crate::tx_state::migrations())
+                    .init_or_migrate(&mut db)
+                    .unwrap();
+            }
+            assert_eq!(secure_delete(&conn), 1);
+        }
+
+        let db = crate::wallet::open_and_migrate("test", name).expect("reopen");
+        let read_conn = open_connection(name).expect("open");
+        assert_eq!(secure_delete(&read_conn), 1);
+        drop(read_conn);
+        drop(db);
+        let _ = std::fs::remove_file(&path);
+    }
+
+    /// Deleting a row must not leave its bytes readable in the file.
+    #[test]
+    fn deleted_rows_leave_no_plaintext_in_the_file() {
+        const MARKER: &str = "zr-secure-delete-marker-viewing-key";
+        // Larger than a page: the overflow pages it frees are zeroed only by
+        // a full secure_delete, not by the FAST mode some hosts default to.
+        let secret = MARKER.repeat(400);
+        let write_and_delete = |path: &std::path::Path, secure_delete: bool| {
+            let _ = std::fs::remove_file(path);
+            let conn = open_connection(path.to_str().unwrap()).expect("open");
+            if !secure_delete {
+                conn.execute_batch("PRAGMA secure_delete = OFF;").unwrap();
+            }
+            conn.execute_batch(
+                "CREATE TABLE secret (id INTEGER PRIMARY KEY, value TEXT NOT NULL);
+                 INSERT INTO secret (value) VALUES ('kept');",
+            )
+            .unwrap();
+            conn.execute("INSERT INTO secret (value) VALUES (?1)", [&secret])
+                .unwrap();
+            conn.execute("DELETE FROM secret WHERE value = ?1", [&secret])
+                .unwrap();
+        };
+        let contains_marker = |path: &std::path::Path| {
+            let bytes = std::fs::read(path).unwrap();
+            let _ = std::fs::remove_file(path);
+            bytes
+                .windows(MARKER.len())
+                .any(|window| window == MARKER.as_bytes())
+        };
+
+        // Control: the same steps with the pragma off keep the bytes, so the
+        // check below can tell the two apart.
+        let plain = std::env::temp_dir().join("zr-secure-delete-plain.sqlite");
+        write_and_delete(&plain, false);
+        assert!(contains_marker(&plain));
+
+        let zeroed = std::env::temp_dir().join("zr-secure-delete-zeroed.sqlite");
+        write_and_delete(&zeroed, true);
+        assert!(!contains_marker(&zeroed));
+    }
+
     /// auto_vacuum is fixed when the first table is created; an older file
     /// keeps its mode and is never touched.
     #[test]

From 202d022a5e799ffe07a0212fb4e3c06752241f1c Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 09:50:19 +0800
Subject: [PATCH 61/97] chore: bump privacy runtimes to 0.1.0-alpha.5

---
 chain-runtimes/monero/Cargo.lock | 2 +-
 chain-runtimes/monero/Cargo.toml | 2 +-
 chain-runtimes/zcash/Cargo.lock  | 6 +++---
 chain-runtimes/zcash/Cargo.toml  | 2 +-
 4 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock
index e945c9f17..3605ea9ec 100644
--- a/chain-runtimes/monero/Cargo.lock
+++ b/chain-runtimes/monero/Cargo.lock
@@ -1259,7 +1259,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-monero-runtime"
-version = "0.1.0-alpha.4"
+version = "0.1.0-alpha.5"
 dependencies = [
  "curve25519-dalek",
  "futures-lite",
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index 5fb28a8a6..a51e794ed 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/monero-runtime"]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.4"
+version = "0.1.0-alpha.5"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index fb0c53b21..9e32409b1 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1655,7 +1655,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-zcash-keys"
-version = "0.1.0-alpha.4"
+version = "0.1.0-alpha.5"
 dependencies = [
  "bip0039",
  "bip32",
@@ -1687,7 +1687,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-runtime"
-version = "0.1.0-alpha.4"
+version = "0.1.0-alpha.5"
 dependencies = [
  "blake2b_simd",
  "console_error_panic_hook",
@@ -1736,7 +1736,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-storage-benchmark"
-version = "0.1.0-alpha.4"
+version = "0.1.0-alpha.5"
 dependencies = [
  "console_error_panic_hook",
  "js-sys",
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index fd0379f66..82f02ee50 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -8,7 +8,7 @@ members = [
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.4"
+version = "0.1.0-alpha.5"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"

From 73b270c3c1bdbd60f691386bef12745a692aef2c Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 11:16:47 +0800
Subject: [PATCH 62/97] docs: trim privacy runtime comments and docs to current
 behavior

---
 chain-runtimes/monero/Cargo.toml              |  10 +-
 chain-runtimes/monero/README.md               |  16 +-
 .../crates/monero-runtime/src/bindgen.rs      |  11 +-
 .../crates/monero-runtime/src/blocks_bin.rs   |  13 +-
 .../monero/crates/monero-runtime/src/keys.rs  |   8 +-
 .../crates/monero-runtime/src/network.rs      |  19 +--
 .../crates/monero-runtime/src/review.rs       |   3 +-
 .../crates/monero-runtime/src/runtime.rs      |  13 +-
 .../monero/crates/monero-runtime/src/scan.rs  |  14 +-
 .../monero/crates/monero-runtime/src/spend.rs |  12 +-
 .../crates/monero-runtime/src/storage.rs      |   3 +-
 .../monero/crates/monero-runtime/src/sync.rs  |  22 +--
 chain-runtimes/monero/scripts/smoke.js        |   2 +-
 chain-runtimes/zcash/Cargo.toml               |  16 +-
 chain-runtimes/zcash/README.md                |   8 +-
 chain-runtimes/zcash/RELEASING.md             |   7 +-
 .../zcash-keys-runtime/TRANSPARENT_TX_API.md  |  15 +-
 .../zcash-keys-runtime/src/account_keys.rs    |   2 +-
 .../crates/zcash-keys-runtime/src/lib.rs      |   5 +-
 .../crates/zcash-keys-runtime/src/sign.rs     |   3 +-
 .../src/transparent_send.rs                   |   3 +-
 .../src/transparent_send/shielding.rs         |   5 +-
 .../zcash/crates/zcash-runtime/Cargo.toml     |   6 +-
 .../zcash/crates/zcash-runtime/src/bindgen.rs | 140 ++++++------------
 .../zcash/crates/zcash-runtime/src/history.rs |   9 +-
 .../zcash/crates/zcash-runtime/src/network.rs |   6 +-
 .../zcash/crates/zcash-runtime/src/perf.rs    |   2 +-
 .../zcash/crates/zcash-runtime/src/runtime.rs |  34 ++---
 .../zcash/crates/zcash-runtime/src/send.rs    | 125 +++++-----------
 .../zcash/crates/zcash-runtime/src/stats.rs   |   3 +-
 .../zcash/crates/zcash-runtime/src/storage.rs |  15 +-
 .../zcash/crates/zcash-runtime/src/sync.rs    | 105 +++++--------
 .../crates/zcash-runtime/tests/scan_repro.rs  |   6 +-
 33 files changed, 229 insertions(+), 432 deletions(-)

diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index a51e794ed..d8a76f858 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -9,13 +9,9 @@ edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
 
-# ── monero-oxide: independent Rust implementation, MIT, no_std ───────────
-#
-# Chosen over wallet2 (see development/research): one wasm build for all
-# platforms, ~226 KB output, no cross-origin isolation, no C++ cross toolchain.
-#
-# It has no storage layer: `Scanner` is pure (register_subaddress +
-# scan(block) -> outputs). This workspace persists wallet state to SQLite.
+# monero-oxide over wallet2: one small wasm build for all platforms, no
+# cross-origin isolation, no C++ cross toolchain. It has no storage layer;
+# this workspace persists wallet state to SQLite.
 [workspace.dependencies]
 monero-wallet = { version = "0.2", default-features = false, features = ["std"] }
 monero-address = { version = "0.1", default-features = false, features = ["std"] }
diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md
index a3eb43557..3ac614a7a 100644
--- a/chain-runtimes/monero/README.md
+++ b/chain-runtimes/monero/README.md
@@ -93,21 +93,19 @@ diagDatabase()
 ```
 prepareTransaction           select inputs, build; no spend key
 verifyTransaction            check recipient, amount, fee and change against the review
-signTransactionWithBip32Key  verify again, then sign; no network, no DB
+signTransactionWithBip32Key  verify again, reduce the spend key from the account BIP-32 key, sign; no network, no DB
 broadcastTransaction         record, then broadcast → { txid, broadcast: accepted | unknown }
 ```
 
 - `prepareTransaction` takes exactly one recipient.
-- Before broadcasting, the host verifies the signed transaction
-  against the same prepared transaction and review before broadcasting. The
-  broadcast boundary repeats that verification before touching the database or
-  node. Missing review evidence is rejected, including calls from older hosts.
-  The reviewed sender and network must match the local account before recording
-  a send, so another account's change cannot be credited to this account.
+- Before broadcasting, the host verifies the signed transaction against the same
+  prepared transaction and review. `broadcastTransaction` repeats that check
+  before touching the database or node, and rejects calls without review
+  evidence. The reviewed sender and network must match the local account, so
+  another account's change cannot be credited to this account.
 - Pending outgoing and change amounts come from that verified review. Optional
   host amount strings must be canonical unsigned integers equal to those values;
-  missing strings do not discard the amounts derived from the review. A retry
-  retains previously recorded amounts and fills only missing values.
+  missing strings do not discard the amounts derived from the review.
 - `verifySignedTransaction` returns the signed transaction id. It uses the pinned
   wallet library's output matching and the transaction's fee; it performs no
   network request and persists no data. This matches outputs and the fee; it
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
index 5a5ba1d80..a9bc3006f 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -310,10 +310,8 @@ pub fn validate_address(network: &str, address: &str) -> std::result::Result Promise`;
 /// `undefined` uninstalls it.
 ///
-/// In-wasm fetch is bound by browser mixed-content and CORS rules, and monerod sends
-/// no CORS headers by default, so few public nodes are reachable. The extension
-/// background, desktop main process and mobile native code are not bound by those
-/// rules, so any node is reachable through them.
+/// Lets nodes that in-wasm fetch cannot reach (mixed content, no CORS headers) be
+/// used through the extension background, desktop main process or mobile native code.
 #[wasm_bindgen(js_name = setRequestHandler)]
 pub fn set_request_handler(handler: Option) {
     crate::network::set_host_handler(handler);
@@ -339,9 +337,8 @@ pub fn diag_database() -> std::result::Result {
                 .map_err(|e| crate::error::db_err("diagCount", e))?;
             counts.insert(table.to_owned(), serde_json::json!(n));
         }
-        // Logical size (pages x page size), as the Zcash runtime reports it.
-        // Works through any VFS; the backing store's physical footprint can
-        // differ (free pages, storage-layer overhead).
+        // Logical size (pages x page size); the backing store's physical footprint
+        // can differ (free pages, storage-layer overhead).
         let pragma = |name: &str| -> Result {
             db.conn()
                 .query_row(&format!("PRAGMA {name}"), [], |r| r.get(0))
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs b/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs
index 5cfb26d37..31f68975c 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs
@@ -11,14 +11,10 @@
 //! it as all zeros (monero-project/monero#10120; fix #10652 is master-only), so it
 //! always drops the batch and falls back to per-block JSON.
 //!
-//! ## Trust model (same as wallet2, Cake, Feather)
+//! ## Trust model (same as wallet2)
 //!
 //! The header's transaction hash list is trusted; content is not re-hashed against
-//! it. Cost: a malicious node can serve fake transaction content under real hashes
-//! and distort the displayed balance (inflate or hide an incoming payment). It
-//! cannot steal funds: spending needs the private key, and the network rejects
-//! spends of fake outputs. See `wallet2::process_new_blockchain_entry`, which uses
-//! `b.tx_hashes[idx]`.
+//! it, as in `wallet2::process_new_blockchain_entry` (`b.tx_hashes[idx]`).
 //!
 //! Still checked: transaction count matches the header list, each block's output
 //! index lists match its transaction outputs, and heights are contiguous from the
@@ -572,9 +568,8 @@ mod tests {
         assert!(matches!(e, BlocksBinError::Protocol(_)));
     }
 
-    /// A real node response (xmr-node.cakewallet.com, 2026-09-23, start_height=3768621,
-    /// max_block_count=2), captured via the desktop main process. Covers the full parse:
-    /// blocks, pruned transactions, output indices, first RingCT index.
+    /// A real mainnet node response (start_height=3768621, max_block_count=2). Covers
+    /// the full parse: blocks, pruned transactions, output indices, first RingCT index.
     #[test]
     fn parses_a_real_node_response() {
         let bytes = include_bytes!("../tests/fixtures/get_blocks_bin_3768621.bin");
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/keys.rs b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
index b1cf73cc5..eed9f4b7e 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
@@ -3,8 +3,8 @@
 //! Holds the public spend key and private view key (monero-oxide `ViewPair`),
 //! everything scanning needs; the Zcash UFVK equivalent.
 //!
-//! The private spend key is never stored here or persisted. Signing takes the
-//! seed from the host per call and drops it afterwards.
+//! The private spend key is never stored or persisted. Signing takes the
+//! account BIP-32 key per call and reduces the spend key internally.
 
 use monero_wallet::{
     address::{MoneroAddress, Network, SubaddressIndex},
@@ -452,8 +452,8 @@ mod derive_tests {
         }
     }
 
-    /// The derivation as shipped before its secrets were wiped, frozen as the
-    /// reference: wiping must not change a single derived byte.
+    /// Reference derivation without stack wiping: wiping must not change a
+    /// single derived byte.
     fn reference_derive(raw: [u8; 32]) -> ([u8; 32], [u8; 32], String) {
         use monero_wallet::ed25519::Point;
         let spend = Scalar::from(curve25519_dalek::Scalar::from_bytes_mod_order(raw));
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/network.rs b/chain-runtimes/monero/crates/monero-runtime/src/network.rs
index 4c8039744..a74ce0c7c 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/network.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/network.rs
@@ -88,18 +88,10 @@ fn cap_response(
 
 // Request handler supplied by the host.
 //
-// ## Why the host sends requests
-//
-// In-wasm `fetch` runs in the browser context, so it is subject to mixed-content
-// blocking (plain-HTTP nodes) and CORS (monerod sends no
-// `Access-Control-Allow-Origin` by default). Few public nodes pass both, and
-// routing every user through one third-party node hands that operator everyone's
-// IP, scan ranges and broadcast timing.
-//
-// This is about reachability, not speed (scanning is 0.4% of total time). The
-// extension background (with `host_permissions`), the Electron main process and
-// React Native native code are not bound by those rules.
-//
+// In-wasm `fetch` is subject to mixed-content blocking (plain-HTTP nodes) and CORS
+// (monerod sends no `Access-Control-Allow-Origin` by default), so few public nodes
+// are reachable from it. The extension background (with `host_permissions`), the
+// Electron main process and React Native native code are not bound by those rules.
 // Without a host handler, requests fall back to in-wasm fetch.
 #[cfg(target_arch = "wasm32")]
 thread_local! {
@@ -237,8 +229,7 @@ impl FetchTransport {
         let url = format!("{base_url}/{}", route.trim_start_matches('/'));
         let content_type = content_type_for(&route);
 
-        // Prefer the host handler: it is not bound by mixed-content or CORS rules, so any
-        // node is usable. Otherwise fall back to in-wasm fetch below.
+        // Prefer the host handler; otherwise fall back to in-wasm fetch below.
         if let Some(handler) = host_handler() {
             let bytes = post_via_host(handler, &url, content_type, &body).await?;
             return cap_response(bytes, limit);
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/review.rs b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
index 75718040f..793145394 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/review.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
@@ -482,8 +482,7 @@ mod tests {
     }
 
     /// Signing from the BIP-32 key produces the same transaction, byte for
-    /// byte under a fixed RNG, as signing from the spend key did. The txids were
-    /// recorded from the spend-key path before it left the wasm interface.
+    /// byte under a fixed RNG, as signing from its reduced spend key (pinned txids).
     #[test]
     fn signing_from_the_bip32_key_matches_the_spend_key_path() {
         use crate::spend::test_support::{plus_group_order, SeededRng};
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
index 05e340784..8ae8094c5 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
@@ -18,16 +18,9 @@ thread_local! {
     static DAEMON_NETWORK: Cell> = const { Cell::new(None) };
     static DB_NAME: RefCell> = const { RefCell::new(None) };
 
-    // ── Concurrency guards ──────────────────────────────────────────────
-    //
-    // Async operations take DB out of here across awaits and put it back
-    // after. wasm is single-threaded, but awaits allow re-entrant host calls.
-    //
-    // Race without guards:
-    //   1. A is scanning with DB(A) taken
-    //   2. B calls openWallet(B); DB_NAME becomes B
-    //   3. A finishes and puts DB(A) back, while DB_NAME says B
-    // Every later operation then silently hits the wrong database.
+    // Async operations take DB out across awaits, and awaits allow re-entrant
+    // host calls: without these guards an openWallet(B) during A's scan would
+    // let A put DB(A) back under DB_NAME B.
     static BUSY: Cell = const { Cell::new(false) };
     static GENERATION: Cell = const { Cell::new(0) };
 
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
index adedaca8e..454b28e69 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
@@ -742,15 +742,13 @@ fn timelock_to_i64(timelock: monero_wallet::transaction::Timelock) -> i64 {
     }
 }
 
-/// Rewinds to `height`, dropping all scan results above it.
+/// Rewinds to `height`, dropping all scan results above it. Destructive; used for
+/// reorg recovery and user rescans.
 ///
-/// Destructive; used for reorg recovery and user rescans. Our own broadcasts
-/// within the reorg window of `tip` are kept: a reorged-out send usually
-/// returns to the pool and is mined again, and releasing its inputs could let
-/// a second send with other inputs also confirm. They revert to pending
-/// (height cleared) with inputs still spent, left to the pending check and
-/// scanning. Deeper sends cannot be reorged out; they are dropped and found
-/// again by the rescan, so a rescan does not turn old history pending.
+/// Our own broadcasts within the reorg window of `tip` revert to pending with
+/// inputs still spent: a reorged-out send usually returns to the pool and is mined
+/// again, and releasing its inputs could let a second send also confirm. Deeper
+/// sends cannot be reorged out; they are dropped and found again by the rescan.
 pub fn rewind_to(db: &mut Db, identity_id: i64, height: u64, tip: u64) -> Result<()> {
     let tx = db
         .conn_mut()
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
index f91afba9d..d341a379e 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -886,8 +886,8 @@ mod tests {
             .unwrap()
     }
 
-    /// Importing from the BIP-32 key stores exactly what the old spend-key path
-    /// stored, for canonical, reducible and non-canonical BIP-32 keys alike.
+    /// Importing from the BIP-32 key stores exactly what importing with the reduced
+    /// spend key stores, for canonical, reducible and non-canonical BIP-32 keys alike.
     #[test]
     fn key_image_import_from_the_bip32_key_matches_the_spend_key_path() {
         let v4: [u8; 32] =
@@ -1903,7 +1903,7 @@ mod double_spend_tests {
         }
     }
 
-    /// Current mainnet rates (2026-10) fit every tier with at least 5x headroom.
+    /// Current mainnet rates fit every tier with at least 5x headroom.
 
     #[test]
     fn current_mainnet_fee_rates_fit_every_priority() {
@@ -1927,14 +1927,14 @@ mod double_spend_tests {
     }
 }
 
-/// Shared test fixtures for comparing the BIP-32-key paths with the old ones.
+/// Shared test fixtures for checking the BIP-32-key paths against the spend-key paths.
 #[cfg(test)]
 pub(crate) mod test_support {
     use monero_wallet::ed25519::Scalar;
     use rand_core::{CryptoRng, RngCore};
 
-    /// The scalar reduction as shipped before signing took the BIP-32 key,
-    /// frozen here as the reference for the old host-side path.
+    /// Reference BIP-32 key to spend scalar reduction (mod l), independent of
+    /// `keys::spend_scalar_from_bip32_key`.
     pub fn reference_spend_scalar(bip32: &[u8; 32]) -> [u8; 32] {
         <[u8; 32]>::from(Scalar::from(
             curve25519_dalek::Scalar::from_bytes_mod_order(*bip32),
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
index e7dd67faa..1d6b0c9bb 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
@@ -2,8 +2,7 @@
 //!
 //! The wasm side runs in a dedicated Worker; desktop, web, extension and mobile
 //! WebEmbed all use the same OPFS sync-access VFS, so SQLite reads and writes
-//! pages directly instead of preloading the database into wasm memory. This is
-//! why monero-oxide was chosen over monero-ts, which serializes the whole wallet.
+//! pages directly instead of preloading the database into wasm memory.
 //!
 //! The native build is kept for Rust tests and local diagnostics.
 
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
index bdf07877a..72748f344 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
@@ -113,14 +113,10 @@ fn next_range(db: &Db, identity_id: i64) -> Result> {
 
 /// Remove the scanned span `[start, scanned_through]` from the pending ranges.
 ///
-/// Pending ranges can overlap: `rewind_and_requeue` queues a span from the rewind
-/// height while the old tail range is still queued. Consuming only the range that
-/// starts at `start` and re-inserting the remainder with a plain INSERT collides on
-/// the primary key when the remainder starts where another range does; the step
-/// rolls back and scanning never advances.
-///
-/// So the scanned span is subtracted from every overlapping range and remainders
-/// are upserted (same start keeps the farther end). Ranges need not be disjoint.
+/// Pending ranges can overlap (`rewind_and_requeue` queues from the rewind height
+/// while the old tail range is still queued), so the span is subtracted from every
+/// overlapping range and remainders are upserted (same start keeps the farther end);
+/// a plain INSERT would collide on the primary key and stall scanning.
 fn consume_range(db: &mut Db, identity_id: i64, start: u64, scanned_through: u64) -> Result<()> {
     let tx = db
         .conn_mut()
@@ -492,9 +488,8 @@ mod tests {
         assert_eq!(before, peek(&db, id).unwrap());
     }
 
-    /// Regression: a requeued range overlaps the old tail range and the remainder
-    /// starts exactly at another range's start. This used to collide on the primary
-    /// key and roll back the step, stalling the scan.
+    /// A requeued range overlaps the old tail range and the remainder starts exactly
+    /// at another range's start; consuming it must not collide on the primary key.
     #[test]
     fn consuming_across_overlapping_ranges_merges_instead_of_colliding() {
         let (mut db, id) = db_with_identity();
@@ -568,9 +563,8 @@ mod tests {
         assert!(MAX_BLOCKS_PER_CALL > 0);
     }
 
-    /// Regression: progress used to be `max(height)` over the shared `blocks` table,
-    /// so a caught-up identity pushed a backfilling identity's progress to the tip
-    /// and that history was never scanned.
+    /// A caught-up identity must not push a backfilling identity's progress to the
+    /// tip, or that history is never scanned.
     #[test]
     fn two_identities_keep_independent_progress() {
         use crate::wallet::testing::key_bytes;
diff --git a/chain-runtimes/monero/scripts/smoke.js b/chain-runtimes/monero/scripts/smoke.js
index e0a2c3e26..30f706d2d 100755
--- a/chain-runtimes/monero/scripts/smoke.js
+++ b/chain-runtimes/monero/scripts/smoke.js
@@ -150,7 +150,7 @@ async function online() {
   check('chain tip is a positive integer', Number.isInteger(tip.height) && tip.height > 0, true);
   console.log(`  chain tip ${tip.height}`);
 
-  // Scan a real range over the binary route (get_blocks_by_height.bin), which
+  // Scan a real range over the binary route (get_blocks.bin), which
   // uses a different Content-Type from the JSON routes.
   rt.updateChainTip(id, BigInt(tip.height));
   rt.rewindTo(id, BigInt(tip.height - 20), BigInt(tip.height));
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index 82f02ee50..259827e78 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -15,13 +15,10 @@ rust-version = "1.85"
 
 # ── Zcash dependencies: official stable releases ─────────────────────────
 #
-# Hard rule: the storage layer comes from unmodified crates.io releases; no
-# vendored or forked zcash storage code.
-#
-# The only change is one Cargo.toml edit to zcash_client_sqlite (see
-# scripts/vendor-deps.sh and patches/) that drops rusqlite's "bundled" feature,
-# which compiles SQLite's C sources and needs a libc sysroot wasm32 lacks.
-# No Zcash Rust source is modified. VFS persistence patches: patches/manifest.json.
+# The storage layer uses unmodified crates.io releases. The only change is a
+# Cargo.toml edit to zcash_client_sqlite (scripts/vendor-deps.sh, patches/) that
+# drops rusqlite's "bundled" feature, which needs a libc sysroot wasm32 lacks.
+# No Zcash Rust source is modified. All patches: patches/manifest.json.
 [workspace.dependencies]
 blake2b_simd = "1"
 zcash_client_backend = { version = "0.24.0", default-features = false, features = ["orchard", "transparent-inputs", "lightwalletd-tonic", "sync", "pczt"] }
@@ -73,15 +70,14 @@ tonic = { version = "0.14", default-features = false, features = ["codegen"] }
 tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] }
 tonic-web-wasm-client = "0.9.1"
 
-# Official zcash_client_sqlite release plus the one-line no-bundled patch.
+# Upstream releases plus the patches in patches/manifest.json.
 # Run `bash scripts/vendor-deps.sh` first to create vendor/.
 [patch.crates-io]
 zcash_client_sqlite = { path = "vendor/zcash_client_sqlite-0.22.0" }
 tonic-web-wasm-client = { path = "vendor/tonic-web-wasm-client-0.9.1" }
 
 [profile.release]
-# Measured: opt-level = 3 is no faster on mainnet scans (msScan 7350-8805 vs
-# 8064-8218 per 1000 blocks) but makes the wasm 31% larger (6.8 -> 8.9 MB).
+# opt-level = 3 is no faster on mainnet scans but makes the wasm ~30% larger.
 opt-level = "s"
 lto = true
 codegen-units = 1
diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md
index f29b38961..220734e0d 100644
--- a/chain-runtimes/zcash/README.md
+++ b/chain-runtimes/zcash/README.md
@@ -141,8 +141,9 @@ reviews opened at once). Sync does not rebroadcast it. Broadcast outcomes:
   its notes return after its expiry height.
 - `unknown`: anything else. It stays pending until mined or expired; the host does
   not resubmit it.
-  Pending transactions do not block another payment or user-requested local-data
-  deletion, reset or rescan.
+
+Pending transactions do not block another payment or user-requested local-data
+deletion, reset or rescan.
 
 Submission always extracts and stores the current signed transaction, including
 on retry. A shared nullifier identifies an input conflict; it never authorizes
@@ -170,7 +171,8 @@ use the stateless API in
   are recorded in `patches/manifest.json`; `--offline` rejects unrecorded vendor
   changes. The precompiled wasm SQLite is linked by `crates/zcash-runtime/build.rs`.
 - **Storage is OPFS** (SAH pool in `.onekey-zcash-opfs`, `zcash-main.db` /
-  `zcash-test.db`), with `journal_mode=DELETE` and `synchronous=FULL`. One Worker
+  `zcash-test.db`), with `journal_mode=DELETE`, `synchronous=FULL` and
+  `secure_delete=ON`. One Worker
   owns each origin's pool. OPFS is per-origin and subject to quota and eviction, so
   the embedding page's origin must be stable. When `storageRequiresWorkerRestart()`
   is true after an I/O failure, keep the failed call's result and restart the
diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md
index 8f8518c5f..b6e03adf6 100644
--- a/chain-runtimes/zcash/RELEASING.md
+++ b/chain-runtimes/zcash/RELEASING.md
@@ -45,9 +45,8 @@ consume the version until both exist: re-run that same run, which skips the
 package already published. Do not dispatch a new run from another commit for the
 same version, or runtime and keys would come from different sources.
 
-## App cutover
+## App update
 
-Until the pair exists on npm, keep the App's local `portal:` dependencies. Once
-both packages have been published, replace both entries in
-`packages/core/package.json` with the same exact version and update `yarn.lock`
+After both packages are on npm, set both entries in the App's
+`packages/core/package.json` to the same exact version and update `yarn.lock`
 through the App repository's dependency workflow. Do not use a version range.
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
index e2892f228..0f9a0793c 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
@@ -86,15 +86,16 @@ zatoshi value.
   Unified Address with an Orchard receiver (paid as an Ironwood note). A Unified
   Address without one is rejected rather than paid at a public receiver.
   Sapling/Sprout destinations are unsupported.
-- Change must be an owned P2PKH address. The App reuses the account's default
-  receive address at `0/0`; internal scope `1` with an address index below 40
-  remains supported for previously prepared transactions. Both signing paths
-  verify that the address matches the declared path in the signing account.
+- Change must be an owned P2PKH address: the account's receive address at
+  `m/44'/133'/account'/0/0`. Internal scope `1` with an address index below 40 is
+  also accepted. Both signing paths verify that the address matches the declared
+  path in the signing account.
 - Send-max: exactly one recipient, no `amountZat` and no `change`; the recipient gets
   the selected total minus the ZIP-317 fee.
 - Fixed amount: a surplus too small to fund a change output (below the 5,000 zatoshi
-  marginal fee, or not enough to pay for the extra output) is added to the fee and shown in the quote, so the overpayment stays
-  below about 0.0001 ZEC. A larger surplus requires `change`.
+  marginal fee, or not enough to pay for the extra output) is added to the fee and
+  shown in the quote, so the overpayment stays below about 0.0001 ZEC. A larger
+  surplus requires `change`.
 - `targetHeight` must be on the mainnet NU6.3 branch. `expiryHeight` is mandatory,
   comes from the host's policy, and must be after the target height and at most 100
   blocks later. The result is a V6 transaction.
@@ -128,4 +129,4 @@ Build:
 
 Build entry points recompute the quote and fail closed if any input script or change
 address does not match the derived key. Reserve every returned outpoint before
-broadcast and keep the exact raw transaction for ambiguous broadcast recovery.
+broadcast.
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
index 8e485ba21..656bce1dc 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
@@ -250,7 +250,7 @@ pub(crate) mod test_keys {
         bs58::encode(payload).with_check().into_string()
     }
 
-    /// Oracle: the upstream seed-based USK this crate no longer accepts.
+    /// Oracle: the upstream seed-based USK, which this crate does not accept.
     pub(crate) fn usk(seed: &[u8], account: u32) -> UnifiedSpendingKey {
         UnifiedSpendingKey::from_seed(&MAIN_NETWORK, seed, AccountId::try_from(account).unwrap())
             .unwrap()
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs
index bf6df47b6..cbf08d293 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs
@@ -13,10 +13,7 @@
 //!   and signed transactions.
 //! - Secret inputs, including the bindgen copies, are wrapped in `Zeroizing` and wiped after use.
 //! - The xprv is parsed without heap copies, and the parsed account keys are wiped on
-//!   drop (`account_keys::Wiped`). Known limit: upstream `SpendingKey`, `AccountPrivKey`,
-//!   and `secp256k1::SecretKey` lack `ZeroizeOnDrop`, so keys derived from them inside
-//!   upstream code (child secret keys, spend authorizing keys) and moved-from stack
-//!   copies are not wiped here; the host wipes the wasm stack after each call.
+//!   drop (`account_keys::Wiped`). The host wipes the wasm stack after each call.
 
 pub mod account_keys;
 pub mod error;
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
index 65c0b28e9..5745021a8 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
@@ -1,7 +1,6 @@
 //! PCZT signing with host-supplied account keys.
 //!
 //! This crate also handles spending keys in `account_keys` and `transparent_send`.
-//! See the crate documentation for the limits of derived-key zeroization.
 
 use pczt::roles::signer::Signer;
 use pczt::roles::verifier::{TransparentError, Verifier};
@@ -49,7 +48,7 @@ fn sign_transparent_inputs(
 
     for index in 0..input_count {
         let mut done = false;
-        // Receiving uses the external scope and change the internal one; try both.
+        // Inputs may belong to the external or the internal scope; try both.
         for scope in [TransparentKeyScope::EXTERNAL, TransparentKeyScope::INTERNAL] {
             for i in 0..TRANSPARENT_SCAN_GAP {
                 let Some(child) = NonHardenedChildIndex::from_index(i) else {
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
index ea1d4d6d0..60ff408f5 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
@@ -408,7 +408,8 @@ fn plan_transaction(request: TransparentTxRequest) -> Result {
         }
         let change_path =
             parse_derivation_path(&change_request.derivation_path, request.account_index)?;
-        // Reuse the default receive address, while accepting legacy internal change.
+        // External-scope change must be the default receive address (/0/0);
+        // internal-scope change is still accepted.
         if change_path.scope == 0 && change_path.index != 0 {
             return Err(KeysError::with(
                 ErrorCode::InvalidDerivationPath,
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
index b4a30da95..3e4d23dea 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
@@ -647,9 +647,8 @@ mod tests {
             .unwrap()
     }
 
-    // Regression: 100000 in, 83000/88000 out leaves change under the dust
-    // threshold, which the quote folds into the fee. Building used to redo the
-    // fee by ZIP-317 and fail with ChangeRequired after the user approved it.
+    // 100000 in, 83000/88000 out leaves sub-dust change that the quote folds into
+    // the fee; building must keep that fee instead of failing with ChangeRequired.
     #[test]
     fn a_quote_with_sub_dust_change_folded_into_the_fee_still_builds() {
         let fingerprint = "00".repeat(32);
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
index 1dbebfb4d..3c5d68b7d 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
+++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
@@ -80,11 +80,11 @@ futures = "0.3"
 # wasm-pack defaults to `wasm-opt -O`; -Oz shrinks further at the cost of build
 # time, with negligible runtime impact on this IO-bound workload.
 [package.metadata.wasm-pack.profile.release]
-# No --enable-simd: measured ~2% faster on mainnet (decrypt-share.html, 500
-# blocks x2) since the curve libraries have no SIMD paths, and it breaks old WebViews.
+# No --enable-simd: the curve libraries have no SIMD paths, so there is no
+# measurable gain, and it breaks old WebViews.
 wasm-opt = ["-Oz", "--enable-bulk-memory", "--enable-nontrapping-float-to-int"]
 
-# Debug profile: keep cargo optimizations (Halo2 proving is unusable without
+# Profiling profile: keep cargo optimizations (Halo2 proving is unusable without
 # them) but skip wasm-opt, which strips the name section panic stacks need.
 [package.metadata.wasm-pack.profile.profiling]
 wasm-opt = false
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
index 1ccdfa069..2b14102d5 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
@@ -84,9 +84,7 @@ pub fn init_memory_storage() {
 
 /// The capabilities of this version-locked wallet and keys package set.
 ///
-/// Lets the host hide unsupported actions up front instead of failing at proving time,
-/// after the user has reviewed the send and entered a password.
-///
+/// Lets the host hide unsupported actions up front instead of failing at proving time.
 #[wasm_bindgen(js_name = capabilities)]
 pub fn capabilities() -> String {
     serde_json::json!({
@@ -98,11 +96,9 @@ pub fn capabilities() -> String {
         "scan": true,
         "balance": true,
         "history": true,
-        // The wallet creates proposals and proofs; the keys package signs inputs.
-        // The host must combine both packages' capabilities.
+        // Proposals and proofs only; the keys package signs the inputs.
         "proveShielding": true,
         "notes": {
-            // Why a capability is unavailable, so the host can show different hints.
             "sapling": "Sapling is out of scope: not scanned, shown, received or spent; \
     its ~50MB proving parameters are not shipped",
             "transparent": "Transparent inputs are signed by the keys package; this package \
@@ -118,9 +114,7 @@ pub fn dependency_versions() -> String {
     crate::dependency_versions().to_string()
 }
 
-/// Diagnostic: structural summary of a single block. No scanning, no writes, no state change.
-///
-/// Confirms whether browser (gRPC-web proxy) and native (gRPC) clients receive the same data.
+/// Diagnostic: structural summary of a single block. No scanning, no writes.
 #[wasm_bindgen(js_name = diagBlockSummary)]
 pub async fn block_summary(height: u32) -> Result {
     Ok(
@@ -132,20 +126,18 @@ pub async fn block_summary(height: u32) -> Result {
     )
 }
 
-/// Open a page-backed database and apply the official SQLite migrations.
-/// No whole-database preload is required by the shared OPFS VFS.
+/// Opens a page-backed database and applies the official SQLite migrations.
 #[wasm_bindgen(js_name = openWallet)]
 pub async fn open_wallet(network_name: String, db_name: String) -> Result {
     let _perf = perf::span("openWallet");
     let (network_name, db_name) = (network_name.as_str(), db_name.as_str());
     let db = wallet::open_and_migrate(network_name, db_name)?;
-    // Rejected with WALLET_BUSY while an async operation runs; must propagate,
-    // otherwise the caller assumes the database was swapped.
+    // WALLET_BUSY must propagate, or the caller assumes the database was swapped.
     runtime::set_db(db, db_name)?;
     Ok(serde_json::json!({ "dbName": db_name, "network": network_name }).to_string())
 }
 
-/// Temporary perf tracing switch: logs per-step timings to the console (`[PRIV-PERF] rt`).
+/// Perf tracing switch: logs per-step timings to the console (`[PRIV-PERF] rt`).
 #[wasm_bindgen(js_name = setPerfTrace)]
 pub fn set_perf_trace(enabled: bool) {
     perf::set_enabled(enabled);
@@ -173,8 +165,7 @@ pub fn set_lightwalletd_url(base_url: &str) -> Result<(), JsValue> {
 
 /// Current chain tip height. Requires only `setLightwalletdUrl`, not an open wallet.
 ///
-/// The host uses it to pick a new account's birthday before the database exists;
-/// otherwise the birthday falls back to Sapling activation and a full scan.
+/// Lets the host pick a new account's birthday before the database exists.
 #[wasm_bindgen(js_name = chainTip)]
 pub async fn chain_tip() -> Result {
     Ok(runtime::with_client(|mut client| async move {
@@ -186,8 +177,7 @@ pub async fn chain_tip() -> Result {
 
 /// Fetches the current chain tip with an isolated client.
 ///
-/// Host-side birthday and scheduler probes must not replace the wallet's
-/// global client while a sync operation has borrowed it across an await.
+/// Probes must not replace the wallet's global client while a sync has borrowed it.
 #[wasm_bindgen(js_name = chainTipAt)]
 pub async fn chain_tip_at(base_url: String) -> Result {
     let mut client = network::connect(&base_url)?;
@@ -198,8 +188,8 @@ pub async fn chain_tip_at(base_url: String) -> Result {
 
 /// Imports a view-only account (UFVK) and returns its UUID.
 ///
-/// `birthdayHeight` is the scan start. New accounts pass the current tip; restores must pass
-/// a height early enough not to miss historical funds. This decision belongs to the host.
+/// `birthdayHeight` is the scan start: the current tip for new accounts, an early enough
+/// height for restores.
 #[wasm_bindgen(js_name = importAccountUfvk)]
 pub async fn import_account_ufvk(
     account_name: String,
@@ -226,7 +216,7 @@ pub async fn import_account_ufvk(
     )
 }
 
-/// Removes one account from the shared database. Does not delete the database, which holds other wallets' accounts.
+/// Removes one account from the shared database; other accounts and the database remain.
 #[wasm_bindgen(js_name = removeAccount)]
 pub async fn remove_account(account_uuid: String) -> Result<(), JsValue> {
     runtime::with_db(|db| account::remove_account(db, &account_uuid))?;
@@ -243,8 +233,7 @@ pub async fn remove_deleted_account(account_uuid: String) -> Result<(), JsValue>
 
 /// Finds the account for a UFVK, returning `{ uuid }` or `"null"` if absent.
 ///
-/// The only correct lookup in the shared per-network database: the first account is not
-/// necessarily the one wanted, and UUIDs change after a purge.
+/// The only correct lookup in the shared per-network database: UUIDs change after a purge.
 #[wasm_bindgen(js_name = accountByUfvk)]
 pub fn account_by_ufvk(ufvk: String) -> Result {
     let _perf = perf::span("accountByUfvk");
@@ -254,7 +243,6 @@ pub fn account_by_ufvk(ufvk: String) -> Result {
 /// Per-account sync status, derived from the account birthday and the database's remaining scan ranges.
 ///
 /// Global progress misleads in a shared database: adding an account makes all accounts look unsynced.
-/// The official schema has no per-account cursor and is not changed for this; this is read-only.
 ///
 /// Returns block heights, not a percentage: the upstream progress ratio is over notes in a moving
 /// window and never reaches 100%.
@@ -273,8 +261,7 @@ pub fn list_accounts() -> Result {
 
 /// Account balance as JSON.
 ///
-/// `trusted` / `untrusted` are confirmation thresholds (both >= 1, trusted <= untrusted):
-/// own change can be looser, external notes stricter. Values are a product decision passed by the host.
+/// `trusted` / `untrusted` are confirmation thresholds (both >= 1, trusted <= untrusted).
 /// Throws `NOT_SYNCED` before any block has been synced.
 #[wasm_bindgen(js_name = accountBalance)]
 pub fn account_balance(
@@ -294,11 +281,9 @@ pub fn account_balance(
 
 /// One-time sync preparation: downloads subtree roots for all three pools and updates the chain tip.
 ///
-/// The slowest step of a first sync, independent of batchSize; exposed separately so the host
-/// can show a distinct "preparing" state.
+/// The slowest step of a first sync; exposed separately so the host can show a "preparing" state.
 ///
 /// Returns `{ chainTip, saplingSubtrees, orchardSubtrees, ironwoodSubtrees }`.
-/// Call once at the start of a sync round.
 #[wasm_bindgen(js_name = syncPrepare)]
 pub async fn sync_prepare() -> Result {
     let _perf = perf::span("syncPrepare");
@@ -311,10 +296,10 @@ pub async fn sync_prepare() -> Result {
     )
 }
 
-/// Updates only the chain tip (one unary call, ~270ms on mainnet). Returns `{ chainTip }`.
+/// Updates only the chain tip (one unary call). Returns `{ chainTip }`.
 ///
-/// Use every sync round; subtree roots go through `syncPrepare` once per open, since
-/// re-downloading the ~1900 immutable roots costs ~7s per round on mainnet.
+/// Use every sync round; call `syncPrepare` once per open, since re-downloading the
+/// ~1900 subtree roots costs several seconds on mainnet.
 #[wasm_bindgen(js_name = syncTip)]
 pub async fn sync_tip() -> Result {
     Ok(
@@ -328,8 +313,6 @@ pub async fn sync_tip() -> Result {
 
 /// Read-only view of pending scan ranges; no network requests. Returns
 /// `{ ranges: [{ start, end, len, priority }], totalBlocks }`.
-///
-/// For host progress bars and for checking which range the wallet wants to scan.
 #[wasm_bindgen(js_name = syncPeek)]
 pub fn sync_peek() -> Result {
     Ok(runtime::with_db(|db| sync::peek(db))?)
@@ -367,8 +350,6 @@ pub fn pczt_quote(
     spend_source: Option,
     memo_hex: Option,
 ) -> Result {
-    // Same constructor and parameter order as `pcztCreate`: any differing selection
-    // field would make the quoted fee differ from the fee paid.
     let policy = send::parse_send_policy(
         trusted,
         untrusted,
@@ -401,8 +382,8 @@ pub fn transaction_details(account_uuid: String, txid: String) -> Result Result {
     Ok(runtime::with_read_conn(|conn| {
@@ -414,18 +395,15 @@ pub fn transaction_outputs(account_uuid: String, txid: String) -> Result Result {
-    // Deliberately no idle gate: this is how the wallet follows a reorg (sole caller is
-    // syncWallet's reorg branch). Refusing because a transaction is unmined would pin the
-    // account to an abandoned chain.
-    //
+    // No idle gate: this is how the wallet follows a reorg, and refusing because a
+    // transaction is unmined would pin the account to an abandoned chain.
     // User-triggered rescans use `queueRescanFrom`, which only requeues ranges.
     let rewound = runtime::with_db(|db| sync::rewind_to(db, height))?;
     runtime::reclaim_storage(storage::RECLAIM_PAGES_AFTER_DELETE);
@@ -495,9 +471,8 @@ pub fn rewind_to(height: u32) -> Result {
 
 /// Re-queue `[fromHeight, chainTip]` as historic work without deleting cached notes or history.
 ///
-/// This is the resume companion to `syncStep(activeUfvksJson)`: the host persists each privacy
-/// identity's pause cursor, applies its reorg margin, queues the missing range, and only then adds
-/// the identity back to the active UFVK set.
+/// Resume companion to `syncStep(activeUfvksJson)`: the host queues the range missed while an
+/// identity was paused (with a reorg margin) before adding it back to the active UFVK set.
 #[wasm_bindgen(js_name = queueRescanFrom)]
 pub fn queue_rescan_from(from_height: u32) -> Result {
     Ok(runtime::with_db(|db| {
@@ -514,7 +489,7 @@ pub fn queue_rescan_from(from_height: u32) -> Result {
 
 /// Builds an unproven, unsigned PCZT for a transfer and returns its bytes.
 ///
-/// `fallbackChangePool`: the product currently always passes `"ironwood"`, so change goes to the newest shielded pool.
+/// `fallbackChangePool`: must be `"ironwood"`; Orchard is spend-only after NU6.3.
 /// `padOrchardBundle`: pads the Orchard bundle to hide the real action count (larger, higher fee).
 #[wasm_bindgen(js_name = pcztCreate)]
 pub fn pczt_create(
@@ -563,9 +538,8 @@ pub fn pczt_prove(pczt_bytes: Vec) -> Result, JsValue> {
 
 /// Merges a redacted PCZT returned by an external (hardware) signer back into the full local PCZT.
 ///
-/// Hardware returns only public fields such as signatures; private fields (rseed, witness, etc.)
-/// come back as None. The Combiner takes whichever side has a value, so local + signed copies
-/// yield a provable, extractable PCZT. Needs no wallet database.
+/// Hardware returns only public fields such as signatures; the Combiner takes whichever side
+/// has a value. Needs no wallet database.
 #[wasm_bindgen(js_name = pcztCombine)]
 pub fn pczt_combine(original: Vec, signed: Vec) -> Result, JsValue> {
     Ok(send::combine_pczt(&original, &signed)?)
@@ -573,12 +547,9 @@ pub fn pczt_combine(original: Vec, signed: Vec) -> Result, JsVal
 
 /// Durability barrier after an irreversible step.
 ///
-/// A barrier failure means "unknown whether persistence reached durable storage", not that
-/// the step failed. Both callers are past the point of no return (`pcztSubmit` committed the
-/// transaction, `broadcastTransaction` sent it), so the real outcome must not be replaced by a
-/// generic storage error that would make the host retry or show an on-chain tx as failed.
-///
-/// Callers supply `params` (outcome shapes differ); the error code and detail are set here.
+/// A barrier failure means persistence is unconfirmed, not that the step failed. Both callers
+/// are past the point of no return, so the outcome travels in `params` instead of being replaced
+/// by a generic storage error that would make the host retry or show an on-chain tx as failed.
 async fn barrier_after_irreversible(params: serde_json::Value) -> Result<(), crate::RuntimeError> {
     storage::durability_barrier().await.map_err(|error| {
         crate::RuntimeError::with(crate::ErrorCode::FinalizeOutcomeUnknown, params).detail(error)
@@ -591,8 +562,7 @@ async fn barrier_after_irreversible(params: serde_json::Value) -> Result<(), cra
 /// - `rejected`: the node definitively judged it consensus-invalid or expired; it can never be
 ///   mined. The transaction stays stored and its notes return only at expiry height.
 /// - `unknown`: delivery to the node is uncertain. The transaction stays pending until mined
-///   or expired and the host does not resubmit it; the host must not treat it as a failed
-///   send.
+///   or expired; the host does not resubmit it and must not treat it as failed.
 #[wasm_bindgen(js_name = pcztSubmit)]
 pub async fn pczt_submit(account_uuid: String, pczt_bytes: Vec) -> Result {
     let outcome = runtime::with_db_and_client(move |mut db, mut client| async move {
@@ -652,8 +622,7 @@ pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> {
         };
         let r = match r {
             Err(e) if e.code == crate::ErrorCode::BroadcastRejected => {
-                // Even if persisting fails, return the node's rejection reason: it is what the
-                // user can act on. The persistence failure is attached as detail.
+                // Return the node's rejection even if persisting it fails.
                 let recorded =
                     tx_state::account_uuid_for_txid(&mut db, &txid).and_then(|account_uuid| {
                         tx_state::record_rejection(&mut db, &txid, &account_uuid, &e)
@@ -683,18 +652,15 @@ pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> {
     Ok(result?)
 }
 
-// ── Self-check ──────────────────────────────────────────────────────────
+// ── Storage and diagnostics ─────────────────────────────────────────────
 
-/// Deletes a wallet database (including its bytes in IndexedDB). Irreversible.
+/// Deletes a wallet database file. Irreversible.
 ///
 /// The database is a derived cache: UFVKs and birthdays are kept by the host, so deleting
-/// only forces a rescan. Used after the last account is removed and on app reset.
+/// only forces a rescan. Pending transactions do not block deletion.
 ///
-/// Does not check in-flight transactions: both uses must succeed, and transactions are already
-/// on chain or will expire. Operations that must wait for settlement are gated by the host.
-///
-/// Closes the database first if it is the one currently open (required before deletion).
-/// Returns `true` if deleted, `false` if it did not exist (not an error).
+/// Closes the database first if it is the one currently open.
+/// Returns `true` if deleted, `false` if it did not exist.
 #[wasm_bindgen(js_name = deleteWallet)]
 pub async fn delete_wallet(db_name: String) -> Result {
     if !storage::database_exists(&db_name).await? {
@@ -708,13 +674,9 @@ pub async fn delete_wallet(db_name: String) -> Result {
 
 /// Usage of the open wallet database, grouped by data meaning. Read-only.
 ///
-/// A stable contract, not `diag*`: the host uses it for capacity guards (e.g. stopping
-/// birthday backfill above a soft threshold).
-///
-/// `logicalBytes` is page count × page size, not IndexedDB physical usage (which includes
-/// write amplification, stale pages and async flushes). Do not extrapolate one from the other.
+/// A stable contract, not `diag*`: the host uses it for capacity guards.
 ///
-/// Arbitrary SQL is deliberately not offered: one bad statement could delete an anchor still needed for proving.
+/// `logicalBytes` is page count × page size, not physical storage usage.
 #[wasm_bindgen(js_name = storageStats)]
 pub fn storage_stats() -> Result {
     let db_name = runtime::open_db_name()
@@ -737,7 +699,7 @@ pub fn database_health() -> Result {
 
 /// Diagnostic: counts inputs per bundle in a PCZT.
 ///
-/// Input counts are direct evidence of which pool funds left from; fee differences are only indirect.
+/// Input counts show which pool funds left from.
 #[wasm_bindgen(js_name = diagPcztInputCounts)]
 pub fn pczt_input_counts(pczt_bytes: Vec) -> Result {
     let pczt = pczt::Pczt::parse(&pczt_bytes).map_err(|e| {
@@ -745,19 +707,13 @@ pub fn pczt_input_counts(pczt_bytes: Vec) -> Result {
             crate::RuntimeError::new(crate::ErrorCode::PcztError).detail(format!("{e:?}")),
         )
     })?;
-    // Action counts alone mislead: Orchard/Ironwood actions pair a spend with an output, and
-    // bundles are padded with dummies to at least 2. Two actions may be a real shielded spend
-    // or just a change output plus a dummy.
-    //
-    // `valueSum` = the pool's spends minus outputs (sign given separately). Negative means net
-    // inflow (change only); positive means notes from this pool were actually spent.
+    // Action counts alone mislead (actions pair a spend with an output and are padded to 2).
+    // `valueSum` = the pool's spends minus outputs; positive means notes from it were spent.
     let sum = |b: &pczt::orchard::Bundle| {
         let (magnitude, negative) = *b.value_sum();
         serde_json::json!({ "magnitude": magnitude, "negative": negative })
     };
-    // The transparent input value is the reliable mixing indicator:
-    // shielded spend = payment + fee − transparent input. `valueSum` gives only net flow, and a
-    // net inflow does not imply zero shielded spend.
+    // shielded spend = payment + fee − transparent input; `valueSum` gives only net flow.
     let transparent_value: u64 = pczt.transparent().inputs().iter().map(|i| *i.value()).sum();
 
     Ok(serde_json::json!({
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
index 4628fb8b0..25df5054e 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
@@ -37,9 +37,8 @@ fn db_err(e: impl std::fmt::Display) -> RuntimeError {
     RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": "history" })).detail(e)
 }
 
-// Keep the list and detail endpoints on the exact same projection. `row_to_json`
-// intentionally has one shape; adding a field to only one query would otherwise
-// compile and then fail when the other endpoint reads a missing column at runtime.
+// List and detail share one projection: `row_to_json` has one shape, so a column
+// added to only one query would fail at runtime in the other.
 const HISTORY_ROW_SELECT: &str = "SELECT
          tx_summary.txid,
          tx_summary.mined_height,
@@ -231,9 +230,7 @@ fn row_to_json(row: &rusqlite::Row<'_>) -> rusqlite::Result {
         // shielding transaction as just its fee.
         "totalSpentZat": row.get::<_, Option>(12)?,
         "totalReceivedZat": row.get::<_, Option>(13)?,
-        // Preserve exact upstream pool identifiers. The host may aggregate
-        // them for today's UI, but a future multi-pool UI must not need a
-        // rescan to recover information discarded here.
+        // Exact upstream pool identifiers; the host aggregates as it needs.
         "poolIds": pool_ids,
         // Signed account-owned value change for each exact pool. This cannot be
         // recovered from the aggregate row after an Orchard-to-Ironwood move.
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
index 46462d162..f6985666e 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
@@ -189,10 +189,8 @@ pub async fn broadcast(client: &mut LightClient, tx_bytes: Vec) -> Result<()
     .await?;
 
     if resp.error_code != 0 {
-        // `SendTransaction` is used as an idempotent retry primitive after an
-        // unknown network outcome. zcashd reports a duplicate through the
-        // same business-error channel as a real rejection, even though the
-        // desired postcondition (the node already has the tx) is satisfied.
+        // Nodes report a transaction they already hold as an error; the node
+        // having the tx is the outcome we want.
         if broadcast_already_known(&resp.error_message) {
             return Ok(());
         }
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs
index 167aac548..ff5c70a33 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs
@@ -1,4 +1,4 @@
-//! Temporary perf tracing: when enabled by the host, logs each export's duration
+//! Perf tracing: when enabled by the host, logs each export's duration
 //! to the console. Shares the host's `[PRIV-PERF]` prefix so one filter covers both.
 
 use std::sync::atomic::{AtomicBool, Ordering};
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs
index 044b2e9eb..f57491fa6 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs
@@ -17,20 +17,10 @@ thread_local! {
     // v_transactions open a separate read connection by name (same VFS, same data).
     static DB_NAME: RefCell> = const { RefCell::new(None) };
 
-    // ── Reentrancy guard ────────────────────────────────────────────────
-    //
-    // Async operations take DB out, hold it across awaits and put it back; the
-    // host can call in meanwhile. Unguarded race:
-    //   1. A is in syncStep with DB(A) taken
-    //   2. B calls openWallet(B); DB_NAME becomes B
-    //   3. A finishes and puts DB(A) back while DB_NAME says B
-    // Every later call then silently hits the wrong wallet, possibly spending
-    // A's notes in B's transactions.
-    //
-    // BUSY is the real guard: it refuses wallet switches meanwhile. GENERATION is
-    // a fallback that is currently unreachable (it is sampled after BUSY is set
-    // and set_db/close are blocked by BUSY); it covers future paths that await
-    // without holding BUSY. It is not a second independent guard today.
+    // Async operations hold DB across awaits. If another wallet were opened
+    // meanwhile, putting the old DB back would make later calls hit the wrong
+    // wallet. BUSY refuses wallet switches during an operation; GENERATION
+    // catches any path that awaits without holding BUSY.
     static BUSY: Cell = const { Cell::new(false) };
     static GENERATION: Cell = const { Cell::new(0) };
 
@@ -65,17 +55,11 @@ fn assert_idle(operation: &str) -> Result<()> {
 /// Sets BUSY while held and always clears it on drop, including early returns
 /// and panic unwinds.
 ///
-/// A wasm-bindgen `async fn` body starts only after the current synchronous
-/// block, so there are two windows:
-///
-/// - **After the call, before the body runs**: nothing is taken yet, so
-///   `openWallet` succeeds and the operation runs on the new wallet. The host's
-///   `withWalletLease` serializes this; the runtime cannot without making exports
-///   return Promises synchronously (typing every result as `any`).
-/// - **During awaits in the body**: DB is taken; BUSY blocks switching or closing.
-///
-/// Generation ensures that in either window a stale wallet never overwrites the
-/// current one.
+/// A wasm-bindgen `async fn` body starts after the current synchronous block,
+/// so an `openWallet` before it runs is not refused and the operation runs on
+/// the new wallet; the host serializes that window. During awaits BUSY blocks
+/// switching or closing, and the generation check keeps a stale wallet from
+/// overwriting the current one.
 struct BusyGuard {
     generation: u64,
 }
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
index 526eb56ce..113b38ca4 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
@@ -9,21 +9,12 @@
 //!   runtime.pcztSubmit()          extract, store, broadcast once (sync does not rebroadcast)
 //! ```
 //!
-//! Proving precedes signing: the upstream Signer role needs enough information
-//! to verify the proofs cover the right data, so proofs must already be in the PCZT.
-//!
 //! Key separation: build and broadcast need the wallet database, signing needs
 //! the spending keys; the two never live in the same crate.
 //!
-//! ## Why this stays in Rust
-//!
-//! Note selection, ZIP-317 fees, anchor choice and witnesses are consensus-relevant:
-//! a wrong anchor gets the transaction rejected, a wrong fee can lose funds. The
-//! mechanism stays in the upstream implementation.
-//!
-//! Policy knobs (change pool, dust policy, OVK policy, confirmations, bundle
-//! padding) all come from the host; this crate makes no product decisions and
-//! hides no defaults.
+//! Note selection, ZIP-317 fees, anchors and witnesses stay in the upstream
+//! implementation; policy knobs (change pool, confirmations, bundle padding)
+//! come from the host.
 
 use zcash_client_backend::data_api::wallet::{
     create_pczt_from_proposal, extract_and_store_transaction_from_pczt,
@@ -48,10 +39,7 @@ fn build_err(stage: &str, e: impl std::fmt::Display) -> RuntimeError {
 
 /// Maps proposal failures to error codes the host can branch on.
 ///
-/// `INSUFFICIENT_FUNDS` (with the shortfall) and `NOT_SYNCED` must not collapse
-/// into a generic `TRANSACTION_BUILD_ERROR`.
-///
-/// Upstream reports insufficient funds from two places; both are handled:
+/// Upstream reports insufficient funds from two places:
 ///
 /// - `Error::InsufficientFunds`: selection cannot cover the amount (transfers)
 /// - `Error::Change(ChangeError::InsufficientFunds)`: selection succeeded but
@@ -115,11 +103,10 @@ pub fn parse_change_pool(name: &str) -> Result {
     }
 }
 
-/// Parses the host's spend-source pool. Build and quote both require it;
-/// `None` is rejected in `build_proposal`.
+/// Parses the host's spend-source pool; `None` is rejected in `build_proposal`.
 ///
-/// Orchard remains a valid spend source, but cannot receive new change.
-/// Sapling spending is unsupported because this runtime does not ship its prover.
+/// Orchard remains a valid spend source but cannot receive new change. Sapling
+/// is unsupported because this runtime does not ship its prover.
 pub fn parse_spend_source(name: Option<&str>) -> Result> {
     match name {
         None => Ok(None),
@@ -151,15 +138,9 @@ pub struct SendPolicy {
     pub allow_zero_conf_shielding: bool,
     /// Select notes only from this shielded pool. Required: `None` is rejected at build.
     ///
-    /// 1. Excludes Sapling. Upstream `SpendPolicy::default()` allows it and
-    ///    selection prefers the oldest eligible note, so an account with pre-2022
-    ///    history would pick Sapling notes and fail at proving (`PROVE_SAPLING = false`),
-    ///    blocking every send.
-    /// 2. Enables per-pool withdrawal, e.g. moving old Orchard funds to a
-    ///    transparent address without spending Ironwood funds the user wants kept private.
-    ///
-    /// If the pool cannot cover the amount the result is `InsufficientFunds`;
-    /// upstream never crosses pools.
+    /// Excludes Sapling, which upstream `SpendPolicy::default()` would select
+    /// first for old accounts and then fail to prove. If the pool cannot cover the
+    /// amount the result is `InsufficientFunds`; pools are never crossed.
     pub spend_source: Option,
 }
 
@@ -179,9 +160,8 @@ impl SendPolicy {
 
 /// Builds a send policy from the host's raw arguments.
 ///
-/// Quote and build must both use this entry point. Fields such as
-/// `pad_orchard_bundle` change the bundle size and therefore the ZIP-317 fee;
-/// wiring them separately lets the quoted fee silently drift from the paid fee.
+/// Quote and build must both use this entry point: fields such as
+/// `pad_orchard_bundle` change the ZIP-317 fee.
 #[allow(clippy::too_many_arguments)]
 pub fn parse_send_policy(
     trusted: u32,
@@ -206,8 +186,7 @@ pub fn parse_send_policy(
 type TransferProposal =
     zcash_client_backend::proposal::Proposal;
 
-/// Recipient can only receive into Sapling. Sapling proving parameters are not
-/// shipped, so such a transaction would fail at proving after the user confirmed;
+/// Recipient can only receive into Sapling, which this runtime cannot prove;
 /// refuse before building.
 fn recipient_needs_sapling_output(
     params: &zcash_protocol::consensus::Network,
@@ -232,7 +211,7 @@ fn recipient_is_tex(
     )
 }
 
-// Keep the legacy text argument compatible; new hosts pass the exact ZIP 302 field.
+// `text` is UTF-8; `hex` is the exact 512-byte ZIP 302 memo field.
 pub fn parse_memo(text: Option<&str>, hex: Option<&str>) -> Result> {
     let invalid = || RuntimeError::new(ErrorCode::InvalidMemo);
     match (text, hex) {
@@ -310,12 +289,10 @@ fn build_proposal(
         policy.allow_zero_conf_shielding,
     )?;
 
-    // Spend only the selected shielded pool, never transparent UTXOs (as upstream's default).
+    // Spend only the selected shielded pool, never transparent UTXOs.
     let spend_policy = {
         use zcash_client_backend::data_api::wallet::input_selection::SpendPolicy;
         // Not SpendPolicy::default(): it allows Sapling. See SendPolicy::spend_source.
-        // Shielded pools are never combined, and the current pool is defined
-        // only by the host (ZCASH_CURRENT_SHIELDED_POOL): no default here, missing is rejected.
         let pool = policy.spend_source.ok_or_else(|| {
             RuntimeError::with(
                 ErrorCode::TransactionBuildError,
@@ -352,8 +329,6 @@ fn build_proposal(
 }
 
 /// Returns the fee only; builds no PCZT and locks no notes.
-///
-/// Must use the same proposal path as `create_pczt` so the quote matches the fee paid.
 pub fn quote(
     db: &mut Db,
     account_uuid: &str,
@@ -378,10 +353,9 @@ pub fn quote(
 
 /// Builds an unsigned transfer PCZT for review. Returns `(pcztBytes, feeZat)`.
 ///
-/// Locks nothing: a review the user abandons, or an app killed on the review
-/// page, must leave the notes spendable. Notes are held from the moment
-/// `submit_signed_pczt` stores the signed transaction, until it is mined or
-/// expires.
+/// Locks nothing, so an abandoned review leaves the notes spendable. Notes are
+/// held once `submit_signed_pczt` stores the signed transaction, until it is
+/// mined or expires.
 pub fn create_pczt(
     db: &mut Db,
     account_uuid: &str,
@@ -463,12 +437,10 @@ fn mark_wallet_outputs(
 }
 
 /// Sets `zip32_derivation` on each output whose recipient `fvk` owns (either
-/// scope) and whose note decrypts under that scope's IVK. Outputs that already
-/// name a `user_address` (real recipients) are left alone, as are outputs we do
-/// not own (padding). Undecryptable owned outputs are the zero-valued outputs
-/// the post-NU6.3 Orchard builder pairs with external-scope spends, with a
-/// randomized ciphertext: no one can decrypt them, so like padding they get no
-/// path claiming them as wallet outputs.
+/// scope) and whose note decrypts under that scope's IVK. Real recipients
+/// (`user_address` set) and padding are left alone. Undecryptable owned outputs
+/// are the zero-valued outputs the post-NU6.3 Orchard builder pairs with
+/// external-scope spends; like padding they get no path.
 fn mark_owned_outputs(
     pczt: pczt::Pczt,
     fvk: &orchard::keys::FullViewingKey,
@@ -565,17 +537,10 @@ fn circuit_version_for_branch(
 /// Merges the signed copy returned by an external signer (hardware) into the
 /// local original PCZT. It may add signatures only, never change the transaction.
 ///
-/// `TransactionExtractor` cannot catch this later: it recomputes the sighash of
-/// the merged transaction, so it only checks self-consistency, not what the user approved.
-///
-/// The bare `Combiner` currently blocks substitution only as a side effect of
-/// upstream behaviour (our PCZTs have `tx_modifiable == 0`, and all effect fields
-/// are set so conflicts are detected), which an upgrade could change.
-///
-/// Invariant enforced here: sighashes must be byte-identical before and after,
-/// and `scriptSig` must stay empty (it is outside the sighash, `None` in the
-/// original, and adopted as-is by `merge_optional`). Fails before proving;
-/// errors carry `field`.
+/// `TransactionExtractor` only checks self-consistency, not what the user
+/// approved, and the bare `Combiner` blocks substitution only as a side effect of
+/// upstream behaviour. So sighashes must be byte-identical before and after, and
+/// `scriptSig` must stay empty (it is outside the sighash). Errors carry `field`.
 pub fn combine_pczt(original: &[u8], signed: &[u8]) -> Result> {
     use pczt::roles::signer::Signer;
     use pczt::roles::verifier::{TransparentError, Verifier};
@@ -647,9 +612,7 @@ pub fn combine_pczt(original: &[u8], signed: &[u8]) -> Result> {
             return Err(mismatch("transparentSighash"));
         }
     }
-    // scriptSig is outside the sighash and is the one field the other side can
-    // inject (always None in our original; merge_optional adopts it). We never set
-    // it; SpendFinalizer builds it from partial_signatures at extraction.
+    // scriptSig is built by SpendFinalizer at extraction, never by a signer.
     // Check a clone: Verifier reparses and reserializes the bundle.
     if transparent_inputs > 0 {
         Verifier::new(combined.clone())
@@ -787,9 +750,7 @@ const SPEND_TABLES: [(&str, &str); 4] = [
 
 /// Refuses a just-stored transaction that does not spend from `account_uuid`,
 /// or that spends an output another stored transaction still holds (mined, or
-/// unmined and unexpired). Reviews lock nothing, so two open at once can select
-/// the same notes; storing both would leave the second pending until expiry
-/// for a spend the node can never accept.
+/// unmined and unexpired). Reviews lock nothing, so two can select the same notes.
 fn assert_sole_spend(
     ext: &zcash_client_sqlite::ExtensionTransaction<'_>,
     txid: &str,
@@ -887,7 +848,8 @@ pub enum SubmitOutcome {
     },
 }
 
-// A spent-input/duplicate-nullifier reply can refer to this transaction itself.
+// Only a definitive rejection is recorded; a spent-input reply can refer to this
+// transaction itself.
 fn first_submit_rejection(error: RuntimeError) -> std::result::Result {
     if error.code == ErrorCode::BroadcastRejected {
         Ok(error)
@@ -914,11 +876,9 @@ fn record_submit_outcome(
     }
 }
 
-/// Persist the exact authorized transaction before any external broadcast.
+/// Persists the exact authorized transaction before broadcasting it.
 ///
-/// Submitting the same signed PCZT again stores the same txid again (upstream
-/// upserts it) and rebroadcasts; a transaction the node already rejected is
-/// not sent again.
+/// A transaction the node already rejected is not sent again.
 pub async fn submit_signed_pczt(
     db: &mut Db,
     client: &mut crate::network::LightClient,
@@ -1228,7 +1188,7 @@ mod policy_tests {
             zcash_protocol::consensus::NetworkType::Main,
             [9; 20],
         );
-        // Pinned: the app decodes this same pair in JS (sdkZcash/index.test.ts).
+        // Pinned: the app decodes the same pair in JS.
         assert_eq!(tex.encode(), "tex1pyysjzgfpyysjzgfpyysjzgfpyysjzgfl7c006");
         assert_eq!(t1.encode(), "t1JhNuqypTPZu5vdcjsvGHzbTCrTd9Xwtru");
         assert!(recipient_is_tex(¶ms, &tex));
@@ -1255,12 +1215,6 @@ mod combine_tests {
     /// A transparent-only PCZT, io-finalized. `extra` appends a second
     /// input/output pair; the first pair stays byte-identical so the two PCZTs
     /// still merge.
-    ///
-    /// Transparent-only is deliberate. `IoFinalizer` clears the three
-    /// `tx_modifiable` flags ONLY when the transaction has shielded spends or
-    /// outputs (io_finalizer/mod.rs:70), so a transparent-only PCZT stays
-    /// modifiable and the bare Combiner will happily append the other side's
-    /// extra inputs, outputs and Orchard actions.
     fn transparent_pczt(send_zat: u64, recipient: u8, extra: bool) -> Vec {
         let secp = secp256k1::Secp256k1::new();
         let pubkey = secp256k1::PublicKey::from_secret_key(&secp, &secret_key());
@@ -1355,8 +1309,7 @@ mod combine_tests {
         assert_ne!(first.txid(), other.txid());
     }
 
-    // Conflicting values on a field both sides carry: the bare Combiner already
-    // refuses this one. Pinned so a future upstream bump cannot quietly relax it.
+    // The bare Combiner already refuses this; pinned against upstream changes.
     #[test]
     fn combine_rejects_a_conflicting_recipient() {
         let approved = transparent_pczt(90_000, 0xaa, false);
@@ -1369,11 +1322,8 @@ mod combine_tests {
         );
     }
 
-    // What actually stops a counterparty from appending an input, output or
-    // Orchard action: `tx_modifiable` is already 0 on anything our pipeline
-    // builds, and the Combiner refuses to grow a non-modifiable bundle. That is
-    // upstream's behaviour, not ours, so pin it -- the sighash comparison in
-    // `combine_pczt` is what still covers us if a future bump relaxes it.
+    // Upstream behaviour, pinned: the Combiner refuses to grow a non-modifiable
+    // PCZT. The sighash check in `combine_pczt` covers a future relaxation.
     #[test]
     fn our_pczts_are_not_modifiable_so_the_combiner_refuses_to_grow_them() {
         let approved = transparent_pczt(90_000, 0xaa, false);
@@ -1393,8 +1343,7 @@ mod combine_tests {
 
     #[test]
     fn combine_rejects_a_copy_that_already_carries_a_script_sig() {
-        // script_sig is absent from the sighash and absent from our original, so
-        // the bare Combiner would adopt whatever the other side put there.
+        // script_sig is outside the sighash, so the bare Combiner would adopt it.
         let original = transparent_pczt(90_000, 0xaa, false);
         let finalized = SpendFinalizer::new(pczt::Pczt::parse(&signed_copy(&original)).unwrap())
             .finalize_spends()
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs
index cffee92c7..74525f24c 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs
@@ -77,8 +77,7 @@ pub fn storage_stats(conn: &Connection) -> Result {
             "pageSize": page_size,
             "pageCount": page_count,
             "freePages": free_pages,
-            // Logical size only; IndexedDB physical usage differs (write
-            // amplification, stale pages, async flushes).
+            // Logical size only; physical storage usage can differ.
             "logicalBytes": page_size * page_count,
         },
         "scan": {
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
index 4e0edb720..7d0129d7c 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
@@ -1,9 +1,8 @@
 //! Shared SQLite storage for every App carrier.
 //!
 //! WASM runs in a dedicated Worker and uses the same OPFS synchronous-access
-//! VFS on desktop, web, extension, and mobile WebEmbed. SQLite accesses pages
-//! directly instead of preloading a complete IndexedDB mirror into WASM memory.
-//! Native builds remain available for Rust tests and diagnostics.
+//! VFS on desktop, web, extension, and mobile WebEmbed, so SQLite reads pages
+//! on demand. Native builds are for Rust tests and diagnostics.
 
 use crate::error::{ErrorCode, Result, RuntimeError};
 use serde_json::json;
@@ -141,10 +140,9 @@ pub async fn install_persistent_vfs() -> Result<()> {
     Ok(())
 }
 
-/// SQLite COMMIT synchronously calls this VFS's xSync under synchronous=FULL.
-/// There is no asynchronous write queue to drain. Retain the explicit boundary
-/// used by transaction finalization and broadcasting; commit errors propagate
-/// from the SQLite operation before this point.
+/// COMMIT already syncs through the VFS under synchronous=FULL, so there is no
+/// write queue to drain; this only checks the storage is still usable before
+/// finalization and broadcast.
 pub async fn durability_barrier() -> Result<()> {
     if requires_worker_restart() {
         return Err(RuntimeError::with(
@@ -277,8 +275,7 @@ pub async fn database_exists(db_name: &str) -> Result {
     Ok(std::path::Path::new(db_name).exists())
 }
 
-/// Delete a closed database. Callers must first resolve active transactions;
-/// pending broadcast state must not be discarded as rebuildable scan cache.
+/// Delete a closed database.
 #[cfg(target_arch = "wasm32")]
 pub async fn delete_database(db_name: &str) -> Result {
     if memory_mode() {
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
index a5207e4b9..1dc7a381d 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
@@ -7,7 +7,7 @@
 //! - [`prepare`]: one-off setup (subtree roots, chain tip). Slow; once per sync.
 //! - [`step`]: scans at most `max_batches` batches, then returns progress.
 //!
-//! The host decides whether to call again; scheduling belongs to TS.
+//! The host decides whether to call again.
 
 use std::collections::{HashMap, HashSet};
 use std::hash::Hash;
@@ -39,8 +39,7 @@ use crate::wallet::Db;
 /// Pick a range from the upstream suggestions by priority.
 ///
 /// `None` means any, in upstream order (ChainTip before Historic). With a priority,
-/// only that lane is considered; `None` is returned when it is empty rather than
-/// silently scanning another lane, which would desync host progress reporting.
+/// only that lane is considered, so host progress stays attributed to it.
 fn pick_range(suggested: &[ScanRange], preferred: Option) -> Option {
     suggested
         .iter()
@@ -48,7 +47,7 @@ fn pick_range(suggested: &[ScanRange], preferred: Option) -> Optio
         .cloned()
 }
 
-/// Host-selectable priority. Strings, not numbers, so values are checkable across the boundary.
+/// Host-selectable priority, as strings so values are checkable across the boundary.
 pub fn parse_priority(name: &str) -> Result> {
     Ok(match name {
         "" | "any" => None,
@@ -68,8 +67,8 @@ pub fn parse_priority(name: &str) -> Result> {
 
 /// Suggested rewind depth on reorg.
 ///
-/// Deep reorgs are rare on Zcash; too deep forces a long rescan, too shallow may
-/// not pass the fork point. Hosts may increase it on repeated failures.
+/// Too deep forces a long rescan, too shallow may not pass the fork point.
+/// Hosts may increase it on repeated failures.
 const REORG_REWIND_BLOCKS: u32 = 10;
 
 fn net_err(operation: &str, e: impl std::fmt::Display) -> RuntimeError {
@@ -104,9 +103,7 @@ async fn subtree_roots(
 
     let mut roots = Vec::new();
     loop {
-        // This is an inactivity timeout, not a deadline for the whole stream.
-        // A healthy long subtree stream can run for as long as it needs, while
-        // a stalled server still releases the carrier after one item timeout.
+        // Per-item inactivity timeout, not a deadline for the whole stream.
         let next = crate::network::with_timeout(
             async { stream.try_next().await.map_err(|e| net_err(operation, e)) },
             crate::network::DEFAULT_TIMEOUT_MS,
@@ -127,10 +124,7 @@ async fn subtree_roots(
 
 /// One-off setup: load subtree roots for all three pools and update the chain tip.
 ///
-/// The slowest step of a first sync (downloads every subtree root), independent of
-/// `batch_size`; exposed separately so the host can report it as its own phase.
-///
-/// Idempotent, but each call re-downloads everything.
+/// Idempotent, but each call re-downloads every subtree root.
 pub async fn prepare(db: &mut Db, client: &mut LightClient) -> Result {
     let sapling: Vec> = subtree_roots(
         client,
@@ -177,9 +171,8 @@ pub async fn prepare(db: &mut Db, client: &mut LightClient) -> Result {
 
 /// Update only the chain tip, leaving subtree roots untouched.
 ///
-/// Subtree roots change rarely (a new shard every few days) while `prepare`
-/// refetches all ~1900 from index 0 (~7.4s on mainnet). Use `prepare` once after
-/// opening the wallet and this unary call for later syncs.
+/// Subtree roots change rarely; use `prepare` once after opening the wallet and
+/// this unary call for later syncs.
 pub async fn tip(db: &mut Db, client: &mut LightClient) -> Result {
     let tip = crate::network::chain_tip(client).await?;
     db.update_chain_tip(BlockHeight::from_u32(tip))
@@ -227,9 +220,7 @@ pub async fn step(
             .suggest_scan_ranges()
             .map_err(|e| db_err("suggestScanRanges", e))?;
 
-        // The host picks the priority, but candidates come only from upstream
-        // suggestions: scheduling stays with the app, while which ranges are safe
-        // to scan stays with the protocol implementation.
+        // The host picks the priority; candidates come only from upstream suggestions.
         let Some(range) = pick_range(&suggested, preferred) else {
             break; // no pending ranges at this priority
         };
@@ -246,11 +237,8 @@ pub async fn step(
         // Download: on failure retry the same batch once, then halve, down to 32 blocks.
         //
         // In the 2022 spam range (heights ~1.71M-1.95M) a 500-block batch can be
-        // tens of MB and never finishes on slow links under a fixed timeout, on any
-        // server. The successful size is remembered across calls (thread_local
-        // below, session-scoped on single-threaded wasm) and doubled back up after
-        // successes, so the shrink happens once and normal size recovers after the
-        // spam range.
+        // tens of MB and never finish on slow links. The successful size is
+        // remembered across calls and grown back after successes.
         const MIN_DOWNLOAD_BATCH: u32 = 32;
         thread_local! {
             static DOWNLOAD_BATCH_HINT: std::cell::Cell =
@@ -295,9 +283,8 @@ pub async fn step(
                 }
             }
         };
-        // After shrinking, remember the size and reset the streak. Grow one step only
-        // after three consecutive full batches at the remembered size (small tip
-        // batches do not count), so the hint does not oscillate back into timeouts.
+        // Grow one step only after three consecutive full batches at the remembered
+        // size, so the hint does not oscillate back into timeouts.
         if attempt_len < initial_len {
             DOWNLOAD_BATCH_HINT.with(|h| h.set(attempt_len));
             DOWNLOAD_BATCH_STREAK.with(|s| s.set(0));
@@ -320,9 +307,6 @@ pub async fn step(
         let t_downloaded = now_ms();
         ms_download += t_downloaded - t_start;
 
-        // Clamp to Sapling activation: lightwalletd has no treestate before it, and its
-        // error reply hangs the wasm gRPC call forever (see the birthday clamp in
-        // zcashWebSdk.ts).
         let anchor = anchor_height(¶ms, start);
 
         let chain_state = crate::network::with_timeout(
@@ -347,7 +331,7 @@ pub async fn step(
         ms_treestate += t_treestate - t_downloaded;
         trace(&format!("step: scanning {batch_len} blocks"));
 
-        // scan_blocks_inline maps reorgs to REORG_DETECTED by error type (exact atHeight).
+        // Reorgs surface as REORG_DETECTED with an exact atHeight.
         scan_blocks_inline(
             ¶ms,
             &cache,
@@ -368,10 +352,8 @@ pub async fn step(
         batches_done += 1;
     }
 
-    // Compact blocks cannot supply full outgoing amounts, fees or memos.
-    // Bound the optional enrichment work independently of the scan lanes.
-    // The host visits several scan lanes per turn; enrich only on historic
-    // steps, or standalone steps, to keep the network budget bounded.
+    // Compact blocks lack full outgoing amounts, fees and memos. Enrich only on
+    // historic or lane-less steps to keep the per-turn network budget bounded.
     let enhancement = if preferred.is_none() || preferred == Some(ScanPriority::Historic) {
         enhance_transactions(db, client, active_ufvks).await
     } else {
@@ -393,7 +375,7 @@ pub async fn step(
         "blocksScanned": blocks_scanned,
         "remainingBlocks": remaining_blocks,
         "remainingRanges": remaining.len(),
-        // Range and priority actually scanned, so the host attributes progress to the right lane
+        // Range and priority actually scanned, so the host attributes progress to the right lane.
         "scannedFrom": scanned_from,
         "scannedTo": scanned_to,
         "scannedPriority": scanned_priority,
@@ -404,9 +386,8 @@ pub async fn step(
     .to_string())
 }
 
-// Use the official decrypt/store APIs with only explicitly enabled identities.
-// The convenience decrypt_and_store_transaction helper would try every stored
-// UFVK, including accounts whose Privacy Mode has been switched off.
+// Decrypts with active identities only; upstream decrypt_and_store_transaction
+// would try every stored UFVK, including paused accounts.
 
 async fn enhance_transactions(
     db: &mut Db,
@@ -440,8 +421,7 @@ async fn enhance_transactions(
     txids = select_enhancement_requests(db, &keys.keys().copied().collect::>(), txids)?;
     txids.sort_by_key(|(priority, txid)| (*priority, txid.to_string()));
     txids.dedup_by_key(|(_, txid)| *txid);
-    // Advance even after a failed fetch so one missing transaction cannot
-    // permanently starve the rest. This scalar belongs to the runtime instance.
+    // Rotates even after a failed fetch so one missing transaction cannot starve the rest.
     thread_local! { static ENHANCEMENT_CURSOR: std::cell::Cell = const { std::cell::Cell::new(0) }; }
     if !txids.is_empty() {
         let offset = ENHANCEMENT_CURSOR.with(|cursor| {
@@ -541,22 +521,13 @@ fn parse_enhancement(data: &[u8], branch: BranchId, expected: TxId) -> Result  rayon::spawn_fifo(|| task.run())
-/// ```
-///
-/// Its `Tasks for ()` overrides `add_task` but not `run_task`, so tasks still go to
-/// rayon. On single-threaded wasm32 the rayon pool has no workers, and
-/// `BatchReceiver::into_results()` blocks the main thread forever at the first
-/// block with shielded outputs.
-///
-/// `scanning::scan_block` (equivalent to `runners = None`) decrypts inline without
-/// rayon, at the cost of batched-inversion amortization and without forking upstream.
+/// `scan_cached_blocks` hands trial decryption to rayon (`Tasks for ()` does not
+/// override `run_task`). On single-threaded wasm32 the pool has no workers, so
+/// `BatchReceiver::into_results()` blocks forever at the first block with shielded
+/// outputs. `scanning::scan_block` decrypts inline without forking upstream.
 fn scan_blocks_inline(
     params: &zcash_protocol::consensus::Network,
     cache: &MemoryBlockCache,
@@ -589,9 +560,7 @@ where
             Ok(())
         })
         .map_err(|e| match &e {
-            // Reorg: classify by the typed upstream predicate (same as the reference
-            // loop) while the error is still typed; string matching can silently
-            // miss it. This also gives an exact at_height.
+            // Classify reorgs by the typed upstream predicate while the error is still typed.
             ChainError::Scan(scan_err) if scan_err.is_continuity_error() => {
                 let at = u32::from(scan_err.at_height());
                 RuntimeError::with(
@@ -613,9 +582,8 @@ where
 
 /// Selects the host-authorized UFVKs and removes every non-Orchard component before scanning.
 ///
-/// `ScanningKeys::from_account_ufvks` normally creates Sapling, Orchard, and Ironwood keys. The
-/// runtime intentionally supplies an ephemeral Orchard-only UFVK instead, so the official
-/// scanner still maintains all required trees while Sapling ownership discovery remains disabled.
+/// An Orchard-only UFVK still yields Orchard and Ironwood scanning keys, so the official
+/// scanner maintains all trees while Sapling ownership discovery stays disabled.
 fn select_active_scanning_ufvks(
     params: &zcash_protocol::consensus::Network,
     wallet_ufvks: HashMap,
@@ -693,7 +661,6 @@ pub fn account_status(db: &Db, account_uuid: &str) -> Result {
         .suggest_scan_ranges()
         .map_err(|e| db_err("suggestScanRanges", e))?;
 
-    // Count only the part relevant to this account
     let mut remaining: u64 = 0;
     let mut lowest_pending: Option = None;
     for r in &ranges {
@@ -725,8 +692,6 @@ pub fn account_status(db: &Db, account_uuid: &str) -> Result {
 }
 
 /// Read-only: the ranges the wallet currently suggests scanning. No network requests.
-///
-/// For host progress bars and for inspecting what a stuck sync is trying to scan.
 pub fn peek(db: &Db) -> Result {
     let ranges = db
         .suggest_scan_ranges()
@@ -751,7 +716,7 @@ pub fn peek(db: &Db) -> Result {
 /// Diagnostic probe: download only, no scan, no writes. Returns per-phase timings.
 ///
 /// Separates a slow or hung network from a slow or hung scan, which look the same
-/// in the browser. Also usable as a network health check; no wallet state changes.
+/// in the browser.
 pub async fn probe_download(db: &Db, client: &mut LightClient, batch_size: u32) -> Result {
     let t0 = now_ms();
 
@@ -852,8 +817,7 @@ fn anchor_height(params: &zcash_protocol::consensus::Network, start: BlockHeight
 }
 
 /// Soft download budget. Past it, scan the contiguous prefix received so far
-/// instead of waiting for the rest; only a stall is fatal. A large but progressing
-/// batch (500 spam-range blocks, tens of MB) is not killed and refetched.
+/// instead of waiting for the rest; only a stall is fatal.
 const DOWNLOAD_SOFT_BUDGET_MS: f64 = 30_000.0;
 
 /// Stream a block range into the cache; returns the number of blocks stored
@@ -978,10 +942,9 @@ pub fn rewind_to(db: &mut Db, height: u32) -> Result {
 
 /// Re-queues an inclusive block range without truncating cached wallet state.
 ///
-/// The host uses this when a previously inactive UFVK becomes active again. Because the upstream
-/// scan queue is shared by the whole network database, other active identities may have advanced
-/// it while this identity was paused. The host owns the pause cursor and passes the first height
-/// that must be trial-decrypted again. A small reorg safety margin should be applied by the host.
+/// Used when a paused UFVK becomes active again: the shared scan queue may have advanced
+/// past its pause point. The host passes the first height to trial-decrypt again, with a
+/// reorg margin applied.
 pub fn queue_rescan_from(db: &mut Db, from_height: u32) -> Result {
     let Some(tip) = db
         .chain_height()
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs b/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs
index 5bda99a23..9a57f46f5 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs
@@ -60,8 +60,8 @@ async fn scan_batch_10() {
     scan_with_batch(10).await;
 }
 
-/// Hung in the browser. A native hang points at upstream scanning; a pass
-/// points at wasm or the storage layer.
+/// A native hang points at upstream scanning; a pass points at wasm or the
+/// storage layer.
 #[tokio::test(flavor = "multi_thread")]
 #[ignore = "requires network"]
 async fn scan_batch_25() {
@@ -158,7 +158,7 @@ async fn scan_batch_curve() {
     }
 }
 
-/// Mirrors the browser `bisect.html`: advances one block at a time, 40 times.
+/// Advances one block at a time, 40 times.
 /// A native stall points at block content; a full run points at wasm.
 #[tokio::test(flavor = "multi_thread")]
 #[ignore = "requires network"]

From bb0984086a8c753b8712d9a5f2d4b52574bd0cad Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 12:05:59 +0800
Subject: [PATCH 63/97] fix: truncate deleted runtime files and refuse newer
 zcash databases

Freeing an OPFS slot cleared only its header, so a dropped wallet database
or a deleted rollback journal kept its plaintext until the slot was reused.
The slot is now truncated after the durable header clear, and free slots are
swept when the pool opens; both are best effort and never fail the delete
or the open. Zcash now refuses a database with migrations it does not know
(DATABASE_TOO_NEW) instead of silently opening it.
---
 chain-runtimes/zcash/README.md                |   6 +-
 .../zcash/crates/zcash-runtime/src/error.rs   |   5 +
 .../zcash/crates/zcash-runtime/src/wallet.rs  | 157 +++++++++++++++++-
 ...qlite-wasm-vfs-0.2.0-opfs-durability.patch |  53 ++++--
 4 files changed, 196 insertions(+), 25 deletions(-)

diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md
index 220734e0d..0811a97e2 100644
--- a/chain-runtimes/zcash/README.md
+++ b/chain-runtimes/zcash/README.md
@@ -172,11 +172,15 @@ use the stateless API in
   changes. The precompiled wasm SQLite is linked by `crates/zcash-runtime/build.rs`.
 - **Storage is OPFS** (SAH pool in `.onekey-zcash-opfs`, `zcash-main.db` /
   `zcash-test.db`), with `journal_mode=DELETE`, `synchronous=FULL` and
-  `secure_delete=ON`. One Worker
+  `secure_delete=ON`. Deleting a database or journal truncates its pool file to
+  the 4 KiB header once the header clear is flushed; opening the pool truncates
+  any free file that still holds data. One Worker
   owns each origin's pool. OPFS is per-origin and subject to quota and eviction, so
   the embedding page's origin must be stable. When `storageRequiresWorkerRestart()`
   is true after an I/O failure, keep the failed call's result and restart the
   Worker. No SharedArrayBuffer or COOP/COEP is needed.
+- `openWallet()` fails with `DATABASE_TOO_NEW` when a newer runtime migrated the
+  database. It is not corruption: keep the database and update the runtime.
 - `syncPrepare()` downloads every pool's subtree roots (many on mainnet); give it its
   own "preparing" state.
 - Sapling is out of scope: not a receiver, scan identity or send source.
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
index 4535ef8cc..15f41a432 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
@@ -81,6 +81,9 @@ pub enum ErrorCode {
     NetworkError,
     /// Wallet database error (including schema migration failure). Params: `{ operation }`
     DatabaseError,
+    /// The database was migrated by a newer runtime; no migration was applied.
+    /// Not corruption: do not delete it, update the runtime. Params: `{ unknownMigrations }`
+    DatabaseTooNew,
     /// Chain reorg detected. Params: `{ atHeight, suggestedRewindHeight }`
     ///
     /// A normal event, not a failure: blocks near the tip were replaced. The host
@@ -150,6 +153,7 @@ impl ErrorCode {
             InsufficientFunds => "INSUFFICIENT_FUNDS",
             NetworkError => "NETWORK_ERROR",
             DatabaseError => "DATABASE_ERROR",
+            DatabaseTooNew => "DATABASE_TOO_NEW",
             ReorgDetected => "REORG_DETECTED",
             WalletBusy => "WALLET_BUSY",
             InvalidScanPriority => "INVALID_SCAN_PRIORITY",
@@ -303,6 +307,7 @@ mod tests {
             InsufficientFunds,
             NetworkError,
             DatabaseError,
+            DatabaseTooNew,
             InvalidTxid,
             PcztError,
             TransactionBuildError,
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
index 6d12b5c51..5c2535ec9 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
@@ -3,8 +3,11 @@
 //! Connects storage, builds the `WalletDb` and runs schema migrations. All
 //! wallet protocol logic comes from `zcash_client_sqlite` / `zcash_client_backend`.
 
+use std::collections::{BTreeSet, HashSet};
+
 use rand::SeedableRng;
 use rand_chacha::ChaCha20Rng;
+use uuid::Uuid;
 use zcash_client_sqlite::{wallet::init::WalletMigrator, WalletDb};
 use zcash_protocol::consensus::Network;
 
@@ -33,6 +36,7 @@ pub fn parse_network(s: &str) -> Result {
 pub fn open_and_migrate(network: &str, db_name: &str) -> Result {
     let params = parse_network(network)?;
     let conn = storage::open_connection(db_name)?;
+    reject_newer_schema(&conn, params)?;
 
     // Used only for non-key purposes inside the library (migration ids, nonces).
     // No key material passes through it or through this crate.
@@ -40,17 +44,104 @@ pub fn open_and_migrate(network: &str, db_name: &str) -> Result {
 
     let mut db = WalletDb::from_connection(conn, params, HostClock, rng);
 
-    WalletMigrator::new()
-        .with_external_migrations(crate::tx_state::migrations())
-        .init_or_migrate(&mut db)
-        .map_err(|e| {
-            RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": "migrate" }))
-                .detail(format!("{e:?}"))
-        })?;
+    migrator().init_or_migrate(&mut db).map_err(|e| {
+        RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": "migrate" }))
+            .detail(format!("{e:?}"))
+    })?;
 
     Ok(db)
 }
 
+fn migrator() -> WalletMigrator {
+    WalletMigrator::new().with_external_migrations(crate::tx_state::migrations())
+}
+
+/// Refuses a database migrated by a newer runtime. Upstream migration skips
+/// unknown applied migrations, so an older runtime would run on a schema it
+/// does not understand. No migration runs against it.
+fn reject_newer_schema(conn: &rusqlite::Connection, params: Network) -> Result<()> {
+    let applied = applied_migrations(conn)?;
+    if applied.is_empty() {
+        return Ok(());
+    }
+    let known = known_migrations(params)?;
+    let unknown: BTreeSet = applied.difference(&known).map(Uuid::to_string).collect();
+    if unknown.is_empty() {
+        return Ok(());
+    }
+    Err(RuntimeError::with(
+        ErrorCode::DatabaseTooNew,
+        json!({ "unknownMigrations": unknown.len() }),
+    )
+    .detail(unknown.into_iter().collect::>().join(",")))
+}
+
+/// Migration ids recorded in a database; empty before its first migration.
+fn applied_migrations(conn: &rusqlite::Connection) -> Result> {
+    let tracked: bool = conn
+        .query_row(
+            "SELECT EXISTS (SELECT 1 FROM sqlite_master \
+             WHERE type = 'table' AND name = 'schemer_migrations')",
+            [],
+            |r| r.get(0),
+        )
+        .map_err(schema_read_err)?;
+    if !tracked {
+        return Ok(HashSet::new());
+    }
+    let mut stmt = conn
+        .prepare("SELECT id FROM schemer_migrations")
+        .map_err(schema_read_err)?;
+    let ids = stmt
+        .query_map([], |r| r.get::<_, Vec>(0))
+        .map_err(schema_read_err)?;
+    let mut applied = HashSet::new();
+    for id in ids {
+        let id = id.map_err(schema_read_err)?;
+        applied.insert(Uuid::from_slice(&id).map_err(schema_read_err)?);
+    }
+    Ok(applied)
+}
+
+fn schema_read_err(e: impl std::fmt::Display) -> RuntimeError {
+    RuntimeError::with(
+        ErrorCode::DatabaseError,
+        json!({ "operation": "readSchemaVersion" }),
+    )
+    .detail(e)
+}
+
+/// Every migration this runtime knows, read back from a fresh in-memory
+/// migration once per thread (upstream does not expose the full list).
+fn known_migrations(params: Network) -> Result> {
+    thread_local! {
+        static KNOWN: std::cell::RefCell>> =
+            const { std::cell::RefCell::new(None) };
+    }
+    if let Some(known) = KNOWN.with(|k| k.borrow().clone()) {
+        return Ok(known);
+    }
+    let reference_err = |detail: String| {
+        RuntimeError::with(
+            ErrorCode::DatabaseError,
+            json!({ "operation": "knownMigrations" }),
+        )
+        .detail(detail)
+    };
+    let mut conn =
+        rusqlite::Connection::open_in_memory().map_err(|e| reference_err(e.to_string()))?;
+    {
+        let rng = ChaCha20Rng::from_seed(random_seed()?);
+        let mut db = WalletDb::from_connection(&mut conn, params, HostClock, rng);
+        migrator()
+            .init_or_migrate(&mut db)
+            .map_err(|e| reference_err(format!("{e:?}")))?;
+    }
+    let known = applied_migrations(&conn)?;
+    KNOWN.with(|k| *k.borrow_mut() = Some(known.clone()));
+    Ok(known)
+}
+
 /// 32-byte random seed; on wasm this uses the host's crypto.getRandomValues.
 fn random_seed() -> Result<[u8; 32]> {
     let mut seed = [0u8; 32];
@@ -83,6 +174,58 @@ mod tests {
         assert_ne!(s, [0u8; 32]);
     }
 
+    #[test]
+    fn refuses_a_database_migrated_by_a_newer_runtime() {
+        let path = std::env::temp_dir().join("zr-newer-schema.sqlite");
+        let _ = std::fs::remove_file(&path);
+        let name = path.to_str().unwrap();
+        drop(open_and_migrate("test", name).expect("create"));
+        drop(open_and_migrate("test", name).expect("reopen a current database"));
+
+        let schema = |conn: &rusqlite::Connection| {
+            let mut stmt = conn
+                .prepare("SELECT sql FROM sqlite_master ORDER BY name")
+                .unwrap();
+            let sql: Vec> = stmt
+                .query_map([], |r| r.get(0))
+                .unwrap()
+                .map(|r| r.unwrap())
+                .collect();
+            (applied_migrations(conn).unwrap(), sql)
+        };
+        let newer = Uuid::from_u128(0x7e57_0000_0000_4000_8000_0000_0000_0001);
+        let conn = rusqlite::Connection::open(&path).unwrap();
+        conn.execute(
+            "INSERT INTO schemer_migrations (id) VALUES (?1)",
+            [&newer.as_bytes()[..]],
+        )
+        .unwrap();
+        let before = schema(&conn);
+        drop(conn);
+
+        let error = open_and_migrate("test", name).err().expect("refused");
+        assert_eq!(error.code, ErrorCode::DatabaseTooNew);
+        assert_eq!(error.params["unknownMigrations"], 1);
+        assert_eq!(error.detail.as_deref(), Some(newer.to_string().as_str()));
+        // No migration ran against the newer schema.
+        let conn = rusqlite::Connection::open(&path).unwrap();
+        assert_eq!(schema(&conn), before);
+        drop(conn);
+        let _ = std::fs::remove_file(&path);
+    }
+
+    #[test]
+    fn known_migrations_match_a_fresh_database() {
+        let path = std::env::temp_dir().join("zr-known-migrations.sqlite");
+        let _ = std::fs::remove_file(&path);
+        drop(open_and_migrate("main", path.to_str().unwrap()).expect("create"));
+        let conn = rusqlite::Connection::open(&path).unwrap();
+        let applied = applied_migrations(&conn).unwrap();
+        assert!(!applied.is_empty());
+        assert_eq!(known_migrations(Network::MainNetwork).unwrap(), applied);
+        let _ = std::fs::remove_file(&path);
+    }
+
     /// Prints the migrated schema. `storageStats` SQL must follow it: a wrong
     /// table name silently returns 0 instead of failing. Runs only with
     /// `ZR_DUMP_SCHEMA=1`.
diff --git a/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch b/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch
index 8cf700deb..b34a32041 100644
--- a/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch
+++ b/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch
@@ -318,7 +318,7 @@
          self.header_buffer_view
              .set_uint32(HEADER_OFFSET_FLAGS, flags as u32);
  
-@@ -285,19 +485,43 @@
+@@ -285,19 +485,57 @@
          } else {
              self.header_buffer
                  .fill(0, 0, HEADER_MAX_FILENAME_SIZE as u32);
@@ -356,6 +356,20 @@
 +            self.poisoned.set(true);
 +        }
 +        result
++    }
++
++    /// Best-effort truncate of a free file's old payload (a dropped database
++    /// or journal). Call only after its association clear is durable. On
++    /// failure the payload stays until the next pool open retries.
++    fn discard_payload(sah: &FileSystemSyncAccessHandle) {
++        let Ok(size) = sah.get_size() else {
++            return;
++        };
++        if size > HEADER_OFFSET_DATA as f64
++            && sah.truncate_with_u32(HEADER_OFFSET_DATA as u32).is_ok()
++        {
++            let _ = sah.flush();
++        }
      }
  
      async fn acquire_access_handles(&self, clear_files: bool) -> Result<()> {
@@ -371,14 +385,17 @@
              let next: IteratorNext = JsFuture::from(future)
                  .await
                  .map_err(OpfsSAHError::IterHandle)?
-@@ -324,45 +548,42 @@
+@@ -324,45 +562,47 @@
                      handle: sah,
                      opaque,
                  };
 -                let clear_file = |file: SyncAccessFile| -> Result<()> {
++                // Also removes payloads left by older builds or by a crash
++                // between a delete's header clear and its truncate.
 +                let mut clear_file = |file: SyncAccessFile| -> Result<()> {
                      self.set_associated_filename(&file.handle, None, 0)?;
 -                    self.available_files.borrow_mut().push(file);
++                    Self::discard_payload(&file.handle);
 +                    available_files.push(file);
                      Ok(())
                  };
@@ -428,11 +445,13 @@
 +        if let Some(file) = map_filename_to_file.get(filename) {
              self.set_associated_filename(&file.handle, None, 0)?;
 +            let file = map_filename_to_file.remove(filename).unwrap();
++            // The delete is already durable; never fail it over the payload.
++            Self::discard_payload(&file.handle);
 +            self.available_files.borrow_mut().push(file);
              Ok(true)
          } else {
              Ok(false)
-@@ -398,6 +619,7 @@
+@@ -398,6 +638,7 @@
          flags: i32,
          f: F,
      ) -> Result> {
@@ -440,7 +459,7 @@
          let mut map_filename_to_file = self.map_filename_to_file.borrow_mut();
          let mut available_files = self.available_files.borrow_mut();
          if map_filename_to_file.contains_key(filename) {
-@@ -408,13 +630,10 @@
+@@ -408,13 +649,10 @@
          let file = available_files
              .pop()
              .ok_or_else(|| OpfsSAHError::Generic("No files available in the pool".into()))?;
@@ -457,7 +476,7 @@
      }
  
      fn pause_vfs(&self) -> Result<()> {
-@@ -442,11 +661,10 @@
+@@ -442,11 +680,10 @@
      }
  
      async fn unpause_vfs(&self) -> Result<()> {
@@ -470,7 +489,7 @@
  
          let (vfs, make_default) = self.vfs.get();
          if vfs.is_null() {
-@@ -455,18 +673,24 @@
+@@ -455,18 +692,24 @@
              ));
          }
  
@@ -498,7 +517,7 @@
          let files = self.map_filename_to_file.borrow();
          let file = files
              .get(filename)
-@@ -603,6 +827,8 @@
+@@ -603,6 +846,8 @@
  
      fn contains_file(vfs: *mut sqlite3_vfs, file: &str) -> VfsResult {
          let pool = unsafe { Self::app_data(vfs) };
@@ -507,7 +526,7 @@
          Ok(pool.has_filename(file))
      }
  
-@@ -619,6 +845,8 @@
+@@ -619,6 +864,8 @@
      ) -> VfsResult {
          let name = unsafe { vfs_file.name() };
          let pool = unsafe { Self::app_data(vfs_file.vfs) };
@@ -516,7 +535,7 @@
          pool.with_file(name, f)
              .ok_or_else(|| VfsError::new(SQLITE_IOERR, format!("{name} not found")))?
      }
-@@ -629,6 +857,8 @@
+@@ -629,6 +876,8 @@
      ) -> VfsResult {
          let name = unsafe { vfs_file.name() };
          let pool = unsafe { Self::app_data(vfs_file.vfs) };
@@ -525,7 +544,7 @@
          pool.with_file_mut(name, f)
              .ok_or_else(|| VfsError::new(SQLITE_IOERR, format!("{name} not found")))?
      }
-@@ -648,11 +878,66 @@
+@@ -648,11 +897,66 @@
      }
  
      unsafe extern "C" fn xCheckReservedLock(
@@ -595,7 +614,7 @@
      }
  
      unsafe extern "C" fn xDeviceCharacteristics(
-@@ -663,14 +948,18 @@
+@@ -663,14 +967,18 @@
  
      unsafe extern "C" fn xClose(pFile: *mut sqlite3_file) -> ::std::os::raw::c_int {
          let vfs_file = SQLiteVfsFile::from_file(pFile);
@@ -621,7 +640,7 @@
          ret
      }
  }
-@@ -691,6 +980,10 @@
+@@ -691,6 +999,10 @@
          flags: ::std::os::raw::c_int,
          pOutFlags: *mut ::std::os::raw::c_int,
      ) -> ::std::os::raw::c_int {
@@ -632,7 +651,7 @@
          let ret = Self::xOpenImpl(pVfs, zName, pFile, flags, pOutFlags);
          if ret == SQLITE_OK {
              let app_data = SyncAccessHandleStore::app_data(pVfs);
-@@ -700,7 +993,7 @@
+@@ -700,7 +1012,7 @@
              app_data
                  .open_files
                  .borrow_mut()
@@ -641,7 +660,7 @@
          }
          ret
      }
-@@ -841,6 +1134,11 @@
+@@ -841,6 +1153,11 @@
  }
  
  impl OpfsSAHPoolUtil {
@@ -653,7 +672,7 @@
      /// Returns the number of files currently contained in the SAH pool.
      pub fn get_capacity(&self) -> u32 {
          self.pool.get_capacity()
-@@ -894,6 +1192,7 @@
+@@ -894,6 +1211,7 @@
  
      /// Delete all database, make sure that all database is closed.
      pub async fn clear_all(&self) -> Result<()> {
@@ -661,7 +680,7 @@
          self.pool.release_access_handles();
          self.pool.acquire_access_handles(true).await?;
          Ok(())
-@@ -901,6 +1200,7 @@
+@@ -901,6 +1219,7 @@
  
      /// Does the database exists.
      pub fn exists(&self, filename: &str) -> Result {
@@ -669,7 +688,7 @@
          Ok(self.pool.has_filename(filename))
      }
  
-@@ -971,6 +1271,7 @@
+@@ -971,6 +1290,7 @@
      };
  
      let pool = unsafe { SyncAccessHandleStore::app_data(vfs) };

From df9007fff4655d6d08f4d017a2333c2372c7bd41 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 12:06:00 +0800
Subject: [PATCH 64/97] chore: bump privacy runtimes to 0.1.0-alpha.6

---
 chain-runtimes/monero/Cargo.lock | 2 +-
 chain-runtimes/monero/Cargo.toml | 2 +-
 chain-runtimes/zcash/Cargo.lock  | 6 +++---
 chain-runtimes/zcash/Cargo.toml  | 2 +-
 4 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock
index 3605ea9ec..6de21098a 100644
--- a/chain-runtimes/monero/Cargo.lock
+++ b/chain-runtimes/monero/Cargo.lock
@@ -1259,7 +1259,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-monero-runtime"
-version = "0.1.0-alpha.5"
+version = "0.1.0-alpha.6"
 dependencies = [
  "curve25519-dalek",
  "futures-lite",
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index d8a76f858..1fd31ad54 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/monero-runtime"]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.5"
+version = "0.1.0-alpha.6"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index 9e32409b1..844c76343 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1655,7 +1655,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-zcash-keys"
-version = "0.1.0-alpha.5"
+version = "0.1.0-alpha.6"
 dependencies = [
  "bip0039",
  "bip32",
@@ -1687,7 +1687,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-runtime"
-version = "0.1.0-alpha.5"
+version = "0.1.0-alpha.6"
 dependencies = [
  "blake2b_simd",
  "console_error_panic_hook",
@@ -1736,7 +1736,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-storage-benchmark"
-version = "0.1.0-alpha.5"
+version = "0.1.0-alpha.6"
 dependencies = [
  "console_error_panic_hook",
  "js-sys",
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index 259827e78..b78d66407 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -8,7 +8,7 @@ members = [
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.5"
+version = "0.1.0-alpha.6"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"

From 92bdee1812824367ddbf357188d68770b8af694b Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 14:16:20 +0800
Subject: [PATCH 65/97] perf: skip the flush after truncating a freed runtime
 file

---
 ...qlite-wasm-vfs-0.2.0-opfs-durability.patch | 44 +++++++++----------
 1 file changed, 21 insertions(+), 23 deletions(-)

diff --git a/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch b/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch
index b34a32041..71776fce5 100644
--- a/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch
+++ b/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch
@@ -318,7 +318,7 @@
          self.header_buffer_view
              .set_uint32(HEADER_OFFSET_FLAGS, flags as u32);
  
-@@ -285,19 +485,57 @@
+@@ -285,19 +485,55 @@
          } else {
              self.header_buffer
                  .fill(0, 0, HEADER_MAX_FILENAME_SIZE as u32);
@@ -359,16 +359,14 @@
 +    }
 +
 +    /// Best-effort truncate of a free file's old payload (a dropped database
-+    /// or journal). Call only after its association clear is durable. On
-+    /// failure the payload stays until the next pool open retries.
++    /// or journal). Call only after its association clear is durable. Not
++    /// flushed: the next pool open retries a failed or lost truncate.
 +    fn discard_payload(sah: &FileSystemSyncAccessHandle) {
 +        let Ok(size) = sah.get_size() else {
 +            return;
 +        };
-+        if size > HEADER_OFFSET_DATA as f64
-+            && sah.truncate_with_u32(HEADER_OFFSET_DATA as u32).is_ok()
-+        {
-+            let _ = sah.flush();
++        if size > HEADER_OFFSET_DATA as f64 {
++            let _ = sah.truncate_with_u32(HEADER_OFFSET_DATA as u32);
 +        }
      }
  
@@ -385,7 +383,7 @@
              let next: IteratorNext = JsFuture::from(future)
                  .await
                  .map_err(OpfsSAHError::IterHandle)?
-@@ -324,45 +562,47 @@
+@@ -324,45 +560,47 @@
                      handle: sah,
                      opaque,
                  };
@@ -451,7 +449,7 @@
              Ok(true)
          } else {
              Ok(false)
-@@ -398,6 +638,7 @@
+@@ -398,6 +636,7 @@
          flags: i32,
          f: F,
      ) -> Result> {
@@ -459,7 +457,7 @@
          let mut map_filename_to_file = self.map_filename_to_file.borrow_mut();
          let mut available_files = self.available_files.borrow_mut();
          if map_filename_to_file.contains_key(filename) {
-@@ -408,13 +649,10 @@
+@@ -408,13 +647,10 @@
          let file = available_files
              .pop()
              .ok_or_else(|| OpfsSAHError::Generic("No files available in the pool".into()))?;
@@ -476,7 +474,7 @@
      }
  
      fn pause_vfs(&self) -> Result<()> {
-@@ -442,11 +680,10 @@
+@@ -442,11 +678,10 @@
      }
  
      async fn unpause_vfs(&self) -> Result<()> {
@@ -489,7 +487,7 @@
  
          let (vfs, make_default) = self.vfs.get();
          if vfs.is_null() {
-@@ -455,18 +692,24 @@
+@@ -455,18 +690,24 @@
              ));
          }
  
@@ -517,7 +515,7 @@
          let files = self.map_filename_to_file.borrow();
          let file = files
              .get(filename)
-@@ -603,6 +846,8 @@
+@@ -603,6 +844,8 @@
  
      fn contains_file(vfs: *mut sqlite3_vfs, file: &str) -> VfsResult {
          let pool = unsafe { Self::app_data(vfs) };
@@ -526,7 +524,7 @@
          Ok(pool.has_filename(file))
      }
  
-@@ -619,6 +864,8 @@
+@@ -619,6 +862,8 @@
      ) -> VfsResult {
          let name = unsafe { vfs_file.name() };
          let pool = unsafe { Self::app_data(vfs_file.vfs) };
@@ -535,7 +533,7 @@
          pool.with_file(name, f)
              .ok_or_else(|| VfsError::new(SQLITE_IOERR, format!("{name} not found")))?
      }
-@@ -629,6 +876,8 @@
+@@ -629,6 +874,8 @@
      ) -> VfsResult {
          let name = unsafe { vfs_file.name() };
          let pool = unsafe { Self::app_data(vfs_file.vfs) };
@@ -544,7 +542,7 @@
          pool.with_file_mut(name, f)
              .ok_or_else(|| VfsError::new(SQLITE_IOERR, format!("{name} not found")))?
      }
-@@ -648,11 +897,66 @@
+@@ -648,11 +895,66 @@
      }
  
      unsafe extern "C" fn xCheckReservedLock(
@@ -614,7 +612,7 @@
      }
  
      unsafe extern "C" fn xDeviceCharacteristics(
-@@ -663,14 +967,18 @@
+@@ -663,14 +965,18 @@
  
      unsafe extern "C" fn xClose(pFile: *mut sqlite3_file) -> ::std::os::raw::c_int {
          let vfs_file = SQLiteVfsFile::from_file(pFile);
@@ -640,7 +638,7 @@
          ret
      }
  }
-@@ -691,6 +999,10 @@
+@@ -691,6 +997,10 @@
          flags: ::std::os::raw::c_int,
          pOutFlags: *mut ::std::os::raw::c_int,
      ) -> ::std::os::raw::c_int {
@@ -651,7 +649,7 @@
          let ret = Self::xOpenImpl(pVfs, zName, pFile, flags, pOutFlags);
          if ret == SQLITE_OK {
              let app_data = SyncAccessHandleStore::app_data(pVfs);
-@@ -700,7 +1012,7 @@
+@@ -700,7 +1010,7 @@
              app_data
                  .open_files
                  .borrow_mut()
@@ -660,7 +658,7 @@
          }
          ret
      }
-@@ -841,6 +1153,11 @@
+@@ -841,6 +1151,11 @@
  }
  
  impl OpfsSAHPoolUtil {
@@ -672,7 +670,7 @@
      /// Returns the number of files currently contained in the SAH pool.
      pub fn get_capacity(&self) -> u32 {
          self.pool.get_capacity()
-@@ -894,6 +1211,7 @@
+@@ -894,6 +1209,7 @@
  
      /// Delete all database, make sure that all database is closed.
      pub async fn clear_all(&self) -> Result<()> {
@@ -680,7 +678,7 @@
          self.pool.release_access_handles();
          self.pool.acquire_access_handles(true).await?;
          Ok(())
-@@ -901,6 +1219,7 @@
+@@ -901,6 +1217,7 @@
  
      /// Does the database exists.
      pub fn exists(&self, filename: &str) -> Result {
@@ -688,7 +686,7 @@
          Ok(self.pool.has_filename(filename))
      }
  
-@@ -971,6 +1290,7 @@
+@@ -971,6 +1288,7 @@
      };
  
      let pool = unsafe { SyncAccessHandleStore::app_data(vfs) };

From ca04fcee7e2400c9538b43b569034d57d2ad095b Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 21:41:58 +0800
Subject: [PATCH 66/97] feat: report zcash dust change beside the account
 balance

Upstream's Balance::total leaves out notes worth no more than the ZIP-317
marginal fee, so a 5000-zat change note made the balance look short. Each
pool and the account now report that value as uneconomic, without changing
what total and spendable mean.
---
 chain-runtimes/zcash/README.md                |   5 +
 .../zcash/crates/zcash-runtime/src/account.rs | 142 ++++++++++++++++--
 2 files changed, 135 insertions(+), 12 deletions(-)

diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md
index 0811a97e2..e91855073 100644
--- a/chain-runtimes/zcash/README.md
+++ b/chain-runtimes/zcash/README.md
@@ -67,6 +67,11 @@ removeAccount(uuid)                     pending transactions do not block remova
 removeDeletedAccount(uuid)              compatibility alias for removeAccount
 accountByUfvk(ufvk) / listAccounts() / accountSyncStatus(uuid)
 accountBalance(uuid, trusted, untrusted, allowZeroConfShielding)
+                                         per pool: spendable, pendingChange,
+                                         pendingSpendable, locked, total,
+                                         uneconomic; total leaves out notes
+                                         worth <= the ZIP-317 marginal fee,
+                                         which are uneconomic instead
 
 syncPrepare() / syncTip() / syncPeek()   prepare (subtree roots + tip), read-only progress
 syncStep(batchSize, maxBatches, priority, activeUfvksJson)
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
index 8475256ea..e43e0ea3e 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
@@ -3,7 +3,8 @@
 
 use zcash_client_backend::data_api::wallet::ConfirmationsPolicy;
 use zcash_client_backend::data_api::{
-    Account as _, AccountBirthday, AccountPurpose, WalletRead, WalletWrite, Zip32Derivation,
+    Account as _, AccountBalance, AccountBirthday, AccountPurpose, Balance, WalletRead,
+    WalletWrite, Zip32Derivation,
 };
 use zcash_keys::keys::UnifiedFullViewingKey;
 
@@ -117,10 +118,27 @@ pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) ->
         )
     })?;
 
-    // Each pool reports all five values with no cross-pool merging: which pools
+    Ok(balance_value(
+        u32::from(summary.chain_tip_height()),
+        u32::from(summary.fully_scanned_height()),
+        balances,
+    )
+    .to_string())
+}
+
+/// `total` (per pool and overall) is upstream's `Balance::total`, which leaves
+/// out notes worth at most the ZIP-317 marginal fee. That value is reported
+/// beside it as `uneconomic`, so a host can show it without changing what
+/// `total` or `spendable` mean.
+fn balance_value(
+    chain_tip: u32,
+    fully_scanned_height: u32,
+    balances: &AccountBalance,
+) -> serde_json::Value {
+    // Each pool reports its values with no cross-pool merging: which pools
     // count as spendable is wallet policy, not chain fact, and per-pool detail is
     // shown in the UI. The host computes any totals it needs.
-    let pool = |b: &zcash_client_backend::data_api::Balance| {
+    let pool = |b: &Balance| {
         serde_json::json!({
             "spendable": u64::from(b.spendable_value()),
             "pendingChange": u64::from(b.change_pending_confirmation()),
@@ -128,23 +146,31 @@ pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) ->
             // Held by an unexpired upstream output lock; this runtime's sends take none.
             "locked": u64::from(b.locked_value()),
             "total": u64::from(b.total()),
+            // Unspent notes worth <= the marginal fee, confirmed or not. Upstream
+            // note selection skips them, so they are never part of `spendable`.
+            "uneconomic": u64::from(b.uneconomic_value()),
         })
     };
 
-    let supported_total = [
+    let supported = [
         balances.orchard_balance(),
         balances.ironwood_balance(),
         balances.unshielded_regular_balance(),
         balances.unshielded_coinbase_balance(),
-    ]
-    .into_iter()
-    .map(|balance| u64::from(balance.total()))
-    .sum::();
+    ];
+    let supported_total = supported
+        .iter()
+        .map(|balance| u64::from(balance.total()))
+        .sum::();
+    let supported_uneconomic = supported
+        .iter()
+        .map(|balance| u64::from(balance.uneconomic_value()))
+        .sum::();
 
-    Ok(serde_json::json!({
+    serde_json::json!({
         "ready": true,
-        "chainTip": u32::from(summary.chain_tip_height()),
-        "fullyScannedHeight": u32::from(summary.fully_scanned_height()),
+        "chainTip": chain_tip,
+        "fullyScannedHeight": fully_scanned_height,
 
         "orchard": pool(balances.orchard_balance()),
         "ironwood": pool(balances.ironwood_balance()),
@@ -156,8 +182,8 @@ pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) ->
 
         // Sapling is intentionally excluded from both the pool list and the product total.
         "total": supported_total,
+        "uneconomic": supported_uneconomic,
     })
-    .to_string())
 }
 
 /// Removes one account from the shared database. Deleting the database would
@@ -325,3 +351,95 @@ mod birthday_tests {
         check_birthday_tree_state(&state("test", 10), 10, &Network::TestNetwork).unwrap();
     }
 }
+
+#[cfg(test)]
+mod balance_tests {
+    use super::balance_value;
+    use zcash_client_backend::data_api::{AccountBalance, Balance};
+    use zcash_protocol::value::{BalanceError, Zatoshis};
+
+    fn zat(value: u64) -> Zatoshis {
+        Zatoshis::const_from_u64(value)
+    }
+
+    #[test]
+    fn dust_change_is_reported_beside_total_not_inside_it() {
+        let mut balances = AccountBalance::ZERO;
+        balances
+            .with_ironwood_balance_mut::<_, BalanceError>(|b: &mut Balance| {
+                b.add_spendable_value(zat(100_000))?;
+                b.add_uneconomic_value(zat(5_000))
+            })
+            .unwrap();
+        balances
+            .with_orchard_balance_mut::<_, BalanceError>(|b: &mut Balance| {
+                b.add_pending_change_value(zat(20_000))?;
+                b.add_uneconomic_value(zat(1_000))
+            })
+            .unwrap();
+        // Sapling is out of the product, dust included.
+        balances
+            .with_sapling_balance_mut::<_, BalanceError>(|b: &mut Balance| {
+                b.add_uneconomic_value(zat(3_000))
+            })
+            .unwrap();
+
+        let v = balance_value(10, 9, &balances);
+
+        assert_eq!(v["ironwood"]["spendable"], 100_000);
+        assert_eq!(v["ironwood"]["total"], 100_000);
+        assert_eq!(v["ironwood"]["uneconomic"], 5_000);
+        assert_eq!(v["orchard"]["pendingChange"], 20_000);
+        assert_eq!(v["orchard"]["total"], 20_000);
+        assert_eq!(v["orchard"]["uneconomic"], 1_000);
+        assert_eq!(v["transparentRegular"]["uneconomic"], 0);
+        assert_eq!(v["total"], 120_000);
+        assert_eq!(v["uneconomic"], 6_000);
+    }
+
+    #[test]
+    fn no_dust_reports_zero() {
+        let v = balance_value(1, 1, &AccountBalance::ZERO);
+        for pool in [
+            "orchard",
+            "ironwood",
+            "transparentRegular",
+            "transparentCoinbase",
+        ] {
+            assert_eq!(v[pool]["uneconomic"], 0);
+        }
+        assert_eq!(v["uneconomic"], 0);
+    }
+
+    #[test]
+    fn small_change_preserves_value_after_payment_and_fee() {
+        let payment = 10_000;
+        let fee = 10_000;
+        for change in [1, 4_999, 5_000] {
+            let mut before = AccountBalance::ZERO;
+            before
+                .with_ironwood_balance_mut::<_, BalanceError>(|balance| {
+                    balance.add_spendable_value(zat(payment + fee + change))
+                })
+                .unwrap();
+            let mut after = AccountBalance::ZERO;
+            after
+                .with_ironwood_balance_mut::<_, BalanceError>(|balance| {
+                    balance.add_uneconomic_value(zat(change))
+                })
+                .unwrap();
+
+            let before = balance_value(10, 10, &before);
+            let after = balance_value(11, 11, &after);
+            assert_eq!(
+                before["total"].as_u64().unwrap(),
+                payment
+                    + fee
+                    + after["total"].as_u64().unwrap()
+                    + after["uneconomic"].as_u64().unwrap()
+            );
+            assert_eq!(after["ironwood"]["spendable"], 0);
+            assert_eq!(after["ironwood"]["uneconomic"], change);
+        }
+    }
+}

From 95c16ced8c63b56c0a70c44326f21ff1da6b41f2 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 21:41:58 +0800
Subject: [PATCH 67/97] chore: bump privacy runtimes to 0.1.0-alpha.7

---
 chain-runtimes/monero/Cargo.lock | 2 +-
 chain-runtimes/monero/Cargo.toml | 2 +-
 chain-runtimes/zcash/Cargo.lock  | 6 +++---
 chain-runtimes/zcash/Cargo.toml  | 2 +-
 4 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock
index 6de21098a..c5d09bdd2 100644
--- a/chain-runtimes/monero/Cargo.lock
+++ b/chain-runtimes/monero/Cargo.lock
@@ -1259,7 +1259,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-monero-runtime"
-version = "0.1.0-alpha.6"
+version = "0.1.0-alpha.7"
 dependencies = [
  "curve25519-dalek",
  "futures-lite",
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index 1fd31ad54..e1596808d 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/monero-runtime"]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.6"
+version = "0.1.0-alpha.7"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index 844c76343..3eb0996d7 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1655,7 +1655,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-zcash-keys"
-version = "0.1.0-alpha.6"
+version = "0.1.0-alpha.7"
 dependencies = [
  "bip0039",
  "bip32",
@@ -1687,7 +1687,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-runtime"
-version = "0.1.0-alpha.6"
+version = "0.1.0-alpha.7"
 dependencies = [
  "blake2b_simd",
  "console_error_panic_hook",
@@ -1736,7 +1736,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-storage-benchmark"
-version = "0.1.0-alpha.6"
+version = "0.1.0-alpha.7"
 dependencies = [
  "console_error_panic_hook",
  "js-sys",
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index b78d66407..1200f34fb 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -8,7 +8,7 @@ members = [
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.6"
+version = "0.1.0-alpha.7"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"

From d768225d3a404ec847a4d140f8dfc4417e209353 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 22:07:47 +0800
Subject: [PATCH 68/97] fix(zcash): refuse half a spending derivation pair on
 import

With only the seed fingerprint or only the account index, the import used to
fall back to a view-only account, so later spends and change lacked the
derivation that signers expect.
---
 .../zcash/crates/zcash-runtime/src/account.rs | 35 +++++++++++++++++++
 .../zcash/crates/zcash-runtime/src/bindgen.rs | 22 +++++++-----
 2 files changed, 48 insertions(+), 9 deletions(-)

diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
index e43e0ea3e..315d1115e 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
@@ -67,6 +67,21 @@ pub async fn import_ufvk(
     Ok(account.id().expose_uuid().to_string())
 }
 
+/// Pairs the spending derivation fields; half a pair is refused, not imported view-only.
+pub fn derivation_pair(
+    seed_fingerprint_hex: Option<&str>,
+    account_index: Option,
+) -> Result> {
+    match (seed_fingerprint_hex, account_index) {
+        (Some(fingerprint), Some(index)) => Ok(Some((fingerprint, index))),
+        (None, None) => Ok(None),
+        _ => Err(RuntimeError::with(
+            ErrorCode::InvalidAccountId,
+            json!({ "field": "derivation", "reason": "incomplete" }),
+        )),
+    }
+}
+
 fn parse_zip32_derivation(fingerprint_hex: &str, account_index: u32) -> Result {
     let bytes = hex::decode(fingerprint_hex).map_err(|e| {
         RuntimeError::with(
@@ -443,3 +458,23 @@ mod balance_tests {
         }
     }
 }
+
+#[cfg(test)]
+mod derivation_tests {
+    use super::derivation_pair;
+    use crate::ErrorCode;
+
+    #[test]
+    fn half_a_derivation_pair_is_refused() {
+        assert_eq!(derivation_pair(None, None).unwrap(), None);
+        assert_eq!(
+            derivation_pair(Some("ab"), Some(0)).unwrap(),
+            Some(("ab", 0))
+        );
+        for (fingerprint, index) in [(Some("ab"), None), (None, Some(0))] {
+            let err = derivation_pair(fingerprint, index).unwrap_err();
+            assert_eq!(err.code, ErrorCode::InvalidAccountId);
+            assert_eq!(err.params["reason"], "incomplete");
+        }
+    }
+}
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
index 2b14102d5..9cab1c72d 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
@@ -200,15 +200,19 @@ pub async fn import_account_ufvk(
 ) -> Result {
     Ok(
         runtime::with_db_and_client(move |mut db, mut client| async move {
-            let derivation = seed_fingerprint_hex.as_deref().zip(account_index);
-            let r = account::import_ufvk(
-                &mut db,
-                &mut client,
-                &account_name,
-                &ufvk,
-                birthday_height,
-                derivation,
-            )
+            let r = async {
+                let derivation =
+                    account::derivation_pair(seed_fingerprint_hex.as_deref(), account_index)?;
+                account::import_ufvk(
+                    &mut db,
+                    &mut client,
+                    &account_name,
+                    &ufvk,
+                    birthday_height,
+                    derivation,
+                )
+                .await
+            }
             .await;
             (db, client, r)
         })

From e056c75ea9b7e0132a9684622ec82fa9ec81d553 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 21 Oct 2026 22:10:42 +0800
Subject: [PATCH 69/97] ci: check the chain runtimes on pull requests

Runs each runtime's scripts/ci.sh when a pull request touches
chain-runtimes, so a failing Rust test or wasm build shows before merge
instead of at the next manual publish. Publishing stays manual.
---
 .github/workflows/runtime-checks.yml | 52 ++++++++++++++++++++++++++++
 1 file changed, 52 insertions(+)
 create mode 100644 .github/workflows/runtime-checks.yml

diff --git a/.github/workflows/runtime-checks.yml b/.github/workflows/runtime-checks.yml
new file mode 100644
index 000000000..a761e6a0c
--- /dev/null
+++ b/.github/workflows/runtime-checks.yml
@@ -0,0 +1,52 @@
+name: runtime-checks
+
+# Runs each runtime's scripts/ci.sh on pull requests. Checks only; publishing
+# stays manual in publish-runtime-packages.yml, whose build tools this mirrors.
+on:
+  pull_request:
+    paths:
+      - 'chain-runtimes/**'
+      - '.github/workflows/runtime-checks.yml'
+
+permissions:
+  contents: read
+
+concurrency:
+  group: runtime-checks-${{ github.ref }}
+  cancel-in-progress: true
+
+jobs:
+  check:
+    strategy:
+      fail-fast: false
+      matrix:
+        runtime: [zcash, monero]
+    runs-on: ubuntu-24.04
+    timeout-minutes: 60
+    defaults:
+      run:
+        working-directory: chain-runtimes/${{ matrix.runtime }}
+    steps:
+      - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
+        with:
+          persist-credentials: false
+      - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
+        with:
+          node-version: 24.21.0
+      - name: Install build tools
+        run: |
+          curl -sSfL -o /tmp/binaryen.tgz https://github.com/WebAssembly/binaryen/releases/download/version_133/binaryen-version_133-x86_64-linux.tar.gz
+          echo "2dc9c7813f5375db93d96ead4b78222fcc3e2677bbb832297af4797782a37489  /tmp/binaryen.tgz" | sha256sum -c -
+          sudo tar xzf /tmp/binaryen.tgz -C /opt
+          echo /opt/binaryen-version_133/bin >> "$GITHUB_PATH"
+          sudo apt-get update
+          sudo apt-get install -y clang llvm libsqlite3-dev libssl-dev pkg-config
+          rustup toolchain install
+          cargo install wasm-pack --version 0.15.0 --locked
+          # Must match wasm-bindgen in both runtimes' Cargo.lock.
+          cargo install wasm-bindgen-cli --version 0.2.127 --locked
+      - name: Test, build and pack
+        env:
+          CC_wasm32_unknown_unknown: /usr/bin/clang
+          AR_wasm32_unknown_unknown: /usr/bin/llvm-ar
+        run: bash scripts/ci.sh

From a6a65298dd922da17d1d78d561d0de4dc3fdcc54 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Thu, 22 Oct 2026 09:53:09 +0800
Subject: [PATCH 70/97] chore: remove runtime debug tooling and unused exports

Drops the perf trace, the unused diag* exports, the storage benchmark
crate, two pre-release aliases and the debug harnesses that printed key
material. Exports the App uses are unchanged.
---
 .../crates/monero-runtime/src/schema.rs       |   6 +-
 .../monero/crates/monero-runtime/src/sync.rs  |   7 +-
 chain-runtimes/zcash/Cargo.lock               |  57 --
 chain-runtimes/zcash/Cargo.toml               |   3 -
 chain-runtimes/zcash/README.md                |  10 +-
 chain-runtimes/zcash/RELEASING.md             |  10 +-
 .../crates/zcash-keys-runtime/src/bindgen.rs  |   2 +-
 .../crates/zcash-keys-runtime/src/keys.rs     | 114 +---
 .../zcash/crates/zcash-runtime/Cargo.toml     |   7 -
 .../zcash/crates/zcash-runtime/src/bindgen.rs | 131 +---
 .../crates/zcash-runtime/src/blockcache.rs    |  17 +-
 .../zcash/crates/zcash-runtime/src/lib.rs     |   1 -
 .../zcash/crates/zcash-runtime/src/network.rs |  70 ---
 .../zcash/crates/zcash-runtime/src/perf.rs    |  69 --
 .../zcash/crates/zcash-runtime/src/stats.rs   |   6 +-
 .../zcash/crates/zcash-runtime/src/storage.rs |  40 +-
 .../zcash/crates/zcash-runtime/src/sync.rs    |  90 ---
 .../zcash/crates/zcash-runtime/src/wallet.rs  |  66 --
 .../crates/zcash-runtime/tests/scan_repro.rs  | 307 ---------
 .../crates/zcash-storage-benchmark/Cargo.toml |  24 -
 .../crates/zcash-storage-benchmark/build.rs   |  46 --
 .../zcash-storage-benchmark/src/error.rs      | 104 ----
 .../crates/zcash-storage-benchmark/src/lib.rs |  19 -
 .../src/storage_benchmark.rs                  | 589 ------------------
 .../zcash/scripts/artifact-manifest.py        |   6 +-
 chain-runtimes/zcash/scripts/build-wasm.sh    |   6 +-
 .../zcash/scripts/package-release.py          |  12 +-
 .../zcash/scripts/test_artifact_manifest.py   |   6 +-
 .../zcash/scripts/test_package_release.py     |  22 +-
 29 files changed, 45 insertions(+), 1802 deletions(-)
 delete mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs
 delete mode 100644 chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs
 delete mode 100644 chain-runtimes/zcash/crates/zcash-storage-benchmark/Cargo.toml
 delete mode 100644 chain-runtimes/zcash/crates/zcash-storage-benchmark/build.rs
 delete mode 100644 chain-runtimes/zcash/crates/zcash-storage-benchmark/src/error.rs
 delete mode 100644 chain-runtimes/zcash/crates/zcash-storage-benchmark/src/lib.rs
 delete mode 100644 chain-runtimes/zcash/crates/zcash-storage-benchmark/src/storage_benchmark.rs

diff --git a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
index 572045369..bb16ff0f1 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
@@ -11,11 +11,7 @@
 //! transparent pool, and before FCMP++ no commitment tree, so no witnesses or
 //! checkpoints. The schema can stay small.
 //!
-//! ## On disk, not in memory
-//!
-//! monero-ts keeps the whole wallet in wasm memory and can only persist by
-//! reserializing all of it, which grows with history and loses everything on
-//! a torn write. Here writes are incremental and transactional.
+//! Writes are incremental and transactional; see the crate docs for why.
 
 use rusqlite::Connection;
 
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
index 72748f344..e73bb3518 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
@@ -239,11 +239,8 @@ async fn fetch_blocks(
 ///
 /// Fallback when the batch path (`blocks_bin`) is unusable.
 ///
-/// Does not use `contiguous_scannable_blocks`: it tries `get_blocks.bin` first, but
-/// released monerod (through v0.18.5.1) omits `prunable_hash` when `prune=true`
-/// (monero-project/monero#10120; fix #10652 is master-only), so monero-oxide drops
-/// the whole batch and falls back to serial per-block JSON, wasting a full download
-/// every step.
+/// Does not use `contiguous_scannable_blocks`; see `blocks_bin` for why its batch
+/// path always fails against released monerod.
 ///
 /// Instead fetch per block with N-way concurrency. Upstream still validates each
 /// block (number, transactions match the block's tx list); cross-block continuity
diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index 3eb0996d7..868d93bc0 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1717,8 +1717,6 @@ dependencies = [
  "tonic",
  "tonic-web-wasm-client",
  "tracing",
- "tracing-subscriber",
- "tracing-wasm",
  "uuid",
  "wasm-bindgen",
  "wasm-bindgen-futures",
@@ -1734,21 +1732,6 @@ dependencies = [
  "zip321",
 ]
 
-[[package]]
-name = "onekey-zcash-storage-benchmark"
-version = "0.1.0-alpha.7"
-dependencies = [
- "console_error_panic_hook",
- "js-sys",
- "rusqlite",
- "serde",
- "serde_json",
- "sqlite-wasm-rs",
- "sqlite-wasm-vfs",
- "wasm-bindgen",
- "wasm-bindgen-futures",
-]
-
 [[package]]
 name = "opaque-debug"
 version = "0.3.1"
@@ -2542,15 +2525,6 @@ dependencies = [
  "digest 0.11.0-pre.9",
 ]
 
-[[package]]
-name = "sharded-slab"
-version = "0.1.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
-dependencies = [
- "lazy_static",
-]
-
 [[package]]
 name = "shardtree"
 version = "0.7.1"
@@ -2748,15 +2722,6 @@ dependencies = [
  "syn 3.0.3",
 ]
 
-[[package]]
-name = "thread_local"
-version = "1.1.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
-dependencies = [
- "cfg-if",
-]
-
 [[package]]
 name = "time"
 version = "0.3.55"
@@ -3018,28 +2983,6 @@ dependencies = [
  "once_cell",
 ]
 
-[[package]]
-name = "tracing-subscriber"
-version = "0.3.23"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
-dependencies = [
- "sharded-slab",
- "thread_local",
- "tracing-core",
-]
-
-[[package]]
-name = "tracing-wasm"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4575c663a174420fa2d78f4108ff68f65bf2fbb7dd89f33749b6e826b3626e07"
-dependencies = [
- "tracing",
- "tracing-subscriber",
- "wasm-bindgen",
-]
-
 [[package]]
 name = "try-lock"
 version = "0.2.5"
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index 1200f34fb..619913113 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -3,7 +3,6 @@ resolver = "2"
 members = [
   "crates/zcash-runtime",
   "crates/zcash-keys-runtime",
-  "crates/zcash-storage-benchmark",
 ]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
@@ -45,8 +44,6 @@ wasm-bindgen-futures = "0.4"
 js-sys = "0.3"
 gloo-timers = { version = "0.3", features = ["futures"] }
 tracing = "0.1"
-tracing-wasm = "0.2"
-tracing-subscriber = { version = "0.3", default-features = false, features = ["registry", "std"] }
 
 # Must match zcash_client_sqlite's rand_core major (0.6), or RngCore does not
 # unify and init_wallet_db's bounds fail.
diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md
index e91855073..ae2cdaf67 100644
--- a/chain-runtimes/zcash/README.md
+++ b/chain-runtimes/zcash/README.md
@@ -8,7 +8,7 @@ the wallet store. Two packages built from one source, used on every App platform
 - `onekey-zcash-runtime`: wallet, scanning, SQLite and PCZT proving.
 
 Both run inside a DedicatedWorker. Native Rust builds are for tests and diagnostics
-only. `zcash-storage-benchmark` is a developer tool for synthetic storage tests.
+only.
 
 ## Build
 
@@ -64,7 +64,6 @@ importAccountUfvk(name, ufvk, birthday, seedFingerprintHex?, accountIndex?)
                                          → UUID; the server's tree state must be
                                          exactly the block before birthday
 removeAccount(uuid)                     pending transactions do not block removal
-removeDeletedAccount(uuid)              compatibility alias for removeAccount
 accountByUfvk(ufvk) / listAccounts() / accountSyncStatus(uuid)
 accountBalance(uuid, trusted, untrusted, allowZeroConfShielding)
                                          per pool: spendable, pendingChange,
@@ -83,6 +82,8 @@ transactionHistory(uuid, limit, offset)  limit ≤ 500
 transactionDetails(uuid, txid) / transactionOutputs(uuid, txid)
 deleteWallet(dbName)                     deletes the local cache (rebuildable)
 storageStats()
+diagDatabaseExists(dbName)               persisted bytes exist; opens nothing
+diagDatabaseHealth()                     read-only consistency checks
 
 pcztQuote(...)                           quote only; builds nothing
 pcztCreate(...) → { pcztHex, feeZat }    build; locks no notes
@@ -95,7 +96,7 @@ broadcastTransaction(txid)               resend a stored transaction; explicit u
 prewarmPczt(network, height)             build proving parameters; no wallet
 pcztProveAtHeight(height, pczt)          prove without a wallet
 pcztExtractStateless(pczt)               verify and extract without a wallet
-dependencyVersions() / setPerfTrace(enabled) / diag*
+capabilities() / dependencyVersions()
 ```
 
 ### `onekey-zcash-keys`
@@ -105,7 +106,7 @@ ufvkFromAccountKeys(network, orchardSk, accountXpub, accountIndex)
                                          mainnet only; orchardSk is the 32-byte Orchard key
 unifiedAddress(network, ufvk, receiverPolicy)
                                          "all" = Orchard + transparent;
-                                         "shielded" / "orchard" = Orchard only; never Sapling
+                                         "orchard" = Orchard only; never Sapling
 transparentAddressFromUfvk(network, ufvk) / transparentAccountPubKeyFromUfvk(network, ufvk)
 validateAddress(network, address)
 pcztVerifyReview(pczt, reviewJson)       check only, no signing
@@ -195,7 +196,6 @@ use the stateless API in
 ```
 crates/zcash-runtime/            wallet, scanning, PCZT build/prove/submit
 crates/zcash-keys-runtime/       derivation, review checks, signing, stateless transparent sends
-crates/zcash-storage-benchmark/  synthetic storage tests
 patches/                         pinned upstream checksums and patches
 scripts/                         vendor-deps.sh, build-wasm.sh, package-release.py
 ```
diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md
index b6e03adf6..b6dacfa4b 100644
--- a/chain-runtimes/zcash/RELEASING.md
+++ b/chain-runtimes/zcash/RELEASING.md
@@ -5,15 +5,13 @@ run the repository-wide `version:patch` or `version:publish` for a Zcash release
 
 ## Version source
 
-Edit only `[workspace.package].version` in `Cargo.toml`. All three crates inherit
-it, and wasm-pack generates the npm versions from those crates. Update the three
+Edit only `[workspace.package].version` in `Cargo.toml`. Both crates inherit it,
+and wasm-pack generates the npm versions from those crates. Update the two
 workspace entries in `Cargo.lock` with `cargo check --workspace --offline` and
 review the lockfile diff; dependency upgrades are a separate change.
 
 Prerelease versions (`X.Y.Z-alpha.N`, `X.Y.Z-rc.N`) go to the npm `next` tag,
-release versions to `latest`. Runtime and keys always share a version and source commit. The
-benchmark ships as a runtime subdirectory to keep the App developer tools' import
-path; it is not a third package, and production App bundles exclude it.
+release versions to `latest`. Runtime and keys always share a version and source commit.
 
 ## Prepare and verify
 
@@ -22,7 +20,7 @@ Use Python 3.11+ and the pinned Rust/WASM tools described in README.md.
 1. Run `python3 -m unittest discover -s scripts -p 'test_*.py'` and
    `cargo test --workspace --locked --offline` with already prepared dependencies.
 2. Commit the release changes. A release build must come from a clean checkout.
-3. Run `bash scripts/build-wasm.sh --offline`. This builds all three WASM
+3. Run `bash scripts/build-wasm.sh --offline`. This builds both WASM
    artifacts, prepares npm metadata and LICENSE, and writes the source manifest.
 4. Run `python3 scripts/package-release.py pack --version 0.1.0-rc.1 --tag next
    --revision ` (as one command). It checks clean-source
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
index bcc4a1928..e32c14145 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
@@ -16,7 +16,7 @@ pub fn validate_address(network: &str, address: &str) -> Result {
 
 /// Derive the Unified Address from a UFVK. Public material only.
 ///
-/// `receiverPolicy` selects the receivers: `"all"` / `"shielded"` / `"orchard"`.
+/// `receiverPolicy` selects the receivers: `"all"` / `"orchard"`.
 /// It is a host privacy decision with no default: a transparent receiver links
 /// the user's transparent and shielded activity.
 #[wasm_bindgen(js_name = unifiedAddress)]
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
index 348829394..d001f19f3 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
@@ -115,14 +115,13 @@ pub(crate) fn without_sapling(params: Network, ufvk: &UnifiedFullViewingKey) ->
 /// The runtime only checks that the combination is valid.
 ///
 /// No policy includes a Sapling receiver: this runtime cannot spend Sapling, so
-/// Sapling-only senders would pay into an unspendable pool. `"shielded"` is
-/// therefore an alias of `"orchard"`, kept for existing callers.
+/// Sapling-only senders would pay into an unspendable pool.
 fn receiver_policy(name: &str) -> Result {
     use zcash_keys::keys::{ReceiverRequirement::*, UnifiedAddressRequest as R};
     match name {
         // No default: an empty policy must not silently select the least private option.
         "all" => Ok(R::unsafe_custom(Require, Omit, Allow)),
-        "shielded" | "orchard" => Ok(R::ORCHARD),
+        "orchard" => Ok(R::ORCHARD),
         other => Err(KeysError::with(
             ErrorCode::InvalidUfvk,
             json!({ "stage": "receiverPolicy", "value": other }),
@@ -132,7 +131,7 @@ fn receiver_policy(name: &str) -> Result Result {
     let params = parse_network(network)?;
     let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str)
@@ -238,7 +237,7 @@ mod tests {
 
         for network in ["main", "test"] {
             let ufvk = ufvk_from_mnemonic(network, TEST_MNEMONIC, 0).unwrap();
-            for policy in ["all", "shielded", "orchard"] {
+            for policy in ["all", "orchard"] {
                 let ua = unified_address_with(network, &ufvk, policy).unwrap();
                 let (_, address) = Address::decode(&ua).unwrap();
                 let receivers = address.items();
@@ -324,8 +323,8 @@ mod tests {
     #[test]
     fn receiver_policy_has_no_default() {
         assert!(receiver_policy("all").is_ok());
-        assert!(receiver_policy("shielded").is_ok());
         assert!(receiver_policy("orchard").is_ok());
+        assert!(receiver_policy("shielded").is_err());
         assert!(receiver_policy("").is_err());
         assert!(receiver_policy("transparent").is_err());
     }
@@ -361,106 +360,3 @@ mod tests {
         assert_ne!(a, b, "different accounts must derive different UFVKs");
     }
 }
-
-#[cfg(test)]
-mod ua_inspect {
-    fn receivers(ua: &str) -> Vec {
-        use zcash_address::unified::{Container, Encoding};
-        let (_, parsed) = zcash_address::unified::Address::decode(ua).expect("decode UA");
-        parsed
-            .items()
-            .iter()
-            .map(|item| match item {
-                zcash_address::unified::Receiver::Orchard(_) => "orchard".to_owned(),
-                zcash_address::unified::Receiver::Sapling(_) => "sapling".to_owned(),
-                zcash_address::unified::Receiver::P2pkh(_) => "transparent-p2pkh".to_owned(),
-                zcash_address::unified::Receiver::P2sh(_) => "transparent-p2sh".to_owned(),
-                other => format!("{other:?}"),
-            })
-            .collect()
-    }
-
-    /// Print receiving addresses for a mnemonic, for manual testing (e.g. faucet
-    /// funds). Skipped unless `ZR_MNEMONIC` is set.
-    ///
-    /// Also prints each policy's receivers, since an unspendable receiver in a
-    /// receiving address would strand incoming funds.
-    #[test]
-    fn print_receiving_addresses() {
-        let mnemonic = std::env::var("ZR_MNEMONIC").unwrap_or_default();
-        if mnemonic.trim().is_empty() {
-            return;
-        }
-        let network = std::env::var("ZR_NETWORK").unwrap_or_else(|_| "test".to_owned());
-        let account: u32 = std::env::var("ZR_ACCOUNT")
-            .ok()
-            .and_then(|v| v.parse().ok())
-            .unwrap_or(0);
-        let ufvk =
-            super::ufvk_from_mnemonic(&network, mnemonic.trim(), account).expect("derive UFVK");
-
-        println!("network      {network}");
-        println!(
-            "t-addr       {}",
-            super::transparent_address(&network, &ufvk).expect("t-address")
-        );
-        for policy in ["all", "shielded", "orchard"] {
-            let ua = super::unified_address_with(&network, &ufvk, policy).expect("UA");
-            println!("UA[{policy}]  {ua}");
-            println!("             receivers = {:?}", receivers(&ua));
-        }
-    }
-
-    /// Decode a UFVK (uview...) and list its key items. Differing item sets mean
-    /// an encoding difference; same items with different bytes mean a derivation
-    /// difference.
-    #[test]
-    fn inspect_external_ufvk() {
-        let s = std::env::var("ZR_UFVK").unwrap_or_default();
-        if s.is_empty() {
-            return;
-        }
-        use zcash_address::unified::{Container, Encoding, Fvk, Ufvk};
-        let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::();
-        let (net, parsed) = Ufvk::decode(&s).expect("decode UFVK");
-        println!("network: {net:?}");
-        for item in parsed.items() {
-            match &item {
-                Fvk::Orchard(d) => println!("  orchard          {}", hex(d)),
-                Fvk::Sapling(d) => println!("  sapling          {}", hex(d)),
-                Fvk::P2pkh(d) => println!("  transparent-p2pkh {}", hex(d)),
-                other => println!("  other key item: {other:?}"),
-            }
-        }
-    }
-
-    /// Decode a UA and list its receivers, e.g. to inspect other wallets' addresses.
-    #[test]
-    fn inspect_external_ua() {
-        let ua = std::env::var("ZR_UA").unwrap_or_default();
-        if ua.is_empty() {
-            return;
-        }
-        use zcash_address::unified::{Container, Encoding};
-        let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::();
-        let (net, parsed) = zcash_address::unified::Address::decode(&ua).expect("decode UA");
-        println!("network: {net:?}");
-        for item in parsed.items() {
-            match &item {
-                zcash_address::unified::Receiver::Orchard(d) => {
-                    println!("  orchard          {}", hex(d));
-                }
-                zcash_address::unified::Receiver::Sapling(d) => {
-                    println!("  sapling          {}", hex(d));
-                }
-                zcash_address::unified::Receiver::P2pkh(d) => {
-                    println!("  transparent-p2pkh {}", hex(d));
-                }
-                zcash_address::unified::Receiver::P2sh(d) => {
-                    println!("  transparent-p2sh {}", hex(d));
-                }
-                other => println!("  other receiver: {other:?}"),
-            }
-        }
-    }
-}
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
index 3c5d68b7d..72b4eeea0 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
+++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
@@ -64,8 +64,6 @@ js-sys.workspace = true
 gloo-timers.workspace = true
 console_error_panic_hook = "0.1"
 tracing.workspace = true
-tracing-wasm = { workspace = true, optional = true }
-tracing-subscriber = { workspace = true, optional = true }
 getrandom = { workspace = true, features = ["wasm_js"] }
 tonic-web-wasm-client.workspace = true
 # Not used directly; only enables the feature. zcash_client_backend records
@@ -88,8 +86,3 @@ wasm-opt = ["-Oz", "--enable-bulk-memory", "--enable-nontrapping-float-to-int"]
 # them) but skip wasm-opt, which strips the name section panic stacks need.
 [package.metadata.wasm-pack.profile.profiling]
 wasm-opt = false
-
-[features]
-# Forward zcash_client_backend tracing events to the browser console.
-# Debugging only: very verbose and slows scanning noticeably.
-debug-tracing = ["dep:tracing-wasm", "dep:tracing-subscriber"]
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
index 9cab1c72d..926f95283 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
@@ -18,7 +18,6 @@
 
 use wasm_bindgen::prelude::*;
 
-use crate::perf;
 use crate::{
     account,
     error::{ErrorCode, RuntimeError},
@@ -49,39 +48,11 @@ pub fn storage_requires_worker_restart() -> bool {
 
 /// Turns a panic into a console error with a stack trace instead of a Promise that never settles.
 ///
-/// Must be installed at every entry point, including `diagInitMemoryStorage()`.
+/// Must be installed at every entry point.
 fn install_panic_hook() {
     console_error_panic_hook::set_once();
 }
 
-/// Enables tracing output to the browser console (requires the `debug-tracing` feature).
-///
-/// Upstream `zcash_client_backend` is instrumented with `tracing`; when sync stalls,
-/// the last console entry shows the step it stopped at.
-///
-/// Very verbose and slows scanning; use only for debugging.
-#[wasm_bindgen(js_name = diagEnableTracing)]
-pub fn enable_debug_tracing() {
-    #[cfg(feature = "debug-tracing")]
-    {
-        use tracing_subscriber::prelude::*;
-        let _ = tracing_subscriber::registry()
-            .with(tracing_wasm::WASMLayer::new(Default::default()))
-            .try_init();
-    }
-}
-
-/// Uses in-memory storage: no persistent VFS; data lives only for the page lifetime.
-///
-/// For ephemeral wallets, and for isolating storage from computation when profiling.
-///
-/// Call instead of `init()`, never both.
-#[wasm_bindgen(js_name = diagInitMemoryStorage)]
-pub fn init_memory_storage() {
-    install_panic_hook();
-    storage::use_memory_storage();
-}
-
 /// The capabilities of this version-locked wallet and keys package set.
 ///
 /// Lets the host hide unsupported actions up front instead of failing at proving time.
@@ -114,22 +85,9 @@ pub fn dependency_versions() -> String {
     crate::dependency_versions().to_string()
 }
 
-/// Diagnostic: structural summary of a single block. No scanning, no writes.
-#[wasm_bindgen(js_name = diagBlockSummary)]
-pub async fn block_summary(height: u32) -> Result {
-    Ok(
-        runtime::with_db_and_client(move |db, mut client| async move {
-            let r = network::block_summary(&mut client, height).await;
-            (db, client, r)
-        })
-        .await?,
-    )
-}
-
 /// Opens a page-backed database and applies the official SQLite migrations.
 #[wasm_bindgen(js_name = openWallet)]
 pub async fn open_wallet(network_name: String, db_name: String) -> Result {
-    let _perf = perf::span("openWallet");
     let (network_name, db_name) = (network_name.as_str(), db_name.as_str());
     let db = wallet::open_and_migrate(network_name, db_name)?;
     // WALLET_BUSY must propagate, or the caller assumes the database was swapped.
@@ -137,12 +95,6 @@ pub async fn open_wallet(network_name: String, db_name: String) -> Result Result<(), JsValue> {
     Ok(())
 }
 
-/// Compatibility alias for hosts that distinguish app-account removal.
-#[wasm_bindgen(js_name = removeDeletedAccount)]
-pub async fn remove_deleted_account(account_uuid: String) -> Result<(), JsValue> {
-    remove_account(account_uuid).await
-}
-
 /// Finds the account for a UFVK, returning `{ uuid }` or `"null"` if absent.
 ///
 /// The only correct lookup in the shared per-network database: UUIDs change after a purge.
 #[wasm_bindgen(js_name = accountByUfvk)]
 pub fn account_by_ufvk(ufvk: String) -> Result {
-    let _perf = perf::span("accountByUfvk");
     Ok(runtime::with_db(|db| account::account_by_ufvk(db, &ufvk))?)
 }
 
@@ -274,7 +219,6 @@ pub fn account_balance(
     untrusted: u32,
     allow_zero_conf_shielding: bool,
 ) -> Result {
-    let _perf = perf::span("accountBalance");
     let policy = account::confirmations_policy(trusted, untrusted, allow_zero_conf_shielding)?;
     Ok(runtime::with_db(|db| {
         account::balance_json(db, &account_uuid, policy)
@@ -290,7 +234,6 @@ pub fn account_balance(
 /// Returns `{ chainTip, saplingSubtrees, orchardSubtrees, ironwoodSubtrees }`.
 #[wasm_bindgen(js_name = syncPrepare)]
 pub async fn sync_prepare() -> Result {
-    let _perf = perf::span("syncPrepare");
     Ok(
         runtime::with_db_and_client(|mut db, mut client| async move {
             let r = sync::prepare(&mut db, &mut client).await;
@@ -322,20 +265,6 @@ pub fn sync_peek() -> Result {
     Ok(runtime::with_db(|db| sync::peek(db))?)
 }
 
-/// Diagnostic: downloads without scanning and returns per-phase timings. Does not change wallet state.
-///
-/// Separates network stalls from scan stalls, which look the same in the browser.
-#[wasm_bindgen(js_name = diagProbeDownload)]
-pub async fn sync_probe_download(batch_size: u32) -> Result {
-    Ok(
-        runtime::with_db_and_client(move |db, mut client| async move {
-            let r = sync::probe_download(&db, &mut client, batch_size).await;
-            (db, client, r)
-        })
-        .await?,
-    )
-}
-
 /// Quotes only: no transaction built. Returns `{ feeZat, steps }`.
 ///
 /// Shares the proposal path with `pcztCreate`, so the quoted fee is the fee paid.
@@ -378,7 +307,6 @@ pub fn pczt_quote(
 /// lacks the transaction (external txid, rolled-back transaction); that is a normal state.
 #[wasm_bindgen(js_name = transactionDetails)]
 pub fn transaction_details(account_uuid: String, txid: String) -> Result {
-    let _perf = perf::span("transactionDetails");
     Ok(runtime::with_read_conn(|conn| {
         history::details(conn, &account_uuid, &txid)
     })?)
@@ -415,7 +343,6 @@ pub async fn sync_step(
     priority: Option,
     active_ufvks_json: String,
 ) -> Result {
-    let _perf = perf::span("syncStep");
     let preferred = sync::parse_priority(priority.as_deref().unwrap_or(""))?;
     let active_ufvks: Vec = serde_json::from_str(&active_ufvks_json).map_err(|e| {
         RuntimeError::new(ErrorCode::InvalidUfvk).detail(format!("activeUfvksJson: {e}"))
@@ -451,7 +378,6 @@ pub fn transaction_history(
     limit: u32,
     offset: u32,
 ) -> Result {
-    let _perf = perf::span("transactionHistory");
     Ok(runtime::with_read_conn(|conn| {
         history::list(conn, &account_uuid, limit, offset)
     })?)
@@ -701,61 +627,6 @@ pub fn database_health() -> Result {
     Ok(runtime::with_read_conn(crate::stats::database_health)?)
 }
 
-/// Diagnostic: counts inputs per bundle in a PCZT.
-///
-/// Input counts show which pool funds left from.
-#[wasm_bindgen(js_name = diagPcztInputCounts)]
-pub fn pczt_input_counts(pczt_bytes: Vec) -> Result {
-    let pczt = pczt::Pczt::parse(&pczt_bytes).map_err(|e| {
-        JsValue::from(
-            crate::RuntimeError::new(crate::ErrorCode::PcztError).detail(format!("{e:?}")),
-        )
-    })?;
-    // Action counts alone mislead (actions pair a spend with an output and are padded to 2).
-    // `valueSum` = the pool's spends minus outputs; positive means notes from it were spent.
-    let sum = |b: &pczt::orchard::Bundle| {
-        let (magnitude, negative) = *b.value_sum();
-        serde_json::json!({ "magnitude": magnitude, "negative": negative })
-    };
-    // shielded spend = payment + fee − transparent input; `valueSum` gives only net flow.
-    let transparent_value: u64 = pczt.transparent().inputs().iter().map(|i| *i.value()).sum();
-
-    Ok(serde_json::json!({
-        "transparent": pczt.transparent().inputs().len(),
-        "transparentValue": transparent_value,
-        "sapling": pczt.sapling().spends().len(),
-        "orchard": pczt.orchard().actions().len(),
-        "ironwood": pczt.ironwood().actions().len(),
-        "orchardValueSum": sum(pczt.orchard()),
-        "ironwoodValueSum": sum(pczt.ironwood()),
-    })
-    .to_string())
-}
-
-/// Self-check: opens the database, runs migrations, and reports table / view / index counts.
-#[wasm_bindgen(js_name = diagSelfCheck)]
-pub fn self_check(network_name: &str, db_name: &str) -> Result {
-    drop(wallet::open_and_migrate(network_name, db_name)?);
-    let conn = storage::open_connection(db_name)?;
-
-    let count_of = |kind: &str| -> Result {
-        conn.query_row(
-            "SELECT COUNT(*) FROM sqlite_master WHERE type = ?1",
-            [kind],
-            |r| r.get(0),
-        )
-        .map_err(|e| JsValue::from(crate::RuntimeError::from(e)))
-    };
-
-    Ok(serde_json::json!({
-        "tables": count_of("table")?,
-        "views": count_of("view")?,
-        "indexes": count_of("index")?,
-        "versions": crate::dependency_versions(),
-    })
-    .to_string())
-}
-
 /// Builds only public circuit parameters without opening wallet storage.
 #[wasm_bindgen(js_name = prewarmPczt)]
 pub fn prewarm_pczt(network_name: &str, target_height: u32) -> Result<(), JsValue> {
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs
index 471594e65..b6c50a559 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs
@@ -140,24 +140,9 @@ impl BlockSource for MemoryBlockCache {
             out
         }; // lock released here
 
-        // Per-block tracing separates a stall in scanning from one in the later
-        // database/tree writes. debug-tracing builds only.
-        #[cfg(feature = "debug-tracing")]
-        let total = selected.len();
-        // The index is consumed only by the debug-tracing build.
-        #[allow(clippy::unused_enumerate_index)]
-        for (_i, block) in selected.into_iter().enumerate() {
-            #[cfg(feature = "debug-tracing")]
-            crate::sync::trace(&format!(
-                "cache: handing out block {}/{} h={}",
-                _i + 1,
-                total,
-                block.height
-            ));
+        for block in selected {
             with_block(block)?;
         }
-        #[cfg(feature = "debug-tracing")]
-        crate::sync::trace("cache: batch handed out; remaining time is upstream db/tree writes");
         Ok(())
     }
 }
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs
index 778bcf60f..344f1c367 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs
@@ -37,7 +37,6 @@ pub mod wallet;
 
 // Network and sync: gRPC-web in browsers, tonic transport natively.
 pub mod network;
-pub mod perf;
 pub mod sync;
 
 // Cross-call state uses thread_local, valid only in the single-threaded wasm host.
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
index f6985666e..6231338c8 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
@@ -271,76 +271,6 @@ fn broadcast_already_known(message: &str) -> bool {
     .any(|needle| message.contains(needle))
 }
 
-/// Diagnostic: fetch one block and return a structural summary. No scanning, no writes.
-///
-/// wasm (gRPC-web proxy) and native (gRPC) may hit different servers returning
-/// different compact blocks; compare summaries before comparing behavior. Per-pool
-/// counts show whether a difference comes from the server rather than computation.
-pub async fn block_summary(client: &mut LightClient, height: u32) -> Result {
-    use futures_util::TryStreamExt;
-    use zcash_client_backend::proto::service::BlockRange;
-
-    let id = |h: u32| BlockId {
-        height: u64::from(h),
-        hash: Vec::new(),
-    };
-    let blocks = with_timeout(
-        async {
-            client
-                .get_block_range(BlockRange {
-                    start: Some(id(height)),
-                    end: Some(id(height)),
-                    pool_types: vec![],
-                })
-                .await
-                .map_err(|e| net_err("getBlockRange", e))?
-                .into_inner()
-                .try_collect::>()
-                .await
-                .map_err(|e| net_err("getBlockRange", e))
-        },
-        DEFAULT_TIMEOUT_MS,
-        "getBlockRange",
-    )
-    .await?;
-
-    let Some(block) = blocks.into_iter().next() else {
-        return Ok(json!({ "height": height, "found": false }).to_string());
-    };
-
-    let (mut spends, mut outputs, mut actions, mut ironwood) = (0usize, 0usize, 0usize, 0usize);
-    for tx in &block.vtx {
-        spends += tx.spends.len();
-        outputs += tx.outputs.len();
-        actions += tx.actions.len();
-        ironwood += tx.ironwood_actions.len();
-    }
-
-    Ok(json!({
-        "height": height,
-        "found": true,
-        // protobuf encoded length + checksum: any differing bit shows up
-        "encodedLen": prost::Message::encoded_len(&block),
-        "checksum": fnv1a(&prost::Message::encode_to_vec(&block)),
-        "vtx": block.vtx.len(),
-        "saplingSpends": spends,
-        "saplingOutputs": outputs,
-        "orchardActions": actions,
-        "ironwoodActions": ironwood,
-    })
-    .to_string())
-}
-
-/// FNV-1a, only for comparing bytes across endpoints; not for security.
-fn fnv1a(bytes: &[u8]) -> String {
-    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
-    for b in bytes {
-        h ^= u64::from(*b);
-        h = h.wrapping_mul(0x1000_0000_01b3);
-    }
-    format!("{h:016x}")
-}
-
 /// Fetch the treestate at `height`.
 ///
 /// Needed for account import: `AccountBirthday` requires the commitment tree state
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs
deleted file mode 100644
index ff5c70a33..000000000
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/perf.rs
+++ /dev/null
@@ -1,69 +0,0 @@
-//! Perf tracing: when enabled by the host, logs each export's duration
-//! to the console. Shares the host's `[PRIV-PERF]` prefix so one filter covers both.
-
-use std::sync::atomic::{AtomicBool, Ordering};
-
-static ENABLED: AtomicBool = AtomicBool::new(false);
-
-pub fn set_enabled(enabled: bool) {
-    ENABLED.store(enabled, Ordering::Relaxed);
-}
-
-pub fn is_enabled() -> bool {
-    ENABLED.load(Ordering::Relaxed)
-}
-
-/// Logs the elapsed time when dropped, including across awaits in async fns.
-pub struct Span {
-    name: &'static str,
-    started_ms: f64,
-}
-
-pub fn span(name: &'static str) -> Option {
-    if !is_enabled() {
-        return None;
-    }
-    Some(Span {
-        name,
-        started_ms: now_ms(),
-    })
-}
-
-impl Drop for Span {
-    fn drop(&mut self) {
-        let ms = now_ms() - self.started_ms;
-        log(&format!(
-            "[PRIV-PERF] rt {} {{\"ms\":{}}}",
-            self.name,
-            ms.round()
-        ));
-    }
-}
-
-#[cfg(target_arch = "wasm32")]
-fn now_ms() -> f64 {
-    js_sys::Date::now()
-}
-
-#[cfg(not(target_arch = "wasm32"))]
-fn now_ms() -> f64 {
-    std::time::SystemTime::now()
-        .duration_since(std::time::UNIX_EPOCH)
-        .map(|d| d.as_secs_f64() * 1000.0)
-        .unwrap_or(0.0)
-}
-
-#[cfg(target_arch = "wasm32")]
-fn log(msg: &str) {
-    #[wasm_bindgen::prelude::wasm_bindgen]
-    extern "C" {
-        #[wasm_bindgen(js_namespace = console, js_name = log)]
-        fn console_log(s: &str);
-    }
-    console_log(msg);
-}
-
-#[cfg(not(target_arch = "wasm32"))]
-fn log(msg: &str) {
-    println!("{msg}");
-}
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs
index 74525f24c..80a1354c7 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs
@@ -1,12 +1,12 @@
 //! Storage usage stats. Read-only, fixed SQL.
 //!
-//! Reports bytes per data group, which `diagSelfCheck` (object counts only) cannot.
+//! Reports bytes per data group.
 //!
 //! There is deliberately no arbitrary-SQL entry point: one bad statement could
 //! delete anchors still needed for proving.
 //!
-//! Table and column names come from `wallet.rs::tests::dump_schema`. A wrong
-//! column name can yield NULL under some aggregates instead of an error.
+//! Table and column names must match the migrated `zcash_client_sqlite` schema.
+//! A wrong column name can yield NULL under some aggregates instead of an error.
 
 use crate::error::{ErrorCode, Result, RuntimeError};
 use rusqlite::Connection;
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
index 7d0129d7c..2f5f34fee 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
@@ -150,7 +150,7 @@ pub async fn durability_barrier() -> Result<()> {
             json!({ "reason": "storageRequiresWorkerRestart" }),
         ));
     }
-    if !memory_mode() && !is_ready() {
+    if !is_ready() {
         return Err(RuntimeError::new(ErrorCode::NotInitialized));
     }
     Ok(())
@@ -180,30 +180,8 @@ pub fn is_ready() -> bool {
     true
 }
 
-#[cfg(target_arch = "wasm32")]
-static MEMORY_MODE: AtomicBool = AtomicBool::new(false);
-
-/// Diagnostic-only mode, selected before installing a persistent VFS.
-#[cfg(target_arch = "wasm32")]
-pub fn use_memory_storage() {
-    MEMORY_MODE.store(true, Ordering::SeqCst);
-}
-
-#[cfg(not(target_arch = "wasm32"))]
-pub fn use_memory_storage() {}
-
-#[cfg(target_arch = "wasm32")]
-fn memory_mode() -> bool {
-    MEMORY_MODE.load(Ordering::SeqCst)
-}
-
-#[cfg(not(target_arch = "wasm32"))]
-fn memory_mode() -> bool {
-    true
-}
-
 pub fn open_connection(db_name: &str) -> Result {
-    if !memory_mode() && !is_ready() {
+    if !is_ready() {
         return Err(RuntimeError::new(ErrorCode::NotInitialized));
     }
     let bad_name = db_name.is_empty()
@@ -221,12 +199,10 @@ pub fn open_connection(db_name: &str) -> Result {
     // Zero deleted rows (viewing keys, notes, memos) instead of leaving them
     // in free pages; per connection, so every open needs it.
     conn.execute_batch("PRAGMA secure_delete = ON;")?;
+    // SAH-pool uses rollback journals, not cross-context WAL coordination.
+    // Never weaken transaction durability to improve scan throughput.
     #[cfg(target_arch = "wasm32")]
-    if !memory_mode() {
-        // SAH-pool uses rollback journals, not cross-context WAL coordination.
-        // Never weaken transaction durability to improve scan throughput.
-        conn.execute_batch("PRAGMA journal_mode = DELETE; PRAGMA synchronous = FULL;")?;
-    }
+    conn.execute_batch("PRAGMA journal_mode = DELETE; PRAGMA synchronous = FULL;")?;
     rusqlite::vtab::array::load_module(&conn)?;
     Ok(conn)
 }
@@ -262,9 +238,6 @@ pub fn reclaim_free_pages(conn: &rusqlite::Connection, max_pages: u32) -> Result
 /// Inspect the pool's file table without opening or creating a database.
 #[cfg(target_arch = "wasm32")]
 pub async fn database_exists(db_name: &str) -> Result {
-    if memory_mode() {
-        return Ok(false);
-    }
     persistent_vfs()?
         .exists(db_name)
         .map_err(|error| db_storage_err("inspectDatabase", db_name, error))
@@ -278,9 +251,6 @@ pub async fn database_exists(db_name: &str) -> Result {
 /// Delete a closed database.
 #[cfg(target_arch = "wasm32")]
 pub async fn delete_database(db_name: &str) -> Result {
-    if memory_mode() {
-        return Ok(false);
-    }
     persistent_vfs()?
         .delete_db(db_name)
         .map_err(|error| db_storage_err("deleteDatabase", db_name, error))
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
index 1dc7a381d..9131b582c 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
@@ -257,13 +257,7 @@ pub async fn step(
         let (batch, batch_len) = loop {
             let attempt_end = std::cmp::min(start + attempt_len, range.block_range().end);
             let candidate = ScanRange::from_parts(start..attempt_end, range.priority());
-            let candidate_len = candidate.len();
-            trace(&format!(
-                "step: download {candidate_len} blocks @{}",
-                u32::from(start)
-            ));
             // download_batch times out on stalls; only real failures reach here.
-            let _ = candidate_len;
             match download_batch(client, &cache, &candidate).await {
                 Ok(got) => break (candidate, got),
                 Err(e) => {
@@ -272,14 +266,12 @@ pub async fn step(
                     }
                     if same_size_retry > 0 {
                         same_size_retry -= 1;
-                        trace("step: download failed, retrying same batch");
                         continue;
                     }
                     if attempt_len <= MIN_DOWNLOAD_BATCH {
                         return Err(e);
                     }
                     attempt_len = std::cmp::max(MIN_DOWNLOAD_BATCH, attempt_len / 2);
-                    trace(&format!("step: download timeout, halving -> {attempt_len}"));
                 }
             }
         };
@@ -298,7 +290,6 @@ pub async fn step(
                 let grown = std::cmp::min(batch_size, attempt_len.saturating_mul(2));
                 DOWNLOAD_BATCH_HINT.with(|h| h.set(grown));
                 DOWNLOAD_BATCH_STREAK.with(|s| s.set(0));
-                trace(&format!("step: growing batch -> {grown}"));
             }
         }
         // A budget cut may store fewer blocks than requested; scan only what arrived.
@@ -329,7 +320,6 @@ pub async fn step(
 
         let t_treestate = now_ms();
         ms_treestate += t_treestate - t_downloaded;
-        trace(&format!("step: scanning {batch_len} blocks"));
 
         // Reorgs surface as REORG_DETECTED with an exact atHeight.
         scan_blocks_inline(
@@ -343,7 +333,6 @@ pub async fn step(
         )?;
 
         ms_scan += now_ms() - t_treestate;
-        trace(&format!("step: scan done, total {ms_scan:.0}ms"));
 
         blocks_scanned += batch_len as u64;
 
@@ -713,62 +702,6 @@ pub fn peek(db: &Db) -> Result {
     Ok(json!({ "ranges": items, "totalBlocks": total }).to_string())
 }
 
-/// Diagnostic probe: download only, no scan, no writes. Returns per-phase timings.
-///
-/// Separates a slow or hung network from a slow or hung scan, which look the same
-/// in the browser.
-pub async fn probe_download(db: &Db, client: &mut LightClient, batch_size: u32) -> Result {
-    let t0 = now_ms();
-
-    let ranges = db
-        .suggest_scan_ranges()
-        .map_err(|e| db_err("suggestScanRanges", e))?;
-    let Some(range) = ranges.into_iter().find(|r| !r.is_empty()) else {
-        return Ok(json!({ "skipped": "noRange" }).to_string());
-    };
-
-    let start = range.block_range().start;
-    let end = std::cmp::min(start + batch_size, range.block_range().end);
-    let batch = ScanRange::from_parts(start..end, range.priority());
-    let t_range = now_ms();
-
-    let cache = MemoryBlockCache::new();
-    download_batch(client, &cache, &batch).await?;
-    let t_download = now_ms();
-
-    let params = *db.params();
-    let anchor = anchor_height(¶ms, start);
-    crate::network::with_timeout(
-        async {
-            client
-                .get_tree_state(service::BlockId {
-                    height: u64::from(anchor),
-                    hash: Vec::new(),
-                })
-                .await
-                .map_err(|e| net_err("getTreeState", e))?
-                .into_inner()
-                .to_chain_state()
-                .map_err(|e| net_err("toChainState", e))
-        },
-        crate::network::DEFAULT_TIMEOUT_MS,
-        "getTreeState",
-    )
-    .await?;
-    let t_tree = now_ms();
-
-    Ok(json!({
-        "rangeStart": u32::from(start),
-        "rangeEnd": u32::from(end),
-        "blocksCached": cache.len(),
-        "anchorHeight": anchor,
-        "msSuggestRanges": (t_range - t0) as u32,
-        "msDownload": (t_download - t_range) as u32,
-        "msTreeState": (t_tree - t_download) as u32,
-    })
-    .to_string())
-}
-
 #[cfg(target_arch = "wasm32")]
 fn now_ms() -> f64 {
     js_sys::Date::now()
@@ -783,27 +716,6 @@ fn now_ms() -> f64 {
         .unwrap_or(0.0)
 }
 
-/// Phase trace. When a call runs long, the last trace shows which phase it is in.
-#[cfg(target_arch = "wasm32")]
-pub(crate) fn trace(msg: &str) {
-    #[wasm_bindgen::prelude::wasm_bindgen]
-    extern "C" {
-        #[wasm_bindgen(js_namespace = console)]
-        fn log(s: &str);
-    }
-    // Every scan step logs several lines; only with diagnostics on.
-    if crate::perf::is_enabled() {
-        log(msg);
-    }
-}
-
-#[cfg(not(target_arch = "wasm32"))]
-pub(crate) fn trace(msg: &str) {
-    if crate::perf::is_enabled() {
-        println!("{msg}");
-    }
-}
-
 /// Anchor at `start - 1`, but not below Sapling activation.
 ///
 /// lightwalletd has no treestate below it, and its error reply hangs the wasm
@@ -862,7 +774,6 @@ async fn download_batch(
     let mut blocks = Vec::new();
     loop {
         if !blocks.is_empty() && now_ms() - started > DOWNLOAD_SOFT_BUDGET_MS {
-            trace(&format!("step: over budget, scan {} blocks", blocks.len()));
             break;
         }
         let next = crate::network::with_timeout(
@@ -883,7 +794,6 @@ async fn download_batch(
                 if blocks.is_empty() {
                     return Err(e); // stalled with nothing received
                 }
-                trace(&format!("step: stalled, scan {} blocks", blocks.len()));
                 break;
             }
         }
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
index 5c2535ec9..39e666b45 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
@@ -225,70 +225,4 @@ mod tests {
         assert_eq!(known_migrations(Network::MainNetwork).unwrap(), applied);
         let _ = std::fs::remove_file(&path);
     }
-
-    /// Prints the migrated schema. `storageStats` SQL must follow it: a wrong
-    /// table name silently returns 0 instead of failing. Runs only with
-    /// `ZR_DUMP_SCHEMA=1`.
-    #[test]
-    fn dump_schema() {
-        if std::env::var("ZR_DUMP_SCHEMA")
-            .unwrap_or_default()
-            .is_empty()
-        {
-            return;
-        }
-        let path = std::env::temp_dir().join("zr-schema-dump.sqlite");
-        let _ = std::fs::remove_file(&path);
-        let db = open_and_migrate("test", path.to_str().unwrap()).expect("migrate");
-        drop(db);
-
-        let conn = crate::storage::open_connection(path.to_str().unwrap()).expect("open");
-        let mut stmt = conn
-            .prepare("SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name")
-            .expect("query sqlite_master");
-        let rows: Vec<(String, String)> = stmt
-            .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
-            .expect("iterate rows")
-            .map(|r| r.expect("row"))
-            .collect();
-        // Stats sum BLOB columns, so column names must come from the real schema.
-        for t in [
-            "blocks",
-            "transactions",
-            "sent_notes",
-            "orchard_tree_shards",
-            "orchard_tree_checkpoints",
-            "orchard_tree_retained_checkpoints",
-            "orchard_received_notes",
-            "orchard_ironwood_migrations",
-            "orchard_ironwood_migration_transactions",
-            "nullifier_map",
-            "tx_locator_map",
-            "tx_retrieval_queue",
-            "scan_queue",
-        ] {
-            let mut s = conn
-                .prepare(&format!("PRAGMA table_info({t})"))
-                .expect("table_info");
-            let cols: Vec = s
-                .query_map([], |r| r.get::<_, String>(1))
-                .expect("iterate columns")
-                .map(|r| r.expect("column name"))
-                .collect();
-            println!("-- {t}: {}", cols.join(", "));
-        }
-
-        for kind in ["table", "view", "index", "trigger"] {
-            let names: Vec<&str> = rows
-                .iter()
-                .filter(|(t, _)| t == kind)
-                .map(|(_, n)| n.as_str())
-                .collect();
-            println!("== {kind} ({}) ==", names.len());
-            for n in &names {
-                println!("  {n}");
-            }
-        }
-        let _ = std::fs::remove_file(&path);
-    }
 }
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs b/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs
deleted file mode 100644
index 9a57f46f5..000000000
--- a/chain-runtimes/zcash/crates/zcash-runtime/tests/scan_repro.rs
+++ /dev/null
@@ -1,307 +0,0 @@
-//! Runs the browser scan flow natively, where a debugger and `sample` are available.
-//!
-//! Needs network, so `#[ignore]` by default. Run with:
-//!
-//! ```bash
-//! cargo test -p onekey-zcash-runtime --test scan_repro -- --ignored --nocapture
-//! # If it hangs, from another terminal:
-//! #   sample  5 -f /tmp/scan.txt     # macOS
-//! ```
-
-use onekey_zcash_runtime::{account, network, sync, wallet};
-
-// Native gRPC endpoint. The chainsafe endpoint is a gRPC-web proxy that native
-// clients cannot use; zec.rocks is the reverse.
-const LWD: &str = "https://testnet.zec.rocks:443";
-
-/// Alice's testnet UFVK, a public test vector. Never use for real funds.
-const ALICE_UFVK: &str = "uviewtest1eacc7lytmvgp0sshwjjv4qsg9fnewq00s6zye8hqwndpdsg0tum2ft4k96t86eapddpq56exfycnxnlds75vvpydv8fgj4cecczkmt3rjat8qjfqrk2cdlm9alep2z04785sx6yekqjk6wywkttlthld4c3xmg8fvneg4p97vzxwu9xtuh0xrgfy90p6uuxf8cwl8nxfq6hlte0nnylk59xceldrkx9vge3k4utkue2txu5kpp60aw07q0f0jgp0pv2c0gr7jdm6273uxyskt72jehte5jf2dg94d84le08h2t5rhd93j2d98ja59h46est69f3a7rav7k6744p2u8dxasc7nr9p2k95x7uaknahj0kw7mu5zq9nllj7x2qswq3jswsuzwms7shv7dhxz9s4yudatwu3u3v3wqznkhu6jt7xt8whjh3dkzvsf28p6mj8tya009gwzgszz2at8alquu8y0fmqt7klayrjx7n3ulml5q00fgdr";
-
-async fn scan_with_batch(batch_size: u32) {
-    let db_name = format!("/tmp/zcash-repro-{batch_size}.sqlite");
-    let _ = std::fs::remove_file(&db_name);
-
-    let mut db = wallet::open_and_migrate("test", &db_name).expect("open wallet");
-    let mut client = network::connect_native(LWD)
-        .await
-        .expect("connect to lightwalletd");
-
-    let tip = network::chain_tip(&mut client).await.expect("chain tip");
-    println!("tip = {tip}");
-
-    let uuid = account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 200, None)
-        .await
-        .expect("import account");
-    println!("account = {uuid}");
-
-    let prep = sync::prepare(&mut db, &mut client).await.expect("prepare");
-    println!("prepare = {prep}");
-
-    println!("peek = {}", sync::peek(&db).expect("peek"));
-
-    let t0 = std::time::Instant::now();
-    println!("starting syncStep(batch_size={batch_size}, max_batches=1) …");
-    let out = sync::step(
-        &mut db,
-        &mut client,
-        batch_size,
-        1,
-        None,
-        &[ALICE_UFVK.to_owned()],
-    )
-    .await
-    .expect("scan");
-    println!("elapsed {:?}  result {out}", t0.elapsed());
-}
-
-#[tokio::test(flavor = "multi_thread")]
-#[ignore = "requires network"]
-async fn scan_batch_10() {
-    scan_with_batch(10).await;
-}
-
-/// A native hang points at upstream scanning; a pass points at wasm or the
-/// storage layer.
-#[tokio::test(flavor = "multi_thread")]
-#[ignore = "requires network"]
-async fn scan_batch_25() {
-    scan_with_batch(25).await;
-}
-
-#[tokio::test(flavor = "multi_thread")]
-#[ignore = "requires network"]
-async fn scan_batch_100() {
-    scan_with_batch(100).await;
-}
-
-/// Scans from a given height (the other tests start at tip-200 / tip-2000).
-///
-/// Usage (height and batch size are overridable):
-/// ```bash
-/// ZR_FROM=4292840 ZR_BATCH=20 cargo test -p onekey-zcash-runtime \
-///   --test scan_repro scan_from_height -- --ignored --nocapture
-/// ```
-#[tokio::test(flavor = "multi_thread")]
-#[ignore = "requires network"]
-async fn scan_from_height() {
-    let from: u32 = std::env::var("ZR_FROM")
-        .ok()
-        .and_then(|v| v.parse().ok())
-        .unwrap_or(4292840);
-    let batch: u32 = std::env::var("ZR_BATCH")
-        .ok()
-        .and_then(|v| v.parse().ok())
-        .unwrap_or(20);
-
-    let db_name = format!("/tmp/zcash-from-{from}.sqlite");
-    let _ = std::fs::remove_file(&db_name);
-
-    let mut db = wallet::open_and_migrate("test", &db_name).expect("open wallet");
-    let mut client = network::connect_native(LWD)
-        .await
-        .expect("connect to lightwalletd");
-    let tip = network::chain_tip(&mut client).await.expect("chain tip");
-    println!("tip = {tip}, scanning {batch} blocks from {from}");
-
-    account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, from, None)
-        .await
-        .expect("import account");
-    sync::prepare(&mut db, &mut client).await.expect("prepare");
-    println!("peek = {}", sync::peek(&db).expect("peek"));
-
-    let t0 = std::time::Instant::now();
-    let out = sync::step(
-        &mut db,
-        &mut client,
-        batch,
-        1,
-        None,
-        &[ALICE_UFVK.to_owned()],
-    )
-    .await
-    .expect("scan");
-    println!("elapsed {:?}  result {out}", t0.elapsed());
-}
-
-/// Native scan time by batch size. Nonlinear here means an algorithmic issue to
-/// profile natively; linear means the browser slowdown is wasm-specific.
-#[tokio::test(flavor = "multi_thread")]
-#[ignore = "requires network"]
-async fn scan_batch_curve() {
-    for batch in [25u32, 100, 400, 1000] {
-        let db_name = format!("/tmp/zcash-curve-{batch}.sqlite");
-        let _ = std::fs::remove_file(&db_name);
-
-        let mut db = wallet::open_and_migrate("test", &db_name).expect("open wallet");
-        let mut client = network::connect_native(LWD)
-            .await
-            .expect("connect to lightwalletd");
-        let tip = network::chain_tip(&mut client).await.expect("chain tip");
-
-        account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 2000, None)
-            .await
-            .expect("import account");
-        sync::prepare(&mut db, &mut client).await.expect("prepare");
-
-        let t0 = std::time::Instant::now();
-        let out = sync::step(
-            &mut db,
-            &mut client,
-            batch,
-            1,
-            None,
-            &[ALICE_UFVK.to_owned()],
-        )
-        .await
-        .expect("scan");
-        println!("batch {batch:>5}  total {:>10?}  {out}", t0.elapsed());
-    }
-}
-
-/// Advances one block at a time, 40 times.
-/// A native stall points at block content; a full run points at wasm.
-#[tokio::test(flavor = "multi_thread")]
-#[ignore = "requires network"]
-async fn scan_one_by_one() {
-    let db_name = "/tmp/zcash-repro-onebyone.sqlite";
-    let _ = std::fs::remove_file(db_name);
-
-    let mut db = wallet::open_and_migrate("test", db_name).expect("open wallet");
-    let mut client = network::connect_native(LWD)
-        .await
-        .expect("connect to lightwalletd");
-    let tip = network::chain_tip(&mut client).await.expect("chain tip");
-    println!("tip = {tip}");
-
-    account::import_ufvk(&mut db, &mut client, "alice", ALICE_UFVK, tip - 200, None)
-        .await
-        .expect("import account");
-    sync::prepare(&mut db, &mut client).await.expect("prepare");
-
-    for i in 0..40 {
-        let peek: serde_json::Value =
-            serde_json::from_str(&sync::peek(&db).expect("peek")).unwrap();
-        let height = peek["ranges"][0]["start"].as_u64();
-        let t0 = std::time::Instant::now();
-        let out = sync::step(&mut db, &mut client, 1, 1, None, &[ALICE_UFVK.to_owned()])
-            .await
-            .expect("scan");
-        println!("#{i} h={height:?} {:?} {out}", t0.elapsed());
-    }
-}
-
-/// Prints block structure summaries for field-by-field comparison with the browser.
-///
-/// ```bash
-/// ZR_FROM=4292845 ZR_SPAN=3 cargo test -p onekey-zcash-runtime \
-///   --test scan_repro block_summary_at -- --ignored --nocapture
-/// ```
-#[tokio::test(flavor = "multi_thread")]
-#[ignore = "requires network"]
-async fn block_summary_at() {
-    let from: u32 = std::env::var("ZR_FROM")
-        .ok()
-        .and_then(|v| v.parse().ok())
-        .unwrap_or(4292845);
-    let span: u32 = std::env::var("ZR_SPAN")
-        .ok()
-        .and_then(|v| v.parse().ok())
-        .unwrap_or(1);
-
-    let mut client = network::connect_native(LWD)
-        .await
-        .expect("connect to lightwalletd");
-    for h in from..from + span {
-        match network::block_summary(&mut client, h).await {
-            Ok(s) => println!("{s}"),
-            Err(e) => println!("{{\"height\":{h},\"error\":\"{e}\"}}"),
-        }
-    }
-}
-
-/// `accounts.uuid` is a BLOB: measures how many rows a string and a BLOB
-/// binding match.
-#[tokio::test(flavor = "multi_thread")]
-#[ignore = "requires network"]
-async fn uuid_binding_string_vs_blob() {
-    let db_name = "/tmp/zcash-uuid-binding.sqlite";
-    let _ = std::fs::remove_file(db_name);
-
-    let mut db = wallet::open_and_migrate("test", db_name).expect("open wallet");
-    let mut client = network::connect_native(LWD).await.expect("connect");
-    let tip = network::chain_tip(&mut client).await.expect("chain tip");
-    let uuid_str = account::import_ufvk(&mut db, &mut client, "a", ALICE_UFVK, tip - 10, None)
-        .await
-        .expect("import account");
-    println!("listAccounts form: {uuid_str}");
-
-    drop(db);
-    let conn = rusqlite::Connection::open(db_name).expect("open the same database directly");
-    let as_text: i64 = conn
-        .query_row(
-            "SELECT COUNT(*) FROM accounts WHERE uuid = ?1",
-            [&uuid_str],
-            |r| r.get(0),
-        )
-        .unwrap();
-    let bytes = uuid::Uuid::parse_str(&uuid_str).unwrap();
-    let as_blob: i64 = conn
-        .query_row(
-            "SELECT COUNT(*) FROM accounts WHERE uuid = ?1",
-            [bytes.as_bytes().as_slice()],
-            |r| r.get(0),
-        )
-        .unwrap();
-    let total: i64 = conn
-        .query_row("SELECT COUNT(*) FROM accounts", [], |r| r.get(0))
-        .unwrap();
-
-    println!(
-        "accounts total={total}  string binding matched={as_text}  BLOB binding matched={as_blob}"
-    );
-    assert_eq!(total, 1, "exactly one account");
-    assert_eq!(as_blob, 1, "BLOB binding must match");
-    assert_eq!(
-        as_text, 0,
-        "string binding matches nothing, which leaves history empty"
-    );
-}
-
-/// Regression: history must actually match the account.
-///
-/// An empty result looks like an empty wallet, so this compares the row count
-/// from history() with a direct v_transactions query instead of the content.
-#[tokio::test(flavor = "multi_thread")]
-#[ignore = "requires network"]
-async fn history_uuid_actually_matches() {
-    let db_name = "/tmp/zcash-history-uuid.sqlite";
-    let _ = std::fs::remove_file(db_name);
-
-    let mut db = wallet::open_and_migrate("test", db_name).expect("open wallet");
-    let mut client = network::connect_native(LWD).await.expect("connect");
-    let tip = network::chain_tip(&mut client).await.expect("chain tip");
-    let uuid = account::import_ufvk(&mut db, &mut client, "a", ALICE_UFVK, tip - 10, None)
-        .await
-        .expect("import account");
-    drop(db);
-
-    let conn = rusqlite::Connection::open(db_name).expect("open database directly");
-    let via_join: i64 = conn
-        .query_row(
-            "SELECT COUNT(*) FROM v_transactions v
-             JOIN accounts a ON a.uuid = v.account_uuid
-             WHERE a.uuid = ?1",
-            [uuid::Uuid::parse_str(&uuid).unwrap().as_bytes().as_slice()],
-            |r| r.get(0),
-        )
-        .unwrap();
-    let history = onekey_zcash_runtime::history::list(&conn, &uuid, 500, 0).expect("history");
-    let via_api = serde_json::from_str::>(&history)
-        .expect("history JSON")
-        .len();
-    println!("direct={via_join}  history()={via_api}");
-    assert_eq!(
-        via_api as i64, via_join,
-        "history() must match the direct query"
-    );
-}
diff --git a/chain-runtimes/zcash/crates/zcash-storage-benchmark/Cargo.toml b/chain-runtimes/zcash/crates/zcash-storage-benchmark/Cargo.toml
deleted file mode 100644
index 1a7ff9139..000000000
--- a/chain-runtimes/zcash/crates/zcash-storage-benchmark/Cargo.toml
+++ /dev/null
@@ -1,24 +0,0 @@
-[package]
-name = "onekey-zcash-storage-benchmark"
-version.workspace = true
-edition.workspace = true
-license.workspace = true
-rust-version.workspace = true
-description = "Isolated SQLite WASM VFS benchmark for OneKey developer diagnostics"
-
-[lib]
-crate-type = ["cdylib", "rlib"]
-
-[target.'cfg(target_arch = "wasm32")'.dependencies]
-rusqlite.workspace = true
-serde.workspace = true
-serde_json.workspace = true
-sqlite-wasm-rs.workspace = true
-sqlite-wasm-vfs.workspace = true
-wasm-bindgen.workspace = true
-wasm-bindgen-futures.workspace = true
-js-sys.workspace = true
-console_error_panic_hook = "0.1"
-
-[package.metadata.wasm-pack.profile.release]
-wasm-opt = ["-Oz", "--enable-bulk-memory", "--enable-nontrapping-float-to-int"]
diff --git a/chain-runtimes/zcash/crates/zcash-storage-benchmark/build.rs b/chain-runtimes/zcash/crates/zcash-storage-benchmark/build.rs
deleted file mode 100644
index 24d4e2e6b..000000000
--- a/chain-runtimes/zcash/crates/zcash-storage-benchmark/build.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-use std::path::{Path, PathBuf};
-
-fn main() {
-    println!("cargo::rerun-if-changed=build.rs");
-    if !std::env::var("TARGET")
-        .unwrap_or_default()
-        .starts_with("wasm32")
-    {
-        return;
-    }
-
-    let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("Cargo must set OUT_DIR"));
-    let Some(source) = find_wasm_sqlite_archive(&out_dir) else {
-        println!("cargo::warning=sqlite-wasm-rs libwsqlite3.a was not found; linking may fail");
-        return;
-    };
-    let destination = out_dir.join("libsqlite3.a");
-    if let Err(error) = std::fs::copy(&source, &destination) {
-        println!(
-            "cargo::warning=failed to copy {}: {error}",
-            source.display()
-        );
-        return;
-    }
-    println!("cargo::rustc-link-search=native={}", out_dir.display());
-    println!("cargo::rerun-if-changed={}", source.display());
-}
-
-fn find_wasm_sqlite_archive(out_dir: &Path) -> Option {
-    let build_root = out_dir.parent()?.parent()?;
-    for entry in std::fs::read_dir(build_root).ok()? {
-        let Ok(entry) = entry else { continue };
-        if !entry
-            .file_name()
-            .to_string_lossy()
-            .starts_with("sqlite-wasm-rs-")
-        {
-            continue;
-        }
-        let candidate = entry.path().join("out").join("libwsqlite3.a");
-        if candidate.is_file() {
-            return Some(candidate);
-        }
-    }
-    None
-}
diff --git a/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/error.rs b/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/error.rs
deleted file mode 100644
index 40d4eaa52..000000000
--- a/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/error.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-use serde_json::{json, Map, Value};
-use std::fmt;
-use wasm_bindgen::{JsCast, JsValue};
-
-#[derive(Clone, Copy, Debug)]
-pub enum ErrorCode {
-    NotInitialized,
-    InvalidDbName,
-    DatabaseError,
-}
-
-impl ErrorCode {
-    fn as_str(self) -> &'static str {
-        match self {
-            Self::NotInitialized => "NOT_INITIALIZED",
-            Self::InvalidDbName => "INVALID_DB_NAME",
-            Self::DatabaseError => "DATABASE_ERROR",
-        }
-    }
-}
-
-#[derive(Debug)]
-pub struct RuntimeError {
-    code: ErrorCode,
-    params: Value,
-    detail: Option,
-}
-
-impl RuntimeError {
-    pub fn new(code: ErrorCode) -> Self {
-        Self {
-            code,
-            params: Value::Object(Map::new()),
-            detail: None,
-        }
-    }
-
-    pub fn with(code: ErrorCode, params: Value) -> Self {
-        Self {
-            code,
-            params,
-            detail: None,
-        }
-    }
-
-    pub fn detail(mut self, detail: impl fmt::Display) -> Self {
-        self.detail = Some(detail.to_string());
-        self
-    }
-
-    pub fn to_json(&self) -> Value {
-        json!({
-            "code": self.code.as_str(),
-            "params": self.params,
-            "detail": self.detail,
-        })
-    }
-}
-
-impl fmt::Display for RuntimeError {
-    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(formatter, "{} {}", self.code.as_str(), self.params)?;
-        if let Some(detail) = &self.detail {
-            write!(formatter, " :: {detail}")?;
-        }
-        Ok(())
-    }
-}
-
-impl std::error::Error for RuntimeError {}
-
-impl From for RuntimeError {
-    fn from(error: rusqlite::Error) -> Self {
-        Self::with(ErrorCode::DatabaseError, json!({ "operation": "sqlite" })).detail(error)
-    }
-}
-
-impl From for JsValue {
-    fn from(error: RuntimeError) -> Self {
-        let js_error = js_sys::Error::new(error.code.as_str());
-        let object: &js_sys::Object = js_error.as_ref();
-        let _ = js_sys::Reflect::set(
-            object,
-            &JsValue::from_str("code"),
-            &JsValue::from_str(error.code.as_str()),
-        );
-        let _ = js_sys::Reflect::set(
-            object,
-            &JsValue::from_str("params"),
-            &js_sys::JSON::parse(&error.params.to_string())
-                .unwrap_or_else(|_| js_sys::Object::new().into()),
-        );
-        if let Some(detail) = error.detail {
-            let _ = js_sys::Reflect::set(
-                object,
-                &JsValue::from_str("detail"),
-                &JsValue::from_str(&detail),
-            );
-        }
-        js_error.unchecked_into()
-    }
-}
-
-pub type Result = std::result::Result;
diff --git a/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/lib.rs b/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/lib.rs
deleted file mode 100644
index 765bd6d84..000000000
--- a/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/lib.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-//! A small diagnostic WASM package for comparing browser SQLite VFS backends.
-//!
-//! It is separate from the wallet runtime so a benchmark Worker does not
-//! duplicate Zcash proving and scanning code in production bundles.
-
-#[cfg(target_arch = "wasm32")]
-mod error;
-#[cfg(target_arch = "wasm32")]
-mod storage_benchmark;
-
-#[cfg(target_arch = "wasm32")]
-use wasm_bindgen::prelude::*;
-
-#[cfg(target_arch = "wasm32")]
-#[wasm_bindgen(js_name = runStorageBenchmark)]
-pub async fn run_storage_benchmark(request_json: &str) -> Result {
-    console_error_panic_hook::set_once();
-    Ok(storage_benchmark::run(request_json).await?)
-}
diff --git a/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/storage_benchmark.rs b/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/storage_benchmark.rs
deleted file mode 100644
index ca321a1e7..000000000
--- a/chain-runtimes/zcash/crates/zcash-storage-benchmark/src/storage_benchmark.rs
+++ /dev/null
@@ -1,589 +0,0 @@
-//! Isolated browser-storage benchmark for the developer Gallery.
-//!
-//! This is intentionally not a wallet abstraction. It owns a fixed synthetic
-//! schema, exposes a small fixed action enum, and rejects every database name
-//! outside the benchmark prefix. Product code must not depend on these APIs.
-
-use std::{cell::RefCell, collections::BTreeMap, rc::Rc};
-
-use rusqlite::{params, Connection, OpenFlags};
-use serde::{Deserialize, Serialize};
-use serde_json::{json, Value};
-use sqlite_wasm_vfs::{
-    relaxed_idb::{install as install_relaxed_idb, Preload, RelaxedIdbCfg, RelaxedIdbUtil},
-    sahpool::{install as install_sahpool, OpfsSAHPoolCfg, OpfsSAHPoolUtil},
-};
-
-use crate::error::{ErrorCode, Result, RuntimeError};
-
-const DATABASE_PREFIX: &str = "onekey-zcash-storage-bench-";
-const RELAXED_VFS_NAME: &str = "onekey-zcash-benchmark-relaxed-idb";
-const SAHPOOL_VFS_NAME: &str = "onekey-zcash-benchmark-opfs-sahpool";
-const SAHPOOL_DIRECTORY: &str = ".onekey-zcash-benchmark-opfs-sahpool";
-const SAHPOOL_CAPACITY: u32 = 6;
-const MAX_ROWS: u32 = 20_000;
-const MAX_PAYLOAD_BYTES: u32 = 16_384;
-const MAX_BATCH_SIZE: u32 = 2_000;
-const MAX_WRITER_ID: u32 = 1_000;
-
-thread_local! {
-    static RELAXED_UTIL: RefCell>> = const { RefCell::new(None) };
-    static SAHPOOL_UTIL: RefCell>> = const { RefCell::new(None) };
-}
-
-#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub enum BenchmarkBackend {
-    RelaxedIdb,
-    OpfsSahpool,
-}
-
-impl BenchmarkBackend {
-    fn vfs_name(self) -> &'static str {
-        match self {
-            Self::RelaxedIdb => RELAXED_VFS_NAME,
-            Self::OpfsSahpool => SAHPOOL_VFS_NAME,
-        }
-    }
-}
-
-#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
-#[serde(rename_all = "camelCase")]
-pub enum BenchmarkAction {
-    Probe,
-    Replace,
-    Append,
-    Verify,
-    Mutate,
-    Cleanup,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
-pub struct BenchmarkRequest {
-    backend: BenchmarkBackend,
-    action: BenchmarkAction,
-    database_name: String,
-    #[serde(default)]
-    row_count: u32,
-    #[serde(default = "default_payload_bytes")]
-    payload_bytes: u32,
-    #[serde(default = "default_batch_size")]
-    batch_size: u32,
-    #[serde(default)]
-    writer_id: u32,
-}
-
-fn default_payload_bytes() -> u32 {
-    1_024
-}
-
-fn default_batch_size() -> u32 {
-    64
-}
-
-pub async fn run(request_json: &str) -> Result {
-    let request: BenchmarkRequest = serde_json::from_str(request_json).map_err(|e| {
-        RuntimeError::with(
-            ErrorCode::DatabaseError,
-            json!({ "operation": "storageBenchmarkConfig" }),
-        )
-        .detail(e)
-    })?;
-    validate_request(&request)?;
-
-    let started = now_ms();
-    let mut timings = BTreeMap::<&str, f64>::new();
-    let memory_start = wasm_memory_bytes();
-
-    let install_started = now_ms();
-    let install_result = install_backend(request.backend).await;
-    timings.insert("install", elapsed(install_started));
-
-    if request.action == BenchmarkAction::Probe {
-        return Ok(match install_result {
-            Ok(()) => json!({
-                "backend": request.backend,
-                "action": request.action,
-                "databaseName": request.database_name,
-                "supported": true,
-                "vfsName": request.backend.vfs_name(),
-                "timingsMs": timings,
-                "memoryBytes": {
-                    "start": memory_start,
-                    "afterAction": wasm_memory_bytes(),
-                },
-                "totalMs": elapsed(started),
-            }),
-            Err(error) => json!({
-                "backend": request.backend,
-                "action": request.action,
-                "databaseName": request.database_name,
-                "supported": false,
-                "vfsName": request.backend.vfs_name(),
-                "timingsMs": timings,
-                "memoryBytes": {
-                    "start": memory_start,
-                    "afterAction": wasm_memory_bytes(),
-                },
-                "error": error.to_json(),
-                "totalMs": elapsed(started),
-            }),
-        }
-        .to_string());
-    }
-    install_result?;
-
-    if request.action == BenchmarkAction::Cleanup {
-        let cleanup_started = now_ms();
-        let deleted = delete_database(request.backend, &request.database_name).await?;
-        timings.insert("cleanup", elapsed(cleanup_started));
-        return Ok(json!({
-            "backend": request.backend,
-            "action": request.action,
-            "databaseName": request.database_name,
-            "supported": true,
-            "vfsName": request.backend.vfs_name(),
-            "deleted": deleted,
-            "timingsMs": timings,
-            "memoryBytes": {
-                "start": memory_start,
-                "afterAction": wasm_memory_bytes(),
-            },
-            "totalMs": elapsed(started),
-        })
-        .to_string());
-    }
-
-    if request.action == BenchmarkAction::Replace {
-        let cleanup_started = now_ms();
-        let _ = delete_database(request.backend, &request.database_name).await?;
-        timings.insert("cleanup", elapsed(cleanup_started));
-    } else if matches!(request.backend, BenchmarkBackend::RelaxedIdb) {
-        let preload_started = now_ms();
-        relaxed_util()?
-            .preload_db(vec![request.database_name.clone()])
-            .await
-            .map_err(|e| benchmark_error("preload", e))?;
-        timings.insert("preload", elapsed(preload_started));
-    }
-
-    let open_started = now_ms();
-    let mut conn = open_connection(&request)?;
-    timings.insert("open", elapsed(open_started));
-    let memory_after_open = wasm_memory_bytes();
-
-    let schema_started = now_ms();
-    configure_connection(&conn, request.backend)?;
-    if matches!(request.action, BenchmarkAction::Replace) {
-        create_schema(&conn)?;
-    }
-    timings.insert("schema", elapsed(schema_started));
-
-    let mut action_metrics = json!({});
-    match request.action {
-        BenchmarkAction::Replace | BenchmarkAction::Append => {
-            let write_started = now_ms();
-            let batch_latencies = insert_rows(
-                &mut conn,
-                request.writer_id,
-                request.row_count,
-                request.payload_bytes,
-                request.batch_size,
-            )?;
-            let write_ms = elapsed(write_started);
-            timings.insert("write", write_ms);
-            action_metrics = json!({
-                "batchLatencyMs": latency_summary(&batch_latencies),
-                "rowsPerSecond": rate(request.row_count as u64, write_ms),
-                "payloadMiBPerSecond": rate(
-                    request.row_count as u64 * request.payload_bytes as u64,
-                    write_ms,
-                ) / (1024.0 * 1024.0),
-            });
-        }
-        BenchmarkAction::Verify => {}
-        BenchmarkAction::Mutate => {
-            let update_started = now_ms();
-            let updated = conn.execute(
-                "UPDATE benchmark_rows SET generation = generation + 1 WHERE row_index % 5 = 0",
-                [],
-            )?;
-            timings.insert("update", elapsed(update_started));
-
-            let delete_started = now_ms();
-            let deleted = conn.execute("DELETE FROM benchmark_rows WHERE row_index % 7 = 0", [])?;
-            timings.insert("delete", elapsed(delete_started));
-            action_metrics = json!({ "updatedRows": updated, "deletedRows": deleted });
-        }
-        BenchmarkAction::Probe | BenchmarkAction::Cleanup => unreachable!(),
-    }
-
-    let read_started = now_ms();
-    let (data, sample_metrics) = inspect_data(&conn)?;
-    timings.insert("read", elapsed(read_started));
-
-    let integrity_started = now_ms();
-    let integrity = integrity(&conn)?;
-    timings.insert("integrity", elapsed(integrity_started));
-    let sqlite = sqlite_stats(&conn)?;
-    drop(conn);
-
-    Ok(json!({
-        "backend": request.backend,
-        "action": request.action,
-        "databaseName": request.database_name,
-        "supported": true,
-        "vfsName": request.backend.vfs_name(),
-        "workload": {
-            "requestedRows": request.row_count,
-            "payloadBytes": request.payload_bytes,
-            "batchSize": request.batch_size,
-            "writerId": request.writer_id,
-        },
-        "timingsMs": timings,
-        "memoryBytes": {
-            "start": memory_start,
-            "afterOpen": memory_after_open,
-            "afterAction": wasm_memory_bytes(),
-        },
-        "actionMetrics": action_metrics,
-        "sampleMetrics": sample_metrics,
-        "data": data,
-        "integrity": integrity,
-        "sqlite": sqlite,
-        "totalMs": elapsed(started),
-    })
-    .to_string())
-}
-
-fn validate_request(request: &BenchmarkRequest) -> Result<()> {
-    let valid_name = request.database_name.starts_with(DATABASE_PREFIX)
-        && request.database_name.ends_with(".db")
-        && request.database_name.len() <= 120
-        && request
-            .database_name
-            .bytes()
-            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'));
-    if !valid_name {
-        return Err(RuntimeError::with(
-            ErrorCode::InvalidDbName,
-            json!({ "value": request.database_name }),
-        ));
-    }
-    if request.row_count > MAX_ROWS
-        || request.payload_bytes == 0
-        || request.payload_bytes > MAX_PAYLOAD_BYTES
-        || request.batch_size == 0
-        || request.batch_size > MAX_BATCH_SIZE
-        || request.writer_id > MAX_WRITER_ID
-    {
-        return Err(RuntimeError::with(
-            ErrorCode::DatabaseError,
-            json!({
-                "operation": "storageBenchmarkConfig",
-                "rowCount": request.row_count,
-                "payloadBytes": request.payload_bytes,
-                "batchSize": request.batch_size,
-                "writerId": request.writer_id,
-            }),
-        ));
-    }
-    Ok(())
-}
-
-async fn install_backend(backend: BenchmarkBackend) -> Result<()> {
-    use sqlite_wasm_rs as ffi;
-
-    match backend {
-        BenchmarkBackend::RelaxedIdb => {
-            let cfg = RelaxedIdbCfg {
-                vfs_name: RELAXED_VFS_NAME.to_owned(),
-                clear_on_init: false,
-                preload: Preload::None,
-            };
-            let util = install_relaxed_idb::(&cfg, false)
-                .await
-                .map_err(|e| benchmark_error("installRelaxedIdb", e))?;
-            RELAXED_UTIL.with(|slot| *slot.borrow_mut() = Some(Rc::new(util)));
-        }
-        BenchmarkBackend::OpfsSahpool => {
-            let cfg = OpfsSAHPoolCfg {
-                vfs_name: SAHPOOL_VFS_NAME.to_owned(),
-                directory: SAHPOOL_DIRECTORY.to_owned(),
-                clear_on_init: false,
-                initial_capacity: SAHPOOL_CAPACITY,
-            };
-            let util = install_sahpool::(&cfg, false)
-                .await
-                .map_err(|e| benchmark_error("installOpfsSahpool", e))?;
-            util.reserve_minimum_capacity(SAHPOOL_CAPACITY)
-                .await
-                .map_err(|e| benchmark_error("reserveOpfsSahpool", e))?;
-            SAHPOOL_UTIL.with(|slot| *slot.borrow_mut() = Some(Rc::new(util)));
-        }
-    }
-    Ok(())
-}
-
-fn relaxed_util() -> Result> {
-    RELAXED_UTIL
-        .with(|slot| slot.borrow().clone())
-        .ok_or_else(|| {
-            RuntimeError::with(
-                ErrorCode::NotInitialized,
-                json!({ "reason": "benchmarkRelaxedVfsNotInstalled" }),
-            )
-        })
-}
-
-fn sahpool_util() -> Result> {
-    SAHPOOL_UTIL
-        .with(|slot| slot.borrow().clone())
-        .ok_or_else(|| {
-            RuntimeError::with(
-                ErrorCode::NotInitialized,
-                json!({ "reason": "benchmarkSahpoolVfsNotInstalled" }),
-            )
-        })
-}
-
-async fn delete_database(backend: BenchmarkBackend, database_name: &str) -> Result {
-    match backend {
-        BenchmarkBackend::RelaxedIdb => {
-            let util = relaxed_util()?;
-            util.preload_db(vec![database_name.to_owned()])
-                .await
-                .map_err(|e| benchmark_error("preloadForDelete", e))?;
-            if !util.exists(database_name) {
-                return Ok(false);
-            }
-            util.delete_db(database_name)
-                .map_err(|e| benchmark_error("deleteRelaxedIdb", e))?
-                .await
-                .map_err(|e| benchmark_error("commitDeleteRelaxedIdb", e))?;
-            Ok(true)
-        }
-        BenchmarkBackend::OpfsSahpool => sahpool_util()?
-            .delete_db(database_name)
-            .map_err(|e| benchmark_error("deleteOpfsSahpool", e)),
-    }
-}
-
-fn open_connection(request: &BenchmarkRequest) -> Result {
-    let mut flags = OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_URI;
-    if request.action == BenchmarkAction::Replace {
-        flags |= OpenFlags::SQLITE_OPEN_CREATE;
-    }
-    Connection::open_with_flags_and_vfs(&request.database_name, flags, request.backend.vfs_name())
-        .map_err(|e| benchmark_error("open", e))
-}
-
-fn configure_connection(conn: &Connection, backend: BenchmarkBackend) -> Result<()> {
-    conn.execute_batch("PRAGMA foreign_keys = ON; PRAGMA journal_mode = DELETE;")?;
-    match backend {
-        // relaxed-idb rejects every synchronous level except OFF. Keeping this
-        // explicit makes the durability difference visible in the result.
-        BenchmarkBackend::RelaxedIdb => conn.execute_batch("PRAGMA synchronous = OFF;")?,
-        BenchmarkBackend::OpfsSahpool => conn.execute_batch("PRAGMA synchronous = FULL;")?,
-    }
-    Ok(())
-}
-
-fn create_schema(conn: &Connection) -> Result<()> {
-    conn.execute_batch(
-        "CREATE TABLE benchmark_rows (
-           writer_id INTEGER NOT NULL,
-           row_index INTEGER NOT NULL,
-           generation INTEGER NOT NULL,
-           payload BLOB NOT NULL,
-           checksum INTEGER NOT NULL,
-           PRIMARY KEY (writer_id, row_index)
-         ) WITHOUT ROWID;",
-    )?;
-    Ok(())
-}
-
-fn insert_rows(
-    conn: &mut Connection,
-    writer_id: u32,
-    row_count: u32,
-    payload_bytes: u32,
-    batch_size: u32,
-) -> Result> {
-    let mut latencies = Vec::new();
-    let mut payload = vec![0u8; payload_bytes as usize];
-    let mut start = 0;
-    while start < row_count {
-        let batch_started = now_ms();
-        let end = (start + batch_size).min(row_count);
-        let tx = conn.transaction()?;
-        {
-            let mut statement = tx.prepare(
-                "INSERT OR REPLACE INTO benchmark_rows
-                 (writer_id, row_index, generation, payload, checksum)
-                 VALUES (?1, ?2, 0, ?3, ?4)",
-            )?;
-            for row_index in start..end {
-                fill_payload(&mut payload, writer_id, row_index);
-                let checksum = payload_checksum(&payload);
-                statement.execute(params![writer_id, row_index, &payload, checksum])?;
-            }
-        }
-        tx.commit()?;
-        latencies.push(elapsed(batch_started));
-        start = end;
-    }
-    Ok(latencies)
-}
-
-fn inspect_data(conn: &Connection) -> Result<(Value, Value)> {
-    let (rows, payload_bytes, checksum_sum, generation_sum, writers): (i64, i64, i64, i64, i64) =
-        conn.query_row(
-            "SELECT COUNT(*),
-                COALESCE(SUM(length(payload)), 0),
-                COALESCE(SUM(checksum), 0),
-                COALESCE(SUM(generation), 0),
-                COUNT(DISTINCT writer_id)
-         FROM benchmark_rows",
-            [],
-            |row| {
-                Ok((
-                    row.get(0)?,
-                    row.get(1)?,
-                    row.get(2)?,
-                    row.get(3)?,
-                    row.get(4)?,
-                ))
-            },
-        )?;
-
-    let sample_count = rows.clamp(0, 128);
-    let mut mismatches = 0i64;
-    let mut read_latencies = Vec::with_capacity(sample_count as usize);
-    for sample in 0..sample_count {
-        let offset = if sample_count <= 1 {
-            0
-        } else {
-            sample * (rows - 1) / (sample_count - 1)
-        };
-        let read_started = now_ms();
-        let (writer_id, row_index, payload, stored_checksum): (u32, u32, Vec, u32) = conn
-            .query_row(
-                "SELECT writer_id, row_index, payload, checksum
-                 FROM benchmark_rows
-                 ORDER BY writer_id, row_index
-                 LIMIT 1 OFFSET ?1",
-                [offset],
-                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
-            )?;
-        read_latencies.push(elapsed(read_started));
-        let mut expected = vec![0u8; payload.len()];
-        fill_payload(&mut expected, writer_id, row_index);
-        if payload != expected || payload_checksum(&payload) != stored_checksum {
-            mismatches += 1;
-        }
-    }
-
-    Ok((
-        json!({
-            "rowCount": rows,
-            "payloadBytes": payload_bytes,
-            "checksumSum": checksum_sum,
-            "generationSum": generation_sum,
-            "writerCount": writers,
-        }),
-        json!({
-            "checkedRows": sample_count,
-            "mismatches": mismatches,
-            "readLatencyMs": latency_summary(&read_latencies),
-        }),
-    ))
-}
-
-fn integrity(conn: &Connection) -> Result {
-    let mut statement = conn.prepare("PRAGMA quick_check(10)")?;
-    let messages = statement
-        .query_map([], |row| row.get::<_, String>(0))?
-        .collect::, _>>()?;
-    let quick_check_ok = messages.len() == 1 && messages.first().is_some_and(|v| v == "ok");
-    let foreign_key_violations: i64 =
-        conn.query_row("SELECT COUNT(*) FROM pragma_foreign_key_check", [], |row| {
-            row.get(0)
-        })?;
-    Ok(json!({
-        "quickCheckOk": quick_check_ok,
-        "messages": messages,
-        "foreignKeyViolations": foreign_key_violations,
-    }))
-}
-
-fn sqlite_stats(conn: &Connection) -> Result {
-    let page_size: i64 = conn.query_row("PRAGMA page_size", [], |row| row.get(0))?;
-    let page_count: i64 = conn.query_row("PRAGMA page_count", [], |row| row.get(0))?;
-    let free_pages: i64 = conn.query_row("PRAGMA freelist_count", [], |row| row.get(0))?;
-    let journal_mode: String = conn.query_row("PRAGMA journal_mode", [], |row| row.get(0))?;
-    let synchronous: i64 = conn.query_row("PRAGMA synchronous", [], |row| row.get(0))?;
-    Ok(json!({
-        "pageSize": page_size,
-        "pageCount": page_count,
-        "freePages": free_pages,
-        "logicalBytes": page_size * page_count,
-        "journalMode": journal_mode,
-        "synchronous": synchronous,
-    }))
-}
-
-fn fill_payload(payload: &mut [u8], writer_id: u32, row_index: u32) {
-    for (index, byte) in payload.iter_mut().enumerate() {
-        *byte = ((index as u32 * 31 + row_index * 17 + writer_id * 13) % 251) as u8;
-    }
-}
-
-fn payload_checksum(payload: &[u8]) -> u32 {
-    payload.iter().fold(2_166_136_261u32, |hash, byte| {
-        (hash ^ u32::from(*byte)).wrapping_mul(16_777_619)
-    })
-}
-
-fn latency_summary(values: &[f64]) -> Value {
-    if values.is_empty() {
-        return json!({ "count": 0, "p50": 0.0, "p95": 0.0, "max": 0.0 });
-    }
-    let mut sorted = values.to_vec();
-    sorted.sort_by(f64::total_cmp);
-    let percentile = |p: f64| {
-        let index = ((sorted.len() - 1) as f64 * p).round() as usize;
-        sorted[index]
-    };
-    json!({
-        "count": sorted.len(),
-        "p50": percentile(0.50),
-        "p95": percentile(0.95),
-        "max": sorted[sorted.len() - 1],
-    })
-}
-
-fn benchmark_error(operation: &'static str, error: impl std::fmt::Debug) -> RuntimeError {
-    RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": operation }))
-        .detail(format!("{error:?}"))
-}
-
-fn now_ms() -> f64 {
-    js_sys::Date::now()
-}
-
-fn elapsed(started: f64) -> f64 {
-    (now_ms() - started).max(0.0)
-}
-
-fn rate(units: u64, duration_ms: f64) -> f64 {
-    if duration_ms <= 0.0 {
-        return 0.0;
-    }
-    units as f64 * 1_000.0 / duration_ms
-}
-
-fn wasm_memory_bytes() -> u64 {
-    core::arch::wasm32::memory_size(0) as u64 * 65_536
-}
diff --git a/chain-runtimes/zcash/scripts/artifact-manifest.py b/chain-runtimes/zcash/scripts/artifact-manifest.py
index ef184e736..5d62db06e 100644
--- a/chain-runtimes/zcash/scripts/artifact-manifest.py
+++ b/chain-runtimes/zcash/scripts/artifact-manifest.py
@@ -10,11 +10,7 @@
 
 ROOT = Path(__file__).resolve().parent.parent
 MANIFEST = "zcash-wasm-manifest.json"
-PACKAGES = {
-    "pkg": "onekey_zcash_runtime",
-    "pkg-keys": "onekey_zcash_keys",
-    "pkg/storage-benchmark": "onekey_zcash_storage_benchmark",
-}
+PACKAGES = {"pkg": "onekey_zcash_runtime", "pkg-keys": "onekey_zcash_keys"}
 
 
 def digest(path):
diff --git a/chain-runtimes/zcash/scripts/build-wasm.sh b/chain-runtimes/zcash/scripts/build-wasm.sh
index 4a0754c06..3f4ed673c 100755
--- a/chain-runtimes/zcash/scripts/build-wasm.sh
+++ b/chain-runtimes/zcash/scripts/build-wasm.sh
@@ -71,15 +71,11 @@ esac
 echo "==> Artifacts"
 ls -lh "${OUT}"/*.wasm | awk '{print "   ", $9, $5}'
 
-echo "==> Building storage benchmark"
-(cd "${ROOT}/crates/zcash-storage-benchmark" && \
-  rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${ROOT}/pkg/storage-benchmark" --release)
-
 # Always rebuild the keys package too, so the host never pairs a fresh runtime
 # with a stale keys build.
 echo "==> Building onekey-zcash-keys"
 (cd "${ROOT}/crates/zcash-keys-runtime" && rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${ROOT}/pkg-keys" --release)
-echo "Artifacts: $(du -h "${ROOT}"/pkg/*.wasm "${ROOT}"/pkg-keys/*.wasm "${ROOT}"/pkg/storage-benchmark/*.wasm | tr '\n' ' ')"
+echo "Artifacts: $(du -h "${ROOT}"/pkg/*.wasm "${ROOT}"/pkg-keys/*.wasm | tr '\n' ' ')"
 
 if [ "${OUT}" = "${ROOT}/pkg" ]; then
   python3 "${ROOT}/scripts/package-release.py" prepare
diff --git a/chain-runtimes/zcash/scripts/package-release.py b/chain-runtimes/zcash/scripts/package-release.py
index ec5b7a68f..a7edab4ba 100644
--- a/chain-runtimes/zcash/scripts/package-release.py
+++ b/chain-runtimes/zcash/scripts/package-release.py
@@ -39,13 +39,6 @@ def prepare(root):
             raise ValueError(f"Rebuild both WASM packages: {directory} version mismatch")
         module = name.replace("-", "_")
         package["files"] = [f"{module}.js", f"{module}.d.ts", f"{module}_bg.wasm", "LICENSE"]
-        if directory == "pkg":
-            benchmark = json.loads((target / "storage-benchmark/package.json").read_text())
-            if benchmark["version"] != release_version:
-                raise ValueError("Rebuild the storage benchmark with the same version")
-            # wasm-pack's nested ignore-all file otherwise excludes these npm files.
-            (target / "storage-benchmark/.gitignore").unlink(missing_ok=True)
-            package["files"].append("storage-benchmark")
         if (target / "snippets").exists():
             package["files"].append("snippets")
         package["repository"] = {
@@ -73,9 +66,8 @@ def verify_tarball(archive, source, name, release_version):
         required = {"package.json", "LICENSE"}
         module = name.replace("-", "_")
         required.update({f"{module}.js", f"{module}.d.ts", f"{module}_bg.wasm"})
-        for directory in ("snippets", "storage-benchmark"):
-            required.update(p.relative_to(source).as_posix() for p in (source / directory).rglob("*")
-                            if p.is_file() and p.name != ".gitignore")
+        required.update(p.relative_to(source).as_posix() for p in (source / "snippets").rglob("*")
+                        if p.is_file() and p.name != ".gitignore")
         if not required.issubset(files):
             raise ValueError(f"npm archive is incomplete: {sorted(required - files.keys())}")
         for relative, content in files.items():
diff --git a/chain-runtimes/zcash/scripts/test_artifact_manifest.py b/chain-runtimes/zcash/scripts/test_artifact_manifest.py
index 17bfcb500..6d8e92d24 100644
--- a/chain-runtimes/zcash/scripts/test_artifact_manifest.py
+++ b/chain-runtimes/zcash/scripts/test_artifact_manifest.py
@@ -25,7 +25,7 @@ def test_lockfile_drift_is_rejected(self):
                 with self.assertRaisesRegex(ValueError, "Cargo.lock checksum"):
                     artifact.verify(root, "revision")
 
-    def test_all_three_packages_and_exact_inventory_are_required(self):
+    def test_both_packages_and_exact_inventory_are_required(self):
         with tempfile.TemporaryDirectory() as directory:
             root = Path(directory)
             for package, module in artifact.PACKAGES.items():
@@ -34,8 +34,8 @@ def test_all_three_packages_and_exact_inventory_are_required(self):
                 for name in ("package.json", f"{module}.js", f"{module}.d.ts", f"{module}_bg.wasm"):
                     (target / name).write_text("synthetic artifact")
             files = artifact.artifact_files(root)
-            self.assertEqual(len(files), 12)
-            path = root / "pkg/storage-benchmark/onekey_zcash_storage_benchmark_bg.wasm"
+            self.assertEqual(len(files), 8)
+            path = root / "pkg-keys/onekey_zcash_keys_bg.wasm"
             path.unlink()
             with self.assertRaisesRegex(ValueError, "Incomplete artifact"):
                 artifact.artifact_files(root)
diff --git a/chain-runtimes/zcash/scripts/test_package_release.py b/chain-runtimes/zcash/scripts/test_package_release.py
index c83f5e65f..704bddeea 100644
--- a/chain-runtimes/zcash/scripts/test_package_release.py
+++ b/chain-runtimes/zcash/scripts/test_package_release.py
@@ -13,7 +13,7 @@
 
 
 class PackageReleaseTests(unittest.TestCase):
-    def test_prepare_preserves_benchmark_and_rejects_mixed_versions(self):
+    def test_prepare_writes_metadata_and_rejects_mixed_versions(self):
         with tempfile.TemporaryDirectory() as directory:
             root = Path(directory)
             (root / "Cargo.toml").write_text('[workspace.package]\nversion = "0.1.0-rc.1"\n')
@@ -22,17 +22,15 @@ def test_prepare_preserves_benchmark_and_rejects_mixed_versions(self):
                 target = root / package
                 target.mkdir()
                 (target / "package.json").write_text(json.dumps({"name": name, "version": "0.1.0-rc.1"}))
-            benchmark = root / "pkg/storage-benchmark"
-            benchmark.mkdir()
-            (benchmark / ".gitignore").write_text("*\n")
-            (benchmark / "package.json").write_text(json.dumps({"version": "0.1.0-rc.1"}))
             release.prepare(root)
-            self.assertFalse((benchmark / ".gitignore").exists())
             package = json.loads((root / "pkg/package.json").read_text())
-            self.assertIn("storage-benchmark", package["files"])
+            self.assertEqual(package["files"], [
+                "onekey_zcash_runtime.js", "onekey_zcash_runtime.d.ts", "onekey_zcash_runtime_bg.wasm", "LICENSE",
+            ])
             self.assertEqual((root / "pkg-keys/LICENSE").read_text(), "license")
-            (benchmark / "package.json").write_text(json.dumps({"version": "0.0.1"}))
-            with self.assertRaisesRegex(ValueError, "same version"):
+            (root / "pkg-keys/package.json").write_text(
+                json.dumps({"name": "onekey-zcash-keys", "version": "0.0.1"}))
+            with self.assertRaisesRegex(ValueError, "version mismatch"):
                 release.prepare(root)
 
     def test_prereleases_cannot_update_latest(self):
@@ -45,7 +43,7 @@ def test_prereleases_cannot_update_latest(self):
         with self.assertRaises(ValueError):
             release.check_version("0.1.0-rc.1", "0.1.0-rc.2", "next")
 
-    def test_missing_benchmark_and_changed_bytes_are_rejected(self):
+    def test_missing_snippets_and_changed_bytes_are_rejected(self):
         with tempfile.TemporaryDirectory() as directory:
             root = Path(directory)
             name = "onekey-zcash-runtime"
@@ -56,7 +54,7 @@ def test_missing_benchmark_and_changed_bytes_are_rejected(self):
                 f"{module}.js": b"javascript",
                 f"{module}.d.ts": b"types",
                 f"{module}_bg.wasm": b"wasm",
-                "storage-benchmark/benchmark.js": b"benchmark",
+                "snippets/helper.js": b"snippet",
             }
             for path, data in files.items():
                 target = root / path
@@ -73,7 +71,7 @@ def pack(contents):
 
             pack(files)
             release.verify_tarball(archive, root, name, "0.1.0-rc.1")
-            pack({k: v for k, v in files.items() if not k.startswith("storage-benchmark/")})
+            pack({k: v for k, v in files.items() if not k.startswith("snippets/")})
             with self.assertRaisesRegex(ValueError, "incomplete"):
                 release.verify_tarball(archive, root, name, "0.1.0-rc.1")
             pack({**files, f"{module}.js": b"changed"})

From 9cc48c32701903182e4e6d671907a3e68acd6403 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Thu, 22 Oct 2026 09:53:10 +0800
Subject: [PATCH 71/97] fix(zcash): name the address an output actually paid in
 history

Upstream can store a wallet address-table UA for an output, and
delete_account rewrites payments to a removed account the same way, so
history showed a UA wrapping the real recipient. A transparent output is
now named by its t-address, and a shielded one by its Orchard-only UA
when the tx was scanned or the stored UA is the wallet's Orchard+P2PKH
shape. The recipient pick is also ordered.
---
 .../zcash/crates/zcash-runtime/src/history.rs | 544 +++++++++++++++++-
 1 file changed, 535 insertions(+), 9 deletions(-)

diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
index 25df5054e..77fd3984a 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
@@ -12,6 +12,9 @@
 //! and labelling transactions is up to the host.
 
 use serde_json::json;
+use zcash_address::unified::{self, Container, Encoding};
+use zcash_address::{ConversionError, ToAddress, TryFromAddress, ZcashAddress};
+use zcash_protocol::consensus::NetworkType;
 
 use crate::error::{ErrorCode, Result, RuntimeError};
 
@@ -96,6 +99,7 @@ const HISTORY_ROW_SELECT: &str = "SELECT
             AND (output.to_account_uuid IS NULL
                  OR output.to_account_uuid <> tx_summary.account_uuid)
             AND COALESCE(output.is_change, 0) = 0
+          ORDER BY output.output_pool, output.output_index
           LIMIT 1) AS recipient,
          (SELECT COUNT(*)
             FROM v_tx_outputs output
@@ -104,7 +108,17 @@ const HISTORY_ROW_SELECT: &str = "SELECT
              AND (output.to_account_uuid IS NULL
                   OR output.to_account_uuid <> tx_summary.account_uuid)
              AND COALESCE(output.is_change, 0) = 0
-         ) AS external_output_count
+         ) AS external_output_count,
+         (SELECT output.output_pool
+          FROM v_tx_outputs output
+          WHERE output.txid = tx_summary.txid
+            AND output.from_account_uuid = tx_summary.account_uuid
+            AND (output.to_account_uuid IS NULL
+                 OR output.to_account_uuid <> tx_summary.account_uuid)
+            AND COALESCE(output.is_change, 0) = 0
+          ORDER BY output.output_pool, output.output_index
+          LIMIT 1) AS recipient_pool,
+         chain_tx.created IS NOT NULL AS created_locally
      FROM v_transactions tx_summary
      JOIN transactions chain_tx ON chain_tx.txid = tx_summary.txid
      LEFT JOIN ext_onekey_tx_state rejected
@@ -211,6 +225,10 @@ fn row_to_json(row: &rusqlite::Row<'_>) -> rusqlite::Result {
         .into_iter()
         .map(|(pool, delta)| (pool.to_string(), serde_json::Value::String(delta)))
         .collect::>();
+    let recipient = match (row.get::<_, Option>(16)?, row.get(18)?) {
+        (Some(address), Some(pool)) => Some(paid_address(&address, pool, row.get(19)?)),
+        (address, _) => address,
+    };
     Ok(json!({
         // Display (big-endian) order, as block explorers show it.
         "txid": hex_display_order(&txid),
@@ -237,7 +255,7 @@ fn row_to_json(row: &rusqlite::Row<'_>) -> rusqlite::Result {
         "perPoolBalanceDeltaZat": per_pool_balance_delta_zat,
         // The trusted node definitively rejected it; it can never be mined.
         "rejected": row.get::<_, bool>(15)?,
-        "recipient": row.get::<_, Option>(16)?,
+        "recipient": recipient,
         // Outputs sent to addresses outside this account. Zero with spends means
         // an internal transfer, whether or not the fee is known; inferring from
         // spent - received misreads self-transfers as sends when the fee is unknown.
@@ -302,12 +320,14 @@ pub fn details_outputs(
                 "SELECT output.output_pool, output.value, output.is_change,
                         output.memo, output.to_address,
                         output.to_account_uuid, output.from_account_uuid,
-                        payment.to_address
+                        payment.to_address, chain_tx.created IS NOT NULL
                  FROM v_tx_outputs output
                  LEFT JOIN sent_notes payment
                    ON payment.transaction_id = output.transaction_id
                   AND payment.output_pool = output.output_pool
                   AND payment.output_index = output.output_index
+                 LEFT JOIN transactions chain_tx
+                   ON chain_tx.id_tx = output.transaction_id
                  WHERE output.txid = ?1",
             )
             .map_err(db_err)?;
@@ -325,6 +345,7 @@ pub fn details_outputs(
             let to_acct: Option> = row.get(5).map_err(db_err)?;
             let from_acct: Option> = row.get(6).map_err(db_err)?;
             let payment_address: Option = row.get(7).map_err(db_err)?;
+            let created_locally: bool = row.get(8).map_err(db_err)?;
             // Compact scanning also marks explicit self-payments as change.
             // A recorded shielded recipient identifies a payment; actual change
             // has no sent-note recipient address. Keep the scan flags intact.
@@ -356,7 +377,8 @@ pub fn details_outputs(
                     "valueZat": value,
                     "pool": pool,
                     "poolName": pool_name(pool),
-                    "address": address,
+                    "address": address
+                        .map(|address| paid_address(&address, pool, created_locally)),
                 }));
             }
         }
@@ -417,6 +439,57 @@ fn pool_name(pool: i64) -> &'static str {
     }
 }
 
+/// A stored Unified Address with the network it was encoded for.
+struct StoredUnified(NetworkType, unified::Address);
+
+impl TryFromAddress for StoredUnified {
+    type Error = std::convert::Infallible;
+
+    fn try_from_unified(
+        net: NetworkType,
+        data: unified::Address,
+    ) -> std::result::Result> {
+        Ok(Self(net, data))
+    }
+}
+
+/// The receiver an output paid, where upstream stored a wallet UA containing it.
+/// Shielded: Orchard-only UA, unless a send made here names an address unlike
+/// the wallet's address-table UAs (exactly Orchard + P2PKH for OneKey UFVKs).
+fn paid_address(stored: &str, pool: i64, created_locally: bool) -> String {
+    let Some(StoredUnified(net, ua)) = ZcashAddress::try_from_encoded(stored)
+        .ok()
+        .and_then(|address| address.convert().ok())
+    else {
+        return stored.to_owned();
+    };
+    let items = ua.items();
+    let is_address_table_shape = items.len() == 2
+        && items
+            .iter()
+            .any(|receiver| matches!(receiver, unified::Receiver::Orchard(_)))
+        && items
+            .iter()
+            .any(|receiver| matches!(receiver, unified::Receiver::P2pkh(_)));
+    let paid = items.into_iter().find_map(|receiver| match receiver {
+        unified::Receiver::P2pkh(data) if pool == 0 => {
+            Some(ZcashAddress::from_transparent_p2pkh(net, data))
+        }
+        unified::Receiver::P2sh(data) if pool == 0 => {
+            Some(ZcashAddress::from_transparent_p2sh(net, data))
+        }
+        unified::Receiver::Orchard(data)
+            if (pool == 3 || pool == 4) && (!created_locally || is_address_table_shape) =>
+        {
+            unified::Address::try_from_items(vec![unified::Receiver::Orchard(data)])
+                .ok()
+                .map(|orchard_only| ZcashAddress::from_unified(net, orchard_only))
+        }
+        _ => None,
+    });
+    paid.map_or_else(|| stored.to_owned(), |address| address.encode())
+}
+
 #[derive(Debug, PartialEq)]
 enum DecodedMemo {
     None,
@@ -618,7 +691,7 @@ mod tests {
         let conn = rusqlite::Connection::open_in_memory().unwrap();
         conn.execute_batch(
             "CREATE TABLE accounts (id INTEGER PRIMARY KEY, uuid BLOB NOT NULL);
-             CREATE TABLE transactions (id_tx INTEGER PRIMARY KEY, txid BLOB NOT NULL);
+             CREATE TABLE transactions (id_tx INTEGER PRIMARY KEY, txid BLOB NOT NULL, created TEXT);
              CREATE TABLE v_received_outputs (
                id_within_pool_table INTEGER NOT NULL,
                transaction_id INTEGER NOT NULL,
@@ -634,6 +707,7 @@ mod tests {
              );
              CREATE TABLE v_tx_outputs (
                transaction_id INTEGER,
+               output_pool INTEGER DEFAULT 4,
                output_index INTEGER DEFAULT 0,
                txid BLOB NOT NULL,
                from_account_uuid BLOB,
@@ -790,8 +864,7 @@ mod tests {
     fn decrypted_memos_are_visible_only_to_the_output_sender_or_receiver() {
         let conn = history_fixture();
         conn.execute_batch(
-            "ALTER TABLE v_tx_outputs ADD COLUMN output_pool INTEGER DEFAULT 4;
-             ALTER TABLE v_tx_outputs ADD COLUMN value INTEGER DEFAULT 10000;
+            "ALTER TABLE v_tx_outputs ADD COLUMN value INTEGER DEFAULT 10000;
              ALTER TABLE v_tx_outputs ADD COLUMN memo BLOB;
              ALTER TABLE v_received_outputs ADD COLUMN address_id INTEGER;
              CREATE TABLE addresses (id INTEGER PRIMARY KEY, address TEXT);",
@@ -844,8 +917,7 @@ mod tests {
     fn explicit_self_payment_is_not_displayed_as_change_after_scanning() {
         let conn = history_fixture();
         conn.execute_batch(
-            "ALTER TABLE v_tx_outputs ADD COLUMN output_pool INTEGER DEFAULT 4;
-             ALTER TABLE v_tx_outputs ADD COLUMN value INTEGER;
+            "ALTER TABLE v_tx_outputs ADD COLUMN value INTEGER;
              ALTER TABLE v_tx_outputs ADD COLUMN memo BLOB;
              ALTER TABLE v_received_outputs ADD COLUMN address_id INTEGER;
              CREATE TABLE addresses (id INTEGER PRIMARY KEY, address TEXT);",
@@ -995,3 +1067,457 @@ mod tests {
         }
     }
 }
+
+/// Recipients of transactions stored the way the wallet really stores them:
+/// decrypted by enhancement, or recorded by a local send.
+#[cfg(test)]
+mod recipient_tests {
+    use std::collections::HashMap;
+
+    use orchard::builder::{Builder as OrchardBuilder, BundleType};
+    use orchard::bundle::{Authorized as OrchardAuthorized, BundleVersion};
+    use orchard::primitives::redpallas::Signature;
+    use orchard::value::NoteValue;
+    use orchard::{Anchor, Proof};
+    use rand::SeedableRng;
+    use rand_chacha::ChaCha20Rng;
+    use transparent::address::{Script, TransparentAddress};
+    use transparent::bundle::{Authorized, Bundle, OutPoint, TxIn, TxOut};
+    use transparent::keys::{IncomingViewingKey, NonHardenedChildIndex};
+    use zcash_client_backend::data_api::chain::ChainState;
+    use zcash_client_backend::data_api::wallet::TargetHeight;
+    use zcash_client_backend::data_api::{
+        Account as _, AccountBirthday, AccountPurpose, SentTransaction, SentTransactionOutput,
+        WalletWrite,
+    };
+    use zcash_client_backend::decrypt_transaction;
+    use zcash_client_backend::encoding::AddressCodec;
+    use zcash_client_backend::wallet::{Recipient, WalletTransparentOutput};
+    use zcash_client_sqlite::wallet::init::WalletMigrator;
+    use zcash_client_sqlite::{AccountUuid, WalletDb};
+    use zcash_keys::keys::{
+        ReceiverRequirement, UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedSpendingKey,
+    };
+    use zcash_primitives::block::BlockHash;
+    use zcash_primitives::transaction::{Transaction, TransactionData};
+    use zcash_protocol::consensus::{BlockHeight, BranchId, Network};
+    use zcash_protocol::memo::MemoBytes;
+    use zcash_protocol::value::{ZatBalance, Zatoshis};
+    use zcash_protocol::PoolType;
+
+    use super::*;
+    use crate::clock::HostClock;
+
+    const NET: Network = Network::MainNetwork;
+    const TIP: u32 = 3_525_600;
+    const MINED: u32 = 3_525_531;
+
+    struct Wallet {
+        conn: rusqlite::Connection,
+        accounts: Vec<(AccountUuid, UnifiedFullViewingKey)>,
+    }
+
+    impl Wallet {
+        /// Accounts 0..count of one seed, as the host registers them.
+        fn new(count: u32) -> Self {
+            let mut conn = rusqlite::Connection::open_in_memory().unwrap();
+            rusqlite::vtab::array::load_module(&conn).unwrap();
+            let mut accounts = Vec::new();
+            {
+                let mut db = db(&mut conn);
+                WalletMigrator::new()
+                    .with_external_migrations(crate::tx_state::migrations())
+                    .init_or_migrate(&mut db)
+                    .unwrap();
+                let birthday = AccountBirthday::from_parts(
+                    ChainState::empty(BlockHeight::from_u32(3_525_000), BlockHash([0; 32])),
+                    None,
+                );
+                for index in 0..count {
+                    let ufvk = ufvk(&[9; 32], index);
+                    let account = db
+                        .import_account_ufvk(
+                            &format!("hd-{index}"),
+                            &ufvk,
+                            &birthday,
+                            AccountPurpose::ViewOnly,
+                            None,
+                        )
+                        .unwrap();
+                    accounts.push((account.id(), ufvk));
+                }
+                db.update_chain_tip(BlockHeight::from_u32(TIP)).unwrap();
+            }
+            Self { conn, accounts }
+        }
+
+        fn account(&self, index: usize) -> AccountUuid {
+            self.accounts[index].0
+        }
+
+        /// A transparent UTXO of `index`, so stored transactions spending it are
+        /// attributed to that account.
+        fn fund(&mut self, index: usize) -> OutPoint {
+            let outpoint = OutPoint::new([5; 32], 0);
+            let utxo = WalletTransparentOutput::from_parts(
+                outpoint.clone(),
+                TxOut::new(
+                    Zatoshis::const_from_u64(1_000_000),
+                    taddr(&self.accounts[index].1, 0).script().into(),
+                ),
+                Some(BlockHeight::from_u32(3_525_100)),
+                Some(self.account(index)),
+                None,
+                None,
+            )
+            .unwrap();
+            db(&mut self.conn)
+                .put_received_transparent_utxo(&utxo)
+                .unwrap();
+            outpoint
+        }
+
+        /// Stores `tx` as enhancement does: decrypted with every account's keys.
+        fn enhance(&mut self, tx: &Transaction) {
+            let keys = self.accounts.iter().cloned().collect::>();
+            db(&mut self.conn)
+                .store_decrypted_tx(decrypt_transaction(
+                    &NET,
+                    Some(BlockHeight::from_u32(MINED)),
+                    Some(BlockHeight::from_u32(TIP)),
+                    tx,
+                    &keys,
+                ))
+                .unwrap();
+        }
+
+        fn remove(&mut self, index: usize) {
+            let account = self.account(index);
+            db(&mut self.conn).delete_account(account).unwrap();
+        }
+
+        fn row(&self, index: usize, tx: &Transaction) -> serde_json::Value {
+            let txid = tx.txid().to_string();
+            let rows: Vec = serde_json::from_str(
+                &list(
+                    &self.conn,
+                    &self.account(index).expose_uuid().to_string(),
+                    20,
+                    0,
+                )
+                .unwrap(),
+            )
+            .unwrap();
+            let row = rows.into_iter().find(|row| row["txid"] == txid).unwrap();
+            let detail: serde_json::Value = serde_json::from_str(
+                &details(
+                    &self.conn,
+                    &self.account(index).expose_uuid().to_string(),
+                    &txid,
+                )
+                .unwrap(),
+            )
+            .unwrap();
+            assert_eq!(row, detail);
+            row
+        }
+
+        fn external(&self, index: usize, tx: &Transaction) -> Vec {
+            let outputs: serde_json::Value = serde_json::from_str(
+                &details_outputs(
+                    &self.conn,
+                    &self.account(index).expose_uuid().to_string(),
+                    &tx.txid().to_string(),
+                )
+                .unwrap(),
+            )
+            .unwrap();
+            outputs["external"].as_array().unwrap().clone()
+        }
+
+        /// What upstream stored for the payment, before the read projection:
+        /// its address and whether it names a receiving account.
+        fn stored_payment(&self) -> (String, bool) {
+            self.conn
+                .query_row(
+                    "SELECT to_address, to_account_id IS NOT NULL FROM sent_notes
+                     WHERE transaction_id = (SELECT MAX(id_tx) FROM transactions)
+                     ORDER BY output_pool, output_index LIMIT 1",
+                    [],
+                    |row| Ok((row.get(0)?, row.get(1)?)),
+                )
+                .unwrap()
+        }
+
+        /// Records `tx` as a send created here, paying `to` in Ironwood.
+        fn record_local_send(&mut self, tx: &Transaction, input: OutPoint, index: usize, to: &str) {
+            let outputs = [SentTransactionOutput::from_parts(
+                index,
+                Recipient::External {
+                    recipient_address: to.parse().unwrap(),
+                    output_pool: PoolType::IRONWOOD,
+                },
+                Zatoshis::const_from_u64(20_000),
+                Some(MemoBytes::empty()),
+            )];
+            let account = self.account(0);
+            db(&mut self.conn)
+                .store_transactions_to_be_sent(&[SentTransaction::new(
+                    tx,
+                    // `time` is a wasm-only dependency of this crate.
+                    std::time::SystemTime::now().into(),
+                    TargetHeight::from(BlockHeight::from_u32(MINED)),
+                    account,
+                    &outputs,
+                    Zatoshis::const_from_u64(10_000),
+                    &[input],
+                )])
+                .unwrap();
+        }
+    }
+
+    fn db(
+        conn: &mut rusqlite::Connection,
+    ) -> WalletDb<&mut rusqlite::Connection, Network, HostClock, ChaCha20Rng> {
+        WalletDb::from_connection(conn, NET, HostClock, ChaCha20Rng::from_seed([7; 32]))
+    }
+
+    /// A UFVK as a third-party wallet derives it, with a Sapling key.
+    fn full_ufvk(seed: &[u8; 32], index: u32) -> UnifiedFullViewingKey {
+        UnifiedSpendingKey::from_seed(&NET, seed, index.try_into().unwrap())
+            .unwrap()
+            .to_unified_full_viewing_key()
+    }
+
+    /// A UFVK as OneKey builds it (keys runtime `ufvkFromAccountKeys`):
+    /// transparent and Orchard only.
+    fn ufvk(seed: &[u8; 32], index: u32) -> UnifiedFullViewingKey {
+        use zcash_address::unified::{Fvk, Ufvk};
+        let (net, full) = Ufvk::decode(&full_ufvk(seed, index).encode(&NET)).unwrap();
+        let items = full
+            .items()
+            .into_iter()
+            .filter(|item| matches!(item, Fvk::P2pkh(_) | Fvk::Orchard(_)))
+            .collect();
+        let onekey = Ufvk::try_from_items(items).unwrap().encode(&net);
+        UnifiedFullViewingKey::decode(&NET, &onekey).unwrap()
+    }
+
+    fn taddr(ufvk: &UnifiedFullViewingKey, index: u32) -> TransparentAddress {
+        ufvk.transparent()
+            .unwrap()
+            .derive_external_ivk()
+            .unwrap()
+            .derive_address(NonHardenedChildIndex::from_index(index).unwrap())
+            .unwrap()
+    }
+
+    fn receive_orchard(encoded: &str) -> orchard::Address {
+        match zcash_keys::address::Address::decode(&NET, encoded) {
+            Some(zcash_keys::address::Address::Unified(ua)) => *ua.orchard().unwrap(),
+            _ => panic!("not a unified address"),
+        }
+    }
+
+    /// The address the Receive page shows (keys runtime policy "orchard").
+    fn receive_address(ufvk: &UnifiedFullViewingKey) -> zcash_keys::address::UnifiedAddress {
+        ufvk.default_address(UnifiedAddressRequest::ORCHARD)
+            .unwrap()
+            .0
+    }
+
+    /// An Ironwood bundle paying `recipient`, and the payment's action index.
+    /// The proof and signatures are placeholders: storing a transaction never
+    /// verifies them.
+    fn ironwood_payment(
+        recipient: orchard::Address,
+    ) -> (orchard::Bundle, usize) {
+        let version = BundleVersion::ironwood_v3();
+        let mut builder = OrchardBuilder::new(
+            BundleType::DEFAULT,
+            version,
+            version.default_flags(),
+            Anchor::empty_tree(),
+        )
+        .unwrap();
+        builder
+            .add_output(None, recipient, NoteValue::from_raw(20_000), [0; 512])
+            .unwrap();
+        let mut rng = ChaCha20Rng::from_seed([3; 32]);
+        let (bundle, meta) = builder.build::(&mut rng).unwrap().unwrap();
+        let proof_len = Proof::expected_proof_size(bundle.actions().len());
+        let bundle = bundle.map_authorization(
+            &mut rng,
+            |_, _, _| Signature::from([0; 64]),
+            |_, _| {
+                OrchardAuthorized::from_parts(
+                    Proof::new(vec![0; proof_len]),
+                    Signature::from([0; 64]),
+                )
+            },
+        );
+        (bundle, meta.output_action_index(0).unwrap())
+    }
+
+    fn transaction(
+        input: OutPoint,
+        outputs: Vec,
+        ironwood: Option>,
+    ) -> Transaction {
+        let transparent = Bundle {
+            vin: vec![TxIn::from_parts(input, Script::default(), u32::MAX)],
+            vout: outputs,
+            authorization: Authorized,
+        };
+        TransactionData::::from_parts_v6(
+            BranchId::Nu6_3,
+            0,
+            BlockHeight::from_u32(MINED + 40),
+            Some(transparent),
+            None,
+            None,
+            ironwood,
+        )
+        .freeze()
+        .unwrap()
+    }
+
+    fn pay(address: &TransparentAddress) -> TxOut {
+        TxOut::new(Zatoshis::const_from_u64(20_000), address.script().into())
+    }
+
+    #[test]
+    fn enhanced_transparent_payment_to_a_sibling_names_its_t_address() {
+        let mut wallet = Wallet::new(2);
+        let input = wallet.fund(0);
+        let sibling = taddr(&wallet.accounts[1].1, 0).encode(&NET);
+        let tx = transaction(input, vec![pay(&taddr(&wallet.accounts[1].1, 0))], None);
+        wallet.enhance(&tx);
+
+        assert_eq!(wallet.row(0, &tx)["recipient"], sibling);
+        assert_eq!(wallet.external(0, &tx)[0]["address"], sibling);
+    }
+
+    #[test]
+    fn removing_the_paid_sibling_keeps_its_t_address() {
+        let mut wallet = Wallet::new(2);
+        let input = wallet.fund(0);
+        let sibling = taddr(&wallet.accounts[1].1, 0).encode(&NET);
+        let tx = transaction(input, vec![pay(&taddr(&wallet.accounts[1].1, 0))], None);
+        wallet.enhance(&tx);
+        wallet.remove(1);
+
+        // Upstream rewrote the payment to the sibling's address-table UA.
+        assert!(wallet.stored_payment().0.starts_with("u1"));
+        assert_eq!(wallet.row(0, &tx)["recipient"], sibling);
+        assert_eq!(wallet.external(0, &tx)[0]["address"], sibling);
+    }
+
+    #[test]
+    fn enhanced_shielded_payment_to_a_sibling_names_its_receive_address() {
+        let mut wallet = Wallet::new(2);
+        let input = wallet.fund(0);
+        let receive = receive_address(&wallet.accounts[1].1);
+        let (bundle, _) = ironwood_payment(*receive.orchard().unwrap());
+        let tx = transaction(input, vec![], Some(bundle));
+        wallet.enhance(&tx);
+        let expected = receive.encode(&NET);
+
+        // Upstream stores the sibling's address-table UA, which adds receivers
+        // the payer never saw.
+        assert_ne!(wallet.stored_payment().0, expected);
+        assert_eq!(wallet.row(0, &tx)["recipient"], expected);
+        assert_eq!(wallet.external(0, &tx)[0]["address"], expected);
+
+        wallet.remove(1);
+        assert_eq!(wallet.row(0, &tx)["recipient"], expected);
+        assert_eq!(wallet.external(0, &tx)[0]["address"], expected);
+    }
+
+    #[test]
+    fn a_local_send_keeps_an_entered_address_unless_it_has_the_address_table_shape() {
+        use ReceiverRequirement::{Omit, Require};
+        let payee = full_ufvk(&[4; 32], 0);
+        let address = |request| payee.default_address(request).unwrap().0.encode(&NET);
+        let all = address(UnifiedAddressRequest::unsafe_custom(
+            Require, Require, Require,
+        ));
+        let orchard_only = address(UnifiedAddressRequest::ORCHARD);
+        let orchard_p2pkh = address(UnifiedAddressRequest::unsafe_custom(Require, Omit, Require));
+        for (entered, shown) in [
+            (all.clone(), all),
+            (orchard_only.clone(), orchard_only.clone()),
+            // The shape upstream substitutes for a sibling account's address.
+            (orchard_p2pkh, orchard_only),
+        ] {
+            let mut wallet = Wallet::new(1);
+            let input = wallet.fund(0);
+            let (bundle, index) = ironwood_payment(receive_orchard(&entered));
+            let tx = transaction(input.clone(), vec![], Some(bundle));
+            wallet.record_local_send(&tx, input, index, &entered);
+
+            assert_eq!(wallet.row(0, &tx)["recipient"], shown);
+            assert_eq!(wallet.external(0, &tx)[0]["address"], shown);
+        }
+    }
+
+    #[test]
+    fn a_local_send_to_a_removed_sibling_names_its_receive_address() {
+        let mut wallet = Wallet::new(2);
+        let input = wallet.fund(0);
+        let receive = receive_address(&wallet.accounts[1].1).encode(&NET);
+        let (bundle, index) = ironwood_payment(receive_orchard(&receive));
+        let tx = transaction(input.clone(), vec![], Some(bundle));
+        wallet.record_local_send(&tx, input, index, &receive);
+        assert_eq!(wallet.stored_payment(), (receive.clone(), false));
+        // Status observation fetches the sent transaction and stores it again,
+        // which links the payment to the sibling.
+        wallet.enhance(&tx);
+        assert_eq!(wallet.stored_payment(), (receive.clone(), true));
+        // Removing the sibling rewrites it to an address-table UA.
+        wallet.remove(1);
+        let (stored, _) = wallet.stored_payment();
+        assert_ne!(stored, receive);
+        let (_, rewritten) = unified::Address::decode(&stored).unwrap();
+        let mut kinds = rewritten
+            .items()
+            .iter()
+            .map(|receiver| match receiver {
+                unified::Receiver::Orchard(_) => "orchard",
+                unified::Receiver::P2pkh(_) => "p2pkh",
+                _ => "other",
+            })
+            .collect::>();
+        kinds.sort_unstable();
+        assert_eq!(kinds, ["orchard", "p2pkh"]);
+
+        assert_eq!(wallet.row(0, &tx)["recipient"], receive);
+        assert_eq!(wallet.external(0, &tx)[0]["address"], receive);
+    }
+
+    #[test]
+    fn the_first_external_output_is_the_recipient() {
+        let mut wallet = Wallet::new(1);
+        let input = wallet.fund(0);
+        let payee = ufvk(&[4; 32], 0);
+        let first = taddr(&payee, 7);
+        let second = taddr(&payee, 3);
+        let tx = transaction(input, vec![pay(&first), pay(&second)], None);
+        wallet.enhance(&tx);
+
+        let row = wallet.row(0, &tx);
+        assert_eq!(row["externalOutputCount"], 2);
+        assert_eq!(row["recipient"], first.encode(&NET));
+    }
+
+    #[test]
+    fn unparseable_or_plain_addresses_are_returned_unchanged() {
+        for pool in [0, 3, 4] {
+            assert_eq!(paid_address("synthetic", pool, false), "synthetic");
+        }
+        let t = taddr(&ufvk(&[4; 32], 0), 0).encode(&NET);
+        assert_eq!(paid_address(&t, 0, false), t);
+        let receive = receive_address(&ufvk(&[4; 32], 0)).encode(&NET);
+        assert_eq!(paid_address(&receive, 4, false), receive);
+    }
+}

From 15c510e8d58ac9fd4e0ca0941f429cc15516e319 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Thu, 22 Oct 2026 09:53:21 +0800
Subject: [PATCH 72/97] chore: bump privacy runtimes to 0.1.0-alpha.8

---
 chain-runtimes/monero/Cargo.lock | 2 +-
 chain-runtimes/monero/Cargo.toml | 2 +-
 chain-runtimes/zcash/Cargo.lock  | 4 ++--
 chain-runtimes/zcash/Cargo.toml  | 2 +-
 4 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock
index c5d09bdd2..a888a1946 100644
--- a/chain-runtimes/monero/Cargo.lock
+++ b/chain-runtimes/monero/Cargo.lock
@@ -1259,7 +1259,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-monero-runtime"
-version = "0.1.0-alpha.7"
+version = "0.1.0-alpha.8"
 dependencies = [
  "curve25519-dalek",
  "futures-lite",
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index e1596808d..8adf39b3c 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/monero-runtime"]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.7"
+version = "0.1.0-alpha.8"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index 868d93bc0..f566c2ade 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1655,7 +1655,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-zcash-keys"
-version = "0.1.0-alpha.7"
+version = "0.1.0-alpha.8"
 dependencies = [
  "bip0039",
  "bip32",
@@ -1687,7 +1687,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-runtime"
-version = "0.1.0-alpha.7"
+version = "0.1.0-alpha.8"
 dependencies = [
  "blake2b_simd",
  "console_error_panic_hook",
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index 619913113..561fc07c6 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -7,7 +7,7 @@ members = [
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.7"
+version = "0.1.0-alpha.8"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"

From a1ae6df5c662ec259eade62c00dd23abf5e049cd Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Tue, 27 Oct 2026 09:48:18 +0800
Subject: [PATCH 73/97] fix(zcash): improve sync reliability and restart at a
 later birthday

Scan a bounded recent window first, then catch up in order. Recover
account imports atomically, keep wallet observations during rescans, and
initialize migration bookkeeping before native wallet startup. Sync
progress is read without building the wallet summary.

A later birthday starts the account over from that height; a pending send
is waited for first.
---
 chain-runtimes/zcash/Cargo.lock               |    2 +
 chain-runtimes/zcash/README.md                |   17 +
 .../zcash/crates/zcash-runtime/Cargo.toml     |    2 +
 .../zcash/crates/zcash-runtime/src/account.rs |  341 +++-
 .../zcash/crates/zcash-runtime/src/bindgen.rs |   23 +-
 .../zcash/crates/zcash-runtime/src/error.rs   |    3 +-
 .../zcash/crates/zcash-runtime/src/sync.rs    |  283 ++-
 .../crates/zcash-runtime/src/sync_tests.rs    | 1722 +++++++++++++++++
 .../zcash/crates/zcash-runtime/src/wallet.rs  |   34 +-
 9 files changed, 2376 insertions(+), 51 deletions(-)
 create mode 100644 chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs

diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index f566c2ade..38e52c183 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1696,6 +1696,7 @@ dependencies = [
  "getrandom 0.4.3",
  "gloo-timers",
  "hex",
+ "incrementalmerkletree",
  "js-sys",
  "orchard",
  "pczt",
@@ -1709,6 +1710,7 @@ dependencies = [
  "secp256k1",
  "serde",
  "serde_json",
+ "shardtree",
  "sqlite-wasm-rs",
  "sqlite-wasm-vfs",
  "thiserror 2.0.20",
diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md
index ae2cdaf67..76a36af8d 100644
--- a/chain-runtimes/zcash/README.md
+++ b/chain-runtimes/zcash/README.md
@@ -43,6 +43,10 @@ bash scripts/vendor-deps.sh --offline   # verify vendor against recorded upstrea
    strings only; no Rust object handles reach JS.
 4. **Rust owns key security, large data and consensus correctness;** the host owns
    scheduling, accounts, persistence policy, retries and display.
+5. **A rescan follows the new birthday.** An earlier start lowers the stored
+   birthday and keeps what is known; a later start deletes the account and imports
+   it again at that height, so nothing found before it remains. A later start
+   waits (`WALLET_BUSY`, reason `pendingSend`) while the account has an unmined send.
 
 ## API
 
@@ -64,6 +68,8 @@ importAccountUfvk(name, ufvk, birthday, seedFingerprintHex?, accountIndex?)
                                          → UUID; the server's tree state must be
                                          exactly the block before birthday
 removeAccount(uuid)                     pending transactions do not block removal
+rescanAccount(uuid, fromHeight)          earlier: rewind and keep; later: start over there
+                                         (new UUID; look the account up by UFVK)
 accountByUfvk(ufvk) / listAccounts() / accountSyncStatus(uuid)
 accountBalance(uuid, trusted, untrusted, allowZeroConfShielding)
                                          per pool: spendable, pendingChange,
@@ -73,6 +79,9 @@ accountBalance(uuid, trusted, untrusted, allowZeroConfShielding)
                                          which are uneconomic instead
 
 syncPrepare() / syncTip() / syncPeek()   prepare (subtree roots + tip), read-only progress
+                                         syncPeek/accountSyncStatus include nullable
+                                         chainTip and fullyScannedHeight without
+                                         computing wallet balances
 syncStep(batchSize, maxBatches, priority, activeUfvksJson)
                                          bounded step, only for UFVKs the host enabled
 queueRescanFrom(fromHeight)              non-destructive requeue of [fromHeight, tip]
@@ -99,6 +108,14 @@ pcztExtractStateless(pczt)               verify and extract without a wallet
 capabilities() / dependencyVersions()
 ```
 
+### Consecutive old-birthday imports
+
+`DATABASE_ERROR` with `params.operation = "importAccount"` and
+`params.reason = "checkpointsDiverged"` is upstream rejecting mismatched pool
+checkpoints. The import rolls back and the database stays usable: keep the account
+pending and retry the import after further scanning; it succeeds once the pending
+scan finishes.
+
 ### `onekey-zcash-keys`
 
 ```
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
index 72b4eeea0..036693606 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
+++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
@@ -10,6 +10,8 @@ description = "OneKey Zcash Runtime: a thin wasm binding over librustzcash"
 crate-type = ["cdylib", "rlib"]
 
 [dependencies]
+incrementalmerkletree = "0.8.2"
+shardtree = "=0.7.1"
 blake2b_simd.workspace = true
 zcash_client_backend.workspace = true
 zcash_client_sqlite.workspace = true
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
index 315d1115e..2b1d237f6 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
@@ -1,11 +1,16 @@
 //! Account import and reads: UFVK import and balances. No private keys,
 //! address derivation or signing on this path.
 
+use incrementalmerkletree::{frontier::Frontier, Hashable};
+use incrementalmerkletree::{Marking, Retention};
+use shardtree::{error::ShardTreeError, store::ShardStore, ShardTree};
+use zcash_client_backend::data_api::chain::ChainState;
 use zcash_client_backend::data_api::wallet::ConfirmationsPolicy;
 use zcash_client_backend::data_api::{
-    Account as _, AccountBalance, AccountBirthday, AccountPurpose, Balance, WalletRead,
-    WalletWrite, Zip32Derivation,
+    Account as _, AccountBalance, AccountBirthday, AccountPurpose, AccountSource, Balance,
+    WalletCommitmentTrees, WalletRead, WalletWrite, Zip32Derivation,
 };
+use zcash_client_sqlite::error::SqliteClientError;
 use zcash_keys::keys::UnifiedFullViewingKey;
 
 use crate::error::{ErrorCode, Result, RuntimeError};
@@ -54,17 +59,275 @@ pub async fn import_ufvk(
         .detail(format!("{e:?}"))
     })?;
 
-    let account = db
-        .import_account_ufvk(account_name, &ufvk, &birthday, purpose, None)
-        .map_err(|e| {
-            RuntimeError::with(
-                ErrorCode::DatabaseError,
-                json!({ "operation": "importAccount" }),
+    match import_with_birthday(db, account_name, &ufvk, &birthday, purpose.clone()) {
+        Err(error) if error.params["reason"] == "checkpointsDiverged" => {
+            let height = error.params["checkpointHeight"].as_u64().ok_or(error)? as u32;
+            let treestate = network::tree_state(client, height).await?;
+            check_birthday_tree_state(&treestate, height, ¶ms)?;
+            let checkpoint = AccountBirthday::from_treestate(treestate, None).map_err(|e| {
+                RuntimeError::new(ErrorCode::InvalidBlockHeight).detail(format!("{e:?}"))
+            })?;
+            import_with_checkpoint(
+                db,
+                account_name,
+                &ufvk,
+                &birthday,
+                purpose,
+                checkpoint.prior_chain_state(),
             )
-            .detail(e)
-        })?;
+            .map_err(|mut error| {
+                if error.params["reason"] == "checkpointsDiverged" {
+                    error.params["reason"] = json!("checkpointRecoveryStalled");
+                }
+                error
+            })
+        }
+        result => result,
+    }
+}
+
+fn missing_checkpoint_height(error: &SqliteClientError) -> Option {
+    let SqliteClientError::CorruptedData(message) = error else {
+        return None;
+    };
+    [
+        "the Sapling note commitment tree retains checkpoints both above and below height ",
+        "the Orchard note commitment tree retains checkpoints both above and below height ",
+        "the Ironwood note commitment tree retains checkpoints both above and below height ",
+    ]
+    .iter()
+    .find_map(|prefix| message.strip_prefix(prefix))
+    .and_then(|rest| rest.split_once(',').map(|(height, _)| height))
+    .and_then(|height| height.parse().ok())
+}
+
+pub(crate) fn import_with_checkpoint(
+    db: &mut Db,
+    name: &str,
+    ufvk: &UnifiedFullViewingKey,
+    birthday: &AccountBirthday,
+    purpose: AccountPurpose,
+    checkpoint: &ChainState,
+) -> Result {
+    db.transactionally(|wallet| {
+        insert_missing_checkpoints(wallet, checkpoint)?;
+        wallet
+            .import_account_ufvk(name, ufvk, birthday, purpose, None)
+            .map(|account| account.id().expose_uuid().to_string())
+    })
+    .map_err(import_error)
+}
+
+fn insert_missing_checkpoints(
+    wallet: &mut W,
+    checkpoint: &ChainState,
+) -> std::result::Result<(), SqliteClientError>
+where
+    W: WalletRead
+        + WalletCommitmentTrees,
+{
+    let height = checkpoint.block_height();
+    if wallet
+        .get_block_hash(height)?
+        .is_some_and(|hash| hash != checkpoint.block_hash())
+    {
+        return Err(SqliteClientError::BlockConflict(height));
+    }
+    // Do not mark blocks scanned or replace existing checkpoint marks.
+    wallet.with_sapling_tree_mut(|tree| {
+        insert_checkpoint(tree, checkpoint.final_sapling_tree().clone(), height)
+    })?;
+    wallet.with_orchard_tree_mut(|tree| {
+        insert_checkpoint(tree, checkpoint.final_orchard_tree().clone(), height)
+    })?;
+    wallet.with_ironwood_tree_mut(|tree| {
+        insert_checkpoint(tree, checkpoint.final_ironwood_tree().clone(), height)
+    })?;
+    Ok(())
+}
+
+/// Rescans one account from `from`. An earlier start rewinds and keeps what is
+/// already known; a later one starts the account over at that height.
+pub async fn rescan_account(
+    db: &mut Db,
+    client: &mut LightClient,
+    uuid: &str,
+    from: u32,
+    has_pending_send: bool,
+) -> Result {
+    let id = parse_account_id(db, uuid)?;
+    let current = u32::from(db.get_account_birthday(id).map_err(import_error)?);
+    let params = *db.params();
+    if from > current {
+        refuse_restart_with_pending_send(has_pending_send)?;
+        let birthday = chain_state_at(client, from.saturating_sub(1), ¶ms).await?;
+        let uuid = match restart_with_birthday(db, id, &birthday, None) {
+            Ok(uuid) => uuid,
+            Err(error) => {
+                let Some(height) = error.params["checkpointHeight"].as_u64() else {
+                    return Err(error);
+                };
+                let checkpoint = chain_state_at(client, height as u32, ¶ms).await?;
+                restart_with_birthday(db, id, &birthday, Some(checkpoint.prior_chain_state()))?
+            }
+        };
+        return Ok(json!({ "fromHeight": from, "accountUuid": uuid }).to_string());
+    }
+    if from < current {
+        let birthday = chain_state_at(client, from.saturating_sub(1), ¶ms).await?;
+        if let Err(error) = rescan_with_birthday(db, id, &birthday, None) {
+            let Some(height) = error.params["checkpointHeight"].as_u64() else {
+                return Err(error);
+            };
+            let checkpoint = chain_state_at(client, height as u32, ¶ms).await?;
+            rescan_with_birthday(db, id, &birthday, Some(checkpoint.prior_chain_state()))?;
+        }
+    } else if db.chain_height().map_err(import_error)?.is_some() {
+        crate::sync::queue_rescan_from(db, from)?;
+    }
+    Ok(json!({ "fromHeight": from, "accountUuid": uuid }).to_string())
+}
+
+/// Starting over drops the notes a pending send spends; it waits until the send settles.
+fn refuse_restart_with_pending_send(has_pending_send: bool) -> Result<()> {
+    if has_pending_send {
+        return Err(RuntimeError::with(
+            ErrorCode::WalletBusy,
+            json!({ "operation": "rescanAccount", "reason": "pendingSend" }),
+        ));
+    }
+    Ok(())
+}
 
-    Ok(account.id().expose_uuid().to_string())
+async fn chain_state_at(
+    client: &mut LightClient,
+    height: u32,
+    params: &zcash_protocol::consensus::Network,
+) -> Result {
+    let state = network::tree_state(client, height).await?;
+    check_birthday_tree_state(&state, height, params)?;
+    AccountBirthday::from_treestate(state, None)
+        .map_err(|e| RuntimeError::new(ErrorCode::InvalidBlockHeight).detail(format!("{e:?}")))
+}
+
+/// Deletes the account and imports it again at `birthday` in one transaction,
+/// so nothing it found before the new birthday is kept.
+pub(crate) fn restart_with_birthday(
+    db: &mut Db,
+    id: zcash_client_sqlite::AccountUuid,
+    birthday: &AccountBirthday,
+    checkpoint: Option<&ChainState>,
+) -> Result {
+    let account = db
+        .get_account(id)
+        .map_err(import_error)?
+        .ok_or_else(|| RuntimeError::new(ErrorCode::AccountNotFound))?;
+    let name = account.name().unwrap_or_default().to_owned();
+    let ufvk = account
+        .ufvk()
+        .cloned()
+        .ok_or_else(|| RuntimeError::new(ErrorCode::InvalidUfvk))?;
+    let AccountSource::Imported { purpose, .. } = account.source().clone() else {
+        return Err(RuntimeError::new(ErrorCode::InvalidAccountId));
+    };
+    db.transactionally_with_extension(|wallet, ext| {
+        if let Some(checkpoint) = checkpoint {
+            insert_missing_checkpoints(wallet, checkpoint).map_err(import_error)?;
+        }
+        wallet.delete_account(id).map_err(import_error)?;
+        let uuid = wallet
+            .import_account_ufvk(&name, &ufvk, birthday, purpose, None)
+            .map_err(import_error)?
+            .id()
+            .expose_uuid()
+            .to_string();
+        crate::tx_state::prune_orphaned_rows(ext)?;
+        Ok(uuid)
+    })
+    .map_err(|mut error: RuntimeError| {
+        error.params["operation"] = json!("rescanAccount");
+        error
+    })
+}
+
+pub(crate) fn rescan_with_birthday(
+    db: &mut Db,
+    id: zcash_client_sqlite::AccountUuid,
+    birthday: &AccountBirthday,
+    checkpoint: Option<&ChainState>,
+) -> Result<()> {
+    use std::collections::HashSet;
+    use zcash_client_backend::data_api::error::RewindError;
+    db.transactionally(|wallet| {
+        if let Some(checkpoint) = checkpoint {
+            insert_missing_checkpoints(wallet, checkpoint).map_err(import_error)?;
+        }
+        wallet
+            .rewind_to_chain_state(birthday.prior_chain_state().clone(), HashSet::from([id]))
+            .map_err(|error| match error {
+                RewindError::DataSource(error) => import_error(error),
+                error => RuntimeError::new(ErrorCode::DatabaseError).detail(format!("{error:?}")),
+            })
+    })
+    .map_err(|mut error: RuntimeError| {
+        error.params["operation"] = json!("rescanAccount");
+        error
+    })
+}
+
+fn insert_checkpoint(
+    tree: &mut ShardTree,
+    frontier: Frontier,
+    height: zcash_protocol::consensus::BlockHeight,
+) -> std::result::Result<(), SqliteClientError>
+where
+    S: ShardStore<
+        CheckpointId = zcash_protocol::consensus::BlockHeight,
+        Error = zcash_client_sqlite::wallet::commitment_tree::Error,
+    >,
+    S::H: Hashable + Clone + PartialEq,
+{
+    let existing = tree
+        .store()
+        .get_checkpoint(&height)
+        .map_err(|error| SqliteClientError::from(ShardTreeError::Storage(error)))?;
+    if let Some(existing) = existing {
+        if existing.position() != frontier.value().map(|frontier| frontier.position()) {
+            return Err(SqliteClientError::CorruptedData(
+                "checkpoint position mismatch".into(),
+            ));
+        }
+        return Ok(());
+    }
+    tree.insert_frontier(
+        frontier,
+        Retention::Checkpoint {
+            id: height,
+            marking: Marking::None,
+        },
+    )
+    .map_err(SqliteClientError::from)
+}
+
+pub(crate) fn import_with_birthday(
+    db: &mut Db,
+    name: &str,
+    ufvk: &UnifiedFullViewingKey,
+    birthday: &AccountBirthday,
+    purpose: AccountPurpose,
+) -> Result {
+    db.import_account_ufvk(name, ufvk, birthday, purpose, None)
+        .map(|account| account.id().expose_uuid().to_string())
+        .map_err(import_error)
+}
+
+pub(crate) fn import_error(error: SqliteClientError) -> RuntimeError {
+    let mut params = json!({ "operation": "importAccount" });
+    if let Some(height) = missing_checkpoint_height(&error) {
+        params["reason"] = json!("checkpointsDiverged");
+        params["checkpointHeight"] = json!(height);
+    }
+    RuntimeError::with(ErrorCode::DatabaseError, params).detail(error)
 }
 
 /// Pairs the spending derivation fields; half a pair is refused, not imported view-only.
@@ -337,6 +600,62 @@ fn check_birthday_tree_state(
     Ok(())
 }
 
+#[cfg(test)]
+mod import_error_tests {
+    use super::*;
+
+    #[test]
+    fn diverged_checkpoints_have_a_structured_reason_and_keep_the_detail() {
+        for pool in ["Sapling", "Orchard", "Ironwood"] {
+            let error = SqliteClientError::CorruptedData(format!(
+                "the {pool} note commitment tree retains checkpoints both above and below \
+                 height 4135105, but none at that height to truncate to"
+            ));
+            let detail = error.to_string();
+            assert_eq!(
+                import_error(error).to_json(),
+                json!({
+                    "code": "DATABASE_ERROR",
+                    "params": { "operation": "importAccount", "reason": "checkpointsDiverged", "checkpointHeight": 4135105 },
+                    "detail": detail,
+                })
+            );
+        }
+    }
+
+    #[test]
+    fn a_later_birthday_waits_for_a_pending_send() {
+        assert!(refuse_restart_with_pending_send(false).is_ok());
+        let error = refuse_restart_with_pending_send(true).unwrap_err();
+        assert_eq!(error.to_json()["code"], "WALLET_BUSY");
+        assert_eq!(error.params["reason"], "pendingSend");
+    }
+
+    #[test]
+    fn other_import_errors_keep_their_params_and_detail() {
+        let prefix = "the Orchard note commitment tree retains checkpoints both above and below height 4135105";
+        for error in [
+            SqliteClientError::CorruptedData("invalid stored note".into()),
+            SqliteClientError::CorruptedData(format!("other failure: {prefix}")),
+            SqliteClientError::DbError(rusqlite::Error::InvalidParameterName(prefix.into())),
+            SqliteClientError::RequestedRewindInvalid {
+                safe_rewind_height: None,
+                requested_height: 4_135_029_u32.into(),
+            },
+        ] {
+            let detail = error.to_string();
+            assert_eq!(
+                import_error(error).to_json(),
+                json!({
+                    "code": "DATABASE_ERROR",
+                    "params": { "operation": "importAccount" },
+                    "detail": detail,
+                })
+            );
+        }
+    }
+}
+
 #[cfg(test)]
 mod birthday_tests {
     use super::check_birthday_tree_state;
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
index 926f95283..d9e7e5ce3 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
@@ -259,7 +259,7 @@ pub async fn sync_tip() -> Result {
 }
 
 /// Read-only view of pending scan ranges; no network requests. Returns
-/// `{ ranges: [{ start, end, len, priority }], totalBlocks }`.
+/// `{ ranges: [{ start, end, len, priority }], totalBlocks, chainTip, fullyScannedHeight }`.
 #[wasm_bindgen(js_name = syncPeek)]
 pub fn sync_peek() -> Result {
     Ok(runtime::with_db(|db| sync::peek(db))?)
@@ -410,6 +410,27 @@ pub fn queue_rescan_from(from_height: u32) -> Result {
     })?)
 }
 
+/// Rescans one account from a new birthday; see `account::rescan_account`.
+#[wasm_bindgen(js_name = rescanAccount)]
+pub async fn rescan_account(account_uuid: String, from_height: u32) -> Result {
+    let has_pending_send =
+        !runtime::with_read_conn(|conn| tx_state::pending_txids(conn, &account_uuid))?.is_empty();
+    Ok(
+        runtime::with_db_and_client(move |mut db, mut client| async move {
+            let result = account::rescan_account(
+                &mut db,
+                &mut client,
+                &account_uuid,
+                from_height,
+                has_pending_send,
+            )
+            .await;
+            (db, client, result)
+        })
+        .await?,
+    )
+}
+
 // ── Send ────────────────────────────────────────────────────────────────
 //
 // Flow: pcztCreate → pcztProve → (keys package) pcztSign → pcztSubmit
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
index 15f41a432..20442ae1d 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
@@ -90,7 +90,8 @@ pub enum ErrorCode {
     /// should `rewindTo` the suggested height and resume syncing.
     ReorgDetected,
     /// An async operation is in flight; the wallet cannot be switched or closed now.
-    /// Params: `{ operation }`
+    /// Params: `{ operation }`. With `reason: "pendingSend"`, `rescanAccount` waits
+    /// for the account's unmined send before starting over at a later birthday.
     ///
     /// Concurrency guard: swapping databases mid-operation would silently write
     /// results to the wrong wallet. Hosts should serialize calls to one runtime or
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
index 9131b582c..c6f80617b 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
@@ -36,15 +36,198 @@ use crate::error::{ErrorCode, Result, RuntimeError};
 use crate::network::LightClient;
 use crate::wallet::Db;
 
-/// Pick a range from the upstream suggestions by priority.
-///
-/// `None` means any, in upstream order (ChainTip before Historic). With a priority,
-/// only that lane is considered, so host progress stays attributed to it.
-fn pick_range(suggested: &[ScanRange], preferred: Option) -> Option {
+/// Bound speculative scanning to the earlier Ironwood / Orchard tail, capped at 30 days.
+/// `pick_range` also floors the cut at the upstream ChainTip start. Note-shard
+/// completion and reorg safety can extend this window.
+const FAST_WINDOW_MAX_BLOCKS: u32 = 34_560;
+const FAST_WINDOW_REORG_MARGIN: u32 = 200;
+
+/// Keep upstream Verify / FoundNote / OpenAdjacent handling. Only partition ChainTip:
+/// its suffix runs in the fast lane, its prefix joins Historic in ascending order.
+/// Keep the original priority on returned ranges for progress attribution.
+fn pick_range(
+    suggested: &[ScanRange],
+    preferred: Option,
+    window_start: BlockHeight,
+) -> Option {
+    let Some(lane) = preferred else {
+        return [
+            ScanPriority::Verify,
+            ScanPriority::ChainTip,
+            ScanPriority::FoundNote,
+            ScanPriority::OpenAdjacent,
+            ScanPriority::Historic,
+        ]
+        .into_iter()
+        .find_map(|lane| pick_range(suggested, Some(lane), window_start));
+    };
     suggested
         .iter()
-        .find(|r| !r.is_empty() && preferred.is_none_or(|p| r.priority() == p))
-        .cloned()
+        .filter(|r| !r.is_empty())
+        .filter_map(|r| {
+            let bounds = r.block_range();
+            match (lane, r.priority()) {
+                (ScanPriority::ChainTip, ScanPriority::ChainTip) if bounds.end > window_start => {
+                    Some(ScanRange::from_parts(
+                        bounds.start.max(window_start)..bounds.end,
+                        r.priority(),
+                    ))
+                }
+                (ScanPriority::Historic, ScanPriority::ChainTip) if bounds.start < window_start => {
+                    Some(ScanRange::from_parts(
+                        bounds.start..bounds.end.min(window_start),
+                        r.priority(),
+                    ))
+                }
+                (p, q) if p == q && p != ScanPriority::ChainTip => Some(r.clone()),
+                _ => None,
+            }
+        })
+        .min_by_key(|r| {
+            // Upstream orders equal-priority ranges by height as well. In particular,
+            // Historic and demoted ChainTip ranges must share one ascending lane.
+            r.block_range().start
+        })
+}
+
+fn window_start(db: &mut Db) -> Result {
+    let Some(tip) = db.chain_height().map_err(|e| db_err("chainHeight", e))? else {
+        return Ok(BlockHeight::from_u32(u32::MAX));
+    };
+    let ironwood_activation = db
+        .params()
+        .activation_height(NetworkUpgrade::Nu6_3)
+        .unwrap_or(BlockHeight::from_u32(0));
+    let orchard_activation = db
+        .params()
+        .activation_height(NetworkUpgrade::Nu5)
+        .unwrap_or(BlockHeight::from_u32(0));
+    db.transactionally_with_extension(|_, ext| {
+        let (ironwood, orchard): (Option, Option) = ext.query_row(
+            "SELECT (SELECT MAX(subtree_end_height) FROM ironwood_tree_shards),
+                    (SELECT MAX(subtree_end_height) FROM orchard_tree_shards)",
+            [],
+            |row| Ok((row.get(0)?, row.get(1)?)),
+        )?;
+        let ironwood = ironwood
+            .map(BlockHeight::from_u32)
+            .unwrap_or(ironwood_activation);
+        let orchard = orchard
+            .map(BlockHeight::from_u32)
+            .unwrap_or(orchard_activation);
+        let mut start = ironwood
+            .min(orchard)
+            .max(tip.saturating_sub(FAST_WINDOW_MAX_BLOCKS))
+            .min(tip.saturating_sub(FAST_WINDOW_REORG_MARGIN));
+
+        // A newly discovered note can span the cut. Complete its entire shard before
+        // moving on, even when its below-window ranges still have ChainTip priority
+        // and therefore cannot be promoted to FoundNote by upstream. Repeat because
+        // extending one pool's window can expose an overlapping shard in the other.
+        loop {
+            let before = start;
+            for pool in ["orchard", "ironwood"] {
+                let note_start: Option = ext.query_row(
+                    &format!(
+                        "SELECT MIN(ss.subtree_start_height)
+                         FROM {pool}_received_notes rn
+                         JOIN v_{pool}_shards_scan_state ss
+                           ON rn.commitment_tree_position >= ss.start_position
+                          AND rn.commitment_tree_position < ss.end_position_exclusive
+                         WHERE ss.max_priority > 10 AND ss.subtree_start_height < ?1
+                           AND IFNULL(ss.subtree_end_height, ?2) >= ?1"
+                    ),
+                    rusqlite::params![u32::from(start), u32::from(tip)],
+                    |row| row.get(0),
+                )?;
+                if let Some(note_start) = note_start {
+                    start = start.min(BlockHeight::from_u32(note_start));
+                }
+            }
+            if start == before {
+                break;
+            }
+        }
+        Ok(start)
+    })
+    .map_err(|e: rusqlite::Error| db_err("fastWindow", e))
+}
+
+/// A frontier cannot bridge missing completed shards in SQLite's shard store.
+/// Check every pool, including Sapling whose ownership scanning is disabled.
+fn roots_cover(db: &mut Db, state: &ChainState) -> Result {
+    let sizes = [
+        ("sapling", state.final_sapling_tree().tree_size()),
+        ("orchard", state.final_orchard_tree().tree_size()),
+        ("ironwood", state.final_ironwood_tree().tree_size()),
+    ];
+    db.transactionally_with_extension(|_, ext| {
+        for (pool, size) in sizes {
+            let required = size >> 16;
+            let known: u64 = ext.query_row(
+                &format!(
+                    "SELECT COUNT(*) FROM {pool}_tree_shards
+                     WHERE shard_index >= 0 AND shard_index < ?1
+                       AND subtree_end_height IS NOT NULL AND root_hash IS NOT NULL"
+                ),
+                [required],
+                |row| row.get(0),
+            )?;
+            if known != required {
+                return Ok(false);
+            }
+        }
+        Ok(true)
+    })
+    .map_err(|e: rusqlite::Error| db_err("fastWindowRoots", e))
+}
+
+/// When the server's roots lag, use upstream's original ChainTip start until
+/// sequential scanning has filled the gap. Never retry the impossible jump forever.
+fn guard_fast_range(
+    db: &mut Db,
+    suggested: &[ScanRange],
+    range: ScanRange,
+    state: &ChainState,
+) -> Result {
+    if range.priority() == ScanPriority::ChainTip {
+        if let Some(original) = suggested
+            .iter()
+            .filter(|r| !r.is_empty() && r.priority() == ScanPriority::ChainTip)
+            .min_by_key(|r| r.block_range().start)
+        {
+            if range.block_range().start > original.block_range().start && !roots_cover(db, state)?
+            {
+                return Ok(original.clone());
+            }
+        }
+    }
+    Ok(range)
+}
+
+async fn range_chain_state(
+    db: &Db,
+    client: &mut LightClient,
+    start: BlockHeight,
+) -> Result {
+    let anchor = anchor_height(db.params(), start);
+    crate::network::with_timeout(
+        async {
+            client
+                .get_tree_state(service::BlockId {
+                    height: u64::from(anchor),
+                    hash: Vec::new(),
+                })
+                .await
+                .map_err(|e| net_err("getTreeState", e))?
+                .into_inner()
+                .to_chain_state()
+                .map_err(|e| net_err("toChainState", e))
+        },
+        crate::network::DEFAULT_TIMEOUT_MS,
+        "getTreeState",
+    )
+    .await
 }
 
 /// Host-selectable priority, as strings so values are checkable across the boundary.
@@ -220,11 +403,32 @@ pub async fn step(
             .suggest_scan_ranges()
             .map_err(|e| db_err("suggestScanRanges", e))?;
 
-        // The host picks the priority; candidates come only from upstream suggestions.
-        let Some(range) = pick_range(&suggested, preferred) else {
+        // Special-priority and empty passes need no window/shard queries.
+        let window = if preferred
+            .is_none_or(|p| matches!(p, ScanPriority::ChainTip | ScanPriority::Historic))
+            && suggested
+                .iter()
+                .any(|r| r.priority() == ScanPriority::ChainTip)
+        {
+            window_start(db)?
+        } else {
+            BlockHeight::from_u32(0)
+        };
+        let Some(range) = pick_range(&suggested, preferred, window) else {
             break; // no pending ranges at this priority
         };
 
+        // Reuse the treestate needed by scanning to validate the jump before downloading.
+        // Only a fallback needs a second treestate request; window planning is local SQL.
+        let t_tree = now_ms();
+        let mut chain_state = range_chain_state(db, client, range.block_range().start).await?;
+        let original_start = range.block_range().start;
+        let range = guard_fast_range(db, &suggested, range, &chain_state)?;
+        if range.block_range().start != original_start {
+            chain_state = range_chain_state(db, client, range.block_range().start).await?;
+        }
+        ms_treestate += now_ms() - t_tree;
+
         // Take only this batch; the rest is left for later calls.
         let start = range.block_range().start;
         if scanned_from.is_none() {
@@ -298,28 +502,7 @@ pub async fn step(
         let t_downloaded = now_ms();
         ms_download += t_downloaded - t_start;
 
-        let anchor = anchor_height(¶ms, start);
-
-        let chain_state = crate::network::with_timeout(
-            async {
-                client
-                    .get_tree_state(service::BlockId {
-                        height: u64::from(anchor),
-                        hash: Vec::new(),
-                    })
-                    .await
-                    .map_err(|e| net_err("getTreeState", e))?
-                    .into_inner()
-                    .to_chain_state()
-                    .map_err(|e| net_err("toChainState", e))
-            },
-            crate::network::DEFAULT_TIMEOUT_MS,
-            "getTreeState",
-        )
-        .await?;
-
-        let t_treestate = now_ms();
-        ms_treestate += t_treestate - t_downloaded;
+        let t_scan = now_ms();
 
         // Reorgs surface as REORG_DETECTED with an exact atHeight.
         scan_blocks_inline(
@@ -332,7 +515,7 @@ pub async fn step(
             batch_len,
         )?;
 
-        ms_scan += now_ms() - t_treestate;
+        ms_scan += now_ms() - t_scan;
 
         blocks_scanned += batch_len as u64;
 
@@ -662,10 +845,7 @@ pub fn account_status(db: &Db, account_uuid: &str) -> Result {
         lowest_pending = Some(lowest_pending.map_or(start, |cur: u32| cur.min(start)));
     }
 
-    let summary = db
-        .get_wallet_summary(zcash_client_backend::data_api::wallet::ConfirmationsPolicy::default())
-        .map_err(|e| db_err("walletSummary", e))?;
-    let chain_tip = summary.as_ref().map(|s| u32::from(s.chain_tip_height()));
+    let (chain_tip, fully_scanned) = scan_heights(db)?;
 
     // Scanned height = lowest pending height for this account, else the chain tip.
     let scanned_to = lowest_pending.or(chain_tip);
@@ -673,6 +853,7 @@ pub fn account_status(db: &Db, account_uuid: &str) -> Result {
     Ok(json!({
         "birthdayHeight": birthday,
         "chainTip": chain_tip,
+        "fullyScannedHeight": fully_scanned,
         "scannedToHeight": scanned_to,
         "remainingBlocks": remaining,
         "isComplete": remaining == 0,
@@ -680,6 +861,23 @@ pub fn account_status(db: &Db, account_uuid: &str) -> Result {
     .to_string())
 }
 
+// Polling heights must not recompute every account's balances and subtree progress.
+fn scan_heights(db: &Db) -> Result<(Option, Option)> {
+    let chain_tip = db.chain_height().map_err(|e| db_err("chainHeight", e))?;
+    let birthday = db
+        .get_wallet_birthday()
+        .map_err(|e| db_err("walletBirthday", e))?;
+    let (Some(chain_tip), Some(birthday)) = (chain_tip, birthday) else {
+        return Ok((None, None));
+    };
+    let fully_scanned = db
+        .block_fully_scanned()
+        .map_err(|e| db_err("blockFullyScanned", e))?
+        .map(|block| u32::from(block.block_height()))
+        .unwrap_or(u32::from(birthday).saturating_sub(1));
+    Ok((Some(u32::from(chain_tip)), Some(fully_scanned)))
+}
+
 /// Read-only: the ranges the wallet currently suggests scanning. No network requests.
 pub fn peek(db: &Db) -> Result {
     let ranges = db
@@ -699,7 +897,14 @@ pub fn peek(db: &Db) -> Result {
         .collect();
 
     let total: u64 = ranges.iter().map(|r| r.len() as u64).sum();
-    Ok(json!({ "ranges": items, "totalBlocks": total }).to_string())
+    let (chain_tip, fully_scanned) = scan_heights(db)?;
+    Ok(json!({
+        "ranges": items,
+        "totalBlocks": total,
+        "chainTip": chain_tip,
+        "fullyScannedHeight": fully_scanned,
+    })
+    .to_string())
 }
 
 #[cfg(target_arch = "wasm32")]
@@ -886,6 +1091,10 @@ pub fn queue_rescan_from(db: &mut Db, from_height: u32) -> Result {
     .to_string())
 }
 
+#[cfg(test)]
+#[path = "sync_tests.rs"]
+mod scan_order_tests;
+
 #[cfg(test)]
 mod tests {
     use super::*;
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs
new file mode 100644
index 000000000..932b1be1c
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs
@@ -0,0 +1,1722 @@
+//! Offline regression tests through the production scanner and wallet database.
+//! Deterministic synthetic chain, generated in memory without network, files or
+//! proving parameters. The layout and compact-note construction are adapted from
+//! the upstream TestBuilder experiment that produced the former binary fixtures.
+//! There are 501 blocks, three accounts, both Orchard and Ironwood receives and
+//! spends, a completed shard in each pool (including Sapling), and a 35-block fork.
+
+use super::*;
+use std::collections::BTreeMap;
+use std::sync::OnceLock;
+
+use incrementalmerkletree::{frontier::Frontier, Hashable};
+use orchard::{
+    keys::FullViewingKey,
+    note::{ExtractedNoteCommitment, NoteVersion, Nullifier, RandomSeed, Rho},
+    note_encryption::{
+        IronwoodDomain, IronwoodNoteEncryption, OrchardDomain, OrchardNoteEncryption,
+    },
+    tree::MerkleHashOrchard,
+};
+use rand::{RngCore, SeedableRng};
+use rand_chacha::ChaCha20Rng;
+use zcash_client_backend::data_api::{Account, AccountBirthday, AccountPurpose};
+use zcash_client_backend::proto::compact_formats::{
+    ChainMetadata, CompactBlock, CompactOrchardAction, CompactSaplingOutput, CompactTx,
+};
+use zcash_client_sqlite::error::SqliteClientError;
+use zcash_keys::keys::UnifiedSpendingKey;
+use zcash_note_encryption::Domain;
+use zcash_primitives::block::BlockHash;
+use zcash_primitives::merkle_tree::read_frontier_v1;
+use zcash_protocol::consensus::Network;
+use zip32::Scope;
+
+fn height(h: u32) -> BlockHeight {
+    BlockHeight::from_u32(h)
+}
+
+fn range(start: u32, end: u32, priority: ScanPriority) -> ScanRange {
+    ScanRange::from_parts(height(start)..height(end), priority)
+}
+
+struct Fixture {
+    birthday: u32,
+    tip: u32,
+    keys: Vec,
+    sapling: Vec>,
+    orchard: Vec>,
+    ironwood: Vec>,
+    states: BTreeMap,
+    blocks: BTreeMap,
+}
+
+const SHARD_SIZE: u32 = 1 << 16;
+
+fn random_hash(rng: &mut ChaCha20Rng) -> H {
+    loop {
+        let mut bytes = [0; 32];
+        rng.fill_bytes(&mut bytes);
+        if let Ok(hash) = H::read(&bytes[..]) {
+            return hash;
+        }
+    }
+}
+
+/// Like TestBuilder's random_with_prior_subtree_roots, construct a pruned
+/// frontier with distinct completed roots and matching high-level ommers.
+/// Only O(depth + completed shards) hashes are needed for the historical tree.
+fn initial_tree(
+    rng: &mut ChaCha20Rng,
+    size: u32,
+    end: u32,
+) -> (Frontier, Vec>) {
+    let roots: Vec = (0..size / SHARD_SIZE).map(|_| random_hash(rng)).collect();
+    let mut completed: Vec<(u8, H)> = Vec::new();
+    for root in &roots {
+        let (mut level, mut node) = (16, root.clone());
+        while completed.last().is_some_and(|(l, _)| *l == level) {
+            let (_, left) = completed.pop().unwrap();
+            node = H::combine(level.into(), &left, &node);
+            level += 1;
+        }
+        completed.push((level, node));
+    }
+    let position = size - 1;
+    let tree = Frontier::from_parts(
+        u64::from(position).into(),
+        random_hash(rng),
+        (0..32)
+            .filter(|level| position & (1 << level) != 0)
+            .map(|level| {
+                if level < 16 {
+                    random_hash(rng)
+                } else {
+                    completed
+                        .iter()
+                        .find(|(l, _)| *l == level)
+                        .unwrap()
+                        .1
+                        .clone()
+                }
+            })
+            .collect(),
+    )
+    .unwrap();
+    (
+        tree,
+        roots
+            .into_iter()
+            .map(|r| CommitmentTreeRoot::from_parts(height(end), r))
+            .collect(),
+    )
+}
+
+fn append(
+    tree: &mut Frontier,
+    roots: &mut Vec>,
+    leaf: H,
+    h: u32,
+) {
+    assert!(tree.append(leaf));
+    if tree.tree_size() % u64::from(SHARD_SIZE) == 0 {
+        roots.push(CommitmentTreeRoot::from_parts(
+            height(h),
+            tree.value().unwrap().root(Some(16.into())),
+        ));
+    }
+}
+
+#[derive(Clone, Copy)]
+enum Pool {
+    Orchard,
+    Ironwood,
+}
+
+struct ChainBuilder {
+    rng: ChaCha20Rng,
+    f: Fixture,
+    // A, B, C and an unowned filler recipient.
+    fvks: Vec,
+}
+
+impl ChainBuilder {
+    fn new() -> Self {
+        let birthday = 4_135_000;
+        let mut rng = ChaCha20Rng::from_seed([0; 32]);
+        let usks: Vec<_> = [(0, 0), (0, 1), (9, 0), (0xf5, 0)]
+            .into_iter()
+            .map(|(seed, account)| {
+                UnifiedSpendingKey::from_seed(
+                    &Network::TestNetwork,
+                    &[seed; 32],
+                    zip32::AccountId::try_from(account).unwrap(),
+                )
+                .unwrap()
+            })
+            .collect();
+        let (sapling_tree, sapling) = initial_tree(&mut rng, 2 * SHARD_SIZE - 2, birthday - 500);
+        let (orchard_tree, orchard) = initial_tree(&mut rng, 3 * SHARD_SIZE - 200, birthday - 500);
+        let (ironwood_tree, ironwood) =
+            initial_tree(&mut rng, 3 * SHARD_SIZE - 300, birthday - 300);
+        let prior = ChainState::new(
+            height(birthday - 1),
+            BlockHash([5; 32]),
+            sapling_tree,
+            orchard_tree,
+            ironwood_tree,
+        );
+        Self {
+            rng,
+            f: Fixture {
+                birthday,
+                tip: birthday - 1,
+                keys: usks[..3]
+                    .iter()
+                    .map(|k| {
+                        k.to_unified_full_viewing_key()
+                            .encode(&Network::TestNetwork)
+                    })
+                    .collect(),
+                sapling,
+                orchard,
+                ironwood,
+                states: BTreeMap::from([(birthday - 1, prior)]),
+                blocks: BTreeMap::new(),
+            },
+            fvks: usks
+                .iter()
+                .map(|k| FullViewingKey::from(k.orchard()))
+                .collect(),
+        }
+    }
+
+    fn random_bytes(&mut self) -> [u8; 32] {
+        let mut bytes = [0; 32];
+        self.rng.fill_bytes(&mut bytes);
+        bytes
+    }
+
+    fn random_nf(&mut self) -> Nullifier {
+        loop {
+            if let Some(nf) = Option::from(Nullifier::from_bytes(&self.random_bytes())) {
+                return nf;
+            }
+        }
+    }
+
+    /// Mirrors TestBuilder's compact Orchard / Ironwood action construction,
+    /// using the matching V2 / V3 note-encryption domain and a real nullifier.
+    fn action(
+        &mut self,
+        pool: Pool,
+        key: usize,
+        scope: Scope,
+        value: u64,
+        nf_old: Nullifier,
+    ) -> (CompactOrchardAction, Nullifier) {
+        let rho = Rho::from_bytes(&nf_old.to_bytes()).unwrap();
+        let rseed = loop {
+            if let Some(seed) = Option::from(RandomSeed::from_bytes(self.random_bytes(), &rho)) {
+                break seed;
+            }
+        };
+        let note = orchard::Note::from_parts(
+            self.fvks[key].address_at(0u32, scope),
+            orchard::value::NoteValue::from_raw(value),
+            rho,
+            rseed,
+            match pool {
+                Pool::Orchard => NoteVersion::V2,
+                Pool::Ironwood => NoteVersion::V3,
+            },
+        )
+        .unwrap();
+        let (ephemeral_key, ciphertext) = match pool {
+            Pool::Orchard => {
+                let enc = OrchardNoteEncryption::new(None, note, [0; 512]);
+                (
+                    OrchardDomain::epk_bytes(enc.epk()),
+                    enc.encrypt_note_plaintext(),
+                )
+            }
+            Pool::Ironwood => {
+                let enc = IronwoodNoteEncryption::new(None, note, [0; 512]);
+                (
+                    IronwoodDomain::epk_bytes(enc.epk()),
+                    enc.encrypt_note_plaintext(),
+                )
+            }
+        };
+        (
+            CompactOrchardAction {
+                nullifier: nf_old.to_bytes().to_vec(),
+                cmx: ExtractedNoteCommitment::from(note.commitment())
+                    .to_bytes()
+                    .to_vec(),
+                ephemeral_key: ephemeral_key.0.to_vec(),
+                ciphertext: ciphertext[..52].to_vec(),
+            },
+            note.nullifier(&self.fvks[key]),
+        )
+    }
+
+    fn push(&mut self, tx: CompactTx) {
+        let h = self.f.tip + 1;
+        let prior = &self.f.states[&self.f.tip];
+        let mut sapling = prior.final_sapling_tree().clone();
+        let mut orchard = prior.final_orchard_tree().clone();
+        let mut ironwood = prior.final_ironwood_tree().clone();
+        for output in &tx.outputs {
+            append(
+                &mut sapling,
+                &mut self.f.sapling,
+                sapling::Node::from_cmu(&output.cmu().unwrap()),
+                h,
+            );
+        }
+        for (actions, tree, roots) in [
+            (&tx.actions, &mut orchard, &mut self.f.orchard),
+            (&tx.ironwood_actions, &mut ironwood, &mut self.f.ironwood),
+        ] {
+            for action in actions {
+                append(
+                    tree,
+                    roots,
+                    MerkleHashOrchard::from_cmx(&action.cmx().unwrap()),
+                    h,
+                );
+            }
+        }
+        let metadata = ChainMetadata {
+            sapling_commitment_tree_size: sapling.tree_size() as u32,
+            orchard_commitment_tree_size: orchard.tree_size() as u32,
+            ironwood_commitment_tree_size: ironwood.tree_size() as u32,
+        };
+        let prev_hash = prior.block_hash().0.to_vec();
+        let hash = self.random_bytes();
+        self.f.blocks.insert(
+            h,
+            CompactBlock {
+                height: u64::from(h),
+                hash: hash.to_vec(),
+                prev_hash,
+                vtx: vec![tx],
+                chain_metadata: Some(metadata),
+                ..Default::default()
+            },
+        );
+        self.f.states.insert(
+            h,
+            ChainState::new(height(h), BlockHash(hash), sapling, orchard, ironwood),
+        );
+        self.f.tip = h;
+    }
+
+    fn transaction(&mut self, pool: Pool, actions: Vec) {
+        let mut tx = CompactTx {
+            txid: self.random_bytes().to_vec(),
+            ..Default::default()
+        };
+        match pool {
+            Pool::Orchard => tx.actions = actions,
+            Pool::Ironwood => tx.ironwood_actions = actions,
+        }
+        self.push(tx);
+    }
+
+    fn receive(&mut self, pool: Pool, key: usize, value: u64) -> (Nullifier, u64) {
+        let nf = self.random_nf();
+        let (action, nf) = self.action(pool, key, Scope::External, value, nf);
+        self.transaction(pool, vec![action]);
+        (nf, value)
+    }
+
+    fn spend(&mut self, pool: Pool, key: usize, (nf, value): (Nullifier, u64), pay: u64) {
+        let (change, _) = self.action(pool, key, Scope::Internal, value - pay, nf);
+        let nf = self.random_nf();
+        // TestBuilder's payment receiver is a UA with an Orchard receiver, even
+        // when the spent note and its change belong to Ironwood.
+        let (payment, _) = self.action(Pool::Orchard, 3, Scope::External, pay, nf);
+        let mut tx = CompactTx {
+            txid: self.random_bytes().to_vec(),
+            actions: vec![payment],
+            ..Default::default()
+        };
+        match pool {
+            Pool::Orchard => tx.actions.insert(0, change),
+            Pool::Ironwood => tx.ironwood_actions.push(change),
+        }
+        self.push(tx);
+    }
+
+    fn filler_to(&mut self, offset: u32) {
+        while self.f.tip + 1 < self.f.birthday + offset {
+            let pool = if (self.f.tip + 1) % 3 == 0 {
+                Pool::Orchard
+            } else {
+                Pool::Ironwood
+            };
+            self.receive(pool, 3, 1000);
+        }
+    }
+
+    /// Put owned notes immediately before and after the next shard boundary.
+    fn fill(&mut self, pool: Pool, marks: &[(i32, usize, u64)]) -> Vec<(Nullifier, u64)> {
+        let state = &self.f.states[&self.f.tip];
+        let start = match pool {
+            Pool::Orchard => state.final_orchard_tree().tree_size() as u32,
+            Pool::Ironwood => state.final_ironwood_tree().tree_size() as u32,
+        };
+        let boundary = (start / SHARD_SIZE + 1) * SHARD_SIZE;
+        let mut actions = Vec::new();
+        let mut notes = Vec::new();
+        for position in start..boundary + 5 {
+            let mark = marks
+                .iter()
+                .find(|m| i64::from(boundary) + i64::from(m.0) == i64::from(position));
+            let (_, key, value) = mark.copied().unwrap_or((0, 3, 1000));
+            let nf = self.random_nf();
+            let (action, nf) = self.action(pool, key, Scope::External, value, nf);
+            actions.push(action);
+            if mark.is_some() {
+                notes.push((nf, value));
+            }
+        }
+        self.transaction(pool, actions);
+        notes
+    }
+
+    fn build(mut self) -> Self {
+        use Pool::{Ironwood as I, Orchard as O};
+        self.receive(O, 3, 1000); // birthday + 0
+        self.receive(O, 3, 1000);
+        let a_i110 = self.receive(I, 0, 110_000);
+        let a_o100 = self.receive(O, 0, 100_000);
+        self.filler_to(25); // B's birthday is +20.
+        self.receive(I, 1, 60_000);
+        self.receive(O, 1, 70_000);
+        self.filler_to(33); // C's birthday is +30.
+        self.receive(I, 2, 33_000);
+        self.filler_to(40);
+        // Complete Sapling's second shard with two unowned, valid outputs.
+        let sk = sapling::zip32::ExtendedSpendingKey::master(&[0xf6; 32]);
+        let outputs = (0..2)
+            .map(|_| {
+                let note = sapling::Note::from_parts(
+                    sk.default_address().1,
+                    sapling::value::NoteValue::from_raw(1000),
+                    sapling::Rseed::AfterZip212(self.random_bytes()),
+                );
+                let enc = sapling::note_encryption::sapling_note_encryption(
+                    None,
+                    note.clone(),
+                    [0; 512],
+                    &mut self.rng,
+                );
+                CompactSaplingOutput {
+                    cmu: note.cmu().to_bytes().to_vec(),
+                    ephemeral_key: sapling::note_encryption::SaplingDomain::epk_bytes(enc.epk())
+                        .0
+                        .to_vec(),
+                    ciphertext: enc.encrypt_note_plaintext()[..52].to_vec(),
+                }
+            })
+            .collect();
+        let txid = self.random_bytes().to_vec();
+        self.push(CompactTx {
+            txid,
+            outputs,
+            ..Default::default()
+        });
+        self.filler_to(50);
+        self.spend(O, 0, a_o100, 30_000);
+        self.filler_to(60);
+        self.spend(I, 0, a_i110, 40_000);
+        self.filler_to(69);
+        let orchard = self.fill(
+            O,
+            &[
+                (-1, 0, 200_000),
+                (0, 0, 150_000),
+                (1, 1, 80_000),
+                (3, 0, 50_000),
+                (4, 1, 90_000),
+            ],
+        );
+        self.filler_to(99);
+        let ironwood = self.fill(
+            I,
+            &[
+                (-1, 0, 210_000),
+                (0, 0, 220_000),
+                (1, 1, 85_000),
+                (2, 2, 44_000),
+                (3, 0, 230_000),
+                (4, 1, 95_000),
+            ],
+        );
+        self.filler_to(140);
+        let a_i300 = self.receive(I, 0, 300_000);
+        self.filler_to(150);
+        self.spend(I, 0, ironwood[1], 70_000); // received below the window
+        self.filler_to(160);
+        self.spend(O, 0, orchard[0], 20_000); // change in Orchard's tail
+        self.filler_to(170);
+        self.spend(I, 1, ironwood[5], 15_000);
+        self.filler_to(180);
+        self.spend(I, 0, a_i300, 120_000); // received and spent in the window
+        self.filler_to(190);
+        self.receive(I, 2, 66_000);
+        self.filler_to(501);
+        assert_eq!(self.f.blocks.len(), 501);
+        assert_eq!(self.f.sapling.len(), 2);
+        assert_eq!(self.f.orchard.len(), 3);
+        assert_eq!(self.f.ironwood.len(), 3);
+        self
+    }
+}
+
+fn fixture() -> &'static Fixture {
+    static FIXTURE: OnceLock = OnceLock::new();
+    FIXTURE.get_or_init(|| ChainBuilder::new().build().f)
+}
+
+fn fork_fixture() -> Fixture {
+    let mut fork = ChainBuilder::new().build();
+    let at = fork.f.birthday + 465;
+    fork.f.blocks.retain(|h, _| *h <= at);
+    fork.f.states.retain(|h, _| *h <= at);
+    fork.f.tip = at;
+    fork.receive(Pool::Ironwood, 3, 777);
+    while fork.f.tip < fork.f.birthday + 501 {
+        fork.receive(Pool::Ironwood, 3, 778);
+    }
+    fork.f
+}
+
+fn old_birthday_fixture(blocks: u32) -> Fixture {
+    let mut f = ChainBuilder::new().build().f;
+    f.tip = f.birthday + blocks - 1;
+    f.blocks.retain(|h, _| *h <= f.tip);
+    f.states.retain(|h, _| *h <= f.tip);
+    f
+}
+
+fn scanned_a(f: &Fixture) -> Db {
+    scanned_a_at(f, ":memory:")
+}
+
+fn scanned_a_at(f: &Fixture, name: &str) -> Db {
+    let mut db = wallet_at(f, &[0], name);
+    scan(&mut db, f, f.birthday, 200, &f.keys[..1]).unwrap();
+    scan(
+        &mut db,
+        f,
+        f.birthday + 200,
+        f.tip - f.birthday - 199,
+        &f.keys[..1],
+    )
+    .unwrap();
+    db
+}
+
+fn import(db: &mut Db, f: &Fixture, key: usize, offset: u32) -> AccountUuid {
+    try_import(db, f, key, offset).unwrap()
+}
+
+fn try_import(db: &mut Db, f: &Fixture, key: usize, offset: u32) -> Result {
+    db.import_account_ufvk(
+        &format!("account {key}"),
+        &UnifiedFullViewingKey::decode(db.params(), &f.keys[key]).unwrap(),
+        &AccountBirthday::from_parts(f.states[&(f.birthday + offset - 1)].clone(), None),
+        AccountPurpose::Spending { derivation: None },
+        None,
+    )
+    .map(|account| account.id())
+    .map_err(crate::account::import_error)
+}
+
+fn wallet(f: &Fixture, offsets: &[u32]) -> Db {
+    wallet_at(f, offsets, ":memory:")
+}
+
+fn wallet_at(f: &Fixture, offsets: &[u32], name: &str) -> Db {
+    let mut db = crate::wallet::open_and_migrate("test", name).unwrap();
+    for (i, offset) in offsets.iter().enumerate() {
+        import(&mut db, f, i, *offset);
+    }
+    db.put_sapling_subtree_roots(0, &f.sapling).unwrap();
+    db.put_orchard_subtree_roots(0, &f.orchard).unwrap();
+    db.put_ironwood_subtree_roots(0, &f.ironwood).unwrap();
+    db.update_chain_tip(height(f.tip)).unwrap();
+    db
+}
+
+fn seed_unmined_sends(conn: &rusqlite::Connection, tip: u32, account_offset: usize) {
+    seed_unmined_sends_at_positions(conn, tip, account_offset, None);
+}
+
+fn seed_unmined_sends_at_positions(
+    conn: &rusqlite::Connection,
+    tip: u32,
+    account_offset: usize,
+    positions: Option<&[u64]>,
+) -> Vec {
+    let (id, uuid): (i64, Vec) = conn
+        .query_row(
+            "SELECT id, uuid FROM accounts ORDER BY id LIMIT 1 OFFSET ?1",
+            [account_offset as i64],
+            |r| Ok((r.get(0)?, r.get(1)?)),
+        )
+        .unwrap();
+    let notes: Vec<(i64, u64)> = conn.prepare("SELECT id, commitment_tree_position FROM orchard_received_notes n WHERE account_id = ?1 AND (?2 IS NULL OR commitment_tree_position IN (?2, ?3)) AND NOT EXISTS (SELECT 1 FROM orchard_received_note_spends s WHERE s.orchard_received_note_id = n.id) ORDER BY commitment_tree_position LIMIT 2").unwrap()
+        .query_map(rusqlite::params![id, positions.and_then(|p| p.first()).copied(), positions.and_then(|p| p.get(1)).copied()], |r| Ok((r.get(0)?, r.get(1)?))).unwrap().collect::>().unwrap();
+    assert_eq!(notes.len(), 2);
+    for index in 0..2u8 {
+        let note = notes[index as usize].0;
+        // Inert raw markers exercise storage retention, not signing/broadcast.
+        let txid = [0xe1 + index; 32];
+        conn.execute("INSERT INTO transactions (txid, created, expiry_height, raw, min_observed_height) VALUES (?1, '2026-10-23T00:00:00Z', ?2, ?3, ?4)", rusqlite::params![txid.as_slice(), tip + 40, [index, 0x55].as_slice(), tip]).unwrap();
+        conn.execute("INSERT INTO orchard_received_note_spends (orchard_received_note_id, transaction_id) VALUES (?1, ?2)", rusqlite::params![note, conn.last_insert_rowid()]).unwrap();
+        if index == 1 {
+            conn.execute("INSERT INTO ext_onekey_tx_state (txid, account_uuid, rejection_code, rejection_reason) VALUES (?1, ?2, 51, 'synthetic rejection')", rusqlite::params![txid.as_slice(), uuid]).unwrap();
+        }
+    }
+    notes.into_iter().map(|(_, p)| p).collect()
+}
+
+fn assert_pending_input_witnesses_and_locks(db: &mut Db, tip: u32) {
+    use zcash_client_backend::data_api::{wallet::input_selection::LockFilter, InputSource};
+    use zcash_primitives::transaction::TxId;
+    use zcash_protocol::ShieldedPool;
+    let inputs: Vec<(Vec, u32, u64)> = read_rows(db, "SELECT source.txid, n.action_index, n.commitment_tree_position FROM orchard_received_note_spends s JOIN orchard_received_notes n ON n.id = s.orchard_received_note_id JOIN transactions source ON source.id_tx = n.transaction_id JOIN transactions pending ON pending.id_tx = s.transaction_id WHERE pending.raw IS NOT NULL AND pending.mined_height IS NULL", |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)));
+    assert_eq!(inputs.len(), 2);
+    for (txid, index, position) in inputs {
+        assert!(db
+            .with_orchard_tree_mut(|tree| tree
+                .witness_at_checkpoint_depth(position.into(), 0)
+                .map_err(SqliteClientError::from))
+            .unwrap()
+            .is_some());
+        let txid = TxId::from_bytes(txid.try_into().unwrap());
+        assert!(
+            db.get_spendable_note(
+                &txid,
+                ShieldedPool::Orchard,
+                index,
+                (tip + 1).into(),
+                LockFilter::Unfiltered
+            )
+            .unwrap()
+            .is_none(),
+            "a pending send input must not be selected again"
+        );
+    }
+}
+
+fn send_evidence(db: &mut Db) -> Vec {
+    let mut evidence = rows(db, "SELECT hex(txid), hex(raw), mined_height, expiry_height FROM transactions WHERE raw IS NOT NULL ORDER BY txid");
+    evidence.extend(rows(
+        db,
+        "SELECT hex(txid), rejection_code, rejection_reason FROM ext_onekey_tx_state ORDER BY txid",
+    ));
+    evidence.extend(rows(db, "SELECT hex(t.txid), n.commitment_tree_position FROM orchard_received_note_spends s JOIN transactions t ON t.id_tx = s.transaction_id JOIN orchard_received_notes n ON n.id = s.orchard_received_note_id WHERE t.raw IS NOT NULL ORDER BY t.txid"));
+    evidence
+}
+
+fn scan(db: &mut Db, f: &Fixture, start: u32, len: u32, active: &[String]) -> Result<()> {
+    let cache = MemoryBlockCache::new();
+    cache
+        .insert(
+            f.blocks
+                .range(start..start + len)
+                .map(|(_, b)| b.clone())
+                .collect(),
+        )
+        .unwrap();
+    let params = *db.params();
+    let keys = ScanningKeys::from_account_ufvks(
+        select_active_scanning_ufvks(¶ms, db.get_unified_full_viewing_keys().unwrap(), active)
+            .unwrap(),
+    );
+    scan_blocks_inline(
+        ¶ms,
+        &cache,
+        db,
+        &keys,
+        height(start),
+        &f.states[&(start - 1)],
+        len as usize,
+    )
+}
+
+#[derive(Clone, Copy)]
+enum Order {
+    Upstream,
+    Ascending,
+    Window,
+    Any,
+}
+
+const LANES: [ScanPriority; 5] = [
+    ScanPriority::Verify,
+    ScanPriority::ChainTip,
+    ScanPriority::FoundNote,
+    ScanPriority::OpenAdjacent,
+    ScanPriority::Historic,
+];
+
+fn next(db: &mut Db, f: &Fixture, order: Order, lane: ScanPriority) -> Option {
+    let suggested = db.suggest_scan_ranges().unwrap();
+    match order {
+        Order::Upstream => suggested.into_iter().find(|r| r.priority() == lane),
+        Order::Ascending => suggested.into_iter().min_by_key(|r| r.block_range().start),
+        Order::Window | Order::Any => {
+            let selected = pick_range(
+                &suggested,
+                if matches!(order, Order::Any) {
+                    None
+                } else {
+                    Some(lane)
+                },
+                window_start(db).unwrap(),
+            )?;
+            let state = &f.states[&(u32::from(selected.block_range().start) - 1)];
+            Some(guard_fast_range(db, &suggested, selected, state).unwrap())
+        }
+    }
+}
+
+fn finish(db: &mut Db, f: &Fixture, order: Order, batch: u32, active: &[String]) {
+    for _ in 0..2000 {
+        if db.suggest_scan_ranges().unwrap().is_empty() {
+            return;
+        }
+        let mut advanced = false;
+        for lane in LANES {
+            if let Some(r) = next(db, f, order, lane) {
+                let start = u32::from(r.block_range().start);
+                scan(db, f, start, batch.min(r.len() as u32), active).unwrap();
+                advanced = true;
+            }
+        }
+        assert!(advanced, "pending ranges must be reachable");
+    }
+    panic!("scan order failed to converge");
+}
+
+fn read_rows(
+    db: &mut Db,
+    sql: &str,
+    mut read: impl FnMut(&rusqlite::Row<'_>) -> rusqlite::Result,
+) -> Vec {
+    use rusqlite::OptionalExtension;
+    db.transactionally_with_extension(|_, ext| {
+        let mut data = Vec::new();
+        loop {
+            let row = ext
+                .query_row(
+                    &format!("SELECT * FROM ({sql}) LIMIT 1 OFFSET {}", data.len()),
+                    [],
+                    &mut read,
+                )
+                .optional()?;
+            let Some(row) = row else {
+                break;
+            };
+            data.push(row);
+        }
+        Ok::<_, rusqlite::Error>(data)
+    })
+    .unwrap()
+}
+
+fn rows(db: &mut Db, sql: &str) -> Vec {
+    read_rows(db, sql, |r| {
+        Ok((0..r.as_ref().column_count())
+            .map(|i| format!("{:?}", r.get_ref(i).unwrap()))
+            .collect::>()
+            .join("|"))
+    })
+}
+
+fn all_table_rows(db: &mut Db) -> Vec {
+    let tables = read_rows(
+        db,
+        "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name",
+        |r| r.get::<_, String>(0),
+    );
+    let mut out = Vec::new();
+    for table in tables {
+        out.extend(
+            rows(db, &format!("SELECT * FROM \"{table}\""))
+                .into_iter()
+                .map(|row| format!("{table}: {row}")),
+        );
+    }
+    out.sort();
+    out
+}
+
+fn assert_checkpoints_diverged(error: RuntimeError) {
+    assert_eq!(error.code, ErrorCode::DatabaseError);
+    assert_eq!(
+        error.params,
+        json!({ "operation": "importAccount", "reason": "checkpointsDiverged", "checkpointHeight": 4135105 })
+    );
+    assert!(error.detail.unwrap().contains(
+        "the Orchard note commitment tree retains checkpoints both above and below height 4135105"
+    ));
+}
+
+/// Compare values, spentness, nullifiers, transaction deltas, spendable balances,
+/// final roots and every unspent note's witness. Compact-only is_change is an
+/// upstream order-dependent hint; full-transaction enhancement corrects it.
+fn snapshot(db: &mut Db, f: &Fixture) -> Vec {
+    let mut out = Vec::new();
+    for pool in ["orchard", "ironwood"] {
+        out.extend(rows(
+            db,
+            &format!(
+                "SELECT rn.account_id, hex(t.txid), rn.value, t.mined_height,
+                    rn.commitment_tree_position, hex(rn.nf), rn.recipient_key_scope,
+                    rn.witness_stabilized, hex(spent.txid)
+             FROM {pool}_received_notes rn JOIN transactions t ON t.id_tx = rn.transaction_id
+             LEFT JOIN {pool}_received_note_spends s ON s.{pool}_received_note_id = rn.id
+             LEFT JOIN transactions spent ON spent.id_tx = s.transaction_id
+             ORDER BY rn.account_id, rn.commitment_tree_position"
+            ),
+        ));
+        let positions: Vec = read_rows(db, &format!(
+                "SELECT commitment_tree_position FROM {pool}_received_notes rn
+                 WHERE rn.id NOT IN (SELECT {pool}_received_note_id FROM {pool}_received_note_spends)
+                 ORDER BY commitment_tree_position"
+            ), |r| r.get(0));
+        for p in positions {
+            let witness = if pool == "orchard" {
+                db.with_orchard_tree_mut(|t| {
+                    t.witness_at_checkpoint_depth(p.into(), 0)
+                        .map_err(SqliteClientError::from)
+                })
+                .unwrap()
+            } else {
+                db.with_ironwood_tree_mut(|t| {
+                    t.witness_at_checkpoint_depth(p.into(), 0)
+                        .map_err(SqliteClientError::from)
+                })
+                .unwrap()
+                .unwrap()
+            }
+            .expect("every unspent note has a usable witness");
+            out.push(format!("{pool} {p} {:?}", witness.path_elems()));
+        }
+    }
+    out.extend(rows(
+        db,
+        "SELECT a.id, hex(t.txid), t.mined_height, t.account_balance_delta,
+        t.spent_note_count FROM v_transactions t
+        JOIN accounts a ON a.uuid = t.account_uuid ORDER BY a.id, t.txid",
+    ));
+    let orchard = db
+        .with_orchard_tree_mut(|t| {
+            t.root_at_checkpoint_depth(Some(0))
+                .map_err(SqliteClientError::from)
+        })
+        .unwrap()
+        .unwrap();
+    let ironwood = db
+        .with_ironwood_tree_mut(|t| {
+            t.root_at_checkpoint_depth(Some(0))
+                .map_err(SqliteClientError::from)
+        })
+        .unwrap()
+        .unwrap()
+        .unwrap();
+    out.push(format!("roots {orchard:?} {ironwood:?}"));
+    let summary = db
+        .get_wallet_summary(zcash_client_backend::data_api::wallet::ConfirmationsPolicy::MIN)
+        .unwrap()
+        .unwrap();
+    for account in db.get_account_ids().unwrap() {
+        let b = summary.account_balances().get(&account).unwrap();
+        out.push(format!(
+            "balance {} {} {} {} {}",
+            db.get_account_birthday(account).unwrap(),
+            b.orchard_balance().total().into_u64(),
+            b.orchard_balance().spendable_value().into_u64(),
+            b.ironwood_balance().total().into_u64(),
+            b.ironwood_balance().spendable_value().into_u64()
+        ));
+    }
+    out.sort();
+    assert!(db.suggest_scan_ranges().unwrap().is_empty());
+    assert_eq!(
+        db.block_fully_scanned().unwrap().unwrap().block_height(),
+        height(f.tip)
+    );
+    out
+}
+
+fn assert_same(actual: Vec, expected: &[String]) {
+    let actual: std::collections::BTreeSet<_> = actual.iter().collect();
+    let expected: std::collections::BTreeSet<_> = expected.iter().collect();
+    let differences: Vec<_> = actual.symmetric_difference(&expected).collect();
+    assert!(
+        differences.is_empty(),
+        "{} different state rows: {:?}",
+        differences.len(),
+        differences.iter().take(3).collect::>()
+    );
+}
+
+#[test]
+fn equivalent_orders_across_both_pools_and_shard_boundaries() {
+    let f = fixture();
+    let mut reference = wallet(f, &[0, 20, 30]);
+    finish(&mut reference, f, Order::Ascending, 31, &f.keys);
+    let expected = snapshot(&mut reference, f);
+    assert!(expected.iter().any(|s| s.starts_with("orchard ")));
+    assert!(expected.iter().any(|s| s.starts_with("ironwood ")));
+    for (order, batch) in [
+        (Order::Upstream, 13),
+        (Order::Window, 7),
+        (Order::Window, 53),
+        (Order::Window, 131),
+        (Order::Any, 23),
+    ] {
+        let mut db = wallet(f, &[0, 20, 30]);
+        finish(&mut db, f, order, batch, &f.keys);
+        assert_same(snapshot(&mut db, f), &expected);
+    }
+}
+
+#[test]
+fn window_note_extends_to_its_orchard_shard_and_becomes_spendable() {
+    let f = fixture();
+    let mut db = wallet(f, &[0, 20, 30]);
+    let initial = window_start(&mut db).unwrap();
+    assert_eq!(initial, height(f.birthday + 69));
+    scan(&mut db, f, u32::from(initial), 132, &f.keys).unwrap();
+    // Starting at the earlier Orchard boundary also discovers its completing-
+    // block note. The cross-pool extension must include that older shard too.
+    assert_eq!(window_start(&mut db).unwrap(), height(f.birthday - 500));
+    // Finish fast work only: Historic remains pending, but both tail witnesses
+    // must be complete and their notes selectable before the full restore.
+    for _ in 0..100 {
+        let Some(r) = next(&mut db, f, Order::Window, ScanPriority::ChainTip) else {
+            break;
+        };
+        scan(
+            &mut db,
+            f,
+            u32::from(r.block_range().start),
+            31.min(r.len() as u32),
+            &f.keys,
+        )
+        .unwrap();
+    }
+    assert!(!db.suggest_scan_ranges().unwrap().is_empty());
+    let summary = db
+        .get_wallet_summary(zcash_client_backend::data_api::wallet::ConfirmationsPolicy::MIN)
+        .unwrap()
+        .unwrap();
+    let a = db
+        .get_account_ids()
+        .unwrap()
+        .into_iter()
+        .find(|a| db.get_account_birthday(*a).unwrap() == height(f.birthday))
+        .unwrap();
+    let balance = &summary.account_balances()[&a];
+    assert!(balance.orchard_balance().spendable_value().into_u64() > 0);
+    assert!(balance.ironwood_balance().spendable_value().into_u64() > 0);
+}
+
+#[test]
+fn already_caught_up_and_birthday_inside_window_keep_upstream_ranges() {
+    let f = fixture();
+    let mut db = wallet(f, &[0]);
+    finish(&mut db, f, Order::Window, 53, &f.keys[..1]);
+    assert!(pick_range(&[], None, window_start(&mut db).unwrap()).is_none());
+    db.update_chain_tip(height(f.tip + 1)).unwrap();
+    let suggested = db.suggest_scan_ranges().unwrap();
+    assert_eq!(
+        pick_range(&suggested, None, window_start(&mut db).unwrap()),
+        suggested.first().cloned()
+    );
+
+    let suggested = vec![range(f.birthday + 150, f.tip + 1, ScanPriority::ChainTip)];
+    assert_eq!(
+        pick_range(
+            &suggested,
+            Some(ScanPriority::ChainTip),
+            height(f.birthday + 99)
+        ),
+        suggested.first().cloned()
+    );
+    assert!(pick_range(
+        &suggested,
+        Some(ScanPriority::Historic),
+        height(f.birthday + 99)
+    )
+    .is_none());
+
+    let mut reference = wallet(f, &[150]);
+    finish(&mut reference, f, Order::Ascending, 53, &f.keys[..1]);
+    let expected = snapshot(&mut reference, f);
+    let mut db = wallet(f, &[150]);
+    finish(&mut db, f, Order::Window, 23, &f.keys[..1]);
+    assert_same(snapshot(&mut db, f), &expected);
+}
+
+#[test]
+fn no_ironwood_activity_matches_ascending_scanning() {
+    let mut f = ChainBuilder::new().build().f;
+    f.ironwood.clear();
+    for state in f.states.values_mut() {
+        *state = ChainState::new(
+            state.block_height(),
+            state.block_hash(),
+            state.final_sapling_tree().clone(),
+            state.final_orchard_tree().clone(),
+            ChainState::empty(state.block_height(), state.block_hash())
+                .final_ironwood_tree()
+                .clone(),
+        );
+    }
+    for block in f.blocks.values_mut() {
+        for tx in &mut block.vtx {
+            tx.ironwood_actions.clear();
+        }
+        block
+            .chain_metadata
+            .as_mut()
+            .unwrap()
+            .ironwood_commitment_tree_size = 0;
+    }
+    let mut reference = wallet(&f, &[0, 20, 30]);
+    finish(&mut reference, &f, Order::Ascending, 53, &f.keys);
+    let expected = snapshot(&mut reference, &f);
+    let mut db = wallet(&f, &[0, 20, 30]);
+    finish(&mut db, &f, Order::Window, 23, &f.keys);
+    assert_same(snapshot(&mut db, &f), &expected);
+}
+
+#[test]
+fn progress_heights_do_not_depend_on_balance_queries() {
+    let f = fixture();
+    let uri = "file:onekey-progress-without-balances?mode=memory&cache=shared";
+    let mut db = wallet_at(f, &[0, 20], uri);
+    finish(&mut db, f, Order::Ascending, 53, &f.keys[..2]);
+    let expected = scan_heights(&db).unwrap();
+    let conn = rusqlite::Connection::open(uri).unwrap();
+    conn.execute_batch("DROP VIEW v_orchard_shards_scan_state")
+        .unwrap();
+    assert!(db
+        .get_wallet_summary(zcash_client_backend::data_api::wallet::ConfirmationsPolicy::default())
+        .is_err());
+
+    let peek: serde_json::Value = serde_json::from_str(&peek(&db).unwrap()).unwrap();
+    assert_eq!(peek["chainTip"], json!(expected.0));
+    assert_eq!(peek["fullyScannedHeight"], json!(expected.1));
+    for id in db.get_account_ids().unwrap() {
+        let status: serde_json::Value =
+            serde_json::from_str(&account_status(&db, &id.expose_uuid().to_string()).unwrap())
+                .unwrap();
+        assert_eq!(status["chainTip"], peek["chainTip"]);
+        assert_eq!(status["fullyScannedHeight"], peek["fullyScannedHeight"]);
+        assert_eq!(status["remainingBlocks"], 0);
+    }
+}
+
+#[test]
+fn progress_heights_match_summary_across_scan_rescan_and_rewind() {
+    fn check(db: &Db) {
+        let summary = db
+            .get_wallet_summary(
+                zcash_client_backend::data_api::wallet::ConfirmationsPolicy::default(),
+            )
+            .unwrap()
+            .unwrap();
+        let expected = (
+            Some(u32::from(summary.chain_tip_height())),
+            Some(u32::from(summary.fully_scanned_height())),
+        );
+        assert_eq!(scan_heights(db).unwrap(), expected);
+        let peek: serde_json::Value = serde_json::from_str(&peek(db).unwrap()).unwrap();
+        assert_eq!(peek["chainTip"], json!(expected.0));
+        assert_eq!(peek["fullyScannedHeight"], json!(expected.1));
+    }
+
+    let f = fixture();
+    let empty = crate::wallet::open_and_migrate("test", ":memory:").unwrap();
+    assert_eq!(scan_heights(&empty).unwrap(), (None, None));
+    let no_accounts = wallet(f, &[]);
+    assert_eq!(scan_heights(&no_accounts).unwrap(), (None, None));
+    let mut db = wallet(f, &[0, 20]);
+    check(&db);
+    assert_eq!(scan_heights(&db).unwrap().1, Some(f.birthday - 1));
+    scan(&mut db, f, f.tip - 19, 20, &f.keys[..2]).unwrap();
+    check(&db);
+    assert_eq!(scan_heights(&db).unwrap().1, Some(f.birthday - 1));
+    scan(&mut db, f, f.birthday, 10, &f.keys[..2]).unwrap();
+    check(&db);
+    finish(&mut db, f, Order::Ascending, 53, &f.keys[..2]);
+    check(&db);
+    queue_rescan_from(&mut db, f.birthday + 30).unwrap();
+    check(&db);
+    rewind_to(&mut db, f.tip - 35).unwrap();
+    check(&db);
+}
+
+#[test]
+fn add_account_rewind_and_pause_resume_match_a_fresh_scan() {
+    let f = fixture();
+    let mut reference = wallet(f, &[0, 20, 30]);
+    finish(&mut reference, f, Order::Ascending, 53, &f.keys);
+    let expected = snapshot(&mut reference, f);
+    let mut db = wallet(f, &[0]);
+    // Isolate rewind/resume from upstream's separate sparse-checkpoint failure
+    // on consecutive old-account imports (also reproduced with the original
+    // order and 53-block batches); one-block checkpoints permit both imports.
+    finish(&mut db, f, Order::Window, 1, &f.keys[..1]);
+    import(&mut db, f, 1, 20);
+    import(&mut db, f, 2, 30);
+    assert!(!db.suggest_scan_ranges().unwrap().is_empty());
+    finish(&mut db, f, Order::Window, 53, &f.keys[..2]);
+    queue_rescan_from(&mut db, f.birthday + 30).unwrap();
+    finish(&mut db, f, Order::Window, 23, &f.keys);
+    assert_same(snapshot(&mut db, f), &expected);
+}
+
+#[test]
+fn checkpoint_repair_imports_without_an_active_registered_identity() {
+    let f = old_birthday_fixture(304);
+    let uri = "file:onekey-checkpoint-repair?mode=memory&cache=shared";
+    let mut db = scanned_a_at(&f, uri);
+    import(&mut db, &f, 1, 20);
+    let conn = rusqlite::Connection::open(uri).unwrap();
+    seed_unmined_sends(&conn, f.tip, 0);
+    let sends = send_evidence(&mut db);
+    assert_checkpoints_diverged(try_import(&mut db, &f, 2, 30).unwrap_err());
+    let accounts = db.get_account_ids().unwrap();
+    let birthdays: Vec<_> = accounts
+        .iter()
+        .map(|id| db.get_account(*id).unwrap().unwrap().birthday_height())
+        .collect();
+    let ufvk = UnifiedFullViewingKey::decode(db.params(), &f.keys[2]).unwrap();
+    crate::account::import_with_checkpoint(
+        &mut db,
+        "account 2",
+        &ufvk,
+        &AccountBirthday::from_parts(f.states[&(f.birthday + 29)].clone(), None),
+        AccountPurpose::Spending { derivation: None },
+        &f.states[&(f.birthday + 105)],
+    )
+    .unwrap();
+    assert_eq!(send_evidence(&mut db), sends);
+    assert_eq!(db.chain_height().unwrap(), Some(height(f.tip)));
+    for (id, birthday) in accounts.iter().zip(birthdays) {
+        assert_eq!(
+            db.get_account(*id).unwrap().unwrap().birthday_height(),
+            birthday
+        );
+    }
+    // Only the newly imported identity is active during recovery.
+    finish(&mut db, &f, Order::Ascending, 53, &f.keys[2..]);
+    // Previously paused keys decrypt their retained span when resumed.
+    queue_rescan_from(&mut db, f.birthday).unwrap();
+    finish(&mut db, &f, Order::Ascending, 53, &f.keys);
+    let reference_uri = "file:onekey-checkpoint-reference?mode=memory&cache=shared";
+    let mut reference = wallet_at(&f, &[0, 20, 30], reference_uri);
+    finish(&mut reference, &f, Order::Ascending, 53, &f.keys);
+    seed_unmined_sends(
+        &rusqlite::Connection::open(reference_uri).unwrap(),
+        f.tip,
+        0,
+    );
+    assert_same(snapshot(&mut db, &f), &snapshot(&mut reference, &f));
+    assert_eq!(send_evidence(&mut db), sends);
+}
+
+#[test]
+fn checkpoint_repair_rolls_back_when_account_import_fails() {
+    let f = old_birthday_fixture(304);
+    let mut db = scanned_a(&f);
+    import(&mut db, &f, 1, 20);
+    let before = all_table_rows(&mut db);
+    let ufvk = UnifiedFullViewingKey::decode(db.params(), &f.keys[1]).unwrap();
+    let error = crate::account::import_with_checkpoint(
+        &mut db,
+        "duplicate account",
+        &ufvk,
+        &AccountBirthday::from_parts(f.states[&(f.birthday + 19)].clone(), None),
+        AccountPurpose::Spending { derivation: None },
+        &f.states[&(f.birthday + 105)],
+    )
+    .unwrap_err();
+    assert!(
+        error
+            .detail
+            .as_deref()
+            .unwrap_or_default()
+            .contains("already exists"),
+        "{error:?}"
+    );
+    assert_eq!(all_table_rows(&mut db), before);
+}
+
+#[test]
+fn checkpoint_repair_rejects_a_conflicting_block_or_tree_position() {
+    let f = fixture();
+    let mut db = wallet(f, &[0]);
+    finish(&mut db, f, Order::Ascending, 53, &f.keys[..1]);
+    let ufvk = UnifiedFullViewingKey::decode(db.params(), &f.keys[1]).unwrap();
+    let state = &f.states[&f.tip];
+    let before = all_table_rows(&mut db);
+    for checkpoint in [
+        ChainState::new(
+            state.block_height(),
+            BlockHash([0xaa; 32]),
+            state.final_sapling_tree().clone(),
+            state.final_orchard_tree().clone(),
+            state.final_ironwood_tree().clone(),
+        ),
+        ChainState::new(
+            state.block_height(),
+            state.block_hash(),
+            state.final_sapling_tree().clone(),
+            f.states[&f.birthday].final_orchard_tree().clone(),
+            state.final_ironwood_tree().clone(),
+        ),
+    ] {
+        assert!(crate::account::import_with_checkpoint(
+            &mut db,
+            "conflicting checkpoint",
+            &ufvk,
+            &AccountBirthday::from_parts(f.states[&(f.birthday + 19)].clone(), None),
+            AccountPurpose::Spending { derivation: None },
+            &checkpoint,
+        )
+        .is_err());
+        assert_eq!(all_table_rows(&mut db), before);
+    }
+}
+
+#[test]
+fn safe_birthday_rescan_retains_pending_raw_rejections_and_other_identities() {
+    let f = fixture();
+    let uri = "file:onekey-safe-birthday-rescan?mode=memory&cache=shared";
+    let mut db = wallet_at(f, &[0, 200], uri);
+    finish(&mut db, f, Order::Ascending, 53, &f.keys[..2]);
+    let conn = rusqlite::Connection::open(uri).unwrap();
+    let positions = seed_unmined_sends_at_positions(&conn, f.tip, 1, None);
+    let evidence = send_evidence(&mut db);
+    let ids = db.get_account_ids().unwrap();
+    let target = ids
+        .iter()
+        .copied()
+        .find(|id| db.get_account_birthday(*id).unwrap() == height(f.birthday + 200))
+        .unwrap();
+    let other = ids.iter().copied().find(|id| *id != target).unwrap();
+    let other_birthday = db.get_account_birthday(other).unwrap();
+    crate::account::rescan_with_birthday(
+        &mut db,
+        target,
+        &AccountBirthday::from_parts(f.states[&(f.birthday + 19)].clone(), None),
+        None,
+    )
+    .unwrap();
+    assert_eq!(send_evidence(&mut db), evidence);
+    assert_eq!(db.get_account_ids().unwrap(), ids);
+    assert_eq!(db.get_account_birthday(other).unwrap(), other_birthday);
+    assert_eq!(
+        db.get_account_birthday(target).unwrap(),
+        height(f.birthday + 20)
+    );
+    finish(&mut db, f, Order::Ascending, 53, &f.keys[..2]);
+    assert_pending_input_witnesses_and_locks(&mut db, f.tip);
+    let reference_uri = "file:onekey-safe-rescan-reference?mode=memory&cache=shared";
+    let mut reference = wallet_at(f, &[0, 20], reference_uri);
+    finish(&mut reference, f, Order::Ascending, 53, &f.keys[..2]);
+    seed_unmined_sends_at_positions(
+        &rusqlite::Connection::open(reference_uri).unwrap(),
+        f.tip,
+        1,
+        Some(&positions),
+    );
+    assert_same(snapshot(&mut db, f), &snapshot(&mut reference, f));
+    assert_eq!(send_evidence(&mut db), evidence);
+}
+
+#[test]
+fn a_later_birthday_starts_the_account_over_at_that_height() {
+    // Notes of one account, independent of internal ids.
+    fn notes_of(db: &mut Db, account: &str) -> Vec {
+        let uuid = account.replace('-', "");
+        ["orchard", "ironwood"]
+            .iter()
+            .flat_map(|pool| {
+                rows(
+                    db,
+                    &format!(
+                        "SELECT '{pool}', hex(t.txid), rn.value, t.mined_height,
+                            rn.commitment_tree_position, hex(rn.nf), hex(spent.txid)
+                         FROM {pool}_received_notes rn
+                         JOIN transactions t ON t.id_tx = rn.transaction_id
+                         JOIN accounts a ON a.id = rn.account_id
+                         LEFT JOIN {pool}_received_note_spends s ON s.{pool}_received_note_id = rn.id
+                         LEFT JOIN transactions spent ON spent.id_tx = s.transaction_id
+                         WHERE hex(a.uuid) = upper('{uuid}')
+                         ORDER BY rn.commitment_tree_position"
+                    ),
+                )
+            })
+            .collect()
+    }
+    let f = fixture();
+    let later = AccountBirthday::from_parts(f.states[&(f.birthday + 199)].clone(), None);
+    let mut db = wallet(f, &[0, 200]);
+    finish(&mut db, f, Order::Ascending, 53, &f.keys[..2]);
+    let ids = db.get_account_ids().unwrap();
+    let uuid_of = |id: &zcash_client_sqlite::AccountUuid| id.expose_uuid().to_string();
+    let (target, other) = if db.get_account_birthday(ids[0]).unwrap() == height(f.birthday) {
+        (ids[0], uuid_of(&ids[1]))
+    } else {
+        (ids[1], uuid_of(&ids[0]))
+    };
+    let before = notes_of(&mut db, &uuid_of(&target));
+    let other_before = notes_of(&mut db, &other);
+
+    let restarted = crate::account::restart_with_birthday(&mut db, target, &later, None).unwrap();
+    finish(&mut db, f, Order::Ascending, 53, &f.keys[..2]);
+
+    let mut reference = wallet(f, &[200]);
+    finish(&mut reference, f, Order::Ascending, 53, &f.keys[..1]);
+    let reference_account = uuid_of(&reference.get_account_ids().unwrap()[0]);
+    let expected = notes_of(&mut reference, &reference_account);
+    assert!(
+        before.len() > expected.len(),
+        "the old birthday found more notes"
+    );
+    assert_eq!(notes_of(&mut db, &restarted), expected);
+    assert_eq!(notes_of(&mut db, &other), other_before);
+}
+
+#[test]
+fn old_birthday_import_rolls_back_and_a_completed_rescan_heals() {
+    let f = old_birthday_fixture(303);
+    let mut db = scanned_a(&f);
+    import(&mut db, &f, 1, 20);
+    import(&mut db, &f, 2, 30);
+    assert_eq!(db.get_account_ids().unwrap().len(), 3);
+
+    let f = old_birthday_fixture(304);
+    let mut reference = wallet(&f, &[0, 20]);
+    finish(&mut reference, &f, Order::Ascending, 304, &f.keys[..2]);
+    let expected_ab = snapshot(&mut reference, &f);
+    let mut reference = wallet(&f, &[0, 20, 30]);
+    finish(&mut reference, &f, Order::Ascending, 304, &f.keys);
+    let expected = snapshot(&mut reference, &f);
+    for order in [Order::Window, Order::Any] {
+        for batch in [53, 200] {
+            let mut db = scanned_a(&f);
+            let b = import(&mut db, &f, 1, 20);
+            let accounts = db.get_account_ids().unwrap();
+            let before = all_table_rows(&mut db);
+            for _ in 0..2 {
+                assert_checkpoints_diverged(try_import(&mut db, &f, 2, 30).unwrap_err());
+                assert_eq!(all_table_rows(&mut db), before);
+                assert_eq!(db.get_account_ids().unwrap(), accounts);
+                assert_eq!(
+                    crate::account::account_by_ufvk(&db, &f.keys[2]).unwrap(),
+                    "null"
+                );
+            }
+            finish(&mut db, &f, order, batch, &f.keys[..2]);
+            assert_same(snapshot(&mut db, &f), &expected_ab);
+            let status: serde_json::Value =
+                serde_json::from_str(&account_status(&db, &b.expose_uuid().to_string()).unwrap())
+                    .unwrap();
+            assert_eq!(status["isComplete"], true);
+            import(&mut db, &f, 2, 30);
+            finish(&mut db, &f, order, batch, &f.keys);
+            assert_same(snapshot(&mut db, &f), &expected);
+        }
+    }
+}
+
+#[test]
+fn old_birthday_import_heals_at_the_first_repaired_checkpoint() {
+    let f = old_birthday_fixture(304);
+    let mut reference = wallet(&f, &[0, 20, 30]);
+    finish(&mut reference, &f, Order::Ascending, 304, &f.keys);
+    let expected = snapshot(&mut reference, &f);
+    for (order, batch, expected_steps, expected_blocks) in [
+        (Order::Window, 1, 18, 18),
+        (Order::Any, 1, 86, 86),
+        (Order::Window, 53, 3, 133),
+        (Order::Any, 53, 3, 133),
+        (Order::Window, 200, 1, 200),
+        (Order::Any, 200, 1, 200),
+    ] {
+        let mut db = scanned_a(&f);
+        import(&mut db, &f, 1, 20);
+        assert_checkpoints_diverged(try_import(&mut db, &f, 2, 30).unwrap_err());
+        let initial = db.block_max_scanned().unwrap().unwrap().block_height();
+        assert_eq!(initial, height(f.birthday + 204));
+        let mut blocks = 0;
+        let mut steps = 0;
+        'scanning: for _ in 0..expected_steps {
+            for lane in LANES {
+                let Some(r) = next(&mut db, &f, order, lane) else {
+                    continue;
+                };
+                let start = u32::from(r.block_range().start);
+                let len = batch.min(r.len() as u32);
+                let checkpoint_sql = format!(
+                    "SELECT checkpoint_id FROM orchard_tree_checkpoints WHERE checkpoint_id = {}",
+                    f.birthday + 105,
+                );
+                if batch == 1 && steps + 1 == expected_steps {
+                    assert!(rows(&mut db, &checkpoint_sql).is_empty());
+                }
+                scan(&mut db, &f, start, len, &f.keys[..2]).unwrap();
+                blocks += len;
+                steps += 1;
+                if steps == expected_steps {
+                    if batch == 1 {
+                        assert_eq!(start, f.birthday + 105);
+                        assert_eq!(rows(&mut db, &checkpoint_sql).len(), 1);
+                    }
+                    if batch <= 53 {
+                        assert_eq!(
+                            db.block_max_scanned().unwrap().unwrap().block_height(),
+                            initial
+                        );
+                    }
+                    import(&mut db, &f, 2, 30);
+                    break 'scanning;
+                }
+                assert_checkpoints_diverged(try_import(&mut db, &f, 2, 30).unwrap_err());
+            }
+        }
+        assert_eq!((steps, blocks), (expected_steps, expected_blocks));
+        assert_eq!(db.get_account_ids().unwrap().len(), 3);
+        finish(&mut db, &f, order, 53, &f.keys);
+        assert_same(snapshot(&mut db, &f), &expected);
+    }
+}
+
+#[test]
+fn deep_reorg_and_verify_converge_to_the_new_chain() {
+    let f = fixture();
+    let fork = fork_fixture();
+    let mut reference = wallet(&fork, &[0, 20, 30]);
+    finish(&mut reference, &fork, Order::Ascending, 31, &fork.keys);
+    let expected = snapshot(&mut reference, &fork);
+    for order in [Order::Upstream, Order::Ascending, Order::Window] {
+        let mut db = wallet(f, &[0, 20, 30]);
+        finish(&mut db, f, order, 23, &f.keys);
+        db.update_chain_tip(height(fork.tip)).unwrap();
+        let error = scan(&mut db, &fork, f.tip + 1, 1, &f.keys).unwrap_err();
+        assert_eq!(error.code, ErrorCode::ReorgDetected);
+        // The fork is 35 blocks below the old tip: repeated host rewinds must
+        // reach it without the old shardtree Insert(Conflict) failure.
+        let mut at = error.params["suggestedRewindHeight"].as_u64().unwrap() as u32;
+        loop {
+            let actual = rewind_to(&mut db, at).unwrap();
+            match scan(&mut db, &fork, actual + 1, 7, &f.keys) {
+                Ok(()) => break,
+                Err(e) => {
+                    assert_eq!(e.code, ErrorCode::ReorgDetected);
+                    at = e.params["suggestedRewindHeight"].as_u64().unwrap() as u32;
+                }
+            }
+        }
+        // A rewind truncates the known tip as well. The next host pass sees
+        // liveTip > storedTip and calls syncTip before it resumes scanning.
+        db.update_chain_tip(height(fork.tip)).unwrap();
+        finish(&mut db, &fork, order, 23, &fork.keys);
+        assert_same(snapshot(&mut db, &fork), &expected);
+        db.update_chain_tip(height(fork.tip + 250)).unwrap();
+        let suggested = db.suggest_scan_ranges().unwrap();
+        assert_eq!(
+            pick_range(&suggested, None, window_start(&mut db).unwrap())
+                .unwrap()
+                .priority(),
+            ScanPriority::Verify
+        );
+    }
+}
+
+#[test]
+fn historic_lane_is_strictly_ascending_and_preserves_special_priorities() {
+    let suggested = vec![
+        range(70, 110, ScanPriority::ChainTip),
+        range(10, 40, ScanPriority::Historic),
+        range(40, 70, ScanPriority::ChainTip),
+        range(1, 5, ScanPriority::FoundNote),
+        range(5, 10, ScanPriority::Verify),
+    ];
+    assert_eq!(
+        pick_range(&suggested, Some(ScanPriority::Historic), height(90)),
+        Some(suggested[1].clone())
+    );
+    assert_eq!(
+        pick_range(&suggested[2..3], Some(ScanPriority::Historic), height(90)),
+        Some(suggested[2].clone())
+    );
+    assert_eq!(
+        pick_range(&suggested, Some(ScanPriority::ChainTip), height(90)),
+        Some(range(90, 110, ScanPriority::ChainTip))
+    );
+    for lane in [ScanPriority::Verify, ScanPriority::FoundNote] {
+        assert_eq!(
+            pick_range(&suggested, Some(lane), height(90)),
+            suggested.iter().find(|r| r.priority() == lane).cloned()
+        );
+    }
+    assert_eq!(
+        pick_range(&suggested, None, height(90)),
+        Some(suggested[4].clone())
+    );
+}
+
+/// Minimal SQL stores let boundary tests exercise local planning without writing
+/// wallet-owned tables via the production extension API.
+fn planning_db(tip: Option, extra: &str) -> Db {
+    let conn = rusqlite::Connection::open_in_memory().unwrap();
+    conn.execute_batch("CREATE TABLE scan_queue(block_range_end INTEGER);")
+        .unwrap();
+    if let Some(tip) = tip {
+        conn.execute("INSERT INTO scan_queue VALUES (?)", [tip + 1])
+            .unwrap();
+    }
+    for pool in ["sapling", "orchard", "ironwood"] {
+        conn.execute_batch(&format!(
+            "CREATE TABLE {pool}_tree_shards(shard_index INTEGER PRIMARY KEY, subtree_end_height INTEGER, root_hash BLOB);
+             CREATE TABLE {pool}_received_notes(commitment_tree_position INTEGER);
+             CREATE TABLE v_{pool}_shards_scan_state(subtree_start_height INTEGER, subtree_end_height INTEGER,
+                 start_position INTEGER, end_position_exclusive INTEGER, max_priority INTEGER);"
+        )).unwrap();
+    }
+    conn.execute_batch(extra).unwrap();
+    zcash_client_sqlite::WalletDb::from_connection(
+        conn,
+        Network::TestNetwork,
+        crate::clock::HostClock,
+        rand_chacha::ChaCha20Rng::from_seed([0; 32]),
+    )
+}
+
+#[test]
+fn earlier_tail_from_either_pool_defines_the_capped_fast_window() {
+    let tip = 100_000;
+    for (ironwood, orchard, expected) in [
+        (99_000, 98_000, 98_000),
+        (98_000, 99_000, 98_000),
+        (60_000, 99_000, tip - FAST_WINDOW_MAX_BLOCKS),
+        (99_000, 60_000, tip - FAST_WINDOW_MAX_BLOCKS),
+    ] {
+        let mut db = planning_db(
+            Some(tip),
+            &format!(
+                "INSERT INTO ironwood_tree_shards VALUES (0, {ironwood}, X'01');
+                 INSERT INTO orchard_tree_shards VALUES (0, {orchard}, X'01');"
+            ),
+        );
+        assert_eq!(window_start(&mut db).unwrap(), height(expected));
+        // The actual fast range is also bounded by upstream's ChainTip start.
+        let upstream = range(expected + 100, tip + 1, ScanPriority::ChainTip);
+        assert_eq!(
+            pick_range(
+                &[upstream.clone()],
+                Some(ScanPriority::ChainTip),
+                height(expected)
+            ),
+            Some(upstream)
+        );
+    }
+}
+
+#[test]
+fn missing_tail_uses_each_pools_activation_height() {
+    let orchard_activation = u32::from(
+        Network::TestNetwork
+            .activation_height(NetworkUpgrade::Nu5)
+            .unwrap(),
+    );
+    let ironwood_activation = u32::from(
+        Network::TestNetwork
+            .activation_height(NetworkUpgrade::Nu6_3)
+            .unwrap(),
+    );
+    assert!(ironwood_activation > orchard_activation + 500);
+    let tip = orchard_activation + 500;
+    for (extra, expected) in [
+        (String::new(), orchard_activation),
+        (
+            format!(
+                "INSERT INTO ironwood_tree_shards VALUES (0, {}, X'01');",
+                tip - 400
+            ),
+            orchard_activation,
+        ),
+        (
+            format!(
+                "INSERT INTO orchard_tree_shards VALUES (0, {}, X'01');",
+                tip - 400
+            ),
+            tip - 400,
+        ),
+    ] {
+        assert_eq!(
+            window_start(&mut planning_db(Some(tip), &extra)).unwrap(),
+            height(expected)
+        );
+    }
+    let tip = ironwood_activation + 100_000;
+    assert_eq!(
+        window_start(&mut planning_db(Some(tip), "")).unwrap(),
+        height(tip - FAST_WINDOW_MAX_BLOCKS)
+    );
+}
+
+#[test]
+fn clamp_keeps_two_hundred_blocks_even_when_both_tails_are_new() {
+    let tip = 100_000;
+    let mut db = planning_db(
+        Some(tip),
+        "INSERT INTO ironwood_tree_shards VALUES (0, 99999, X'01');
+         INSERT INTO orchard_tree_shards VALUES (0, 99998, X'01');",
+    );
+    assert_eq!(
+        window_start(&mut db).unwrap(),
+        height(tip - FAST_WINDOW_REORG_MARGIN)
+    );
+    assert_eq!(
+        window_start(&mut planning_db(None, "")).unwrap(),
+        height(u32::MAX)
+    );
+}
+
+#[test]
+fn note_extension_reaches_a_fixed_point_across_both_pools() {
+    let mut db = planning_db(
+        Some(100_000),
+        "INSERT INTO ironwood_tree_shards VALUES (0, 99000, X'01');
+         INSERT INTO orchard_received_notes VALUES (0);
+         INSERT INTO ironwood_received_notes VALUES (0);
+         INSERT INTO v_orchard_shards_scan_state VALUES (98000, NULL, 0, 65536, 50);
+         INSERT INTO v_ironwood_shards_scan_state VALUES (97000, 98500, 0, 65536, 50);",
+    );
+    assert_eq!(window_start(&mut db).unwrap(), height(97000));
+}
+
+#[test]
+fn missing_completed_roots_fall_back_in_each_pool_including_sapling() {
+    let f = fixture();
+    let original = range(f.birthday, f.tip + 1, ScanPriority::ChainTip);
+    let fast = range(f.birthday + 100, f.tip + 1, ScanPriority::ChainTip);
+    let state = &f.states[&(f.birthday + 99)];
+    for missing in ["sapling", "orchard", "ironwood"] {
+        let mut sql = String::new();
+        for (pool, size) in [
+            ("sapling", state.final_sapling_tree().tree_size()),
+            ("orchard", state.final_orchard_tree().tree_size()),
+            ("ironwood", state.final_ironwood_tree().tree_size()),
+        ] {
+            for i in 0..(size >> 16) {
+                if pool != missing || i != 0 {
+                    sql.push_str(&format!(
+                        "INSERT INTO {pool}_tree_shards VALUES ({i}, 1, X'01');"
+                    ));
+                }
+            }
+        }
+        let mut db = planning_db(Some(f.tip), &sql);
+        assert!(!roots_cover(&mut db, state).unwrap());
+        assert_eq!(
+            guard_fast_range(&mut db, &[original.clone()], fast.clone(), state).unwrap(),
+            original
+        );
+    }
+    let mut db = wallet(f, &[0]);
+    assert!(roots_cover(&mut db, state).unwrap());
+    assert_eq!(
+        guard_fast_range(&mut db, &[original], fast.clone(), state).unwrap(),
+        fast
+    );
+}
+
+#[test]
+fn missing_root_guard_prevents_a_real_subtree_discontinuity_retry_loop() {
+    use zcash_primitives::merkle_tree::write_frontier_v1;
+    let f = fixture();
+    let start = f.birthday + 201;
+    let prior = &f.states[&(start - 1)];
+    // Model two completed Ironwood shards that the server has not supplied.
+    // Shard indices 3 and 5 have the same frontier shape, so relocating this
+    // synthetic frontier preserves its encoding while leaving a gap in SQL.
+    let mut encoded = Vec::new();
+    write_frontier_v1(&mut encoded, prior.final_ironwood_tree()).unwrap();
+    let position = u64::from_le_bytes(encoded[1..9].try_into().unwrap()) + (2 << 16);
+    encoded[1..9].copy_from_slice(&position.to_le_bytes());
+    let state = ChainState::new(
+        prior.block_height(),
+        prior.block_hash(),
+        prior.final_sapling_tree().clone(),
+        prior.final_orchard_tree().clone(),
+        read_frontier_v1(&encoded[..]).unwrap(),
+    );
+    let mut block = f.blocks[&start].clone();
+    block
+        .chain_metadata
+        .as_mut()
+        .unwrap()
+        .ironwood_commitment_tree_size += 2 << 16;
+    let cache = MemoryBlockCache::new();
+    cache.insert(vec![block]).unwrap();
+    let mut db = wallet(f, &[0]);
+    let params = *db.params();
+    let keys = ScanningKeys::from_account_ufvks(
+        select_active_scanning_ufvks(
+            ¶ms,
+            db.get_unified_full_viewing_keys().unwrap(),
+            &f.keys[..1],
+        )
+        .unwrap(),
+    );
+    let error =
+        scan_blocks_inline(¶ms, &cache, &mut db, &keys, height(start), &state, 1).unwrap_err();
+    assert_eq!(error.params["operation"], "putBlocks");
+    assert!(
+        error
+            .detail
+            .as_ref()
+            .is_some_and(|s| s.contains("discontinuous with existing subtree range")),
+        "{error:?}"
+    );
+    let original = range(f.birthday, f.tip + 1, ScanPriority::ChainTip);
+    let guarded = guard_fast_range(
+        &mut db,
+        &[original.clone()],
+        range(start, f.tip + 1, ScanPriority::ChainTip),
+        &state,
+    )
+    .unwrap();
+    assert_eq!(guarded, original);
+    scan(
+        &mut db,
+        f,
+        u32::from(guarded.block_range().start),
+        7,
+        &f.keys[..1],
+    )
+    .unwrap();
+    assert_eq!(
+        db.block_fully_scanned().unwrap().unwrap().block_height(),
+        height(f.birthday + 6)
+    );
+}
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
index 39e666b45..1979cd85a 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
@@ -7,7 +7,9 @@ use std::collections::{BTreeSet, HashSet};
 
 use rand::SeedableRng;
 use rand_chacha::ChaCha20Rng;
+use schemerz_rusqlite::RusqliteAdapter;
 use uuid::Uuid;
+use zcash_client_sqlite::wallet::init::WalletMigrationError;
 use zcash_client_sqlite::{wallet::init::WalletMigrator, WalletDb};
 use zcash_protocol::consensus::Network;
 
@@ -35,8 +37,9 @@ pub fn parse_network(s: &str) -> Result {
 /// current schema. Migration is idempotent and runs on every open.
 pub fn open_and_migrate(network: &str, db_name: &str) -> Result {
     let params = parse_network(network)?;
-    let conn = storage::open_connection(db_name)?;
+    let mut conn = storage::open_connection(db_name)?;
     reject_newer_schema(&conn, params)?;
+    initialize_migration_table(&mut conn)?;
 
     // Used only for non-key purposes inside the library (migration ids, nonces).
     // No key material passes through it or through this crate.
@@ -56,6 +59,16 @@ fn migrator() -> WalletMigrator {
     WalletMigrator::new().with_external_migrations(crate::tx_state::migrations())
 }
 
+fn initialize_migration_table(conn: &mut rusqlite::Connection) -> Result<()> {
+    // Upstream expects this initialization to succeed; storage failures must remain errors.
+    RusqliteAdapter::<'_, WalletMigrationError>::new(conn, Some("schemer_migrations".to_string()))
+        .init()
+        .map_err(|error| {
+            RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": "migrate" }))
+                .detail(error)
+        })
+}
+
 /// Refuses a database migrated by a newer runtime. Upstream migration skips
 /// unknown applied migrations, so an older runtime would run on a schema it
 /// does not understand. No migration runs against it.
@@ -159,6 +172,25 @@ fn random_seed() -> Result<[u8; 32]> {
 mod tests {
     use super::*;
 
+    #[test]
+    fn migration_table_storage_failures_are_errors_without_a_panic() {
+        for pragma in ["PRAGMA max_page_count = 1", "PRAGMA query_only = ON"] {
+            let mut conn = rusqlite::Connection::open_in_memory().unwrap();
+            conn.execute_batch(pragma).unwrap();
+            let error = initialize_migration_table(&mut conn).unwrap_err();
+            assert_eq!(error.code, ErrorCode::DatabaseError);
+            assert_eq!(error.params["operation"], "migrate");
+            let tables: i64 = conn
+                .query_row(
+                    "SELECT count(*) FROM sqlite_master WHERE name = 'schemer_migrations'",
+                    [],
+                    |row| row.get(0),
+                )
+                .unwrap();
+            assert_eq!(tables, 0);
+        }
+    }
+
     #[test]
     fn network_parsing() {
         assert!(matches!(parse_network("main"), Ok(Network::MainNetwork)));

From 3b8a09a68030fb4ec1669323eaccf55f4c715486 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Tue, 27 Oct 2026 09:48:18 +0800
Subject: [PATCH 74/97] fix(monero): improve scanning, restart at a later
 birthday, record spend fees

Scan a bounded recent window first, then catch up in order. Keep
outgoing transaction metadata with scan-validity markers, reject stale
send preparations and simplify the shared rewind flow. Schema v1 is
edited in place until release.

A later birthday starts the identity over from that height. Scanning keeps
the RingCT fee of each transaction that spends ours, so history can tell
the payment from the fee.
---
 chain-runtimes/monero/README.md               |   8 +-
 .../crates/monero-runtime/src/bindgen.rs      |   9 +-
 .../monero/crates/monero-runtime/src/error.rs |   3 +
 .../monero/crates/monero-runtime/src/query.rs |  15 +-
 .../monero/crates/monero-runtime/src/scan.rs  | 285 +++++++++++++++---
 .../crates/monero-runtime/src/schema.rs       |  21 +-
 .../monero/crates/monero-runtime/src/spend.rs |  55 +++-
 .../monero/crates/monero-runtime/src/sync.rs  |  91 ++++++
 .../crates/monero-runtime/src/wallet.rs       | 157 +++++++++-
 9 files changed, 554 insertions(+), 90 deletions(-)

diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md
index 3ac614a7a..bbc99b816 100644
--- a/chain-runtimes/monero/README.md
+++ b/chain-runtimes/monero/README.md
@@ -54,6 +54,12 @@ releases to `latest`. Branches other than `main` can publish alpha versions only
 6. **Local management does not require a live tip.** Deletion needs only the local
    database. For `rewindTo`, pass the last locally observed tip; normal sync fetches
    a fresh one later. Rewind, cursor updates and range requeue commit together.
+7. **Changing an existing identity's birthday starts it over there.** `addAccount`
+   keeps the identity and subaddresses, deletes outputs and transactions below the
+   new birthday (except inputs of unmined own sends), and atomically requeues the
+   target range. Rows at or above it are re-verified by the rescan: until seen
+   again they do not count toward balance or input selection, and sends show
+   without a confirmed height.
 
 ## API
 
@@ -71,7 +77,7 @@ chainTip()                                      { height, network }
 deriveAccount(network, bip32PrivateKeyHex)
 deriveSubaddress(network, spendPub, viewPriv, major, minor)
 validateAddress(network, address)
-addAccount(uuid, spendPub, viewPriv, birthday) / listAccounts() / removeAccount(uuid)
+addAccount(uuid, spendPub, viewPriv, birthday, forceRescan?) / listAccounts() / removeAccount(uuid)
 registerSubaddress(accountId, major, minor, label?)
 importKeyImagesWithBip32Key(accountId, bip32PrivateKeyHex)
 
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
index a9bc3006f..efa4903f5 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -103,12 +103,19 @@ pub fn add_account(
     spend_public_key_hex: &str,
     view_private_key_hex: String,
     birthday_height: u64,
+    force_rescan: Option,
 ) -> std::result::Result {
     let view_private_key_hex = Zeroizing::new(view_private_key_hex);
     let spend = decode_hex(spend_public_key_hex, "spendPublicKeyHex")?;
     let view = decode_secret_hex(&view_private_key_hex, "viewPrivateKeyHex")?;
     let result = runtime::with_db(|db| {
-        let identity = db.add_identity(uuid, &spend, &view, birthday_height)?;
+        let identity = db.add_identity_with_rescan(
+            uuid,
+            &spend,
+            &view,
+            birthday_height,
+            force_rescan.unwrap_or(false),
+        )?;
         Ok(serde_json::json!({
             "accountId": identity.id,
             "uuid": identity.uuid,
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/error.rs b/chain-runtimes/monero/crates/monero-runtime/src/error.rs
index d7ae5ee02..bfb0b3ebc 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/error.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/error.rs
@@ -70,6 +70,8 @@ pub enum ErrorCode {
     // ── Storage ────────────────────────────────────────────────────────────
     /// SQLite operation failed. Params: `{ operation }`
     DatabaseError,
+    /// Database migrated by a newer runtime; preserve it and update the app.
+    DatabaseTooNew,
     /// Invalid database name (empty or contains a path separator). Params: `{ value }`
     InvalidDbName,
 
@@ -102,6 +104,7 @@ impl ErrorCode {
             MalformedNodeResponse => "MALFORMED_NODE_RESPONSE",
             BroadcastRejected => "BROADCAST_REJECTED",
             DatabaseError => "DATABASE_ERROR",
+            DatabaseTooNew => "DATABASE_TOO_NEW",
             InvalidDbName => "INVALID_DB_NAME",
             Unimplemented => "UNIMPLEMENTED",
         }
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/query.rs b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
index 93452decb..aaef699e3 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/query.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
@@ -72,7 +72,7 @@ pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result Result Result Result>(5)?,
                 "failed": r.get::<_, i64>(6)? != 0,
                 "outgoingAtomic": r.get::<_, Option>(7)?,
+                "feeAtomic": r.get::<_, Option>(8)?.map(|fee| fee.to_string()),
             }))
         })
         .map_err(|e| db_err("history", e))?;
@@ -379,7 +382,7 @@ pub fn transaction_details(db: &Db, identity_id: i64, txid_hex: &str) -> Result<
     let row = db
         .conn()
         .query_row(
-            "SELECT t.height, t.direction, COALESCE(t.timestamp, b.timestamp, t.sent_at)
+            "SELECT CASE WHEN t.scan_valid = 1 THEN t.height END, t.direction, COALESCE(t.timestamp, b.timestamp, t.sent_at)
              FROM transactions t LEFT JOIN blocks b ON b.identity_id = t.identity_id AND b.height = t.height
              WHERE t.identity_id = ?1 AND t.txid = ?2",
             params![identity_id, &txid],
@@ -402,7 +405,7 @@ pub fn transaction_details(db: &Db, identity_id: i64, txid_hex: &str) -> Result<
         .conn()
         .prepare(
             "SELECT amount_atomic, subaddress_major, subaddress_minor, index_in_tx
-             FROM outputs WHERE identity_id = ?1 AND txid = ?2 ORDER BY index_in_tx",
+             FROM outputs WHERE identity_id = ?1 AND txid = ?2 AND scan_valid = 1 ORDER BY index_in_tx",
         )
         .map_err(|e| db_err("transactionOutputs", e))?;
     let received = stmt
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
index 454b28e69..09b0046ca 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
@@ -153,6 +153,26 @@ fn key_images_in(block: &ScannableBlock) -> Result> {
     Ok(out)
 }
 
+/// Fee of each transaction in the block, from its RingCT data. Pre-RingCT
+/// (V1) transactions are skipped: no OneKey account predates RingCT.
+///
+/// Length mismatches are reported by `key_images_in`; skip here.
+fn tx_fees_in(block: &ScannableBlock) -> Vec<([u8; 32], u64)> {
+    block
+        .block
+        .transactions
+        .iter()
+        .zip(block.transactions.iter())
+        .filter_map(|(txid, tx)| match tx {
+            Transaction::V2 {
+                proofs: Some(proofs),
+                ..
+            } => Some((*txid, proofs.base.fee)),
+            _ => None,
+        })
+        .collect()
+}
+
 /// Rings referenced by each input: `(key image, txid, amount pool, absolute global member indices)`.
 ///
 /// `key_offsets` are deltas: the first is absolute, each next is relative to the previous.
@@ -216,7 +236,7 @@ fn load_ring_candidates(db: &Db, identity_id: i64) -> Result {
         .conn()
         .prepare(
             "SELECT txid, index_in_tx, global_index, amount_atomic FROM outputs
-             WHERE identity_id = ?1 AND key_image IS NULL AND spent_at_height IS NULL",
+             WHERE identity_id = ?1 AND scan_valid = 1 AND key_image IS NULL AND spent_at_height IS NULL",
         )
         .map_err(|e| db_err("loadRingCandidates", e))?;
     let rows = stmt
@@ -341,6 +361,9 @@ pub fn scan_blocks(
     // txid -> (R, additional), only for transactions that paid us.
     let mut tx_pub_keys: HashMap<[u8; 32], (Vec, Option>)> = HashMap::new();
     let mut spends: Vec<(u64, [u8; 32], [u8; 32])> = Vec::new(); // (height, key_image, txid)
+
+    // Fees of transactions that spend ours: history needs them to tell the payment from the fee.
+    let mut spend_fees: HashMap<[u8; 32], u64> = HashMap::new();
     let mut block_rows: Vec<(u64, [u8; 32], Option, u64)> = Vec::new(); // (height, hash, ringct_next, ts)
 
     // Block before the batch start, for continuity and RingCT cursor checks.
@@ -409,6 +432,7 @@ pub fn scan_blocks(
                 tx_pub_keys.insert(txid, (keys, additional));
             }
         }
+        let spends_before = spends.len() + possible_spends.len();
         // Match inputs before adding this block's outputs as candidates: new
         // outputs are locked for at least 10 blocks and cannot be spent in the same block.
         for reference in ring_references_in(block) {
@@ -444,6 +468,9 @@ pub fn scan_blocks(
                 spends.push((height, key_image, txid));
             }
         }
+        if spends.len() + possible_spends.len() > spends_before {
+            spend_fees.extend(tx_fees_in(block));
+        }
 
         // Cursor base: the previous block's cursor, else the node's claimed
         // start. With neither, stay unknown; falling back to 0 would raise a
@@ -478,6 +505,7 @@ pub fn scan_blocks(
         &known_key_images,
         &block_rows,
         &possible_spends,
+        &spend_fees,
     )?;
     outcome.outputs_without_key_image = count_outputs_without_key_image(db, identity_id)?;
     Ok(outcome)
@@ -522,7 +550,7 @@ fn load_key_images(db: &Db, identity_id: i64) -> Result>
             "SELECT id, key_image FROM outputs o
              WHERE o.identity_id = ?1 AND o.key_image IS NOT NULL
                AND (o.spent_at_height IS NULL OR o.spent_in_txid IN (
-                 SELECT txid FROM transactions WHERE identity_id = ?1 AND height IS NULL))",
+                 SELECT txid FROM transactions WHERE identity_id = ?1 AND (height IS NULL OR scan_valid = 0)))",
         )
         .map_err(|e| db_err("loadKeyImages", e))?;
     let rows = stmt
@@ -546,7 +574,7 @@ fn load_key_images(db: &Db, identity_id: i64) -> Result>
 fn count_outputs_without_key_image(db: &Db, identity_id: i64) -> Result {
     db.conn()
         .query_row(
-            "SELECT count(*) FROM outputs WHERE identity_id = ?1 AND key_image IS NULL",
+            "SELECT count(*) FROM outputs WHERE identity_id = ?1 AND scan_valid = 1 AND key_image IS NULL",
             [identity_id],
             |r| r.get(0),
         )
@@ -563,6 +591,7 @@ fn persist(
     known_key_images: &HashMap<[u8; 32], i64>,
     block_rows: &[(u64, [u8; 32], Option, u64)],
     possible_spends: &[PossibleSpend],
+    spend_fees: &HashMap<[u8; 32], u64>,
 ) -> Result<()> {
     let tx = db
         .conn_mut()
@@ -590,14 +619,20 @@ fn persist(
         )? {
             continue;
         }
-        // `INSERT OR IGNORE`: rescans must be idempotent or balances double.
-        // Unique key is (identity_id, txid, index_in_tx).
+        // Revalidate the same output without losing its key image or send lock.
         tx.execute(
-            "INSERT OR IGNORE INTO outputs
+            "INSERT INTO outputs
                (identity_id, blob, txid, global_index, index_in_tx, amount_atomic,
                 subaddress_major, subaddress_minor, height, additional_timelock,
                 tx_pub_keys, tx_additional_pub_keys, output_key)
-             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
+             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)
+             ON CONFLICT (identity_id, txid, index_in_tx) DO UPDATE SET
+               blob = excluded.blob, global_index = excluded.global_index,
+               amount_atomic = excluded.amount_atomic,
+               subaddress_major = excluded.subaddress_major, subaddress_minor = excluded.subaddress_minor,
+               height = excluded.height, additional_timelock = excluded.additional_timelock,
+               tx_pub_keys = excluded.tx_pub_keys, tx_additional_pub_keys = excluded.tx_additional_pub_keys,
+               output_key = excluded.output_key, scan_valid = 1",
             params![
                 identity_id,
                 output.serialize(),
@@ -621,7 +656,7 @@ fn persist(
                 "INSERT INTO transactions (identity_id, txid, height, timestamp, direction)
                  VALUES (?1, ?2, ?3, ?4, 'in')
                  ON CONFLICT (identity_id, txid) DO UPDATE
-                   SET height = COALESCE(transactions.height, excluded.height), failed = 0,
+                   SET height = excluded.height, failed = 0, scan_valid = 1,
                        timestamp = COALESCE(excluded.timestamp, transactions.timestamp)",
                 params![
                     identity_id,
@@ -641,21 +676,23 @@ fn persist(
         tx.execute(
             "UPDATE outputs SET spent_at_height = ?1, spent_in_txid = ?2
              WHERE id = ?3 AND (spent_at_height IS NULL OR spent_in_txid IN (
-               SELECT txid FROM transactions WHERE identity_id = ?4 AND height IS NULL))",
+               SELECT txid FROM transactions WHERE identity_id = ?4 AND (height IS NULL OR scan_valid = 0)))",
             params![*height as i64, txid.as_slice(), output_id, identity_id],
         )
         .map_err(|e| db_err("markOutputSpent", e))?;
         tx.execute(
-            "INSERT INTO transactions (identity_id, txid, height, timestamp, direction)
-             VALUES (?1, ?2, ?3, ?4, 'out')
+            "INSERT INTO transactions (identity_id, txid, height, timestamp, direction, fee_atomic)
+             VALUES (?1, ?2, ?3, ?4, 'out', ?5)
              ON CONFLICT (identity_id, txid) DO UPDATE
-               SET direction = 'out', height = ?3, failed = 0,
-                   timestamp = COALESCE(excluded.timestamp, transactions.timestamp)",
+               SET direction = 'out', height = ?3, failed = 0, scan_valid = 1,
+                   timestamp = COALESCE(excluded.timestamp, transactions.timestamp),
+                   fee_atomic = COALESCE(excluded.fee_atomic, transactions.fee_atomic)",
             params![
                 identity_id,
                 txid.as_slice(),
                 *height as i64,
-                block_time.get(height)
+                block_time.get(height),
+                spend_fees.get(txid).map(|fee| *fee as i64)
             ],
         )
         .map_err(|e| db_err("insertOutgoingTransaction", e))?;
@@ -665,8 +702,8 @@ fn persist(
     for ps in possible_spends {
         tx.execute(
             "INSERT OR IGNORE INTO possible_spends
-               (identity_id, out_txid, out_index, key_image, spend_txid, height, timestamp)
-             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
+               (identity_id, out_txid, out_index, key_image, spend_txid, height, timestamp, fee_atomic)
+             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
             params![
                 identity_id,
                 ps.out_txid.as_slice(),
@@ -674,7 +711,8 @@ fn persist(
                 ps.key_image.as_slice(),
                 ps.spend_txid.as_slice(),
                 ps.height as i64,
-                ps.timestamp as i64
+                ps.timestamp as i64,
+                spend_fees.get(&ps.spend_txid).map(|fee| *fee as i64)
             ],
         )
         .map_err(|e| db_err("insertPossibleSpend", e))?;
@@ -720,7 +758,7 @@ fn is_burning_duplicate(
 ) -> Result {
     conn.query_row(
         "SELECT EXISTS (SELECT 1 FROM outputs
-           WHERE identity_id = ?1 AND output_key = ?2
+           WHERE identity_id = ?1 AND scan_valid = 1 AND output_key = ?2
              AND NOT (txid = ?3 AND index_in_tx = ?4))",
         params![
             identity_id,
@@ -742,22 +780,7 @@ fn timelock_to_i64(timelock: monero_wallet::transaction::Timelock) -> i64 {
     }
 }
 
-/// Rewinds to `height`, dropping all scan results above it. Destructive; used for
-/// reorg recovery and user rescans.
-///
-/// Our own broadcasts within the reorg window of `tip` revert to pending with
-/// inputs still spent: a reorged-out send usually returns to the pool and is mined
-/// again, and releasing its inputs could let a second send also confirm. Deeper
-/// sends cannot be reorged out; they are dropped and found again by the rescan.
-pub fn rewind_to(db: &mut Db, identity_id: i64, height: u64, tip: u64) -> Result<()> {
-    let tx = db
-        .conn_mut()
-        .transaction()
-        .map_err(|e| db_err("beginRewind", e))?;
-    rewind_in_transaction(&tx, identity_id, height, tip)?;
-    tx.commit().map_err(|e| db_err("commitRewind", e))
-}
-
+/// Invalidate the rewound span, retaining key images and local send evidence.
 pub(crate) fn rewind_in_transaction(
     tx: &rusqlite::Transaction<'_>,
     identity_id: i64,
@@ -766,6 +789,11 @@ pub(crate) fn rewind_in_transaction(
 ) -> Result<()> {
     // Must run before clearing spend marks: that step keeps marks for pending transactions.
     let reorgable_above = height.max(tip.saturating_sub(REORG_WINDOW_BLOCKS));
+    tx.execute(
+        "UPDATE transactions SET scan_valid = 0 WHERE identity_id = ?1 AND height > ?2",
+        params![identity_id, height as i64],
+    )
+    .map_err(|e| db_err("invalidateRewoundTransactions", e))?;
     tx.execute(
         "UPDATE transactions SET height = NULL, failed = 0, pool_checked_at = NULL
          WHERE identity_id = ?1 AND height > ?2 AND sent_at IS NOT NULL",
@@ -774,24 +802,23 @@ pub(crate) fn rewind_in_transaction(
     .map_err(|e| db_err("rewindOwnSends", e))?;
 
     tx.execute(
-        "DELETE FROM outputs WHERE identity_id = ?1 AND height > ?2",
+        "UPDATE outputs SET scan_valid = 0 WHERE identity_id = ?1 AND height > ?2",
         params![identity_id, height as i64],
     )
     .map_err(|e| db_err("rewindOutputs", e))?;
 
-    // Clear spend marks above the height, except for our pending sends: their
-    // height is only the tip at broadcast, and clearing would make the inputs selectable again.
+    // Retain our own send locks until the transaction is reconciled on chain or in the pool.
     tx.execute(
         "UPDATE outputs SET spent_at_height = NULL, spent_in_txid = NULL
          WHERE identity_id = ?1 AND spent_at_height > ?2
            AND spent_in_txid NOT IN (
-             SELECT txid FROM transactions WHERE identity_id = ?1 AND height IS NULL)",
+             SELECT txid FROM transactions WHERE identity_id = ?1 AND (height IS NULL OR sent_at IS NOT NULL))",
         params![identity_id, height as i64],
     )
     .map_err(|e| db_err("rewindSpends", e))?;
 
     tx.execute(
-        "DELETE FROM transactions WHERE identity_id = ?1 AND height > ?2",
+        "DELETE FROM transactions WHERE identity_id = ?1 AND height > ?2 AND sent_at IS NULL",
         params![identity_id, height as i64],
     )
     .map_err(|e| db_err("rewindTransactions", e))?;
@@ -816,6 +843,104 @@ mod tests {
     use super::*;
     use crate::wallet::testing::db_with_identity;
 
+    #[test]
+    fn a_rescan_and_reorg_revalidate_outputs_without_losing_local_send_evidence() {
+        use monero_wallet::ed25519::{Commitment, Point, Scalar};
+        let (mut db, id) = db_with_identity();
+        let txid = [0x61; 32];
+        let own_send = [0x62; 32];
+        let image = [0x63; 32];
+        let mut blob = Vec::new();
+        blob.extend_from_slice(&txid);
+        blob.extend_from_slice(&0u64.to_le_bytes());
+        blob.extend_from_slice(&7u64.to_le_bytes());
+        let scalar = Scalar::read(&mut [1u8; 32].as_slice()).unwrap();
+        Point::from(curve25519_dalek::constants::ED25519_BASEPOINT_POINT)
+            .compress()
+            .write(&mut blob)
+            .unwrap();
+        scalar.write(&mut blob).unwrap();
+        Commitment::new(scalar, 1_000).write(&mut blob).unwrap();
+        blob.extend_from_slice(&[0, 0, 0, 0]);
+        let output = WalletOutput::read(&mut blob.as_slice()).unwrap();
+        persist(
+            &mut db,
+            id,
+            &[(990, output)],
+            &HashMap::new(),
+            &[],
+            &HashMap::new(),
+            &[],
+            &[],
+            &HashMap::new(),
+        )
+        .unwrap();
+        db.conn().execute("INSERT INTO transactions (identity_id, txid, height, direction, sent_at) VALUES (?1, ?2, 995, 'out', 1)", params![id, own_send.as_slice()]).unwrap();
+        db.conn()
+            .execute(
+                "UPDATE outputs SET key_image = ?1, spent_at_height = 995, spent_in_txid = ?2",
+                params![image.as_slice(), own_send.as_slice()],
+            )
+            .unwrap();
+        db.conn()
+            .execute(
+                "UPDATE identities SET scanned_to_height = 1000 WHERE id = ?1",
+                [id],
+            )
+            .unwrap();
+        crate::sync::reset_from_birthday(&mut db, id, 100).unwrap();
+        crate::sync::rewind_and_requeue(&mut db, id, 550, 600).unwrap();
+        let (valid, stored_image, lock): (i64, Vec, Vec) = db
+            .conn()
+            .query_row(
+                "SELECT scan_valid, key_image, spent_in_txid FROM outputs",
+                [],
+                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
+            )
+            .unwrap();
+        assert_eq!(
+            (valid, stored_image, lock),
+            (0, image.to_vec(), own_send.to_vec())
+        );
+        assert_eq!(load_key_images(&db, id).unwrap().get(&image), Some(&1));
+        // The same output on the canonical chain replaces stale chain metadata.
+        blob[40..48].copy_from_slice(&17u64.to_le_bytes());
+        let output = WalletOutput::read(&mut blob.as_slice()).unwrap();
+        persist(
+            &mut db,
+            id,
+            &[(991, output)],
+            &HashMap::new(),
+            &[],
+            &HashMap::new(),
+            &[],
+            &[],
+            &HashMap::new(),
+        )
+        .unwrap();
+        let (valid, index, height, stored_image, lock): (i64, i64, i64, Vec, Vec) = db
+            .conn()
+            .query_row(
+                "SELECT scan_valid, global_index, height, key_image, spent_in_txid FROM outputs",
+                [],
+                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
+            )
+            .unwrap();
+        assert_eq!(
+            (valid, index, height, stored_image, lock),
+            (1, 17, 991, image.to_vec(), own_send.to_vec())
+        );
+        let own_sends: i64 = db
+            .conn()
+            .query_row(
+                "SELECT count(*) FROM transactions WHERE txid = ?1 AND sent_at = 1",
+                [own_send.as_slice()],
+                |r| r.get(0),
+            )
+            .unwrap();
+        assert_eq!(own_sends, 1);
+    }
+
     /// On real mainnet blocks, ring offsets resolve to strictly increasing
     /// absolute indices; ring size is 16 and all inputs are RingCT.
     #[test]
@@ -842,6 +967,23 @@ mod tests {
         assert_eq!(ring_matches(&candidates, target).count(), 1);
     }
 
+    /// Every RingCT transaction in a real block states a small, non-zero fee.
+    #[test]
+    fn real_transactions_state_their_fee() {
+        let blocks = crate::blocks_bin::parse_response(
+            include_bytes!("../tests/fixtures/get_blocks_bin_3768621.bin"),
+            3_768_621,
+        )
+        .expect("parse real response");
+        let fees: Vec<([u8; 32], u64)> = blocks.iter().flat_map(tx_fees_in).collect();
+        let tx_count: usize = blocks.iter().map(|b| b.transactions.len()).sum();
+        assert!(tx_count > 0);
+        assert_eq!(fees.len(), tx_count);
+        for (_, fee) in fees {
+            assert!(fee > 0 && fee < 1_000_000_000_000, "fee {fee}");
+        }
+    }
+
     /// Pre-RingCT input indices are only meaningful within the same amount pool.
     #[test]
     fn a_pre_ringct_input_matches_only_outputs_of_its_amount() {
@@ -936,7 +1078,7 @@ mod tests {
                 .unwrap();
         }
 
-        rewind_to(&mut db, a, 50, 60).unwrap();
+        crate::sync::rewind_and_requeue(&mut db, a, 50, 60).unwrap();
 
         assert!(previous_block_state(&db, a, 101).unwrap().is_none());
         assert!(previous_block_state(&db, b, 101).unwrap().is_some());
@@ -999,6 +1141,7 @@ mod tests {
                 (tip, [8u8; 32], None, 1_700_100_000),
             ],
             &[],
+            &HashMap::new(),
         )
         .unwrap();
 
@@ -1057,6 +1200,7 @@ mod tests {
             &known,
             &[(mined_at, [7u8; 32], None, 1_700_000_000)],
             &[],
+            &HashMap::new(),
         )
         .unwrap();
 
@@ -1084,6 +1228,58 @@ mod tests {
         );
     }
 
+    /// A spend found by scanning keeps its fee, so history can tell the
+    /// payment apart from the fee; a possible spend keeps it until confirmed.
+    #[test]
+    fn a_scanned_spend_records_its_transaction_fee() {
+        let (mut db, id) = db_with_identity();
+        let key_image = [1u8; 32];
+        let (txid, possible_txid) = ([2u8; 32], [3u8; 32]);
+        db.conn()
+            .execute(
+                "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx,
+                                      amount_atomic, height, key_image)
+                 VALUES (?1, x'00', ?2, 1, 0, 700, 10, ?3)",
+                params![id, [9u8; 32].as_slice(), key_image.as_slice()],
+            )
+            .unwrap();
+        let known = load_key_images(&db, id).unwrap();
+        let possible = PossibleSpend {
+            out_txid: [8; 32],
+            out_index: 0,
+            key_image: [4; 32],
+            spend_txid: possible_txid,
+            height: 503,
+            timestamp: 1_700_000_000,
+        };
+        let fees = HashMap::from([(txid, 30_000_000u64), (possible_txid, 40_000_000)]);
+
+        persist(
+            &mut db,
+            id,
+            &[],
+            &HashMap::new(),
+            &[(503, key_image, txid)],
+            &known,
+            &[(503, [7u8; 32], None, 1_700_000_000)],
+            &[possible],
+            &fees,
+        )
+        .unwrap();
+
+        let history = crate::query::history(&db, id, 10, 0).unwrap();
+        assert_eq!(history["items"][0]["feeAtomic"], "30000000");
+        let possible_fee: Option = db
+            .conn()
+            .query_row(
+                "SELECT fee_atomic FROM possible_spends WHERE spend_txid = ?1",
+                [possible_txid.as_slice()],
+                |r| r.get(0),
+            )
+            .unwrap();
+        assert_eq!(possible_fee, Some(40_000_000));
+    }
+
     #[test]
     fn a_rewind_keeps_the_mark_on_outputs_our_pending_send_spent() {
         let (mut db, id) = db_with_identity();
@@ -1104,7 +1300,7 @@ mod tests {
             )
             .unwrap();
 
-        rewind_to(&mut db, id, 490, 505).unwrap();
+        crate::sync::rewind_and_requeue(&mut db, id, 490, 505).unwrap();
 
         let spent_in: Option> = db
             .conn()
@@ -1113,8 +1309,7 @@ mod tests {
         assert_eq!(spent_in, Some(txid.to_vec()));
     }
 
-    /// A rescan far below the reorg window drops our old send instead of
-    /// turning it pending; scanning finds it again.
+    /// A deep rewind retains old sends as unverified instead of treating them as pool transactions.
     #[test]
     fn a_deep_rewind_does_not_turn_old_sends_pending() {
         let (mut db, id) = db_with_identity();
@@ -1127,7 +1322,7 @@ mod tests {
             )
             .unwrap();
 
-        rewind_to(&mut db, id, 490, 500 + REORG_WINDOW_BLOCKS + 10).unwrap();
+        crate::sync::rewind_and_requeue(&mut db, id, 490, 500 + REORG_WINDOW_BLOCKS + 10).unwrap();
 
         let pending: i64 = db
             .conn()
@@ -1164,7 +1359,7 @@ mod tests {
             )
             .unwrap();
 
-        rewind_to(&mut db, id, 490, 505).unwrap();
+        crate::sync::rewind_and_requeue(&mut db, id, 490, 505).unwrap();
 
         let rows: Vec<(Vec, Option)> = db
             .conn()
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
index bb16ff0f1..068a88583 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
@@ -15,9 +15,10 @@
 
 use rusqlite::Connection;
 
-use crate::error::{db_err, Result};
+use crate::error::{db_err, ErrorCode, Result, RuntimeError};
 
-/// Current schema version. Any schema change must add a migration and bump this.
+/// Current schema version. Once released, any schema change must add a migration
+/// and bump this; before that, V1 is edited in place.
 pub const SCHEMA_VERSION: i64 = 1;
 
 /// Reorg safety window: `blocks` keeps hashes only for this many blocks below the tip.
@@ -34,11 +35,9 @@ pub fn migrate(conn: &Connection) -> Result<()> {
         .map_err(|e| db_err("readUserVersion", e))?;
 
     if version > SCHEMA_VERSION {
-        return Err(db_err(
-            "migrate",
-            format!(
-                "database schema version {version} is newer than supported {SCHEMA_VERSION}; refusing to open"
-            ),
+        return Err(RuntimeError::with(
+            ErrorCode::DatabaseTooNew,
+            serde_json::json!({ "version": version, "supportedVersion": SCHEMA_VERSION }),
         ));
     }
 
@@ -187,6 +186,8 @@ CREATE TABLE IF NOT EXISTS outputs (
     tx_additional_pub_keys  BLOB,
     -- One-time output public key, for burning-bug checks (only one output per key is spendable)
     output_key          BLOB    CHECK (output_key IS NULL OR length(output_key) = 32),
+    -- 0 while a rescan or reorg re-verifies the row; it does not count until seen again
+    scan_valid          INTEGER NOT NULL DEFAULT 1 CHECK (scan_valid IN (0, 1)),
     UNIQUE (identity_id, txid, index_in_tx)
 );
 CREATE INDEX IF NOT EXISTS idx_outputs_unspent
@@ -216,6 +217,10 @@ CREATE TABLE IF NOT EXISTS transactions (
     -- Pending change, piconero decimal string. wallet2 counts it in the total
     -- (locked) balance; once scanned it becomes a normal output and is not counted here.
     change_atomic   TEXT,
+    -- Network fee, piconero, read from the scanned spending transaction.
+    fee_atomic      INTEGER,
+    -- 0 while a rescan or reorg re-verifies the row; shown without a height until seen again
+    scan_valid      INTEGER NOT NULL DEFAULT 1 CHECK (scan_valid IN (0, 1)),
     PRIMARY KEY (identity_id, txid)
 );
 CREATE INDEX IF NOT EXISTS idx_transactions_height ON transactions(identity_id, height);
@@ -237,6 +242,8 @@ CREATE TABLE IF NOT EXISTS possible_spends (
     spend_txid   BLOB    NOT NULL CHECK (length(spend_txid) = 32),
     height       INTEGER NOT NULL,
     timestamp    INTEGER,
+    -- The spending transaction's fee, moved to `transactions` once confirmed
+    fee_atomic   INTEGER,
     PRIMARY KEY (identity_id, out_txid, out_index, key_image)
 );
 CREATE INDEX IF NOT EXISTS idx_possible_spends_height ON possible_spends(identity_id, height);
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
index d341a379e..042d9ddf6 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -146,17 +146,17 @@ fn apply_key_images(
         )
         .map_err(|e| db_err("updateKeyImage", e))?;
 
-        let spent: Option<(Vec, i64, Option)> = tx
+        let spent: Option<(Vec, i64, Option, Option)> = tx
             .query_row(
-                "SELECT spend_txid, height, timestamp FROM possible_spends
+                "SELECT spend_txid, height, timestamp, fee_atomic FROM possible_spends
                  WHERE identity_id = ?1 AND out_txid = ?2 AND out_index = ?3 AND key_image = ?4
                  ORDER BY height LIMIT 1",
                 params![identity_id, txid, index, image.as_slice()],
-                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
+                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
             )
             .optional()
             .map_err(|e| db_err("matchPossibleSpend", e))?;
-        if let Some((spend_txid, height, timestamp)) = spent {
+        if let Some((spend_txid, height, timestamp, fee)) = spent {
             tx.execute(
                 "UPDATE outputs SET spent_at_height = ?1, spent_in_txid = ?2
                  WHERE id = ?3 AND spent_at_height IS NULL",
@@ -164,12 +164,13 @@ fn apply_key_images(
             )
             .map_err(|e| db_err("markPossibleSpend", e))?;
             tx.execute(
-                "INSERT INTO transactions (identity_id, txid, height, timestamp, direction)
-                 VALUES (?1, ?2, ?3, ?4, 'out')
+                "INSERT INTO transactions (identity_id, txid, height, timestamp, direction, fee_atomic)
+                 VALUES (?1, ?2, ?3, ?4, 'out', ?5)
                  ON CONFLICT (identity_id, txid) DO UPDATE
                    SET direction = 'out', height = ?3, failed = 0,
-                       timestamp = COALESCE(excluded.timestamp, transactions.timestamp)",
-                params![identity_id, spend_txid, height, timestamp],
+                       timestamp = COALESCE(excluded.timestamp, transactions.timestamp),
+                       fee_atomic = COALESCE(excluded.fee_atomic, transactions.fee_atomic)",
+                params![identity_id, spend_txid, height, timestamp, fee],
             )
             .map_err(|e| db_err("recordPossibleSpend", e))?;
             spends_found += 1;
@@ -818,6 +819,29 @@ mod tests {
         assert_eq!(left, 0, "key-imaged outputs need no possible spends");
     }
 
+    /// A confirmed possible spend carries the fee scanning read from its transaction.
+    #[test]
+    fn a_confirmed_possible_spend_keeps_its_fee() {
+        let (mut db, id) = db_with_identity();
+        let spent = add_output(&db, id, 700, 10, false);
+        add_possible_spend(&db, id, 10, 0xAA, 0x51, 30);
+        db.conn()
+            .execute("UPDATE possible_spends SET fee_atomic = 30000000", [])
+            .unwrap();
+
+        apply_key_images(&mut db, id, &[(spent, [0xAA; 32], vec![10; 32], 0)]).unwrap();
+
+        let fee: Option = db
+            .conn()
+            .query_row(
+                "SELECT fee_atomic FROM transactions WHERE txid = ?1",
+                [vec![0x51u8; 32]],
+                |r| r.get(0),
+            )
+            .unwrap();
+        assert_eq!(fee, Some(30_000_000));
+    }
+
     /// A serialized `WalletOutput` owned by `spend` with the given offset.
     fn owned_output_blob(spend: &[u8; 32], offset: u8, txid: [u8; 32]) -> (Vec, [u8; 32]) {
         use monero_wallet::ed25519::Commitment;
@@ -1718,18 +1742,21 @@ pub(crate) fn check_inputs_owned(
         ));
     }
     for key_image in key_images {
-        let spent_in: Option>> = db
+        let owned: Option<(Option>, bool, bool)> = db
             .query_row(
-                "SELECT CASE WHEN spent_at_height IS NULL THEN NULL ELSE spent_in_txid END
+                "SELECT CASE WHEN spent_at_height IS NULL THEN NULL ELSE spent_in_txid END,
+                        scan_valid, EXISTS (SELECT 1 FROM transactions
+                          WHERE identity_id = ?1 AND txid = ?3 AND sent_at IS NOT NULL)
                  FROM outputs WHERE identity_id = ?1 AND key_image = ?2",
-                params![identity_id, key_image.as_slice()],
-                |r| r.get(0),
+                params![identity_id, key_image.as_slice(), txid.as_slice()],
+                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
             )
             .optional()
             .map_err(|e| db_err("checkInputOwner", e))?;
-        let reason = match spent_in {
+        let reason = match owned {
             None => "inputNotOwnedByAccount",
-            Some(Some(other)) if other.as_slice() != txid.as_slice() => "inputAlreadySpent",
+            Some((_, false, false)) => "inputNotVerified",
+            Some((Some(other), _, _)) if other.as_slice() != txid.as_slice() => "inputAlreadySpent",
             Some(_) => continue,
         };
         return Err(RuntimeError::with(
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
index e73bb3518..6901a4982 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
@@ -401,6 +401,97 @@ pub fn peek(db: &Db, identity_id: i64) -> Result {
     }))
 }
 
+/// Starts the identity over at `birthday`: rows below it are removed, rows at or
+/// above it are re-verified by the rescan, and pending sends keep their inputs.
+pub(crate) fn reset_from_birthday(db: &mut Db, identity_id: i64, birthday: u64) -> Result<()> {
+    let tx = db
+        .conn_mut()
+        .transaction()
+        .map_err(|e| db_err("beginResetScan", e))?;
+    reset_scan_in_transaction(&tx, identity_id, birthday)?;
+    tx.commit().map_err(|e| db_err("commitResetScan", e))
+}
+
+pub(crate) fn reset_scan_in_transaction(
+    tx: &rusqlite::Transaction<'_>,
+    identity_id: i64,
+    birthday: u64,
+) -> Result<()> {
+    let birthday = i64::try_from(birthday).map_err(|_| {
+        RuntimeError::with(
+            ErrorCode::InvalidBlockRange,
+            json!({ "birthdayHeight": birthday }),
+        )
+    })?;
+    let tip: Option = tx
+        .query_row(
+            "SELECT max(height) FROM (
+           SELECT scanned_to_height AS height FROM identities WHERE id = ?1
+           UNION ALL SELECT end_height - 1 FROM scan_ranges WHERE identity_id = ?1
+           UNION ALL SELECT height FROM blocks WHERE identity_id = ?1)",
+            [identity_id],
+            |row| row.get(0),
+        )
+        .map_err(|e| db_err("resetScanTip", e))?;
+    // The new birthday drops everything found before it, except the inputs of
+    // own sends that are not mined yet.
+    tx.execute(
+        "DELETE FROM outputs WHERE identity_id = ?1 AND height < ?2
+           AND (spent_in_txid IS NULL OR spent_in_txid NOT IN (
+             SELECT txid FROM transactions
+             WHERE identity_id = ?1 AND sent_at IS NOT NULL AND height IS NULL))",
+        params![identity_id, birthday],
+    )
+    .map_err(|e| db_err("clearOutputsBeforeBirthday", e))?;
+    tx.execute(
+        "DELETE FROM transactions WHERE identity_id = ?1 AND height < ?2",
+        params![identity_id, birthday],
+    )
+    .map_err(|e| db_err("clearTransactionsBeforeBirthday", e))?;
+    tx.execute(
+        "UPDATE outputs SET scan_valid = 0,
+           spent_at_height = CASE WHEN spent_in_txid IN (
+             SELECT txid FROM transactions WHERE identity_id = ?1 AND sent_at IS NOT NULL)
+             THEN spent_at_height ELSE NULL END,
+           spent_in_txid = CASE WHEN spent_in_txid IN (
+             SELECT txid FROM transactions WHERE identity_id = ?1 AND sent_at IS NOT NULL)
+             THEN spent_in_txid ELSE NULL END
+         WHERE identity_id = ?1",
+        [identity_id],
+    )
+    .map_err(|e| db_err("invalidateScanOutputs", e))?;
+    tx.execute(
+        "DELETE FROM transactions WHERE identity_id = ?1 AND sent_at IS NULL",
+        [identity_id],
+    )
+    .map_err(|e| db_err("clearScannedTransactions", e))?;
+    tx.execute(
+        "UPDATE transactions SET scan_valid = 0 WHERE identity_id = ?1",
+        [identity_id],
+    )
+    .map_err(|e| db_err("invalidateScanTransactions", e))?;
+    for table in ["blocks", "scan_ranges", "possible_spends"] {
+        tx.execute(
+            &format!("DELETE FROM {table} WHERE identity_id = ?1"),
+            [identity_id],
+        )
+        .map_err(|e| db_err("clearScanIndexes", e))?;
+    }
+    tx.execute(
+        "UPDATE identities SET birthday_height = ?2, scanned_to_height = NULL WHERE id = ?1",
+        params![identity_id, birthday],
+    )
+    .map_err(|e| db_err("resetScanBirthday", e))?;
+    if let Some(tip) = tip.filter(|tip| *tip >= birthday) {
+        tx.execute(
+            "INSERT INTO scan_ranges (identity_id, start_height, end_height) VALUES (?1, ?2, ?3)",
+            params![identity_id, birthday, tip.saturating_add(1)],
+        )
+        .map_err(|e| db_err("resetScanRange", e))?;
+    }
+    Ok(())
+}
+
 /// Reorg recovery: rewind to `height` and requeue everything above it.
 pub fn rewind_and_requeue(db: &mut Db, identity_id: i64, height: u64, tip: u64) -> Result {
     let tx = db
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs
index f5a6fbee5..652e60001 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs
@@ -100,6 +100,17 @@ impl Db {
         spend_public: &[u8],
         view_private: &[u8],
         birthday_height: u64,
+    ) -> Result {
+        self.add_identity_with_rescan(uuid, spend_public, view_private, birthday_height, false)
+    }
+
+    pub fn add_identity_with_rescan(
+        &mut self,
+        uuid: &str,
+        spend_public: &[u8],
+        view_private: &[u8],
+        birthday_height: u64,
+        force_rescan: bool,
     ) -> Result {
         let pair = keys::view_pair_from_bytes(spend_public, view_private)?;
         let primary = keys::primary_address(&pair, self.network);
@@ -115,12 +126,15 @@ impl Db {
             .map_err(|e| db_err("findIdentity", e))?;
         if let Some((id, address)) = by_uuid {
             if address == primary {
+                if force_rescan || self.identity_by_id(id)?.birthday_height != birthday_height {
+                    crate::sync::reset_from_birthday(self, id, birthday_height)?;
+                }
                 return self.identity_by_id(id);
             }
-            // Same account id with new keys (a reset wallet reused the id): the
-            // old data belongs to a gone wallet and would be attributed to the
-            // new one, so delete it.
-            self.remove_identity(uuid)?;
+            return Err(RuntimeError::with(
+                ErrorCode::InvalidRequest,
+                json!({ "field": "uuid", "reason": "identityKeyMismatch" }),
+            ));
         }
 
         // Same keys under a new id (deleted and reimported): keep the scan data under the new id.
@@ -136,12 +150,21 @@ impl Db {
 
         let id = match by_address {
             Some(id) => {
-                self.conn
-                    .execute(
-                        "UPDATE identities SET uuid = ?1 WHERE id = ?2",
-                        params![uuid, id],
-                    )
-                    .map_err(|e| db_err("renameIdentity", e))?;
+                let rescan =
+                    force_rescan || self.identity_by_id(id)?.birthday_height != birthday_height;
+                let tx = self
+                    .conn
+                    .transaction()
+                    .map_err(|e| db_err("beginRenameIdentity", e))?;
+                tx.execute(
+                    "UPDATE identities SET uuid = ?1 WHERE id = ?2",
+                    params![uuid, id],
+                )
+                .map_err(|e| db_err("renameIdentity", e))?;
+                if rescan {
+                    crate::sync::reset_scan_in_transaction(&tx, id, birthday_height)?;
+                }
+                tx.commit().map_err(|e| db_err("commitRenameIdentity", e))?;
                 id
             }
             None => {
@@ -413,21 +436,26 @@ mod tests {
     }
 
     #[test]
-    fn the_same_account_id_with_other_keys_starts_clean() {
+    fn different_keys_require_explicit_identity_deletion() {
         let (mut db, old) = db_with_identity();
         insert_output_at_minor(&db, old, 1);
         let (spend, _) = key_bytes();
         let mut other_view = [0u8; 32];
         other_view[0] = 11;
 
-        let fresh = db.add_identity("acct-1", &spend, &other_view, 100).unwrap();
-
-        assert_ne!(fresh.id, old);
+        let error = db
+            .add_identity("acct-1", &spend, &other_view, 100)
+            .err()
+            .unwrap();
+        assert_eq!(error.params["reason"], "identityKeyMismatch");
         let outputs: i64 = db
             .conn()
             .query_row("SELECT count(*) FROM outputs", [], |r| r.get(0))
             .unwrap();
-        assert_eq!(outputs, 0);
+        assert_eq!(outputs, 1);
+        db.remove_identity("acct-1").unwrap();
+        let fresh = db.add_identity("acct-1", &spend, &other_view, 100).unwrap();
+        assert_ne!(fresh.id, old);
     }
 
     /// Reimport after deletion (new id, same keys) reuses the scan data and must
@@ -448,7 +476,7 @@ mod tests {
         let mut db = db();
         let (spend, view) = key_bytes();
         let a = db.add_identity("acct-1", &spend, &view, 100).unwrap();
-        let b = db.add_identity("acct-1", &spend, &view, 999).unwrap();
+        let b = db.add_identity("acct-1", &spend, &view, 100).unwrap();
         assert_eq!(a.id, b.id, "same uuid must reuse the row");
         assert_eq!(
             b.birthday_height, 100,
@@ -457,6 +485,103 @@ mod tests {
         assert_eq!(db.list_identities().unwrap().len(), 1);
     }
 
+    #[test]
+    fn a_later_birthday_drops_older_rows_but_keeps_pending_send_inputs() {
+        let (mut db, id) = db_with_identity();
+        let (spend, view) = key_bytes();
+        insert_output_at_minor(&db, id, 1);
+        insert_output_at_minor(&db, id, 2);
+        for (minor, image) in [(1, [7u8; 32]), (2, [8u8; 32])] {
+            db.conn().execute("UPDATE outputs SET key_image = ?2 WHERE identity_id = ?1 AND subaddress_minor = ?3", params![id, image.as_slice(), minor]).unwrap();
+        }
+        let sent = [9u8; 32];
+        db.conn().execute("INSERT INTO transactions (identity_id, txid, direction, sent_at, change_atomic) VALUES (?1, ?2, 'out', 1, '2')", params![id, sent.as_slice()]).unwrap();
+        db.conn().execute("UPDATE outputs SET spent_at_height = 200, spent_in_txid = ?2 WHERE identity_id = ?1 AND subaddress_minor = 1", params![id, sent.as_slice()]).unwrap();
+        crate::sync::update_chain_tip(&mut db, id, 1_000).unwrap();
+
+        let changed = db.add_identity("acct-1", &spend, &view, 900).unwrap();
+
+        assert_eq!(changed.id, id);
+        assert_eq!(changed.birthday_height, 900);
+        assert_eq!(
+            crate::sync::peek(&db, id).unwrap()["ranges"],
+            json!([{ "start": 900, "end": 1_001 }])
+        );
+        assert!(crate::query::spendable_rows(&db, id, 1_000)
+            .unwrap()
+            .is_empty());
+        let balance = crate::query::balance(&db, id, Some(1_000)).unwrap();
+        assert_eq!(
+            balance.total_atomic, 2,
+            "only the still-pending change is retained in balance"
+        );
+        let images: i64 = db
+            .conn()
+            .query_row(
+                "SELECT count(*) FROM outputs WHERE identity_id = ?1 AND key_image IS NOT NULL",
+                [id],
+                |r| r.get(0),
+            )
+            .unwrap();
+        assert_eq!(images, 1, "only the pending send's input is kept");
+        assert!(crate::spend::check_inputs_owned(db.conn(), id, &sent, &[[7u8; 32]]).is_ok());
+        let error =
+            crate::spend::check_inputs_owned(db.conn(), id, &[10u8; 32], &[[8u8; 32]]).unwrap_err();
+        assert_eq!(error.params["reason"], "inputNotOwnedByAccount");
+        assert_eq!(
+            db.add_identity("acct-1", &spend, &view, 100)
+                .unwrap()
+                .birthday_height,
+            100
+        );
+    }
+
+    #[test]
+    fn a_later_birthday_removes_older_confirmed_sends_from_history() {
+        let (mut db, id) = db_with_identity();
+        let (spend, view) = key_bytes();
+        for (txid, height) in [([3u8; 32], 150), ([4u8; 32], 950)] {
+            db.conn().execute("INSERT INTO transactions (identity_id, txid, height, direction, sent_at) VALUES (?1, ?2, ?3, 'out', 1)", params![id, txid.as_slice(), height]).unwrap();
+        }
+        crate::sync::update_chain_tip(&mut db, id, 1_000).unwrap();
+
+        db.add_identity("acct-1", &spend, &view, 900).unwrap();
+
+        let history = crate::query::history(&db, id, 10, 0).unwrap();
+        let txids: Vec<_> = history["items"]
+            .as_array()
+            .unwrap()
+            .iter()
+            .map(|item| item["txid"].as_str().unwrap().to_owned())
+            .collect();
+        assert_eq!(txids, vec![hex::encode([4u8; 32])]);
+    }
+
+    #[test]
+    fn a_failed_birthday_change_rolls_back_scan_invalidation() {
+        let (mut db, id) = db_with_identity();
+        insert_output_at_minor(&db, id, 1);
+        crate::sync::update_chain_tip(&mut db, id, 200).unwrap();
+        db.conn().execute_batch("CREATE TRIGGER fail_scan_reset BEFORE UPDATE OF birthday_height ON identities BEGIN SELECT RAISE(ABORT, 'synthetic storage failure'); END;").unwrap();
+        let (spend, view) = key_bytes();
+        assert!(db.add_identity("acct-1", &spend, &view, 150).is_err());
+        assert_eq!(db.identity_by_id(id).unwrap().birthday_height, 100);
+        assert_eq!(
+            crate::sync::peek(&db, id).unwrap()["ranges"],
+            json!([{ "start": 100, "end": 201 }])
+        );
+        assert_eq!(
+            db.conn()
+                .query_row(
+                    "SELECT scan_valid FROM outputs WHERE identity_id = ?1",
+                    [id],
+                    |r| r.get::<_, i64>(0)
+                )
+                .unwrap(),
+            1
+        );
+    }
+
     /// Per-database network invariant: mixing networks silently breaks scanning.
     #[test]
     fn a_database_refuses_a_different_network() {

From 4b267905a9793751cfbe3a8b8310b1c7e4c4e323 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Tue, 27 Oct 2026 09:48:19 +0800
Subject: [PATCH 75/97] chore: bump privacy runtimes to 0.1.0-alpha.9

---
 chain-runtimes/monero/Cargo.lock | 2 +-
 chain-runtimes/monero/Cargo.toml | 2 +-
 chain-runtimes/zcash/Cargo.lock  | 4 ++--
 chain-runtimes/zcash/Cargo.toml  | 2 +-
 4 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock
index a888a1946..1da2dff5a 100644
--- a/chain-runtimes/monero/Cargo.lock
+++ b/chain-runtimes/monero/Cargo.lock
@@ -1259,7 +1259,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-monero-runtime"
-version = "0.1.0-alpha.8"
+version = "0.1.0-alpha.9"
 dependencies = [
  "curve25519-dalek",
  "futures-lite",
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index 8adf39b3c..53cbbbaae 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/monero-runtime"]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.8"
+version = "0.1.0-alpha.9"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index 38e52c183..f010dd4fe 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1655,7 +1655,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-zcash-keys"
-version = "0.1.0-alpha.8"
+version = "0.1.0-alpha.9"
 dependencies = [
  "bip0039",
  "bip32",
@@ -1687,7 +1687,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-runtime"
-version = "0.1.0-alpha.8"
+version = "0.1.0-alpha.9"
 dependencies = [
  "blake2b_simd",
  "console_error_panic_hook",
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index 561fc07c6..df8db6e37 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -7,7 +7,7 @@ members = [
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.8"
+version = "0.1.0-alpha.9"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"

From a28c995bcd702d8d908f0ec4772e13fc25c73389 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Tue, 27 Oct 2026 10:51:30 +0800
Subject: [PATCH 76/97] chore: trim chain runtime comments and docs

Comments drop history, comparisons and doc pointers and keep the rule they
carry; code is unchanged. The runtime READMEs keep build, release and API
notes only; the Zcash release note and transparent API doc leave the repo.
---
 .github/workflows/runtime-checks.yml          |   3 +-
 chain-runtimes/README.md                      |   2 +-
 chain-runtimes/monero/Cargo.toml              |   8 +-
 chain-runtimes/monero/README.md               |  92 +--------
 .../monero/crates/monero-runtime/build.rs     |   9 +-
 .../crates/monero-runtime/src/bindgen.rs      |  91 +++------
 .../crates/monero-runtime/src/blocks_bin.rs   |  82 ++------
 .../monero/crates/monero-runtime/src/error.rs |  15 +-
 .../monero/crates/monero-runtime/src/keys.rs  |  85 ++-------
 .../monero/crates/monero-runtime/src/lib.rs   |  16 +-
 .../crates/monero-runtime/src/network.rs      |  99 +++-------
 .../monero/crates/monero-runtime/src/perf.rs  |   5 +-
 .../monero/crates/monero-runtime/src/query.rs |  79 ++------
 .../crates/monero-runtime/src/runtime.rs      |  10 +-
 .../monero/crates/monero-runtime/src/scan.rs  | 102 +++-------
 .../crates/monero-runtime/src/schema.rs       |  29 +--
 .../monero/crates/monero-runtime/src/spend.rs | 169 +++++-----------
 .../crates/monero-runtime/src/storage.rs      |  68 ++-----
 .../monero/crates/monero-runtime/src/sync.rs  |  72 +++----
 .../crates/monero-runtime/src/wallet.rs       |   9 +-
 .../crates/monero-runtime/tests/live_node.rs  |  15 +-
 chain-runtimes/monero/rust-toolchain.toml     |   3 +-
 chain-runtimes/zcash/Cargo.toml               |  26 +--
 chain-runtimes/zcash/README.md                | 180 +++---------------
 chain-runtimes/zcash/RELEASING.md             |  50 -----
 .../crates/zcash-keys-runtime/Cargo.toml      |  20 +-
 .../zcash-keys-runtime/TRANSPARENT_TX_API.md  | 132 -------------
 .../zcash/crates/zcash-keys-runtime/build.rs  |   4 +-
 .../zcash-keys-runtime/src/account_keys.rs    |  42 +---
 .../crates/zcash-keys-runtime/src/bindgen.rs  |  39 +---
 .../crates/zcash-keys-runtime/src/error.rs    |  38 +---
 .../crates/zcash-keys-runtime/src/keys.rs     |  40 +---
 .../crates/zcash-keys-runtime/src/lib.rs      |  19 +-
 .../crates/zcash-keys-runtime/src/review.rs   |   7 +-
 .../crates/zcash-keys-runtime/src/sign.rs     |  52 ++---
 .../src/transparent_prevouts.rs               |   4 +-
 .../src/transparent_send.rs                   |  55 ++----
 .../src/transparent_send/shielding.rs         |  37 +---
 .../zcash/crates/zcash-runtime/Cargo.toml     |   6 +-
 .../zcash/crates/zcash-runtime/build.rs       |  10 +-
 .../zcash/crates/zcash-runtime/src/account.rs |  38 ++--
 .../zcash/crates/zcash-runtime/src/bindgen.rs |  45 +----
 .../crates/zcash-runtime/src/blockcache.rs    |  26 +--
 .../zcash/crates/zcash-runtime/src/clock.rs   |   9 +-
 .../zcash/crates/zcash-runtime/src/error.rs   |  38 +---
 .../zcash/crates/zcash-runtime/src/history.rs |  40 ++--
 .../zcash/crates/zcash-runtime/src/lib.rs     |  28 +--
 .../zcash/crates/zcash-runtime/src/network.rs |  63 ++----
 .../zcash/crates/zcash-runtime/src/runtime.rs |  52 ++---
 .../zcash/crates/zcash-runtime/src/send.rs    |  37 ++--
 .../zcash/crates/zcash-runtime/src/stats.rs   |  15 +-
 .../zcash/crates/zcash-runtime/src/storage.rs |  29 +--
 .../zcash/crates/zcash-runtime/src/sync.rs    |  82 +++-----
 .../crates/zcash-runtime/src/sync_tests.rs    |  25 +--
 .../crates/zcash-runtime/src/tx_state.rs      |  16 +-
 .../zcash/crates/zcash-runtime/src/wallet.rs  |   7 +-
 chain-runtimes/zcash/scripts/build-wasm.sh    |  22 +--
 .../zcash/scripts/prepare-vendor.py           |   1 -
 58 files changed, 530 insertions(+), 1867 deletions(-)
 delete mode 100644 chain-runtimes/zcash/RELEASING.md
 delete mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md

diff --git a/.github/workflows/runtime-checks.yml b/.github/workflows/runtime-checks.yml
index a761e6a0c..19bab5328 100644
--- a/.github/workflows/runtime-checks.yml
+++ b/.github/workflows/runtime-checks.yml
@@ -1,7 +1,6 @@
 name: runtime-checks
 
-# Runs each runtime's scripts/ci.sh on pull requests. Checks only; publishing
-# stays manual in publish-runtime-packages.yml, whose build tools this mirrors.
+# Runs each runtime's scripts/ci.sh on pull requests; mirrors the build tools of publish-runtime-packages.yml.
 on:
   pull_request:
     paths:
diff --git a/chain-runtimes/README.md b/chain-runtimes/README.md
index e7bf9b7af..8c5907478 100644
--- a/chain-runtimes/README.md
+++ b/chain-runtimes/README.md
@@ -4,7 +4,7 @@ Rust chain libraries compiled to wasm. Each chain owns its Cargo workspace,
 lockfile, toolchain, patches and build outputs. These are not React Native packages
 and are not part of the root Yarn workspaces or their version/publish commands.
 
-- [Zcash](./zcash/README.md) ([release process](./zcash/RELEASING.md))
+- [Zcash](./zcash/README.md)
 - [Monero](./monero/README.md)
 
 Root shortcuts for Zcash (the direct commands in its README need no Node install):
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index 53cbbbaae..e14e343b8 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -9,9 +9,7 @@ edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
 
-# monero-oxide over wallet2: one small wasm build for all platforms, no
-# cross-origin isolation, no C++ cross toolchain. It has no storage layer;
-# this workspace persists wallet state to SQLite.
+# monero-oxide has no storage layer; this workspace persists wallet state to SQLite.
 [workspace.dependencies]
 monero-wallet = { version = "0.2", default-features = false, features = ["std"] }
 monero-address = { version = "0.1", default-features = false, features = ["std"] }
@@ -20,9 +18,7 @@ monero-interface = { version = "0.2", default-features = false, features = ["std
 # get_blocks.bin request and parsing (blocks_bin.rs); same version as monero-daemon-rpc uses.
 monero-epee = { version = "0.2", default-features = false }
 
-# SQLite on wasm, same setup as the Zcash runtime. rusqlite without "bundled"
-# (wasm32 has no libc sysroot for SQLite's C sources); sqlite-wasm-rs provides
-# the sqlite3 symbols.
+# rusqlite without "bundled" (no libc sysroot on wasm32); sqlite-wasm-rs provides the symbols.
 rusqlite = { version = "0.37", default-features = false }
 sqlite-wasm-rs = "0.5"
 # OPFS sync-access VFS, patched with the Zcash runtime's patch (see
diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md
index bbc99b816..5fa2cf304 100644
--- a/chain-runtimes/monero/README.md
+++ b/chain-runtimes/monero/README.md
@@ -17,12 +17,8 @@ cargo check --workspace --target wasm32-unknown-unknown
 `smoke.js` runs offline; set `XMR_NODE=` to add node checks. The
 toolchain matches the Zcash runtime: Rust 1.93.0 (pinned in `rust-toolchain.toml`),
 wasm-pack 0.15.0, `wasm-bindgen-cli` at the version in `Cargo.lock`, and `wasm-opt`
-(Binaryen).
-
-**macOS needs `llvm-ar`** (`brew install llvm`). `/usr/bin/ar` cannot read wasm
-objects and silently writes an empty archive; linking then fails with
-`undefined symbol: sqlite3_*`, which `cargo check` never shows. `build-wasm.sh` and
-`.cargo/config.toml` pick up Homebrew's toolchain.
+(Binaryen). On macOS, install `llvm-ar` (`brew install llvm`); `/usr/bin/ar` cannot
+read wasm objects.
 
 ## Release
 
@@ -32,47 +28,17 @@ releases to `latest`. Branches other than `main` can publish alpha versions only
 `python3 scripts/package-release.py --version  --tag ` packs into
 `dist/` locally without publishing.
 
-## Host contract
-
-1. **Import key images on unlock.** A view-only wallet cannot detect spends, so the
-   balance stays too high until `importKeyImagesWithBip32Key` is called. It covers
-   only blocks scanned afterwards; earlier spends need a rewind and rescan. `balance`
-   reports the unverified part as `unverifiableAtomic`.
-2. **The node must be on the wallet's network.** It is identified by its genesis
-   block; a mismatch fails with `NODE_NETWORK_MISMATCH`. `chainTip` works without an
-   open wallet and returns `network`; check it before picking a birthday.
-3. **An `unknown` broadcast is not a failure.** The send is recorded and its inputs
-   marked spent before broadcasting; pool checks and scanning settle it. Do not
-   translate an unclear broadcast result into a failure or prompt a resend.
-4. **The host schedules sync.** `syncStep` scans at most `maxBlocks` and returns.
-   Its existing pool refresh includes previously failed own sends. A matching
-   transaction seen in the pool restores the record and released inputs in one
-   SQLite transaction, unless a later local spend already owns an input.
-   `sendsRestored` reports those changes so the host can refresh balances/history.
-5. **Register subaddresses before use.** Funds to unregistered subaddresses go
-   undetected.
-6. **Local management does not require a live tip.** Deletion needs only the local
-   database. For `rewindTo`, pass the last locally observed tip; normal sync fetches
-   a fresh one later. Rewind, cursor updates and range requeue commit together.
-7. **Changing an existing identity's birthday starts it over there.** `addAccount`
-   keeps the identity and subaddresses, deletes outputs and transactions below the
-   new birthday (except inputs of unmined own sends), and atomically requeues the
-   target range. Rows at or above it are re-verified by the rescan: until seen
-   again they do not count toward balance or input selection, and sends show
-   without a confirmed height.
-
 ## API
 
 Values cross the boundary as strings, numbers, booleans, bytes or JSON strings.
-Errors carry a stable `code` and structured `params`; user-facing text belongs to
-the host.
+Errors carry a stable `code` and structured `params`.
 
 ```
 init() / dependencyVersions()
-storageRequiresWorkerRestart()                  true after a VFS failure
+storageRequiresWorkerRestart()
 openWallet(dbName, network) / closeWallet() / deleteWallet(dbName)
-setNodeUrl(url) / setRequestHandler(handler)    no default node
-chainTip()                                      { height, network }
+setNodeUrl(url) / setRequestHandler(handler)
+chainTip()
 
 deriveAccount(network, bip32PrivateKeyHex)
 deriveSubaddress(network, spendPub, viewPriv, major, minor)
@@ -82,7 +48,7 @@ registerSubaddress(accountId, major, minor, label?)
 importKeyImagesWithBip32Key(accountId, bip32PrivateKeyHex)
 
 updateChainTip(accountId, tip) / syncStep(accountId, maxBlocks) / syncPeek(accountId)
-rewindTo(accountId, height, tip)                destructive
+rewindTo(accountId, height, tip)
 balance(accountId, chainTip?) / history(accountId, limit, offset)
 transactionDetails(accountId, txid)
 
@@ -93,47 +59,3 @@ signTransactionWithBip32Key(signableHex, bip32PrivateKeyHex, reviewJson)
 broadcastTransaction(accountId, rawHex, chainTip, outgoingAtomic?, changeAtomic?, signableHex, reviewJson)
 diagDatabase()
 ```
-
-### Sending
-
-```
-prepareTransaction           select inputs, build; no spend key
-verifyTransaction            check recipient, amount, fee and change against the review
-signTransactionWithBip32Key  verify again, reduce the spend key from the account BIP-32 key, sign; no network, no DB
-broadcastTransaction         record, then broadcast → { txid, broadcast: accepted | unknown }
-```
-
-- `prepareTransaction` takes exactly one recipient.
-- Before broadcasting, the host verifies the signed transaction against the same
-  prepared transaction and review. `broadcastTransaction` repeats that check
-  before touching the database or node, and rejects calls without review
-  evidence. The reviewed sender and network must match the local account, so
-  another account's change cannot be credited to this account.
-- Pending outgoing and change amounts come from that verified review. Optional
-  host amount strings must be canonical unsigned integers equal to those values;
-  missing strings do not discard the amounts derived from the review.
-- `verifySignedTransaction` returns the signed transaction id. It uses the pinned
-  wallet library's output matching and the transaction's fee; it performs no
-  network request and persists no data. This matches outputs and the fee; it
-  does not replace the node's signature and consensus validation.
-- A `broadcastTransaction` whose inputs are not this account's, or are already
-  spent elsewhere, is refused with `INVALID_REQUEST` before anything is recorded.
-- `BROADCAST_REJECTED` is thrown only when the node explicitly rejects a first
-  broadcast for a reason other than double spend; the record is undone and the
-  inputs released.
-- Inputs are not reserved between prepare and broadcast. Two sends built from
-  the same inputs both sign, but only the first broadcast is recorded; the second
-  is refused with `inputAlreadySpent`. Inputs of a send the node never received
-  are released after the propagation timeout and an explicit missing response,
-  and can be spent again. Failed sends remain eligible for normal pool refresh;
-  response transaction hashes are checked against their serialized bodies before
-  updating local input ownership.
-- The scanner derives RingCT output indexes itself and fails with
-  `RINGCT_INDEX_MISMATCH` when the node's claim differs.
-
-## Relation to the Zcash runtime
-
-No code dependency, but one storage layer: `vendor-deps.sh` rebuilds
-`sqlite-wasm-vfs` with the Zcash patch via its `prepare-vendor.py`, so a VFS fix
-lands in both. `crates/monero-runtime/build.rs` mirrors the Zcash wasm SQLite link
-glue; keep them in sync.
diff --git a/chain-runtimes/monero/crates/monero-runtime/build.rs b/chain-runtimes/monero/crates/monero-runtime/build.rs
index 1331c740a..655b863b1 100644
--- a/chain-runtimes/monero/crates/monero-runtime/build.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/build.rs
@@ -1,11 +1,8 @@
 //! Links the wasm SQLite build.
 //!
-//! `rusqlite` is used without `bundled` (wasm32 has no libc sysroot to compile
-//! SQLite's C sources), so libsqlite3-sys emits `-l sqlite3`. On wasm32 the library
-//! comes from `sqlite-wasm-rs` as `libwsqlite3.a`; this script copies it into
-//! OUT_DIR as `libsqlite3.a` and adds that to the search path, so no RUSTFLAGS are needed.
-//!
-//! Duplicate of `chain-runtimes/zcash/crates/zcash-runtime/build.rs`; keep them in sync.
+//! rusqlite is built without `bundled` on wasm32, so libsqlite3-sys emits `-l sqlite3`.
+//! This script copies `sqlite-wasm-rs`'s `libwsqlite3.a` into OUT_DIR as `libsqlite3.a`
+//! and adds it to the search path. Keep in sync with the zcash-runtime build.rs.
 
 use std::path::{Path, PathBuf};
 
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
index efa4903f5..d970bc8af 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -1,21 +1,10 @@
 //! Host-facing wasm interface.
 //!
-//! ## Conventions
-//!
-//! - Every return value is a JSON string for the host to `JSON.parse`. Errors are
-//!   JSON too (`{ code, params, detail }`), so the host needs no separate Error path.
-//! - Amounts are always strings: piconero values exceed JS `Number.MAX_SAFE_INTEGER`,
-//!   and numbers would silently lose precision.
-//! - Key material goes in, never out: the BIP-32 key and the view key may be
-//!   passed in but are never returned. The spend key is reduced from the BIP-32
-//!   key inside each export that needs it, so it never crosses this boundary.
-//! - Secret parameters are owned `String`s wrapped in `Zeroizing`, wiping the
-//!   bindgen allocation itself; a `&str` would leave the input in freed memory.
-//!
-//! ## No scheduling here
-//!
-//! When to scan, how much, and how to back off on failure belong to the host. Each
-//! export is one complete round trip and never loops.
+//! Returns are JSON strings, errors included (`{ code, params, detail }`). Amounts are
+//! strings: piconero values exceed `Number.MAX_SAFE_INTEGER`. Key material goes in, never
+//! out; the spend key is reduced from the BIP-32 key inside each export that needs it, and
+//! secret parameters are `Zeroizing` owned `String`s so the bindgen allocation is wiped.
+//! Scheduling belongs to the host; each export is one round trip and never loops.
 
 use wasm_bindgen::prelude::*;
 
@@ -62,24 +51,19 @@ pub fn close_wallet() -> std::result::Result<(), JsValue> {
     Ok(())
 }
 
-/// Set the node URL; an empty string disables it. No built-in default: one would
-/// decide for the user who sees their IP and queries.
+/// Set the node URL; an empty string disables it. There is no built-in default.
 ///
-/// The old node is dropped before connecting the new one: a replaced or disabled
-/// node must receive no further requests, even if the new one fails to connect.
-/// If calls overlap, the last one wins.
+/// The old node is dropped before connecting the new one, so a replaced node gets no
+/// further requests. If calls overlap, the last one wins.
 #[wasm_bindgen(js_name = setNodeUrl)]
 pub async fn set_node_url(url: &str) -> std::result::Result<(), JsValue> {
     runtime::select_node(url).await?;
     Ok(())
 }
 
-/// Fetch the chain tip. Does not require an open wallet DB: account creation needs
-/// it for the birthday before the DB exists.
+/// Fetch the chain tip. Does not require an open wallet DB (account creation needs the birthday first).
 ///
-/// Returns `{ height, network }`, where `network` is the node's chain (by genesis
-/// block). There is no wallet DB to compare against yet, so the host must check it
-/// matches the wallet being created before setting the birthday.
+/// Returns `{ height, network }`; the host must check `network` matches the wallet being created.
 #[wasm_bindgen(js_name = chainTip)]
 pub async fn chain_tip() -> std::result::Result {
     let tip: u64 = runtime::with_daemon(|daemon| async move {
@@ -151,8 +135,7 @@ pub fn remove_account(uuid: &str) -> std::result::Result {
 
 /// Delete the whole wallet DB file (app reset, storage rebuild). Irreversible.
 ///
-/// Does not open the DB, so unsupported-version or corrupt DBs can still be deleted.
-/// Closes the DB first if it is the one currently open.
+/// Does not open the DB, so unsupported or corrupt DBs can be deleted; closes it first if open.
 #[wasm_bindgen(js_name = deleteWallet)]
 pub async fn delete_wallet(db_name: String) -> std::result::Result {
     if runtime::open_db_name().as_deref() == Some(db_name.as_str()) {
@@ -184,8 +167,6 @@ pub fn update_chain_tip(account_id: i64, tip: u64) -> std::result::Result std::result::Result {
     let progress = runtime::with_db_and_daemon(|mut db, daemon| async move {
@@ -242,12 +223,9 @@ pub fn transaction_details(
 
 /// Import key images so spend detection works.
 ///
-/// Call as early as possible after unlock. Until then the balance is too high: a
-/// view-only wallet cannot detect spends, so spent outputs still look unspent. This
-/// only affects blocks scanned afterwards; earlier spends need a rewind and rescan.
-///
-/// Takes the account's BIP-32 key (as `deriveAccount`); the spend key is reduced
-/// here and wiped after use.
+/// Call as early as possible after unlock: until then the balance is too high, and spends
+/// in earlier blocks need a rewind and rescan. Takes the account's BIP-32 key (as
+/// `deriveAccount`); the spend key is reduced here and wiped after use.
 #[wasm_bindgen(js_name = importKeyImagesWithBip32Key)]
 pub fn import_key_images_with_bip32_key(
     account_id: i64,
@@ -265,11 +243,8 @@ pub fn import_key_images_with_bip32_key(
 
 /// Derive Monero view material and the primary address from a BIP-32-derived private key.
 ///
-/// Pure derivation: no DB, no node, so an address can exist before any scanning.
-///
-/// Matches OneKey V4 (`spend = sc_reduce32(key)`, `view = keccak(spend)`). Changing
-/// it would show existing users an empty wallet after importing the same mnemonic.
-///
+/// Pure derivation (no DB, no node). Matches OneKey V4 (`spend = sc_reduce32(key)`,
+/// `view = keccak(spend)`); changing it would show existing users an empty wallet.
 /// Does not return the spend private key.
 #[wasm_bindgen(js_name = deriveAccount)]
 pub fn derive_account(
@@ -314,11 +289,8 @@ pub fn validate_address(network: &str, address: &str) -> std::result::Result Promise`;
-/// `undefined` uninstalls it.
-///
-/// Lets nodes that in-wasm fetch cannot reach (mixed content, no CORS headers) be
-/// used through the extension background, desktop main process or mobile native code.
+/// `handler` is `(url, contentType, body: Uint8Array) => Promise`; `undefined`
+/// uninstalls it. Reaches nodes that in-wasm fetch cannot (mixed content, no CORS).
 #[wasm_bindgen(js_name = setRequestHandler)]
 pub fn set_request_handler(handler: Option) {
     crate::network::set_host_handler(handler);
@@ -344,8 +316,7 @@ pub fn diag_database() -> std::result::Result {
                 .map_err(|e| crate::error::db_err("diagCount", e))?;
             counts.insert(table.to_owned(), serde_json::json!(n));
         }
-        // Logical size (pages x page size); the backing store's physical footprint
-        // can differ (free pages, storage-layer overhead).
+        // Logical size (pages x page size); the physical footprint can differ.
         let pragma = |name: &str| -> Result {
             db.conn()
                 .query_row(&format!("PRAGMA {name}"), [], |r| r.get(0))
@@ -386,22 +357,15 @@ fn decode_secret_hex(value: &str, field: &str) -> Result>> {
     Ok(out)
 }
 
-// ── Spend path ─────────────────────────────────────────────────────────────
-
 /// Select inputs and build. Needs no spend private key; does not broadcast.
 ///
-/// `recipientsJson` is `[{ "address": "...", "amountAtomic": "1000000000000" }]`.
-///
-/// With `maxSend`, exactly one recipient is accepted and its amount is computed as
-/// spendable total minus fee; the passed amount is ignored. Merely omitting change
-/// would fold the remainder into the fee.
+/// `recipientsJson` is `[{ "address": "...", "amountAtomic": "1000000000000" }]`. With
+/// `maxSend`, exactly one recipient is accepted and its amount is spendable total minus fee.
 ///
 /// Returns `{ signableHex, feeAtomic, amountAtomic, changeAtomic, inputsAtomic,
-/// inputCount }`. `feeAtomic` and `amountAtomic` are what the
-/// transaction will use: the confirmation page shows them and signing keeps them.
-///
-/// Inputs are not reserved: a second prepare before broadcast may select the same
-/// ones, and broadcast then refuses the later transaction as `inputAlreadySpent`.
+/// inputCount }`; the confirmation page shows `feeAtomic`/`amountAtomic` and signing keeps them.
+/// Inputs are not reserved: a later prepare may select the same ones, and broadcast then
+/// refuses the later transaction as `inputAlreadySpent`.
 #[wasm_bindgen(js_name = prepareTransaction)]
 pub async fn prepare_transaction(
     account_id: i64,
@@ -452,10 +416,9 @@ pub async fn prepare_transaction(
 
 /// Sign a prepared transaction. No network, no DB, no broadcast.
 ///
-/// Takes the account's BIP-32 key (as `deriveAccount`); the spend key is reduced
-/// here, and both are wiped after use, never stored or returned.
-/// Returns `{ txid, rawHex, sizeBytes }`; the txid is fixed at signing, so the host
-/// can record the pending transaction before broadcasting.
+/// Takes the account's BIP-32 key (as `deriveAccount`); the spend key is reduced here and
+/// both are wiped after use. Returns `{ txid, rawHex, sizeBytes }`; the txid is fixed at
+/// signing so the host can record the pending transaction before broadcasting.
 #[wasm_bindgen(js_name = signTransactionWithBip32Key)]
 pub fn sign_transaction_with_bip32_key(
     signable_hex: &str,
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs b/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs
index 31f68975c..dff338aef 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs
@@ -1,28 +1,11 @@
 //! Batch block fetch via `get_blocks.bin`, using wallet2's trust model.
 //!
-//! One request returns a whole batch of blocks with their transactions and the
-//! output indices scanning needs, instead of 3-4 round trips per block.
+//! The header's transaction hash list is trusted and content is not re-hashed against it,
+//! because released monerod sends zeroed `prunable_hash` values for pruned transactions.
+//! Transaction counts, output index lists and height contiguity are still checked;
+//! cross-block continuity is checked by `scan::scan_blocks`.
 //!
-//! ## Why not monero-oxide's built-in path
-//!
-//! It also uses `get_blocks.bin` but recomputes transaction hashes from content and
-//! checks them against the block header's hash list. Pruned transactions need the
-//! node's `prunable_hash` for that, and released monerod (through v0.18.5.1) sends
-//! it as all zeros (monero-project/monero#10120; fix #10652 is master-only), so it
-//! always drops the batch and falls back to per-block JSON.
-//!
-//! ## Trust model (same as wallet2)
-//!
-//! The header's transaction hash list is trusted; content is not re-hashed against
-//! it, as in `wallet2::process_new_blockchain_entry` (`b.tx_hashes[idx]`).
-//!
-//! Still checked: transaction count matches the header list, each block's output
-//! index lists match its transaction outputs, and heights are contiguous from the
-//! requested start. Cross-block continuity (previous hash, RingCT cursor) is
-//! checked by `scan::scan_blocks`.
-//!
-//! Request format and parser skeleton follow monero-oxide's `monero-daemon-rpc`
-//! (`src/bin_rpc/blocks_bin.rs`, `epee.rs`, MIT).
+//! Request format and parser skeleton follow monero-oxide's `monero-daemon-rpc` (MIT).
 
 use std::{
     cell::{Cell, RefCell},
@@ -60,13 +43,7 @@ fn epee_err(e: EpeeError) -> BlocksBinError {
     protocol(format!("epee: {e:?}"))
 }
 
-// ── Batch size: adaptive, capped as in wallet2 ─────────────────────────────
-//
-// wallet2 sends `getblocks.bin` uncapped; the node returns at most 1000 blocks /
-// 20k transactions. That is fastest on a good link, but a multi-MB request may never
-// finish on a tunneled or jittery one. So the size adapts: double when fast, up to
-// 1000; halve when slow or failed, down to 10. Each step sends one request and scans
-// and stores what it gets, so a slow later request never discards earlier blocks.
+// Batch size adapts: double when fast up to 1000, halve when slow or failed down to 10.
 
 /// Per-request cap of wallet2 / monerod (`COMMAND_RPC_GET_BLOCKS_FAST_MAX_BLOCK_COUNT`).
 pub const MAX_BATCH_BLOCKS: u64 = 1000;
@@ -103,14 +80,10 @@ fn record_failure() {
     BATCH_BLOCKS.with(|size| size.set((size.get() / 2).max(MIN_BATCH_BLOCKS)));
 }
 
-// ── Requests and pipelining ────────────────────────────────────────────────
-//
-// One request at a time, as in wallet2. Concurrent requests to a public node are
-// served one after another (monerod holds the blockchain DB lock while building
-// `get_blocks.bin`, and nodes may limit per-IP concurrency). The speedup comes from
-// pipelining (`prefetch`): the next batch is in flight while this one is scanned.
+// One request at a time: monerod serializes concurrent `get_blocks.bin` requests.
+// `prefetch` pipelines the next batch while the current one is scanned.
 
-/// A request's result and its duration from send to completion (from send time for a prefetch).
+/// A request's result and its duration from send to completion.
 type RequestOutcome = (Result, BlocksBinError>, f64);
 type RequestFuture = Pin>>;
 
@@ -137,8 +110,7 @@ fn request_future(url: &str, start: u64, count: u64) -> RequestFuture {
     })
 }
 
-/// Take the prefetched result only if it matches this span exactly. Otherwise (node
-/// changed, rewind, range changed) drop it: refetching beats using the wrong data.
+/// Take the prefetched result only if it matches this span exactly; otherwise drop it.
 fn take_prefetched(url: &str, start: u64, count: u64) -> Option {
     PREFETCH.with(|slot| match slot.borrow_mut().take() {
         Some(p) if p.url == url && p.start == start && p.count == count => Some(p.future),
@@ -152,9 +124,7 @@ pub struct Fetched {
     pub prefetch_hit: bool,
 }
 
-/// Backoff (ms) before retrying a network failure; the length is the number of extra
-/// retries. Each retry halves the request, since a smaller one often completes where a
-/// large one cannot. Protocol errors are not retried.
+/// Backoff (ms) before each network-failure retry, each with a halved request. Protocol errors are not retried.
 const RETRY_BACKOFF_MS: [u32; 2] = [500, 1500];
 
 async fn backoff(ms: u32) {
@@ -168,8 +138,7 @@ async fn backoff(ms: u32) {
 /// nonzero: monerod ignores `start_height` when it is zero.
 ///
 /// Sends one request (retried smaller on failure) and accepts however many blocks
-/// the node returns; it may return fewer due to the 20k-transaction cap, and the
-/// next step requests the rest.
+/// the node returns, which may be fewer than asked.
 pub async fn fetch(base_url: &str, start: u64, limit: u64) -> Result {
     if start == 0 {
         return Err(protocol("get_blocks.bin cannot start at the genesis block"));
@@ -212,11 +181,7 @@ pub async fn fetch(base_url: &str, start: u64, limit: u64) -> Result Vec {
     let mut request = Vec::with_capacity(64);
     request.extend(HEADER);
     request.push(VERSION);
-    // Three fields. The low two bits of an epee varint mark its length; 00 means one byte.
+    // Three fields; the low two bits of an epee varint give its length (00 = one byte).
     request.push(3 << 2);
 
     push_key(&mut request, "prune");
@@ -438,7 +403,6 @@ pub(crate) fn parse_response(
                 "expected block {expected}, node sent {height}"
             )));
         }
-        // Check against the header's transaction hash list, which is what we trust.
         if raw.transactions.len() != raw.block.transactions.len() {
             return Err(protocol(format!(
                 "block {height}: header lists {} transactions, node sent {}",
@@ -454,8 +418,7 @@ pub(crate) fn parse_response(
             )));
         }
 
-        // Global index of this block's first RingCT output: the first index of the first
-        // non-V1 transaction with outputs.
+        // First RingCT output index: the first index of the first non-V1 transaction with outputs.
         let miner = raw.block.miner_transaction();
         let mut first_ringct = None;
         let shapes = std::iter::once((
@@ -493,21 +456,17 @@ pub(crate) fn parse_response(
 mod tests {
     use super::*;
 
-    /// Request bytes must match monero-oxide's byte for byte; nodes are known to accept that layout.
     #[test]
     fn the_request_matches_the_upstream_layout() {
         let request = build_request(3_000_000, 50);
         assert_eq!(&request[..8], &HEADER);
         assert_eq!(request[8], VERSION);
         assert_eq!(request[9], 3 << 2);
-        // header(8) + version(1) + count(1)
-        // + prune: 1+5+1+1 + start_height: 1+12+1+8 + max_block_count: 1+15+1+8
         assert_eq!(request.len(), 10 + 8 + 22 + 25);
         assert!(request.windows(5).any(|w| w == b"prune"));
         assert!(request.ends_with(&50u64.to_le_bytes()));
     }
 
-    /// Doubles up to 1000 when fast; halves down to 10 when slow or failed.
     #[test]
     fn the_batch_grows_on_fast_requests_and_shrinks_on_slow_or_failed_ones() {
         BATCH_BLOCKS.with(|b| b.set(INITIAL_BATCH_BLOCKS));
@@ -526,7 +485,6 @@ mod tests {
         BATCH_BLOCKS.with(|b| b.set(INITIAL_BATCH_BLOCKS));
     }
 
-    /// A prefetch is taken only by an exact match; a mismatch discards it and clears the slot.
     #[test]
     fn a_prefetch_is_taken_only_by_the_exact_same_request() {
         let park = |url: &str, start: u64, count: u64| {
@@ -568,8 +526,7 @@ mod tests {
         assert!(matches!(e, BlocksBinError::Protocol(_)));
     }
 
-    /// A real mainnet node response (start_height=3768621, max_block_count=2). Covers
-    /// the full parse: blocks, pruned transactions, output indices, first RingCT index.
+    /// A real mainnet response (start_height=3768621, max_block_count=2).
     #[test]
     fn parses_a_real_node_response() {
         let bytes = include_bytes!("../tests/fixtures/get_blocks_bin_3768621.bin");
@@ -590,14 +547,12 @@ mod tests {
         for (i, b) in blocks.iter().enumerate() {
             assert_eq!(b.block.number() as u64, 3_768_621 + i as u64);
             assert_eq!(b.transactions.len(), b.block.transactions.len());
-            // Every block has miner outputs, so a first RingCT index always exists.
             assert!(b.output_index_for_first_ringct_output.is_some());
         }
-        // Previous hashes chain: the blocks really are contiguous.
         for pair in blocks.windows(2) {
             assert_eq!(pair[1].block.header.previous, pair[0].block.hash());
         }
-        // RingCT cursor chains: next first index = this first index + this block's output count.
+        // Next first index = this first index + this block's output count.
         for pair in blocks.windows(2) {
             let outputs: u64 =
                 std::iter::once(pair[0].block.miner_transaction().prefix().outputs.len())
@@ -618,8 +573,7 @@ mod tests {
         }
     }
 
-    /// Scan cost benchmark (native; release is more accurate). The fixture is too large
-    /// to commit; capture it on demand:
+    /// Scan cost benchmark; the fixture is too large to commit, so capture it on demand:
     /// `XMR_BLOCKS_BIN=/path/to/get_blocks.bin XMR_BLOCKS_BIN_START=3767000 \
     ///  cargo test --release --lib scan_cost -- --nocapture`
     #[test]
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/error.rs b/chain-runtimes/monero/crates/monero-runtime/src/error.rs
index bfb0b3ebc..d7d818f16 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/error.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/error.rs
@@ -11,7 +11,6 @@ use std::fmt;
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
 pub enum ErrorCode {
-    // ── Input validation ────────────────────────────────────────────────────────
     /// Network name is not mainnet/stagenet/testnet. Params: `{ value }`
     InvalidNetwork,
     /// Address does not parse or belongs to another network. Params: `{ field }`
@@ -25,7 +24,6 @@ pub enum ErrorCode {
     /// Malformed JSON from the host. Params: `{ field, reason }`
     InvalidRequest,
 
-    // ── Lifecycle ────────────────────────────────────────────────────────
     /// `openWallet` has not been called.
     WalletNotOpen,
     /// An async operation is in flight; wallet-switching calls are refused. Params: `{ operation }`
@@ -39,21 +37,16 @@ pub enum ErrorCode {
     /// Account not in the database. Params: `{ accountId }`
     AccountNotFound,
 
-    // ── Scanning ────────────────────────────────────────────────────────────
     /// Node blocks do not chain onto local records: a reorg or a lying node.
     /// Params: `{ atHeight, suggestedRewindHeight }`
     ReorgDetected,
-    /// **Node-reported RingCT output index differs from the locally derived one.**
-    ///
-    /// Upstream warns this field is unverifiable and clients must track and
-    /// compare it themselves; a mismatch means the node serves a false view,
-    /// so disconnect rather than keep scanning.
+    /// Node-reported RingCT output index differs from the locally derived one:
+    /// the node serves a false view, so disconnect rather than keep scanning.
     /// Params: `{ height, claimed, expected }`
     RingCtIndexMismatch,
     /// Scanner rejected the block (upstream `ScanError`). Params: `{ height }`
     ScanFailed,
 
-    // ── External ────────────────────────────────────────────────────────
     /// No node URL configured.
     NodeNotConfigured,
     /// Node is on a different network than the wallet (by genesis block), or
@@ -67,7 +60,6 @@ pub enum ErrorCode {
     /// Node explicitly rejected the transaction (double spend, low fee, ...). The fresh record is undone and its inputs released.
     BroadcastRejected,
 
-    // ── Storage ────────────────────────────────────────────────────────────
     /// SQLite operation failed. Params: `{ operation }`
     DatabaseError,
     /// Database migrated by a newer runtime; preserve it and update the app.
@@ -179,8 +171,7 @@ pub fn net_err(operation: &str, e: impl fmt::Display) -> RuntimeError {
 #[cfg(target_arch = "wasm32")]
 impl From for wasm_bindgen::JsValue {
     fn from(e: RuntimeError) -> Self {
-        // A JSON string rather than an Error object: the host always
-        // `JSON.parse`s it to get code/params, with a single code path.
+        // A JSON string, not an Error object: the host always `JSON.parse`s it.
         wasm_bindgen::JsValue::from_str(&e.to_json().to_string())
     }
 }
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/keys.rs b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
index eed9f4b7e..e2d411f2f 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
@@ -1,10 +1,7 @@
 //! View keys and address derivation.
 //!
-//! Holds the public spend key and private view key (monero-oxide `ViewPair`),
-//! everything scanning needs; the Zcash UFVK equivalent.
-//!
-//! The private spend key is never stored or persisted. Signing takes the
-//! account BIP-32 key per call and reduces the spend key internally.
+//! Holds the public spend key and private view key (monero-oxide `ViewPair`).
+//! The private spend key is never stored; signing takes the BIP-32 key per call.
 
 use monero_wallet::{
     address::{MoneroAddress, Network, SubaddressIndex},
@@ -16,8 +13,7 @@ use zeroize::{Zeroize, Zeroizing};
 
 use crate::error::{ErrorCode, Result, RuntimeError};
 
-/// Parses a network name. **No default**: a wrong guess sends funds to a
-/// valid-looking address nobody controls.
+/// Parses a network name. No default: a wrong guess sends funds to an address nobody controls.
 pub fn parse_network(name: &str) -> Result {
     match name {
         "mainnet" | "main" => Ok(Network::Mainnet),
@@ -47,10 +43,7 @@ fn expect_32(bytes: &[u8], field: &str) -> Result<[u8; 32]> {
     })
 }
 
-/// Builds a view pair from raw bytes.
-///
-/// `spend_public` is a compressed ed25519 point, `view_private` a canonical
-/// scalar. Both come from the host.
+/// Builds a view pair from a compressed ed25519 spend point and a canonical view scalar.
 pub fn view_pair_from_bytes(spend_public: &[u8], view_private: &[u8]) -> Result {
     let spend = CompressedPoint::from(expect_32(spend_public, "spendPublicKey")?)
         .decompress()
@@ -69,8 +62,7 @@ pub fn view_pair_from_bytes(spend_public: &[u8], view_private: &[u8]) -> Result<
         )
     })?;
 
-    // Upstream rejects spend keys with torsion (spendability is doubtful).
-    // Pass its reason through unchanged.
+    // Upstream rejects spend keys with torsion.
     ViewPair::new(spend, Zeroizing::new(view)).map_err(|e| {
         RuntimeError::with(
             ErrorCode::InvalidKeyMaterial,
@@ -85,8 +77,7 @@ pub fn primary_address(pair: &ViewPair, network: Network) -> String {
     pair.legacy_address(network).to_string()
 }
 
-/// Subaddress. `(0, 0)` is the primary address; upstream returns `None` and we
-/// reject it too, or the registry would get an entry the scanner never matches.
+/// Subaddress. `(0, 0)` is the primary address and is rejected, or the scanner would never match the entry.
 pub fn subaddress(pair: &ViewPair, network: Network, major: u32, minor: u32) -> Result {
     let index = SubaddressIndex::new(major, minor).ok_or_else(|| {
         RuntimeError::with(
@@ -130,11 +121,9 @@ mod tests {
             assert_eq!(parse_network(name).unwrap(), net);
             assert_eq!(network_name(net), name);
         }
-        // Aliases are accepted
         assert_eq!(parse_network("main").unwrap(), Network::Mainnet);
     }
 
-    /// No default network: a wrong guess sends funds to an unowned address.
     #[test]
     fn unknown_network_is_rejected_not_defaulted() {
         let e = parse_network("").unwrap_err();
@@ -149,8 +138,7 @@ mod tests {
         assert!(!validate_address(Network::Stagenet, MAINNET_ADDR));
     }
 
-    /// `ViewPair` deliberately lacks `Debug` (keeps keys out of logs), so
-    /// `unwrap_err` is unavailable; match explicitly.
+    /// `ViewPair` lacks `Debug`, so `unwrap_err` is unavailable.
     fn expect_key_error(spend: &[u8], view: &[u8]) -> RuntimeError {
         match view_pair_from_bytes(spend, view) {
             Ok(_) => panic!("key material should have been rejected"),
@@ -165,7 +153,6 @@ mod tests {
         assert_eq!(e.params["byteLen"], 31);
     }
 
-    /// An invalid point must be rejected at decompression, not reach scanning.
     #[test]
     fn non_curve_spend_key_is_rejected() {
         let mut not_a_point = [0u8; 32];
@@ -174,8 +161,6 @@ mod tests {
         assert_eq!(e.code, ErrorCode::InvalidKeyMaterial);
     }
 
-    /// (0,0) is the primary address. Registering it as a subaddress would
-    /// create an entry whose incoming funds are never scanned.
     #[test]
     fn subaddress_zero_zero_is_refused() {
         let pair = test_pair();
@@ -185,8 +170,6 @@ mod tests {
         assert!(subaddress(&pair, Network::Mainnet, 1, 0).is_ok());
     }
 
-    /// Subaddresses must differ from the primary and from each other; a
-    /// collision would make accounts share a receiving address.
     #[test]
     fn subaddresses_are_distinct_from_each_other_and_the_primary() {
         let pair = test_pair();
@@ -203,8 +186,7 @@ mod tests {
     }
 
     fn test_pair() -> ViewPair {
-        // Spend key from a known address plus an arbitrary view scalar. They
-        // need not match; this tests derivation and encoding.
+        // The spend key and view scalar need not match; this tests derivation and encoding.
         let addr = MoneroAddress::from_str(Network::Mainnet, MAINNET_ADDR).unwrap();
         let spend = addr.spend().compress().to_bytes();
         let mut view = [0u8; 32];
@@ -216,43 +198,31 @@ mod tests {
     }
 }
 
-// ── Monero keys from BIP-39 / BIP-32 ─────────────────────────────────
-
 /// Derives Monero keys from a 32-byte BIP-32 private key.
 ///
-/// Monero natively uses its own 25-word mnemonic; OneKey uses BIP-39 for all
-/// chains. The common convention, also used by **OneKey V4**, is:
-///
 /// ```text
 /// spend_secret = sc_reduce32(bip32_private_key)
 /// view_secret   = sc_reduce32(keccak256(spend_secret))
 /// ```
 ///
-/// **Do not change it.** V4 uses it (`getKeyPairFromRawPrivatekey` in
-/// `sdkXmr/helper.ts`: `scReduce32` then `hashToScalar`); any other scheme shows
-/// existing users an empty wallet for the same mnemonic.
-///
-/// Returns view material and the primary address. **The spend key is not
-/// returned**: the host already holds the BIP-32 key it passed in.
+/// Do not change it: OneKey V4 users would see an empty wallet for the same mnemonic.
+/// Returns view material and the primary address, never the spend key.
 pub fn derive_from_bip32_key(network: Network, bip32_private_key: &[u8]) -> Result {
     let derived = derive_keys_in_frame(network, bip32_private_key);
     scrub_stack();
     derived
 }
 
-// Separate frame so `scrub_stack` can overwrite it, including the by-value
-// key copies passed to the reductions.
+// Separate frame so `scrub_stack` can overwrite its by-value key copies.
 #[inline(never)]
 fn derive_keys_in_frame(network: Network, bip32_private_key: &[u8]) -> Result {
     use monero_wallet::ed25519::Point;
 
     let raw = secret_32(bip32_private_key, "bip32PrivateKey")?;
 
-    // sc_reduce32: reduce 32 bytes into the scalar field.
     let spend = Zeroizing::new(Scalar::from(
         curve25519_dalek::Scalar::from_bytes_mod_order(*raw),
     ));
-    // hash_to_scalar: keccak256 then reduce; upstream `Scalar::hash`.
     let view = Zeroizing::new(Scalar::hash(<[u8; 32]>::from(*spend)));
 
     let spend_public =
@@ -281,8 +251,7 @@ pub struct DerivedKeys {
 
 /// Spend key scalar for signing; same reduction as [`derive_from_bip32_key`].
 ///
-/// Stays inside the runtime: signing and key-image import take the BIP-32 key
-/// and call this, so the spend key never crosses the wasm boundary.
+/// Stays inside the runtime, so the spend key never crosses the wasm boundary.
 pub fn spend_scalar_from_bip32_key(bip32_private_key: &[u8]) -> Result> {
     let spend = reduce_spend_key_in_frame(bip32_private_key);
     scrub_stack();
@@ -315,14 +284,11 @@ fn secret_32(bytes: &[u8], field: &str) -> Result> {
     Ok(out)
 }
 
-/// Stack overwritten by [`scrub_stack`]; more than the key derivation, key-image
-/// and signing call chains use below their entry frames.
+/// Stack bytes overwritten by [`scrub_stack`].
 const STACK_SCRUB_BYTES: usize = 64 * 1024;
 
-/// Overwrites the stack just below the caller's frame, where the functions it
-/// just returned from kept their secret temporaries (by-value key copies,
-/// reduction intermediates) that `Zeroizing` cannot reach. Best effort: frames
-/// deeper than [`STACK_SCRUB_BYTES`] are not covered.
+/// Overwrites the stack below the caller's frame, wiping secret temporaries that
+/// `Zeroizing` cannot reach. Best effort: deeper frames are not covered.
 #[inline(never)]
 pub(crate) fn scrub_stack() {
     let mut area = [0u8; STACK_SCRUB_BYTES];
@@ -334,8 +300,6 @@ pub(crate) fn scrub_stack() {
 mod derive_tests {
     use super::*;
 
-    /// Derivation is deterministic, and the address prefix is per network
-    /// (mainnet 4 / testnet 9 / stagenet 5).
     #[test]
     fn derivation_is_deterministic_and_network_scoped() {
         let key = [3u8; 32];
@@ -349,7 +313,6 @@ mod derive_tests {
         assert_ne!(t.primary_address, a.primary_address);
     }
 
-    /// Different BIP-32 keys must give different addresses.
     #[test]
     fn different_keys_give_different_addresses() {
         let a = derive_from_bip32_key(Network::Mainnet, &[1u8; 32]).unwrap();
@@ -358,12 +321,7 @@ mod derive_tests {
         assert_ne!(a.view_private_key, b.view_private_key);
     }
 
-    /// **V4 compatibility contract.** Real OneKey V4 vector: the BIP-32 key at
-    /// `m/44'/128'/0'` and the primary address V4 showed (fixture in the app
-    /// repo's `CoreChainSoftware.test.ts`).
-    ///
-    /// Pins `spend = sc_reduce32(bip32_key)`, `view = keccak256(spend)`; any
-    /// change shows V4 users an **empty wallet** for the same mnemonic.
+    /// V4 compatibility: a real V4 vector (`m/44'/128'/0'` key and primary address).
     #[test]
     fn the_v4_derivation_vector_still_produces_the_v4_address() {
         let key = hex::decode("8b28f5749ec99464d5a9d6527125aa8778ea017dd9e5cffaa567d2f62f2c8cbc")
@@ -385,13 +343,10 @@ mod derive_tests {
         assert_eq!(derived.view_private_key, expected);
     }
 
-    /// Pinned reduction outputs (`sc_reduce32`, little-endian mod l), checked
-    /// against an independent big-integer reference. Signing and key-image
-    /// import must reduce exactly as address derivation does.
+    /// Pinned `sc_reduce32` outputs (little-endian mod l), checked against a big-integer reference.
     #[test]
     fn spend_scalar_reduction_is_pinned() {
         for (input, expected) in [
-            // V4 vector (`m/44'/128'/0'`)
             (
                 "8b28f5749ec99464d5a9d6527125aa8778ea017dd9e5cffaa567d2f62f2c8cbc",
                 "5c0d65767c87ca9b9fec3252e06815a277ea017dd9e5cffaa567d2f62f2c8c0c",
@@ -425,9 +380,6 @@ mod derive_tests {
         }
     }
 
-    /// Signing and key-image import reduce exactly as the shipped reduction and
-    /// as address derivation: the reduced key's public point is the address's
-    /// spend key.
     #[test]
     fn spend_scalar_matches_the_reference_and_the_derived_address_for_random_keys() {
         use rand_core::RngCore;
@@ -452,8 +404,7 @@ mod derive_tests {
         }
     }
 
-    /// Reference derivation without stack wiping: wiping must not change a
-    /// single derived byte.
+    /// Reference derivation without stack wiping.
     fn reference_derive(raw: [u8; 32]) -> ([u8; 32], [u8; 32], String) {
         use monero_wallet::ed25519::Point;
         let spend = Scalar::from(curve25519_dalek::Scalar::from_bytes_mod_order(raw));
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/lib.rs b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs
index 27230fc79..59a1a8792 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/lib.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs
@@ -1,18 +1,6 @@
-//! # OneKey Monero Runtime
+//! OneKey Monero runtime: monero-oxide scanning and signing with SQLite persistence.
 //!
-//! monero-oxide provides cryptography, scanning, and transaction construction but
-//! no storage. This crate adds it: scanned outputs are persisted to SQLite and queryable.
-//!
-//! ## Why not monero-ts
-//!
-//! monero-ts keeps the whole wallet in wasm memory and persists by serializing it
-//! all via `getData()`, so saves grow with history and a crash mid-write loses
-//! everything. This crate uses incremental transactional writes, like the Zcash runtime.
-//!
-//! ## Boundary
-//!
-//! Rust owns cryptography and protocol, platform glue (storage VFS, clock), and
-//! conversion to JSON. Scheduling (when and what range to scan) belongs to the host.
+//! Rust owns cryptography, protocol and storage; the host owns scan scheduling.
 
 pub mod blocks_bin;
 pub mod error;
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/network.rs b/chain-runtimes/monero/crates/monero-runtime/src/network.rs
index a74ce0c7c..e33072461 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/network.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/network.rs
@@ -1,17 +1,6 @@
-//! Transport to monerod.
+//! Transport to monerod: implements upstream's `HttpTransport` and only moves bytes.
 //!
-//! Upstream `monero-daemon-rpc` abstracts the network as a trait with one method,
-//! `post(route, body, size_limit) -> Vec`. Binary RPC and epee parsing stay
-//! upstream; this module only moves bytes.
-//!
-//! ## `Send`
-//!
-//! Upstream requires `post` to return `impl Send + Future`, but a browser `fetch`
-//! future is not `Send` (it holds JS values bound to their thread).
-//!
-//! Our wasm32-unknown-unknown build has no atomics or threads and runs in a single
-//! Worker, so `Send` has nothing to violate there. An asserting wrapper is sound on
-//! that target only; see the safety note on [`SingleThreaded`].
+//! A browser `fetch` future is not `Send`; `SingleThreaded` asserts it on wasm32, which is sound only without threads.
 
 use monero_daemon_rpc::{HttpTransport, MoneroDaemon};
 use monero_interface::InterfaceError;
@@ -19,19 +8,13 @@ use serde_json::json;
 
 use crate::error::{net_err, ErrorCode, Result, RuntimeError};
 
-/// Default per-request timeout.
-///
-/// A stall timeout, not a whole-batch deadline: a block stream that keeps progressing survives.
+/// Default per-request timeout; a stall timeout, not a whole-batch deadline.
 pub const DEFAULT_TIMEOUT_MS: u32 = 30_000;
 
-/// Response body cap, so a malicious node cannot exhaust the wasm heap with an
-/// oversized response. 32 MB: a batch in the spam-wall range can reach tens of MB.
+/// Response body cap (32 MB) so a malicious node cannot exhaust the wasm heap.
 pub const MAX_RESPONSE_BYTES: usize = 32 * 1024 * 1024;
 
-/// monerod expects a Content-Type per route.
-///
-/// `/json_rpc` rejects `application/octet-stream`, which surfaces as an unexplained
-/// connect failure. Binary routes end in `.bin`; the rest are JSON.
+/// monerod expects a Content-Type per route: `.bin` routes are binary, the rest JSON.
 fn content_type_for(route: &str) -> &'static str {
     if route.ends_with(".bin") {
         "application/octet-stream"
@@ -44,12 +27,8 @@ fn content_type_for(route: &str) -> &'static str {
 ///
 /// # Safety
 ///
-/// Compiled only for wasm32. This project builds that target without atomics or
-/// threads: the module runs in a single Worker, so no second thread can observe
-/// the future and `Send` constrains nothing.
-///
-/// If this crate ever supports wasm threads (atomics + SharedArrayBuffer), this
-/// wrapper must be removed first; otherwise it is a real data race.
+/// Compiled only for wasm32, built without atomics or threads, so no second thread
+/// can observe the future. Remove this wrapper before ever enabling wasm threads.
 #[cfg(target_arch = "wasm32")]
 struct SingleThreaded(F);
 
@@ -69,11 +48,7 @@ impl core::future::Future for SingleThreaded {
     }
 }
 
-/// Response size check shared by the host channel and in-wasm fetch.
-///
-/// Guards the wasm heap against oversized responses from a malicious node. Neither
-/// path can truncate while streaming, so this runs after receipt, but before the
-/// parser would double the footprint.
+/// Response size check shared by the host channel and in-wasm fetch; runs after receipt, before parsing.
 #[cfg(target_arch = "wasm32")]
 fn cap_response(
     bytes: Vec,
@@ -86,13 +61,8 @@ fn cap_response(
     Ok(bytes)
 }
 
-// Request handler supplied by the host.
-//
-// In-wasm `fetch` is subject to mixed-content blocking (plain-HTTP nodes) and CORS
-// (monerod sends no `Access-Control-Allow-Origin` by default), so few public nodes
-// are reachable from it. The extension background (with `host_permissions`), the
-// Electron main process and React Native native code are not bound by those rules.
-// Without a host handler, requests fall back to in-wasm fetch.
+// Request handler supplied by the host. In-wasm `fetch` is subject to mixed-content
+// blocking and CORS, which the host's own network stack is not.
 #[cfg(target_arch = "wasm32")]
 thread_local! {
     static HOST_HANDLER: std::cell::RefCell> =
@@ -152,10 +122,7 @@ async fn post_via_host(
     Ok(bytes.to_vec())
 }
 
-/// Reduce a JS exception to a readable message.
-///
-/// `JsValue`'s Debug output is useless for diagnosis; `Error.message` is where the
-/// browser puts the real cause (DNS failure, CORS rejection, connection reset).
+/// Reduce a JS exception to its `Error.message`; `JsValue`'s Debug output is not useful.
 #[cfg(target_arch = "wasm32")]
 fn describe_js(value: &wasm_bindgen::JsValue) -> String {
     use wasm_bindgen::JsValue;
@@ -166,12 +133,10 @@ fn describe_js(value: &wasm_bindgen::JsValue) -> String {
         .unwrap_or_else(|| format!("{value:?}"))
 }
 
-/// Per-request cap. A full batch can take over ten seconds on a slow node.
 #[cfg(target_arch = "wasm32")]
 const REQUEST_TIMEOUT_MS: u32 = 45_000;
 
-// The host enforces a per-chunk idle limit. Its backstop must allow a large
-// response to keep progressing on a slow link, matching the Worker relay.
+// Backstop only: the host enforces its own per-chunk idle limit.
 #[cfg(target_arch = "wasm32")]
 const HOST_REQUEST_TIMEOUT_MS: u32 = 10 * 60 * 1000;
 
@@ -190,8 +155,7 @@ impl FetchTransport {
         }
     }
 
-    /// Await one request with a cap. A stuck request holds the wallet DB, so every later
-    /// call gets WALLET_BUSY; on timeout it is abandoned to finish in the background.
+    /// Await one request with a cap; a stuck request holds the wallet DB (later calls get WALLET_BUSY).
     async fn post_inner(
         base_url: String,
         route: String,
@@ -235,8 +199,7 @@ impl FetchTransport {
             return cap_response(bytes, limit);
         }
 
-        // Tag each failure with its stage: a down node, missing CORS, a bad URL and an
-        // unreadable body need different fixes from the user.
+        // Tag each failure with its stage so the cause is identifiable.
         let fail = |stage: &str, detail: String| {
             InterfaceError::InterfaceError(format!("{url}: {stage}: {detail}"))
         };
@@ -268,8 +231,7 @@ impl FetchTransport {
 
         let response = JsFuture::from(promise)
             .await
-            // Usually the network is down or the node sent no CORS headers; the browser
-            // does not say which, so name both.
+            // The browser does not say whether the network is down or CORS headers are missing.
             .map_err(|e| {
                 fail(
                     "await response",
@@ -316,7 +278,7 @@ impl HttpTransport for FetchTransport {
     }
 }
 
-/// Native transport for local tests and diagnostics; reproduces browser issues under a debugger.
+/// Native transport for local tests and diagnostics.
 #[cfg(not(target_arch = "wasm32"))]
 #[derive(Clone, Debug)]
 pub struct NativeTransport {
@@ -333,8 +295,7 @@ impl NativeTransport {
                 let builder = reqwest::Client::builder().timeout(std::time::Duration::from_millis(
                     u64::from(DEFAULT_TIMEOUT_MS),
                 ));
-                // reqwest uses the macOS system proxy by default; curl and Node do not. Set this
-                // to rule out the proxy when a node answers curl instantly but times out here.
+                // reqwest uses the macOS system proxy by default; this rules it out.
                 let builder = if std::env::var_os("XMR_NATIVE_NO_PROXY").is_some() {
                     builder.no_proxy()
                 } else {
@@ -359,7 +320,6 @@ impl HttpTransport for NativeTransport {
         let content_type = content_type_for(route);
         let client = self.client.clone();
         async move {
-            // Keep the real cause: refused, 404, timeout and TLS failure otherwise look identical.
             let response = client
                 .post(&url)
                 .header("Content-Type", content_type)
@@ -367,8 +327,7 @@ impl HttpTransport for NativeTransport {
                 .send()
                 .await
                 .map_err(|e| {
-                    // reqwest's top-level message is just "error sending request"; the cause
-                    // (timeout, TLS, reset, DNS) is in the source chain.
+                    // The cause (timeout, TLS, reset, DNS) is in the source chain.
                     let mut chain = e.to_string();
                     let mut source = std::error::Error::source(&e);
                     while let Some(inner) = source {
@@ -411,8 +370,7 @@ pub type Daemon = MoneroDaemon;
 
 /// Connect to a monerod node and return it with the network its genesis block identifies.
 ///
-/// The host supplies the URL; there is no built-in default. A default would decide for
-/// the user who sees their IP and queries, a privacy choice the runtime must not make.
+/// The host supplies the URL; there is no built-in default node, which would be a privacy choice for the user.
 pub async fn connect(base_url: &str) -> Result<(Daemon, monero_wallet::address::Network)> {
     if base_url.trim().is_empty() {
         return Err(RuntimeError::new(ErrorCode::NodeNotConfigured));
@@ -430,11 +388,8 @@ pub async fn connect(base_url: &str) -> Result<(Daemon, monero_wallet::address::
     Ok((daemon, network))
 }
 
-/// Genesis block hash per network.
-///
-/// The same keys derive the same output keys on all three networks: a testnet wallet
-/// on a mainnet node would scan and send real XMR. Address prefixes cannot catch
-/// this; the node's chain must be checked.
+/// Genesis block hash per network. The same keys work on all three networks, so the
+/// node's chain must be checked: a testnet wallet on a mainnet node would spend real XMR.
 const GENESIS_HASHES: [(monero_wallet::address::Network, &str); 3] = [
     (
         monero_wallet::address::Network::Mainnet,
@@ -458,8 +413,7 @@ pub(crate) fn network_for_genesis(hash: &[u8; 32]) -> Option Result {
     use monero_daemon_rpc::prelude::*;
 
@@ -476,8 +430,7 @@ async fn node_network(daemon: &Daemon) -> Result> =
         const { std::cell::RefCell::new(None) };
 }
@@ -510,7 +463,6 @@ mod tests {
         assert_ne!(Network::Mainnet, Network::Stagenet);
     }
 
-    /// No built-in default node: it would decide for the user who sees their IP and queries.
     #[test]
     fn an_empty_node_url_is_refused_not_defaulted() {
         let e = futures_lite::future::block_on(connect("")).unwrap_err();
@@ -519,8 +471,6 @@ mod tests {
         assert_eq!(e.code, ErrorCode::NodeNotConfigured);
     }
 
-    /// The scheme must be explicit: `1.2.3.4:18081` would be treated as a relative path
-    /// and yield a malformed URL that fails far from the cause.
     #[test]
     fn the_node_url_must_carry_a_scheme() {
         for bad in ["1.2.3.4:18081", "node.example.com", "ftp://x"] {
@@ -529,8 +479,6 @@ mod tests {
         }
     }
 
-    /// The route decides Content-Type. The wrong one makes `/json_rpc` reject at
-    /// connect time, far from the cause.
     #[test]
     fn json_and_binary_routes_get_different_content_types() {
         assert_eq!(content_type_for("json_rpc"), "application/json");
@@ -544,7 +492,6 @@ mod tests {
 
     #[test]
     fn response_cap_never_exceeds_the_hard_limit() {
-        // A host value above the hard cap is clamped to it
         let requested = MAX_RESPONSE_BYTES * 4;
         assert_eq!(requested.min(MAX_RESPONSE_BYTES), MAX_RESPONSE_BYTES);
     }
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/perf.rs b/chain-runtimes/monero/crates/monero-runtime/src/perf.rs
index 367d49d22..4fe8c4f3f 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/perf.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/perf.rs
@@ -1,7 +1,4 @@
-//! Timing.
-//!
-//! Fetch and scan time are measured separately: public node RPC round trips can
-//! reach ~490 ms, which would otherwise read as slow decryption.
+//! Timing. Fetch and scan time are measured separately; node round trips can reach ~490 ms.
 
 #[cfg(target_arch = "wasm32")]
 pub fn now_ms() -> f64 {
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/query.rs b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
index aaef699e3..0c6cb3433 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/query.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
@@ -1,7 +1,6 @@
 //! Balance, history and spendable-output queries.
 //!
-//! Paging, height filters and per-subaddress aggregation are indexed SQLite
-//! queries, so long histories are never loaded into memory.
+//! Paging and aggregation run as indexed SQLite queries.
 
 use monero_wallet::address::Network;
 use monero_wallet::WalletOutput;
@@ -11,10 +10,7 @@ use serde_json::{json, Value};
 use crate::error::{db_err, ErrorCode, Result, RuntimeError};
 use crate::wallet::Db;
 
-/// Consensus lock on **all** outputs: 10 confirmations.
-///
-/// Younger outputs cannot be used in a ring; nodes reject them.
-/// `additional_timelock` applies on top of this.
+/// Consensus lock on all outputs: 10 confirmations. `additional_timelock` applies on top.
 pub const COINBASE_AND_STANDARD_LOCK: u64 = 10;
 
 /// `CRYPTONOTE_MAX_BLOCK_NUMBER`: unlock values at or above it are Unix timestamps.
@@ -33,21 +29,17 @@ pub struct Balance {
     pub total_atomic: u128,
     /// Spendable now: past the 10-block lock and any extra timelock.
     pub unlocked_atomic: u128,
-    /// Outputs without a key image that appear in some ring. **May already be
-    /// spent** until the host supplies key images; outputs never seen in a ring
-    /// are certainly unspent and excluded.
+    /// Outputs without a key image that appear in some ring; may already be spent.
     pub unverifiable_atomic: u128,
     /// Change from own unconfirmed sends. Counted in total but locked, as in wallet2.
     pub pending_change_atomic: u128,
-    /// Unspent outputs lacking a key image. If > 0, compute key images before
-    /// sending (selection only uses outputs with one).
+    /// Unspent outputs lacking a key image; selection only uses outputs with one.
     pub outputs_without_key_image: u64,
 }
 
 impl Balance {
     pub fn to_json(&self) -> Value {
-        // Amounts cross the boundary as strings: piconero values exceed JS
-        // Number.MAX_SAFE_INTEGER.
+        // Strings: piconero values exceed JS Number.MAX_SAFE_INTEGER.
         json!({
             "totalAtomic": self.total_atomic.to_string(),
             "unlockedAtomic": self.unlocked_atomic.to_string(),
@@ -96,8 +88,7 @@ pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result) -> Result> = db
         .conn()
         .prepare(
@@ -131,10 +122,8 @@ pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result u64 {
     }
 }
 
-/// "Now" for timestamp locks.
-///
-/// wallet2 uses the node's `get_info.adjusted_time`; this recomputes it from the
-/// identity's latest stored block timestamps. With fewer than 60 stored there is
-/// no chain time (`None`): the local clock is never trusted for an unlock.
+/// "Now" for timestamp locks, recomputed from the latest 60 stored block timestamps.
+/// With fewer stored it is `None`: the local clock is never trusted for an unlock.
 pub fn adjusted_time(db: &Db, identity_id: i64) -> Result> {
     let mut timestamps: Vec = db
         .conn()
@@ -217,10 +203,7 @@ fn daemon_adjusted_time(timestamps: &mut [u64]) -> u64 {
     current_ts.min(median_ts)
 }
 
-/// Spendable output **metadata**, without the deserialized crypto object.
-///
-/// Enough for selection and display; blobs are deserialized only when building
-/// the transaction.
+/// Spendable output metadata; blobs are deserialized only when building the transaction.
 #[derive(Debug, Clone)]
 pub struct SpendableRow {
     pub id: i64,
@@ -231,8 +214,7 @@ pub struct SpendableRow {
 
 /// Currently spendable outputs, largest first (fewer inputs, lower fee).
 ///
-/// Only outputs **with a key image**: without one we cannot tell whether it is
-/// already spent, and the node would reject a double spend.
+/// Only outputs with a key image: without one it may already be spent.
 pub fn spendable_rows(db: &Db, identity_id: i64, chain_tip: u64) -> Result> {
     let now = adjusted_time(db, identity_id)?;
     let network = db.network();
@@ -280,11 +262,8 @@ pub fn spendable_rows(db: &Db, identity_id: i64, chain_tip: u64) -> Result Result {
     let blob: Vec = db
         .conn()
@@ -310,7 +289,6 @@ pub fn load_output(db: &Db, output_id: i64) -> Result {
 
 /// Transaction history, paged, newest height first.
 pub fn history(db: &Db, identity_id: i64, limit: u32, offset: u32) -> Result {
-    // Cap the page size so a huge limit cannot load the whole history.
     let limit = limit.clamp(1, 500);
 
     let mut stmt = db
@@ -444,7 +422,6 @@ mod tests {
     ) -> i64 {
         let ki: Option> = with_key_image.then(|| {
             let mut k = vec![0u8; 32];
-            // Distinct key image per output so uniqueness issues do not mask bugs
             k[0] = (amount % 251) as u8;
             k[1] = (height % 251) as u8;
             k
@@ -469,8 +446,6 @@ mod tests {
 
     const MAIN: Network = Network::Mainnet;
 
-    /// wallet2::is_transfer_unlocked: locked while `height + 10 > current_height`,
-    /// where current_height is the chain length (tip + 1).
     #[test]
     fn the_ten_block_lock_is_enforced() {
         assert!(
@@ -488,8 +463,6 @@ mod tests {
         assert!(is_unlocked(100, 0, 110, None, MAIN));
     }
 
-    /// wallet2::is_tx_spendtime_unlocked: unlocked once
-    /// `current_height - 1 + 1 >= unlock_time`, i.e. tip + 1 >= unlock_time.
     #[test]
     fn additional_block_timelock_is_honoured() {
         assert!(!is_unlocked(100, 200, 150, None, MAIN));
@@ -502,15 +475,12 @@ mod tests {
             "unlocked at wallet2's unlock height"
         );
         assert!(is_unlocked(100, 200, 200, None, MAIN));
-        // Height locks ignore the clock
         assert!(!is_unlocked(100, 200, 198, Some(u64::MAX), MAIN));
-        // The 10-block lock still applies when the height lock is already past
         assert!(!is_unlocked(100, 50, 108, None, MAIN));
         assert!(is_unlocked(100, 50, 109, None, MAIN));
     }
 
-    /// wallet2::is_tx_spendtime_unlocked: `now + leeway >= unlock_time`, with a
-    /// 120 s leeway after the v2 fork and 60 s before it.
+    /// `now + leeway >= unlock_time`, with a 120 s leeway after the v2 fork and 60 s before it.
     #[test]
     fn timestamp_timelocks_unlock_at_the_leeway_boundary() {
         let t = 1_700_000_000;
@@ -550,26 +520,21 @@ mod tests {
             Some(t - 120),
             Network::Testnet
         ));
-        // The 10-block lock still applies to an expired timestamp lock
         assert!(!is_unlocked(h, t, h + 8, Some(t + 1), MAIN));
         assert!(is_unlocked(h, t, h + 9, Some(t + 1), MAIN));
-        // Timestamp boundary is unchanged at wallet2's first unlocked tip
         assert!(!is_unlocked(h, t, h + 9, Some(t - 121), MAIN));
         assert!(is_unlocked(h, t, h + 9, Some(t - 120), MAIN));
-        // Without chain time a timestamp lock stays locked, however old
         assert!(!is_unlocked(h, 500_000_000, h + 10, None, MAIN));
     }
 
     /// Matches monerod's `get_adjusted_time`: min(max ts + 120, median + 3660).
     #[test]
     fn adjusted_time_follows_monerod() {
-        // Regular 120 s blocks: the max-timestamp projection wins
         let mut regular: Vec = (0..60).map(|i| 1_000_000 + i * 120).collect();
         assert_eq!(
             daemon_adjusted_time(&mut regular),
             1_000_000 + 59 * 120 + 120
         );
-        // A far-future outlier is capped by the median projection
         let mut outlier: Vec = (0..60).map(|i| 1_000_000 + i * 120).collect();
         outlier[59] = 9_000_000;
         let median = (1_000_000 + 29 * 120) / 2 + (1_000_000 + 30 * 120) / 2;
@@ -603,7 +568,6 @@ mod tests {
         }
     }
 
-    /// Too few stored blocks for a median: no chain time, and no local clock.
     #[test]
     fn adjusted_time_needs_sixty_stored_blocks() {
         let (db, id) = db_with_identity();
@@ -613,8 +577,6 @@ mod tests {
         assert_eq!(adjusted_time(&db, id).unwrap(), Some(1_000_240));
     }
 
-    /// Fewer than 60 stored blocks: a long-expired timestamp lock stays locked
-    /// in balance and selection, while height locks still unlock.
     #[test]
     fn timestamp_locked_outputs_stay_locked_without_chain_time() {
         let (db, id) = db_with_identity();
@@ -643,7 +605,6 @@ mod tests {
         assert_eq!(spendable_rows(&db, id, 1_100).unwrap().len(), 2);
     }
 
-    /// Balance and selection judge timestamp locks against the chain's adjusted time.
     #[test]
     fn timestamp_locked_outputs_unlock_in_balance_and_selection() {
         let (db, id) = db_with_identity();
@@ -669,7 +630,6 @@ mod tests {
         assert_eq!(spendable_rows(&db, id, 1_100).unwrap().len(), 1);
     }
 
-    /// With an unknown chain tip the unlocked balance must be 0.
     #[test]
     fn unknown_chain_tip_means_nothing_is_spendable() {
         let (db, id) = db_with_identity();
@@ -679,9 +639,6 @@ mod tests {
         assert_eq!(b.unlocked_atomic, 0);
     }
 
-    /// Outputs without a key image seen in a ring **may be spent** and are
-    /// reported separately; never-ringed ones are certainly unspent (spending
-    /// requires a ring).
     #[test]
     fn only_outputs_seen_in_a_ring_are_pending_verification() {
         let (db, id) = db_with_identity();
@@ -705,7 +662,6 @@ mod tests {
         );
     }
 
-    /// Spent outputs drop out of every balance figure.
     #[test]
     fn spent_outputs_leave_the_balance() {
         let (db, id) = db_with_identity();
@@ -717,8 +673,6 @@ mod tests {
         assert_eq!(b.total_atomic, 0);
     }
 
-    /// An unconfirmed own send reports its broadcast time (not "now"), the
-    /// recorded amount, and failure.
     #[test]
     fn a_pending_send_reports_its_broadcast_time_amount_and_failure() {
         let (db, id) = db_with_identity();
@@ -736,7 +690,6 @@ mod tests {
         assert_eq!(item["outgoingAtomic"], "1234");
     }
 
-    /// History page size has a hard cap.
     #[test]
     fn history_limit_is_clamped() {
         let (db, id) = db_with_identity();
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
index 8ae8094c5..42d0f32fa 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
@@ -1,8 +1,7 @@
 //! Session state across calls.
 //!
-//! The wasm side holds no session state except the database connection and
-//! node client, which are too costly to reopen per call (migration checks).
-//! No caches, timers or background tasks: each host call runs to completion.
+//! Holds only the database connection and node client; no caches, timers or
+//! background tasks.
 
 use std::cell::{Cell, RefCell};
 
@@ -24,9 +23,8 @@ thread_local! {
     static BUSY: Cell = const { Cell::new(false) };
     static GENERATION: Cell = const { Cell::new(0) };
 
-    // The node client has its **own** generation. Switching nodes leaves DB
-    // and GENERATION untouched, so without it an in-flight tip fetch would
-    // restore the old node and route all later requests there.
+    // Separate from GENERATION: switching nodes leaves DB untouched, and an in-flight
+    // fetch must not restore the old node.
     static DAEMON_GENERATION: Cell = const { Cell::new(0) };
 }
 
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
index 09b0046ca..3d41d81fb 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
@@ -1,35 +1,11 @@
 //! Scanning: feeds blocks to the monero-oxide `Scanner` and persists results to SQLite.
 //!
-//! ## Bounded steps
-//!
-//! Never loops to full sync. The caller passes a batch and gets one result; the
-//! host decides whether to continue, since a run-to-completion call cannot be
-//! interrupted, report progress, or yield the main thread on web and mobile.
-//!
-//! ## Three checks
-//!
-//! 1. **Block continuity**: `header.previous` must equal the recorded previous
-//!    hash. A mismatch is a reorg (or a lying node), reported as
-//!    `REORG_DETECTED` with the exact height.
-//!
-//! 2. **RingCT output index**: upstream `ScannableBlock` documents that
-//!    `output_index_for_first_ringct_output` cannot be verified and the client
-//!    must track and compare it. The cursor advances by the block's v2 output
-//!    count and the next block is checked against it. A wrong index picks the
-//!    wrong ring members and the transaction is rejected.
-//!
-//! 3. **Increasing heights within a batch**: out-of-order blocks are rejected,
-//!    not sorted, because an out-of-order peer is untrusted.
-//!
-//! ## Spend detection limits
-//!
-//! A view-only wallet cannot tell whether its outputs were spent: that needs
-//! key images, which need the private spend key. This is a protocol property.
-//!
-//! The host fills `outputs.key_image` via [`crate::spend::import_key_images`]
-//! on unlock; scanning matches known key images against transaction inputs.
-//! Outputs without a key image cannot be detected as spent, so the balance may
-//! be overstated; see [`ScanOutcome::outputs_without_key_image`].
+//! Each call scans one bounded batch; the host decides whether to continue. Checks:
+//! block continuity (`header.previous` vs the recorded hash, else `REORG_DETECTED`), the
+//! RingCT output index cursor (upstream cannot verify it; a wrong index picks wrong ring
+//! members), and strictly increasing heights (out-of-order blocks are rejected, not sorted).
+//! Outputs without a key image cannot be detected as spent; see
+//! [`ScanOutcome::outputs_without_key_image`].
 
 use std::collections::{HashMap, HashSet};
 
@@ -46,10 +22,7 @@ use crate::error::{db_err, ErrorCode, Result, RuntimeError};
 use crate::schema::REORG_WINDOW_BLOCKS;
 use crate::wallet::Db;
 
-/// Suggested rewind depth on a detected reorg.
-///
-/// Monero reorgs rarely exceed a few blocks. Too deep forces a long rescan; too
-/// shallow may not pass the fork point. The host should increase it on repeated failures.
+/// Suggested rewind depth on a detected reorg; the host should increase it on repeated failures.
 pub const REORG_REWIND_BLOCKS: u64 = 10;
 
 #[derive(Debug, Default, Clone)]
@@ -99,10 +72,7 @@ impl ScanOutcome {
     }
 }
 
-/// Number of RingCT outputs in the block.
-///
-/// Only v2 transactions produce RingCT outputs; the miner transaction counts
-/// and comes first. Used to derive global output indices independently of the node.
+/// Number of RingCT outputs in the block (v2 transactions only; the miner transaction counts and comes first).
 fn ringct_output_count(block: &ScannableBlock) -> u64 {
     fn count(tx: &Transaction) -> u64 {
         match tx {
@@ -115,15 +85,9 @@ fn ringct_output_count(block: &ScannableBlock) -> u64 {
 
 /// Key images of all inputs in the block, with the txid of their transaction.
 ///
-/// Txids come from `block.block.transactions`, which matches
-/// `block.transactions` one to one and in order (upstream
-/// `expand_to_scannable_block` fetches bodies from that list).
-///
-/// Not `Transaction::hash()`: these are `Pruned` transactions, and a V2 hash
-/// needs the prunable hash that was pruned.
-///
-/// A length mismatch means an inconsistent block and is rejected; misalignment
-/// would attribute spends to the wrong transaction.
+/// Txids come from `block.block.transactions`, which matches `block.transactions` one to one;
+/// `Transaction::hash()` is unavailable on pruned V2 transactions. A length mismatch is
+/// rejected: misalignment would attribute spends to the wrong transaction.
 fn key_images_in(block: &ScannableBlock) -> Result> {
     if block.block.transactions.len() != block.transactions.len() {
         return Err(RuntimeError::with(
@@ -153,9 +117,7 @@ fn key_images_in(block: &ScannableBlock) -> Result> {
     Ok(out)
 }
 
-/// Fee of each transaction in the block, from its RingCT data. Pre-RingCT
-/// (V1) transactions are skipped: no OneKey account predates RingCT.
-///
+/// Fee of each transaction from its RingCT data; pre-RingCT (V1) transactions are skipped.
 /// Length mismatches are reported by `key_images_in`; skip here.
 fn tx_fees_in(block: &ScannableBlock) -> Vec<([u8; 32], u64)> {
     block
@@ -278,18 +240,9 @@ fn ring_matches<'a>(
 
 /// Transaction public keys `(R, additional)` by txid.
 ///
-/// ## Why kept separately
-///
-/// monero-oxide folds the R + output index + subaddress derivation into a
-/// `key_offset` scalar on `WalletOutput` and drops R. Software signing only
-/// needs `spend + key_offset`.
-///
-/// Firmware does not accept `key_offset`; it derives the one-time key and key
-/// image from `real_out_tx_key` itself, since accepting a host-computed offset
-/// would let a malicious host make the device sign with any key.
-///
-/// R is only available at scan time; recovering it later needs a full rescan
-/// or asking the node for the transaction by txid, which leaks interest in it.
+/// monero-oxide folds R into `key_offset` and drops it. Firmware does not accept a
+/// host-computed `key_offset` (a malicious host could make it sign with any key), so R is
+/// kept; recovering it later needs a rescan or a txid query that leaks interest.
 fn tx_public_keys_in(block: &ScannableBlock) -> Vec<([u8; 32], Vec, Option>)> {
     // Length mismatches are reported by `key_images_in`; skip here.
     let mut out = Vec::new();
@@ -307,9 +260,7 @@ fn tx_public_keys_in(block: &ScannableBlock) -> Vec<([u8; 32], Vec, Option Option<(Vec, Option>)> {
     fn flatten(points: &[monero_wallet::ed25519::Point]) -> Vec {
         let mut out = Vec::with_capacity(points.len() * 32);
@@ -422,8 +373,7 @@ pub fn scan_blocks(
                 RuntimeError::with(ErrorCode::ScanFailed, json!({ "height": height }))
                     .detail(format!("{e:?}"))
             })?
-            // Timelocks are evaluated by the query layer against the current
-            // height; dropping locked outputs here would lose them for good.
+            // Timelocks are checked by the query layer; dropping locked outputs here would lose them.
             .ignore_additional_timelock();
 
         if !outputs.is_empty() {
@@ -472,9 +422,8 @@ pub fn scan_blocks(
             spend_fees.extend(tx_fees_in(block));
         }
 
-        // Cursor base: the previous block's cursor, else the node's claimed
-        // start. With neither, stay unknown; falling back to 0 would raise a
-        // false RINGCT_INDEX_MISMATCH on the next block.
+        // Cursor base: the previous block's cursor, else the node's claimed start. Never fall
+        // back to 0: it raises a false RINGCT_INDEX_MISMATCH on the next block.
         let next_ringct = prev
             .and_then(|(_, _, n)| n)
             .or(block.output_index_for_first_ringct_output)
@@ -746,9 +695,8 @@ fn persist(
     tx.commit().map_err(|e| db_err("commitScan", e))
 }
 
-/// Burning bug: the same one-time key in another output. Only one is spendable,
-/// so only the first seen is counted, never overstating the balance. A rescan
-/// of the same output is not a duplicate.
+/// Burning bug: the same one-time key in another output. Only one is spendable, so only
+/// the first seen counts. A rescan of the same output is not a duplicate.
 fn is_burning_duplicate(
     conn: &rusqlite::Connection,
     identity_id: i64,
@@ -1031,12 +979,8 @@ mod tests {
         assert!(tx_public_keys_from_extra(&[]).is_none());
     }
 
-    /// An unknown RingCT cursor is stored as NULL, not 0.
-    ///
-    /// Starting mid-chain at a block without RingCT outputs leaves
-    /// `output_index_for_first_ringct_output` as None. Storing 0 would raise a
-    /// false `RINGCT_INDEX_MISMATCH` against an honest node on the next block;
-    /// NULL skips the check until a real anchor is known.
+    /// An unknown RingCT cursor is stored as NULL, not 0; 0 would raise a false
+    /// `RINGCT_INDEX_MISMATCH` against an honest node on the next block.
     #[test]
     fn an_unknown_ringct_cursor_is_stored_as_null_not_zero() {
         let (db, id) = db_with_identity();
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
index 068a88583..09758807a 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
@@ -1,17 +1,7 @@
 //! Wallet database schema and migrations.
 //!
-//! ## Why hand-written
-//!
-//! monero-oxide provides cryptography and a scanner but no storage; there is
-//! no counterpart to `zcash_client_sqlite`.
-//!
-//! ## Narrower than Zcash
-//!
-//! Monero has a single output type (no sapling/orchard/ironwood pools), no
-//! transparent pool, and before FCMP++ no commitment tree, so no witnesses or
-//! checkpoints. The schema can stay small.
-//!
-//! Writes are incremental and transactional; see the crate docs for why.
+//! Monero has no pools and (before FCMP++) no commitment tree, so no witnesses
+//! or checkpoints. Writes are incremental and transactional.
 
 use rusqlite::Connection;
 
@@ -21,11 +11,7 @@ use crate::error::{db_err, ErrorCode, Result, RuntimeError};
 /// and bump this; before that, V1 is edited in place.
 pub const SCHEMA_VERSION: i64 = 1;
 
-/// Reorg safety window: `blocks` keeps hashes only for this many blocks below the tip.
-///
-/// Real Monero reorgs rarely exceed a few blocks, but a malicious node is not
-/// bound by that. 720 blocks (about a day) covers any realistic reorg without
-/// letting the table grow with chain height.
+/// Reorg safety window: `blocks` keeps hashes only for this many blocks below the tip (about a day).
 pub const REORG_WINDOW_BLOCKS: u64 = 720;
 
 /// Creates the tables. Idempotent: safe to call on every open.
@@ -259,13 +245,8 @@ mod tests {
         conn
     }
 
-    /// Transaction public keys must round-trip byte for byte.
-    ///
-    /// Hardware signing derives the one-time key from these bytes; corruption
-    /// would not error, it would yield an unspendable signed transaction.
-    ///
-    /// Uses `db_with_identity` rather than a separate identity fixture that
-    /// could drift from the table constraints.
+    /// Transaction public keys must round-trip byte for byte: corruption would
+    /// yield an unspendable signed transaction without an error.
     #[test]
     fn transaction_public_keys_round_trip() {
         let (db, identity_id) = crate::wallet::testing::db_with_identity();
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
index 042d9ddf6..896e484bf 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -1,19 +1,9 @@
 //! Spend path: key image import, transaction construction, signing, broadcast.
 //!
-//! ## The private spend key appears only here
-//!
-//! The host passes the account's BIP-32 key per call and the spend key is
-//! reduced from it here; both are zeroized after use, never persisted, and
-//! never returned across the wasm boundary.
-//!
-//! ## Why key images are imported
-//!
-//! A view-only wallet cannot tell whether its outputs were spent: that needs
-//! the key image `(spend key + output offset) × H(output key)`, which requires
-//! the private spend key.
-//!
-//! Scanning records outputs only; spend state is complete once the host calls
-//! [`import_key_images`] on unlock. Until then the balance may be overstated.
+//! The private spend key is reduced from the host-supplied BIP-32 key per call,
+//! zeroized after use, and never persisted or returned across the wasm boundary.
+//! Spend state is complete only after `import_key_images` on unlock; until then the
+//! balance may be overstated.
 
 use std::collections::HashMap;
 
@@ -33,19 +23,12 @@ use crate::keys;
 use crate::query;
 use crate::wallet::Db;
 
-/// Ring size. Current consensus is 16, including the real member.
-///
-/// Hardcoded rather than asked of the node: a smaller value weakens privacy
-/// and may be rejected. It changes with hard forks via our releases.
+/// Ring size, including the real member. Hardcoded: a smaller value weakens privacy.
 pub const RING_LEN: u8 = 16;
 
 /// Computes an output's key image from the private spend key.
 ///
-/// Same formula as upstream `SignableTransaction::sign`:
-/// `key_image = (spend + key_offset) × biased_hash(output_key)`.
-///
-/// Also checks that the key owns the output. A mismatch (wrong account seed)
-/// errors instead of storing a meaningless key image that would never match a spend.
+/// Errors if the key does not own the output (wrong account seed).
 fn key_image_for(output: &WalletOutput, spend: &Zeroizing) -> Result<[u8; 32]> {
     use core::ops::Deref;
 
@@ -73,10 +56,8 @@ fn key_image_for(output: &WalletOutput, spend: &Zeroizing) -> Result<[u8
 
 /// Fills in key images for outputs that lack one, enabling spend detection.
 ///
-/// Earlier spends are confirmed from possible spends recorded while scanning:
-/// if the computed key image appears in one of the output's possible spends,
-/// that is the real spend. Later spends are caught by normal scanning, so the
-/// output's possible spends are then cleared.
+/// A computed image found in the output's possible spends confirms an earlier spend
+/// and clears them; later spends come from normal scanning.
 pub fn import_key_images(
     db: &mut Db,
     identity_id: i64,
@@ -111,8 +92,7 @@ type PendingOutput = (i64, Vec, Vec, i64);
 /// `(output id, key image, txid, index in tx)`.
 type ComputedKeyImage = (i64, [u8; 32], Vec, i64);
 
-// Separate frame so `scrub_stack` can overwrite what the key-image math left
-// on the stack.
+// Separate frame so `scrub_stack` can clear the key-image math's stack.
 #[inline(never)]
 fn compute_key_images(
     pending: Vec,
@@ -128,7 +108,6 @@ fn compute_key_images(
 }
 
 /// Stores computed key images and confirms earlier spends from possible spends.
-/// Separate from computation so the matching can be tested without real outputs.
 fn apply_key_images(
     db: &mut Db,
     identity_id: i64,
@@ -215,24 +194,19 @@ fn parse_spend_key(bytes: &[u8]) -> Result> {
     Ok(Zeroizing::new(scalar))
 }
 
-/// A payment in a pending transaction.
 #[derive(Debug, Clone)]
 pub struct Payment {
     pub address: MoneroAddress,
     pub amount_atomic: u64,
 }
 
-/// Input selection result.
 #[derive(Debug, Clone)]
 pub struct Selection {
     pub output_ids: Vec,
     pub total_atomic: u64,
 }
 
-/// Selects inputs largest first until `needed` is covered.
-///
-/// Fees are by weight, so fewer inputs are cheaper, at the cost of breaking up
-/// large outputs sooner; this matches wallet2's default.
+/// Selects inputs largest first until `needed` is covered; fewer inputs mean a lower fee.
 pub fn select_inputs(
     db: &Db,
     identity_id: i64,
@@ -274,7 +248,6 @@ pub fn select_inputs(
     })
 }
 
-/// A constructed transaction awaiting signature.
 pub struct Prepared {
     pub signable: SignableTransaction,
     pub output_ids: Vec,
@@ -294,9 +267,8 @@ fn is_double_spend(error: &RuntimeError) -> bool {
 
 /// Shares one RingCT output distribution across all inputs of a construction.
 ///
-/// Upstream fetches the full-chain distribution (about 18MB) per decoy
-/// selection, N times for N inputs, which easily times out when relayed through
-/// the host on mobile. Same range is reused, so the node is asked once.
+/// Upstream fetches the full-chain distribution (about 18MB) per input, which times out
+/// easily when relayed through the host on mobile.
 struct CachedDecoys<'a, P> {
     inner: &'a P,
     distributions:
@@ -376,10 +348,8 @@ impl
     }
 }
 
-/// Picks a ring of decoys for one output.
-///
-/// Decoys must be selected at the current height; a stale height skews the
-/// ring distribution into a statistical fingerprint.
+/// Picks a ring of decoys for one output at the current height; a stale height
+/// skews the ring distribution into a fingerprint.
 async fn ring_for(
     db: &Db,
     decoy_source: &impl monero_wallet::interface::ProvidesDecoys,
@@ -400,8 +370,6 @@ async fn ring_for(
 }
 
 /// Rings for a set of outputs, reusing ones already fetched.
-///
-/// Each ring costs a dozen or more network round trips.
 async fn rings_for(
     db: &Db,
     decoy_source: &impl monero_wallet::interface::ProvidesDecoys,
@@ -432,8 +400,7 @@ fn assemble(
 ) -> std::result::Result {
     let change = Change::new(identity.view_pair.clone(), None);
 
-    // `outgoing_view_key` seeds this transaction's deterministic RNG. Never reuse
-    // it across transactions (upstream: reuse repeats ephemeral secrets).
+    // `outgoing_view_key` seeds this transaction's RNG; never reuse it across transactions.
     let mut ovk = Zeroizing::new([0u8; 32]);
     rng.fill_bytes(ovk.as_mut());
 
@@ -455,14 +422,8 @@ fn build_error(e: monero_wallet::send::SendError) -> RuntimeError {
 
 /// Selects inputs and constructs a transaction; no private spend key needed.
 ///
-/// `Prepared` carries the actual fee, which the host shows on the confirm
-/// screen, so the displayed fee is the one charged.
-///
-/// ## Why iterate
-///
-/// The fee depends on weight, weight on input count, and input count on the
-/// fee. The first round covers the amount only; upstream reports the real fee
-/// in `NotEnoughFunds`, and selection repeats with the new target. Converges in two rounds in practice.
+/// `Prepared` carries the actual fee shown on the confirm screen. Fee depends on weight,
+/// weight on input count: selection repeats with the fee upstream reports in `NotEnoughFunds`.
 #[allow(clippy::too_many_arguments)]
 pub async fn prepare(
     db: &Db,
@@ -486,8 +447,7 @@ pub async fn prepare(
     let mut cache: HashMap = HashMap::new();
     let mut needed = out_total;
 
-    // Three rounds: without fee, with the real fee, and once more in case the
-    // added inputs raised the fee. Not converging means insufficient funds.
+    // Three rounds: without fee, with the real fee, and once more if added inputs raised it.
     for _ in 0..3 {
         let selection = select_inputs(db, identity_id, chain_tip, needed)?;
         let inputs = rings_for(
@@ -538,13 +498,10 @@ pub async fn prepare(
     Err(insufficient(0, needed))
 }
 
-/// Sends all currently spendable outputs to one address.
-///
-/// Omitting the change output would, per upstream, add the remainder to the
-/// fee. Instead the real fee is obtained first and the amount derived.
+/// Sends all spendable outputs to one address.
 ///
-/// Amounts do not affect weight (RingCT amounts are fixed-size), so a probe
-/// with 1 piconero gives the fee, then `total - fee` is built with the same weight.
+/// Probes with 1 piconero to get the fee (amounts do not affect weight), then builds
+/// `total - fee`; omitting change would fold the remainder into the fee.
 #[allow(clippy::too_many_arguments)]
 pub async fn prepare_max(
     db: &Db,
@@ -646,9 +603,7 @@ fn insufficient(available: u64, needed: u64) -> RuntimeError {
     )
 }
 
-/// Signs a constructed transaction. No network or database access.
-///
-/// `spend_private` is zeroized after use. Returns broadcastable bytes and the txid.
+/// Signs a constructed transaction. No network or database access; `spend_private` is zeroized after use.
 pub fn sign_prepared(
     signable: SignableTransaction,
     rng: &mut R,
@@ -1354,18 +1309,10 @@ mod tests {
     }
 }
 
-// ── End-to-end send ─────────────────────────────────────────────────────
-
 /// Fee rate cap per priority (piconero / weight).
 ///
-/// Upstream `fee_rate` requires a cap because the rate comes from the node,
-/// which may lie; an absurd rate could spend the balance on fees.
-///
-/// monerod's four tiers are fixed multiples of the base fee, currently 20,000 /
-/// 80,000 / 320,000 / 4,000,000 on mainnet. The base fee derives from block
-/// reward and median block size: busier blocks lower it, and tail emission
-/// fixes the reward. Caps leave 5x headroom over current values. Hitting a cap
-/// fails the send at that tier; it never overpays.
+/// The rate comes from the node, which may lie. Caps leave 5x headroom over current
+/// mainnet tiers (20,000 / 80,000 / 320,000 / 4,000,000); hitting one fails the send.
 pub fn max_fee_per_weight(priority: monero_wallet::interface::FeePriority) -> u64 {
     use monero_wallet::interface::FeePriority;
     match priority {
@@ -1378,14 +1325,12 @@ pub fn max_fee_per_weight(priority: monero_wallet::interface::FeePriority) -> u6
 
 /// Fee quantization mask (piconero).
 ///
-/// A monerod constant (`PER_KB_FEE_QUANTIZATION_DECIMALS = 8`, i.e.
-/// 10^(12-8)), not a price. Upstream rounds the fee up to a multiple of the
-/// node-supplied mask with no cap, so a large mask would multiply the fee;
-/// only this value is accepted.
+/// A monerod constant (`PER_KB_FEE_QUANTIZATION_DECIMALS = 8`), not a price.
+/// Upstream rounds the fee up to a node-supplied mask, so only this value is accepted.
 pub const FEE_QUANTIZATION_MASK: u64 = 10_000;
 
-/// Upstream `FeeRate` does not expose the mask; read it from the serialization
-/// (per_weight then mask, 8 bytes LE each). The layout is pinned by a test.
+/// `FeeRate` does not expose the mask; read from the serialization (per_weight then
+/// mask, 8 bytes LE each), pinned by a test.
 fn fee_mask(rate: &monero_wallet::interface::FeeRate) -> Option {
     let bytes = rate.serialize();
     Some(u64::from_le_bytes(bytes.get(8..16)?.try_into().ok()?))
@@ -1427,25 +1372,15 @@ pub fn parse_priority(name: &str) -> Result(
     }))
 }
 
-// Separate frame so `scrub_stack` can overwrite what signing left on the stack.
+// Separate frame so `scrub_stack` can clear signing's stack.
 #[inline(never)]
 fn verify_and_sign(
     signable_hex: &str,
@@ -1661,14 +1595,11 @@ pub fn reviewed_broadcast_amounts(
     })
 }
 
-/// Pre-broadcast bookkeeping in one transaction: mark inputs spent and record a
-/// pending send.
-///
-/// Returns whether the record is fresh. An existing record means the same
-/// transaction was sent before (a retry), which the node may have accepted.
+/// Pre-broadcast bookkeeping in one transaction: mark inputs spent and record a pending send.
 ///
-/// A fresh record must spend only this account's outputs that no other
-/// transaction spent; otherwise nothing is recorded and nothing is sent.
+/// Returns whether the record is fresh; an existing record means a retry the node may have accepted.
+/// A fresh record must spend only this account's outputs not spent by another transaction;
+/// otherwise nothing is recorded and nothing is sent.
 fn record_broadcast(
     db: &Db,
     identity_id: i64,
@@ -1791,10 +1722,8 @@ fn undo_recorded_broadcast(db: &Db, identity_id: i64, txid: &[u8; 32]) -> Result
 
 /// Records, then broadcasts a signed transaction. Irreversible.
 ///
-/// Recording first marks inputs spent and creates a pending record, so an
-/// interruption (worker killed, response lost) leaves the send visible and its
-/// inputs unselectable. Otherwise the next send could use other inputs and both
-/// would confirm, paying twice.
+/// Recording first keeps an interrupted send visible and its inputs unselectable;
+/// otherwise a later send could use other inputs and both would confirm.
 pub async fn broadcast_signed(
     db: &Db,
     daemon: &crate::network::Daemon,
@@ -1814,7 +1743,6 @@ pub async fn broadcast_signed(
         .map_err(|e| db_err("parseSignedTransaction", e))?;
     let txid = tx.hash();
 
-    // Mark by the transaction's own key images.
     let key_images: Vec<[u8; 32]> = tx
         .prefix()
         .inputs
@@ -1832,13 +1760,9 @@ pub async fn broadcast_signed(
     // inputs selectable again while the transaction is in flight.
     crate::storage::durability_barrier().await?;
 
-    // An explicit rejection means it will not confirm: undo the fresh record
-    // and release the inputs. Other errors are uncertain: keep the record so the
-    // inputs are not reselected; the pending check fails it after the
-    // propagation window if the node never got it.
-    // "double spend" may be this transaction already mined (lost response,
-    // retried signature), so it is uncertain too, as is a rejection of a
-    // non-fresh record, which the node may have accepted earlier.
+    // Only an explicit rejection of a fresh record is undone. Other errors are uncertain:
+    // the record stays so inputs are not reselected. "double spend" may be this
+    // transaction already mined, and a non-fresh record may have been accepted earlier.
     let unknown = match broadcast(daemon, &raw).await {
         Ok(()) => None,
         Err(e) if e.code == ErrorCode::BroadcastRejected && !is_double_spend(&e) && fresh => {
@@ -1891,7 +1815,6 @@ mod cached_decoys_tests {
         }
     }
 
-    // Every input's decoy selection asks for the same range; the node is asked once.
     #[test]
     fn one_distribution_download_per_prepare() {
         let source = CountingSource(AtomicUsize::new(0));
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
index 1d6b0c9bb..fdab4cbba 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
@@ -1,18 +1,13 @@
 //! SQLite storage shared by all platforms.
 //!
-//! The wasm side runs in a dedicated Worker; desktop, web, extension and mobile
-//! WebEmbed all use the same OPFS sync-access VFS, so SQLite reads and writes
-//! pages directly instead of preloading the database into wasm memory.
-//!
-//! The native build is kept for Rust tests and local diagnostics.
+//! wasm runs in a dedicated Worker on the OPFS sync-access VFS; native is for tests and diagnostics.
 
 use rusqlite::Connection;
 use serde_json::json;
 
 use crate::error::{db_err, ErrorCode, Result, RuntimeError};
 
-// Force linking: an unreferenced crate is not linked, which would fail with
-// `undefined symbol: sqlite3_*`.
+// Force linking, or `undefined symbol: sqlite3_*`.
 #[cfg(target_arch = "wasm32")]
 use sqlite_wasm_rs as _;
 
@@ -22,7 +17,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
 #[cfg(target_arch = "wasm32")]
 static VFS_READY: AtomicBool = AtomicBool::new(false);
 
-// Installed pool handle; lets us delete databases that cannot be opened (unknown version, corruption).
+// Pool handle, used to delete databases that cannot be opened.
 #[cfg(target_arch = "wasm32")]
 thread_local! {
     static VFS_UTIL: std::cell::RefCell>> =
@@ -41,20 +36,11 @@ pub fn is_ready() -> bool {
     }
 }
 
-/// Installs the persistent VFS in the browser carrier. Call once before opening
-/// any database.
-///
-/// The pool holds file handles exclusively until its Worker terminates, so two
-/// Workers cannot open the same database; the host must serialize.
-///
-/// A dedicated name instead of the default `.opfs-sahpool` keeps the pool from
-/// sharing a directory and handles with other pools on the same origin (e.g.
-/// Zcash's `.onekey-zcash-opfs`).
+/// Installs the persistent VFS in the browser carrier. Call once before opening any database.
 ///
-/// Worker termination is **asynchronous**: after a carrier reset, reload or hot
-/// update, the old Worker briefly keeps its SAH handles and install fails with
-/// `NoModificationAllowedError`. Only that error is retried, with a bound; a
-/// live second holder still fails, which is correct.
+/// The pool holds file handles exclusively until its Worker terminates, so the host must serialize.
+/// A dedicated pool name avoids sharing a directory with other pools on the same origin.
+/// A just-reset Worker briefly keeps its handles (`NoModificationAllowedError`); only that error is retried, bounded.
 #[cfg(target_arch = "wasm32")]
 pub async fn install_persistent_vfs() -> Result<()> {
     use sqlite_wasm_vfs::sahpool::{install, OpfsSAHError, OpfsSAHPoolCfg};
@@ -72,16 +58,13 @@ pub async fn install_persistent_vfs() -> Result<()> {
     let cfg = OpfsSAHPoolCfg {
         vfs_name: "onekey-xmr-opfs".to_owned(),
         directory: ".onekey-xmr-opfs".to_owned(),
-        // Never true: it wipes the pool on every start, forcing a full rescan.
+        // Never true: it wipes the pool on every start.
         clear_on_init: false,
-        // One database per network, plus rollback journals and spare handles.
         initial_capacity: 4,
     };
 
     let mut retries = 20;
     loop {
-        // `WasmOsCallback` is sqlite-wasm-rs's implementation of the VFS crate's
-        // trait; the type parameter cannot be inferred.
         match install::(&cfg, true).await {
             Ok(util) => {
                 VFS_UTIL.with(|slot| *slot.borrow_mut() = Some(std::rc::Rc::new(util)));
@@ -122,9 +105,7 @@ pub async fn install_persistent_vfs() -> Result<()> {
     }
 }
 
-/// The OPFS API the pool needs, checked before installing it: on an outdated
-/// WebView the install would otherwise throw a bare TypeError from inside the
-/// bindings, which the host cannot tell apart from any other failure.
+/// The OPFS API the pool needs, checked up front so an outdated WebView gives a clear error instead of a bare TypeError.
 #[cfg(target_arch = "wasm32")]
 fn missing_opfs_api() -> Option<&'static str> {
     use wasm_bindgen::JsValue;
@@ -169,8 +150,7 @@ pub async fn install_persistent_vfs() -> Result<()> {
 
 /// Database name must be non-empty with no path separators.
 ///
-/// **Checked on every target**: on wasm the name is an opaque VFS key, but on
-/// native it becomes a file path, where traversal actually matters.
+/// Checked on every target: on native the name becomes a file path.
 fn validate_db_name(db_name: &str) -> Result<()> {
     let bad = db_name.is_empty()
         || db_name.contains('/')
@@ -191,7 +171,6 @@ fn validate_db_name(db_name: &str) -> Result<()> {
 pub fn open_connection(db_name: &str) -> Result {
     if db_name == ":memory:" {
         let conn = Connection::open_in_memory().map_err(|e| db_err("openInMemory", e))?;
-        // Match real databases so cascade-delete tests are meaningful
         conn.execute_batch("PRAGMA foreign_keys = ON;")
             .map_err(|e| db_err("pragmaForeignKeys", e))?;
         return Ok(conn);
@@ -205,13 +184,11 @@ pub fn open_connection(db_name: &str) -> Result {
 
     let conn = Connection::open(db_name).map_err(|e| db_err("open", e))?;
 
-    // Only takes effect before the first table exists, so every database
-    // created from here on can hand freed pages back; see reclaim_free_pages.
+    // Only takes effect before the first table exists; see reclaim_free_pages.
     conn.execute_batch("PRAGMA auto_vacuum = INCREMENTAL;")
         .map_err(|e| db_err("pragmaAutoVacuum", e))?;
 
-    // Foreign keys are off by default; without them identity cascades fail and
-    // deleting a wallet leaves readable orphan rows.
+    // Off by default; without it deleting a wallet leaves readable orphan rows.
     conn.execute_batch("PRAGMA foreign_keys = ON;")
         .map_err(|e| db_err("pragmaForeignKeys", e))?;
     // Zero deleted rows (view keys, receipts) instead of leaving them in free pages.
@@ -220,8 +197,7 @@ pub fn open_connection(db_name: &str) -> Result {
 
     #[cfg(target_arch = "wasm32")]
     {
-        // SAH pool uses a rollback journal, no cross-context WAL.
-        // **Never weaken durability for scan throughput.**
+        // SAH pool uses a rollback journal, no cross-context WAL. Never weaken durability for scan throughput.
         conn.execute_batch("PRAGMA journal_mode = DELETE; PRAGMA synchronous = FULL;")
             .map_err(|e| db_err("pragmaDurability", e))?;
     }
@@ -231,7 +207,6 @@ pub fn open_connection(db_name: &str) -> Result {
 
 /// Free pages below which a reclaim is not worth its write transaction.
 const RECLAIM_MIN_FREE_PAGES: i64 = 256;
-/// Per sync step: small enough never to hold the step up noticeably.
 pub const RECLAIM_PAGES_PER_STEP: u32 = 512;
 /// After removing or rewinding an identity; later steps take the rest.
 pub const RECLAIM_PAGES_AFTER_DELETE: u32 = 4096;
@@ -244,7 +219,6 @@ pub fn reclaim_free_pages(conn: &Connection, max_pages: u32) -> Result {
         conn.query_row(sql, [], |r| r.get(0))
             .map_err(|e| db_err("reclaimFreePages", e))
     };
-    // 2 = INCREMENTAL.
     if read("PRAGMA auto_vacuum")? != 2 {
         return Ok(0);
     }
@@ -266,7 +240,7 @@ pub fn reclaim_free_pages(conn: &Connection, max_pages: u32) -> Result {
     Ok(u32::try_from(before - after).unwrap_or(0))
 }
 
-/// Deletes a closed database **without opening it**, so unopenable ones can be deleted.
+/// Deletes a closed database without opening it, so unopenable ones can be deleted.
 /// Returns `true` if deleted, `false` if it did not exist.
 #[cfg(target_arch = "wasm32")]
 pub async fn delete_database(db_name: &str) -> Result {
@@ -300,10 +274,8 @@ pub async fn delete_database(db_name: &str) -> Result {
 /// Durability barrier: fails if committed transactions may not have reached
 /// durable storage.
 ///
-/// SQLite commits synchronously through the VFS, so commit errors already
-/// surface from the statement. This catches the rest: a metadata I/O failure
-/// (e.g. deleting the rollback journal) poisons the patched pool, and nothing
-/// written since can be trusted until the Worker restarts.
+/// Commit errors already surface from the statement; this catches a metadata I/O failure
+/// that poisons the pool, after which nothing written can be trusted until the Worker restarts.
 pub async fn durability_barrier() -> Result<()> {
     if requires_worker_restart() {
         return Err(RuntimeError::with(
@@ -341,7 +313,6 @@ mod tests {
             .unwrap()
     }
 
-    // A rewind or removal frees pages that only a reclaim gives back.
     #[test]
     fn reclaims_freed_pages_in_bounded_batches() {
         let name = format!("xmr-reclaim-test-{}.db", std::process::id());
@@ -366,7 +337,6 @@ mod tests {
         let _ = std::fs::remove_file(&name);
     }
 
-    // Deletion does not open the file, so even a non-SQLite file is deleted.
     #[test]
     fn deletes_a_database_it_cannot_open() {
         let name = format!("xmr-delete-test-{}.db", std::process::id());
@@ -376,8 +346,6 @@ mod tests {
         assert!(!delete().unwrap());
     }
 
-    // Native storage has no pool to poison, so the restart signal stays clear
-    // and the barrier passes.
     #[test]
     fn healthy_storage_needs_no_worker_restart() {
         assert!(!requires_worker_restart());
@@ -389,8 +357,6 @@ mod tests {
         assert!(open_connection(":memory:").is_ok());
     }
 
-    /// Path traversal is dangerous on **native** (the name becomes a file
-    /// path), so the check must not be wasm-only.
     #[test]
     fn path_separators_are_rejected_on_every_target() {
         for bad in ["", "a/b", "a\\b", "../escape", "x/../y"] {
@@ -402,7 +368,7 @@ mod tests {
     #[test]
     fn foreign_keys_are_on() {
         let conn = open_connection(":memory:").unwrap();
-        // The in-memory branch is special; set it explicitly to verify the pragma itself
+        // The in-memory branch is special; set it explicitly to verify the pragma.
         conn.execute_batch("PRAGMA foreign_keys = ON;").unwrap();
         let on: i64 = conn
             .query_row("PRAGMA foreign_keys", [], |r| r.get(0))
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
index 6901a4982..43812a94b 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
@@ -1,14 +1,8 @@
 //! Sync orchestration: fetch blocks, scan, record progress. Bounded; never runs to completion.
 //!
-//! One call processes at most `max_blocks` blocks and returns progress; the host
-//! decides whether to call again. A run-to-completion call cannot be interrupted,
-//! report progress, or yield on browsers and mobile, so the page would freeze.
-//!
-//! ## Scan progress is tracked per identity
-//!
-//! `scan_ranges` is keyed by `identity_id`. Unlike Zcash, Monero has no commitment
-//! tree that forces wallet-wide contiguous scanning, so each identity tracks its
-//! own progress and a paused account never loses a span scanned for another.
+//! One call processes at most `max_blocks` blocks; the host decides whether to continue.
+//! `scan_ranges` is keyed by `identity_id` (no wallet-wide contiguity as in Zcash), so a
+//! paused account never loses a span scanned for another.
 
 use futures_util::stream::{self, StreamExt, TryStreamExt};
 use monero_daemon_rpc::prelude::*;
@@ -21,18 +15,14 @@ use crate::perf::now_ms;
 use crate::scan::{self, ScanOutcome};
 use crate::wallet::Db;
 
-/// Per-call block cap.
-///
-/// A hang guard, not a tuning knob: a huge value would make one call run for
-/// minutes with no way to interrupt it. The host sizes batches from measured throughput.
+/// Per-call block cap: a hang guard; a huge value would run for minutes uninterruptibly.
 pub const MAX_BLOCKS_PER_CALL: u64 = 1_000;
 
 /// Limit per-block fallback requests to three, leaving the host's fourth
 /// stream slot available for a chain-tip probe or another privacy chain.
 pub const FETCH_CONCURRENCY: usize = 3;
 
-/// Fetch the chain tip without touching the wallet DB: account creation needs it
-/// for the birthday before the DB exists.
+/// Fetch the chain tip without touching the wallet DB (account creation needs it first).
 pub async fn chain_tip(daemon: &Daemon) -> Result {
     let n = daemon
         .latest_block_number()
@@ -68,9 +58,8 @@ pub fn update_chain_tip(db: &mut Db, identity_id: i64, tip: u64) -> Result<()> {
 
 /// Highest height this identity has scanned contiguously (inclusive); `None` if nothing scanned.
 ///
-/// Reads `identities.scanned_to_height`, not `max` over the global `blocks` table:
-/// that would let a caught-up identity push a backfilling identity's progress to
-/// the tip, permanently skipping that history.
+/// Reads `identities.scanned_to_height`, not `max` over the global `blocks` table, which
+/// would let a caught-up identity skip a backfilling identity's history.
 pub fn scanned_to_height(db: &Db, identity_id: i64) -> Result> {
     Ok(db
         .conn()
@@ -113,10 +102,9 @@ fn next_range(db: &Db, identity_id: i64) -> Result> {
 
 /// Remove the scanned span `[start, scanned_through]` from the pending ranges.
 ///
-/// Pending ranges can overlap (`rewind_and_requeue` queues from the rewind height
-/// while the old tail range is still queued), so the span is subtracted from every
-/// overlapping range and remainders are upserted (same start keeps the farther end);
-/// a plain INSERT would collide on the primary key and stall scanning.
+/// Ranges can overlap (`rewind_and_requeue` queues while the old tail is still queued), so
+/// the span is subtracted from every overlapping range and remainders are upserted; a plain
+/// INSERT would collide on the primary key and stall scanning.
 fn consume_range(db: &mut Db, identity_id: i64, start: u64, scanned_through: u64) -> Result<()> {
     let tx = db
         .conn_mut()
@@ -189,12 +177,11 @@ fn blocks_bin_skipped_for(node: Option<&str>, now: f64) -> bool {
     })
 }
 
-/// Try the batch path (`get_blocks.bin`, one round trip per batch) first; fall back
-/// to concurrent per-block fetches if the node does not cooperate.
+/// Try the batch path (`get_blocks.bin`, one round trip per batch) first; fall back to
+/// concurrent per-block fetches.
 ///
-/// Only protocol failures (unsupported, malformed, count mismatch) skip the batch
-/// path for this node (see `BLOCKS_BIN_RETRY_AFTER_MS`). Network failures propagate
-/// and the next step retries; one timeout must not downgrade a good node.
+/// Only protocol failures (unsupported, malformed, count mismatch) skip the batch path for
+/// this node (see `BLOCKS_BIN_RETRY_AFTER_MS`); network failures propagate and are retried.
 async fn fetch_blocks(
     daemon: &Daemon,
     start: u64,
@@ -237,15 +224,9 @@ async fn fetch_blocks(
 
 /// Fetch scannable blocks for `[start, last]`, ordered by height.
 ///
-/// Fallback when the batch path (`blocks_bin`) is unusable.
-///
-/// Does not use `contiguous_scannable_blocks`; see `blocks_bin` for why its batch
-/// path always fails against released monerod.
-///
-/// Instead fetch per block with N-way concurrency. Upstream still validates each
-/// block (number, transactions match the block's tx list); cross-block continuity
-/// (heights, previous hash, RingCT cursor) is checked by `scan::scan_blocks`.
-/// `buffered` preserves order, so results are sorted by height.
+/// Fallback when the batch path (`blocks_bin`) is unusable: fetches per block with N-way
+/// concurrency. Upstream validates each block; cross-block continuity is checked by
+/// `scan::scan_blocks`. `buffered` preserves order.
 async fn fetch_scannable_blocks(
     daemon: &Daemon,
     start: u64,
@@ -263,10 +244,7 @@ async fn fetch_scannable_blocks(
         .await
 }
 
-/// One bounded step.
-///
-/// Returns progress JSON; `done` means no pending ranges remain. Never loops to
-/// completion; the host decides whether to call again.
+/// One bounded step; returns progress JSON, `done` means no pending ranges remain.
 pub async fn step(
     db: &mut Db,
     daemon: &Daemon,
@@ -297,8 +275,7 @@ pub async fn step(
         return Ok(progress(db, identity_id, &ScanOutcome::default(), true)?);
     }
 
-    // Time download and scan separately: both look the same in a browser (a frozen
-    // UI), and public-node latency would otherwise be misread as CPU cost.
+    // Time download and scan separately so node latency is not misread as CPU cost.
     let t0 = now_ms();
 
     let (blocks, fetched_via, fetch_note, prefetch_hit) = fetch_blocks(daemon, start, last).await?;
@@ -317,8 +294,7 @@ pub async fn step(
     let t_downloaded = now_ms();
 
     if blocks.is_empty() {
-        // Zero blocks for a non-empty range violates the protocol. Advancing as if
-        // scanned would skip this span forever.
+        // Zero blocks for a non-empty range violates the protocol; advancing would skip it forever.
         return Err(RuntimeError::with(
             ErrorCode::MalformedNodeResponse,
             json!({ "operation": "contiguousScannableBlocks", "from": start, "to": last }),
@@ -327,9 +303,8 @@ pub async fn step(
 
     db.ensure_subaddress_lookahead(identity_id)?;
     let mut outcome = scan::scan_blocks(db, identity_id, &blocks)?;
-    // Funds near the end of the subaddress window grow it; rescan the same batch with
-    // the new window (blocks in hand, writes idempotent) so later funds to the newly
-    // registered subaddresses are not missed.
+    // Funds near the end of the subaddress window grow it; rescan the same batch with the new
+    // window (writes are idempotent) so funds to newly registered subaddresses are not missed.
     while outcome.outputs_found > 0 && db.ensure_subaddress_lookahead(identity_id)? > 0 {
         outcome = scan::scan_blocks(db, identity_id, &blocks)?;
     }
@@ -642,8 +617,7 @@ mod tests {
         assert!(next_range(&db, id).unwrap().is_none());
     }
 
-    /// The per-call block cap is hard: a huge value would run for minutes with no
-    /// way to interrupt it, freezing the page.
+    /// The per-call block cap is hard: a huge value would freeze the page.
     #[test]
     fn max_blocks_is_clamped_and_zero_is_rejected() {
         assert_eq!(u64::MAX.min(MAX_BLOCKS_PER_CALL), MAX_BLOCKS_PER_CALL);
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs
index 652e60001..79e1abcd8 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs
@@ -1,12 +1,7 @@
 //! Wallet database handle and identity management.
 //!
-//! One identity = one view key pair = one host account. Identities **share** a
-//! SQLite file, each with its own scan progress.
-//!
-//! Unlike Zcash, whose scan queue is database-wide (the commitment tree needs
-//! contiguous scanning), Monero has no commitment tree, so **scan progress is
-//! per identity** (`scan_ranges.identity_id`) and a paused account never misses
-//! ranges scanned for another.
+//! One identity = one view key pair = one host account. Identities share a
+//! SQLite file; scan progress is per identity (`scan_ranges.identity_id`).
 
 use monero_wallet::{address::Network, ViewPair};
 use rusqlite::{params, Connection, OptionalExtension};
diff --git a/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs
index 838d0b2c9..367074f35 100644
--- a/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs
@@ -9,10 +9,6 @@
 //! XMR_SPEND_PUB=<64 hex chars> XMR_VIEW_PRIV=<64 hex chars> XMR_BIRTHDAY=3000000 \
 //!   cargo test --test live_node -- --nocapture
 //! ```
-//!
-//! Unit tests use synthetic data; these exercise the scan loop checks and
-//! RingCT index derivation on the real chain, where bugs show up as missing
-//! funds or spurious reorgs rather than compile errors.
 
 use onekey_monero_runtime::{keys, network, scan, sync, wallet};
 
@@ -55,15 +51,8 @@ fn connects_and_reads_the_chain_tip() {
     });
 }
 
-/// **The key live test.** Scans a short range of real blocks and checks:
-///
-/// - blocks download and upstream accepts them as `ScannableBlock`
-/// - continuity checks raise no false reorgs on a valid chain
-/// - our independently derived RingCT cursor matches the node's claim
-///
-/// Upstream says the last field is unverifiable and clients must compute and
-/// compare it. A `RINGCT_INDEX_MISMATCH` here means **our** derivation is
-/// wrong, not a malicious node.
+/// Scans a short range of real blocks: no false reorgs, and the derived RingCT
+/// cursor matches the node's claim (a mismatch here means our derivation is wrong).
 #[test]
 fn scans_real_blocks_without_false_alarms() {
     let Some(url) = node() else {
diff --git a/chain-runtimes/monero/rust-toolchain.toml b/chain-runtimes/monero/rust-toolchain.toml
index f7fb285f3..3dca7acbe 100644
--- a/chain-runtimes/monero/rust-toolchain.toml
+++ b/chain-runtimes/monero/rust-toolchain.toml
@@ -1,5 +1,4 @@
-# Same toolchain as the Zcash runtime, so one install builds both. Pinned for
-# reproducible wasm; this is not the MSRV (`rust-version` in Cargo.toml).
+# Pinned for reproducible wasm, same as the Zcash runtime; not the MSRV.
 [toolchain]
 channel = "1.93.0"
 profile = "minimal"
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index df8db6e37..0ecbed1df 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -12,12 +12,8 @@ edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
 
-# ── Zcash dependencies: official stable releases ─────────────────────────
-#
-# The storage layer uses unmodified crates.io releases. The only change is a
-# Cargo.toml edit to zcash_client_sqlite (scripts/vendor-deps.sh, patches/) that
-# drops rusqlite's "bundled" feature, which needs a libc sysroot wasm32 lacks.
-# No Zcash Rust source is modified. All patches: patches/manifest.json.
+# Unmodified crates.io releases, except zcash_client_sqlite's Cargo.toml drops rusqlite "bundled"
+# (needs a libc sysroot wasm32 lacks). See patches/manifest.json.
 [workspace.dependencies]
 blake2b_simd = "1"
 zcash_client_backend = { version = "0.24.0", default-features = false, features = ["orchard", "transparent-inputs", "lightwalletd-tonic", "sync", "pczt"] }
@@ -25,13 +21,12 @@ zcash_client_backend = { version = "0.24.0", default-features = false, features
 zcash_client_sqlite = { version = "0.22.0", default-features = false, features = ["orchard", "transparent-inputs", "serde"] }
 zcash_keys = { version = "0.16.1", features = ["orchard", "sapling", "transparent-inputs"] }
 zcash_protocol = "0.10"
-# default-features = false is required: the default multicore feature makes
-# halo2_proofs compile_error on wasm32 without atomics.
+# default-features = false: multicore makes halo2_proofs compile_error on wasm32 without atomics.
 zcash_primitives = { version = "0.30", default-features = false }
 transparent = { package = "zcash_transparent", version = "0.10" }
 zcash_address = "0.13"
 zip321 = "0.9.0"
-# Same as zcash_client_backend: default features off. They pull the yanked core2 0.3.
+# Default features pull the yanked core2 0.3.
 pczt = { version = "0.9.3", default-features = false }
 orchard = { version = "0.15", default-features = false }
 
@@ -45,8 +40,7 @@ js-sys = "0.3"
 gloo-timers = { version = "0.3", features = ["futures"] }
 tracing = "0.1"
 
-# Must match zcash_client_sqlite's rand_core major (0.6), or RngCore does not
-# unify and init_wallet_db's bounds fail.
+# Must match zcash_client_sqlite's rand_core major (0.6) so RngCore unifies.
 rand = "0.8"
 rand_chacha = "0.3"
 serde = { version = "1", features = ["derive"] }
@@ -59,26 +53,22 @@ schemerz-rusqlite = "0.370"
 futures-util = { version = "0.3", default-features = false }
 sapling = { package = "sapling-crypto", version = "0.7", default-features = false }
 
-# lightwalletd uses gRPC-web; browsers cannot speak native gRPC.
-# tonic-web-wasm-client must be >= 0.9.1: 0.8.0 drops gRPC trailers.
+# tonic-web-wasm-client >= 0.9.1: 0.8.0 drops gRPC trailers.
 hex = "0.4"
 prost = "0.14"
 tonic = { version = "0.14", default-features = false, features = ["codegen"] }
 tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] }
 tonic-web-wasm-client = "0.9.1"
 
-# Upstream releases plus the patches in patches/manifest.json.
 # Run `bash scripts/vendor-deps.sh` first to create vendor/.
 [patch.crates-io]
 zcash_client_sqlite = { path = "vendor/zcash_client_sqlite-0.22.0" }
 tonic-web-wasm-client = { path = "vendor/tonic-web-wasm-client-0.9.1" }
 
 [profile.release]
-# opt-level = 3 is no faster on mainnet scans but makes the wasm ~30% larger.
+# opt-level 3 is no faster but ~30% larger.
 opt-level = "s"
 lto = true
 codegen-units = 1
-# Do not use panic = "abort": on wasm it kills the instance silently and the
-# caller sees a Promise that never settles. unwind surfaces as a JS exception
-# with a message that the host can catch and report.
+# Not "abort": on wasm it kills the instance silently and the caller's Promise never settles.
 panic = "unwind"
diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md
index 76a36af8d..066f25857 100644
--- a/chain-runtimes/zcash/README.md
+++ b/chain-runtimes/zcash/README.md
@@ -29,185 +29,67 @@ cargo test --workspace --locked
 bash scripts/vendor-deps.sh --offline   # verify vendor against recorded upstream + patches
 ```
 
-`pkg/` and `pkg-keys/` are build outputs and are not committed. Publishing is in
-[RELEASING.md](./RELEASING.md).
-
-## Design rules
-
-1. **No forked Zcash storage.** `zcash_client_sqlite` is used unmodified except for
-   one Cargo.toml feature (see Pitfalls).
-2. **No seed or mnemonic enters any wasm.** The host passes only account-scoped keys
-   (Orchard `m/32'/133'/account'`, transparent `m/44'/133'/account'`), only for a
-   derive or sign call. The scanner holds the UFVK, never a spending key.
-3. **Plain data across the boundary.** Strings, numbers, booleans, bytes and JSON
-   strings only; no Rust object handles reach JS.
-4. **Rust owns key security, large data and consensus correctness;** the host owns
-   scheduling, accounts, persistence policy, retries and display.
-5. **A rescan follows the new birthday.** An earlier start lowers the stored
-   birthday and keeps what is known; a later start deletes the account and imports
-   it again at that height, so nothing found before it remains. A later start
-   waits (`WALLET_BUSY`, reason `pendingSend`) while the account has an unmined send.
+`pkg/` and `pkg-keys/` are build outputs and are not committed.
+
+## Release
+
+Zcash versions are independent of the native modules' release train. Both packages
+share the version in `Cargo.toml`. Run the **publish-runtime-packages** workflow
+manually. It builds, tests and publishes each package whose version is not on npm
+yet: prereleases to `next`, releases to `latest`. Branches other than `main` can
+publish alpha versions only. `python3 scripts/package-release.py pack --version 
+--tag  --revision ` packs locally without publishing. The App
+pins the exact version.
 
 ## API
 
 Failures throw an `Error` with a stable `code`, structured `params`, and a log-only
-`detail`. Rust produces no user-facing text. `capabilities()` / `keysCapabilities()`
-report what the build supports.
+`detail`. `capabilities()` / `keysCapabilities()` report what the build supports.
 
 ### `onekey-zcash-runtime`
 
 ```
-init()                                   install storage; idempotent; call first
-storageRequiresWorkerRestart()           true after a VFS failure
-setRequestHandler(handler)               host fetch for lightwalletd
-openWallet(network, dbName) / closeWallet()
-setLightwalletdUrl(baseUrl)
+init() / storageRequiresWorkerRestart()
+setRequestHandler(handler) / setLightwalletdUrl(baseUrl)
+openWallet(network, dbName) / closeWallet() / deleteWallet(dbName)
 chainTip() / chainTipAt(baseUrl)
 
 importAccountUfvk(name, ufvk, birthday, seedFingerprintHex?, accountIndex?)
-                                         → UUID; the server's tree state must be
-                                         exactly the block before birthday
-removeAccount(uuid)                     pending transactions do not block removal
-rescanAccount(uuid, fromHeight)          earlier: rewind and keep; later: start over there
-                                         (new UUID; look the account up by UFVK)
+removeAccount(uuid) / rescanAccount(uuid, fromHeight)
 accountByUfvk(ufvk) / listAccounts() / accountSyncStatus(uuid)
 accountBalance(uuid, trusted, untrusted, allowZeroConfShielding)
-                                         per pool: spendable, pendingChange,
-                                         pendingSpendable, locked, total,
-                                         uneconomic; total leaves out notes
-                                         worth <= the ZIP-317 marginal fee,
-                                         which are uneconomic instead
-
-syncPrepare() / syncTip() / syncPeek()   prepare (subtree roots + tip), read-only progress
-                                         syncPeek/accountSyncStatus include nullable
-                                         chainTip and fullyScannedHeight without
-                                         computing wallet balances
+
+syncPrepare() / syncTip() / syncPeek()
 syncStep(batchSize, maxBatches, priority, activeUfvksJson)
-                                         bounded step, only for UFVKs the host enabled
-queueRescanFrom(fromHeight)              non-destructive requeue of [fromHeight, tip]
-rewindTo(height)                         destructive
+queueRescanFrom(fromHeight) / rewindTo(height)
 
-transactionHistory(uuid, limit, offset)  limit ≤ 500
+transactionHistory(uuid, limit, offset)
 transactionDetails(uuid, txid) / transactionOutputs(uuid, txid)
-deleteWallet(dbName)                     deletes the local cache (rebuildable)
-storageStats()
-diagDatabaseExists(dbName)               persisted bytes exist; opens nothing
-diagDatabaseHealth()                     read-only consistency checks
-
-pcztQuote(...)                           quote only; builds nothing
-pcztCreate(...) → { pcztHex, feeZat }    build; locks no notes
-pcztProve(pczt)
-pcztCombine(original, signed)            merge an external signer's copy (signatures only)
-pcztSubmit(uuid, pczt)                   → { txid, broadcast }
-pendingBroadcastTxids(uuid)              stored, unmined, unexpired, not rejected
-broadcastTransaction(txid)               resend a stored transaction; explicit user request only
-
-prewarmPczt(network, height)             build proving parameters; no wallet
-pcztProveAtHeight(height, pczt)          prove without a wallet
-pcztExtractStateless(pczt)               verify and extract without a wallet
-capabilities() / dependencyVersions()
-```
+storageStats() / diagDatabaseExists(dbName) / diagDatabaseHealth()
 
-### Consecutive old-birthday imports
+pcztQuote(...) / pcztCreate(...) / pcztProve(pczt)
+pcztCombine(original, signed) / pcztSubmit(uuid, pczt)
+pendingBroadcastTxids(uuid) / broadcastTransaction(txid)
 
-`DATABASE_ERROR` with `params.operation = "importAccount"` and
-`params.reason = "checkpointsDiverged"` is upstream rejecting mismatched pool
-checkpoints. The import rolls back and the database stays usable: keep the account
-pending and retry the import after further scanning; it succeeds once the pending
-scan finishes.
+prewarmPczt(network, height) / pcztProveAtHeight(height, pczt)
+pcztExtractStateless(pczt)
+capabilities() / dependencyVersions()
+```
 
 ### `onekey-zcash-keys`
 
 ```
 ufvkFromAccountKeys(network, orchardSk, accountXpub, accountIndex)
-                                         mainnet only; orchardSk is the 32-byte Orchard key
 unifiedAddress(network, ufvk, receiverPolicy)
-                                         "all" = Orchard + transparent;
-                                         "orchard" = Orchard only; never Sapling
 transparentAddressFromUfvk(network, ufvk) / transparentAccountPubKeyFromUfvk(network, ufvk)
 validateAddress(network, address)
-pcztVerifyReview(pczt, reviewJson)       check only, no signing
+pcztVerifyReview(pczt, reviewJson)
 pcztSignWithAccountKeys(network, orchardSk, accountXprv, accountIndex, pczt, reviewJson)
-                                         mainnet only; requires the keys to rebuild the
-                                         reviewed UFVK, then checks every spend and output
-pcztRedactForHardwareSigner(pczt)        copy to send to a device; keep the original
-transparentTx* / transparentShield*      stateless transparent sends, see
-parseTransparentTransactions(requestJson)  crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
+pcztRedactForHardwareSigner(pczt)
+transparentTx* / transparentShield* / parseTransparentTransactions(requestJson)
 keysCapabilities() / keysDependencyVersions()
 ```
 
-### Sending
-
-The transaction-output history API distinguishes recorded payment outputs from
-change using the exact transaction, pool and output index in `sent_notes`. Its
-`isChange` excludes explicit self-payments, which compact scanning also flags as
-change for wallet accounting. This read projection does not modify scan state.
-
-```
-runtime.pcztCreate()             build (selection, witness, anchor)
-runtime.pcztProve()              zero-knowledge proofs (slow)
-keys.pcztSignWithAccountKeys()   check against the review, then sign
-  or hardware: keys.pcztRedactForHardwareSigner() → device → runtime.pcztCombine()
-runtime.pcztSubmit()             extract → store → broadcast
-```
-
-Prove before signing: the upstream Signer must be able to verify what the proofs
-cover. Building locks no notes: the signed transaction is stored before broadcast
-and from then on holds its notes until mined or expired. Storing is refused when
-another stored, unexpired transaction already spends one of the same notes (two
-reviews opened at once). Sync does not rebroadcast it. Broadcast outcomes:
-
-- `accepted`: the node took it (`already known` / `in mempool` / `in blockchain`
-  count as success).
-- `rejected`: only an explicit consensus-invalid or expired reply, recorded in
-  `ext_onekey_tx_state` (the only rows it holds). The transaction stays stored;
-  its notes return after its expiry height.
-- `unknown`: anything else. It stays pending until mined or expired; the host does
-  not resubmit it.
-
-Pending transactions do not block another payment or user-requested local-data
-deletion, reset or rescan.
-
-Submission always extracts and stores the current signed transaction, including
-on retry. A shared nullifier identifies an input conflict; it never authorizes
-returning or broadcasting a different stored transaction in its place.
-
-`FINALIZE_OUTCOME_UNKNOWN` means persistence is unconfirmed: treat it like `unknown`
-and do not rebuild. Network calls time out after 30 seconds.
-
-Transparent-only sends (t-address or Unified Address recipients, no wallet or scan)
-use the stateless API in
-[TRANSPARENT_TX_API.md](./crates/zcash-keys-runtime/TRANSPARENT_TX_API.md).
-
-## Pitfalls
-
-- **The lightwalletd endpoint must support gRPC-web** (and CORS without a host
-  transport). A native-gRPC-only endpoint hangs on the first browser request even
-  if `grpcurl` works. No endpoint is hardcoded.
-- **Scanning does not use upstream `scan_cached_blocks`.** It hands trial decryption
-  to `rayon::spawn_fifo`, which never runs in single-threaded wasm and blocks the
-  thread forever. `scan_blocks_inline` replaces it; use `syncPeek()` for progress.
-- **`rusqlite`'s `bundled` feature breaks wasm32** (`'stdio.h' file not found`) and
-  Cargo features cannot be disabled downstream, so `scripts/vendor-deps.sh` patches
-  `zcash_client_sqlite`'s Cargo.toml. It also applies OPFS durability fixes to
-  `sqlite-wasm-vfs` and host fetch injection to `tonic-web-wasm-client`. All patches
-  are recorded in `patches/manifest.json`; `--offline` rejects unrecorded vendor
-  changes. The precompiled wasm SQLite is linked by `crates/zcash-runtime/build.rs`.
-- **Storage is OPFS** (SAH pool in `.onekey-zcash-opfs`, `zcash-main.db` /
-  `zcash-test.db`), with `journal_mode=DELETE`, `synchronous=FULL` and
-  `secure_delete=ON`. Deleting a database or journal truncates its pool file to
-  the 4 KiB header once the header clear is flushed; opening the pool truncates
-  any free file that still holds data. One Worker
-  owns each origin's pool. OPFS is per-origin and subject to quota and eviction, so
-  the embedding page's origin must be stable. When `storageRequiresWorkerRestart()`
-  is true after an I/O failure, keep the failed call's result and restart the
-  Worker. No SharedArrayBuffer or COOP/COEP is needed.
-- `openWallet()` fails with `DATABASE_TOO_NEW` when a newer runtime migrated the
-  database. It is not corruption: keep the database and update the runtime.
-- `syncPrepare()` downloads every pool's subtree roots (many on mainnet); give it its
-  own "preparing" state.
-- Sapling is out of scope: not a receiver, scan identity or send source.
-
 ## Layout
 
 ```
diff --git a/chain-runtimes/zcash/RELEASING.md b/chain-runtimes/zcash/RELEASING.md
deleted file mode 100644
index b6dacfa4b..000000000
--- a/chain-runtimes/zcash/RELEASING.md
+++ /dev/null
@@ -1,50 +0,0 @@
-# Zcash WASM releases
-
-Zcash versions are independent of the native modules' 3.x release train. Do not
-run the repository-wide `version:patch` or `version:publish` for a Zcash release.
-
-## Version source
-
-Edit only `[workspace.package].version` in `Cargo.toml`. Both crates inherit it,
-and wasm-pack generates the npm versions from those crates. Update the two
-workspace entries in `Cargo.lock` with `cargo check --workspace --offline` and
-review the lockfile diff; dependency upgrades are a separate change.
-
-Prerelease versions (`X.Y.Z-alpha.N`, `X.Y.Z-rc.N`) go to the npm `next` tag,
-release versions to `latest`. Runtime and keys always share a version and source commit.
-
-## Prepare and verify
-
-Use Python 3.11+ and the pinned Rust/WASM tools described in README.md.
-
-1. Run `python3 -m unittest discover -s scripts -p 'test_*.py'` and
-   `cargo test --workspace --locked --offline` with already prepared dependencies.
-2. Commit the release changes. A release build must come from a clean checkout.
-3. Run `bash scripts/build-wasm.sh --offline`. This builds both WASM
-   artifacts, prepares npm metadata and LICENSE, and writes the source manifest.
-4. Run `python3 scripts/package-release.py pack --version 0.1.0-rc.1 --tag next
-   --revision ` (as one command). It checks clean-source
-   provenance, Cargo.lock, all artifact hashes, versions, and npm archive contents.
-   `dist/` contains the two verified tarballs and source manifest.
-
-`--allow-dirty` is only for local packaging diagnostics. Never publish those
-archives or manually rewrite the manifest to make an old artifact pass.
-
-## Publish
-
-Run the **publish-runtime-packages** workflow manually. It builds, tests and packs
-every runtime, then publishes each package whose version is not on npm yet.
-Prereleases go to `next`, release versions to `latest`. Branches other than
-`main` can publish alpha versions only. Publishing uses the repository's
-`NPM_TOKEN`.
-
-npm cannot publish two packages atomically. If one of the pair fails, do not
-consume the version until both exist: re-run that same run, which skips the
-package already published. Do not dispatch a new run from another commit for the
-same version, or runtime and keys would come from different sources.
-
-## App update
-
-After both packages are on npm, set both entries in the App's
-`packages/core/package.json` to the same exact version and update `yarn.lock`
-through the App repository's dependency workflow. Do not use a version range.
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml
index 7ad6e24db..42368a778 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml
@@ -9,9 +9,7 @@ description = "OneKey Zcash keys: derivation and signing only, no storage, scann
 [lib]
 crate-type = ["cdylib", "rlib"]
 
-# Minimal dependencies: this crate ships in mobile bundles. Deliberately excludes
-# zcash_client_backend, zcash_client_sqlite, rusqlite, sqlite-wasm-rs, and tonic,
-# which belong to onekey-zcash-runtime.
+# Minimal deps for mobile bundles: no client_backend, sqlite, or tonic.
 [dependencies]
 zcash_keys.workspace = true
 zcash_protocol.workspace = true
@@ -26,21 +24,17 @@ serde.workspace = true
 serde_json.workspace = true
 hex.workspace = true
 secp256k1 = { version = "0.29", features = ["alloc"], default-features = false }
-# Same pinned version as zcash_transparent: parses the account xprv without upstream
-# `AccountPrivKey::from_bytes`, which re-encodes it into an unwiped heap string.
+# Pinned to match zcash_transparent; parses the xprv without upstream `AccountPrivKey::from_bytes` (unwiped heap string).
 bip32 = { version = "=0.6.0-pre.1", default-features = false, features = ["secp256k1-ffi"] }
 zcash_script = { version = "0.4.3", default-features = false }
-# signer + orchard: sign PCZT Orchard spends. prover/tx-extractor belong to the runtime crate.
-# transparent: shielding must sign transparent inputs. Pulls in zcash_script (pure Rust
-# since 0.4, builds for wasm32).
+# transparent: shielding signs transparent inputs; zcash_script is pure Rust since 0.4.
 pczt = { workspace = true, features = ["signer", "orchard", "transparent", "zcp-builder", "spend-finalizer", "io-finalizer"] }
 transparent = { workspace = true, features = ["transparent-inputs"] }
 orchard = { version = "0.15", default-features = false }
 sapling.workspace = true
 thiserror.workspace = true
 
-# Test-only: shipped builds never take a seed or mnemonic. bip0039 and blake2b_simd
-# derive account keys from seeds for parity tests against upstream.
+# Test-only: seed-based derivation for parity tests.
 [dev-dependencies]
 bip0039 = { version = "0.12", features = ["all-languages"] }
 blake2b_simd.workspace = true
@@ -49,11 +43,9 @@ blake2b_simd.workspace = true
 wasm-bindgen.workspace = true
 js-sys.workspace = true
 getrandom = { workspace = true, features = ["wasm_js"] }
-# Older crates also pull in getrandom 0.2, which needs the legacy "js" feature on
-# wasm32-unknown-unknown.
+# Older crates pull in getrandom 0.2, which needs "js" on wasm32-unknown-unknown.
 getrandom_02 = { package = "getrandom", version = "0.2", features = ["js"] }
 
-# -Oz instead of wasm-pack's default -O: smaller output; slower builds, negligible
-# runtime cost for this IO-bound workload.
+# -Oz: smaller output at negligible runtime cost.
 [package.metadata.wasm-pack.profile.release]
 wasm-opt = ["-Oz", "--enable-bulk-memory", "--enable-nontrapping-float-to-int"]
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md b/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
deleted file mode 100644
index 0f9a0793c..000000000
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/TRANSPARENT_TX_API.md
+++ /dev/null
@@ -1,132 +0,0 @@
-# Stateless transparent transaction API
-
-`onekey-zcash-keys` can quote and sign a mainnet transaction that spends transparent
-funds without a wallet database, scanner or network client. The host owns UTXO
-discovery, outpoint reservation, revalidation at signing time, broadcast and status
-reconciliation. Recipients find shielded outputs by scanning; the sender does not scan.
-
-## Exports
-
-- `transparentTxQuote(requestJson)`
-- `transparentTxBuildWithAccountXprv(requestJson, accountXprv)`: transparent recipients
-- `transparentShieldCreateWithAccountXprv(requestJson, accountXprv)` and
-  `transparentShieldSignWithAccountXprv(requestJson, accountXprv, original, proved)`:
-  Unified Address recipients through a proved PCZT
-- `transparentTxCreateWithAccountXpub(requestJson, accountXpub, seedFingerprintHex)` and
-  `transparentTxCombineHardwareSigned(requestJson, accountXpub, original, signed)`:
-  hardware signing
-- `parseTransparentTransactions(requestJson)`: verifies raw previous transactions
-  against their txids and returns output values, scripts and coinbase status; the
-  host checks each UTXO's index and value against it
-
-All entry points take the same request. No entry point takes a seed or mnemonic.
-`seedFingerprintHex` is the 32-byte ZIP-32 seed fingerprint written into the PCZT's
-derivation metadata for the device; it is an identifier, not key material.
-
-The xprv entry points take the account-level BIP-44 xprv at `m/44'/133'/account'`.
-An account xprv cannot attest its ancestors, so the crate checks its depth and
-hardened account child; deriving it from the right purpose and coin type is the
-host's job.
-
-## Call sequences
-
-Unified Address recipient, software key:
-
-1. `keys.transparentShieldCreateWithAccountXprv` builds a PCZT from the quoted request.
-2. `runtime.pcztProveAtHeight` proves it.
-3. `keys.transparentShieldSignWithAccountXprv` checks the request, the original PCZT
-   and the proved PCZT, then signs.
-4. `runtime.pcztExtractStateless` verifies and extracts the final transaction.
-
-Hardware: `keys.transparentTxCreateWithAccountXpub` → device signs →
-`keys.transparentTxCombineHardwareSigned` (verifies every signature against the
-request) → `runtime.pcztProveAtHeight` → `runtime.pcztExtractStateless`.
-
-## Request
-
-Amounts are decimal strings because JavaScript numbers cannot represent every valid
-zatoshi value.
-
-```json
-{
-  "network": "main",
-  "accountIndex": 0,
-  "targetHeight": 3500000,
-  "expiryHeight": 3500020,
-  "utxos": [
-    {
-      "txid": "0000000000000000000000000000000000000000000000000000000000000001",
-      "vout": 0,
-      "valueZat": "100000",
-      "scriptPubKey": "76a914000000000000000000000000000000000000000088ac",
-      "isCoinbase": false,
-      "confirmations": 1,
-      "derivationPath": "m/44'/133'/0'/0/0"
-    }
-  ],
-  "selectedOutpoints": [
-    {
-      "txid": "0000000000000000000000000000000000000000000000000000000000000001",
-      "vout": 0
-    }
-  ],
-  "recipients": [{ "address": "t1...", "amountZat": "50000" }],
-  "sendMax": false,
-  "change": {
-    "address": "t1...",
-    "derivationPath": "m/44'/133'/0'/0/0"
-  }
-}
-```
-
-- Only selected outpoints are spent; each must resolve to exactly one supplied UTXO.
-- Inputs must be confirmed, non-coinbase P2PKH coins controlled by their declared
-  external or internal BIP-44 path.
-- Recipients may be `t1` (P2PKH), `t3` (P2SH), ZIP-320 `tex1` (paid as P2PKH), or a
-  Unified Address with an Orchard receiver (paid as an Ironwood note). A Unified
-  Address without one is rejected rather than paid at a public receiver.
-  Sapling/Sprout destinations are unsupported.
-- Change must be an owned P2PKH address: the account's receive address at
-  `m/44'/133'/account'/0/0`. Internal scope `1` with an address index below 40 is
-  also accepted. Both signing paths verify that the address matches the declared
-  path in the signing account.
-- Send-max: exactly one recipient, no `amountZat` and no `change`; the recipient gets
-  the selected total minus the ZIP-317 fee.
-- Fixed amount: a surplus too small to fund a change output (below the 5,000 zatoshi
-  marginal fee, or not enough to pay for the extra output) is added to the fee and
-  shown in the quote, so the overpayment stays below about 0.0001 ZEC. A larger
-  surplus requires `change`.
-- `targetHeight` must be on the mainnet NU6.3 branch. `expiryHeight` is mandatory,
-  comes from the host's policy, and must be after the target height and at most 100
-  blocks later. The result is a V6 transaction.
-
-## Results
-
-Quote:
-
-```json
-{
-  "feeZat": "10000",
-  "inputTotalZat": "100000",
-  "sendAmountZat": "50000",
-  "changeZat": "40000",
-  "expiryHeight": 3500020,
-  "spentOutpoints": [{ "txid": "...", "vout": 0 }]
-}
-```
-
-Build:
-
-```json
-{
-  "rawTx": "...",
-  "txid": "...",
-  "feeZat": "10000",
-  "expiryHeight": 3500020,
-  "spentOutpoints": [{ "txid": "...", "vout": 0 }]
-}
-```
-
-Build entry points recompute the quote and fail closed if any input script or change
-address does not match the derived key. Reserve every returned outpoint before
-broadcast.
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/build.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/build.rs
index c6e569441..81c4cd075 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/build.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/build.rs
@@ -1,8 +1,6 @@
 fn main() {
     if std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() == Ok("wasm32") {
-        // The host wipes inactive stack frames after synchronous key operations.
-        // Export linker-owned bounds so it never guesses a memory layout or
-        // overwrites static data and live heap allocations.
+        // Host wipes the inactive stack using linker-owned bounds, never guessed ones.
         println!("cargo:rustc-link-arg=--export=__stack_low");
         println!("cargo:rustc-link-arg=--export=__stack_high");
     }
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
index 656bce1dc..daf21b833 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
@@ -1,8 +1,6 @@
 //! Account-scoped software keys supplied by the host.
 //!
-//! The host derives the ZIP-32 Orchard account spending key (`m/32'/133'/account'`)
-//! and the BIP-44 transparent account key (`m/44'/133'/account'`) from its seed;
-//! no seed or mnemonic crosses this boundary. Mainnet only.
+//! Orchard key at `m/32'/133'/account'`, transparent key at `m/44'/133'/account'`; no seed crosses the boundary. Mainnet only.
 
 use std::ops::Deref;
 
@@ -22,15 +20,12 @@ use crate::{
 ///
 /// # Safety
 ///
-/// Implementors must be flat: no drop glue, pointers, or niches, so all-zero bytes
-/// are a valid value. `SpendingKey` is `[u8; 32]`; `AccountPrivKey` is a bip32
-/// `ExtendedPrivateKey` of `secp256k1::SecretKey([u8; 32])` and plain attributes.
+/// Implementors must be flat (no drop glue, pointers, or niches) so all-zero bytes are valid.
 pub(crate) unsafe trait FlatKey {}
 unsafe impl FlatKey for SpendingKey {}
 unsafe impl FlatKey for AccountPrivKey {}
 
-/// Wipes an upstream key that lacks `ZeroizeOnDrop` when dropped. Copies the
-/// compiler leaves in moved-from stack slots are outside its reach.
+/// Wipes a key lacking `ZeroizeOnDrop` on drop; moved-from stack copies are out of reach.
 pub(crate) struct Wiped(T);
 
 impl Wiped {
@@ -55,8 +50,7 @@ impl Drop for Wiped {
     }
 }
 
-/// Spending keys for one account, wiped on drop. Only the xprv carries account
-/// metadata; `review::verify_signer` binds both keys to the reviewed UFVK.
+/// Spending keys for one account, wiped on drop. `review::verify_signer` binds both keys to the reviewed UFVK.
 pub struct AccountSigningKeys {
     params: Network,
     orchard: Wiped,
@@ -93,7 +87,6 @@ impl AccountSigningKeys {
         &self.transparent
     }
 
-    /// The UFVK these keys control, encoded exactly like `ufvkFromAccountKeys`.
     pub fn ufvk(&self) -> Result {
         ufvk_from_parts(
             self.params,
@@ -103,7 +96,6 @@ impl AccountSigningKeys {
     }
 }
 
-/// The account-key APIs reject testnet.
 fn parse_mainnet(network: &str) -> Result {
     match keys::parse_network(network)? {
         Network::MainNetwork => Ok(Network::MainNetwork),
@@ -123,7 +115,6 @@ fn account_id(account_index: u32) -> Result {
     })
 }
 
-/// Parse a raw 32-byte Orchard spending key, rejecting keys upstream deems invalid.
 pub(crate) fn parse_orchard_sk(bytes: &[u8]) -> Result> {
     let bytes: Zeroizing<[u8; 32]> = Zeroizing::new(bytes.try_into().map_err(|_| {
         KeysError::with(
@@ -136,10 +127,7 @@ pub(crate) fn parse_orchard_sk(bytes: &[u8]) -> Result> {
         .ok_or_else(|| KeysError::new(ErrorCode::InvalidSpendingKey))
 }
 
-/// Transparent + Orchard UFVK, the same items the OneKey firmware returns.
-///
-/// Sapling is left out: this runtime can neither scan for nor spend it.
-/// Ironwood keys derive from the Orchard item.
+/// Transparent + Orchard UFVK, the same items the firmware returns. Sapling is omitted.
 pub(crate) fn ufvk_from_parts(
     params: Network,
     fvk: &FullViewingKey,
@@ -155,9 +143,7 @@ pub(crate) fn ufvk_from_parts(
     Ok(container.encode(¶ms.network_type()))
 }
 
-/// UFVK from the Orchard account spending key and the transparent account xpub.
-///
-/// Account setup needs no transparent secret: the xpub is public account material.
+/// Needs no transparent secret: the xpub is public.
 pub fn ufvk_from_account_keys(
     network: &str,
     orchard_sk: &[u8],
@@ -171,7 +157,6 @@ pub fn ufvk_from_account_keys(
     ufvk_from_parts(params, &FullViewingKey::from(&*orchard), &transparent)
 }
 
-/// Verify a PCZT against the reviewed payment and the signer's own UFVK, then sign it.
 pub fn sign_reviewed_pczt(
     network: &str,
     orchard_sk: &[u8],
@@ -185,7 +170,6 @@ pub fn sign_reviewed_pczt(
     sign::sign_pczt_with_account_keys(&keys, pczt_bytes)
 }
 
-/// Test-only key material derived from a seed, mirroring the host derivation.
 #[cfg(test)]
 pub(crate) mod test_keys {
     use super::*;
@@ -206,7 +190,6 @@ pub(crate) mod test_keys {
         state.finalize().as_bytes().try_into().unwrap()
     }
 
-    /// ZIP-32 Orchard hardened derivation, written out the way the host computes it.
     pub(crate) fn orchard_sk_at(seed: &[u8], path: &[u32]) -> [u8; 32] {
         let i = blake2b_512(b"ZcashIP32Orchard", &[seed]);
         let (mut sk, mut chain): ([u8; 32], [u8; 32]) =
@@ -220,7 +203,6 @@ pub(crate) mod test_keys {
         sk
     }
 
-    /// `m/32'/133'/account'`.
     pub(crate) fn orchard_sk(seed: &[u8], account: u32) -> [u8; 32] {
         orchard_sk_at(seed, &[32, 133, account])
     }
@@ -242,7 +224,6 @@ pub(crate) mod test_keys {
 
     pub(crate) fn account_xpub(seed: &[u8], account: u32) -> String {
         let key = account_priv_key(seed, account);
-        // depth || parent fingerprint || child number, then chain code || pubkey.
         let header = key.to_bytes()[..9].to_vec();
         let mut payload = XPUB_VERSION.to_vec();
         payload.extend(header);
@@ -250,7 +231,6 @@ pub(crate) mod test_keys {
         bs58::encode(payload).with_check().into_string()
     }
 
-    /// Oracle: the upstream seed-based USK, which this crate does not accept.
     pub(crate) fn usk(seed: &[u8], account: u32) -> UnifiedSpendingKey {
         UnifiedSpendingKey::from_seed(&MAIN_NETWORK, seed, AccountId::try_from(account).unwrap())
             .unwrap()
@@ -283,11 +263,9 @@ mod tests {
             .to_vec()
     }
 
-    /// Deterministic seeds of both lengths the transparent and Orchard derivations accept.
     fn deterministic_seeds(count: u32) -> Vec> {
         (0..count)
             .map(|i| {
-                // BIP-32 (transparent) accepts 16, 32 or 64 bytes; BIP-39 seeds are 64.
                 let len = [64usize, 32][i as usize % 2];
                 let mut seed = Vec::new();
                 let mut block = 0u32;
@@ -335,7 +313,6 @@ mod tests {
             new_fvk.to_bytes() == oracle_fvk.to_bytes(),
             "Orchard full viewing key must match the seed oracle"
         );
-        // ak, the SpendValidatingKey encoding, is the first 32 bytes of the FVK encoding.
         assert!(
             new_fvk.to_bytes()[..32] == oracle_fvk.to_bytes()[..32],
             "Spend validating key encoding must match the seed oracle"
@@ -386,8 +363,7 @@ mod tests {
         });
     }
 
-    /// ZIP-32 Orchard test vectors (orchard `test_vectors::zip32`, seed 0x00..0x1f):
-    /// pin the hand-written derivation the host mirrors.
+    /// ZIP-32 Orchard test vectors (seed 0x00..0x1f).
     #[test]
     fn orchard_derivation_matches_zip32_vectors() {
         let seed = (0u8..32).collect::>();
@@ -423,7 +399,6 @@ mod tests {
             assert_eq!(e.params["byteLen"], len);
         }
 
-        // The xpub/xprv metadata must name the requested account.
         let e = ufvk_from_account_keys("main", &sk, &xpub, 1).unwrap_err();
         assert_eq!(e.code, ErrorCode::InvalidAccountXpub);
         let e = AccountSigningKeys::parse("main", &sk, &xprv, 1)
@@ -496,8 +471,7 @@ mod tests {
         }
     }
 
-    /// Hardware parity vectors from the independent firmware implementation:
-    /// fingerprint, Orchard FVK (96B), transparent pubkey (65B), and both receivers.
+    /// Parity vectors from the firmware implementation.
     #[test]
     fn hardware_parity_vectors() {
         use zcash_address::unified::{Container, Encoding, Fvk, Receiver, Ufvk};
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
index e32c14145..f176ac733 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
@@ -1,24 +1,16 @@
-//! Host-facing key API.
-//!
-//! No seed or mnemonic crosses this boundary. Spending keys enter only as
-//! account-scoped inputs and never cross it outward.
+//! Host-facing key API. No seed or mnemonic crosses this boundary; spending keys only enter, never leave.
 
 use wasm_bindgen::prelude::*;
 use zeroize::Zeroizing;
 
 use crate::{account_keys, keys, review, sign, transparent_prevouts, transparent_send};
 
-/// Check recipient encoding, network, and supported receivers locally.
 #[wasm_bindgen(js_name = validateAddress)]
 pub fn validate_address(network: &str, address: &str) -> Result {
     Ok(keys::validate_address(network, address)?)
 }
 
-/// Derive the Unified Address from a UFVK. Public material only.
-///
-/// `receiverPolicy` selects the receivers: `"all"` / `"orchard"`.
-/// It is a host privacy decision with no default: a transparent receiver links
-/// the user's transparent and shielded activity.
+/// `receiverPolicy` (`"all"` / `"orchard"`) has no default: a transparent receiver links transparent and shielded activity.
 #[wasm_bindgen(js_name = unifiedAddress)]
 pub fn unified_address(
     network: &str,
@@ -28,8 +20,7 @@ pub fn unified_address(
     Ok(keys::unified_address_with(network, ufvk, receiver_policy)?)
 }
 
-/// Derive a mainnet UFVK from the 32-byte Orchard account spending key
-/// (`m/32'/133'/account'`) and the transparent account xpub (`m/44'/133'/account'`).
+/// Mainnet UFVK from the 32-byte Orchard account spending key and the transparent account xpub.
 #[wasm_bindgen(js_name = ufvkFromAccountKeys)]
 pub fn ufvk_from_account_keys(
     network: &str,
@@ -37,8 +28,7 @@ pub fn ufvk_from_account_keys(
     account_xpub: &str,
     account_index: u32,
 ) -> Result {
-    // Own and wipe the original bindgen allocation, including on validation errors.
-    // Wiping another copy would leave the JS-to-WASM input in freed linear memory.
+    // Wipe the original bindgen allocation, including on validation errors; a copy would leave it in freed memory.
     let orchard_sk = Zeroizing::new(orchard_sk);
     Ok(account_keys::ufvk_from_account_keys(
         network,
@@ -48,10 +38,8 @@ pub fn ufvk_from_account_keys(
     )?)
 }
 
-/// Sign a mainnet PCZT with the Orchard account spending key and the transparent
-/// account xprv, after checking that they control the reviewed UFVK and that the
-/// PCZT matches the reviewed payment. The caller wipes its own copies; this side
-/// cannot wipe the JS heap.
+/// Signs only after checking the keys control the reviewed UFVK and the PCZT matches the reviewed
+/// payment. The caller wipes its own copies; this side cannot wipe the JS heap.
 #[wasm_bindgen(js_name = pcztSignWithAccountKeys)]
 pub fn pczt_sign_with_account_keys(
     network: &str,
@@ -73,19 +61,17 @@ pub fn pczt_sign_with_account_keys(
     )?)
 }
 
-/// The copy of a PCZT to send to a hardware signer; keep the original for combining.
+/// PCZT copy for a hardware signer; keep the original for combining.
 #[wasm_bindgen(js_name = pcztRedactForHardwareSigner)]
 pub fn pczt_redact_for_hardware_signer(pczt_bytes: Vec) -> Result, JsValue> {
     Ok(sign::redact_for_hardware_signer(&pczt_bytes)?)
 }
 
-/// Verify a private payment before showing its confirmation or contacting a signer.
 #[wasm_bindgen(js_name = pcztVerifyReview)]
 pub fn pczt_verify_review(pczt_bytes: Vec, review_json: &str) -> Result<(), JsValue> {
     Ok(review::verify_json(&pczt_bytes, review_json)?)
 }
 
-/// Derive the transparent receiving address (t-address) from a UFVK, offline.
 #[wasm_bindgen(js_name = transparentAddressFromUfvk)]
 pub fn transparent_address_from_ufvk(network: &str, ufvk: &str) -> Result {
     Ok(keys::transparent_address(network, ufvk)?)
@@ -97,19 +83,16 @@ pub fn transparent_account_pubkey_from_ufvk(network: &str, ufvk: &str) -> Result
     Ok(keys::transparent_account_pubkey(network, ufvk)?)
 }
 
-/// Parses and verifies previous transactions without loading wallet state.
 #[wasm_bindgen(js_name = parseTransparentTransactions)]
 pub fn parse_transparent_transactions(request_json: &str) -> Result {
     Ok(transparent_prevouts::parse_json(request_json)?)
 }
 
-/// Quotes a mainnet V6 transparent transaction without loading wallet state.
 #[wasm_bindgen(js_name = transparentTxQuote)]
 pub fn transparent_tx_quote(request_json: &str) -> Result {
     Ok(transparent_send::quote_json(request_json)?)
 }
 
-/// Builds and signs using an account xprv at `m/44'/133'/account'`.
 #[wasm_bindgen(js_name = transparentTxBuildWithAccountXprv)]
 pub fn transparent_tx_build_with_account_xprv(
     request_json: &str,
@@ -122,8 +105,7 @@ pub fn transparent_tx_build_with_account_xprv(
     )?)
 }
 
-/// What the keys side can sign. Combine with the runtime's `capabilities()`:
-/// a bundle is usable only if both proving and signing support it.
+/// What the keys side can sign; a bundle is usable only if the runtime's `capabilities()` also supports it.
 #[wasm_bindgen(js_name = keysCapabilities)]
 pub fn keys_capabilities() -> String {
     serde_json::json!({
@@ -154,7 +136,6 @@ pub fn keys_capabilities() -> String {
     .to_string()
 }
 
-/// Creates a device-signable PCZT from public account material without wallet storage.
 #[wasm_bindgen(js_name = transparentTxCreateWithAccountXpub)]
 pub fn transparent_tx_create_with_account_xpub(
     request_json: &str,
@@ -168,7 +149,6 @@ pub fn transparent_tx_create_with_account_xpub(
     )?)
 }
 
-/// Validates and finalizes device signatures against the approved transaction.
 #[wasm_bindgen(js_name = transparentTxCombineHardwareSigned)]
 pub fn transparent_tx_combine_hardware_signed(
     request_json: &str,
@@ -184,13 +164,11 @@ pub fn transparent_tx_combine_hardware_signed(
     )?)
 }
 
-/// Pinned upstream dependency versions.
 #[wasm_bindgen(js_name = keysDependencyVersions)]
 pub fn dependency_versions() -> String {
     crate::dependency_versions().to_string()
 }
 
-/// Creates a shielding PCZT with an account-level transparent key.
 #[wasm_bindgen(js_name = transparentShieldCreateWithAccountXprv)]
 pub fn transparent_shield_create_with_account_xprv(
     request_json: &str,
@@ -203,7 +181,6 @@ pub fn transparent_shield_create_with_account_xprv(
     )?)
 }
 
-/// Signs a proved shielding PCZT with an account-level transparent key.
 #[wasm_bindgen(js_name = transparentShieldSignWithAccountXprv)]
 pub fn transparent_shield_sign_with_account_xprv(
     request_json: &str,
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs
index 56fde100a..6d08ee398 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs
@@ -1,7 +1,5 @@
-//! Error contract, same shape as `onekey-zcash-runtime`: stable error codes plus
-//! structured params. Rust never produces user-facing text.
-//!
-//! The two crates' code sets do not overlap, so hosts can share one handler.
+//! Stable error codes plus structured params; Rust never produces user-facing text.
+//! Same shape as `onekey-zcash-runtime`; the code sets do not overlap.
 
 use serde_json::{json, Map, Value};
 use std::fmt;
@@ -17,50 +15,32 @@ pub enum ErrorCode {
     InvalidSeed,
     /// Account index out of range. Params: `{ value }`
     InvalidAccountIndex,
-    /// UFVK cannot be parsed.
     InvalidUfvk,
-    /// Key derivation failed.
     DeriveFailed,
-    /// PCZT cannot be parsed.
     PcztParseFailed,
     /// PCZT signing failed. Params: `{ orchardActions }` when available.
     PcztSignFailed,
-    /// The stateless transparent transaction request is malformed.
     InvalidTransactionRequest,
-    /// The requested target height is not valid for the supported V6 mainnet branch.
     InvalidTargetHeight,
-    /// A destination or change address is invalid or belongs to another network.
     InvalidAddress,
-    /// An outpoint is malformed or reserved.
     InvalidOutpoint,
-    /// A selected outpoint is not present in the supplied UTXO catalog.
     UnknownInput,
-    /// An outpoint appears more than once.
     DuplicateInput,
-    /// Coinbase inputs are intentionally unsupported by transparent send.
+    /// Unsupported by transparent send.
     CoinbaseInput,
-    /// Unconfirmed transparent inputs are intentionally unsupported.
+    /// Unsupported by transparent send.
     UnconfirmedInput,
     /// Only regular P2PKH inputs are supported.
     UnsupportedInputScript,
-    /// The supplied BIP-44 path is outside the exact Zcash account path.
     InvalidDerivationPath,
-    /// A selected coin or change address does not match its derived key.
     KeyMismatch,
-    /// A zatoshi amount is malformed or outside the consensus range.
     InvalidAmount,
-    /// Selected inputs cannot cover outputs and the ZIP-317 fee.
     InsufficientFunds,
-    /// An account-level BIP-44 xprv is malformed or has unexpected metadata.
     InvalidAccountXprv,
-    /// An account-level BIP-44 xpub is malformed or has unexpected metadata.
     InvalidAccountXpub,
-    /// Transparent transaction construction or signing failed.
     TransactionBuildFailed,
-    /// The signed transaction could not be serialized.
     TransactionSerializeFailed,
-    /// An Orchard spending key is not 32 bytes or is rejected by ZIP-32 validity rules.
-    /// Params: `{ byteLen, expected }` for a length error.
+    /// Orchard spending key is not 32 bytes or fails ZIP-32 validity. Params: `{ byteLen, expected }` for a length error.
     InvalidSpendingKey,
 }
 
@@ -101,12 +81,9 @@ impl ErrorCode {
 #[derive(Debug)]
 pub struct KeysError {
     pub code: ErrorCode,
-    /// Structured params for host i18n placeholders. Always a JSON object.
+    /// Always a JSON object.
     pub params: Value,
-    /// Raw upstream error, for logs only.
-    ///
-    /// Must never contain seeds, spending keys, or anything derived from them. Upstream
-    /// errors describe structure and do not echo input, so passing them through is safe.
+    /// Raw upstream error, for logs only. Must never contain seeds, spending keys, or anything derived from them.
     pub detail: Option,
 }
 
@@ -151,7 +128,6 @@ impl std::error::Error for KeysError {}
 
 pub type Result = std::result::Result;
 
-/// Thrown to JS as an `Error` carrying `code` / `params` / `detail`.
 #[cfg(target_arch = "wasm32")]
 impl From for wasm_bindgen::JsValue {
     fn from(e: KeysError) -> Self {
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
index d001f19f3..2762ab25e 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
@@ -1,6 +1,4 @@
 //! Public key material: networks, recipients, UFVK-derived addresses.
-//!
-//! Account UFVKs are built from host-supplied account keys in `account_keys`.
 
 use zcash_keys::keys::UnifiedFullViewingKey;
 #[cfg(test)]
@@ -31,7 +29,7 @@ pub(crate) fn supported_recipient(
     encoded: &str,
 ) -> Option {
     use zcash_keys::address::Address;
-    // Host routing uses canonical lowercase Unified Address prefixes.
+    // Only lowercase UA prefixes are canonical.
     if encoded.starts_with("U") {
         return None;
     }
@@ -42,15 +40,12 @@ pub(crate) fn supported_recipient(
     }
 }
 
-/// Validate a recipient locally without storage, scanning, or network access.
 pub fn validate_address(network: &str, encoded: &str) -> Result {
     let params = parse_network(network)?;
     Ok(supported_recipient(¶ms, encoded).is_some())
 }
 
 /// Test-only: derive a UFVK from a mnemonic.
-///
-/// Shipped builds never take a mnemonic or seed.
 #[cfg(test)]
 pub(crate) fn ufvk_from_mnemonic(
     network: &str,
@@ -64,8 +59,7 @@ pub(crate) fn ufvk_from_mnemonic(
     ufvk_from_seed_bytes(params, seed.as_ref(), account_index)
 }
 
-/// Test-only oracle: the upstream seed-based UFVK, reduced to the transparent and
-/// Orchard items. Parity tests compare `account_keys` against it.
+/// Test-only oracle for parity tests: upstream seed-based UFVK reduced to transparent and Orchard items.
 #[cfg(test)]
 pub(crate) fn ufvk_from_seed_bytes(
     params: Network,
@@ -110,16 +104,12 @@ pub(crate) fn without_sapling(params: Network, ufvk: &UnifiedFullViewingKey) ->
     Ok(container.encode(&network))
 }
 
-/// Receivers to include in a UA. This is a privacy policy chosen by the host:
-/// a transparent receiver links the user's transparent and shielded activity.
-/// The runtime only checks that the combination is valid.
-///
-/// No policy includes a Sapling receiver: this runtime cannot spend Sapling, so
-/// Sapling-only senders would pay into an unspendable pool.
+/// Receivers to include in a UA, chosen by the host: a transparent receiver links transparent and
+/// shielded activity. No policy includes Sapling, which this runtime cannot spend.
 fn receiver_policy(name: &str) -> Result {
     use zcash_keys::keys::{ReceiverRequirement::*, UnifiedAddressRequest as R};
     match name {
-        // No default: an empty policy must not silently select the least private option.
+        // No default: an empty policy must not select the least private option.
         "all" => Ok(R::unsafe_custom(Require, Omit, Allow)),
         "orchard" => Ok(R::ORCHARD),
         other => Err(KeysError::with(
@@ -129,8 +119,6 @@ fn receiver_policy(name: &str) -> Result Result {
     let params = parse_network(network)?;
@@ -144,17 +132,12 @@ pub fn unified_address_with(network: &str, ufvk_str: &str, policy: &str) -> Resu
     Ok(addr.encode(¶ms))
 }
 
-/// Derive the transparent receiving address (t-address) from a UFVK. No
-/// spending key or wallet database involved.
-///
-/// This is the transparent receiver of the `"all"` UA, encoded on its own for
-/// counterparties that only accept t-addresses.
+/// The transparent receiver of the `"all"` UA, encoded as a t-address.
 pub fn transparent_address(network: &str, ufvk_str: &str) -> Result {
     let params = parse_network(network)?;
     let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str)
         .map_err(|e| KeysError::new(ErrorCode::InvalidUfvk).detail(e))?;
 
-    // Same address as `"all"`, so this matches the UA's transparent receiver.
     let (addr, _) = ufvk
         .default_address(receiver_policy("all")?)
         .map_err(|e| KeysError::new(ErrorCode::DeriveFailed).detail(format!("{e:?}")))?;
@@ -171,9 +154,7 @@ pub fn transparent_address(network: &str, ufvk_str: &str) -> Result {
     ))
 }
 
-/// Transparent account public key from the UFVK at the BIP32 account level
-/// (m/44'/133'/account'), hex of 32-byte chain code || 33-byte compressed key.
-/// The host builds the xpub from it without asking a hardware device again.
+/// Transparent account pubkey at m/44'/133'/account': hex of 32-byte chain code || 33-byte compressed key.
 pub fn transparent_account_pubkey(network: &str, ufvk_str: &str) -> Result {
     let params = parse_network(network)?;
     let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str)
@@ -191,8 +172,7 @@ pub fn transparent_account_pubkey(network: &str, ufvk_str: &str) -> Result serde_json::Value {
     serde_json::json!({
         "zcash_keys": "0.16.1",
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs
index 3d0821822..3b4a30c6a 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs
@@ -456,13 +456,11 @@ mod tests {
         assert!(signer_account_mismatch(sign_with(
             &[8; 32], 0, &bytes, &json
         )));
-        // Wrong-account keys, each self-consistent with their own account index.
         for account in [1, (1 << 31) - 1] {
             assert!(signer_account_mismatch(sign_with(
                 &seed, account, &bytes, &json
             )));
         }
-        // Mixed accounts: the Orchard key of account 0 with the transparent key of account 1.
         for (orchard_account, transparent_account) in [(0, 1), (1, 0)] {
             let mixed = account_keys::AccountSigningKeys::parse(
                 "main",
@@ -509,9 +507,7 @@ mod tests {
         )));
     }
 
-    /// Re-applies each spend authorization signature to the unsigned PCZT, where
-    /// upstream verifies it against the action's randomized key `rk`. Returns the
-    /// signed (pool, action) positions.
+    /// Verifies each spend auth signature against the action's `rk`; returns signed (pool, action) positions.
     fn verified_signatures(unsigned: &[u8], signed: &pczt::Pczt) -> Vec<(bool, usize)> {
         let signatures = extract_orchard_spend_auth_signatures(signed);
         let mut signer = Signer::new(pczt::Pczt::parse(unsigned).unwrap()).unwrap();
@@ -531,7 +527,6 @@ mod tests {
             .collect()
     }
 
-    /// Account keys and the upstream seed-derived USK authorize the same spends.
     #[test]
     fn account_keys_and_seed_oracle_sign_the_same_reviewed_pczt() {
         let seed = [7u8; 32];
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
index 5745021a8..dd30aefa9 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
@@ -1,6 +1,4 @@
 //! PCZT signing with host-supplied account keys.
-//!
-//! This crate also handles spending keys in `account_keys` and `transparent_send`.
 
 use pczt::roles::signer::Signer;
 use pczt::roles::verifier::{TransparentError, Verifier};
@@ -11,31 +9,21 @@ use crate::{
     error::{ErrorCode, KeysError, Result},
 };
 
-/// Whether a transparent input's signature commits to all outputs.
-///
-/// A non-`SIGHASH_ALL` signature lets anyone holding the signed transaction
-/// rewrite the recipients. All signing and verification paths share this check.
+/// Whether a transparent input is `SIGHASH_ALL`; any other type lets a holder of the signed tx rewrite recipients.
 pub(crate) fn is_sighash_all(input: &transparent::pczt::Input) -> bool {
     *input.sighash_type() == SighashType::ALL
 }
 
-/// Bundle types this crate can sign. Kept next to the implementation so they change together.
 pub const SIGN_ORCHARD: bool = true;
 pub const SIGN_SAPLING: bool = false;
 pub const SIGN_TRANSPARENT: bool = true;
 pub const SIGN_IRONWOOD: bool = true;
 
-/// Address indices to try when signing transparent inputs.
-///
-/// `pczt` does not expose each input's BIP-32 derivation path, so indices are
-/// tried in order. Upstream `sign` checks the derived pubkey against
-/// `script_pubkey`, so a wrong key fails instead of producing a bad signature.
-///
-/// Covers twice the default gap limit (20). It also bounds change address
-/// indices (see `transparent_send`): change beyond this range could not be signed.
+/// Address indices tried per input, since `pczt` hides derivation paths; upstream rejects a key that does
+/// not match `script_pubkey`. Also bounds change indices in `transparent_send`.
 pub(crate) const TRANSPARENT_SCAN_GAP: u32 = 40;
 
-/// Sign all transparent inputs; returns (signed count, last failure).
+/// Returns (signed count, last failure).
 fn sign_transparent_inputs(
     signer: &mut Signer,
     account_key: &AccountPrivKey,
@@ -48,7 +36,6 @@ fn sign_transparent_inputs(
 
     for index in 0..input_count {
         let mut done = false;
-        // Inputs may belong to the external or the internal scope; try both.
         for scope in [TransparentKeyScope::EXTERNAL, TransparentKeyScope::INTERNAL] {
             for i in 0..TRANSPARENT_SCAN_GAP {
                 let Some(child) = NonHardenedChildIndex::from_index(i) else {
@@ -75,11 +62,8 @@ fn sign_transparent_inputs(
     (signed, last_err)
 }
 
-/// Sign a PCZT with the account's Orchard spending key and transparent account key.
-///
-/// Signs Orchard/Ironwood spends and transparent inputs only. Sapling spends are
-/// unsupported (the ~50 MB Groth16 parameters are not shipped). Callers verify the
-/// PCZT against the reviewed payment first (`account_keys::sign_reviewed_pczt`).
+/// Signs Orchard/Ironwood spends and transparent inputs; Sapling is unsupported.
+/// Callers verify the PCZT against the reviewed payment first (`account_keys::sign_reviewed_pczt`).
 pub fn sign_pczt_with_account_keys(
     keys: &AccountSigningKeys,
     pczt_bytes: &[u8],
@@ -87,8 +71,7 @@ pub fn sign_pczt_with_account_keys(
     let pczt = pczt::Pczt::parse(pczt_bytes)
         .map_err(|e| KeysError::new(ErrorCode::PcztParseFailed).detail(format!("{e:?}")))?;
 
-    // Upstream `Signer::sign_*` leaves semantic checks to the caller. Require
-    // `SIGHASH_ALL` on every transparent input so signatures commit to all outputs.
+    // Require `SIGHASH_ALL` on every transparent input; upstream does not check.
     let pczt = Verifier::new(pczt)
         .with_transparent(|bundle| {
             match bundle
@@ -112,13 +95,10 @@ pub fn sign_pczt_with_account_keys(
     let mut signer = Signer::new(pczt)
         .map_err(|e| KeysError::new(ErrorCode::PcztSignFailed).detail(format!("{e:?}")))?;
 
-    // Orchard spend authorizing key, derived from the spending key.
     let ask = orchard::keys::SpendAuthorizingKey::from(keys.orchard());
 
-    // Shielded actions are signed best-effort: upstream rejects actions not owned
-    // by this account, and it is an error only if nothing is signed. Both pools are
-    // signed: post-NU6.3 spends use Ironwood, while migrations out of Orchard use
-    // Orchard, and one transaction can have both.
+    // Shielded actions are signed best-effort (upstream rejects foreign actions); error only if
+    // nothing is signed. Both pools are signed since one transaction can have Ironwood and Orchard.
     let (orchard_count, ironwood_count, transparent_count) = bundle_counts(pczt_bytes)?;
     let mut signed_any = false;
     let mut last_err: Option = None;
@@ -171,14 +151,8 @@ pub fn sign_pczt_with_account_keys(
         .map_err(|e| KeysError::new(ErrorCode::PcztSignFailed).detail(format!("{e:?}")))
 }
 
-/// The copy of a PCZT sent to a hardware signer.
-///
-/// A subset of upstream `redact_pczt_for_signer`'s compact-view redaction:
-/// clears the Sapling `bsk` (the IO Finalizer sets it even on an empty bundle)
-/// and, in Orchard and Ironwood, the proof, `bsk`, spend witnesses and dummy
-/// spend keys. Wallet metadata, anchors and resolvable fields are kept as is.
-/// The host keeps the original and combines the device's result into it, so
-/// proving and extraction still have them.
+/// PCZT copy for a hardware signer: clears Sapling and Orchard/Ironwood `bsk`, proofs, spend
+/// witnesses and dummy spend keys. The host keeps the original to combine the device result into.
 pub fn redact_for_hardware_signer(pczt_bytes: &[u8]) -> Result> {
     fn redact_orchard_protocol(mut bundle: pczt::roles::redactor::orchard::OrchardRedactor<'_>) {
         bundle.clear_zkproof();
@@ -199,9 +173,7 @@ pub fn redact_for_hardware_signer(pczt_bytes: &[u8]) -> Result> {
         .map_err(|e| KeysError::new(ErrorCode::PcztParseFailed).detail(format!("{e:?}")))
 }
 
-/// Count signable items per bundle: (orchard, ironwood, transparent).
-///
-/// Ironwood and Orchard share Rust types but are separate PCZT bundles.
+/// Signable items per bundle: (orchard, ironwood, transparent).
 fn bundle_counts(pczt_bytes: &[u8]) -> Result<(usize, usize, usize)> {
     let pczt = pczt::Pczt::parse(pczt_bytes)
         .map_err(|e| KeysError::new(ErrorCode::PcztParseFailed).detail(format!("{e:?}")))?;
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs
index db60708c7..1e845c059 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs
@@ -41,8 +41,7 @@ pub fn parse_json(request_json: &str) -> Result {
         .map(|previous| {
             let bytes = hex::decode(&previous.raw_tx).map_err(|_| invalid())?;
             let mut reader = &bytes[..];
-            // The legacy branch metadata is unused for txids and transparent outputs.
-            // V5 and later read the branch from the transaction itself. Never sign this object.
+            // Branch is unused for txids and transparent outputs; never sign this object.
             let tx = Transaction::read(&mut reader, BranchId::Sprout)
                 .map_err(|e| invalid().detail(e))?;
             let txid = tx.txid().to_string();
@@ -110,7 +109,6 @@ mod tests {
     fn recognizes_coinbase_instead_of_assuming_regular_inputs() {
         let mut request = request();
         let mut bytes = hex::decode(request["transactions"][0]["rawTx"].as_str().unwrap()).unwrap();
-        // The V4 fixture has one transparent input after its eight-byte header.
         bytes[9..41].fill(0);
         bytes[41..45].fill(0xff);
         let tx = Transaction::read(&bytes[..], BranchId::Nu6_2).unwrap();
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
index 60ff408f5..f9b46634a 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
@@ -1,8 +1,7 @@
 //! Stateless transparent transaction quoting, construction, and signing.
 //!
-//! This module deliberately has no wallet database, scanner, or network client. The host supplies
-//! a complete UTXO catalog plus an explicit set of outpoints to spend. Every selected coin is
-//! revalidated against its exact BIP-44 path before a transaction is signed.
+//! The host supplies the UTXO catalog and the outpoints to spend; every selected coin is
+//! revalidated against its exact BIP-44 path before signing.
 
 use std::collections::{HashMap, HashSet};
 
@@ -156,10 +155,7 @@ struct TransactionPlan {
     send_amount: Zatoshis,
 }
 
-/// Authorization marker for a transaction whose only unauthorized component is transparent.
-///
-/// `zcash_primitives::transaction::Unauthorized` is gated behind its `circuits` feature. Using a
-/// local marker keeps the stateless transparent signer free of Sapling and Orchard proving code.
+/// Local marker because upstream `Unauthorized` is gated behind `circuits` (proving code).
 struct TransparentUnauthorized;
 
 impl Authorization for TransparentUnauthorized {
@@ -175,11 +171,8 @@ pub fn quote_json(request_json: &str) -> Result {
         .map_err(|e| KeysError::new(ErrorCode::TransactionBuildFailed).detail(e))
 }
 
-/// Builds with an account-level BIP-44 xprv at `m/44'/133'/account'`.
-///
-/// An account xprv cannot prove its ancestor path. The encoded key metadata is therefore checked
-/// for depth 3 and the expected hardened account index, while the host remains responsible for
-/// obtaining it from the exact `m/44'/133'/account'` path.
+/// An account xprv cannot prove its ancestor path: only depth 3 and the hardened account index are
+/// checked, so the host must derive it from exactly `m/44'/133'/account'`.
 pub fn build_with_account_xprv_json(request_json: &str, account_xprv: &str) -> Result {
     let request = parse_request(request_json)?;
     let plan = plan_transaction(request)?;
@@ -408,16 +401,14 @@ fn plan_transaction(request: TransparentTxRequest) -> Result {
         }
         let change_path =
             parse_derivation_path(&change_request.derivation_path, request.account_index)?;
-        // External-scope change must be the default receive address (/0/0);
-        // internal-scope change is still accepted.
+        // External-scope change must be /0/0.
         if change_path.scope == 0 && change_path.index != 0 {
             return Err(KeysError::with(
                 ErrorCode::InvalidDerivationPath,
                 serde_json::json!({ "field": "change.derivationPath", "reason": "defaultReceiveAddressRequired" }),
             ));
         }
-        // The change index must be within the signer's scan range
-        // (`TRANSPARENT_SCAN_GAP`); change beyond it could never be signed.
+        // Change beyond `TRANSPARENT_SCAN_GAP` could never be signed.
         if change_path.index >= crate::sign::TRANSPARENT_SCAN_GAP {
             return Err(KeysError::with(
                 ErrorCode::InvalidDerivationPath,
@@ -437,12 +428,8 @@ fn plan_transaction(request: TransparentTxRequest) -> Result {
             .ok_or_else(|| amount_error("recipientTotal"))?;
         let change_raw = input_total_raw.saturating_sub(needed_with_change);
 
-        // If change cannot pay for its own output, add it to the fee and send
-        // without change (like upstream `DustAction::AddDustToFee`).
-        //
-        // input_total > send_total + fee_without_change holds here, so the
-        // subtraction cannot underflow and the fee meets the minimum. Overpayment
-        // is bounded by fee_with_change + MARGINAL_FEE.
+        // Dust change goes to the fee (like upstream `AddDustToFee`). The subtraction cannot underflow
+        // because input_total > send_total + fee_without_change here.
         if input_total_raw < needed_with_change || change_raw < MARGINAL_FEE.into_u64() {
             let fee_raw = input_total_raw - send_total_raw;
             (parse_zatoshis_u64(fee_raw, "fee")?, None)
@@ -770,9 +757,7 @@ pub(crate) fn parse_account_xpub(encoded: &str, expected_account: u32) -> Result
         .map_err(|_| invalid())
 }
 
-/// Parses straight from the base58 string: bip32 decodes into a stack buffer it wipes, and
-/// `ExtendedKey` wipes its key bytes on drop. Upstream `AccountPrivKey::from_bytes` is avoided
-/// because it re-encodes the key into a heap string and buffer that are freed unwiped.
+/// Parses straight from base58 so every buffer is wiped; upstream `AccountPrivKey::from_bytes` re-encodes into unwiped heap memory.
 pub(crate) fn parse_account_xprv(
     encoded: &str,
     expected_account: u32,
@@ -1136,7 +1121,6 @@ mod tests {
             );
         }
         request["change"]["derivationPath"] = "m/44'/133'/0'/0/0".into();
-        // The existing internal address is not the declared receive address.
         assert_eq!(
             build_with_account_xprv_json(&request.to_string(), &xprv())
                 .unwrap_err()
@@ -1145,11 +1129,7 @@ mod tests {
         );
     }
 
-    /// Sub-dust change is added to the fee instead of failing.
-    ///
-    /// Sending 88,000 from a 100,000 UTXO: the fee is 10,000 with or without
-    /// change (ZIP-317, 1-in stays within grace 2), and the 2,000 surplus cannot
-    /// fund a change output.
+    /// 88,000 from a 100,000 UTXO: fee is 10,000 either way (ZIP-317 grace), the 2,000 surplus is too small for change.
     #[test]
     fn sub_dust_change_goes_into_the_fee_instead_of_failing() {
         let mut request: serde_json::Value =
@@ -1168,10 +1148,7 @@ mod tests {
         assert_eq!(built.fee_zat, "12000");
     }
 
-    /// A surplus between the two fee tiers is not insufficient funds.
-    ///
-    /// 1-in/3-out: fee_without_change=15,000, fee_with_change=20,000. A 17,000
-    /// surplus cannot fund change, but the no-change transaction is valid.
+    /// 1-in/3-out: fee_without_change=15,000, fee_with_change=20,000; a 17,000 surplus cannot fund change.
     #[test]
     fn surplus_between_the_two_fee_tiers_is_not_reported_as_insufficient_funds() {
         let mut request: serde_json::Value =
@@ -1189,7 +1166,6 @@ mod tests {
         assert_eq!(quote.fee_zat, "17000");
     }
 
-    /// The change index must be within the signer's scan range.
     #[test]
     fn rejects_change_index_outside_the_signing_scan_range() {
         let mut request: serde_json::Value =
@@ -1198,7 +1174,6 @@ mod tests {
         let e = quote_json(&request.to_string()).unwrap_err();
         assert_eq!(e.code, ErrorCode::InvalidDerivationPath);
 
-        // In range is still accepted.
         request["change"]["derivationPath"] = "m/44'/133'/0'/1/39".into();
         assert!(quote_json(&request.to_string()).is_ok());
     }
@@ -1348,13 +1323,11 @@ fn require_transparent(address: RecipientAddress) -> Result
 fn parse_recipient_address(encoded: &str) -> Result {
     match crate::keys::supported_recipient(&MAIN_NETWORK, encoded) {
         Some(Address::Transparent(address)) => Ok(RecipientAddress::Transparent(address)),
-        // ZIP-320: a TEX address is a P2PKH hash that only accepts transparent
-        // inputs, which is all this builder spends.
+        // ZIP-320 TEX: only accepts transparent inputs, which is all this builder spends.
         Some(Address::Tex(hash)) => Ok(RecipientAddress::Transparent(
             TransparentAddress::PublicKeyHash(hash),
         )),
-        // Unified Orchard receivers receive Ironwood notes after NU6.3. Never silently
-        // fall back to a public receiver when a Unified Address lacks this receiver.
+        // Orchard receivers get Ironwood notes after NU6.3; never fall back to a public receiver.
         Some(Address::Unified(address)) => address
             .orchard()
             .copied()
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
index 3e4d23dea..2a173a1f4 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
@@ -14,10 +14,7 @@ use zcash_primitives::transaction::builder::{BuildConfig, Builder, BundlePadding
 use zcash_primitives::transaction::fees::fixed::FeeRule as FixedFeeRule;
 use zcash_protocol::memo::MemoBytes;
 
-/// Entry points this module provides, kept next to the implementation.
-///
-/// Hosts must check these capabilities before calling: older wasm builds lack
-/// the exports entirely, so a direct call fails with `undefined is not a function`.
+/// Hosts check these before calling: older wasm builds lack the exports entirely.
 pub const SHIELD_CREATE_WITH_ACCOUNT_XPRV: bool = true;
 pub const SHIELD_SIGN_WITH_ACCOUNT_XPRV: bool = true;
 
@@ -38,7 +35,7 @@ fn create_with_public_key(plan: &TransactionPlan, key: &AccountPubKey) -> Result
         BuildConfig::Standard {
             sapling_anchor: None,
             orchard_anchor: None,
-            // No shielded spends: the empty anchor needs no scanned commitment tree.
+            // No shielded spends, so the empty anchor needs no commitment tree.
             ironwood_anchor: plan
                 .recipients
                 .iter()
@@ -88,9 +85,7 @@ fn create_with_public_key(plan: &TransactionPlan, key: &AccountPubKey) -> Result
             .add_transparent_output(&address, output.value)
             .map_err(failure)?;
     }
-    // The plan's fee, not a recomputed ZIP-317 one: change below the dust
-    // threshold is folded into the fee at quote time, and the ZIP-317 rule
-    // rejects that surplus as ChangeRequired after the user has approved it.
+    // Use the plan's fee: sub-dust change was folded into it at quote time, and ZIP-317 would reject that with ChangeRequired.
     let parts = builder
         .build_for_pczt(rand::rngs::OsRng, &FixedFeeRule::non_standard(plan.fee))
         .map_err(failure)?;
@@ -145,8 +140,7 @@ fn create_with_public_key(plan: &TransactionPlan, key: &AccountPubKey) -> Result
         .map_err(failure)
 }
 
-/// Builds an unproved PCZT from an account xpub. Device derivation metadata
-/// covers every selected input and the transparent change output.
+/// Unproved PCZT with device derivation metadata on every input and the change output.
 pub fn create_with_account_xpub(
     request_json: &str,
     account_xpub: &str,
@@ -219,8 +213,7 @@ pub fn create_with_account_xpub(
     updated.serialize().map_err(failure)
 }
 
-/// Combines a device's redacted signatures with the approved original, verifies
-/// every signature against the exact request, then finalizes transparent spends.
+/// Verifies the device's signatures against the exact request before finalizing.
 pub fn combine_hardware_signed(
     request_json: &str,
     account_xpub: &str,
@@ -349,8 +342,7 @@ fn validate_ironwood(bundle: &orchard::pczt::Bundle, plan: &TransactionPlan) ->
                 .ok_or_else(mismatch)?;
             approved_memo = expected.remove(index).2;
         }
-        // A matching commitment alone does not ensure the recipient can decrypt the note.
-        // Dummy output ciphertexts may be randomized by the upstream builder.
+        // A matching commitment does not prove the recipient can decrypt the note; dummy outputs are skipped.
         if value.inner() != 0 {
             let note = orchard::Note::from_parts(
                 recipient,
@@ -498,7 +490,7 @@ fn sign_with_key(
         pczt::Pczt::parse(original).map_err(failure)?,
     )?;
     let pczt = pczt::Pczt::parse(pczt).map_err(failure)?;
-    // V6 deliberately excludes anchors from the effects hash (ZIP 374).
+    // V6 excludes anchors from the effects hash (ZIP 374).
     if pczt.ironwood().anchor() != original.ironwood().anchor()
         || pczt.transparent().inputs().len() != plan.inputs.len()
     {
@@ -647,8 +639,7 @@ mod tests {
             .unwrap()
     }
 
-    // 100000 in, 83000/88000 out leaves sub-dust change that the quote folds into
-    // the fee; building must keep that fee instead of failing with ChangeRequired.
+    // 100000 in, 83000/88000 out: sub-dust change folds into the fee instead of ChangeRequired.
     #[test]
     fn a_quote_with_sub_dust_change_folded_into_the_fee_still_builds() {
         let fingerprint = "00".repeat(32);
@@ -878,9 +869,6 @@ mod tests {
         }
     }
 
-    // The device signs a copy without Sapling `bsk` (set by the IO Finalizer
-    // even on the empty bundle) or proving fields, which signing doesn't need;
-    // combining its result into the original gives the same transaction.
     #[test]
     fn hardware_signs_a_copy_without_sapling_or_proving_fields() {
         for transparent_destination in [false, true] {
@@ -954,7 +942,6 @@ mod tests {
         for send_max in [false, true] {
             let request = request(send_max).to_string();
             let original = create(&request).unwrap();
-            // Proof generation is independent of the transparent signing authorization.
             sign(&request, &original, &original).unwrap();
         }
     }
@@ -990,11 +977,7 @@ mod tests {
         }
     }
 
-    /// `pcztSignWithAccountKeys` signs host-supplied PCZTs, and upstream `Signer`
-    /// leaves semantic checks to the caller, so it must enforce `SIGHASH_ALL` itself.
-    ///
-    /// The positive case also pins that a pool with nothing signable is fine: the
-    /// shielding PCZT's Ironwood actions are outputs only.
+    /// Upstream `Signer` does not check semantics, so the generic signer must enforce `SIGHASH_ALL`.
     #[test]
     fn generic_signer_requires_sighash_all_on_transparent_inputs() {
         let keys = crate::account_keys::test_keys::signing_keys(&SEED, 0);
@@ -1035,8 +1018,6 @@ mod tests {
         all
     }
 
-    /// The xprv path and the seed-derived USK produce identical transparent
-    /// signatures (RFC 6979), each valid for its input's sighash.
     #[test]
     fn account_keys_and_seed_oracle_sign_the_same_transparent_inputs() {
         use crate::account_keys::test_keys;
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
index 036693606..47fb7efeb 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
+++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
@@ -45,8 +45,7 @@ futures-util.workspace = true
 sapling.workspace = true
 uuid.workspace = true
 
-# Native targets: add tonic transport (features are additive; wasm is unaffected)
-# so browser issues can be reproduced natively under a debugger.
+# Native only: tonic transport, to reproduce browser issues under a debugger.
 [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
 tonic = { workspace = true, features = ["transport", "tls-ring", "tls-webpki-roots"] }
 tokio = { workspace = true }
@@ -77,8 +76,7 @@ time = { version = "0.3", features = ["wasm-bindgen"] }
 [dev-dependencies]
 futures = "0.3"
 
-# wasm-pack defaults to `wasm-opt -O`; -Oz shrinks further at the cost of build
-# time, with negligible runtime impact on this IO-bound workload.
+# -Oz shrinks further than wasm-pack's default -O, with negligible runtime impact.
 [package.metadata.wasm-pack.profile.release]
 # No --enable-simd: the curve libraries have no SIMD paths, so there is no
 # measurable gain, and it breaks old WebViews.
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/build.rs b/chain-runtimes/zcash/crates/zcash-runtime/build.rs
index 9bf5ef819..e3bcc324b 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/build.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/build.rs
@@ -1,10 +1,6 @@
-//! Links the wasm SQLite build.
-//!
-//! With rusqlite's `bundled` feature removed (see scripts/vendor-deps.sh),
-//! `libsqlite3-sys` emits `-l sqlite3` instead of compiling C sources. On wasm32
-//! the library comes from `sqlite-wasm-rs` as `libwsqlite3.a`; this script copies
-//! it to OUT_DIR as `libsqlite3.a` and adds that to the search path, so no manual
-//! RUSTFLAGS are needed.
+//! Links the wasm SQLite build. With rusqlite's `bundled` feature removed (see
+//! scripts/vendor-deps.sh), `libsqlite3-sys` emits `-l sqlite3`; on wasm32 this
+//! script copies `sqlite-wasm-rs`'s `libwsqlite3.a` to OUT_DIR as `libsqlite3.a`.
 
 use std::path::{Path, PathBuf};
 
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
index 2b1d237f6..22856e5a1 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
@@ -1,5 +1,4 @@
-//! Account import and reads: UFVK import and balances. No private keys,
-//! address derivation or signing on this path.
+//! Account import and reads (UFVK import, balances); no private keys or signing.
 
 use incrementalmerkletree::{frontier::Frontier, Hashable};
 use incrementalmerkletree::{Marking, Retention};
@@ -18,10 +17,7 @@ use crate::network::{self, LightClient};
 use crate::wallet::Db;
 use serde_json::json;
 
-/// Imports an account from a UFVK.
-///
-/// `birthday_height` is the earliest height the account can have received a
-/// note; scanning starts there. Fetches the tree state of the block before it.
+/// Imports an account from a UFVK; scanning starts at `birthday_height`.
 pub async fn import_ufvk(
     db: &mut Db,
     client: &mut LightClient,
@@ -35,10 +31,9 @@ pub async fn import_ufvk(
     let ufvk = UnifiedFullViewingKey::decode(¶ms, ufvk_str)
         .map_err(|e| RuntimeError::new(ErrorCode::InvalidUfvk).detail(e))?;
 
-    // With a seed fingerprint and account index the account is imported as
-    // spending: upstream then puts zip32_derivation on PCZT spends, and
-    // send::mark_wallet_outputs puts it on change outputs (upstream does not),
-    // so signers can find the key and verify change returns to the wallet.
+    // A seed fingerprint plus account index imports the account as spending, so
+    // zip32_derivation is set on PCZT spends and (by send::mark_wallet_outputs) on
+    // change outputs; signers can then verify change returns to the wallet.
     let purpose = match derivation {
         Some((fingerprint_hex, account_index)) => AccountPurpose::Spending {
             derivation: Some(parse_zip32_derivation(fingerprint_hex, account_index)?),
@@ -371,7 +366,6 @@ fn parse_zip32_derivation(fingerprint_hex: &str, account_index: u32) -> Result Result {
     let account_id = parse_account_id(db, account_uuid)?;
 
@@ -383,8 +377,7 @@ pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) ->
         .detail(e)
     })?;
 
-    // No summary before any block is scanned; reported as an error code, with
-    // user-facing text left to the host.
+    // No summary before any block is scanned; reported as an error code, text left to the host.
     let Some(summary) = summary else {
         return Err(RuntimeError::new(ErrorCode::NotSynced));
     };
@@ -404,18 +397,15 @@ pub fn balance_json(db: &Db, account_uuid: &str, policy: ConfirmationsPolicy) ->
     .to_string())
 }
 
-/// `total` (per pool and overall) is upstream's `Balance::total`, which leaves
-/// out notes worth at most the ZIP-317 marginal fee. That value is reported
-/// beside it as `uneconomic`, so a host can show it without changing what
-/// `total` or `spendable` mean.
+/// `total` is upstream's `Balance::total`, which leaves out notes worth at most
+/// the ZIP-317 marginal fee; those are reported separately as `uneconomic`.
 fn balance_value(
     chain_tip: u32,
     fully_scanned_height: u32,
     balances: &AccountBalance,
 ) -> serde_json::Value {
-    // Each pool reports its values with no cross-pool merging: which pools
-    // count as spendable is wallet policy, not chain fact, and per-pool detail is
-    // shown in the UI. The host computes any totals it needs.
+    // Per-pool values, no cross-pool merging: which pools count as spendable is
+    // wallet policy; the host computes any totals.
     let pool = |b: &Balance| {
         serde_json::json!({
             "spendable": u64::from(b.spendable_value()),
@@ -480,11 +470,8 @@ pub fn remove_account(db: &mut Db, account_uuid: &str) -> Result<()> {
     })
 }
 
-/// Finds the account with this UFVK, or returns `"null"`.
-///
-/// This is how to locate an account in the shared database: it holds every
-/// wallet's accounts, and runtime UUIDs change after a purge. The UFVK is the
-/// host's stable unique key.
+/// Finds the account with this UFVK, or returns `"null"`. The UFVK is the host's
+/// stable key; runtime UUIDs change after a purge.
 pub fn account_by_ufvk(db: &Db, ufvk_str: &str) -> Result {
     let params = *db.params();
     let target = UnifiedFullViewingKey::decode(¶ms, ufvk_str)
@@ -515,7 +502,6 @@ pub fn account_by_ufvk(db: &Db, ufvk_str: &str) -> Result {
     Ok("null".to_string())
 }
 
-/// Local account UUIDs as a JSON array.
 pub fn list_accounts_json(db: &Db) -> Result {
     let ids = db.get_account_ids().map_err(|e| {
         RuntimeError::with(
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
index d9e7e5ce3..528dc27a3 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
@@ -1,20 +1,10 @@
 //! Host-facing JS/TS interface.
 //!
-//! ## Conventions
-//!
 //! - Parameters and return values are only string / number / boolean / JSON string.
-//! - No Rust object handles are handed to JS for lifetime management.
-//! - A thrown `Error` carries `code` / `params` / `detail`.
-//!   Branch on `code` (stable error code); fill i18n placeholders from `params`;
-//!   `detail` is for logs only. No user-facing text is produced here; that belongs to the host.
+//! - A thrown `Error` carries `code` / `params` / `detail`; see `error`.
 //! - Every call is a complete round trip: no background tasks, no timers.
 
-// ── Stable contract vs diagnostics ──────────────────────────────────────
-//
-// `diag*` methods are debugging tools, not a stable contract: their signatures may
-// change or they may disappear. The prefix makes dependence on them visible at the call site.
-//
-// All other methods form the wallet contract; changes require a version bump.
+// `diag*` methods are not a stable contract; all others are, and changes require a version bump.
 
 use wasm_bindgen::prelude::*;
 
@@ -30,8 +20,6 @@ pub fn set_request_handler(handler: Option) {
     network::set_request_handler(handler);
 }
 
-// ── Lifecycle ───────────────────────────────────────────────────────────
-
 /// Installs the storage layer. Must be awaited once before any other call. Idempotent.
 #[wasm_bindgen(js_name = init)]
 pub async fn init() -> Result<(), JsValue> {
@@ -105,7 +93,6 @@ pub fn close_wallet() -> Result<(), JsValue> {
 
 /// Configures the lightwalletd endpoint, e.g. `https://host:port`.
 ///
-/// The host chooses the endpoint; this runtime hardcodes no server address.
 /// The endpoint must support gRPC-web. CORS is required only without a host transport.
 #[wasm_bindgen(js_name = setLightwalletdUrl)]
 pub fn set_lightwalletd_url(base_url: &str) -> Result<(), JsValue> {
@@ -113,11 +100,8 @@ pub fn set_lightwalletd_url(base_url: &str) -> Result<(), JsValue> {
     Ok(())
 }
 
-// ── Chain info ──────────────────────────────────────────────────────────
-
 /// Current chain tip height. Requires only `setLightwalletdUrl`, not an open wallet.
 ///
-/// Lets the host pick a new account's birthday before the database exists.
 #[wasm_bindgen(js_name = chainTip)]
 pub async fn chain_tip() -> Result {
     Ok(runtime::with_client(|mut client| async move {
@@ -136,8 +120,6 @@ pub async fn chain_tip_at(base_url: String) -> Result {
     Ok(network::chain_tip(&mut client).await?)
 }
 
-// ── Accounts ────────────────────────────────────────────────────────────
-
 /// Imports a view-only account (UFVK) and returns its UUID.
 ///
 /// `birthdayHeight` is the scan start: the current tip for new accounts, an early enough
@@ -191,7 +173,6 @@ pub fn account_by_ufvk(ufvk: String) -> Result {
 
 /// Per-account sync status, derived from the account birthday and the database's remaining scan ranges.
 ///
-/// Global progress misleads in a shared database: adding an account makes all accounts look unsynced.
 ///
 /// Returns block heights, not a percentage: the upstream progress ratio is over notes in a moving
 /// window and never reaches 100%.
@@ -225,8 +206,6 @@ pub fn account_balance(
     })?)
 }
 
-// ── Scanning ────────────────────────────────────────────────────────────
-
 /// One-time sync preparation: downloads subtree roots for all three pools and updates the chain tip.
 ///
 /// The slowest step of a first sync; exposed separately so the host can show a "preparing" state.
@@ -364,8 +343,6 @@ pub async fn sync_step(
     Ok(progress)
 }
 
-// ── Transaction history ─────────────────────────────────────────────────
-
 /// Paged transaction history as a JSON array. Unmined first, then by height descending.
 ///
 /// Returns neutral facts (value delta, change flag, note counts, timestamps), no
@@ -383,17 +360,13 @@ pub fn transaction_history(
     })?)
 }
 
-// ── Rescan ──────────────────────────────────────────────────────────────
-
 /// Rewinds the wallet to a height so later syncs rescan that range.
 ///
 /// Destructive: scan results above the height are discarded. Returns the actual height
 /// rewound to (upstream may go further back to a commitment tree checkpoint).
 #[wasm_bindgen(js_name = rewindTo)]
 pub fn rewind_to(height: u32) -> Result {
-    // No idle gate: this is how the wallet follows a reorg, and refusing because a
-    // transaction is unmined would pin the account to an abandoned chain.
-    // User-triggered rescans use `queueRescanFrom`, which only requeues ranges.
+    // No idle gate: refusing while a transaction is unmined would pin the account to an abandoned chain.
     let rewound = runtime::with_db(|db| sync::rewind_to(db, height))?;
     runtime::reclaim_storage(storage::RECLAIM_PAGES_AFTER_DELETE);
     Ok(rewound)
@@ -431,8 +404,6 @@ pub async fn rescan_account(account_uuid: String, from_height: u32) -> Result, signed: Vec) -> Result, JsVal
 
 /// Durability barrier after an irreversible step.
 ///
-/// A barrier failure means persistence is unconfirmed, not that the step failed. Both callers
-/// are past the point of no return, so the outcome travels in `params` instead of being replaced
-/// by a generic storage error that would make the host retry or show an on-chain tx as failed.
+/// A failure means persistence is unconfirmed, not that the step failed; callers are past the
+/// point of no return, so a generic storage error would make the host retry or show a sent tx as failed.
 async fn barrier_after_irreversible(params: serde_json::Value) -> Result<(), crate::RuntimeError> {
     storage::durability_barrier().await.map_err(|error| {
         crate::RuntimeError::with(crate::ErrorCode::FinalizeOutcomeUnknown, params).detail(error)
@@ -603,12 +573,9 @@ pub async fn broadcast_transaction(txid: String) -> Result<(), JsValue> {
     Ok(result?)
 }
 
-// ── Storage and diagnostics ─────────────────────────────────────────────
-
 /// Deletes a wallet database file. Irreversible.
 ///
-/// The database is a derived cache: UFVKs and birthdays are kept by the host, so deleting
-/// only forces a rescan. Pending transactions do not block deletion.
+/// The database is a derived cache; deleting only forces a rescan.
 ///
 /// Closes the database first if it is the one currently open.
 /// Returns `true` if deleted, `false` if it did not exist.
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs
index b6c50a559..0a4063718 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs
@@ -1,8 +1,5 @@
-//! In-memory compact block cache.
-//!
-//! `zcash_client_backend::sync::run` needs a `BlockCache`; upstream's `FsBlockDb`
-//! needs a filesystem. Compact blocks are transient (download, scan, discard);
-//! scan results are persisted by `zcash_client_sqlite`. Memory is bounded by the
+//! In-memory compact block cache for `zcash_client_backend::sync::run` (upstream's
+//! `FsBlockDb` needs a filesystem). Blocks are transient; memory is bounded by the
 //! `sync::run` batch size.
 
 use std::collections::BTreeMap;
@@ -96,14 +93,13 @@ impl BlockSource for MemoryBlockCache {
     where
         F: FnMut(CompactBlock) -> Result<(), error::Error>,
     {
-        // Hand out only a contiguous prefix starting at from_height; short reads
-        // are allowed. A gap would surface upstream as `BlockHeightDiscontinuity`,
-        // which `is_continuity_error()` treats as a reorg, so a block missing on
-        // the server would trigger a destructive rewind that hits the same gap again.
+        // Hand out only a contiguous prefix starting at from_height; short reads are
+        // allowed. A gap would surface upstream as `BlockHeightDiscontinuity`, which is
+        // treated as a reorg and would trigger a destructive rewind that hits the same gap.
         //
-        // Collect under the lock and release it before calling back: the callback
-        // writes the wallet and upstream may read this cache again on that path.
-        // `std::sync::Mutex` is not reentrant, so that would deadlock on wasm.
+        // Collect under the lock and release it before calling back: the callback writes
+        // the wallet and upstream may read this cache again, and `std::sync::Mutex` is
+        // not reentrant (deadlock on wasm).
         let selected: Vec = {
             let blocks = self
                 .blocks
@@ -129,9 +125,8 @@ impl BlockSource for MemoryBlockCache {
                 expect = next;
             }
 
-            // A missing start is an error, not an empty batch: upstream treats an
-            // empty batch as success without advancing the queue, so the caller
-            // would re-download the same range until it runs out of batches.
+            // A missing start is an error, not an empty batch: upstream treats an empty
+            // batch as success without advancing, so the range would be re-downloaded forever.
             if out.is_empty() && cap > 0 && !blocks.is_empty() {
                 return Err(error::Error::BlockSource(CacheError(format!(
                     "cache is missing start block {start}; cannot scan from later blocks"
@@ -214,7 +209,6 @@ mod tests {
         );
     }
 
-    /// A missing start must error; an empty batch would read as a successful scan.
     #[test]
     fn missing_start_is_an_error_not_an_empty_batch() {
         let c = MemoryBlockCache::new();
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs
index 4e2f4b8b8..a492cda8d 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs
@@ -1,8 +1,6 @@
-//! Clock.
-//!
-//! `zcash_client_sqlite` timestamps records through a `Clock`. The upstream
-//! `SystemClock` calls `std::time::SystemTime::now()`, which panics on
-//! wasm32-unknown-unknown, so the browser needs its own.
+//! Clock for `zcash_client_sqlite`: upstream's `SystemClock` calls
+//! `SystemTime::now()`, which panics on wasm32-unknown-unknown, so the browser
+//! uses its own.
 
 use std::time::{Duration, SystemTime};
 use zcash_client_sqlite::util::Clock;
@@ -19,7 +17,6 @@ impl Clock for HostClock {
 
 #[cfg(target_arch = "wasm32")]
 fn now_millis() -> u64 {
-    // Milliseconds since the epoch, as f64.
     let ms = js_sys::Date::now();
     if ms.is_finite() && ms > 0.0 {
         ms as u64
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
index 20442ae1d..ce6b68fbb 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
@@ -1,11 +1,7 @@
 //! Error contract.
 //!
-//! The Rust side produces no user-facing text. The host receives a stable error
-//! code plus structured params and renders copy and i18n from the code. Text baked
-//! into wasm would need a rebuild and release (and an app-store review on mobile)
-//! for every wording change.
-//!
-//! ## Host usage
+//! No user-facing text: the host gets a stable error code plus structured params
+//! and renders copy from them.
 //!
 //! ```js
 //! try {
@@ -22,10 +18,7 @@
 //! }
 //! ```
 //!
-//! ## Evolution
-//!
-//! Error codes and param fields are append-only: never change the meaning of or
-//! remove an existing one, since host branching depends on them.
+//! Error codes and param fields are append-only; host branching depends on them.
 
 use serde_json::{json, Map, Value};
 use std::fmt;
@@ -33,7 +26,6 @@ use std::fmt;
 /// Stable error code. Hosts branch on this, never on `detail` text.
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
 pub enum ErrorCode {
-    // ── Lifecycle ──
     /// `init()` not called; storage layer not installed.
     NotInitialized,
     /// The browser lacks the OPFS API the storage needs (an outdated WebView,
@@ -45,7 +37,6 @@ pub enum ErrorCode {
     /// `setLightwalletdUrl()` not called.
     LightwalletdNotConfigured,
 
-    // ── Input validation ──
     /// Network name is not "main" / "test". Params: `{ value }`
     InvalidNetwork,
     /// Database name is empty or contains a path separator. Params: `{ value }`
@@ -68,7 +59,6 @@ pub enum ErrorCode {
     /// Block height out of range. Params: `{ value }`
     InvalidBlockHeight,
 
-    // ── Wallet state ──
     /// Account not found. Params: `{ accountId }`
     AccountNotFound,
     /// No blocks synced yet; wallet summary unavailable.
@@ -76,7 +66,6 @@ pub enum ErrorCode {
     /// Insufficient funds. Params: `{ requiredZat, availableZat }` (when available)
     InsufficientFunds,
 
-    // ── External dependencies ──
     /// lightwalletd network error. Params: `{ operation }`
     NetworkError,
     /// Wallet database error (including schema migration failure). Params: `{ operation }`
@@ -86,16 +75,14 @@ pub enum ErrorCode {
     DatabaseTooNew,
     /// Chain reorg detected. Params: `{ atHeight, suggestedRewindHeight }`
     ///
-    /// A normal event, not a failure: blocks near the tip were replaced. The host
-    /// should `rewindTo` the suggested height and resume syncing.
+    /// Not a failure: the host should `rewindTo` the suggested height and resume.
     ReorgDetected,
     /// An async operation is in flight; the wallet cannot be switched or closed now.
     /// Params: `{ operation }`. With `reason: "pendingSend"`, `rescanAccount` waits
     /// for the account's unmined send before starting over at a later birthday.
     ///
-    /// Concurrency guard: swapping databases mid-operation would silently write
-    /// results to the wrong wallet. Hosts should serialize calls to one runtime or
-    /// retry after the current operation finishes.
+    /// Guards against swapping databases mid-operation, which would write results
+    /// to the wrong wallet.
     WalletBusy,
     /// Invalid scan priority name. Params: `{ value }`
     InvalidScanPriority,
@@ -112,8 +99,7 @@ pub enum ErrorCode {
     /// The node definitively judged the transaction consensus-invalid or expired; it
     /// can never be mined. Params: `{ errorCode }`; `detail` holds the node's message.
     ///
-    /// Unlike `NETWORK_ERROR`, this must not be retried as-is. The transaction is
-    /// already stored; its spent notes return only at the expiry height.
+    /// Unlike `NETWORK_ERROR`, do not retry as-is; the spent notes return only at the expiry height.
     BroadcastRejected,
     /// The node returned an error that does not prove the transaction can never be
     /// mined: it may already be mined or in the mempool (double spend, duplicate
@@ -236,8 +222,7 @@ pub type Result = std::result::Result;
 
 /// JS shape: an `Error` carrying `code` / `params` / `detail`.
 ///
-/// `message` is just the error code; it is not user-facing text. Hosts map `code`
-/// through their own i18n table.
+/// `message` is the error code, not user-facing text.
 #[cfg(target_arch = "wasm32")]
 impl From for wasm_bindgen::JsValue {
     fn from(e: RuntimeError) -> Self {
@@ -260,12 +245,7 @@ impl From for wasm_bindgen::JsValue {
             set("detail", wasm_bindgen::JsValue::from_str(d));
         }
 
-        // Duplicate the same fields under `payload`.
-        //
-        // When the host forwards errors across processes or WebViews, its serializer
-        // only passes a fixed field allowlist that includes `payload` but not `params`
-        // or `detail`. The flat fields are this crate's contract for direct calls;
-        // `payload` carries them across that boundary.
+        // The host's cross-process serializer only passes `payload`, not `params`/`detail`.
         let payload = js_sys::Object::new();
         let pset = |k: &str, v: wasm_bindgen::JsValue| {
             let _ = js_sys::Reflect::set(&payload, &wasm_bindgen::JsValue::from_str(k), &v);
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
index 77fd3984a..ae0d44d5e 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
@@ -1,15 +1,9 @@
 //! Transaction history.
 //!
-//! Upstream `WalletRead::get_tx_history` is test-only (its return type lives in
-//! `testing`), so this reads the `v_transactions` view maintained by
-//! `zcash_client_sqlite`, as the official Android / iOS SDKs do.
+//! Reads the `v_transactions` view maintained by `zcash_client_sqlite`, as the official SDKs do.
 //!
-//! Column names are not checked at compile time: run the `history_smoke` test
-//! after upgrading `zcash_client_sqlite`. Failures are `DATABASE_ERROR` with
-//! `params.operation = "history"`.
-//!
-//! Returns neutral facts (deltas, change, note counts, timestamps); classifying
-//! and labelling transactions is up to the host.
+//! Column names are not checked at compile time; run `history_smoke` after upgrading
+//! `zcash_client_sqlite`. Failures are `DATABASE_ERROR` with `params.operation = "history"`.
 
 use serde_json::json;
 use zcash_address::unified::{self, Container, Encoding};
@@ -20,8 +14,7 @@ use crate::error::{ErrorCode, Result, RuntimeError};
 
 /// Account UUIDs are 16-byte BLOBs in the upstream schema, not text.
 ///
-/// Binding the hyphenated string matches no rows without any error, which is
-/// indistinguishable from an empty wallet.
+/// Binding the hyphenated string silently matches no rows.
 pub(crate) fn uuid_blob(account_uuid: &str) -> Result> {
     uuid::Uuid::parse_str(account_uuid)
         .map(|u| u.as_bytes().to_vec())
@@ -40,8 +33,7 @@ fn db_err(e: impl std::fmt::Display) -> RuntimeError {
     RuntimeError::with(ErrorCode::DatabaseError, json!({ "operation": "history" })).detail(e)
 }
 
-// List and detail share one projection: `row_to_json` has one shape, so a column
-// added to only one query would fail at runtime in the other.
+// List and detail share one projection because `row_to_json` has one shape.
 const HISTORY_ROW_SELECT: &str = "SELECT
          tx_summary.txid,
          tx_summary.mined_height,
@@ -243,22 +235,16 @@ fn row_to_json(row: &rusqlite::Row<'_>) -> rusqlite::Result {
         "receivedNoteCount": row.get::<_, Option>(9)?.unwrap_or(0),
         "memoCount": row.get::<_, Option>(10)?.unwrap_or(0),
         "isShielding": row.get::<_, Option>(11)?.unwrap_or(false),
-        // Account-side amounts. Hosts show sends as spent - received - fee and
-        // self-transfers/shielding as received; balance_delta would show a
-        // shielding transaction as just its fee.
+        // Account-side amounts; balance_delta would show a shielding transaction as just its fee.
         "totalSpentZat": row.get::<_, Option>(12)?,
         "totalReceivedZat": row.get::<_, Option>(13)?,
-        // Exact upstream pool identifiers; the host aggregates as it needs.
         "poolIds": pool_ids,
-        // Signed account-owned value change for each exact pool. This cannot be
-        // recovered from the aggregate row after an Orchard-to-Ironwood move.
+        // Signed value change per pool; not recoverable from the aggregate after an Orchard-to-Ironwood move.
         "perPoolBalanceDeltaZat": per_pool_balance_delta_zat,
         // The trusted node definitively rejected it; it can never be mined.
         "rejected": row.get::<_, bool>(15)?,
         "recipient": recipient,
-        // Outputs sent to addresses outside this account. Zero with spends means
-        // an internal transfer, whether or not the fee is known; inferring from
-        // spent - received misreads self-transfers as sends when the fee is unknown.
+        // Outputs sent outside this account. Zero with spends means an internal transfer.
         "externalOutputCount": row.get::<_, i64>(17)?,
     }))
 }
@@ -294,7 +280,7 @@ pub fn details(conn: &rusqlite::Connection, account_uuid: &str, txid: &str) -> R
 /// Per-output breakdown of one transaction: outputs this account spent,
 /// received, and sent externally.
 ///
-/// Reads `v_tx_outputs`, the per-output view the official SDKs also use:
+/// Reads `v_tx_outputs`:
 ///
 /// - `received`: `to_account_uuid` is this account (`is_change` marks change)
 /// - `external`: sent by this account to an unknown or different account,
@@ -346,9 +332,7 @@ pub fn details_outputs(
             let from_acct: Option> = row.get(6).map_err(db_err)?;
             let payment_address: Option = row.get(7).map_err(db_err)?;
             let created_locally: bool = row.get(8).map_err(db_err)?;
-            // Compact scanning also marks explicit self-payments as change.
-            // A recorded shielded recipient identifies a payment; actual change
-            // has no sent-note recipient address. Keep the scan flags intact.
+            // Compact scanning also marks explicit self-payments as change; real change has no recipient address.
             let is_change = is_change && (pool == 0 || payment_address.is_none());
             let address = payment_address.or(address);
 
@@ -386,9 +370,7 @@ pub fn details_outputs(
 
     let mut spent = Vec::new();
     {
-        // This account's received outputs spent by this transaction. Join on
-        // (pool, id_within_pool_table) = (pool, received_output_id);
-        // `v_received_output_spends` has no output_index.
+        // Join on (pool, id_within_pool_table) = (pool, received_output_id); `v_received_output_spends` has no output_index.
         let mut stmt = conn
             .prepare(
                 "SELECT ro.pool, ro.value, addr.address
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs
index 344f1c367..fd0ed1f86 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs
@@ -1,28 +1,11 @@
 //! # OneKey Zcash Runtime
 //!
-//! A thin binding layer over the official `librustzcash`.
-//!
-//! ## Scope
-//!
-//! Only three things live on this side:
-//!
-//! 1. **Cryptography and protocol**: trial decryption, witness and commitment
-//!    tree maintenance, transaction building and note selection. Costly to move
-//!    across the boundary, and mistakes lose funds.
-//! 2. **Platform glue**: clock, randomness, storage VFS, which std lacks on wasm32.
-//! 3. **Shape conversion**: Rust types to JSON for the host.
-//!
-//! Scheduling, account and birthday management, caching, progress and retries
-//! belong to the host.
-//!
-//! ## Interface
-//!
-//! Few verbs, simple data. Each call is a full round trip; apart from the
-//! database, wasm holds no state across calls.
+//! A thin binding layer over `librustzcash`: cryptography and protocol (trial
+//! decryption, trees, transaction building, note selection), platform glue
+//! (clock, randomness, storage VFS) and Rust-to-JSON shape conversion.
+//! Scheduling, accounts, caching, progress and retries belong to the host. Apart
+//! from the database, wasm holds no state across calls.
 
-// ── All platforms: wallet core ─────────────────────────────────────────
-// Builds on wasm32, aarch64-apple-ios and Android, so mobile can run the full
-// wallet, not just keys.
 pub mod account;
 pub mod blockcache;
 mod circuit_keys;
@@ -35,7 +18,6 @@ pub mod storage;
 pub mod tx_state;
 pub mod wallet;
 
-// Network and sync: gRPC-web in browsers, tonic transport natively.
 pub mod network;
 pub mod sync;
 
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
index 6231338c8..c8a238458 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
@@ -1,7 +1,4 @@
-//! lightwalletd network layer.
-//!
-//! Browsers have no raw HTTP/2, so wasm uses gRPC-web: `tonic-web-wasm-client`
-//! runs the tonic-generated client over fetch.
+//! lightwalletd network layer: gRPC-web on wasm, tonic transport on native.
 //!
 //! Requires `tonic-web-wasm-client` >= 0.9.1; 0.8.0 drops gRPC trailers at stream
 //! end, so streaming calls like `get_block_range` never complete.
@@ -24,8 +21,7 @@ pub fn set_request_handler(handler: Option) {
     REQUEST_HANDLER.with(|slot| *slot.borrow_mut() = handler);
 }
 
-// wasm uses gRPC-web; native uses tonic's own transport. `LightClient` has the
-// same signature on both, so `chain_tip` / `tree_state` etc. need no cfg split.
+// `LightClient` has the same signature on both transports, so callers need no cfg split.
 #[cfg(target_arch = "wasm32")]
 pub type Transport = tonic_web_wasm_client::Client;
 
@@ -39,11 +35,8 @@ fn net_err(operation: &str, e: impl std::fmt::Display) -> RuntimeError {
     RuntimeError::with(ErrorCode::NetworkError, json!({ "operation": operation })).detail(e)
 }
 
-/// Wrap a network future in a timeout.
-///
-/// In wasm the host cannot cancel a hung call (no thread to interrupt, the
-/// Promise never rejects), so a gRPC call that never returns would wedge the
-/// wallet silently. `get_block_range` can hang this way.
+/// Wrap a network future in a timeout; in wasm the host cannot cancel a hung call
+/// (the Promise never rejects), which would wedge the wallet silently.
 #[cfg(target_arch = "wasm32")]
 pub async fn with_timeout(
     fut: impl std::future::Future>,
@@ -61,7 +54,6 @@ pub async fn with_timeout(
     }
 }
 
-/// Native targets use the tokio timer.
 #[cfg(not(target_arch = "wasm32"))]
 pub async fn with_timeout(
     fut: impl std::future::Future>,
@@ -85,7 +77,6 @@ fn timeout_err(operation: &str, timeout_ms: u32) -> RuntimeError {
 pub const DEFAULT_TIMEOUT_MS: u32 = 30_000;
 
 /// Build a lightwalletd client. `base_url` looks like `https://host:port`.
-///
 /// No network round trip; the connection happens on the first call.
 #[cfg(target_arch = "wasm32")]
 pub fn connect(base_url: &str) -> Result {
@@ -95,9 +86,7 @@ pub fn connect(base_url: &str) -> Result {
             json!({ "reason": "emptyUrl" }),
         ));
     }
-    // Plaintext would expose which addresses this wallet queries to anyone on the
-    // path. Require https so a custom node or mistyped fallback URL cannot
-    // silently downgrade.
+    // Require https: plaintext would expose which addresses this wallet queries.
     if !base_url.starts_with("https://") {
         return Err(RuntimeError::with(
             ErrorCode::LightwalletdNotConfigured,
@@ -138,7 +127,6 @@ pub async fn connect_native(base_url: &str) -> Result {
     Ok(CompactTxStreamerClient::new(channel))
 }
 
-/// Current chain tip height.
 pub async fn chain_tip(client: &mut LightClient) -> Result {
     let block = with_timeout(
         async {
@@ -162,12 +150,9 @@ pub async fn chain_tip(client: &mut LightClient) -> Result {
 
 /// Submit a signed transaction to lightwalletd.
 ///
-/// `SendTransaction` does not signal node errors via gRPC status: the call
-/// succeeds but `SendResponse.error_code != 0` means the node did not accept the
-/// transaction.
-///
-/// Definite rejections return `BROADCAST_REJECTED` (not retryable), other node
-/// errors `BROADCAST_OUTCOME_UNKNOWN`, transport failures `NETWORK_ERROR`.
+/// Node rejections arrive as `SendResponse.error_code != 0`, not a gRPC status.
+/// Definite rejections return `BROADCAST_REJECTED`, other node errors
+/// `BROADCAST_OUTCOME_UNKNOWN`, transport failures `NETWORK_ERROR`.
 pub async fn broadcast(client: &mut LightClient, tx_bytes: Vec) -> Result<()> {
     use zcash_client_backend::proto::service::RawTransaction;
 
@@ -189,8 +174,7 @@ pub async fn broadcast(client: &mut LightClient, tx_bytes: Vec) -> Result<()
     .await?;
 
     if resp.error_code != 0 {
-        // Nodes report a transaction they already hold as an error; the node
-        // having the tx is the outcome we want.
+        // A node that already holds the tx is the outcome we want.
         if broadcast_already_known(&resp.error_message) {
             return Ok(());
         }
@@ -211,9 +195,9 @@ pub async fn broadcast(client: &mut LightClient, tx_bytes: Vec) -> Result<()
     Ok(())
 }
 
-/// A rejection that a node also gives for a transaction it already mined or
-/// holds: its inputs are spent, possibly by this very transaction. Marking it
-/// rejected would show a failed send for a payment that went through.
+/// Replies a node also gives for a tx it already mined or holds (inputs spent,
+/// possibly by this very tx); treating them as rejected would show a failed send
+/// for a payment that went through.
 fn broadcast_outcome_ambiguous(message: &str) -> bool {
     let message = message.to_lowercase();
     [
@@ -237,19 +221,15 @@ fn broadcast_outcome_ambiguous(message: &str) -> bool {
 
 /// Only replies proving these bytes can never be mined count as a rejection.
 ///
-/// A rejection makes the host show a failure and the user resend with other
-/// notes (the stored original holds its notes until expiry). If the original
-/// actually propagated, both would be mined. So this is an allowlist:
-/// consensus-invalid (proof, signature, value, branch) or expired. Transient or
-/// policy replies (busy, mempool full, lagging, non-standard) are an unknown
-/// outcome: the tx stays pending until mined or expired.
+/// A rejection lets the user resend with other notes, and both could be mined if
+/// the original propagated. So this is an allowlist (consensus-invalid or expired);
+/// transient or policy replies stay an unknown outcome.
 fn broadcast_definitely_invalid(message: &str) -> bool {
     if broadcast_outcome_ambiguous(message) {
         return false;
     }
     let message = message.to_lowercase();
-    // zcashd: consensus reject reasons from main.cpp. `tx-expiring-soon` is policy
-    // (other nodes may still mine it) and is excluded.
+    // zcashd consensus reject reasons; `tx-expiring-soon` is policy and excluded.
     ["bad-txns-", "bad-tx-", "tx-overwinter-expired"]
         .iter()
         .any(|needle| message.contains(needle))
@@ -271,10 +251,7 @@ fn broadcast_already_known(message: &str) -> bool {
     .any(|needle| message.contains(needle))
 }
 
-/// Fetch the treestate at `height`.
-///
-/// Needed for account import: `AccountBirthday` requires the commitment tree state
-/// preceding the birthday height to compute witnesses for notes received later.
+/// Fetch the treestate at `height`; `AccountBirthday` needs the tree state preceding the birthday.
 pub async fn tree_state(client: &mut LightClient, height: u32) -> Result {
     let ts = with_timeout(
         async {
@@ -302,8 +279,7 @@ mod tests {
     };
     use crate::error::{ErrorCode, RuntimeError};
 
-    // A node gives these for our own tx once it is mined, as well as for a real
-    // conflict; they must stay "unknown" so scanning decides (mined or expired).
+    // A node also gives these for our own mined tx; they must stay unknown so scanning decides.
     #[test]
     fn spent_input_rejections_are_an_unknown_outcome_not_a_rejection() {
         for message in [
@@ -328,8 +304,6 @@ mod tests {
         }
     }
 
-    // Rejection is an allowlist: any uncertain reply is an unknown outcome and
-    // the tx stays pending until mined or expired.
     #[test]
     fn only_consensus_invalid_or_expired_replies_count_as_a_rejection() {
         for message in [
@@ -361,7 +335,6 @@ mod tests {
             "txn-already-known",
             "Transaction already in mempool",
             "transaction already in block chain",
-            // Zebra's wording (zebrad/src/components/mempool/error.rs).
             "transaction already exists in mempool",
             "transaction dropped because it is already queued for download",
         ] {
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs
index f57491fa6..60858b715 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs
@@ -1,8 +1,5 @@
-//! Cross-call runtime state.
-//!
-//! Only the database connection and the lightwalletd client are kept, since
-//! reopening per call would rerun migration checks. No caches, timers or
-//! background tasks.
+//! Cross-call runtime state: the database connection and lightwalletd client
+//! only (reopening per call would rerun migration checks).
 
 use std::cell::{Cell, RefCell};
 
@@ -17,10 +14,8 @@ thread_local! {
     // v_transactions open a separate read connection by name (same VFS, same data).
     static DB_NAME: RefCell> = const { RefCell::new(None) };
 
-    // Async operations hold DB across awaits. If another wallet were opened
-    // meanwhile, putting the old DB back would make later calls hit the wrong
-    // wallet. BUSY refuses wallet switches during an operation; GENERATION
-    // catches any path that awaits without holding BUSY.
+    // Async operations hold DB across awaits. BUSY refuses wallet switches during one;
+    // GENERATION catches any path that awaits without holding BUSY.
     static BUSY: Cell = const { Cell::new(false) };
     static GENERATION: Cell = const { Cell::new(0) };
 
@@ -29,8 +24,8 @@ thread_local! {
     static CLIENT_GENERATION: Cell = const { Cell::new(0) };
 }
 
-/// Sampled before taking the client and compared before putting it back; a
-/// mismatch means the endpoint changed or closed, so the stale client is dropped.
+/// Compared against the value sampled before taking the client; a mismatch means
+/// the endpoint changed or closed, so the stale client is dropped.
 fn client_generation() -> u64 {
     CLIENT_GENERATION.with(Cell::get)
 }
@@ -52,14 +47,10 @@ fn assert_idle(operation: &str) -> Result<()> {
     Ok(())
 }
 
-/// Sets BUSY while held and always clears it on drop, including early returns
-/// and panic unwinds.
+/// Sets BUSY while held and always clears it on drop, including panic unwinds.
 ///
-/// A wasm-bindgen `async fn` body starts after the current synchronous block,
-/// so an `openWallet` before it runs is not refused and the operation runs on
-/// the new wallet; the host serializes that window. During awaits BUSY blocks
-/// switching or closing, and the generation check keeps a stale wallet from
-/// overwriting the current one.
+/// A wasm-bindgen `async fn` body starts after the current synchronous block, so
+/// an `openWallet` before it runs is not refused; the host serializes that window.
 struct BusyGuard {
     generation: u64,
 }
@@ -69,13 +60,11 @@ impl BusyGuard {
         assert_idle(operation)?;
         BUSY.with(|b| b.set(true));
         Ok(Self {
-            // Sampled when DB is taken: a switch before this is not stale (the
-            // operation just runs on the new wallet); one after is.
+            // Sampled when DB is taken: a switch after this makes the operation stale.
             generation: GENERATION.with(Cell::get),
         })
     }
 
-    /// Whether the wallet was switched or closed since the operation started.
     fn stale(&self) -> bool {
         self.generation != GENERATION.with(Cell::get)
     }
@@ -147,10 +136,8 @@ pub fn set_client(client: LightClient) {
     bump_client_generation();
 }
 
-/// Lends the database for a synchronous operation.
-///
-/// Take, use, put back rather than holding a `RefCell` borrow, so reentry from
-/// `f` does not panic.
+/// Lends the database for a synchronous operation: take, use, put back rather
+/// than hold a `RefCell` borrow, so reentry from `f` does not panic.
 pub fn with_db(f: impl FnOnce(&mut Db) -> Result) -> Result {
     let mut db = DB
         .with(|c| c.borrow_mut().take())
@@ -161,15 +148,12 @@ pub fn with_db(f: impl FnOnce(&mut Db) -> Result) -> Result {
 }
 
 /// Lends the database and client for an async operation (sync, account import).
-///
-/// No `RefCell` borrow is held across awaits.
 pub async fn with_db_and_client(f: F) -> Result
 where
     F: FnOnce(Db, LightClient) -> Fut,
     Fut: std::future::Future)>,
 {
-    // No await between acquiring the guard and taking DB, so the generation is
-    // sampled at the moment DB is taken; staleness relies on this.
+    // No await between acquiring the guard and taking DB: staleness relies on it.
     let guard = BusyGuard::acquire("walletOperation")?;
     let client_gen = client_generation();
     let db = DB.with(|c| c.borrow_mut().take()).ok_or_else(not_open)?;
@@ -196,9 +180,7 @@ where
 
 /// Lends only the client; no wallet needs to be open.
 ///
-/// New accounts need the chain tip for their birthday before the database
-/// exists. Requiring an open wallet here would fall back to the Sapling
-/// activation birthday and force a full scan.
+/// New accounts need the chain tip for their birthday before the database exists.
 pub async fn with_client(f: F) -> Result
 where
     F: FnOnce(LightClient) -> Fut,
@@ -218,10 +200,8 @@ pub fn open_db_name() -> Option {
     DB_NAME.with(|c| c.borrow().clone())
 }
 
-/// Closes the wallet, releasing the database and client (account removal,
-/// network switch).
-///
-/// Refused during an async operation, which holds DB and would put it back.
+/// Closes the wallet, releasing the database and client. Refused during an async
+/// operation, which holds DB and would put it back.
 pub fn close() -> Result<()> {
     assert_idle("closeWallet")?;
     DB.with(|c| *c.borrow_mut() = None);
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
index 113b38ca4..0ea8a1bf7 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
@@ -1,6 +1,6 @@
 //! Sending: PCZT construction and broadcast.
 //!
-//! Four stages; signing is not in this crate:
+//! Signing is not in this crate:
 //!
 //! ```text
 //!   runtime.pcztCreate()          build (needs wallet state: note selection, witness, anchor)
@@ -9,12 +9,7 @@
 //!   runtime.pcztSubmit()          extract, store, broadcast once (sync does not rebroadcast)
 //! ```
 //!
-//! Key separation: build and broadcast need the wallet database, signing needs
-//! the spending keys; the two never live in the same crate.
-//!
-//! Note selection, ZIP-317 fees, anchors and witnesses stay in the upstream
-//! implementation; policy knobs (change pool, confirmations, bundle padding)
-//! come from the host.
+//! Build and broadcast need the wallet database, signing needs the spending keys; they never share a crate.
 
 use zcash_client_backend::data_api::wallet::{
     create_pczt_from_proposal, extract_and_store_transaction_from_pczt,
@@ -39,11 +34,8 @@ fn build_err(stage: &str, e: impl std::fmt::Display) -> RuntimeError {
 
 /// Maps proposal failures to error codes the host can branch on.
 ///
-/// Upstream reports insufficient funds from two places:
-///
-/// - `Error::InsufficientFunds`: selection cannot cover the amount (transfers)
-/// - `Error::Change(ChangeError::InsufficientFunds)`: selection succeeded but
-///   change plus fee does not fit (shielding)
+/// Upstream reports insufficient funds from `Error::InsufficientFunds` (selection) and
+/// `Error::Change(ChangeError::InsufficientFunds)` (change plus fee does not fit).
 fn propose_err(
     stage: &str,
     e: zcash_client_backend::data_api::error::Error,
@@ -66,7 +58,6 @@ where
             json!({
                 "availableZat": have,
                 "requiredZat": need,
-                // Precomputed so the host does not subtract in the wrong direction.
                 "shortfallZat": need.saturating_sub(have),
                 "stage": stage,
             }),
@@ -128,19 +119,16 @@ pub struct SendPolicy {
     pub untrusted: u32,
     /// Shielded pool for change when the transaction is fully transparent.
     pub fallback_change_pool: ShieldedPool,
-    /// Pad the Orchard bundle to a fixed action count (hides the real count at
-    /// the cost of a larger transaction and higher fee).
+    /// Pad the Orchard bundle to hide the real action count (larger transaction, higher fee).
     pub pad_orchard_bundle: bool,
     /// Allow spending zero-conf outputs of our own shielding (ZIP-315 recommends it).
     ///
-    /// Must match the balance query's setting, or the balance shows funds that
-    /// selection refuses to spend.
+    /// Must match the balance query's setting.
     pub allow_zero_conf_shielding: bool,
     /// Select notes only from this shielded pool. Required: `None` is rejected at build.
     ///
-    /// Excludes Sapling, which upstream `SpendPolicy::default()` would select
-    /// first for old accounts and then fail to prove. If the pool cannot cover the
-    /// amount the result is `InsufficientFunds`; pools are never crossed.
+    /// Excludes Sapling, which upstream `SpendPolicy::default()` would select and then fail to prove.
+    /// Pools are never crossed: an uncovered amount is `InsufficientFunds`.
     pub spend_source: Option,
 }
 
@@ -519,9 +507,8 @@ fn circuit_version_for(
     }
 }
 
-/// The transaction's own branch decides, not our tip: around an upgrade the two
-/// disagree, and a proof under the wrong circuit is rejected. The tip is only
-/// the fallback for a branch id this build does not know.
+/// The transaction's own branch decides, not the tip: around an upgrade they disagree and a
+/// proof under the wrong circuit is rejected. The tip is only the fallback for an unknown branch id.
 fn circuit_version_for_branch(
     params: &zcash_protocol::consensus::Network,
     consensus_branch_id: u32,
@@ -1358,8 +1345,7 @@ mod combine_tests {
         );
     }
 
-    // Hardware signers get a copy without the Sapling `bsk` (see the keys
-    // runtime's `redact_for_hardware_signer`); the original keeps it.
+    // Hardware signers get a copy without the Sapling `bsk`; the original keeps it.
     #[test]
     fn combine_restores_sapling_bsk_from_the_original() {
         let original = transparent_pczt(90_000, 0xaa, false);
@@ -1866,7 +1852,6 @@ mod owned_output_tests {
             let parsed = pczt::Pczt::parse(&bytes).unwrap();
             assert_eq!(parsed.clone().serialize().unwrap(), bytes);
 
-            // Same loop as zcash-keys-runtime sign_pczt_with_account_keys.
             let ask = SpendAuthorizingKey::from(&spending_key(&SEED, ACCOUNT));
             let actions = parsed.orchard().actions().len();
             let mut signer = Signer::new(parsed).unwrap();
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs
index 80a1354c7..5921ef1cf 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs
@@ -1,12 +1,9 @@
-//! Storage usage stats. Read-only, fixed SQL.
-//!
-//! Reports bytes per data group.
+//! Storage usage stats: read-only, fixed SQL, bytes per data group.
 //!
 //! There is deliberately no arbitrary-SQL entry point: one bad statement could
-//! delete anchors still needed for proving.
-//!
-//! Table and column names must match the migrated `zcash_client_sqlite` schema.
-//! A wrong column name can yield NULL under some aggregates instead of an error.
+//! delete anchors still needed for proving. Table and column names must match the
+//! migrated `zcash_client_sqlite` schema; a wrong column can yield NULL under some
+//! aggregates instead of an error.
 
 use crate::error::{ErrorCode, Result, RuntimeError};
 use rusqlite::Connection;
@@ -83,8 +80,7 @@ pub fn storage_stats(conn: &Connection) -> Result {
         "scan": {
             "minHeight": opt_i64(conn, "SELECT MIN(height) FROM blocks", "minHeight")?,
             "maxHeight": opt_i64(conn, "SELECT MAX(height) FROM blocks", "maxHeight")?,
-            // Grows linearly with scanned blocks. Rows hold height/hash/time and
-            // per-pool tree sizes and action counts, not compact blocks.
+            // Grows linearly with scanned blocks; rows are small block metadata, not compact blocks.
             "blockRows": count(conn, "SELECT COUNT(*) FROM blocks", "blockRows")?,
             "rangeRows": count(conn, "SELECT COUNT(*) FROM scan_queue", "rangeRows")?,
         },
@@ -218,7 +214,6 @@ mod tests {
         let out = storage_stats(&conn).expect("storage stats");
         let v: Value = serde_json::from_str(&out).expect("valid JSON");
 
-        // An empty database still reports every field.
         for group in [
             "sqlite",
             "scan",
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
index 2f5f34fee..0c81d0f18 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
@@ -1,8 +1,5 @@
-//! Shared SQLite storage for every App carrier.
-//!
-//! WASM runs in a dedicated Worker and uses the same OPFS synchronous-access
-//! VFS on desktop, web, extension, and mobile WebEmbed, so SQLite reads pages
-//! on demand. Native builds are for Rust tests and diagnostics.
+//! Shared SQLite storage: an OPFS sync-access VFS in a Worker for every browser
+//! carrier. Native builds are for Rust tests and diagnostics.
 
 use crate::error::{ErrorCode, Result, RuntimeError};
 use serde_json::json;
@@ -33,9 +30,8 @@ fn persistent_vfs() -> Result Option<&'static str> {
     use wasm_bindgen::JsValue;
@@ -95,9 +91,8 @@ pub async fn install_persistent_vfs() -> Result<()> {
         // Two network databases plus their rollback journals and spare handles.
         initial_capacity: 6,
     };
-    // Worker termination is asynchronous in browsers. Retry only acquiring
-    // ownership, before opening SQLite or dispatching any wallet operation.
-    // A live owner still fails after the bounded handoff window.
+    // Worker termination is asynchronous: retry only acquiring ownership, before
+    // opening SQLite. A live owner still fails after the bounded handoff window.
     let mut retries = 20;
     let util = loop {
         match install::(&cfg, true).await {
@@ -141,8 +136,7 @@ pub async fn install_persistent_vfs() -> Result<()> {
 }
 
 /// COMMIT already syncs through the VFS under synchronous=FULL, so there is no
-/// write queue to drain; this only checks the storage is still usable before
-/// finalization and broadcast.
+/// write queue to drain; this only checks the storage is still usable.
 pub async fn durability_barrier() -> Result<()> {
     if requires_worker_restart() {
         return Err(RuntimeError::with(
@@ -215,8 +209,7 @@ pub const RECLAIM_PAGES_PER_STEP: u32 = 512;
 pub const RECLAIM_PAGES_AFTER_DELETE: u32 = 4096;
 
 /// Hands up to `max_pages` free pages back to the file system and returns how
-/// many it reclaimed. Rescans and removals otherwise leave a file that only
-/// grows. Databases created before auto_vacuum was set report 0.
+/// many it reclaimed. Databases created before auto_vacuum was set report 0.
 pub fn reclaim_free_pages(conn: &rusqlite::Connection, max_pages: u32) -> Result {
     let mode: i64 = conn.query_row("PRAGMA auto_vacuum", [], |r| r.get(0))?;
     // 2 = INCREMENTAL.
@@ -248,7 +241,6 @@ pub async fn database_exists(db_name: &str) -> Result {
     Ok(std::path::Path::new(db_name).exists())
 }
 
-/// Delete a closed database.
 #[cfg(target_arch = "wasm32")]
 pub async fn delete_database(db_name: &str) -> Result {
     persistent_vfs()?
@@ -298,7 +290,6 @@ mod tests {
         (pages, free)
     }
 
-    /// A rescan or removal frees pages that only a reclaim gives back.
     #[test]
     fn reclaims_freed_pages_in_bounded_batches() {
         let path = std::env::temp_dir().join("zr-reclaim-free-pages.sqlite");
@@ -326,7 +317,6 @@ mod tests {
         let _ = std::fs::remove_file(&path);
     }
 
-    /// Too few free pages to be worth a write transaction.
     #[test]
     fn leaves_a_small_freelist_alone() {
         let path = std::env::temp_dir().join("zr-reclaim-small-freelist.sqlite");
@@ -356,8 +346,7 @@ mod tests {
         let _ = std::fs::remove_file(&path);
         let name = path.to_str().unwrap();
 
-        // Same steps as wallet::open_and_migrate, keeping the connection so it
-        // can be asked afterwards: migrations must not turn the pragma off.
+        // Same steps as wallet::open_and_migrate; migrations must not turn the pragma off.
         for _ in 0..2 {
             let mut conn = open_connection(name).expect("open");
             {
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
index c6f80617b..8d8d583b7 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
@@ -1,13 +1,9 @@
 //! Chain scanning with bounded progress.
 //!
-//! `zcash_client_backend::sync::run` loops until fully synced (`batch_size` only
-//! sizes each batch), so callers cannot interrupt, observe progress, or yield the
-//! main thread. This module drives the upstream public APIs in two parts:
+//! Upstream `sync::run` loops until fully synced, so this module drives the upstream APIs in two parts:
 //!
 //! - [`prepare`]: one-off setup (subtree roots, chain tip). Slow; once per sync.
 //! - [`step`]: scans at most `max_batches` batches, then returns progress.
-//!
-//! The host decides whether to call again.
 
 use std::collections::{HashMap, HashSet};
 use std::hash::Hash;
@@ -37,14 +33,12 @@ use crate::network::LightClient;
 use crate::wallet::Db;
 
 /// Bound speculative scanning to the earlier Ironwood / Orchard tail, capped at 30 days.
-/// `pick_range` also floors the cut at the upstream ChainTip start. Note-shard
-/// completion and reorg safety can extend this window.
+/// Note-shard completion and reorg safety can extend this window.
 const FAST_WINDOW_MAX_BLOCKS: u32 = 34_560;
 const FAST_WINDOW_REORG_MARGIN: u32 = 200;
 
-/// Keep upstream Verify / FoundNote / OpenAdjacent handling. Only partition ChainTip:
-/// its suffix runs in the fast lane, its prefix joins Historic in ascending order.
-/// Keep the original priority on returned ranges for progress attribution.
+/// Keeps upstream Verify / FoundNote / OpenAdjacent handling; only ChainTip is split into a
+/// fast-lane suffix and a Historic prefix. Returned ranges keep their original priority.
 fn pick_range(
     suggested: &[ScanRange],
     preferred: Option,
@@ -84,8 +78,7 @@ fn pick_range(
             }
         })
         .min_by_key(|r| {
-            // Upstream orders equal-priority ranges by height as well. In particular,
-            // Historic and demoted ChainTip ranges must share one ascending lane.
+            // Historic and demoted ChainTip ranges share one ascending lane.
             r.block_range().start
         })
 }
@@ -120,10 +113,8 @@ fn window_start(db: &mut Db) -> Result {
             .max(tip.saturating_sub(FAST_WINDOW_MAX_BLOCKS))
             .min(tip.saturating_sub(FAST_WINDOW_REORG_MARGIN));
 
-        // A newly discovered note can span the cut. Complete its entire shard before
-        // moving on, even when its below-window ranges still have ChainTip priority
-        // and therefore cannot be promoted to FoundNote by upstream. Repeat because
-        // extending one pool's window can expose an overlapping shard in the other.
+        // A new note can span the cut: complete its shard, repeating because extending
+        // one pool's window can expose an overlapping shard in the other.
         loop {
             let before = start;
             for pool in ["orchard", "ironwood"] {
@@ -182,8 +173,7 @@ fn roots_cover(db: &mut Db, state: &ChainState) -> Result {
     .map_err(|e: rusqlite::Error| db_err("fastWindowRoots", e))
 }
 
-/// When the server's roots lag, use upstream's original ChainTip start until
-/// sequential scanning has filled the gap. Never retry the impossible jump forever.
+/// When the server's roots lag, fall back to upstream's ChainTip start until sequential scanning fills the gap.
 fn guard_fast_range(
     db: &mut Db,
     suggested: &[ScanRange],
@@ -251,7 +241,6 @@ pub fn parse_priority(name: &str) -> Result> {
 /// Suggested rewind depth on reorg.
 ///
 /// Too deep forces a long rescan, too shallow may not pass the fork point.
-/// Hosts may increase it on repeated failures.
 const REORG_REWIND_BLOCKS: u32 = 10;
 
 fn net_err(operation: &str, e: impl std::fmt::Display) -> RuntimeError {
@@ -393,7 +382,6 @@ pub async fn step(
 
     let mut batches_done = 0u32;
     let mut blocks_scanned = 0u64;
-    // Per-phase timings: in the browser slow download and slow scan look identical.
     let (mut ms_download, mut ms_treestate, mut ms_scan) = (0.0f64, 0.0f64, 0.0f64);
     let (mut scanned_from, mut scanned_to) = (None::, None::);
     let mut scanned_priority: Option = None;
@@ -438,11 +426,8 @@ pub async fn step(
 
         let t_start = now_ms();
 
-        // Download: on failure retry the same batch once, then halve, down to 32 blocks.
-        //
-        // In the 2022 spam range (heights ~1.71M-1.95M) a 500-block batch can be
-        // tens of MB and never finish on slow links. The successful size is
-        // remembered across calls and grown back after successes.
+        // On failure retry the same batch once, then halve down to 32 blocks (500 blocks
+        // can be tens of MB in the 2022 spam range). The working size is remembered.
         const MIN_DOWNLOAD_BATCH: u32 = 32;
         thread_local! {
             static DOWNLOAD_BATCH_HINT: std::cell::Cell =
@@ -479,8 +464,7 @@ pub async fn step(
                 }
             }
         };
-        // Grow one step only after three consecutive full batches at the remembered
-        // size, so the hint does not oscillate back into timeouts.
+        // Grow only after three consecutive full batches, to avoid oscillating back into timeouts.
         if attempt_len < initial_len {
             DOWNLOAD_BATCH_HINT.with(|h| h.set(attempt_len));
             DOWNLOAD_BATCH_STREAK.with(|s| s.set(0));
@@ -524,15 +508,14 @@ pub async fn step(
         batches_done += 1;
     }
 
-    // Compact blocks lack full outgoing amounts, fees and memos. Enrich only on
-    // historic or lane-less steps to keep the per-turn network budget bounded.
+    // Compact blocks lack outgoing amounts, fees and memos; enrich only on historic or
+    // lane-less steps to bound the per-turn network budget.
     let enhancement = if preferred.is_none() || preferred == Some(ScanPriority::Historic) {
         enhance_transactions(db, client, active_ufvks).await
     } else {
         Ok(0)
     };
 
-    // Re-query to report remaining work for the host progress bar.
     let remaining = db
         .suggest_scan_ranges()
         .map_err(|e| db_err("suggestScanRanges", e))?;
@@ -547,7 +530,6 @@ pub async fn step(
         "blocksScanned": blocks_scanned,
         "remainingBlocks": remaining_blocks,
         "remainingRanges": remaining.len(),
-        // Range and priority actually scanned, so the host attributes progress to the right lane.
         "scannedFrom": scanned_from,
         "scannedTo": scanned_to,
         "scannedPriority": scanned_priority,
@@ -558,8 +540,7 @@ pub async fn step(
     .to_string())
 }
 
-// Decrypts with active identities only; upstream decrypt_and_store_transaction
-// would try every stored UFVK, including paused accounts.
+// Decrypts with active identities only; upstream would try every stored UFVK, including paused accounts.
 
 async fn enhance_transactions(
     db: &mut Db,
@@ -696,10 +677,8 @@ fn parse_enhancement(data: &[u8], branch: BranchId, expected: TxId) -> Result(
     params: &zcash_protocol::consensus::Network,
     cache: &MemoryBlockCache,
@@ -819,9 +798,7 @@ fn orchard_only_ufvk(
 
 /// Sync completeness for a single account. No network requests.
 ///
-/// All accounts in a shared database share one scan queue, so whole-database
-/// progress is misleading per account. Only pending ranges above this account's
-/// birthday count; ranges below it belong to other accounts' history.
+/// Only pending ranges above this account's birthday count; the scan queue is shared.
 pub fn account_status(db: &Db, account_uuid: &str) -> Result {
     let account_id = crate::account::parse_account_id(db, account_uuid)?;
     let birthday = u32::from(
@@ -847,7 +824,6 @@ pub fn account_status(db: &Db, account_uuid: &str) -> Result {
 
     let (chain_tip, fully_scanned) = scan_heights(db)?;
 
-    // Scanned height = lowest pending height for this account, else the chain tip.
     let scanned_to = lowest_pending.or(chain_tip);
 
     Ok(json!({
@@ -923,8 +899,7 @@ fn now_ms() -> f64 {
 
 /// Anchor at `start - 1`, but not below Sapling activation.
 ///
-/// lightwalletd has no treestate below it, and its error reply hangs the wasm
-/// gRPC call forever instead of failing, so clamp before requesting.
+/// lightwalletd has no treestate below it and its error reply hangs the wasm gRPC call.
 fn anchor_height(params: &zcash_protocol::consensus::Network, start: BlockHeight) -> u32 {
     let sapling = params
         .activation_height(NetworkUpgrade::Sapling)
@@ -940,9 +915,8 @@ const DOWNLOAD_SOFT_BUDGET_MS: f64 = 30_000.0;
 /// Stream a block range into the cache; returns the number of blocks stored
 /// (a contiguous prefix).
 ///
-/// Each stream item has its own DEFAULT_TIMEOUT_MS stall timeout. A stall before
-/// any block arrives is an error (caller retries or halves); a later stall, like
-/// the budget, truncates.
+/// Each stream item has its own DEFAULT_TIMEOUT_MS stall timeout. A stall before any block
+/// is an error; a later stall, like the budget, truncates.
 
 async fn download_batch(
     client: &mut LightClient,
@@ -1041,12 +1015,9 @@ fn check_block_sequence(
 
 /// Rewind the wallet to `height` so later syncs rescan above it.
 ///
-/// Destructive: scan results above the height (notes, witnesses, commitment tree
-/// checkpoints) are discarded. Broadcast transactions are unaffected on chain,
-/// but local unconfirmed records may be lost.
-///
-/// Returns the actual height, which may be lower than requested because of
-/// checkpoint positions.
+/// Destructive: notes, witnesses and commitment tree checkpoints above the height are
+/// discarded, and local unconfirmed records may be lost. Returns the actual height,
+/// which may be lower because of checkpoint positions.
 pub fn rewind_to(db: &mut Db, height: u32) -> Result {
     let target = BlockHeight::from_u32(height);
     let actual = db
@@ -1057,9 +1028,8 @@ pub fn rewind_to(db: &mut Db, height: u32) -> Result {
 
 /// Re-queues an inclusive block range without truncating cached wallet state.
 ///
-/// Used when a paused UFVK becomes active again: the shared scan queue may have advanced
-/// past its pause point. The host passes the first height to trial-decrypt again, with a
-/// reorg margin applied.
+/// Used when a paused UFVK becomes active again, since the shared scan queue may have
+/// advanced past its pause point.
 pub fn queue_rescan_from(db: &mut Db, from_height: u32) -> Result {
     let Some(tip) = db
         .chain_height()
@@ -1185,10 +1155,8 @@ mod tests {
     fn anchor_never_precedes_sapling_activation() {
         for net in [Network::MainNetwork, Network::TestNetwork] {
             let sapling = u32::from(net.activation_height(NetworkUpgrade::Sapling).unwrap());
-            // Far below Sapling: must clamp to activation or gRPC hangs
             assert_eq!(anchor_height(&net, BlockHeight::from_u32(1)), sapling);
             assert_eq!(anchor_height(&net, BlockHeight::from_u32(sapling)), sapling);
-            // Normally start - 1
             let h = sapling + 1000;
             assert_eq!(anchor_height(&net, BlockHeight::from_u32(h)), h - 1);
         }
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs
index 932b1be1c..7377ebdf9 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs
@@ -1,9 +1,6 @@
-//! Offline regression tests through the production scanner and wallet database.
-//! Deterministic synthetic chain, generated in memory without network, files or
-//! proving parameters. The layout and compact-note construction are adapted from
-//! the upstream TestBuilder experiment that produced the former binary fixtures.
-//! There are 501 blocks, three accounts, both Orchard and Ironwood receives and
-//! spends, a completed shard in each pool (including Sapling), and a 35-block fork.
+//! Offline regression tests through the production scanner and wallet database,
+//! on a deterministic in-memory synthetic chain (501 blocks, three accounts,
+//! Orchard and Ironwood, a completed shard per pool, a 35-block fork).
 
 use super::*;
 use std::collections::BTreeMap;
@@ -63,9 +60,9 @@ fn random_hash(rng: &mut ChaCha20Rng) -> H {
     }
 }
 
-/// Like TestBuilder's random_with_prior_subtree_roots, construct a pruned
-/// frontier with distinct completed roots and matching high-level ommers.
-/// Only O(depth + completed shards) hashes are needed for the historical tree.
+/// Builds a pruned frontier with distinct completed roots and matching ommers
+/// (like TestBuilder's random_with_prior_subtree_roots); only O(depth + completed
+/// shards) hashes are needed.
 fn initial_tree(
     rng: &mut ChaCha20Rng,
     size: u32,
@@ -1076,9 +1073,8 @@ fn add_account_rewind_and_pause_resume_match_a_fresh_scan() {
     finish(&mut reference, f, Order::Ascending, 53, &f.keys);
     let expected = snapshot(&mut reference, f);
     let mut db = wallet(f, &[0]);
-    // Isolate rewind/resume from upstream's separate sparse-checkpoint failure
-    // on consecutive old-account imports (also reproduced with the original
-    // order and 53-block batches); one-block checkpoints permit both imports.
+    // Isolates rewind/resume from upstream's sparse-checkpoint failure on consecutive
+    // old-account imports; one-block checkpoints permit both imports.
     finish(&mut db, f, Order::Window, 1, &f.keys[..1]);
     import(&mut db, f, 1, 20);
     import(&mut db, f, 2, 30);
@@ -1251,7 +1247,6 @@ fn safe_birthday_rescan_retains_pending_raw_rejections_and_other_identities() {
 
 #[test]
 fn a_later_birthday_starts_the_account_over_at_that_height() {
-    // Notes of one account, independent of internal ids.
     fn notes_of(db: &mut Db, account: &str) -> Vec {
         let uuid = account.replace('-', "");
         ["orchard", "ironwood"]
@@ -1421,8 +1416,8 @@ fn deep_reorg_and_verify_converge_to_the_new_chain() {
         db.update_chain_tip(height(fork.tip)).unwrap();
         let error = scan(&mut db, &fork, f.tip + 1, 1, &f.keys).unwrap_err();
         assert_eq!(error.code, ErrorCode::ReorgDetected);
-        // The fork is 35 blocks below the old tip: repeated host rewinds must
-        // reach it without the old shardtree Insert(Conflict) failure.
+        // The fork is 35 blocks below the old tip: repeated rewinds must reach it
+        // without the shardtree Insert(Conflict) failure.
         let mut at = error.params["suggestedRewindHeight"].as_u64().unwrap() as u32;
         loop {
             let actual = rewind_to(&mut db, at).unwrap();
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
index cbd9359d7..b8ad03491 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
@@ -1,12 +1,9 @@
 //! OneKey-owned record of node rejections.
 //!
-//! Everything else about a sent transaction lives in `zcash_client_sqlite`:
-//! the signed transaction is stored before broadcast, and stays in
-//! `v_transactions` as unmined (holding its notes) until it is mined or
-//! expires. The one fact the wallet schema cannot hold is that the trusted node
-//! definitively rejected it; that must stop any resend and show the send as
-//! failed. An unmined send that was not rejected stays pending until mined or
-//! expired; the host does not resubmit it.
+//! The wallet schema cannot hold that the trusted node definitively rejected a
+//! send; that must stop any resend and show the send as failed. An unmined send
+//! that was not rejected stays pending until mined or expired; the host does not
+//! resubmit it.
 
 use std::collections::HashSet;
 
@@ -26,13 +23,12 @@ const LIFECYCLE_MIGRATION_ID: Uuid = Uuid::from_u128(0x5be0af90_63f4_43ea_ae65_8
 const REJECTIONS_MIGRATION_ID: Uuid = Uuid::from_u128(0x0d3b6f2e_9a41_4c8e_b7d5_3e1f6a2c9b70);
 pub(crate) const TABLE: &str = "ext_onekey_tx_state";
 
-/// External migrations, in dependency order.
 pub fn migrations() -> Vec>> {
     vec![Box::new(LifecycleMigration), Box::new(RejectionsMigration)]
 }
 
-/// The original lifecycle table. Kept so databases that already applied it
-/// keep a consistent migration graph; `RejectionsMigration` replaces it.
+/// The original lifecycle table, kept so databases that applied it keep a
+/// consistent migration graph; `RejectionsMigration` replaces it.
 struct LifecycleMigration;
 
 impl schemerz::Migration for LifecycleMigration {
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
index 1979cd85a..67ed58572 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
@@ -1,7 +1,4 @@
-//! Opening and initializing the wallet database.
-//!
-//! Connects storage, builds the `WalletDb` and runs schema migrations. All
-//! wallet protocol logic comes from `zcash_client_sqlite` / `zcash_client_backend`.
+//! Opening and initializing the wallet database: storage, `WalletDb` and schema migrations.
 
 use std::collections::{BTreeSet, HashSet};
 
@@ -18,7 +15,6 @@ use crate::error::{ErrorCode, Result, RuntimeError};
 use crate::storage;
 use serde_json::json;
 
-/// The concrete `WalletDb` used by this runtime.
 pub type Db = WalletDb;
 
 /// Parses the network name passed across the wasm boundary.
@@ -239,7 +235,6 @@ mod tests {
         assert_eq!(error.code, ErrorCode::DatabaseTooNew);
         assert_eq!(error.params["unknownMigrations"], 1);
         assert_eq!(error.detail.as_deref(), Some(newer.to_string().as_str()));
-        // No migration ran against the newer schema.
         let conn = rusqlite::Connection::open(&path).unwrap();
         assert_eq!(schema(&conn), before);
         drop(conn);
diff --git a/chain-runtimes/zcash/scripts/build-wasm.sh b/chain-runtimes/zcash/scripts/build-wasm.sh
index 3f4ed673c..3f8971cc1 100755
--- a/chain-runtimes/zcash/scripts/build-wasm.sh
+++ b/chain-runtimes/zcash/scripts/build-wasm.sh
@@ -1,16 +1,8 @@
 #!/usr/bin/env bash
 # Build the browser wasm packages.
 #
-# Prerequisites:
-#   1. wasm32-unknown-unknown target: rustup target add wasm32-unknown-unknown
-#   2. A clang that targets wasm32. Apple clang does not ("No available targets
-#      are compatible with triple wasm32-unknown-unknown"); use brew install llvm.
-#      (secp256k1-sys ships its own wasm sysroot; it only needs the compiler.)
-#   3. wasm-pack: cargo install wasm-pack
-#
-# Usage:
-#   bash scripts/build-wasm.sh            # release
-#   PROFILE=dev bash scripts/build-wasm.sh
+# Needs the wasm32-unknown-unknown target, wasm-pack, and a wasm32-capable clang (not Apple clang; brew install llvm).
+# Usage: bash scripts/build-wasm.sh, or PROFILE=dev bash scripts/build-wasm.sh
 
 set -euo pipefail
 
@@ -25,7 +17,6 @@ fi
 RUST_TOOLCHAIN="$(python3 -c 'import sys, tomllib; print(tomllib.load(open(sys.argv[1], "rb"))["toolchain"]["channel"])' "${ROOT}/rust-toolchain.toml")"
 rustup run "${RUST_TOOLCHAIN}" rustc --version
 
-# Find a clang that can compile for wasm32.
 pick_clang() {
   for c in "${CC_wasm32_unknown_unknown:-}" \
            /opt/homebrew/opt/llvm/bin/clang \
@@ -51,8 +42,7 @@ export AR_wasm32_unknown_unknown="${AR_wasm32_unknown_unknown:-$(dirname "${CLAN
 
 bash "${ROOT}/scripts/vendor-deps.sh" "$@"
 
-# With --mode no-install a missing wasm-opt is only an INFO line and the output
-# silently doubles in size. Release requires it.
+# With --mode no-install a missing wasm-opt is only an INFO line and the output doubles in size.
 if [ "${PROFILE}" = "release" ] && ! command -v wasm-opt >/dev/null 2>&1; then
   echo "✗ wasm-opt (Binaryen) not found; release output would be unoptimized" >&2
   exit 1
@@ -62,8 +52,7 @@ echo "==> wasm-pack build (${PROFILE})"
 cd "${ROOT}/crates/zcash-runtime"
 case "${PROFILE}" in
   release) rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --release ;;
-  # Optimized but keeps the name section, which wasm panic stacks need.
-  # --dev would make Halo2 proving unusably slow.
+  # Keeps the name section for panic stacks; --dev makes Halo2 proving unusably slow.
   profiling) rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --profiling ;;
   *) rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${OUT}" --dev ;;
 esac
@@ -71,8 +60,7 @@ esac
 echo "==> Artifacts"
 ls -lh "${OUT}"/*.wasm | awk '{print "   ", $9, $5}'
 
-# Always rebuild the keys package too, so the host never pairs a fresh runtime
-# with a stale keys build.
+# Rebuild keys too so the host never pairs a fresh runtime with a stale keys build.
 echo "==> Building onekey-zcash-keys"
 (cd "${ROOT}/crates/zcash-keys-runtime" && rustup run "${RUST_TOOLCHAIN}" wasm-pack build --mode no-install --locked --target web --out-dir "${ROOT}/pkg-keys" --release)
 echo "Artifacts: $(du -h "${ROOT}"/pkg/*.wasm "${ROOT}"/pkg-keys/*.wasm | tr '\n' ' ')"
diff --git a/chain-runtimes/zcash/scripts/prepare-vendor.py b/chain-runtimes/zcash/scripts/prepare-vendor.py
index ac79137be..b97dd33ba 100644
--- a/chain-runtimes/zcash/scripts/prepare-vendor.py
+++ b/chain-runtimes/zcash/scripts/prepare-vendor.py
@@ -25,7 +25,6 @@ def file_hashes(directory):
 
 def extract_crate(archive, temporary, identity):
     # Accept only ordinary files/directories under the expected crate root.
-    # This also works on macOS Python versions without tarfile's data filter.
     with tarfile.open(archive) as contents:
         for member in contents:
             path = PurePosixPath(member.name)

From 5981ec3071a0e51a8fbc68ccf77b362b56974af2 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Tue, 27 Oct 2026 10:59:23 +0800
Subject: [PATCH 77/97] fix: clear clippy warnings in the chain runtimes

Name the complex tuple and map types, drop no-op conversions and an
always-true test, and turn the non-zero block cap into a compile-time check.
Behavior is unchanged.
---
 .../crates/monero-runtime/src/review.rs       |  5 ++--
 .../monero/crates/monero-runtime/src/scan.rs  | 26 +++++++++++--------
 .../monero/crates/monero-runtime/src/spend.rs | 20 +++++++++-----
 .../monero/crates/monero-runtime/src/sync.rs  | 12 +++------
 .../crates/monero-runtime/src/wallet.rs       |  4 +--
 .../zcash/crates/zcash-runtime/src/sync.rs    |  3 +--
 .../crates/zcash-runtime/src/sync_tests.rs    | 12 ++++++---
 7 files changed, 47 insertions(+), 35 deletions(-)

diff --git a/chain-runtimes/monero/crates/monero-runtime/src/review.rs b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
index 793145394..4c0ea08dd 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/review.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
@@ -124,7 +124,7 @@ pub fn verify(
                             return Err(std::io::Error::other("unapproved change"));
                         }
                         if let Some(key) = spend_key {
-                            let scalar = Zeroizing::new(Scalar::read(&mut key.as_ref())?);
+                            let scalar = Zeroizing::new(Scalar::read(&mut &key[..])?);
                             let public = Point::from(
                                 (*scalar).into()
                                     * curve25519_dalek::constants::ED25519_BASEPOINT_POINT,
@@ -635,7 +635,8 @@ mod tests {
             )
         };
         let to_other_account = |_| Change::new(other_account(3), None);
-        let cases: [(&str, Box Change>); 2] = [
+        type ChangeFor = Box Change>;
+        let cases: [(&str, ChangeFor); 2] = [
             ("subaddress", Box::new(to_subaddress)),
             ("other account", Box::new(to_other_account)),
         ];
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
index 3d41d81fb..689f41273 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
@@ -193,6 +193,13 @@ struct RingReference {
 /// Only these need possible spends; outputs with a key image use normal spend detection.
 type RingCandidates = HashMap>;
 
+/// A transaction's public key R and its additional keys.
+type TxKeys = (Vec, Option>);
+/// `(txid, R, additional)` for one transaction.
+type TxPublicKeys = ([u8; 32], Vec, Option>);
+/// `(height, hash, RingCT cursor)` of a stored block.
+type BlockState = (u64, [u8; 32], Option);
+
 fn load_ring_candidates(db: &Db, identity_id: i64) -> Result {
     let mut stmt = db
         .conn()
@@ -243,7 +250,7 @@ fn ring_matches<'a>(
 /// monero-oxide folds R into `key_offset` and drops it. Firmware does not accept a
 /// host-computed `key_offset` (a malicious host could make it sign with any key), so R is
 /// kept; recovering it later needs a rescan or a txid query that leaks interest.
-fn tx_public_keys_in(block: &ScannableBlock) -> Vec<([u8; 32], Vec, Option>)> {
+fn tx_public_keys_in(block: &ScannableBlock) -> Vec {
     // Length mismatches are reported by `key_images_in`; skip here.
     let mut out = Vec::new();
     for (txid, tx) in block
@@ -284,9 +291,10 @@ pub fn scan_blocks(
     blocks: &[ScannableBlock],
 ) -> Result {
     if blocks.is_empty() {
-        let mut outcome = ScanOutcome::default();
-        outcome.outputs_without_key_image = count_outputs_without_key_image(db, identity_id)?;
-        return Ok(outcome);
+        return Ok(ScanOutcome {
+            outputs_without_key_image: count_outputs_without_key_image(db, identity_id)?,
+            ..ScanOutcome::default()
+        });
     }
 
     let identity = db.identity_by_id(identity_id)?;
@@ -310,7 +318,7 @@ pub fn scan_blocks(
     let mut outcome = ScanOutcome::default();
     let mut found: Vec<(u64, WalletOutput)> = Vec::new();
     // txid -> (R, additional), only for transactions that paid us.
-    let mut tx_pub_keys: HashMap<[u8; 32], (Vec, Option>)> = HashMap::new();
+    let mut tx_pub_keys: HashMap<[u8; 32], TxKeys> = HashMap::new();
     let mut spends: Vec<(u64, [u8; 32], [u8; 32])> = Vec::new(); // (height, key_image, txid)
 
     // Fees of transactions that spend ours: history needs them to tell the payment from the fee.
@@ -461,11 +469,7 @@ pub fn scan_blocks(
 }
 
 /// (height, hash, RingCT cursor after it) of the block before `height`.
-fn previous_block_state(
-    db: &Db,
-    identity_id: i64,
-    height: u64,
-) -> Result)>> {
+fn previous_block_state(db: &Db, identity_id: i64, height: u64) -> Result> {
     if height == 0 {
         return Ok(None);
     }
@@ -535,7 +539,7 @@ fn persist(
     db: &mut Db,
     identity_id: i64,
     found: &[(u64, WalletOutput)],
-    tx_pub_keys: &HashMap<[u8; 32], (Vec, Option>)>,
+    tx_pub_keys: &HashMap<[u8; 32], TxKeys>,
     spends: &[(u64, [u8; 32], [u8; 32])],
     known_key_images: &HashMap<[u8; 32], i64>,
     block_rows: &[(u64, [u8; 32], Option, u64)],
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
index 896e484bf..3520e6132 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -49,8 +49,8 @@ fn key_image_for(output: &WalletOutput, spend: &Zeroizing) -> Result<[u8
     }
 
     let generator = Point::biased_hash(output.key().compress().to_bytes());
-    let image =
-        Point::from(input_key.deref() * curve25519_dalek::EdwardsPoint::from(generator.into()));
+    let generator: curve25519_dalek::EdwardsPoint = generator.into();
+    let image = Point::from(input_key.deref() * generator);
     Ok(image.compress().to_bytes())
 }
 
@@ -125,13 +125,20 @@ fn apply_key_images(
         )
         .map_err(|e| db_err("updateKeyImage", e))?;
 
-        let spent: Option<(Vec, i64, Option, Option)> = tx
+        let spent = tx
             .query_row(
                 "SELECT spend_txid, height, timestamp, fee_atomic FROM possible_spends
                  WHERE identity_id = ?1 AND out_txid = ?2 AND out_index = ?3 AND key_image = ?4
                  ORDER BY height LIMIT 1",
                 params![identity_id, txid, index, image.as_slice()],
-                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
+                |r| {
+                    Ok((
+                        r.get::<_, Vec>(0)?,
+                        r.get::<_, i64>(1)?,
+                        r.get::<_, Option>(2)?,
+                        r.get::<_, Option>(3)?,
+                    ))
+                },
             )
             .optional()
             .map_err(|e| db_err("matchPossibleSpend", e))?;
@@ -269,10 +276,11 @@ fn is_double_spend(error: &RuntimeError) -> bool {
 ///
 /// Upstream fetches the full-chain distribution (about 18MB) per input, which times out
 /// easily when relayed through the host on mobile.
+type DistributionCache = HashMap<(std::ops::Bound, std::ops::Bound), Vec>;
+
 struct CachedDecoys<'a, P> {
     inner: &'a P,
-    distributions:
-        std::sync::Mutex, std::ops::Bound), Vec>>,
+    distributions: std::sync::Mutex,
 }
 
 impl<'a, P> CachedDecoys<'a, P> {
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
index 43812a94b..ab86a7c5b 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
@@ -17,6 +17,8 @@ use crate::wallet::Db;
 
 /// Per-call block cap: a hang guard; a huge value would run for minutes uninterruptibly.
 pub const MAX_BLOCKS_PER_CALL: u64 = 1_000;
+// 0 would underflow `start + max_blocks - 1`.
+const _: () = assert!(MAX_BLOCKS_PER_CALL > 0);
 
 /// Limit per-block fallback requests to three, leaving the host's fourth
 /// stream slot available for a chain-tip probe or another privacy chain.
@@ -272,7 +274,7 @@ pub async fn step(
     // Ranges are half-open (`end` is exclusive); upstream takes a closed range.
     let last = (start + max_blocks - 1).min(end.saturating_sub(1));
     if last < start {
-        return Ok(progress(db, identity_id, &ScanOutcome::default(), true)?);
+        return progress(db, identity_id, &ScanOutcome::default(), true);
     }
 
     // Time download and scan separately so node latency is not misread as CPU cost.
@@ -617,14 +619,6 @@ mod tests {
         assert!(next_range(&db, id).unwrap().is_none());
     }
 
-    /// The per-call block cap is hard: a huge value would freeze the page.
-    #[test]
-    fn max_blocks_is_clamped_and_zero_is_rejected() {
-        assert_eq!(u64::MAX.min(MAX_BLOCKS_PER_CALL), MAX_BLOCKS_PER_CALL);
-        // 0 would underflow `start + max_blocks - 1`; it is rejected at the entry
-        assert!(MAX_BLOCKS_PER_CALL > 0);
-    }
-
     /// A caught-up identity must not push a backfilling identity's progress to the
     /// tip, or that history is never scanned.
     #[test]
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs
index 79e1abcd8..13c2bde85 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs
@@ -287,8 +287,8 @@ impl Db {
         Ok(address)
     }
 
-    /// Ensures account 0 has subaddresses registered up to the highest used minor
-    /// + SUBADDRESS_LOOKAHEAD; returns how many were added. Cost is one scalar
+    /// Ensures account 0 has subaddresses registered up to the highest used minor plus
+    /// SUBADDRESS_LOOKAHEAD; returns how many were added. Cost is one scalar
     /// multiplication per registration; scanning is a table lookup.
     pub fn ensure_subaddress_lookahead(&mut self, identity_id: i64) -> Result {
         let (highest_used, highest_registered): (i64, i64) = self
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
index 8d8d583b7..9b46b33c5 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
@@ -917,7 +917,6 @@ const DOWNLOAD_SOFT_BUDGET_MS: f64 = 30_000.0;
 ///
 /// Each stream item has its own DEFAULT_TIMEOUT_MS stall timeout. A stall before any block
 /// is an error; a later stall, like the budget, truncates.
-
 async fn download_batch(
     client: &mut LightClient,
     cache: &MemoryBlockCache,
@@ -1279,7 +1278,7 @@ mod tests {
         assert!(ranges.iter().any(|range| {
             range.priority() == ScanPriority::Historic
                 && u32::from(range.block_range().start) <= resume_from
-                && u32::from(range.block_range().end) >= tip + 1
+                && u32::from(range.block_range().end) > tip
         }));
 
         let resumed_keys = ScanningKeys::from_account_ufvks(
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs
index 7377ebdf9..486d5e532 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs
@@ -1526,7 +1526,7 @@ fn earlier_tail_from_either_pool_defines_the_capped_fast_window() {
         let upstream = range(expected + 100, tip + 1, ScanPriority::ChainTip);
         assert_eq!(
             pick_range(
-                &[upstream.clone()],
+                std::slice::from_ref(&upstream),
                 Some(ScanPriority::ChainTip),
                 height(expected)
             ),
@@ -1633,7 +1633,13 @@ fn missing_completed_roots_fall_back_in_each_pool_including_sapling() {
         let mut db = planning_db(Some(f.tip), &sql);
         assert!(!roots_cover(&mut db, state).unwrap());
         assert_eq!(
-            guard_fast_range(&mut db, &[original.clone()], fast.clone(), state).unwrap(),
+            guard_fast_range(
+                &mut db,
+                std::slice::from_ref(&original),
+                fast.clone(),
+                state
+            )
+            .unwrap(),
             original
         );
     }
@@ -1696,7 +1702,7 @@ fn missing_root_guard_prevents_a_real_subtree_discontinuity_retry_loop() {
     let original = range(f.birthday, f.tip + 1, ScanPriority::ChainTip);
     let guarded = guard_fast_range(
         &mut db,
-        &[original.clone()],
+        std::slice::from_ref(&original),
         range(start, f.tip + 1, ScanPriority::ChainTip),
         &state,
     )

From 5a2a851b57bcca5fcb854cb53ef13cdb5357ed1c Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 00:56:05 +0800
Subject: [PATCH 78/97] feat: prune the Zcash scan queue on account removal and
 look accounts up by name

---
 .../zcash/crates/zcash-runtime/src/account.rs | 116 +++++++++++++++++-
 .../zcash/crates/zcash-runtime/src/bindgen.rs |   8 ++
 2 files changed, 123 insertions(+), 1 deletion(-)

diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
index 22856e5a1..37536cecd 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
@@ -4,6 +4,7 @@ use incrementalmerkletree::{frontier::Frontier, Hashable};
 use incrementalmerkletree::{Marking, Retention};
 use shardtree::{error::ShardTreeError, store::ShardStore, ShardTree};
 use zcash_client_backend::data_api::chain::ChainState;
+use zcash_client_backend::data_api::scanning::ScanPriority;
 use zcash_client_backend::data_api::wallet::ConfirmationsPolicy;
 use zcash_client_backend::data_api::{
     Account as _, AccountBalance, AccountBirthday, AccountPurpose, AccountSource, Balance,
@@ -466,6 +467,26 @@ pub fn remove_account(db: &mut Db, account_uuid: &str) -> Result<()> {
             )
             .detail(e)
         })?;
+        // delete_account leaves the scan queue alone, so ranges queued only for
+        // this account's earlier birthday would still be scanned for nobody.
+        let birthday = wallet.get_wallet_birthday().map_err(|e| {
+            RuntimeError::with(
+                ErrorCode::DatabaseError,
+                json!({ "operation": "getWalletBirthday" }),
+            )
+            .detail(e)
+        })?;
+        if let Some(birthday) = birthday {
+            wallet
+                .prune_scan_queue_below(birthday, Some(ScanPriority::OpenAdjacent))
+                .map_err(|e| {
+                    RuntimeError::with(
+                        ErrorCode::DatabaseError,
+                        json!({ "operation": "pruneScanQueue" }),
+                    )
+                    .detail(e)
+                })?;
+        }
         crate::tx_state::prune_orphaned_rows(ext)
     })
 }
@@ -477,7 +498,22 @@ pub fn account_by_ufvk(db: &Db, ufvk_str: &str) -> Result {
     let target = UnifiedFullViewingKey::decode(¶ms, ufvk_str)
         .map_err(|e| RuntimeError::new(ErrorCode::InvalidUfvk).detail(e))?
         .encode(¶ms);
+    find_account(db, |acct| {
+        acct.ufvk().map(|k| k.encode(¶ms)).as_deref() == Some(target.as_str())
+    })
+}
+
+/// Finds the account the host named at import (its viewing key fingerprint), or
+/// returns `"null"`. Names survive a purge, and need no viewing key to match.
+pub fn account_by_name(db: &Db, name: &str) -> Result {
+    find_account(db, |acct| acct.name() == Some(name))
+}
 
+/// `{ uuid }` of the first account `matches` accepts, or `"null"`.
+fn find_account(
+    db: &Db,
+    matches: impl Fn(&::Account) -> bool,
+) -> Result {
     for id in db.get_account_ids().map_err(|e| {
         RuntimeError::with(
             ErrorCode::DatabaseError,
@@ -495,7 +531,7 @@ pub fn account_by_ufvk(db: &Db, ufvk_str: &str) -> Result {
         else {
             continue;
         };
-        if acct.ufvk().map(|k| k.encode(¶ms)).as_deref() == Some(target.as_str()) {
+        if matches(&acct) {
             return Ok(json!({ "uuid": acct.id().expose_uuid().to_string() }).to_string());
         }
     }
@@ -783,3 +819,81 @@ mod derivation_tests {
         }
     }
 }
+
+#[cfg(test)]
+mod remove_account_tests {
+    use rand::SeedableRng;
+    use rand_chacha::ChaCha20Rng;
+    use zcash_client_sqlite::wallet::init::WalletMigrator;
+    use zcash_client_sqlite::WalletDb;
+    use zcash_keys::keys::UnifiedSpendingKey;
+    use zcash_primitives::block::BlockHash;
+    use zcash_protocol::consensus::{BlockHeight, Network};
+
+    use super::*;
+    use crate::clock::HostClock;
+
+    const NET: Network = Network::MainNetwork;
+    const TIP: u32 = 3_525_600;
+
+    fn wallet() -> Db {
+        let conn = rusqlite::Connection::open_in_memory().unwrap();
+        rusqlite::vtab::array::load_module(&conn).unwrap();
+        let mut db = WalletDb::from_connection(conn, NET, HostClock, ChaCha20Rng::from_seed([7; 32]));
+        WalletMigrator::new()
+            .with_external_migrations(crate::tx_state::migrations())
+            .init_or_migrate(&mut db)
+            .unwrap();
+        db
+    }
+
+    fn import(db: &mut Db, name: &str, index: u32, birthday: u32) -> String {
+        let ufvk = UnifiedSpendingKey::from_seed(&NET, &[9; 32], index.try_into().unwrap())
+            .unwrap()
+            .to_unified_full_viewing_key();
+        let birthday = AccountBirthday::from_parts(
+            ChainState::empty(BlockHeight::from_u32(birthday), BlockHash([0; 32])),
+            None,
+        );
+        db.import_account_ufvk(name, &ufvk, &birthday, AccountPurpose::ViewOnly, None)
+            .unwrap()
+            .id()
+            .expose_uuid()
+            .to_string()
+    }
+
+    fn lowest_queued(db: &Db) -> u32 {
+        db.suggest_scan_ranges()
+            .unwrap()
+            .iter()
+            .map(|range| u32::from(range.block_range().start))
+            .min()
+            .unwrap()
+    }
+
+    #[test]
+    fn removing_the_earliest_account_stops_scanning_below_the_rest() {
+        let mut db = wallet();
+        let early = import(&mut db, "fp-early", 0, 3_500_000);
+        import(&mut db, "fp-late", 1, 3_520_000);
+        db.update_chain_tip(BlockHeight::from_u32(TIP)).unwrap();
+        assert!(lowest_queued(&db) < 3_520_000);
+
+        remove_account(&mut db, &early).unwrap();
+
+        assert!(lowest_queued(&db) >= 3_520_000);
+    }
+
+    #[test]
+    fn finds_an_account_by_the_name_it_was_imported_under() {
+        let mut db = wallet();
+        let uuid = import(&mut db, "fp-a", 0, 3_520_000);
+        import(&mut db, "fp-b", 1, 3_520_000);
+
+        assert_eq!(
+            account_by_name(&db, "fp-a").unwrap(),
+            json!({ "uuid": uuid }).to_string()
+        );
+        assert_eq!(account_by_name(&db, "fp-missing").unwrap(), "null");
+    }
+}
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
index 528dc27a3..d3ad425a9 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
@@ -171,6 +171,14 @@ pub fn account_by_ufvk(ufvk: String) -> Result {
     Ok(runtime::with_db(|db| account::account_by_ufvk(db, &ufvk))?)
 }
 
+/// Finds the account the host named at import, returning `{ uuid }` or `"null"`.
+///
+/// The host names each account by its viewing key fingerprint, so it can drop one without the key.
+#[wasm_bindgen(js_name = accountByName)]
+pub fn account_by_name(name: String) -> Result {
+    Ok(runtime::with_db(|db| account::account_by_name(db, &name))?)
+}
+
 /// Per-account sync status, derived from the account birthday and the database's remaining scan ranges.
 ///
 ///

From 7d49ca2e617ed5fa8e93850cd305a243731f87e7 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 00:56:43 +0800
Subject: [PATCH 79/97] chore: bump privacy runtimes to 0.1.0-alpha.10

---
 chain-runtimes/monero/Cargo.lock | 2 +-
 chain-runtimes/monero/Cargo.toml | 2 +-
 chain-runtimes/zcash/Cargo.lock  | 4 ++--
 chain-runtimes/zcash/Cargo.toml  | 2 +-
 4 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock
index 1da2dff5a..8381995bf 100644
--- a/chain-runtimes/monero/Cargo.lock
+++ b/chain-runtimes/monero/Cargo.lock
@@ -1259,7 +1259,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-monero-runtime"
-version = "0.1.0-alpha.9"
+version = "0.1.0-alpha.10"
 dependencies = [
  "curve25519-dalek",
  "futures-lite",
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index e14e343b8..420610d4f 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/monero-runtime"]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.9"
+version = "0.1.0-alpha.10"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index f010dd4fe..35792dd77 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1655,7 +1655,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-zcash-keys"
-version = "0.1.0-alpha.9"
+version = "0.1.0-alpha.10"
 dependencies = [
  "bip0039",
  "bip32",
@@ -1687,7 +1687,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-runtime"
-version = "0.1.0-alpha.9"
+version = "0.1.0-alpha.10"
 dependencies = [
  "blake2b_simd",
  "console_error_panic_hook",
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index 0ecbed1df..5518a39ec 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -7,7 +7,7 @@ members = [
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.9"
+version = "0.1.0-alpha.10"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"

From afcea405e12726453a5df18945548f7369520b29 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 01:31:11 +0800
Subject: [PATCH 80/97] fix: prune the scan queue when a Zcash rescan moves the
 birthday later and refuse ambiguous account names

---
 .../zcash/crates/zcash-runtime/src/account.rs | 105 ++++++++++++++----
 1 file changed, 82 insertions(+), 23 deletions(-)

diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
index 37536cecd..8622fefdf 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
@@ -237,6 +237,8 @@ pub(crate) fn restart_with_birthday(
             .id()
             .expose_uuid()
             .to_string();
+        // The old birthday's unscanned ranges would find what the new one excludes.
+        prune_scan_queue_below_wallet_birthday(wallet)?;
         crate::tx_state::prune_orphaned_rows(ext)?;
         Ok(uuid)
     })
@@ -467,30 +469,39 @@ pub fn remove_account(db: &mut Db, account_uuid: &str) -> Result<()> {
             )
             .detail(e)
         })?;
-        // delete_account leaves the scan queue alone, so ranges queued only for
-        // this account's earlier birthday would still be scanned for nobody.
-        let birthday = wallet.get_wallet_birthday().map_err(|e| {
-            RuntimeError::with(
-                ErrorCode::DatabaseError,
-                json!({ "operation": "getWalletBirthday" }),
-            )
-            .detail(e)
-        })?;
-        if let Some(birthday) = birthday {
-            wallet
-                .prune_scan_queue_below(birthday, Some(ScanPriority::OpenAdjacent))
-                .map_err(|e| {
-                    RuntimeError::with(
-                        ErrorCode::DatabaseError,
-                        json!({ "operation": "pruneScanQueue" }),
-                    )
-                    .detail(e)
-                })?;
-        }
+        prune_scan_queue_below_wallet_birthday(wallet)?;
         crate::tx_state::prune_orphaned_rows(ext)
     })
 }
 
+/// delete_account leaves the scan queue alone, so ranges queued only for a
+/// removed account's earlier birthday would still be scanned for nobody.
+fn prune_scan_queue_below_wallet_birthday(wallet: &mut W) -> Result<()>
+where
+    W: WalletWrite,
+    ::Error: std::fmt::Display,
+{
+    let birthday = wallet.get_wallet_birthday().map_err(|e| {
+        RuntimeError::with(
+            ErrorCode::DatabaseError,
+            json!({ "operation": "getWalletBirthday" }),
+        )
+        .detail(e)
+    })?;
+    if let Some(birthday) = birthday {
+        wallet
+            .prune_scan_queue_below(birthday, Some(ScanPriority::OpenAdjacent))
+            .map_err(|e| {
+                RuntimeError::with(
+                    ErrorCode::DatabaseError,
+                    json!({ "operation": "pruneScanQueue" }),
+                )
+                .detail(e)
+            })?;
+    }
+    Ok(())
+}
+
 /// Finds the account with this UFVK, or returns `"null"`. The UFVK is the host's
 /// stable key; runtime UUIDs change after a purge.
 pub fn account_by_ufvk(db: &Db, ufvk_str: &str) -> Result {
@@ -505,8 +516,16 @@ pub fn account_by_ufvk(db: &Db, ufvk_str: &str) -> Result {
 
 /// Finds the account the host named at import (its viewing key fingerprint), or
 /// returns `"null"`. Names survive a purge, and need no viewing key to match.
+/// The host deletes by this, so a name held twice is refused, never guessed.
 pub fn account_by_name(db: &Db, name: &str) -> Result {
-    find_account(db, |acct| acct.name() == Some(name))
+    match matching_accounts(db, |acct| acct.name() == Some(name))?.as_slice() {
+        [] => Ok("null".to_string()),
+        [uuid] => Ok(json!({ "uuid": uuid }).to_string()),
+        _ => Err(RuntimeError::with(
+            ErrorCode::InvalidAccountId,
+            json!({ "reason": "duplicateName" }),
+        )),
+    }
 }
 
 /// `{ uuid }` of the first account `matches` accepts, or `"null"`.
@@ -514,6 +533,17 @@ fn find_account(
     db: &Db,
     matches: impl Fn(&::Account) -> bool,
 ) -> Result {
+    Ok(matching_accounts(db, matches)?
+        .first()
+        .map_or_else(|| "null".to_string(), |uuid| json!({ "uuid": uuid }).to_string()))
+}
+
+/// UUIDs of every account `matches` accepts.
+fn matching_accounts(
+    db: &Db,
+    matches: impl Fn(&::Account) -> bool,
+) -> Result> {
+    let mut found = Vec::new();
     for id in db.get_account_ids().map_err(|e| {
         RuntimeError::with(
             ErrorCode::DatabaseError,
@@ -532,10 +562,10 @@ fn find_account(
             continue;
         };
         if matches(&acct) {
-            return Ok(json!({ "uuid": acct.id().expose_uuid().to_string() }).to_string());
+            found.push(acct.id().expose_uuid().to_string());
         }
     }
-    Ok("null".to_string())
+    Ok(found)
 }
 
 pub fn list_accounts_json(db: &Db) -> Result {
@@ -896,4 +926,33 @@ mod remove_account_tests {
         );
         assert_eq!(account_by_name(&db, "fp-missing").unwrap(), "null");
     }
+
+    // Deleting goes by this name, so a name held twice must not pick one.
+    #[test]
+    fn refuses_a_name_two_accounts_share() {
+        let mut db = wallet();
+        import(&mut db, "fp-same", 0, 3_520_000);
+        import(&mut db, "fp-same", 1, 3_520_000);
+
+        let err = account_by_name(&db, "fp-same").unwrap_err();
+        assert_eq!(err.code, ErrorCode::InvalidAccountId);
+        assert_eq!(err.params["reason"], "duplicateName");
+    }
+
+    #[test]
+    fn moving_the_birthday_later_stops_scanning_below_it() {
+        let mut db = wallet();
+        let uuid = import(&mut db, "fp-a", 0, 3_500_000);
+        db.update_chain_tip(BlockHeight::from_u32(TIP)).unwrap();
+        assert!(lowest_queued(&db) < 3_520_000);
+
+        let id = parse_account_id(&db, &uuid).unwrap();
+        let later = AccountBirthday::from_parts(
+            ChainState::empty(BlockHeight::from_u32(3_520_000), BlockHash([0; 32])),
+            None,
+        );
+        restart_with_birthday(&mut db, id, &later, None).unwrap();
+
+        assert!(lowest_queued(&db) >= 3_520_000);
+    }
 }

From ebc73b59f56f82817a0a44ae9a80c53102584973 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 02:18:13 +0800
Subject: [PATCH 81/97] feat: export Monero outputs for device key image sync
 and import verified key images

---
 chain-runtimes/monero/README.md               |   1 +
 .../crates/monero-runtime/src/bindgen.rs      |  31 +-
 .../monero-runtime/src/device_key_images.rs   | 585 ++++++++++++++++++
 .../monero/crates/monero-runtime/src/error.rs |   5 +
 .../monero/crates/monero-runtime/src/lib.rs   |   1 +
 .../monero/crates/monero-runtime/src/spend.rs |   2 +-
 chain-runtimes/monero/scripts/smoke.js        |  14 +
 7 files changed, 637 insertions(+), 2 deletions(-)
 create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs

diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md
index 5fa2cf304..b1715da91 100644
--- a/chain-runtimes/monero/README.md
+++ b/chain-runtimes/monero/README.md
@@ -46,6 +46,7 @@ validateAddress(network, address)
 addAccount(uuid, spendPub, viewPriv, birthday, forceRescan?) / listAccounts() / removeAccount(uuid)
 registerSubaddress(accountId, major, minor, label?)
 importKeyImagesWithBip32Key(accountId, bip32PrivateKeyHex)
+exportKeyImageSyncData(accountId) / importDeviceKeyImages(accountId, itemsJson)
 
 updateChainTip(accountId, tip) / syncStep(accountId, maxBlocks) / syncPeek(accountId)
 rewindTo(accountId, height, tip)
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
index d970bc8af..ec9b51b01 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -11,7 +11,7 @@ use wasm_bindgen::prelude::*;
 use crate::error::{ErrorCode, Result, RuntimeError};
 use zeroize::Zeroizing;
 
-use crate::{keys, query, runtime, spend, storage, sync, wallet};
+use crate::{device_key_images, keys, query, runtime, spend, storage, sync, wallet};
 
 fn json(value: serde_json::Value) -> std::result::Result {
     Ok(value.to_string())
@@ -241,6 +241,35 @@ pub fn import_key_images_with_bip32_key(
     }))
 }
 
+/// Outputs whose key images a hardware wallet must compute, for view-only device accounts.
+///
+/// Returns `{ items: [{ outputId, outKey, txPubKey, additionalTxPubKey, internalOutputIndex,
+/// subAddrMajor, subAddrMinor }] }` (keys hex; `additionalTxPubKey` may be `null`) for the
+/// scan-valid outputs lacking a key image.
+#[wasm_bindgen(js_name = exportKeyImageSyncData)]
+pub fn export_key_image_sync_data(account_id: i64) -> std::result::Result {
+    let v = runtime::with_db_read(|db| device_key_images::export_sync_data(db, account_id))?;
+    json(v)
+}
+
+/// Import key images computed by a hardware wallet from `exportKeyImageSyncData`.
+///
+/// `itemsJson` is `[{ outputId, keyImage, signature }]`: hex key image and its one-member
+/// ring signature (`c || r`) by the output key. Every item is verified first; any failure
+/// (`INVALID_KEY_IMAGE`) imports nothing. Returns `{ imported, spendsFound }`.
+#[wasm_bindgen(js_name = importDeviceKeyImages)]
+pub fn import_device_key_images(
+    account_id: i64,
+    items_json: &str,
+) -> std::result::Result {
+    let result =
+        runtime::with_db(|db| device_key_images::import_verified(db, account_id, items_json))?;
+    json(serde_json::json!({
+        "imported": result.imported,
+        "spendsFound": result.spends_found,
+    }))
+}
+
 /// Derive Monero view material and the primary address from a BIP-32-derived private key.
 ///
 /// Pure derivation (no DB, no node). Matches OneKey V4 (`spend = sc_reduce32(key)`,
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs b/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs
new file mode 100644
index 000000000..7abbee4c9
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs
@@ -0,0 +1,585 @@
+//! Key image sync for hardware accounts, whose spend key stays on the device.
+//!
+//! The device derives each output's key image from the exported keys and proves it
+//! with a one-member ring signature by the output key (as wallet2 `import_key_images`);
+//! only verified images are stored.
+
+use std::collections::HashSet;
+
+use curve25519_dalek::{constants::ED25519_BASEPOINT_POINT, EdwardsPoint};
+use monero_wallet::{
+    address::SubaddressIndex,
+    ed25519::{CompressedPoint, Scalar},
+    io::VarInt,
+    ring_signatures::RingSignature,
+};
+use rusqlite::OptionalExtension;
+use serde_json::{json, Value};
+use zeroize::Zeroizing;
+
+use crate::error::{db_err, ErrorCode, Result, RuntimeError};
+use crate::spend::{apply_key_images, KeyImageImport};
+use crate::wallet::{Db, Identity};
+
+/// `(id, index in tx, output key, R keys, additional keys, subaddress major, minor)`.
+type SyncRow = (
+    i64,
+    i64,
+    Option>,
+    Option>,
+    Option>,
+    Option,
+    Option,
+);
+
+/// Outputs still lacking a key image, with the keys a device needs to derive them.
+pub fn export_sync_data(db: &Db, identity_id: i64) -> Result {
+    let identity = db.identity_by_id(identity_id)?;
+    let view = view_scalar(db, identity_id)?;
+
+    let rows: Vec = {
+        let mut stmt = db
+            .conn()
+            .prepare(
+                "SELECT id, index_in_tx, output_key, tx_pub_keys, tx_additional_pub_keys,
+                        subaddress_major, subaddress_minor
+                 FROM outputs
+                 WHERE identity_id = ?1 AND key_image IS NULL AND scan_valid = 1
+                 ORDER BY id",
+            )
+            .map_err(|e| db_err("listKeyImageSyncOutputs", e))?;
+        let rows = stmt
+            .query_map([identity_id], |r| {
+                Ok((
+                    r.get(0)?,
+                    r.get(1)?,
+                    r.get(2)?,
+                    r.get(3)?,
+                    r.get(4)?,
+                    r.get(5)?,
+                    r.get(6)?,
+                ))
+            })
+            .map_err(|e| db_err("listKeyImageSyncOutputs", e))?;
+        rows.collect::>()
+            .map_err(|e| db_err("listKeyImageSyncOutputs", e))?
+    };
+
+    let mut items = Vec::with_capacity(rows.len());
+    for (id, index, output_key, tx_keys, additional, major, minor) in rows {
+        let corrupt = |what: &str| db_err("exportKeyImageSyncData", format!("output {id}: {what}"));
+        let output_key = output_key
+            .and_then(|k| <[u8; 32]>::try_from(k).ok())
+            .ok_or_else(|| corrupt("no output key"))?;
+        let tx_keys = tx_keys
+            .filter(|k| !k.is_empty() && k.len() % 32 == 0)
+            .ok_or_else(|| corrupt("no transaction public key"))?;
+        let index = u32::try_from(index).map_err(|_| corrupt("output index out of range"))?;
+        let major = u32::try_from(major.unwrap_or(0)).map_err(|_| corrupt("bad subaddress"))?;
+        let minor = u32::try_from(minor.unwrap_or(0)).map_err(|_| corrupt("bad subaddress"))?;
+
+        let first = &tx_keys[..32];
+        let tx_pub_key = if tx_keys.len() == 32 {
+            first
+        } else {
+            let spend = receiving_spend_key(db, &identity, major, minor);
+            // None matching means the output was received via its additional key.
+            tx_keys
+                .chunks_exact(32)
+                .find(|r| derives_output_key(&view, r, index, spend, &output_key))
+                .unwrap_or(first)
+        };
+        let additional = additional
+            .as_deref()
+            .and_then(|a| a.chunks_exact(32).nth(index as usize))
+            .map(hex::encode);
+
+        items.push(json!({
+            "outputId": id,
+            "outKey": hex::encode(output_key),
+            "txPubKey": hex::encode(tx_pub_key),
+            "additionalTxPubKey": additional,
+            "internalOutputIndex": index,
+            "subAddrMajor": major,
+            "subAddrMinor": minor,
+        }));
+    }
+    Ok(json!({ "items": items }))
+}
+
+fn view_scalar(db: &Db, identity_id: i64) -> Result> {
+    let bytes: Zeroizing> = Zeroizing::new(
+        db.conn()
+            .query_row(
+                "SELECT view_private_key FROM identities WHERE id = ?1",
+                [identity_id],
+                |r| r.get(0),
+            )
+            .map_err(|e| db_err("loadViewKey", e))?,
+    );
+    let scalar = Scalar::read(&mut bytes.as_slice()).map_err(|e| db_err("loadViewKey", e))?;
+    Ok(Zeroizing::new(scalar.into()))
+}
+
+fn receiving_spend_key(db: &Db, identity: &Identity, major: u32, minor: u32) -> EdwardsPoint {
+    match SubaddressIndex::new(major, minor) {
+        Some(index) => identity
+            .view_pair
+            .subaddress(db.network(), index)
+            .spend()
+            .into(),
+        None => identity.view_pair.spend().into(),
+    }
+}
+
+/// Whether `Hs(8·a·R || index)·G + spend` is the output key.
+fn derives_output_key(
+    view: &curve25519_dalek::Scalar,
+    r: &[u8],
+    index: u32,
+    spend: EdwardsPoint,
+    output_key: &[u8; 32],
+) -> bool {
+    let Some(r) = <[u8; 32]>::try_from(r)
+        .ok()
+        .and_then(|r| CompressedPoint::from(r).decompress())
+    else {
+        return false;
+    };
+    let mut derivation = Zeroizing::new(
+        (view * r.into())
+            .mul_by_cofactor()
+            .compress()
+            .to_bytes()
+            .to_vec(),
+    );
+    VarInt::write(&u64::from(index), &mut *derivation).expect("writing to a Vec cannot fail");
+    let shared: curve25519_dalek::Scalar = Scalar::hash(&*derivation).into();
+    (shared * ED25519_BASEPOINT_POINT + spend)
+        .compress()
+        .to_bytes()
+        == *output_key
+}
+
+/// `(output key, key image, txid, index in tx, scan valid)`.
+type ImportRow = (Option>, Option>, Vec, i64, bool);
+
+#[derive(serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceKeyImage {
+    output_id: i64,
+    key_image: String,
+    /// `c || r`, 64 bytes.
+    signature: String,
+}
+
+/// Stores device-computed key images once every item verifies; one bad item imports nothing.
+///
+/// Items whose output already has the same key image are skipped.
+pub fn import_verified(db: &mut Db, identity_id: i64, items_json: &str) -> Result {
+    db.identity_by_id(identity_id)?;
+    let items: Vec = serde_json::from_str(items_json).map_err(|e| {
+        RuntimeError::with(ErrorCode::InvalidRequest, json!({ "field": "itemsJson" })).detail(e)
+    })?;
+
+    let mut verified = Vec::with_capacity(items.len());
+    let mut seen = HashSet::new();
+    for item in &items {
+        let id = item.output_id;
+        let key_image: [u8; 32] =
+            decode(&item.key_image).ok_or_else(|| rejected(id, "malformedKeyImage"))?;
+        let signature: [u8; 64] =
+            decode(&item.signature).ok_or_else(|| rejected(id, "malformedSignature"))?;
+
+        let row: Option = db
+            .conn()
+            .query_row(
+                "SELECT output_key, key_image, txid, index_in_tx, scan_valid FROM outputs
+                 WHERE id = ?1 AND identity_id = ?2",
+                [id, identity_id],
+                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
+            )
+            .optional()
+            .map_err(|e| db_err("loadKeyImageOutput", e))?;
+        let Some((output_key, existing, txid, index, scan_valid)) = row else {
+            return Err(rejected(id, "outputNotFound"));
+        };
+        if !scan_valid {
+            return Err(rejected(id, "outputNotScanValid"));
+        }
+        let output_key = output_key
+            .and_then(|k| <[u8; 32]>::try_from(k).ok())
+            .ok_or_else(|| {
+                db_err(
+                    "importDeviceKeyImages",
+                    format!("output {id}: no output key"),
+                )
+            })?;
+        if !signature_verifies(&key_image, &output_key, &signature) {
+            return Err(rejected(id, "badSignature"));
+        }
+        match existing {
+            Some(stored) if stored == key_image => continue,
+            Some(_) => return Err(rejected(id, "keyImageConflict")),
+            None => {}
+        }
+        // A valid signature fixes the image, so a repeated id carries the same one.
+        if seen.insert(id) {
+            verified.push((id, key_image, txid, index));
+        }
+    }
+
+    apply_key_images(db, identity_id, &verified)
+}
+
+/// One-member ring signature by `output_key` over the key image itself (wallet2's message).
+fn signature_verifies(key_image: &[u8; 32], output_key: &[u8; 32], signature: &[u8; 64]) -> bool {
+    // Non-canonical scalars fail to read.
+    let Ok(signature) = RingSignature::read(1, &mut signature.as_slice()) else {
+        return false;
+    };
+    signature.verify(
+        key_image,
+        &[CompressedPoint::from(*output_key)],
+        &CompressedPoint::from(*key_image),
+    )
+}
+
+fn decode(value: &str) -> Option<[u8; N]> {
+    let mut out = [0u8; N];
+    hex::decode_to_slice(value, &mut out).ok()?;
+    Some(out)
+}
+
+fn rejected(output_id: i64, reason: &str) -> RuntimeError {
+    RuntimeError::with(
+        ErrorCode::InvalidKeyImage,
+        json!({ "outputId": output_id, "reason": reason }),
+    )
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::wallet::testing::{db_with_identity, key_bytes};
+    use curve25519_dalek::Scalar as Dalek;
+    use monero_wallet::ed25519::Point;
+    use rusqlite::params;
+
+    const G: EdwardsPoint = ED25519_BASEPOINT_POINT;
+
+    /// The test identity's private view scalar and public spend key.
+    fn identity_keys() -> (Dalek, EdwardsPoint) {
+        let (spend, view) = key_bytes();
+        let spend = CompressedPoint::from(spend).decompress().unwrap().into();
+        (Dalek::from_canonical_bytes(view).unwrap(), spend)
+    }
+
+    /// Sender side: the key of output `index` paid with secret `r` to (view, spend) public keys.
+    fn sent_output_key(r: Dalek, view: EdwardsPoint, spend: EdwardsPoint, index: u64) -> [u8; 32] {
+        let mut derivation = (r * view).mul_by_cofactor().compress().to_bytes().to_vec();
+        VarInt::write(&index, &mut derivation).unwrap();
+        let shared: Dalek = Scalar::hash(&derivation).into();
+        (shared * G + spend).compress().to_bytes()
+    }
+
+    fn concat(points: &[EdwardsPoint]) -> Vec {
+        points
+            .iter()
+            .flat_map(|p| p.compress().to_bytes())
+            .collect()
+    }
+
+    fn insert_output(
+        db: &Db,
+        identity_id: i64,
+        txid: u8,
+        index: i64,
+        output_key: [u8; 32],
+        tx_keys: &[EdwardsPoint],
+        additional: Option<&[EdwardsPoint]>,
+    ) -> i64 {
+        db.conn()
+            .execute(
+                "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx,
+                   amount_atomic, height, tx_pub_keys, tx_additional_pub_keys, output_key)
+                 VALUES (?1, x'00', ?2, 7, ?3, 1000, 10, ?4, ?5, ?6)",
+                params![
+                    identity_id,
+                    vec![txid; 32],
+                    index,
+                    concat(tx_keys),
+                    additional.map(concat),
+                    output_key.to_vec()
+                ],
+            )
+            .unwrap();
+        db.conn().last_insert_rowid()
+    }
+
+    fn set_subaddress(db: &Db, id: i64, major: u32, minor: u32) {
+        db.conn()
+            .execute(
+                "UPDATE outputs SET subaddress_major = ?1, subaddress_minor = ?2 WHERE id = ?3",
+                params![major, minor, id],
+            )
+            .unwrap();
+    }
+
+    fn subaddress_spend(db: &Db, identity_id: i64, minor: u32) -> EdwardsPoint {
+        let identity = db.identity_by_id(identity_id).unwrap();
+        receiving_spend_key(db, &identity, 0, minor)
+    }
+
+    fn hex_of(point: EdwardsPoint) -> String {
+        hex::encode(point.compress().to_bytes())
+    }
+
+    fn export(db: &Db, id: i64) -> Vec {
+        export_sync_data(db, id).unwrap()["items"]
+            .as_array()
+            .unwrap()
+            .clone()
+    }
+
+    /// Among several R, the one that derives the output key is exported, not the first or last.
+    #[test]
+    fn export_picks_the_tx_public_key_that_derives_the_output() {
+        let (db, id) = db_with_identity();
+        let (view, spend) = identity_keys();
+        let r: Vec = [11u64, 22, 33].map(Dalek::from).to_vec();
+
+        let primary_keys: Vec = r.iter().map(|r| r * G).collect();
+        let key = sent_output_key(r[1], view * G, spend, 1);
+        let primary = insert_output(&db, id, 1, 1, key, &primary_keys, None);
+
+        // To a subaddress D the sender uses R = r·D and pays the view key a·D.
+        let d = subaddress_spend(&db, id, 3);
+        let sub_keys: Vec = r.iter().map(|r| r * d).collect();
+        let key = sent_output_key(r[1], view * d, d, 0);
+        let sub = insert_output(&db, id, 2, 0, key, &sub_keys, None);
+        set_subaddress(&db, sub, 0, 3);
+
+        let items = export(&db, id);
+        assert_eq!(items.len(), 2);
+        assert_eq!(items[0]["outputId"], primary);
+        assert_eq!(items[0]["txPubKey"], hex_of(primary_keys[1]));
+        assert_eq!(items[0]["internalOutputIndex"], 1);
+        assert_eq!(items[0]["additionalTxPubKey"], Value::Null);
+        assert_eq!(items[0]["subAddrMajor"], 0);
+        assert_eq!(items[0]["subAddrMinor"], 0);
+        assert_eq!(items[1]["outputId"], sub);
+        assert_eq!(items[1]["txPubKey"], hex_of(sub_keys[1]));
+        assert_eq!(items[1]["subAddrMinor"], 3);
+    }
+
+    /// An output paid via its additional key exports that key, with the first R as `txPubKey`.
+    #[test]
+    fn export_includes_the_additional_key_and_skips_resolved_outputs() {
+        let (db, id) = db_with_identity();
+        let (view, _) = identity_keys();
+        let d = subaddress_spend(&db, id, 2);
+        let tx_keys = [Dalek::from(5u64) * G, Dalek::from(6u64) * G];
+        let k: Vec = [41u64, 42, 43].map(Dalek::from).to_vec();
+        let additional: Vec = k.iter().map(|k| k * d).collect();
+        let key = sent_output_key(k[2], view * d, d, 2);
+        let out = insert_output(&db, id, 1, 2, key, &tx_keys, Some(&additional));
+        set_subaddress(&db, out, 0, 2);
+
+        let imaged = insert_output(&db, id, 2, 0, [9; 32], &tx_keys[..1], None);
+        db.conn()
+            .execute(
+                "UPDATE outputs SET key_image = ?1 WHERE id = ?2",
+                params![vec![1u8; 32], imaged],
+            )
+            .unwrap();
+        let invalid = insert_output(&db, id, 3, 0, [8; 32], &tx_keys[..1], None);
+        db.conn()
+            .execute("UPDATE outputs SET scan_valid = 0 WHERE id = ?1", [invalid])
+            .unwrap();
+
+        let items = export(&db, id);
+        assert_eq!(
+            items.len(),
+            1,
+            "imaged and unverified outputs are not exported"
+        );
+        assert_eq!(items[0]["outputId"], out);
+        assert_eq!(items[0]["outKey"], hex::encode(key));
+        assert_eq!(items[0]["txPubKey"], hex_of(tx_keys[0]));
+        assert_eq!(items[0]["additionalTxPubKey"], hex_of(additional[2]));
+        assert_eq!(items[0]["subAddrMinor"], 2);
+    }
+
+    /// `(output key, key image, c || r)`: a key image and its one-member ring signature
+    /// for the output with secret `x`, following Monero's `generate_ring_signature`.
+    fn device_sign(x: Dalek, nonce: Dalek) -> ([u8; 32], [u8; 32], [u8; 64]) {
+        let output_key = (x * G).compress().to_bytes();
+        let hp: EdwardsPoint = Point::biased_hash(output_key).into();
+        let image = (x * hp).compress().to_bytes();
+        let mut transcript = image.to_vec();
+        transcript.extend_from_slice((nonce * G).compress().as_bytes());
+        transcript.extend_from_slice((nonce * hp).compress().as_bytes());
+        let c: Dalek = Scalar::hash(&transcript).into();
+        let r = nonce - c * x;
+        let mut signature = [0u8; 64];
+        signature[..32].copy_from_slice(c.as_bytes());
+        signature[32..].copy_from_slice(r.as_bytes());
+        (output_key, image, signature)
+    }
+
+    fn item(id: i64, image: &[u8], signature: &[u8]) -> Value {
+        json!({ "outputId": id, "keyImage": hex::encode(image), "signature": hex::encode(signature) })
+    }
+
+    fn key_images(db: &Db) -> Vec>> {
+        let mut stmt = db
+            .conn()
+            .prepare("SELECT key_image FROM outputs ORDER BY id")
+            .unwrap();
+        stmt.query_map([], |r| r.get(0))
+            .unwrap()
+            .collect::>()
+            .unwrap()
+    }
+
+    fn rejection(db: &mut Db, id: i64, items: Value) -> RuntimeError {
+        match import_verified(db, id, &items.to_string()) {
+            Ok(_) => panic!("import must be rejected"),
+            Err(e) => e,
+        }
+    }
+
+    /// `(output id, key image, signature)`.
+    type SignedOutput = (i64, [u8; 32], [u8; 64]);
+
+    /// Two device-signed outputs; the first has a possible spend with its real key image.
+    fn db_with_signed_outputs() -> (Db, i64, [SignedOutput; 2]) {
+        let (db, id) = db_with_identity();
+        let signed = [(101u64, 7u64, 1u8), (202, 8, 2)].map(|(x, nonce, txid)| {
+            let (key, image, signature) = device_sign(Dalek::from(x), Dalek::from(nonce));
+            let out = insert_output(&db, id, txid, 0, key, &[G], None);
+            (out, image, signature)
+        });
+        db.conn()
+            .execute(
+                "INSERT INTO possible_spends
+                   (identity_id, out_txid, out_index, key_image, spend_txid, height, timestamp)
+                 VALUES (?1, ?2, 0, ?3, ?4, 40, 1700000000), (?1, ?2, 0, ?5, ?6, 41, 1700000000)",
+                params![
+                    id,
+                    vec![1u8; 32],
+                    signed[0].1.to_vec(),
+                    vec![0x51u8; 32],
+                    vec![0xEEu8; 32],
+                    vec![0x52u8; 32]
+                ],
+            )
+            .unwrap();
+        (db, id, signed)
+    }
+
+    #[test]
+    fn a_device_key_image_with_a_bad_signature_rejects_the_whole_import() {
+        let (mut db, id, [(a, a_image, a_sig), (b, b_image, mut b_sig)]) = db_with_signed_outputs();
+        b_sig[0] ^= 1;
+
+        let e = rejection(
+            &mut db,
+            id,
+            json!([item(a, &a_image, &a_sig), item(b, &b_image, &b_sig)]),
+        );
+        assert_eq!(e.code, ErrorCode::InvalidKeyImage);
+        assert_eq!(e.params, json!({ "outputId": b, "reason": "badSignature" }));
+        assert_eq!(key_images(&db), vec![None, None], "nothing is written");
+        let pending: i64 = db
+            .conn()
+            .query_row("SELECT count(*) FROM possible_spends", [], |r| r.get(0))
+            .unwrap();
+        assert_eq!(pending, 2);
+
+        // A valid signature for another output's key does not prove this output's image.
+        let e = rejection(&mut db, id, json!([item(b, &a_image, &a_sig)]));
+        assert_eq!(e.params["reason"], "badSignature");
+        let e = rejection(&mut db, id, json!([item(b, &b_image, &a_sig[..63])]));
+        assert_eq!(e.params["reason"], "malformedSignature");
+    }
+
+    #[test]
+    fn verified_device_key_images_are_stored_and_confirm_an_earlier_spend() {
+        let (mut db, id, [(a, a_image, a_sig), (b, b_image, b_sig)]) = db_with_signed_outputs();
+        let items = json!([item(a, &a_image, &a_sig), item(b, &b_image, &b_sig)]).to_string();
+
+        let result = import_verified(&mut db, id, &items).unwrap();
+        assert_eq!((result.imported, result.spends_found), (2, 1));
+        assert_eq!(
+            key_images(&db),
+            vec![Some(a_image.to_vec()), Some(b_image.to_vec())]
+        );
+        let (height, txid): (Option, Option>) = db
+            .conn()
+            .query_row(
+                "SELECT spent_at_height, spent_in_txid FROM outputs WHERE id = ?1",
+                [a],
+                |r| Ok((r.get(0)?, r.get(1)?)),
+            )
+            .unwrap();
+        assert_eq!((height, txid), (Some(40), Some(vec![0x51; 32])));
+        let direction: String = db
+            .conn()
+            .query_row(
+                "SELECT direction FROM transactions WHERE txid = ?1",
+                [vec![0x51u8; 32]],
+                |r| r.get(0),
+            )
+            .unwrap();
+        assert_eq!(direction, "out");
+        assert!(export(&db, id).is_empty());
+
+        let again = import_verified(&mut db, id, &items).unwrap();
+        assert_eq!(
+            (again.imported, again.spends_found),
+            (0, 0),
+            "already stored"
+        );
+    }
+
+    #[test]
+    fn device_key_images_for_foreign_unverified_or_conflicting_outputs_are_refused() {
+        let (mut db, id, [(a, a_image, a_sig), (b, b_image, b_sig)]) = db_with_signed_outputs();
+
+        let derived = crate::keys::derive_from_bip32_key(db.network(), &[5; 32]).unwrap();
+        let other = db
+            .add_identity(
+                "acct-2",
+                &derived.spend_public_key,
+                &derived.view_private_key,
+                100,
+            )
+            .unwrap()
+            .id;
+        let e = rejection(&mut db, other, json!([item(a, &a_image, &a_sig)]));
+        assert_eq!(
+            e.params,
+            json!({ "outputId": a, "reason": "outputNotFound" })
+        );
+
+        db.conn()
+            .execute("UPDATE outputs SET scan_valid = 0 WHERE id = ?1", [a])
+            .unwrap();
+        let e = rejection(&mut db, id, json!([item(a, &a_image, &a_sig)]));
+        assert_eq!(e.params["reason"], "outputNotScanValid");
+
+        db.conn()
+            .execute(
+                "UPDATE outputs SET key_image = ?1 WHERE id = ?2",
+                params![vec![3u8; 32], b],
+            )
+            .unwrap();
+        let e = rejection(&mut db, id, json!([item(b, &b_image, &b_sig)]));
+        assert_eq!(e.params["reason"], "keyImageConflict");
+
+        let e = rejection(&mut db, id, json!({ "outputId": a }));
+        assert_eq!(e.code, ErrorCode::InvalidRequest);
+    }
+}
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/error.rs b/chain-runtimes/monero/crates/monero-runtime/src/error.rs
index d7d818f16..bf74f89f4 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/error.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/error.rs
@@ -23,6 +23,9 @@ pub enum ErrorCode {
     InvalidBlockRange,
     /// Malformed JSON from the host. Params: `{ field, reason }`
     InvalidRequest,
+    /// A device-supplied key image failed verification; nothing was imported.
+    /// Params: `{ outputId, reason }`
+    InvalidKeyImage,
 
     /// `openWallet` has not been called.
     WalletNotOpen,
@@ -82,6 +85,7 @@ impl ErrorCode {
             InvalidSubaddressIndex => "INVALID_SUBADDRESS_INDEX",
             InvalidBlockRange => "INVALID_BLOCK_RANGE",
             InvalidRequest => "INVALID_REQUEST",
+            InvalidKeyImage => "INVALID_KEY_IMAGE",
             WalletNotOpen => "WALLET_NOT_OPEN",
             WalletBusy => "WALLET_BUSY",
             NotInitialized => "NOT_INITIALIZED",
@@ -193,6 +197,7 @@ mod tests {
             InvalidSubaddressIndex,
             InvalidBlockRange,
             InvalidRequest,
+            InvalidKeyImage,
             WalletNotOpen,
             WalletBusy,
             NotInitialized,
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/lib.rs b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs
index 59a1a8792..c0f416304 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/lib.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs
@@ -3,6 +3,7 @@
 //! Rust owns cryptography, protocol and storage; the host owns scan scheduling.
 
 pub mod blocks_bin;
+pub mod device_key_images;
 pub mod error;
 pub mod keys;
 pub mod network;
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
index 3520e6132..7a1bafd79 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -108,7 +108,7 @@ fn compute_key_images(
 }
 
 /// Stores computed key images and confirms earlier spends from possible spends.
-fn apply_key_images(
+pub(crate) fn apply_key_images(
     db: &mut Db,
     identity_id: i64,
     computed: &[(i64, [u8; 32], Vec, i64)],
diff --git a/chain-runtimes/monero/scripts/smoke.js b/chain-runtimes/monero/scripts/smoke.js
index 30f706d2d..0d905d0db 100755
--- a/chain-runtimes/monero/scripts/smoke.js
+++ b/chain-runtimes/monero/scripts/smoke.js
@@ -68,6 +68,20 @@ for (const name of ['spendScalar', 'signTransaction', 'importKeyImages']) {
 const imported = JSON.parse(rt.importKeyImagesWithBip32Key(id, key));
 check('key-image import from the BIP-32 key on an empty wallet', imported.imported, 0);
 
+// Hardware accounts: nothing to sync yet, and an unverifiable device item is refused.
+const syncData = JSON.parse(rt.exportKeyImageSyncData(id));
+check('key-image sync export on an empty wallet', syncData.items.length, 0);
+try {
+  rt.importDeviceKeyImages(
+    id,
+    JSON.stringify([{ outputId: 1, keyImage: '00'.repeat(32), signature: '00'.repeat(64) }]),
+  );
+  check('device key-image import rejects an unknown output', 'succeeded', 'failed');
+} catch (e) {
+  const err = JSON.parse(e.message ?? e);
+  check('device key-image import rejects an unknown output', err.code, 'INVALID_KEY_IMAGE');
+}
+
 // Signing is pure computation. Bad input must be rejected, never passed on to broadcast.
 const review = JSON.stringify({
   network: 'mainnet',

From 7d9a32ec9e798de6b0ce81882f6ce539ae92f921 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 02:34:45 +0800
Subject: [PATCH 82/97] chore: bump privacy runtimes to 0.1.0-alpha.11

---
 chain-runtimes/monero/Cargo.lock | 2 +-
 chain-runtimes/monero/Cargo.toml | 2 +-
 chain-runtimes/zcash/Cargo.lock  | 4 ++--
 chain-runtimes/zcash/Cargo.toml  | 2 +-
 4 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock
index 8381995bf..67e9eee07 100644
--- a/chain-runtimes/monero/Cargo.lock
+++ b/chain-runtimes/monero/Cargo.lock
@@ -1259,7 +1259,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-monero-runtime"
-version = "0.1.0-alpha.10"
+version = "0.1.0-alpha.11"
 dependencies = [
  "curve25519-dalek",
  "futures-lite",
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index 420610d4f..c0c920cec 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/monero-runtime"]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.10"
+version = "0.1.0-alpha.11"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index 35792dd77..abc88a204 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1655,7 +1655,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-zcash-keys"
-version = "0.1.0-alpha.10"
+version = "0.1.0-alpha.11"
 dependencies = [
  "bip0039",
  "bip32",
@@ -1687,7 +1687,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-runtime"
-version = "0.1.0-alpha.10"
+version = "0.1.0-alpha.11"
 dependencies = [
  "blake2b_simd",
  "console_error_panic_hook",
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index 5518a39ec..e80d27a57 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -7,7 +7,7 @@ members = [
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.10"
+version = "0.1.0-alpha.11"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"

From 455a3877f3176c8094d0bcd1c264d16b89b1debe Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 04:47:24 +0800
Subject: [PATCH 83/97] feat: report Monero receive fees, primary-address
 receipts and confirmation wait

---
 .../monero/crates/monero-runtime/src/query.rs | 69 ++++++++++++++++++-
 .../monero/crates/monero-runtime/src/scan.rs  | 29 ++++----
 2 files changed, 84 insertions(+), 14 deletions(-)

diff --git a/chain-runtimes/monero/crates/monero-runtime/src/query.rs b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
index 0c6cb3433..9634637b5 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/query.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
@@ -35,6 +35,8 @@ pub struct Balance {
     pub pending_change_atomic: u128,
     /// Unspent outputs lacking a key image; selection only uses outputs with one.
     pub outputs_without_key_image: u64,
+    /// Blocks until every output still inside the 10-block lock is spendable.
+    pub confirming_blocks_left: Option,
 }
 
 impl Balance {
@@ -46,6 +48,7 @@ impl Balance {
             "unverifiableAtomic": self.unverifiable_atomic.to_string(),
             "pendingChangeAtomic": self.pending_change_atomic.to_string(),
             "outputsWithoutKeyImage": self.outputs_without_key_image,
+            "confirmingBlocksLeft": self.confirming_blocks_left,
         })
     }
 }
@@ -96,6 +99,12 @@ pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result 0 {
+                    b.confirming_blocks_left = b.confirming_blocks_left.max(Some(left));
+                }
             }
         }
     }
@@ -300,7 +309,10 @@ pub fn history(db: &Db, identity_id: i64, limit: u32, offset: u32) -> Result Result(6)? != 0,
                 "outgoingAtomic": r.get::<_, Option>(7)?,
                 "feeAtomic": r.get::<_, Option>(8)?.map(|fee| fee.to_string()),
+                // Paid to the account's primary address (subaddresses are not shown as ours).
+                "receivedOnPrimary": r.get::<_, bool>(9)?,
             }))
         })
         .map_err(|e| db_err("history", e))?;
@@ -605,6 +619,23 @@ mod tests {
         assert_eq!(spendable_rows(&db, id, 1_100).unwrap().len(), 2);
     }
 
+    #[test]
+    fn reports_how_many_blocks_the_youngest_output_still_waits() {
+        let (db, id) = db_with_identity();
+        add_output(&db, id, 100, 1_000, true);
+        add_output(&db, id, 200, 1_095, true);
+        add_output(&db, id, 300, 1_098, true);
+        // Chain length 1_101: the 1_095 output needs 4 more blocks, the 1_098 one 7.
+        let b = balance(&db, id, Some(1_100)).unwrap();
+        assert_eq!(b.unlocked_atomic, 100);
+        assert_eq!(b.confirming_blocks_left, Some(7));
+        assert_eq!(b.to_json()["confirmingBlocksLeft"], 7);
+
+        let settled = balance(&db, id, Some(1_200)).unwrap();
+        assert_eq!(settled.confirming_blocks_left, None);
+        assert!(settled.to_json()["confirmingBlocksLeft"].is_null());
+    }
+
     #[test]
     fn timestamp_locked_outputs_unlock_in_balance_and_selection() {
         let (db, id) = db_with_identity();
@@ -690,6 +721,42 @@ mod tests {
         assert_eq!(item["outgoingAtomic"], "1234");
     }
 
+    #[test]
+    fn a_receive_reports_its_fee_and_whether_it_reached_the_primary_address() {
+        let (db, id) = db_with_identity();
+        for (txid, subaddress) in [([6u8; 32], None), ([7u8; 32], Some(1i64))] {
+            db.conn()
+                .execute(
+                    "INSERT INTO transactions (identity_id, txid, height, direction, fee_atomic)
+                     VALUES (?1, ?2, 100, 'in', 30000000)",
+                    params![id, txid.as_slice()],
+                )
+                .unwrap();
+            db.conn()
+                .execute(
+                    "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx,
+                                          amount_atomic, height, subaddress_major, subaddress_minor)
+                     VALUES (?1, x'00', ?2, ?3, 0, 700, 100, ?4, ?4)",
+                    params![id, txid.as_slice(), txid[0] as i64, subaddress],
+                )
+                .unwrap();
+        }
+        let items = &history(&db, id, 10, 0).unwrap()["items"];
+        let by_txid = |txid: [u8; 32]| {
+            items
+                .as_array()
+                .unwrap()
+                .iter()
+                .find(|item| item["txid"] == hex::encode(txid))
+                .unwrap()
+                .clone()
+        };
+        let primary = by_txid([6u8; 32]);
+        assert_eq!(primary["feeAtomic"], "30000000");
+        assert_eq!(primary["receivedOnPrimary"], true);
+        assert_eq!(by_txid([7u8; 32])["receivedOnPrimary"], false);
+    }
+
     #[test]
     fn history_limit_is_clamped() {
         let (db, id) = db_with_identity();
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
index 689f41273..ba7806fab 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
@@ -321,8 +321,9 @@ pub fn scan_blocks(
     let mut tx_pub_keys: HashMap<[u8; 32], TxKeys> = HashMap::new();
     let mut spends: Vec<(u64, [u8; 32], [u8; 32])> = Vec::new(); // (height, key_image, txid)
 
-    // Fees of transactions that spend ours: history needs them to tell the payment from the fee.
-    let mut spend_fees: HashMap<[u8; 32], u64> = HashMap::new();
+    // Fees of transactions that pay or spend ours: history shows them, and needs them to tell
+    // a payment from its fee.
+    let mut tx_fees: HashMap<[u8; 32], u64> = HashMap::new();
     let mut block_rows: Vec<(u64, [u8; 32], Option, u64)> = Vec::new(); // (height, hash, ringct_next, ts)
 
     // Block before the batch start, for continuity and RingCT cursor checks.
@@ -390,7 +391,7 @@ pub fn scan_blocks(
                 tx_pub_keys.insert(txid, (keys, additional));
             }
         }
-        let spends_before = spends.len() + possible_spends.len();
+        let ours_before = found.len() + spends.len() + possible_spends.len();
         // Match inputs before adding this block's outputs as candidates: new
         // outputs are locked for at least 10 blocks and cannot be spent in the same block.
         for reference in ring_references_in(block) {
@@ -426,8 +427,8 @@ pub fn scan_blocks(
                 spends.push((height, key_image, txid));
             }
         }
-        if spends.len() + possible_spends.len() > spends_before {
-            spend_fees.extend(tx_fees_in(block));
+        if found.len() + spends.len() + possible_spends.len() > ours_before {
+            tx_fees.extend(tx_fees_in(block));
         }
 
         // Cursor base: the previous block's cursor, else the node's claimed start. Never fall
@@ -462,7 +463,7 @@ pub fn scan_blocks(
         &known_key_images,
         &block_rows,
         &possible_spends,
-        &spend_fees,
+        &tx_fees,
     )?;
     outcome.outputs_without_key_image = count_outputs_without_key_image(db, identity_id)?;
     Ok(outcome)
@@ -544,7 +545,7 @@ fn persist(
     known_key_images: &HashMap<[u8; 32], i64>,
     block_rows: &[(u64, [u8; 32], Option, u64)],
     possible_spends: &[PossibleSpend],
-    spend_fees: &HashMap<[u8; 32], u64>,
+    tx_fees: &HashMap<[u8; 32], u64>,
 ) -> Result<()> {
     let tx = db
         .conn_mut()
@@ -606,16 +607,18 @@ fn persist(
 
         if seen_txids.insert(txid) {
             tx.execute(
-                "INSERT INTO transactions (identity_id, txid, height, timestamp, direction)
-                 VALUES (?1, ?2, ?3, ?4, 'in')
+                "INSERT INTO transactions (identity_id, txid, height, timestamp, direction, fee_atomic)
+                 VALUES (?1, ?2, ?3, ?4, 'in', ?5)
                  ON CONFLICT (identity_id, txid) DO UPDATE
                    SET height = excluded.height, failed = 0, scan_valid = 1,
-                       timestamp = COALESCE(excluded.timestamp, transactions.timestamp)",
+                       timestamp = COALESCE(excluded.timestamp, transactions.timestamp),
+                       fee_atomic = COALESCE(excluded.fee_atomic, transactions.fee_atomic)",
                 params![
                     identity_id,
                     txid.as_slice(),
                     *height as i64,
-                    block_time.get(height)
+                    block_time.get(height),
+                    tx_fees.get(&txid).map(|fee| *fee as i64)
                 ],
             )
             .map_err(|e| db_err("insertIncomingTransaction", e))?;
@@ -645,7 +648,7 @@ fn persist(
                 txid.as_slice(),
                 *height as i64,
                 block_time.get(height),
-                spend_fees.get(txid).map(|fee| *fee as i64)
+                tx_fees.get(txid).map(|fee| *fee as i64)
             ],
         )
         .map_err(|e| db_err("insertOutgoingTransaction", e))?;
@@ -665,7 +668,7 @@ fn persist(
                 ps.spend_txid.as_slice(),
                 ps.height as i64,
                 ps.timestamp as i64,
-                spend_fees.get(&ps.spend_txid).map(|fee| *fee as i64)
+                tx_fees.get(&ps.spend_txid).map(|fee| *fee as i64)
             ],
         )
         .map_err(|e| db_err("insertPossibleSpend", e))?;

From f1d8e444365ddb624720032cb31dea8355250a71 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 04:47:24 +0800
Subject: [PATCH 84/97] test: cover the fee a Zcash receive reports

---
 .../zcash/crates/zcash-runtime/src/history.rs | 98 ++++++++++++++++++-
 1 file changed, 95 insertions(+), 3 deletions(-)

diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
index ae0d44d5e..e68fee8ac 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
@@ -1050,8 +1050,8 @@ mod tests {
     }
 }
 
-/// Recipients of transactions stored the way the wallet really stores them:
-/// decrypted by enhancement, or recorded by a local send.
+/// Recipients and fees of transactions stored the way the wallet really stores
+/// them: decrypted by enhancement, or recorded by a local send.
 #[cfg(test)]
 mod recipient_tests {
     use std::collections::HashMap;
@@ -1325,6 +1325,55 @@ mod recipient_tests {
         builder
             .add_output(None, recipient, NoteValue::from_raw(20_000), [0; 512])
             .unwrap();
+        let (bundle, meta) = authorize_placeholder(builder);
+        (bundle, meta.output_action_index(0).unwrap())
+    }
+
+    /// An Ironwood bundle in which a stranger spends a 30_000 note to pay
+    /// `recipient` 20_000, leaving 10_000 as the fee.
+    fn stranger_ironwood_payment(
+        recipient: orchard::Address,
+    ) -> orchard::Bundle {
+        use incrementalmerkletree::{Hashable, Level};
+        use orchard::keys::{FullViewingKey, Scope, SpendingKey};
+        use orchard::note::{RandomSeed, Rho};
+        use orchard::tree::{MerkleHashOrchard, MerklePath};
+
+        let version = BundleVersion::ironwood_v3();
+        let fvk = FullViewingKey::from(&SpendingKey::from_bytes([8; 32]).unwrap());
+        let rho = Rho::from_bytes(&[0; 32]).unwrap();
+        let note = orchard::Note::from_parts(
+            fvk.address_at(0u32, Scope::External),
+            NoteValue::from_raw(30_000),
+            rho,
+            RandomSeed::from_bytes([1; 32], &rho).unwrap(),
+            version.note_version(),
+        )
+        .unwrap();
+        let path = MerklePath::from_parts(
+            0,
+            std::array::from_fn(|level| MerkleHashOrchard::empty_root(Level::from(level as u8))),
+        );
+        let mut builder = OrchardBuilder::new(
+            BundleType::DEFAULT,
+            version,
+            version.default_flags(),
+            path.root(note.commitment().into()),
+        )
+        .unwrap();
+        builder.add_spend(fvk, note, path).unwrap();
+        builder
+            .add_output(None, recipient, NoteValue::from_raw(20_000), [0; 512])
+            .unwrap();
+        authorize_placeholder(builder).0
+    }
+
+    fn authorize_placeholder(
+        builder: OrchardBuilder,
+    ) -> (
+        orchard::Bundle,
+        orchard::builder::BundleMetadata,
+    ) {
         let mut rng = ChaCha20Rng::from_seed([3; 32]);
         let (bundle, meta) = builder.build::(&mut rng).unwrap().unwrap();
         let proof_len = Proof::expected_proof_size(bundle.actions().len());
@@ -1338,7 +1387,24 @@ mod recipient_tests {
                 )
             },
         );
-        (bundle, meta.output_action_index(0).unwrap())
+        (bundle, meta)
+    }
+
+    /// A transaction with no transparent part.
+    fn shielded_transaction(
+        ironwood: orchard::Bundle,
+    ) -> Transaction {
+        TransactionData::::from_parts_v6(
+            BranchId::Nu6_3,
+            0,
+            BlockHeight::from_u32(MINED + 40),
+            None,
+            None,
+            None,
+            Some(ironwood),
+        )
+        .freeze()
+        .unwrap()
     }
 
     fn transaction(
@@ -1492,6 +1558,32 @@ mod recipient_tests {
         assert_eq!(row["recipient"], first.encode(&NET));
     }
 
+    #[test]
+    fn an_enhanced_shielded_receive_reports_the_fee_its_sender_paid() {
+        let mut wallet = Wallet::new(1);
+        let receive = receive_address(&wallet.accounts[0].1);
+        let tx = shielded_transaction(stranger_ironwood_payment(*receive.orchard().unwrap()));
+        wallet.enhance(&tx);
+
+        let row = wallet.row(0, &tx);
+        assert_eq!(row["totalReceivedZat"], 20_000);
+        assert_eq!(row["feeZat"], 10_000);
+    }
+
+    #[test]
+    fn a_receive_spending_an_unknown_transparent_input_has_no_fee() {
+        let mut wallet = Wallet::new(1);
+        let receive = receive_address(&wallet.accounts[0].1);
+        let (bundle, _) = ironwood_payment(*receive.orchard().unwrap());
+        // Not the wallet's output: its value, and so the fee, is unknown.
+        let tx = transaction(OutPoint::new([6; 32], 0), vec![], Some(bundle));
+        wallet.enhance(&tx);
+
+        let row = wallet.row(0, &tx);
+        assert_eq!(row["totalReceivedZat"], 20_000);
+        assert_eq!(row["feeZat"], json!(null));
+    }
+
     #[test]
     fn unparseable_or_plain_addresses_are_returned_unchanged() {
         for pool in [0, 3, 4] {

From 62ffe206ae351ffbb77a0dbd400ffcea21a4b681 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 05:44:10 +0800
Subject: [PATCH 85/97] feat: record the payment ID of Monero receives

---
 .../monero/crates/monero-runtime/src/query.rs |  37 +++++-
 .../monero/crates/monero-runtime/src/scan.rs  | 122 +++++++++++++++++-
 .../crates/monero-runtime/src/schema.rs       |  19 +++
 3 files changed, 173 insertions(+), 5 deletions(-)

diff --git a/chain-runtimes/monero/crates/monero-runtime/src/query.rs b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
index 9634637b5..fe2ea895f 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/query.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
@@ -312,7 +312,9 @@ pub fn history(db: &Db, identity_id: i64, limit: u32, offset: u32) -> Result Result>(8)?.map(|fee| fee.to_string()),
                 // Paid to the account's primary address (subaddresses are not shown as ours).
                 "receivedOnPrimary": r.get::<_, bool>(9)?,
+                "paymentId": r.get::<_, Option>>(10)?.map(hex::encode),
             }))
         })
         .map_err(|e| db_err("history", e))?;
@@ -757,6 +760,38 @@ mod tests {
         assert_eq!(by_txid([7u8; 32])["receivedOnPrimary"], false);
     }
 
+    /// A send's scanned change decrypts the payment ID with our key, so only receives report it.
+    #[test]
+    fn only_receives_report_their_payment_id() {
+        let (db, id) = db_with_identity();
+        for (txid, direction, payment_id) in [
+            ([6u8; 32], "in", Some(vec![0xABu8; 8])),
+            ([7u8; 32], "out", Some(vec![0xCDu8; 8])),
+            ([8u8; 32], "in", None),
+        ] {
+            db.conn()
+                .execute(
+                    "INSERT INTO transactions (identity_id, txid, height, direction, payment_id)
+                     VALUES (?1, ?2, 100, ?3, ?4)",
+                    params![id, txid.as_slice(), direction, payment_id],
+                )
+                .unwrap();
+        }
+        let items = &history(&db, id, 10, 0).unwrap()["items"];
+        let payment_id = |txid: [u8; 32]| {
+            items
+                .as_array()
+                .unwrap()
+                .iter()
+                .find(|item| item["txid"] == hex::encode(txid))
+                .unwrap()["paymentId"]
+                .clone()
+        };
+        assert_eq!(payment_id([6u8; 32]), "abababababababab");
+        assert!(payment_id([7u8; 32]).is_null());
+        assert!(payment_id([8u8; 32]).is_null());
+    }
+
     #[test]
     fn history_limit_is_clamped() {
         let (db, id) = db_with_identity();
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
index ba7806fab..2b211062f 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
@@ -11,6 +11,7 @@ use std::collections::{HashMap, HashSet};
 
 use monero_wallet::{
     address::SubaddressIndex,
+    extra::PaymentId,
     interface::ScannableBlock,
     transaction::{Input, Transaction},
     Scanner, WalletOutput,
@@ -282,6 +283,16 @@ fn tx_public_keys_from_extra(extra: &[u8]) -> Option<(Vec, Option>)>
     Some((flatten(&keys), additional.as_deref().map(flatten)))
 }
 
+/// Payment ID bytes worth showing: `None` when absent or all zeros, the dummy wallet2 encrypts
+/// into ordinary two-output transactions.
+fn shown_payment_id(payment_id: Option) -> Option> {
+    let bytes = match payment_id? {
+        PaymentId::Encrypted(id) => id.to_vec(),
+        PaymentId::Unencrypted(id) => id.to_vec(),
+    };
+    bytes.iter().any(|b| *b != 0).then_some(bytes)
+}
+
 /// Scans and persists a batch of blocks in one transaction: all or nothing.
 ///
 /// Blocks must be contiguous in ascending height. The host fetches them by range.
@@ -559,6 +570,13 @@ fn persist(
         .iter()
         .map(|(h, _, _, ts)| (*h, *ts as i64))
         .collect();
+    // First non-dummy payment ID per transaction, in output order.
+    let mut payment_ids: HashMap<[u8; 32], Vec> = HashMap::new();
+    for (_, output) in found {
+        if let Some(id) = shown_payment_id(output.payment_id()) {
+            payment_ids.entry(output.transaction()).or_insert(id);
+        }
+    }
 
     for (height, output) in found {
         let txid = output.transaction();
@@ -607,18 +625,20 @@ fn persist(
 
         if seen_txids.insert(txid) {
             tx.execute(
-                "INSERT INTO transactions (identity_id, txid, height, timestamp, direction, fee_atomic)
-                 VALUES (?1, ?2, ?3, ?4, 'in', ?5)
+                "INSERT INTO transactions (identity_id, txid, height, timestamp, direction, fee_atomic, payment_id)
+                 VALUES (?1, ?2, ?3, ?4, 'in', ?5, ?6)
                  ON CONFLICT (identity_id, txid) DO UPDATE
                    SET height = excluded.height, failed = 0, scan_valid = 1,
                        timestamp = COALESCE(excluded.timestamp, transactions.timestamp),
-                       fee_atomic = COALESCE(excluded.fee_atomic, transactions.fee_atomic)",
+                       fee_atomic = COALESCE(excluded.fee_atomic, transactions.fee_atomic),
+                       payment_id = COALESCE(excluded.payment_id, transactions.payment_id)",
                 params![
                     identity_id,
                     txid.as_slice(),
                     *height as i64,
                     block_time.get(height),
-                    tx_fees.get(&txid).map(|fee| *fee as i64)
+                    tx_fees.get(&txid).map(|fee| *fee as i64),
+                    payment_ids.get(&txid)
                 ],
             )
             .map_err(|e| db_err("insertIncomingTransaction", e))?;
@@ -1346,4 +1366,98 @@ mod tests {
         assert_eq!(outcome.outputs_found, 0);
         assert!(outcome.from_height.is_none());
     }
+
+    #[test]
+    fn only_a_non_zero_payment_id_is_shown() {
+        assert_eq!(shown_payment_id(None), None);
+        assert_eq!(shown_payment_id(Some(PaymentId::Encrypted([0; 8]))), None);
+        assert_eq!(
+            shown_payment_id(Some(PaymentId::Unencrypted([0; 32]))),
+            None
+        );
+        assert_eq!(
+            shown_payment_id(Some(PaymentId::Encrypted([0, 0, 0, 0, 0, 0, 0, 1]))),
+            Some(vec![0, 0, 0, 0, 0, 0, 0, 1])
+        );
+        assert_eq!(
+            shown_payment_id(Some(PaymentId::Unencrypted([7; 32]))),
+            Some(vec![7; 32])
+        );
+    }
+
+    // Vector from monero-wallet 0.2.0 `src/tests/scan.rs`: a transaction paying these keys two
+    // outputs, with wallet2's dummy encrypted payment ID (it decrypts to zeros).
+    const VECTOR_SPEND_KEY: &str =
+        "ccf0ea10e1ea64354f42fa710c2b318e581969cf49046d809d1f0aadb3fc7a02";
+    const VECTOR_VIEW_KEY: &str =
+        "a28b4b2085592881df94ee95da332c16b5bb773eb8bb74730208cbb236c73806";
+    #[rustfmt::skip]
+    const VECTOR_TX: &str = "020001020003060101cf60390bb71aa15eb24037772012d59dc68cb4b6211e1c93206db09a6c346261020002ee8ca293511571c0005e1c144e49d09b8ff03046dbafb3e064a34cb9fc1994b600029e2e5cd08c8681dbcf2ce66071467e835f7e86613fbfed3c4fb170127b94e1072c01d3ce2a622c6e06ed465f81017dd6188c3a6e3d8e65a846f9c98416da0e150a82020901c553d35e54111bd001e0bbcbf289d701ce90e309ead2b487ec1d4d8af5d649543eb99a7620f6b54e532898527be29704f050e6f06de61e5967b2ddd506b4d6d36546065d6aae156ac7bec18c99580c07867fb98cb29853edbafec91af2df605c12f9aaa81a9165625afb6649f5a652012c5ba6612351140e1fb4a8463cc765d0a9bb7d999ba35750f365c5285d77230b76c7a612784f4845812a2899f2ca6a304fee61362db59b263115c27d2ce78af6b1d9e939c1f4036c7707851f41abe6458cf1c748353e593469ebf43536a939f7";
+    #[rustfmt::skip]
+    const VECTOR_BLOCK: &str = "0202e8e28efe04db09e2fc4d57854786220bd33e0169ff692440d27ae3932b9219df9ab1d7260b00000000014101ff050580d0acf30e02704972eb1878e94686b62fa4c0202f3e7e3a263073bd6edd751990ea769494ee80c0fc82aa0202edac72ab7c5745d4acaa95f76a3b76e238a55743cd51efb586f968e09821788d80d0dbc3f40202f9b4cf3141aac4203a1aaed01f09326615544997d1b68964928d9aafd07e38e580a0e5b9c29101023405e3aa75b1b7adf04e8c7faa3c3d45616ae740a8b11fb7cc1555dd8b9e4c9180c0dfda8ee90602d2b78accfe1c2ae57bed4fe3385f7735a988f160ef3bbc1f9d7a0c911c26ffd92101d2d55b5066d247a97696be4a84bf70873e4f149687f57e606eb6682f11650e1701b74773bbea995079805398052da9b69244bda034b089b50e4d9151dedb59a12f";
+    /// Extra nonce in `VECTOR_TX`: tag, length, encrypted marker, then the 8 encrypted bytes.
+    /// Encryption XORs a mask derived from the shared secret, so these bytes are the mask.
+    const VECTOR_NONCE_PREFIX: &str = "020901";
+    const VECTOR_PAYMENT_ID_MASK: [u8; 8] = [0xc5, 0x53, 0xd3, 0x5e, 0x54, 0x11, 0x1b, 0xd0];
+
+    /// Scans the vector block, its encrypted payment ID swapped for `encrypted`, into a fresh
+    /// wallet; returns the history row and the stored `payment_id`.
+    fn scan_vector_with(encrypted: [u8; 8]) -> (serde_json::Value, Option>) {
+        use monero_wallet::{block::Block, transaction::Pruned};
+
+        let spend: [u8; 32] = hex::decode(VECTOR_SPEND_KEY).unwrap().try_into().unwrap();
+        let spend_public = (curve25519_dalek::constants::ED25519_BASEPOINT_POINT
+            * curve25519_dalek::Scalar::from_bytes_mod_order(spend))
+        .compress()
+        .to_bytes();
+        let view: [u8; 32] = hex::decode(VECTOR_VIEW_KEY).unwrap().try_into().unwrap();
+        let mut db = crate::wallet::testing::db();
+        let id = db
+            .add_identity("vector", &spend_public, &view, 0)
+            .unwrap()
+            .id;
+
+        let original = format!(
+            "{VECTOR_NONCE_PREFIX}{}",
+            hex::encode(VECTOR_PAYMENT_ID_MASK)
+        );
+        assert_eq!(VECTOR_TX.matches(&original).count(), 1);
+        let tx_hex = VECTOR_TX.replace(
+            &original,
+            &format!("{VECTOR_NONCE_PREFIX}{}", hex::encode(encrypted)),
+        );
+        let block = ScannableBlock {
+            block: Block::read(&mut hex::decode(VECTOR_BLOCK).unwrap().as_slice()).unwrap(),
+            transactions: vec![Transaction::::read(
+                &mut hex::decode(tx_hex).unwrap().as_slice(),
+            )
+            .unwrap()],
+            output_index_for_first_ringct_output: Some(0),
+        };
+        assert_eq!(scan_blocks(&mut db, id, &[block]).unwrap().outputs_found, 2);
+
+        let stored = db
+            .conn()
+            .query_row("SELECT payment_id FROM transactions", [], |r| r.get(0))
+            .unwrap();
+        let item = crate::query::history(&db, id, 10, 0).unwrap()["items"][0].clone();
+        (item, stored)
+    }
+
+    #[test]
+    fn the_dummy_payment_id_of_a_real_transaction_is_not_stored() {
+        let (item, stored) = scan_vector_with(VECTOR_PAYMENT_ID_MASK);
+        assert_eq!(item["direction"], "in");
+        assert_eq!(stored, None);
+        assert!(item["paymentId"].is_null());
+    }
+
+    #[test]
+    fn a_receive_reports_its_decrypted_payment_id() {
+        let wanted = [0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef];
+        let encrypted: [u8; 8] = core::array::from_fn(|i| VECTOR_PAYMENT_ID_MASK[i] ^ wanted[i]);
+        let (item, stored) = scan_vector_with(encrypted);
+        assert_eq!(stored, Some(wanted.to_vec()));
+        assert_eq!(item["paymentId"], "1234567890abcdef");
+    }
 }
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
index 09758807a..45398ff83 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
@@ -205,6 +205,9 @@ CREATE TABLE IF NOT EXISTS transactions (
     change_atomic   TEXT,
     -- Network fee, piconero, read from the scanned spending transaction.
     fee_atomic      INTEGER,
+    -- Payment ID decrypted with the view key when an output of the tx is scanned (8 bytes, or
+    -- 32 for a pre-v12 unencrypted one). NULL when absent or all zeros (wallet2's dummy).
+    payment_id      BLOB    CHECK (payment_id IS NULL OR length(payment_id) IN (8, 32)),
     -- 0 while a rescan or reorg re-verifies the row; shown without a height until seen again
     scan_valid      INTEGER NOT NULL DEFAULT 1 CHECK (scan_valid IN (0, 1)),
     PRIMARY KEY (identity_id, txid)
@@ -296,6 +299,22 @@ mod tests {
         assert_eq!(additional, None);
     }
 
+    /// Only an 8-byte (encrypted) or 32-byte (legacy) payment ID fits.
+    #[test]
+    fn a_payment_id_must_be_8_or_32_bytes() {
+        let (db, identity_id) = crate::wallet::testing::db_with_identity();
+        let insert = |txid: u8, payment_id: Vec| {
+            db.conn().execute(
+                "INSERT INTO transactions (identity_id, txid, direction, payment_id)
+                 VALUES (?1, ?2, 'in', ?3)",
+                rusqlite::params![identity_id, vec![txid; 32], payment_id],
+            )
+        };
+        insert(1, vec![1; 8]).expect("encrypted payment ID");
+        insert(2, vec![1; 32]).expect("legacy payment ID");
+        assert!(insert(3, vec![1; 9]).is_err());
+    }
+
     #[test]
     fn migrate_is_idempotent() {
         let conn = db();

From 8d6d94eefaa8b6b2f75126529f8ed85ac5e17165 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 05:44:10 +0800
Subject: [PATCH 86/97] feat: plan, assemble and verify Monero transactions
 signed on a hardware wallet

---
 .../crates/monero-runtime/src/bindgen.rs      |   98 +-
 .../monero-runtime/src/device_key_images.rs   |   65 +-
 .../crates/monero-runtime/src/device_sign.rs  | 2350 +++++++++++++++++
 .../monero/crates/monero-runtime/src/lib.rs   |    1 +
 .../crates/monero-runtime/src/review.rs       |   17 +-
 .../monero/crates/monero-runtime/src/spend.rs |   78 +-
 6 files changed, 2548 insertions(+), 61 deletions(-)
 create mode 100644 chain-runtimes/monero/crates/monero-runtime/src/device_sign.rs

diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
index ec9b51b01..52af2d606 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -11,7 +11,7 @@ use wasm_bindgen::prelude::*;
 use crate::error::{ErrorCode, Result, RuntimeError};
 use zeroize::Zeroizing;
 
-use crate::{device_key_images, keys, query, runtime, spend, storage, sync, wallet};
+use crate::{device_key_images, device_sign, keys, query, runtime, spend, storage, sync, wallet};
 
 fn json(value: serde_json::Value) -> std::result::Result {
     Ok(value.to_string())
@@ -403,27 +403,52 @@ pub async fn prepare_transaction(
     chain_tip: u64,
     priority: &str,
 ) -> std::result::Result {
-    let recipients: Vec = serde_json::from_str(recipients_json).map_err(|e| {
-        JsValue::from(
-            RuntimeError::with(
-                ErrorCode::InvalidRequest,
-                serde_json::json!({ "field": "recipientsJson" }),
-            )
-            .detail(e),
-        )
-    })?;
-    if recipients.is_empty() {
-        return Err(RuntimeError::with(
-            ErrorCode::InvalidRequest,
-            serde_json::json!({ "field": "recipientsJson", "reason": "empty" }),
+    let recipients = parse_recipients(recipients_json)?;
+    let fee_priority = spend::parse_priority(priority)?;
+
+    let v = runtime::with_db_and_daemon(move |db, daemon| async move {
+        let r = spend::prepare_for_host(
+            &db,
+            &daemon,
+            account_id,
+            &recipients
+                .iter()
+                .map(|r| (r.address.as_str(), r.amount_atomic.as_str()))
+                .collect::>(),
+            max_send,
+            chain_tip,
+            fee_priority,
         )
-        .into());
-    }
+        .await;
+        (db, daemon, r)
+    })
+    .await?;
 
+    json(v)
+}
+
+/// Select inputs and build the plan a hardware wallet signs. Same arguments, selection and
+/// fee as `prepareTransaction`; every selected output needs a key image (sync them from the
+/// device first), else `INVALID_REQUEST` with `reason: keyImageRequired`.
+///
+/// Returns `{ devicePlan, feeAtomic, amountAtomic, changeAtomic, inputsAtomic, inputCount }`.
+/// `devicePlan` is a JSON string `{ version, networkType, tsxData, inputs, expected }`: the
+/// device gets `tsxData` and `inputs`; the whole plan goes to `assembleDeviceTransaction` and,
+/// in place of `signableHex`, to `verifySignedTransaction` and `broadcastTransaction`. It holds
+/// the private view key, the real ring members and the masks: never log or persist it.
+#[wasm_bindgen(js_name = prepareDeviceTransaction)]
+pub async fn prepare_device_transaction(
+    account_id: i64,
+    recipients_json: &str,
+    max_send: bool,
+    chain_tip: u64,
+    priority: &str,
+) -> std::result::Result {
+    let recipients = parse_recipients(recipients_json)?;
     let fee_priority = spend::parse_priority(priority)?;
 
     let v = runtime::with_db_and_daemon(move |db, daemon| async move {
-        let r = spend::prepare_for_host(
+        let r = device_sign::prepare_for_host(
             &db,
             &daemon,
             account_id,
@@ -443,6 +468,20 @@ pub async fn prepare_transaction(
     json(v)
 }
 
+/// Rebuild and verify the transaction a hardware wallet signed from `devicePlanJson`.
+///
+/// `signedJson` is the device result with its CLSAGs opened (`clsags`). Checks the device's
+/// prefix and message hashes, the range proof, every CLSAG against its planned ring and
+/// stored key image, the balance, the fee against the weight, and the change against the
+/// plan with the view key. No DB or network. Returns `{ txid, rawHex }`.
+#[wasm_bindgen(js_name = assembleDeviceTransaction)]
+pub fn assemble_device_transaction(
+    device_plan_json: &str,
+    signed_json: &str,
+) -> std::result::Result {
+    json(device_sign::assemble(device_plan_json, signed_json)?)
+}
+
 /// Sign a prepared transaction. No network, no DB, no broadcast.
 ///
 /// Takes the account's BIP-32 key (as `deriveAccount`); the spend key is reduced here and
@@ -464,16 +503,21 @@ pub fn sign_transaction_with_bip32_key(
 }
 
 /// Validate actual payment effects before the host presents its confirmation.
+/// `signableHex` may be a device plan instead.
 #[wasm_bindgen(js_name = verifyTransaction)]
 pub fn verify_transaction(
     signable_hex: &str,
     review_json: &str,
 ) -> std::result::Result<(), JsValue> {
     let request = crate::review::parse_request(review_json)?;
-    crate::review::verify(signable_hex, &request, None)?;
+    crate::review::verify_unsigned(signable_hex, &request)?;
     Ok(())
 }
 
+/// Check a signed transaction against what was reviewed; returns its txid.
+///
+/// `signableHex` may be a device plan (a JSON object) from `prepareDeviceTransaction`; the
+/// device-built transaction is then checked as in `assembleDeviceTransaction`.
 #[wasm_bindgen(js_name = verifySignedTransaction)]
 pub fn verify_signed_transaction(
     signable_hex: &str,
@@ -490,6 +534,7 @@ pub fn verify_signed_transaction(
 /// Accepted and uncertain (network error) outcomes are both recorded: spent outputs
 /// are marked, the transaction goes in flight, and `broadcast: accepted | unknown` is
 /// returned. Only an explicit node rejection errors and releases the inputs.
+/// `signableHex` may be a device plan, as in `verifySignedTransaction`.
 #[wasm_bindgen(js_name = broadcastTransaction)]
 pub async fn broadcast_transaction(
     account_id: i64,
@@ -530,6 +575,23 @@ pub async fn broadcast_transaction(
     json(v)
 }
 
+fn parse_recipients(recipients_json: &str) -> Result> {
+    let recipients: Vec = serde_json::from_str(recipients_json).map_err(|e| {
+        RuntimeError::with(
+            ErrorCode::InvalidRequest,
+            serde_json::json!({ "field": "recipientsJson" }),
+        )
+        .detail(e)
+    })?;
+    if recipients.is_empty() {
+        return Err(RuntimeError::with(
+            ErrorCode::InvalidRequest,
+            serde_json::json!({ "field": "recipientsJson", "reason": "empty" }),
+        ));
+    }
+    Ok(recipients)
+}
+
 #[derive(serde::Deserialize)]
 struct RecipientJson {
     address: String,
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs b/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs
index 7abbee4c9..e8a754c33 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs
@@ -78,27 +78,21 @@ pub fn export_sync_data(db: &Db, identity_id: i64) -> Result {
         let major = u32::try_from(major.unwrap_or(0)).map_err(|_| corrupt("bad subaddress"))?;
         let minor = u32::try_from(minor.unwrap_or(0)).map_err(|_| corrupt("bad subaddress"))?;
 
-        let first = &tx_keys[..32];
-        let tx_pub_key = if tx_keys.len() == 32 {
-            first
-        } else {
-            let spend = receiving_spend_key(db, &identity, major, minor);
-            // None matching means the output was received via its additional key.
-            tx_keys
-                .chunks_exact(32)
-                .find(|r| derives_output_key(&view, r, index, spend, &output_key))
-                .unwrap_or(first)
-        };
-        let additional = additional
-            .as_deref()
-            .and_then(|a| a.chunks_exact(32).nth(index as usize))
-            .map(hex::encode);
+        let spend = receiving_spend_key(db, &identity, major, minor);
+        let (tx_pub_key, additional) = real_tx_keys(
+            &view,
+            spend,
+            &tx_keys,
+            additional.as_deref(),
+            index,
+            &output_key,
+        );
 
         items.push(json!({
             "outputId": id,
             "outKey": hex::encode(output_key),
             "txPubKey": hex::encode(tx_pub_key),
-            "additionalTxPubKey": additional,
+            "additionalTxPubKey": additional.map(hex::encode),
             "internalOutputIndex": index,
             "subAddrMajor": major,
             "subAddrMinor": minor,
@@ -107,7 +101,35 @@ pub fn export_sync_data(db: &Db, identity_id: i64) -> Result {
     Ok(json!({ "items": items }))
 }
 
-fn view_scalar(db: &Db, identity_id: i64) -> Result> {
+/// The R a device derives output `index` from, and that output's additional key if any.
+///
+/// Among several R the one deriving `output_key` is chosen; when none does, the output
+/// was received via its additional key and the first R is returned.
+pub(crate) fn real_tx_keys<'a>(
+    view: &curve25519_dalek::Scalar,
+    spend: EdwardsPoint,
+    tx_keys: &'a [u8],
+    additional: Option<&'a [u8]>,
+    index: u32,
+    output_key: &[u8; 32],
+) -> (&'a [u8], Option<&'a [u8]>) {
+    let first = &tx_keys[..32];
+    let tx_pub_key = if tx_keys.len() == 32 {
+        first
+    } else {
+        tx_keys
+            .chunks_exact(32)
+            .find(|r| derives_output_key(view, r, index, spend, output_key))
+            .unwrap_or(first)
+    };
+    let additional = additional.and_then(|a| a.chunks_exact(32).nth(index as usize));
+    (tx_pub_key, additional)
+}
+
+pub(crate) fn view_scalar(
+    db: &Db,
+    identity_id: i64,
+) -> Result> {
     let bytes: Zeroizing> = Zeroizing::new(
         db.conn()
             .query_row(
@@ -121,7 +143,12 @@ fn view_scalar(db: &Db, identity_id: i64) -> Result EdwardsPoint {
+pub(crate) fn receiving_spend_key(
+    db: &Db,
+    identity: &Identity,
+    major: u32,
+    minor: u32,
+) -> EdwardsPoint {
     match SubaddressIndex::new(major, minor) {
         Some(index) => identity
             .view_pair
@@ -133,7 +160,7 @@ fn receiving_spend_key(db: &Db, identity: &Identity, major: u32, minor: u32) ->
 }
 
 /// Whether `Hs(8·a·R || index)·G + spend` is the output key.
-fn derives_output_key(
+pub(crate) fn derives_output_key(
     view: &curve25519_dalek::Scalar,
     r: &[u8],
     index: u32,
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/device_sign.rs b/chain-runtimes/monero/crates/monero-runtime/src/device_sign.rs
new file mode 100644
index 000000000..cd158806d
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/device_sign.rs
@@ -0,0 +1,2350 @@
+//! Hardware wallet signing (the Trezor Monero protocol, as OneKey firmware runs it).
+//!
+//! The device draws its own tx key, output masks and pseudo-out blinding, so neither
+//! monero-oxide's `SignableTransaction` nor its `Eventuality` can describe what it signs.
+//! A device plan carries the inputs, rings and destinations instead, and the transaction
+//! the device returns is rebuilt and checked against it. The recipient output cannot be
+//! re-derived without the device's tx key; the device shows it to the user.
+//!
+//! The plan is as private as `signableHex`: real ring members, masks, amounts and the
+//! private view key. Never log or persist it.
+
+use std::collections::{BTreeSet, HashSet};
+
+use curve25519_dalek::{constants::ED25519_BASEPOINT_POINT, traits::IsIdentity as _, EdwardsPoint};
+use monero_wallet::{
+    address::{AddressType, MoneroAddress, Network},
+    ed25519::{Commitment, CompressedPoint, Point, Scalar},
+    extra::{Extra, MAX_EXTRA_SIZE_BY_RELAY_RULE},
+    interface::FeeRate,
+    io::VarInt,
+    primitives::keccak256,
+    ringct::{
+        bulletproofs::Bulletproof, clsag::Clsag, EncryptedAmount, RctBase, RctProofs, RctPrunable,
+        RctType,
+    },
+    transaction::{Input, NotPruned, Output, Timelock, Transaction, TransactionPrefix},
+    OutputWithDecoys,
+};
+use rand_core::{CryptoRng, RngCore};
+use rusqlite::OptionalExtension;
+use serde::{de::Error as _, Deserialize, Deserializer, Serialize, Serializer};
+use serde_json::{json, Value};
+use zeroize::{Zeroize, Zeroizing};
+
+use crate::device_key_images::{
+    derives_output_key, real_tx_keys, receiving_spend_key, view_scalar,
+};
+use crate::error::{db_err, ErrorCode, Result, RuntimeError};
+use crate::keys;
+use crate::review::{self, ReviewRequest};
+use crate::spend::{self, Prepared, FEE_QUANTIZATION_MASK, RING_LEN};
+use crate::wallet::{Db, Identity};
+
+const PLAN_VERSION: u32 = 1;
+/// `MoneroTransactionData.version`.
+const TSX_VERSION: u32 = 1;
+/// Lowest host protocol version the firmware accepts (sealed CLSAGs).
+const CLIENT_VERSION: u32 = 3;
+/// The firmware defaults a missing hard fork to 12 and refuses it; view tags need 15+.
+const HARD_FORK: u32 = 16;
+/// `RangeProofPaddedBulletproof`, as wallet2 sends.
+const RSIG_TYPE: u32 = 3;
+/// Bulletproof+.
+const BP_VERSION: u32 = 4;
+/// Recipient and change: the device proves the Bulletproof+ itself only up to two outputs.
+const OUTPUTS: usize = 2;
+/// Same bound as `signableHex`.
+const MAX_HEX_LEN: usize = 8 * 1024 * 1024;
+
+const G: EdwardsPoint = ED25519_BASEPOINT_POINT;
+
+/// What `prepareDeviceTransaction` returns as `devicePlan`; field names follow the
+/// firmware protobuf messages (`MoneroTransactionData`, `...SourceEntry`, `...DestinationEntry`).
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DevicePlan {
+    pub version: u32,
+    /// `MoneroNetworkType`: 0 mainnet, 1 testnet, 2 stagenet.
+    pub network_type: u32,
+    pub tsx_data: TsxData,
+    /// Original order; the device sorts by key image itself.
+    pub inputs: Vec,
+    /// Read by this runtime only; not sent to the device.
+    pub expected: Expected,
+}
+
+#[derive(Serialize, Deserialize)]
+pub struct TsxData {
+    pub version: u32,
+    pub client_version: u32,
+    pub hard_fork: u32,
+    pub unlock_time: u64,
+    pub num_inputs: u32,
+    pub mixin: u32,
+    #[serde(with = "atomic")]
+    pub fee: u64,
+    pub account: u32,
+    pub minor_indices: Vec,
+    pub outputs: Vec,
+    pub change_dts: DestinationEntry,
+    pub rsig_data: RsigData,
+    /// Integrated recipients only; otherwise the device adds a dummy one.
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub payment_id: Option,
+    pub integrated_indices: Vec,
+}
+
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct DestinationEntry {
+    #[serde(with = "atomic")]
+    pub amount: u64,
+    pub addr: AccountPublicAddress,
+    pub is_subaddress: bool,
+    pub is_integrated: bool,
+}
+
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct AccountPublicAddress {
+    pub spend_public_key: String,
+    pub view_public_key: String,
+}
+
+#[derive(PartialEq, Eq, Serialize, Deserialize)]
+pub struct RsigData {
+    pub rsig_type: u32,
+    pub bp_version: u32,
+    pub grouping: Vec,
+}
+
+#[derive(Serialize, Deserialize)]
+pub struct SourceEntry {
+    /// The ring, ascending by global index (the device derives `key_offsets` from it).
+    pub outputs: Vec,
+    pub real_output: u64,
+    pub real_out_tx_key: String,
+    /// Only this output's additional key; the device reads one element as that.
+    pub real_out_additional_tx_keys: Vec,
+    pub real_output_in_tx_index: u64,
+    #[serde(with = "atomic")]
+    pub amount: u64,
+    pub rct: bool,
+    pub mask: String,
+    pub subaddr_minor: u32,
+}
+
+#[derive(Serialize, Deserialize)]
+pub struct OutputEntry {
+    pub idx: u64,
+    pub key: RctKeyPublic,
+}
+
+#[derive(Serialize, Deserialize)]
+pub struct RctKeyPublic {
+    pub dest: String,
+    pub commitment: String,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Expected {
+    /// From the stored outputs, per input in original order.
+    pub key_images: Vec,
+    #[serde(with = "atomic")]
+    pub fee: u64,
+    #[serde(with = "atomic")]
+    pub recipient_amount: u64,
+    #[serde(with = "atomic")]
+    pub change_amount: u64,
+    /// The node's fee rate the fee was computed with.
+    #[serde(with = "atomic")]
+    pub fee_per_weight: u64,
+    /// The account's private view key, to find the change in the signed transaction.
+    pub view_key: SecretKeyHex,
+}
+
+/// A 32-byte secret as hex, wiped on drop (including the decoded string).
+pub struct SecretKeyHex(Zeroizing<[u8; 32]>);
+
+impl Serialize for SecretKeyHex {
+    fn serialize(&self, serializer: S) -> std::result::Result {
+        serializer.serialize_str(&Zeroizing::new(hex::encode(*self.0)))
+    }
+}
+
+impl<'de> Deserialize<'de> for SecretKeyHex {
+    fn deserialize>(deserializer: D) -> std::result::Result {
+        let mut text = String::deserialize(deserializer)?;
+        let mut key = Zeroizing::new([0u8; 32]);
+        let decoded = hex::decode_to_slice(&text, key.as_mut_slice());
+        text.zeroize();
+        decoded.map_err(|_| D::Error::custom("not a 32-byte hex key"))?;
+        Ok(Self(key))
+    }
+}
+
+/// Piconero amounts cross the boundary as canonical decimal strings.
+mod atomic {
+    use super::*;
+
+    pub fn serialize(
+        value: &u64,
+        serializer: S,
+    ) -> std::result::Result {
+        serializer.serialize_str(&value.to_string())
+    }
+
+    pub fn deserialize<'de, D: Deserializer<'de>>(
+        deserializer: D,
+    ) -> std::result::Result {
+        let text = String::deserialize(deserializer)?;
+        text.parse::()
+            .ok()
+            .filter(|value| value.to_string() == text)
+            .ok_or_else(|| D::Error::custom("not a canonical decimal amount"))
+    }
+}
+
+/// The device's result with its CLSAGs opened (contract §4).
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DeviceSigned {
+    /// Plan input index of each sorted input.
+    pub orig_indices: Vec,
+    /// Sorted order, as are `pseudo_outs` and `clsags`.
+    pub vinis: Vec,
+    pub pseudo_outs: Vec,
+    /// `varint(ring_len) || s[ring_len] || c1 || D`.
+    pub clsags: Vec,
+    /// Output (`tsxData.outputs`) order, as are `out_pks` and `ecdh_infos`.
+    pub tx_outs: Vec,
+    pub out_pks: Vec,
+    pub ecdh_infos: Vec,
+    pub rsig: String,
+    pub extra: String,
+    pub tx_prefix_hash: String,
+    pub full_message_hash: String,
+    pub rv: RingCtSig,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RingCtSig {
+    #[serde(deserialize_with = "atomic::deserialize")]
+    pub txn_fee: u64,
+    pub message: String,
+    pub rv_type: u8,
+}
+
+fn invalid_plan(reason: &str) -> RuntimeError {
+    RuntimeError::with(
+        ErrorCode::InvalidRequest,
+        json!({ "field": "devicePlan", "reason": reason }),
+    )
+}
+
+/// The device's transaction fails a check against the plan.
+fn rejected(reason: &str) -> RuntimeError {
+    RuntimeError::with(
+        ErrorCode::InvalidRequest,
+        json!({ "field": "deviceTransaction", "reason": reason }),
+    )
+}
+
+fn hex32(value: &str) -> Option<[u8; 32]> {
+    let mut out = [0u8; 32];
+    hex::decode_to_slice(value, &mut out).ok()?;
+    Some(out)
+}
+
+fn hex_bytes(value: &str) -> Option> {
+    if value.len() > MAX_HEX_LEN {
+        return None;
+    }
+    hex::decode(value).ok()
+}
+
+fn point(value: &str) -> Option {
+    CompressedPoint::from(hex32(value)?)
+        .decompress()
+        .map(Point::into)
+}
+
+fn hex_point(point: EdwardsPoint) -> String {
+    hex::encode(point.compress().to_bytes())
+}
+
+fn public_address(spend: Point, view: Point) -> AccountPublicAddress {
+    AccountPublicAddress {
+        spend_public_key: hex::encode(spend.compress().to_bytes()),
+        view_public_key: hex::encode(view.compress().to_bytes()),
+    }
+}
+
+fn device_network_type(network: Network) -> u32 {
+    match network {
+        Network::Mainnet => 0,
+        Network::Testnet => 1,
+        Network::Stagenet => 2,
+    }
+}
+
+fn network_from_type(network_type: u32) -> Option {
+    match network_type {
+        0 => Some(Network::Mainnet),
+        1 => Some(Network::Testnet),
+        2 => Some(Network::Stagenet),
+        _ => None,
+    }
+}
+
+/// `(is_subaddress, payment id)` of a recipient, or `None` for an address the device
+/// cannot pay (featured addresses).
+fn destination_kind(address: &MoneroAddress) -> Option<(bool, Option<[u8; 8]>)> {
+    match address.kind() {
+        AddressType::Legacy => Some((false, None)),
+        AddressType::LegacyIntegrated(id) => Some((false, Some(*id))),
+        AddressType::Subaddress => Some((true, None)),
+        AddressType::Featured { .. } => None,
+    }
+}
+
+/// `8·R/8`, as wallet2 sends tx keys (`pubkey_clear_torsion`); the device's `8·a·R` is unchanged.
+fn clear_torsion(key: &[u8]) -> Option {
+    let key = <[u8; 32]>::try_from(key).ok()?;
+    let key: EdwardsPoint = CompressedPoint::from(key).decompress()?.into();
+    Some(hex_point(key.mul_by_cofactor() * Scalar::INV_EIGHT.into()))
+}
+
+/// First absolute index, then each one's distance from the previous.
+fn relative_offsets(positions: &[u64]) -> Option> {
+    let mut offsets = Vec::with_capacity(positions.len());
+    for (i, position) in positions.iter().enumerate() {
+        offsets.push(if i == 0 {
+            *position
+        } else {
+            position
+                .checked_sub(positions[i - 1])
+                .filter(|offset| *offset > 0)?
+        });
+    }
+    Some(offsets)
+}
+
+/// `keccak(varint(2) || prefix)`; oxide keeps the prefix hash private.
+pub(crate) fn prefix_hash(prefix: &TransactionPrefix) -> [u8; 32] {
+    // Without proofs a V2 transaction serializes as its version, prefix and one 0 byte.
+    let mut bytes = Transaction::::V2 {
+        prefix: prefix.clone(),
+        proofs: None,
+    }
+    .serialize();
+    bytes.pop();
+    keccak256(bytes)
+}
+
+pub fn is_device_plan(value: &str) -> bool {
+    value.trim_start().starts_with('{')
+}
+
+// ── Plan ──
+
+/// Selects inputs and builds the plan a hardware wallet signs. Same selection, rings and
+/// fee as `prepareTransaction`; every input must carry a key image (device key image sync).
+#[allow(clippy::too_many_arguments)]
+pub async fn prepare_for_host(
+    db: &Db,
+    daemon: &crate::network::Daemon,
+    identity_id: i64,
+    recipients: &[(&str, &str)],
+    max_send: bool,
+    chain_tip: u64,
+    priority: monero_wallet::interface::FeePriority,
+) -> Result {
+    let (prepared, recipient, rate) = spend::prepare_selection(
+        db,
+        daemon,
+        identity_id,
+        recipients,
+        max_send,
+        chain_tip,
+        priority,
+    )
+    .await?;
+    let plan = build_plan(
+        db,
+        identity_id,
+        &prepared,
+        &recipient,
+        rate.per_weight(),
+        &mut rand_core::OsRng,
+    )?;
+    let device_plan = Zeroizing::new(
+        serde_json::to_string(&plan).map_err(|e| invalid_plan("serialize").detail(e))?,
+    );
+
+    Ok(json!({
+        "devicePlan": device_plan.as_str(),
+        "feeAtomic": prepared.fee_atomic.to_string(),
+        "amountAtomic": prepared.amount_atomic.to_string(),
+        "inputsAtomic": prepared.inputs_atomic.to_string(),
+        "changeAtomic": prepared.change_atomic().to_string(),
+        "inputCount": prepared.output_ids.len(),
+    }))
+}
+
+/// Builds the device plan from a prepared selection. Change goes to the primary address.
+pub fn build_plan(
+    db: &Db,
+    identity_id: i64,
+    prepared: &Prepared,
+    recipient: &MoneroAddress,
+    fee_per_weight: u64,
+    rng: &mut R,
+) -> Result {
+    let identity = db.identity_by_id(identity_id)?;
+    let view = view_scalar(db, identity_id)?;
+    let (is_subaddress, payment_id) = destination_kind(recipient).ok_or_else(|| {
+        RuntimeError::with(
+            ErrorCode::InvalidAddress,
+            json!({ "field": "recipient.address", "reason": "unsupportedByDevice" }),
+        )
+    })?;
+    if prepared.output_ids.len() != prepared.inputs.len() {
+        return Err(invalid_plan("inputCount"));
+    }
+
+    let change = DestinationEntry {
+        amount: prepared.change_atomic(),
+        addr: public_address(identity.view_pair.spend(), identity.view_pair.view()),
+        is_subaddress: false,
+        is_integrated: false,
+    };
+    let mut outputs = vec![
+        DestinationEntry {
+            amount: prepared.amount_atomic,
+            addr: public_address(recipient.spend(), recipient.view()),
+            is_subaddress,
+            is_integrated: payment_id.is_some(),
+        },
+        change.clone(),
+    ];
+    // The device keeps the order it is given; oxide shuffles its payments too.
+    let recipient_index = rng.next_u32() & 1;
+    if recipient_index == 1 {
+        outputs.swap(0, 1);
+    }
+
+    let mut inputs = Vec::with_capacity(prepared.inputs.len());
+    let mut key_images = Vec::with_capacity(prepared.inputs.len());
+    let mut minors = BTreeSet::new();
+    for (output_id, input) in prepared.output_ids.iter().zip(&prepared.inputs) {
+        let (entry, key_image) = source_entry(db, &identity, &view, *output_id, input)?;
+        minors.insert(entry.subaddr_minor);
+        key_images.push(hex::encode(key_image));
+        inputs.push(entry);
+    }
+
+    let plan = DevicePlan {
+        version: PLAN_VERSION,
+        network_type: device_network_type(db.network()),
+        tsx_data: TsxData {
+            version: TSX_VERSION,
+            client_version: CLIENT_VERSION,
+            hard_fork: HARD_FORK,
+            unlock_time: 0,
+            num_inputs: u32::try_from(inputs.len()).map_err(|_| invalid_plan("inputCount"))?,
+            mixin: u32::from(RING_LEN) - 1,
+            fee: prepared.fee_atomic,
+            account: 0,
+            minor_indices: minors.into_iter().collect(),
+            outputs,
+            change_dts: change,
+            rsig_data: RsigData {
+                rsig_type: RSIG_TYPE,
+                bp_version: BP_VERSION,
+                grouping: vec![OUTPUTS as u64],
+            },
+            payment_id: payment_id.map(hex::encode),
+            integrated_indices: payment_id.map(|_| recipient_index).into_iter().collect(),
+        },
+        inputs,
+        expected: Expected {
+            key_images,
+            fee: prepared.fee_atomic,
+            recipient_amount: prepared.amount_atomic,
+            change_amount: prepared.change_atomic(),
+            fee_per_weight,
+            view_key: SecretKeyHex(Zeroizing::new(view.to_bytes())),
+        },
+    };
+    check_plan(&plan)?;
+    Ok(plan)
+}
+
+/// `(key image, index in tx, global index, output key, R keys, additional keys, major, minor)`.
+type InputRow = (
+    Option>,
+    i64,
+    i64,
+    Option>,
+    Option>,
+    Option>,
+    Option,
+    Option,
+);
+
+/// One input as the device needs it, and its stored key image.
+fn source_entry(
+    db: &Db,
+    identity: &Identity,
+    view: &curve25519_dalek::Scalar,
+    output_id: i64,
+    input: &OutputWithDecoys,
+) -> Result<(SourceEntry, [u8; 32])> {
+    let row: Option = db
+        .conn()
+        .query_row(
+            "SELECT key_image, index_in_tx, global_index, output_key, tx_pub_keys,
+                    tx_additional_pub_keys, subaddress_major, subaddress_minor
+             FROM outputs WHERE id = ?1 AND identity_id = ?2",
+            [output_id, identity.id],
+            |r| {
+                Ok((
+                    r.get(0)?,
+                    r.get(1)?,
+                    r.get(2)?,
+                    r.get(3)?,
+                    r.get(4)?,
+                    r.get(5)?,
+                    r.get(6)?,
+                    r.get(7)?,
+                ))
+            },
+        )
+        .optional()
+        .map_err(|e| db_err("loadDeviceInput", e))?;
+    let corrupt = |what: &str| db_err("loadDeviceInput", format!("output {output_id}: {what}"));
+    let (key_image, index, global_index, output_key, tx_keys, additional, major, minor) =
+        row.ok_or_else(|| corrupt("not found"))?;
+
+    // The hardware flow syncs key images before preparing; selection only takes outputs with one.
+    let key_image = key_image
+        .and_then(|k| <[u8; 32]>::try_from(k).ok())
+        .ok_or_else(|| {
+            RuntimeError::with(
+                ErrorCode::InvalidRequest,
+                json!({ "field": "inputs", "reason": "keyImageRequired", "outputId": output_id }),
+            )
+        })?;
+    // The plan signs for account (major) 0 only.
+    if major.unwrap_or(0) != 0 {
+        return Err(RuntimeError::with(
+            ErrorCode::InvalidRequest,
+            json!({ "field": "inputs", "reason": "subaddressAccountUnsupported", "outputId": output_id }),
+        ));
+    }
+    let minor = u32::try_from(minor.unwrap_or(0)).map_err(|_| corrupt("bad subaddress"))?;
+    let index = u32::try_from(index).map_err(|_| corrupt("output index out of range"))?;
+    let output_key = output_key
+        .and_then(|k| <[u8; 32]>::try_from(k).ok())
+        .ok_or_else(|| corrupt("no output key"))?;
+    if output_key != input.key().compress().to_bytes() {
+        return Err(corrupt("output key differs from its blob"));
+    }
+    let tx_keys = tx_keys
+        .filter(|k| !k.is_empty() && k.len() % 32 == 0)
+        .ok_or_else(|| corrupt("no transaction public key"))?;
+
+    let spend = receiving_spend_key(db, identity, 0, minor);
+    let (tx_key, additional) = real_tx_keys(
+        view,
+        spend,
+        &tx_keys,
+        additional.as_deref(),
+        index,
+        &output_key,
+    );
+    // The device derives the one-time key from these; fail here rather than on the device.
+    let derives = |r: &[u8]| derives_output_key(view, r, index, spend, &output_key);
+    if !derives(tx_key) && !additional.is_some_and(derives) {
+        return Err(corrupt("no transaction key derives the output"));
+    }
+
+    let decoys = input.decoys();
+    let positions = decoys.positions();
+    let ring = decoys.ring();
+    let real = usize::from(decoys.signer_index());
+    if positions.len() != usize::from(RING_LEN)
+        || relative_offsets(&positions).is_none()
+        || u64::try_from(global_index).ok() != Some(positions[real])
+        || ring[real][0].compress().to_bytes() != output_key
+    {
+        return Err(corrupt("ring does not hold the output"));
+    }
+
+    let commitment = input.commitment();
+    let entry = SourceEntry {
+        outputs: positions
+            .iter()
+            .zip(ring)
+            .map(|(idx, member)| OutputEntry {
+                idx: *idx,
+                key: RctKeyPublic {
+                    dest: hex_point(member[0].into()),
+                    commitment: hex_point(member[1].into()),
+                },
+            })
+            .collect(),
+        real_output: real as u64,
+        real_out_tx_key: clear_torsion(tx_key)
+            .ok_or_else(|| corrupt("invalid transaction public key"))?,
+        real_out_additional_tx_keys: additional
+            .map(|key| clear_torsion(key).ok_or_else(|| corrupt("invalid additional key")))
+            .transpose()?
+            .into_iter()
+            .collect(),
+        real_output_in_tx_index: u64::from(index),
+        amount: commitment.amount,
+        rct: true,
+        mask: hex::encode(<[u8; 32]>::from(commitment.mask)),
+        subaddr_minor: minor,
+    };
+    Ok((entry, key_image))
+}
+
+// ── Plan checks ──
+
+/// A ring as the transaction commits to it.
+struct Ring {
+    offsets: Vec,
+    members: Vec<[CompressedPoint; 2]>,
+}
+
+/// The decoded, consistency-checked plan.
+struct Checked {
+    network: Network,
+    key_images: Vec<[u8; 32]>,
+    rings: Vec,
+    change_index: usize,
+    recipient_index: usize,
+    /// The recipient is the account's own primary address, so its output is scanned too.
+    self_send: bool,
+    change_spend: EdwardsPoint,
+    view: Zeroizing,
+    fee: u64,
+    recipient_amount: u64,
+    change_amount: u64,
+    fee_rate: FeeRate,
+}
+
+fn parse_plan(json: &str) -> Result {
+    if json.len() > MAX_HEX_LEN {
+        return Err(invalid_plan("tooLarge"));
+    }
+    serde_json::from_str(json).map_err(|e| invalid_plan("malformed").detail(e))
+}
+
+/// Structure and amounts the runtime itself produced; anything else is refused.
+fn check_plan(plan: &DevicePlan) -> Result {
+    let tsx = &plan.tsx_data;
+    let expected = &plan.expected;
+    let network =
+        network_from_type(plan.network_type).ok_or_else(|| invalid_plan("networkType"))?;
+    if plan.version != PLAN_VERSION
+        || tsx.version != TSX_VERSION
+        || tsx.client_version < CLIENT_VERSION
+        || tsx.hard_fork != HARD_FORK
+        || tsx.unlock_time != 0
+        || tsx.account != 0
+        || tsx.mixin != u32::from(RING_LEN) - 1
+        || tsx.rsig_data
+            != (RsigData {
+                rsig_type: RSIG_TYPE,
+                bp_version: BP_VERSION,
+                grouping: vec![OUTPUTS as u64],
+            })
+        || tsx.outputs.len() != OUTPUTS
+    {
+        return Err(invalid_plan("unsupportedTransaction"));
+    }
+    if plan.inputs.is_empty()
+        || usize::try_from(tsx.num_inputs).ok() != Some(plan.inputs.len())
+        || expected.key_images.len() != plan.inputs.len()
+    {
+        return Err(invalid_plan("inputCount"));
+    }
+
+    // The change is the entry equal to `change_dts`; if both are (a self-send of the
+    // same amount), either one is.
+    let change = &tsx.change_dts;
+    let change_index = tsx
+        .outputs
+        .iter()
+        .position(|output| output == change)
+        .ok_or_else(|| invalid_plan("change"))?;
+    let recipient_index = 1 - change_index;
+    let recipient = &tsx.outputs[recipient_index];
+    if change.is_subaddress
+        || change.is_integrated
+        || change.amount != expected.change_amount
+        || recipient.amount != expected.recipient_amount
+        || expected.recipient_amount == 0
+        || tsx.fee != expected.fee
+    {
+        return Err(invalid_plan("amounts"));
+    }
+    let integrated: &[u32] = match &tsx.payment_id {
+        Some(id) if id.len() == 16 && hex::decode(id).is_ok() => &[recipient_index as u32],
+        Some(_) => return Err(invalid_plan("paymentId")),
+        None => &[],
+    };
+    if tsx.integrated_indices != integrated
+        || recipient.is_integrated != tsx.payment_id.is_some()
+        || (recipient.is_integrated && recipient.is_subaddress)
+    {
+        return Err(invalid_plan("paymentId"));
+    }
+
+    let change_spend =
+        point(&change.addr.spend_public_key).ok_or_else(|| invalid_plan("change"))?;
+    let view = Zeroizing::new(
+        Scalar::read(&mut expected.view_key.0.as_slice())
+            .map_err(|_| invalid_plan("viewKey"))?
+            .into(),
+    );
+    if point(&change.addr.view_public_key) != Some(*view * G) {
+        return Err(invalid_plan("viewKey"));
+    }
+    let fee_rate = FeeRate::new(expected.fee_per_weight, FEE_QUANTIZATION_MASK)
+        .ok_or_else(|| invalid_plan("feePerWeight"))?;
+
+    let mut total: u64 = 0;
+    let mut rings = Vec::with_capacity(plan.inputs.len());
+    let mut minors = BTreeSet::new();
+    for input in &plan.inputs {
+        let positions: Vec = input.outputs.iter().map(|o| o.idx).collect();
+        let offsets = relative_offsets(&positions).ok_or_else(|| invalid_plan("ring"))?;
+        let members = input
+            .outputs
+            .iter()
+            .map(|o| {
+                Some([
+                    CompressedPoint::from(hex32(&o.key.dest)?),
+                    CompressedPoint::from(hex32(&o.key.commitment)?),
+                ])
+            })
+            .collect::>>()
+            .ok_or_else(|| invalid_plan("ring"))?;
+        let real = usize::try_from(input.real_output).map_err(|_| invalid_plan("ring"))?;
+        if members.len() != usize::from(RING_LEN) || real >= members.len() || !input.rct {
+            return Err(invalid_plan("ring"));
+        }
+        let mask = hex32(&input.mask)
+            .and_then(|mask| Scalar::read(&mut mask.as_slice()).ok())
+            .ok_or_else(|| invalid_plan("mask"))?;
+        // The device refuses an input whose mask and amount do not open its commitment.
+        if Commitment::new(mask, input.amount)
+            .commit()
+            .compress()
+            .to_bytes()
+            != members[real][1].to_bytes()
+        {
+            return Err(invalid_plan("mask"));
+        }
+        total = total
+            .checked_add(input.amount)
+            .ok_or_else(|| invalid_plan("amounts"))?;
+        minors.insert(input.subaddr_minor);
+        rings.push(Ring { offsets, members });
+    }
+    if tsx.minor_indices != minors.into_iter().collect::>() {
+        return Err(invalid_plan("minorIndices"));
+    }
+    let spent = expected
+        .fee
+        .checked_add(expected.recipient_amount)
+        .and_then(|sum| sum.checked_add(expected.change_amount));
+    if spent != Some(total) {
+        return Err(invalid_plan("amounts"));
+    }
+
+    let key_images = expected
+        .key_images
+        .iter()
+        .map(|k| hex32(k))
+        .collect::>>()
+        .ok_or_else(|| invalid_plan("keyImages"))?;
+    if key_images.iter().collect::>().len() != key_images.len() {
+        return Err(invalid_plan("keyImages"));
+    }
+
+    Ok(Checked {
+        network,
+        key_images,
+        rings,
+        change_index,
+        recipient_index,
+        // The device derives every output to the change address with the view key.
+        self_send: recipient.addr == change.addr,
+        change_spend,
+        view,
+        fee: expected.fee,
+        recipient_amount: expected.recipient_amount,
+        change_amount: expected.change_amount,
+        fee_rate,
+    })
+}
+
+/// The review the user confirmed must describe this plan.
+fn check_review(plan: &DevicePlan, checked: &Checked, request: &ReviewRequest) -> Result<()> {
+    let mismatch = review::mismatch;
+    let network = keys::parse_network(&request.network)?;
+    if network != checked.network {
+        return Err(mismatch("network"));
+    }
+    let tsx = &plan.tsx_data;
+    let from = keys::parse_address(network, &request.from_address, "fromAddress")?;
+    if *from.kind() != AddressType::Legacy
+        || public_address(from.spend(), from.view()) != tsx.change_dts.addr
+    {
+        return Err(mismatch("fromAddress"));
+    }
+    let to = keys::parse_address(network, &request.to_address, "toAddress")?;
+    let recipient = &tsx.outputs[checked.recipient_index];
+    match destination_kind(&to) {
+        Some((is_subaddress, payment_id))
+            if public_address(to.spend(), to.view()) == recipient.addr
+                && recipient.is_subaddress == is_subaddress
+                && tsx.payment_id == payment_id.map(hex::encode) => {}
+        _ => return Err(mismatch("toAddress")),
+    }
+    let expected = &plan.expected;
+    let change = review::amount(&request.change_atomic)?;
+    if review::amount(&request.amount_atomic)? != expected.recipient_amount {
+        return Err(mismatch("amount"));
+    }
+    if review::amount(&request.fee_atomic)? != expected.fee
+        || change != expected.change_amount
+        || (request.is_max_send && change != 0)
+    {
+        return Err(mismatch("feeOrChange"));
+    }
+    Ok(())
+}
+
+/// Checks a plan against the review before it goes to the device.
+pub fn verify_unsigned(plan_json: &str, request: &ReviewRequest) -> Result<()> {
+    let plan = parse_plan(plan_json)?;
+    let checked = check_plan(&plan)?;
+    check_review(&plan, &checked, request)
+}
+
+// ── Assembly and verification ──
+
+/// Rebuilds the device's transaction, verifies it against the plan and returns
+/// `{ txid, rawHex }`. No DB or network access.
+pub fn assemble(plan_json: &str, signed_json: &str) -> Result {
+    let plan = parse_plan(plan_json)?;
+    let checked = check_plan(&plan)?;
+    let signed: DeviceSigned = serde_json::from_str(signed_json).map_err(|e| {
+        RuntimeError::with(
+            ErrorCode::InvalidRequest,
+            json!({ "field": "signedJson", "reason": "malformed" }),
+        )
+        .detail(e)
+    })?;
+    let transaction = rebuild(&plan, &checked, &signed)?;
+    verify_transaction(&checked, &transaction)?;
+
+    let raw = transaction.serialize();
+    // Broadcast verification reads it back; make sure it can.
+    let mut reader = raw.as_slice();
+    if Transaction::read(&mut reader).ok().as_ref() != Some(&transaction) || !reader.is_empty() {
+        return Err(rejected("serialization"));
+    }
+    Ok(json!({
+        "txid": hex::encode(transaction.hash()),
+        "rawHex": hex::encode(raw),
+    }))
+}
+
+/// The transaction from the device's parts, with the device's prefix and message hashes checked.
+fn rebuild(plan: &DevicePlan, checked: &Checked, signed: &DeviceSigned) -> Result {
+    let inputs_len = checked.key_images.len();
+    let outputs_len = plan.tsx_data.outputs.len();
+    if [
+        signed.orig_indices.len(),
+        signed.vinis.len(),
+        signed.pseudo_outs.len(),
+        signed.clsags.len(),
+    ] != [inputs_len; 4]
+        || [
+            signed.tx_outs.len(),
+            signed.out_pks.len(),
+            signed.ecdh_infos.len(),
+        ] != [outputs_len; 3]
+    {
+        return Err(rejected("count"));
+    }
+    let mut seen = vec![false; inputs_len];
+    for &orig in &signed.orig_indices {
+        if orig >= inputs_len || std::mem::replace(&mut seen[orig], true) {
+            return Err(rejected("origIndices"));
+        }
+    }
+
+    let mut inputs = Vec::with_capacity(inputs_len);
+    for (vini, &orig) in signed.vinis.iter().zip(&signed.orig_indices) {
+        let bytes = hex_bytes(vini).ok_or_else(|| rejected("vini"))?;
+        let mut reader = bytes.as_slice();
+        let input = Input::read(&mut reader).map_err(|_| rejected("vini"))?;
+        if !reader.is_empty() {
+            return Err(rejected("vini"));
+        }
+        match &input {
+            Input::ToKey { key_image, .. } if key_image.to_bytes() == checked.key_images[orig] => {}
+            _ => return Err(rejected("keyImageMismatch")),
+        }
+        inputs.push(input);
+    }
+
+    let mut outputs = Vec::with_capacity(outputs_len);
+    let mut commitments = Vec::with_capacity(outputs_len);
+    let mut encrypted_amounts = Vec::with_capacity(outputs_len);
+    for ((tx_out, out_pk), ecdh) in signed
+        .tx_outs
+        .iter()
+        .zip(&signed.out_pks)
+        .zip(&signed.ecdh_infos)
+    {
+        let bytes = hex_bytes(tx_out).ok_or_else(|| rejected("txOut"))?;
+        let mut reader = bytes.as_slice();
+        let output = Output::read(true, &mut reader).map_err(|_| rejected("txOut"))?;
+        if !reader.is_empty() {
+            return Err(rejected("txOut"));
+        }
+        let out_pk: [u8; 64] = hex_bytes(out_pk)
+            .and_then(|b| b.try_into().ok())
+            .ok_or_else(|| rejected("outPk"))?;
+        if out_pk[..32] != output.key.to_bytes() {
+            return Err(rejected("outPk"));
+        }
+        let commitment: [u8; 32] = out_pk[32..].try_into().expect("32 of 64 bytes");
+        let amount: [u8; 8] = hex_bytes(ecdh)
+            .and_then(|b| b.try_into().ok())
+            .ok_or_else(|| rejected("ecdhInfo"))?;
+        outputs.push(output);
+        commitments.push(CompressedPoint::from(commitment));
+        encrypted_amounts.push(EncryptedAmount::Compact { amount });
+    }
+
+    let extra = hex_bytes(&signed.extra)
+        .filter(|extra| extra.len() <= MAX_EXTRA_SIZE_BY_RELAY_RULE)
+        .ok_or_else(|| rejected("extra"))?;
+    let prefix = TransactionPrefix {
+        additional_timelock: Timelock::None,
+        inputs,
+        outputs,
+        extra,
+    };
+    let prefix_hash = prefix_hash(&prefix);
+    if hex32(&signed.tx_prefix_hash) != Some(prefix_hash)
+        || hex32(&signed.rv.message) != Some(prefix_hash)
+    {
+        return Err(rejected("prefixHashMismatch"));
+    }
+    if signed.rv.rv_type != u8::from(RctType::ClsagBulletproofPlus) {
+        return Err(rejected("rctType"));
+    }
+    if signed.rv.txn_fee != plan.expected.fee {
+        return Err(rejected("feeMismatch"));
+    }
+
+    let rsig = hex_bytes(&signed.rsig).ok_or_else(|| rejected("rangeProof"))?;
+    let mut reader = rsig.as_slice();
+    let bulletproof = Bulletproof::read_plus(&mut reader).map_err(|_| rejected("rangeProof"))?;
+    if !reader.is_empty() {
+        return Err(rejected("rangeProof"));
+    }
+
+    let mut clsags = Vec::with_capacity(inputs_len);
+    for (clsag, &orig) in signed.clsags.iter().zip(&signed.orig_indices) {
+        let bytes = Zeroizing::new(hex_bytes(clsag).ok_or_else(|| rejected("signature"))?);
+        let mut reader = bytes.as_slice();
+        let ring_len: usize = VarInt::read(&mut reader).map_err(|_| rejected("signature"))?;
+        if ring_len != checked.rings[orig].members.len() {
+            return Err(rejected("signature"));
+        }
+        let clsag = Clsag::read(ring_len, &mut reader).map_err(|_| rejected("signature"))?;
+        if !reader.is_empty() {
+            return Err(rejected("signature"));
+        }
+        clsags.push(clsag);
+    }
+    let pseudo_outs = signed
+        .pseudo_outs
+        .iter()
+        .map(|p| hex32(p).map(CompressedPoint::from))
+        .collect::>>()
+        .ok_or_else(|| rejected("pseudoOut"))?;
+
+    let transaction = Transaction::V2 {
+        prefix,
+        proofs: Some(RctProofs {
+            base: RctBase {
+                fee: signed.rv.txn_fee,
+                pseudo_outs: vec![],
+                encrypted_amounts,
+                commitments,
+            },
+            prunable: RctPrunable::Clsag {
+                bulletproof,
+                clsags,
+                pseudo_outs,
+            },
+        }),
+    };
+    if transaction.signature_hash() != hex32(&signed.full_message_hash) {
+        return Err(rejected("fullMessageHashMismatch"));
+    }
+    Ok(transaction)
+}
+
+/// Everything the host can check of a device-built transaction against its plan.
+fn verify_transaction(checked: &Checked, transaction: &Transaction) -> Result<()> {
+    let Transaction::V2 {
+        prefix,
+        proofs: Some(proofs),
+    } = transaction
+    else {
+        return Err(rejected("notRingCt"));
+    };
+    let RctPrunable::Clsag {
+        bulletproof,
+        clsags,
+        pseudo_outs,
+    } = &proofs.prunable
+    else {
+        return Err(rejected("rctType"));
+    };
+    let inputs_len = checked.key_images.len();
+    if proofs.rct_type() != RctType::ClsagBulletproofPlus
+        || prefix.additional_timelock != Timelock::None
+        || prefix.inputs.len() != inputs_len
+        || clsags.len() != inputs_len
+        || pseudo_outs.len() != inputs_len
+        || prefix.outputs.len() != OUTPUTS
+        || proofs.base.commitments.len() != OUTPUTS
+        || proofs.base.encrypted_amounts.len() != OUTPUTS
+        || !proofs.base.pseudo_outs.is_empty()
+        || prefix
+            .outputs
+            .iter()
+            .any(|output| output.amount.is_some() || output.view_tag.is_none())
+    {
+        return Err(rejected("shape"));
+    }
+    if proofs.base.fee != checked.fee {
+        return Err(rejected("feeMismatch"));
+    }
+
+    // Each input spends one planned input, by its stored key image, over its planned ring.
+    let message = transaction
+        .signature_hash()
+        .ok_or_else(|| rejected("notRingCt"))?;
+    let mut spent = vec![false; inputs_len];
+    let mut previous: Option<[u8; 32]> = None;
+    for ((input, clsag), pseudo_out) in prefix.inputs.iter().zip(clsags).zip(pseudo_outs) {
+        let Input::ToKey {
+            amount: None,
+            key_offsets,
+            key_image,
+        } = input
+        else {
+            return Err(rejected("input"));
+        };
+        let image = key_image.to_bytes();
+        // Strictly descending, as consensus and the device require.
+        if previous.is_some_and(|previous| previous <= image) {
+            return Err(rejected("keyImageOrder"));
+        }
+        previous = Some(image);
+        let index = checked
+            .key_images
+            .iter()
+            .position(|expected| *expected == image)
+            .filter(|index| !std::mem::replace(&mut spent[*index], true))
+            .ok_or_else(|| rejected("keyImageMismatch"))?;
+        let ring = &checked.rings[index];
+        if *key_offsets != ring.offsets {
+            return Err(rejected("ringMismatch"));
+        }
+        clsag
+            .verify(ring.members.clone(), key_image, pseudo_out, &message)
+            .map_err(|e| rejected("invalidSignature").detail(format!("{e:?}")))?;
+    }
+
+    if !bulletproof.verify(&mut rand_core::OsRng, &proofs.base.commitments) {
+        return Err(rejected("invalidRangeProof"));
+    }
+
+    // Inputs balance outputs plus fee.
+    let sum = |points: &[CompressedPoint]| -> Option {
+        points
+            .iter()
+            .map(|p| p.decompress().map(Point::into))
+            .sum::>()
+    };
+    let fee = Commitment::new(Scalar::ZERO, proofs.base.fee)
+        .commit()
+        .into();
+    match (sum(pseudo_outs), sum(&proofs.base.commitments)) {
+        (Some(inputs), Some(outputs)) if (inputs - outputs - fee).is_identity() => {}
+        _ => return Err(rejected("unbalanced")),
+    }
+
+    let weight = u64::try_from(transaction.weight()).map_err(|_| rejected("feeTooLow"))?;
+    if u128::from(proofs.base.fee) < checked.fee_rate.calculate_fee_from_weight(weight) {
+        return Err(rejected("feeTooLow"));
+    }
+
+    verify_change(checked, prefix, &proofs.base)
+}
+
+/// The change, scanned with the view key, pays the planned amount to the primary address;
+/// so does the recipient output of a self-send.
+fn verify_change(checked: &Checked, prefix: &TransactionPrefix, base: &RctBase) -> Result<()> {
+    let extra = Extra::read(&mut prefix.extra.as_slice()).map_err(|_| rejected("extra"))?;
+    let (keys, additional) = extra.keys().ok_or_else(|| rejected("extra"))?;
+    let owned = |index: usize| -> Result> {
+        let output = &prefix.outputs[index];
+        let candidates = keys
+            .iter()
+            .chain(additional.as_ref().and_then(|keys| keys.get(index)));
+        for key in candidates {
+            let derivation = Zeroizing::new(
+                (*checked.view * Point::into(*key))
+                    .mul_by_cofactor()
+                    .compress()
+                    .to_bytes(),
+            );
+            let mut hashed = Zeroizing::new(derivation.to_vec());
+            VarInt::write(&(index as u64), &mut *hashed).expect("writing to a Vec cannot fail");
+            let view_tag = keccak256([b"view_tag".as_slice(), &hashed].concat())[0];
+            let shared = Zeroizing::new(Scalar::hash(&*hashed));
+            if output.view_tag != Some(view_tag)
+                || (Scalar::into(*shared) * G + checked.change_spend)
+                    .compress()
+                    .to_bytes()
+                    != output.key.to_bytes()
+            {
+                continue;
+            }
+            let shared_bytes = Zeroizing::new(<[u8; 32]>::from(*shared));
+            let EncryptedAmount::Compact { amount } = &base.encrypted_amounts[index] else {
+                return Err(rejected("shape"));
+            };
+            let pad = keccak256([b"amount".as_slice(), shared_bytes.as_slice()].concat());
+            let amount = u64::from_le_bytes(*amount)
+                ^ u64::from_le_bytes(pad[..8].try_into().expect("8 of 32 bytes"));
+            let mask =
+                Scalar::hash([b"commitment_mask".as_slice(), shared_bytes.as_slice()].concat());
+            if Commitment::new(mask, amount).commit().compress() != base.commitments[index] {
+                return Err(rejected("changeCommitmentMismatch"));
+            }
+            return Ok(Some(amount));
+        }
+        Ok(None)
+    };
+
+    if owned(checked.change_index)? != Some(checked.change_amount) {
+        return Err(rejected("changeMismatch"));
+    }
+    if checked.self_send && owned(checked.recipient_index)? != Some(checked.recipient_amount) {
+        return Err(rejected("changeMismatch"));
+    }
+    Ok(())
+}
+
+/// [`crate::review::verify_signed`] for a hardware device plan.
+pub fn verify_signed(
+    plan_json: &str,
+    request: &ReviewRequest,
+    raw_hex: &str,
+) -> Result {
+    let plan = parse_plan(plan_json)?;
+    let checked = check_plan(&plan)?;
+    check_review(&plan, &checked, request)?;
+    if raw_hex.len() > MAX_HEX_LEN {
+        return Err(review::mismatch("rawHex"));
+    }
+    let raw = hex::decode(raw_hex).map_err(|_| review::mismatch("rawHex"))?;
+    let mut reader = raw.as_slice();
+    let transaction = Transaction::read(&mut reader).map_err(|_| review::mismatch("rawHex"))?;
+    if !reader.is_empty() {
+        return Err(review::mismatch("trailingBytes"));
+    }
+    verify_transaction(&checked, &transaction)?;
+    Ok(transaction)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::spend::test_support::SeededRng;
+    use curve25519_dalek::Scalar as Dalek;
+    use monero_wallet::{
+        address::SubaddressIndex,
+        ringct::clsag::{ClsagContext, Decoys},
+        send::{Change, SignableTransaction},
+        ViewPair, WalletOutput,
+    };
+    use rusqlite::params;
+
+    /// A hardware account: the runtime holds the view key, the (software) device the spend key.
+    struct Wallet {
+        spend: Dalek,
+        view: Dalek,
+        pair: ViewPair,
+        db: Db,
+        id: i64,
+    }
+
+    fn random_scalar(rng: &mut SeededRng) -> Dalek {
+        let mut wide = [0u8; 64];
+        rng.fill_bytes(&mut wide);
+        Dalek::from_bytes_mod_order_wide(&wide)
+    }
+
+    fn random_point(rng: &mut SeededRng) -> EdwardsPoint {
+        random_scalar(rng) * G
+    }
+
+    fn wallet(rng: &mut SeededRng) -> Wallet {
+        let spend = random_scalar(rng);
+        // OneKey derives the view key as Hs(spend).
+        let view: Dalek = Scalar::hash(spend.to_bytes()).into();
+        let mut db = Db::open(":memory:", Network::Mainnet).unwrap();
+        let id = db
+            .add_identity(
+                "hw-1",
+                &(spend * G).compress().to_bytes(),
+                &view.to_bytes(),
+                100,
+            )
+            .unwrap()
+            .id;
+        let pair =
+            ViewPair::new(Point::from(spend * G), Zeroizing::new(Scalar::from(view))).unwrap();
+        Wallet {
+            spend,
+            view,
+            pair,
+            db,
+            id,
+        }
+    }
+
+    fn subaddress_secret(view: &Dalek, minor: u32) -> Dalek {
+        if minor == 0 {
+            return Dalek::ZERO;
+        }
+        Scalar::hash(
+            [
+                b"SubAddr\0".as_slice(),
+                &view.to_bytes(),
+                &0u32.to_le_bytes(),
+                &minor.to_le_bytes(),
+            ]
+            .concat(),
+        )
+        .into()
+    }
+
+    /// `(8·shared || varint(index), Hs(8·shared || varint(index)))`.
+    fn derive(shared: EdwardsPoint, index: u64) -> (Vec, Dalek) {
+        let mut bytes = shared.mul_by_cofactor().compress().to_bytes().to_vec();
+        VarInt::write(&index, &mut bytes).unwrap();
+        let scalar = Scalar::hash(&bytes).into();
+        (bytes, scalar)
+    }
+
+    /// How an output reached the wallet.
+    #[derive(Clone, Copy)]
+    enum Via {
+        Primary,
+        Subaddress(u32),
+        /// To a subaddress through the transaction's additional key.
+        Additional(u32),
+        /// To the primary address, the transaction listing several R.
+        ManyKeys,
+    }
+
+    struct Owned {
+        id: i64,
+        input: OutputWithDecoys,
+        key_image: [u8; 32],
+        amount: u64,
+        global: u64,
+        output_key: [u8; 32],
+        mask: [u8; 32],
+        minor: u32,
+        tx_key: EdwardsPoint,
+        additional: Option,
+    }
+
+    /// Stores an output paid to the wallet (as scanning does) with a ring of 16 around it.
+    fn receive(w: &Wallet, rng: &mut SeededRng, n: u64, amount: u64, via: Via) -> Owned {
+        let minor = match via {
+            Via::Subaddress(minor) | Via::Additional(minor) => minor,
+            Via::Primary | Via::ManyKeys => 0,
+        };
+        let m = subaddress_secret(&w.view, minor);
+        let spend_key = w.spend * G + m * G;
+        let index_in_tx = 1u64;
+        let r = random_scalar(rng);
+        // Paying a subaddress D the sender's key is r·D; the primary address, r·G.
+        let used = if minor == 0 { r * G } else { r * spend_key };
+        let (tx_keys, additional, tx_key, real_additional) = match via {
+            Via::Primary | Via::Subaddress(_) => (vec![used], None, used, None),
+            Via::ManyKeys => (
+                vec![random_point(rng), used, random_point(rng)],
+                None,
+                used,
+                None,
+            ),
+            Via::Additional(_) => {
+                let main = random_point(rng);
+                (
+                    vec![main],
+                    Some(vec![random_point(rng), used]),
+                    main,
+                    Some(used),
+                )
+            }
+        };
+        let (_, shared) = derive(w.view * used, index_in_tx);
+        let key = shared * G + spend_key;
+        let key_offset = shared + m;
+        let mask = random_scalar(rng);
+        let commitment = Commitment::new(Scalar::from(mask), amount);
+
+        let global = 10_000 * n + 5_000;
+        let real = u64::from(rng.next_u32() % 16);
+        let positions: Vec = (0..16).map(|k| global - real * 13 + k * 13).collect();
+        let ring = (0..16)
+            .map(|k| {
+                if k == real {
+                    [Point::from(key), commitment.commit()]
+                } else {
+                    [
+                        Point::from(random_point(rng)),
+                        Point::from(random_point(rng)),
+                    ]
+                }
+            })
+            .collect();
+        let decoys = Decoys::new(relative_offsets(&positions).unwrap(), real as u8, ring).unwrap();
+        let mut bytes = key.compress().to_bytes().to_vec();
+        Scalar::from(key_offset).write(&mut bytes).unwrap();
+        commitment.write(&mut bytes).unwrap();
+        decoys.write(&mut bytes).unwrap();
+        let input = OutputWithDecoys::read(&mut bytes.as_slice()).unwrap();
+
+        let txid = keccak256(n.to_le_bytes());
+        let mut blob = txid.to_vec();
+        blob.extend(index_in_tx.to_le_bytes());
+        blob.extend(global.to_le_bytes());
+        blob.extend(key.compress().to_bytes());
+        Scalar::from(key_offset).write(&mut blob).unwrap();
+        commitment.write(&mut blob).unwrap();
+        blob.push(0); // no timelock
+        if minor == 0 {
+            blob.push(0);
+        } else {
+            blob.push(1);
+            blob.extend(0u32.to_le_bytes());
+            blob.extend(minor.to_le_bytes());
+        }
+        blob.extend([0, 0]); // no payment ID, no data
+        WalletOutput::read(&mut blob.as_slice()).expect("fixture must deserialize");
+
+        let generator: EdwardsPoint = Point::biased_hash(key.compress().to_bytes()).into();
+        let key_image = ((w.spend + key_offset) * generator).compress().to_bytes();
+        let concat = |points: &[EdwardsPoint]| -> Vec {
+            points
+                .iter()
+                .flat_map(|p| p.compress().to_bytes())
+                .collect()
+        };
+        w.db.conn()
+            .execute(
+                "INSERT INTO outputs (identity_id, blob, txid, global_index, index_in_tx,
+                   amount_atomic, height, key_image, tx_pub_keys, tx_additional_pub_keys,
+                   output_key, subaddress_major, subaddress_minor)
+                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, 10, ?7, ?8, ?9, ?10, ?11, ?12)",
+                params![
+                    w.id,
+                    blob,
+                    txid.to_vec(),
+                    global as i64,
+                    index_in_tx as i64,
+                    amount as i64,
+                    key_image.to_vec(),
+                    concat(&tx_keys),
+                    additional.as_deref().map(concat),
+                    key.compress().to_bytes().to_vec(),
+                    (minor != 0).then_some(0i64),
+                    (minor != 0).then_some(i64::from(minor)),
+                ],
+            )
+            .unwrap();
+        Owned {
+            id: w.db.conn().last_insert_rowid(),
+            input,
+            key_image,
+            amount,
+            global,
+            output_key: key.compress().to_bytes(),
+            mask: mask.to_bytes(),
+            minor,
+            tx_key,
+            additional: real_additional,
+        }
+    }
+
+    fn fee_rate() -> FeeRate {
+        FeeRate::new(20_000, FEE_QUANTIZATION_MASK).unwrap()
+    }
+
+    #[derive(Clone, Copy, PartialEq, Eq)]
+    enum To {
+        Standard,
+        Subaddress,
+        Integrated,
+        OwnPrimary,
+    }
+
+    struct Scenario {
+        w: Wallet,
+        owned: Vec,
+        prepared: Prepared,
+        recipient: MoneroAddress,
+        max_send: bool,
+    }
+
+    const XMR: u64 = 1_000_000_000_000;
+
+    /// A prepared send as `prepareTransaction` builds it (oxide's selection, fee and rings).
+    fn scenario(seed: u64, inputs: &[Via], to: To, max_send: bool) -> Scenario {
+        let mut rng = SeededRng::new(seed);
+        let w = wallet(&mut rng);
+        let owned: Vec = inputs
+            .iter()
+            .enumerate()
+            .map(|(n, via)| receive(&w, &mut rng, n as u64 + 1, (n as u64 + 2) * XMR, *via))
+            .collect();
+        let other = ViewPair::new(
+            Point::from(random_point(&mut rng)),
+            Zeroizing::new(Scalar::from(random_scalar(&mut rng))),
+        )
+        .unwrap();
+        let recipient = match to {
+            To::Standard => other.legacy_address(Network::Mainnet),
+            To::Subaddress => {
+                other.subaddress(Network::Mainnet, SubaddressIndex::new(0, 3).unwrap())
+            }
+            To::Integrated => other.legacy_integrated_address(Network::Mainnet, [9; 8]),
+            To::OwnPrimary => w.pair.legacy_address(Network::Mainnet),
+        };
+
+        let inputs: Vec = owned.iter().map(|o| o.input.clone()).collect();
+        let total: u64 = owned.iter().map(|o| o.amount).sum();
+        let build = |paid| {
+            SignableTransaction::new(
+                RctType::ClsagBulletproofPlus,
+                Zeroizing::new([7; 32]),
+                inputs.clone(),
+                vec![(recipient, paid)],
+                Change::new(w.pair.clone(), None),
+                vec![],
+                fee_rate(),
+            )
+            .unwrap()
+        };
+        let paid = if max_send {
+            total - build(1).necessary_fee()
+        } else {
+            XMR + 123_456
+        };
+        let signable = build(paid);
+        let prepared = Prepared {
+            fee_atomic: signable.necessary_fee(),
+            signable,
+            output_ids: owned.iter().map(|o| o.id).collect(),
+            inputs,
+            inputs_atomic: total,
+            amount_atomic: paid,
+        };
+        Scenario {
+            w,
+            owned,
+            prepared,
+            recipient,
+            max_send,
+        }
+    }
+
+    fn plan_json(s: &Scenario, seed: u64) -> String {
+        let plan = build_plan(
+            &s.w.db,
+            s.w.id,
+            &s.prepared,
+            &s.recipient,
+            fee_rate().per_weight(),
+            &mut SeededRng::new(seed),
+        )
+        .unwrap();
+        serde_json::to_string(&plan).unwrap()
+    }
+
+    fn review(s: &Scenario) -> ReviewRequest {
+        ReviewRequest {
+            network: "mainnet".into(),
+            from_address: s.w.pair.legacy_address(Network::Mainnet).to_string(),
+            to_address: s.recipient.to_string(),
+            amount_atomic: s.prepared.amount_atomic.to_string(),
+            fee_atomic: s.prepared.fee_atomic.to_string(),
+            change_atomic: s.prepared.change_atomic().to_string(),
+            is_max_send: s.max_send,
+        }
+    }
+
+    /// Ways a faulty or malicious device departs from the protocol while staying self-consistent.
+    #[derive(Clone, Copy, PartialEq, Eq)]
+    enum Tamper {
+        None,
+        AscendingKeyImages,
+        /// Moves one piconero from the change to the recipient.
+        ShiftChange,
+        /// Pays the change to a key that is not the account's.
+        ChangeElsewhere,
+        /// Proves the range for other commitments than the outputs'.
+        BadRangeProof,
+    }
+
+    /// The device side of the protocol for the wallet's keys, following the firmware
+    /// (`signing/step_01..10`): returns the SDK result with the CLSAGs already opened.
+    fn device_sign(w: &Wallet, plan: &DevicePlan, rng: &mut SeededRng, tamper: Tamper) -> Value {
+        let tsx = &plan.tsx_data;
+        let pt = |value: &str| point(value).unwrap();
+
+        // Step 2: one-time key, key image and vin per input, in original order.
+        let mut inputs = Vec::new();
+        for src in &plan.inputs {
+            let out_key = pt(&src.outputs[src.real_output as usize].key.dest);
+            let m = subaddress_secret(&w.view, src.subaddr_minor);
+            let keys = std::iter::once(pt(&src.real_out_tx_key))
+                .chain(src.real_out_additional_tx_keys.first().map(|k| pt(k)));
+            let x = keys
+                .map(|r| derive(w.view * r, src.real_output_in_tx_index).1 + w.spend + m)
+                .find(|x| x * G == out_key)
+                .expect("the device owns every input");
+            let generator: EdwardsPoint = Point::biased_hash(out_key.compress().to_bytes()).into();
+            let key_image = CompressedPoint::from((x * generator).compress().to_bytes());
+            let positions: Vec = src.outputs.iter().map(|o| o.idx).collect();
+            let offsets = relative_offsets(&positions).unwrap();
+            let vini = Input::ToKey {
+                amount: None,
+                key_offsets: offsets.clone(),
+                key_image,
+            }
+            .serialize();
+            let ring = src
+                .outputs
+                .iter()
+                .map(|o| {
+                    [
+                        Point::from(pt(&o.key.dest)),
+                        Point::from(pt(&o.key.commitment)),
+                    ]
+                })
+                .collect();
+            let mask = Scalar::read(&mut hex32(&src.mask).unwrap().as_slice()).unwrap();
+            let context = ClsagContext::new(
+                Decoys::new(offsets, src.real_output as u8, ring).unwrap(),
+                Commitment::new(mask, src.amount),
+            )
+            .expect("mask and amount open the commitment");
+            inputs.push((vini, key_image.to_bytes(), x, context));
+        }
+        // The host sorts by key image, descending.
+        let mut order: Vec = (0..inputs.len()).collect();
+        order.sort_by(|i, j| inputs[*j].1.cmp(&inputs[*i].1));
+        if tamper == Tamper::AscendingKeyImages {
+            order.reverse();
+        }
+
+        // Steps 1 and 6: tx key, outputs and the range proof.
+        let r = random_scalar(rng);
+        let change = &tsx.change_dts;
+        let others: Vec<&DestinationEntry> = tsx
+            .outputs
+            .iter()
+            .filter(|o| o.addr != change.addr)
+            .collect();
+        let tx_pub = match others.as_slice() {
+            [only] if only.is_subaddress => r * pt(&only.addr.spend_public_key),
+            _ => r * G,
+        };
+        let change_index = tsx.outputs.iter().position(|o| o == change).unwrap();
+        let mut amounts: Vec = tsx.outputs.iter().map(|o| o.amount).collect();
+        if tamper == Tamper::ShiftChange {
+            amounts[change_index] -= 1;
+            amounts[1 - change_index] += 1;
+        }
+        let mut tx_outs = vec![];
+        let mut out_pks = vec![];
+        let mut ecdhs = vec![];
+        let mut openings = vec![];
+        for (i, dst) in tsx.outputs.iter().enumerate() {
+            let to_change = dst.addr == change.addr;
+            let shared = if to_change {
+                w.view * tx_pub
+            } else {
+                r * pt(&dst.addr.view_public_key)
+            };
+            let (hashed, scalar) = derive(shared, i as u64);
+            let spend = if to_change && tamper == Tamper::ChangeElsewhere {
+                random_point(rng)
+            } else {
+                pt(&dst.addr.spend_public_key)
+            };
+            let key = scalar * G + spend;
+            let view_tag = keccak256([b"view_tag".as_slice(), &hashed].concat())[0];
+            let mask = Scalar::hash([b"commitment_mask".as_slice(), &scalar.to_bytes()].concat());
+            let pad = keccak256([b"amount".as_slice(), &scalar.to_bytes()].concat());
+            let opening = Commitment::new(mask, amounts[i]);
+            tx_outs.push(
+                Output {
+                    amount: None,
+                    key: CompressedPoint::from(key.compress().to_bytes()),
+                    view_tag: Some(view_tag),
+                }
+                .serialize(),
+            );
+            out_pks.push(
+                [
+                    key.compress().to_bytes(),
+                    opening.commit().compress().to_bytes(),
+                ]
+                .concat(),
+            );
+            ecdhs.push(
+                (amounts[i] ^ u64::from_le_bytes(pad[..8].try_into().unwrap())).to_le_bytes(),
+            );
+            openings.push(opening);
+        }
+        let sum_masks: Dalek = openings.iter().map(|o| o.mask.into()).sum();
+        let mut proven = openings.clone();
+        if tamper == Tamper::BadRangeProof {
+            proven[0].amount += 1;
+        }
+        let bulletproof = Bulletproof::prove_plus(rng, proven).unwrap();
+
+        // Step 7: extra with the tx key and the (dummy or real) encrypted payment ID.
+        let payment_id: [u8; 8] = tsx
+            .payment_id
+            .as_ref()
+            .map(|id| hex::decode(id).unwrap().try_into().unwrap())
+            .unwrap_or([0; 8]);
+        let id_key = others.iter().find(|o| o.amount > 0).map_or_else(
+            || pt(&change.addr.view_public_key),
+            |o| pt(&o.addr.view_public_key),
+        );
+        let mut id_derivation = (r * id_key)
+            .mul_by_cofactor()
+            .compress()
+            .to_bytes()
+            .to_vec();
+        id_derivation.push(0x8d);
+        let pad = keccak256(id_derivation);
+        let mut extra = vec![1];
+        extra.extend(tx_pub.compress().to_bytes());
+        extra.extend([2, 9, 1]);
+        extra.extend(payment_id.iter().zip(pad).map(|(id, pad)| id ^ pad));
+
+        let prefix = TransactionPrefix {
+            additional_timelock: Timelock::None,
+            inputs: order
+                .iter()
+                .map(|i| Input::read(&mut inputs[*i].0.as_slice()).unwrap())
+                .collect(),
+            outputs: tx_outs
+                .iter()
+                .map(|o| Output::read(true, &mut o.as_slice()).unwrap())
+                .collect(),
+            extra: extra.clone(),
+        };
+        let unsigned = Transaction::V2 {
+            prefix: prefix.clone(),
+            proofs: Some(RctProofs {
+                base: RctBase {
+                    fee: tsx.fee,
+                    pseudo_outs: vec![],
+                    encrypted_amounts: ecdhs
+                        .iter()
+                        .map(|amount| EncryptedAmount::Compact { amount: *amount })
+                        .collect(),
+                    commitments: openings.iter().map(|o| o.commit().compress()).collect(),
+                },
+                prunable: RctPrunable::Clsag {
+                    bulletproof: bulletproof.clone(),
+                    clsags: vec![],
+                    pseudo_outs: vec![],
+                },
+            }),
+        };
+        let full_message = unsigned.signature_hash().unwrap();
+
+        // Step 9: CLSAGs in the sorted order; pseudo-out masks sum to the outputs'.
+        let signed = Clsag::sign(
+            rng,
+            order
+                .iter()
+                .map(|i| {
+                    (
+                        Zeroizing::new(Scalar::from(inputs[*i].2)),
+                        inputs[*i].3.clone(),
+                    )
+                })
+                .collect(),
+            Scalar::from(sum_masks),
+            full_message,
+        )
+        .unwrap();
+        let clsags: Vec = signed
+            .iter()
+            .map(|(clsag, _)| {
+                let mut bytes = vec![];
+                VarInt::write(&clsag.s.len(), &mut bytes).unwrap();
+                clsag.write(&mut bytes).unwrap();
+                hex::encode(bytes)
+            })
+            .collect();
+        let prefix_hash = hex::encode(prefix_hash(&prefix));
+        json!({
+            "origIndices": order,
+            "vinis": order.iter().map(|i| hex::encode(&inputs[*i].0)).collect::>(),
+            "pseudoOuts": signed
+                .iter()
+                .map(|(_, pseudo_out)| hex::encode(pseudo_out.compress().to_bytes()))
+                .collect::>(),
+            "clsags": clsags,
+            "txOuts": tx_outs.iter().map(hex::encode).collect::>(),
+            "outPks": out_pks.iter().map(hex::encode).collect::>(),
+            "ecdhInfos": ecdhs.iter().map(hex::encode).collect::>(),
+            "rsig": hex::encode(bulletproof.serialize()),
+            "extra": hex::encode(&extra),
+            "txPrefixHash": prefix_hash,
+            "fullMessageHash": hex::encode(full_message),
+            "rv": { "txnFee": tsx.fee.to_string(), "message": prefix_hash, "rvType": 6 },
+        })
+    }
+
+    fn sign(s: &Scenario, plan: &str, seed: u64, tamper: Tamper) -> Value {
+        device_sign(
+            &s.w,
+            &parse_plan(plan).unwrap(),
+            &mut SeededRng::new(seed),
+            tamper,
+        )
+    }
+
+    fn reason(e: RuntimeError) -> String {
+        e.params["reason"].as_str().unwrap_or_default().to_owned()
+    }
+
+    fn assemble_err(plan: &str, signed: &Value) -> String {
+        match assemble(plan, &signed.to_string()) {
+            Ok(_) => panic!("assembly must be refused"),
+            Err(e) => reason(e),
+        }
+    }
+
+    /// Every layout the app sends, signed by the software device, assembles; the result
+    /// passes broadcast verification and pays exactly the fee oxide computed for its weight.
+    #[test]
+    fn device_signed_transactions_assemble_and_verify_end_to_end() {
+        let cases: [(&[Via], To, bool); 6] = [
+            (&[Via::Primary, Via::ManyKeys], To::Standard, false),
+            (
+                &[Via::Subaddress(2), Via::Additional(5)],
+                To::Subaddress,
+                false,
+            ),
+            (&[Via::Primary], To::Integrated, false),
+            (&[Via::Primary, Via::Subaddress(1)], To::OwnPrimary, false),
+            (
+                &[Via::Primary, Via::ManyKeys, Via::Additional(4)],
+                To::Standard,
+                true,
+            ),
+            (&[Via::Subaddress(7)], To::OwnPrimary, true),
+        ];
+        for (seed, (vias, to, max_send)) in cases.into_iter().enumerate() {
+            let seed = seed as u64;
+            let s = scenario(seed, vias, to, max_send);
+            for plan_seed in [0, 1] {
+                let plan = plan_json(&s, plan_seed);
+                let signed = sign(&s, &plan, seed + 100, Tamper::None);
+                let result = assemble(&plan, &signed.to_string()).unwrap();
+                let raw = result["rawHex"].as_str().unwrap();
+                let tx = Transaction::read(&mut hex::decode(raw).unwrap().as_slice()).unwrap();
+                assert_eq!(result["txid"], hex::encode(tx.hash()));
+                assert_eq!(
+                    fee_rate().calculate_fee_from_weight(tx.weight() as u64),
+                    u128::from(s.prepared.fee_atomic),
+                    "the device's weight is what oxide priced"
+                );
+
+                // Sync will find the change (and a self-send's payment) at the planned amounts.
+                let parsed = parse_plan(&plan).unwrap();
+                let checked = check_plan(&parsed).unwrap();
+                let mut wanted = vec![(checked.change_index as u64, s.prepared.change_atomic())];
+                if to == To::OwnPrimary {
+                    wanted.push((checked.recipient_index as u64, s.prepared.amount_atomic));
+                    wanted.sort();
+                }
+                assert_eq!(scanned(&s.w, &tx), wanted);
+
+                let request = review(&s);
+                review::verify_unsigned(&plan, &request).unwrap();
+                let verified = review::verify_signed(&plan, &request, raw).unwrap();
+                assert_eq!(verified.hash(), tx.hash());
+                let amounts =
+                    spend::reviewed_broadcast_amounts(&plan, &request, raw, None, None).unwrap();
+                assert_eq!(amounts.change_atomic, Some(s.prepared.change_atomic()));
+                assert_eq!(
+                    amounts.outgoing_atomic,
+                    Some(s.prepared.amount_atomic + s.prepared.fee_atomic)
+                );
+                if max_send {
+                    assert_eq!(s.prepared.change_atomic(), 0);
+                }
+            }
+        }
+    }
+
+    /// `(index, amount)` of the outputs oxide's scanner, which sync uses, finds for the wallet.
+    fn scanned(w: &Wallet, tx: &Transaction) -> Vec<(u64, u64)> {
+        use monero_wallet::{
+            block::{Block, BlockHeader},
+            interface::ScannableBlock,
+            Scanner,
+        };
+        let miner = Transaction::V2 {
+            prefix: TransactionPrefix {
+                additional_timelock: Timelock::Block(160),
+                inputs: vec![Input::Gen(100)],
+                outputs: vec![],
+                extra: vec![],
+            },
+            proofs: None,
+        };
+        let header = BlockHeader {
+            hardfork_version: 16,
+            hardfork_signal: 16,
+            timestamp: 0,
+            previous: [0; 32],
+            nonce: 0,
+        };
+        let block = ScannableBlock {
+            block: Block::new(header, miner, vec![tx.hash()]).unwrap(),
+            transactions: vec![tx.clone().into()],
+            output_index_for_first_ringct_output: Some(0),
+        };
+        Scanner::new(w.pair.clone())
+            .scan(block)
+            .unwrap()
+            .ignore_additional_timelock()
+            .iter()
+            .map(|output| (output.index_in_transaction(), output.commitment().amount))
+            .collect()
+    }
+
+    fn keys_of(value: &Value) -> BTreeSet<&str> {
+        value
+            .as_object()
+            .unwrap()
+            .keys()
+            .map(String::as_str)
+            .collect()
+    }
+
+    /// The plan has exactly the protobuf fields the device takes, with the values it needs.
+    #[test]
+    fn the_plan_carries_what_the_device_needs() {
+        let vias = [
+            Via::Primary,
+            Via::Subaddress(2),
+            Via::Additional(5),
+            Via::ManyKeys,
+        ];
+        let s = scenario(7, &vias, To::Standard, false);
+        let plan: Value = serde_json::from_str(&plan_json(&s, 3)).unwrap();
+
+        assert_eq!(
+            keys_of(&plan),
+            BTreeSet::from(["version", "networkType", "tsxData", "inputs", "expected"])
+        );
+        assert_eq!(
+            (plan["version"].clone(), plan["networkType"].clone()),
+            (json!(1), json!(0))
+        );
+        let tsx = &plan["tsxData"];
+        assert_eq!(
+            keys_of(tsx),
+            BTreeSet::from([
+                "version",
+                "client_version",
+                "hard_fork",
+                "unlock_time",
+                "num_inputs",
+                "mixin",
+                "fee",
+                "account",
+                "minor_indices",
+                "outputs",
+                "change_dts",
+                "rsig_data",
+                "integrated_indices",
+            ]),
+            "no payment_id without an integrated recipient, and never null"
+        );
+        for (field, value) in [
+            ("version", json!(1)),
+            ("client_version", json!(3)),
+            ("hard_fork", json!(16)),
+            ("unlock_time", json!(0)),
+            ("num_inputs", json!(4)),
+            ("mixin", json!(15)),
+            ("fee", json!(s.prepared.fee_atomic.to_string())),
+            ("account", json!(0)),
+            ("minor_indices", json!([0, 2, 5])),
+            (
+                "rsig_data",
+                json!({ "rsig_type": 3, "bp_version": 4, "grouping": [2] }),
+            ),
+            ("integrated_indices", json!([])),
+        ] {
+            assert_eq!(tsx[field], value, "{field}");
+        }
+
+        let change = &tsx["change_dts"];
+        let primary = |v: &Value| {
+            v["addr"]
+                == json!({
+                    "spend_public_key": hex::encode(s.w.pair.spend().compress().to_bytes()),
+                    "view_public_key": hex::encode(s.w.pair.view().compress().to_bytes()),
+                })
+        };
+        assert!(primary(change));
+        assert_eq!(change["amount"], s.prepared.change_atomic().to_string());
+        assert_eq!(
+            (
+                change["is_subaddress"].clone(),
+                change["is_integrated"].clone()
+            ),
+            (json!(false), json!(false))
+        );
+        let outputs = tsx["outputs"].as_array().unwrap();
+        assert_eq!(outputs.len(), 2);
+        let change_index = outputs.iter().position(|o| o == change).unwrap();
+        let recipient = &outputs[1 - change_index];
+        assert_eq!(
+            keys_of(recipient),
+            BTreeSet::from(["amount", "addr", "is_subaddress", "is_integrated"])
+        );
+        assert_eq!(recipient["amount"], s.prepared.amount_atomic.to_string());
+        assert_eq!(
+            recipient["addr"]["spend_public_key"],
+            hex::encode(s.recipient.spend().compress().to_bytes())
+        );
+        assert!(!primary(recipient));
+
+        let inputs = plan["inputs"].as_array().unwrap();
+        assert_eq!(inputs.len(), 4);
+        for (input, owned) in inputs.iter().zip(&s.owned) {
+            assert_eq!(
+                keys_of(input),
+                BTreeSet::from([
+                    "outputs",
+                    "real_output",
+                    "real_out_tx_key",
+                    "real_out_additional_tx_keys",
+                    "real_output_in_tx_index",
+                    "amount",
+                    "rct",
+                    "mask",
+                    "subaddr_minor",
+                ])
+            );
+            let ring = input["outputs"].as_array().unwrap();
+            assert_eq!(ring.len(), 16);
+            let idx: Vec = ring.iter().map(|o| o["idx"].as_u64().unwrap()).collect();
+            assert!(
+                idx.windows(2).all(|w| w[0] < w[1]),
+                "ascending by global index"
+            );
+            let real = &ring[input["real_output"].as_u64().unwrap() as usize];
+            assert_eq!(real["idx"], owned.global);
+            assert_eq!(real["key"]["dest"], hex::encode(owned.output_key));
+            assert_eq!(input["real_out_tx_key"], hex_point(owned.tx_key));
+            assert_eq!(
+                input["real_out_additional_tx_keys"],
+                json!(owned
+                    .additional
+                    .map(hex_point)
+                    .into_iter()
+                    .collect::>())
+            );
+            assert_eq!(input["real_output_in_tx_index"], 1);
+            assert_eq!(input["amount"], owned.amount.to_string());
+            assert_eq!(input["rct"], true);
+            assert_eq!(input["mask"], hex::encode(owned.mask));
+            assert_eq!(input["subaddr_minor"], owned.minor);
+        }
+
+        let expected = &plan["expected"];
+        assert_eq!(
+            expected["keyImages"],
+            json!(s
+                .owned
+                .iter()
+                .map(|o| hex::encode(o.key_image))
+                .collect::>())
+        );
+        assert_eq!(expected["fee"], s.prepared.fee_atomic.to_string());
+        assert_eq!(
+            expected["recipientAmount"],
+            s.prepared.amount_atomic.to_string()
+        );
+        assert_eq!(
+            expected["changeAmount"],
+            s.prepared.change_atomic().to_string()
+        );
+        assert_eq!(expected["feePerWeight"], "20000");
+        assert_eq!(expected["viewKey"], hex::encode(s.w.view.to_bytes()));
+    }
+
+    #[test]
+    fn an_integrated_recipient_carries_its_payment_id() {
+        let s = scenario(8, &[Via::Primary], To::Integrated, false);
+        let plan: Value = serde_json::from_str(&plan_json(&s, 0)).unwrap();
+        let tsx = &plan["tsxData"];
+        assert_eq!(tsx["payment_id"], hex::encode([9u8; 8]));
+        let index = tsx["integrated_indices"][0].as_u64().unwrap() as usize;
+        assert_eq!(tsx["integrated_indices"].as_array().unwrap().len(), 1);
+        assert_eq!(tsx["outputs"][index]["is_integrated"], true);
+        assert_ne!(tsx["outputs"][index], tsx["change_dts"]);
+
+        let s = scenario(8, &[Via::Primary], To::Subaddress, false);
+        let plan: Value = serde_json::from_str(&plan_json(&s, 0)).unwrap();
+        let outputs = plan["tsxData"]["outputs"].as_array().unwrap();
+        assert!(outputs.iter().any(|o| o["is_subaddress"] == true));
+    }
+
+    /// The device keeps the order it is given, so the plan shuffles recipient and change.
+    #[test]
+    fn recipient_and_change_are_shuffled() {
+        let s = scenario(9, &[Via::Primary], To::Standard, false);
+        let positions: BTreeSet = (0..16)
+            .map(|seed| {
+                let plan = parse_plan(&plan_json(&s, seed)).unwrap();
+                check_plan(&plan).unwrap().change_index
+            })
+            .collect();
+        assert_eq!(positions, BTreeSet::from([0, 1]));
+    }
+
+    #[test]
+    fn an_input_without_a_key_image_is_refused() {
+        let s = scenario(10, &[Via::Primary, Via::Primary], To::Standard, false);
+        s.w.db
+            .conn()
+            .execute(
+                "UPDATE outputs SET key_image = NULL WHERE id = ?1",
+                [s.owned[1].id],
+            )
+            .unwrap();
+        let e = build_plan(
+            &s.w.db,
+            s.w.id,
+            &s.prepared,
+            &s.recipient,
+            20_000,
+            &mut SeededRng::new(0),
+        )
+        .err()
+        .expect("must be refused");
+        assert_eq!(e.code, ErrorCode::InvalidRequest);
+        assert_eq!(e.params["reason"], "keyImageRequired");
+        assert_eq!(e.params["outputId"], s.owned[1].id);
+    }
+
+    #[test]
+    fn a_featured_recipient_is_refused() {
+        let s = scenario(11, &[Via::Primary], To::Standard, false);
+        let featured = MoneroAddress::new(
+            Network::Mainnet,
+            AddressType::Featured {
+                subaddress: false,
+                payment_id: None,
+                guaranteed: true,
+            },
+            s.recipient.spend(),
+            s.recipient.view(),
+        );
+        let e = build_plan(
+            &s.w.db,
+            s.w.id,
+            &s.prepared,
+            &featured,
+            20_000,
+            &mut SeededRng::new(0),
+        )
+        .err()
+        .expect("must be refused");
+        assert_eq!(e.code, ErrorCode::InvalidAddress);
+        assert_eq!(e.params["reason"], "unsupportedByDevice");
+    }
+
+    /// A device that departs from the protocol, or a result altered on the way back,
+    /// never yields a transaction.
+    #[test]
+    fn assembly_refuses_a_deviating_device() {
+        let s = scenario(
+            12,
+            &[Via::Primary, Via::ManyKeys, Via::Subaddress(3)],
+            To::Standard,
+            false,
+        );
+        let plan = plan_json(&s, 0);
+        let good = sign(&s, &plan, 1, Tamper::None);
+        assemble(&plan, &good.to_string()).unwrap();
+
+        for (tamper, expected) in [
+            (Tamper::AscendingKeyImages, "keyImageOrder"),
+            (Tamper::ShiftChange, "changeMismatch"),
+            (Tamper::ChangeElsewhere, "changeMismatch"),
+            (Tamper::BadRangeProof, "invalidRangeProof"),
+        ] {
+            assert_eq!(assemble_err(&plan, &sign(&s, &plan, 1, tamper)), expected);
+        }
+
+        let edit = |f: &dyn Fn(&mut Value)| {
+            let mut signed = good.clone();
+            f(&mut signed);
+            assemble_err(&plan, &signed)
+        };
+        let flip = |value: &mut Value, at: usize| {
+            let mut bytes = hex::decode(value.as_str().unwrap()).unwrap();
+            bytes[at] ^= 1;
+            *value = json!(hex::encode(bytes));
+        };
+        assert_eq!(
+            edit(&|v| v["pseudoOuts"][0] = v["pseudoOuts"][1].clone()),
+            "invalidSignature"
+        );
+        assert_eq!(edit(&|v| flip(&mut v["clsags"][1], 1)), "invalidSignature");
+        assert_eq!(
+            edit(&|v| flip(&mut v["txPrefixHash"], 0)),
+            "prefixHashMismatch"
+        );
+        assert_eq!(
+            edit(&|v| flip(&mut v["rv"]["message"], 0)),
+            "prefixHashMismatch"
+        );
+        assert_eq!(
+            edit(&|v| v["extra"] = json!(format!("{}00", v["extra"].as_str().unwrap()))),
+            "prefixHashMismatch"
+        );
+        assert_eq!(
+            edit(&|v| flip(&mut v["fullMessageHash"], 0)),
+            "fullMessageHashMismatch"
+        );
+        assert_eq!(
+            edit(&|v| flip(&mut v["ecdhInfos"][0], 0)),
+            "fullMessageHashMismatch"
+        );
+        assert_eq!(
+            edit(&|v| {
+                let vinis = v["vinis"].as_array_mut().unwrap();
+                vinis.swap(0, 1);
+            }),
+            "keyImageMismatch"
+        );
+        assert_eq!(
+            edit(&|v| v["origIndices"] = json!([0, 0, 1])),
+            "origIndices"
+        );
+        assert_eq!(
+            edit(&|v| v["rv"]["txnFee"] = json!((s.prepared.fee_atomic + 1).to_string())),
+            "feeMismatch"
+        );
+        assert_eq!(edit(&|v| v["rv"]["rvType"] = json!(5)), "rctType");
+        assert_eq!(
+            edit(&|v| {
+                v["ecdhInfos"].as_array_mut().unwrap().pop();
+            }),
+            "count"
+        );
+        assert_eq!(edit(&|v| flip(&mut v["outPks"][0], 0)), "outPk");
+        assert_eq!(
+            edit(&|v| v["rsig"] = json!(format!("{}00", v["rsig"].as_str().unwrap()))),
+            "rangeProof"
+        );
+        assert_eq!(
+            edit(&|v| v["clsags"][0] =
+                json!(format!("0f{}", &v["clsags"][0].as_str().unwrap()[2..]))),
+            "signature"
+        );
+        let e = assemble(&plan, &json!({ "origIndices": [] }).to_string()).unwrap_err();
+        assert_eq!(e.params["field"], "signedJson");
+    }
+
+    /// The plan that comes back is checked too: a different stored key image, a higher
+    /// fee rate or an altered amount is refused.
+    #[test]
+    fn assembly_holds_the_device_to_the_plan() {
+        let s = scenario(
+            13,
+            &[Via::Primary, Via::Additional(2)],
+            To::Subaddress,
+            false,
+        );
+        let plan = plan_json(&s, 1);
+        let signed = sign(&s, &plan, 2, Tamper::None);
+        let alter = |f: &dyn Fn(&mut Value)| {
+            let mut altered: Value = serde_json::from_str(&plan).unwrap();
+            f(&mut altered);
+            altered.to_string()
+        };
+
+        let other_image = alter(&|p| {
+            p["expected"]["keyImages"][0] = json!(hex::encode(
+                random_point(&mut SeededRng::new(5)).compress().to_bytes()
+            ));
+        });
+        assert_eq!(assemble_err(&other_image, &signed), "keyImageMismatch");
+
+        let dearer = alter(&|p| {
+            p["expected"]["feePerWeight"] = json!("40000");
+        });
+        assert_eq!(assemble_err(&dearer, &signed), "feeTooLow");
+
+        let e = assemble(
+            &alter(&|p| p["expected"]["changeAmount"] = json!("1")),
+            &signed.to_string(),
+        )
+        .unwrap_err();
+        assert_eq!(
+            (e.params["field"].clone(), reason(e)),
+            (json!("devicePlan"), "amounts".to_owned())
+        );
+
+        let e = assemble(
+            &alter(&|p| p["tsxData"]["hard_fork"] = json!(15)),
+            &signed.to_string(),
+        )
+        .unwrap_err();
+        assert_eq!(reason(e), "unsupportedTransaction");
+
+        let other_view = alter(&|p| p["expected"]["viewKey"] = json!(hex::encode([3u8; 32])));
+        assert_eq!(
+            reason(assemble(&other_view, &signed.to_string()).unwrap_err()),
+            "viewKey"
+        );
+    }
+
+    /// At broadcast the review the user confirmed is bound to the plan, and the raw
+    /// transaction to both.
+    #[test]
+    fn broadcast_verification_binds_review_plan_and_transaction() {
+        let s = scenario(14, &[Via::Primary, Via::ManyKeys], To::Standard, false);
+        let plan = plan_json(&s, 0);
+        let signed = sign(&s, &plan, 3, Tamper::None);
+        let raw = assemble(&plan, &signed.to_string()).unwrap()["rawHex"]
+            .as_str()
+            .unwrap()
+            .to_owned();
+        let request = review(&s);
+        review::verify_signed(&plan, &request, &raw).unwrap();
+
+        let other = scenario(15, &[Via::Primary], To::Standard, false);
+        for field in ["amount", "fee", "change", "max", "from", "to", "network"] {
+            let mut changed = review(&s);
+            match field {
+                "amount" => changed.amount_atomic = (s.prepared.amount_atomic - 1).to_string(),
+                "fee" => changed.fee_atomic = (s.prepared.fee_atomic + 1).to_string(),
+                "change" => changed.change_atomic = "0".into(),
+                "max" => changed.is_max_send = true,
+                "from" => {
+                    changed.from_address = other.w.pair.legacy_address(Network::Mainnet).to_string()
+                }
+                "to" => changed.to_address = other.recipient.to_string(),
+                "network" => changed.network = "testnet".into(),
+                _ => unreachable!(),
+            }
+            assert!(
+                review::verify_signed(&plan, &changed, &raw).is_err(),
+                "{field}"
+            );
+            assert!(review::verify_unsigned(&plan, &changed).is_err(), "{field}");
+        }
+
+        let mut tx: Transaction =
+            Transaction::read(&mut hex::decode(&raw).unwrap().as_slice()).unwrap();
+        assert!(review::verify_signed(&plan, &request, &format!("{raw}00")).is_err());
+        if let Transaction::V2 {
+            proofs: Some(ref mut proofs),
+            ..
+        } = tx
+        {
+            proofs.base.fee -= 1;
+        }
+        let e = review::verify_signed(&plan, &request, &hex::encode(tx.serialize())).unwrap_err();
+        assert_eq!(reason(e), "feeMismatch");
+
+        // Another account's transaction under this plan spends other key images.
+        let other_plan = plan_json(&other, 0);
+        let other_raw = assemble(
+            &other_plan,
+            &sign(&other, &other_plan, 4, Tamper::None).to_string(),
+        )
+        .unwrap()["rawHex"]
+            .as_str()
+            .unwrap()
+            .to_owned();
+        assert!(review::verify_signed(&plan, &request, &other_raw).is_err());
+        // A device plan never reaches the software signer.
+        let json = serde_json::to_string(&json!({
+            "network": request.network, "fromAddress": request.from_address,
+            "toAddress": request.to_address, "amountAtomic": request.amount_atomic,
+            "feeAtomic": request.fee_atomic, "changeAtomic": request.change_atomic,
+            "isMaxSend": request.is_max_send,
+        }))
+        .unwrap();
+        assert!(spend::sign_for_host(&plan, &[1; 32], &json).is_err());
+    }
+
+    #[test]
+    fn device_plans_are_told_from_signable_hex_by_content() {
+        assert!(is_device_plan("{\"version\":1}"));
+        assert!(is_device_plan(" \n{"));
+        assert!(!is_device_plan("0102ab"));
+        assert!(!is_device_plan(""));
+    }
+}
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/lib.rs b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs
index c0f416304..c27a90414 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/lib.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs
@@ -4,6 +4,7 @@
 
 pub mod blocks_bin;
 pub mod device_key_images;
+pub mod device_sign;
 pub mod error;
 pub mod keys;
 pub mod network;
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/review.rs b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
index 4c0ea08dd..2caee0642 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/review.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
@@ -26,14 +26,14 @@ pub struct ReviewRequest {
     pub is_max_send: bool,
 }
 
-fn mismatch(field: &str) -> RuntimeError {
+pub(crate) fn mismatch(field: &str) -> RuntimeError {
     RuntimeError::with(
         ErrorCode::InvalidRequest,
         serde_json::json!({"field": field, "reason": "transactionDoesNotMatchReview"}),
     )
 }
 
-fn amount(value: &str) -> Result {
+pub(crate) fn amount(value: &str) -> Result {
     let parsed = value.parse::().map_err(|_| mismatch("amount"))?;
     if parsed.to_string() != value {
         return Err(mismatch("amount"));
@@ -174,13 +174,26 @@ pub fn verify(
     Ok(signable)
 }
 
+/// [`verify`] without signing, for a software signable or a hardware device plan.
+pub fn verify_unsigned(signable_or_plan: &str, request: &ReviewRequest) -> Result<()> {
+    if crate::device_sign::is_device_plan(signable_or_plan) {
+        return crate::device_sign::verify_unsigned(signable_or_plan, request);
+    }
+    verify(signable_or_plan, request, None).map(|_| ())
+}
+
 /// Bind the reviewed outputs to the actual signed transaction without changing
 /// signing or scanning. Eventuality validates output keys, commitments and ciphertexts.
+///
+/// A hardware device plan in place of `signable_hex` is checked by `device_sign` instead.
 pub fn verify_signed(
     signable_hex: &str,
     request: &ReviewRequest,
     raw_hex: &str,
 ) -> Result {
+    if crate::device_sign::is_device_plan(signable_hex) {
+        return crate::device_sign::verify_signed(signable_hex, request, raw_hex);
+    }
     let signable = verify(signable_hex, request, None)?;
     if raw_hex.len() > 8 * 1024 * 1024 {
         return Err(mismatch("rawHex"));
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
index 7a1bafd79..cedec64a3 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -258,12 +258,23 @@ pub fn select_inputs(
 pub struct Prepared {
     pub signable: SignableTransaction,
     pub output_ids: Vec,
+    /// The signable's inputs with their rings, in `output_ids` order (hardware signing needs them).
+    pub inputs: Vec,
     pub inputs_atomic: u64,
     /// Total received by recipients. For max-send it is derived, not the host's input.
     pub amount_atomic: u64,
     pub fee_atomic: u64,
 }
 
+impl Prepared {
+    /// Returned to the primary address; 0 for a max send.
+    pub fn change_atomic(&self) -> u64 {
+        self.inputs_atomic
+            .saturating_sub(self.amount_atomic)
+            .saturating_sub(self.fee_atomic)
+    }
+}
+
 /// monerod joins rejection reasons by flag; a double spend reads "double spend".
 fn is_double_spend(error: &RuntimeError) -> bool {
     error
@@ -472,7 +483,7 @@ pub async fn prepare(
             &identity,
             rng,
             rct_type,
-            inputs,
+            inputs.clone(),
             recipients.clone(),
             fee_rate,
         ) {
@@ -481,6 +492,7 @@ pub async fn prepare(
                 return Ok(Prepared {
                     signable,
                     output_ids: selection.output_ids,
+                    inputs,
                     inputs_atomic: selection.total_atomic,
                     amount_atomic: out_total,
                     fee_atomic,
@@ -567,7 +579,7 @@ pub async fn prepare_max(
         &identity,
         rng,
         rct_type,
-        inputs,
+        inputs.clone(),
         vec![(recipient, amount_atomic)],
         fee_rate,
     )
@@ -576,6 +588,7 @@ pub async fn prepare_max(
     Ok(Prepared {
         signable,
         output_ids,
+        inputs,
         inputs_atomic,
         amount_atomic,
         fee_atomic,
@@ -1399,6 +1412,39 @@ pub async fn prepare_for_host(
     chain_tip: u64,
     priority: monero_wallet::interface::FeePriority,
 ) -> Result {
+    let (prepared, _, _) = prepare_selection(
+        db,
+        daemon,
+        identity_id,
+        recipients,
+        max_send,
+        chain_tip,
+        priority,
+    )
+    .await?;
+
+    Ok(json!({
+        "signableHex": hex::encode(prepared.signable.serialize()),
+        "feeAtomic": prepared.fee_atomic.to_string(),
+        "amountAtomic": prepared.amount_atomic.to_string(),
+        "inputsAtomic": prepared.inputs_atomic.to_string(),
+        "changeAtomic": prepared.change_atomic().to_string(),
+        "inputCount": prepared.output_ids.len(),
+    }))
+}
+
+/// Fee rate, input selection, rings and fee shared by software and hardware sends.
+///
+/// Returns the prepared transaction, the parsed recipient and the node's fee rate.
+pub(crate) async fn prepare_selection(
+    db: &Db,
+    daemon: &crate::network::Daemon,
+    identity_id: i64,
+    recipients: &[(&str, &str)],
+    max_send: bool,
+    chain_tip: u64,
+    priority: monero_wallet::interface::FeePriority,
+) -> Result<(Prepared, MoneroAddress, monero_wallet::interface::FeeRate)> {
     use monero_daemon_rpc::prelude::*;
 
     if recipients.len() != 1 {
@@ -1422,9 +1468,9 @@ pub async fn prepare_for_host(
     let mut rng = rand_core::OsRng;
     let decoys = CachedDecoys::new(daemon);
 
-    let prepared = if max_send {
+    if max_send {
         let address = keys::parse_address(network, recipients[0].0, "recipient.address")?;
-        prepare_max(
+        let prepared = prepare_max(
             db,
             &decoys,
             &mut rng,
@@ -1434,13 +1480,14 @@ pub async fn prepare_for_host(
             chain_tip,
             rct_type,
         )
-        .await?
+        .await?;
+        Ok((prepared, address, rate))
     } else {
         let payments = recipients
             .iter()
             .map(|(addr, amount)| parse_payment(network, addr, amount))
             .collect::>>()?;
-        prepare(
+        let prepared = prepare(
             db,
             &decoys,
             &mut rng,
@@ -1450,22 +1497,9 @@ pub async fn prepare_for_host(
             chain_tip,
             rct_type,
         )
-        .await?
-    };
-
-    let change_atomic = prepared
-        .inputs_atomic
-        .saturating_sub(prepared.amount_atomic)
-        .saturating_sub(prepared.fee_atomic);
-
-    Ok(json!({
-        "signableHex": hex::encode(prepared.signable.serialize()),
-        "feeAtomic": prepared.fee_atomic.to_string(),
-        "amountAtomic": prepared.amount_atomic.to_string(),
-        "inputsAtomic": prepared.inputs_atomic.to_string(),
-        "changeAtomic": change_atomic.to_string(),
-        "inputCount": prepared.output_ids.len(),
-    }))
+        .await?;
+        Ok((prepared, payments[0].address, rate))
+    }
 }
 
 /// Signs a constructed transaction. No network or database access.

From b84cb8702c12f446003dc5f6165da8d5e041211e Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 11:58:49 +0800
Subject: [PATCH 87/97] feat: return the Monero tx private key from signing,
 checked against the signed tx

---
 .../crates/monero-runtime/src/bindgen.rs      |   6 +-
 .../crates/monero-runtime/src/review.rs       | 164 +++++++++++++++++-
 .../monero/crates/monero-runtime/src/spend.rs | 113 ++++++++++--
 3 files changed, 270 insertions(+), 13 deletions(-)

diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
index 52af2d606..51f42eb06 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -485,8 +485,10 @@ pub fn assemble_device_transaction(
 /// Sign a prepared transaction. No network, no DB, no broadcast.
 ///
 /// Takes the account's BIP-32 key (as `deriveAccount`); the spend key is reduced here and
-/// both are wiped after use. Returns `{ txid, rawHex, sizeBytes }`; the txid is fixed at
-/// signing so the host can record the pending transaction before broadcasting.
+/// both are wiped after use. Returns `{ txid, rawHex, sizeBytes, txKeyHex, additionalTxKeysHex }`;
+/// the txid is fixed at signing so the host can record the pending transaction before
+/// broadcasting. The tx private keys, checked against the transaction's public keys, are for
+/// payment proofs (wallet2 `get_tx_key`).
 #[wasm_bindgen(js_name = signTransactionWithBip32Key)]
 pub fn sign_transaction_with_bip32_key(
     signable_hex: &str,
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/review.rs b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
index 2caee0642..4750647c9 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/review.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
@@ -419,6 +419,18 @@ mod tests {
         input_count: u8,
         self_payment: bool,
         max_send: bool,
+    ) -> (Vec, ReviewRequest, [u8; 32]) {
+        let recipient = (!self_payment).then_some(RECIPIENT);
+        fixture_paying(extra, change, input_count, recipient, max_send)
+    }
+
+    /// `recipient` `None` pays the sender's own primary address.
+    fn fixture_paying(
+        extra: Vec>,
+        change: impl FnOnce(ViewPair) -> Change,
+        input_count: u8,
+        recipient: Option<&str>,
+        max_send: bool,
     ) -> (Vec, ReviewRequest, [u8; 32]) {
         let mut public_bytes = [0x66u8; 32];
         public_bytes[0] = 0x58;
@@ -455,7 +467,7 @@ mod tests {
         let spend_bytes = <[u8; 32]>::from(scalar(1));
         let pair = ViewPair::new(public, Zeroizing::new(Scalar::hash(spend_bytes))).unwrap();
         let sender = pair.legacy_address(Network::Mainnet).to_string();
-        let recipient = if self_payment { &sender } else { RECIPIENT };
+        let recipient = recipient.unwrap_or(&sender);
         let change = change(pair);
         let build = |payment_amount| {
             SignableTransaction::new(
@@ -674,4 +686,154 @@ mod tests {
             assert!(verify(&hex::encode(bytes), &review, Some(&spend)).is_err());
         }
     }
+
+    /// monero `check_tx_key`: outputs whose key `Hs(8rA || o)G + B` pays `recipient`
+    /// (`A`, `B` its view and spend keys), derived from the tx key alone.
+    fn outputs_proven_by(
+        transaction: &Transaction,
+        tx_key: &str,
+        recipient: &MoneroAddress,
+    ) -> Vec {
+        let tx_key = Scalar::read(&mut hex::decode(tx_key).unwrap().as_slice()).unwrap();
+        let r: curve25519_dalek::Scalar = tx_key.into();
+        let view: curve25519_dalek::EdwardsPoint = recipient.view().into();
+        let spend: curve25519_dalek::EdwardsPoint = recipient.spend().into();
+        let derivation = (r * view).mul_by_cofactor().compress().to_bytes();
+        transaction
+            .prefix()
+            .outputs
+            .iter()
+            .enumerate()
+            .filter(|(index, output)| {
+                let index = u8::try_from(*index).unwrap();
+                assert!(index < 0x80, "one-byte varint");
+                let shared: curve25519_dalek::Scalar =
+                    Scalar::hash([derivation.as_slice(), &[index]].concat()).into();
+                let key = shared * curve25519_dalek::constants::ED25519_BASEPOINT_POINT + spend;
+                key.compress().to_bytes() == output.key.to_bytes()
+            })
+            .map(|(index, _)| index)
+            .collect()
+    }
+
+    fn transaction_public_key(transaction: &Transaction) -> curve25519_dalek::EdwardsPoint {
+        let extra =
+            monero_wallet::extra::Extra::read(&mut transaction.prefix().extra.as_slice()).unwrap();
+        let (keys, additional) = extra.keys().unwrap();
+        assert_eq!(keys.len(), 1);
+        assert!(
+            additional.is_none(),
+            "two outputs with a view-keyed change need none"
+        );
+        keys[0].into()
+    }
+
+    fn sign_fixture(
+        (bytes, review, spend): (Vec, ReviewRequest, [u8; 32]),
+    ) -> (serde_json::Value, Transaction) {
+        let signed =
+            crate::spend::sign_for_host(&hex::encode(bytes), &spend, &review_json(&review))
+                .unwrap();
+        let raw = hex::decode(signed["rawHex"].as_str().unwrap()).unwrap();
+        let transaction = Transaction::read(&mut raw.as_slice()).unwrap();
+        (signed, transaction)
+    }
+
+    /// The returned tx key is the one the transaction was built with: it is the discrete log
+    /// of R, and `check_tx_key` with it finds exactly the recipient's output.
+    #[test]
+    fn the_returned_tx_key_proves_the_payment_to_the_recipient() {
+        let (signed, transaction) = sign_fixture(fixture(vec![]));
+        // Pinned: monero-wallet derives it from the outgoing view key ([7; 32]) and the inputs.
+        assert_eq!(
+            signed["txKeyHex"],
+            "74b0219efe14a4ff500848b6fc703f55aaac172f114ab04da733dddf62719309"
+        );
+        assert_eq!(signed["additionalTxKeysHex"], serde_json::json!([]));
+
+        let tx_key = signed["txKeyHex"].as_str().unwrap();
+        let r: curve25519_dalek::Scalar =
+            Scalar::read(&mut hex::decode(tx_key).unwrap().as_slice())
+                .unwrap()
+                .into();
+        assert_eq!(
+            transaction_public_key(&transaction),
+            r * curve25519_dalek::constants::ED25519_BASEPOINT_POINT
+        );
+        let recipient = MoneroAddress::from_str(Network::Mainnet, RECIPIENT).unwrap();
+        assert_eq!(outputs_proven_by(&transaction, tx_key, &recipient).len(), 1);
+        let other = MoneroAddress::from_str(Network::Mainnet, OTHER).unwrap();
+        assert!(outputs_proven_by(&transaction, tx_key, &other).is_empty());
+    }
+
+    /// The sender's derivation `8rA` equals the receiver's `8aR`, so the proof agrees with
+    /// what the recipient's wallet scans (self-payment: the receiver's view key is known).
+    #[test]
+    fn the_tx_key_derivation_matches_the_receivers_view_key_derivation() {
+        let paid = fixture_with_options(vec![], |pair| Change::new(pair, None), 1, true, false);
+        let (to_address, spend) = (paid.1.to_address.clone(), paid.2);
+        let (signed, transaction) = sign_fixture(paid);
+        let r: curve25519_dalek::Scalar = Scalar::read(
+            &mut hex::decode(signed["txKeyHex"].as_str().unwrap())
+                .unwrap()
+                .as_slice(),
+        )
+        .unwrap()
+        .into();
+        let a: curve25519_dalek::Scalar = Scalar::hash(spend).into();
+        let recipient = MoneroAddress::from_str(Network::Mainnet, &to_address).unwrap();
+        let view: curve25519_dalek::EdwardsPoint = recipient.view().into();
+        assert_eq!(
+            (r * view).mul_by_cofactor(),
+            (a * transaction_public_key(&transaction)).mul_by_cofactor()
+        );
+        // A self-payment proves both outputs: the payment and the change.
+        assert_eq!(
+            outputs_proven_by(
+                &transaction,
+                signed["txKeyHex"].as_str().unwrap(),
+                &recipient
+            )
+            .len(),
+            2
+        );
+    }
+
+    /// A subaddress recipient: R is `rD` (D its spend key), and the receiver's `8aR` with the
+    /// account view key equals `8rC` (C its view key).
+    #[test]
+    fn a_subaddress_payment_keeps_a_tx_key_over_its_spend_key() {
+        let a: curve25519_dalek::Scalar = scalar(11).into();
+        let d: curve25519_dalek::Scalar = scalar(9).into();
+        let spend = Point::from(d * curve25519_dalek::constants::ED25519_BASEPOINT_POINT);
+        let view = Point::from(a * spend.into());
+        let subaddress = MoneroAddress::new(
+            Network::Mainnet,
+            monero_wallet::address::AddressType::Subaddress,
+            spend,
+            view,
+        );
+        let (signed, transaction) = sign_fixture(fixture_paying(
+            vec![],
+            |pair| Change::new(pair, None),
+            1,
+            Some(&subaddress.to_string()),
+            false,
+        ));
+        let tx_key = signed["txKeyHex"].as_str().unwrap();
+        let r: curve25519_dalek::Scalar =
+            Scalar::read(&mut hex::decode(tx_key).unwrap().as_slice())
+                .unwrap()
+                .into();
+        let public = transaction_public_key(&transaction);
+        assert_eq!(public, r * spend.into());
+        assert_eq!(
+            (a * public).mul_by_cofactor(),
+            (r * view.into()).mul_by_cofactor()
+        );
+        assert_eq!(
+            outputs_proven_by(&transaction, tx_key, &subaddress).len(),
+            1
+        );
+    }
 }
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
index cedec64a3..012a6eca2 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -10,7 +10,10 @@ use std::collections::HashMap;
 use monero_wallet::{
     address::MoneroAddress,
     ed25519::{Point, Scalar},
-    send::{Change, SignableTransaction},
+    extra::Extra,
+    io::{read_byte, read_bytes, read_vec},
+    send::{Change, SignableTransaction, TransactionKeys},
+    transaction::Transaction,
     OutputWithDecoys, WalletOutput,
 };
 use rand_core::{CryptoRng, RngCore};
@@ -629,14 +632,88 @@ pub fn sign_prepared(
     signable: SignableTransaction,
     rng: &mut R,
     spend_private: &[u8],
-) -> Result<(Vec, [u8; 32])> {
+) -> Result {
     let spend = parse_spend_key(spend_private)?;
-    let signed = signable.sign(rng, &spend).map_err(|e| {
+    signable.sign(rng, &spend).map_err(|e| {
         RuntimeError::with(ErrorCode::InvalidRequest, json!({ "field": "signature" }))
             .detail(format!("{e:?}"))
-    })?;
-    let txid = signed.hash();
-    Ok((signed.serialize(), txid))
+    })
+}
+
+/// A send's transaction private keys, kept for payment proofs as wallet2 keeps
+/// `m_tx_keys` and `m_additional_tx_keys`.
+struct TxKeys {
+    tx_key: Zeroizing,
+    /// One per output when the transaction carries additional public keys; usually none.
+    additional: Vec>,
+}
+
+/// Re-derives the keys monero-wallet drew for `signable` (from its outgoing view key and
+/// inputs) and checks them against the public keys in the signed transaction's extra.
+fn transaction_keys(
+    signable: &[u8],
+    signed: &Transaction,
+    recipient: &MoneroAddress,
+) -> Result {
+    use core::ops::Deref;
+
+    let mismatch = || {
+        RuntimeError::with(
+            ErrorCode::InvalidRequest,
+            json!({ "field": "transactionKey", "reason": "doesNotMatchTransaction" }),
+        )
+    };
+    let mut reader = signable;
+    let mut read_seed = || -> std::io::Result<_> {
+        read_byte(&mut reader)?;
+        let outgoing_view_key = Zeroizing::new(read_bytes::<_, 32>(&mut reader)?);
+        let inputs = read_vec(OutputWithDecoys::read, Some(1024), &mut reader)?;
+        Ok((outgoing_view_key, inputs))
+    };
+    let (outgoing_view_key, inputs) = read_seed().map_err(|_| mismatch())?;
+    let mut keys = TransactionKeys::new(
+        &outgoing_view_key,
+        inputs
+            .iter()
+            .map(|input| (input.key(), input.commitment().commit()))
+            .collect(),
+    );
+
+    let extra = Extra::read(&mut signed.prefix().extra.as_slice()).map_err(|_| mismatch())?;
+    let (public, additional_public) = extra.keys().ok_or_else(mismatch)?;
+    let [public] = public.as_slice() else {
+        return Err(mismatch());
+    };
+    let basepoint = curve25519_dalek::constants::ED25519_BASEPOINT_POINT;
+    let subaddress_spend: Option =
+        recipient.is_subaddress().then(|| recipient.spend().into());
+    let commits_to =
+        |key: &Zeroizing, generator: curve25519_dalek::EdwardsPoint, public: &Point| {
+            let key: Zeroizing = Zeroizing::new((**key).into());
+            Point::from(key.deref() * generator) == *public
+        };
+
+    let tx_key = keys.next().ok_or_else(mismatch)?;
+    // A lone subaddress payment uses R = rD (D its spend key) instead of rG; additional
+    // keys use rD per subaddress output, rG otherwise.
+    let generator = match (subaddress_spend, &additional_public) {
+        (Some(spend), None) => spend,
+        _ => basepoint,
+    };
+    if !commits_to(&tx_key, generator, public) {
+        return Err(mismatch());
+    }
+    let additional = additional_public
+        .unwrap_or_default()
+        .iter()
+        .map(|public| {
+            let key = keys.next().ok_or_else(mismatch)?;
+            let matches = commits_to(&key, basepoint, public)
+                || subaddress_spend.is_some_and(|spend| commits_to(&key, spend, public));
+            matches.then_some(key).ok_or_else(mismatch)
+        })
+        .collect::>>()?;
+    Ok(TxKeys { tx_key, additional })
 }
 
 /// Broadcasts. Irreversible.
@@ -1557,11 +1634,19 @@ pub(crate) fn sign_for_host_with_rng(
     let request = crate::review::parse_request(review_json)?;
     let signed = verify_and_sign(signable_hex, &request, spend_private, rng);
     keys::scrub_stack();
-    let (raw, txid) = signed?;
+    let (transaction, tx_keys) = signed?;
+    let raw = transaction.serialize();
     Ok(json!({
-        "txid": hex::encode(txid),
+        "txid": hex::encode(transaction.hash()),
         "rawHex": hex::encode(&raw),
         "sizeBytes": raw.len(),
+        // For payment proofs (wallet2 `get_tx_key`); the host keeps them with its sent record.
+        "txKeyHex": hex::encode(<[u8; 32]>::from(*tx_keys.tx_key)),
+        "additionalTxKeysHex": tx_keys
+            .additional
+            .iter()
+            .map(|key| hex::encode(<[u8; 32]>::from(**key)))
+            .collect::>(),
     }))
 }
 
@@ -1572,9 +1657,17 @@ fn verify_and_sign(
     request: &crate::review::ReviewRequest,
     spend_private: &[u8],
     rng: &mut R,
-) -> Result<(Vec, [u8; 32])> {
+) -> Result<(Transaction, TxKeys)> {
     let signable = crate::review::verify(signable_hex, request, Some(spend_private))?;
-    sign_prepared(signable, rng, spend_private)
+    let recipient = keys::parse_address(
+        keys::parse_network(&request.network)?,
+        &request.to_address,
+        "toAddress",
+    )?;
+    let serialized = Zeroizing::new(signable.serialize());
+    let signed = sign_prepared(signable, rng, spend_private)?;
+    let tx_keys = transaction_keys(&serialized, &signed, &recipient)?;
+    Ok((signed, tx_keys))
 }
 
 /// Amounts of our own send, known only at broadcast.

From f20db62f1a875cf5dc14bddd5143b2b9293ce805 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 11:58:50 +0800
Subject: [PATCH 88/97] feat: mark Monero coinbase receives and keep their tx
 public key for key image sync

---
 .../monero-runtime/src/device_key_images.rs   |  45 +++--
 .../monero/crates/monero-runtime/src/query.rs |   5 +-
 .../monero/crates/monero-runtime/src/scan.rs  | 182 ++++++++++++++++--
 .../crates/monero-runtime/src/schema.rs       |   2 +
 4 files changed, 199 insertions(+), 35 deletions(-)

diff --git a/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs b/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs
index e8a754c33..399377cfb 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs
@@ -285,12 +285,38 @@ fn rejected(output_id: i64, reason: &str) -> RuntimeError {
     )
 }
 
+/// What a device returns for an output, for tests outside this module too.
+#[cfg(test)]
+pub(crate) mod test_support {
+    use curve25519_dalek::{
+        constants::ED25519_BASEPOINT_POINT as G, EdwardsPoint, Scalar as Dalek,
+    };
+    use monero_wallet::ed25519::{Point, Scalar};
+
+    /// `(output key, key image, c || r)`: a key image and its one-member ring signature
+    /// for the output with secret `x`, following Monero's `generate_ring_signature`.
+    pub fn device_sign(x: Dalek, nonce: Dalek) -> ([u8; 32], [u8; 32], [u8; 64]) {
+        let output_key = (x * G).compress().to_bytes();
+        let hp: EdwardsPoint = Point::biased_hash(output_key).into();
+        let image = (x * hp).compress().to_bytes();
+        let mut transcript = image.to_vec();
+        transcript.extend_from_slice((nonce * G).compress().as_bytes());
+        transcript.extend_from_slice((nonce * hp).compress().as_bytes());
+        let c: Dalek = Scalar::hash(&transcript).into();
+        let r = nonce - c * x;
+        let mut signature = [0u8; 64];
+        signature[..32].copy_from_slice(c.as_bytes());
+        signature[32..].copy_from_slice(r.as_bytes());
+        (output_key, image, signature)
+    }
+}
+
 #[cfg(test)]
 mod tests {
+    use super::test_support::device_sign;
     use super::*;
     use crate::wallet::testing::{db_with_identity, key_bytes};
     use curve25519_dalek::Scalar as Dalek;
-    use monero_wallet::ed25519::Point;
     use rusqlite::params;
 
     const G: EdwardsPoint = ED25519_BASEPOINT_POINT;
@@ -438,23 +464,6 @@ mod tests {
         assert_eq!(items[0]["subAddrMinor"], 2);
     }
 
-    /// `(output key, key image, c || r)`: a key image and its one-member ring signature
-    /// for the output with secret `x`, following Monero's `generate_ring_signature`.
-    fn device_sign(x: Dalek, nonce: Dalek) -> ([u8; 32], [u8; 32], [u8; 64]) {
-        let output_key = (x * G).compress().to_bytes();
-        let hp: EdwardsPoint = Point::biased_hash(output_key).into();
-        let image = (x * hp).compress().to_bytes();
-        let mut transcript = image.to_vec();
-        transcript.extend_from_slice((nonce * G).compress().as_bytes());
-        transcript.extend_from_slice((nonce * hp).compress().as_bytes());
-        let c: Dalek = Scalar::hash(&transcript).into();
-        let r = nonce - c * x;
-        let mut signature = [0u8; 64];
-        signature[..32].copy_from_slice(c.as_bytes());
-        signature[32..].copy_from_slice(r.as_bytes());
-        (output_key, image, signature)
-    }
-
     fn item(id: i64, image: &[u8], signature: &[u8]) -> Value {
         json!({ "outputId": id, "keyImage": hex::encode(image), "signature": hex::encode(signature) })
     }
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/query.rs b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
index fe2ea895f..b963e5078 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/query.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
@@ -314,7 +314,8 @@ pub fn history(db: &Db, identity_id: i64, limit: u32, offset: u32) -> Result Result(9)?,
                 "paymentId": r.get::<_, Option>>(10)?.map(hex::encode),
+                // Paid by a block's miner transaction (wallet2 `m_coinbase`).
+                "isCoinbase": r.get::<_, bool>(11)?,
             }))
         })
         .map_err(|e| db_err("history", e))?;
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
index 2b211062f..20d5efe14 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
@@ -252,8 +252,13 @@ fn ring_matches<'a>(
 /// host-computed `key_offset` (a malicious host could make it sign with any key), so R is
 /// kept; recovering it later needs a rescan or a txid query that leaks interest.
 fn tx_public_keys_in(block: &ScannableBlock) -> Vec {
-    // Length mismatches are reported by `key_images_in`; skip here.
     let mut out = Vec::new();
+    // The miner transaction pays coinbase outputs, which need their R as much as any other.
+    let miner = block.block.miner_transaction();
+    if let Some((keys, additional)) = tx_public_keys_from_extra(&miner.prefix().extra) {
+        out.push((miner.hash(), keys, additional));
+    }
+    // Length mismatches are reported by `key_images_in`; skip here.
     for (txid, tx) in block
         .block
         .transactions
@@ -330,6 +335,8 @@ pub fn scan_blocks(
     let mut found: Vec<(u64, WalletOutput)> = Vec::new();
     // txid -> (R, additional), only for transactions that paid us.
     let mut tx_pub_keys: HashMap<[u8; 32], TxKeys> = HashMap::new();
+    // Miner transactions of blocks that paid us.
+    let mut coinbase_txids: HashSet<[u8; 32]> = HashSet::new();
     let mut spends: Vec<(u64, [u8; 32], [u8; 32])> = Vec::new(); // (height, key_image, txid)
 
     // Fees of transactions that pay or spend ours: history shows them, and needs them to tell
@@ -401,6 +408,7 @@ pub fn scan_blocks(
             for (txid, keys, additional) in tx_public_keys_in(block) {
                 tx_pub_keys.insert(txid, (keys, additional));
             }
+            coinbase_txids.insert(block.block.miner_transaction().hash());
         }
         let ours_before = found.len() + spends.len() + possible_spends.len();
         // Match inputs before adding this block's outputs as candidates: new
@@ -475,6 +483,7 @@ pub fn scan_blocks(
         &block_rows,
         &possible_spends,
         &tx_fees,
+        &coinbase_txids,
     )?;
     outcome.outputs_without_key_image = count_outputs_without_key_image(db, identity_id)?;
     Ok(outcome)
@@ -557,6 +566,7 @@ fn persist(
     block_rows: &[(u64, [u8; 32], Option, u64)],
     possible_spends: &[PossibleSpend],
     tx_fees: &HashMap<[u8; 32], u64>,
+    coinbase_txids: &HashSet<[u8; 32]>,
 ) -> Result<()> {
     let tx = db
         .conn_mut()
@@ -625,20 +635,22 @@ fn persist(
 
         if seen_txids.insert(txid) {
             tx.execute(
-                "INSERT INTO transactions (identity_id, txid, height, timestamp, direction, fee_atomic, payment_id)
-                 VALUES (?1, ?2, ?3, ?4, 'in', ?5, ?6)
+                "INSERT INTO transactions (identity_id, txid, height, timestamp, direction, fee_atomic, payment_id, coinbase)
+                 VALUES (?1, ?2, ?3, ?4, 'in', ?5, ?6, ?7)
                  ON CONFLICT (identity_id, txid) DO UPDATE
                    SET height = excluded.height, failed = 0, scan_valid = 1,
                        timestamp = COALESCE(excluded.timestamp, transactions.timestamp),
                        fee_atomic = COALESCE(excluded.fee_atomic, transactions.fee_atomic),
-                       payment_id = COALESCE(excluded.payment_id, transactions.payment_id)",
+                       payment_id = COALESCE(excluded.payment_id, transactions.payment_id),
+                       coinbase = excluded.coinbase",
                 params![
                     identity_id,
                     txid.as_slice(),
                     *height as i64,
                     block_time.get(height),
                     tx_fees.get(&txid).map(|fee| *fee as i64),
-                    payment_ids.get(&txid)
+                    payment_ids.get(&txid),
+                    coinbase_txids.contains(&txid)
                 ],
             )
             .map_err(|e| db_err("insertIncomingTransaction", e))?;
@@ -848,6 +860,7 @@ mod tests {
             &[],
             &[],
             &HashMap::new(),
+            &HashSet::new(),
         )
         .unwrap();
         db.conn().execute("INSERT INTO transactions (identity_id, txid, height, direction, sent_at) VALUES (?1, ?2, 995, 'out', 1)", params![id, own_send.as_slice()]).unwrap();
@@ -891,6 +904,7 @@ mod tests {
             &[],
             &[],
             &HashMap::new(),
+            &HashSet::new(),
         )
         .unwrap();
         let (valid, index, height, stored_image, lock): (i64, i64, i64, Vec, Vec) = db
@@ -1113,6 +1127,7 @@ mod tests {
             ],
             &[],
             &HashMap::new(),
+            &HashSet::new(),
         )
         .unwrap();
 
@@ -1172,6 +1187,7 @@ mod tests {
             &[(mined_at, [7u8; 32], None, 1_700_000_000)],
             &[],
             &HashMap::new(),
+            &HashSet::new(),
         )
         .unwrap();
 
@@ -1235,6 +1251,7 @@ mod tests {
             &[(503, [7u8; 32], None, 1_700_000_000)],
             &[possible],
             &fees,
+            &HashSet::new(),
         )
         .unwrap();
 
@@ -1405,17 +1422,7 @@ mod tests {
     fn scan_vector_with(encrypted: [u8; 8]) -> (serde_json::Value, Option>) {
         use monero_wallet::{block::Block, transaction::Pruned};
 
-        let spend: [u8; 32] = hex::decode(VECTOR_SPEND_KEY).unwrap().try_into().unwrap();
-        let spend_public = (curve25519_dalek::constants::ED25519_BASEPOINT_POINT
-            * curve25519_dalek::Scalar::from_bytes_mod_order(spend))
-        .compress()
-        .to_bytes();
-        let view: [u8; 32] = hex::decode(VECTOR_VIEW_KEY).unwrap().try_into().unwrap();
-        let mut db = crate::wallet::testing::db();
-        let id = db
-            .add_identity("vector", &spend_public, &view, 0)
-            .unwrap()
-            .id;
+        let (mut db, id) = vector_wallet();
 
         let original = format!(
             "{VECTOR_NONCE_PREFIX}{}",
@@ -1444,6 +1451,149 @@ mod tests {
         (item, stored)
     }
 
+    /// A fresh wallet holding the vector keys.
+    fn vector_wallet() -> (Db, i64) {
+        let spend: [u8; 32] = hex::decode(VECTOR_SPEND_KEY).unwrap().try_into().unwrap();
+        let spend_public = (curve25519_dalek::constants::ED25519_BASEPOINT_POINT
+            * curve25519_dalek::Scalar::from_bytes_mod_order(spend))
+        .compress()
+        .to_bytes();
+        let view: [u8; 32] = hex::decode(VECTOR_VIEW_KEY).unwrap().try_into().unwrap();
+        let mut db = crate::wallet::testing::db();
+        let id = db
+            .add_identity("vector", &spend_public, &view, 0)
+            .unwrap()
+            .id;
+        (db, id)
+    }
+
+    /// The vector block with its miner transaction paying the vector keys (the outputs and
+    /// keys of `VECTOR_TX`), and that miner transaction's id.
+    fn vector_coinbase_block() -> (ScannableBlock, [u8; 32]) {
+        use monero_wallet::{
+            block::Block,
+            transaction::{Pruned, Timelock, TransactionPrefix},
+        };
+
+        let paying =
+            Transaction::::read(&mut hex::decode(VECTOR_TX).unwrap().as_slice()).unwrap();
+        let template = Block::read(&mut hex::decode(VECTOR_BLOCK).unwrap().as_slice()).unwrap();
+        let height = template.number();
+        let mut outputs = paying.prefix().outputs.clone();
+        for output in &mut outputs {
+            output.amount = Some(600_000_000_000);
+        }
+        let miner = Transaction::V2 {
+            prefix: TransactionPrefix {
+                additional_timelock: Timelock::Block(height + 60),
+                inputs: vec![Input::Gen(height)],
+                outputs,
+                extra: paying.prefix().extra.clone(),
+            },
+            proofs: None,
+        };
+        let miner_txid = miner.hash();
+        let block = ScannableBlock {
+            block: Block::new(template.header.clone(), miner, vec![]).unwrap(),
+            transactions: vec![],
+            output_index_for_first_ringct_output: Some(0),
+        };
+        (block, miner_txid)
+    }
+
+    /// A receive from the block's miner transaction is a coinbase; an ordinary one is not.
+    #[test]
+    fn a_receive_from_a_miner_transaction_is_flagged_as_coinbase() {
+        let (ordinary, _) = scan_vector_with(VECTOR_PAYMENT_ID_MASK);
+        assert_eq!(ordinary["isCoinbase"], false);
+
+        let (block, miner_txid) = vector_coinbase_block();
+        let (mut db, id) = vector_wallet();
+        assert_eq!(scan_blocks(&mut db, id, &[block]).unwrap().outputs_found, 2);
+        let item = crate::query::history(&db, id, 10, 0).unwrap()["items"][0].clone();
+        assert_eq!(item["txid"], hex::encode(miner_txid));
+        assert_eq!(item["direction"], "in");
+        assert_eq!(item["isCoinbase"], true);
+    }
+
+    /// A hardware account syncs coinbase outputs like any other: the export carries the miner
+    /// transaction's R, and the key image a device derives from it is the software one.
+    #[test]
+    fn a_coinbase_output_syncs_its_key_image_from_the_device() {
+        use curve25519_dalek::Scalar as Dalek;
+        use monero_wallet::{ed25519::Scalar, io::VarInt};
+
+        let (block, _) = vector_coinbase_block();
+        let (miner_r, _) =
+            tx_public_keys_from_extra(&block.block.miner_transaction().prefix().extra).unwrap();
+        let (mut device_db, device_id) = vector_wallet();
+        scan_blocks(&mut device_db, device_id, std::slice::from_ref(&block)).unwrap();
+        let (mut software_db, software_id) = vector_wallet();
+        scan_blocks(&mut software_db, software_id, &[block]).unwrap();
+
+        let exported = crate::device_key_images::export_sync_data(&device_db, device_id).unwrap();
+        let items = exported["items"].as_array().unwrap();
+        assert_eq!(items.len(), 2);
+
+        // Device side: x = Hs(8aR || i) + b from the exported R and index alone.
+        let view =
+            Dalek::from_bytes_mod_order(hex::decode(VECTOR_VIEW_KEY).unwrap().try_into().unwrap());
+        let spend: [u8; 32] = hex::decode(VECTOR_SPEND_KEY).unwrap().try_into().unwrap();
+        let mut signed = Vec::new();
+        for (n, item) in items.iter().enumerate() {
+            assert_eq!(item["txPubKey"], hex::encode(&miner_r));
+            assert!(item["additionalTxPubKey"].is_null());
+            let r: [u8; 32] = hex::decode(item["txPubKey"].as_str().unwrap())
+                .unwrap()
+                .try_into()
+                .unwrap();
+            let r = monero_wallet::ed25519::CompressedPoint::from(r)
+                .decompress()
+                .unwrap();
+            let mut derivation = (view * r.into())
+                .mul_by_cofactor()
+                .compress()
+                .to_bytes()
+                .to_vec();
+            VarInt::write(
+                &item["internalOutputIndex"].as_u64().unwrap(),
+                &mut derivation,
+            )
+            .unwrap();
+            let shared: Dalek = Scalar::hash(&derivation).into();
+            let x = shared + Dalek::from_bytes_mod_order(spend);
+            let (output_key, image, signature) =
+                crate::device_key_images::test_support::device_sign(x, Dalek::from(n as u64 + 7));
+            assert_eq!(hex::encode(output_key), item["outKey"]);
+            signed.push(json!({
+                "outputId": item["outputId"],
+                "keyImage": hex::encode(image),
+                "signature": hex::encode(signature),
+            }));
+        }
+        let imported = crate::device_key_images::import_verified(
+            &mut device_db,
+            device_id,
+            &serde_json::Value::Array(signed).to_string(),
+        )
+        .unwrap();
+        assert_eq!(imported.imported, 2);
+
+        crate::spend::import_key_images(&mut software_db, software_id, &spend).unwrap();
+        let key_images = |db: &Db| -> Vec>> {
+            db.conn()
+                .prepare("SELECT key_image FROM outputs ORDER BY index_in_tx")
+                .unwrap()
+                .query_map([], |r| r.get(0))
+                .unwrap()
+                .collect::>()
+                .unwrap()
+        };
+        let from_device = key_images(&device_db);
+        assert!(from_device.iter().all(Option::is_some));
+        assert_eq!(from_device, key_images(&software_db));
+    }
+
     #[test]
     fn the_dummy_payment_id_of_a_real_transaction_is_not_stored() {
         let (item, stored) = scan_vector_with(VECTOR_PAYMENT_ID_MASK);
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
index 45398ff83..f225d6021 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
@@ -208,6 +208,8 @@ CREATE TABLE IF NOT EXISTS transactions (
     -- Payment ID decrypted with the view key when an output of the tx is scanned (8 bytes, or
     -- 32 for a pre-v12 unencrypted one). NULL when absent or all zeros (wallet2's dummy).
     payment_id      BLOB    CHECK (payment_id IS NULL OR length(payment_id) IN (8, 32)),
+    -- Received in a block's miner (coinbase) transaction, as wallet2 `m_coinbase`
+    coinbase        INTEGER NOT NULL DEFAULT 0 CHECK (coinbase IN (0, 1)),
     -- 0 while a rescan or reorg re-verifies the row; shown without a height until seen again
     scan_valid      INTEGER NOT NULL DEFAULT 1 CHECK (scan_valid IN (0, 1)),
     PRIMARY KEY (identity_id, txid)

From 9039d0f1571db14dd28361fc035ee1ecb9e78749 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 14:58:11 +0800
Subject: [PATCH 89/97] feat: share one Zcash fee and expiry policy across the
 runtimes (ZIP 2009) and bump to 0.1.0-alpha.12

---
 chain-runtimes/zcash/Cargo.lock               |  16 ++-
 chain-runtimes/zcash/Cargo.toml               |   6 +-
 .../crates/zcash-keys-runtime/Cargo.toml      |   1 +
 .../zcash/crates/zcash-runtime/Cargo.toml     |   1 +
 .../zcash/crates/zcash-send-policy/Cargo.toml |  11 ++
 .../zcash/crates/zcash-send-policy/src/lib.rs | 109 +++++++++++++++++
 ...cash_client_sqlite-0.22.0-no-bundled.patch | 113 ++++++++++++++++++
 7 files changed, 253 insertions(+), 4 deletions(-)
 create mode 100644 chain-runtimes/zcash/crates/zcash-send-policy/Cargo.toml
 create mode 100644 chain-runtimes/zcash/crates/zcash-send-policy/src/lib.rs

diff --git a/chain-runtimes/zcash/Cargo.lock b/chain-runtimes/zcash/Cargo.lock
index abc88a204..1509b9aab 100644
--- a/chain-runtimes/zcash/Cargo.lock
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -1655,7 +1655,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-zcash-keys"
-version = "0.1.0-alpha.11"
+version = "0.1.0-alpha.12"
 dependencies = [
  "bip0039",
  "bip32",
@@ -1665,6 +1665,7 @@ dependencies = [
  "getrandom 0.4.3",
  "hex",
  "js-sys",
+ "onekey-zcash-send-policy",
  "orchard",
  "pczt",
  "rand",
@@ -1687,7 +1688,7 @@ dependencies = [
 
 [[package]]
 name = "onekey-zcash-runtime"
-version = "0.1.0-alpha.11"
+version = "0.1.0-alpha.12"
 dependencies = [
  "blake2b_simd",
  "console_error_panic_hook",
@@ -1698,6 +1699,7 @@ dependencies = [
  "hex",
  "incrementalmerkletree",
  "js-sys",
+ "onekey-zcash-send-policy",
  "orchard",
  "pczt",
  "prost",
@@ -1734,6 +1736,15 @@ dependencies = [
  "zip321",
 ]
 
+[[package]]
+name = "onekey-zcash-send-policy"
+version = "0.1.0-alpha.12"
+dependencies = [
+ "serde",
+ "zcash_primitives",
+ "zcash_protocol",
+]
+
 [[package]]
 name = "opaque-debug"
 version = "0.3.1"
@@ -3373,6 +3384,7 @@ dependencies = [
  "jubjub",
  "maybe-rayon",
  "nonempty",
+ "onekey-zcash-send-policy",
  "orchard",
  "pczt",
  "prost",
diff --git a/chain-runtimes/zcash/Cargo.toml b/chain-runtimes/zcash/Cargo.toml
index e80d27a57..aa6395fb5 100644
--- a/chain-runtimes/zcash/Cargo.toml
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -1,13 +1,14 @@
 [workspace]
 resolver = "2"
 members = [
+  "crates/zcash-send-policy",
   "crates/zcash-runtime",
   "crates/zcash-keys-runtime",
 ]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.11"
+version = "0.1.0-alpha.12"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"
@@ -22,7 +23,8 @@ zcash_client_sqlite = { version = "0.22.0", default-features = false, features =
 zcash_keys = { version = "0.16.1", features = ["orchard", "sapling", "transparent-inputs"] }
 zcash_protocol = "0.10"
 # default-features = false: multicore makes halo2_proofs compile_error on wasm32 without atomics.
-zcash_primitives = { version = "0.30", default-features = false }
+zcash_primitives = { version = "0.30", default-features = false, features = ["non-standard-fees"] }
+onekey-zcash-send-policy = { path = "crates/zcash-send-policy" }
 transparent = { package = "zcash_transparent", version = "0.10" }
 zcash_address = "0.13"
 zip321 = "0.9.0"
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml
index 42368a778..ba2ed2a58 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml
@@ -11,6 +11,7 @@ crate-type = ["cdylib", "rlib"]
 
 # Minimal deps for mobile bundles: no client_backend, sqlite, or tonic.
 [dependencies]
+onekey-zcash-send-policy.workspace = true
 zcash_keys.workspace = true
 zcash_protocol.workspace = true
 zcash_address.workspace = true
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
index 47fb7efeb..69d193924 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
+++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
@@ -10,6 +10,7 @@ description = "OneKey Zcash Runtime: a thin wasm binding over librustzcash"
 crate-type = ["cdylib", "rlib"]
 
 [dependencies]
+onekey-zcash-send-policy.workspace = true
 incrementalmerkletree = "0.8.2"
 shardtree = "=0.7.1"
 blake2b_simd.workspace = true
diff --git a/chain-runtimes/zcash/crates/zcash-send-policy/Cargo.toml b/chain-runtimes/zcash/crates/zcash-send-policy/Cargo.toml
new file mode 100644
index 000000000..0a587ca69
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-send-policy/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "onekey-zcash-send-policy"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[dependencies]
+zcash_primitives.workspace = true
+zcash_protocol.workspace = true
+serde = { workspace = true, features = ["derive"] }
diff --git a/chain-runtimes/zcash/crates/zcash-send-policy/src/lib.rs b/chain-runtimes/zcash/crates/zcash-send-policy/src/lib.rs
new file mode 100644
index 000000000..3aad3894d
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-send-policy/src/lib.rs
@@ -0,0 +1,109 @@
+//! Shared transaction policy for the wallet runtime, stateless signer and host UI.
+
+use zcash_primitives::transaction::fees::zip317::{self, FeeRule};
+use zcash_protocol::{
+    consensus::{BlockHeight, BranchId, NetworkType, Parameters},
+    value::Zatoshis,
+};
+
+pub const ZIP2009_MAINNET_HEIGHT: u32 = 3_590_000;
+// Match Ledger's rollout margin; `target` is the next block, not the synced tip.
+pub const ZIP2009_SWITCH_MARGIN: u32 = 100;
+pub const EXPIRY_DELTA: u32 = 40;
+pub const MIN_VALID_BLOCKS: u32 = 8;
+
+pub fn marginal_fee(params: &P, target: BlockHeight) -> Zatoshis {
+    if params.network_type() != NetworkType::Main
+        || u32::from(target) >= ZIP2009_MAINNET_HEIGHT + ZIP2009_SWITCH_MARGIN
+    {
+        Zatoshis::const_from_u64(1_000)
+    } else {
+        zip317::MARGINAL_FEE
+    }
+}
+
+pub fn fee_rule(params: &P, target: BlockHeight) -> FeeRule {
+    FeeRule::non_standard(
+        marginal_fee(params, target),
+        zip317::GRACE_ACTIONS,
+        zip317::P2PKH_STANDARD_INPUT_SIZE,
+        zip317::P2PKH_STANDARD_OUTPUT_SIZE,
+    )
+    .expect("standard ZIP-317 input and output sizes are nonzero")
+}
+
+pub fn expiry_height(params: &P, target: BlockHeight) -> Option {
+    let target_u32 = u32::from(target);
+    let expiry = target_u32.checked_add(EXPIRY_DELTA)?;
+    let next_upgrade = BranchId::for_height(params, target)
+        .height_bounds(params)
+        .and_then(|(_, upper)| upper);
+    let expiry = next_upgrade.map_or(expiry, |height| expiry.min(u32::from(height) - 1));
+    (expiry.checked_sub(target_u32)? >= MIN_VALID_BLOCKS).then(|| BlockHeight::from_u32(expiry))
+}
+
+#[derive(serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TransactionPolicy {
+    pub marginal_fee_zat: String,
+    pub minimum_fee_zat: String,
+    pub expiry_height: Option,
+}
+
+pub fn transaction_policy(params: &P, target: BlockHeight) -> TransactionPolicy {
+    let marginal = u64::from(marginal_fee(params, target));
+    TransactionPolicy {
+        marginal_fee_zat: marginal.to_string(),
+        minimum_fee_zat: (marginal * zip317::GRACE_ACTIONS as u64).to_string(),
+        expiry_height: expiry_height(params, target).map(u32::from),
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use zcash_protocol::consensus::{NetworkUpgrade, MAIN_NETWORK, TEST_NETWORK};
+
+    #[test]
+    fn fees_switch_at_the_target_block() {
+        for (height, expected) in [
+            (3_589_999, 5_000),
+            (3_590_000, 5_000),
+            (3_590_099, 5_000),
+            (3_590_100, 1_000),
+        ] {
+            let target = BlockHeight::from_u32(height);
+            assert_eq!(
+                u64::from(fee_rule(&MAIN_NETWORK, target).marginal_fee()),
+                expected
+            );
+            assert_eq!(u64::from(marginal_fee(&TEST_NETWORK, target)), 1_000);
+        }
+    }
+
+    #[test]
+    fn expiry_stays_in_the_current_consensus_epoch() {
+        let upgrade = MAIN_NETWORK
+            .activation_height(NetworkUpgrade::Nu6_3)
+            .unwrap();
+        let target = upgrade - 20;
+        assert_eq!(expiry_height(&MAIN_NETWORK, target), Some(upgrade - 1));
+        assert_eq!(expiry_height(&MAIN_NETWORK, upgrade - 9), Some(upgrade - 1));
+        assert_eq!(expiry_height(&MAIN_NETWORK, upgrade - 8), None);
+        assert_eq!(
+            expiry_height(&MAIN_NETWORK, upgrade),
+            Some(upgrade + EXPIRY_DELTA)
+        );
+    }
+
+    #[test]
+    fn overflow_cannot_create_a_nonexpiring_transaction() {
+        assert_eq!(
+            expiry_height(&MAIN_NETWORK, BlockHeight::from_u32(u32::MAX)),
+            None
+        );
+        let policy = transaction_policy(&MAIN_NETWORK, BlockHeight::from_u32(3_590_100));
+        assert_eq!(policy.minimum_fee_zat, "2000");
+        assert_eq!(policy.expiry_height, Some(3_590_140));
+    }
+}
diff --git a/chain-runtimes/zcash/patches/zcash_client_sqlite-0.22.0-no-bundled.patch b/chain-runtimes/zcash/patches/zcash_client_sqlite-0.22.0-no-bundled.patch
index 3ae96b3fd..2baa1456b 100644
--- a/chain-runtimes/zcash/patches/zcash_client_sqlite-0.22.0-no-bundled.patch
+++ b/chain-runtimes/zcash/patches/zcash_client_sqlite-0.22.0-no-bundled.patch
@@ -8,3 +8,116 @@
      "time",
      "array",
      "uuid",
+@@ -454,3 +453,6 @@
+     'cfg(zcash_unstable, values("nu7"))',
+     "cfg(live_network_tests)",
+ ]
++
++[dependencies.onekey-zcash-send-policy]
++path = "../../crates/zcash-send-policy"
+--- a/src/wallet/common.rs
++++ b/src/wallet/common.rs
+@@ -12,7 +12,7 @@
+     },
+     wallet::ReceivedNote,
+ };
+-use zcash_primitives::transaction::{TxId, builder::DEFAULT_TX_EXPIRY_DELTA, fees::zip317};
++use zcash_primitives::transaction::{TxId, builder::DEFAULT_TX_EXPIRY_DELTA};
+ use zcash_protocol::{
+     PoolType, ShieldedPool,
+     consensus::{self, BlockHeight},
+@@ -436,13 +436,13 @@
+     .next())
+ }
+ 
+-/// Selects all the unspent notes with value greater than [`zip317::MARGINAL_FEE`] and for the
++/// Selects all the unspent notes with value greater than the height-dependent marginal fee and for the
+ /// specified shielded protocols from a given account, excepting any explicitly excluded note
+ /// identifiers.
+ ///
+ /// Implementation details:
+ ///
+-/// - Notes with individual value *below* the ``MARGINAL_FEE`` will be ignored
++/// - Notes with individual value *below* the marginal fee will be ignored
+ /// - Note spendability is determined using the `target_height`. If the note is mined at a height
+ ///   greater than or equal to the target height, it will still be returned by this query.
+ /// - The `to_received_note` function is expected to return `Ok(None)` in the case that spending
+@@ -528,7 +528,7 @@
+ 
+     let account_uuid = account.0;
+     let target_height_arg = u32::from(target_height);
+-    let min_value = u64::from(zip317::MARGINAL_FEE);
++    let min_value = u64::from(onekey_zcash_send_policy::marginal_fee(params, target_height.into()));
+     let overridable_owners = overridable_owners_rarray(lock_filter);
+     let mut sql_params: Vec<(&str, &dyn ToSql)> = vec![
+         (":account_uuid", &account_uuid),
+@@ -630,7 +630,7 @@
+ /// covers ``target_value`` alone, oldest first; callers take the head.
+ ///
+ /// - Implementation details
+-///   - Notes with individual value *below* the ``MARGINAL_FEE`` will be ignored
++///   - Notes with individual value *below* the marginal fee will be ignored
+ ///   - Note spendability is determined using the `anchor_height`
+ #[allow(clippy::too_many_arguments)]
+ fn select_spendable_notes_matching_value(
+@@ -810,7 +810,7 @@
+     let target_value_arg = u64::from(target_value);
+     let scanned_priority = priority_code(&ScanPriority::Scanned);
+     let tip_unscanned_arg = i64::from(tip_unscanned);
+-    let min_value = u64::from(zip317::MARGINAL_FEE);
++    let min_value = u64::from(onekey_zcash_send_policy::marginal_fee(params, target_height.into()));
+     let overridable_owners = overridable_owners_rarray(lock_filter);
+     let mut sql_params: Vec<(&str, &dyn ToSql)> = vec![
+         (":account_uuid", &account_uuid),
+--- a/src/wallet.rs
++++ b/src/wallet.rs
+@@ -127,7 +127,7 @@
+ use zcash_primitives::{
+     block::BlockHash,
+     merkle_tree::{HashSer, read_commitment_tree},
+-    transaction::{Transaction, TransactionData, builder::DEFAULT_TX_EXPIRY_DELTA, fees::zip317},
++    transaction::{Transaction, TransactionData, builder::DEFAULT_TX_EXPIRY_DELTA},
+ };
+ use zcash_protocol::{
+     PoolType, ShieldedPool, TxId,
+@@ -2749,6 +2749,7 @@
+     fn with_pool_balances(
+         tx: &rusqlite::Transaction,
+         target_height: TargetHeight,
++        marginal_fee: Zatoshis,
+         anchor_height: Option,
+         confirmations_policy: ConfirmationsPolicy,
+         account_balances: &mut HashMap,
+@@ -2912,7 +2913,7 @@
+                 uneconomic_value,
+             ) = {
+                 let zero = Zatoshis::ZERO;
+-                if value <= zip317::MARGINAL_FEE {
++                if value <= marginal_fee {
+                     (zero, zero, zero, zero, value)
+                 } else if is_spendable && is_locked {
+                     // Only notes that would otherwise be spendable are counted as locked; a
+@@ -2949,6 +2950,7 @@
+         with_pool_balances(
+             tx,
+             target_height,
++            onekey_zcash_send_policy::marginal_fee(params, target_height.into()),
+             anchor_height,
+             confirmations_policy,
+             &mut account_balances,
+@@ -2978,6 +2980,7 @@
+         with_pool_balances(
+             tx,
+             target_height,
++            onekey_zcash_send_policy::marginal_fee(params, target_height.into()),
+             anchor_height,
+             confirmations_policy,
+             &mut account_balances,
+@@ -3005,6 +3008,7 @@
+     with_pool_balances(
+         tx,
+         target_height,
++        onekey_zcash_send_policy::marginal_fee(params, target_height.into()),
+         anchor_height,
+         confirmations_policy,
+         &mut account_balances,

From 003a2de6ae014a10c0b97d5af45ccffa2dffd2f4 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 14:58:12 +0800
Subject: [PATCH 90/97] feat: seal Zcash transparent-to-shielded outputs to the
 Orchard OVK and inspect backend transactions

---
 chain-runtimes/zcash/README.md                |   6 +
 .../crates/zcash-keys-runtime/src/bindgen.rs  |  26 ++
 .../crates/zcash-keys-runtime/src/lib.rs      |   1 +
 .../src/transaction_history.rs                | 227 ++++++++++++
 .../src/transparent_send.rs                   |  48 ++-
 .../src/transparent_send/shielding.rs         | 345 ++++++++++++++++--
 6 files changed, 609 insertions(+), 44 deletions(-)
 create mode 100644 chain-runtimes/zcash/crates/zcash-keys-runtime/src/transaction_history.rs

diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md
index 066f25857..3bb8c1312 100644
--- a/chain-runtimes/zcash/README.md
+++ b/chain-runtimes/zcash/README.md
@@ -87,6 +87,7 @@ pcztVerifyReview(pczt, reviewJson)
 pcztSignWithAccountKeys(network, orchardSk, accountXprv, accountIndex, pczt, reviewJson)
 pcztRedactForHardwareSigner(pczt)
 transparentTx* / transparentShield* / parseTransparentTransactions(requestJson)
+transactionPolicy(targetHeight) / inspectTransaction(requestJson)
 keysCapabilities() / keysDependencyVersions()
 ```
 
@@ -94,7 +95,12 @@ keysCapabilities() / keysDependencyVersions()
 
 ```
 crates/zcash-runtime/            wallet, scanning, PCZT build/prove/submit
+crates/zcash-send-policy/        height-gated ZIP 2009 fees and bounded expiry
 crates/zcash-keys-runtime/       derivation, review checks, signing, stateless transparent sends
 patches/                         pinned upstream checksums and patches
 scripts/                         vendor-deps.sh, build-wasm.sh, package-release.py
 ```
+
+The pinned SQLite patch also uses the shared height-dependent marginal fee for
+spendable-note selection and uneconomic balance classification. `vendor-deps.sh`
+verifies this patch against the recorded upstream archive before a build.
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
index f176ac733..41001a66a 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
@@ -5,6 +5,20 @@ use zeroize::Zeroizing;
 
 use crate::{account_keys, keys, review, sign, transparent_prevouts, transparent_send};
 
+#[wasm_bindgen(js_name = transactionPolicy)]
+pub fn transaction_policy(target_height: u32) -> Result {
+    serde_json::to_string(&onekey_zcash_send_policy::transaction_policy(
+        &zcash_protocol::consensus::MAIN_NETWORK,
+        zcash_protocol::consensus::BlockHeight::from_u32(target_height),
+    ))
+    .map_err(|error| JsValue::from_str(&error.to_string()))
+}
+
+#[wasm_bindgen(js_name = inspectTransaction)]
+pub fn inspect_transaction(request_json: &str) -> Result {
+    Ok(crate::transaction_history::inspect_json(request_json)?)
+}
+
 #[wasm_bindgen(js_name = validateAddress)]
 pub fn validate_address(network: &str, address: &str) -> Result {
     Ok(keys::validate_address(network, address)?)
@@ -136,31 +150,38 @@ pub fn keys_capabilities() -> String {
     .to_string()
 }
 
+/// `ufvk` (this account's) seals Ironwood outputs to its Orchard external OVK so the sender can
+/// recover them; without it they are unrecoverable by the sender. The same key goes to the finalizing call.
 #[wasm_bindgen(js_name = transparentTxCreateWithAccountXpub)]
 pub fn transparent_tx_create_with_account_xpub(
     request_json: &str,
     account_xpub: &str,
     seed_fingerprint_hex: &str,
+    ufvk: Option,
 ) -> Result, JsValue> {
     Ok(transparent_send::shielding::create_with_account_xpub(
         request_json,
         account_xpub,
         seed_fingerprint_hex,
+        ufvk.as_deref(),
     )?)
 }
 
+/// With `ufvk`, every Ironwood output must be recoverable with its OVK.
 #[wasm_bindgen(js_name = transparentTxCombineHardwareSigned)]
 pub fn transparent_tx_combine_hardware_signed(
     request_json: &str,
     account_xpub: &str,
     original: Vec,
     signed: Vec,
+    ufvk: Option,
 ) -> Result, JsValue> {
     Ok(transparent_send::shielding::combine_hardware_signed(
         request_json,
         account_xpub,
         &original,
         &signed,
+        ufvk.as_deref(),
     )?)
 }
 
@@ -169,15 +190,18 @@ pub fn dependency_versions() -> String {
     crate::dependency_versions().to_string()
 }
 
+/// `ufvk` as in `transparentTxCreateWithAccountXpub`; pass the same key to the signing call.
 #[wasm_bindgen(js_name = transparentShieldCreateWithAccountXprv)]
 pub fn transparent_shield_create_with_account_xprv(
     request_json: &str,
     account_xprv: String,
+    ufvk: Option,
 ) -> Result, JsValue> {
     let account_xprv = Zeroizing::new(account_xprv);
     Ok(transparent_send::shielding::create_with_account_xprv(
         request_json,
         &account_xprv,
+        ufvk.as_deref(),
     )?)
 }
 
@@ -187,6 +211,7 @@ pub fn transparent_shield_sign_with_account_xprv(
     account_xprv: String,
     original: Vec,
     pczt: Vec,
+    ufvk: Option,
 ) -> Result, JsValue> {
     let account_xprv = Zeroizing::new(account_xprv);
     Ok(transparent_send::shielding::sign_with_account_xprv(
@@ -194,5 +219,6 @@ pub fn transparent_shield_sign_with_account_xprv(
         &account_xprv,
         &original,
         &pczt,
+        ufvk.as_deref(),
     )?)
 }
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs
index f2784c25b..4b4caf318 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs
@@ -8,6 +8,7 @@ pub mod error;
 pub mod keys;
 pub mod review;
 pub mod sign;
+pub mod transaction_history;
 pub mod transparent_prevouts;
 pub mod transparent_send;
 
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transaction_history.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transaction_history.rs
new file mode 100644
index 000000000..7f17c49a2
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transaction_history.rs
@@ -0,0 +1,227 @@
+//! Authenticated transaction facts and sender-side recovery; never queries a node.
+
+use std::collections::HashMap;
+
+use serde::{Deserialize, Serialize};
+use zcash_keys::keys::UnifiedFullViewingKey;
+use zcash_primitives::transaction::Transaction;
+use zcash_protocol::{
+    consensus::{BranchId, MAIN_NETWORK},
+    value::BalanceError,
+    TxId,
+};
+
+use crate::{ErrorCode, KeysError, Result};
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+struct RawTransaction {
+    txid: String,
+    raw_tx: String,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+struct Request {
+    transaction: RawTransaction,
+    #[serde(default)]
+    previous_transactions: Vec,
+    ufvk: Option,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct Outpoint {
+    txid: String,
+    vout: u32,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct RecoveredOutput {
+    recipient: String,
+    amount_zat: String,
+    memo_hex: String,
+}
+
+fn parse(raw: &RawTransaction) -> Result {
+    let invalid = || KeysError::new(ErrorCode::InvalidTransactionRequest);
+    if raw.raw_tx.len() > 8 * 1024 * 1024 {
+        return Err(invalid());
+    }
+    let bytes = hex::decode(&raw.raw_tx).map_err(|_| invalid())?;
+    let mut reader = &bytes[..];
+    let tx = Transaction::read(&mut reader, BranchId::Sprout).map_err(|e| invalid().detail(e))?;
+    if !reader.is_empty() || !tx.txid().to_string().eq_ignore_ascii_case(&raw.txid) {
+        return Err(invalid().detail("transaction does not match its txid"));
+    }
+    Ok(tx)
+}
+
+pub fn inspect_json(request_json: &str) -> Result {
+    if request_json.len() > 16 * 1024 * 1024 {
+        return Err(KeysError::new(ErrorCode::InvalidTransactionRequest));
+    }
+    let request: Request = serde_json::from_str(request_json)
+        .map_err(|_| KeysError::new(ErrorCode::InvalidTransactionRequest))?;
+    if request.previous_transactions.len() > 256 {
+        return Err(KeysError::new(ErrorCode::InvalidTransactionRequest));
+    }
+    let tx = parse(&request.transaction)?;
+    let previous = request
+        .previous_transactions
+        .iter()
+        .map(|raw| parse(raw).map(|tx| (tx.txid().to_string(), tx)))
+        .collect::>>()?;
+    let is_coinbase = tx
+        .transparent_bundle()
+        .is_some_and(|bundle| bundle.is_coinbase());
+    let inputs = tx
+        .transparent_bundle()
+        .filter(|_| !is_coinbase)
+        .map(|bundle| {
+            bundle
+                .vin
+                .iter()
+                .map(|input| Outpoint {
+                    txid: TxId::from_bytes(*input.prevout().hash()).to_string(),
+                    vout: input.prevout().n(),
+                })
+                .collect::>()
+        })
+        .unwrap_or_default();
+    let fee = if is_coinbase {
+        None
+    } else {
+        tx.fee_paid::(|outpoint| {
+            Ok(previous
+                .get(&TxId::from_bytes(*outpoint.hash()).to_string())
+                .and_then(|tx| tx.transparent_bundle())
+                .and_then(|bundle| bundle.vout.get(outpoint.n() as usize))
+                .map(|output| output.value()))
+        })
+        .map_err(|e| KeysError::new(ErrorCode::InvalidAmount).detail(e))?
+    };
+    let mut recovered = Vec::new();
+    if let Some(ufvk) = request.ufvk {
+        let ufvk = UnifiedFullViewingKey::decode(&MAIN_NETWORK, &ufvk)
+            .map_err(|e| KeysError::new(ErrorCode::InvalidUfvk).detail(e))?;
+        if let (Some(fvk), Some(bundle)) = (ufvk.orchard(), tx.ironwood_bundle()) {
+            let ovk = fvk.to_ovk(zip32::Scope::External);
+            for action in bundle.actions().iter() {
+                if let Some((note, recipient, memo)) =
+                    zcash_note_encryption::try_output_recovery_with_ovk(
+                        &orchard::note_encryption::IronwoodDomain::for_action(action),
+                        &ovk,
+                        action,
+                        action.cv_net(),
+                        &action.encrypted_note().out_ciphertext,
+                    )
+                {
+                    if note.value().inner() == 0 {
+                        continue;
+                    }
+                    let recipient = zcash_keys::address::UnifiedAddress::from_receivers(
+                        Some(recipient),
+                        None,
+                        None,
+                    )
+                    .ok_or_else(|| KeysError::new(ErrorCode::InvalidAddress))?
+                    .encode(&MAIN_NETWORK);
+                    recovered.push(RecoveredOutput {
+                        recipient,
+                        amount_zat: note.value().inner().to_string(),
+                        memo_hex: hex::encode(memo),
+                    });
+                }
+            }
+        }
+    }
+    serde_json::to_string(&serde_json::json!({
+        "txid": tx.txid().to_string(),
+        "inputs": inputs,
+        "feeZat": fee.map(|value| u64::from(value).to_string()),
+        "recoveredOutputs": recovered,
+    }))
+    .map_err(|e| KeysError::new(ErrorCode::InvalidTransactionRequest).detail(e))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use serde_json::{json, Value};
+
+    fn fixture() -> Value {
+        serde_json::from_str(include_str!("../tests/fixtures/previous-transactions.json")).unwrap()
+    }
+
+    fn raw_transaction(input: Option, value: u64) -> Value {
+        use transparent::address::{Script, TransparentAddress};
+        use transparent::bundle::{Bundle, OutPoint, TxIn, TxOut};
+        use zcash_primitives::transaction::{Authorized, TransactionData};
+        use zcash_protocol::{consensus::BlockHeight, value::Zatoshis};
+        let vin = input
+            .map(|prevout: OutPoint| TxIn::from_parts(prevout, Script::default(), u32::MAX))
+            .into_iter()
+            .collect();
+        let bundle = Bundle {
+            vin,
+            vout: vec![TxOut::new(
+                Zatoshis::from_u64(value).unwrap(),
+                TransparentAddress::PublicKeyHash([1; 20]).script().into(),
+            )],
+            authorization: transparent::bundle::Authorized,
+        };
+        let tx = TransactionData::::from_parts_v6(
+            BranchId::Nu6_3,
+            0,
+            BlockHeight::from_u32(3_500_040),
+            Some(bundle),
+            None,
+            None,
+            None,
+        )
+        .freeze()
+        .unwrap();
+        let mut bytes = Vec::new();
+        tx.write(&mut bytes).unwrap();
+        json!({ "txid": tx.txid().to_string(), "rawTx": hex::encode(bytes) })
+    }
+
+    #[test]
+    fn fee_uses_the_authenticated_previous_output() {
+        let previous = raw_transaction(None, 100_000);
+        let previous_tx = parse(&serde_json::from_value(previous.clone()).unwrap()).unwrap();
+        let transaction = raw_transaction(
+            Some(transparent::bundle::OutPoint::new(
+                *previous_tx.txid().as_ref(),
+                0,
+            )),
+            90_000,
+        );
+        let request = json!({ "transaction": transaction, "previousTransactions": [previous] });
+        let result: Value =
+            serde_json::from_str(&inspect_json(&request.to_string()).unwrap()).unwrap();
+        assert_eq!(result["feeZat"], "10000");
+        let mut corrupt = request;
+        corrupt["previousTransactions"][0]["txid"] = "ff".repeat(32).into();
+        assert!(inspect_json(&corrupt.to_string()).is_err());
+    }
+
+    #[test]
+    fn an_unknown_previous_output_does_not_invent_a_fee() {
+        let request = json!({"transaction": fixture()["transactions"][0]});
+        let result: Value =
+            serde_json::from_str(&inspect_json(&request.to_string()).unwrap()).unwrap();
+        assert!(result["feeZat"].is_null());
+        assert!(!result["inputs"].as_array().unwrap().is_empty());
+        assert!(result["recoveredOutputs"].as_array().unwrap().is_empty());
+    }
+
+    #[test]
+    fn a_backend_transaction_must_match_its_requested_hash() {
+        let mut request = json!({"transaction": fixture()["transactions"][0]});
+        request["transaction"]["txid"] = "00".repeat(32).into();
+        assert!(inspect_json(&request.to_string()).is_err());
+    }
+}
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
index f9b46634a..eb8812138 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
@@ -19,7 +19,6 @@ use zcash_keys::address::Address;
 use zcash_primitives::transaction::{
     fees::{
         transparent::{InputSize, OutputView},
-        zip317::{FeeRule as Zip317FeeRule, MARGINAL_FEE},
         FeeRule as _,
     },
     sighash::{signature_hash, SignableInput},
@@ -39,7 +38,7 @@ use crate::{
     error::{ErrorCode, KeysError, Result},
 };
 
-const MAX_EXPIRY_DELTA: u32 = 100;
+const MAX_EXPIRY_DELTA: u32 = onekey_zcash_send_policy::EXPIRY_DELTA;
 const XPRV_VERSION: [u8; 4] = [0x04, 0x88, 0xad, 0xe4];
 const ACCOUNT_XPRV_DEPTH: u8 = 3;
 
@@ -265,7 +264,10 @@ fn plan_transaction(request: TransparentTxRequest) -> Result {
                 }),
             )
         })?;
-    if expiry_delta == 0 || expiry_delta > MAX_EXPIRY_DELTA {
+    if expiry_delta < onekey_zcash_send_policy::MIN_VALID_BLOCKS
+        || onekey_zcash_send_policy::expiry_height(&MAIN_NETWORK, target_height)
+            .is_none_or(|maximum| request.expiry_height > u32::from(maximum))
+    {
         return Err(KeysError::with(
             ErrorCode::InvalidTargetHeight,
             serde_json::json!({
@@ -430,7 +432,13 @@ fn plan_transaction(request: TransparentTxRequest) -> Result {
 
         // Dust change goes to the fee (like upstream `AddDustToFee`). The subtraction cannot underflow
         // because input_total > send_total + fee_without_change here.
-        if input_total_raw < needed_with_change || change_raw < MARGINAL_FEE.into_u64() {
+        if input_total_raw < needed_with_change
+            || change_raw
+                < u64::from(onekey_zcash_send_policy::marginal_fee(
+                    &MAIN_NETWORK,
+                    target_height,
+                ))
+        {
             let fee_raw = input_total_raw - send_total_raw;
             (parse_zatoshis_u64(fee_raw, "fee")?, None)
         } else {
@@ -685,7 +693,7 @@ fn calculate_fee(
     } else {
         ironwood_outputs.max(2)
     };
-    Zip317FeeRule::standard()
+    onekey_zcash_send_policy::fee_rule(&MAIN_NETWORK, target_height)
         .fee_required(
             &MAIN_NETWORK,
             target_height,
@@ -998,6 +1006,34 @@ mod tests {
         request.to_string()
     }
 
+    #[test]
+    fn fee_quotes_follow_the_shared_height_policy() {
+        for (height, expected) in [
+            (3_589_999, "10000"),
+            (3_590_000, "10000"),
+            (3_590_099, "10000"),
+            (3_590_100, "2000"),
+        ] {
+            let mut request: serde_json::Value =
+                serde_json::from_str(&request_json(&[100_000], true)).unwrap();
+            request["targetHeight"] = height.into();
+            request["expiryHeight"] = (height + 40).into();
+            let quote: serde_json::Value =
+                serde_json::from_str("e_json(&request.to_string()).unwrap()).unwrap();
+            assert_eq!(quote["feeZat"], expected);
+        }
+    }
+
+    #[test]
+    fn a_transparent_quote_needs_eight_valid_blocks_and_at_most_forty() {
+        for delta in [0, 7, 41, 100] {
+            let mut request: serde_json::Value =
+                serde_json::from_str(&request_json(&[100_000], true)).unwrap();
+            request["expiryHeight"] = (3_500_000 + delta).into();
+            assert!(quote_json(&request.to_string()).is_err());
+        }
+    }
+
     #[test]
     fn quotes_and_creates_shielding_without_a_wallet_or_scan() {
         for send_max in [false, true] {
@@ -1009,7 +1045,7 @@ mod tests {
                 quote.send_amount_zat,
                 if send_max { "85000" } else { "50000" }
             );
-            let created = shielding::create_with_account_xprv(&request, &xprv()).unwrap();
+            let created = shielding::create_with_account_xprv(&request, &xprv(), None).unwrap();
             let pczt = pczt::Pczt::parse(&created).unwrap();
             assert_eq!(pczt.transparent().inputs().len(), 1);
             assert_eq!(pczt.transparent().outputs().len(), usize::from(!send_max));
diff --git a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
index 2a173a1f4..c25de416c 100644
--- a/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
@@ -22,13 +22,41 @@ fn failure(error: impl std::fmt::Debug) -> KeysError {
     KeysError::new(ErrorCode::TransactionBuildFailed).detail(format!("{error:?}"))
 }
 
-pub fn create_with_account_xprv(request_json: &str, account_xprv: &str) -> Result> {
+/// The Orchard external OVK upstream wallets seal outputs to others with; never the transparent OVK, which the xpub reveals.
+fn outgoing_viewing_key(
+    ufvk: Option<&str>,
+    key: &AccountPubKey,
+) -> Result> {
+    let Some(ufvk) = ufvk else {
+        return Ok(None);
+    };
+    let ufvk = zcash_keys::keys::UnifiedFullViewingKey::decode(&MAIN_NETWORK, ufvk)
+        .map_err(|e| KeysError::new(ErrorCode::InvalidUfvk).detail(e))?;
+    if ufvk.transparent() != Some(key) {
+        return Err(mismatch());
+    }
+    let fvk = ufvk
+        .orchard()
+        .ok_or_else(|| KeysError::new(ErrorCode::InvalidUfvk))?;
+    Ok(Some(fvk.to_ovk(zip32::Scope::External)))
+}
+
+pub fn create_with_account_xprv(
+    request_json: &str,
+    account_xprv: &str,
+    ufvk: Option<&str>,
+) -> Result> {
     let plan = plan_transaction(parse_request(request_json)?)?;
-    let key = parse_account_xprv(account_xprv, u32::from(plan.account_index))?;
-    create_with_public_key(&plan, &key.to_account_pubkey())
+    let key = parse_account_xprv(account_xprv, u32::from(plan.account_index))?.to_account_pubkey();
+    let ovk = outgoing_viewing_key(ufvk, &key)?;
+    create_with_public_key(&plan, &key, ovk)
 }
 
-fn create_with_public_key(plan: &TransactionPlan, key: &AccountPubKey) -> Result> {
+fn create_with_public_key(
+    plan: &TransactionPlan,
+    key: &AccountPubKey,
+    ovk: Option,
+) -> Result> {
     let mut builder = Builder::new(
         MAIN_NETWORK,
         plan.target_height,
@@ -67,7 +95,7 @@ fn create_with_public_key(plan: &TransactionPlan, key: &AccountPubKey) -> Result
                 .map_err(failure)?,
             RecipientAddress::Ironwood(address) => builder
                 .add_ironwood_output::(
-                    None,
+                    ovk.clone(),
                     address,
                     output.value,
                     output.memo.clone(),
@@ -145,6 +173,7 @@ pub fn create_with_account_xpub(
     request_json: &str,
     account_xpub: &str,
     seed_fingerprint_hex: &str,
+    ufvk: Option<&str>,
 ) -> Result> {
     let plan = plan_transaction(parse_request(request_json)?)?;
     let key = parse_account_xpub(account_xpub, u32::from(plan.account_index))?;
@@ -152,7 +181,8 @@ pub fn create_with_account_xpub(
         .map_err(|_| KeysError::new(ErrorCode::InvalidTransactionRequest))?
         .try_into()
         .map_err(|_| KeysError::new(ErrorCode::InvalidTransactionRequest))?;
-    let original = create_with_public_key(&plan, &key)?;
+    let ovk = outgoing_viewing_key(ufvk, &key)?;
+    let original = create_with_public_key(&plan, &key, ovk)?;
     let pczt = pczt::Pczt::parse(&original).map_err(failure)?;
     let derivation = |path: DerivationPath| {
         transparent::pczt::Bip32Derivation::parse(
@@ -219,10 +249,17 @@ pub fn combine_hardware_signed(
     account_xpub: &str,
     original: &[u8],
     signed: &[u8],
+    ufvk: Option<&str>,
 ) -> Result> {
     let plan = plan_transaction(parse_request(request_json)?)?;
     let key = parse_account_xpub(account_xpub, u32::from(plan.account_index))?;
-    let original = validate_original(&plan, &key, pczt::Pczt::parse(original).map_err(failure)?)?;
+    let ovk = outgoing_viewing_key(ufvk, &key)?;
+    let original = validate_original(
+        &plan,
+        &key,
+        ovk.as_ref(),
+        pczt::Pczt::parse(original).map_err(failure)?,
+    )?;
     let original_signer = Signer::new(original.clone()).map_err(failure)?;
     let combined = Combiner::new(vec![original, pczt::Pczt::parse(signed).map_err(failure)?])
         .combine()
@@ -287,7 +324,11 @@ fn mismatch() -> KeysError {
     KeysError::new(ErrorCode::KeyMismatch)
 }
 
-fn validate_ironwood(bundle: &orchard::pczt::Bundle, plan: &TransactionPlan) -> Result<()> {
+fn validate_ironwood(
+    bundle: &orchard::pczt::Bundle,
+    plan: &TransactionPlan,
+    ovk: Option<&orchard::keys::OutgoingViewingKey>,
+) -> Result<()> {
     let mut expected = plan
         .recipients
         .iter()
@@ -355,6 +396,7 @@ fn validate_ironwood(bundle: &orchard::pczt::Bundle, plan: &TransactionPlan) ->
             )
             .into_option()
             .ok_or_else(mismatch)?;
+            // The OVK seals only `out_ciphertext`, checked below.
             let encryptor = orchard::note_encryption::IronwoodNoteEncryption::new(
                 None,
                 note,
@@ -366,6 +408,16 @@ fn validate_ironwood(bundle: &orchard::pczt::Bundle, plan: &TransactionPlan) ->
             {
                 return Err(mismatch());
             }
+            if let Some(ovk) = ovk {
+                zcash_note_encryption::try_output_recovery_with_ovk(
+                    &orchard::note_encryption::IronwoodDomain::for_pczt_action(action),
+                    ovk,
+                    action,
+                    action.cv_net(),
+                    &output.encrypted_note().out_ciphertext,
+                )
+                .ok_or_else(mismatch)?;
+            }
         }
     }
     if !expected.is_empty() {
@@ -374,9 +426,11 @@ fn validate_ironwood(bundle: &orchard::pczt::Bundle, plan: &TransactionPlan) ->
     Ok(())
 }
 
+/// With an OVK, every Ironwood payment must also be recoverable with it.
 fn validate_original(
     plan: &TransactionPlan,
     key: &AccountPubKey,
+    ovk: Option<&orchard::keys::OutgoingViewingKey>,
     pczt: pczt::Pczt,
 ) -> Result {
     let global = pczt.global();
@@ -459,7 +513,9 @@ fn validate_original(
         .map_err(failure)?;
     let verified = if has_ironwood {
         verified
-            .with_ironwood(|bundle| validate_ironwood(bundle, plan).map_err(OrchardError::Custom))
+            .with_ironwood(|bundle| {
+                validate_ironwood(bundle, plan, ovk).map_err(OrchardError::Custom)
+            })
             .map_err(failure)?
     } else {
         verified
@@ -472,21 +528,25 @@ pub fn sign_with_account_xprv(
     account_xprv: &str,
     original: &[u8],
     pczt: &[u8],
+    ufvk: Option<&str>,
 ) -> Result> {
     let plan = plan_transaction(parse_request(request_json)?)?;
     let key = parse_account_xprv(account_xprv, u32::from(plan.account_index))?;
-    sign_with_key(&plan, &key, original, pczt)
+    let ovk = outgoing_viewing_key(ufvk, &key.to_account_pubkey())?;
+    sign_with_key(&plan, &key, ovk.as_ref(), original, pczt)
 }
 
 fn sign_with_key(
     plan: &TransactionPlan,
     key: &AccountPrivKey,
+    ovk: Option<&orchard::keys::OutgoingViewingKey>,
     original: &[u8],
     pczt: &[u8],
 ) -> Result> {
     let original = validate_original(
         plan,
         &key.to_account_pubkey(),
+        ovk,
         pczt::Pczt::parse(original).map_err(failure)?,
     )?;
     let pczt = pczt::Pczt::parse(pczt).map_err(failure)?;
@@ -545,11 +605,11 @@ mod tests {
     }
 
     fn create(request_json: &str) -> Result> {
-        create_with_account_xprv(request_json, &xprv())
+        create_with_account_xprv(request_json, &xprv(), None)
     }
 
     fn sign(request_json: &str, original: &[u8], pczt: &[u8]) -> Result> {
-        sign_with_account_xprv(request_json, &xprv(), original, pczt)
+        sign_with_account_xprv(request_json, &xprv(), original, pczt, None)
     }
 
     fn transparent_address(scope: u32, index: u32) -> TransparentAddress {
@@ -661,7 +721,7 @@ mod tests {
             let folded = 100_000 - amount.parse::().unwrap();
             assert_eq!(quote["feeZat"], folded.to_string(), "surplus goes to fee");
             if hardware {
-                create_with_account_xpub(&request, &account_xpub(), &fingerprint)
+                create_with_account_xpub(&request, &account_xpub(), &fingerprint, None)
                     .expect("hardware path builds with the quoted fee");
             } else {
                 create(&request).expect("software path builds with the quoted fee");
@@ -679,9 +739,13 @@ mod tests {
             { "address": transparent_address(0, 9).to_zcash_address(NetworkType::Main).to_string(), "amountZat": "10000" },
         ]);
         for _ in 0..4 {
-            let original =
-                create_with_account_xpub(&request.to_string(), &account_xpub(), &"01".repeat(32))
-                    .unwrap();
+            let original = create_with_account_xpub(
+                &request.to_string(),
+                &account_xpub(),
+                &"01".repeat(32),
+                None,
+            )
+            .unwrap();
             let pczt = pczt::Pczt::parse(&original).unwrap();
             Verifier::new(pczt)
                 .with_transparent::(|bundle| {
@@ -740,18 +804,22 @@ mod tests {
             .push(outpoint);
         let request = request.to_string();
         let original =
-            create_with_account_xpub(&request, &account_xpub(), &"01".repeat(32)).unwrap();
+            create_with_account_xpub(&request, &account_xpub(), &"01".repeat(32), None).unwrap();
         assert!(combine_hardware_signed(
             &request,
             &account_xpub(),
             &original,
-            &simulated_device_signatures(&original, 1)
+            &simulated_device_signatures(&original, 1),
+            None
         )
         .is_err());
         let signed = simulated_device_signatures(&original, 2);
         let finalized =
-            combine_hardware_signed(&request, &account_xpub(), &original, &signed).unwrap();
-        assert!(combine_hardware_signed(&request, &account_xpub(), &original, &finalized).is_err());
+            combine_hardware_signed(&request, &account_xpub(), &original, &signed, None).unwrap();
+        assert!(
+            combine_hardware_signed(&request, &account_xpub(), &original, &finalized, None)
+                .is_err()
+        );
         let parsed = pczt::Pczt::parse(&signed).unwrap();
         let mut signature = Vec::new();
         Verifier::new(parsed)
@@ -771,9 +839,12 @@ mod tests {
             .unwrap();
         let mut corrupted = signed.clone();
         corrupted[position + signature.len() - 3] ^= 1;
-        assert!(combine_hardware_signed(&request, &account_xpub(), &original, &corrupted).is_err());
-        assert!(create_with_account_xpub(&request, "not-an-xpub", &"01".repeat(32)).is_err());
-        assert!(create_with_account_xpub(&request, &account_xpub(), "01").is_err());
+        assert!(
+            combine_hardware_signed(&request, &account_xpub(), &original, &corrupted, None)
+                .is_err()
+        );
+        assert!(create_with_account_xpub(&request, "not-an-xpub", &"01".repeat(32), None).is_err());
+        assert!(create_with_account_xpub(&request, &account_xpub(), "01", None).is_err());
     }
 
     #[test]
@@ -790,10 +861,11 @@ mod tests {
             });
             let request_json = request.to_string();
             let original =
-                create_with_account_xpub(&request_json, &account_xpub(), &"01".repeat(32)).unwrap();
+                create_with_account_xpub(&request_json, &account_xpub(), &"01".repeat(32), None)
+                    .unwrap();
             let signed = simulated_device_signature(&original);
             let finalized =
-                combine_hardware_signed(&request_json, &account_xpub(), &original, &signed)
+                combine_hardware_signed(&request_json, &account_xpub(), &original, &signed, None)
                     .unwrap();
             Verifier::new(pczt::Pczt::parse(&finalized).unwrap())
                 .with_transparent::(|bundle| {
@@ -816,7 +888,8 @@ mod tests {
             assert!(create_with_account_xpub(
                 &request.to_string(),
                 &account_xpub(),
-                &"01".repeat(32)
+                &"01".repeat(32),
+                None
             )
             .is_err());
         }
@@ -834,13 +907,22 @@ mod tests {
                         .into();
                 }
                 let request_json = request.to_string();
-                let original =
-                    create_with_account_xpub(&request_json, &account_xpub(), &"01".repeat(32))
-                        .unwrap();
+                let original = create_with_account_xpub(
+                    &request_json,
+                    &account_xpub(),
+                    &"01".repeat(32),
+                    None,
+                )
+                .unwrap();
                 let signed = simulated_device_signature(&original);
-                let finalized =
-                    combine_hardware_signed(&request_json, &account_xpub(), &original, &signed)
-                        .unwrap();
+                let finalized = combine_hardware_signed(
+                    &request_json,
+                    &account_xpub(),
+                    &original,
+                    &signed,
+                    None,
+                )
+                .unwrap();
                 Verifier::new(pczt::Pczt::parse(&finalized).unwrap())
                     .with_transparent::(|bundle| {
                         assert!(bundle.inputs()[0].script_sig().is_some());
@@ -855,14 +937,16 @@ mod tests {
                     &request_json,
                     &account_xpub(),
                     &original,
-                    &changed
+                    &changed,
+                    None
                 )
                 .is_err());
                 assert!(combine_hardware_signed(
                     &request_json,
                     &account_xpub(),
                     &original,
-                    &original
+                    &original,
+                    None
                 )
                 .is_err());
             }
@@ -881,7 +965,8 @@ mod tests {
             }
             let request_json = request.to_string();
             let original =
-                create_with_account_xpub(&request_json, &account_xpub(), &"01".repeat(32)).unwrap();
+                create_with_account_xpub(&request_json, &account_xpub(), &"01".repeat(32), None)
+                    .unwrap();
             let redacted = crate::sign::redact_for_hardware_signer(&original).unwrap();
             assert!(redacted.len() < original.len());
             assert_eq!(
@@ -894,6 +979,7 @@ mod tests {
                 &account_xpub(),
                 &original,
                 &simulated_device_signature(&original),
+                None,
             )
             .unwrap();
             let from_redacted = combine_hardware_signed(
@@ -901,6 +987,7 @@ mod tests {
                 &account_xpub(),
                 &original,
                 &simulated_device_signature(&redacted),
+                None,
             )
             .unwrap();
             assert_eq!(from_redacted, from_original);
@@ -1150,11 +1237,14 @@ mod tests {
     fn account_xprv_has_the_same_authorization_checks() {
         let request = request(false).to_string();
         let xprv = xprv();
-        let original = create_with_account_xprv(&request, &xprv).unwrap();
-        sign_with_account_xprv(&request, &xprv, &original, &original).unwrap();
+        let original = create_with_account_xprv(&request, &xprv, None).unwrap();
+        sign_with_account_xprv(&request, &xprv, &original, &original, None).unwrap();
         let mut changed: Value = serde_json::from_str(&request).unwrap();
         changed["recipients"][0]["address"] = recipient(1).into();
-        assert!(sign_with_account_xprv(&changed.to_string(), &xprv, &original, &original).is_err());
+        assert!(
+            sign_with_account_xprv(&changed.to_string(), &xprv, &original, &original, None)
+                .is_err()
+        );
     }
 
     #[test]
@@ -1178,4 +1268,183 @@ mod tests {
         });
         assert!(sign(&request, &modified, &modified).is_err());
     }
+
+    fn ufvk(account: u32) -> String {
+        crate::account_keys::test_keys::signing_keys(&SEED, account)
+            .ufvk()
+            .unwrap()
+    }
+
+    // Seed oracle: the OVK upstream `decrypt_transaction` tries for an account's Orchard-family outputs.
+    fn account_ovk(scope: zip32::Scope) -> orchard::keys::OutgoingViewingKey {
+        crate::account_keys::test_keys::usk(&SEED, 0)
+            .to_unified_full_viewing_key()
+            .orchard()
+            .unwrap()
+            .to_ovk(scope)
+    }
+
+    fn ironwood_receiver(address: &str) -> orchard::Address {
+        let RecipientAddress::Ironwood(receiver) = parse_recipient_address(address).unwrap() else {
+            panic!("expected an Ironwood recipient");
+        };
+        receiver
+    }
+
+    // The sender-side recovery `decrypt_transaction` runs on each Ironwood action.
+    fn recovered_payments(
+        pczt: &[u8],
+        ovk: &orchard::keys::OutgoingViewingKey,
+    ) -> Vec<(orchard::Address, u64, Vec)> {
+        let mut recovered = Vec::new();
+        Verifier::new(pczt::Pczt::parse(pczt).unwrap())
+            .with_ironwood::(|bundle| {
+                for action in bundle.actions() {
+                    if let Some((note, address, memo)) =
+                        zcash_note_encryption::try_output_recovery_with_ovk(
+                            &orchard::note_encryption::IronwoodDomain::for_pczt_action(action),
+                            ovk,
+                            action,
+                            action.cv_net(),
+                            &action.output().encrypted_note().out_ciphertext,
+                        )
+                    {
+                        recovered.push((address, note.value().inner(), memo.to_vec()));
+                    }
+                }
+                Ok(())
+            })
+            .unwrap();
+        recovered
+    }
+
+    #[test]
+    fn ironwood_payments_are_recoverable_with_the_account_external_ovk() {
+        let memo = format!("e4b8ade6968720f09f9982{}", "00".repeat(512 - 11));
+        for send_max in [false, true] {
+            let mut request = request(send_max);
+            request["recipients"][0]["memoHex"] = memo.clone().into();
+            let request = request.to_string();
+            let quote: Value = serde_json::from_str("e_json(&request).unwrap()).unwrap();
+            let expected = vec![(
+                ironwood_receiver(&recipient(0)),
+                quote["sendAmountZat"].as_str().unwrap().parse().unwrap(),
+                hex::decode(&memo).unwrap(),
+            )];
+            let original = create_with_account_xprv(&request, &xprv(), Some(&ufvk(0))).unwrap();
+            let signed =
+                sign_with_account_xprv(&request, &xprv(), &original, &original, Some(&ufvk(0)))
+                    .unwrap();
+            assert_eq!(
+                recovered_payments(&signed, &account_ovk(zip32::Scope::External)),
+                expected
+            );
+            assert!(recovered_payments(&signed, &account_ovk(zip32::Scope::Internal)).is_empty());
+        }
+    }
+
+    #[test]
+    fn hardware_ironwood_payments_are_recoverable_with_the_account_external_ovk() {
+        let request = request(false).to_string();
+        let original =
+            create_with_account_xpub(&request, &account_xpub(), &"01".repeat(32), Some(&ufvk(0)))
+                .unwrap();
+        let redacted = crate::sign::redact_for_hardware_signer(&original).unwrap();
+        let finalized = combine_hardware_signed(
+            &request,
+            &account_xpub(),
+            &original,
+            &simulated_device_signature(&redacted),
+            Some(&ufvk(0)),
+        )
+        .unwrap();
+        assert_eq!(
+            recovered_payments(&finalized, &account_ovk(zip32::Scope::External)),
+            vec![(
+                ironwood_receiver(&recipient(0)),
+                50_000,
+                MemoBytes::empty().as_array().to_vec()
+            )]
+        );
+    }
+
+    #[test]
+    fn without_a_ufvk_payments_stay_unrecoverable_and_a_ufvk_signer_refuses_them() {
+        let request = request(false).to_string();
+        let original = create(&request).unwrap();
+        assert!(recovered_payments(&original, &account_ovk(zip32::Scope::External)).is_empty());
+        sign(&request, &original, &original).unwrap();
+        assert!(
+            sign_with_account_xprv(&request, &xprv(), &original, &original, Some(&ufvk(0)))
+                .is_err()
+        );
+
+        let original =
+            create_with_account_xpub(&request, &account_xpub(), &"01".repeat(32), None).unwrap();
+        let signed = simulated_device_signature(&original);
+        combine_hardware_signed(&request, &account_xpub(), &original, &signed, None).unwrap();
+        assert!(combine_hardware_signed(
+            &request,
+            &account_xpub(),
+            &original,
+            &signed,
+            Some(&ufvk(0))
+        )
+        .is_err());
+    }
+
+    #[test]
+    fn a_ufvk_signer_rejects_an_out_ciphertext_it_cannot_recover() {
+        let request = request(false).to_string();
+        let original = create_with_account_xprv(&request, &xprv(), Some(&ufvk(0))).unwrap();
+        let modified = mutate(&original, |value| {
+            let output = &mut value["ironwood"]["actions"]
+                .as_array_mut()
+                .unwrap()
+                .iter_mut()
+                .find(|action| action["output"]["value"].as_u64().unwrap() != 0)
+                .unwrap()["output"];
+            output["out_ciphertext"] = json!(vec![0u8; 80]);
+        });
+        sign(&request, &modified, &modified).unwrap();
+        assert!(
+            sign_with_account_xprv(&request, &xprv(), &modified, &modified, Some(&ufvk(0)))
+                .is_err()
+        );
+    }
+
+    #[test]
+    fn rejects_a_ufvk_that_does_not_name_this_account() {
+        let request = request(false).to_string();
+        let other = ufvk(1);
+        let code = |result: Result>| result.unwrap_err().code;
+        assert_eq!(
+            code(create_with_account_xprv(&request, &xprv(), Some(&other))),
+            ErrorCode::KeyMismatch
+        );
+        assert_eq!(
+            code(create_with_account_xpub(
+                &request,
+                &account_xpub(),
+                &"01".repeat(32),
+                Some(&other)
+            )),
+            ErrorCode::KeyMismatch
+        );
+        assert_eq!(
+            code(create_with_account_xprv(&request, &xprv(), Some("uview1"))),
+            ErrorCode::InvalidUfvk
+        );
+        let original = create_with_account_xprv(&request, &xprv(), Some(&ufvk(0))).unwrap();
+        assert_eq!(
+            code(sign_with_account_xprv(
+                &request,
+                &xprv(),
+                &original,
+                &original,
+                Some(&other)
+            )),
+            ErrorCode::KeyMismatch
+        );
+    }
 }

From fee159dbae572b074a995a6b1a6d44894af966d5 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 14:58:12 +0800
Subject: [PATCH 91/97] fix: release the notes of a definitively rejected Zcash
 send at once and apply the shared fee policy

---
 .../zcash/crates/zcash-runtime/src/account.rs |  17 +-
 .../zcash/crates/zcash-runtime/src/bindgen.rs |  17 +-
 .../zcash/crates/zcash-runtime/src/error.rs   |   7 +-
 .../zcash/crates/zcash-runtime/src/network.rs |  31 +-
 .../zcash/crates/zcash-runtime/src/send.rs    | 576 +++++++++++++-----
 .../crates/zcash-runtime/src/tx_state.rs      | 157 ++++-
 6 files changed, 606 insertions(+), 199 deletions(-)

diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
index 8622fefdf..5820484ab 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
@@ -414,7 +414,7 @@ fn balance_value(
             "spendable": u64::from(b.spendable_value()),
             "pendingChange": u64::from(b.change_pending_confirmation()),
             "pendingSpendable": u64::from(b.value_pending_spendability()),
-            // Held by an unexpired upstream output lock; this runtime's sends take none.
+            // Held by an unexpired upstream output lock: a send not yet stored after its broadcast.
             "locked": u64::from(b.locked_value()),
             "total": u64::from(b.total()),
             // Unspent notes worth <= the marginal fee, confirmed or not. Upstream
@@ -529,13 +529,11 @@ pub fn account_by_name(db: &Db, name: &str) -> Result {
 }
 
 /// `{ uuid }` of the first account `matches` accepts, or `"null"`.
-fn find_account(
-    db: &Db,
-    matches: impl Fn(&::Account) -> bool,
-) -> Result {
-    Ok(matching_accounts(db, matches)?
-        .first()
-        .map_or_else(|| "null".to_string(), |uuid| json!({ "uuid": uuid }).to_string()))
+fn find_account(db: &Db, matches: impl Fn(&::Account) -> bool) -> Result {
+    Ok(matching_accounts(db, matches)?.first().map_or_else(
+        || "null".to_string(),
+        |uuid| json!({ "uuid": uuid }).to_string(),
+    ))
 }
 
 /// UUIDs of every account `matches` accepts.
@@ -869,7 +867,8 @@ mod remove_account_tests {
     fn wallet() -> Db {
         let conn = rusqlite::Connection::open_in_memory().unwrap();
         rusqlite::vtab::array::load_module(&conn).unwrap();
-        let mut db = WalletDb::from_connection(conn, NET, HostClock, ChaCha20Rng::from_seed([7; 32]));
+        let mut db =
+            WalletDb::from_connection(conn, NET, HostClock, ChaCha20Rng::from_seed([7; 32]));
         WalletMigrator::new()
             .with_external_migrations(crate::tx_state::migrations())
             .init_or_migrate(&mut db)
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
index d3ad425a9..891e50ff4 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
@@ -74,12 +74,16 @@ pub fn dependency_versions() -> String {
 }
 
 /// Opens a page-backed database and applies the official SQLite migrations.
+///
+/// Also stores, as pending, any send whose submit stopped before its outcome was stored.
 #[wasm_bindgen(js_name = openWallet)]
 pub async fn open_wallet(network_name: String, db_name: String) -> Result {
     let (network_name, db_name) = (network_name.as_str(), db_name.as_str());
     let db = wallet::open_and_migrate(network_name, db_name)?;
     // WALLET_BUSY must propagate, or the caller assumes the database was swapped.
     runtime::set_db(db, db_name)?;
+    // Best effort: until stored, the send's inputs stay locked and the next submit retries.
+    let _ = runtime::with_db(send::settle_interrupted_submissions);
     Ok(serde_json::json!({ "dbName": db_name, "network": network_name }).to_string())
 }
 
@@ -485,13 +489,18 @@ async fn barrier_after_irreversible(params: serde_json::Value) -> Result<(), cra
     })
 }
 
-/// Submits a proven and signed PCZT: extracts the transaction, persists it, then broadcasts.
+/// Submits a proven and signed PCZT: locks its notes and records it, broadcasts it, then
+/// stores it unless the node definitively rejected it.
 ///
 /// Returns `{ txid, broadcast: "accepted" | "rejected" | "unknown", error? }`.
 /// - `rejected`: the node definitively judged it consensus-invalid or expired; it can never be
-///   mined. The transaction stays stored and its notes return only at expiry height.
-/// - `unknown`: delivery to the node is uncertain. The transaction stays pending until mined
-///   or expired; the host does not resubmit it and must not treat it as failed.
+///   mined. It is not stored and its notes are spendable again at once (if an earlier submit
+///   stored it, it is marked rejected and its notes return at its expiry height).
+/// - `unknown`: delivery to the node is uncertain. The transaction is stored and stays pending
+///   until mined or expired; the host does not resubmit it and must not treat it as failed.
+///
+/// Throws `FINALIZE_OUTCOME_UNKNOWN` when storing fails after the broadcast; `openWallet` or
+/// the next submit stores it as pending.
 #[wasm_bindgen(js_name = pcztSubmit)]
 pub async fn pczt_submit(account_uuid: String, pczt_bytes: Vec) -> Result {
     let outcome = runtime::with_db_and_client(move |mut db, mut client| async move {
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
index ce6b68fbb..eb760f07e 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
@@ -99,7 +99,8 @@ pub enum ErrorCode {
     /// The node definitively judged the transaction consensus-invalid or expired; it
     /// can never be mined. Params: `{ errorCode }`; `detail` holds the node's message.
     ///
-    /// Unlike `NETWORK_ERROR`, do not retry as-is; the spent notes return only at the expiry height.
+    /// Unlike `NETWORK_ERROR`, do not retry as-is. A first submit's notes are spendable again;
+    /// a stored transaction's notes return only at its expiry height.
     BroadcastRejected,
     /// The node returned an error that does not prove the transaction can never be
     /// mined: it may already be mined or in the mempool (double spend, duplicate
@@ -108,8 +109,8 @@ pub enum ErrorCode {
     /// resubmit it; scanning resolves it as mined or expired. Hosts must not treat
     /// this as a failed send. Params: `{ errorCode }`; `detail` holds the node's message.
     BroadcastOutcomeUnknown,
-    /// The transaction may be in the in-memory wallet but persistence is unconfirmed.
-    /// Do not unlock or rebuild the transaction.
+    /// The transaction may have been broadcast but persisting the outcome is unconfirmed.
+    /// The send is kept, as pending once stored; do not rebuild it.
     FinalizeOutcomeUnknown,
 
     /// Capability not implemented. Params: `{ what }`
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
index c8a238458..58c064221 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
@@ -229,10 +229,25 @@ fn broadcast_definitely_invalid(message: &str) -> bool {
         return false;
     }
     let message = message.to_lowercase();
-    // zcashd consensus reject reasons; `tx-expiring-soon` is policy and excluded.
-    ["bad-txns-", "bad-tx-", "tx-overwinter-expired"]
-        .iter()
-        .any(|needle| message.contains(needle))
+    // These reasons reject immutable transaction contents. A broad `bad-txns-`
+    // prefix also includes chain-dependent anchors, nullifiers and relay policy.
+    const DEFINITIVE_REASONS: &[&str] = &[
+        "tx-overwinter-expired",
+        "bad-txns-vin-empty",
+        "bad-txns-vout-empty",
+        "bad-txns-oversize",
+        "bad-txns-vout-negative",
+        "bad-txns-vout-toolarge",
+        "bad-txns-txouttotal-toolarge",
+        "bad-txns-txintotal-toolarge",
+        "bad-txns-inputs-duplicate",
+        "bad-txns-in-belowout",
+        "bad-txns-fee-outofrange",
+        "bad-txns-orchard-verification-failed",
+    ];
+    message
+        .split(|character: char| !character.is_ascii_alphanumeric() && character != '-')
+        .any(|reason| DEFINITIVE_REASONS.contains(&reason))
 }
 
 fn broadcast_already_known(message: &str) -> bool {
@@ -308,7 +323,6 @@ mod tests {
     fn only_consensus_invalid_or_expired_replies_count_as_a_rejection() {
         for message in [
             "tx-overwinter-expired",
-            "bad-txns-fee-too-low",
             "bad-txns-orchard-verification-failed",
             "16: bad-txns-vout-negative",
         ] {
@@ -318,6 +332,13 @@ mod tests {
             "bad-txns-inputs-spent",
             "bad-txns-inputs-missingorspent",
             "bad-txns-shielded-requirements-not-met",
+            "bad-txns-orchard-unknown-anchor",
+            "bad-txns-orchard-duplicate-nullifier",
+            "bad-txns-ironwood-duplicate-nullifier",
+            "bad-txns-fee-too-low",
+            "bad-txns-nonfinal",
+            "bad-tx-overwinter-version-too-high",
+            "bad-txns-vout-negative-unrecognized-suffix",
             "tx-expiring-soon",
             "transaction is non-standard",
             "transaction dropped because the queue is full",
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
index 0ea8a1bf7..5dd2b71c7 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
@@ -6,21 +6,25 @@
 //!   runtime.pcztCreate()          build (needs wallet state: note selection, witness, anchor)
 //!   runtime.pcztProve()           prove; pure computation, no private keys
 //!   keys.pcztSignWithAccountKeys() sign (needs the spending keys; in onekey-zcash-keys)
-//!   runtime.pcztSubmit()          extract, store, broadcast once (sync does not rebroadcast)
+//!   runtime.pcztSubmit()          hold inputs, broadcast once, store unless rejected (sync does not rebroadcast)
 //! ```
 //!
 //! Build and broadcast need the wallet database, signing needs the spending keys; they never share a crate.
 
+use rusqlite::OptionalExtension;
 use zcash_client_backend::data_api::wallet::{
     create_pczt_from_proposal, extract_and_store_transaction_from_pczt,
     input_selection::GreedyInputSelector, propose_transfer,
 };
-use zcash_client_backend::data_api::WalletRead;
+use zcash_client_backend::data_api::{locking::LockError, OutputLockStore, WalletRead};
 use zcash_client_backend::fees::{zip317::SingleOutputChangeStrategy, DustOutputPolicy};
-use zcash_client_backend::wallet::OvkPolicy;
+use zcash_client_backend::wallet::{LockOwner, OutputRef, OvkPolicy};
 use zcash_primitives::transaction::builder::BundlePadding;
 use zcash_primitives::transaction::fees::zip317::FeeRule as Zip317FeeRule;
-use zcash_protocol::{memo::MemoBytes, value::Zatoshis, ShieldedPool};
+use zcash_primitives::transaction::TxId;
+use zcash_protocol::{
+    consensus::BlockHeight, memo::MemoBytes, value::Zatoshis, PoolType, ShieldedPool,
+};
 
 use crate::account;
 use crate::error::{ErrorCode, Result, RuntimeError};
@@ -276,6 +280,14 @@ fn build_proposal(
         policy.untrusted,
         policy.allow_zero_conf_shielding,
     )?;
+    let (target, _) = db
+        .get_target_and_anchor_heights(confirmations.trusted())
+        .map_err(|error| build_err("targetHeight", error))?
+        .ok_or_else(|| RuntimeError::new(ErrorCode::NotSynced))?;
+    let target = BlockHeight::from(target);
+    if onekey_zcash_send_policy::expiry_height(¶ms, target).is_none() {
+        return Err(build_err("expiryHeight", "network upgrade is too close"));
+    }
 
     // Spend only the selected shielded pool, never transparent UTXOs.
     let spend_policy = {
@@ -292,7 +304,7 @@ fn build_proposal(
 
     let selector = GreedyInputSelector::::new();
     let change = SingleOutputChangeStrategy::<_, Db>::new(
-        Zip317FeeRule::standard(),
+        onekey_zcash_send_policy::fee_rule(¶ms, target),
         None,
         policy.change_pool(),
         DustOutputPolicy::default(),
@@ -342,8 +354,8 @@ pub fn quote(
 /// Builds an unsigned transfer PCZT for review. Returns `(pcztBytes, feeZat)`.
 ///
 /// Locks nothing, so an abandoned review leaves the notes spendable. Notes are
-/// held once `submit_signed_pczt` stores the signed transaction, until it is
-/// mined or expires.
+/// held from `submit_signed_pczt` until the transaction is mined or expires, or
+/// the node rejects it.
 pub fn create_pczt(
     db: &mut Db,
     account_uuid: &str,
@@ -360,6 +372,11 @@ pub fn create_pczt(
         .iter()
         .map(|step| u64::from(step.balance().fee_required()))
         .sum();
+    let expiry = onekey_zcash_send_policy::expiry_height(
+        ¶ms,
+        BlockHeight::from(proposal.min_target_height()),
+    )
+    .ok_or_else(|| build_err("expiryHeight", "network upgrade is too close"))?;
 
     // InputsErrT / ChangeErrT appear only in the Err branch and cannot be inferred.
     let pczt = create_pczt_from_proposal::<
@@ -375,7 +392,7 @@ pub fn create_pczt(
         account_id,
         OvkPolicy::Sender,
         &proposal,
-        None,
+        Some(expiry),
         policy.padding(),
     )
     .map_err(|e| build_err("createPczt", format!("{e:?}")))?;
@@ -724,17 +741,46 @@ pub fn prove_pczt_at_height(
     })
 }
 
-/// Spend tables and their spent-output columns, one per pool.
-const SPEND_TABLES: [(&str, &str); 4] = [
-    ("sapling_received_note_spends", "sapling_received_note_id"),
-    ("orchard_received_note_spends", "orchard_received_note_id"),
-    ("ironwood_received_note_spends", "ironwood_received_note_id"),
+/// Spend tables with their spent-output columns, and the spent outputs' tables,
+/// index columns and pools.
+const SPEND_TABLES: [(&str, &str, &str, &str, PoolType); 4] = [
+    (
+        "sapling_received_note_spends",
+        "sapling_received_note_id",
+        "sapling_received_notes",
+        "output_index",
+        PoolType::SAPLING,
+    ),
+    (
+        "orchard_received_note_spends",
+        "orchard_received_note_id",
+        "orchard_received_notes",
+        "action_index",
+        PoolType::ORCHARD,
+    ),
+    (
+        "ironwood_received_note_spends",
+        "ironwood_received_note_id",
+        "ironwood_received_notes",
+        "action_index",
+        PoolType::IRONWOOD,
+    ),
     (
         "transparent_received_output_spends",
         "transparent_received_output_id",
+        "transparent_received_outputs",
+        "output_index",
+        PoolType::TRANSPARENT,
     ),
 ];
 
+fn refuse_store(reason: &str) -> RuntimeError {
+    RuntimeError::with(
+        ErrorCode::TransactionBuildError,
+        json!({ "stage": "storeSignedPczt", "reason": reason }),
+    )
+}
+
 /// Refuses a just-stored transaction that does not spend from `account_uuid`,
 /// or that spends an output another stored transaction still holds (mined, or
 /// unmined and unexpired). Reviews lock nothing, so two can select the same notes.
@@ -744,12 +790,6 @@ fn assert_sole_spend(
     account_uuid: &str,
 ) -> Result<()> {
     let internal = crate::history::display_order_to_internal(txid)?;
-    let refuse = |reason: &str| {
-        RuntimeError::with(
-            ErrorCode::TransactionBuildError,
-            json!({ "stage": "storeSignedPczt", "reason": reason }),
-        )
-    };
     let spends_from_account: bool = ext
         .query_row(
             "SELECT EXISTS(
@@ -761,9 +801,9 @@ fn assert_sole_spend(
         )
         .map_err(|e| build_err("readStoredSpend", e))?;
     if !spends_from_account {
-        return Err(refuse("accountMismatch"));
+        return Err(refuse_store("accountMismatch"));
     }
-    for (table, output) in SPEND_TABLES {
+    for (table, output, ..) in SPEND_TABLES {
         let conflict: bool = ext
             .query_row(
                 &format!(
@@ -787,33 +827,177 @@ fn assert_sole_spend(
             )
             .map_err(|e| build_err("readConflictingSpends", e))?;
         if conflict {
-            return Err(refuse("inputsAlreadySpent"));
+            return Err(refuse_store("inputsAlreadySpent"));
         }
     }
     Ok(())
 }
 
-/// Stores the signed PCZT in the wallet; from now on this transaction holds its
-/// spent notes until it is mined or expires. Stored atomically with its checks:
-/// a refusal leaves the wallet unchanged.
-fn store_signed_pczt(
+/// Extracts the signed PCZT and stores it in the wallet; from then on the
+/// transaction holds its spent notes until it is mined or expires.
+fn extract_and_store(
+    wallet: &mut zcash_client_sqlite::WalletDb<
+        zcash_client_sqlite::SqlTransaction<'_>,
+        &zcash_protocol::consensus::Network,
+        &crate::clock::HostClock,
+        &mut rand_chacha::ChaCha20Rng,
+    >,
+    pczt: pczt::Pczt,
+    orchard_vk: &orchard::circuit::VerifyingKey,
+) -> Result {
+    extract_and_store_transaction_from_pczt::<_, zcash_client_sqlite::ReceivedNoteId>(
+        wallet,
+        pczt,
+        None,
+        Some(orchard_vk),
+    )
+    .map_err(|e| build_err("extractAndStore", format!("{e:?}")))
+}
+
+/// The wallet outputs a stored transaction spends.
+fn spent_outputs(
+    ext: &zcash_client_sqlite::ExtensionTransaction<'_>,
+    txid: &TxId,
+) -> Result> {
+    let mut outputs = Vec::new();
+    for (spends, spent, table, index, pool) in SPEND_TABLES {
+        let mut after = -1_i64;
+        while let Some((id, source, output_index)) = ext
+            .query_row(
+                &format!(
+                    "SELECT output.id, source.txid, output.{index}
+                     FROM {spends} spend
+                     JOIN {table} output ON output.id = spend.{spent}
+                     JOIN transactions source ON source.id_tx = output.transaction_id
+                     JOIN transactions own ON own.id_tx = spend.transaction_id
+                     WHERE own.txid = ?1 AND output.id > ?2
+                     ORDER BY output.id LIMIT 1"
+                ),
+                rusqlite::params![txid.as_ref(), after],
+                |row| Ok((row.get(0)?, row.get::<_, [u8; 32]>(1)?, row.get(2)?)),
+            )
+            .optional()
+            .map_err(|e| build_err("readSpentOutputs", e))?
+        {
+            outputs.push(OutputRef::new(TxId::from_bytes(source), pool, output_index));
+            after = id;
+        }
+    }
+    Ok(outputs)
+}
+
+/// A signed transaction that passed the store checks but is not stored.
+struct Staged {
+    txid: TxId,
+    raw: Vec,
+    inputs: Vec,
+    /// The transaction's expiry height, or the maximum if it never expires.
+    lock_expiry: BlockHeight,
+}
+
+/// Stores the signed PCZT with its checks in a transaction that is then rolled
+/// back, to learn what storing it would hold. Leaves the wallet unchanged.
+fn stage_signed_pczt(
     db: &mut Db,
     account_uuid: &str,
     pczt: pczt::Pczt,
     orchard_vk: &orchard::circuit::VerifyingKey,
-) -> Result {
+) -> Result {
+    // Only an error from the closure rolls the transaction back.
+    enum Rollback {
+        Staged(Staged),
+        Failed(RuntimeError),
+    }
+    impl From for Rollback {
+        fn from(error: rusqlite::Error) -> Self {
+            Rollback::Failed(error.into())
+        }
+    }
+    let rehearsal = db.transactionally_with_extension(
+        |wallet, ext| -> std::result::Result {
+            let staged = extract_and_store(wallet, pczt, orchard_vk).and_then(|txid| {
+                assert_sole_spend(ext, &txid.to_string(), account_uuid)?;
+                let (raw, expiry) = ext
+                    .query_row(
+                        "SELECT raw, expiry_height FROM transactions WHERE txid = ?1",
+                        [txid.as_ref()],
+                        |row| Ok((row.get(0)?, row.get::<_, Option>(1)?)),
+                    )
+                    .map_err(|e| build_err("readStaged", e))?;
+                Ok(Staged {
+                    txid,
+                    raw,
+                    inputs: spent_outputs(ext, &txid)?,
+                    lock_expiry: BlockHeight::from_u32(
+                        expiry.filter(|height| *height != 0).unwrap_or(u32::MAX),
+                    ),
+                })
+            });
+            Err(match staged {
+                Ok(staged) => Rollback::Staged(staged),
+                Err(error) => Rollback::Failed(error),
+            })
+        },
+    );
+    match rehearsal {
+        Ok(never) => match never {},
+        Err(Rollback::Staged(staged)) => Ok(staged),
+        Err(Rollback::Failed(error)) => Err(error),
+    }
+}
+
+/// Locks the inputs until the transaction's expiry height, as long as a stored
+/// spend would hold them, and records the submission, before any broadcast.
+fn hold_inputs(db: &mut Db, account_uuid: &str, staged: &Staged, pczt_bytes: &[u8]) -> Result<()> {
     db.transactionally_with_extension(|wallet, ext| {
-        let txid =
-            extract_and_store_transaction_from_pczt::<_, zcash_client_sqlite::ReceivedNoteId>(
-                wallet,
-                pczt,
-                None,
-                Some(orchard_vk),
+        wallet
+            .lock_outputs(
+                &staged.inputs,
+                LockOwner::new(*staged.txid.as_ref()),
+                staged.lock_expiry,
             )
-            .map_err(|e| build_err("extractAndStore", format!("{e:?}")))?
-            .to_string();
-        assert_sole_spend(ext, &txid, account_uuid)?;
-        Ok(txid)
+            .map_err(|error| match error {
+                LockError::LockFailure(_) => refuse_store("inputsAlreadySpent"),
+                error => build_err("lockInputs", error),
+            })?;
+        tx_state::put_submission(ext, &staged.txid.to_string(), account_uuid, pczt_bytes)
+    })
+}
+
+/// Stores a held submission; its spends take over from the input locks.
+fn store_submission(
+    db: &mut Db,
+    txid: &str,
+    pczt: pczt::Pczt,
+    orchard_vk: &orchard::circuit::VerifyingKey,
+) -> Result<()> {
+    db.transactionally_with_extension(|wallet, ext| {
+        extract_and_store(wallet, pczt, orchard_vk)?;
+        tx_state::delete_submission(ext, txid)
+    })
+}
+
+/// Releases a rejected submission's inputs. A copy an earlier submit stored still
+/// spends them until expiry, so its rejection is recorded instead.
+fn release_rejected(
+    db: &mut Db,
+    account_uuid: &str,
+    staged: &Staged,
+    error: &RuntimeError,
+) -> Result<()> {
+    let txid = staged.txid.to_string();
+    let owner = LockOwner::new(*staged.txid.as_ref());
+    db.transactionally_with_extension(|wallet, ext| {
+        for input in &staged.inputs {
+            wallet
+                .unlock_output(input, owner)
+                .map_err(|e| build_err("releaseInputs", e))?;
+        }
+        tx_state::delete_submission(ext, &txid)?;
+        if tx_state::is_stored(ext, &txid)? {
+            tx_state::insert_rejection(ext, &txid, account_uuid, error)?;
+        }
+        Ok(())
     })
 }
 
@@ -822,7 +1006,8 @@ pub enum SubmitOutcome {
     Accepted {
         txid: String,
     },
-    /// The trusted node rejected it; the stored transaction holds its notes until chain expiry.
+    /// The trusted node rejected it. It is not stored and its notes are spendable
+    /// again, unless an earlier submit stored it: then they return at its expiry.
     Rejected {
         txid: String,
         error: RuntimeError,
@@ -835,8 +1020,8 @@ pub enum SubmitOutcome {
     },
 }
 
-// Only a definitive rejection is recorded; a spent-input reply can refer to this
-// transaction itself.
+// Only a definitive rejection releases the notes; a spent-input reply can refer to
+// this transaction itself.
 fn first_submit_rejection(error: RuntimeError) -> std::result::Result {
     if error.code == ErrorCode::BroadcastRejected {
         Ok(error)
@@ -845,65 +1030,130 @@ fn first_submit_rejection(error: RuntimeError) -> std::result::Result,
-) -> SubmitOutcome {
-    match result {
-        Ok(()) => SubmitOutcome::Accepted { txid },
-        Err(error) => match first_submit_rejection(error) {
-            Ok(error) => match tx_state::record_rejection(db, &txid, account_uuid, &error) {
+) -> Result {
+    let txid = staged.txid.to_string();
+    let result = match result.map_err(first_submit_rejection) {
+        Err(Ok(error)) => {
+            return Ok(match release_rejected(db, account_uuid, &staged, &error) {
                 Ok(()) => SubmitOutcome::Rejected { txid, error },
+                // Still recorded: it is kept as a pending send.
                 Err(error) => SubmitOutcome::Unknown { txid, error },
-            },
-            Err(error) => SubmitOutcome::Unknown { txid, error },
-        },
+            });
+        }
+        Err(Err(error)) => Err(error),
+        Ok(()) => Ok(()),
+    };
+    if let Err(error) = store_submission(db, &txid, pczt, orchard_vk) {
+        let broadcast = if result.is_ok() {
+            "accepted"
+        } else {
+            "unknown"
+        };
+        return Err(RuntimeError::with(
+            ErrorCode::FinalizeOutcomeUnknown,
+            json!({ "txid": txid, "broadcast": broadcast }),
+        )
+        .detail(error));
+    }
+    Ok(match result {
+        Ok(()) => SubmitOutcome::Accepted { txid },
+        Err(error) => SubmitOutcome::Unknown { txid, error },
+    })
+}
+
+fn parse_pczt(bytes: &[u8]) -> Result {
+    pczt::Pczt::parse(bytes).map_err(|e| {
+        RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "parse" }))
+            .detail(format!("{e:?}"))
+    })
+}
+
+/// The Orchard verifying key for the transaction's own branch.
+fn verifying_key_for(
+    db: &Db,
+    pczt: &pczt::Pczt,
+) -> Result<&'static orchard::circuit::VerifyingKey> {
+    let chain_tip = db
+        .chain_height()
+        .map_err(|error| build_err("chainHeight", error))?
+        .ok_or_else(|| RuntimeError::new(ErrorCode::NotSynced))?;
+    Ok(crate::circuit_keys::verifying_key(
+        circuit_version_for_branch(db.params(), *pczt.global().consensus_branch_id(), chain_tip),
+    ))
+}
+
+/// Stores submissions whose outcome was never stored: the process stopped after
+/// holding their inputs, or storing failed after the broadcast. The node may have
+/// them, so each is kept as a pending send, like an unknown outcome.
+pub fn settle_interrupted_submissions(db: &mut Db) -> Result<()> {
+    while let Some((txid, pczt_bytes)) =
+        db.transactionally_with_extension(|_wallet, ext| tx_state::first_submission(ext))?
+    {
+        let pczt = parse_pczt(&pczt_bytes)?;
+        let orchard_vk = verifying_key_for(db, &pczt)?;
+        store_submission(db, &txid, pczt, orchard_vk)?;
     }
+    Ok(())
 }
 
-/// Persists the exact authorized transaction before broadcasting it.
+/// Holds the inputs and records the submission before broadcasting, then stores
+/// the transaction unless the node definitively rejected it.
 ///
-/// A transaction the node already rejected is not sent again.
+/// Storing is what makes the upstream wallet hold the notes until expiry, so a
+/// rejection must come first to release them at once. The record made before the
+/// broadcast keeps a lost outcome from looking like an unsent payment.
 pub async fn submit_signed_pczt(
     db: &mut Db,
     client: &mut crate::network::LightClient,
     account_uuid: &str,
     pczt_bytes: &[u8],
 ) -> Result {
-    let pczt = pczt::Pczt::parse(pczt_bytes).map_err(|e| {
-        RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "parse" }))
-            .detail(format!("{e:?}"))
-    })?;
-    let params = *db.params();
-    let chain_tip = db
-        .chain_height()
-        .map_err(|error| build_err("chainHeight", error))?
-        .ok_or_else(|| RuntimeError::new(ErrorCode::NotSynced))?;
-    let version =
-        circuit_version_for_branch(¶ms, *pczt.global().consensus_branch_id(), chain_tip);
-    let orchard_vk = crate::circuit_keys::verifying_key(version);
-
-    let txid = store_signed_pczt(db, account_uuid, pczt, orchard_vk)?;
-    if let Err(error) = tx_state::assert_not_rejected(db, &txid) {
-        return Ok(match error.code {
-            ErrorCode::BroadcastRejected => SubmitOutcome::Rejected { txid, error },
-            _ => SubmitOutcome::Unknown { txid, error },
-        });
+    submit_with(db, account_uuid, pczt_bytes, |raw| {
+        crate::network::broadcast(client, raw)
+    })
+    .await
+}
+
+pub(crate) async fn submit_with(
+    db: &mut Db,
+    account_uuid: &str,
+    pczt_bytes: &[u8],
+    broadcast: F,
+) -> Result
+where
+    F: FnOnce(Vec) -> Fut,
+    Fut: std::future::Future>,
+{
+    let pczt = parse_pczt(pczt_bytes)?;
+    settle_interrupted_submissions(db)?;
+    let orchard_vk = verifying_key_for(db, &pczt)?;
+    let mut staged = stage_signed_pczt(db, account_uuid, pczt.clone(), orchard_vk)?;
+    // A stored copy the node already rejected is not sent again.
+    if let Err(error) = tx_state::assert_not_rejected(db, &staged.txid.to_string()) {
+        if error.code == ErrorCode::BroadcastRejected {
+            let txid = staged.txid.to_string();
+            return Ok(SubmitOutcome::Rejected { txid, error });
+        }
+        return Err(error);
     }
-    let raw = match raw_transaction(db, &txid) {
-        Ok(raw) => raw,
-        Err(error) => return Ok(SubmitOutcome::Unknown { txid, error }),
-    };
-    let result = crate::network::broadcast(client, raw).await;
-    Ok(record_submit_outcome(db, account_uuid, txid, result))
+    hold_inputs(db, account_uuid, &staged, pczt_bytes)?;
+    // Each extraction draws a new binding signature: the stored bytes can differ
+    // from the broadcast ones, never the txid.
+    let result = broadcast(std::mem::take(&mut staged.raw)).await;
+    finish_submission(db, account_uuid, staged, pczt, orchard_vk, result)
 }
 
 /// Reads a stored transaction's raw bytes from the wallet for broadcast.
 pub fn raw_transaction(db: &Db, txid: &str) -> Result> {
-    use zcash_primitives::transaction::TxId;
-
     let bytes = hex::decode(txid)
         .ok()
         .filter(|b| b.len() == 32)
@@ -955,82 +1205,6 @@ mod submit_state_tests {
         )
     }
 
-    fn outcome_wallet(fail_write: bool) -> (Db, String) {
-        let conn = Connection::open_in_memory().unwrap();
-        conn.execute_batch(
-            "CREATE TABLE ext_onekey_tx_state (
-               txid BLOB PRIMARY KEY NOT NULL,
-               account_uuid BLOB NOT NULL,
-               rejection_code INTEGER,
-               rejection_reason TEXT
-             );",
-        )
-        .unwrap();
-        if fail_write {
-            conn.execute_batch(
-                "CREATE TRIGGER fail_state BEFORE INSERT ON ext_onekey_tx_state
-                 BEGIN SELECT RAISE(ABORT, 'synthetic write failure'); END;",
-            )
-            .unwrap();
-        }
-        (wallet(conn), "01".repeat(32))
-    }
-
-    #[test]
-    fn only_a_node_rejection_is_recorded() {
-        let (mut db, txid) = outcome_wallet(false);
-        let account = uuid::Uuid::nil().to_string();
-        assert!(matches!(
-            record_submit_outcome(&mut db, &account, txid.clone(), Ok(())),
-            SubmitOutcome::Accepted { .. }
-        ));
-        tx_state::assert_not_rejected(&mut db, &txid).unwrap();
-
-        let rejected = RuntimeError::new(ErrorCode::BroadcastRejected).detail("bad-txns-expired");
-        assert!(matches!(
-            record_submit_outcome(&mut db, &account, txid.clone(), Err(rejected)),
-            SubmitOutcome::Rejected { .. }
-        ));
-        assert_eq!(
-            tx_state::assert_not_rejected(&mut db, &txid)
-                .unwrap_err()
-                .code,
-            ErrorCode::BroadcastRejected
-        );
-    }
-
-    #[test]
-    fn duplicate_spend_or_network_failure_keeps_the_stored_send_pending() {
-        for code in [ErrorCode::BroadcastOutcomeUnknown, ErrorCode::NetworkError] {
-            let (mut db, txid) = outcome_wallet(false);
-            assert!(matches!(
-                record_submit_outcome(
-                    &mut db,
-                    &uuid::Uuid::nil().to_string(),
-                    txid.clone(),
-                    Err(RuntimeError::new(code))
-                ),
-                SubmitOutcome::Unknown { .. }
-            ));
-            tx_state::assert_not_rejected(&mut db, &txid).unwrap();
-        }
-    }
-
-    #[test]
-    fn a_rejection_that_cannot_be_recorded_stays_unknown() {
-        let (mut db, txid) = outcome_wallet(true);
-        let rejected = RuntimeError::new(ErrorCode::BroadcastRejected);
-        match record_submit_outcome(
-            &mut db,
-            &uuid::Uuid::nil().to_string(),
-            txid.clone(),
-            Err(rejected),
-        ) {
-            SubmitOutcome::Unknown { txid: retained, .. } => assert_eq!(retained, txid),
-            _ => panic!("an unrecorded rejection must not drop the stored transaction"),
-        }
-    }
-
     /// Transaction 1 is the one just stored; it spends orchard note 7.
     fn spend_fixture(other: Option<(Option, Option)>) -> Db {
         let conn = Connection::open_in_memory().unwrap();
@@ -1043,7 +1217,7 @@ mod submit_state_tests {
              CREATE TABLE v_transactions (txid BLOB, account_uuid BLOB, total_spent INTEGER);",
         )
         .unwrap();
-        for (table, output) in SPEND_TABLES {
+        for (table, output, ..) in SPEND_TABLES {
             conn.execute_batch(&format!(
                 "CREATE TABLE {table} ({output} INTEGER, transaction_id INTEGER);"
             ))
@@ -1079,6 +1253,93 @@ mod submit_state_tests {
         db.transactionally_with_extension(|_, ext| assert_sole_spend(ext, &txid, &account))
     }
 
+    fn lock_fixture(fail_delete: bool) -> (Db, Staged, String) {
+        let conn = Connection::open_in_memory().unwrap();
+        conn.execute_batch(
+            "CREATE TABLE transactions (id_tx INTEGER PRIMARY KEY, txid BLOB);
+             CREATE TABLE scan_queue (block_range_end INTEGER);
+             INSERT INTO scan_queue VALUES (1001);
+             CREATE TABLE orchard_received_notes (
+               transaction_id INTEGER, action_index INTEGER,
+               lock_owner BLOB, lock_expiry_height INTEGER
+             );
+             INSERT INTO orchard_received_notes VALUES (1, 0, NULL, NULL);
+             CREATE TABLE ext_onekey_submission (
+               txid BLOB PRIMARY KEY, account_uuid BLOB, pczt BLOB
+             );",
+        )
+        .unwrap();
+        conn.execute("INSERT INTO transactions VALUES (1, ?1)", [[9_u8; 32]])
+            .unwrap();
+        if fail_delete {
+            conn.execute_batch(
+                "CREATE TRIGGER fail_release BEFORE DELETE ON ext_onekey_submission
+                 BEGIN SELECT RAISE(ABORT, 'simulated storage failure'); END;",
+            )
+            .unwrap();
+        }
+        let staged = Staged {
+            txid: TxId::from_bytes([1; 32]),
+            raw: vec![],
+            inputs: vec![OutputRef::new(
+                TxId::from_bytes([9; 32]),
+                PoolType::ORCHARD,
+                0,
+            )],
+            lock_expiry: BlockHeight::from_u32(1040),
+        };
+        (wallet(conn), staged, uuid::Uuid::from_u128(1).to_string())
+    }
+
+    fn held_state(db: &mut Db) -> (Option>, bool) {
+        db.transactionally_with_extension(|_, ext| {
+            let owner =
+                ext.query_row("SELECT lock_owner FROM orchard_received_notes", [], |row| {
+                    row.get(0)
+                })?;
+            Ok::<_, RuntimeError>((owner, tx_state::first_submission(ext)?.is_some()))
+        })
+        .unwrap()
+    }
+
+    #[test]
+    fn definite_rejection_releases_the_input_and_durable_submission_together() {
+        let (mut db, staged, account) = lock_fixture(false);
+        hold_inputs(&mut db, &account, &staged, &[4, 5]).unwrap();
+        assert_eq!(held_state(&mut db), (Some(vec![1; 32]), true));
+        release_rejected(
+            &mut db,
+            &account,
+            &staged,
+            &RuntimeError::new(ErrorCode::BroadcastRejected),
+        )
+        .unwrap();
+        assert_eq!(held_state(&mut db), (None, false));
+    }
+
+    #[test]
+    fn failed_release_rolls_back_the_unlock_and_keeps_recovery_state() {
+        let (mut db, staged, account) = lock_fixture(true);
+        hold_inputs(&mut db, &account, &staged, &[4, 5]).unwrap();
+        assert!(release_rejected(
+            &mut db,
+            &account,
+            &staged,
+            &RuntimeError::new(ErrorCode::BroadcastRejected)
+        )
+        .is_err());
+        assert_eq!(held_state(&mut db), (Some(vec![1; 32]), true));
+    }
+
+    #[test]
+    fn a_second_submission_cannot_take_the_first_submissions_inputs() {
+        let (mut db, mut staged, account) = lock_fixture(false);
+        hold_inputs(&mut db, &account, &staged, &[4, 5]).unwrap();
+        staged.txid = TxId::from_bytes([2; 32]);
+        assert!(hold_inputs(&mut db, &account, &staged, &[6, 7]).is_err());
+        assert_eq!(held_state(&mut db), (Some(vec![1; 32]), true));
+    }
+
     #[test]
     fn a_spend_already_held_by_another_stored_transaction_is_refused() {
         check(&mut spend_fixture(None), 1).unwrap();
@@ -1603,7 +1864,8 @@ mod owned_output_tests {
             CREATE TABLE orchard_received_note_spends (orchard_received_note_id INTEGER, transaction_id INTEGER);
             CREATE TABLE ironwood_received_notes (id INTEGER, nf BLOB);
             CREATE TABLE ironwood_received_note_spends (ironwood_received_note_id INTEGER, transaction_id INTEGER);
-            CREATE TABLE ext_onekey_tx_state (txid BLOB, account_uuid BLOB, rejection_code INTEGER, rejection_reason TEXT);")
+            CREATE TABLE ext_onekey_tx_state (txid BLOB, account_uuid BLOB, rejection_code INTEGER, rejection_reason TEXT);
+            CREATE TABLE ext_onekey_submission (txid BLOB, account_uuid BLOB, pczt BLOB);")
             .unwrap();
         conn.execute(
             "INSERT INTO transactions VALUES (1, ?1, x'00', NULL, 3500040)",
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
index b8ad03491..e7115b570 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
@@ -1,9 +1,12 @@
-//! OneKey-owned record of node rejections.
+//! OneKey-owned send state: node rejections and submissions awaiting their outcome.
 //!
 //! The wallet schema cannot hold that the trusted node definitively rejected a
-//! send; that must stop any resend and show the send as failed. An unmined send
-//! that was not rejected stays pending until mined or expired; the host does not
-//! resubmit it.
+//! stored send; that must stop any resend and show the send as failed. An unmined
+//! send that was not rejected stays pending until mined or expired; the host does
+//! not resubmit it.
+//!
+//! A submission is recorded before its broadcast and removed once the outcome is
+//! stored, so a broadcast whose outcome was lost is still found and kept.
 
 use std::collections::HashSet;
 
@@ -21,10 +24,16 @@ use crate::wallet::Db;
 
 const LIFECYCLE_MIGRATION_ID: Uuid = Uuid::from_u128(0x5be0af90_63f4_43ea_ae65_8207c84e46dd);
 const REJECTIONS_MIGRATION_ID: Uuid = Uuid::from_u128(0x0d3b6f2e_9a41_4c8e_b7d5_3e1f6a2c9b70);
+const SUBMISSIONS_MIGRATION_ID: Uuid = Uuid::from_u128(0xe82d3b63_186f_4b69_b602_0a7e289c5914);
 pub(crate) const TABLE: &str = "ext_onekey_tx_state";
+const SUBMISSIONS: &str = "ext_onekey_submission";
 
 pub fn migrations() -> Vec>> {
-    vec![Box::new(LifecycleMigration), Box::new(RejectionsMigration)]
+    vec![
+        Box::new(LifecycleMigration),
+        Box::new(RejectionsMigration),
+        Box::new(SubmissionsMigration),
+    ]
 }
 
 /// The original lifecycle table, kept so databases that applied it keep a
@@ -119,6 +128,42 @@ impl RusqliteMigration for RejectionsMigration {
     }
 }
 
+/// Signed sends whose inputs are locked for a broadcast whose outcome is not stored yet.
+struct SubmissionsMigration;
+
+impl schemerz::Migration for SubmissionsMigration {
+    fn id(&self) -> Uuid {
+        SUBMISSIONS_MIGRATION_ID
+    }
+
+    fn dependencies(&self) -> HashSet {
+        HashSet::from([REJECTIONS_MIGRATION_ID])
+    }
+
+    fn description(&self) -> &'static str {
+        "Adds OneKey Zcash submissions awaiting their broadcast outcome."
+    }
+}
+
+impl RusqliteMigration for SubmissionsMigration {
+    type Error = WalletMigrationError;
+
+    fn up(&self, transaction: &rusqlite::Transaction) -> std::result::Result<(), Self::Error> {
+        transaction.execute_batch(
+            "CREATE TABLE ext_onekey_submission (
+               txid BLOB PRIMARY KEY NOT NULL,
+               account_uuid BLOB NOT NULL,
+               pczt BLOB NOT NULL
+             );",
+        )?;
+        Ok(())
+    }
+
+    fn down(&self, _transaction: &rusqlite::Transaction) -> std::result::Result<(), Self::Error> {
+        Err(WalletMigrationError::CannotRevert(SUBMISSIONS_MIGRATION_ID))
+    }
+}
+
 fn db_err(operation: &'static str, error: impl std::fmt::Display) -> RuntimeError {
     RuntimeError::with(
         ErrorCode::DatabaseError,
@@ -152,6 +197,17 @@ pub fn record_rejection(
     txid: &str,
     account_uuid: &str,
     error: &RuntimeError,
+) -> Result<()> {
+    db.transactionally_with_extension(|_wallet, ext| {
+        insert_rejection(ext, txid, account_uuid, error)
+    })
+}
+
+pub(crate) fn insert_rejection(
+    ext: &ExtensionTransaction<'_>,
+    txid: &str,
+    account_uuid: &str,
+    error: &RuntimeError,
 ) -> Result<()> {
     let txid = display_order_to_internal(txid)?;
     let account_uuid = uuid_blob(account_uuid)?;
@@ -159,21 +215,74 @@ pub fn record_rejection(
         .params
         .get("errorCode")
         .and_then(serde_json::Value::as_i64);
-    db.transactionally_with_extension(|_wallet, ext| {
-        ext.execute(
-            &format!(
-                "INSERT INTO {TABLE} (txid, account_uuid, rejection_code, rejection_reason)
-                 VALUES (?1, ?2, ?3, ?4)
-                 ON CONFLICT(txid) DO UPDATE SET
-                   account_uuid = excluded.account_uuid,
-                   rejection_code = excluded.rejection_code,
-                   rejection_reason = excluded.rejection_reason"
-            ),
-            params![txid, account_uuid, rejection_code, error.detail.as_deref()],
-        )
-        .map_err(|error| db_err("recordRejection", error))?;
-        Ok(())
-    })
+    ext.execute(
+        &format!(
+            "INSERT INTO {TABLE} (txid, account_uuid, rejection_code, rejection_reason)
+             VALUES (?1, ?2, ?3, ?4)
+             ON CONFLICT(txid) DO UPDATE SET
+               account_uuid = excluded.account_uuid,
+               rejection_code = excluded.rejection_code,
+               rejection_reason = excluded.rejection_reason"
+        ),
+        params![txid, account_uuid, rejection_code, error.detail.as_deref()],
+    )
+    .map_err(|error| db_err("recordRejection", error))?;
+    Ok(())
+}
+
+/// Whether the wallet already stores this transaction, e.g. from an earlier submit.
+pub(crate) fn is_stored(ext: &ExtensionTransaction<'_>, txid: &str) -> Result {
+    let txid = display_order_to_internal(txid)?;
+    ext.query_row(
+        "SELECT EXISTS(SELECT 1 FROM transactions WHERE txid = ?1)",
+        [txid],
+        |row| row.get(0),
+    )
+    .map_err(|error| db_err("readStoredTransaction", error))
+}
+
+pub(crate) fn put_submission(
+    ext: &ExtensionTransaction<'_>,
+    txid: &str,
+    account_uuid: &str,
+    pczt: &[u8],
+) -> Result<()> {
+    let txid = display_order_to_internal(txid)?;
+    let account_uuid = uuid_blob(account_uuid)?;
+    ext.execute(
+        &format!(
+            "INSERT INTO {SUBMISSIONS} (txid, account_uuid, pczt) VALUES (?1, ?2, ?3)
+             ON CONFLICT(txid) DO UPDATE SET
+               account_uuid = excluded.account_uuid,
+               pczt = excluded.pczt"
+        ),
+        params![txid, account_uuid, pczt],
+    )
+    .map_err(|error| db_err("recordSubmission", error))?;
+    Ok(())
+}
+
+pub(crate) fn delete_submission(ext: &ExtensionTransaction<'_>, txid: &str) -> Result<()> {
+    let txid = display_order_to_internal(txid)?;
+    ext.execute(
+        &format!("DELETE FROM {SUBMISSIONS} WHERE txid = ?1"),
+        [txid],
+    )
+    .map_err(|error| db_err("deleteSubmission", error))?;
+    Ok(())
+}
+
+/// A submission whose outcome was never stored, as `(txid, pczt)`.
+pub(crate) fn first_submission(
+    ext: &ExtensionTransaction<'_>,
+) -> Result)>> {
+    ext.query_row(
+        &format!("SELECT txid, pczt FROM {SUBMISSIONS} ORDER BY txid LIMIT 1"),
+        [],
+        |row| Ok((hex_display_order(&row.get::<_, Vec>(0)?), row.get(1)?)),
+    )
+    .optional()
+    .map_err(|error| db_err("readSubmission", error))
 }
 
 /// Fails with the recorded `BroadcastRejected` if the node already rejected this transaction.
@@ -233,13 +342,19 @@ pub fn pending_txids(conn: &rusqlite::Connection, account_uuid: &str) -> Result<
     .collect()
 }
 
-/// Drops rejections whose transaction left the wallet with a removed account.
+/// Drops rejections whose transaction left the wallet with a removed account, and
+/// that account's submissions (its notes and their locks went with it).
 pub fn prune_orphaned_rows(ext: &ExtensionTransaction<'_>) -> Result<()> {
     ext.execute(
         &format!("DELETE FROM {TABLE} WHERE txid NOT IN (SELECT txid FROM transactions)"),
         [],
     )
     .map_err(|error| db_err("pruneTransactionState", error))?;
+    ext.execute(
+        &format!("DELETE FROM {SUBMISSIONS} WHERE account_uuid NOT IN (SELECT uuid FROM accounts)"),
+        [],
+    )
+    .map_err(|error| db_err("pruneSubmissions", error))?;
     Ok(())
 }
 

From d63d74e94ee8b0e2f2f7023606160dc35b081016 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 15:43:09 +0800
Subject: [PATCH 92/97] fix: refuse a Zcash lightwalletd endpoint on another
 chain and bound each sync step

---
 .../zcash/crates/zcash-runtime/src/bindgen.rs |  4 ++
 .../zcash/crates/zcash-runtime/src/error.rs   |  6 ++
 .../zcash/crates/zcash-runtime/src/network.rs | 57 ++++++++++++++++-
 .../zcash/crates/zcash-runtime/src/runtime.rs | 42 +++++++++++--
 .../zcash/crates/zcash-runtime/src/sync.rs    | 63 ++++++++++++++++---
 5 files changed, 158 insertions(+), 14 deletions(-)

diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
index 891e50ff4..001f57afc 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
@@ -98,6 +98,8 @@ pub fn close_wallet() -> Result<(), JsValue> {
 /// Configures the lightwalletd endpoint, e.g. `https://host:port`.
 ///
 /// The endpoint must support gRPC-web. CORS is required only without a host transport.
+/// Its chain is checked against the open wallet before the first call that uses both;
+/// a mismatch throws `NODE_NETWORK_MISMATCH`.
 #[wasm_bindgen(js_name = setLightwalletdUrl)]
 pub fn set_lightwalletd_url(base_url: &str) -> Result<(), JsValue> {
     runtime::set_client(network::connect(base_url)?);
@@ -316,6 +318,8 @@ pub fn transaction_outputs(account_uuid: String, txid: String) -> Result "NOT_SYNCED",
             InsufficientFunds => "INSUFFICIENT_FUNDS",
             NetworkError => "NETWORK_ERROR",
+            NodeNetworkMismatch => "NODE_NETWORK_MISMATCH",
             DatabaseError => "DATABASE_ERROR",
             DatabaseTooNew => "DATABASE_TOO_NEW",
             ReorgDetected => "REORG_DETECTED",
@@ -288,6 +293,7 @@ mod tests {
             NotSynced,
             InsufficientFunds,
             NetworkError,
+            NodeNetworkMismatch,
             DatabaseError,
             DatabaseTooNew,
             InvalidTxid,
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
index 58c064221..6291f246e 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
@@ -4,8 +4,9 @@
 //! end, so streaming calls like `get_block_range` never complete.
 
 use zcash_client_backend::proto::service::{
-    compact_tx_streamer_client::CompactTxStreamerClient, BlockId, ChainSpec, TreeState,
+    compact_tx_streamer_client::CompactTxStreamerClient, BlockId, ChainSpec, Empty, TreeState,
 };
+use zcash_protocol::consensus::Network;
 
 use crate::error::{ErrorCode, Result, RuntimeError};
 use serde_json::json;
@@ -148,6 +149,38 @@ pub async fn chain_tip(client: &mut LightClient) -> Result {
     })
 }
 
+/// The chain an endpoint serves: `LightdInfo.chainName` ("main", "test" or "regtest").
+pub async fn chain_name(client: &mut LightClient) -> Result {
+    let info = with_timeout(
+        async {
+            client
+                .get_lightd_info(Empty {})
+                .await
+                .map(|response| response.into_inner())
+                .map_err(|e| net_err("getLightdInfo", e))
+        },
+        DEFAULT_TIMEOUT_MS,
+        "getLightdInfo",
+    )
+    .await?;
+    Ok(info.chain_name)
+}
+
+/// Refuses an endpoint on another chain: its tree roots and tip would corrupt the wallet.
+pub fn check_chain_name(chain_name: &str, wallet: &Network) -> Result<()> {
+    let wallet_name = match wallet {
+        Network::MainNetwork => "main",
+        Network::TestNetwork => "test",
+    };
+    if chain_name == wallet_name {
+        return Ok(());
+    }
+    Err(RuntimeError::with(
+        ErrorCode::NodeNetworkMismatch,
+        json!({ "nodeNetwork": chain_name, "walletNetwork": wallet_name }),
+    ))
+}
+
 /// Submit a signed transaction to lightwalletd.
 ///
 /// Node rejections arrive as `SendResponse.error_code != 0`, not a gRPC status.
@@ -290,10 +323,30 @@ pub async fn tree_state(client: &mut LightClient, height: u32) -> Result = const { Cell::new(0) };
+
+    // Chain name reported per client generation: one GetLightdInfo per endpoint,
+    // compared with whichever wallet is open.
+    static CLIENT_CHAIN: RefCell> = const { RefCell::new(None) };
 }
 
 /// Compared against the value sampled before taking the client; a mismatch means
@@ -36,6 +42,27 @@ fn put_client_back(client: LightClient, sampled: u64) {
     }
 }
 
+/// Refuses an endpoint on another chain before an operation stores what it returns.
+async fn check_client_chain(
+    client: &mut LightClient,
+    sampled: u64,
+    wallet: &Network,
+) -> Result<()> {
+    let known = CLIENT_CHAIN.with(|c| match &*c.borrow() {
+        Some((generation, chain)) if *generation == sampled => Some(chain.clone()),
+        _ => None,
+    });
+    let chain = match known {
+        Some(chain) => chain,
+        None => {
+            let chain = crate::network::chain_name(client).await?;
+            CLIENT_CHAIN.with(|c| *c.borrow_mut() = Some((sampled, chain.clone())));
+            chain
+        }
+    };
+    crate::network::check_chain_name(&chain, wallet)
+}
+
 /// Refuses wallet-switching calls while an async operation is running.
 fn assert_idle(operation: &str) -> Result<()> {
     if BUSY.with(Cell::get) {
@@ -147,7 +174,8 @@ pub fn with_db(f: impl FnOnce(&mut Db) -> Result) -> Result {
     out
 }
 
-/// Lends the database and client for an async operation (sync, account import).
+/// Lends the database and client for an async operation (sync, account import), after
+/// checking that the endpoint serves the wallet's chain.
 pub async fn with_db_and_client(f: F) -> Result
 where
     F: FnOnce(Db, LightClient) -> Fut,
@@ -157,7 +185,7 @@ where
     let guard = BusyGuard::acquire("walletOperation")?;
     let client_gen = client_generation();
     let db = DB.with(|c| c.borrow_mut().take()).ok_or_else(not_open)?;
-    let client = match CLIENT.with(|c| c.borrow_mut().take()) {
+    let mut client = match CLIENT.with(|c| c.borrow_mut().take()) {
         Some(c) => c,
         None => {
             DB.with(|cell| *cell.borrow_mut() = Some(db));
@@ -165,7 +193,11 @@ where
         }
     };
 
-    let (db, client, out) = f(db, client).await;
+    let checked = check_client_chain(&mut client, client_gen, db.params()).await;
+    let (db, client, out) = match checked {
+        Ok(()) => f(db, client).await,
+        Err(e) => (db, client, Err(e)),
+    };
 
     // If the wallet was switched or closed meanwhile, drop this one rather than
     // overwrite the current wallet with a stale one.
diff --git a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
index 9b46b33c5..8fa3a2b2c 100644
--- a/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
@@ -352,6 +352,29 @@ pub async fn tip(db: &mut Db, client: &mut LightClient) -> Result {
     Ok(json!({ "chainTip": tip }).to_string())
 }
 
+/// Per-call cap on `batch_size × max_batches`: a hang guard, as a call cannot be interrupted.
+pub const MAX_BLOCKS_PER_CALL: u64 = 1_000;
+
+fn check_step_size(batch_size: u32, max_batches: u32) -> Result<()> {
+    let blocks = u64::from(batch_size) * u64::from(max_batches);
+    if blocks == 0 || blocks > MAX_BLOCKS_PER_CALL {
+        return Err(RuntimeError::with(
+            ErrorCode::InvalidBatchSize,
+            json!({
+                "batchSize": batch_size,
+                "maxBatches": max_batches,
+                "maxBlocksPerCall": MAX_BLOCKS_PER_CALL,
+            }),
+        ));
+    }
+    Ok(())
+}
+
+/// Exclusive end of a batch of `len` blocks from `start`, within `range_end`.
+fn batch_end(start: BlockHeight, len: u32, range_end: BlockHeight) -> BlockHeight {
+    BlockHeight::from_u32(u32::from(start).saturating_add(len)).min(range_end)
+}
+
 /// Bounded progress: at most `max_batches` batches of `batch_size` blocks.
 ///
 /// Returns progress JSON; `done` means no ranges remain. Never loops to full sync;
@@ -364,12 +387,7 @@ pub async fn step(
     preferred: Option,
     active_ufvks: &[String],
 ) -> Result {
-    if batch_size == 0 || max_batches == 0 {
-        return Err(RuntimeError::with(
-            ErrorCode::InvalidBatchSize,
-            json!({ "batchSize": batch_size, "maxBatches": max_batches }),
-        ));
-    }
+    check_step_size(batch_size, max_batches)?;
 
     let params = *db.params();
     let wallet_ufvks = db
@@ -444,7 +462,7 @@ pub async fn step(
         let mut attempt_len: u32 = initial_len;
         let mut same_size_retry = 1u32;
         let (batch, batch_len) = loop {
-            let attempt_end = std::cmp::min(start + attempt_len, range.block_range().end);
+            let attempt_end = batch_end(start, attempt_len, range.block_range().end);
             let candidate = ScanRange::from_parts(start..attempt_end, range.priority());
             // download_batch times out on stalls; only real failures reach here.
             match download_batch(client, &cache, &candidate).await {
@@ -1132,6 +1150,37 @@ mod tests {
         .to_unified_full_viewing_key()
     }
 
+    #[test]
+    fn step_size_is_bounded_per_call() {
+        for (batch_size, max_batches) in [(50, 1), (500, 1), (1_000, 1), (1, 1_000), (500, 2)] {
+            check_step_size(batch_size, max_batches).expect("within the per-call cap");
+        }
+        for (batch_size, max_batches) in [
+            (0, 1),
+            (1, 0),
+            (1_001, 1),
+            (501, 2),
+            (u32::MAX, 1),
+            (1, u32::MAX),
+            (u32::MAX, u32::MAX),
+        ] {
+            let error = check_step_size(batch_size, max_batches).expect_err("rejected");
+            assert_eq!(error.code, ErrorCode::InvalidBatchSize);
+            assert_eq!(error.params["batchSize"], batch_size);
+            assert_eq!(error.params["maxBatches"], max_batches);
+            assert_eq!(error.params["maxBlocksPerCall"], MAX_BLOCKS_PER_CALL);
+        }
+    }
+
+    #[test]
+    fn batch_end_stays_within_the_range_near_the_height_limit() {
+        let h = BlockHeight::from_u32;
+        assert_eq!(batch_end(h(100), 50, h(1_000)), h(150));
+        assert_eq!(batch_end(h(100), 50, h(120)), h(120));
+        assert_eq!(batch_end(h(u32::MAX - 10), 1_000, h(u32::MAX)), h(u32::MAX));
+        assert_eq!(batch_end(h(u32::MAX), u32::MAX, h(u32::MAX)), h(u32::MAX));
+    }
+
     #[test]
     fn only_a_contiguous_prefix_of_the_range_is_accepted() {
         assert!(check_block_sequence(10, 13, [10u64, 11, 12].into_iter()).is_ok());

From fdf75e06e87079586a00ecac29d857a8fb8e9b5b Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 15:43:10 +0800
Subject: [PATCH 93/97] fix: report a Monero chain tip with the network of the
 node that served it

---
 .../crates/monero-runtime/src/bindgen.rs      |  7 +-
 .../crates/monero-runtime/src/runtime.rs      | 72 +++++++++++++++++--
 2 files changed, 71 insertions(+), 8 deletions(-)

diff --git a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
index 51f42eb06..74d01c65b 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -64,16 +64,17 @@ pub async fn set_node_url(url: &str) -> std::result::Result<(), JsValue> {
 /// Fetch the chain tip. Does not require an open wallet DB (account creation needs the birthday first).
 ///
 /// Returns `{ height, network }`; the host must check `network` matches the wallet being created.
+/// `network` is that of the node that reported `height`.
 #[wasm_bindgen(js_name = chainTip)]
 pub async fn chain_tip() -> std::result::Result {
-    let tip: u64 = runtime::with_daemon(|daemon| async move {
-        let r = sync::chain_tip(&daemon).await;
+    let (tip, network) = runtime::with_daemon(|daemon, network| async move {
+        let r = sync::chain_tip(&daemon).await.map(|tip| (tip, network));
         (daemon, r)
     })
     .await?;
     json(serde_json::json!({
         "height": tip,
-        "network": runtime::daemon_network().map(crate::keys::network_name),
+        "network": network.map(crate::keys::network_name),
     }))
 }
 
diff --git a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
index 42d0f32fa..bef00ea9b 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
@@ -223,19 +223,21 @@ where
     out
 }
 
-/// Borrows only the node client; **no wallet needs to be open**.
+/// Borrows only the node client, with its network; **no wallet needs to be open**.
 ///
 /// Account creation needs the chain tip for the birthday before the database exists.
+/// The network is read with the client, so a node switch during the call cannot pair
+/// one node's answer with another node's network.
 pub async fn with_daemon(f: F) -> Result
 where
-    F: FnOnce(Daemon) -> Fut,
+    F: FnOnce(Daemon, Option) -> Fut,
     Fut: std::future::Future)>,
 {
     let daemon_gen = daemon_generation();
     let daemon = DAEMON
         .with(|c| c.borrow_mut().take())
         .ok_or_else(no_daemon)?;
-    let (daemon, result) = f(daemon).await;
+    let (daemon, result) = f(daemon, daemon_network()).await;
     put_daemon_back(daemon, daemon_gen);
     result
 }
@@ -332,8 +334,24 @@ mod tests {
             .block_on(f)
     }
 
+    const MAINNET_GENESIS: &str =
+        "418015bb9ae982a1975da7d79277c2705727a56894ba0fb246adaabb1f4632e3";
+    const TESTNET_GENESIS: &str =
+        "48ca7cd3c8de5b6a4d53d2861fbdaedca141553559f9be9520068053cda8430b";
+
     /// Minimal mainnet node: every JSON-RPC call gets the genesis hash, after `delay`.
     fn fake_node(delay: std::time::Duration) -> String {
+        fake_node_with(MAINNET_GENESIS, delay, 1, delay)
+    }
+
+    /// Minimal node: JSON-RPC calls get `genesis` after `delay`; `get_height`
+    /// reports `height` after `height_delay`.
+    fn fake_node_with(
+        genesis: &'static str,
+        delay: std::time::Duration,
+        height: u64,
+        height_delay: std::time::Duration,
+    ) -> String {
         use std::io::{Read, Write};
         let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
         let url = format!("http://{}", listener.local_addr().unwrap());
@@ -368,8 +386,13 @@ mod tests {
                         Ok(n) => request.extend_from_slice(&buf[..n]),
                     }
                 }
-                std::thread::sleep(delay);
-                let body = r#"{"jsonrpc":"2.0","id":0,"result":"418015bb9ae982a1975da7d79277c2705727a56894ba0fb246adaabb1f4632e3"}"#;
+                let body = if request.starts_with(b"POST /get_height") {
+                    std::thread::sleep(height_delay);
+                    format!(r#"{{"height":{height},"status":"OK"}}"#)
+                } else {
+                    std::thread::sleep(delay);
+                    format!(r#"{{"jsonrpc":"2.0","id":0,"result":"{genesis}"}}"#)
+                };
                 let _ = write!(
                     stream,
                     "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
@@ -400,6 +423,45 @@ mod tests {
         assert!(DAEMON.with(|c| c.borrow().is_some()));
     }
 
+    /// A tip keeps the network of the node that reported it, even when another node
+    /// is selected before it arrives.
+    #[test]
+    fn a_chain_tip_keeps_the_network_of_the_node_that_reported_it() {
+        let slow_mainnet = fake_node_with(
+            MAINNET_GENESIS,
+            std::time::Duration::ZERO,
+            3_000_001,
+            std::time::Duration::from_millis(400),
+        );
+        let testnet = fake_node_with(
+            TESTNET_GENESIS,
+            std::time::Duration::ZERO,
+            1_500_001,
+            std::time::Duration::ZERO,
+        );
+        block_on(async {
+            select_node(&slow_mainnet).await.expect("connect mainnet");
+            let tip = with_daemon(|daemon, network| async move {
+                let r = crate::sync::chain_tip(&daemon)
+                    .await
+                    .map(|tip| (tip, network));
+                (daemon, r)
+            });
+            let switch = async {
+                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+                select_node(&testnet).await
+            };
+            let (tip, switched) = tokio::join!(tip, switch);
+            switched.expect("connect testnet");
+            assert_eq!(
+                daemon_network(),
+                Some(Network::Testnet),
+                "switch finished first"
+            );
+            assert_eq!(tip.expect("tip"), (3_000_000, Some(Network::Mainnet)));
+        });
+    }
+
     /// Disabling the node while a connect is pending keeps it disabled.
     #[test]
     fn clearing_the_node_cancels_a_pending_selection() {

From 7c39250e36b468c2ec18924ca307bb50c521e7fe Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 15:43:10 +0800
Subject: [PATCH 94/97] fix: drop queued Monero scan ranges above a lowered
 chain tip

---
 .../monero/crates/monero-runtime/src/sync.rs  | 92 +++++++++++++++++--
 1 file changed, 84 insertions(+), 8 deletions(-)

diff --git a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
index ab86a7c5b..4f2abf66a 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
@@ -36,6 +36,7 @@ pub async fn chain_tip(daemon: &Daemon) -> Result {
 /// Tell an identity the chain tip and queue the range it still needs to scan.
 ///
 /// A new identity queues `[birthday, tip]`; one with progress queues `(scanned_to, tip]`.
+/// A lower tip (a node that is behind) drops queued heights above it.
 pub fn update_chain_tip(db: &mut Db, identity_id: i64, tip: u64) -> Result<()> {
     let identity = db.identity_by_id(identity_id)?;
     let scanned_to = scanned_to_height(db, identity_id)?;
@@ -43,18 +44,42 @@ pub fn update_chain_tip(db: &mut Db, identity_id: i64, tip: u64) -> Result<()> {
         .map(|h| h + 1)
         .unwrap_or(identity.birthday_height);
 
-    if start > tip {
-        return Ok(()); // Already at the tip; nothing to queue
-    }
-
-    db.conn()
-        .execute(
+    let tx = db
+        .conn_mut()
+        .transaction()
+        .map_err(|e| db_err("beginUpdateChainTip", e))?;
+    trim_ranges_above(&tx, identity_id, tip)?;
+    if start <= tip {
+        tx.execute(
             "INSERT INTO scan_ranges (identity_id, start_height, end_height)
              VALUES (?1, ?2, ?3)
              ON CONFLICT (identity_id, start_height) DO UPDATE SET end_height = max(end_height, ?3)",
-            params![identity_id, start as i64, (tip + 1) as i64],
+            params![identity_id, start as i64, end_after(tip)],
         )
         .map_err(|e| db_err("updateChainTip", e))?;
+    }
+    tx.commit().map_err(|e| db_err("commitUpdateChainTip", e))
+}
+
+/// Exclusive `end_height` of a range through `tip`.
+fn end_after(tip: u64) -> i64 {
+    i64::try_from(tip.saturating_add(1)).unwrap_or(i64::MAX)
+}
+
+/// Drop queued heights above `tip`; a node at that tip cannot serve them, and
+/// `update_chain_tip` queues them again once the tip passes them.
+fn trim_ranges_above(conn: &rusqlite::Connection, identity_id: i64, tip: u64) -> Result<()> {
+    let end = end_after(tip);
+    conn.execute(
+        "DELETE FROM scan_ranges WHERE identity_id = ?1 AND start_height >= ?2",
+        params![identity_id, end],
+    )
+    .map_err(|e| db_err("trimScanRanges", e))?;
+    conn.execute(
+        "UPDATE scan_ranges SET end_height = ?2 WHERE identity_id = ?1 AND end_height > ?2",
+        params![identity_id, end],
+    )
+    .map_err(|e| db_err("trimScanRanges", e))?;
     Ok(())
 }
 
@@ -492,13 +517,14 @@ pub fn rewind_and_requeue(db: &mut Db, identity_id: i64, height: u64, tip: u64)
         params![identity_id, (height + 1) as i64],
     )
     .map_err(|e| db_err("rewindBirthday", e))?;
+    trim_ranges_above(&tx, identity_id, tip)?;
     // Requeue the rewound span here instead of relying on the host to call `update_chain_tip`.
     if tip > height {
         tx.execute(
                 "INSERT INTO scan_ranges (identity_id, start_height, end_height)
                  VALUES (?1, ?2, ?3)
                  ON CONFLICT (identity_id, start_height) DO UPDATE SET end_height = max(end_height, ?3)",
-                params![identity_id, (height + 1) as i64, (tip + 1) as i64],
+                params![identity_id, (height + 1) as i64, end_after(tip)],
             )
             .map_err(|e| db_err("requeueAfterRewind", e))?;
     }
@@ -661,6 +687,56 @@ mod tests {
         assert_eq!((start, end), (181, 201));
     }
 
+    fn queued(db: &Db, id: i64) -> Vec<(i64, i64)> {
+        db.conn()
+            .prepare("SELECT start_height, end_height FROM scan_ranges WHERE identity_id = ?1 ORDER BY start_height")
+            .unwrap()
+            .query_map([id], |r| Ok((r.get(0)?, r.get(1)?)))
+            .unwrap()
+            .collect::>()
+            .unwrap()
+    }
+
+    /// A reorg can lower the tip: nothing above it stays queued, and scanning
+    /// resumes from the rewound height once the tip grows again.
+    #[test]
+    fn rewinding_to_a_lower_tip_drops_queued_heights_above_it() {
+        let (mut db, id) = db_with_identity(); // birthday 100
+        update_chain_tip(&mut db, id, 200).unwrap();
+        consume_range(&mut db, id, 100, 175).unwrap();
+        advance_scanned_to(&db, id, 175).unwrap();
+        assert_eq!(queued(&db, id), vec![(176, 201)]);
+
+        rewind_and_requeue(&mut db, id, 170, 180).unwrap();
+        assert_eq!(queued(&db, id), vec![(171, 181), (176, 181)]);
+
+        update_chain_tip(&mut db, id, 220).unwrap();
+        assert_eq!(queued(&db, id), vec![(171, 221), (176, 181)]);
+        consume_range(&mut db, id, 171, 220).unwrap();
+        advance_scanned_to(&db, id, 220).unwrap();
+        assert!(next_range(&db, id).unwrap().is_none());
+        assert_eq!(scanned_to_height(&db, id).unwrap(), Some(220));
+    }
+
+    /// A node that is behind cannot serve heights above its tip.
+    #[test]
+    fn a_node_that_is_behind_leaves_nothing_queued_above_its_tip() {
+        let (mut db, id) = db_with_identity(); // birthday 100
+        update_chain_tip(&mut db, id, 200).unwrap();
+        update_chain_tip(&mut db, id, 180).unwrap();
+        assert_eq!(queued(&db, id), vec![(100, 181)]);
+
+        update_chain_tip(&mut db, id, 200).unwrap();
+        consume_range(&mut db, id, 100, 190).unwrap();
+        advance_scanned_to(&db, id, 190).unwrap();
+        // Progress is already past the lower tip.
+        update_chain_tip(&mut db, id, 180).unwrap();
+        assert!(queued(&db, id).is_empty());
+
+        update_chain_tip(&mut db, id, 220).unwrap();
+        assert_eq!(queued(&db, id), vec![(191, 221)]);
+    }
+
     #[test]
     fn a_failed_rewind_cursor_write_keeps_the_scan_data_intact() {
         let (mut db, id) = db_with_identity();

From b18d54a0c1786d52ab24a3cb1c052032f892c9b9 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 15:43:10 +0800
Subject: [PATCH 95/97] fix: saturate the Monero confirmation count at the
 largest chain tip

---
 .../monero/crates/monero-runtime/src/query.rs | 20 ++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)

diff --git a/chain-runtimes/monero/crates/monero-runtime/src/query.rs b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
index b963e5078..9aa69bcfb 100644
--- a/chain-runtimes/monero/crates/monero-runtime/src/query.rs
+++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
@@ -101,7 +101,8 @@ pub fn balance(db: &Db, identity_id: i64, chain_tip: Option) -> Result 0 {
                     b.confirming_blocks_left = b.confirming_blocks_left.max(Some(left));
                 }
@@ -667,6 +668,23 @@ mod tests {
         assert_eq!(spendable_rows(&db, id, 1_100).unwrap().len(), 1);
     }
 
+    /// A still-locked output must not overflow the confirmation count at the largest tip.
+    #[test]
+    fn the_largest_chain_tip_does_not_overflow_the_confirmation_count() {
+        let (db, id) = db_with_identity();
+        add_output(&db, id, 100, 1_000, true);
+        let timestamp_locked = add_output(&db, id, 800, 1_001, true);
+        db.conn()
+            .execute(
+                "UPDATE outputs SET additional_timelock = ?1 WHERE id = ?2",
+                params![500_000_000i64, timestamp_locked],
+            )
+            .unwrap();
+        let b = balance(&db, id, Some(u64::MAX)).unwrap();
+        assert_eq!(b.unlocked_atomic, 100);
+        assert_eq!(b.confirming_blocks_left, None);
+    }
+
     #[test]
     fn unknown_chain_tip_means_nothing_is_spendable() {
         let (db, id) = db_with_identity();

From a162994806b8addab2878d6bf72fbf56507b116a Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 15:46:11 +0800
Subject: [PATCH 96/97] chore: bump the Monero runtime to 0.1.0-alpha.12

---
 chain-runtimes/monero/Cargo.lock | 2 +-
 chain-runtimes/monero/Cargo.toml | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/chain-runtimes/monero/Cargo.lock b/chain-runtimes/monero/Cargo.lock
index 67e9eee07..4e94374c1 100644
--- a/chain-runtimes/monero/Cargo.lock
+++ b/chain-runtimes/monero/Cargo.lock
@@ -1259,7 +1259,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
 
 [[package]]
 name = "onekey-monero-runtime"
-version = "0.1.0-alpha.11"
+version = "0.1.0-alpha.12"
 dependencies = [
  "curve25519-dalek",
  "futures-lite",
diff --git a/chain-runtimes/monero/Cargo.toml b/chain-runtimes/monero/Cargo.toml
index c0c920cec..0a896b9e4 100644
--- a/chain-runtimes/monero/Cargo.toml
+++ b/chain-runtimes/monero/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/monero-runtime"]
 exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
 
 [workspace.package]
-version = "0.1.0-alpha.11"
+version = "0.1.0-alpha.12"
 edition = "2021"
 license = "Apache-2.0"
 rust-version = "1.85"

From daf733d5aa63db8afff613e397018a5a6fdb64b7 Mon Sep 17 00:00:00 2001
From: ByteZhang 
Date: Wed, 28 Oct 2026 21:05:00 +0800
Subject: [PATCH 97/97] chore: publish the runtimes as @onekeyfe/zcash-runtime,
 @onekeyfe/zcash-keys and @onekeyfe/monero-runtime

---
 .../workflows/publish-runtime-packages.yml    | 11 ++++----
 chain-runtimes/monero/README.md               |  2 +-
 chain-runtimes/monero/scripts/ci.sh           |  2 +-
 .../monero/scripts/package-release.py         | 17 ++++++++----
 chain-runtimes/zcash/README.md                |  8 +++---
 chain-runtimes/zcash/scripts/ci.sh            |  4 +--
 .../zcash/scripts/package-release.py          | 27 ++++++++++++-------
 .../zcash/scripts/test_package_release.py     | 17 +++++++-----
 8 files changed, 54 insertions(+), 34 deletions(-)

diff --git a/.github/workflows/publish-runtime-packages.yml b/.github/workflows/publish-runtime-packages.yml
index b76055706..63a5f6688 100644
--- a/.github/workflows/publish-runtime-packages.yml
+++ b/.github/workflows/publish-runtime-packages.yml
@@ -67,8 +67,9 @@ jobs:
         env:
           NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
         run: |
-          # The only packages this workflow publishes, as /.
-          packages='zcash/onekey-zcash-keys zcash/onekey-zcash-runtime monero/onekey-monero-runtime'
+          # The only packages this workflow publishes, as /;
+          # each is published as @onekeyfe/.
+          packages='zcash/zcash-keys zcash/zcash-runtime monero/monero-runtime'
           # main publishes x.y.z or x.y.z-
.n; other branches only x.y.z-alpha.n.
           versions='^[0-9]+\.[0-9]+\.[0-9]+(-[a-z]+\.[0-9]+)?$'
           if [ "$GITHUB_REF" != refs/heads/main ]; then
@@ -78,8 +79,8 @@ jobs:
 
           # Check every package before publishing any.
           for pkg in $packages; do
-            if [ "$(field "$pkg" name)" != "$(basename "$pkg")" ]; then
-              echo "::error::dist/$pkg.tgz is missing or is not $(basename "$pkg")"
+            if [ "$(field "$pkg" name)" != "@onekeyfe/$(basename "$pkg")" ]; then
+              echo "::error::dist/$pkg.tgz is missing or is not @onekeyfe/$(basename "$pkg")"
               exit 1
             fi
             if [[ ! "$(field "$pkg" version)" =~ $versions ]]; then
@@ -89,7 +90,7 @@ jobs:
           done
 
           for pkg in $packages; do
-            name=$(basename "$pkg")
+            name="@onekeyfe/$(basename "$pkg")"
             version=$(field "$pkg" version)
             if [ -n "$(npm view "$name@$version" version 2>/dev/null)" ]; then
               echo "$name@$version already published"
diff --git a/chain-runtimes/monero/README.md b/chain-runtimes/monero/README.md
index b1715da91..b94a0a5ec 100644
--- a/chain-runtimes/monero/README.md
+++ b/chain-runtimes/monero/README.md
@@ -1,6 +1,6 @@
 # OneKey Monero Runtime
 
-Wallet state layer over monero-oxide, published as `onekey-monero-runtime`.
+Wallet state layer over monero-oxide, published as `@onekeyfe/monero-runtime`.
 monero-oxide provides cryptography, scanning and transaction construction; this
 crate adds the storage it lacks: SQLite with incremental, transactional writes.
 
diff --git a/chain-runtimes/monero/scripts/ci.sh b/chain-runtimes/monero/scripts/ci.sh
index ab0d1d094..c015dd0fa 100644
--- a/chain-runtimes/monero/scripts/ci.sh
+++ b/chain-runtimes/monero/scripts/ci.sh
@@ -13,4 +13,4 @@ bash scripts/build-wasm.sh release
 python3 scripts/package-release.py --version "$VERSION" --tag "$TAG"
 
 # Fixed file names for the publish workflow.
-mv "dist/onekey-monero-runtime-$VERSION.tgz" dist/onekey-monero-runtime.tgz
+mv "dist/onekeyfe-monero-runtime-$VERSION.tgz" dist/monero-runtime.tgz
diff --git a/chain-runtimes/monero/scripts/package-release.py b/chain-runtimes/monero/scripts/package-release.py
index df01d8019..b25fdc7d6 100644
--- a/chain-runtimes/monero/scripts/package-release.py
+++ b/chain-runtimes/monero/scripts/package-release.py
@@ -13,7 +13,9 @@
 from pathlib import Path
 
 ROOT = Path(__file__).resolve().parents[1]
-NAME = "onekey-monero-runtime"
+# wasm-bindgen module name, and the npm package name apps install.
+MODULE = "onekey_monero_runtime"
+NAME = "@onekeyfe/monero-runtime"
 
 
 def workspace_version(root=ROOT):
@@ -34,10 +36,12 @@ def prepare(root=ROOT):
     pkg = root / "pkg"
     path = pkg / "package.json"
     package = json.loads(path.read_text())
-    if package["name"] != NAME or package["version"] != workspace_version(root):
+    # wasm-pack names the package after the crate.
+    crate = MODULE.replace("_", "-")
+    if package["name"] != crate or package["version"] != workspace_version(root):
         raise ValueError("Rebuild the wasm package: pkg version mismatch")
-    module = NAME.replace("-", "_")
-    package["files"] = [f"{module}.js", f"{module}.d.ts", f"{module}_bg.wasm", "LICENSE"]
+    package["name"] = NAME
+    package["files"] = [f"{MODULE}.js", f"{MODULE}.d.ts", f"{MODULE}_bg.wasm", "LICENSE"]
     if (pkg / "snippets").exists():
         package["files"].append("snippets")
     package["repository"] = {
@@ -45,6 +49,8 @@ def prepare(root=ROOT):
         "url": "git+https://github.com/OneKeyHQ/app-modules.git",
         "directory": "chain-runtimes/monero/crates/monero-runtime",
     }
+    # A scoped package is private unless published public.
+    package["publishConfig"] = {"access": "public", "registry": "https://registry.npmjs.org/"}
     path.write_text(json.dumps(package, indent=2) + "\n")
     shutil.copyfile(root / "LICENSE", pkg / "LICENSE")
 
@@ -61,7 +67,8 @@ def main():
     subprocess.run(
         ["npm", "pack", "--pack-destination", str(dist)], cwd=ROOT / "pkg", check=True
     )
-    archive = dist / f"{NAME}-{args.version}.tgz"
+    # npm pack names @scope/pkg archives scope-pkg-.tgz.
+    archive = dist / f"{NAME.removeprefix('@').replace('/', '-')}-{args.version}.tgz"
     if not archive.exists():
         raise SystemExit(f"missing {archive}")
     print(archive)
diff --git a/chain-runtimes/zcash/README.md b/chain-runtimes/zcash/README.md
index 3bb8c1312..ac0ffff5a 100644
--- a/chain-runtimes/zcash/README.md
+++ b/chain-runtimes/zcash/README.md
@@ -3,9 +3,9 @@
 Thin wasm bindings over the official `librustzcash`, with `zcash_client_sqlite` as
 the wallet store. Two packages built from one source, used on every App platform:
 
-- `onekey-zcash-keys`: derivation, review checks and signing. No SQLite, network,
+- `@onekeyfe/zcash-keys`: derivation, review checks and signing. No SQLite, network,
   scanner or prover.
-- `onekey-zcash-runtime`: wallet, scanning, SQLite and PCZT proving.
+- `@onekeyfe/zcash-runtime`: wallet, scanning, SQLite and PCZT proving.
 
 Both run inside a DedicatedWorker. Native Rust builds are for tests and diagnostics
 only.
@@ -46,7 +46,7 @@ pins the exact version.
 Failures throw an `Error` with a stable `code`, structured `params`, and a log-only
 `detail`. `capabilities()` / `keysCapabilities()` report what the build supports.
 
-### `onekey-zcash-runtime`
+### `@onekeyfe/zcash-runtime`
 
 ```
 init() / storageRequiresWorkerRestart()
@@ -76,7 +76,7 @@ pcztExtractStateless(pczt)
 capabilities() / dependencyVersions()
 ```
 
-### `onekey-zcash-keys`
+### `@onekeyfe/zcash-keys`
 
 ```
 ufvkFromAccountKeys(network, orchardSk, accountXpub, accountIndex)
diff --git a/chain-runtimes/zcash/scripts/ci.sh b/chain-runtimes/zcash/scripts/ci.sh
index 829a333bc..66c5902e8 100644
--- a/chain-runtimes/zcash/scripts/ci.sh
+++ b/chain-runtimes/zcash/scripts/ci.sh
@@ -14,5 +14,5 @@ bash scripts/build-wasm.sh --offline
 python3 scripts/package-release.py pack --version "$VERSION" --tag "$TAG" --revision "$(git rev-parse HEAD)"
 
 # Fixed file names for the publish workflow.
-mv "dist/onekey-zcash-keys-$VERSION.tgz" dist/onekey-zcash-keys.tgz
-mv "dist/onekey-zcash-runtime-$VERSION.tgz" dist/onekey-zcash-runtime.tgz
+mv "dist/onekeyfe-zcash-keys-$VERSION.tgz" dist/zcash-keys.tgz
+mv "dist/onekeyfe-zcash-runtime-$VERSION.tgz" dist/zcash-runtime.tgz
diff --git a/chain-runtimes/zcash/scripts/package-release.py b/chain-runtimes/zcash/scripts/package-release.py
index a7edab4ba..685ea3730 100644
--- a/chain-runtimes/zcash/scripts/package-release.py
+++ b/chain-runtimes/zcash/scripts/package-release.py
@@ -13,7 +13,16 @@
 
 
 ROOT = Path(__file__).resolve().parent.parent
-PACKAGES = {"pkg": "onekey-zcash-runtime", "pkg-keys": "onekey-zcash-keys"}
+# Build directory -> (wasm-bindgen module name, npm package name).
+PACKAGES = {
+    "pkg": ("onekey_zcash_runtime", "@onekeyfe/zcash-runtime"),
+    "pkg-keys": ("onekey_zcash_keys", "@onekeyfe/zcash-keys"),
+}
+
+
+def archive_name(name, release_version):
+    # npm pack names @scope/pkg archives scope-pkg-.tgz.
+    return f"{name.removeprefix('@').replace('/', '-')}-{release_version}.tgz"
 
 
 def version(root):
@@ -31,13 +40,14 @@ def check_version(value, expected, tag):
 
 def prepare(root):
     release_version = version(root)
-    for directory, name in PACKAGES.items():
+    for directory, (module, name) in PACKAGES.items():
         target = root / directory
         path = target / "package.json"
         package = json.loads(path.read_text())
-        if package["name"] != name or package["version"] != release_version:
+        # wasm-pack names the package after the crate.
+        if package["name"] != module.replace("_", "-") or package["version"] != release_version:
             raise ValueError(f"Rebuild both WASM packages: {directory} version mismatch")
-        module = name.replace("-", "_")
+        package["name"] = name
         package["files"] = [f"{module}.js", f"{module}.d.ts", f"{module}_bg.wasm", "LICENSE"]
         if (target / "snippets").exists():
             package["files"].append("snippets")
@@ -50,7 +60,7 @@ def prepare(root):
         path.write_text(json.dumps(package, indent=2) + "\n")
 
 
-def verify_tarball(archive, source, name, release_version):
+def verify_tarball(archive, source, module, name, release_version):
     with tarfile.open(archive, "r:gz") as tar:
         files = {}
         for member in tar.getmembers():
@@ -64,7 +74,6 @@ def verify_tarball(archive, source, name, release_version):
         if package["name"] != name or package["version"] != release_version:
             raise ValueError("Packed package identity mismatch")
         required = {"package.json", "LICENSE"}
-        module = name.replace("-", "_")
         required.update({f"{module}.js", f"{module}.d.ts", f"{module}_bg.wasm"})
         required.update(p.relative_to(source).as_posix() for p in (source / "snippets").rglob("*")
                         if p.is_file() and p.name != ".gitignore")
@@ -83,14 +92,14 @@ def pack(root, expected, tag, revision, allow_dirty=False):
     artifact.verify(root, revision, allow_dirty)
     output = root / "dist"
     output.mkdir(exist_ok=True)
-    for directory, name in PACKAGES.items():
+    for directory, (module, name) in PACKAGES.items():
         result = subprocess.check_output([
             "npm", "pack", "--ignore-scripts", "--json", "--pack-destination", str(output.resolve()),
         ], cwd=root / directory, text=True)
         filename = json.loads(result)[0]["filename"]
-        if filename != f"{name}-{expected}.tgz":
+        if filename != archive_name(name, expected):
             raise ValueError("Unexpected npm archive filename")
-        verify_tarball(output / filename, root / directory, name, expected)
+        verify_tarball(output / filename, root / directory, module, name, expected)
         print(f"Verified {filename}")
     shutil.copyfile(root / "zcash-wasm-manifest.json", output / "zcash-wasm-manifest.json")
 
diff --git a/chain-runtimes/zcash/scripts/test_package_release.py b/chain-runtimes/zcash/scripts/test_package_release.py
index 704bddeea..c7af5e341 100644
--- a/chain-runtimes/zcash/scripts/test_package_release.py
+++ b/chain-runtimes/zcash/scripts/test_package_release.py
@@ -18,15 +18,19 @@ def test_prepare_writes_metadata_and_rejects_mixed_versions(self):
             root = Path(directory)
             (root / "Cargo.toml").write_text('[workspace.package]\nversion = "0.1.0-rc.1"\n')
             (root / "LICENSE").write_text("license")
-            for package, name in release.PACKAGES.items():
+            for package, (module, _name) in release.PACKAGES.items():
                 target = root / package
                 target.mkdir()
-                (target / "package.json").write_text(json.dumps({"name": name, "version": "0.1.0-rc.1"}))
+                crate = module.replace("_", "-")
+                (target / "package.json").write_text(json.dumps({"name": crate, "version": "0.1.0-rc.1"}))
             release.prepare(root)
             package = json.loads((root / "pkg/package.json").read_text())
+            self.assertEqual(package["name"], "@onekeyfe/zcash-runtime")
             self.assertEqual(package["files"], [
                 "onekey_zcash_runtime.js", "onekey_zcash_runtime.d.ts", "onekey_zcash_runtime_bg.wasm", "LICENSE",
             ])
+            self.assertEqual(json.loads((root / "pkg-keys/package.json").read_text())["name"],
+                             "@onekeyfe/zcash-keys")
             self.assertEqual((root / "pkg-keys/LICENSE").read_text(), "license")
             (root / "pkg-keys/package.json").write_text(
                 json.dumps({"name": "onekey-zcash-keys", "version": "0.0.1"}))
@@ -46,8 +50,7 @@ def test_prereleases_cannot_update_latest(self):
     def test_missing_snippets_and_changed_bytes_are_rejected(self):
         with tempfile.TemporaryDirectory() as directory:
             root = Path(directory)
-            name = "onekey-zcash-runtime"
-            module = name.replace("-", "_")
+            module, name = release.PACKAGES["pkg"]
             files = {
                 "package.json": json.dumps({"name": name, "version": "0.1.0-rc.1"}).encode(),
                 "LICENSE": b"license",
@@ -70,13 +73,13 @@ def pack(contents):
                         tar.addfile(member, io.BytesIO(data))
 
             pack(files)
-            release.verify_tarball(archive, root, name, "0.1.0-rc.1")
+            release.verify_tarball(archive, root, module, name, "0.1.0-rc.1")
             pack({k: v for k, v in files.items() if not k.startswith("snippets/")})
             with self.assertRaisesRegex(ValueError, "incomplete"):
-                release.verify_tarball(archive, root, name, "0.1.0-rc.1")
+                release.verify_tarball(archive, root, module, name, "0.1.0-rc.1")
             pack({**files, f"{module}.js": b"changed"})
             with self.assertRaisesRegex(ValueError, "differs"):
-                release.verify_tarball(archive, root, name, "0.1.0-rc.1")
+                release.verify_tarball(archive, root, module, name, "0.1.0-rc.1")
 
 
 if __name__ == "__main__":