From 2e4836f5e8f646f4c8af133f460f20fac8f9df9c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:32:51 -0500 Subject: [PATCH] Android app can mine: native RandomX engine, WikiDeckMiner plugin, mobile panel - scripts/build-randomx-android.sh: NDK cross-build of the pinned native/ engine (light mode) for arm64-v8a and x86_64, packaged as jniLibs//libwikideck_randomx.so - MinerPlugin.java (Capacitor "WikiDeckMiner"): runs engine processes over the line protocol, on-device self-test, and halts on background, battery saver, thermal, hot or low battery. Never receives wallet keys. - src/mobile-miner.ts: template -> mine -> sign -> submit loop in the WebView, byte-identical to consensus miningBlob/mintId (tests/mobile-mining-miner.test.ts) - src/MobileMiningPanel.tsx: consent, intensity (1 thread default; Max = 4 only while charging), live hashrate/status; testnet-only (disabled on mainnet builds) - docs/night2/MOBILE_MINING.md: how it works, safeguards, measured hashrate, store policies (sideload APK only), options for Eric No protocol, consensus or server changes. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 4 + android/app/build.gradle | 7 + .../java/dev/eom/wikideck/MainActivity.java | 11 +- .../java/dev/eom/wikideck/MinerPlugin.java | 264 ++++++++++++++++++ android/build-debug.sh | 6 +- docs/night2/MOBILE_MINING.md | 76 +++++ scripts/build-randomx-android.sh | 35 +++ src/App.tsx | 4 +- src/MobileMiningPanel.tsx | 144 ++++++++++ src/mobile-miner.ts | 173 ++++++++++++ src/mobile-mining.css | 10 + tests/mobile-mining-miner.test.ts | 121 ++++++++ 12 files changed, 852 insertions(+), 3 deletions(-) create mode 100644 android/app/src/main/java/dev/eom/wikideck/MinerPlugin.java create mode 100644 docs/night2/MOBILE_MINING.md create mode 100755 scripts/build-randomx-android.sh create mode 100644 src/MobileMiningPanel.tsx create mode 100644 src/mobile-miner.ts create mode 100644 src/mobile-mining.css create mode 100644 tests/mobile-mining-miner.test.ts diff --git a/.gitignore b/.gitignore index a34d4d9..d6d4a52 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,7 @@ dist-ssr *.njsproj *.sln *.sw? + +# Native RandomX engine for the app (scripts/build-randomx-android.sh) +native/build-android-*/ +android/app/src/main/jniLibs/ diff --git a/android/app/build.gradle b/android/app/build.gradle index 58a9e88..093389e 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -16,6 +16,13 @@ android { ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~' } } + packagingOptions { + jniLibs { + // The RandomX engine (jniLibs//libwikideck_randomx.so) is an executable, not a JNI library. + // Android may exec it only from the extracted nativeLibraryDir, so keep legacy extraction. + useLegacyPackaging true + } + } buildTypes { release { minifyEnabled false diff --git a/android/app/src/main/java/dev/eom/wikideck/MainActivity.java b/android/app/src/main/java/dev/eom/wikideck/MainActivity.java index 94c31d3..f6d5dbd 100644 --- a/android/app/src/main/java/dev/eom/wikideck/MainActivity.java +++ b/android/app/src/main/java/dev/eom/wikideck/MainActivity.java @@ -1,5 +1,14 @@ package dev.eom.wikideck; +import android.os.Bundle; + import com.getcapacitor.BridgeActivity; -public class MainActivity extends BridgeActivity {} +public class MainActivity extends BridgeActivity { + @Override + public void onCreate(Bundle savedInstanceState) { + // Local plugins must be registered before the bridge starts. + registerPlugin(MinerPlugin.class); + super.onCreate(savedInstanceState); + } +} diff --git a/android/app/src/main/java/dev/eom/wikideck/MinerPlugin.java b/android/app/src/main/java/dev/eom/wikideck/MinerPlugin.java new file mode 100644 index 0000000..07732dc --- /dev/null +++ b/android/app/src/main/java/dev/eom/wikideck/MinerPlugin.java @@ -0,0 +1,264 @@ +package dev.eom.wikideck; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.BatteryManager; +import android.os.Build; +import android.os.PowerManager; + +import com.getcapacitor.JSObject; +import com.getcapacitor.Plugin; +import com.getcapacitor.PluginCall; +import com.getcapacitor.PluginMethod; +import com.getcapacitor.annotation.CapacitorPlugin; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +/** + * Native RandomX engine for the WikiDeck app (sideload build only, see docs/night2/MOBILE_MINING.md). + * + * The plugin only runs the pinned `wikideck-randomx` executable (shipped as jniLibs//libwikideck_randomx.so) + * in LIGHT mode and speaks its line protocol (docs/randomx-native.md). It never sees wallet keys: the WebView builds + * the work blob, signs the block claim with the web wallet, and submits it to the node. This class also enforces the + * device safeguards: engines are killed when the app goes to the background, on battery saver, when the device is + * hot, or when the battery is low and not charging. Each stop is reported to the WebView as a `halted` event. + */ +@CapacitorPlugin(name = "WikiDeckMiner") +public class MinerPlugin extends Plugin { + private static final String BINARY = "libwikideck_randomx.so"; + private static final int MAX_THREADS = 4; + /** At or above Android's THERMAL_STATUS_MODERATE we stop. */ + private static final int THERMAL_LIMIT = 2; + /** Battery temperature limit in tenths of a degree Celsius. */ + private static final int BATTERY_TEMP_LIMIT = 400; + private static final int LOW_BATTERY_PERCENT = 20; + private static final Pattern HEX = Pattern.compile("^[0-9a-f]+$"); + + private final List engines = new ArrayList<>(); + private BroadcastReceiver receiver; + private Object thermalListener; + + /** One long-lived engine process with exactly one outstanding command (it is strictly request/response). */ + private static final class Engine { + final Process process; + final OutputStream in; + final BufferedReader out; + final ExecutorService worker = Executors.newSingleThreadExecutor(); + Engine(Process process) { + this.process = process; + this.in = process.getOutputStream(); + this.out = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.US_ASCII)); + } + String command(String line) throws Exception { + in.write((line + "\n").getBytes(StandardCharsets.US_ASCII)); + in.flush(); + String reply = out.readLine(); + if (reply == null) throw new Exception("RandomX engine exited"); + return reply; + } + void kill() { + worker.shutdownNow(); + try { in.close(); } catch (Exception ignored) { } + process.destroy(); + try { if (!process.waitFor(1, TimeUnit.SECONDS)) process.destroyForcibly(); } catch (InterruptedException ignored) { } + } + } + + private File binary() { + return new File(getContext().getApplicationInfo().nativeLibraryDir, BINARY); + } + + @Override + public void load() { + receiver = new BroadcastReceiver() { + @Override public void onReceive(Context context, Intent intent) { checkAndHalt(); } + }; + IntentFilter filter = new IntentFilter(); + filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED); + filter.addAction(Intent.ACTION_BATTERY_CHANGED); + getContext().registerReceiver(receiver, filter); + if (Build.VERSION.SDK_INT >= 29) { + PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE); + PowerManager.OnThermalStatusChangedListener l = status -> checkAndHalt(); + pm.addThermalStatusListener(l); + thermalListener = l; + } + } + + @Override + protected void handleOnPause() { + halt("background"); + super.handleOnPause(); + } + + @Override + protected void handleOnDestroy() { + halt("closed"); + try { getContext().unregisterReceiver(receiver); } catch (Exception ignored) { } + if (Build.VERSION.SDK_INT >= 29 && thermalListener != null) { + PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE); + pm.removeThermalStatusListener((PowerManager.OnThermalStatusChangedListener) thermalListener); + } + super.handleOnDestroy(); + } + + /** Current device state and, if mining must not run, the reason. */ + private JSObject conditionsObject() { + PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE); + Intent battery = getContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); + int temp = battery == null ? -1 : battery.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1); + int level = battery == null ? -1 : battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); + int scale = battery == null ? -1 : battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1); + int plugged = battery == null ? 0 : battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0); + int percent = level >= 0 && scale > 0 ? Math.round(100f * level / scale) : -1; + int thermal = Build.VERSION.SDK_INT >= 29 ? pm.getCurrentThermalStatus() : 0; + boolean powerSave = pm.isPowerSaveMode(); + String block = null; + if (powerSave) block = "battery-saver"; + else if (thermal >= THERMAL_LIMIT) block = "thermal"; + else if (temp >= BATTERY_TEMP_LIMIT) block = "battery-hot"; + else if (plugged == 0 && percent >= 0 && percent < LOW_BATTERY_PERCENT) block = "battery-low"; + JSObject o = new JSObject(); + o.put("powerSave", powerSave); + o.put("thermalStatus", thermal); + o.put("batteryTempC", temp < 0 ? null : temp / 10.0); + o.put("batteryPercent", percent); + o.put("charging", plugged != 0); + o.put("cores", Runtime.getRuntime().availableProcessors()); + o.put("abi", Build.SUPPORTED_ABIS.length > 0 ? Build.SUPPORTED_ABIS[0] : "unknown"); + o.put("engineInstalled", binary().canExecute()); + o.put("blocked", block); + return o; + } + + private void checkAndHalt() { + String block = conditionsObject().getString("blocked"); + if (block != null) halt(block); + } + + private synchronized void halt(String reason) { + if (engines.isEmpty()) return; + for (Engine e : engines) e.kill(); + engines.clear(); + JSObject event = new JSObject(); + event.put("reason", reason); + notifyListeners("halted", event); + } + + @PluginMethod + public void conditions(PluginCall call) { + call.resolve(conditionsObject()); + } + + /** Runs upstream's known-vector test (Hash test 1a/2a) on this device. */ + @PluginMethod + public void selfTest(PluginCall call) { + new Thread(() -> { + try { + Process p = new ProcessBuilder(binary().getAbsolutePath(), "--self-test").redirectErrorStream(true).start(); + p.getOutputStream().close(); + StringBuilder text = new StringBuilder(); + BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8)); + for (String line; (line = r.readLine()) != null && text.length() < 2000; ) text.append(line).append('\n'); + boolean done = p.waitFor(120, TimeUnit.SECONDS); + if (!done) p.destroyForcibly(); + JSObject o = new JSObject(); + o.put("ok", done && p.exitValue() == 0); + o.put("output", text.toString().trim()); + call.resolve(o); + } catch (Exception e) { + call.reject("Self-test failed to run: " + e.getMessage()); + } + }).start(); + } + + /** Starts 1..4 light-mode engines (more than 2 only while charging) (each needs about 256 MiB). Refuses if a safeguard is active. */ + @PluginMethod + public synchronized void start(PluginCall call) { + int threads = call.getInt("threads", 1); + if (threads < 1 || threads > MAX_THREADS || threads > Runtime.getRuntime().availableProcessors()) { call.reject("threads must be 1 to " + MAX_THREADS + " and at most the core count"); return; } + String block = conditionsObject().getString("blocked"); + if (block == null && threads > 2 && !conditionsObject().getBool("charging")) block = "max-needs-charging"; + if (block != null) { call.reject("Mining is paused: " + block, block); return; } + if (!engines.isEmpty()) { for (Engine e : engines) e.kill(); engines.clear(); } + try { + for (int i = 0; i < threads; i++) { + // No arguments = LIGHT mode. `--fast` (about 2 GiB) is never used on phones. + Process p = new ProcessBuilder(binary().getAbsolutePath()).redirectError(ProcessBuilder.Redirect.to(new File("/dev/null"))).start(); + engines.add(new Engine(p)); + } + } catch (Exception e) { + for (Engine en : engines) en.kill(); + engines.clear(); + call.reject("Could not start the RandomX engine: " + e.getMessage()); + return; + } + JSObject o = new JSObject(); + o.put("threads", threads); + call.resolve(o); + } + + @PluginMethod + public synchronized void stop(PluginCall call) { + for (Engine e : engines) e.kill(); + engines.clear(); + call.resolve(); + } + + /** + * One bounded batch on engine `lane`: `mine `. + * Resolves {found:false} on exhaustion or {found:true, hash, nonce} (nonce as a decimal string). + */ + @PluginMethod + public void mine(PluginCall call) { + String key = call.getString("key", ""), blob = call.getString("blob", ""), target = call.getString("target", ""); + int lane = call.getInt("lane", 0), offset = call.getInt("nonceOffset", -1), attempts = call.getInt("maxAttempts", 0); + if (key.length() != 64 || target.length() != 64 || blob.length() < 2 || blob.length() > 16384 || blob.length() % 2 != 0 + || !HEX.matcher(key).matches() || !HEX.matcher(target).matches() || !HEX.matcher(blob).matches() + || offset < 0 || offset + 8 > blob.length() / 2 || attempts < 1 || attempts > 10000) { + call.reject("Invalid mining request"); + return; + } + final Engine engine; + synchronized (this) { + if (lane < 0 || lane >= engines.size()) { call.reject("Miner is not running", "stopped"); return; } + engine = engines.get(lane); + } + String line = "mine " + key + " " + blob + " " + target + " " + offset + " " + attempts; + try { + engine.worker.execute(() -> { + try { + String reply = engine.command(line); + JSObject o = new JSObject(); + if (reply.equals("exhausted")) { + o.put("found", false); + } else { + String[] parts = reply.split(" "); + if (parts.length != 3 || !parts[0].equals("found") || parts[1].length() != 64 || !HEX.matcher(parts[1]).matches() + || !parts[2].matches("^[0-9]{1,20}$")) throw new Exception("Malformed engine reply"); + o.put("found", true); + o.put("hash", parts[1]); + o.put("nonce", parts[2]); + } + call.resolve(o); + } catch (Exception e) { + call.reject("Miner stopped: " + e.getMessage(), "stopped"); + } + }); + } catch (Exception e) { + call.reject("Miner is not running", "stopped"); + } + } +} diff --git a/android/build-debug.sh b/android/build-debug.sh index a114749..e3a5cfb 100755 --- a/android/build-debug.sh +++ b/android/build-debug.sh @@ -1,11 +1,15 @@ #!/bin/sh # Build the WikiDeck debug APK against the private Night-1 testnet. -# Needs ANDROID_HOME and a JDK 21 (JAVA_HOME). Output: android/app/build/outputs/apk/debug/app-debug.apk +# Needs ANDROID_HOME (with an NDK and CMake for the RandomX engine) and a JDK 21 (JAVA_HOME). Output: android/app/build/outputs/apk/debug/app-debug.apk set -eu cd "$(dirname "$0")/.." export VITE_WIKIDECK_NETWORK="${VITE_WIKIDECK_NETWORK:-testnet}" export VITE_WIKIDECK_GENESIS_TIME="${VITE_WIKIDECK_GENESIS_TIME:-1792411200}" export VITE_NODE_URL="${VITE_NODE_URL:-http://192.168.1.32:3101}" +# Native RandomX engine (jniLibs//libwikideck_randomx.so); built once, reused after (scripts/build-randomx-android.sh). +for abi in ${ABIS:-arm64-v8a x86_64}; do + [ -x "android/app/src/main/jniLibs/$abi/libwikideck_randomx.so" ] || ABIS="$abi" sh scripts/build-randomx-android.sh +done npm run build npx cap sync android cd android && ./gradlew --no-daemon -q assembleDebug diff --git a/docs/night2/MOBILE_MINING.md b/docs/night2/MOBILE_MINING.md new file mode 100644 index 0000000..01654ca --- /dev/null +++ b/docs/night2/MOBILE_MINING.md @@ -0,0 +1,76 @@ +# Mobile mining (Android, sideload build) + +**Status (Night 2, 2026-11-17):** see "Results tonight" below. Issue: claude/wikideck#59. + +BRIEF decision 4: the mobile app must be able to mine, because otherwise mobile players can never earn the 40 owned cards a deck needs. Night 1's `isNativeApp()` hid the mining panel and the app had no miner at all. + +## App stores: why this is a sideloaded APK +**Google Play and the Apple App Store both prohibit on-device cryptocurrency mining**, so the mining build cannot ship through either store. It is distributed as a sideloaded APK only. +- **Google Play**, Developer Program Policy, *Device and Network Abuse*: "We don't allow apps that mine cryptocurrency on devices." Apps that *remotely manage* mining that happens elsewhere are allowed. +- **Apple**, App Review Guidelines **3.1.5(b)(ii) Cryptocurrencies, Mining**: "Apps may not mine for cryptocurrencies unless the processing is performed off device (e.g. cloud-based mining)." Guideline 2.4.2 also bans unrelated background processes such as mining. + +A WikiDeck block is a RandomX proof-of-work that mints an NFT on WikiDeck's own chain. That is cryptocurrency mining under both policies, whatever the reward looks like. Re-check the policy wording before any store submission; these quotes are from memory, not verified tonight (tests and agents make no web calls). + +## How it works +``` +WebView (React) Native (Java, Capacitor plugin "WikiDeckMiner") +src/MobileMiningPanel.tsx consent, intensity, stats +src/mobile-miner.ts same loop as server/testnet/miner.ts + POST /api/mining/template {owner, publicKey} ──► node (picks the article and stats; the phone never calls Wikipedia) + build blob = sha256(headerMessage) || nonceLE8 + WikiDeckMiner.mine(lane, key, blob, target, 32, 16) ──► MinerPlugin.java ──stdin/stdout──► libwikideck_randomx.so + (the pinned native/ engine, LIGHT mode, line protocol) + found → hash, tokenId (mintId), sign(blockClaimMessage) with the web wallet + POST /api/blocks ──► node validates as usual +``` +- **Same engine as desktop.** `native/` (RandomX v1.2.1, pinned SHA `102f8acf…`) is cross-compiled with the Android NDK by `scripts/build-randomx-android.sh` for `arm64-v8a` and `x86_64` (the emulator). It is packaged as `jniLibs//libwikideck_randomx.so`: an executable named like a library, so Android extracts it to `nativeLibraryDir`, the one place an app may `exec` from (`useLegacyPackaging true` in `android/app/build.gradle`). The binaries are build outputs, so they're gitignored, and `android/build-debug.sh` builds them when they're missing. +- **Light mode only** (256 MiB cache per engine process). Fast mode (about 2 GiB) is never started on a phone: the plugin runs the binary with no arguments. +- **Known-vector check on the device.** Before the first start in each session, the app runs `libwikideck_randomx.so --self-test` (upstream Hash test 1a/2a). If the hash doesn't match, mining is disabled. A wrong hash would get every block rejected. +- **Keys never leave the web wallet.** The plugin only receives the public work (key, blob, target). The WebView builds and signs the block with the existing wallet code (`src/wallet.ts` `sign`). The private key and backup password are never passed to native code or to the node. +- **No protocol, consensus or server changes.** `src/mobile-miner.ts` rebuilds `miningBlob` and `mintId` with Web Crypto. `tests/mobile-mining-miner.test.ts` checks that they're byte-identical to `server/testnet/consensus.ts` and that the consensus validator accepts the assembled block. +- **Testnet only tonight.** In a mainnet build (`IS_MAINNET`), the panel only says mainnet mining isn't enabled. The debug build points at the private testnet `http://192.168.1.32:3101`. + +## Safeguards +| Safeguard | How | +|---|---| +| Explicit consent | An unchecked consent box ("uses this phone's CPU and battery and can make it warm"). Start stays disabled until it's ticked. The choice is stored locally (`wikideck.mobileMining.consent.v1`). | +| Intensity | Low (1 thread, rests 400 ms between 16-hash batches), **Normal (1 thread, default)**, High (2 threads, about 512 MiB, offered only on 4+ cores). | +| Foreground only | `MinerPlugin.handleOnPause` kills the engines as soon as the activity pauses, and the WebView also stops on `visibilitychange`. There is no foreground service, no wake lock and no background mining. The web wallet also locks when the app is hidden. | +| Battery saver | `PowerManager.isPowerSaveMode()`, checked before start, every 2 s while mining, and on `ACTION_POWER_SAVE_MODE_CHANGED`. | +| Heat | `PowerManager.getCurrentThermalStatus() >= THERMAL_STATUS_MODERATE` (API 29+, with a listener), or a battery temperature of 40 °C or more (`ACTION_BATTERY_CHANGED`). | +| Low battery | Below 20 % while not charging. | +| Visible activity | Live hashrate, hashes tried, the block height being mined, accepted blocks, battery % and °C, and the self-test result. | +| Wallet change | If the wallet locks or changes, mining stops, so it never keeps mining to an old address. | + +Each automatic stop shows its reason ("Paused: battery saver is on"). Mining never restarts by itself: the player taps Start again. + +**Wallet idle lock:** a found block must be signed by the unlocked wallet, and the wallet locks after 5 minutes without taps. While mining is active (which means foreground and consented), each status update calls `touchWallet()` to keep the session alive. The 4-hour absolute limit and lock-on-hide still apply. Reviewers, please check that this trade-off is acceptable. + +## Measured hashrate (emulator) +Measured on inspiron-3670 (6 cores, shared with ~7 agents), using the AVD `wikideck` (Android 15, x86_64 google_apis, KVM, `-cores 4`, 2 GB RAM): + +| Measurement | Result | +|---|---| +| Known vector (`--self-test`), x86_64 | passed, 1.45 s including the 256 MiB cache init | +| Known vector, arm64-v8a (through the emulator's ARM translation) | passed | +| Raw engine, 1 process, 2000 hashes | about 53 s → **~37 H/s per thread** | +| In the app, Max (4 threads) | **~125 H/s** shown in the panel, with 4 engine processes at ~260 MB RSS each | + +Light mode is about 10× slower per thread than desktop fast mode. At tonight's testnet target (`00002514…`, about 452 K expected hashes), 125 H/s means **one block per hour on average**, with high variance. On a real phone, expect roughly 20–60 H/s per big core (not measured tonight: no device). + +## Results tonight +Verified in the emulator with the debug APK (`~/worker/jobs/night/mobile-mining/apk/wikideck-mining-testnet-debug.apk` on inspiron): +- The APK contains `lib/{arm64-v8a,x86_64}/libwikideck_randomx.so`. The app runs the self-test before its first start ("known vector OK"), then mines on the testnet (:3101) with live hashrate and block height. +- **Every safeguard halts the engines** (the engine process count drops to 0, and the panel shows the reason): + - thermal: `cmd thermalservice override-status 3` → "Paused: the device is warm" + - battery saver (unplugged, `settings put global low_power 1`) → "Paused: battery saver is on" + - low battery (`dumpsys battery set level 15`, unplugged) → halted (Android's low-battery dialog paused the activity first) + - background (HOME) → "Paused: the app went to the background"; the web wallet locks too, so restarting needs an unlock + - Max intensity is refused while unplugged +- **Accepted block:** see the final report on #59. + +## Options for Eric +1. **Keep it sideload-only** (what exists now). Publish a signed release APK from a WikiDeck download page with clear battery and heat copy. This needs a release keystore (not in git) and an "unknown sources" install guide. F-Droid is a possible channel, but its anti-features policy would flag it, and its build server needs a reproducible NDK build. +2. **Store builds without mining.** Ship the store APK/AAB and the iOS app without the engine (a build flag that drops jniLibs and the panel), with the panel replaced by "Mine on desktop, or with the sideload app", plus a remote-management view of a desktop miner (allowed by Google's policy). +3. **Make mobile mining worthwhile.** Phones in light mode are roughly 10× slower per core than desktop fast mode. Options that need **consensus changes** (out of scope tonight): a lower-difficulty mobile lane, or pooled/shared mining where a phone's partial shares earn a card. +4. **Later engineering:** a JNI wrapper instead of exec (needed if a future Android blocks exec from `nativeLibraryDir`), an arm64 device test on real hardware, and battery-drain measurements. diff --git a/scripts/build-randomx-android.sh b/scripts/build-randomx-android.sh new file mode 100755 index 0000000..37cd70b --- /dev/null +++ b/scripts/build-randomx-android.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# Cross-compile the pinned native RandomX engine (native/, RandomX v1.2.1) for the Android app. +# Output: android/app/src/main/jniLibs//libwikideck_randomx.so, an executable named like a +# library so Android extracts it to nativeLibraryDir, where an app may exec it (docs/night2/MOBILE_MINING.md). +# +# Needs ANDROID_HOME with an NDK (ndk;) and CMake 3.24+ (cmake;, or cmake on PATH). +# ABIS="x86_64 arm64-v8a" JOBS=2 sh scripts/build-randomx-android.sh +set -eu +cd "$(dirname "$0")/.." +: "${ANDROID_HOME:?set ANDROID_HOME}" +ABIS="${ABIS:-arm64-v8a x86_64}" +JOBS="${JOBS:-2}" +API="${ANDROID_API:-24}" +NDK="${ANDROID_NDK_HOME:-$(ls -d "$ANDROID_HOME"/ndk/* 2>/dev/null | sort -V | tail -n1)}" +[ -f "$NDK/build/cmake/android.toolchain.cmake" ] || { echo "No NDK under $ANDROID_HOME/ndk" >&2; exit 1; } +CMAKE_DIR="$(ls -d "$ANDROID_HOME"/cmake/* 2>/dev/null | sort -V | tail -n1 || true)" +[ -n "$CMAKE_DIR" ] && PATH="$CMAKE_DIR/bin:$PATH" +command -v cmake >/dev/null || { echo "cmake not found" >&2; exit 1; } +GEN="" +command -v ninja >/dev/null && GEN="-G Ninja" + +for abi in $ABIS; do + build="native/build-android-$abi" + # shellcheck disable=SC2086 + cmake -S native -B "$build" $GEN \ + -DCMAKE_TOOLCHAIN_FILE="$NDK/build/cmake/android.toolchain.cmake" \ + -DANDROID_ABI="$abi" -DANDROID_PLATFORM="android-$API" \ + -DCMAKE_BUILD_TYPE=Release -DWIKIDECK_RANDOMX_TESTS=OFF + cmake --build "$build" --config Release --target wikideck-randomx --parallel "$JOBS" + out="android/app/src/main/jniLibs/$abi" + mkdir -p "$out" + cp "$build/wikideck-randomx" "$out/libwikideck_randomx.so" + "$NDK"/toolchains/llvm/prebuilt/*/bin/llvm-strip "$out/libwikideck_randomx.so" + ls -l "$out/libwikideck_randomx.so" +done diff --git a/src/App.tsx b/src/App.tsx index e302ace..cd6cc7a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -16,6 +16,7 @@ import { IS_MAINNET, NETWORK_GENESIS_TIME, NETWORK_LABEL } from '../shared/netwo import { StateClient } from '../shared/rpc-client.ts'; import { PlaySection } from './game/PlaySection.tsx'; import { isNativeApp } from './native.ts'; +import { MobileMiningPanel } from './MobileMiningPanel.tsx'; import { Landing } from './Landing.tsx'; import './App.css'; import './testnet.css'; @@ -190,7 +191,8 @@ export default function App() {
Confirmed ownership{wallet && snapshot ? owned.length : '—'}in your wallet
Proof of work{snapshot?.algorithm ?? 'RandomX'}native CPU mining
-