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/.github/workflows/runtime-checks.yml b/.github/workflows/runtime-checks.yml
new file mode 100644
index 000000000..19bab5328
--- /dev/null
+++ b/.github/workflows/runtime-checks.yml
@@ -0,0 +1,51 @@
+name: runtime-checks
+
+# Runs each runtime's scripts/ci.sh on pull requests; mirrors the build tools of publish-runtime-packages.yml.
+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
diff --git a/README.md b/README.md
index d19af9bc1..e65d14766 100644
--- a/README.md
+++ b/README.md
@@ -75,3 +75,8 @@ 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 (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
new file mode 100644
index 000000000..8c5907478
--- /dev/null
+++ b/chain-runtimes/README.md
@@ -0,0 +1,19 @@
+# Chain runtimes
+
+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)
+- [Monero](./monero/README.md)
+
+Root shortcuts for Zcash (the direct commands in its README need no Node install):
+
+```sh
+yarn zcash:prepare
+yarn zcash:test
+yarn zcash:build
+```
+
+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/.cargo/config.toml b/chain-runtimes/monero/.cargo/config.toml
new file mode 100644
index 000000000..07d9ba901
--- /dev/null
+++ b/chain-runtimes/monero/.cargo/config.toml
@@ -0,0 +1,5 @@
+# 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/.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/Cargo.lock b/chain-runtimes/monero/Cargo.lock
new file mode 100644
index 000000000..4e94374c1
--- /dev/null
+++ b/chain-runtimes/monero/Cargo.lock
@@ -0,0 +1,2419 @@
+# 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.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a"
+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.1.0-alpha.12"
+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"
+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.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 = "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 = "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..0a896b9e4
--- /dev/null
+++ b/chain-runtimes/monero/Cargo.toml
@@ -0,0 +1,48 @@
+[workspace]
+resolver = "2"
+members = ["crates/monero-runtime"]
+exclude = ["vendor/sqlite-wasm-vfs-0.2.0"]
+
+[workspace.package]
+version = "0.1.0-alpha.12"
+edition = "2021"
+license = "Apache-2.0"
+rust-version = "1.85"
+
+# 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"] }
+monero-daemon-rpc = { version = "0.2", default-features = false, features = ["std"] }
+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 }
+
+# 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
+# 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"
+thiserror = "2"
+hex = "0.4"
+rand_core = { version = "0.6", features = ["getrandom"] }
+# 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"] }
+
+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"] }
+# 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 needs a Tokio reactor, so native integration tests need a runtime.
+tokio = { version = "1", features = ["rt", "macros", "time"] }
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/README.md b/chain-runtimes/monero/README.md
new file mode 100644
index 000000000..b94a0a5ec
--- /dev/null
+++ b/chain-runtimes/monero/README.md
@@ -0,0 +1,62 @@
+# 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.
+
+## 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/ (prepares vendor first)
+./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: 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). On macOS, install `llvm-ar` (`brew install llvm`); `/usr/bin/ar` cannot
+read wasm objects.
+
+## Release
+
+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.
+
+## API
+
+Values cross the boundary as strings, numbers, booleans, bytes or JSON strings.
+Errors carry a stable `code` and structured `params`.
+
+```
+init() / dependencyVersions()
+storageRequiresWorkerRestart()
+openWallet(dbName, network) / closeWallet() / deleteWallet(dbName)
+setNodeUrl(url) / setRequestHandler(handler)
+chainTip()
+
+deriveAccount(network, bip32PrivateKeyHex)
+deriveSubaddress(network, spendPub, viewPriv, major, minor)
+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)
+balance(accountId, chainTip?) / history(accountId, limit, offset)
+transactionDetails(accountId, txid)
+
+prepareTransaction(accountId, recipientsJson, maxSend, chainTip, priority)
+verifyTransaction(signableHex, reviewJson)
+verifySignedTransaction(signableHex, reviewJson, rawHex)
+signTransactionWithBip32Key(signableHex, bip32PrivateKeyHex, reviewJson)
+broadcastTransaction(accountId, rawHex, chainTip, outgoingAtomic?, changeAtomic?, signableHex, reviewJson)
+diagDatabase()
+```
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..8af5f0602
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/Cargo.toml
@@ -0,0 +1,52 @@
+[package]
+name = "onekey-monero-runtime"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+description = "OneKey Monero Runtime: wallet state over monero-oxide, persisted in 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
+
+# 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
+# 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
+
+[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
+# 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
new file mode 100644
index 000000000..655b863b1
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/build.rs
@@ -0,0 +1,59 @@
+//! Links the wasm SQLite build.
+//!
+//! 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};
+
+fn main() {
+    println!("cargo::rerun-if-changed=build.rs");
+
+    let target = std::env::var("TARGET").unwrap_or_default();
+    if !target.starts_with("wasm32") {
+        // Native targets use system or bundled SQLite.
+        return;
+    }
+
+    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 {
+        // Warn instead of panicking so a later link error has context.
+        println!(
+            "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=failed to copy {}: {e}", src.display());
+        return;
+    }
+
+    println!("cargo::rustc-link-search=native={}", out_dir.display());
+    println!("cargo::rerun-if-changed={}", src.display());
+}
+
+/// 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 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 };
+        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..74d01c65b
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/bindgen.rs
@@ -0,0 +1,603 @@
+//! Host-facing wasm interface.
+//!
+//! 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::*;
+
+use crate::error::{ErrorCode, Result, RuntimeError};
+use zeroize::Zeroizing;
+
+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())
+}
+
+/// 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(())
+}
+
+/// 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 {
+    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)?;
+    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(())
+}
+
+/// 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, 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 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, 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": network.map(crate::keys::network_name),
+    }))
+}
+
+/// Register an identity (view key pair).
+///
+/// `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: 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_with_rescan(
+            uuid,
+            &spend,
+            &view,
+            birthday_height,
+            force_rescan.unwrap_or(false),
+        )?;
+        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 }))
+}
+
+/// 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| {
+        let removed = db.remove_identity(uuid)?;
+        db.reclaim_storage(storage::RECLAIM_PAGES_AFTER_DELETE);
+        Ok(removed)
+    })?;
+    json(serde_json::json!({ "removed": removed }))
+}
+
+/// Delete the whole wallet DB file (app reset, storage rebuild). Irreversible.
+///
+/// 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()) {
+        runtime::close()?;
+    }
+    let deleted = storage::delete_database(&db_name).await?;
+    json(serde_json::json!({ "deleted": deleted }))
+}
+
+/// Register a subaddress and return its address. Funds to unregistered subaddresses go undetected.
+#[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 }))
+}
+
+/// Tell an identity the chain tip and queue its pending scan ranges.
+#[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)
+}
+
+/// One bounded step: scan at most `maxBlocks` blocks and return progress.
+#[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;
+        if r.is_ok() {
+            db.reclaim_storage(storage::RECLAIM_PAGES_PER_STEP);
+        }
+        (db, daemon, r)
+    })
+    .await?;
+    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| {
+        let v = sync::rewind_and_requeue(db, account_id, height, tip)?;
+        db.reclaim_storage(storage::RECLAIM_PAGES_AFTER_DELETE);
+        Ok(v)
+    })?;
+    json(v)
+}
+
+/// 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))?;
+    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)
+}
+
+/// Import key images so spend detection works.
+///
+/// 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,
+    bip32_private_key_hex: String,
+) -> std::result::Result {
+    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!({
+        "imported": result.imported,
+        "spendsFound": result.spends_found,
+    }))
+}
+
+/// 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)`,
+/// `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(
+    network: &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 = 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,
+        "spendPublicKeyHex": hex::encode(derived.spend_public_key),
+        "viewPrivateKeyHex": hex::encode(derived.view_private_key),
+    }))
+}
+
+/// 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: 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 = 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 }))
+}
+
+/// Check that a recipient address is valid and belongs to this network.
+#[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))
+}
+
+/// Hand network requests to the host instead of `fetch`ing in wasm.
+///
+/// `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);
+}
+
+/// 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| {
+        let mut counts = serde_json::Map::new();
+        for table in [
+            "identities",
+            "subaddresses",
+            "outputs",
+            "transactions",
+            "blocks",
+            "scan_ranges",
+            "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); the physical footprint can differ.
+        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" }),
+        )
+    })
+}
+
+/// [`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)
+}
+
+/// 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 spendable total minus fee.
+///
+/// Returns `{ signableHex, feeAtomic, amountAtomic, changeAtomic, inputsAtomic,
+/// 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,
+    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(
+            &db,
+            &daemon,
+            account_id,
+            &recipients
+                .iter()
+                .map(|r| (r.address.as_str(), r.amount_atomic.as_str()))
+                .collect::>(),
+            max_send,
+            chain_tip,
+            fee_priority,
+        )
+        .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 = device_sign::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,
+        )
+        .await;
+        (db, daemon, r)
+    })
+    .await?;
+
+    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
+/// 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,
+    bip32_private_key_hex: String,
+    review_json: &str,
+) -> std::result::Result {
+    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,
+        review_json,
+    )?)
+}
+
+/// 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_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,
+    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
+/// 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,
+    raw_hex: &str,
+    chain_tip: u64,
+    outgoing_atomic: Option,
+    change_atomic: Option,
+    signable_hex: Option,
+    review_json: Option,
+) -> std::result::Result {
+    let raw = raw_hex.to_owned();
+    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 = 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?;
+    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,
+    #[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..dff338aef
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/blocks_bin.rs
@@ -0,0 +1,614 @@
+//! Batch block fetch via `get_blocks.bin`, using wallet2's trust model.
+//!
+//! 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`.
+//!
+//! Request format and parser skeleton follow monero-oxide's `monero-daemon-rpc` (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;
+
+/// 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),
+}
+
+fn protocol(detail: impl Into) -> BlocksBinError {
+    BlocksBinError::Protocol(detail.into())
+}
+
+fn epee_err(e: EpeeError) -> BlocksBinError {
+    protocol(format!("epee: {e:?}"))
+}
+
+// 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;
+/// 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)
+}
+
+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)));
+}
+
+// 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.
+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,
+    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 {
+        // 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;
+        (result, now_ms() - started)
+    })
+}
+
+/// 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),
+        _ => None,
+    })
+}
+
+/// 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 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) {
+    #[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;
+}
+
+/// Fetch up to `limit` blocks from `start`, ordered by height. `start` must be
+/// nonzero: monerod ignores `start_height` when it is zero.
+///
+/// Sends one request (retried smaller on failure) and accepts however many blocks
+/// 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"));
+    }
+    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),
+        }
+    }
+}
+
+/// Send the request from `start` now, sized by the current batch (at most `limit`),
+/// and keep the result for the next step.
+///
+/// Polls once to send the request without a thread; the next step awaits it.
+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;
+    // A completed future must not be polled again; keep its result separately.
+    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,
+        });
+    });
+}
+
+/// 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,
+    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);
+    // 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");
+    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());
+
+    // 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());
+
+    request
+}
+
+/// One block: the block and its pruned non-miner transactions.
+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` is deliberately ignored; see the module docs.
+                        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`: block -> transaction (miner first) -> global index of each output.
+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()
+            )));
+        }
+
+        // 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((
+            !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::*;
+
+    #[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);
+        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()));
+    }
+
+    #[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, "steady at medium speed");
+        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(),
+            "taking clears the slot"
+        );
+
+        park("https://a", 100, 20);
+        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"
+        );
+    }
+
+    #[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(_)));
+    }
+
+    /// 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");
+        let blocks = parse_response(bytes, 3_768_621).expect("parse real response");
+        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());
+            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());
+        }
+        // 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())
+                    .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)
+            );
+        }
+    }
+
+    /// 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]
+    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!("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("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("scan");
+        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/device_key_images.rs b/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs
new file mode 100644
index 000000000..399377cfb
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/device_key_images.rs
@@ -0,0 +1,621 @@
+//! 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 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.map(hex::encode),
+            "internalOutputIndex": index,
+            "subAddrMajor": major,
+            "subAddrMinor": minor,
+        }));
+    }
+    Ok(json!({ "items": items }))
+}
+
+/// 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(
+                "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()))
+}
+
+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
+            .subaddress(db.network(), index)
+            .spend()
+            .into(),
+        None => identity.view_pair.spend().into(),
+    }
+}
+
+/// Whether `Hs(8·a·R || index)·G + spend` is the output key.
+pub(crate) 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 }),
+    )
+}
+
+/// 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 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);
+    }
+
+    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/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/error.rs b/chain-runtimes/monero/crates/monero-runtime/src/error.rs
new file mode 100644
index 000000000..bf74f89f4
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/error.rs
@@ -0,0 +1,247 @@
+//! Error codes: a stable contract across the wasm boundary.
+//!
+//! 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 {
+    /// Network name is not mainnet/stagenet/testnet. Params: `{ value }`
+    InvalidNetwork,
+    /// Address does not parse or belongs to another network. Params: `{ field }`
+    InvalidAddress,
+    /// Key/seed has the wrong byte length. Params: `{ byteLen, expected }`
+    InvalidKeyMaterial,
+    /// Invalid subaddress index (major and minor cannot both be 0; that is the primary address).
+    InvalidSubaddressIndex,
+    /// Invalid height range (from > to, or to is past the chain tip). Params: `{ from, to }`
+    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,
+    /// An async operation is in flight; wallet-switching calls are refused. Params: `{ operation }`
+    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,
+
+    /// 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:
+    /// 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,
+
+    /// No node URL configured.
+    NodeNotConfigured,
+    /// Node is on a different network than the wallet (by genesis block), or
+    /// its chain is unrecognized.
+    /// Params: `{ nodeNetwork, walletNetwork }` or `{ nodeGenesis }`
+    NodeNetworkMismatch,
+    /// Network request failed or timed out. Params: `{ operation }`
+    NetworkError,
+    /// Node response does not decode (bad epee/JSON). Params: `{ operation }`
+    MalformedNodeResponse,
+    /// Node explicitly rejected the transaction (double spend, low fee, ...). The fresh record is undone and its inputs released.
+    BroadcastRejected,
+
+    /// 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,
+
+    /// 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 {
+            InvalidNetwork => "INVALID_NETWORK",
+            InvalidAddress => "INVALID_ADDRESS",
+            InvalidKeyMaterial => "INVALID_KEY_MATERIAL",
+            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",
+            StorageUnsupported => "STORAGE_UNSUPPORTED",
+            AccountNotFound => "ACCOUNT_NOT_FOUND",
+            ReorgDetected => "REORG_DETECTED",
+            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",
+            DatabaseError => "DATABASE_ERROR",
+            DatabaseTooNew => "DATABASE_TOO_NEW",
+            InvalidDbName => "INVALID_DB_NAME",
+            Unimplemented => "UNIMPLEMENTED",
+        }
+    }
+}
+
+#[derive(Debug)]
+pub struct RuntimeError {
+    pub code: ErrorCode,
+    /// Structured params for host i18n placeholders. **Always a JSON object.**
+    pub params: Value,
+    /// Raw upstream error. **Log-only**; not user-facing, not translated.
+    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;
+
+/// 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)
+}
+
+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 {
+        // A JSON string, not an Error object: the host always `JSON.parse`s it.
+        wasm_bindgen::JsValue::from_str(&e.to_json().to_string())
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::collections::HashSet;
+
+    /// 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::*;
+        let all = [
+            InvalidNetwork,
+            InvalidAddress,
+            InvalidKeyMaterial,
+            InvalidSubaddressIndex,
+            InvalidBlockRange,
+            InvalidRequest,
+            InvalidKeyImage,
+            WalletNotOpen,
+            WalletBusy,
+            NotInitialized,
+            StorageUnsupported,
+            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), "duplicate code: {s}");
+            assert!(
+                !s.is_empty()
+                    && s.chars()
+                        .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'),
+                "malformed code: {s}"
+            );
+        }
+    }
+
+    /// `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);
+        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("from > to");
+        let v = e.to_json();
+        assert_eq!(v["code"], "INVALID_BLOCK_RANGE");
+        assert_eq!(v["params"]["from"], 5);
+        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
new file mode 100644
index 000000000..e2d411f2f
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/keys.rs
@@ -0,0 +1,454 @@
+//! View keys and address derivation.
+//!
+//! 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},
+    ed25519::{CompressedPoint, Scalar},
+    ViewPair,
+};
+use serde_json::json;
+use zeroize::{Zeroize, Zeroizing};
+
+use crate::error::{ErrorCode, Result, RuntimeError};
+
+/// 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),
+        "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 }),
+        )
+    })
+}
+
+/// 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()
+        .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" }),
+        )
+    })?;
+
+    // Upstream rejects spend keys with torsion.
+    ViewPair::new(spend, Zeroizing::new(view)).map_err(|e| {
+        RuntimeError::with(
+            ErrorCode::InvalidKeyMaterial,
+            json!({ "field": "spendPublicKey" }),
+        )
+        .detail(format!("{e:?}"))
+    })
+}
+
+/// Primary (standard) address.
+pub fn primary_address(pair: &ViewPair, network: Network) -> String {
+    pair.legacy_address(network).to_string()
+}
+
+/// 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(
+            ErrorCode::InvalidSubaddressIndex,
+            json!({ "major": major, "minor": minor, "reason": "zeroZeroIsThePrimaryAddress" }),
+        )
+    })?;
+    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(
+            ErrorCode::InvalidAddress,
+            json!({ "field": field, "network": network_name(network) }),
+        )
+        .detail(format!("{e:?}"))
+    })
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    /// A public address outside upstream test vectors; only exercises parsing.
+    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` 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"),
+            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; // does not decompress
+        let e = expect_key_error(¬_a_point, &[1u8; 32]);
+        assert_eq!(e.code, ErrorCode::InvalidKeyMaterial);
+    }
+
+    #[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());
+    }
+
+    #[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 {
+        // 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];
+        view[0] = 9; // small, hence canonical
+        match view_pair_from_bytes(&spend, &view) {
+            Ok(pair) => pair,
+            Err(e) => panic!("failed to build test key pair: {e}"),
+        }
+    }
+}
+
+/// Derives Monero keys from a 32-byte BIP-32 private key.
+///
+/// ```text
+/// spend_secret = sc_reduce32(bip32_private_key)
+/// view_secret   = sc_reduce32(keccak256(spend_secret))
+/// ```
+///
+/// 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 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")?;
+
+    let spend = Zeroizing::new(Scalar::from(
+        curve25519_dalek::Scalar::from_bytes_mod_order(*raw),
+    ));
+    let view = Zeroizing::new(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,
+}
+
+/// Spend key scalar for signing; same reduction as [`derive_from_bip32_key`].
+///
+/// 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();
+    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),
+    ));
+    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.
+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)
+}
+
+/// Stack bytes overwritten by [`scrub_stack`].
+const STACK_SCRUB_BYTES: usize = 64 * 1024;
+
+/// 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];
+    area.zeroize();
+    core::hint::black_box(&area);
+}
+
+#[cfg(test)]
+mod derive_tests {
+    use super::*;
+
+    #[test]
+    fn derivation_is_deterministic_and_network_scoped() {
+        let key = [3u8; 32];
+        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("derive");
+        assert_ne!(t.primary_address, a.primary_address);
+    }
+
+    #[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);
+    }
+
+    /// 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")
+            .unwrap();
+        let derived =
+            derive_from_bip32_key(Network::Mainnet, &key).expect("derivation should succeed");
+        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);
+    }
+
+    /// 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 [
+            (
+                "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}");
+        }
+    }
+
+    #[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
+            );
+        }
+    }
+
+    /// 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));
+        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])
+            .err()
+            .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
new file mode 100644
index 000000000..c27a90414
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/lib.rs
@@ -0,0 +1,35 @@
+//! OneKey Monero runtime: monero-oxide scanning and signing with SQLite persistence.
+//!
+//! Rust owns cryptography, protocol and storage; the host owns scan scheduling.
+
+pub mod blocks_bin;
+pub mod device_key_images;
+pub mod device_sign;
+pub mod error;
+pub mod keys;
+pub mod network;
+pub mod perf;
+pub mod pool;
+pub mod query;
+pub mod review;
+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;
+
+/// Pinned upstream versions, for host self-checks and logs.
+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..e33072461
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/network.rs
@@ -0,0 +1,498 @@
+//! Transport to monerod: implements upstream's `HttpTransport` and only moves bytes.
+//!
+//! 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;
+use serde_json::json;
+
+use crate::error::{net_err, ErrorCode, Result, RuntimeError};
+
+/// Default per-request timeout; a stall timeout, not a whole-batch deadline.
+pub const DEFAULT_TIMEOUT_MS: u32 = 30_000;
+
+/// 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: `.bin` routes are binary, the rest JSON.
+fn content_type_for(route: &str) -> &'static str {
+    if route.ends_with(".bin") {
+        "application/octet-stream"
+    } else {
+        "application/json"
+    }
+}
+
+/// Asserts that a `!Send` future is `Send`.
+///
+/// # Safety
+///
+/// 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);
+
+#[cfg(target_arch = "wasm32")]
+// SAFETY: see above; the target is single-threaded, so no other thread can observe it.
+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 projection onto the only field; it is never moved.
+        unsafe { self.map_unchecked_mut(|s| &mut s.0).poll(cx) }
+    }
+}
+
+/// 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,
+    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("response too big".into()));
+    }
+    Ok(bytes)
+}
+
+// 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> =
+        const { std::cell::RefCell::new(None) };
+}
+
+/// Install the host request handler; `None` uninstalls it and falls back to in-wasm fetch.
+///
+/// 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);
+}
+
+#[cfg(target_arch = "wasm32")]
+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,
+    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}: host channel {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("call", describe_js(&e)))?;
+
+    // Accept bytes returned directly or via a Promise.
+    let resolved = match returned.dyn_into::() {
+        Ok(promise) => JsFuture::from(promise)
+            .await
+            .map_err(|e| fail("await response", describe_js(&e)))?,
+        Err(value) => value,
+    };
+
+    let bytes = resolved
+        .dyn_into::()
+        .map_err(|_| fail("return value", "host must return a Uint8Array".to_owned()))?;
+    Ok(bytes.to_vec())
+}
+
+/// 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;
+    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;
+
+// Backstop only: the host enforces its own per-chunk idle limit.
+#[cfg(target_arch = "wasm32")]
+const HOST_REQUEST_TIMEOUT_MS: u32 = 10 * 60 * 1000;
+
+/// Browser transport based on `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(),
+        }
+    }
+
+    /// 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,
+        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_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}: no response in {} s",
+                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);
+
+        // 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);
+        }
+
+        // Tag each failure with its stage so the cause is identifiable.
+        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("build request", 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(
+                    "get fetch",
+                    "no global fetch here (host environment issue, not the node)".to_owned(),
+                )
+            })?;
+        let promise = fetch
+            .call1(&global, &request)
+            .map_err(|e| fail("send request", describe_js(&e)))?
+            .dyn_into::()
+            .map_err(|e| fail("send request", describe_js(&e)))?;
+
+        let response = JsFuture::from(promise)
+            .await
+            // The browser does not say whether the network is down or CORS headers are missing.
+            .map_err(|e| {
+                fail(
+                    "await response",
+                    format!("{} (node unreachable or no CORS headers)", describe_js(&e)),
+                )
+            })?
+            .dyn_into::()
+            .map_err(|e| fail("parse response", describe_js(&e)))?;
+
+        if !response.ok() {
+            return Err(fail(
+                "node rejected",
+                format!("HTTP {} {}", response.status(), response.status_text()),
+            ));
+        }
+
+        let buffer = JsFuture::from(
+            response
+                .array_buffer()
+                .map_err(|e| fail("read response body", describe_js(&e)))?,
+        )
+        .await
+        .map_err(|e| fail("read response body", 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,
+        ))
+    }
+}
+
+/// Native transport for local tests and diagnostics.
+#[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 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 {
+                    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 {
+            let response = client
+                .post(&url)
+                .header("Content-Type", content_type)
+                .body(body)
+                .send()
+                .await
+                .map_err(|e| {
+                    // 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 {
+                        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!("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("response too big".into()));
+            }
+            Ok(bytes)
+        }
+    }
+}
+
+#[cfg(target_arch = "wasm32")]
+pub type Transport = FetchTransport;
+#[cfg(not(target_arch = "wasm32"))]
+pub type Transport = NativeTransport;
+
+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 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));
+    }
+    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:?}")))?;
+    let network = node_network(&daemon).await?;
+    Ok((daemon, network))
+}
+
+/// 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,
+        "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)
+}
+
+/// Identify the node's chain by its genesis block; unknown chains are refused.
+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! {
+    /// URL of the connected node, for `blocks_bin`, which sends its own requests.
+    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())
+}
+
+/// 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);
+}
+
+#[cfg(test)]
+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);
+    }
+
+    #[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);
+    }
+
+    #[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}");
+        }
+    }
+
+    #[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..4fe8c4f3f
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/perf.rs
@@ -0,0 +1,15 @@
+//! Timing. Fetch and scan time are measured separately; node round trips can reach ~490 ms.
+
+#[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..5a0071793
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/pool.rs
@@ -0,0 +1,476 @@
+//! Liveness of our own broadcast, unconfirmed transactions.
+//!
+//! 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.
+//!
+//! 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, ErrorCode, Result};
+use crate::network::Daemon;
+use crate::wallet::{now_secs, Db};
+
+/// 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;
+
+/// 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 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)",
+        )
+        .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())
+}
+
+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;
+    }
+    let hash = |value: &Value| {
+        let bytes = hex::decode(value.as_str()?).ok()?;
+        <[u8; 32]>::try_from(bytes.as_slice()).ok()
+    };
+    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<()> {
+    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(())
+}
+
+/// Mark a send failed: keep the transaction (shown as failed) and release its inputs.
+///
+/// `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()
+        .unchecked_transaction()
+        .map_err(|e| db_err("beginMarkFailed", 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))?;
+    Ok(true)
+}
+
+// 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, 0));
+    }
+    let hashes: Vec = due.iter().map(hex::encode).collect();
+    // 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, 0));
+    };
+    apply_pool_response(db, identity_id, &due, &response, now)
+}
+
+#[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(), "recent");
+        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, "output released");
+        assert_eq!(
+            due_pending(&db, id, i64::MAX / 2).unwrap(),
+            vec![txid],
+            "failed sends remain eligible for the normal pool refresh"
+        );
+    }
+
+    #[test]
+    fn only_a_clear_answer_from_the_node_counts() {
+        let tx = hex::encode([2u8; 32]);
+        assert_eq!(
+            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!(
+            crate::query::balance(&db, id, Some(1000))
+                .unwrap()
+                .total_atomic,
+            700
+        );
+    }
+}
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..9aa69bcfb
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/query.rs
@@ -0,0 +1,840 @@
+//! Balance, history and spendable-output queries.
+//!
+//! Paging and aggregation run as indexed SQLite queries.
+
+use monero_wallet::address::Network;
+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;
+
+/// 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.
+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.
+    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.
+    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; 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 {
+    pub fn to_json(&self) -> Value {
+        // Strings: piconero values exceed JS Number.MAX_SAFE_INTEGER.
+        json!({
+            "totalAtomic": self.total_atomic.to_string(),
+            "unlockedAtomic": self.unlocked_atomic.to_string(),
+            "unverifiableAtomic": self.unverifiable_atomic.to_string(),
+            "pendingChangeAtomic": self.pending_change_atomic.to_string(),
+            "outputsWithoutKeyImage": self.outputs_without_key_image,
+            "confirmingBlocksLeft": self.confirming_blocks_left,
+        })
+    }
+}
+
+/// 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(
+            "SELECT o.amount_atomic, o.height, o.additional_timelock,
+                    o.key_image IS NULL AS no_ki,
+                    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
+             WHERE o.identity_id = ?1 AND o.scan_valid = 1 AND o.spent_at_height IS NULL",
+        )
+        .map_err(|e| db_err("balanceQuery", e))?;
+
+    let rows = stmt
+        .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, maybe_spent) =
+            row.map_err(|e| db_err("balanceQuery", e))?;
+        b.total_atomic += amount;
+        if no_key_image {
+            b.outputs_without_key_image += 1;
+        }
+        // May be spent, so not counted as unlocked.
+        if no_key_image && maybe_spent {
+            b.unverifiable_atomic += amount;
+            continue;
+        }
+        if let Some(tip) = chain_tip {
+            if is_unlocked(height, timelock, tip, now, network) {
+                b.unlocked_atomic += amount;
+            } else {
+                // As is_unlocked: the chain length is tip + 1.
+                let left =
+                    (height + COINBASE_AND_STANDARD_LOCK).saturating_sub(tip.saturating_add(1));
+                if left > 0 {
+                    b.confirming_blocks_left = b.confirming_blocks_left.max(Some(left));
+                }
+            }
+        }
+    }
+    // Pending change is not in `outputs` until scanned.
+    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)
+}
+
+/// Whether an output is spendable now, as wallet2's `is_transfer_unlocked`.
+///
+/// `chain_tip` is the top block number. `additional_timelock` is raw: below 500M a
+/// height, otherwise a Unix timestamp compared against `now`; with `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 {
+        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 {
+        TARGET_SECONDS_V2
+    }
+}
+
+/// "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()
+        .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; blobs are deserialized only when building the transaction.
+#[derive(Debug, Clone)]
+pub struct SpendableRow {
+    pub id: i64,
+    pub amount_atomic: u64,
+    pub global_index: u64,
+    pub height: u64,
+}
+
+/// Currently spendable outputs, largest first (fewer inputs, lower fee).
+///
+/// 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();
+    let mut stmt = db
+        .conn()
+        .prepare(
+            "SELECT o.id, o.amount_atomic, o.global_index, o.height, o.additional_timelock
+             FROM outputs o
+             WHERE o.identity_id = ?1
+               AND o.scan_valid = 1
+               AND o.spent_at_height IS NULL
+               AND o.key_image IS NOT NULL
+             ORDER BY o.amount_atomic DESC",
+        )
+        .map_err(|e| db_err("spendableRows", e))?;
+
+    let rows = stmt
+        .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();
+    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, now, network) {
+            continue;
+        }
+        out.push(SpendableRow {
+            id,
+            amount_atomic,
+            global_index,
+            height,
+        });
+    }
+    Ok(out)
+}
+
+/// Deserializes an output blob into the monero-oxide object.
+///
+/// All cryptographic use goes through the blob; the other `outputs` columns are for filtering and display.
+/// An unreadable blob errors out rather than being skipped, which would hide funds.
+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!("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 {
+    let limit = limit.clamp(1, 500);
+
+    let mut stmt = db
+        .conn()
+        .prepare(
+            "SELECT t.txid, CASE WHEN t.scan_valid = 1 THEN t.height END, t.direction,
+                    COALESCE((SELECT sum(amount_atomic) FROM outputs
+                              WHERE identity_id = t.identity_id AND txid = t.txid AND scan_valid = 1), 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,
+                    t.fee_atomic,
+                    EXISTS (SELECT 1 FROM outputs
+                            WHERE identity_id = t.identity_id AND txid = t.txid AND scan_valid = 1
+                              AND subaddress_major IS NULL) AS received_on_primary,
+                    -- Change in our own send decrypts it with our key into noise; wallet2 skips it too.
+                    CASE WHEN t.direction = 'in' THEN t.payment_id END,
+                    t.coinbase
+             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)?,
+                "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)?,
+                "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))?;
+
+    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 }))
+}
+
+/// Details of a single transaction.
+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 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],
+            |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 AND scan_valid = 1 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];
+            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()
+    }
+
+    const MAIN: Network = Network::Mainnet;
+
+    #[test]
+    fn the_ten_block_lock_is_enforced() {
+        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));
+    }
+
+    #[test]
+    fn additional_block_timelock_is_honoured() {
+        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));
+        assert!(!is_unlocked(100, 200, 198, Some(u64::MAX), MAIN));
+        assert!(!is_unlocked(100, 50, 108, None, MAIN));
+        assert!(is_unlocked(100, 50, 109, None, MAIN));
+    }
+
+    /// `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
+        ));
+        assert!(!is_unlocked(h, t, h + 8, Some(t + 1), MAIN));
+        assert!(is_unlocked(h, t, h + 9, Some(t + 1), MAIN));
+        assert!(!is_unlocked(h, t, h + 9, Some(t - 121), MAIN));
+        assert!(is_unlocked(h, t, h + 9, Some(t - 120), MAIN));
+        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() {
+        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
+        );
+        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,
+            );
+        }
+    }
+
+    #[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));
+    }
+
+    #[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);
+    }
+
+    #[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();
+        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);
+    }
+
+    /// 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();
+        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);
+    }
+
+    #[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,
+            "possibly spent outputs are not unlocked"
+        );
+    }
+
+    #[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");
+    }
+
+    #[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);
+    }
+
+    /// 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();
+        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/review.rs b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
new file mode 100644
index 000000000..4750647c9
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/review.rs
@@ -0,0 +1,839 @@
+use monero_wallet::{
+    address::MoneroAddress,
+    ed25519::{CompressedPoint, Point, Scalar},
+    io::{read_byte, read_bytes, read_u32, read_u64, read_vec},
+    send::{Eventuality, SignableTransaction},
+    transaction::Transaction,
+    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,
+}
+
+pub(crate) fn mismatch(field: &str) -> RuntimeError {
+    RuntimeError::with(
+        ErrorCode::InvalidRequest,
+        serde_json::json!({"field": field, "reason": "transactionDoesNotMatchReview"}),
+    )
+}
+
+pub(crate) 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"))
+}
+
+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(
+    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[..])?);
+                            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)
+}
+
+/// [`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"));
+    }
+    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::*;
+    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()
+    }
+
+    fn fixture(extra: Vec>) -> (Vec, ReviewRequest, [u8; 32]) {
+        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));
+        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]) {
+        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 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;
+        let public = CompressedPoint::from(public_bytes).decompress().unwrap();
+        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();
+        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 = recipient.unwrap_or(&sender);
+        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.clone(),
+            to_address: recipient.into(),
+            amount_atomic: paid.to_string(),
+            fee_atomic: fee.to_string(),
+            change_atomic: (total - paid - fee).to_string(),
+            is_max_send: max_send,
+        };
+        (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 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};
+        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![]);
+        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());
+    }
+
+    /// 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);
+        type ChangeFor = Box Change>;
+        let cases: [(&str, ChangeFor); 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![]);
+        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());
+        }
+    }
+
+    /// 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/runtime.rs b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
new file mode 100644
index 000000000..bef00ea9b
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/runtime.rs
@@ -0,0 +1,517 @@
+//! Session state across calls.
+//!
+//! Holds only the database connection and node client; no caches, timers or
+//! background tasks.
+
+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) };
+    /// 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) };
+
+    // 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) };
+
+    // 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) };
+}
+
+fn assert_idle(operation: &str) -> Result<()> {
+    if BUSY.with(Cell::get) {
+        return Err(RuntimeError::with(
+            ErrorCode::WalletBusy,
+            serde_json::json!({ "operation": operation }),
+        ));
+    }
+    Ok(())
+}
+
+/// Sets BUSY while held; Drop **always** clears it, including early returns and panic unwinding.
+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)
+}
+
+/// `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));
+    }
+}
+
+fn not_open() -> RuntimeError {
+    RuntimeError::new(ErrorCode::WalletNotOpen)
+}
+
+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));
+    DB_NAME.with(|c| *c.borrow_mut() = Some(db_name.to_owned()));
+    bump_generation();
+    Ok(())
+}
+
+/// 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
+/// node would scan and send real 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),
+        }),
+    ))
+}
+
+/// 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.
+/// 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();
+}
+
+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);
+    DB_NAME.with(|c| *c.borrow_mut() = None);
+    bump_generation();
+    clear_daemon();
+    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| {
+        let mut slot = c.borrow_mut();
+        let db = slot.as_mut().ok_or_else(not_open)?;
+        f(db)
+    })
+}
+
+/// 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 Some(db) = slot.as_ref() else {
+            assert_idle("walletRead")?;
+            return Err(not_open());
+        };
+        f(db)
+    })
+}
+
+/// Borrows the database and node client for an async operation.
+///
+/// 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,
+    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());
+        }
+    };
+    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;
+
+    // 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 {
+        DB.with(|c| *c.borrow_mut() = Some(db));
+    }
+    put_daemon_back(daemon, daemon_gen);
+    drop(guard);
+    out
+}
+
+/// 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, 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, daemon_network()).await;
+    put_daemon_back(daemon, daemon_gen);
+    result
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use monero_wallet::address::Network;
+
+    // Each test runs on its own thread, so thread_locals are isolated.
+
+    fn open_memory_db() {
+        let db = Db::open(":memory:", Network::Mainnet).expect("in-memory db");
+        set_db(db, ":memory:").expect("open db");
+    }
+
+    #[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
+        );
+    }
+
+    /// 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(|_| {
+            // 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);
+    }
+
+    /// 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 must be cleared on failure");
+        // Usable again afterwards
+        with_db(|_| Ok(())).expect("operations should work after a failure");
+    }
+
+    /// 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();
+        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 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]
+    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);
+        }
+    }
+
+    /// 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)
+    }
+
+    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());
+        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]),
+                    }
+                }
+                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}",
+                    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()));
+    }
+
+    /// 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() {
+        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]
+    fn closing_invalidates_an_in_flight_daemon_borrow() {
+        let sampled = daemon_generation();
+        assert_eq!(
+            daemon_generation(),
+            sampled,
+            "generation is stable when nothing happens"
+        );
+        close().expect("close should succeed on empty state");
+        assert_ne!(
+            daemon_generation(),
+            sampled,
+            "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
new file mode 100644
index 000000000..20d5efe14
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/scan.rs
@@ -0,0 +1,1613 @@
+//! Scanning: feeds blocks to the monero-oxide `Scanner` and persists results to SQLite.
+//!
+//! 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};
+
+use monero_wallet::{
+    address::SubaddressIndex,
+    extra::PaymentId,
+    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;
+
+/// 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)]
+pub struct ScanOutcome {
+    pub blocks_scanned: u64,
+    pub outputs_found: usize,
+    pub spends_detected: usize,
+    /// 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,
+    /// 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,
+    /// 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,
+    /// 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,
+}
+
+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,
+        })
+    }
+}
+
+/// 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 {
+            Transaction::V1 { .. } => 0,
+            Transaction::V2 { prefix, .. } => prefix.outputs.len() as u64,
+        }
+    }
+    count(block.block.miner_transaction()) + block.transactions.iter().map(count).sum::()
+}
+
+/// 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;
+/// `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(
+            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)
+}
+
+/// 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
+        .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.
+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
+}
+
+/// A possible spend: one of our outputs appears in an input's ring.
+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 pool; otherwise a pre-2017 per-amount pool.
+    amount: Option,
+    members: Vec,
+}
+
+/// 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>;
+
+/// 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()
+        .prepare(
+            "SELECT txid, index_in_tx, global_index, amount_atomic FROM outputs
+             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
+        .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)
+}
+
+/// 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,
+) -> 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))
+}
+
+/// Transaction public keys `(R, additional)` by txid.
+///
+/// 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 {
+    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
+        .iter()
+        .zip(block.transactions.iter())
+    {
+        if let Some((keys, additional)) = tx_public_keys_from_extra(&tx.prefix().extra) {
+            out.push((*txid, keys, additional));
+        }
+    }
+    out
+}
+
+/// Extracts `(R, additional)` from a transaction `extra`, each as concatenated 32-byte keys.
+/// Pure, so it can be tested against real chain data.
+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)))
+}
+
+/// 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.
+pub fn scan_blocks(
+    db: &mut Db,
+    identity_id: i64,
+    blocks: &[ScannableBlock],
+) -> Result {
+    if blocks.is_empty() {
+        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)?;
+    let subaddresses = db.subaddress_indices(identity_id)?;
+
+    let mut scanner = Scanner::new(identity.view_pair.clone());
+    for (major, minor) in &subaddresses {
+        // 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);
+        }
+    }
+
+    // Known key images, for spend detection.
+    let known_key_images = load_key_images(db, identity_id)?;
+    // 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), 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
+    // 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.
+    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. Heights must be strictly increasing and contiguous ─────────
+        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. Previous hash check: reorg detection ──────────────────────
+        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 index check (upstream requires client-side tracking) ─
+        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:?}"))
+            })?
+            // Timelocks are checked by the query layer; dropping locked outputs here would lose them.
+            .ignore_additional_timelock();
+
+        if !outputs.is_empty() {
+            // 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));
+            }
+            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
+        // 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;
+            }
+            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) {
+                // The spending transaction's txid, not the block hash.
+                spends.push((height, key_image, txid));
+            }
+        }
+        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
+        // 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)
+            .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,
+        &tx_fees,
+        &coinbase_txids,
+    )?;
+    outcome.outputs_without_key_image = count_outputs_without_key_image(db, identity_id)?;
+    Ok(outcome)
+}
+
+/// (height, hash, RingCT cursor after it) of the block before `height`.
+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", "block hash is not 32 bytes"))?;
+            Ok((h, hash, next))
+        })
+        .transpose()
+}
+
+/// 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()
+        .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 OR scan_valid = 0)))",
+        )
+        .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 scan_valid = 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], TxKeys>,
+    spends: &[(u64, [u8; 32], [u8; 32])],
+    known_key_images: &HashMap<[u8; 32], i64>,
+    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()
+        .transaction()
+        .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))
+        .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();
+        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;
+        }
+        // Revalidate the same output without losing its key image or send lock.
+        tx.execute(
+            "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)
+             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(),
+                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, 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),
+                       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),
+                    coinbase_txids.contains(&txid)
+                ],
+            )
+            .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 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, fee_atomic)
+             VALUES (?1, ?2, ?3, ?4, 'out', ?5)
+             ON CONFLICT (identity_id, txid) DO UPDATE
+               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),
+                tx_fees.get(txid).map(|fee| *fee as i64)
+            ],
+        )
+        .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
+               (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(),
+                ps.out_index as i64,
+                ps.key_image.as_slice(),
+                ps.spend_txid.as_slice(),
+                ps.height as i64,
+                ps.timestamp as i64,
+                tx_fees.get(&ps.spend_txid).map(|fee| *fee 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))?;
+    }
+
+    // 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(
+            "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))
+}
+
+/// 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,
+    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 scan_valid = 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,
+    }
+}
+
+/// Invalidate the rewound span, retaining key images and local send evidence.
+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(
+        "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",
+        params![identity_id, reorgable_above as i64],
+    )
+    .map_err(|e| db_err("rewindOwnSends", e))?;
+
+    tx.execute(
+        "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))?;
+
+    // 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 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 AND sent_at IS NULL",
+        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))?;
+
+    Ok(())
+}
+
+#[cfg(test)]
+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(),
+            &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();
+        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(),
+            &HashSet::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]
+    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("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 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);
+    }
+
+    /// 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() {
+        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;
+
+    /// Real mainnet vector.
+    ///
+    /// 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(
+            "01d3c8b566d9fd0bff3f93448591ec257cc8bf813e1aaa808e97254a5c65ea166\
+             00209012c9f54c03a7c72d0",
+        )
+        .unwrap();
+
+        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, "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);
+    }
+
+    /// 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());
+    }
+
+    /// 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();
+        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("cursor should allow NULL");
+
+        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, "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();
+        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();
+        }
+
+        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());
+    }
+
+    #[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(),
+            "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();
+        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));
+    }
+
+    /// 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();
+        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),
+            ],
+            &[],
+            &HashMap::new(),
+            &HashSet::new(),
+        )
+        .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, "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);
+    }
+
+    /// 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();
+        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),
+            "pending spends must be matched too"
+        );
+
+        persist(
+            &mut db,
+            id,
+            &[],
+            &HashMap::new(),
+            &[(mined_at, key_image, txid)],
+            &known,
+            &[(mined_at, [7u8; 32], None, 1_700_000_000)],
+            &[],
+            &HashMap::new(),
+            &HashSet::new(),
+        )
+        .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(),
+            "confirmed spends are no longer matched"
+        );
+    }
+
+    /// 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,
+            &HashSet::new(),
+        )
+        .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();
+        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();
+
+        crate::sync::rewind_and_requeue(&mut db, id, 490, 505).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()));
+    }
+
+    /// 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();
+        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();
+
+        crate::sync::rewind_and_requeue(&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() {
+        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();
+
+        crate::sync::rewind_and_requeue(&mut db, id, 490, 505).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)],
+            "our send reverts to pending, scanned ones are deleted"
+        );
+        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]);
+    }
+
+    /// 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("empty batch");
+
+        assert_eq!(outcome.blocks_scanned, 0);
+        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 (mut db, id) = vector_wallet();
+
+        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)
+    }
+
+    /// 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);
+        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
new file mode 100644
index 000000000..f225d6021
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/schema.rs
@@ -0,0 +1,439 @@
+//! Wallet database schema and migrations.
+//!
+//! Monero has no pools and (before FCMP++) no commitment tree, so no witnesses
+//! or checkpoints. Writes are incremental and transactional.
+
+use rusqlite::Connection;
+
+use crate::error::{db_err, ErrorCode, Result, RuntimeError};
+
+/// 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 (about a day).
+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))
+        .map_err(|e| db_err("readUserVersion", e))?;
+
+    if version > SCHEMA_VERSION {
+        return Err(RuntimeError::with(
+            ErrorCode::DatabaseTooNew,
+            serde_json::json!({ "version": version, "supportedVersion": SCHEMA_VERSION }),
+        ));
+    }
+
+    // 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))?;
+    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))
+}
+
+/// Version 1.
+///
+/// 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;
+
+-- 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
+);
+
+-- One identity = one view key pair = one host account.
+--
+-- 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),
+    -- 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
+);
+
+-- Subaddress registry. All entries are loaded into the monero-oxide Scanner,
+-- which only recognises registered subaddresses.
+--
+-- (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),
+    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);
+
+-- 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.
+--
+-- Not shared across identities: one identity's rollback or pruning would
+-- remove anchors another identity still needs, hiding a reorg from it.
+--
+-- 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),
+    -- Global index of the next RingCT output after this block.
+    --
+    -- 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).
+--
+-- 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,
+    end_height      INTEGER NOT NULL,
+    PRIMARY KEY (identity_id, start_height),
+    CHECK (end_height > start_height)
+);
+
+-- Received outputs.
+--
+-- `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 serialization, read back when spending
+    blob                BLOB    NOT NULL,
+    -- ── 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),
+    -- Receiving subaddress; NULL for the primary address
+    subaddress_major    INTEGER,
+    subaddress_minor    INTEGER,
+    height              INTEGER NOT NULL,
+    -- 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),
+    -- Height spent at; NULL if unspent
+    spent_at_height     INTEGER,
+    spent_in_txid       BLOB,
+    -- Transaction public keys R, concatenated 32 bytes each (usually one).
+    --
+    -- 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 for subaddress receives, one per output; NULL if none.
+    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
+    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);
+
+-- 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 = in mempool
+    timestamp       INTEGER,
+    -- 'in' receive / 'out' spend. A tx with both (change) is recorded as 'out'.
+    direction       TEXT    NOT NULL CHECK (direction IN ('in', 'out')),
+    -- 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,
+    -- Total paid out (destinations + fee), piconero decimal string. Only known
+    -- from the broadcast while pending (change appears once scanned).
+    outgoing_atomic TEXT,
+    -- 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,
+    -- 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)
+);
+CREATE INDEX IF NOT EXISTS idx_transactions_height ON transactions(identity_id, height);
+
+-- Possible spends (as in monero-lws).
+--
+-- 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,
+    -- 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 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,
+    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);
+"#;
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn db() -> Connection {
+        let conn = Connection::open_in_memory().expect("in-memory db");
+        migrate(&conn).expect("migrate");
+        conn
+    }
+
+    /// 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();
+        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));
+    }
+
+    /// 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();
+        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);
+    }
+
+    /// 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();
+        migrate(&conn).expect("repeated migration must be harmless");
+        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();
+        // Old code could misread data written by a newer version
+        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",
+            "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, "missing table {t}");
+        }
+    }
+
+    /// (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();
+        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) must be rejected by the CHECK");
+        conn.execute(
+            "INSERT INTO subaddresses (identity_id, major, minor, address) VALUES (1, 0, 1, 'a')",
+            [],
+        )
+        .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();
+        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("first insert");
+        assert!(
+            conn.execute(insert, []).is_err(),
+            "duplicate (identity, txid, index_in_tx) must hit the unique constraint"
+        );
+    }
+
+    /// 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();
+        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} 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
new file mode 100644
index 000000000..012a6eca2
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/spend.rs
@@ -0,0 +1,2081 @@
+//! Spend path: key image import, transaction construction, signing, broadcast.
+//!
+//! 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;
+
+use monero_wallet::{
+    address::MoneroAddress,
+    ed25519::{Point, Scalar},
+    extra::Extra,
+    io::{read_byte, read_bytes, read_vec},
+    send::{Change, SignableTransaction, TransactionKeys},
+    transaction::Transaction,
+    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;
+
+/// 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.
+///
+/// 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;
+
+    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 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 generator: curve25519_dalek::EdwardsPoint = generator.into();
+    let image = Point::from(input_key.deref() * generator);
+    Ok(image.compress().to_bytes())
+}
+
+/// Fills in key images for outputs that lack one, enabling spend detection.
+///
+/// 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,
+    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 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 clear the key-image math's 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));
+    }
+    Ok(computed)
+}
+
+/// Stores computed key images and confirms earlier spends from possible spends.
+pub(crate) 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 = 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::<_, Vec>(0)?,
+                        r.get::<_, i64>(1)?,
+                        r.get::<_, Option>(2)?,
+                        r.get::<_, Option>(3)?,
+                    ))
+                },
+            )
+            .optional()
+            .map_err(|e| db_err("matchPossibleSpend", e))?;
+        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",
+                params![height, spend_txid, id],
+            )
+            .map_err(|e| db_err("markPossibleSpend", e))?;
+            tx.execute(
+                "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),
+                       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;
+        }
+        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,
+    })
+}
+
+/// Result of `import_key_images`.
+pub struct KeyImageImport {
+    /// Outputs whose key image was computed.
+    pub imported: usize,
+    /// Of those, outputs confirmed as already spent via possible spends.
+    pub spends_found: usize,
+}
+
+fn parse_spend_key(bytes: &[u8]) -> Result> {
+    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,
+            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,
+}
+
+/// Selects inputs largest first until `needed` is covered; fewer inputs mean a lower fee.
+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,
+    })
+}
+
+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
+        .detail
+        .as_deref()
+        .is_some_and(|reason| reason.to_lowercase().contains("double spend"))
+}
+
+/// Shares one RingCT output distribution across all inputs of a construction.
+///
+/// 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,
+}
+
+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,
+        )
+    }
+}
+
+/// 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,
+    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:?}"))
+        })
+}
+
+/// Rings for a set of outputs, reusing ones already fetched.
+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)
+}
+
+/// Assembles a `SignableTransaction`. Change always goes to the account's primary address.
+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` seeds this transaction's RNG; never reuse it across transactions.
+    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:?}"))
+}
+
+/// Selects inputs and constructs a transaction; no private spend key needed.
+///
+/// `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,
+    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;
+
+    // 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(
+            db,
+            decoy_source,
+            rng,
+            &selection.output_ids,
+            chain_tip,
+            &mut cache,
+        )
+        .await?;
+
+        match assemble(
+            &identity,
+            rng,
+            rct_type,
+            inputs.clone(),
+            recipients.clone(),
+            fee_rate,
+        ) {
+            Ok(signable) => {
+                let fee_atomic = signable.necessary_fee();
+                return Ok(Prepared {
+                    signable,
+                    output_ids: selection.output_ids,
+                    inputs,
+                    inputs_atomic: selection.total_atomic,
+                    amount_atomic: out_total,
+                    fee_atomic,
+                });
+            }
+            Err(SendError::NotEnoughFunds {
+                outputs,
+                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;
+            }
+            Err(e) => return Err(build_error(e)),
+        }
+    }
+
+    Err(insufficient(0, needed))
+}
+
+/// Sends all spendable outputs to one address.
+///
+/// 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,
+    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?;
+
+    // Probe for the fee: `necessary_fee()` on success, or from `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.clone(),
+        vec![(recipient, amount_atomic)],
+        fee_rate,
+    )
+    .map_err(build_error)?;
+
+    Ok(Prepared {
+        signable,
+        output_ids,
+        inputs,
+        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(),
+        }),
+    )
+}
+
+/// Signs a constructed transaction. No network or database access; `spend_private` is zeroized after use.
+pub fn sign_prepared(
+    signable: SignableTransaction,
+    rng: &mut R,
+    spend_private: &[u8],
+) -> Result {
+    let spend = parse_spend_key(spend_private)?;
+    signable.sign(rng, &spend).map_err(|e| {
+        RuntimeError::with(ErrorCode::InvalidRequest, json!({ "field": "signature" }))
+            .detail(format!("{e:?}"))
+    })
+}
+
+/// 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.
+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:?}")),
+    })
+}
+
+/// Validates a recipient address and parses the amount.
+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::test_support::{plus_group_order, reference_spend_scalar};
+    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();
+    }
+
+    /// 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); // 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,
+            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, "only used as a decoy, not spent");
+
+        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-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;
+        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 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] =
+            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() {
+        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"], "transactionDoesNotMatchReview");
+
+        let e = sign_for_host("00010203", &[0u8; 32], review).unwrap_err();
+        assert_eq!(e.code, ErrorCode::InvalidRequest);
+        assert_eq!(e.params["reason"], "transactionDoesNotMatchReview");
+    }
+
+    /// 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(
+            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);
+    }
+
+    /// 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();
+        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 suffice; skip the 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");
+    }
+
+    /// 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();
+        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");
+    }
+
+    /// 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);
+        // 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");
+        // Unlocked at 105
+        assert!(select_inputs(&db, id, 105, 1_000).is_ok());
+    }
+
+    /// 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();
+        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],
+            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);
+
+        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() {
+        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],
+            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"));
+    }
+
+    /// 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 (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 txid = [0x66u8; 32];
+        let record = |db: &Db| {
+            record_broadcast(db, id, &txid, &[key_image], 900, SentAmounts::default()).unwrap()
+        };
+
+        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), "recording the same tx again is not fresh");
+
+        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, "rejected transaction is not kept in history");
+    }
+
+    /// A send passed with the wrong account records nothing and leaves the
+    /// 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();
+        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);
+        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],
+                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);
+        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();
+        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"
+        );
+    }
+
+    /// A send failed by the pending check releases its inputs; a new
+    /// transaction over the same inputs must be recordable again.
+    #[test]
+    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())
+        };
+
+        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]
+    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());
+    }
+
+    /// 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;
+        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);
+    }
+}
+
+/// Fee rate cap per priority (piconero / weight).
+///
+/// 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 {
+        FeePriority::Unimportant => 100_000,
+        FeePriority::Normal => 400_000,
+        FeePriority::Elevated => 1_600_000,
+        FeePriority::Priority | FeePriority::Custom { .. } => 20_000_000,
+    }
+}
+
+/// Fee quantization mask (piconero).
+///
+/// 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;
+
+/// `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()?))
+}
+
+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(())
+}
+
+/// 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 {
+        "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"],
+                }),
+            ))
+        }
+    })
+}
+
+/// Constructs a transaction to sign. No private spend key needed; does not broadcast.
+///
+/// `signableHex` contains the private view key (upstream writes the view pair into the
+/// change; the keyless variant is documented as harming privacy), so it is equivalent
+/// to a view key and must be treated as one.
+///
+/// `recipients` are `(address, piconero amount)`; exactly one is accepted. With `max_send`
+/// the amount is spendable total minus fee and the given amount is ignored. `feeAtomic`
+/// is the fee actually paid; `amountAtomic` is what the recipient receives.
+#[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, _, _) = 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 {
+        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))
+        .await
+        .map_err(|e| {
+            RuntimeError::with(ErrorCode::NetworkError, json!({ "operation": "feeRate" }))
+                .detail(format!("{e:?}"))
+        })?;
+    check_fee_rate(&rate)?;
+
+    // CLSAG + Bulletproofs+ per current consensus; set per hard fork, a wrong type is rejected.
+    let rct_type = monero_wallet::ringct::RctType::ClsagBulletproofPlus;
+    let mut rng = rand_core::OsRng;
+    let decoys = CachedDecoys::new(daemon);
+
+    if max_send {
+        let address = keys::parse_address(network, recipients[0].0, "recipient.address")?;
+        let prepared = prepare_max(
+            db,
+            &decoys,
+            &mut rng,
+            identity_id,
+            address,
+            rate,
+            chain_tip,
+            rct_type,
+        )
+        .await?;
+        Ok((prepared, address, rate))
+    } else {
+        let payments = recipients
+            .iter()
+            .map(|(addr, amount)| parse_payment(network, addr, amount))
+            .collect::>>()?;
+        let prepared = prepare(
+            db,
+            &decoys,
+            &mut rng,
+            identity_id,
+            &payments,
+            rate,
+            chain_tip,
+            rct_type,
+        )
+        .await?;
+        Ok((prepared, payments[0].address, rate))
+    }
+}
+
+/// 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 signed = verify_and_sign(signable_hex, &request, spend_private, rng);
+    keys::scrub_stack();
+    let (transaction, tx_keys) = signed?;
+    let raw = transaction.serialize();
+    Ok(json!({
+        "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::>(),
+    }))
+}
+
+// Separate frame so `scrub_stack` can clear signing's stack.
+#[inline(never)]
+fn verify_and_sign(
+    signable_hex: &str,
+    request: &crate::review::ReviewRequest,
+    spend_private: &[u8],
+    rng: &mut R,
+) -> Result<(Transaction, TxKeys)> {
+    let signable = crate::review::verify(signable_hex, request, Some(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.
+#[derive(Debug, Default, Clone, Copy)]
+pub struct SentAmounts {
+    /// Total paid out (destinations + fee).
+    pub outgoing_atomic: Option,
+    /// Change, counted in the total (locked) balance until mined, as wallet2.
+    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.
+///
+/// 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,
+    txid: &[u8; 32],
+    key_images: &[[u8; 32]],
+    chain_tip: u64,
+    amounts: SentAmounts,
+) -> 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))?;
+    check_inputs_owned(&tx_db, identity_id, txid, key_images)?;
+    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(outgoing_atomic, ?4),
+                   change_atomic = COALESCE(change_atomic, ?5)",
+            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.commit().map_err(|e| db_err("commitRecordSend", e))?;
+    Ok(!existed)
+}
+
+/// Every input must be an output of `identity_id` not spent by another transaction.
+///
+/// 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],
+    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 owned: Option<(Option>, bool, bool)> = db
+            .query_row(
+                "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(), 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 owned {
+            None => "inputNotOwnedByAccount",
+            Some((_, false, false)) => "inputNotVerified",
+            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
+        .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))
+}
+
+/// Records, then broadcasts a signed transaction. Irreversible.
+///
+/// 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,
+    identity_id: i64,
+    raw_hex: &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 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();
+    // If recording fails, do not send; nothing has happened yet.
+    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?;
+
+    // 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 => {
+            undo_recorded_broadcast(db, identity_id, &txid)?;
+            return Err(e);
+        }
+        Err(e) => 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())
+        }
+    }
+
+    #[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 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),
+            "serialization layout changed"
+        );
+        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");
+        }
+    }
+
+    /// Current mainnet rates fit every tier with at least 5x headroom.
+
+    #[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");
+        let other = RuntimeError::new(ErrorCode::BroadcastRejected).detail("fee too low");
+        assert!(is_double_spend(&spent));
+        assert!(!is_double_spend(&other));
+    }
+}
+
+/// 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};
+
+    /// 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),
+        ))
+    }
+
+    /// `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/crates/monero-runtime/src/storage.rs b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
new file mode 100644
index 000000000..fdab4cbba
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/storage.rs
@@ -0,0 +1,378 @@
+//! SQLite storage shared by all platforms.
+//!
+//! 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, or `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);
+
+// Pool handle, used to delete databases that cannot be opened.
+#[cfg(target_arch = "wasm32")]
+thread_local! {
+    static VFS_UTIL: std::cell::RefCell>> =
+        const { std::cell::RefCell::new(None) };
+}
+
+/// Whether the VFS is ready. Always true on native (system filesystem).
+pub fn is_ready() -> bool {
+    #[cfg(target_arch = "wasm32")]
+    {
+        VFS_READY.load(Ordering::SeqCst)
+    }
+    #[cfg(not(target_arch = "wasm32"))]
+    {
+        true
+    }
+}
+
+/// 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 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};
+
+    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(),
+        directory: ".onekey-xmr-opfs".to_owned(),
+        // Never true: it wipes the pool on every start.
+        clear_on_init: false,
+        initial_capacity: 4,
+    };
+
+    let mut retries = 20;
+    loop {
+        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 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,
+                        json!({ "reason": "vfsInstallFailed" }),
+                    )
+                    .detail(format!("{error:?}")));
+                }
+                retries -= 1;
+                gloo_timers::future::TimeoutFuture::new(250).await;
+            }
+        }
+    }
+}
+
+/// 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;
+    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<()> {
+    Ok(())
+}
+
+/// Database name must be non-empty with no path separators.
+///
+/// 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('/')
+        || db_name.contains('\\')
+        || db_name.contains("..");
+    if bad {
+        return Err(RuntimeError::with(
+            ErrorCode::InvalidDbName,
+            json!({ "value": db_name }),
+        ));
+    }
+    Ok(())
+}
+
+/// Opens a connection and sets pragmas.
+///
+/// `: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))?;
+        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))?;
+
+    // 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))?;
+
+    // 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.
+    conn.execute_batch("PRAGMA secure_delete = ON;")
+        .map_err(|e| db_err("pragmaSecureDelete", e))?;
+
+    #[cfg(target_arch = "wasm32")]
+    {
+        // 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))?;
+    }
+
+    Ok(conn)
+}
+
+/// Free pages below which a reclaim is not worth its write transaction.
+const RECLAIM_MIN_FREE_PAGES: i64 = 256;
+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))
+    };
+    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")]
+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())),
+    }
+}
+
+/// Durability barrier: fails if committed transactions may not have reached
+/// durable storage.
+///
+/// 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(
+            ErrorCode::DatabaseError,
+            json!({ "reason": "storageRequiresWorkerRestart" }),
+        ));
+    }
+    if !is_ready() {
+        return Err(RuntimeError::new(ErrorCode::NotInitialized));
+    }
+    Ok(())
+}
+
+/// Poisoned pool: only a fresh Worker can reopen storage.
+#[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(test)]
+mod tests {
+    use super::*;
+
+    fn free_pages(conn: &Connection) -> i64 {
+        conn.query_row("PRAGMA freelist_count", [], |r| r.get(0))
+            .unwrap()
+    }
+
+    #[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);
+    }
+
+    #[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 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());
+    }
+
+    #[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:?} should be rejected"));
+            assert_eq!(e.code, ErrorCode::InvalidDbName);
+        }
+    }
+
+    #[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.
+        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..4f2abf66a
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/sync.rs
@@ -0,0 +1,805 @@
+//! Sync orchestration: fetch blocks, scan, record progress. Bounded; never runs to completion.
+//!
+//! 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::*;
+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;
+
+/// 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.
+pub const FETCH_CONCURRENCY: usize = 3;
+
+/// 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()
+        .await
+        .map_err(|e| net_err("latestBlockNumber", format!("{e:?}")))?;
+    Ok(n as u64)
+}
+
+/// 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)?;
+    let start = scanned_to
+        .map(|h| h + 1)
+        .unwrap_or(identity.birthday_height);
+
+    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, 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(())
+}
+
+/// Highest height this identity has scanned contiguously (inclusive); `None` if nothing scanned.
+///
+/// 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()
+        .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))
+}
+
+/// 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(
+            "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(())
+}
+
+/// The lowest pending scan range.
+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))
+}
+
+/// Remove the scanned span `[start, scanned_through]` from the pending ranges.
+///
+/// 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()
+        .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))?;
+        // 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)?;
+        }
+    }
+
+    tx.commit().map_err(|e| db_err("commitConsumeRange", e))
+}
+
+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 {
+    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,
+    })
+}
+
+/// 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 are retried.
+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())));
+                // 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,
+                    "perBlock",
+                    Some(format!("getBlocksBin unusable: {detail}")),
+                    false,
+                ));
+            }
+        }
+    }
+    Ok((
+        fetch_scannable_blocks(daemon, start, last).await?,
+        "perBlock",
+        None,
+        false,
+    ))
+}
+
+/// Fetch scannable blocks for `[start, last]`, ordered 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,
+    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
+}
+
+/// One bounded step; returns progress JSON, `done` means no pending ranges remain.
+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, 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);
+    };
+
+    // 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 progress(db, identity_id, &ScanOutcome::default(), true);
+    }
+
+    // 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?;
+
+    // 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) {
+            // 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;
+        }
+    }
+
+    let t_downloaded = now_ms();
+
+    if blocks.is_empty() {
+        // 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 }),
+        ));
+    }
+
+    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 (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)?;
+    }
+    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);
+    v["sendsRestored"] = json!(sends_restored);
+    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)
+}
+
+/// Read-only scan progress; makes no network requests.
+///
+/// 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()
+        .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)?,
+        // 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,
+    }))
+}
+
+/// 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
+        .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.
+    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))?;
+    // Rescan before the birthday (user picked an earlier date): move the birthday
+    // back so progress starts there.
+    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))?;
+    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, end_after(tip)],
+            )
+            .map_err(|e| db_err("requeueAfterRewind", e))?;
+    }
+    tx.commit()
+        .map_err(|e| db_err("commitRewindAndRequeue", 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, "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("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();
+        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, "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();
+        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());
+    }
+
+    /// 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();
+        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("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")
+            .unwrap()
+            .query_map([id], |r| Ok((r.get(0)?, r.get(1)?)))
+            .unwrap()
+            .collect::>()
+            .unwrap();
+        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();
+        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("remainder queued");
+        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());
+    }
+
+    /// 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;
+
+        let (mut db, a) = db_with_identity(); // birthday 100
+        let (spend, mut view) = key_bytes();
+        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 scans to the tip; B scans nothing
+        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 scanned nothing, so its progress must stay None"
+        );
+
+        // 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]
+    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("rewind should requeue");
+        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();
+        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)));
+        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
+        ));
+    }
+
+    /// 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(); // 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("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(); // 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("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
new file mode 100644
index 000000000..13c2bde85
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/src/wallet.rs
@@ -0,0 +1,647 @@
+//! Wallet database handle and identity management.
+//!
+//! 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};
+use serde_json::json;
+
+use crate::error::{db_err, ErrorCode, Result, RuntimeError};
+use crate::keys::{self, network_name};
+use crate::schema;
+
+/// 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 {
+    conn: Connection,
+    network: Network,
+}
+
+/// An identity in the database.
+pub struct Identity {
+    pub id: i64,
+    pub uuid: String,
+    pub primary_address: String,
+    pub birthday_height: u64,
+    pub view_pair: ViewPair,
+}
+
+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)?;
+        schema::migrate(&conn)?;
+
+        // 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)
+            })
+            .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
+    }
+
+    /// Registers an identity; idempotent by uuid.
+    ///
+    /// `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,
+        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);
+
+        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 {
+                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);
+            }
+            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.
+        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) => {
+                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 => {
+                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();
+
+                // 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
+            }
+        };
+
+        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))
+    }
+
+    /// Deletes an identity and all its data. **Irreversible.**
+    ///
+    /// 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
+            .execute("DELETE FROM identities WHERE uuid = ?1", [uuid])
+            .map_err(|e| db_err("removeIdentity", e))?;
+        Ok(n > 0)
+    }
+
+    /// Registers a subaddress. These are fed to the Scanner; **unregistered ones receive nothing**.
+    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)
+    }
+
+    /// 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
+            .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)
+    }
+
+    /// All registered subaddress indices of the identity.
+    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";
+
+    /// 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();
+        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("in-memory db")
+    }
+
+    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("add identity")
+            .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,
+            "no registration once the window is full"
+        );
+    }
+
+    #[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 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 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, 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
+    /// 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();
+        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, 100).unwrap();
+        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);
+    }
+
+    #[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() {
+        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();
+        // 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)
+            })
+            .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'),
+            "mainnet primary address starts with 4"
+        );
+    }
+
+    #[test]
+    fn missing_identity_is_account_not_found_not_a_database_error() {
+        let db = db();
+        // 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!("missing identity must not be found"),
+            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)]);
+        // Re-registering an index is idempotent
+        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(),
+            "second delete should return 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 000000000..dda7a0414
Binary files /dev/null and b/chain-runtimes/monero/crates/monero-runtime/tests/fixtures/get_blocks_bin_3768621.bin differ
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..367074f35
--- /dev/null
+++ b/chain-runtimes/monero/crates/monero-runtime/tests/live_node.rs
@@ -0,0 +1,250 @@
+//! Integration tests against a **real node**. All skipped by default.
+//!
+//! ```bash
+//! # 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 chars> XMR_VIEW_PRIV=<64 hex chars> XMR_BIRTHDAY=3000000 \
+//!   cargo test --test live_node -- --nocapture
+//! ```
+
+use onekey_monero_runtime::{keys, network, scan, sync, wallet};
+
+fn node() -> Option {
+    std::env::var("XMR_NODE")
+        .ok()
+        .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 {
+    tokio::runtime::Builder::new_current_thread()
+        .enable_all()
+        .build()
+        .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!("skipped: XMR_NODE not set");
+        return;
+    };
+
+    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!(
+            tip > 3_000_000,
+            "mainnet is well past height 3M; {tip} is implausible"
+        );
+    });
+}
+
+/// 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 {
+        eprintln!("skipped: XMR_NODE not set");
+        return;
+    };
+
+    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.
+        let start = tip.saturating_sub(200);
+        let count = 40u64;
+
+        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("add identity");
+
+        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("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;
+            }
+            scanned += n;
+            if progress["done"].as_bool().unwrap_or(false) {
+                break;
+            }
+        }
+
+        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.
+///
+/// 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)) = (
+        node(),
+        std::env::var("XMR_SPEND_PUB"),
+        std::env::var("XMR_VIEW_PRIV"),
+    ) else {
+        eprintln!("skipped: XMR_NODE / XMR_SPEND_PUB / XMR_VIEW_PRIV not set");
+        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 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("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())
+            .expect("in-memory db");
+        let identity = db
+            .add_identity("live-wallet", &spend, &view, birthday)
+            .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("register subaddress");
+        }
+
+        sync::update_chain_tip(&mut db, identity.id, tip).expect("update chain tip");
+
+        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("scan");
+            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();
+
+        // Scan throughput.
+        println!(
+            "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("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!("skipped: XMR_NODE not set");
+        return;
+    };
+
+    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);
+
+        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("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("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("rewind");
+
+        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("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";
+    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() {
+    // 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("add identity");
+
+    // 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/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/rust-toolchain.toml b/chain-runtimes/monero/rust-toolchain.toml
new file mode 100644
index 000000000..3dca7acbe
--- /dev/null
+++ b/chain-runtimes/monero/rust-toolchain.toml
@@ -0,0 +1,5 @@
+# Pinned for reproducible wasm, same as the Zcash runtime; not the MSRV.
+[toolchain]
+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
new file mode 100755
index 000000000..49b7aa539
--- /dev/null
+++ b/chain-runtimes/monero/scripts/build-node-pkg.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# 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)"
+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
new file mode 100755
index 000000000..dcb7fb9ad
--- /dev/null
+++ b/chain-runtimes/monero/scripts/build-wasm.sh
@@ -0,0 +1,70 @@
+#!/usr/bin/env bash
+#
+# Build the wasm package into pkg/.
+#
+# Requires:
+#   1. rustup with the toolchain pinned in rust-toolchain.toml
+#   2. wasm-pack: cargo install wasm-pack
+#   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="${OUT:-${ROOT}/pkg}"
+# web for the App; build-node-pkg.sh passes nodejs for the smoke test.
+TARGET="${WASM_PACK_TARGET:-web}"
+
+# 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
+  exit 1
+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
+  echo "✗ wasm-opt (Binaryen) not found; the release build would be unoptimized" >&2
+  exit 1
+fi
+
+echo "==> wasm-pack build (${PROFILE})"
+cd "${ROOT}/crates/monero-runtime"
+case "${PROFILE}" in
+  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"
+du -h "${OUT}"/*.wasm
diff --git a/chain-runtimes/monero/scripts/ci.sh b/chain-runtimes/monero/scripts/ci.sh
new file mode 100644
index 000000000..c015dd0fa
--- /dev/null
+++ b/chain-runtimes/monero/scripts/ci.sh
@@ -0,0 +1,16 @@
+#!/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
+
+bash scripts/vendor-deps.sh
+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/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
new file mode 100644
index 000000000..b25fdc7d6
--- /dev/null
+++ b/chain-runtimes/monero/scripts/package-release.py
@@ -0,0 +1,78 @@
+#!/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 next
+"""
+
+import argparse
+import json
+import re
+import shutil
+import subprocess
+import tomllib
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+# wasm-bindgen module name, and the npm package name apps install.
+MODULE = "onekey_monero_runtime"
+NAME = "@onekeyfe/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 = "next" if match.group(1) else "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())
+    # 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")
+    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"] = {
+        "type": "git",
+        "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")
+
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--version", required=True)
+    parser.add_argument("--tag", required=True, choices=["next", "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
+    )
+    # 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)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/chain-runtimes/monero/scripts/smoke.js b/chain-runtimes/monero/scripts/smoke.js
new file mode 100755
index 000000000..0d905d0db
--- /dev/null
+++ b/chain-runtimes/monero/scripts/smoke.js
@@ -0,0 +1,222 @@
+#!/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.
+ *
+ * Offline by default; set XMR_NODE to also run the node checks.
+ *
+ *   ./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 ${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('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('subaddress starts with 8', sub.address[0], '8');
+check('subaddress differs from primary address', sub.address !== a.primaryAddress, true);
+
+// 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('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('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('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('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);
+
+// 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',
+  fromAddress: a.primaryAddress,
+  toAddress: a.primaryAddress,
+  amountAtomic: '1000',
+  feeAtomic: '0',
+  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'],
+  ['a malformed review', '00010203', '{}', 'reviewRequest'],
+]) {
+  try {
+    rt.signTransactionWithBip32Key(hex, key, req);
+    check(`signing rejects ${label}`, 'succeeded', 'failed');
+  } catch (e) {
+    const err = JSON.parse(e.message ?? e);
+    check(`signing rejects ${label}`, err.params.field, field);
+  }
+}
+
+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;
+  if (!url) {
+    console.log('\n(skipping node checks: XMR_NODE not set)');
+    return;
+  }
+  console.log(`\nnode checks against ${url}`);
+  await rt.setNodeUrl(url);
+
+  const tip = JSON.parse(await rt.chainTip());
+  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.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('blocks scanned', step.blocksScanned > 0, true);
+  console.log(
+    `  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,
+      JSON.stringify([{ address: a.primaryAddress, amountAtomic: '1000' }]),
+      false,
+      BigInt(tip.height),
+      'normal',
+    );
+    check('empty wallet build fails', 'succeeded', 'failed');
+  } catch (e) {
+    const err = JSON.parse(e.message ?? e);
+    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,
+      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');
+  }
+}
+
+broadcastReviewBoundaries()
+  .then(online)
+  .catch((e) => {
+    failures += 1;
+    console.log(`✗ node checks threw: ${e.message ?? e}`);
+  })
+  .then(() => {
+    rt.closeWallet();
+    console.log(failures === 0 ? '\nall passed' : `\n${failures} failed`);
+    process.exit(failures === 0 ? 0 : 1);
+  });
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/.cargo/config.toml b/chain-runtimes/zcash/.cargo/config.toml
new file mode 100644
index 000000000..031c7fde5
--- /dev/null
+++ b/chain-runtimes/zcash/.cargo/config.toml
@@ -0,0 +1,4 @@
+# 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/.gitignore b/chain-runtimes/zcash/.gitignore
new file mode 100644
index 000000000..0a8c62261
--- /dev/null
+++ b/chain-runtimes/zcash/.gitignore
@@ -0,0 +1,12 @@
+/target
+/pkg
+/pkg-keys
+/zcash-wasm-manifest.json
+/vendor
+*.log
+__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
new file mode 100644
index 000000000..1509b9aab
--- /dev/null
+++ b/chain-runtimes/zcash/Cargo.lock
@@ -0,0 +1,3660 @@
+# 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.1.0-alpha.12"
+dependencies = [
+ "bip0039",
+ "bip32",
+ "blake2b_simd",
+ "bs58",
+ "getrandom 0.2.17",
+ "getrandom 0.4.3",
+ "hex",
+ "js-sys",
+ "onekey-zcash-send-policy",
+ "orchard",
+ "pczt",
+ "rand",
+ "sapling-crypto",
+ "secp256k1",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.20",
+ "wasm-bindgen",
+ "zcash_address",
+ "zcash_keys",
+ "zcash_note_encryption",
+ "zcash_primitives",
+ "zcash_protocol",
+ "zcash_script",
+ "zcash_transparent",
+ "zeroize",
+ "zip32",
+]
+
+[[package]]
+name = "onekey-zcash-runtime"
+version = "0.1.0-alpha.12"
+dependencies = [
+ "blake2b_simd",
+ "console_error_panic_hook",
+ "futures",
+ "futures-util",
+ "getrandom 0.4.3",
+ "gloo-timers",
+ "hex",
+ "incrementalmerkletree",
+ "js-sys",
+ "onekey-zcash-send-policy",
+ "orchard",
+ "pczt",
+ "prost",
+ "rand",
+ "rand_chacha",
+ "rusqlite",
+ "sapling-crypto",
+ "schemerz",
+ "schemerz-rusqlite",
+ "secp256k1",
+ "serde",
+ "serde_json",
+ "shardtree",
+ "sqlite-wasm-rs",
+ "sqlite-wasm-vfs",
+ "thiserror 2.0.20",
+ "time",
+ "tokio",
+ "tonic",
+ "tonic-web-wasm-client",
+ "tracing",
+ "uuid",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "zcash_address",
+ "zcash_client_backend",
+ "zcash_client_sqlite",
+ "zcash_keys",
+ "zcash_note_encryption",
+ "zcash_primitives",
+ "zcash_protocol",
+ "zcash_transparent",
+ "zip32",
+ "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"
+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 = "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 = "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"
+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 = "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",
+ "onekey-zcash-send-policy",
+ "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..aa6395fb5
--- /dev/null
+++ b/chain-runtimes/zcash/Cargo.toml
@@ -0,0 +1,76 @@
+[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.12"
+edition = "2021"
+license = "Apache-2.0"
+rust-version = "1.85"
+
+# 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"] }
+# 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 makes halo2_proofs compile_error on wasm32 without atomics.
+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"
+# Default features pull the yanked 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"
+
+# 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"] }
+serde_json = "1"
+uuid = { version = "1", features = ["js"] }
+getrandom = "0.4"
+thiserror = "2"
+schemerz = "0.2"
+schemerz-rusqlite = "0.370"
+futures-util = { version = "0.3", default-features = false }
+sapling = { package = "sapling-crypto", version = "0.7", default-features = false }
+
+# 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"
+
+# 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 but ~30% larger.
+opt-level = "s"
+lto = true
+codegen-units = 1
+# Not "abort": on wasm it kills the instance silently and the caller's Promise never settles.
+panic = "unwind"
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
new file mode 100644
index 000000000..ac0ffff5a
--- /dev/null
+++ b/chain-runtimes/zcash/README.md
@@ -0,0 +1,106 @@
+# OneKey Zcash Runtime
+
+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:
+
+- `@onekeyfe/zcash-keys`: derivation, review checks and signing. No SQLite, network,
+  scanner or prover.
+- `@onekeyfe/zcash-runtime`: wallet, scanning, SQLite and PCZT proving.
+
+Both run inside a DedicatedWorker. Native Rust builds are for tests and diagnostics
+only.
+
+## 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 never update
+`Cargo.lock`.
+
+```bash
+rustup target add wasm32-unknown-unknown
+brew install llvm                       # Apple clang cannot target wasm32
+
+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
+```
+
+`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`. `capabilities()` / `keysCapabilities()` report what the build supports.
+
+### `@onekeyfe/zcash-runtime`
+
+```
+init() / storageRequiresWorkerRestart()
+setRequestHandler(handler) / setLightwalletdUrl(baseUrl)
+openWallet(network, dbName) / closeWallet() / deleteWallet(dbName)
+chainTip() / chainTipAt(baseUrl)
+
+importAccountUfvk(name, ufvk, birthday, seedFingerprintHex?, accountIndex?)
+removeAccount(uuid) / rescanAccount(uuid, fromHeight)
+accountByUfvk(ufvk) / listAccounts() / accountSyncStatus(uuid)
+accountBalance(uuid, trusted, untrusted, allowZeroConfShielding)
+
+syncPrepare() / syncTip() / syncPeek()
+syncStep(batchSize, maxBatches, priority, activeUfvksJson)
+queueRescanFrom(fromHeight) / rewindTo(height)
+
+transactionHistory(uuid, limit, offset)
+transactionDetails(uuid, txid) / transactionOutputs(uuid, txid)
+storageStats() / diagDatabaseExists(dbName) / diagDatabaseHealth()
+
+pcztQuote(...) / pcztCreate(...) / pcztProve(pczt)
+pcztCombine(original, signed) / pcztSubmit(uuid, pczt)
+pendingBroadcastTxids(uuid) / broadcastTransaction(txid)
+
+prewarmPczt(network, height) / pcztProveAtHeight(height, pczt)
+pcztExtractStateless(pczt)
+capabilities() / dependencyVersions()
+```
+
+### `@onekeyfe/zcash-keys`
+
+```
+ufvkFromAccountKeys(network, orchardSk, accountXpub, accountIndex)
+unifiedAddress(network, ufvk, receiverPolicy)
+transparentAddressFromUfvk(network, ufvk) / transparentAccountPubKeyFromUfvk(network, ufvk)
+validateAddress(network, address)
+pcztVerifyReview(pczt, reviewJson)
+pcztSignWithAccountKeys(network, orchardSk, accountXprv, accountIndex, pczt, reviewJson)
+pcztRedactForHardwareSigner(pczt)
+transparentTx* / transparentShield* / parseTransparentTransactions(requestJson)
+transactionPolicy(targetHeight) / inspectTransaction(requestJson)
+keysCapabilities() / keysDependencyVersions()
+```
+
+## Layout
+
+```
+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/Cargo.toml b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml
new file mode 100644
index 000000000..ba2ed2a58
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/Cargo.toml
@@ -0,0 +1,52 @@
+[package]
+name = "onekey-zcash-keys"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+description = "OneKey Zcash keys: derivation and signing only, no storage, scanning or network"
+
+[lib]
+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
+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"] }
+zcash_note_encryption = "0.4"
+rand.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+hex.workspace = true
+secp256k1 = { version = "0.29", features = ["alloc"], default-features = false }
+# 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 }
+# 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: seed-based derivation for parity tests.
+[dev-dependencies]
+bip0039 = { version = "0.12", features = ["all-languages"] }
+blake2b_simd.workspace = true
+
+[target.'cfg(target_arch = "wasm32")'.dependencies]
+wasm-bindgen.workspace = true
+js-sys.workspace = true
+getrandom = { workspace = true, features = ["wasm_js"] }
+# Older crates pull in getrandom 0.2, which needs "js" on wasm32-unknown-unknown.
+getrandom_02 = { package = "getrandom", version = "0.2", features = ["js"] }
+
+# -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/build.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/build.rs
new file mode 100644
index 000000000..81c4cd075
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/build.rs
@@ -0,0 +1,7 @@
+fn main() {
+    if std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() == Ok("wasm32") {
+        // 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
new file mode 100644
index 000000000..daf21b833
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/account_keys.rs
@@ -0,0 +1,547 @@
+//! Account-scoped software keys supplied by the host.
+//!
+//! 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;
+
+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 valid.
+pub(crate) unsafe trait FlatKey {}
+unsafe impl FlatKey for SpendingKey {}
+unsafe impl FlatKey for AccountPrivKey {}
+
+/// Wipes a key lacking `ZeroizeOnDrop` on drop; moved-from stack copies are out of 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. `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
+    }
+
+    pub fn ufvk(&self) -> Result {
+        ufvk_from_parts(
+            self.params,
+            &FullViewingKey::from(&*self.orchard),
+            &self.transparent.to_account_pubkey(),
+        )
+    }
+}
+
+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 }),
+        )
+    })
+}
+
+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 firmware returns. Sapling is omitted.
+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()))
+}
+
+/// Needs no transparent secret: the xpub is public.
+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)
+}
+
+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)
+}
+
+#[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()
+    }
+
+    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
+    }
+
+    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);
+        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()
+    }
+
+    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()
+    }
+
+    fn deterministic_seeds(count: u32) -> Vec> {
+        (0..count)
+            .map(|i| {
+                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!(
+            &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!(
+            new_ufvk == keys::without_sapling(Network::MainNetwork, &oracle_ufvk).unwrap(),
+            "UFVK must match the seed oracle"
+        );
+        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!(
+            new_fvk.to_bytes() == oracle_fvk.to_bytes(),
+            "Orchard full viewing key must match the seed oracle"
+        );
+        assert!(
+            new_fvk.to_bytes()[..32] == oracle_fvk.to_bytes()[..32],
+            "Spend validating key encoding must match the seed oracle"
+        );
+        assert!(
+            SpendValidatingKey::from(&SpendAuthorizingKey::from(keys.orchard()))
+                == SpendValidatingKey::from(&SpendAuthorizingKey::from(oracle.orchard())),
+            "Spend authorizing keys must derive the same spend validating key"
+        );
+        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"
+        );
+    }
+
+    #[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 (seed 0x00..0x1f).
+    #[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);
+        }
+
+        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()),
+                    "Error output must not contain key material"
+                );
+            }
+        }
+    }
+
+    /// Parity vectors from the firmware implementation.
+    #[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!(
+                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!(
+                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/bindgen.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
new file mode 100644
index 000000000..41001a66a
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/bindgen.rs
@@ -0,0 +1,224 @@
+//! 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};
+
+#[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)?)
+}
+
+/// `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,
+    ufvk: &str,
+    receiver_policy: &str,
+) -> Result {
+    Ok(keys::unified_address_with(network, ufvk, receiver_policy)?)
+}
+
+/// 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,
+    orchard_sk: Vec,
+    account_xpub: &str,
+    account_index: u32,
+) -> Result {
+    // 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,
+        &orchard_sk,
+        account_xpub,
+        account_index,
+    )?)
+}
+
+/// 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,
+    orchard_sk: Vec,
+    account_xprv: String,
+    account_index: u32,
+    pczt_bytes: Vec,
+    review_json: &str,
+) -> Result, JsValue> {
+    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,
+    )?)
+}
+
+/// 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)?)
+}
+
+#[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)?)
+}
+
+#[wasm_bindgen(js_name = transparentAddressFromUfvk)]
+pub fn transparent_address_from_ufvk(network: &str, ufvk: &str) -> Result {
+    Ok(keys::transparent_address(network, ufvk)?)
+}
+
+/// 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)?)
+}
+
+#[wasm_bindgen(js_name = parseTransparentTransactions)]
+pub fn parse_transparent_transactions(request_json: &str) -> Result {
+    Ok(transparent_prevouts::parse_json(request_json)?)
+}
+
+#[wasm_bindgen(js_name = transparentTxQuote)]
+pub fn transparent_tx_quote(request_json: &str) -> Result {
+    Ok(transparent_send::quote_json(request_json)?)
+}
+
+#[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,
+    )?)
+}
+
+/// 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!({
+        "sign": {
+            "orchard": sign::SIGN_ORCHARD,
+            "sapling": sign::SIGN_SAPLING,
+            "transparent": sign::SIGN_TRANSPARENT,
+            "ironwood": sign::SIGN_IRONWOOD,
+        },
+        "accountKeys": {
+            "network": "main",
+            "ufvk": true,
+            "pcztSign": true,
+        },
+        "transparentTx": {
+            "network": "main",
+            "version": 6,
+            "quote": true,
+            "buildWithAccountXprv": true,
+            "createWithAccountXpub": true,
+            "combineHardwareSigned": true,
+        },
+        "transparentShield": {
+            "createWithAccountXprv": transparent_send::shielding::SHIELD_CREATE_WITH_ACCOUNT_XPRV,
+            "signWithAccountXprv": transparent_send::shielding::SHIELD_SIGN_WITH_ACCOUNT_XPRV,
+        },
+    })
+    .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(),
+    )?)
+}
+
+#[wasm_bindgen(js_name = keysDependencyVersions)]
+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(),
+    )?)
+}
+
+#[wasm_bindgen(js_name = transparentShieldSignWithAccountXprv)]
+pub fn transparent_shield_sign_with_account_xprv(
+    request_json: &str,
+    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(
+        request_json,
+        &account_xprv,
+        &original,
+        &pczt,
+        ufvk.as_deref(),
+    )?)
+}
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..6d08ee398
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/error.rs
@@ -0,0 +1,212 @@
+//! 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;
+
+/// Stable error codes. Append only; never change the meaning of an existing code.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ErrorCode {
+    /// Network is not "main" / "test". Params: `{ value }`
+    InvalidNetwork,
+    /// Mnemonic cannot be parsed. Retired: no shipped API takes a mnemonic.
+    InvalidMnemonic,
+    /// Seed is too short. Retired: no shipped API takes a seed.
+    InvalidSeed,
+    /// Account index out of range. Params: `{ value }`
+    InvalidAccountIndex,
+    InvalidUfvk,
+    DeriveFailed,
+    PcztParseFailed,
+    /// PCZT signing failed. Params: `{ orchardActions }` when available.
+    PcztSignFailed,
+    InvalidTransactionRequest,
+    InvalidTargetHeight,
+    InvalidAddress,
+    InvalidOutpoint,
+    UnknownInput,
+    DuplicateInput,
+    /// Unsupported by transparent send.
+    CoinbaseInput,
+    /// Unsupported by transparent send.
+    UnconfirmedInput,
+    /// Only regular P2PKH inputs are supported.
+    UnsupportedInputScript,
+    InvalidDerivationPath,
+    KeyMismatch,
+    InvalidAmount,
+    InsufficientFunds,
+    InvalidAccountXprv,
+    InvalidAccountXpub,
+    TransactionBuildFailed,
+    TransactionSerializeFailed,
+    /// Orchard spending key is not 32 bytes or fails ZIP-32 validity. Params: `{ byteLen, expected }` for a length error.
+    InvalidSpendingKey,
+}
+
+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",
+            InvalidAccountXprv => "INVALID_ACCOUNT_XPRV",
+            InvalidAccountXpub => "INVALID_ACCOUNT_XPUB",
+            TransactionBuildFailed => "TRANSACTION_BUILD_FAILED",
+            TransactionSerializeFailed => "TRANSACTION_SERIALIZE_FAILED",
+            InvalidSpendingKey => "INVALID_SPENDING_KEY",
+        }
+    }
+}
+
+#[derive(Debug)]
+pub struct KeysError {
+    pub code: ErrorCode,
+    /// Always a JSON object.
+    pub params: Value,
+    /// Raw upstream error, for logs only. Must never contain seeds, spending keys, or anything derived from them.
+    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;
+
+#[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,
+            InvalidAccountXprv,
+            InvalidAccountXpub,
+            TransactionBuildFailed,
+            TransactionSerializeFailed,
+            InvalidSpendingKey,
+        ];
+        let mut seen = std::collections::HashSet::new();
+        for c in all {
+            let s = c.as_str();
+            assert!(seen.insert(s), "duplicate error code: {s}");
+            assert!(
+                s.chars().all(|ch| ch.is_ascii_uppercase() || ch == '_'),
+                "malformed error code: {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..2762ab25e
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/keys.rs
@@ -0,0 +1,340 @@
+//! Public key material: networks, recipients, UFVK-derived addresses.
+
+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};
+use serde_json::json;
+
+pub fn parse_network(s: &str) -> Result {
+    match s {
+        "main" => Ok(Network::MainNetwork),
+        "test" => Ok(Network::TestNetwork),
+        other => Err(KeysError::with(
+            ErrorCode::InvalidNetwork,
+            json!({ "value": other }),
+        )),
+    }
+}
+
+/// 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;
+    // Only lowercase UA prefixes are canonical.
+    if encoded.starts_with("U") {
+        return None;
+    }
+    match Address::decode(params, encoded)? {
+        address @ (Address::Transparent(_) | Address::Tex(_)) => Some(address),
+        Address::Unified(address) if address.has_orchard() => Some(Address::Unified(address)),
+        _ => None,
+    }
+}
+
+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.
+#[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))?;
+    let seed = Zeroizing::new(parsed.to_seed(""));
+    ufvk_from_seed_bytes(params, seed.as_ref(), account_index)
+}
+
+/// 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,
+    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()
+    };
+
+    without_sapling(params, &ufvk)
+}
+
+#[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:?}")))?;
+    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, 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 select the least private option.
+        "all" => Ok(R::unsafe_custom(Require, Omit, Allow)),
+        "orchard" => Ok(R::ORCHARD),
+        other => Err(KeysError::with(
+            ErrorCode::InvalidUfvk,
+            json!({ "stage": "receiverPolicy", "value": other }),
+        )),
+    }
+}
+
+/// `policy` selects the receivers: `"all"` / `"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))
+}
+
+/// 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))?;
+
+    let (addr, _) = ufvk
+        .default_address(receiver_policy("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,
+    ))
+}
+
+/// 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)
+        .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()))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    /// Same items as the firmware's UFVK.
+    #[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 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()
+            .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());
+    }
+
+    #[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"), "expected a tm t-address, got {t}");
+        let ua = unified_address_with("test", &ufvk, "all").unwrap();
+        assert!(ua.starts_with("utest"), "UA must start with utest");
+        assert_ne!(t, ua, "t-address and UA must differ");
+    }
+
+    #[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", "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} must not contain a 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}"
+                );
+            }
+            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}: expected a UA");
+            };
+            assert_eq!(
+                zcash_keys::encoding::encode_transparent_address_p(
+                    ¶ms,
+                    all.transparent().unwrap()
+                ),
+                transparent_address(network, &ufvk).unwrap()
+            );
+        }
+    }
+
+    // Public test vector.
+    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();
+        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",
+            "compressed key prefix must be 02/03"
+        );
+    }
+
+    #[test]
+    fn receiver_policy_has_no_default() {
+        assert!(receiver_policy("all").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());
+    }
+
+    #[test]
+    fn network_parsing() {
+        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]
+    fn derives_ufvk_and_address() {
+        let ufvk = ufvk_from_mnemonic("test", TEST_MNEMONIC, 0).expect("derive UFVK");
+        assert!(
+            ufvk.starts_with("uview"),
+            "testnet UFVK must start with uview, got {ufvk}"
+        );
+
+        let addr = unified_address_with("test", &ufvk, "all").expect("derive address");
+        assert!(
+            addr.starts_with("utest"),
+            "testnet UA must start with utest, got {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, "different accounts must derive different UFVKs");
+    }
+}
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..4b4caf318
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/lib.rs
@@ -0,0 +1,27 @@
+//! Zcash key derivation, signing, and export of public viewing material. No storage, scanning, or network.
+//!
+//! No seed or mnemonic crosses the wasm boundary: software signing takes only the Orchard spending
+//! key and transparent account xprv. Secrets are zeroized and never returned to JS. Mainnet only.
+
+pub mod account_keys;
+pub mod error;
+pub mod keys;
+pub mod review;
+pub mod sign;
+pub mod transaction_history;
+pub mod transparent_prevouts;
+pub mod transparent_send;
+
+#[cfg(target_arch = "wasm32")]
+pub mod bindgen;
+
+pub use error::{ErrorCode, KeysError, Result};
+
+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/review.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs
new file mode 100644
index 000000000..3b4a30c6a
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/review.rs
@@ -0,0 +1,595 @@
+use pczt::roles::verifier::{OrchardError, Verifier};
+use serde::Deserialize;
+use zcash_keys::{address::Address, keys::UnifiedFullViewingKey};
+use zcash_note_encryption::Domain;
+use zcash_protocol::memo::MemoBytes;
+use zcash_script::script::Evaluable;
+use zip32::Scope;
+
+use crate::{
+    account_keys::AccountSigningKeys,
+    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)?)
+}
+
+/// 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)? != keys.params() || keys.ufvk()? != request.ufvk {
+        return Err(mismatch("signerAccount"));
+    }
+    verify(pczt_bytes, &request)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    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) {
+        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 = 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 = 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 =
+            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 = test_keys::signing_keys(&[9; 32], 0).ufvk().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());
+        }
+    }
+
+    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 = 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
+        )));
+        for account in [1, (1 << 31) - 1] {
+            assert!(signer_account_mismatch(sign_with(
+                &seed, account, &bytes, &json
+            )));
+        }
+        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)
+        )));
+    }
+
+    /// 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();
+        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()
+    }
+
+    #[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]
+    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/sign.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
new file mode 100644
index 000000000..dd30aefa9
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/sign.rs
@@ -0,0 +1,198 @@
+//! PCZT signing with host-supplied account keys.
+
+use pczt::roles::signer::Signer;
+use pczt::roles::verifier::{TransparentError, Verifier};
+use transparent::{keys::AccountPrivKey, sighash::SighashType};
+
+use crate::{
+    account_keys::AccountSigningKeys,
+    error::{ErrorCode, KeysError, Result},
+};
+
+/// 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
+}
+
+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 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;
+
+/// Returns (signed count, last failure).
+fn sign_transparent_inputs(
+    signer: &mut Signer,
+    account_key: &AccountPrivKey,
+    input_count: usize,
+) -> (usize, Option) {
+    use transparent::keys::{NonHardenedChildIndex, TransparentKeyScope};
+
+    let mut signed = 0usize;
+    let mut last_err = None;
+
+    for index in 0..input_count {
+        let mut done = false;
+        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)
+}
+
+/// 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],
+) -> Result> {
+    let pczt = pczt::Pczt::parse(pczt_bytes)
+        .map_err(|e| KeysError::new(ErrorCode::PcztParseFailed).detail(format!("{e:?}")))?;
+
+    // Require `SIGHASH_ALL` on every transparent input; upstream does not check.
+    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:?}")))?;
+
+    let ask = orchard::keys::SpendAuthorizingKey::from(keys.orchard());
+
+    // 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;
+
+    // Every transparent input must be signed; one missing signature invalidates the transaction.
+    let (transparent_signed, transparent_err) =
+        sign_transparent_inputs(&mut signer, keys.transparent(), 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 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();
+        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:?}")))
+}
+
+/// 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:?}")))?;
+    Ok((
+        pczt.orchard().actions().len(),
+        pczt.ironwood().actions().len(),
+        pczt.transparent().inputs().len(),
+    ))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::account_keys::test_keys;
+
+    #[test]
+    fn rejects_garbage_pczt() {
+        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/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_prevouts.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs
new file mode 100644
index 000000000..1e845c059
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_prevouts.rs
@@ -0,0 +1,122 @@
+use serde::{Deserialize, Serialize};
+use zcash_primitives::transaction::Transaction;
+use zcash_protocol::consensus::BranchId;
+
+use crate::{ErrorCode, KeysError, Result};
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+struct Request {
+    transactions: Vec,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+struct PreviousTransaction {
+    txid: String,
+    raw_tx: String,
+}
+
+#[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 parsed = request
+        .transactions
+        .into_iter()
+        .map(|previous| {
+            let bytes = hex::decode(&previous.raw_tx).map_err(|_| invalid())?;
+            let mut reader = &bytes[..];
+            // 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();
+            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,
+                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"] {
+            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(),
+                _ => 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();
+        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),
+        }]);
+        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/src/transparent_send.rs b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
new file mode 100644
index 000000000..eb8812138
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send.rs
@@ -0,0 +1,1376 @@
+//! Stateless transparent transaction quoting, construction, and signing.
+//!
+//! 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};
+
+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, AccountPubKey, NonHardenedChildIndex, TransparentKeyScope},
+};
+use zcash_address::ZcashAddress;
+use zcash_keys::address::Address;
+use zcash_primitives::transaction::{
+    fees::{
+        transparent::{InputSize, OutputView},
+        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 zip32::AccountId;
+
+use crate::{
+    account_keys::Wiped,
+    error::{ErrorCode, KeysError, Result},
+};
+
+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;
+
+#[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,
+    pub memo_hex: 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(Clone, Copy, Debug)]
+enum RecipientAddress {
+    Transparent(TransparentAddress),
+    Ironwood(orchard::Address),
+}
+
+#[derive(Debug)]
+struct PlannedOutput {
+    address: RecipientAddress,
+    user_address: String,
+    memo: zcash_protocol::memo::MemoBytes,
+    value: Zatoshis,
+}
+
+#[derive(Debug)]
+struct TransactionPlan {
+    account_index: AccountId,
+    expiry_height: BlockHeight,
+    target_height: BlockHeight,
+    inputs: Vec,
+    recipients: Vec,
+    change: Option<(TransparentChange, PlannedOutput, DerivationPath)>,
+    fee: Zatoshis,
+    input_total: Zatoshis,
+    send_amount: Zatoshis,
+}
+
+/// Local marker because upstream `Unauthorized` is gated behind `circuits` (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))
+}
+
+/// 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)?;
+    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(),
+        }
+    }
+}
+
+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(
+            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 < 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!({
+                "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_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(
+                        ErrorCode::InvalidTransactionRequest,
+                        serde_json::json!({ "field": "amountZat", "reason": "mustBeOmittedForSendMax" }),
+                    ));
+                }
+                Ok((address, None, recipient.address, memo))
+            } 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), recipient.address, memo))
+            }
+        })
+        .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,
+            target_height,
+            inputs,
+            recipients: vec![PlannedOutput {
+                address,
+                user_address: parsed_recipients[0].2.clone(),
+                memo: parsed_recipients[0].3.clone(),
+                value: send_amount,
+            }],
+            change: None,
+            fee,
+            input_total,
+            send_amount,
+        });
+    }
+
+    let recipients = parsed_recipients
+        .into_iter()
+        .map(|(address, value, user_address, memo)| PlannedOutput {
+            memo,
+            address,
+            user_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)?;
+        // 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" }),
+            ));
+        }
+        // Change beyond `TRANSPARENT_SCAN_GAP` could never be signed.
+        if change_path.index >= crate::sign::TRANSPARENT_SCAN_GAP {
+            return Err(KeysError::with(
+                ErrorCode::InvalidDerivationPath,
+                serde_json::json!({
+                    "field": "change.derivationPath",
+                    "reason": "indexBeyondSigningScanRange",
+                    "index": change_path.index,
+                    "max": crate::sign::TRANSPARENT_SCAN_GAP - 1,
+                }),
+            ));
+        }
+        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);
+
+        // 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
+                < 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 {
+            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,
+                        memo: zcash_protocol::memo::MemoBytes::empty(),
+                        value: change_value,
+                    },
+                    change_path,
+                )),
+            )
+        }
+    };
+
+    Ok(TransactionPlan {
+        account_index,
+        expiry_height,
+        target_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(&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 != require_transparent(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(&require_transparent(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: &[RecipientAddress],
+) -> Result {
+    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()
+        .filter(|a| matches!(a, RecipientAddress::Ironwood(_)))
+        .count();
+    let ironwood_actions = if ironwood_outputs == 0 {
+        0
+    } else {
+        ironwood_outputs.max(2)
+    };
+    onekey_zcash_send_policy::fee_rule(&MAIN_NETWORK, target_height)
+        .fee_required(
+            &MAIN_NETWORK,
+            target_height,
+            std::iter::repeat_n(InputSize::STANDARD_P2PKH, input_count),
+            output_sizes,
+            0,
+            0,
+            0,
+            ironwood_actions,
+        )
+        .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 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))
+}
+
+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)
+        .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())
+}
+
+/// 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,
+) -> 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 expected_child = expected_account.checked_add(1 << 31).ok_or_else(|| {
+        KeysError::with(
+            ErrorCode::InvalidAccountIndex,
+            serde_json::json!({ "value": expected_account }),
+        )
+    })?;
+    if u32::from(key.attrs.child_number) != expected_child {
+        return Err(KeysError::with(
+            ErrorCode::InvalidAccountXprv,
+            serde_json::json!({ "reason": "accountIndexMismatch" }),
+        ));
+    }
+    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 {
+    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 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()
+    }
+
+    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()
+    }
+
+    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 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] {
+            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_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));
+            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);
+        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_account_xprv_json(&request, &xprv()).unwrap())
+                .unwrap();
+        assert_eq!(built.fee_zat, "15000");
+        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();
+        assert_eq!(
+            build_with_account_xprv_json(&request.to_string(), &xprv())
+                .unwrap_err()
+                .code,
+            ErrorCode::KeyMismatch
+        );
+    }
+
+    /// 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 =
+            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", "surplus must all go to the fee");
+
+        let built: TransparentBuildResult =
+            serde_json::from_str(&build_with_account_xprv_json(&request, &xprv()).unwrap())
+                .unwrap();
+        assert_eq!(built.fee_zat, "12000");
+    }
+
+    /// 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 =
+            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 =
+            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_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_account_xprv_json(&request.to_string(), &other_xprv).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 mut encoded = XPRV_VERSION.to_vec();
+        encoded.extend(account_key(&seed, 0).to_bytes());
+        let account_xprv = bs58::encode(encoded).with_check().into_string();
+        assert_eq!(account_xprv, xprv());
+
+        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();
+        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_account_xprv_json(&request.to_string(), &xprv()).unwrap();
+        request["recipients"][0]["address"] =
+            ::from_tex(
+                NetworkType::Main,
+                hash,
+            )
+            .encode()
+            .into();
+        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_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);
+        assert_eq!(result.spent_outpoints.len(), 1);
+        assert_eq!(
+            result.raw_tx,
+            "0600008098b684d85b16a53700000000f4673500010100000000000000000000000000000000000000000000000000000000000000000000006a47304402206be3be8ac1c9bc252843c9ad8a1f1d41f3e7c0716217078f44ecd819f7103bc902202bdd61b62d35d0be08ca15b558fd01d4c076102584a03371d3e064d0b856bea1012103db98d8f87716269ed31879aef19bdadbc869a9ea67729e36332d023b916cbcc9ffffffff01905f0100000000001976a9148d484bcaf1d7993da6db4cca2c1517e1cf020ab788ac00000000"
+        );
+        assert_eq!(
+            result.txid,
+            "81004865cdc4217f34aafd1d4b307b3cc5d60fcee7afdb4a829983d394ae39cd"
+        );
+    }
+}
+
+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 crate::keys::supported_recipient(&MAIN_NETWORK, encoded) {
+        Some(Address::Transparent(address)) => Ok(RecipientAddress::Transparent(address)),
+        // ZIP-320 TEX: only accepts transparent inputs, which is all this builder spends.
+        Some(Address::Tex(hash)) => Ok(RecipientAddress::Transparent(
+            TransparentAddress::PublicKeyHash(hash),
+        )),
+        // Orchard receivers get Ironwood notes after NU6.3; never fall back to a public 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..c25de416c
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/src/transparent_send/shielding.rs
@@ -0,0 +1,1450 @@
+//! 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;
+use zcash_primitives::transaction::builder::{BuildConfig, Builder, BundlePadding};
+use zcash_primitives::transaction::fees::fixed::FeeRule as FixedFeeRule;
+use zcash_protocol::memo::MemoBytes;
+
+/// 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;
+
+fn failure(error: impl std::fmt::Debug) -> KeysError {
+    KeysError::new(ErrorCode::TransactionBuildFailed).detail(format!("{error:?}"))
+}
+
+/// 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))?.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,
+    ovk: Option,
+) -> Result> {
+    let mut builder = Builder::new(
+        MAIN_NETWORK,
+        plan.target_height,
+        BuildConfig::Standard {
+            sapling_anchor: None,
+            orchard_anchor: None,
+            // No shielded spends, so the empty anchor needs no commitment tree.
+            ironwood_anchor: plan
+                .recipients
+                .iter()
+                .any(|output| matches!(output.address, RecipientAddress::Ironwood(_)))
+                .then(orchard::Anchor::empty_tree),
+            orchard_padding: BundlePadding::DEFAULT,
+            ironwood_padding: BundlePadding::DEFAULT,
+        },
+    )
+    .with_expiry_height(plan.expiry_height);
+    for input in &plan.inputs {
+        let pubkey = derive_public_key(key, input.path)?;
+        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::(
+                    ovk.clone(),
+                    address,
+                    output.value,
+                    output.memo.clone(),
+                )
+                .map_err(failure)?,
+        }
+    }
+    if let Some((_, output, path)) = &plan.change {
+        let pubkey = derive_public_key(key, *path)?;
+        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)?;
+    }
+    // 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)?;
+    let pczt = Creator::build_from_parts(parts.pczt_parts)
+        .ok_or_else(|| KeysError::new(ErrorCode::TransactionBuildFailed))?;
+    let mut transparent_index = 0;
+    let mut ironwood_index = 0;
+    let mut transparent_addresses = Vec::new();
+    let mut ironwood_addresses = Vec::new();
+    for output in &plan.recipients {
+        match output.address {
+            RecipientAddress::Transparent(_) => {
+                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)?
+        .serialize()
+        .map_err(failure)
+}
+
+/// 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,
+    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))?;
+    let fingerprint: [u8; 32] = hex::decode(seed_fingerprint_hex)
+        .map_err(|_| KeysError::new(ErrorCode::InvalidTransactionRequest))?
+        .try_into()
+        .map_err(|_| KeysError::new(ErrorCode::InvalidTransactionRequest))?;
+    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(
+            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();
+    updated.serialize().map_err(failure)
+}
+
+/// Verifies the device's signatures against the exact request before finalizing.
+pub fn combine_hardware_signed(
+    request_json: &str,
+    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 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()
+        .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()
+                    || !crate::sign::is_sighash_all(input)
+                {
+                    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)
+}
+
+fn validate_ironwood(
+    bundle: &orchard::pczt::Bundle,
+    plan: &TransactionPlan,
+    ovk: Option<&orchard::keys::OutgoingViewingKey>,
+) -> Result<()> {
+    let mut expected = plan
+        .recipients
+        .iter()
+        .filter_map(|output| match output.address {
+            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 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)?;
+        let mut approved_memo = MemoBytes::empty();
+        if value.inner() != 0 {
+            let index = expected
+                .iter()
+                .position(|entry| entry.0 == recipient && entry.1 == value.inner())
+                .ok_or_else(mismatch)?;
+            approved_memo = expected.remove(index).2;
+        }
+        // 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,
+                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)?;
+            // The OVK seals only `out_ciphertext`, checked below.
+            let encryptor = orchard::note_encryption::IronwoodNoteEncryption::new(
+                None,
+                note,
+                *approved_memo.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 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() {
+        return Err(mismatch());
+    }
+    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();
+    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)
+        || *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() != 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 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)
+            || 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 public = derive_public_key(key, *path)?;
+        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| {
+                !crate::sign::is_sighash_all(input)
+                    || 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)?;
+    let verified = if has_ironwood {
+        verified
+            .with_ironwood(|bundle| {
+                validate_ironwood(bundle, plan, ovk).map_err(OrchardError::Custom)
+            })
+            .map_err(failure)?
+    } else {
+        verified
+    };
+    Ok(verified.finish())
+}
+
+pub fn sign_with_account_xprv(
+    request_json: &str,
+    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))?;
+    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)?;
+    // V6 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| !crate::sign::is_sighash_all(input))
+            {
+                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 xprv() -> String {
+        crate::account_keys::test_keys::account_xprv(&SEED, 0)
+    }
+
+    fn create(request_json: &str) -> Result> {
+        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, None)
+    }
+
+    fn transparent_address(scope: u32, index: u32) -> TransparentAddress {
+        let key = crate::account_keys::test_keys::account_priv_key(&SEED, 0);
+        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 account_xpub() -> String {
+        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());
+        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 = 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
+                .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()
+    }
+
+    // 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);
+        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(), "surplus goes to fee");
+            if hardware {
+                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");
+            }
+        }
+    }
+
+    #[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),
+                None,
+            )
+            .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), None).unwrap();
+        assert!(combine_hardware_signed(
+            &request,
+            &account_xpub(),
+            &original,
+            &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, 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)
+            .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, 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]
+    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), None)
+                    .unwrap();
+            let signed = simulated_device_signature(&original);
+            let finalized =
+                combine_hardware_signed(&request_json, &account_xpub(), &original, &signed, None)
+                    .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),
+                None
+            )
+            .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),
+                    None,
+                )
+                .unwrap();
+                let signed = simulated_device_signature(&original);
+                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());
+                        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()).unwrap());
+                assert!(combine_hardware_signed(
+                    &request_json,
+                    &account_xpub(),
+                    &original,
+                    &changed,
+                    None
+                )
+                .is_err());
+                assert!(combine_hardware_signed(
+                    &request_json,
+                    &account_xpub(),
+                    &original,
+                    &original,
+                    None
+                )
+                .is_err());
+            }
+        }
+    }
+
+    #[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), None)
+                    .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),
+                None,
+            )
+            .unwrap();
+            let from_redacted = combine_hardware_signed(
+                &request_json,
+                &account_xpub(),
+                &original,
+                &simulated_device_signature(&redacted),
+                None,
+            )
+            .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();
+        change(&mut value);
+        serde_json::from_value::(value)
+            .unwrap()
+            .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()).unwrap();
+                sign(&approved.to_string(), &original, &original).unwrap();
+                approved["recipients"][0]["memoHex"] =
+                    Value::String(format!("ff99{}", "00".repeat(510)));
+                assert!(sign(&approved.to_string(), &original, &original).is_err());
+                approved["recipients"][0]
+                    .as_object_mut()
+                    .unwrap()
+                    .remove("memoHex");
+                assert!(sign(&approved.to_string(), &original, &original).is_err());
+            }
+        }
+    }
+
+    #[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).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()).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(), &original, &original).is_err(),
+                "{field}"
+            );
+        }
+    }
+
+    /// 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);
+        let request = request(false).to_string();
+        let original = create(&request).unwrap();
+
+        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_account_keys(&keys, &modified)
+            .expect_err("non-ALL sighash_type must be rejected");
+        assert_eq!(e.code, ErrorCode::PcztSignFailed);
+        assert!(
+            format!("{:?}", e.detail).contains("transparentInputSighashNotAll"),
+            "expected a sighash policy error, got {e:?}"
+        );
+    }
+
+    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
+    }
+
+    #[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).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, &modified, &modified).is_err(), "{field}");
+            assert!(
+                sign(&request, &original, &modified).is_err(),
+                "prover {field}"
+            );
+        }
+        let modified = mutate(&original, |value| {
+            value["transparent"]["outputs"][0]["value"] = 1.into()
+        });
+        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).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, &modified, &modified).is_err(), "{field}");
+            if field != "real_spend" && field != "output_value" {
+                assert!(
+                    sign(&request, &original, &modified).is_err(),
+                    "prover {field}"
+                );
+            }
+        }
+    }
+
+    #[test]
+    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, 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, None)
+                .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).unwrap();
+        sign(&request, &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, &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
+        );
+    }
+}
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..16c10789a
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/README.md
@@ -0,0 +1,11 @@
+# Previous transaction fixtures
+
+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.
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..6c30536e4
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-keys-runtime/tests/fixtures/previous-transactions.json
@@ -0,0 +1,12 @@
+{
+  "transactions": [
+    {
+      "txid": "69ff03c1e3d19df98087396f86783addbc9f8ad615022efdeb5de10fe78597ae",
+      "rawTx": "0400008085202f890117699175d8be6b17f152bffd0989847fde1f079b5201f363d76a6e0e3d175e85000000006b483045022100e18e7e7f1f91a3b2801b12cbaee85ee23d6723a3f7f608162eee668f6c99cee402205056b948b456858b58ea9204ed4c34d6ec9d6c836675bd30d3e621485946f9ae01210223fa326a1f5d5c85b9cb6a8b574ce828b38bb3bcc789da448f2f66f6731d3ca7ffffffff0200e1f505000000001976a914aea70bc6d77fe2369ddb9a8758e3bbf83bcef96e88ace0789408000000001976a914d5af23c4d585c1496fed2e88582473e97de851eb88ac00000000ff64cd1d0000000000000000000000"
+    },
+    {
+      "txid": "70177881b2a62c93ed023725a24166362a5bd65cc93dbbd3b3a243ff5927d89c",
+      "rawTx": "0600008098b684d85b16a53700000000890a35000001e8030000000000001976a9149564d9fed247986b15a2f57d0b3b032eeb28476c88ac000000027dda7edf24fb49e6a688abafea52dbbec2cd9427e20f8c97b3ba25c8a8fc73266a490b5f302b639afb45648c5b3c0f3f3f63ea52ba79a71a29e38eca0ede5f3af17b0377cca55ff5253226ce8f67acd7609f64c9873ab177e670465ded636e8c865cf3ebc50965b00a1b5dda951a67612b87656a58bc2c730c64e9df2c2fd02a276014bc0d6744fe10f51e65d7d7df44c699c6e0a621c3a8c67e4a609401c837c4409a7023e4f41400e87d1711e86277bd8f3898de56bd2a85f2f7742f19d7e5f49a66ad8049dff2321ce9201ff9a765897e5396f31e513367b150128b32f15db70e5f6286082dd50f571670515c000299ffd755c2bcf9ddca1be6339ac602496a6cba5ad769df8feb4a374d63328f1e3bed5b66ebe772e02988426b98bf44b01dda5a4a021e07f1b0327a0612b170ee0671dac959eb029e43d6b5f4d00e6bb29f77728c82ccdfaf6341e6563d17b6b816b03ad3d1a78c8378ecc5eda98cf7c69f2bfbaf3a1f4a7c5de7ebbf39622b59d6485189ad03b6e2cb5aa87cb4df73dc6b39071bb9ecd1a888fec04b428aeb6bbd33aca58f4f6f2a6eced4ccf123c6ac686883dedd1ef96856cfc4a58ad9272165f24ba4d1e9cba91d30aa1d2ec9d0d0b3bb0a06e925f460a88b129dce20499c07a3ef02388475d8314c41142515d37338f9b9312e2c14a39b84f4586867717e94f5ae6719922cc3480efe7aedc30a1d915561418d6c9c74fe4925fc8218a9a7a698374d958cfa569d57b3c6da21ed0a2bea669412086294a2bd325d37f0887aeeba5b93b9f738c51f6c4f28e0c770016c38ef9241fad5156c28870c36e469897405464e0ab00cc6eb0a30effe00c651a9711e0fed404ee0a30b61f0d775e56fed9f8e37c3d51aad0a55fa81a11bcdcad13dc11c5e1fa21b972481c1686fa6751e62ec580bb64b3947f80cebbf0e40fbe3881d235519df44c22aeca9fa83bb651f2af6db786ec019b0c176bd91be04b3e67c1e4ca44dafbcc3a6418900f759e7f9ae206110a0ab3d74c020c52d90463b76de67b9ed8384bc5265559e9f8b33dde4d966d39d955e356af6b22ca19dc7635f5536eb13d90dd3fbfeaa36d8e4c1108f69b7d1eae71391ebfa9b4ebdb844de3799d4a7bfa10a22d1dd1952867f003091c33b1cee25aa0d3dee777f061c9a66fdf67dbdf033fd6d59d09a89fa25235f74a4ad06094e918ea7d62851a1ccf8e3e8affc1ecf1bc711a98dffdec8458f745fcc5039e411e337275ed0066d6ab6fb569a82f4dda789f4ffbbf5a830550ac5d354622337e7107b5df60c32ef03ed0db5ee9298040c13460cd685f8c4c100611cd65e2ff2881328cc2f5e736d748d363edc82377f25cd70b5d48c0793f949631ccc5f378a391fa575e0744ab7e257ba8a5a978b05007a0fb15e3abf8a50df69f96df3d697a75dc4e1e21ebcb4a0b1daef6d78450c797325c8ca9fd8188920976f7102504f0d3ae3234afbd44147efd345f297f98e74d3a096ba215cd0d776c02c88bdb72fac4c774f20a68cf82bc2d04f871246babaae626b60afc1fdef99697eb2a82f5687bd9abd6cc6c863fe5a5dd77fec6fed45f53355ac46f690b54f6bc28ba2ef8a1403b55a66fb80eb9691f289a76296d286ecca2d0ae4fa285f68923cf050e6940121e0f827a2f045c3a560da7d3b8de2446391311cd62a0b06d4a7523caca47b4ddac7ce589a88d832c371e5d8405a69d4f3ad412c786234cff667d6f3edc61fbb82711ecf2fe83343aca77c46083b648fa80a6cb5f4b286b3ac8cf3ae6490d4e07d89b2392bde4a0fd1f487f79dc8ac79ff201b1b1d677fcb131bf15bd34a4a84730608849d4df0b69cb250dbc3fa41c45ab1842037cbd1f2996d8b1729d3443eaecd8150e3efee9fd77693cb16ef3a69956842fb257066fdc513e0dde5617fab5ac2132474abd6654d4bb5341f443bc4ff1462b3cf47345c07764ecc6639d5175dd6e2e9edf13e572735dbe777514fc21af8fb6ce0621c369a98f46d0d0b8f4f99f30019b27299b260aee22fb15431ddf8c34661fb213c94536e2846d35dcceb3276ba194c0021094a9cb80cd2915fc8eb8ea9c9c6824cb2bdba23ce7891656d0e717f998e0c9596d7f28baba07ca47b4c5377d37b615c4af34429cbb8eeac49bc809a8a571851bf8a9e5405ea3431e2a4d710b97f90639e04e3126359623e35130832730c8bffdefe0627bace75ca818b76aad897ae0dfb326e3a5e1128677dff7b82aa9d0b0e3f2c94be5fe02f1abf36489b1af8c29f7f9c62480c5cae51747705b1c8662cb5597bd3fe3f6da67701768307803e000000000000b42479f6f64477396fcccb0b672bd0722b5345689122677ff88385970c3acd21fd601c3b83828b7d5c5bf64104c3d38697068121167a2cd5b668ba4cb1f24b9c68fc1eb38304a0193869aa3c3951d7554b3a97b16f7a3b6ef65d0f6d1356cd471021ac66ddcfb1a9c878d9f96ebc1702b77f753b014535993d191b886c424ad47b9d1d80e8def985be67a9a210e5eb138213b59ad354676f283bd270868d2c411d3313d5f7c3e6c24a3783a23471999b875715e9425e3405766848dccbc8cbc115b0028f91a0f6332759a9f557355074f8a837a1a301deae944b7c7a39d01d1795232cebc29ff5379ebcf821621eab1847d22fbf12bc2684a7d0f272644278e2a1f88ef9ba1ed5db23d07185bdacd3fc962ad39ceb94f2bcec114944e532518be2631e329c2aa4ddcf06d9f9d2a79a4f2d0d956ab118336737813b7f2351634bc2a9a98d5cca035c13599dc78e343543d0dc80877485fbf9d9b9021716335c3a4c2c1e58709c030279727510829427622c56e0f5e999554c897822dd758620d111c904599a11432174df11f53ae8ed3191ba7611315409387beef3e8af18f3c786f1bba129a9be24e87a9dffa301b65eed8e6be08dc68f2f72c0aac233c098eb336a808f213afffee343af4b1c4bd9e3fed0ceb861080a2f9e3acbf3022a18df95f882aa042f8cbb7d709d01a2f52bf3736917c717074b55c08d8a6e87316c7b1a7787c62a05ff29d8300fd80b1ccee432333681c5b9eb759ed356f3ad14ae07c88b04d479d9ecbe74c156a48f693299c3ff23146654d773146dd44924a7c7b287f1a58c0037fb3f5882f48e02211a581376b30644075ae39e893e724339a1dc2977054832b7238474d790523969b792950da430d3a17c8d2a1d4065ea006d14040d830cf70bfbb4072211c4b1f25f66fcd1d5a66a7276a0e07edc7bb77b64d5b03aaa0620257ab00b54fd616db1e60e8ea3f9ab4819f028025a281087e6b05c963e22f8b78d8d2ed8f0ed14d1aafda605bc3c9cd9b929a42c33b26464d97192d1a88a89baab2d63f909fcde7758c427ded63b718c6625eadf6bf2ee591831dce08d9604eafb855eaa3d456b97d3aab185fd718581e642bbe1c5a2dcfdeab2f1fb39b2c419d89a49c1ed3c7877256cf47f61b0a9edc838adcdbbeaca6b30dca3e5bba3d7176ae2db5ed38b5af8a99855557d49d427d0c5a2c19a844e8f441a9dfb551034f68619a422ae9e397b0818fb994f29e83a6299874058b7077f80eabac921baeb9960b2466ed2cdd9870ed49a6df8ce663bf3220c61bccfc8dfe66a5190d6bbf2570a9396071195fec6741daf64f2bc977da2d5b250cb0e420c1e4e9d538a2562b9d3175256a16fe8b94215fb92d2594095b183e81cd4285f22e1a62e9e149eab486fff3d29d10488043c21d5eab0b2f127ba8ffcd0a1c6c63a94acb8fcb2014ba3460eb52ea0b0f12d121a2eabfd6f0ffd2b0be7a5ac7794fd4563ebdf7d1cdbc688c380f6c9e8131976f5cf052bdff2a646f09467c4c9e654112a4f52c63c838a6409f96b401ed7358274ee5ffe0367f20b200d52d68ad577db94e51cea97bdd86fabdf08cbd4eb98865b464ce30e4d9ef6e4f0b17e911f7307cbe43a5dba0cbbacec902a43206ee43e7b212f4d752e768387116c770744dc7c4f3363d09128fef6329b61c081dc175b3ccebbea3047185b3db0e497f8ffe6d72e98af1a0d37a077b4f5c8432aa1d428d3e5efabe6a982d0cc47d2632363c44dd90bc08217a9b81b81fd15615c65e67ee7c8ba149bb2e0d8ebfe9facd2d7fdeb230fb3ed1fda983b03dfd6d647533781b88b78c5ae6c9d1656c7ad509849de5ddb5edc072e95d202a0ccaa8bf6239cc0d18de583b4ee3542a6e37b10ceb4ad586f87c7a6a749b751bb132b823f2db7009ee37994f05afd2b75e5d205ba336f524fde24c5935b64252b7145b08dc2383dcae6cedc77c9b7c3ada777c091524edc08bbaf798095a87de7957747ba7b1812c0930463fa183fb96991c4c43c69e34411ee6a9c3c83e2c630846e33b1b4224297715d6902974635d56daf1f0e94a649b1a95e7c319aa42c690374767026c74973f1c97035bbe8353c359b4bb0295615702f0b39336078c2e1462aec15e73021fd8db9a9c3905f73d51b61c1e29566b319981715823c848a2ad3bb001186b7290a19072ba1ce44a259abfafa6c462fbeb39c72b085c03a965c42eb25ed2c0853e3646e014ef0bb92c486f8bf4dfed50e8bc9043130486dee297732071dc7079d4b1d24b2463e6c730db78602e80d0ec843ed5e540111239b733bc81c870475f9e43c071168bdf0e022a5cfb0aa69977078fe78e30b44a5cfe205d4377816c143f6cb2bdd4881cf645e28aa32ca2f51f90c8aac47ac08b4443bd90d5db0713bd60a16d6ca540b48506ad3a7ed62f359193fe1cd6e36df81a50d17c714c096679d9462366d8467c29153dcb6f270c296407b008565013946e6f20c65c21f7f6dc4014ccd8b92461588c801082aad19f0c8f6f658683f30dab9baef74080825a10df950c0e0c2751f7bf3d9d500ad65eb7ee6817a6637474fc40f480e796ea8e40b58c69b6447116962d148292758a5955f468fb8571128a4e3921b8d898a60a6fe9d402af3f0be25f051bc98bfafa47017e4ab4a05346fd155f638f1686e9e5d54946f9143cbc7988f384050adc985bee40d98023326dc6b75a07eac8f6d16bd3cb7af2732321bf3586991434a12503f066ec17ca328cc718f5937c4b05c161da30c2c75476cfd9f0c42ae4ab8ee0da18e7347ae5a360167abb145bf2b06af8739b481d8a55594cd8653f29b63fe2815b9227f62550fb1b21b8c36763d756492736097bb834b9b6562b683c41e0eef5be3b4d28a210430782dfa8bd21f159aeecb5e0c8c359523bbe727124172090620ed1616ed552628d0dfb0e760124ae7906e868aaca9045c5977c8769d31d11512a0f96b6b84355190209eac3cea45cf052799f4596d08773c5b2ea09f6e5d56004f77d0603c2bd2b19624f02e2d1d07db4c74a43b67f6ad56b4f77883929e2e12e1a982b7053d976f847f1db062ab8a57b1ee68dab848606207be9ae969cb0321a56d4aca2a0e375b8cd20314d9f8e52eaa0a4f4b013ef5203573e0e4a61b5a2917ede0fd0e009755f83879325a8cd6bd819a4e9f1e6b982da9c52a102c1b1458f80ec499f73d9cbbf515e00987a2dfeb41be319d8a397cc032a46ff6ef211b07a47e79de772c8712d430f64b504144a0246d38690c54838105f9b4037fa54898353e8b099801df711ab9557b7a5f60f1042e4f377c8337f4962d709264d7e85741674f464c146133e17d7116ac255cedd627cc1cdec802c76f4e1875a9fc60211cc8946c161914bcd46993c46157367c66b2a8ef6d8e4fedb7ea345f6ce6a421b7705bbe093c171f0b8f9867534db5168acaa9f64aefd9c4fd0a0732adca3342a28ad74dd93e89210500993cc87ad77db797232a52b4d1b8ef38791c03913031732d3bef85228fb28c5c8694c07ca6d8b2aa65c098aea31cbdf37479a1da56f44a9dca0160284de0a9fbc2b41658545dc7386d16947299425c6ab691acb6c5818a57a4df1b28fac918e39f26e7fa532a86f7a567f60482d85201b6399cf30284deafd55a6d21b5a7a62684be72af5c1788b4712524214c394c246a6c0046d9687a9b145b522416899c355e29e7a467bca5ddff45041155bfdd17ed786cc2ce44c6f6f1510e1c67aa38f84fca1009299bb7a1cbf8ebd2cc3cf75111c26e73db5161a13d0e6d19155540ae59218d245ae7ea0ff2f46c84665fb5240ae6f8629e267a4a4d170e0b34a6d2ec75c97b93c072f9c7923ffbd4e441c21442e3815607973f3afa2aaa1ccac11f2ef4e2f6a64f8523b8e98c2b7d0e0ba8893cc9141201ab4d54705d27141a60c60667210069de569136502b081ecfb316459191e2b4187a9dbff8e0ca3ea3cdee1347c6bfdce84958c7d164d228866e538bbe2404c2aecb042f3b9b782710f697141b4b9b26c046c91459bcfd501f255315218169b220af50a851843c2839f1706eb7c54cbcd015612c1878a7afc727ea5f58f3393f8de0ec5f1cc26a39d70702650b21a5c14e445198d33cf0787c5b0c6e83022ba7bfb660f58296fe1ae59763258d0b3b6ac0f467d5763af9edf70d18e666ca65cfdbe9aec833b4ea18a2a6f0d28b6f5ff32d4ade7ead29df347a164df943891eb1b34fbe93b041ca07a978912d815de398853b00f756bd286e376a290d8f0b15f6fa2329ee5a6694380988f07e1d6fbb8a4fb22569cc844b9c6ec0c90e59dbe9f721b3035ab85f2a2d8cb2c4833f31bdbcd6bc518f5b14f5b1d69088322fc4129c0df1538e8eb61131eb0f9b54e1a406eace2accbf0c1a44761fae98566bc10839a1f425cd4facbc3f5b813fc190360f8f416059881ff1b7d3bf4beec132046936cae4d207da7fcb2a592a92d8c520e4fc8158415b1ca55e2745464d5a02669ecf7dbfffabd1d896037b476dac3a548f2c97a68648d96d85a4e247953c8dd357b8250eea2977d8c33c0a0e1f7d27af835eab8552bf6a164920c4a4d78c825410a2895e7c744d12af2ed0d9c4955962bac58078357517bc57285fb30a683c27f3eabd237d89566194123aeef8ff6de2d45617e445fa21d9ff69e77c501474dcd852e91a8301bb62dd02e5e53b13734e6217009fae1e5fa755f67e497046281434a05a64f14233299903b82b9f1a8e824348d3086cfc445c228038ea2fb8571f0f7ae4efa9a1f05eab1cf4672a5873bacaf5ad5e1990904b8cb0cfe6d564ecf3f16e1aca77945faecc088c18a26bd5f163e7f71aa56aa9ed9feac697a30c5b3e5b2dce028f3d2d37c803d7379ea90cf47ed6d2e7f813f2983105025d04449fc14a98275ad8599132d71299de8297d626e964535179a471e2d86d68d3b620783f62d6a94d052aff09160cbde576a27c58ee59a0d44c7a02de86d0b88dfda8ed8c3429477d798fbf798922e02516d601514c0f2b351515574ec5eaf7be6d3ee7e9f5e525bb89959b39c21cc550dbb1cec0e01f57be9f7cae57bdaf1642d647e181077701f92baeead14b20434d01c73f2d62e6897346552c18e3bbf34e9d28b49795c74199e9c1855a1816fd745e4b5ffa0f5e2549d4503467366a8ce1a859d88cb332e3cd9ba15f21e43d6eb369f71c696d81f6f1fd93a0dca5fb8cba57ddc78b6c82be07319716f0d6250ef2ee201904707f3e9d5994b32011e36f28ada05feffa000330638b65faf92f7ec9ff45648cf18c38301157314823ba9ae0ffc249a96a470c4f8f3d65c3981e1d2c0c384259801441d3407d46d515a9769b87a18145c44ca444759c445ecc07c5c24e544533129b46036ab79a667dff224d9d6ab2ecd5825008297c8d99b6129503764bbf3a058751843d6b7fd14a22843efc788d0cacdc4ec0ee55dd63353157e283aae339349dfa92ad575563aebb49d1697d57f944831300e34e5fc2fa1a9b45cdbc48a56e98d2501a461a0a56c4861fe8ce74f677b4a93936878b55112f74c718370e78b32bdc99502e772bd9fe4cb87a9feed1276c295fb4b11578c30c6d7671e815a0caa93ba5c33f9c3de7885ef0cdd5ef6e3e99b733eb89fb3234067ecf6174fa0f82f0b1c9d40b0f092627e137e4ad1e26111775b369105f8ba3090f29eef5925bea27c333450ab6b516cd48352cf3beadc4b62e81161e41ec2c09ba797f0d284d93707e4367c7f32b10cac164c2305fad5423e68813ed36fb6c345f7109539f9d27dfc72870a542603037d326972f1807a308e9c28af06d14473ee5576c342c2740018ea87a8f3999bab84407233c4f08ba0a08f0a47203164208c5fb740256b99a22ac00d40c90d20271684c45984a6cb4688cff5b5d82e1c035ba7107d05024f03ce8eca0001fefb8958d6718b702b8ec11271d9112bcb5fc0269f3e081f12848a278312773ac26ba715776029f3a7b664aa94bb83e31deee3f6510baafc40f660fab24a868a6f4a8fdf138bc5466bf2603054746a14032d70772a0f8f8f4877b0bc5dadfcb921bd578b5db5ca31a2be63d252bb8131200b91db7cd9014a1e716436303d2776e236ed4760f8c6acc69b37a81301e8521db022da4818a74f47221ed72d21d07a6f1bc20ba1331e3cdc71069b29aa9bd9e826f28982ea698170472c5a20cbb8e5991b34e2c505248586946d4e4b65f8b3377622bf23eba40ba651005ae0e32a4f1cb7d0ca3505fe39b90786c973c1d886d6375024437e3e6d833fd454acc15658376d1396a3a21997cc46ced4fd83c803343551a91a3b75acc540fe56ee62780b40c3a79de268726e4e572a1eee60429394b0a3884f1cc64e5ef82d406aad1c18484b0680ba59032a0f4dcfd004ae367763537311ad387151ded692c2065e4b286b35c572ff3b9852a69eb68683ccd55caef791abae7bf36134f92981584b2a972bd2b91fbc59c2f92d35e803cc1423011d9c41675d2ae610ff83d97fd5f3870bf370272f0cf8e0bbe0d69dc7031d04fcf348303c8ad1ee7c20f97cae3caee74b3775674a74e31e7c2dde4b4778f31e402cd1b04a993d2b09288df969d50910da2c7572e2ee03c1d8c8e060ec80bf417c214cd151d9b9a28a0bfa00128b781977a6ae8517ece6d081c1e7f5d54d810539032e6096d962915cb6bff796e927ba97909767bb059a0c110fdbca0a95152a9dd4c27248a410ff89d0103cb5414d88533bfff4e7ce114c84ab689c40917910b6f22ff03795d6d474cf354b9017232dd8584777663b72454e7b0e945d02716a599294f2b4a216c4172f9f18aff43c521dd34e60f3d1edada40318e3eaf861b26d9087b1dd8000224b403560d8991ab803c1ebee29c0db5fc15cd0f1ac61cfe2ed847951e4776eb88f65aed9a72f5b7529c6c9a051948994397e920cab00767140bb1c603af77c29be810741a7507144aa2665b9c87a88169cec50dbc413f74e711480d34884a312a60d8790b24b44d59904faed3df28d71f4d0fa4d9f1233a6f8511d718032eb042e3b627fc46f51e1266fb7171ff87202c1175723f9e50538bd6c2fe11be731fb5e3f72eafe6b86772d1e73ebe02fd8d2f1468fbbd3643b1f881f4441b92b7d4ef505518cdbc4a65fe1537dd8825d5d97c352fdd53136118612415a107c16213b2b503fc4717cb55b3bb352443a8ce99c40905ac296aeb25e18fddae1a956d49042973e4c2e525059e353258606953461a3e736c1cb93591feff9b3e3a4823d7c4c387da635631379e751e0fab02ae7211aa0681f0f0a80a91c654441fbbc9d5cd4952ff62dfe54b048401bc6f9d844d0415d74844cfe021df565b3c2145e10103971a64c67874aa971b321cfb6dde55b0bd9561b2c6438c1885f7f429a2273743b41fa87cd0bd029384306e4993ea730db318deeff32a225d660600001f2ca5e5a4136a08df29d764b889b59bb1810c49b0b3ce4ee0ab9aa21f5b1d026b24eecad4a1cf99a3e5cf58fc1e1d78279444bb2a1bd7844edc498df9b5f205c6006e42fb5a2945bdcfa668f341565a87d5c2c4bf5adb7ead9c75637eabff17d1501c6699d96a790a6ee62a6e333d7d3c57097156453cb18681949e176ccc12fa54f43a31360328e66cee28415dbd6cfc833ad38b43413218d76daeaecf2b1b9d73c07899072ae18523b8862ae966ff0c042bed2e986bfce40d0708521d242f2e7dcdb2712c9e6127ab0d1a810998a6b39a0ad063466dab00ba56543dada631da18eee41dcf1b90f372582172d25cfcab7f702a47e02b59bc0a26faed65940fb5074dbf193e99ace30848d9074fff7b5910f54881bdad170e12d576b029b521e1ba1d17c7db67c7682b61c247e383e6a21cf72cdd566a4960a5493a31cb4025cb8f8353827f3c731f9aeb51af2aa063c74c1bc8c88169d4e2cc143d3b8cfb32eefa31edb3905ffe147097b95c99c3eb5a0dcb05771f89f345da5130cedf9e34eef45d332f02c55dcb6eb4ff8d90b421c2e8550ef20d94e7c7aff318e4dfaf06df1e9b5306cc207fb7811ba57236f8d54263b61723d2ae4b952cce2712119e1abb07d5b7b3dfdeba515f150fbd6bc9453c77ad9783cac3620198cab9eedc263e52691c99536ee85520606b33c707f0642ddef6871df61817eff3dbec4f5793321d67a1428625608c172eec7e91e36bc5199eafa3b54a15692d710b0e1374293798ae0394f5955f7eca2996cb01344981081a234614e2cd6c888faff46c80e305b17fec5c26db7511ac6b8feb910209fdf09b1542e5f1531b11dc3318035e412ff71aa9af85ef0ae4903e0d6a8d16d438fe6969b24da1aacd565267518b33d00604370c345c8007c382f1c931daa695d9ef59dfb996629c4d73e69693d8e88a2ee7edaa5b6359067e0676c7eaea9d250cdd50e99173d1e68d54a2ea0085516f1461f7dcbd088dc6d7537f9bd2db5e3436346a22cc67a72fcfa7bef32677e9933f2198659b117541839c9c27b6bb990018779fefacf93ef58ac74481d486109d177dceff7bed85ddc3e82e2c126a66aa84d57caad2edadb33e56511d4becb5d320fd9eff979586d884cf3e34342d4435804d0bb7eb972eae8a21b486e4120b55101b1a52f63bf1d9cb5033496b5258d27c34a94a8813c146cd7aff1b427f99560b4678313b648438c95371c31277d86a78d947110f4bc1b8146d3df402551f351172df48e6ef1eaf0d46b05b16509ca044657afb54084403a135def4c4b9e43c15d0d8dde203d4108064e07822f1021b748f95eb9a983f9259d49becf46642c93e8f10a8a56a4697ee1c653c0f6bc3b6548cb0604a23442b65d459cfb239b44e32e356db260e8634a457649171a7fef6547b971fdd90ddfd8e9548d48922fbeb3937e5900b9e55156ea63547970ab902fd3cb490481e82a3c69b0b08b2a215a03ad5a1277c4e1c7ffd6cf984457a1352735e007246fa12289629781400e648ed086b48442859c126cad10f41d715e01a6bde4241c12a4bfce362be59a1b8a8952379eb22e20e093c2d1d30a0701eb9a3f6f9010703699ed7d6dec9b4d529617c38fe0b9d8188270047c588818b843618b067303770d20449e8cf1df2b74524512db7fa458260ca52b00f46d344499dd82ee951edc94e6da28db68fefba95fe273a52190a10c234aaffbe35534323a9757ef169709b80594ec6b099ec6d156eb1b659c283b1a80c0179fbb18a5a180d6c3d5f43821969aa7c092fcfa06c08762c3b7e4850c76e4180eb1175891fe119b303b823dc8c1fee5fd589edddc238876414ccf36f16f01061616517a92d57d0acc00d7ebb0410a7a8b3761c68b45de850002f76680ee13db5cff191f933b22479e16cb9a973d5183d4528c5d1acc2085627fda64ff2bba9a88b71f32fcbbf82c49b8d9d49477bf9a02901b85b9e5374f5ad6a013900b119a04d532583c847fab9d6bb7f5125babf86f958e05334571dff2a391070b7a33ff77e3dd373e632344bbb7e1d19eab65a7b27fdd8820372a66230a48fd2321606bf2f5cca4f7b69e87d7388cb7ccc5830fcc5517934ff881e9910afeadf194876fe2ed267aefd880633bb37892e87ab561b2145a12cb27d32188bb1eaf7ca6cb4f5c34836637bdbda227230f37b6aec4235bd24657c8dfead530822a5133d69fac63893fbff9ebce128242536307145fc879ba4573d4eb95c918a31a26ac0f985003afe083733a8e5f8d4aab377b100ea05490533517dcc336ca599f7582a07eab9629533df6eb38fdd3ef09963fcf76b84f492ef5833245aecb9979c3e4b09c61b30eb6d31d1f7a3434f3f5f04e6285098320993b51d848d6a349b80e89e6857e8394380d91710eb2ba03221bc4562fe5f8bb7f8f6e1353f4da07733f58ec3c847e54fd6bf31cb32adbb701b6c5bcd79defe5de7901b5ca92010289991b83079959d64dcc140c612f4a773995a0de2abbc2b9c601b026fa5e3340c03fd06fca4c8e2d58d117132cb86647a2a16c1dbf71262ce644e1c178799b9e5941c7cd866bd407196caa9a511acc3c1f0ff73150ce847b6a88aaa8f8c5c2685dba9ba63cefafd89d7ddcf97e133951639cf6d021d92f172437c72968098b3f0ed3040c282cfcb7bced1baa9d17c6af35b97946a16170d8cda40039f08872a35bab3924b871a7620357c329f9c6c0bb9e03fe77313e77e5e4f7f2f151e600c8cb330b21599e4ce616ca5ad16e1548bdfa10c5aa92d7b436d22ccf894fd28364b7e5eb81a5967b1cc3f7cf3dea6c432595a0389cafa00059e3cac41c67bb71427cf56501fcd77cb3c239c73b996774a7fa9fd410e3fe3184900c8578a8d0a988445d0567ad0a2fbbb055cfdf14c4184516d5ce31b3ac4dbad3fe89367c83f0fdcdb1dcab1b8eac5da64183cf9849a471425f2f63135644a45ccd0f5a68cc7b1f3871e32729ea37c1ca433c13011d725898b455e1c74104d9bdd9a99c0ca640a159d4a6040e69480f82da58d9ea45284353cfeee835c023d8f9b07a14d43be376d4421b4f6a1fbbc2b877272098ca2b61bb2d38cb2691e7429619fa53a566709"
+    }
+  ]
+}
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..69d193924
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/Cargo.toml
@@ -0,0 +1,89 @@
+[package]
+name = "onekey-zcash-runtime"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+description = "OneKey Zcash Runtime: a thin wasm binding over librustzcash"
+
+[lib]
+crate-type = ["cdylib", "rlib"]
+
+[dependencies]
+onekey-zcash-send-policy.workspace = true
+incrementalmerkletree = "0.8.2"
+shardtree = "=0.7.1"
+blake2b_simd.workspace = true
+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
+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
+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
+
+futures-util.workspace = true
+sapling.workspace = true
+uuid.workspace = true
+
+# 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 }
+
+[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
+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
+getrandom = { workspace = true, features = ["wasm_js"] }
+tonic-web-wasm-client.workspace = true
+# 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"
+
+# -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.
+wasm-opt = ["-Oz", "--enable-bulk-memory", "--enable-nontrapping-float-to-int"]
+
+# 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/build.rs b/chain-runtimes/zcash/crates/zcash-runtime/build.rs
new file mode 100644
index 000000000..e3bcc324b
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/build.rs
@@ -0,0 +1,56 @@
+//! 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};
+
+fn main() {
+    println!("cargo::rerun-if-changed=build.rs");
+
+    let target = std::env::var("TARGET").unwrap_or_default();
+    if !target.starts_with("wasm32") {
+        // Native targets use system or bundled SQLite.
+        return;
+    }
+
+    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 {
+        // Warn instead of panicking so a later link error has context.
+        println!(
+            "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=failed to copy {}: {e}", src.display());
+        return;
+    }
+
+    println!("cargo::rustc-link-search=native={}", out_dir.display());
+    println!("cargo::rerun-if-changed={}", src.display());
+}
+
+/// 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 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 };
+        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..5820484ab
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/account.rs
@@ -0,0 +1,957 @@
+//! Account import and reads (UFVK import, balances); no private keys or signing.
+
+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,
+    WalletCommitmentTrees, WalletRead, WalletWrite, Zip32Derivation,
+};
+use zcash_client_sqlite::error::SqliteClientError;
+use zcash_keys::keys::UnifiedFullViewingKey;
+
+use crate::error::{ErrorCode, Result, RuntimeError};
+use crate::network::{self, LightClient};
+use crate::wallet::Db;
+use serde_json::json;
+
+/// Imports an account from a UFVK; scanning starts at `birthday_height`.
+pub async fn import_ufvk(
+    db: &mut Db,
+    client: &mut LightClient,
+    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))?;
+
+    // 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)?),
+        },
+        None => AccountPurpose::ViewOnly,
+    };
+
+    // 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)?;
+
+    let birthday = AccountBirthday::from_treestate(treestate, None).map_err(|e| {
+        RuntimeError::with(
+            ErrorCode::InvalidBlockHeight,
+            json!({ "birthdayHeight": birthday_height }),
+        )
+        .detail(format!("{e:?}"))
+    })?;
+
+    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(),
+            )
+            .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(())
+}
+
+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();
+        // 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)
+    })
+    .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.
+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(
+            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,
+    ))
+}
+
+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)
+    })?;
+
+    // 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));
+    };
+
+    let balances = summary.account_balances().get(&account_id).ok_or_else(|| {
+        RuntimeError::with(
+            ErrorCode::AccountNotFound,
+            json!({ "accountId": account_uuid }),
+        )
+    })?;
+
+    Ok(balance_value(
+        u32::from(summary.chain_tip_height()),
+        u32::from(summary.fully_scanned_height()),
+        balances,
+    )
+    .to_string())
+}
+
+/// `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 {
+    // 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()),
+            "pendingChange": u64::from(b.change_pending_confirmation()),
+            "pendingSpendable": u64::from(b.value_pending_spendability()),
+            // 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
+            // note selection skips them, so they are never part of `spendable`.
+            "uneconomic": u64::from(b.uneconomic_value()),
+        })
+    };
+
+    let supported = [
+        balances.orchard_balance(),
+        balances.ironwood_balance(),
+        balances.unshielded_regular_balance(),
+        balances.unshielded_coinbase_balance(),
+    ];
+    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::();
+
+    serde_json::json!({
+        "ready": true,
+        "chainTip": chain_tip,
+        "fullyScannedHeight": fully_scanned_height,
+
+        "orchard": pool(balances.orchard_balance()),
+        "ironwood": pool(balances.ironwood_balance()),
+
+        // 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()),
+
+        // Sapling is intentionally excluded from both the pool list and the product total.
+        "total": supported_total,
+        "uneconomic": supported_uneconomic,
+    })
+}
+
+/// 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| {
+        wallet.delete_account(account_id).map_err(|e| {
+            RuntimeError::with(
+                ErrorCode::DatabaseError,
+                json!({ "operation": "deleteAccount" }),
+            )
+            .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 {
+    let params = *db.params();
+    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.
+/// The host deletes by this, so a name held twice is refused, never guessed.
+pub fn account_by_name(db: &Db, name: &str) -> Result {
+    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"`.
+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,
+            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 matches(&acct) {
+            found.push(acct.id().expose_uuid().to_string());
+        }
+    }
+    Ok(found)
+}
+
+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)
+    })
+}
+
+/// Builds a confirmations policy. Both thresholds must be >= 1 and 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))
+}
+
+/// 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,
+    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 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;
+    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();
+    }
+}
+
+#[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);
+        }
+    }
+}
+
+#[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");
+        }
+    }
+}
+
+#[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");
+    }
+
+    // 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);
+    }
+}
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..001f57afc
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/bindgen.rs
@@ -0,0 +1,674 @@
+//! Host-facing JS/TS interface.
+//!
+//! - Parameters and return values are only string / number / boolean / JSON string.
+//! - A thrown `Error` carries `code` / `params` / `detail`; see `error`.
+//! - Every call is a complete round trip: no background tasks, no timers.
+
+// `diag*` methods are not a stable contract; all others are, and changes require a version bump.
+
+use wasm_bindgen::prelude::*;
+
+use crate::{
+    account,
+    error::{ErrorCode, RuntimeError},
+    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);
+}
+
+/// 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();
+    storage::install_persistent_vfs().await?;
+    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()
+}
+
+/// 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.
+fn install_panic_hook() {
+    console_error_panic_hook::set_once();
+}
+
+/// 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.
+#[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,
+        // Proposals and proofs only; the keys package signs the inputs.
+        "proveShielding": true,
+        "notes": {
+            "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()
+}
+
+/// 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()
+}
+
+/// 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())
+}
+
+/// Closes the wallet, releasing the database and network client.
+///
+/// Throws `WALLET_BUSY` while an async operation holds the database.
+#[wasm_bindgen(js_name = closeWallet)]
+pub fn close_wallet() -> Result<(), JsValue> {
+    Ok(runtime::close()?)
+}
+
+/// 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)?);
+    Ok(())
+}
+
+/// Current chain tip height. Requires only `setLightwalletdUrl`, not an open wallet.
+///
+#[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.
+///
+/// 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)?;
+    Ok(network::chain_tip(&mut client).await?)
+}
+
+/// Imports a view-only account (UFVK) and returns its UUID.
+///
+/// `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,
+    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 = 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)
+        })
+        .await?,
+    )
+}
+
+/// 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))?;
+    storage::durability_barrier().await?;
+    runtime::reclaim_storage(storage::RECLAIM_PAGES_AFTER_DELETE);
+    Ok(())
+}
+
+/// 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 {
+    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.
+///
+///
+/// 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| {
+        sync::account_status(db, &account_uuid)
+    })?)
+}
+
+/// 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))?)
+}
+
+/// Account balance as JSON.
+///
+/// `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(
+    account_uuid: String,
+    trusted: u32,
+    untrusted: u32,
+    allow_zero_conf_shielding: bool,
+) -> Result {
+    let policy = account::confirmations_policy(trusted, untrusted, allow_zero_conf_shielding)?;
+    Ok(runtime::with_db(|db| {
+        account::balance_json(db, &account_uuid, policy)
+    })?)
+}
+
+/// 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.
+///
+/// Returns `{ chainTip, saplingSubtrees, orchardSubtrees, ironwoodSubtrees }`.
+#[wasm_bindgen(js_name = syncPrepare)]
+pub async fn sync_prepare() -> Result {
+    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?,
+    )
+}
+
+/// Updates only the chain tip (one unary call). Returns `{ chainTip }`.
+///
+/// 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(
+        runtime::with_db_and_client(|mut db, mut client| async move {
+            let r = sync::tip(&mut db, &mut client).await;
+            (db, client, r)
+        })
+        .await?,
+    )
+}
+
+/// Read-only view of pending scan ranges; no network requests. Returns
+/// `{ 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))?)
+}
+
+/// 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).
+#[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,
+    pad_orchard_bundle: bool,
+    allow_zero_conf_shielding: Option,
+    spend_source: Option,
+    memo_hex: Option,
+) -> Result {
+    let policy = send::parse_send_policy(
+        trusted,
+        untrusted,
+        &fallback_change_pool,
+        pad_orchard_bundle,
+        allow_zero_conf_shielding,
+        spend_source.as_deref(),
+    )?;
+    Ok(runtime::with_db(|db| {
+        send::quote(
+            db,
+            &account_uuid,
+            &to_address,
+            amount_zat,
+            send::parse_memo(memo.as_deref(), memo_hex.as_deref())?.as_ref(),
+            policy,
+        )
+    })?)
+}
+
+/// 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 {
+    Ok(runtime::with_read_conn(|conn| {
+        history::details(conn, &account_uuid, &txid)
+    })?)
+}
+
+/// Per-output breakdown of one transaction: `{ txid, spent[], received[], external[] }`.
+///
+/// `transactionDetails` gives aggregates; this gives each output (value, pool, change flag,
+/// memo, address).
+#[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)
+    })?)
+}
+
+/// Bounded scan step: at most `maxBatches` batches of `batchSize` blocks.
+///
+/// `batchSize × maxBatches` must be 1..=1000; otherwise throws `INVALID_BATCH_SIZE`.
+///
+/// `priority` selects the lane: `"chainTip"` follows new blocks, `"historic"` backfills,
+/// absent or `"any"` follows upstream order. Candidate ranges come only from upstream
+/// suggestions; the host cannot pick arbitrary heights.
+///
+/// `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.
+///
+/// Never loops to completion. Returns
+/// `{ done, batchesDone, blocksScanned, remainingBlocks, remainingRanges, scannedFrom,
+/// scannedTo, scannedPriority }`; the host decides whether to call again.
+#[wasm_bindgen(js_name = syncStep)]
+pub async fn sync_step(
+    batch_size: u32,
+    max_batches: u32,
+    priority: Option,
+    active_ufvks_json: String,
+) -> Result {
+    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}"))
+    })?;
+    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)
+}
+
+/// Paged transaction history as a JSON array. Unmined first, then by height descending.
+///
+/// Returns neutral facts (value delta, change flag, note counts, timestamps), no
+/// incoming/outgoing classification.
+///
+/// `limit` is capped at 500; above that throws `INVALID_BATCH_SIZE`.
+#[wasm_bindgen(js_name = transactionHistory)]
+pub fn transaction_history(
+    account_uuid: String,
+    limit: u32,
+    offset: u32,
+) -> Result {
+    Ok(runtime::with_read_conn(|conn| {
+        history::list(conn, &account_uuid, limit, offset)
+    })?)
+}
+
+/// 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: 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)
+}
+
+/// Re-queue `[fromHeight, chainTip]` as historic work without deleting cached notes or history.
+///
+/// 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| {
+        sync::queue_rescan_from(db, from_height)
+    })?)
+}
+
+/// 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?,
+    )
+}
+
+// Flow: pcztCreate → pcztProve → (keys package) pcztSign → 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.
+
+/// Builds an unproven, unsigned PCZT for a transfer and returns its bytes.
+///
+/// `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(
+    account_uuid: String,
+    to_address: String,
+    amount_zat: u64,
+    memo: Option,
+    trusted: u32,
+    untrusted: u32,
+    fallback_change_pool: String,
+    pad_orchard_bundle: bool,
+    allow_zero_conf_shielding: Option,
+    spend_source: Option,
+    memo_hex: Option,
+) -> Result {
+    let policy = send::parse_send_policy(
+        trusted,
+        untrusted,
+        &fallback_change_pool,
+        pad_orchard_bundle,
+        allow_zero_conf_shielding,
+        spend_source.as_deref(),
+    )?;
+    Ok(runtime::with_db(|db| {
+        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,
+        )?;
+        Ok(serde_json::json!({
+            "pcztHex": bytes.iter().map(|b| format!("{b:02x}")).collect::(),
+            "feeZat": fee_zat,
+        })
+        .to_string())
+    })?)
+}
+
+/// 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))?)
+}
+
+/// Merges a redacted PCZT returned by an external (hardware) signer back into the full local PCZT.
+///
+/// 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)?)
+}
+
+/// Durability barrier after an irreversible step.
+///
+/// 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)
+    })
+}
+
+/// 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. 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 {
+        let r = send::submit_signed_pczt(&mut db, &mut client, &account_uuid, &pczt_bytes).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 } => serde_json::json!({
+            "txid": txid,
+            "broadcast": "rejected",
+            "error": error.to_json(),
+        }),
+        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())
+}
+
+/// Stored outgoing transactions of this account that are unmined, unexpired, and not
+/// rejected by the node. Each stays pending until mined or expired; the host does not
+/// resubmit 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::pending_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)
+    })?)
+}
+
+/// 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
+/// 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 {
+        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 {
+            Err(e) if e.code == crate::ErrorCode::BroadcastRejected => {
+                // 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)
+                    });
+                match recorded {
+                    Ok(()) => Err(e),
+                    Err(persist_error) => {
+                        Err(e.detail(format!("record_rejection failed: {persist_error}")))
+                    }
+                }
+            }
+            r => r,
+        };
+        (db, client, r)
+    })
+    .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?)
+}
+
+/// Deletes a wallet database file. Irreversible.
+///
+/// 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.
+#[wasm_bindgen(js_name = deleteWallet)]
+pub async fn delete_wallet(db_name: String) -> Result {
+    if !storage::database_exists(&db_name).await? {
+        return Ok(false);
+    }
+    if runtime::open_db_name().as_deref() == Some(db_name.as_str()) {
+        runtime::close()?;
+    }
+    Ok(storage::delete_database(&db_name).await?)
+}
+
+/// Usage of the open wallet database, grouped by data meaning. Read-only.
+///
+/// A stable contract, not `diag*`: the host uses it for capacity guards.
+///
+/// `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()
+        .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)?)
+}
+
+/// 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> {
+    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 = send::extract_pczt(pczt)?;
+    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/blockcache.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs
new file mode 100644
index 000000000..0a4063718
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/blockcache.rs
@@ -0,0 +1,231 @@
+//! 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;
+use std::ops::Range;
+use std::sync::Mutex;
+
+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;
+
+#[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()),
+        }
+    }
+
+    /// Number of cached blocks, for observing memory use.
+    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)
+    }
+    /// 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!("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);
+        let doomed: Vec = blocks.range(r).map(|(h, _)| *h).collect();
+        for h in doomed {
+            blocks.remove(&h);
+        }
+        Ok(())
+    }
+}
+
+/// Cache error. In memory, the only failure is a poisoned lock.
+#[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("internal lock poisoned (a previous holder panicked)".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>,
+    {
+        // 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, and `std::sync::Mutex` is
+        // not reentrant (deadlock on wasm).
+        let selected: Vec = {
+            let blocks = self
+                .blocks
+                .lock()
+                .map_err(|_| error::Error::BlockSource(poisoned()))?;
+
+            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;
+            }
+
+            // 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"
+                ))));
+            }
+            out
+        }; // lock released here
+
+        for block in selected {
+            with_block(block)?;
+        }
+        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,
+        )
+    }
+
+    /// Heights actually handed out by `with_blocks`, the path scanning uses.
+    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_hands_out_nothing() {
+        let c = MemoryBlockCache::new();
+        assert!(c.is_empty());
+        assert_eq!(handed_out(&c, 10, 5).unwrap(), Vec::::new());
+    }
+
+    #[test]
+    fn insert_then_hand_out_contiguous() {
+        let c = MemoryBlockCache::new();
+        c.insert(vec![block(10), block(11), block(12)]).unwrap();
+        assert_eq!(c.len(), 3);
+        assert_eq!(handed_out(&c, 10, 3).unwrap(), vec![10, 11, 12]);
+    }
+
+    #[test]
+    fn limit_is_respected() {
+        let c = MemoryBlockCache::new();
+        c.insert(vec![block(10), block(11), block(12)]).unwrap();
+        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();
+        c.insert(vec![block(10), block(11), block(13)]).unwrap();
+        assert_eq!(
+            handed_out(&c, 10, 4).unwrap(),
+            vec![10, 11],
+            "must stop at missing height 12"
+        );
+    }
+
+    #[test]
+    fn missing_start_is_an_error_not_an_empty_batch() {
+        let c = MemoryBlockCache::new();
+        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")),
+            "missing start should be a BlockSource error, got {e:?}"
+        );
+    }
+
+    #[test]
+    fn delete_removes_only_the_range() {
+        let c = MemoryBlockCache::new();
+        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/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/clock.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs
new file mode 100644
index 000000000..a492cda8d
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/clock.rs
@@ -0,0 +1,49 @@
+//! 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;
+
+/// Clock backed by the host's 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 {
+    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("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
new file mode 100644
index 000000000..4c38ca601
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/error.rs
@@ -0,0 +1,340 @@
+//! Error contract.
+//!
+//! No user-facing text: the host gets a stable error code plus structured params
+//! and renders copy from them.
+//!
+//! ```js
+//! try {
+//!   await rt.syncAdvance(1000);
+//! } catch (e) {
+//!   // 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 }));
+//!       break;
+//!   }
+//! }
+//! ```
+//!
+//! Error codes and param fields are append-only; host branching depends on them.
+
+use serde_json::{json, Map, Value};
+use std::fmt;
+
+/// Stable error code. Hosts branch on this, never on `detail` text.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ErrorCode {
+    /// `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.
+    LightwalletdNotConfigured,
+
+    /// Network name is not "main" / "test". Params: `{ value }`
+    InvalidNetwork,
+    /// Database name is empty or contains a path separator. Params: `{ value }`
+    InvalidDbName,
+    /// Recipient address cannot be parsed. Params: `{ value }`
+    InvalidAddress,
+    /// UFVK cannot be parsed.
+    InvalidUfvk,
+    /// Invalid memo (too long, or sent to a transparent address). Params: `{ byteLen }`
+    InvalidMemo,
+    /// Account id is not a valid UUID. Params: `{ value }`
+    InvalidAccountId,
+    /// Amount outside the Zatoshis range. Params: `{ valueZat }`
+    AmountOutOfRange,
+    /// Invalid confirmations policy (requires >= 1 and trusted <= untrusted).
+    /// Params: `{ trusted, untrusted }`
+    InvalidConfirmationsPolicy,
+    /// Batch size is 0 or out of range. Params: `{ value }`
+    InvalidBatchSize,
+    /// Block height out of range. Params: `{ value }`
+    InvalidBlockHeight,
+
+    /// Account not found. Params: `{ accountId }`
+    AccountNotFound,
+    /// No blocks synced yet; wallet summary unavailable.
+    NotSynced,
+    /// Insufficient funds. Params: `{ requiredZat, availableZat }` (when available)
+    InsufficientFunds,
+
+    /// lightwalletd network error. Params: `{ operation }`
+    NetworkError,
+    /// The lightwalletd endpoint serves another chain than the open wallet; the operation
+    /// did not run. Params: `{ nodeNetwork, walletNetwork }`; `nodeNetwork` is the
+    /// endpoint's raw `chainName`.
+    NodeNetworkMismatch,
+    /// 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 }`
+    ///
+    /// 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.
+    ///
+    /// Guards against swapping databases mid-operation, which would write results
+    /// to the wrong wallet.
+    WalletBusy,
+    /// 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,
+    /// Malformed txid (not 64 hex chars). Params: `{ value }` or `{ value, byteLen }`
+    InvalidTxid,
+    /// PCZT parse or serialization failed. Params: `{ stage }`
+    PcztError,
+    /// Transaction construction failed (note selection, fee, anchor, etc.). Params: `{ stage }`
+    TransactionBuildError,
+    /// 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. 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
+    /// nullifier, missing inputs), or the node may be temporarily refusing (busy,
+    /// 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 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 }`
+    Unimplemented,
+}
+
+impl ErrorCode {
+    /// Stable string form. Never change existing values.
+    pub fn as_str(self) -> &'static str {
+        use ErrorCode::*;
+        match self {
+            NotInitialized => "NOT_INITIALIZED",
+            StorageUnsupported => "STORAGE_UNSUPPORTED",
+            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",
+            NetworkError => "NETWORK_ERROR",
+            NodeNetworkMismatch => "NODE_NETWORK_MISMATCH",
+            DatabaseError => "DATABASE_ERROR",
+            DatabaseTooNew => "DATABASE_TOO_NEW",
+            ReorgDetected => "REORG_DETECTED",
+            WalletBusy => "WALLET_BUSY",
+            InvalidScanPriority => "INVALID_SCAN_PRIORITY",
+            NoActiveAccounts => "NO_ACTIVE_ACCOUNTS",
+            InvalidTxid => "INVALID_TXID",
+            PcztError => "PCZT_ERROR",
+            TransactionBuildError => "TRANSACTION_BUILD_ERROR",
+            BroadcastRejected => "BROADCAST_REJECTED",
+            BroadcastOutcomeUnknown => "BROADCAST_OUTCOME_UNKNOWN",
+            FinalizeOutcomeUnknown => "FINALIZE_OUTCOME_UNKNOWN",
+            Unimplemented => "UNIMPLEMENTED",
+        }
+    }
+}
+
+#[derive(Debug)]
+pub struct RuntimeError {
+    pub code: ErrorCode,
+    /// Structured params for host i18n placeholders. Always a JSON object.
+    pub params: Value,
+    /// Raw upstream error. Logs only; not user-facing, not localized.
+    pub detail: Option,
+}
+
+impl RuntimeError {
+    pub fn new(code: ErrorCode) -> Self {
+        Self {
+            code,
+            params: Value::Object(Map::new()),
+            detail: None,
+        }
+    }
+
+    /// With structured params. `params` should be a JSON object.
+    pub fn with(code: ErrorCode, params: Value) -> Self {
+        Self {
+            code,
+            params,
+            detail: None,
+        }
+    }
+
+    /// 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
+    }
+
+    /// Serialize to JSON the host can consume directly.
+    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 {
+        // For logs, not users.
+        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 shape: an `Error` carrying `code` / `params` / `detail`.
+///
+/// `message` is the error code, not user-facing text.
+#[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));
+        }
+
+        // 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);
+        };
+        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,
+            NodeNetworkMismatch,
+            DatabaseError,
+            DatabaseTooNew,
+            InvalidTxid,
+            PcztError,
+            TransactionBuildError,
+            BroadcastRejected,
+            BroadcastOutcomeUnknown,
+            Unimplemented,
+            ReorgDetected,
+            WalletBusy,
+            InvalidScanPriority,
+            FinalizeOutcomeUnknown,
+        ];
+        let mut seen = std::collections::HashSet::new();
+        for c in all {
+            let s = c.as_str();
+            assert!(seen.insert(s), "duplicate error code: {s}");
+            assert!(
+                s.chars().all(|ch| ch.is_ascii_uppercase() || ch == '_'),
+                "error code must be 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..e68fee8ac
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/history.rs
@@ -0,0 +1,1597 @@
+//! Transaction history.
+//!
+//! Reads the `v_transactions` view maintained by `zcash_client_sqlite`, as the official SDKs do.
+//!
+//! 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};
+use zcash_address::{ConversionError, ToAddress, TryFromAddress, ZcashAddress};
+use zcash_protocol::consensus::NetworkType;
+
+use crate::error::{ErrorCode, Result, RuntimeError};
+
+/// Account UUIDs are 16-byte BLOBs in the upstream schema, not text.
+///
+/// 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())
+        .map_err(|_| {
+            RuntimeError::with(
+                ErrorCode::InvalidAccountId,
+                json!({ "value": account_uuid }),
+            )
+        })
+}
+
+/// Maximum rows per page.
+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)
+}
+
+// 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,
+         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,
+         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
+          ORDER BY output.output_pool, output.output_index
+          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
+                  OR output.to_account_uuid <> tx_summary.account_uuid)
+             AND COALESCE(output.is_change, 0) = 0
+         ) 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
+       ON rejected.txid = tx_summary.txid";
+
+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
+  )
+)";
+
+/// A page of an account's transaction history as a JSON array.
+///
+/// Unmined transactions come first, then by height descending.
+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)
+}
+
+/// 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
+        .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::>();
+    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),
+        "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),
+        // Account-side amounts; balance_delta would show a shielding transaction as just its fee.
+        "totalSpentZat": row.get::<_, Option>(12)?,
+        "totalReceivedZat": row.get::<_, Option>(13)?,
+        "poolIds": pool_ids,
+        // 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 outside this account. Zero with spends means an internal transfer.
+        "externalOutputCount": row.get::<_, i64>(17)?,
+    }))
+}
+
+/// 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 {
+    // Stored in internal (little-endian) order; the input is display order.
+    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)
+        }
+    }
+}
+
+/// Per-output breakdown of one transaction: outputs this account spent,
+/// received, and sent externally.
+///
+/// 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,
+///   including another account registered in this wallet database.
+///   Recipient addresses are only known for our own sends.
+/// - `spent`: outputs received earlier and spent here, via `v_received_output_spends`
+///
+/// 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,
+    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.output_pool, output.value, output.is_change,
+                        output.memo, output.to_address,
+                        output.to_account_uuid, output.from_account_uuid,
+                        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)?;
+        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)?;
+            // 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)?;
+            let created_locally: bool = row.get(8).map_err(db_err)?;
+            // 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);
+
+            if pool == 2 {
+                continue;
+            }
+
+            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_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),
+                    "address": address
+                        .map(|address| paid_address(&address, pool, created_locally)),
+                }));
+            }
+        }
+    }
+
+    let mut spent = Vec::new();
+    {
+        // 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
+                 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)
+}
+
+/// Name for an upstream pool code.
+fn pool_name(pool: i64) -> &'static str {
+    match pool {
+        0 => "transparent",
+        2 => "sapling",
+        3 => "orchard",
+        4 => "ironwood",
+        _ => "unknown",
+    }
+}
+
+/// 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,
+    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()),
+            }
+        }
+    }
+}
+
+/// 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()),
+        })),
+    )
+}
+
+/// 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 })))?;
+    if bytes.len() != 32 {
+        return Err(RuntimeError::with(
+            ErrorCode::InvalidTxid,
+            json!({ "value": txid, "byteLen": bytes.len() }),
+        ));
+    }
+    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> {
+    hex::decode(s).ok()
+}
+
+/// 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()
+}
+
+#[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;
+
+    // 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.
+        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");
+        assert_eq!(hex_display_order(&[]), "");
+    }
+
+    #[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();
+            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(crate::tx_state::migrations())
+                .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"
+        );
+        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 {
+        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, created TEXT);
+             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 (
+               transaction_id INTEGER,
+               output_pool INTEGER DEFAULT 4,
+               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,
+               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();
+
+        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)",
+            [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" })
+        );
+    }
+    #[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 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 explicit_self_payment_is_not_displayed_as_change_after_scanning() {
+        let conn = history_fixture();
+        conn.execute_batch(
+            "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();
+        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);
+        }
+    }
+}
+
+/// 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;
+
+    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 (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());
+        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)
+    }
+
+    /// 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(
+        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 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] {
+            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);
+    }
+}
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..fd0ed1f86
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/lib.rs
@@ -0,0 +1,41 @@
+//! # OneKey Zcash Runtime
+//!
+//! 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.
+
+pub mod account;
+pub mod blockcache;
+mod circuit_keys;
+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;
+
+pub mod network;
+pub mod sync;
+
+// Cross-call state uses thread_local, valid only in the single-threaded wasm host.
+#[cfg(target_arch = "wasm32")]
+pub mod runtime;
+
+#[cfg(target_arch = "wasm32")]
+pub mod bindgen;
+
+pub use error::{ErrorCode, Result, RuntimeError};
+
+/// 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",
+        "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..6291f246e
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/network.rs
@@ -0,0 +1,459 @@
+//! 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.
+
+use zcash_client_backend::proto::service::{
+    compact_tx_streamer_client::CompactTxStreamerClient, BlockId, ChainSpec, Empty, TreeState,
+};
+use zcash_protocol::consensus::Network;
+
+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);
+}
+
+// `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;
+
+#[cfg(not(target_arch = "wasm32"))]
+pub type Transport = tonic::transport::Channel;
+
+pub type LightClient = CompactTxStreamerClient;
+
+/// `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)
+}
+
+/// 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>,
+    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)),
+    }
+}
+
+#[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 }),
+    )
+}
+
+/// Default network timeout; a single gRPC call exceeding it is treated as hung.
+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 {
+    if base_url.is_empty() {
+        return Err(RuntimeError::with(
+            ErrorCode::LightwalletdNotConfigured,
+            json!({ "reason": "emptyUrl" }),
+        ));
+    }
+    // Require https: plaintext would expose which addresses this wallet queries.
+    if !base_url.starts_with("https://") {
+        return Err(RuntimeError::with(
+            ErrorCode::LightwalletdNotConfigured,
+            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_with_options(
+            base_url.trim_end_matches('/').to_owned(),
+            options,
+        ),
+    ))
+}
+
+/// 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() {
+        return Err(RuntimeError::with(
+            ErrorCode::LightwalletdNotConfigured,
+            json!({ "reason": "emptyUrl" }),
+        ));
+    }
+    // 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://") {
+        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 }),
+        )
+    })
+}
+
+/// 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.
+/// 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;
+
+    let resp = with_timeout(
+        async {
+            client
+                .send_transaction(RawTransaction {
+                    data: tx_bytes,
+                    // Height is unknown at broadcast; lightwalletd ignores it.
+                    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 {
+        // A node that already holds the tx is the outcome we want.
+        if broadcast_already_known(&resp.error_message) {
+            return Ok(());
+        }
+        let code = if broadcast_definitely_invalid(&resp.error_message) {
+            ErrorCode::BroadcastRejected
+        } else {
+            ErrorCode::BroadcastOutcomeUnknown
+        };
+        return Err(RuntimeError::with(
+            code,
+            json!({
+                "errorCode": resp.error_code,
+                "errorMessage": resp.error_message,
+            }),
+        )
+        .detail(resp.error_message));
+    }
+    Ok(())
+}
+
+/// 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();
+    [
+        // 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",
+        // 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))
+}
+
+/// Only replies proving these bytes can never be mined count as a rejection.
+///
+/// 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();
+    // 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 {
+    let message = message.to_lowercase();
+    [
+        "already in mempool",
+        "already in block chain",
+        "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))
+}
+
+/// 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 {
+            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, broadcast_definitely_invalid, broadcast_outcome_ambiguous,
+        check_chain_name, with_timeout, Network,
+    };
+    use crate::error::{ErrorCode, RuntimeError};
+
+    #[test]
+    fn an_endpoint_on_another_chain_is_refused() {
+        check_chain_name("main", &Network::MainNetwork).expect("same chain");
+        check_chain_name("test", &Network::TestNetwork).expect("same chain");
+        for (chain, wallet, wallet_name) in [
+            ("test", Network::MainNetwork, "main"),
+            ("main", Network::TestNetwork, "test"),
+            ("regtest", Network::MainNetwork, "main"),
+            ("regtest", Network::TestNetwork, "test"),
+            ("", Network::MainNetwork, "main"),
+            ("Main", Network::MainNetwork, "main"),
+        ] {
+            let error = check_chain_name(chain, &wallet).expect_err(chain);
+            assert_eq!(error.code, ErrorCode::NodeNetworkMismatch);
+            assert_eq!(error.code.as_str(), "NODE_NETWORK_MISMATCH");
+            assert_eq!(error.params["nodeNetwork"], chain);
+            assert_eq!(error.params["walletNetwork"], wallet_name);
+        }
+    }
+
+    // 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 [
+            "orchard double-spend: duplicate nullifier: Nullifier(..)",
+            "ironwood double-spend: duplicate nullifier: Nullifier(..)",
+            "transparent double-spend: OutPoint(..) is spent twice",
+            "could not find transparent input UTXO in the best chain or mempool",
+            "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}");
+        }
+        for message in [
+            "transaction is non-standard",
+            "tx-overwinter-expired",
+            "bad-txns-fee-too-low",
+        ] {
+            assert!(!broadcast_outcome_ambiguous(message), "{message}");
+        }
+    }
+
+    #[test]
+    fn only_consensus_invalid_or_expired_replies_count_as_a_rejection() {
+        for message in [
+            "tx-overwinter-expired",
+            "bad-txns-orchard-verification-failed",
+            "16: bad-txns-vout-negative",
+        ] {
+            assert!(broadcast_definitely_invalid(message), "{message}");
+        }
+        for message in [
+            "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",
+            "mempool is disabled since synchronization is behind the chain tip",
+            "",
+            "something nobody has seen before",
+        ] {
+            assert!(!broadcast_definitely_invalid(message), "{message}");
+        }
+    }
+
+    #[test]
+    fn duplicate_broadcast_is_an_idempotent_success() {
+        for message in [
+            "txn-already-known",
+            "Transaction already in mempool",
+            "transaction already in block chain",
+            "transaction already exists in mempool",
+            "transaction dropped because it is already queued for download",
+        ] {
+            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/runtime.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs
new file mode 100644
index 000000000..fc7f1a7df
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/runtime.rs
@@ -0,0 +1,245 @@
+//! Cross-call runtime state: only the database connection, the lightwalletd client
+//! and the chain it serves (reopening per call would rerun migration checks).
+
+use std::cell::{Cell, RefCell};
+
+use zcash_protocol::consensus::Network;
+
+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) };
+    // 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) };
+
+    // 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) };
+
+    // 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) };
+
+    // 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
+/// the endpoint changed or closed, so the stale client is dropped.
+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));
+    }
+}
+
+/// 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) {
+        return Err(RuntimeError::with(
+            ErrorCode::WalletBusy,
+            serde_json::json!({ "operation": operation }),
+        ));
+    }
+    Ok(())
+}
+
+/// 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; the host serializes that window.
+struct BusyGuard {
+    generation: u64,
+}
+
+impl BusyGuard {
+    fn acquire(operation: &str) -> Result {
+        assert_idle(operation)?;
+        BUSY.with(|b| b.set(true));
+        Ok(Self {
+            // Sampled when DB is taken: a switch after this makes the operation stale.
+            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_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)));
+}
+
+fn not_open() -> RuntimeError {
+    RuntimeError::new(ErrorCode::WalletNotOpen)
+}
+
+/// 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(
+            ErrorCode::WalletBusy,
+            serde_json::json!({ "operation": operation }),
+        )
+    } else {
+        not_open()
+    }
+}
+
+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));
+    DB_NAME.with(|c| *c.borrow_mut() = Some(db_name.to_owned()));
+    bump_generation();
+    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)?;
+    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();
+}
+
+/// 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())
+        .ok_or_else(|| db_unavailable("walletRead"))?;
+    let out = f(&mut db);
+    DB.with(|c| *c.borrow_mut() = Some(db));
+    out
+}
+
+/// 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,
+    Fut: std::future::Future)>,
+{
+    // 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)?;
+    let mut 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 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.
+    if guard.stale() {
+        drop(db);
+    } else {
+        DB.with(|c| *c.borrow_mut() = Some(db));
+    }
+    put_client_back(client, client_gen);
+    out
+}
+
+/// Lends only the client; no wallet needs to be open.
+///
+/// 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,
+    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;
+    put_client_back(client, client_gen);
+    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. 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);
+    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
new file mode 100644
index 000000000..5dd2b71c7
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/send.rs
@@ -0,0 +1,2161 @@
+//! Sending: PCZT construction and broadcast.
+//!
+//! Signing is not in this crate:
+//!
+//! ```text
+//!   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()          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::{locking::LockError, OutputLockStore, WalletRead};
+use zcash_client_backend::fees::{zip317::SingleOutputChangeStrategy, DustOutputPolicy};
+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_primitives::transaction::TxId;
+use zcash_protocol::{
+    consensus::BlockHeight, memo::MemoBytes, value::Zatoshis, PoolType, ShieldedPool,
+};
+
+use crate::account;
+use crate::error::{ErrorCode, Result, RuntimeError};
+use crate::{tx_state, wallet::Db};
+use serde_json::json;
+
+/// `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.
+///
+/// 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,
+) -> 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:?}")),
+    }
+}
+
+/// 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 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 }),
+        )),
+    }
+}
+
+/// 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
+/// is unsupported because this runtime does not ship its prover.
+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 }),
+        )),
+    }
+}
+
+/// Host-controlled send policy. Every field is explicit; no hidden defaults.
+#[derive(Debug, Clone, Copy)]
+pub struct SendPolicy {
+    /// Confirmations required for trusted notes (>= 1).
+    pub trusted: u32,
+    /// Confirmations required for untrusted notes (>= trusted).
+    pub untrusted: u32,
+    /// Shielded pool for change when the transaction is fully transparent.
+    pub fallback_change_pool: ShieldedPool,
+    /// 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.
+    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 and then fail to prove.
+    /// Pools are never crossed: an uncovered amount is `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
+        }
+    }
+}
+
+/// 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 ZIP-317 fee.
+#[allow(clippy::too_many_arguments)]
+pub fn parse_send_policy(
+    trusted: u32,
+    untrusted: u32,
+    fallback_change_pool: &str,
+    pad_orchard_bundle: bool,
+    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,
+        allow_zero_conf_shielding: allow_zero_conf_shielding.unwrap_or(false),
+        spend_source: parse_spend_source(spend_source)?,
+    })
+}
+
+/// 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;
+
+/// Recipient can only receive into Sapling, which this runtime cannot prove;
+/// refuse before building.
+fn recipient_needs_sapling_output(
+    params: &zcash_protocol::consensus::Network,
+    recipient: &zcash_address::ZcashAddress,
+) -> bool {
+    use zcash_keys::address::Address;
+    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 addresses accept only transparent inputs; a shielded spend cannot pay them.
+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(_))
+    )
+}
+
+// `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) {
+        (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<&MemoBytes>,
+    policy: SendPolicy,
+) -> Result {
+    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())
+        .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)
+    })?;
+
+    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" }),
+        ));
+    }
+
+    // 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" }))
+                .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,
+    )?;
+    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 = {
+        use zcash_client_backend::data_api::wallet::input_selection::SpendPolicy;
+        // Not SpendPolicy::default(): it allows Sapling. See SendPolicy::spend_source.
+        let pool = policy.spend_source.ok_or_else(|| {
+            RuntimeError::with(
+                ErrorCode::TransactionBuildError,
+                json!({ "stage": "spendSource", "reason": "required" }),
+            )
+        })?;
+        SpendPolicy::shielded_pools([pool])
+    };
+
+    let selector = GreedyInputSelector::::new();
+    let change = SingleOutputChangeStrategy::<_, Db>::new(
+        onekey_zcash_send_policy::fee_rule(¶ms, target),
+        None,
+        policy.change_pool(),
+        DustOutputPolicy::default(),
+    );
+
+    // The commitment-tree error type cannot be inferred here.
+    let proposal =
+        propose_transfer::(
+            db,
+            ¶ms,
+            account_id,
+            &selector,
+            &change,
+            request,
+            confirmations,
+            &spend_policy,
+            None,
+            None,
+        );
+
+    proposal.map_err(|e| propose_err("proposeTransfer", e))
+}
+
+/// Returns the fee only; builds no PCZT and locks no notes.
+pub fn quote(
+    db: &mut Db,
+    account_uuid: &str,
+    to_address: &str,
+    amount_zat: u64,
+    memo: Option<&MemoBytes>,
+    policy: SendPolicy,
+) -> Result {
+    let proposal = build_proposal(db, account_uuid, to_address, amount_zat, memo, policy)?;
+    let fee: u64 = proposal
+        .steps()
+        .iter()
+        .map(|s| u64::from(s.balance().fee_required()))
+        .sum();
+
+    Ok(json!({
+        "feeZat": fee,
+        "steps": proposal.steps().len(),
+    })
+    .to_string())
+}
+
+/// Builds an unsigned transfer PCZT for review. Returns `(pcztBytes, feeZat)`.
+///
+/// Locks nothing, so an abandoned review leaves the notes spendable. Notes are
+/// 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,
+    to_address: &str,
+    amount_zat: u64,
+    memo: Option<&MemoBytes>,
+    policy: SendPolicy,
+) -> Result<(Vec, u64)> {
+    let params = *db.params();
+    let account_id = account::parse_account_id(db, account_uuid)?;
+    let proposal = build_proposal(db, account_uuid, to_address, amount_zat, memo, policy)?;
+    let fee_zat = proposal
+        .steps()
+        .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::<
+        Db,
+        _,
+        std::convert::Infallible,
+        _,
+        std::convert::Infallible,
+        _,
+    >(
+        db,
+        ¶ms,
+        account_id,
+        OvkPolicy::Sender,
+        &proposal,
+        Some(expiry),
+        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
+/// 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. 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,
+    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
+/// 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,
+) -> orchard::circuit::OrchardCircuitVersion {
+    use zcash_protocol::consensus::{NetworkUpgrade, Parameters};
+    match params.activation_height(NetworkUpgrade::Nu6_3) {
+        Some(activation) if height >= activation => {
+            orchard::circuit::OrchardCircuitVersion::PostNu6_3
+        }
+        _ => orchard::circuit::OrchardCircuitVersion::FixedPostNu6_2,
+    }
+}
+
+/// 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,
+    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))
+}
+
+/// 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` 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};
+
+    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 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"));
+        }
+    }
+    // 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())
+            .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:?}"))
+    })
+}
+
+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))?;
+    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,
+    chain_tip: zcash_protocol::consensus::BlockHeight,
+    pczt_bytes: &[u8],
+) -> Result> {
+    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() {
+        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
+    };
+
+    if prover.requires_sapling_proofs() {
+        return Err(RuntimeError::with(
+            ErrorCode::Unimplemented,
+            json!({ "what": "saplingProof" }),
+        ));
+    }
+
+    let prover = if prover.requires_orchard_proof() {
+        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:?}"))
+        })?
+    } else {
+        prover
+    };
+
+    prover.finish().serialize().map_err(|error| {
+        RuntimeError::with(ErrorCode::PcztError, json!({ "stage": "serializeProven" }))
+            .detail(format!("{error:?}"))
+    })
+}
+
+/// 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.
+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 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_store("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_store("inputsAlreadySpent"));
+        }
+    }
+    Ok(())
+}
+
+/// 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 {
+    // 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| {
+        wallet
+            .lock_outputs(
+                &staged.inputs,
+                LockOwner::new(*staged.txid.as_ref()),
+                staged.lock_expiry,
+            )
+            .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(())
+    })
+}
+
+/// Outcome of a submit.
+pub enum SubmitOutcome {
+    Accepted {
+        txid: String,
+    },
+    /// 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,
+    },
+    /// 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,
+    },
+}
+
+// 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)
+    } else {
+        Err(error)
+    }
+}
+
+/// Stores the broadcast transaction, or releases its inputs if the node
+/// definitively rejected it. Storing after a broadcast cannot fail as a plain error.
+fn finish_submission(
+    db: &mut Db,
+    account_uuid: &str,
+    staged: Staged,
+    pczt: pczt::Pczt,
+    orchard_vk: &orchard::circuit::VerifyingKey,
+    result: Result<()>,
+) -> 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(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(())
+}
+
+/// Holds the inputs and records the submission before broadcasting, then stores
+/// the transaction unless the node definitively rejected it.
+///
+/// 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 {
+    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);
+    }
+    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> {
+    let bytes = hex::decode(txid)
+        .ok()
+        .filter(|b| b.len() == 32)
+        .ok_or_else(|| {
+            RuntimeError::with(ErrorCode::TransactionBuildError, json!({ "stage": "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;
+    }
+
+    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)
+}
+
+/// 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;
+
+#[cfg(all(test, not(target_arch = "wasm32")))]
+mod submit_state_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]),
+        )
+    }
+
+    /// 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, 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();
+        for (table, output, ..) in SPEND_TABLES {
+            conn.execute_batch(&format!(
+                "CREATE TABLE {table} ({output} INTEGER, transaction_id INTEGER);"
+            ))
+            .unwrap();
+        }
+        conn.execute(
+            "INSERT INTO transactions VALUES (1, ?1, NULL, 1040)",
+            [[1_u8; 32]],
+        )
+        .unwrap();
+        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();
+            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))
+    }
+
+    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();
+        // 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::*;
+
+    /// 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());
+        assert!(parse_change_pool("orchard").is_err());
+        assert!(parse_change_pool("sapling").is_err());
+        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;
+        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"
+        );
+    }
+
+    #[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"
+        );
+    }
+
+    #[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 the same pair in JS.
+        assert_eq!(tex.encode(), "tex1pyysjzgfpyysjzgfpyysjzgfpyysjzgfl7c006");
+        assert_eq!(t1.encode(), "t1JhNuqypTPZu5vdcjsvGHzbTCrTd9Xwtru");
+        assert!(recipient_is_tex(¶ms, &tex));
+        assert!(!recipient_is_tex(¶ms, &t1));
+    }
+}
+
+#[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};
+
+    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.
+    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()
+    }
+
+    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()
+    }
+
+    fn reason(error: &RuntimeError) -> String {
+        format!("{error:?}")
+    }
+
+    #[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());
+    }
+
+    #[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());
+    }
+
+    // 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);
+        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)
+        );
+    }
+
+    // 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);
+        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 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()
+            .unwrap()
+            .serialize()
+            .unwrap();
+        let error = combine_pczt(&original, &finalized).unwrap_err();
+        assert!(
+            reason(&error).contains("transparentScriptSig"),
+            "{}",
+            reason(&error)
+        );
+    }
+
+    // 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);
+        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")))]
+mod submit_tests {
+    use super::*;
+
+    #[test]
+    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_err();
+        assert_eq!(rejection.code, ErrorCode::BroadcastOutcomeUnknown);
+        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
+        );
+    }
+}
+
+#[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());
+    }
+}
+
+#[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 {
+        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(&[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);
+        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,
+        }
+    }
+
+    #[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);
+            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)",
+            [[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;
+        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()
+    }
+
+    /// 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() {
+            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);
+
+            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, &[]));
+    }
+}
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..5921ef1cf
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/stats.rs
@@ -0,0 +1,266 @@
+//! 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 can yield NULL under some
+//! aggregates instead of an error.
+
+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` 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))
+        .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))
+}
+
+/// 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 is usually the largest BLOB column in the database.
+        "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 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"),
+            "retained",
+        )?,
+        "marksRemoved": count(
+            conn,
+            &format!("SELECT COUNT(*) FROM {prefix}_tree_checkpoint_marks_removed"),
+            "marksRemoved",
+        )?,
+    }))
+}
+
+/// Storage usage of the wallet database by group, as a JSON string.
+pub fn storage_stats(conn: &Connection) -> Result {
+    // 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")?;
+
+    Ok(json!({
+        "sqlite": {
+            "pageSize": page_size,
+            "pageCount": page_count,
+            "freePages": free_pages,
+            // Logical size only; physical storage usage can differ.
+            "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")?,
+            // 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")?,
+        },
+        "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")?,
+            // Full transaction bytes, present only for own or enhanced transactions.
+            "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",
+            )?,
+        },
+        // 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")?,
+            "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",
+            )?,
+            // In-flight migration PCZTs can be large and grow with each run.
+            "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::*;
+
+    /// 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("migrate");
+        drop(db);
+
+        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");
+
+        for group in [
+            "sqlite",
+            "scan",
+            "trees",
+            "wallet",
+            "transient",
+            "poolMigration",
+        ] {
+            assert!(v.get(group).is_some(), "missing group {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} missing {k}");
+            }
+        }
+        // Unscanned heights are null, not 0, which would read as genesis.
+        assert!(v["scan"]["minHeight"].is_null());
+        assert!(v["scan"]["maxHeight"].is_null());
+        // 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);
+
+        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..0c81d0f18
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/storage.rs
@@ -0,0 +1,437 @@
+//! 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;
+
+#[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<
+        Option>,
+    > = const { std::cell::RefCell::new(None) };
+}
+
+#[cfg(target_arch = "wasm32")]
+fn persistent_vfs() -> Result> {
+    VFS_UTIL.with(|slot| slot.borrow().clone()).ok_or_else(|| {
+        RuntimeError::with(
+            ErrorCode::NotInitialized,
+            json!({ "reason": "vfsNotInstalled" }),
+        )
+    })
+}
+
+/// The OPFS API the pool needs, checked before install: an outdated WebView would
+/// otherwise throw a bare TypeError the host cannot tell apart from other failures.
+#[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")
+}
+
+/// 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::sahpool::{install, OpfsSAHError, OpfsSAHPoolCfg};
+
+    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(),
+        clear_on_init: false,
+        // Two network databases plus their rollback journals and spare handles.
+        initial_capacity: 6,
+    };
+    // 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 {
+            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 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:?}"))
+                    );
+                }
+                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(())
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+pub async fn install_persistent_vfs() -> Result<()> {
+    Ok(())
+}
+
+/// 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.
+pub async fn durability_barrier() -> Result<()> {
+    if requires_worker_restart() {
+        return Err(RuntimeError::with(
+            ErrorCode::DatabaseError,
+            json!({ "reason": "storageRequiresWorkerRestart" }),
+        ));
+    }
+    if !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)
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+pub fn is_ready() -> bool {
+    true
+}
+
+pub fn open_connection(db_name: &str) -> Result {
+    if !is_ready() {
+        return Err(RuntimeError::new(ErrorCode::NotInitialized));
+    }
+    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)?;
+    // 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;")?;
+    // SAH-pool uses rollback journals, not cross-context WAL coordination.
+    // Never weaken transaction durability to improve scan throughput.
+    #[cfg(target_arch = "wasm32")]
+    conn.execute_batch("PRAGMA journal_mode = DELETE; PRAGMA synchronous = FULL;")?;
+    rusqlite::vtab::array::load_module(&conn)?;
+    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. 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 {
+    persistent_vfs()?
+        .exists(db_name)
+        .map_err(|error| db_storage_err("inspectDatabase", db_name, error))
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+pub async fn database_exists(db_name: &str) -> Result {
+    Ok(std::path::Path::new(db_name).exists())
+}
+
+#[cfg(target_arch = "wasm32")]
+pub async fn delete_database(db_name: &str) -> Result {
+    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(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)),
+    }
+}
+
+#[cfg(target_arch = "wasm32")]
+fn db_storage_err(operation: &str, db_name: &str, error: impl std::fmt::Debug) -> RuntimeError {
+    RuntimeError::with(
+        ErrorCode::DatabaseError,
+        json!({ "operation": operation, "dbName": db_name }),
+    )
+    .detail(format!("{error:?}"))
+}
+
+#[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
+            .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)
+    }
+
+    #[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);
+    }
+
+    #[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);
+    }
+
+    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; 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]
+    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);
+    }
+}
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..8fa3a2b2c
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync.rs
@@ -0,0 +1,1346 @@
+//! Chain scanning with bounded progress.
+//!
+//! 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.
+
+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::{BlockSource, ChainState, CommitmentTreeRoot};
+use zcash_client_backend::data_api::scanning::{ScanPriority, ScanRange};
+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_primitives::transaction::{Transaction, TxId};
+use zcash_protocol::consensus::{BlockHeight, BranchId, NetworkUpgrade, Parameters};
+
+use crate::blockcache::MemoryBlockCache;
+use crate::error::{ErrorCode, Result, RuntimeError};
+use crate::network::LightClient;
+use crate::wallet::Db;
+
+/// Bound speculative scanning to the earlier Ironwood / Orchard tail, capped at 30 days.
+/// 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;
+
+/// 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,
+    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()
+        .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| {
+            // Historic and demoted ChainTip ranges 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 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"] {
+                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, fall back to upstream's ChainTip start until sequential scanning fills the gap.
+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.
+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"] }),
+            ))
+        }
+    })
+}
+
+/// Suggested rewind depth on reorg.
+///
+/// Too deep forces a long rescan, too shallow may not pass the fork point.
+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)
+}
+
+/// Fetch all subtree roots for one pool.
+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 {
+        // 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,
+            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)
+}
+
+/// One-off setup: load subtree roots for all three pools and update the chain tip.
+///
+/// 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,
+        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())
+}
+
+/// Update only the chain tip, leaving subtree roots untouched.
+///
+/// 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))
+        .map_err(|e| db_err("updateChainTip", e))?;
+    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;
+/// the host decides whether to call again.
+pub async fn step(
+    db: &mut Db,
+    client: &mut LightClient,
+    batch_size: u32,
+    max_batches: u32,
+    preferred: Option,
+    active_ufvks: &[String],
+) -> Result {
+    check_step_size(batch_size, 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))?;
+
+        // 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() {
+            scanned_from = Some(u32::from(start));
+        }
+        scanned_priority = Some(format!("{:?}", range.priority()));
+
+        let t_start = now_ms();
+
+        // 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 =
+                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 = 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 {
+                Ok(got) => break (candidate, got),
+                Err(e) => {
+                    if e.code != ErrorCode::NetworkError {
+                        return Err(e);
+                    }
+                    if same_size_retry > 0 {
+                        same_size_retry -= 1;
+                        continue;
+                    }
+                    if attempt_len <= MIN_DOWNLOAD_BATCH {
+                        return Err(e);
+                    }
+                    attempt_len = std::cmp::max(MIN_DOWNLOAD_BATCH, attempt_len / 2);
+                }
+            }
+        };
+        // 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));
+        } 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));
+            }
+        }
+        // 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;
+
+        let t_scan = now_ms();
+
+        // Reorgs surface as REORG_DETECTED with an exact atHeight.
+        scan_blocks_inline(
+            ¶ms,
+            &cache,
+            db,
+            &scanning_keys,
+            start,
+            &chain_state,
+            batch_len,
+        )?;
+
+        ms_scan += now_ms() - t_scan;
+
+        blocks_scanned += batch_len as u64;
+
+        cache.delete(&batch).map_err(|e| db_err("cacheDelete", e))?;
+
+        batches_done += 1;
+    }
+
+    // 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)
+    };
+
+    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,
+        "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,
+        "remainingBlocks": remaining_blocks,
+        "remainingRanges": remaining.len(),
+        "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())
+}
+
+// Decrypts with active identities only; upstream would try every stored UFVK, including paused accounts.
+
+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);
+    // 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| {
+            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)
+}
+
+/// Scans a batch of blocks inline and stores the results, without upstream
+/// `scan_cached_blocks`.
+///
+/// `scan_cached_blocks` uses rayon, which has no workers on single-threaded wasm32 and
+/// blocks forever at the first block with shielded outputs; `scanning::scan_block` decrypts inline.
+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 {
+            // 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(
+                    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.
+///
+/// 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,
+    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))
+}
+
+/// Sync completeness for a single account. No network requests.
+///
+/// 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(
+        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 (chain_tip, fully_scanned) = scan_heights(db)?;
+
+    let scanned_to = lowest_pending.or(chain_tip);
+
+    Ok(json!({
+        "birthdayHeight": birthday,
+        "chainTip": chain_tip,
+        "fullyScannedHeight": fully_scanned,
+        "scannedToHeight": scanned_to,
+        "remainingBlocks": remaining,
+        "isComplete": remaining == 0,
+    })
+    .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
+        .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();
+    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")]
+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)
+}
+
+/// Anchor at `start - 1`, but not below Sapling activation.
+///
+/// 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)
+        .map(u32::from)
+        .unwrap_or(1);
+    u32::from(start).saturating_sub(1).max(sapling)
+}
+
+/// Soft download budget. Past it, scan the contiguous prefix received so far
+/// 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
+/// (a contiguous prefix).
+///
+/// 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,
+    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 {
+            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, // stream ended normally (full batch)
+            Err(e) => {
+                if blocks.is_empty() {
+                    return Err(e); // stalled with nothing received
+                }
+                break;
+            }
+        }
+    }
+
+    let got = blocks.len();
+    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)
+}
+
+/// 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,
+    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(())
+}
+
+/// Rewind the wallet to `height` so later syncs rescan above it.
+///
+/// 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
+        .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.
+///
+/// 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()
+        .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())
+}
+
+#[cfg(test)]
+#[path = "sync_tests.rs"]
+mod scan_order_tests;
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    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,
+            &[seed_byte; 32],
+            0u32.try_into().expect("valid ZIP-32 account index"),
+        )
+        .expect("test seed derives a USK")
+        .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());
+        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(
+        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());
+            assert_eq!(anchor_height(&net, BlockHeight::from_u32(1)), sapling);
+            assert_eq!(anchor_height(&net, BlockHeight::from_u32(sapling)), sapling);
+            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
+        }));
+
+        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/sync_tests.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs
new file mode 100644
index 000000000..486d5e532
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/sync_tests.rs
@@ -0,0 +1,1723 @@
+//! 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;
+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;
+        }
+    }
+}
+
+/// 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,
+    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]);
+    // 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);
+    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() {
+    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 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();
+            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(
+                std::slice::from_ref(&upstream),
+                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,
+                std::slice::from_ref(&original),
+                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,
+        std::slice::from_ref(&original),
+        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/tx_state.rs b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
new file mode 100644
index 000000000..e7115b570
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/tx_state.rs
@@ -0,0 +1,498 @@
+//! OneKey-owned send state: node rejections and submissions awaiting their outcome.
+//!
+//! The wallet schema cannot hold that the trusted node definitively rejected a
+//! 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;
+
+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 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),
+        Box::new(SubmissionsMigration),
+    ]
+}
+
+/// 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 {
+    fn id(&self) -> Uuid {
+        LIFECYCLE_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 LifecycleMigration {
+    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(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))
+    }
+}
+
+/// 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,
+        serde_json::json!({ "operation": operation }),
+    )
+    .detail(error)
+}
+
+/// 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),
+        )
+        .map_err(|error| db_err("readAccountForTxid", error))
+    })?;
+    uuid::Uuid::from_slice(&bytes)
+        .map(|uuid| uuid.to_string())
+        .map_err(|error| db_err("parseAccountForTxid", error))
+}
+
+/// Records the node's definitive rejection of a stored transaction.
+pub fn record_rejection(
+    db: &mut Db,
+    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)?;
+    let rejection_code = error
+        .params
+        .get("errorCode")
+        .and_then(serde_json::Value::as_i64);
+    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.
+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)
+        }
+    }
+}
+
+/// This account's stored outgoing transactions that are neither mined, expired
+/// 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
+        .prepare(&format!(
+            "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 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("listPendingBroadcasts", error))?;
+    let rows = stmt
+        .query_map([account_uuid], |row| row.get::<_, Vec>(0))
+        .map_err(|error| db_err("listPendingBroadcasts", error))?;
+    rows.map(|row| {
+        row.map(|bytes| hex_display_order(&bytes))
+            .map_err(|error| db_err("listPendingBroadcasts", error))
+    })
+    .collect()
+}
+
+/// 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(())
+}
+
+#[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;
+
+    fn wallet(conn: rusqlite::Connection) -> Db {
+        WalletDb::from_connection(
+            conn,
+            Network::TestNetwork,
+            HostClock,
+            ChaCha20Rng::from_seed([7; 32]),
+        )
+    }
+
+    #[test]
+    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,
+               rejection_code INTEGER,
+               rejection_reason TEXT
+             );",
+        )
+        .unwrap();
+        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_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);
+             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,
+               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, 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, mined_height, expired_unmined, total_spent, has_raw, rejected) in rows {
+            let txid = vec![byte; 32];
+            conn.execute(
+                "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 rejected {
+                conn.execute("INSERT INTO ext_onekey_tx_state VALUES (?1)", [txid])
+                    .unwrap();
+            }
+        }
+
+        assert_eq!(
+            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
new file mode 100644
index 000000000..67ed58572
--- /dev/null
+++ b/chain-runtimes/zcash/crates/zcash-runtime/src/wallet.rs
@@ -0,0 +1,255 @@
+//! Opening and initializing the wallet database: storage, `WalletDb` and schema migrations.
+
+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;
+
+use crate::clock::HostClock;
+use crate::error::{ErrorCode, Result, RuntimeError};
+use crate::storage;
+use serde_json::json;
+
+pub type Db = WalletDb;
+
+/// Parses the network name passed across the wasm boundary.
+pub fn parse_network(s: &str) -> Result {
+    match s {
+        "main" => Ok(Network::MainNetwork),
+        "test" => Ok(Network::TestNetwork),
+        other => Err(RuntimeError::with(
+            ErrorCode::InvalidNetwork,
+            json!({ "value": other }),
+        )),
+    }
+}
+
+/// 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 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.
+    let rng = ChaCha20Rng::from_seed(random_seed()?);
+
+    let mut db = WalletDb::from_connection(conn, params, HostClock, rng);
+
+    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())
+}
+
+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.
+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];
+    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 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)));
+        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]
+    fn seed_is_not_all_zero() {
+        let s = random_seed().expect("random bytes available");
+        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()));
+        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);
+    }
+}
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/.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..9af7c348f
--- /dev/null
+++ b/chain-runtimes/zcash/patches/manifest.json
@@ -0,0 +1,20 @@
+[
+  {
+    "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-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/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..71776fce5
--- /dev/null
+++ b/chain-runtimes/zcash/patches/sqlite-wasm-vfs-0.2.0-opfs-durability.patch
@@ -0,0 +1,696 @@
+--- 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,55 @@
+         } 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
++    }
++
++    /// Best-effort truncate of a free file's old payload (a dropped database
++    /// 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 {
++            let _ = sah.truncate_with_u32(HEADER_OFFSET_DATA as u32);
++        }
+     }
+ 
+     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 +560,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(())
+                 };
+                 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();
++            // 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 +636,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 +647,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 +678,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 +690,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 +844,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 +862,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 +874,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 +895,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 +965,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 +997,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 +1010,7 @@
+             app_data
+                 .open_files
+                 .borrow_mut()
+-                .insert(vfs_file.name().into());
++                .open(pFile as usize, vfs_file.name());
+         }
+         ret
+     }
+@@ -841,6 +1151,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 +1209,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 +1217,7 @@
+ 
+     /// Does the database exists.
+     pub fn exists(&self, filename: &str) -> Result {
++        self.pool.ensure_usable()?;
+         Ok(self.pool.has_filename(filename))
+     }
+ 
+@@ -971,6 +1288,7 @@
+     };
+ 
+     let pool = unsafe { SyncAccessHandleStore::app_data(vfs) };
++    pool.ensure_usable()?;
+     pool.vfs.set((vfs, default_vfs));
+ 
+     Ok(OpfsSAHPoolUtil { pool })
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,
+ 
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..2baa1456b
--- /dev/null
+++ b/chain-runtimes/zcash/patches/zcash_client_sqlite-0.22.0-no-bundled.patch
@@ -0,0 +1,123 @@
+--- a/Cargo.toml
++++ b/Cargo.toml
+@@ -229,7 +229,6 @@
+ [dependencies.rusqlite]
+ version = "0.37"
+ features = [
+-    "bundled",
+     "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,
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/artifact-manifest.py b/chain-runtimes/zcash/scripts/artifact-manifest.py
new file mode 100644
index 000000000..5d62db06e
--- /dev/null
+++ b/chain-runtimes/zcash/scripts/artifact-manifest.py
@@ -0,0 +1,81 @@
+#!/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"}
+
+
+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 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}")
+
+
+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
new file mode 100755
index 000000000..3f8971cc1
--- /dev/null
+++ b/chain-runtimes/zcash/scripts/build-wasm.sh
@@ -0,0 +1,73 @@
+#!/usr/bin/env bash
+# Build the browser wasm packages.
+#
+# 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
+
+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
+
+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 "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 "==> 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" "$@"
+
+# 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
+fi
+
+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 ;;
+  # 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
+
+echo "==> Artifacts"
+ls -lh "${OUT}"/*.wasm | awk '{print "   ", $9, $5}'
+
+# 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' ' ')"
+
+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."
+fi
diff --git a/chain-runtimes/zcash/scripts/ci.sh b/chain-runtimes/zcash/scripts/ci.sh
new file mode 100644
index 000000000..66c5902e8
--- /dev/null
+++ b/chain-runtimes/zcash/scripts/ci.sh
@@ -0,0 +1,18 @@
+#!/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)"
+
+# Fixed file names for the publish workflow.
+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
new file mode 100644
index 000000000..685ea3730
--- /dev/null
+++ b/chain-runtimes/zcash/scripts/package-release.py
@@ -0,0 +1,120 @@
+#!/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
+# 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):
+    return tomllib.loads((root / "Cargo.toml").read_text())["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 = "next" if match.group(1) 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, (module, name) in PACKAGES.items():
+        target = root / directory
+        path = target / "package.json"
+        package = json.loads(path.read_text())
+        # 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")
+        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")
+        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, module, 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"}
+        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")
+        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, (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 != archive_name(name, expected):
+            raise ValueError("Unexpected npm archive filename")
+        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")
+
+
+if __name__ == "__main__":
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("operation", choices=("prepare", "pack"))
+    parser.add_argument("--version")
+    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()
+    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/prepare-vendor.py b/chain-runtimes/zcash/scripts/prepare-vendor.py
new file mode 100644
index 000000000..b97dd33ba
--- /dev/null
+++ b/chain-runtimes/zcash/scripts/prepare-vendor.py
@@ -0,0 +1,96 @@
+#!/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.
+    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, 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())
+    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")
+    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)
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..6d8e92d24
--- /dev/null
+++ b/chain-runtimes/zcash/scripts/test_artifact_manifest.py
@@ -0,0 +1,55 @@
+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"))
+artifact = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(artifact)
+
+
+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_both_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), 8)
+            path = root / "pkg-keys/onekey_zcash_keys_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()
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..c7af5e341
--- /dev/null
+++ b/chain-runtimes/zcash/scripts/test_package_release.py
@@ -0,0 +1,86 @@
+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_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')
+            (root / "LICENSE").write_text("license")
+            for package, (module, _name) in release.PACKAGES.items():
+                target = root / package
+                target.mkdir()
+                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"}))
+            with self.assertRaisesRegex(ValueError, "version mismatch"):
+                release.prepare(root)
+
+    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", "next")
+        release.check_version("0.1.0", "0.1.0", "latest")
+        for value, tag in (("0.1.0-alpha.1", "latest"), ("0.1.0", "next")):
+            with self.assertRaises(ValueError):
+                release.check_version(value, value, tag)
+        with self.assertRaises(ValueError):
+            release.check_version("0.1.0-rc.1", "0.1.0-rc.2", "next")
+
+    def test_missing_snippets_and_changed_bytes_are_rejected(self):
+        with tempfile.TemporaryDirectory() as directory:
+            root = Path(directory)
+            module, name = release.PACKAGES["pkg"]
+            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",
+                "snippets/helper.js": b"snippet",
+            }
+            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, 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, module, name, "0.1.0-rc.1")
+            pack({**files, f"{module}.js": b"changed"})
+            with self.assertRaisesRegex(ValueError, "differs"):
+                release.verify_tarball(archive, root, module, name, "0.1.0-rc.1")
+
+
+if __name__ == "__main__":
+    unittest.main()
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 1a9a813ed..a2fdda81d 100644
--- a/package.json
+++ b/package.json
@@ -9,7 +9,10 @@
     "create:view": "node scripts/create-nitro-view.js",
     "version:set": "node scripts/set-release-version.mjs",
     "version:patch": "node scripts/set-release-version.mjs --next",
-    "version:publish": "node scripts/validate-npm-dist-tag.mjs latest && 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 --tag latest"
+    "version:publish": "node scripts/validate-npm-dist-tag.mjs latest && 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 --tag latest",
+    "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/*",