onionwire/android/sdk/build.gradle.kts
sirius f9f2055f70
Some checks failed
ci / test (pull_request) Successful in 5m3s
ci / sdk (pull_request) Successful in 1m6s
ci / fuzz (pull_request) Successful in 4m45s
android-ci / android (pull_request) Failing after 13m57s
android: build the SDK with cuprate-daemon and offer the on-device node
Part 3 of "cuprated built in": the chain daemon now ships inside the APK and the
wallet screen can pick it.

Build (android/sdk/build.gradle.kts)
- `cargoBuildAndroid` runs `cargo ndk … build --release --lib --features
  cuprate-daemon`. The Android target only: `cargoHostLib` / `uniffiBindgen` stay
  feature-free, because the host cdylib exists only so `uniffi-bindgen --library`
  can dlopen it and the UniFFI surface does not fork on a cargo feature.
- The link needs the NDK's libc++ and compiler-rt builtins explicitly (RandomX is
  C++ and its aarch64 JIT calls `__clear_cache`; `randomx-rs` links the NDK's stub
  `libstdc++.a`). `cargo ndk --link-builtins` covers the builtins only, so the
  whole set is spelled out as per-ABI `CARGO_TARGET_<TRIPLE>_RUSTFLAGS` — a global
  `RUSTFLAGS` would break the host build scripts. The linker is the NDK clang
  driver at the app's API level, named explicitly, because the dev machines pin
  the API 21 wrapper for `aarch64-linux-android` and API 21 fails this link.
- `ANDROID_NDK` is exported alongside `ANDROID_NDK_HOME`/`NDK_HOME`: without it
  `cmake-rs` aborts and `randomx-rs`'s build script panics.
- The task logs the feature it builds with, so CI carries the request, not just
  the task name.

Wallet screen
- Third chain source, **On-device node (Cuprate)**, beside the daemon field and
  Receive-only. Stored as `ChainChoice.InProcessCuprate` with an empty
  `monerod_datadir`, which the SDK resolves to `$ONIONWIRE_HOME/chain`. Existing
  Save daemon / Receive-only / Start / Stop behaviour is unchanged.
- The status line grows `· node <word>` from `WalletChildStatus.node_state` for
  this source only, fail-closed on an unrecognised word. No sync height: the SDK
  exposes none, so the screen does not show a number it cannot get.
- Storage honesty: free space on the chain store's filesystem, and Start is
  refused below a 3 GiB floor or when that filesystem cannot be read. The floor is
  a floor, not a sync estimate — nothing here exposes one.
