Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,29 @@ jobs:
- name: Build and test
run: cargo test -vv


android:
name: Android (${{ matrix.package }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
Comment thread
jaoleal marked this conversation as resolved.
matrix:
package:
- libbitcoinkernel-android-aarch64
- libbitcoinkernel-android-armv7
# Build-only: Rust 1.71 compiler_builtins lacks f128 routines
# required by bionic on x86_64. Tests are skipped until the
# MSRV is bumped or a workaround is found. See #198
- libbitcoinkernel-android-x86_64
steps:
- uses: actions/checkout@v4

- name: Install Nix
uses: cachix/install-nix-action@v31

- name: Build${{ matrix.package != 'libbitcoinkernel-android-x86_64' && ' and Test' || '' }}
run: nix build .#${{ matrix.package }} -L

fuzz-corpus:
name: Verify Fuzz Corpus
runs-on: ubuntu-latest
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/target
Cargo.lock
coverage_report
result
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]

### Added
- Added Nix package outputs for Android with bundled NDK r24, Rust toolchains, Boost, and cmake.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be r27? Judging by line 93 of flake.nix.

@jaoleal jaoleal Jun 13, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, i had the same doubt, If you check on flake.nix, youll see that we dont use ANDROID_API_LEVEL = "24"; directly in the build process itself but its still declared as a variable for one to alter if needed, it would reflect also altering

       // API level 24+ is required because Bitcoin Core uses getifaddrs
       // which was introduced in Android API 24 (Nougat).
       //
       // This can be overridden to a higher level by setting ANDROID_API_LEVEL.
       let api_level = match env::var("ANDROID_API_LEVEL") {
           Ok(level) => {
               let n: u32 = level.parse().expect("ANDROID_API_LEVEL must be a number");
               assert!(n >= 24, "ANDROID_API_LEVEL must be 24+");
               level
           }
           _ => "24".to_string(),
       };

It appears that the API version is not the same number as the RELEASE version, the ndkVersion = "27.2.12479018"; that we use to declare the components release.

Ill add a comment clarifying that to avoid future confusion

- Added `Block::check` to perform context-free validation of a block (size, weight, coinbase, transactions, sigops), with optional proof-of-work and merkle-root checks toggled via the `BLOCK_CHECK_BASE` / `_POW` / `_MERKLE` / `_ALL` flags. Returns a `BlockCheckResult` enum carrying the validation state on failure.
- Implemented `Debug` for `BlockValidationResult`, `BlockValidationStateRef`, `ProcessBlockHeaderresult` and `BlockCheckResult`, enabling inspection via `{:?}` in logs and test output.
- Added `#[must_use]` to `BlockCheckResult` and `ProcessBlockHeaderResult` to warn when validation results are silently ignored.
Expand Down Expand Up @@ -36,7 +37,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added `From<BlockHeader>` and `From<&BlockHeader>` for `[u8; 80]` to align with existing block conversions.

### Dependencies

- The sys crate no longer uses auto-generated bindings from bindgen. This removes some build-time dependencies for this crate.

## [0.2.0] 2026-01-26
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,23 @@ dependencies. Once setup, run:
cargo b
```

### Android Cross-Compilation
Comment thread
jaoleal marked this conversation as resolved.

Android cross-compilation requires [Nix](https://nixos.org/).

Nix handles the exact NDK version, Rust toolchains, Boost, and cmake
automatically, giving you a reproducible build environment with no manual setup.

```bash
nix build .#libbitcoinkernel-android-aarch64
nix build .#libbitcoinkernel-android-armv7
nix build .#libbitcoinkernel-android-x86_64 # build only; tests skipped (see flake.nix)
```

The resulting libraries and headers are placed in `result/lib/` and `result/include`.

Output targets Android API 24+ (Nougat) minimum.

## MSRV (Minimum Supported Rust Version)

The minimum supported Rust version is 1.71. Users on rustc older than
Expand Down
126 changes: 125 additions & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@
};

rustVersion = "1.71.0";
rustToolchainSha256 = "sha256-ks0nMEGGXKrHnfv4Fku+vhQ7gx76ruv6Ij4fKZR3l78=";
rustToolchain = fenix.packages.${system}.fromToolchainName {
name = rustVersion;
sha256 = "sha256-ks0nMEGGXKrHnfv4Fku+vhQ7gx76ruv6Ij4fKZR3l78=";
sha256 = rustToolchainSha256;
};
rustBuildToolchain = fenix.packages.${system}.combine [
rustToolchain.rustc
Expand Down Expand Up @@ -85,6 +86,129 @@
pkgs.gcc.cc.lib
];
};

packages =
# Android build infrastructure (unfree NDK + SDK).
let
ndkVersion = "27.2.12479018"; # which NDK release to download
lockfile = ./Cargo-minimal.lock;
Comment thread
jaoleal marked this conversation as resolved.
ANDROID_API_LEVEL = "24";
crateVersion =
(builtins.fromTOML (builtins.readFile ./libbitcoinkernel-sys/Cargo.toml)).package.version;

androidPkgs = import nixpkgs {
inherit system;
config.android_sdk.accept_license = true;
config.allowUnfree = true;
};
androidComposition = androidPkgs.androidenv.composeAndroidPackages {
# platformVersions is the SDK tooling version, not the minimum API level.
# The NDK target floor is set via ANDROID_API_LEVEL in build.rs (default 24).
platformVersions = [ "34" ];
ndkVersions = [ ndkVersion ];
includeNDK = true;
};
androidSdk = androidComposition.androidsdk;
androidNdk = "${androidSdk}/libexec/android-sdk/ndk/${ndkVersion}";

runTests = system == "x86_64-linux";

# x86_64-linux-android is excluded from tests: Rust 1.71's
# compiler_builtins lacks the f128 routines (__eqtf2, __multf3, …)
# that bionic's static libc.a requires on x86_64.
Comment thread
jaoleal marked this conversation as resolved.
#
# See #198
testableTargets = [
"aarch64-linux-android"
"armv7-linux-androideabi"
];

mkAndroidPackage =
rustTarget:
let
canTest = runTests && builtins.elem rustTarget testableTargets;
rustTargetToolchain = fenix.packages.${system}.combine [
rustToolchain.rustc
rustToolchain.cargo
rustToolchain.rust-src
rustToolchain.rust-std
(fenix.packages.${system}.targets.${rustTarget}.fromToolchainName {
name = rustVersion;
sha256 = rustToolchainSha256;
}).rust-std
];
rustPlatform = androidPkgs.makeRustPlatform {
cargo = rustTargetToolchain;
rustc = rustTargetToolchain;
};
qemuBin =
if builtins.match "aarch64.*" rustTarget != null then
"qemu-aarch64"
else if builtins.match "armv7.*" rustTarget != null then
"qemu-arm"
else
throw "Unsupported Android target: ${rustTarget}";
# NDK clang wrapper triple: armv7 uses "armv7a-linux-androideabi",
# all others match the Rust target triple.
ndkClangTriple =
if builtins.match "armv7.*" rustTarget != null then "armv7a-linux-androideabi" else rustTarget;
ndkLinker = "${androidNdk}/toolchains/llvm/prebuilt/linux-x86_64/bin/${ndkClangTriple}${ANDROID_API_LEVEL}-clang";
cargoTargetPrefix = "CARGO_TARGET_${
builtins.replaceStrings [ "-" ] [ "_" ] (pkgs.lib.toUpper rustTarget)
}";
cargoRunnerEnvVar = "${cargoTargetPrefix}_RUNNER";
cargoLinkerEnvVar = "${cargoTargetPrefix}_LINKER";
in
rustPlatform.buildRustPackage {
pname = "libbitcoinkernel-${rustTarget}";
version = crateVersion;
src = ./.;
cargoLock.lockFile = lockfile;
postPatch = ''
cp ${lockfile} Cargo.lock
'';
nativeBuildInputs = [
androidPkgs.cmake
androidPkgs.boost.dev
androidSdk
]
++ pkgs.lib.optionals canTest [
pkgs.qemu
];

ANDROID_HOME = "${androidSdk}/libexec/android-sdk";
ANDROID_NDK_HOME = androidNdk;
CMAKE_PREFIX_PATH = "${androidPkgs.boost.dev}";

# cargoBuildHook hardcodes the host --target at
# derivation time, so we bypass it for cross builds.
dontCargoBuild = true;
doCheck = canTest;
buildPhase = ''
cargo build -p libbitcoinkernel-sys --target ${rustTarget} --offline --release
'';
checkPhase = pkgs.lib.optionalString canTest ''
Comment thread
jaoleal marked this conversation as resolved.
export ${cargoLinkerEnvVar}=${ndkLinker}
export ${cargoRunnerEnvVar}=${pkgs.qemu}/bin/${qemuBin}
export QEMU_LD_PREFIX=${androidNdk}/toolchains/llvm/prebuilt/linux-x86_64/sysroot
export RUSTFLAGS="-C target-feature=+crt-static"
cargo test --target ${rustTarget} --offline --release --verbose
'';
installPhase = ''
mkdir -p $out/lib $out/include
find target/${rustTarget}/release -path "*/out/install/lib/*.a" \
-exec cp {} $out/lib/ \;
find target/${rustTarget}/release -path "*/out/install/include/*" \
-exec cp {} $out/include/ \;
'';
};
in
{
libbitcoinkernel-android-aarch64 = mkAndroidPackage "aarch64-linux-android";
libbitcoinkernel-android-armv7 = mkAndroidPackage "armv7-linux-androideabi";
libbitcoinkernel-android-x86_64 = mkAndroidPackage "x86_64-linux-android";
# i686 omitted: not a current target
};
}
);
}
2 changes: 2 additions & 0 deletions libbitcoinkernel-sys/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- Added build support for Android

### Added
- New `btck_TxValidationState` opaque type for holding transaction validation state
- New `btck_TxValidationResult` type with named constants for all transaction validation result variants
Expand Down
103 changes: 98 additions & 5 deletions libbitcoinkernel-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@ use std::path::Path;
use std::process::Command;

fn main() {
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let is_android = target_os == "android";

let ndk = if is_android {
Some(
env::var("ANDROID_NDK_HOME")
.expect("Android target detected but ANDROID_NDK_HOME is not set"),
)
} else {
None
};

let bitcoin_dir = Path::new("bitcoin");
let out_dir = env::var("OUT_DIR").unwrap();
let build_dir = Path::new(&out_dir).join("bitcoin");
Expand All @@ -15,7 +27,8 @@ fn main() {

let build_config = "RelWithDebInfo";

Command::new("cmake")
let mut cmake_configure = Command::new("cmake");
cmake_configure
.arg("-B")
.arg(&build_dir)
.arg("-S")
Expand All @@ -38,7 +51,46 @@ fn main() {
.arg("-DBUILD_SHARED_LIBS=OFF")
.arg("-DCMAKE_INSTALL_LIBDIR=lib")
.arg("-DENABLE_IPC=OFF")
.arg(format!("-DCMAKE_INSTALL_PREFIX={}", install_dir.display()))
.arg(format!("-DCMAKE_INSTALL_PREFIX={}", install_dir.display()));

if is_android {
let ndk = ndk.as_deref().unwrap();
let toolchain_file = format!("{ndk}/build/cmake/android.toolchain.cmake");

// Rust target triple -> NDK ABI name.
let abi = match env::var("TARGET").unwrap() {
t if t.contains("aarch64") => "arm64-v8a",
t if t.contains("armv7") => "armeabi-v7a",
t if t.contains("x86_64") => "x86_64",
target => panic!("Unsupported Android ABI: {target}"),
};

// API level 24+ is required because Bitcoin Core uses getifaddrs
// which was introduced in Android API 24 (Nougat).
//
// This can be overridden to a higher level by setting ANDROID_API_LEVEL.
let api_level = match env::var("ANDROID_API_LEVEL") {
Ok(level) => {
let n: u32 = level.parse().expect("ANDROID_API_LEVEL must be a number");
assert!(n >= 24, "ANDROID_API_LEVEL must be 24+");
level
}
_ => "24".to_string(),
};

cmake_configure
.arg(format!("-DCMAKE_TOOLCHAIN_FILE={toolchain_file}"))
.arg(format!("-DANDROID_ABI={abi}"))
.arg(format!("-DANDROID_PLATFORM=android-{api_level}"))
.arg("-DCMAKE_SYSTEM_NAME=Android")
.arg(format!("-DCMAKE_ANDROID_NDK={ndk}"))
// The Android NDK toolchain sets CMAKE_FIND_ROOT_PATH_MODE_PACKAGE
// to ONLY, which prevents cmake from finding host packages via
// CMAKE_PREFIX_PATH. Override it so Boost headers can be located.
.arg("-DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=BOTH");
}

cmake_configure
.status()
.expect("cmake should be installed and available in PATH");

Expand Down Expand Up @@ -70,19 +122,60 @@ fn main() {
} else {
install_dir.join("lib")
};

println!("cargo:rustc-link-search=native={}", lib_dir.display());

println!("cargo:rustc-link-lib=static=bitcoinkernel");

let compiler = cc::Build::new().get_compiler();
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();

if target_os == "windows" {
println!("cargo:rustc-link-lib=bcrypt");
println!("cargo:rustc-link-lib=shell32");
}
} else if is_android {
Comment thread
jaoleal marked this conversation as resolved.
// Without these, changing either variable between builds won't trigger a rebuild,
// so we could silently end up with a stale binary built against the wrong NDK or API level.
println!("cargo:rerun-if-env-changed=ANDROID_NDK_HOME");
println!("cargo:rerun-if-env-changed=ANDROID_API_LEVEL");
// Android NDK ships libc++_static.a and libc++abi.a in the
// per-architecture sysroot directory (not the API-level subdirectory).
let ndk = ndk.as_deref().unwrap();

if compiler.is_like_clang() {
// Rust target triple -> NDK sysroot lib directory triple.
// armv7 differs: Rust says `armv7-linux-androideabi`, NDK says `arm-linux-androideabi`.
let ndk_triple = env::var("TARGET")
.map(|target| {
if target.starts_with("armv7") {
"arm-linux-androideabi".into()
} else {
target
}
})
.unwrap();

let host_tag = match std::env::consts::OS {
"macos" => "darwin-x86_64",
"linux" => "linux-x86_64",
os => panic!("unsupported build host for Android cross-compilation: {os}"),
};

let ndk_lib_dir =
format!("{ndk}/toolchains/llvm/prebuilt/{host_tag}/sysroot/usr/lib/{ndk_triple}");
println!("cargo:rustc-link-search=native={ndk_lib_dir}");
println!("cargo:rustc-link-lib=static=c++_static");
println!("cargo:rustc-link-lib=static=c++abi");

// The pre-compiled libcompiler_builtins for armv7-linux-androideabi
// ships ARM EABI helper symbols tagged with @@LIBC_N (e.g.
// __aeabi_memcpy@@LIBC_N). When lld links a shared library or
// executable it errors because the LIBC_N version node is not
// defined in any version script. --exclude-libs,ALL marks every
// symbol pulled from static archives as local, which suppresses
// the version-node error.
if ndk_triple == "arm-linux-androideabi" {
println!("cargo:rustc-link-arg=-Wl,--exclude-libs,ALL");
}
} else if compiler.is_like_clang() {
if target_os == "macos" {
println!("cargo:rustc-link-lib=dylib=c++");
} else {
Expand Down
Loading