From ffea4bf9df8a24ebf9e9d67349a5b1ae42330c21 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 18 Sep 2026 13:45:59 -0400 Subject: [PATCH] wallet: land the in-process Cuprate chain source on main MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P, consensus and RandomX run inside the OnionWire process instead of as a spawned `monerod`. The wallet layer does not move — the daemon binds the same loopback unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment frames and the receipt-verification path are untouched. - Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the `cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is disabled (`default-features = false`): its arti-client 0.44 cannot unify with this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in the process. `Cargo.lock` gains the graph; a default build's `cargo tree --locked -e normal -i cuprated` still says "did not match any packages", and only `arti-client v0.46.0` is in the lock. - src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML (testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P off), launches it on a runtime it owns, and owns the node. `launch` is synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its blocking thread, UniFFI calls it from an async context) and a runtime cannot be started from inside a runtime, so the launch runs on a thread of its own and the node + its runtime come back over a channel. Dropping the value asks the node to shut down and `shutdown_background`s the runtime, which is the only exit that cannot panic when the value is dropped inside another runtime. The type exists in every build (feature off: `launch` fails with the feature name), so the chain-source type, its stored record and its copy do not fork on a cargo feature. - src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon client the wallet line carried (typed `WalletError`, de-chunked HTTP, `get_height` over the URI endpoint, an above-the-tip height as one typed error). Cuprate answers those three differently from monerod and the in-process source is what makes them the *local* case. - src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the free-space/ownership question, the honest `chain_copy` line, `kind = "cuprate"` in the sealed record, and `ChildConfig::validate` for it. - src/tui.rs: the wallet screen's chain line carries the testnet caveat when the configured source is the in-process one. It computes the line at draw time, so `Screen::Wallet`'s shape (which tests construct) does not change. - docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the feature flag and how to enable it, where the (fjall) chain store lives, the **measured** +11.8 MiB delta, the pre-production/testnet caveat, and the in-repo aarch64-linux-android proof with exit codes. Scope deviations, stated plainly: - `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's allowed list; the card's own deliverable describes the module's behaviour. - `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a `pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the root CI `sdk` job runs on every PR. One variant plus two match arms land here so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card owns the rest — feature passthrough, the config field's semantics, the label and its tests, and the Android check. - `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched: main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7 work, and `docs/WALLET.md` says so rather than describing a picker that does not exist). Proof (all on this tree): - Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345 passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked --all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0. - Feature on: `cargo test --locked --features cuprate-daemon --target x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with `--features cuprate-daemon` exit 0. The two extra tests are the real thing: `wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down` and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client` — the latter launches the node, drives `get_info` / `get_height` / `get_block` through the typed client, checks the above-the-tip 500 maps to `DaemonHeightOutOfRange`, checks the chain store is under the chain datadir, and checks the listener dies with the node. - aarch64: `cargo check --locked --release --target aarch64-linux-android --features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0 (`cargo rustc ... --bin onionwire -- `) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26, built by NDK r28c`. - Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and 37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure `docs/WALLET.md` now quotes. --- Cargo.lock | 1509 ++++++++++++++++++++++++++++++- Cargo.toml | 18 + crates/onionwire-sdk/src/lib.rs | 26 +- docs/THREAT_MODEL.md | 29 +- docs/WALLET.md | 74 +- docs/cuprate-android-spike.md | 47 +- src/cuprate.rs | 298 ++++++ src/lib.rs | 1 + src/tui.rs | 25 +- src/wallet.rs | 352 +++++++ src/wallet_child.rs | 336 ++++++- tests/wallet.rs | 109 +++ 12 files changed, 2789 insertions(+), 35 deletions(-) create mode 100644 src/cuprate.rs diff --git a/Cargo.lock b/Cargo.lock index df3aebe..52967c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -125,6 +125,18 @@ dependencies = [ "libc", ] +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "approx" version = "0.5.1" @@ -134,6 +146,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "arc-swap" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +dependencies = [ + "rustversion", +] + [[package]] name = "argon2" version = "0.5.3" @@ -334,12 +355,66 @@ dependencies = [ "bytemuck", ] +[[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 = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + [[package]] name = "base16ct" version = "0.2.0" @@ -368,6 +443,21 @@ dependencies = [ "unty", ] +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + [[package]] name = "bitflags" version = "1.3.2" @@ -379,6 +469,10 @@ name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "bytemuck", + "serde_core", +] [[package]] name = "bitvec" @@ -401,6 +495,19 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures 0.3.1", +] + [[package]] name = "blanket" version = "0.3.0" @@ -431,6 +538,30 @@ dependencies = [ "zeroize", ] +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.5", +] + [[package]] name = "bs58" version = "0.5.1" @@ -468,6 +599,20 @@ name = "bytemuck" version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] [[package]] name = "byteorder" @@ -475,11 +620,26 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + +[[package]] +name = "byteview" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d74937895e761d5984206f82ca8ff7725d0fd8021921011921894b41ab1b9f7" [[package]] name = "caret" @@ -514,6 +674,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "chacha20" version = "0.9.1" @@ -584,6 +750,55 @@ dependencies = [ "zeroize", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstyle", + "clap_lex", + "strsim 0.11.1", + "terminal_size", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + [[package]] name = "cmov" version = "0.5.4" @@ -615,6 +830,12 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "compare" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea0095f6103c2a8b44acd6fd15960c801dafebf02e21940360833e0673f48ba7" + [[package]] name = "compression-codecs" version = "0.4.41" @@ -646,6 +867,34 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "const_format" +version = "0.2.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4481a617ad9a412be3b97c5d403fef8ed023103368908b9c50af598ff467cc1e" +dependencies = [ + "const_format_proc_macros", + "konst", +] + +[[package]] +name = "const_format_proc_macros" +version = "0.2.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", + "unicode-xid", +] + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "convert_case" version = "0.10.0" @@ -713,6 +962,47 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e71406cd8807725f7ac2f999a4cdd32e98f829fdf65f528343cebf945e41df1e" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-epoch", + "crossbeam-queue", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-queue" version = "0.3.14" @@ -722,6 +1012,16 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-skiplist" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df29de440c58ca2cc6e587ec3d22347551a32435fbde9d2bff64e78a9ffa151b" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -767,6 +1067,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "crypto-bigint" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271" +dependencies = [ + "cpubits", + "ctutils", + "num-traits", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -814,6 +1125,491 @@ dependencies = [ "cmov", ] +[[package]] +name = "cuprate-address-book" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "borsh", + "cuprate-constants", + "cuprate-p2p-core", + "cuprate-pruning", + "futures", + "indexmap 2.14.2", + "rand 0.8.8", + "thiserror 2.0.20", + "tokio", + "tokio-util", + "tower", + "tracing", +] + +[[package]] +name = "cuprate-async-buffer" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "futures", + "pin-project", + "thiserror 2.0.20", +] + +[[package]] +name = "cuprate-blockchain" +version = "0.0.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "arc-swap", + "bytemuck", + "bytes", + "crossbeam", + "cuprate-constants", + "cuprate-helper", + "cuprate-pruning", + "cuprate-types", + "fjall", + "futures", + "indexmap 2.14.2", + "monero-oxide", + "rand 0.8.8", + "rayon", + "serde", + "tapes", + "thiserror 2.0.20", + "tower", + "tracing", +] + +[[package]] +name = "cuprate-consensus" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "cfg-if", + "cuprate-consensus-context", + "cuprate-consensus-rules", + "cuprate-helper", + "cuprate-types", + "hex", + "indexmap 2.14.2", + "monero-oxide", + "rand 0.8.8", + "rayon", + "thiserror 2.0.20", + "thread_local", + "tower", + "tracing", +] + +[[package]] +name = "cuprate-consensus-context" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "arc-swap", + "cuprate-consensus-rules", + "cuprate-helper", + "cuprate-types", + "futures", + "hex", + "monero-oxide", + "randomx-rs", + "rayon", + "strum", + "thread_local", + "tokio", + "tokio-util", + "tower", + "tracing", +] + +[[package]] +name = "cuprate-consensus-rules" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "cfg-if", + "crypto-bigint 0.7.5", + "cuprate-constants", + "cuprate-cryptonight", + "cuprate-helper", + "cuprate-types", + "curve25519-dalek", + "hex", + "hex-literal 1.1.0", + "indexmap 2.14.2", + "monero-oxide", + "rand 0.8.8", + "rayon", + "thiserror 2.0.20", + "tracing", +] + +[[package]] +name = "cuprate-constants" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" + +[[package]] +name = "cuprate-cryptonight" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "digest 0.10.7", + "groestl", + "jh", + "keccak 0.1.6", + "seq-macro", + "sha3 0.10.9", + "skein", + "thiserror 2.0.20", +] + +[[package]] +name = "cuprate-dandelion-tower" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "futures", + "rand 0.8.8", + "rand_distr", + "thiserror 2.0.20", + "tokio", + "tokio-util", + "tower", + "tracing", +] + +[[package]] +name = "cuprate-epee-encoding" +version = "0.5.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "bytes", + "cuprate-fixed-bytes", + "cuprate-hex", + "paste", + "ref-cast", + "thiserror 2.0.20", +] + +[[package]] +name = "cuprate-fast-sync" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "blake3", + "clap", + "cuprate-blockchain", + "cuprate-consensus", + "cuprate-consensus-context", + "cuprate-helper", + "cuprate-hex", + "cuprate-p2p", + "cuprate-p2p-core", + "cuprate-types", + "fjall", + "futures", + "hex", + "monero-oxide", + "rayon", + "serde_json", + "tokio", + "tower", + "tracing-subscriber", +] + +[[package]] +name = "cuprate-fixed-bytes" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "bytes", + "serde", + "thiserror 2.0.20", +] + +[[package]] +name = "cuprate-helper" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "chrono", + "cuprate-constants", + "curve25519-dalek", + "dirs", + "futures", + "libc", + "monero-oxide", + "rayon", + "serde", + "windows", +] + +[[package]] +name = "cuprate-hex" +version = "0.0.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "hex", + "serde", +] + +[[package]] +name = "cuprate-json-rpc" +version = "0.0.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.20", +] + +[[package]] +name = "cuprate-levin" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "cfg-if", + "cuprate-helper", + "thiserror 2.0.20", + "tokio-util", + "tracing", +] + +[[package]] +name = "cuprate-p2p" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "borsh", + "bytes", + "cuprate-address-book", + "cuprate-async-buffer", + "cuprate-constants", + "cuprate-fixed-bytes", + "cuprate-helper", + "cuprate-p2p-core", + "cuprate-pruning", + "cuprate-types", + "cuprate-wire", + "futures", + "indexmap 2.14.2", + "monero-oxide", + "pin-project", + "rand 0.8.8", + "rand_distr", + "rayon", + "thiserror 2.0.20", + "tokio", + "tokio-stream", + "tokio-util", + "tower", + "tracing", +] + +[[package]] +name = "cuprate-p2p-core" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "async-trait", + "borsh", + "cfg-if", + "cuprate-helper", + "cuprate-pruning", + "cuprate-types", + "cuprate-wire", + "futures", + "hex", + "hex-literal 1.1.0", + "rand 0.8.8", + "thiserror 2.0.20", + "tokio", + "tokio-stream", + "tokio-util", + "tower", + "tracing", +] + +[[package]] +name = "cuprate-p2p-transport" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "async-trait", + "cuprate-p2p-core", + "cuprate-wire", + "futures", + "tokio", + "tokio-socks", + "tokio-util", +] + +[[package]] +name = "cuprate-pruning" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "borsh", + "cuprate-constants", + "thiserror 2.0.20", +] + +[[package]] +name = "cuprate-rpc-interface" +version = "0.0.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "anyhow", + "axum", + "cuprate-epee-encoding", + "cuprate-helper", + "cuprate-json-rpc", + "cuprate-rpc-types", + "futures", + "paste", + "serde", + "serde_json", + "tower", +] + +[[package]] +name = "cuprate-rpc-types" +version = "0.0.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "cuprate-epee-encoding", + "cuprate-fixed-bytes", + "cuprate-helper", + "cuprate-hex", + "cuprate-p2p-core", + "cuprate-types", + "hex", + "monero-oxide", + "paste", + "serde", + "serde_json", +] + +[[package]] +name = "cuprate-txpool" +version = "0.0.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "bitflags 2.13.2", + "blake3", + "bytemuck", + "cuprate-helper", + "cuprate-types", + "fjall", + "futures", + "hex", + "monero-oxide", + "rayon", + "thiserror 2.0.20", + "tower", +] + +[[package]] +name = "cuprate-types" +version = "0.0.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "cfg-if", + "cuprate-epee-encoding", + "cuprate-fixed-bytes", + "cuprate-helper", + "cuprate-hex", + "indexmap 2.14.2", + "monero-oxide", + "proptest", + "proptest-derive", + "serde", + "strum", + "thiserror 2.0.20", +] + +[[package]] +name = "cuprate-wire" +version = "0.1.0" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "bitflags 2.13.2", + "borsh", + "bytes", + "cuprate-epee-encoding", + "cuprate-fixed-bytes", + "cuprate-helper", + "cuprate-levin", + "cuprate-types", + "serde", + "thiserror 2.0.20", +] + +[[package]] +name = "cuprated" +version = "0.1.0-preview" +source = "git+https://github.com/Cuprate/cuprate?rev=4f8fcd1bf468f566fcd89c460d50de4adb6825bf#4f8fcd1bf468f566fcd89c460d50de4adb6825bf" +dependencies = [ + "anyhow", + "axum", + "borsh", + "bytes", + "clap", + "const_format", + "cuprate-address-book", + "cuprate-blockchain", + "cuprate-consensus", + "cuprate-consensus-context", + "cuprate-consensus-rules", + "cuprate-constants", + "cuprate-cryptonight", + "cuprate-dandelion-tower", + "cuprate-fast-sync", + "cuprate-fixed-bytes", + "cuprate-helper", + "cuprate-hex", + "cuprate-p2p", + "cuprate-p2p-core", + "cuprate-p2p-transport", + "cuprate-pruning", + "cuprate-rpc-interface", + "cuprate-rpc-types", + "cuprate-txpool", + "cuprate-types", + "cuprate-wire", + "dashmap", + "fjall", + "futures", + "hex", + "hyper", + "hyper-util", + "indexmap 2.14.2", + "monero-address", + "monero-oxide", + "nu-ansi-term", + "pin-project-lite", + "rayon", + "serde", + "serde_json", + "sysinfo", + "thiserror 2.0.20", + "tokio", + "tokio-util", + "toml 1.1.5+spec-1.1.0", + "toml_edit 0.25.13+spec-1.1.0", + "tower", + "tower-http", + "tracing", + "tracing-appender", + "tracing-subscriber", +] + [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -944,6 +1740,20 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "dashmap" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + [[package]] name = "data-encoding" version = "2.11.1" @@ -1247,7 +2057,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [ "base16ct", - "crypto-bigint", + "crypto-bigint 0.5.5", "digest 0.10.7", "ff", "generic-array", @@ -1405,6 +2215,23 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" +[[package]] +name = "fjall" +version = "3.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd201c93927cdf4712e8f7d4c9c8d34d68c7534380c05d4a58864a309f91c33f" +dependencies = [ + "byteorder-lite", + "byteview", + "dashmap", + "flume", + "log", + "lsm-tree", + "lz4_flex", + "tempfile", + "xxhash-rust", +] + [[package]] name = "flate2" version = "1.1.10" @@ -1422,6 +2249,15 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "749cff877dc1af878a0b31a41dd221a753634401ea0ef2f87b62d3171522485a" +[[package]] +name = "flume" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" +dependencies = [ + "spin 0.9.9", +] + [[package]] name = "fnv" version = "1.0.7" @@ -1676,6 +2512,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9985c9503b412198aa4197559e9a318524ebc4519c229bfa05a535828c950b9d" +[[package]] +name = "groestl" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "343cfc165f92a988fd60292f7a0bfde4352a5a0beff9fbec29251ca4e9676e4d" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "group" version = "0.13.0" @@ -1705,6 +2550,12 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + [[package]] name = "hashbrown" version = "0.15.5" @@ -1756,6 +2607,21 @@ name = "hex" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +dependencies = [ + "serde", +] + +[[package]] +name = "hex-literal" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" + +[[package]] +name = "hex-literal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1" [[package]] name = "hkdf" @@ -1791,6 +2657,29 @@ dependencies = [ "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" @@ -1829,6 +2718,41 @@ dependencies = [ "zeroize", ] +[[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", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -1992,6 +2916,7 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", + "rayon", "serde", "serde_core", ] @@ -2056,6 +2981,15 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "interval-heap" +version = "0.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11274e5e8e89b8607cfedc2910b6626e998779b48a019151c7604d0adcb86ac6" +dependencies = [ + "compare", +] + [[package]] name = "inventory" version = "0.3.24" @@ -2104,6 +3038,17 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jh" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f65735f9e73adc203417d2e05352aef71d7e832ec090f65de26c96c9ec563aa5" +dependencies = [ + "digest 0.10.7", + "hex-literal 0.4.1", + "ppv-lite86", +] + [[package]] name = "jiff" version = "0.2.35" @@ -2218,6 +3163,21 @@ dependencies = [ "cpufeatures 0.3.1", ] +[[package]] +name = "konst" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "128133ed7824fcd73d6e7b17957c5eb7bacb885649bd8c69708b2331a10bcefb" +dependencies = [ + "konst_macro_rules", +] + +[[package]] +name = "konst_macro_rules" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" + [[package]] name = "kqueue" version = "1.2.1" @@ -2244,7 +3204,7 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" dependencies = [ - "spin", + "spin 0.9.9", ] [[package]] @@ -2351,6 +3311,37 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "lsm-tree" +version = "3.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5498808f4d41cf785079d3ef3f28716f1b4364af1b512f3097bfb651bded1b3e" +dependencies = [ + "byteorder-lite", + "byteview", + "crossbeam-skiplist", + "enum_dispatch", + "interval-heap", + "log", + "lz4_flex", + "quick_cache", + "rustc-hash", + "self_cell", + "sfa", + "tempfile", + "varint-rs", + "xxhash-rust", +] + +[[package]] +name = "lz4_flex" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e" +dependencies = [ + "twox-hash", +] + [[package]] name = "matchers" version = "0.2.0" @@ -2360,6 +3351,12 @@ dependencies = [ "regex-automata", ] +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "md-5" version = "0.10.6" @@ -2397,6 +3394,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -2425,6 +3428,147 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "monero-address" +version = "0.1.0" +source = "git+https://github.com/monero-oxide/monero-oxide.git?rev=946ec5f#946ec5f00ff071b129758ee8cba5528539fccfe4" +dependencies = [ + "monero-base58", + "monero-ed25519", + "monero-io", + "monero-primitives", + "thiserror 2.0.20", + "zeroize", +] + +[[package]] +name = "monero-base58" +version = "0.1.0" +source = "git+https://github.com/monero-oxide/monero-oxide.git?rev=946ec5f#946ec5f00ff071b129758ee8cba5528539fccfe4" +dependencies = [ + "monero-primitives", + "std-shims", +] + +[[package]] +name = "monero-borromean" +version = "0.1.0" +source = "git+https://github.com/monero-oxide/monero-oxide.git?rev=946ec5f#946ec5f00ff071b129758ee8cba5528539fccfe4" +dependencies = [ + "curve25519-dalek", + "monero-ed25519", + "monero-io", + "std-shims", + "zeroize", +] + +[[package]] +name = "monero-bulletproofs" +version = "0.1.0" +source = "git+https://github.com/monero-oxide/monero-oxide.git?rev=946ec5f#946ec5f00ff071b129758ee8cba5528539fccfe4" +dependencies = [ + "curve25519-dalek", + "monero-bulletproofs-generators", + "monero-ed25519", + "monero-io", + "monero-primitives", + "rand_core 0.6.4", + "std-shims", + "thiserror 2.0.20", + "zeroize", +] + +[[package]] +name = "monero-bulletproofs-generators" +version = "0.1.0" +source = "git+https://github.com/monero-oxide/monero-oxide.git?rev=946ec5f#946ec5f00ff071b129758ee8cba5528539fccfe4" +dependencies = [ + "curve25519-dalek", + "monero-ed25519", + "monero-io", + "monero-primitives", + "std-shims", +] + +[[package]] +name = "monero-clsag" +version = "0.1.0" +source = "git+https://github.com/monero-oxide/monero-oxide.git?rev=946ec5f#946ec5f00ff071b129758ee8cba5528539fccfe4" +dependencies = [ + "curve25519-dalek", + "group", + "monero-ed25519", + "monero-io", + "rand_chacha 0.3.1", + "rand_core 0.6.4", + "std-shims", + "subtle", + "thiserror 2.0.20", + "zeroize", +] + +[[package]] +name = "monero-ed25519" +version = "0.1.0" +source = "git+https://github.com/monero-oxide/monero-oxide.git?rev=946ec5f#946ec5f00ff071b129758ee8cba5528539fccfe4" +dependencies = [ + "crypto-bigint 0.5.5", + "curve25519-dalek", + "monero-io", + "rand_core 0.6.4", + "sha3 0.10.9", + "std-shims", + "subtle", + "zeroize", +] + +[[package]] +name = "monero-io" +version = "0.1.0" +source = "git+https://github.com/monero-oxide/monero-oxide.git?rev=946ec5f#946ec5f00ff071b129758ee8cba5528539fccfe4" +dependencies = [ + "std-shims", +] + +[[package]] +name = "monero-mlsag" +version = "0.1.0" +source = "git+https://github.com/monero-oxide/monero-oxide.git?rev=946ec5f#946ec5f00ff071b129758ee8cba5528539fccfe4" +dependencies = [ + "curve25519-dalek", + "monero-ed25519", + "monero-io", + "std-shims", + "thiserror 2.0.20", + "zeroize", +] + +[[package]] +name = "monero-oxide" +version = "0.1.4-alpha" +source = "git+https://github.com/monero-oxide/monero-oxide.git?rev=946ec5f#946ec5f00ff071b129758ee8cba5528539fccfe4" +dependencies = [ + "curve25519-dalek", + "hex-literal 1.1.0", + "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 = "git+https://github.com/monero-oxide/monero-oxide.git?rev=946ec5f#946ec5f00ff071b129758ee8cba5528539fccfe4" +dependencies = [ + "sha3 0.10.9", +] + [[package]] name = "native-tls" version = "0.2.18" @@ -2635,6 +3779,7 @@ dependencies = [ "argon2", "arti-client", "chacha20poly1305", + "cuprated", "ed25519-dalek", "futures", "hkdf", @@ -2653,6 +3798,7 @@ dependencies = [ "snow", "tempfile", "tokio", + "toml 0.8.23", "tor-cell", "tor-hsservice", "tor-rtcompat", @@ -3098,6 +4244,36 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proptest" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "num-traits", + "rand 0.9.5", + "rand_chacha 0.9.0", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "proptest-derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c57924a81864dddafba92e1bf92f9bf82f97096c44489548a60e888e1547549b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "pwd-grp" version = "1.0.2" @@ -3116,6 +4292,22 @@ version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quick_cache" +version = "0.6.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9c6658afe513a3b484e3abfdaa0d03ef3c0bbf017542c178dd55f94eb3051f9" +dependencies = [ + "equivalent", + "hashbrown 0.16.1", +] + [[package]] name = "quote" version = "1.0.47" @@ -3154,6 +4346,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + [[package]] name = "rand" version = "0.10.2" @@ -3175,6 +4377,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + [[package]] name = "rand_chacha" version = "0.10.0" @@ -3194,12 +4406,31 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "rand_core" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rand_distr" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" +dependencies = [ + "num-traits", + "rand 0.8.8", +] + [[package]] name = "rand_jitter" version = "0.6.1" @@ -3211,6 +4442,27 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "rand_xorshift" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +dependencies = [ + "rand_core 0.9.5", +] + +[[package]] +name = "randomx-rs" +version = "1.4.1" +source = "git+https://github.com/Cuprate/randomx-rs.git?rev=76c2385#76c2385771ca5aca941e0991ebd822e6edb8d94d" +dependencies = [ + "bitflags 1.3.2", + "cc", + "cmake", + "libc", + "thiserror 1.0.69", +] + [[package]] name = "rangemap" version = "1.8.0" @@ -3283,6 +4535,26 @@ dependencies = [ "unicode-width", ] +[[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 = "rdrand" version = "0.9.0" @@ -3462,6 +4734,12 @@ dependencies = [ "time", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustc_version" version = "0.4.1" @@ -3534,6 +4812,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + [[package]] name = "ryu" version = "1.0.23" @@ -3653,12 +4943,24 @@ dependencies = [ "libc", ] +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + [[package]] name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + [[package]] name = "serde" version = "1.0.229" @@ -3732,6 +5034,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_spanned" version = "0.6.9" @@ -3783,6 +5096,17 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "sfa" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1296838937cab56cd6c4eeeb8718ec777383700c33f060e2869867bd01d1175" +dependencies = [ + "byteorder-lite", + "log", + "xxhash-rust", +] + [[package]] name = "sha1" version = "0.10.7" @@ -3905,6 +5229,16 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" +[[package]] +name = "skein" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96a90a220ab98dbbfeabeae7c558a79f37839c10b9ef55c77082a741a463cab7" +dependencies = [ + "digest 0.10.7", + "threefish", +] + [[package]] name = "slab" version = "0.4.12" @@ -3972,6 +5306,15 @@ name = "spin" version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spin" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" [[package]] name = "spki" @@ -4043,6 +5386,17 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[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 0.10.1", +] + [[package]] name = "strsim" version = "0.10.0" @@ -4082,6 +5436,12 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + [[package]] name = "syn" version = "1.0.109" @@ -4152,6 +5512,18 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +[[package]] +name = "tapes" +version = "0.2.0" +source = "git+https://github.com/Cuprate/Tapes.git?rev=04562f4#04562f44fd8e029ce0caf7dfa993682ffe69837d" +dependencies = [ + "blake2", + "borsh", + "bytemuck", + "parking_lot", + "slab", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -4165,6 +5537,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "terminal_size" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" +dependencies = [ + "rustix", + "windows-sys 0.59.0", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -4214,6 +5596,12 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "threefish" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a693d0c8cf16973fac5a93fbe47b8c6452e7097d4fcac49f3d7a18e39c76e62e" + [[package]] name = "time" version = "0.3.55" @@ -4281,6 +5669,7 @@ dependencies = [ "bytes", "libc", "mio", + "parking_lot", "pin-project-lite", "signal-hook-registry", "socket2", @@ -4299,6 +5688,29 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "tokio-socks" +version = "0.5.2" +source = "git+https://github.com/Cuprate/tokio-socks.git?rev=8737caf#8737caf429a86ab181954444fac4f9b917795b19" +dependencies = [ + "either", + "futures-util", + "thiserror 1.0.69", + "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", + "tokio-util", +] + [[package]] name = "tokio-util" version = "0.7.19" @@ -4309,8 +5721,12 @@ dependencies = [ "futures-core", "futures-io", "futures-sink", + "futures-util", + "libc", "pin-project-lite", + "slab", "tokio", + "tracing", ] [[package]] @@ -4381,6 +5797,7 @@ dependencies = [ "indexmap 2.14.2", "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", + "toml_writer", "winnow 1.0.4", ] @@ -5522,6 +6939,54 @@ dependencies = [ "tor-memquota", ] +[[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", + "tokio-util", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "http", + "http-body", + "http-body-util", + "percent-encoding", + "pin-project-lite", + "tokio", + "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" @@ -5533,6 +6998,19 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror 2.0.20", + "time", + "tracing-subscriber", +] + [[package]] name = "tracing-attributes" version = "0.1.31" @@ -5604,6 +7082,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "twox-hash" +version = "2.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5283634e518fe9e82c7b20520bb4bc209009fd16c82077c802f8111ecbb0117a" + [[package]] name = "typed-index-collections" version = "3.5.0" @@ -5620,6 +7104,12 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "uncased" version = "0.9.10" @@ -5720,6 +7210,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "varint-rs" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa6c38708f6257f1ec2ca7e5a11f9bbf58a27d7060078b6b333624968183d96" + [[package]] name = "vcpkg" version = "0.2.15" @@ -5749,6 +7245,15 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + [[package]] name = "walkdir" version = "2.5.0" diff --git a/Cargo.toml b/Cargo.toml index 7761aa5..4bd00bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,18 @@ repository = "https://github.com/sirius0xdev/onionwire" default = ["rustls"] native-tls = ["arti-client/native-tls"] rustls = ["arti-client/rustls"] +# In-process Monero chain daemon (Cuprate) as the local chain source, instead of +# spawning `monerod`. OFF by default: `cuprated` is pre-1.0 and is not published +# to crates.io (every Cuprate crate there is a `0.0.0-placeholder` name +# reservation), so this pins a git revision and pulls a large tree (RandomX, +# fjall, axum/hyper, rayon). See `docs/WALLET.md`, "The in-process chain daemon". +# +# Cuprate's own `arti` feature stays OFF (and is off in its default feature set, +# which is why `default-features = false` is load-bearing): it would link a +# second, older Tor stack (arti-client 0.44, which cannot unify with this +# crate's 0.46) next to OnionWire's. The in-process daemon runs clearnet-only; +# OnionWire's Arti is the only Tor in the process. +cuprate-daemon = ["dep:cuprated", "dep:toml"] [dependencies] arti-client = { version = "0.46", default-features = false, features = [ @@ -57,6 +69,12 @@ md-5 = "0.10" rpassword = "7" zeroize = { version = "1", features = ["derive"] } qrcode = { version = "0.14", default-features = false } +cuprated = { git = "https://github.com/Cuprate/cuprate", rev = "4f8fcd1bf468f566fcd89c460d50de4adb6825bf", default-features = false, optional = true } +# `cuprated::config::Config` is deserialized, not built field by field: the +# struct's nested types move with the pinned revision, a TOML document does not. +# Cuprate has `deny_unknown_fields` on every config struct, so a stale key is a +# parse error instead of a silently ignored setting. +toml = { version = "0.8", features = ["parse", "display"], optional = true } [dev-dependencies] tempfile = "3" diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index c03ad35..ad2f077 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -727,6 +727,9 @@ fn child_config(cfg: ChainConfig) -> ChildConfig { monerod_bin: PathBuf::from(cfg.monerod_bin), datadir: PathBuf::from(cfg.monerod_datadir), }, + ChainChoice::InProcessCuprate => ChainSource::InProcessCuprate { + datadir: PathBuf::from(cfg.monerod_datadir), + }, ChainChoice::Remote => ChainSource::Remote { host: cfg.host, port: cfg.port, @@ -760,6 +763,13 @@ fn chain_config(cfg: &ChildConfig) -> ChainConfig { monerod_bin.display().to_string(), datadir.display().to_string(), ), + ChainSource::InProcessCuprate { datadir } => ( + ChainChoice::InProcessCuprate, + String::new(), + 0, + String::new(), + datadir.display().to_string(), + ), ChainSource::Remote { host, port } => ( ChainChoice::Remote, host.clone(), @@ -881,15 +891,21 @@ pub enum ChainChoice { None, /// The app spawns `monerod` on this device. Local, + /// The chain daemon runs **inside this app** (Cuprate). No `monerod` binary. + /// Testnet only, and pre-production software — see the core's + /// `ChainSource::InProcessCuprate`. `monerod_datadir` is the chain data + /// directory for it, and no binary path is needed. + InProcessCuprate, /// A daemon address the user supplied (loopback, `.onion`, or clearnet). Remote, } /// The wallet-child settings, as the Kotlin side sets them. /// -/// One record for all three kinds: the fields a kind does not use are ignored +/// One record for all four kinds: the fields a kind does not use are ignored /// by that kind (`None` needs no binaries, `Local` needs `monerod_bin` and -/// `monerod_datadir`, `Remote` needs `host` and `port`). Persisted in the +/// `monerod_datadir`, `InProcessCuprate` needs only `monerod_datadir` as its +/// chain directory, `Remote` needs `host` and `port`). Persisted in the /// encrypted store, so it survives a restart without env vars. #[derive(Debug, Clone, uniffi::Record)] pub struct ChainConfig { @@ -898,6 +914,9 @@ pub struct ChainConfig { /// resolves on `PATH` on desktop. pub monerod_bin: String, /// `Local` only. Data directory for the local daemon. + /// + /// `InProcessCuprate` also uses this field, as the chain data directory the + /// in-process daemon stores its (fjall) chain in. pub monerod_datadir: String, /// `Remote` only. Daemon host. pub host: String, @@ -916,7 +935,8 @@ pub struct ChainConfig { /// Derived from the real child process plus the last probe, never from env-var /// presence. `state` is one of `off`, `connecting`, `syncing`, `ready`, /// `exited`. `chain_source` is the label of the configured source: -/// `receive-only`, `local node`, `remote onion daemon`, or `remote daemon`. +/// `receive-only`, `local node`, `in-process node`, `remote onion daemon`, or +/// `remote daemon`. #[derive(Debug, Clone, uniffi::Record)] pub struct WalletChildStatus { /// `off` until the child is started and again after it is stopped; `exited` diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 52d4506..9fd2b6c 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -193,7 +193,34 @@ the app does not pick a public remote node for them. Unsynced or not running is an honest “not ready” / unverified state, not a fake success. -2. **A daemon address they supply.** The wallet child points `--daemon-address` +2. **An in-process daemon** (Cuprate, behind the `cuprate-daemon` feature, off by + default). P2P, consensus and RandomX run in the OnionWire process; nothing is + spawned and nothing leaves the device except the chain P2P traffic itself. + What that changes: there is **no daemon operator** to trust — your own process + is the daemon, so the "operator sees your addresses" question does not exist. + The spend key, the chain, and the messenger are then all on one device. + What it does not change: the **device is now the trust root for chain data**. + Chain state is only as trustworthy as the binary running it, and a + compromised device corrupts the chain view along with everything else. + Honest limits, stated here rather than in a footnote: + - Cuprate is **pre-production**. Its own user book says *"do NOT use cuprated + for any serious purposes"*, and its `monerod` RPC parity is incomplete + (Cuprate issue #278). This is why the source is an opt-in build feature and + a stored user choice, never a default. + - The config pins **testnet**. Mainnet is not validated by this app. + - Cuprate's own `arti` feature is off (its Tor stack is `arti-client` 0.44, + which cannot unify with this crate's 0.46), so the in-process daemon's P2P + traffic is **clearnet**: your ISP sees that this device talks to Monero + peers. No Tor is on the chain path — Tor is the messenger's transport here, + not the chain's. + - Inbound P2P is off and the restricted RPC listener is disabled; the + unrestricted RPC binds loopback only, and it is the address the wallet + child dials. `--trusted-daemon` is still never passed. + - The chain database is a separate embedded store (fjall) under the chain + data directory, not the SQLCipher store the messenger writes — different + file, different exposure: it is not encrypted by that store's key. + +3. **A daemon address they supply.** The wallet child points `--daemon-address` at that host. Trust follows the address: - **Loopback** — same privacy as (1); the user owns `monerod`. - **`.onion`** — chain traffic over Tor through a localhost SOCKS5 listener diff --git a/docs/WALLET.md b/docs/WALLET.md index 46a880e..4dd38eb 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -57,17 +57,23 @@ not something the app stores for you. ## Chain source The wallet needs a daemon for scan, verify, and spend. You pick one; OnionWire -does not pick a public remote node for you. The three shapes are: +does not pick a public remote node for you. The four shapes are: ``` ChainSource::None receive-only; no child, no daemon ChainSource::Local { monerod_bin, datadir } the app spawns monerod on this box +ChainSource::InProcessCuprate { datadir } the daemon is inside this app ChainSource::Remote { host, port } a daemon address you typed ``` 1. **Local `monerod`.** Chain traffic stays on the box. You accept disk, first sync, and (on Android) the daemon not always running. -2. **A daemon address you supply** — becomes `--daemon-address` on the wallet +2. **An in-process daemon** ([Cuprate](https://github.com/Cuprate/cuprate) + running inside the OnionWire process). No `monerod` binary to install or + spawn, chain on this device, and the wallet child dials the same loopback + port. **Testnet only** in this build, and it needs the `cuprate-daemon` + feature — see *The in-process chain daemon* below. +3. **A daemon address you supply** — becomes `--daemon-address` on the wallet child. Loopback if you already run `monerod`. `.onion` if you want chain traffic over Tor (see *Chain traffic over Tor* below). Clearnet only if you type it — your ISP sees Monero-node traffic; it is never a default. @@ -75,6 +81,70 @@ ChainSource::Remote { host, port } a daemon address you typed The port is a convention, not a constant: restricted RPC on `18089` is common, but you supply it. +### The in-process chain daemon (`cuprate-daemon`) + +Cuprate's chain daemon — P2P, consensus, RandomX — can run **inside the +OnionWire process** instead of as a spawned `monerod`. The wallet layer does not +change: `monero-wallet-rpc` is still a child, and it still dials the unrestricted +loopback RPC, `127.0.0.1:18081`, the same address a spawned `monerod` gets. + +``` +cargo build --release --features cuprate-daemon +``` + +- **Off by default.** `cuprated` is pre-1.0 and is not published to crates.io + (every Cuprate crate there is a `0.0.0-placeholder` name reservation), so it is + a git dependency pinned to a revision, behind the `cuprate-daemon` feature. A + default build does not compile it: the graph is large (RandomX, fjall, + axum/hyper, rayon) and it is a *choice*, never compiled-in. Without the feature + a stored in-process chain source can still be read back — the chain-source type + and its record do not fork on a cargo feature — but starting it fails with + `this build has no in-process chain daemon — rebuild with --features + cuprate-daemon`. +- **+11.8 MiB (12,327,768 bytes)** on a stripped `aarch64-linux-android` release + binary, measured in this repo: 24,725,704 bytes without the feature and + 37,053,472 with it (`cargo rustc --release --target aarch64-linux-android + [--features cuprate-daemon] --bin onionwire`, both linked with the NDK C++ + runtime / compiler-rt link args, then `llvm-strip`). The `+5.6 MB` figure that + circulated with the spike was an estimate and understates it. A cold build + also compiles the Cuprate graph in addition to this crate's own, so first-build + time grows accordingly. +- **Testnet only.** Cuprate is **pre-production software**. Its own user book + says *"do NOT use cuprated for any serious purposes"*, and its `monerod` RPC + parity is incomplete (Cuprate issue #278; the four gaps measured in this repo + are in `docs/cuprate-launch-spike.md` §Parity gaps). The config pins + `network = "Testnet"`; pointing a mainnet wallet at it is not something this + build claims to do. The wallet screen's chain line says so next to the source + (`testnet only — mainnet is unvalidated`). +- **No Tor in the chain path.** Cuprate's own `arti` feature is *not* enabled: + its Tor stack is `arti-client` 0.44, which cannot unify with this crate's 0.46, + and running two Tor stacks in one process is not a trade this app makes. + OnionWire's Arti is the only Tor here, and it serves the messenger. The + in-process daemon's P2P traffic is therefore **clearnet**: your ISP can see + that this device talks to Monero testnet peers, exactly as a spawned `monerod` + would. +- **Inbound connections are off** and the restricted RPC listener is disabled: + this is a wallet's daemon, not a public node (the restricted listener only + answers placeholder metrics — see below). +- **It is not a child process.** There is no pid to watch or signal: the node is + a value the app owns, and dropping it shuts the daemon down. `stop` (TUI key + `x`, or the SDK's `stop_wallet_child`) asks it to shut down with the wallet + child, and it does not outlive the app. +- **The chain lives in `$ONIONWIRE_HOME/chain`** — the same per-identity + directory a spawned `monerod` would use, so the two local sources are + interchangeable on disk. It is created `0700`. The chain database itself is + **fjall**, a separate embedded store from OnionWire's SQLCipher file: + Cuprate puts it under the datadir it is given (`/testnet/fjall`), so + it is never beside `onionwire.db`. +- **Selecting it.** The chain source is a stored setting (`ChildConfig`), and + this build has no on-screen chain-source picker on the desktop TUI — that is + true of the other three sources too; the picker is a separate, unmerged piece + of work. What selects this source today is a `ChainSource::InProcessCuprate` + record with a `datadir` written through `Node::set_wallet_child_config` (the + SDK's `ChainConfig` path), and the daemon then starts with the child when the + wallet is started. The SDK gains its own chain-choice variant in a follow-up + card; until then `kind = "cuprate"` is the record's spelling. + ### Chain traffic over Tor (`.onion` daemons) A `.onion` daemon cannot be dialled directly, and OnionWire does not fall back diff --git a/docs/cuprate-android-spike.md b/docs/cuprate-android-spike.md index 8dd4d4f..9433ab1 100644 --- a/docs/cuprate-android-spike.md +++ b/docs/cuprate-android-spike.md @@ -142,10 +142,49 @@ The release demo binary is 51 MB unstripped. - `RANDOMX_DIR` / `DARCH` in `randomx-rs`'s build script are not a cross-compile hazard today only because `DARCH` is inert. If the fork ever honours it, a `-march=native` Android build would be a silent host-arch miscompile. -- Dependency cost is worth restating for the Android AAR: the same Cargo graph builds - **two** `tor-*`/`arti-client` families (Cuprate's 0.44 and OnionWire's 0.46) plus - `axum`/`hyper`/`fjall` for `cuprated`. That is build time and binary size, not a - correctness problem, but it is real on a phone. +- Dependency cost is worth restating for the Android AAR: the `cuprated` graph adds + `axum`/`hyper`/`fjall`/RandomX on top of this crate's own. That is build time and + binary size, not a correctness problem, but it is real on a phone. + The **two `arti` families** the spike tree built were an artifact of the PoC + manifest enabling `cuprated`'s default `arti` feature: OnionWire pins + `default-features = false` for `cuprated`, so its arti-client 0.44 is **not** in + this crate's graph — one Tor stack per process (see `docs/WALLET.md`). - Throwaway harness (not committed, per spike policy): `/var/tmp/cuprate-android-poc/{check-acceptance.sh,check-cold.sh,build-android.sh,link-android.sh}` and the logs next to them (`/var/tmp/cuprate-android-{checkcold,accept,ndk2,link6}.log`). + +## Proven in-repo (2026-09-18, card `t_04975420`) + +The spike above ran on a throwaway PoC tree. The same two commands were re-run in +this repository, against `cuprated` at the same pinned revision +(`4f8fcd1bf468f566fcd89c460d50de4adb6825bf`) and behind this crate's +`cuprate-daemon` feature, with the environment from *Recipe* above: + +``` +$ cargo check --locked --release --target aarch64-linux-android --features cuprate-daemon + Finished `release` profile [optimized] target(s) in 1m 50s +CHECK_EXIT=0 + +$ cargo rustc --locked --release --target aarch64-linux-android \ + --features cuprate-daemon --bin onionwire -- + Finished `release` profile [optimized] target(s) in 2m 05s +LINK_EXIT=0 +$ file /aarch64-linux-android/release/onionwire +ELF 64-bit LSB pie executable, ARM aarch64, version 1 (SYSV), dynamically linked, +interpreter /system/bin/linker64, for Android 26, built by NDK r28c (13676358), +not stripped +``` + +`cargo rustc` needs `--bin onionwire` (or `--lib`) because this crate has both +targets and rustc link args may only go to one of them — the PoC had a single bin, +so this is new to the real tree. + +Sizes, same target and link args, `llvm-strip`ed: + +| build | stripped | +|---|---| +| without the feature | 24,725,704 bytes | +| `--features cuprate-daemon` | 37,053,472 bytes | + +That is a delta of **12,327,768 bytes (≈ +11.8 MiB)**, the number +`docs/WALLET.md` quotes. diff --git a/src/cuprate.rs b/src/cuprate.rs new file mode 100644 index 0000000..b6a4006 --- /dev/null +++ b/src/cuprate.rs @@ -0,0 +1,298 @@ +//! In-process Monero chain daemon (Cuprate) as OnionWire's local chain source. +//! +//! This is the chain half of the wallet's "the app owns the daemon" story: the +//! daemon — P2P, consensus, RandomX — runs **in this process** instead of as a +//! spawned `monerod`. `monero-wallet-rpc` is still a child and is unchanged: it +//! dials the unrestricted loopback RPC that [`crate::wallet_child`] already +//! computes ([`DEFAULT_MONEROD_RPC_PORT`]), so no wallet-layer code moves. +//! +//! [`DEFAULT_MONEROD_RPC_PORT`]: crate::wallet_child::DEFAULT_MONEROD_RPC_PORT +//! +//! Locked facts this module encodes: +//! +//! * `cuprated` is a **git** dependency pinned to a revision, behind the +//! `cuprate-daemon` feature, off by default. Cuprate is pre-1.0 and is not +//! published to crates.io (every Cuprate crate there is a `0.0.0-placeholder` +//! name reservation), so a pinned revision is the only honest way to depend on +//! it. +//! * Cuprate's own `arti` feature stays **off**. Its Tor stack is arti 0.44, +//! which cannot unify with this crate's arti 0.46, and this daemon is +//! clearnet-only: OnionWire's Arti is the only Tor in the process. +//! * The **unrestricted** RPC listener binds `127.0.0.1:` — the address +//! `WalletChild::daemon_address` returns for a local source. The restricted +//! listener is disabled: nothing here dials it, and its metrics are +//! placeholders (a 5 GiB `database_size`, an empty `version`, `free_space = +//! u64::MAX`). +//! * The network is **testnet**. Mainnet is not validated: Cuprate is +//! pre-production and its monerod RPC parity is incomplete +//! (`docs/cuprate-launch-spike.md` §Parity gaps). Pointing a mainnet wallet at +//! it is not something this build claims to do. +//! * The chain database is **fjall**, a separate embedded store from OnionWire's +//! SQLCipher file. Cuprate puts it under the datadir it is given +//! (`//fjall`), so it never lands next to `onionwire.db`. +//! +//! # Building without the feature +//! +//! [`CuprateNode`] exists in every build with the same constructor, so the +//! chain-source type, its stored record and the picker do not fork on a cargo +//! feature. In a build without `cuprate-daemon`, [`CuprateNode::launch`] fails +//! with the feature name instead of silently doing nothing. + +/// The one-line caveat every surface that offers the in-process daemon has to +/// carry, so the picker, the chain block and the docs cannot drift apart. +/// +/// Unconditional — *not* feature-gated: a build without `cuprate-daemon` says +/// the same thing rather than describing a daemon it cannot start. +pub const TESTNET_ONLY: &str = "testnet only — mainnet is unvalidated"; + +/// Can this build actually start the daemon? `false` without the feature. +pub const fn available() -> bool { + cfg!(feature = "cuprate-daemon") +} + +/// Why starting the daemon fails in a build without the feature. One string, so +/// the refusal cannot drift between this module and its callers. +pub const NO_FEATURE_MSG: &str = + "this build has no in-process chain daemon — rebuild with --features cuprate-daemon"; + +#[cfg(feature = "cuprate-daemon")] +mod imp { + use std::path::Path; + use std::sync::mpsc; + + use cuprated::Node; + use cuprated::config::{Config, resolve_max_memory}; + + /// The network this daemon runs. Testnet, deliberately — see the module + /// docs. Cuprate spells this `Testnet`. + pub const NETWORK: &str = "Testnet"; + + /// What the daemon aims to stay under, in bytes. Cuprate would otherwise + /// read total system memory, which on a phone with a wallet on it is not a + /// number this app gets to choose. + const TARGET_MAX_MEMORY: u64 = 2_000_000_000; + + /// Threads for the tx-pool + blockchain reader pool. Small on purpose: this + /// runs next to the messenger, not on its own box. + const READER_THREADS: usize = 4; + + /// Worker threads for the runtime the daemon's tasks live on. The node's + /// services are spawned tasks; two workers is enough to drive them (and the + /// wallet child's RPC is the only client). + const RUNTIME_WORKERS: usize = 2; + + /// A running in-process chain daemon. + /// + /// Owning it *is* the lifecycle: `cuprated::Node` implements `Drop` and asks + /// its services to stop there, so dropping this value stops the daemon. + /// There is no pid to signal. + pub struct CuprateNode { + /// The runtime the node's services were launched on. Owned here so it + /// lives exactly as long as the daemon does — drop the runtime and the + /// services stop being polled. + runtime: Option, + /// `None` only inside `Drop`, where it is taken out to be dropped first. + node: Option, + } + + impl CuprateNode { + /// Launch the daemon with its chain in `datadir`, unrestricted RPC on + /// loopback `port`. + /// + /// Synchronous on purpose: [`crate::wallet_child::WalletChild::start`] + /// is sync (the TUI calls it off its own thread, UniFFI calls it from an + /// async context), and a runtime cannot be *started* from inside another + /// runtime. The launch therefore happens on a thread of its own with a + /// runtime this value owns, and the result is handed back over a channel. + /// Blocking this thread for the duration of the launch is the same thing + /// the app already does for a `.onion` chain source's SOCKS readiness + /// wait. + pub fn launch(datadir: &Path, port: u16) -> Result { + let text = config_toml(datadir, port); + let (tx, rx) = mpsc::channel(); + std::thread::Builder::new() + .name("onionwire-cuprate".into()) + .spawn(move || { + let _ = tx.send(launch_on_owned_runtime(&text)); + }) + .map_err(|e| format!("launch thread: {e}"))?; + let (runtime, node) = rx + .recv() + .map_err(|_| "the launch thread died before answering".to_string())??; + Ok(Self { + runtime: Some(runtime), + node: Some(node), + }) + } + + /// Ask the node's services to stop. + /// + /// Cancels the node's shutdown token; the services then drain on the + /// runtime that launched them (dropping the value cuts that short, so + /// [`crate::wallet_child::WalletChild::stop`] calls this first). Safe in + /// any context — no blocking, no runtime handle needed. + pub fn shutdown(&self) { + if let Some(node) = &self.node { + node.shutdown(); + } + } + + /// Blocks the daemon has, from its own consensus context. The RPC + /// answer is the same number; this one needs no HTTP round trip. + pub fn chain_height(&mut self) -> u64 { + match self.node.as_mut() { + Some(node) => node.blockchain.context().chain_height as u64, + None => 0, + } + } + } + + impl Drop for CuprateNode { + fn drop(&mut self) { + // Ask first, then take the value out and drop it *here* so its own + // `Drop` (the node's shutdown) runs while the runtime is still + // alive to poll the services that observe it. + if let Some(node) = &self.node { + node.shutdown(); + } + drop(self.node.take()); + // A runtime cannot be dropped from inside another runtime's context + // (tokio panics: "Cannot drop a runtime in a context where blocking + // is not allowed"), and this value can be dropped from the SDK's + // async context. `shutdown_background` is the exit that never blocks + // and never panics; the services are already shutting down above. + if let Some(runtime) = self.runtime.take() { + runtime.shutdown_background(); + } + } + } + + /// Build the daemon's runtime, launch the node on it, hand both back. + /// + /// Runs on the launch thread — never on a thread that is already inside a + /// runtime, which is what makes `block_on` legal here. + fn launch_on_owned_runtime(text: &str) -> Result<(tokio::runtime::Runtime, Node), String> { + let mut config: Config = toml::from_str(text).map_err(|e| format!("config: {e}"))?; + resolve_max_memory(&mut config).map_err(|e| format!("config: {e}"))?; + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(RUNTIME_WORKERS) + .enable_all() + .build() + .map_err(|e| format!("runtime: {e}"))?; + let node = runtime + .block_on(Node::launch(config)) + .map_err(|e| format!("launch: {e}"))?; + Ok((runtime, node)) + } + + /// The cuprated config this app launches with, as TOML. + /// + /// A TOML document rather than a struct literal: cuprated's nested config + /// types move between revisions, and every one of them is `Deserialize` with + /// `deny_unknown_fields`, so a stale key is a parse error instead of a + /// default silently standing in for the setting that was meant. + /// + /// No data directory is created here — the caller owns the 0700 wallet dir. + pub fn config_toml(datadir: &Path, port: u16) -> String { + let datadir = datadir.display(); + format!( + r#"network = "{NETWORK}" +offline = false +fast_sync = true +target_max_memory = {TARGET_MAX_MEMORY} + +[fs] +fast_data_directory = "{datadir}" +slow_data_directory = "{datadir}" +cache_directory = "{datadir}/cache" + +[storage] +reader_threads = {READER_THREADS} + +# The unrestricted listener: this is the one the wallet child dials, and the one +# with real numbers. The restricted listener is off — its metrics are +# placeholders, and nothing in this app reads them. +[rpc.unrestricted] +address = "127.0.0.1" +port = {port} +enable = true + +[rpc.restricted] +address = "127.0.0.1" +port = 0 +enable = false + +# Inbound connections are off: this is a wallet's daemon, not a public node. +# Tor P2P stays off too — OnionWire already runs Arti for the messenger, and +# chain traffic on loopback-only clearnet does not need a second Tor stack. +[p2p.clear_net] +enable_inbound = false +enable_inbound_v6 = false + +[p2p.tor_net] +enabled = false + +[tor] +mode = "Auto" +"# + ) + } + + #[cfg(test)] + mod tests { + use super::*; + + /// The config has to *parse* into this revision's `Config`: every + /// cuprated config struct is `deny_unknown_fields`, so a key that moved + /// between revisions is a hard error, not a silently ignored setting. + #[test] + fn the_config_parses_into_this_revision() { + let mut config: Config = + toml::from_str(&config_toml(Path::new("/tmp/onionwire-chain"), 18081)) + .expect("the config must parse against the pinned cuprated revision"); + resolve_max_memory(&mut config).expect("target_max_memory is set, so nothing to probe"); + assert_eq!(format!("{:?}", config.network), NETWORK); + // The fjall store is Cuprate's, under the datadir it was given — + // never beside OnionWire's SQLCipher file. + assert_eq!( + config.fjall_directory(), + Path::new("/tmp/onionwire-chain/testnet/fjall"), + "the chain database is a separate store under the chain datadir" + ); + } + } +} + +#[cfg(not(feature = "cuprate-daemon"))] +mod imp { + use std::path::Path; + + /// Placeholder for a build without `cuprate-daemon`. + /// + /// It has no state because nothing can ever be launched: [`launch`] always + /// fails. It exists so the chain-source type, its persistence and the + /// status copy do not fork on a cargo feature. + /// + /// [`launch`]: CuprateNode::launch + pub struct CuprateNode(()); + + impl CuprateNode { + /// Always fails: this build has no in-process daemon. + pub fn launch(_datadir: &Path, _port: u16) -> Result { + Err(super::NO_FEATURE_MSG.into()) + } + + /// Nothing to stop: no daemon was ever launched. + pub fn shutdown(&self) {} + + /// No daemon, no chain: the same number a stopped node reports. + pub fn chain_height(&mut self) -> u64 { + 0 + } + } +} + +pub use imp::CuprateNode; + +#[cfg(feature = "cuprate-daemon")] +pub use imp::{NETWORK, config_toml}; diff --git a/src/lib.rs b/src/lib.rs index fbb8928..226aa94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ pub mod backup; +pub mod cuprate; pub mod dispatch; pub mod file; pub mod frame; diff --git a/src/tui.rs b/src/tui.rs index ef0a0e7..e44bf0d 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -16,7 +16,7 @@ use crate::outbox::DEFAULT_MAX_ATTEMPTS; use crate::qr::{self, QrPayload}; use crate::sanitize; use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus}; -use crate::wallet; +use crate::wallet::{self, ChainSource}; const C_ACCENT: Color = Color::Rgb(232, 165, 75); const C_TEXT: Color = Color::Rgb(196, 214, 176); @@ -1805,6 +1805,27 @@ impl App { } } + /// The wallet screen's chain-source line: the child status, plus the + /// caveat the configured source carries. + /// + /// The in-process daemon is **testnet only** in this build, and this line is + /// the only place the wallet screen names the configured chain source (the + /// source itself is a stored setting), so the caveat travels with it — a + /// user who reads it as a mainnet node would be misled. + fn wallet_child_screen_line(&self) -> String { + let mut line = self.node.wallet_child_line(); + if matches!( + self.node.wallet_child_config().source, + ChainSource::InProcessCuprate { .. } + ) { + if !line.is_empty() { + line.push_str(" · "); + } + line.push_str(crate::cuprate::TESTNET_ONLY); + } + line + } + /// Key `s` on the wallet screen: start the app-owned wallet child. The /// balance/address readouts refresh on the next F6 — the child's RPC is not /// answering in the same breath — so this reports the state it reached. @@ -2218,7 +2239,7 @@ impl App { transfers, qr_modal, } => { - let child = self.node.wallet_child_line(); + let child = self.wallet_child_screen_line(); draw_wallet( f, receive_addr, diff --git a/src/wallet.rs b/src/wallet.rs index 1c02368..4430a2d 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -35,6 +35,17 @@ pub enum ChainSource { /// Data directory for the local daemon. datadir: PathBuf, }, + /// A chain daemon **inside this process** (Cuprate), with its chain in + /// `datadir`. Nothing is spawned; the wallet child still dials loopback + /// RPC, so this is a [`ChainSource::Local`] with a different owner. + /// + /// Two consequences the UI has to state: the chain is on this device, and + /// the in-process daemon is **testnet-only** in this build (Cuprate is + /// pre-production and its mainnet RPC parity is unvalidated). + InProcessCuprate { + /// Data directory for the daemon's chain database. + datadir: PathBuf, + }, /// A daemon address the user supplied. Trust follows the address. Remote { /// Daemon host. May be loopback, `.onion`, or a clearnet host the user @@ -61,6 +72,7 @@ impl ChainSource { match self { ChainSource::None => "receive-only".to_string(), ChainSource::Local { .. } => "local node".to_string(), + ChainSource::InProcessCuprate { .. } => "in-process node".to_string(), ChainSource::Remote { host, .. } if is_onion_host(host) => { "remote onion daemon".to_string() } @@ -1103,3 +1115,343 @@ fn json_amount(v: &serde_json::Value) -> String { _ => String::new(), } } + +// --------------------------------------------------------------------------- +// Chain daemon client (the chain side of the RPC layer) +// --------------------------------------------------------------------------- +// +// This is *not* the wallet child: that one is a loopback HTTP Digest RPC. This +// one dials the *daemon* the wallet child scans from, and that is the connection +// Cuprate changes shape on (`docs/cuprate-launch-spike.md` §Parity gaps, all +// three measured by running it): +// +// * a height above the tip is a **bare HTTP 500 with a zero-byte body**, where +// monerod answers a JSON-RPC error object (`TOO_BIG_HEIGHT`); +// * `get_info` metrics are not measurements — a placeholder 5 GiB +// `database_size`, an empty `version`, `free_space = u64::MAX`, and zero peers +// even while blocks are arriving; +// * `get_height` is a **URI endpoint**: `{"method":"get_height"}` over +// `/json_rpc` is rejected with 422. +// +// Nothing here parses a peer count, a database size, a free-space figure or a +// version string. There is no field for them to land in, so a caller cannot show +// a placeholder as a measurement. +// +// The in-process chain source ([`ChainSource::InProcessCuprate`]) is what makes +// these the *local* case rather than a remote corner: it is the daemon this app +// starts itself. + +/// `CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT` in monero's +/// `src/rpc/core_rpc_server_error_codes.h`. Cuprate answers the same request +/// with a bare HTTP 500 instead, which is why both spellings map to +/// [`WalletError::DaemonHeightOutOfRange`]. +const TOO_BIG_HEIGHT_CODE: i64 = -2; + +/// Typed failures of the chain-daemon calls. The wallet-child path above keeps +/// its plain string errors; this side distinguishes a *height* failure from +/// every other one because that is the answer Cuprate mangles. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WalletError { + /// The requested height is above the daemon's tip. Cuprate: bare HTTP 500, + /// empty body. monerod: HTTP 200, error code `-2`. + DaemonHeightOutOfRange, + /// A non-2xx status that is not the height case above. + DaemonHttpStatus(u16), + /// A JSON-RPC error object we do not special-case. + DaemonRpc { + /// The `error.code` the daemon sent. + code: i64, + /// The `error.message` the daemon sent. + message: String, + }, + /// A 2xx answer with no usable body. Carries the address and the reason. + DaemonNoBody(String), + /// The daemon could not be reached, or the answer could not be read. + DaemonTransport(String), +} + +impl WalletError { + /// Is this the "height above tip" failure? A caller that just asked for a + /// block at an unverified height may retry lower; every other error is a + /// different problem. + pub fn is_height_out_of_range(&self) -> bool { + matches!(self, Self::DaemonHeightOutOfRange) + } +} + +impl std::fmt::Display for WalletError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::DaemonHeightOutOfRange => { + f.write_str("daemon: height is above its chain tip (not synced that far yet)") + } + Self::DaemonHttpStatus(code) => write!(f, "daemon: HTTP {code}"), + Self::DaemonRpc { code, message } => write!(f, "daemon rpc error {code}: {message}"), + Self::DaemonNoBody(msg) | Self::DaemonTransport(msg) => f.write_str(msg), + } + } +} + +impl std::error::Error for WalletError {} + +/// What the chain view is allowed to know about a daemon: how far it is and how +/// far it is going. Deliberately nothing else — see the section comment. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DaemonInfo { + /// Blocks the daemon has. + pub height: u64, + /// Blocks it is syncing towards. `0` means it reported none, which is not + /// the same as "caught up". + pub target_height: u64, +} + +/// Cap on a daemon answer, in bytes. A `get_block` blob is the large case. +pub const DAEMON_MAX_BYTES: usize = 8 * 1024 * 1024; + +/// `get_info` as the chain view needs it: height and target, nothing else. +pub async fn daemon_get_info( + addr: &str, + budget: Duration, +) -> std::result::Result { + let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_info"}"#; + let request = json_rpc_request(addr, "/json_rpc", body); + let (status, raw) = daemon_http(addr, &request, budget).await?; + daemon_ok_status(status)?; + let json = daemon_json(&raw, addr)?; + let result = json + .get("result") + .ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_info has no result")))?; + let height = result + .get("height") + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| { + WalletError::DaemonNoBody(format!("{addr}: get_info has no chain height")) + })?; + let target_height = result + .get("target_height") + .and_then(serde_json::Value::as_u64) + .unwrap_or(0); + Ok(DaemonInfo { + height, + target_height, + }) +} + +/// The daemon's tip, over the `get_height` URI endpoint. +/// +/// Cuprate rejects `{"method":"get_height"}` over `/json_rpc` with 422, and the +/// URI endpoint is what monerod has always answered — one spelling works on +/// both, so this is the one to use. +pub async fn daemon_get_height( + addr: &str, + budget: Duration, +) -> std::result::Result { + let request = uri_request(addr, "GET", "/get_height"); + let (status, raw) = daemon_http(addr, &request, budget).await?; + if is_server_error(status) { + return Err(WalletError::DaemonHeightOutOfRange); + } + daemon_ok_status(status)?; + let json = daemon_json(&raw, addr)?; + // Both daemons answer a top-level `height` here; tolerate a jsonrpc + // envelope too rather than betting on the shape. + json.get("height") + .or_else(|| json.get("result").and_then(|r| r.get("height"))) + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_height has no height"))) +} + +/// One block by height, as raw bytes (the hex `blob` field, decoded). +/// +/// Not called by the app yet: the wallet's block scan still lives in +/// `monero-wallet-rpc`. It exists because the out-of-range answer above is the +/// Cuprate behaviour such a scan has to survive, and the mapping belongs with +/// the rest of the client. +pub async fn daemon_get_block( + addr: &str, + height: u64, + budget: Duration, +) -> std::result::Result, WalletError> { + let body = format!( + r#"{{"jsonrpc":"2.0","id":"0","method":"get_block","params":{{"height":{height}}}}}"# + ); + let request = json_rpc_request(addr, "/json_rpc", &body); + let (status, raw) = daemon_http(addr, &request, budget).await?; + if is_server_error(status) { + return Err(WalletError::DaemonHeightOutOfRange); + } + daemon_ok_status(status)?; + let json = daemon_json(&raw, addr)?; + let blob = json + .get("result") + .and_then(|r| r.get("blob")) + .and_then(|b| b.as_str()) + .ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_block has no blob")))?; + hex_decode(blob) + .ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_block blob is not hex"))) +} + +/// A bare 5xx is how Cuprate says "no such height" — it carries no body to +/// decode, so the *call* decides what it means: height-addressed calls (the two +/// above) read it as [`WalletError::DaemonHeightOutOfRange`], everything else +/// reads it as a status error. +fn is_server_error(status: u16) -> bool { + (500..600).contains(&status) +} + +fn daemon_ok_status(status: u16) -> std::result::Result<(), WalletError> { + if (200..300).contains(&status) { + return Ok(()); + } + Err(WalletError::DaemonHttpStatus(status)) +} + +fn json_rpc_request(addr: &str, path: &str, body: &str) -> String { + format!( + "POST {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) +} + +fn uri_request(addr: &str, method: &str, path: &str) -> String { + format!( + "{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) +} + +/// One request, one answer: status code plus body. `Connection: close` and read +/// to EOF, so `Content-Length` never has to be trusted. +async fn daemon_http( + addr: &str, + request: &str, + budget: Duration, +) -> std::result::Result<(u16, Vec), WalletError> { + let mut stream = tokio::time::timeout(budget, TcpStream::connect(addr)) + .await + .map_err(|_| WalletError::DaemonTransport(format!("{addr}: connect timed out")))? + .map_err(|e| WalletError::DaemonTransport(format!("{addr}: {e}")))?; + let raw = tokio::time::timeout(budget, async { + stream.write_all(request.as_bytes()).await?; + let mut buf = Vec::new(); + let mut tmp = [0u8; 8192]; + loop { + let n = stream.read(&mut tmp).await?; + if n == 0 { + break; + } + buf.extend_from_slice(&tmp[..n]); + if buf.len() >= DAEMON_MAX_BYTES { + break; + } + } + Ok::, std::io::Error>(buf) + }) + .await + .map_err(|_| WalletError::DaemonTransport(format!("{addr}: read timed out")))? + .map_err(|e| WalletError::DaemonTransport(format!("{addr}: {e}")))?; + split_http(&raw) + .ok_or_else(|| WalletError::DaemonTransport(format!("{addr}: not an HTTP response"))) +} + +/// Status code and body from a raw HTTP/1.1 response. +/// +/// Cuprate is axum/hyper: the body arrives `Transfer-Encoding: chunked`, so +/// scanning for the outermost braces is not a parse once a blob spans more than +/// one chunk. De-chunk here, once, for every call. +fn split_http(raw: &[u8]) -> Option<(u16, Vec)> { + let (head, body) = match find(raw, b"\r\n\r\n") { + Some(at) => (&raw[..at], &raw[at + 4..]), + None => { + let at = find(raw, b"\n\n")?; + (&raw[..at], &raw[at + 2..]) + } + }; + let head = std::str::from_utf8(head).ok()?; + let mut lines = head.lines(); + let status = lines.next()?.split_whitespace().nth(1)?.parse().ok()?; + let chunked = lines.any(|line| { + line.split_once(':').is_some_and(|(k, v)| { + k.eq_ignore_ascii_case("transfer-encoding") + && v.to_ascii_lowercase().contains("chunked") + }) + }); + let body = if chunked { + dechunk(body)? + } else { + body.to_vec() + }; + Some((status, body)) +} + +fn dechunk(body: &[u8]) -> Option> { + let mut out = Vec::new(); + let mut at = 0; + loop { + let line_end = find(&body[at..], b"\r\n")?; + let size_line = std::str::from_utf8(&body[at..at + line_end]).ok()?; + // `size[;chunk-extension]` + let size = usize::from_str_radix(size_line.split(';').next()?.trim(), 16).ok()?; + at += line_end + 2; + if size == 0 { + return Some(out); + } + if at + size > body.len() { + return None; + } + out.extend_from_slice(&body[at..at + size]); + at += size; + if body[at..].starts_with(b"\r\n") { + at += 2; + } else if body[at..].starts_with(b"\n") { + at += 1; + } + } +} + +fn find(haystack: &[u8], needle: &[u8]) -> Option { + haystack.windows(needle.len()).position(|w| w == needle) +} + +fn daemon_json(body: &[u8], addr: &str) -> std::result::Result { + let text = std::str::from_utf8(body) + .map_err(|_| WalletError::DaemonNoBody(format!("{addr}: body is not UTF-8")))?; + let json: serde_json::Value = serde_json::from_str(text.trim()) + .map_err(|e| WalletError::DaemonNoBody(format!("{addr}: {e}")))?; + if let Some(err) = json.get("error") { + let code = err + .get("code") + .and_then(serde_json::Value::as_i64) + .unwrap_or(0); + if code == TOO_BIG_HEIGHT_CODE { + return Err(WalletError::DaemonHeightOutOfRange); + } + let message = err + .get("message") + .and_then(|m| m.as_str()) + .unwrap_or("rpc error") + .to_string(); + return Err(WalletError::DaemonRpc { code, message }); + } + Ok(json) +} + +fn hex_decode(s: &str) -> Option> { + let bytes = s.as_bytes(); + if !bytes.len().is_multiple_of(2) { + return None; + } + let mut out = Vec::with_capacity(bytes.len() / 2); + for pair in bytes.chunks(2) { + out.push((hex_val(pair[0])? << 4) | hex_val(pair[1])?); + } + Some(out) +} + +fn hex_val(c: u8) -> Option { + match c { + b'0'..=b'9' => Some(c - b'0'), + b'a'..=b'f' => Some(c - b'a' + 10), + b'A'..=b'F' => Some(c - b'A' + 10), + _ => None, + } +} diff --git a/src/wallet_child.rs b/src/wallet_child.rs index 2ff650a..d8cce49 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -1,6 +1,7 @@ //! Wallet child lifecycle: the app owns `monero-wallet-rpc` — and, when the -//! user chose a local chain source, `monerod` — instead of asking the user to -//! start them and export an env var. +//! user chose a local chain source, `monerod` or an **in-process Cuprate node** +//! ([`crate::cuprate`], behind the `cuprate-daemon` feature) — instead of asking +//! the user to start them and export an env var. //! //! Locked shape: //! @@ -21,6 +22,9 @@ //! * The two Tor clients do not share state: the SOCKS child gets its own //! `state_dir`/`cache_dir` under the wallet dir. //! * `--trusted-daemon` is never passed: a remote daemon is untrusted. +//! * The in-process daemon is *not* a child: it is a value owned by this struct, +//! and dropping it shuts the node down. It still binds the same loopback RPC +//! port, so everything downstream of `--daemon-address` is unchanged. use std::fs; use std::net::{Ipv4Addr, SocketAddr, TcpStream}; @@ -33,11 +37,15 @@ use std::time::{Duration, Instant}; use rand::RngCore; use zeroize::Zeroizing; +use crate::cuprate::CuprateNode; use crate::store::Store; use crate::wallet::{self, ChainSource, Wallet}; /// `monerod` RPC port for a local chain source. Unrestricted RPC default; the /// wallet child is the only thing that dials it. +/// +/// An in-process Cuprate node binds the same port in its config, so the wallet +/// child's `--daemon-address` does not change with the chain source. pub const DEFAULT_MONEROD_RPC_PORT: u16 = 18081; /// Name of the `monero-wallet-rpc` binary when the caller does not point at one. @@ -94,6 +102,10 @@ pub struct WalletChild { monerod: Mutex>, socks: Mutex>, wallet_rpc: Mutex>, + /// The in-process Cuprate node, when [`ChainSource::InProcessCuprate`] is + /// the source. Owning it is the lifecycle: dropping it shuts the daemon + /// down. Never a child process, so there is no pid to watch or signal. + cuprate: Mutex>, } impl WalletChild { @@ -123,6 +135,7 @@ impl WalletChild { monerod: Mutex::new(None), socks: Mutex::new(None), wallet_rpc: Mutex::new(None), + cuprate: Mutex::new(None), }) } @@ -196,8 +209,17 @@ impl WalletChild { /// Is a tracked child still alive? Polls the process table; an exited child /// is reaped here so a later `stop` is a no-op. + /// + /// The in-process daemon has no process to poll: it counts as running for as + /// long as this struct holds it. pub fn running(&self) -> bool { let _ = self.reap_exited(); + self.launched_processes() || self.cuprate.lock().map(|g| g.is_some()).unwrap_or(false) + } + + /// Is a tracked *child process* alive? The in-process daemon is not one, so + /// it is never reported here. + fn launched_processes(&self) -> bool { self.monerod.lock().map(|g| g.is_some()).unwrap_or(false) || self.socks.lock().map(|g| g.is_some()).unwrap_or(false) || self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false) @@ -298,6 +320,11 @@ impl WalletChild { ChainSource::Local { .. } => { "local monerod on this box (loopback): no Tor, no remote operator".into() } + ChainSource::InProcessCuprate { .. } => format!( + "in-process daemon: chain and consensus run in this app, on this device \ + (loopback, no Tor) — {}", + crate::cuprate::TESTNET_ONLY + ), ChainSource::Remote { host, port } if Self::is_onion_host(host) => format!( "remote {host}:{port} over Tor (SOCKS5 on loopback, never clearnet) — Tor hides \ the transport, not the host: the daemon operator still sees your addresses \ @@ -311,16 +338,30 @@ impl WalletChild { } /// The `--daemon-address` for each chain source. A local source is the - /// loopback daemon this struct owns; a remote one is exactly what the user - /// typed. + /// loopback daemon this struct owns — spawned `monerod` or in-process + /// Cuprate, the same port; a remote one is exactly what the user typed. pub fn daemon_address(source: &ChainSource) -> Option { match source { ChainSource::None => None, - ChainSource::Local { .. } => Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")), + ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. } => { + Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")) + } ChainSource::Remote { host, port } => Some(format!("{host}:{port}")), } } + /// The directory a local chain source stores its chain in: the spawned + /// daemon's and the in-process daemon's are the same idea on disk. `None` + /// for a remote source (their disk, not ours) and for receive-only. + pub fn chain_datadir(source: &ChainSource) -> Option<&Path> { + match source { + ChainSource::Local { datadir, .. } | ChainSource::InProcessCuprate { datadir } => { + Some(datadir) + } + ChainSource::None | ChainSource::Remote { .. } => None, + } + } + /// Bind a loopback port and hand it back. The listener is dropped /// immediately; the port is only used to keep two instances from colliding. pub fn pick_port() -> Result { @@ -412,21 +453,26 @@ impl WalletChild { } fn start_children(&self, store: &Store) -> Result> { - // Local chain source: own monerod first, so the wallet child has a - // daemon to dial. - if let ChainSource::Local { - monerod_bin, - datadir, - } = &self.source - { - ensure_parent(datadir)?; - let argv = Self::monerod_argv(monerod_bin, datadir, DEFAULT_MONEROD_RPC_PORT); - let child = spawn(&argv, "monerod")?; - let mut guard = self - .monerod - .lock() - .map_err(|e| ChildError(format!("monerod lock: {e}")))?; - *guard = Some(child); + // Local chain source: own the daemon first, so the wallet child has + // something to dial. Either a spawned `monerod` or the in-process + // Cuprate node — both bind `DEFAULT_MONEROD_RPC_PORT` on loopback, so + // `wallet_rpc_argv` below is identical either way. + match &self.source { + ChainSource::Local { + monerod_bin, + datadir, + } => { + ensure_parent(datadir)?; + let argv = Self::monerod_argv(monerod_bin, datadir, DEFAULT_MONEROD_RPC_PORT); + let child = spawn(&argv, "monerod")?; + let mut guard = self + .monerod + .lock() + .map_err(|e| ChildError(format!("monerod lock: {e}")))?; + *guard = Some(child); + } + ChainSource::InProcessCuprate { datadir } => self.start_in_process_daemon(datadir)?, + ChainSource::None | ChainSource::Remote { .. } => {} } // A `.onion` daemon is only reachable through SOCKS. The app bundles the @@ -502,13 +548,48 @@ impl WalletChild { Ok(Self::socks_proxy_url(port)) } + /// Launch the in-process Cuprate daemon and hold it. + /// + /// Blocking is deliberate: [`CuprateNode::launch`] is synchronous (it runs + /// the async launch on a runtime it owns and blocks this thread until the + /// node answers), so this works from the TUI's blocking thread *and* from an + /// SDK async context. It is the same shape as the SOCKS readiness wait + /// above: no daemon, no wallet child. + fn start_in_process_daemon(&self, datadir: &Path) -> Result<()> { + // Feature first: in a build without it, a datadir complaint would be a + // misleading answer to "why is there no daemon". + if !crate::cuprate::available() { + return Err(ChildError(crate::cuprate::NO_FEATURE_MSG.into())); + } + create_dir_700(datadir).map_err(|e| ChildError(format!("chain datadir: {e}")))?; + let node = CuprateNode::launch(datadir, DEFAULT_MONEROD_RPC_PORT) + .map_err(|e| ChildError(format!("in-process daemon: {e}")))?; + let mut guard = self + .cuprate + .lock() + .map_err(|e| ChildError(format!("cuprate lock: {e}")))?; + *guard = Some(node); + Ok(()) + } + /// Stop every child. Idempotent, and tolerant of a child that already /// exited on its own. The wallet child goes first so no wallet RPC can be - /// mid-request against the chain, then the SOCKS listener, then `monerod`. + /// mid-request against the chain, then the SOCKS listener, then the chain + /// daemon — the in-process one is asked to shut down rather than signalled. pub fn stop(&self) -> Result<()> { kill_slot(&self.wallet_rpc, "monero-wallet-rpc")?; kill_slot(&self.socks, "arti proxy")?; kill_slot(&self.monerod, "monerod")?; + let node = self + .cuprate + .lock() + .map_err(|e| ChildError(format!("cuprate lock: {e}")))? + .take(); + if let Some(node) = node { + // Ask before the value goes out of scope: the services drain on the + // runtime this node owns, and dropping alone would cut them off. + node.shutdown(); + } Ok(()) } @@ -629,6 +710,13 @@ impl ChildConfig { )); } } + ChainSource::InProcessCuprate { datadir } => { + if datadir.as_os_str().is_empty() { + return Err(ChildError( + "chain data dir required for an in-process daemon".into(), + )); + } + } ChainSource::Remote { host, port } => { if host.trim().is_empty() { return Err(ChildError( @@ -837,6 +925,10 @@ fn source_to_json(source: &ChainSource) -> serde_json::Value { "monerod_bin": monerod_bin.display().to_string(), "datadir": datadir.display().to_string(), }), + ChainSource::InProcessCuprate { datadir } => serde_json::json!({ + "kind": "cuprate", + "datadir": datadir.display().to_string(), + }), ChainSource::Remote { host, port } => serde_json::json!({ "kind": "remote", "host": host, @@ -870,6 +962,18 @@ fn source_from_json(value: &serde_json::Value) -> Result { datadir: PathBuf::from(datadir), }) } + "cuprate" => { + let datadir = value + .get("datadir") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| { + ChildError("stored in-process chain source has no data dir".into()) + })?; + Ok(ChainSource::InProcessCuprate { + datadir: PathBuf::from(datadir), + }) + } "remote" => { let host = value .get("host") @@ -1603,4 +1707,194 @@ mod tests { let mode = fs::metadata(&wallet_dir).unwrap().permissions().mode() & 0o777; assert_eq!(mode, 0o700, "wallet dir must be 0700"); } + + fn in_process_source(dir: &Path) -> ChainSource { + ChainSource::InProcessCuprate { + datadir: dir.join("chain"), + } + } + + /// The in-process source is a local daemon in every sense the caller cares + /// about: same loopback port, same datadir idea, nothing remote about it. + /// That is the whole reason `wallet_rpc_argv` does not change. + #[test] + fn the_in_process_source_is_a_local_daemon_on_the_same_port() { + let dir = tmp_dir("cuprate-local"); + let source = in_process_source(&dir); + let local = local_source(&dir, PathBuf::from("monerod")); + + assert_eq!( + WalletChild::daemon_address(&source), + Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")), + "the wallet child dials the same port either way" + ); + assert_eq!( + WalletChild::daemon_address(&source), + WalletChild::daemon_address(&local), + "a spawned and an in-process local source are the same address" + ); + assert_eq!( + WalletChild::chain_datadir(&source), + Some(dir.join("chain").as_path()), + "the chain is on this device's disk" + ); + assert_eq!(WalletChild::chain_datadir(&ChainSource::None), None); + assert_eq!( + WalletChild::chain_datadir(&ChainSource::Remote { + host: "node.example.com".into(), + port: 18089, + }), + None, + "a remote daemon's chain is not ours" + ); + + // The wallet-child argv is byte-for-byte the tested local-node shape: + // same `--daemon-address`, and never `--trusted-daemon`. + let argv = WalletChild::wallet_rpc_argv( + Path::new("monero-wallet-rpc"), + 39127, + "u:p", + &dir.join("wallet"), + WalletChild::daemon_address(&source).as_deref(), + None, + ); + assert!( + argv.windows(2).any(|w| w[0] == "--daemon-address" + && w[1] == format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")), + "{argv:?}" + ); + assert!(!argv.iter().any(|a| a == "--trusted-daemon"), "{argv:?}"); + + assert!( + WalletChild::new(source, dir.join("wallet"), None) + .unwrap() + .is_enabled(), + "an in-process source is a chain source: there is something to start" + ); + } + + /// The copy names what is on this device and the one thing that must not be + /// buried: this daemon is testnet-only. + #[test] + fn in_process_copy_says_local_and_testnet_only() { + let dir = tmp_dir("cuprate-copy"); + let copy = WalletChild::chain_copy(&in_process_source(&dir)); + assert!(copy.contains("in this app"), "{copy}"); + assert!(copy.contains("no Tor"), "{copy}"); + assert!(copy.contains(crate::cuprate::TESTNET_ONLY), "{copy}"); + assert_eq!( + crate::cuprate::TESTNET_ONLY, + "testnet only — mainnet is unvalidated" + ); + } + + /// The picker's choice has to survive a restart without a child ever + /// starting, exactly like the other sources — and read back as itself, + /// never as receive-only. + #[test] + fn the_in_process_choice_round_trips_through_the_sealed_record() { + let dir = tmp_dir("cuprate-record"); + let store = open_store(&dir); + let source = in_process_source(&dir); + let cfg = ChildConfig { + source: source.clone(), + ..ChildConfig::default() + }; + cfg.validate().unwrap(); + let record = merge_record(None, cfg.record_fields()); + store.save_wallet_child(&record).unwrap(); + + let raw = store.load_wallet_child().unwrap().expect("sealed record"); + assert_eq!(ChildConfig::from_record(&raw).unwrap().unwrap(), cfg); + let json: serde_json::Value = serde_json::from_str(&raw).unwrap(); + assert_eq!(json["source"]["kind"], "cuprate"); + assert_eq!( + json["source"]["datadir"].as_str().unwrap(), + dir.join("chain").display().to_string() + ); + + // An empty datadir is rejected before it is stored, never persisted and + // then failed over. + let empty = ChildConfig { + source: ChainSource::InProcessCuprate { + datadir: PathBuf::new(), + }, + ..ChildConfig::default() + }; + let err = empty.validate().unwrap_err().to_string(); + assert!(err.contains("chain data dir"), "{err}"); + } + + /// Without the feature, starting the in-process source names the feature — + /// never a silent no-op, and never a spawned `monero-wallet-rpc` pointed at + /// a daemon that does not exist. + #[cfg(not(feature = "cuprate-daemon"))] + #[test] + fn in_process_source_without_the_feature_names_the_feature() { + let dir = tmp_dir("cuprate-off"); + let store = open_store(&dir); + let rpc_log = dir.join("wallet-rpc.argv"); + let child = WalletChild::new(in_process_source(&dir), dir.join("wallet"), None) + .unwrap() + .with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log)); + let err = child.start(&store).unwrap_err().to_string(); + assert!(err.contains("cuprate-daemon"), "{err}"); + assert!(!child.running(), "nothing may be left running: {err}"); + assert!( + !rpc_log.exists(), + "the wallet RPC child must not be spawned against a daemon that never started" + ); + child.stop().unwrap(); + } + + /// With the feature compiled in, the launch is real: the daemon answers on + /// the port the wallet child is pointed at, `stop` shuts it down, and the + /// app-owned child list reports it honestly (as a daemon, never as a + /// process — there is no pid). + #[cfg(feature = "cuprate-daemon")] + #[test] + fn in_process_source_launches_a_daemon_and_stop_shuts_it_down() { + let dir = tmp_dir("cuprate-on"); + let store = open_store(&dir); + let rpc_log = dir.join("wallet-rpc.argv"); + let child = WalletChild::new(in_process_source(&dir), dir.join("wallet"), None) + .unwrap() + .with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log)); + + // The wallet RPC child is fake, so `start` reaches only the daemon: the + // whole point of the in-process source is that the daemon *is* us. + let _ = child.start(&store); + let addr = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"); + assert!( + waits_for_tcp(&addr, Duration::from_secs(20)), + "the in-process daemon never answered on {addr}" + ); + assert!(child.running(), "an owned daemon counts as running"); + assert!(dir.join("chain").exists(), "the chain dir is created 0700"); + + child.stop().unwrap(); + assert!(!child.running(), "stop must drop the daemon"); + let mut closed = false; + for _ in 0..60 { + if std::net::TcpStream::connect(&addr).is_err() { + closed = true; + break; + } + std::thread::sleep(Duration::from_millis(250)); + } + assert!(closed, "the daemon's RPC listener outlived stop()"); + } + + /// Poll a loopback address until it accepts, inside a budget. + #[cfg(feature = "cuprate-daemon")] + fn waits_for_tcp(addr: &str, budget: Duration) -> bool { + let deadline = Instant::now() + budget; + while Instant::now() <= deadline { + if std::net::TcpStream::connect(addr).is_ok() { + return true; + } + std::thread::sleep(Duration::from_millis(100)); + } + false + } } diff --git a/tests/wallet.rs b/tests/wallet.rs index 6a57b87..26d7168 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -1245,3 +1245,112 @@ fn freed_loopback_port() -> u16 { drop(listener); port } + +// --------------------------------------------------------------------------- +// The in-process chain daemon (feature `cuprate-daemon`). +// +// The one test in the suite that runs a real chain daemon: it launches the +// `cuprated` node OnionWire embeds, asks it through the *same* typed daemon +// client a remote `monerod` is asked through, and then proves the listener dies +// with the node. A testnet node with no peers answers RPC and stays at genesis, +// so this needs no network. +// --------------------------------------------------------------------------- + +#[cfg(feature = "cuprate-daemon")] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_in_process_cuprate_node_answers_the_typed_daemon_client() { + let dir = tempfile::tempdir().expect("tempdir"); + let datadir = dir.path().join("chain"); + let port = freed_loopback_port(); + let addr = format!("127.0.0.1:{port}"); + let budget = std::time::Duration::from_secs(5); + + let mut node = onionwire::cuprate::CuprateNode::launch(&datadir, port) + .expect("launch the in-process testnet daemon"); + + // `launch` returns with the services started; the RPC listener can still be + // a moment behind, so poll with a deadline instead of racing it. + let mut info = None; + for _ in 0..40 { + if let Ok(got) = wallet::daemon_get_info(&addr, budget).await { + info = Some(got); + break; + } + tokio::time::sleep(std::time::Duration::from_millis(250)).await; + } + let info = info.expect("the in-process daemon never answered get_info on /json_rpc"); + + // A fresh testnet chain: genesis is height 1 and there is nothing to sync + // towards. The daemon's own consensus context is the reference, and the RPC + // answer may trail it by a block or two while it is running. + assert!(info.height >= 1, "genesis is height 1: {info:?}"); + let context_height = node.chain_height(); + assert!(context_height >= 1, "in-process height: {context_height}"); + assert!( + info.height.abs_diff(context_height) <= 2, + "get_info ({}) and the node's own context ({context_height}) disagree", + info.height + ); + assert_eq!( + info.target_height, 0, + "a testnet node with no peers reports no target, not a caught-up chain" + ); + + // `get_height` is the URI endpoint (Cuprate rejects it over /json_rpc), and + // it has to agree with `get_info`. + let height = wallet::daemon_get_height(&addr, budget) + .await + .expect("get_height on the URI endpoint"); + assert!(height >= 1, "{height}"); + assert!( + height.abs_diff(info.height) <= 2, + "get_height ({height}) and get_info ({}) disagree", + info.height + ); + + // Genesis is always retrievable, and a height above the tip is the bare-500 + // answer the typed client normalizes. + let genesis = wallet::daemon_get_block(&addr, 0, std::time::Duration::from_secs(30)) + .await + .expect("get_block at genesis"); + assert!( + genesis.len() > 70, + "a genesis block with a header and one tx is longer than this: {}", + genesis.len() + ); + let far = wallet::daemon_get_block( + &addr, + info.height + 1_000_000, + std::time::Duration::from_secs(30), + ) + .await; + assert!( + matches!(far, Err(wallet::WalletError::DaemonHeightOutOfRange)), + "an above-the-tip height must map to the typed height error: {far:?}" + ); + + // The chain database is Cuprate's own embedded store, under the datadir it + // was given — never beside OnionWire's SQLCipher file. + let fjall = datadir.join("testnet").join("fjall"); + assert!( + fjall.is_dir(), + "the chain store must live under the chain datadir: {}", + fjall.display() + ); + + // Dropping the node *is* the shutdown. The listener has to go with it, or + // the app would leave a chain daemon behind after quitting. + drop(node); + let mut closed = false; + for _ in 0..40 { + if tokio::net::TcpStream::connect(&addr).await.is_err() { + closed = true; + break; + } + tokio::time::sleep(std::time::Duration::from_millis(250)).await; + } + assert!( + closed, + "the unrestricted RPC was still accepting after shutdown" + ); +} -- 2.52.0