- The pre-production warning (quoted user book, testnet only, Cuprate issue #278)
  is a sentence above Start, assertable in a test. Opt-in, never a default.
- The daemon field's hint no longer suggests a loopback daemon on the phone.

CI
- `android-ci.yml` extracts `lib/<abi>/libonionwire_sdk.so` from the built APK and
  fails the job unless it contains `target_max_memory`, a rodata literal compiled
  only under `cuprate-daemon`. v0.7.0's shipped `.so` has zero of them, so this
  separates "in the artifact" from "requested".

Docs
- `android/CUPRATE_DAEMON.md`: the build wiring, the link line, the CI gate, and
  an explicit "not verified on a device" section. `MONERO_BINARIES.md` points at
  it for the chain source that is not a binary.
2026-09-18 15:34:30 -04:00

299 lines
13 KiB
Kotlin

import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.android)
}
// ---------------------------------------------------------------------------
// Rust: build crates/onionwire-sdk for the requested Android ABIs and generate
// the UniFFI Kotlin bindings from the host cdylib.
//
// Nothing here touches the Linux TUI crate's feature graph: the SDK crate is
// its own Cargo workspace that selects Arti's rustls backend.
// ---------------------------------------------------------------------------
val repoRoot: File = rootProject.projectDir.parentFile
val sdkCrateDir: File = repoRoot.resolve("crates/onionwire-sdk")
/** NDK version used for the Rust link step. Must match an installed NDK. */
val onionwireNdkVersion: String = (findProperty("onionwire.ndk") as String?)
?: "28.2.13676358"
/** Compile against this API level. Keep in sync with `minSdk`. */
val onionwireApiLevel: Int = ((findProperty("onionwire.api") as String?) ?: "26").toInt()
val androidSdkDir: File = sequenceOf(
System.getenv("ANDROID_HOME"),
System.getenv("ANDROID_SDK_ROOT"),
).filterNotNull().map(::File).firstOrNull()
?: rootProject.file("local.properties")
.takeIf { it.exists() }
?.readLines()
?.firstOrNull { it.startsWith("sdk.dir=") }
?.substringAfter('=')
?.trim()
?.let(::File)
?: error("ANDROID_HOME / ANDROID_SDK_ROOT unset and no sdk.dir in android/local.properties")
val ndkDir: File = androidSdkDir.resolve("ndk/$onionwireNdkVersion")
require(ndkDir.isDirectory) {
"NDK $onionwireNdkVersion not found at $ndkDir — run: sdkmanager --install \"ndk;$onionwireNdkVersion\""
}
val cargoExe: String = (findProperty("onionwire.cargo") as String?)
?: System.getenv("CARGO")
?: File(System.getProperty("user.home"), ".cargo/bin/cargo").takeIf { it.canExecute() }?.absolutePath
?: "cargo"
/** `-Ponionwire.abis=arm64-v8a,x86_64` to build more than one ABI. */
val onionwireAbis: List<String> = (findProperty("onionwire.abis") as String?)
?.split(',')?.map(String::trim)?.filter(String::isNotEmpty)
?: listOf("arm64-v8a")
/**
* Rust features for the **Android** target build.
*
* `cuprate-daemon` is what puts the in-process Monero chain daemon (Cuprate) in
* the APK — the SDK crate's passthrough to the core
* (`cuprate-daemon = ["onionwire/cuprate-daemon"]`), so `WalletChildStatus.node_available`
* is `true` on the device and `ChainChoice.InProcessCuprate` can actually start.
*
* Deliberately **not** applied to `cargoHostLib` / `uniffiBindgen`: those build a
* host cdylib only so `uniffi-bindgen --library` can dlopen it, the cuprated graph
* (152 crates plus a C++ RandomX build) buys nothing there, and the UniFFI surface
* does not fork on a cargo feature. The Kotlin bindings are byte-identical either
* way, which is what `crates/onionwire-sdk`'s own tests cover.
*/
val onionwireRustFeatures: List<String> = listOf("cuprate-daemon")
/** `arm64-v8a` -> the Rust triple, the sysroot dir name and the builtins archive. */
data class AndroidTarget(
val abi: String,
val triple: String,
/** Sysroot library dir under `.../sysroot/usr/lib/`. */
val sysrootLib: String,
/** `libclang_rt.builtins-<this>.a`, from the NDK clang resource dir. */
val builtins: String,
/** NDK clang driver prefix: `<this><api>-clang`. */
val clangPrefix: String,
)
val androidTargets: Map<String, AndroidTarget> = listOf(
AndroidTarget("arm64-v8a", "aarch64-linux-android", "aarch64-linux-android", "aarch64-android", "aarch64-linux-android"),
AndroidTarget("x86_64", "x86_64-linux-android", "x86_64-linux-android", "x86_64-android", "x86_64-linux-android"),
AndroidTarget("armeabi-v7a", "armv7-linux-androideabi", "arm-linux-androideabi", "arm-android", "armv7a-linux-androideabi"),
AndroidTarget("x86", "i686-linux-android", "i686-linux-android", "i386-android", "i686-linux-android"),
).associateBy(AndroidTarget::abi)
/** The NDK's host tag (`linux-x86_64`, `darwin-x86_64`, …) — exactly one prebuilt tree. */
val ndkHostTag: String = ndkDir.resolve("toolchains/llvm/prebuilt").listFiles()
?.filter(File::isDirectory)?.singleOrNull()?.name
?: error("expected exactly one NDK prebuilt toolchain under $ndkDir/toolchains/llvm/prebuilt")
/** The NDK clang resource dir (`lib/clang/<version>/lib/linux`) — exactly one version. */
val ndkClangLibDir: File = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/lib/clang")
.listFiles()?.filter(File::isDirectory)?.singleOrNull()
?.resolve("lib/linux")
?: error("expected exactly one clang resource dir under $ndkDir/toolchains/llvm/prebuilt/$ndkHostTag/lib/clang")
/**
* Per-ABI link flags for the Android build.
*
* RandomX is C++ and its aarch64 JIT calls `__clear_cache`, and `randomx-rs`'s
* build script emits `rustc-link-lib=static=stdc++` against the NDK's *stub*
* `libstdc++.a`. Without libc++ and the compiler-rt builtins on the link line the
* build dies on `__cxa_allocate_exception` / `std::runtime_error` / `typeinfo`
* (and `__clear_cache`) undefined. `cargo ndk --link-builtins` covers only the
* builtins, not libc++ — and `-static-libstdc++` is ignored by NDK clang — so the
* whole set is spelled out. Recipe and evidence: `docs/cuprate-android-spike.md`.
*
* Exported as `CARGO_TARGET_<TRIPLE>_RUSTFLAGS` rather than `RUSTFLAGS`: a global
* rustflags would also apply to build scripts and proc macros, which are
* **host**-targeted, and `-lc++_static` there breaks the host link.
*
* The same variables also *replace* any `target.<triple>.rustflags` in
* `~/.cargo/config.toml`, so the sysroot `-L` it carried is repeated here.
*/
fun linkFlags(target: AndroidTarget): String {
val sysrootLib = ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/sysroot/usr/lib/${target.sysrootLib}")
return listOf(
"-C", "link-arg=-L$sysrootLib",
"-C", "link-arg=-L$ndkClangLibDir",
"-C", "link-arg=-lclang_rt.builtins-${target.builtins}",
"-C", "link-arg=-lc++_static",
"-C", "link-arg=-lc++abi",
"-C", "link-arg=-Wl,--exclude-libs,libc++_static.a",
"-C", "link-arg=-Wl,--exclude-libs,libc++abi.a",
).joinToString(" ")
}
/** The NDK clang driver for one ABI at [onionwireApiLevel]. */
private fun clangDriver(target: AndroidTarget): File =
ndkDir.resolve("toolchains/llvm/prebuilt/$ndkHostTag/bin/${target.clangPrefix}$onionwireApiLevel-clang")
val jniLibsDir = layout.buildDirectory.dir("rustJniLibs")
val uniffiKotlinDir = layout.buildDirectory.dir("generated/uniffi")
// cargo honors CARGO_TARGET_DIR when set (CI sibling container). UniFFI's
// --library path must match, or bindgen dies with ENOENT after a green compile.
val cargoTargetDir: File = System.getenv("CARGO_TARGET_DIR")?.let(::File)
?: sdkCrateDir.resolve("target")
val hostCdylib: File = cargoTargetDir.resolve("release/libonionwire_sdk.so")
/**
* Host cdylib. UniFFI's `--library` mode dlopens it, so it must be host-arch.
*
* Feature-free **on purpose**: this exists only to emit the Kotlin bindings, and
* `cuprate-daemon` would drag the whole Cuprate graph (152 crates + a C++ RandomX
* build) through a host compile that never runs the daemon. The UniFFI surface
* does not fork on a cargo feature — `ChainChoice.InProcessCuprate` is present in
* both — so the generated Kotlin is the same. `onionwireRustFeatures` is for
* [cargoBuildAndroid] only.
*/
val cargoHostLib by tasks.registering(Exec::class) {
group = "onionwire"
description = "Builds libonionwire_sdk.so for the host (used only to emit bindings)."
workingDir = sdkCrateDir
environment("ANDROID_HOME", androidSdkDir.absolutePath)
commandLine(cargoExe, "build", "--release", "--lib")
}
val uniffiBindgen by tasks.registering(Exec::class) {
group = "onionwire"
description = "Generates the Kotlin UniFFI bindings into build/generated/uniffi."
dependsOn(cargoHostLib)
workingDir = sdkCrateDir
inputs.file(sdkCrateDir.resolve("src/lib.rs"))
outputs.dir(uniffiKotlinDir)
environment("ANDROID_HOME", androidSdkDir.absolutePath)
doFirst { uniffiKotlinDir.get().asFile.mkdirs() }
commandLine(
cargoExe, "run", "--release", "--bin", "uniffi-bindgen", "--",
"generate",
"--library", hostCdylib.absolutePath,
"--language", "kotlin",
"--no-format",
"--config", "uniffi.toml",
"--out-dir", uniffiKotlinDir.get().asFile.absolutePath,
)
}
val cargoBuildAndroid by tasks.registering(Exec::class) {
group = "onionwire"
description = "Cross-compiles crates/onionwire-sdk for ${onionwireAbis.joinToString()}."
workingDir = sdkCrateDir
inputs.dir(sdkCrateDir.resolve("src"))
inputs.file(sdkCrateDir.resolve("Cargo.toml"))
inputs.file(sdkCrateDir.resolve("Cargo.lock"))
inputs.dir(repoRoot.resolve("src"))
inputs.file(repoRoot.resolve("Cargo.toml"))
// The feature set is an input: `-Ponionwire.features=` … there is no knob
// (a build that silently dropped `cuprate-daemon` would ship an APK whose
// on-device node can only fail), but the task must not stay "up to date"
// across a change to this list.
inputs.property("rustFeatures", onionwireRustFeatures)
outputs.dir(jniLibsDir)
environment("ANDROID_HOME", androidSdkDir.absolutePath)
environment("ANDROID_NDK_HOME", ndkDir.absolutePath)
environment("NDK_HOME", ndkDir.absolutePath)
// `cmake-rs` (RandomX's C++ half) aborts with "Neither the NDK or a standalone
// toolchain was found" unless ANDROID_NDK itself is exported — NDK_HOME and
// ANDROID_NDK_HOME are not enough, and `randomx-rs`'s build script then panics
// inside `cmake`.
environment("ANDROID_NDK", ndkDir.absolutePath)
environment("ANDROID_NDK_ROOT", ndkDir.absolutePath)
// Per-ABI link env. The clang driver is named explicitly because
// `~/.cargo/config.toml` on the dev machines pins the *API 21* wrapper for
// `aarch64-linux-android`, and API 21 fails this link (`pthread_atfork` is
// API 23+); `cargo-ndk`'s own linker wrapper is bypassed on purpose so the
// `-Wl,…` args below reach clang as link args.
onionwireAbis.forEach { abi ->
val target = androidTargets[abi]
?: error("no Android target mapping for ABI '$abi' — add it to androidTargets in sdk/build.gradle.kts")
val rustFlagsVar = "CARGO_TARGET_${target.triple.uppercase().replace('-', '_')}_RUSTFLAGS"
val linkerVar = "CARGO_TARGET_${target.triple.uppercase().replace('-', '_')}_LINKER"
val linker = clangDriver(target)
require(linker.canExecute()) {
"NDK clang driver for $abi not found at $linker — NDK $onionwireNdkVersion incomplete?"
}
environment(rustFlagsVar, linkFlags(target))
environment(linkerVar, linker.absolutePath)
}
commandLine(
buildList {
add(cargoExe); add("ndk")
onionwireAbis.forEach { add("-t"); add(it) }
add("--platform"); add(onionwireApiLevel.toString())
add("-o"); add(jniLibsDir.get().asFile.absolutePath)
add("build"); add("--release"); add("--lib")
if (onionwireRustFeatures.isNotEmpty()) {
add("--features"); add(onionwireRustFeatures.joinToString(","))
}
}
)
// The CI log has to show the feature actually requested, not merely the task
// name: "the feature is in the artifact" is checked against this line.
doFirst {
logger.lifecycle(
"cargo ndk build for ${onionwireAbis.joinToString()} " +
"features=${onionwireRustFeatures.joinToString(",").ifEmpty { "(none)" }} " +
"api=$onionwireApiLevel ndk=$onionwireNdkVersion",
)
}
}
// ---------------------------------------------------------------------------
android {
namespace = "com.siriusdevops.onionwire.sdk"
compileSdk = 36
ndkVersion = onionwireNdkVersion
defaultConfig {
minSdk = onionwireApiLevel
consumerProguardFiles("consumer-rules.pro")
ndk {
abiFilters += onionwireAbis
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
sourceSets["main"].jniLibs.srcDir(jniLibsDir)
sourceSets["main"].kotlin.srcDir(uniffiKotlinDir)
buildTypes {
release {
isMinifyEnabled = false
}
}
}
kotlin {
compilerOptions {
jvmTarget.set(JvmTarget.JVM_17)
}
}
dependencies {
// UniFFI's Kotlin backend talks to the Rust cdylib through JNA direct
// mapping, and the async bindings need coroutines. Both are part of the
// public API surface, so they are `api` — a consumer of the AAR needs them
// on its own compile classpath. JNA's `aar` variant is what carries
// libjnidispatch.so for each ABI.
api(variantOf(libs.jna) { artifactType("aar") })
api(libs.kotlinx.coroutines.core)
}
tasks.withType<KotlinCompile>().configureEach {
dependsOn(uniffiBindgen)
}
tasks.matching { it.name == "preBuild" }.configureEach {
dependsOn(cargoBuildAndroid, uniffiBindgen)
}