onionwire-sdk: expose the on-device Cuprate chain source (choice, lifecycle, node status) #111

4 changed files with 1758 additions and 32 deletions

File diff suppressed because it is too large Load diff

View file

@ -17,6 +17,16 @@ resolver = "2"
name = "onionwire_sdk"
crate-type = ["cdylib", "lib"]
[features]
default = []
# The in-process Monero chain daemon (Cuprate). Off by default: it pulls a
# pinned `cuprated` git revision, ~152 crates and a C++ RandomX cross-build
# (+11.8 MiB on an aarch64 release binary). Without it the SDK can still store
# and read back a `ChainChoice.InProcessCuprate` setting — starting one fails
# with the core's "rebuild with --features cuprate-daemon" message.
cuprate-daemon = ["onionwire/cuprate-daemon"]
[dependencies]
onionwire = { path = "../..", default-features = false, features = ["rustls"] }
# `static-sqlite`: Android has no system libsqlite3 to link against.

View file

@ -25,7 +25,7 @@
//! The façade deliberately exposes only plain data (records + hex strings) so
//! no TUI/ratatui type leaks into the AAR.
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use onionwire::Message;
@ -35,7 +35,7 @@ use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus};
use onionwire::pay;
use onionwire::qr;
use onionwire::wallet::ChainSource;
use onionwire::wallet_child::ChildConfig;
use onionwire::wallet_child::{ChildConfig, WalletChildState};
uniffi::setup_scaffolding!();
@ -244,6 +244,10 @@ pub struct FlushOutcome {
#[derive(uniffi::Object)]
pub struct Wire {
node: Mutex<Option<Arc<Node>>>,
/// `$ONIONWIRE_HOME` exactly as [`open_wire`] was given it. The SDK resolves
/// the per-identity defaults a caller cannot know (the in-process chain
/// data directory) against it, so Kotlin never has to invent a path.
home: PathBuf,
}
impl Wire {
@ -279,11 +283,13 @@ pub async fn open_wire(home: String, passphrase: String) -> WResult<Arc<Wire>> {
// with "Could not automatically determine the process-level CryptoProvider"
// if no provider is resolvable. See `install_crypto_provider`.
install_crypto_provider();
let node = Node::start_with_passphrase(PathBuf::from(home), &passphrase)
let home = PathBuf::from(home);
let node = Node::start_with_passphrase(home.clone(), &passphrase)
.await
.map_err(WireError::new)?;
Ok(Arc::new(Wire {
node: Mutex::new(Some(node)),
home,
}))
}
@ -616,7 +622,8 @@ impl Wire {
pub async fn start_wallet_child(&self) -> WResult<WalletChildStatus> {
let node = self.node()?;
node.start_wallet_child().map_err(WireError::new)?;
Ok(child_status(node.wallet_child_refresh().await))
let source = node.wallet_child_config().source;
Ok(child_status(node.wallet_child_refresh().await, &source))
}
/// Stop the wallet child and its daemon/SOCKS siblings. Idempotent: stopping
@ -632,7 +639,9 @@ impl Wire {
///
/// Synchronous on purpose — it is safe to call from a UI refresh loop.
pub fn wallet_status(&self) -> WResult<WalletChildStatus> {
Ok(child_status(self.node()?.wallet_child_status()))
let node = self.node()?;
let source = node.wallet_child_config().source;
Ok(child_status(node.wallet_child_status(), &source))
}
/// The chain-source + binary settings the child spawns with, as stored.
@ -652,7 +661,7 @@ impl Wire {
/// binary the caller named explicitly.
pub fn set_chain_source(&self, config: ChainConfig) -> WResult<()> {
self.node()?
.set_wallet_child_config(&child_config(config))
.set_wallet_child_config(&child_config(config, &self.home))
.map_err(WireError::new)
}
@ -720,7 +729,13 @@ fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome {
}
/// The core child settings a [`ChainConfig`] describes.
fn child_config(cfg: ChainConfig) -> ChildConfig {
///
/// `home` is the `$ONIONWIRE_HOME` the identity was opened with. An in-process
/// chain source with an empty `monerod_datadir` resolves to `home/chain` — the
/// per-identity directory the core documents for a local chain — so a Kotlin
/// caller never has to invent an absolute path. Every other kind uses exactly
/// what it was given (or the core's own default), unchanged.
fn child_config(cfg: ChainConfig, home: &Path) -> ChildConfig {
let source = match cfg.kind {
ChainChoice::None => ChainSource::None,
ChainChoice::Local => ChainSource::Local {
@ -728,7 +743,11 @@ fn child_config(cfg: ChainConfig) -> ChildConfig {
datadir: PathBuf::from(cfg.monerod_datadir),
},
ChainChoice::InProcessCuprate => ChainSource::InProcessCuprate {
datadir: PathBuf::from(cfg.monerod_datadir),
datadir: if cfg.monerod_datadir.trim().is_empty() {
home.join("chain")
} else {
PathBuf::from(cfg.monerod_datadir)
},
},
ChainChoice::Remote => ChainSource::Remote {
host: cfg.host,
@ -791,16 +810,56 @@ fn chain_config(cfg: &ChildConfig) -> ChainConfig {
}
/// The core child snapshot as the SDK record.
fn child_status(status: onionwire::wallet_child::WalletChildStatus) -> WalletChildStatus {
///
/// `source` is the configured chain source the snapshot came from: it is what
/// makes the node-scoped fields possible without the core exposing a second
/// liveness signal for the in-process daemon.
fn child_status(
status: onionwire::wallet_child::WalletChildStatus,
source: &ChainSource,
) -> WalletChildStatus {
let in_process = matches!(source, ChainSource::InProcessCuprate { .. });
WalletChildStatus {
state: status.state.as_str().to_string(),
running: status.running,
configured: status.configured,
chain_source: status.chain_source,
chain_in_process: in_process,
node_available: onionwire::cuprate::available(),
node_state: if in_process {
node_state(status.state).to_string()
} else {
String::new()
},
last_error: status.last_error,
}
}
/// The node-scoped word for the in-process daemon, derived from the core's own
/// child state. A projection, not a second state machine: no input here is a
/// timer, an env var, or a file.
///
/// For an in-process source the wallet child is a client of *this app's* node,
/// so the core's own sequence is the node's: it cannot answer before the
/// daemon's loopback RPC is up (`connecting`), it answers but is behind the tip
/// while the daemon syncs (`syncing`), and `ready` requires a synced chain.
///
/// Limit, stated rather than papered over: the core exposes no separate
/// liveness signal for the in-process node (it is a value this app owns, not a
/// process with a pid), so a daemon that dies *after* its wallet child came up
/// cannot be reported as `exited` — the chain probe fails and the state stays
/// `syncing`. It is never reported `ready`, and `exited` still means what it
/// says: the `monero-wallet-rpc` child is gone.
fn node_state(state: WalletChildState) -> &'static str {
match state {
WalletChildState::Off => "off",
WalletChildState::Connecting => "starting",
WalletChildState::Syncing => "syncing",
WalletChildState::Ready => "ready",
WalletChildState::Exited => "exited",
}
}
fn hex(bytes: &[u8]) -> String {
let mut s = String::with_capacity(bytes.len() * 2);
for b in bytes {
@ -916,7 +975,10 @@ pub struct ChainConfig {
/// `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.
/// in-process daemon stores its (fjall) chain in. For that kind an empty
/// string means "use the per-identity default" (`$ONIONWIRE_HOME/chain`,
/// resolved by the SDK), so Kotlin never has to invent an absolute path;
/// `Local` still requires a real one.
pub monerod_datadir: String,
/// `Remote` only. Daemon host.
pub host: String,
@ -950,6 +1012,23 @@ pub struct WalletChildStatus {
pub configured: bool,
/// The chain-source label.
pub chain_source: String,
/// The configured source runs the chain daemon **inside this app** (Cuprate)
/// rather than spawning `monerod` or dialling a remote one. When true,
/// `state` — and `node_state` — describe this app's own node *and* its
/// wallet child: there is no separate daemon process to report on, and the
/// wallet child is a client of the in-process node, not a peer of one.
pub chain_in_process: bool,
/// This build can actually start the in-process daemon (`cuprate-daemon`).
/// `false` means the option is offered by the store but a start can only
/// fail — grey it out before the user commits, do not start and catch.
pub node_available: bool,
/// The in-process daemon's own state, for a status line that names the
/// node: `off` / `starting` / `syncing` / `ready` / `exited`. Empty for
/// every other chain source, so a Kotlin line shows no node segment for a
/// spawned `monerod`. `starting` is the core's `connecting` read from the
/// node's side (the daemon's loopback RPC has not answered yet); it is
/// never persisted, polled from a file, or inferred from a timeout.
pub node_state: String,
/// The last failure, display-ready. Never carries the generated login.
pub last_error: Option<String>,
}
@ -1168,6 +1247,7 @@ mod tests {
fn stopped_wire() -> Wire {
Wire {
node: Mutex::new(None),
home: PathBuf::from("/tmp/onionwire-sdk-stopped"),
}
}
@ -1611,4 +1691,184 @@ mod tests {
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
}
/// The `$ONIONWIRE_HOME` a caller opened the identity with. `Wire` keeps it
/// internally; these tests drive the same two pure helpers
/// `set_chain_source` / `chain_source` go through.
fn sdk_home() -> PathBuf {
PathBuf::from("/data/user/0/dev.sirius.onionwire/files")
}
/// A request as Kotlin builds one: only the fields the chosen kind uses are
/// set.
fn request(kind: ChainChoice, datadir: &str) -> ChainConfig {
ChainConfig {
kind,
monerod_bin: String::new(),
monerod_datadir: datadir.to_string(),
host: String::new(),
port: 0,
wallet_rpc_bin: "/data/app/nativeLibraryDir/libmonerowalletrpc.so".to_string(),
arti_bin: "/data/app/nativeLibraryDir/libarti.so".to_string(),
wallet_filename: "wallet".to_string(),
}
}
/// Kotlin must not have to invent a chain data directory: an empty
/// `monerod_datadir` on the in-process source resolves to the per-identity
/// `chain` directory the core documents (`$ONIONWIRE_HOME/chain`), and no
/// binary path is involved at all.
#[test]
fn an_empty_in_process_datadir_resolves_under_the_wire_home() {
let child = child_config(request(ChainChoice::InProcessCuprate, ""), &sdk_home());
assert_eq!(
child.source,
ChainSource::InProcessCuprate {
datadir: sdk_home().join("chain")
}
);
assert_eq!(child.source_label(), "in-process node");
}
#[test]
fn an_explicit_in_process_datadir_is_taken_as_given() {
let given = "/data/user/0/dev.sirius.onionwire/files/chain-heavy";
let child = child_config(request(ChainChoice::InProcessCuprate, given), &sdk_home());
assert_eq!(
child.source,
ChainSource::InProcessCuprate {
datadir: PathBuf::from(given)
}
);
}
/// Every kind survives the round trip a settings screen does (`ChainConfig`
/// -> core `ChildConfig` -> `ChainConfig`), so a prefill shows what was
/// stored rather than a default.
#[test]
fn every_chain_choice_round_trips_through_the_sdk_mapping() {
for kind in [
ChainChoice::None,
ChainChoice::Local,
ChainChoice::InProcessCuprate,
ChainChoice::Remote,
] {
let mut req = request(kind, "");
match kind {
ChainChoice::Local => {
req.monerod_bin = "/data/app/nativeLibraryDir/libmonerod.so".to_string();
req.monerod_datadir = sdk_home().join("chain").display().to_string();
}
ChainChoice::Remote => {
req.host = "peer.onion".to_string();
req.port = 18081;
}
ChainChoice::None | ChainChoice::InProcessCuprate => {}
}
let back = chain_config(&child_config(req.clone(), &sdk_home()));
assert_eq!(back.kind, kind, "kind lost for {kind:?}");
assert_eq!(back.wallet_rpc_bin, req.wallet_rpc_bin);
assert_eq!(back.arti_bin, req.arti_bin);
assert_eq!(back.wallet_filename, req.wallet_filename);
match kind {
ChainChoice::InProcessCuprate => {
assert_eq!(
back.monerod_datadir,
sdk_home().join("chain").display().to_string()
);
assert!(
back.monerod_bin.is_empty(),
"no binary for an in-process node"
);
}
ChainChoice::Local => {
assert_eq!(back.monerod_bin, req.monerod_bin);
assert_eq!(back.monerod_datadir, req.monerod_datadir);
}
ChainChoice::Remote => {
assert_eq!(back.host, "peer.onion");
assert_eq!(back.port, 18081);
}
ChainChoice::None => {
assert_eq!(back.monerod_datadir, "");
assert_eq!(back.host, "");
}
}
}
}
fn core_status(state: WalletChildState) -> onionwire::wallet_child::WalletChildStatus {
onionwire::wallet_child::WalletChildStatus {
state,
running: true,
configured: true,
chain_source: "in-process node".to_string(),
last_error: None,
}
}
/// `wallet_status` speaks about the app's own node for the in-process
/// source: the five core states map to node-scoped words, and no state
/// becomes `ready` that the core did not report as ready.
#[test]
fn node_state_names_the_apps_own_chain_for_the_in_process_source() {
let source = ChainSource::InProcessCuprate {
datadir: sdk_home().join("chain"),
};
let cases = [
(WalletChildState::Off, "off"),
(WalletChildState::Connecting, "starting"),
(WalletChildState::Syncing, "syncing"),
(WalletChildState::Ready, "ready"),
(WalletChildState::Exited, "exited"),
];
for (state, want) in cases {
let status = child_status(core_status(state), &source);
assert_eq!(status.node_state, want, "state {state:?}");
assert!(status.chain_in_process, "state {state:?}");
// The core's own word is still carried verbatim, for a caller that
// renders `state` instead.
assert_eq!(status.state, state.as_str());
}
}
/// A source that is not the in-process node reports no node segment, so a
/// Kotlin status line cannot show a node word for a spawned `monerod` or a
/// remote daemon — and `state` still passes straight through.
#[test]
fn node_state_is_empty_for_every_other_chain_source() {
for source in [
ChainSource::None,
ChainSource::Local {
monerod_bin: PathBuf::from("monerod"),
datadir: PathBuf::from("/chain"),
},
ChainSource::Remote {
host: "peer.onion".to_string(),
port: 18081,
},
] {
let status = child_status(core_status(WalletChildState::Ready), &source);
assert!(
!status.chain_in_process,
"{} is not in-process",
source.label()
);
assert_eq!(
status.node_state,
"",
"{} must have no node state",
source.label()
);
assert_eq!(status.state, "ready");
}
}
/// Whether *this* build can start the node is a build fact the picker greys
/// the option out with before a start is attempted.
#[test]
fn node_available_reports_whether_this_build_has_the_daemon() {
let status = child_status(core_status(WalletChildState::Off), &ChainSource::None);
assert_eq!(status.node_available, onionwire::cuprate::available());
}
}

View file

@ -142,8 +142,8 @@ cargo build --release --features cuprate-daemon
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.
wallet is started. The SDK's `ChainChoice.InProcessCuprate` is that variant
over UniFFI, and `kind = "cuprate"` is the record's spelling.
### Chain traffic over Tor (`.onion` daemons)
@ -329,9 +329,9 @@ wallet screen (F6):
The state shown next to the wallet readouts is `off` / `connecting` / `syncing`
/ `ready` / `exited`, plus the chain-source label (`receive-only`,
`local node`, `remote onion daemon`, `remote daemon`). It is derived from the
real process (`try_wait`) and the last probe — **never** from env-var presence,
and `ready` is never reported for a child that has died.
`local node`, `in-process node`, `remote onion daemon`, `remote daemon`). It is
derived from the real process (`try_wait`) and the last probe — **never** from
env-var presence, and `ready` is never reported for a child that has died.
- **`off`** — nothing started (or stopped). The default state.
- **`connecting`** — the `monero-wallet-rpc` process is alive but has not
@ -357,7 +357,15 @@ credentials live*), so they survive a restart:
- Android (UniFFI): `set_chain_source(ChainConfig)` / `chain_source()`,
`start_wallet_child()`, `stop_wallet_child()`, `wallet_status()`. Pass
absolute paths for `wallet_rpc_bin` / `arti_bin` (`nativeLibraryDir`); the
core never resolves a binary the caller named explicitly.
core never resolves a binary the caller named explicitly. `ChainChoice` has a
fourth variant, `InProcessCuprate`, for the in-process daemon: no binary path
and, with an empty `monerod_datadir`, the SDK resolves the chain directory to
`$ONIONWIRE_HOME/chain`. `start_wallet_child()` is the whole lifecycle for it
(the core launches the node *and* the wallet child in that one call), and
`wallet_status()` carries `chain_in_process` (this app's node is the source),
`node_available` (this build has `cuprate-daemon`) and `node_state`
(`off` / `starting` / `syncing` / `ready` / `exited`, empty for every other
source) beside the core's own five `state` words.
So local mode is **available**, not wired off: a local chain source spawns
`monerod` from the path you set, a `.onion` daemon spawns the `arti` SOCKS