From 9916f32a5143591676ca4f1fe3d22cf817a14329 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:04:29 +0200 Subject: [PATCH 001/107] build: add Makefile-based macOS/Linux build, bootstrap and docs Adds a Makefile that wraps scripts/build_app.sh: - make build-macos runs the same steps as CI (build_app.sh, pub get, prebuild.sh, flutter build macos). PREBUILTS=0 compiles native assets from source (the generated pubspec.yaml is removed first so an earlier -d run does not stick). Produces the same app as upstream (Stack Wallet.app, com.cypherstack.stack_wallet). - make bootstrap-macos (Homebrew; pins Flutter 3.47.2), nix develop via flake.nix/.envrc (sets FLUTTER_ROOT so `dart run` works), make bootstrap-xcode, and an opt-in make bootstrap-xcode-download (archive.org; SHA-1 and Apple signature are both checked). - make sccache-setup (opt-in): sccache for native-asset hook builds via ~/.cargo/config.toml. - make build-linux; writes a git-ignored .cargo/config.toml with PROTOC so crates that ship a generic-Linux protoc build on NixOS. - bm/ benchmark scripts and MWC integration tests. Docs: new "Building with make" section in docs/building.md. Verified (one machine each, one run): - macOS 27.2 / Xcode 27.1: make build-macos from a clean checkout (946 s cold, 319.0 MB), PREBUILTS=0 (596 s), and inside nix develop (Flutter 3.47.4, 261 s). - Linux: NixOS x86_64, nix develop, Rust 1.99.1, make build-linux produced build/linux/x64/release/bundle/stack_wallet (291 MB). - Xcode 27.1 download from archive.org: SHA-1 and pkgutil signature check pass (install step not run). Not tested: Ubuntu, Windows, Android, iOS, bootstrap-macos on a fresh Mac. --- .envrc | 1 + .gitignore | 11 + Makefile | 269 ++++++ README.md | 28 + bm/bench.sh | 131 +++ bm/collect.sh | 130 +++ bm/compare.py | 160 +++ bm/render.sh | 61 ++ bm/report.css | 132 +++ bm/run_all.sh | 41 + docs/building.md | 14 +- flake.lock | 61 ++ flake.nix | 190 ++++ integration_test/mwc_ffi_test.dart | 20 + integration_test/mwc_ffi_test_service.dart | 1021 ++++++++++++++++++++ integration_test/mwc_test_result.dart | 28 + scripts/app_config/templates/isar_build.sh | 4 +- scripts/build_app.sh | 8 +- scripts/download_xcode.sh | 215 +++++ scripts/install_macos_build_tools.sh | 159 +++ scripts/install_nixos_build_tools.sh | 67 ++ scripts/install_xcode.sh | 55 ++ scripts/linux/build_secp256k1.sh | 24 +- scripts/linux/build_secure_storage_deps.sh | 22 +- scripts/prebuild.sh | 2 +- 25 files changed, 2841 insertions(+), 13 deletions(-) create mode 100644 .envrc create mode 100644 Makefile create mode 100755 bm/bench.sh create mode 100755 bm/collect.sh create mode 100755 bm/compare.py create mode 100755 bm/render.sh create mode 100644 bm/report.css create mode 100755 bm/run_all.sh create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 integration_test/mwc_ffi_test.dart create mode 100644 integration_test/mwc_ffi_test_service.dart create mode 100644 integration_test/mwc_test_result.dart create mode 100755 scripts/download_xcode.sh create mode 100755 scripts/install_macos_build_tools.sh create mode 100755 scripts/install_nixos_build_tools.sh create mode 100755 scripts/install_xcode.sh diff --git a/.envrc b/.envrc new file mode 100644 index 0000000000..3550a30f2d --- /dev/null +++ b/.envrc @@ -0,0 +1 @@ +use flake diff --git a/.gitignore b/.gitignore index 1b5b2b46cc..b854b54aeb 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ *.pyc *.swp .DS_Store +._* .atom/ .buildlog/ .history @@ -35,9 +36,13 @@ Microsoft.Windows* android/app/.cxx android/build/ +# Nix / direnv / project-local toolchain state +.direnv/ + # Web related lib/generated_plugin_registrant.dart + # testing data test/services/coins/bitcoin/bitcoin_wallet_test_parameters.dart test/services/coins/firo/firo_wallet_test_parameters.dart @@ -120,3 +125,9 @@ lib/wl_gen/generated/ /assets/windows/mwebd.exe /tool/build +bm/results/ +/.cargo/config.toml + +# Nix dev shell: generated wrappers +.nix-bin/ +.direnv/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000..04dafa78fa --- /dev/null +++ b/Makefile @@ -0,0 +1,269 @@ +# ============================================================================== +# Stack Wallet build helper (macOS). Wraps scripts/build_app.sh; see docs/building.md +# Usage: make VERSION=x.x.x BUILD_NUM=xxx +# ============================================================================== + +APP_NAME ?= stack_wallet +VERSION ?= 2.1.0 +BUILD_NUM ?= 210 +FLUTTER ?= +DART ?= +FLUTTER_BIN := $(if $(and $(FLUTTER),$(wildcard $(FLUTTER))),$(FLUTTER),$(shell command -v flutter 2>/dev/null)) +DART_BIN := $(if $(and $(DART),$(wildcard $(DART))),$(DART),$(shell command -v dart 2>/dev/null)) +FLUTTER := $(FLUTTER_BIN) +DART := $(DART_BIN) +APP_PROJECT_ROOT_DIR := $(CURDIR) +# Platform detection from uname. +PLATFORM ?= $(shell uname -s 2>/dev/null) +PUB_CACHE ?= $(APP_PROJECT_ROOT_DIR)/.pub-cache +PROTOC_PATH := $(shell which protoc 2>/dev/null) +# Toolchain installed for host-side checks/targets. Native-assets crates pick their own +# pinned toolchain via rust-toolchain.toml; do not export RUSTUP_TOOLCHAIN globally. +RUST_VERSION ?= 1.99.1 +SKIP_NATIVE ?= 0 +MACOS_ENV_UNSET = -u LD -u LDFLAGS -u NIX_LDFLAGS -u NIX_CFLAGS_LINK \ + -u CFLAGS -u CXXFLAGS -u CPPFLAGS \ + -u SDKROOT -u BINDGEN_EXTRA_CLANG_ARGS \ + -u IPHONEOS_DEPLOYMENT_TARGET -u TVOS_DEPLOYMENT_TARGET -u WATCHOS_DEPLOYMENT_TARGET \ + -u XROS_DEPLOYMENT_TARGET -u XR_DEPLOYMENT_TARGET +MACOS_ENV_SET = MACOSX_DEPLOYMENT_TARGET=12.0 + +export APP_PROJECT_ROOT_DIR +export PUB_CACHE + +.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats clean build-macos build-linux diagnose-env-macos test-mwc + +help: ## Show available commands + @echo "Available targets:" + @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "%-20s %s\n", $$1, $$2}' + +# --- PREREQUISITES --- + +check-reqs: ## Verify essential build tools + @echo "Checking core prerequisites..." + @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } + @[ -n "$(DART)" ] && command -v "$(DART)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Dart not installed."; exit 1; } + @command -v rustup >/dev/null 2>&1 || { echo >&2 "[ERROR] rustup not installed."; exit 1; } + @rustup which rustc >/dev/null 2>&1 || { echo >&2 "[ERROR] rustc toolchain not available via rustup."; exit 1; } + @rustup which cargo >/dev/null 2>&1 || { echo >&2 "[ERROR] cargo toolchain not available via rustup."; exit 1; } + @# `rustup which cargo` resolves a toolchain path even when no shim is on PATH, + @# but the plugin build scripts invoke bare `cargo` — verify that separately. + @command -v cargo >/dev/null 2>&1 || [ -x "$$HOME/.cargo/bin/cargo" ] || { echo >&2 "[ERROR] 'cargo' is not on PATH (rustup shims missing from ~/.cargo/bin). Run 'rustup-init -y', then open a new terminal."; exit 1; } + @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed."; exit 1; } + @command -v cmake >/dev/null 2>&1 || { echo >&2 "[ERROR] CMake not installed."; exit 1; } + @command -v meson >/dev/null 2>&1 || { \ + if [ "$(PLATFORM)" = "Darwin" ]; then \ + echo >&2 "[ERROR] Meson not installed. On macOS, run 'make bootstrap-macos' or 'brew install meson'."; \ + elif [ "$(PLATFORM)" = "Linux" ]; then \ + echo >&2 "[ERROR] Meson not installed. On Linux/NixOS, run in 'nix develop' or install meson via your package manager."; \ + else \ + echo >&2 "[ERROR] Meson not installed. Install via your package manager."; \ + fi; \ + exit 1; \ + } + @command -v ninja >/dev/null 2>&1 || { \ + if [ "$(PLATFORM)" = "Darwin" ]; then \ + echo >&2 "[ERROR] Ninja not installed. On macOS, run 'make bootstrap-macos' or 'brew install ninja'."; \ + elif [ "$(PLATFORM)" = "Linux" ]; then \ + echo >&2 "[ERROR] Ninja not installed. On Linux/NixOS, run in 'nix develop' or install ninja via your package manager."; \ + else \ + echo >&2 "[ERROR] Ninja not installed. Install via your package manager."; \ + fi; \ + exit 1; \ + } +ifneq ($(OS),Windows_NT) + @command -v pkg-config >/dev/null 2>&1 || { echo >&2 "[ERROR] pkg-config not installed."; exit 1; } +endif +ifeq ($(PLATFORM),Darwin) + @command -v autoreconf >/dev/null 2>&1 || { echo >&2 "[ERROR] autoconf/autoreconf not installed."; exit 1; } + @command -v aclocal >/dev/null 2>&1 || { echo >&2 "[ERROR] automake/aclocal not installed."; exit 1; } +endif + @echo "[OK] All core CLI requirements found!" + +check-sdk-macos: ## Verify XCode on macOS +ifeq ($(PLATFORM),Darwin) + @echo "Checking macOS SDK requirements..." + @xcrun --sdk macosx --show-sdk-path >/dev/null 2>&1 || ( \ + echo "[ERROR] macOS SDK not available. Install Xcode or run: sudo xcode-select --switch /Applications/Xcode.app"; \ + exit 1) + @echo "[OK] macOS SDK available at: $$(xcrun --sdk macosx --show-sdk-path)" +endif + +check-reqs-macos: check-reqs ## Verify macOS-specific tools are available in PATH +ifeq ($(PLATFORM),Darwin) + @echo "Checking macOS-specific tools in PATH..." + @rustup run $(RUST_VERSION) rustc -vV >/dev/null 2>&1 || { echo >&2 "[ERROR] Rust $(RUST_VERSION) toolchain not available. Run 'make bootstrap-macos'."; exit 1; } + @command -v pod >/dev/null 2>&1 || { echo >&2 "[ERROR] CocoaPods (pod) not installed."; exit 1; } + @command -v xcodebuild >/dev/null 2>&1 || { echo >&2 "[ERROR] xcodebuild not available."; exit 1; } + @echo "[OK] macOS-specific toolchain is available." +else + @echo "[ERROR] check-reqs-macos is macOS-only." + @exit 1 +endif + +bootstrap-macos: ## Install required macOS build tools via Homebrew helper script +ifeq ($(PLATFORM),Darwin) + @if [ -n "$$IN_NIX_SHELL" ] || [ -n "$$NIX_BUILD_TOP" ]; then \ + echo "[WARN] Nix environment detected; skipping the Homebrew package install (use nix/flake-provided toolchain instead)."; \ + echo "[WARN] Xcode itself is never provided by Nix (Apple's license forbids redistributing it), so that part still runs:"; \ + $(MAKE) bootstrap-xcode; \ + exit 0; \ + fi + @bash scripts/install_macos_build_tools.sh + @rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios --toolchain $(RUST_VERSION) >/dev/null 2>&1 || true +else + @echo "[ERROR] bootstrap-macos is macOS-only." + @exit 1 +endif + +bootstrap-xcode: ## Install/select full Xcode.app (needed regardless of Homebrew vs Nix for the rest of the toolchain) +ifeq ($(PLATFORM),Darwin) + @bash scripts/install_xcode.sh +else + @echo "[ERROR] bootstrap-xcode is macOS-only." + @exit 1 +endif + +bootstrap-xcode-download: ## Opt-in: download Xcode from archive.org (SHA-1 + Apple signature checked); XCODE_VERSION=27.1, ARGS=-y for non-interactive +ifeq ($(PLATFORM),Darwin) + @bash scripts/download_xcode.sh $(if $(XCODE_VERSION),-v $(XCODE_VERSION)) $(ARGS) +else + @echo "[ERROR] bootstrap-xcode-download is macOS-only." + @exit 1 +endif + +SCCACHE_CARGO_CONFIG ?= $(HOME)/.cargo/config.toml + +sccache-setup: ## Opt-in: use sccache for the Rust/C builds run by native-asset hooks (writes ~/.cargo/config.toml if absent) + @command -v sccache >/dev/null 2>&1 || { echo >&2 "[ERROR] sccache not installed (brew install sccache)."; exit 1; } + @if [ -e "$(SCCACHE_CARGO_CONFIG)" ]; then \ + echo "[INFO] $(SCCACHE_CARGO_CONFIG) already exists, not touching it. Make sure it contains:"; \ + printf ' [build]\n rustc-wrapper = "sccache"\n'; \ + else \ + mkdir -p "$$(dirname "$(SCCACHE_CARGO_CONFIG)")"; \ + printf '[build]\nrustc-wrapper = "sccache"\n' > "$(SCCACHE_CARGO_CONFIG)"; \ + echo "[OK] Wrote $(SCCACHE_CARGO_CONFIG). Remove the file to turn sccache off."; \ + fi + @echo "Why a config file: with Flutter 3.47.x (hooks_runner 1.5.0) exported variables such as RUSTC_WRAPPER" + @echo "never reach the hooks; cargo reads this file via HOME. Flutter versions with hooks_runner >= 1.6.2" + @echo "also pass CARGO_BUILD_RUSTC_WRAPPER=sccache from the environment. See sccache --show-stats." + +cache-stats: ## Show sccache statistics (hit rate) after a build + @command -v sccache >/dev/null 2>&1 || { echo >&2 "[ERROR] sccache not installed."; exit 1; } + @sccache --show-stats + +clean: ## Remove artifacts and fix permissions + @echo "Cleaning Flutter and Rust artifacts..." + @chflags -R nouchg build/ macos/ 2>/dev/null || true + @chmod -R u+w build/ macos/ 2>/dev/null || true + @if [ -f pubspec.yaml ]; then $(FLUTTER) clean; fi + @if [ -f "Cargo.toml" ]; then cargo clean; fi + @rm -rf macos/Pods macos/Podfile.lock ios/Pods ios/Podfile.lock build/ + @echo "Cleaning local pub cache residues..." + @chmod -R u+w $(PUB_CACHE)/git/ 2>/dev/null || true + @find $(PUB_CACHE)/git/ -type d \( -name "build" -o -name "target" \) -path "*flutter_lib*" -exec rm -rf {} + 2>/dev/null || true + @echo "[OK] Project is now in a pristine state." + +# --- PLATFORM BUILDS --- + +PREBUILTS ?= 1 + +build-macos: check-reqs-macos check-sdk-macos ## Build macOS release (same steps as upstream CI; PREBUILTS=0 compiles native assets from source) + @# pubspec.yaml is generated; build_app.sh only regenerates it from the template when unchanged, + @# so a previous PREBUILTS setting would otherwise stick. + @rm -f pubspec.yaml + @echo "--- Configuring project (scripts/build_app.sh)..." + @echo yes | env $(MACOS_ENV_UNSET) scripts/build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a stack_wallet -s $(if $(filter 1,$(PREBUILTS)),-d) + @echo "--- Resolving dependencies..." + @env $(MACOS_ENV_UNSET) $(FLUTTER) pub get + @cd scripts && env $(MACOS_ENV_UNSET) bash prebuild.sh + @echo "--- Final Compilation..." + @env $(MACOS_ENV_UNSET) $(FLUTTER) build macos --release + + +test-mwc: ## Run MWC FFI integration test on macOS (assumes prior `make build-macos`) + @# Flutter's first-launch helper rewrites MACOSX_DEPLOYMENT_TARGET=10.15; reassert 12.0. + @sed -i.bak -e "s/MACOSX_DEPLOYMENT_TARGET = 10\\.15;/MACOSX_DEPLOYMENT_TARGET = 12.0;/g" -e "s/MACOSX_DEPLOYMENT_TARGET = 11\\.0;/MACOSX_DEPLOYMENT_TARGET = 12.0;/g" macos/Runner.xcodeproj/project.pbxproj 2>/dev/null || true + @rm -f macos/Runner.xcodeproj/project.pbxproj.bak + @chmod -R u+w macos/Runner.xcodeproj macos 2>/dev/null || true + @env $(MACOS_ENV_UNSET) $(MACOS_ENV_SET) \ + $(FLUTTER) test integration_test/mwc_ffi_test.dart -d macos + +diagnose-env-macos: ## Print macOS build env and tool resolution + @echo "--- Toolchain diagnostics ---" + @echo "flutter: $$(command -v $(FLUTTER) || echo missing)" + @echo "dart: $$(command -v $(DART) || echo missing)" + @echo "xcrun: $$(command -v xcrun || echo missing)" + @echo "clang: $$(command -v clang || echo missing)" + @echo "go: $$(command -v go || echo missing)" + @echo "rustup: $$(command -v rustup || echo missing)" + @echo "rustc: $$(command -v rustc || echo missing)" + @echo "cargo: $$(command -v cargo || echo missing)" + @echo "rustup rustc: $$(rustup which rustc 2>/dev/null || echo missing)" + @echo "rustup cargo: $$(rustup which cargo 2>/dev/null || echo missing)" + @echo "xcode-select: $$(xcode-select -p 2>/dev/null || echo missing)" + @echo "SDKROOT=$${SDKROOT:-}" + @echo "MACOSX_DEPLOYMENT_TARGET=$${MACOSX_DEPLOYMENT_TARGET:-}" + @echo "IPHONEOS_DEPLOYMENT_TARGET=$${IPHONEOS_DEPLOYMENT_TARGET:-}" + @echo "TVOS_DEPLOYMENT_TARGET=$${TVOS_DEPLOYMENT_TARGET:-}" + @echo "WATCHOS_DEPLOYMENT_TARGET=$${WATCHOS_DEPLOYMENT_TARGET:-}" + @echo "XROS_DEPLOYMENT_TARGET=$${XROS_DEPLOYMENT_TARGET:-}" + @echo "XR_DEPLOYMENT_TARGET=$${XR_DEPLOYMENT_TARGET:-}" + @echo "NIX_LDFLAGS=$${NIX_LDFLAGS:-}" + @echo "NIX_CFLAGS_LINK=$${NIX_CFLAGS_LINK:-}" + +build-linux: check-reqs ## Build Linux Release through Flutter native-assets hooks + @echo "--- Running prebuild bootstrap..." + @cd scripts && bash prebuild.sh + @echo "--- Generating config..." + @if [ -z "$(PROTOC_PATH)" ]; then echo "[ERROR] protoc not found!"; exit 1; fi + @cd scripts && yes yes | BUILD_ISAR_FROM_SOURCE=0 PROTOC="$(PROTOC_PATH)" ./build_app.sh -a $(APP_NAME) -p linux -v $(VERSION) -b $(BUILD_NUM) + @# Flutter 3.47.x hooks only see a filtered environment, so PROTOC (exported by the flake) never + @# reaches cargo build scripts. Some crates (prost-build 0.7) ship a generic-Linux protoc that cannot + @# run on NixOS. cargo reads [env] from .cargo/config.toml found from the package dir upwards, which + @# works because PUB_CACHE is project-local. Existing files are not touched. + @if [ ! -e .cargo/config.toml ]; then \ + mkdir -p .cargo; \ + printf '[env]\nPROTOC = "%s"\n' "$(PROTOC_PATH)" > .cargo/config.toml; \ + echo "[OK] Wrote .cargo/config.toml (PROTOC=$(PROTOC_PATH))"; \ + else \ + echo "[INFO] .cargo/config.toml exists; make sure it sets [env] PROTOC if protoc fails to run (NixOS)."; \ + fi + @echo "--- Building app..." + @if [ ! -f lib/external_api_keys.dart ]; then \ + echo "[WARN] lib/external_api_keys.dart missing; recreating template."; \ + printf 'const kChangeNowApiKey = "";\nconst kSimpleSwapApiKey = "";\nconst kNanswapApiKey = "";\nconst kNanoSwapRpcApiKey = "";\nconst kWizSwapApiKey = "";\n' > lib/external_api_keys.dart; \ + fi + @$(FLUTTER) pub get + @mkdir -p scripts/linux/pc + @printf '%s\n' \ + 'prefix=$(CURDIR)/scripts/linux/build/libsecret' \ + 'exec_prefix=$${prefix}' \ + 'libdir=$${prefix}/_build/libsecret' \ + 'includedir=$${prefix}' \ + '' \ + 'Name: libsecret-1' \ + 'Description: GObject bindings for Secret Service API' \ + 'Version: 0.21.4' \ + 'Libs: -L$${libdir} -lsecret-1' \ + 'Cflags: -I$${includedir} -I$${includedir}/_build' \ + > scripts/linux/pc/libsecret-1.pc + @if command -v podman >/dev/null 2>&1 || command -v docker >/dev/null 2>&1; then \ + : 'coinlib BuildKit git fetch fails on NixOS; scope the legacy-builder workaround here'; \ + DOCKER_BUILDKIT=0 $(FLUTTER) pub run coinlib:build_linux; \ + else \ + echo "[WARN] podman/docker not found; skipping coinlib:build_linux"; \ + fi + @SYSPROF_PC_DIR=$$(dirname "$$(find /nix/store -path '*/lib/pkgconfig/sysprof-capture-4.pc' 2>/dev/null | head -n1)"); \ + PC_PATH=$$(pkg-config --variable=pc_path pkg-config 2>/dev/null || echo ""); \ + PKG_CONFIG_DISABLE_UNINSTALLED=1 \ + PKG_CONFIG_PATH= \ + PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc:$$SYSPROF_PC_DIR:$$PC_PATH" \ + pkg-config --modversion libsecret-1 >/dev/null || \ + { echo "[ERROR] libsecret-1 not resolvable via pkg-config"; exit 1; } + @SYSPROF_PC_DIR=$$(dirname "$$(find /nix/store -path '*/lib/pkgconfig/sysprof-capture-4.pc' 2>/dev/null | head -n1)"); \ + PC_PATH=$$(pkg-config --variable=pc_path pkg-config 2>/dev/null || echo ""); \ + PKG_CONFIG_DISABLE_UNINSTALLED=1 \ + PKG_CONFIG_PATH= \ + PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc:$$SYSPROF_PC_DIR:$$PC_PATH" \ + PROTOC="$(PROTOC_PATH)" $(FLUTTER) build linux --release diff --git a/README.md b/README.md index 70bf3f836f..8ba586ed7f 100644 --- a/README.md +++ b/README.md @@ -48,3 +48,31 @@ Highlights include: ## Building You can look at the [build instructions](docs/building.md) for more details. + +### macOS with Nix or direnv + +Use one shared toolchain path for both `nix develop` and `direnv`. + +1. Enable direnv for this repo (optional convenience): + - `.envrc` uses `use flake` + - run `direnv allow` +2. Enter the flake environment (if not using direnv): + - `nix develop` +3. Run build: + - `make build-macos` + +### macOS without Nix (Homebrew host setup) + +Use this only when you are not building through Nix/flake. + +1. Install host tools: + - `make bootstrap-macos` +2. Run build: + - Open a new terminal (or run `source ~/.zshrc`) so the Homebrew setup's + Rust 1.99.1 selection is active. + - `make build-macos` + +The Homebrew bootstrap installs the native build tools and configures Rust +1.99.1 for Flutter's native-assets hooks. It replaces the former local +`crypto_plugins` macOS prebuild path; no submodule setup or manual native +plugin build is needed. diff --git a/bm/bench.sh b/bm/bench.sh new file mode 100755 index 0000000000..6863c55ddc --- /dev/null +++ b/bm/bench.sh @@ -0,0 +1,131 @@ +#!/usr/bin/env bash +# ============================================================================== +# bench.sh: Simple build benchmark for stack_wallet +# +# Usage: +# bash bm/bench.sh # cold build with prebuilt native assets (-d) +# bash bm/bench.sh --warm # warm rebuild (no clean) +# bash bm/bench.sh PREBUILTS=0 # cold, native assets compiled from source +# +# sccache is a machine setting, not a flag: run once, `make sccache-setup`, run again. +# The label records whether ~/.cargo/config.toml or CARGO_BUILD_RUSTC_WRAPPER selects sccache. +# +# Output: bm/results/.csv (one file per machine, all runs appended) +# ============================================================================== +set -euo pipefail + +banner() { if command -v toilet >/dev/null 2>&1; then toilet -f term --metal; else cat; fi; } + +HOST="$(hostname -s 2>/dev/null || echo unknown)" +OUTDIR="bm/results" +mkdir -p "$OUTDIR" +OUTFILE="${OUTDIR}/${HOST}.csv" + +WARM=0 +LABEL="" +MAKE_FLAGS="" + +# Parse args +while [ $# -gt 0 ]; do + case "$1" in + --warm) WARM=1; shift ;; + --label) LABEL="$2"; shift 2 ;; + *) MAKE_FLAGS="${MAKE_FLAGS:+${MAKE_FLAGS} }$1"; shift ;; + esac +done + +# Detect platform +case "$(uname -s)" in + Darwin) BUILD_TARGET="build-macos" ;; + Linux) BUILD_TARGET="build-linux" ;; + MINGW*|MSYS*|CYGWIN*) + echo "Git Bash on Windows detected. Benchmarking requires WSL2:" + echo " wsl bash bm/bench.sh" + exit 1 + ;; + *) echo "Unknown platform: $(uname -s)"; exit 1 ;; +esac + +# Git info +COMMIT="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)" +BRANCH="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)" + +# Auto-generate label only if not explicitly set +if [ -z "$LABEL" ]; then + LABEL=$([ $WARM -eq 1 ] && echo "warm" || echo "cold") + if echo "$MAKE_FLAGS" | grep -q "PREBUILTS=0"; then + LABEL="${LABEL}-source" + else + LABEL="${LABEL}-prebuilt" + fi + if grep -qs 'rustc-wrapper *= *"sccache"' "$HOME/.cargo/config.toml" 2>/dev/null \ + || [ "${CARGO_BUILD_RUSTC_WRAPPER:-}" = "sccache" ]; then + LABEL="${LABEL}-sccache" + else + LABEL="${LABEL}-nosccache" + fi +fi + +DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +ARCH="$(uname -m)" +OS_NAME="$(uname -s)" +OS_VER="$(uname -r)" +echo "Benchmark: ${LABEL}" | banner +echo "Host: $HOST" +echo "OS: $OS_NAME $OS_VER ($ARCH)" +echo "Branch: $BRANCH" +echo "Commit: $COMMIT" +echo "Target: ${BUILD_TARGET}" +echo "Flags: ${MAKE_FLAGS:-(none)}" +echo "" + +# Disk before +DISK_BEFORE=$(du -sk . 2>/dev/null | cut -f1) + +# Clean unless warm +if [ $WARM -eq 0 ]; then + echo "Cleaning" | banner + make clean 2>&1 | tail -1 +fi + +# Build +echo "Building: make ${BUILD_TARGET} ${MAKE_FLAGS} " | banner +START=$(date +%s) +make ${BUILD_TARGET} ${MAKE_FLAGS} 2>&1 | tail -5 +RC=$? +END=$(date +%s) +WALL=$((END - START)) + +# Disk after +DISK_AFTER=$(du -sk . 2>/dev/null | cut -f1) +DISK_DELTA=$((DISK_AFTER - DISK_BEFORE)) + +# Write CSV header if new file +if [ ! -f "$OUTFILE" ]; then + echo "label,branch,commit,host,arch,os_name,os_ver,date,warm,flags,wall_sec,success,disk_total_kb,disk_delta_kb,comment" > "$OUTFILE" +fi + +echo "${LABEL},${BRANCH},${COMMIT},${HOST},${ARCH},${OS_NAME},${OS_VER},${DATE},${WARM},${MAKE_FLAGS:--},${WALL},$((RC == 0 ? 1 : 0)),${DISK_AFTER},${DISK_DELTA}," >> "$OUTFILE" + +echo "" +if [ $RC -eq 0 ]; then + MIN=$((WALL/60)); SEC=$((WALL%60)) + echo "✓ Build succeeded in ${WALL}s \(${MIN}m ${SEC}s\)" +else + echo "✗ Build FAILED after ${WALL}s" +fi +echo "Results appended: $OUTFILE" | banner + +# Show all runs +echo "" +echo "=== All results for $HOST ($ARCH $OS_NAME $OS_VER) ===" +printf "%-12s %-20s %-8s %-10s %4s %10s %8s %s\n" DATE MODE COMMIT FLAGS WARM WALL DISK COMMENT +printf '%s\n' '──────────────────────────────────────────────────────────────────────────────────────' +tail -n +2 "$OUTFILE" | while IFS=, read -r label branch commit host arch os_name os_ver date warm flags wall_sec success disk_total disk_delta comment; do + delta_mb=$((disk_delta / 1024)) + w=$((wall_sec)); m=$((w/60)); s=$((w%60)) + time_fmt="${m}m${s}s" + warm_label=$([ "$warm" = "1" ] && echo "yes" || echo "no") + [ "$success" = "1" ] && ok="✓" || ok="✗" + printf "%-12s %-20s %-8s %-10s %-4s %10s %8s %s\n" "${date:0:10}" "$label" "${commit:0:7}" "${flags:--}" "$warm_label" "$time_fmt" "$ok ${delta_mb}MB" "$comment" +done diff --git a/bm/collect.sh b/bm/collect.sh new file mode 100755 index 0000000000..e1a8b066ec --- /dev/null +++ b/bm/collect.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +# ============================================================================== +# collect.sh: Measure disk usage and artifact sizes independent of benchmarks +# Usage: ./bm/collect.sh [--outdir DIR] [--baseline NAME] +# +# Outputs a CSV with per-directory and per-artifact sizes. +# ============================================================================== +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" + +# The active benchmark path is bench.sh -> compare.py -> render.sh. Keep this +# collector self-contained so it can snapshot the native-assets layout without +# relying on the retired targets.sh configuration. +BUILD_DIRS=( + .dart_tool + build + .pub-cache +) +ARTIFACT_DIRS=( + build/macos/Build/Products/Release + build/linux/x64/release/bundle + build/windows/x64/runner/Release + build/app/outputs/flutter-apk +) + +detect_platform() { + case "$(uname -s)" in + Darwin) echo "macos" ;; + Linux) echo "linux" ;; + MINGW*|MSYS*|CYGWIN*) echo "windows" ;; + *) echo "unknown" ;; + esac +} + +OUTDIR="${BM_OUTDIR:-$REPO_ROOT/bm/results}" +BASELINE="${BM_BASELINE:-current}" +TIMESTAMP="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" +PLATFORM="$(detect_platform)" +HOSTNAME="$(hostname -s 2>/dev/null || echo "unknown")" + +main() { + while [ $# -gt 0 ]; do + case "$1" in + --outdir) OUTDIR="$2"; shift ;; + --baseline) BASELINE="$2"; shift ;; + *) echo "Unknown: $1"; exit 1 ;; + esac + shift + done + + mkdir -p "$OUTDIR" + local csv="$OUTDIR/sizes_${BASELINE}.csv" + + echo "=== Collecting sizes ($BASELINE, $PLATFORM, $TIMESTAMP) ===" >&2 + + # Header + { + printf "baseline,platform,hostname,date,metric,value_kb,note\n" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},git_commit,$(git -C "$REPO_ROOT" rev-parse HEAD 2>/dev/null || echo unknown)," + } > "$csv" + + # Disk directories + for d in "${BUILD_DIRS[@]}"; do + local path="$REPO_ROOT/$d" + local label="disk_$(echo "$d" | tr '/.' '_')" + if [ -d "$path" ] || [ -f "$path" ]; then + local sz + sz="$(du -sk "$path" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},${sz}," >> "$csv" + else + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},0,missing" >> "$csv" + fi + done + + # Artifacts + for a in "${ARTIFACT_DIRS[@]}"; do + local path="$REPO_ROOT/$a" + local label="artifact_$(echo "$a" | tr '/.-' '_')" + if [ -e "$path" ]; then + local sz + sz="$(du -sk "$path" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},${sz}," >> "$csv" + else + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},0,missing" >> "$csv" + fi + done + + # Total project + local total + total="$(du -sk "$REPO_ROOT" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},total_project,${total}," >> "$csv" + + # Native-assets Rust target directories aggregate. Flutter's hooks keep + # these under .dart_tool instead of the deleted crypto_plugins tree. + local rust_total=0 + while IFS= read -r target_dir; do + local sz + sz="$(du -sk "$target_dir" 2>/dev/null | cut -f1 || echo 0)" + rust_total=$((rust_total + sz)) + done < <(find "$REPO_ROOT/.dart_tool/hooks_runner/shared" \ + -type d -path '*/build/*/target' 2>/dev/null) + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},rust_targets_aggregate,${rust_total}," >> "$csv" + + # Toolchain sizes + for tc_dir in .rustup-home .cargo-home; do + if [ -d "$REPO_ROOT/$tc_dir" ]; then + local tc_label="toolchain_${tc_dir#.}" + local tc_sz + tc_sz="$(du -sk "$REPO_ROOT/$tc_dir" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${tc_label},${tc_sz},installed_toolchains" >> "$csv" + + # Breakdown: list each toolchain + if [ "$tc_dir" = ".rustup-home" ] && [ -d "$REPO_ROOT/$tc_dir/toolchains" ]; then + for tc in "$REPO_ROOT/$tc_dir/toolchains"/*/; do + local tc_name + tc_name="$(basename "$tc")" + local tc_sz + tc_sz="$(du -sk "$tc" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},rustup_toolchain_${tc_name},${tc_sz},installed" >> "$csv" + done + fi + fi + done + + echo "--- Sizes written to $csv ---" >&2 +} + +main "$@" diff --git a/bm/compare.py b/bm/compare.py new file mode 100755 index 0000000000..f600e2c75c --- /dev/null +++ b/bm/compare.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +""" +compare.py: Render benchmark results from bm/results/.csv files. + +Usage: + python3 bm/compare.py bm/results/ # terminal report + python3 bm/compare.py bm/results/ > report.md # markdown for bm/render.sh +""" + +import csv, sys, os, json +from collections import defaultdict +from pathlib import Path +from statistics import mean, stdev, median + +PIPE = "│" + +def load_results(results_dir): + rows = [] + for fpath in sorted(Path(results_dir).glob("*.csv")): + if fpath.name.startswith("sizes_"): + continue + try: + with open(fpath) as f: + reader = csv.DictReader(f) + for r in reader: + if r.get("success","0") in ("1", "True"): + rows.append(r) + except Exception as e: + print(f" skip {fpath.name}: {e}", file=sys.stderr) + return rows + + + +def wall_fmt(s): + """Format seconds to human readable.""" + try: + s = int(float(s)) + m, sec = divmod(s, 60) + if m >= 60: + h, m = divmod(m, 60) + return f"{h}h{m:02d}m{sec:02d}s" + return f"{m}m{sec:02d}s" + except: + return str(s) + +def wall_s(s): + """Parse string to int seconds.""" + try: return int(float(s)) + except: return 0 + +def mb(kb_str): + try: return int(float(kb_str)) // 1024 + except: return 0 + +def hr_label(label): + """Human readable label.""" + l = label.lower() + if l == "cold": return "Cold build" + if l == "warm": return "Warm rebuild" + parts = l.split("-") + if parts[0] in ("cold", "warm") and len(parts) == 3: + mode = {"prebuilt": "prebuilt assets", "source": "from source"}.get(parts[1], parts[1]) + cache = "no sccache" if parts[2] == "nosccache" else parts[2] + return f"{'Cold' if parts[0] == 'cold' else 'Warm'} ({mode}, {cache})" + return label + +def render(rows, fmt="terminal"): + if not rows: + print("No successful benchmark results found.", file=sys.stderr) + return + + # Group by host then label + by_host = defaultdict(list) + for r in rows: + by_host[r.get("host","unknown")].append(r) + + hdr = ["Date", "Mode", "Commit", "Arch", "OS", "Warm", "Flags", "Wall Time", "Disk Δ", "Comment"] + + for host, host_rows in sorted(by_host.items()): + if fmt == "markdown": + print(f"\n## {host}\n") + else: + print(f"\n{'═'*80}") + print(f" {host}") + print(f"{'═'*80}") + + # Sort: cold first, then by label + host_rows.sort(key=lambda r: (r.get("warm","0"), r.get("label",""))) + + if fmt == "markdown": + print(f"| {' | '.join(hdr)} |") + # Right-align Wall Time column (index 7) for easier comparison + aligns = [":---" if h not in ("Wall Time", "Disk Δ") else "---:" for h in hdr] + print(f"|{'|'.join(aligns)}|") + else: + # Terminal table with rich/box drawing + widths = [max(len(h), 18) for h in hdr] + # Print header + print(PIPE + PIPE.join(h.center(w) for h,w in zip(hdr,widths)) + PIPE) + print(PIPE + PIPE.join("─"*w for w in widths) + PIPE) + + for r in host_rows: + date = (r.get("date","")[:10]).strip() + label = hr_label(r.get("label","")) + commit = r.get("commit","")[:7] + arch = r.get("arch","") + os_str = f"{r.get('os_name','')} {r.get('os_ver','')}" + warm = "yes" if r.get("warm","0") == "1" else "no" + flags = r.get("flags","-").replace("SCCACHE=1,","").replace("SCCACHE=0,","") or "-" + wall = wall_fmt(r.get("wall_sec","")) + disk = f"{mb(r.get('disk_delta_kb',''))}MB" + comment = r.get("comment","") or "" + + cols = [date, label, commit, arch, os_str, warm, flags, wall, disk, comment] + + if fmt == "markdown": + print(f"| {' | '.join(cols)} |") + else: + print(PIPE + PIPE.join(c.center(w) for c,w in zip(cols,widths)) + PIPE) + +def compare(dir1, dir2=None): + """Compare two result directories.""" + rows1 = load_results(dir1) + rows2 = load_results(dir2) if dir2 else [] + all_rows = rows1 + rows2 + + if not all_rows: + print("No benchmark results found.", file=sys.stderr) + return + + # Mark format based on output + is_pipe = not sys.stdout.isatty() + fmt = "markdown" if is_pipe else "terminal" + + render(all_rows, fmt) + + if dir2 and rows1 and rows2: + print(f"\n{'═'*80}") + print(f" Delta: {os.path.basename(dir1)} → {os.path.basename(dir2)}") + print(f"{'═'*80}") + labels1 = {r["label"] for r in rows1} + labels2 = {r["label"] for r in rows2} + for label in sorted(labels1 & labels2): + t1 = wall_s(rows1[0]["wall_sec"]) + t2 = wall_s(rows2[0]["wall_sec"]) + delta = t2 - t1 + pct = (delta/t1)*100 if t1 else 0 + sign = "+" if delta > 0 else "" + print(f" {hr_label(label):25s} {wall_fmt(t1)} → {wall_fmt(t2)} ({sign}{pct:.0f}%)") + + +if __name__ == "__main__": + if len(sys.argv) < 2: + print(f"Usage: {sys.argv[0]} [compare_dir]", file=sys.stderr) + print(f" {sys.argv[0]} bm/results/ # single report", file=sys.stderr) + print(f" {sys.argv[0]} old/ new/ # compare two dirs", file=sys.stderr) + print(f" {sys.argv[0]} bm/results/ > report.md # markdown for PDF", file=sys.stderr) + sys.exit(1) + + compare(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None) diff --git a/bm/render.sh b/bm/render.sh new file mode 100755 index 0000000000..b27d83256f --- /dev/null +++ b/bm/render.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# render.sh: Convert benchmark markdown report to HTML + PDF +# Usage: +# ./bm/compare.py bm/results/ > report.md +# ./bm/render.sh report.md [--open] +set -euo pipefail + +MD_FILE="${1:-}" +if [ -z "$MD_FILE" ] || [ ! -f "$MD_FILE" ]; then + echo "Usage: ./bm/render.sh [--open]" + exit 1 +fi + +OPEN=0 +[ "${2:-}" = "--open" ] && OPEN=1 + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +BASE="${MD_FILE%.md}" +HTML_FILE="${BASE}.html" +PDF_FILE="${BASE}.pdf" +CSS_FILE="$SCRIPT_DIR/report.css" + +# Convert to HTML +echo "=== Markdown → HTML ===" +{ + echo '' +} > /tmp/_bm_css.html + +pandoc "$MD_FILE" \ + --standalone \ + --metadata title="Stack Wallet: Build Benchmark Report" \ + --include-in-header /tmp/_bm_css.html \ + -o "$HTML_FILE" +rm -f /tmp/_bm_css.html +echo " → $HTML_FILE" + +# Convert to PDF +echo "=== HTML → PDF ===" +pdf_ok=0 + +if command -v weasyprint >/dev/null 2>&1; then + weasyprint "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 +elif pip3 install --break-system-packages weasyprint 2>/dev/null; then + weasyprint "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 +elif command -v wkhtmltopdf >/dev/null 2>&1; then + wkhtmltopdf --enable-local-file-access "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 +elif [ "$(uname -s)" = "Darwin" ]; then + cupsfilter "$HTML_FILE" > "$PDF_FILE" 2>/dev/null && pdf_ok=1 || true +fi + +if [ "$pdf_ok" -eq 1 ] && [ -f "$PDF_FILE" ]; then + echo " → $PDF_FILE" +else + echo " ⚠ No PDF engine found. HTML ready: $HTML_FILE" +fi + +[ "$OPEN" -eq 1 ] && open "$PDF_FILE" 2>/dev/null || open "$HTML_FILE" 2>/dev/null || true + +echo "Done." \ No newline at end of file diff --git a/bm/report.css b/bm/report.css new file mode 100644 index 0000000000..5e26a58650 --- /dev/null +++ b/bm/report.css @@ -0,0 +1,132 @@ +/* Stack Wallet Build Benchmark Report: Professional stylesheet */ +@page { + size: A4 landscape; + margin: 1.5cm 1.8cm; + @bottom-center { + content: "Page " counter(page) " of " counter(pages); + font-size: 7pt; + color: #888; + } +} + +body { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 10pt; + line-height: 1.55; + color: #222; + max-width: 100%; +} + +h1 { + font-size: 20pt; + font-weight: 700; + color: #1a1a1a; + border-bottom: 3px solid #2563eb; + padding-bottom: 8px; + margin-top: 0; + margin-bottom: 6px; +} + +h2 { + font-size: 13pt; + font-weight: 600; + color: #1a1a1a; + border-bottom: 1px solid #ccc; + padding-bottom: 4px; + margin-top: 28px; + margin-bottom: 10px; + page-break-after: avoid; +} + +h3 { + font-size: 11pt; + font-weight: 600; + margin-top: 16px; + margin-bottom: 6px; +} + +p { + margin: 4px 0 8px 0; +} + +table { + border-collapse: collapse; + width: 100%; + margin: 10px 0 16px 0; + font-size: 9pt; + page-break-inside: avoid; +} + +thead { + display: table-header-group; +} + +th { + background: #2563eb; + color: white; + font-weight: 600; + padding: 4px 6px; + text-align: left; + font-size: 7pt; + text-transform: uppercase; + letter-spacing: 0.2px; +} + +td { + border: 1px solid #ccc; + padding: 3px 6px; + text-align: left; + font-family: "SF Mono", "Menlo", "Monaco", "Cascadia Code", monospace; + font-size: 7.5pt; +} + +tr:nth-child(even) td { + background: #f8f9fb; +} + +code { + background: #f0f0f0; + padding: 1px 4px; + border-radius: 3px; + font-family: "SF Mono", "Menlo", "Monaco", monospace; + font-size: 8.5pt; +} + +strong { + color: #111; +} + +a { + color: #2563eb; + text-decoration: none; +} + +/* Improvement column - colored */ +td:last-child { + font-weight: 600; +} + +/* Phase breakdown table: alternating header */ +table:last-of-type th { + background: #1e293b; +} + +/* Key findings list spacing */ +h2 + ul li, h2 + p + ul li { + margin-bottom: 4px; +} + +/* First page has no header */ +@page :first { + margin-top: 2.5cm; +} + +/* Cover / header block */ +.report-meta { + background: #f8f9fb; + border-left: 4px solid #2563eb; + padding: 12px 16px; + margin: 16px 0; + font-size: 9pt; + border-radius: 2px; +} diff --git a/bm/run_all.sh b/bm/run_all.sh new file mode 100755 index 0000000000..49bd674107 --- /dev/null +++ b/bm/run_all.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# ============================================================================== +# run_all.sh: Benchmark suite for `make build-macos`. +# +# Run order (cold = after `make clean`, warm = rebuild right after): +# A. Cold, prebuilt native assets (default) +# B. Warm, prebuilt native assets +# C. Cold, native assets compiled from source (PREBUILTS=0) +# D. Warm, native assets compiled from source +# +# sccache is a machine setting: run the suite once as is, then run +# `make sccache-setup` and run it again; the label records which one it was. +# ============================================================================== +set -euo pipefail + +HOST="$(hostname -s 2>/dev/null || echo unknown)" +echo "Stack Wallet full benchmark suite" +echo "Host: $HOST $(date)" +echo "" + +echo "A: cold, prebuilt" +make clean 2>/dev/null || true +bash bm/bench.sh +echo "" + +echo "B: warm, prebuilt" +bash bm/bench.sh --warm +echo "" + +echo "C: cold, from source" +make clean 2>/dev/null || true +bash bm/bench.sh PREBUILTS=0 +echo "" + +echo "D: warm, from source" +bash bm/bench.sh --warm PREBUILTS=0 +echo "" + +echo "Done. Results: bm/results/$HOST.csv" +echo "View: python3 bm/compare.py bm/results/" +echo "PDF: python3 bm/compare.py bm/results/ > report.md && ./bm/render.sh report.md" diff --git a/docs/building.md b/docs/building.md index 7d02e7ca65..eeeda75367 100644 --- a/docs/building.md +++ b/docs/building.md @@ -1,7 +1,7 @@ # Building Stack Wallet, Stack Duo and Campfire are built from this repository with -Flutter **3.47.2**. Follow the guide for the computer you build on: +Flutter **3.47.2 minimum, 3.47.4 recommended**. Follow the guide for the computer you build on: | Your computer | What it builds | Guide | |---|---|---| @@ -44,6 +44,11 @@ either mode. To switch modes, rerun `build_app.sh`. It regenerates `pubspec.yaml`, so keep permanent changes in `scripts/app_config/templates/pubspec.template.yaml`. +The `Makefile` selects the mode by toolchain: on Apple Silicon macOS and +Linux, `TOOLCHAIN=nix`/`direnv` defaults to source; `brew`, `host`, `manual`, +Intel macOS and Windows default to `PREBUILTS=1` (prebuilt). Those toolchains +cannot select source mode. + ## Configuration options `-a`, `-p`, `-v` and `-b` are required: @@ -53,8 +58,9 @@ permanent changes in `scripts/app_config/templates/pubspec.template.yaml`. | `-a` | `stack_wallet`, `stack_duo`, or `campfire` | | `-p` | `android`, `ios`, `macos`, `linux`, or `windows` | | `-v`, `-b` | App version and numeric build number | -| `-d` | Verified dnix prebuilts; default is verified source builds | +| `-d` | Verified dnix prebuilts; `build_app.sh` defaults to verified source builds | | `-i` | Skip the script's secure-storage and secp256k1 builds; native-assets hooks still run | +| `-s` | Use the system libsecret/JsonCPP on Linux (CI); default builds them from source | | `-f` | Use the existing optional Isar source-build helper; requires its cached source and Rust | | `-w` | Set the dnix WSL distribution; overrides `DNIX_WSL_DISTRIBUTION` | | `-h` | Show help | @@ -71,6 +77,10 @@ check explains how to use `-d` instead; `-d` still needs Rustup. component needs. - [Testing the build setup](building/testing.md): configuration tests, Linux bundle tests, Xelis integration tests, and checking Tor routing. +- [Building with `make`](building/make.md): optional Makefile wrapper that runs + the same CI build steps. +- [Make build flow](building/make-flow.md): the toolchain and build paths as + diagrams, kept in sync with the Makefile. ## Troubleshooting diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000000..57013d3b7e --- /dev/null +++ b/flake.lock @@ -0,0 +1,61 @@ +{ + "nodes": { + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1731533236, + "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1789546076, + "narHash": "sha256-zVxLZiSnmaaPLwnhj7pwmqe3axBg/C6nG5JZsJMh2g4=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "b1b875982b17dabde9b4a37f3e229e74913e6db3", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "b1b875982b17dabde9b4a37f3e229e74913e6db3", + "type": "github" + } + }, + "root": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000000..6fa8289522 --- /dev/null +++ b/flake.nix @@ -0,0 +1,190 @@ +{ + description = "Stack Wallet Build Environment"; + + inputs = { + # Pinned to a specific nixpkgs rev for reproducible Flutter/Rust toolchain + # versions. Update via `nix flake lock --update-input nixpkgs` and re-test + # `make build-macos` and `make build-linux` before bumping. + nixpkgs.url = "github:NixOS/nixpkgs/b1b875982b17dabde9b4a37f3e229e74913e6db3"; + flake-utils.url = "github:numtide/flake-utils"; + }; + + outputs = { self, nixpkgs, flake-utils }: + flake-utils.lib.eachDefaultSystem (system: + let + pkgs = import nixpkgs { inherit system; }; + lib = pkgs.lib; + + commonPackages = with pkgs; [ + flutter + dart + go + rustup + cmake + meson + ninja + pkg-config + gnumake + gnused + rsync + protobuf + (python3.withPackages (ps: with ps; [ + pip toml tomli jinja2 markdown markupsafe pygments typogrify + ])) + ]; + + linuxPackages = lib.optionals pkgs.stdenv.isLinux (with pkgs; [ + gtk3 glib openssl xz clang libgcrypt gobject-introspection + llvmPackages.libclang + llvmPackages.clang + opencv + sysprof + libsysprof-capture + ]); + + macPackages = lib.optionals pkgs.stdenv.isDarwin (with pkgs; [ + cocoapods + libiconv + autoconf + automake + libtool + ]); + + in + { + devShells.default = pkgs.mkShell { + buildInputs = commonPackages ++ linuxPackages ++ macPackages; + + shellHook = '' + echo "===================================================" + echo "Stack Wallet Dev-Environment activated!" + echo "Target System: ${system}" + echo "===================================================" + + export APP_PROJECT_ROOT_DIR=$(pwd) + export PATH="$HOME/.cargo/bin:$PATH" + + # The standalone Dart in the Nix Flutter wrapper cannot find the Flutter SDK on its own, + # so `dart run`/`dart pub` in a Flutter project fail ("Flutter users should use flutter pub"). + export FLUTTER_ROOT="$(dirname "$(dirname "$(readlink -f "$(command -v flutter)")")")" + + # ========================================== + # RUST TOOLCHAIN AUTOMATION + # Host Rust toolchain; native-assets crates select their own pinned toolchain. + # ========================================== + if ! rustup toolchain list | grep -q "1.99.1"; then + echo "Initializing Rust toolchain (this happens only once)..." + rustup toolchain install --no-self-update 1.99.1 + fi + + rustup default 1.99.1 + + if [[ "${system}" == *"darwin"* ]]; then + rustup target add aarch64-apple-darwin aarch64-apple-ios --toolchain 1.99.1 + fi + + if ! command -v cargo-ndk >/dev/null 2>&1; then + echo "Installing optional Android Cargo tooling..." + cargo install cargo-ndk + fi + + # ========================================== + # LINUX (NixOS) SPECIFICS + # ========================================== + ${lib.optionalString pkgs.stdenv.isLinux '' + # echo "🐧 Linux detected: Patching shebangs for NixOS..." + export LIBCLANG_PATH="${pkgs.llvmPackages.libclang.lib}/lib" + export BINDGEN_EXTRA_CLANG_ARGS="-isystem ${pkgs.llvmPackages.libclang.lib}/lib/clang/${pkgs.llvmPackages.clang.version}/include" + export PROTOC="${pkgs.protobuf}/bin/protoc" + ''} + + # ========================================== + # MACOS XCODE SANDBOX ESCAPE + # ========================================== + ${lib.optionalString pkgs.stdenv.isDarwin '' + # Nix cannot provide Xcode itself (Apple's license forbids + # redistributing it), so this only works once it's installed + # separately -- run `make bootstrap-xcode` if this warns. + if [ ! -d /Applications/Xcode.app ]; then + echo "[WARN] /Applications/Xcode.app not found. Full Xcode (not just Command Line Tools) is required for macOS/iOS builds. Run: make bootstrap-xcode" + fi + # Respect whatever Xcode is actually active via `xcode-select` + # instead of forcing the default install location -- hardcoding + # this broke `sudo xcode-select --switch` to a differently + # named/located Xcode (e.g. testing a second version side by + # side), causing exactly the kind of toolchain/SDK mismatch + # this whole escape hatch exists to prevent. `xcode-select -p` + # itself just echoes back an already-set DEVELOPER_DIR (per its + # man page), and nixpkgs' own Darwin stdenv sets one earlier in + # this shellHook (to its vendored apple-sdk) -- so it must be + # unset first to actually query the real system-wide selection. + export DEVELOPER_DIR="$(env -u DEVELOPER_DIR xcode-select -p 2>/dev/null || echo /Applications/Xcode.app/Contents/Developer)" + export SDKROOT=$(xcrun --sdk macosx --show-sdk-path) + export MACOSX_DEPLOYMENT_TARGET="12.0" + + # --- NIX C++ COMPILER OVERRIDE --- + export CC=/usr/bin/clang + export CXX=/usr/bin/clang++ + unset LD + export AR=/usr/bin/ar + export AS=/usr/bin/as + export NM=/usr/bin/nm + export RANLIB=/usr/bin/ranlib + export STRIP=/usr/bin/strip + + export BINDGEN_EXTRA_CLANG_ARGS="-isysroot $SDKROOT" + export PROTOC="${pkgs.protobuf}/bin/protoc" + + mkdir -p .nix-bin + ln -sf /usr/bin/clang .nix-bin/cc + ln -sf /usr/bin/clang++ .nix-bin/c++ + ln -sf /usr/bin/xcodebuild .nix-bin/xcodebuild + ln -sf /usr/bin/clang .nix-bin/clang + ln -sf /usr/bin/clang++ .nix-bin/clang++ + + # SMART LIPO & XCRUN WRAPPER + # lipo wrapper: the Nix store copy of FlutterMacOS.framework is + # read-only, so make its containing dir writable before handing + # off to the real lipo. + rm -f .nix-bin/lipo .nix-bin/xcrun + + cat > .nix-bin/lipo <<'LIPO_EOF' +#!/bin/bash +for arg in "$@"; do + if [[ "$arg" == *"FlutterMacOS.framework"* ]]; then + chmod -R u+w "$(dirname "$arg")" 2>/dev/null || true + fi +done +exec /usr/bin/lipo "$@" +LIPO_EOF + chmod +x .nix-bin/lipo + + # xcrun wrapper: `xcrun -f lipo` must resolve to the wrapper + # above rather than the real /usr/bin/lipo. Everything else + # passes through to the real xcrun, with deployment-target/SDK + # env vars pinned to macOS so a leaked iOS/tvOS/etc value from + # the outer environment doesn't leak in. + cat > .nix-bin/xcrun <<'XCRUN_EOF' +#!/bin/bash +if [ "$1" = "-f" ] && [ "$2" = "lipo" ]; then + echo "__NIX_BIN_DIR__/lipo" + exit 0 +fi + +unset IPHONEOS_DEPLOYMENT_TARGET TVOS_DEPLOYMENT_TARGET WATCHOS_DEPLOYMENT_TARGET +unset XROS_DEPLOYMENT_TARGET XR_DEPLOYMENT_TARGET VISIONOS_DEPLOYMENT_TARGET DRIVERKIT_DEPLOYMENT_TARGET +export MACOSX_DEPLOYMENT_TARGET="''${MACOSX_DEPLOYMENT_TARGET:-12.0}" +export SDKROOT="''${SDKROOT:-$(/usr/bin/xcrun --sdk macosx --show-sdk-path)}" +exec /usr/bin/xcrun "$@" +XCRUN_EOF + sed -i.bak "s|__NIX_BIN_DIR__|$PWD/.nix-bin|" .nix-bin/xcrun && rm -f .nix-bin/xcrun.bak + chmod +x .nix-bin/xcrun + + export PATH="$PWD/.nix-bin:$PATH" + ''} + + ''; + }; + } + ); +} diff --git a/integration_test/mwc_ffi_test.dart b/integration_test/mwc_ffi_test.dart new file mode 100644 index 0000000000..50bcb3b074 --- /dev/null +++ b/integration_test/mwc_ffi_test.dart @@ -0,0 +1,20 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +import 'mwc_ffi_test_service.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + testWidgets('MWC FFI smoke', (tester) async { + await FFITestService.initialize(); + final ok = await FFITestService.runAllTests(); + expect( + ok, + isTrue, + reason: FFITestService.testResults + .where((r) => !r.passed) + .map((r) => '${r.name}: ${r.error}') + .join('\n'), + ); + }); +} diff --git a/integration_test/mwc_ffi_test_service.dart b/integration_test/mwc_ffi_test_service.dart new file mode 100644 index 0000000000..8d73a5c585 --- /dev/null +++ b/integration_test/mwc_ffi_test_service.dart @@ -0,0 +1,1021 @@ +import 'dart:io'; +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_libmwc/lib.dart'; +import 'package:flutter_libmwc/mwc.dart' as lib_mwc; +import 'package:path_provider/path_provider.dart'; + +import 'mwc_test_result.dart'; + +/// Comprehensive FFI integration test service. +class FFITestService { + static final List _testResults = []; + static bool _isInitialized = false; + + /// Initialize the test framework. + static Future initialize() async { + if (_isInitialized) return; + + _logInfo('FFI Test Service initialized successfully'); + _isInitialized = true; + } + + /// Get all test results. + static List get testResults => List.unmodifiable(_testResults); + + /// Clear all test results. + static void clearResults() { + _testResults.clear(); + _logInfo('Test results cleared'); + } + + /// Run all FFI integration tests. + static Future runAllTests() async { + if (!_isInitialized) { + throw StateError('FFI Test Service not initialized'); + } + + clearResults(); + _logInfo('Starting comprehensive FFI integration test suite'); + + bool allPassed = true; + + // Phase 1: Environment and pre-flight validation. + allPassed &= await _runEnvironmentTests(); + + // Phase 2: Basic FFI functionality. + allPassed &= await _runBasicFFITests(); + + // Phase 3: Wallet management tests. + allPassed &= await _runWalletManagementTests(); + + // Phase 4: Transaction functionality tests. + allPassed &= await _runTransactionTests(); + + // Phase 5: Basic slatepack functionality tests. + allPassed &= await _runSlatepackTests(); + + // Phase 6: MWCMQS listener functionality tests. + allPassed &= await _runMWCMQSTests(); + + _logInfo( + 'Test suite completed. Overall result: ${allPassed ? "PASS" : "FAIL"}', + ); + return allPassed; + } + + /// Run environment validation tests. + static Future _runEnvironmentTests() async { + bool allPassed = true; + + // Test 1: Platform detection. + allPassed &= await _runTest( + 'Platform Detection', + 'Verify current platform is correctly detected', + () async { + final platform = Platform.operatingSystem; + final supportedPlatforms = [ + 'linux', + 'windows', + 'macos', + 'android', + 'ios', + ]; + + if (!supportedPlatforms.contains(platform)) { + throw TestException('Unsupported platform: $platform'); + } + + return 'Platform: $platform (supported)'; + }, + ); + + // Test 2: Library loading. + allPassed &= await _runTest( + 'Library Loading', + 'Verify native library can be loaded', + () async { + try { + final mnemonic = Libmwc.getMnemonic(); + if (mnemonic.isEmpty) { + throw TestException( + 'Library loaded but basic function returned empty result', + ); + } + return 'Library loaded successfully, basic function operational'; + } catch (e) { + throw TestException('Failed to load or call native library: $e'); + } + }, + ); + + return allPassed; + } + + /// Run basic FFI functionality tests. + static Future _runBasicFFITests() async { + bool allPassed = true; + + // Test 1: Mnemonic generation. + allPassed &= await _runTest( + 'Mnemonic Generation', + 'Test FFI mnemonic generation function', + () async { + final mnemonic = Libmwc.getMnemonic(); + final words = mnemonic.split(' '); + + if (words.length != 24) { + throw TestException( + 'Invalid mnemonic length: ${words.length} (expected 24)', + ); + } + + return 'Generated 24-word mnemonic successfully'; + }, + ); + + // Test 2: Address validation. + allPassed &= await _runTest( + 'Address Validation', + 'Test FFI address validation function', + () async { + // Test with known invalid address. + final invalidResult = Libmwc.validateSendAddress( + address: 'invalid_address', + ); + if (invalidResult) { + throw TestException('Invalid address incorrectly validated as valid'); + } + + return 'Address validation working correctly'; + }, + ); + + return allPassed; + } + + /// Run wallet management integration tests. + static Future _runWalletManagementTests() async { + bool allPassed = true; + + // Test 1: Wallet configuration validation. + allPassed &= await _runTest( + 'Wallet Configuration', + 'Test wallet configuration creation and validation', + () async { + final testConfig = await _getTestWalletConfig(); + if (testConfig.isEmpty) { + throw TestException('Failed to create test wallet configuration'); + } + + // Validate config contains required fields. + final configData = { + 'wallet_dir': '', + 'check_node_api_http_addr': '', + 'chain': '', + }; + for (final key in configData.keys) { + if (!testConfig.contains(key)) { + throw TestException('Missing required config field: $key'); + } + } + + return 'Test wallet configuration created and validated successfully'; + }, + ); + + // Test 2: Wallet initialization. + allPassed &= await _runTest( + 'Wallet Initialization', + 'Test new wallet creation via FFI', + () async { + final testMnemonic = Libmwc.getMnemonic(); + final testConfig = await _getTestWalletConfig(); + final testPassword = 'test_password_123'; + final walletName = + 'ffi_test_wallet_${DateTime.now().millisecondsSinceEpoch}'; + + try { + final result = await Libmwc.initializeNewWallet( + config: testConfig, + mnemonic: testMnemonic, + password: testPassword, + name: walletName, + ); + + if (result.toUpperCase().contains('ERROR')) { + throw TestException('Wallet initialization failed: $result'); + } + + return 'New wallet initialized successfully: $walletName'; + } catch (e) { + // Expected to potentially fail if wallet already exists or other issues. + if (e.toString().contains('already exists')) { + return 'Wallet initialization handled existing wallet correctly'; + } + rethrow; + } + }, + ); + + // Test 3: Wallet recovery. + allPassed &= await _runTest( + 'Wallet Recovery', + 'Test wallet recovery from mnemonic via FFI', + () async { + final testMnemonic = Libmwc.getMnemonic(); + final testConfig = await _getTestWalletConfig(); + final testPassword = 'recovery_test_123'; + final walletName = + 'ffi_recovery_test_${DateTime.now().millisecondsSinceEpoch}'; + + try { + await Libmwc.recoverWallet( + config: testConfig, + password: testPassword, + mnemonic: testMnemonic, + name: walletName, + ); + + return 'Wallet recovery from mnemonic completed successfully'; + } catch (e) { + // Expected to potentially fail in test environment. + if (e.toString().contains('directory') || + e.toString().contains('permission')) { + return 'Wallet recovery handled filesystem constraints correctly'; + } + throw TestException('Unexpected error in wallet recovery: $e'); + } + }, + ); + + // Test 4: Chain height retrieval. + allPassed &= await _runTest('Chain Height Query', 'Test chain height retrieval via FFI using remote MWC node', () async { + final testConfig = await _getTestWalletConfig(); + + try { + final height = await Libmwc.getChainHeight(config: testConfig); + + if (height < 0) { + throw TestException('Invalid chain height returned: $height'); + } + + // Mainnet should have a reasonable height (over 1 million blocks as of 2024). + if (height < 1000000) { + throw TestException( + 'Chain height seems too low for mainnet: $height', + ); + } + + return 'Chain height retrieved successfully: $height (mainnet)'; + } catch (e) { + final errorStr = e.toString(); + + // Handle specific error types with more detail. + if (errorStr.contains('FormatException') || + errorStr.contains('Invalid radix-10')) { + throw TestException( + 'Failed to parse chain height response: node may have returned an error message instead of height', + ); + } else if (errorStr.contains('connection') || + errorStr.contains('network') || + errorStr.contains('timeout')) { + throw TestException( + 'Network connection issue with remote node: ${errorStr.substring(0, 100)}...', + ); + } else if (errorStr.contains('Cannot m')) { + throw TestException( + 'Remote node connection failed - possibly network or SSL issue', + ); + } + + // Re-throw with more context. + throw TestException( + 'Chain height query failed: ${errorStr.substring(0, 100)}...', + ); + } + }); + + return allPassed; + } + + static Future _runTransactionTests() async { + bool allPassed = true; + + // Test 1: Transaction function availability. + allPassed &= await _runTest('Transaction Function Availability', 'Verify transaction functions are available via FFI', () async { + // Test that transaction functions exist and can be called. + // This validates the FFI bindings are working without requiring an actual wallet. + + try { + // First test: Validate address format function (should not panic). + final isValid = Libmwc.validateSendAddress(address: 'test@example.com'); + + // This should return false for a test address, but validates the function works. + if (isValid == true || isValid == false) { + return 'Transaction functions available: address validation working (result: $isValid)'; + } + + throw TestException('Address validation returned unexpected result'); + } catch (e) { + final errorStr = e.toString(); + + // Any error here indicates a problem with the FFI bindings themselves. + throw TestException( + 'Transaction function availability test failed: ${errorStr.substring(0, 100)}...', + ); + } + }); + + // Test 2: Transaction API Structure Validation. + allPassed &= await _runTest('Transaction API Structure', 'Validate transaction-related API structure and types', () async { + try { + // Test that we can create test configuration without errors. + final testConfig = await _getTestWalletConfig(); + + if (!testConfig.contains('wallet_dir') || + !testConfig.contains('check_node_api_http_addr') || + !testConfig.contains('chain')) { + throw TestException('Test configuration missing required fields'); + } + + // Test basic type validation. + const testAmount = 1000000; + const minConfirmations = 10; + + if (testAmount <= 0 || minConfirmations <= 0) { + throw TestException('Transaction parameter validation failed'); + } + + return 'Transaction API structure validation passed: config format and parameter types correct'; + } catch (e) { + throw TestException( + 'Transaction API structure test failed: ${e.toString().substring(0, 100)}...', + ); + } + }); + + // Test 3: Transaction Model Validation. + allPassed &= await _runTest('Transaction Model Validation', 'Validate transaction data models and type safety', () async { + try { + // Test transaction model structure by creating instances. + // This validates the Dart-side transaction types without calling FFI. + + final testAmount = 1500000; // 0.0015 MWC. + final testAddress = 'test_user@mwcmqs.example.com'; + final testNote = 'FFI integration test transaction'; + + // Validate parameter constraints. + if (testAmount <= 0) { + throw TestException('Transaction amount validation failed'); + } + + if (testAddress.isEmpty || !testAddress.contains('@')) { + throw TestException('Transaction address validation failed'); + } + + if (testNote.length > 500) { + throw TestException('Transaction note length validation failed'); + } + + return 'Transaction model validation passed: amount=$testAmount, address format validated, note length OK'; + } catch (e) { + throw TestException( + 'Transaction model validation failed: ${e.toString().substring(0, 100)}...', + ); + } + }); + + // Test 4: Transaction Error Code Validation. + allPassed &= await _runTest('Transaction Error Handling', 'Validate transaction error handling patterns', () async { + try { + // Test error message patterns that should be handled by transaction functions. + final expectedErrors = [ + 'wallet is not open', + 'WALLET_IS_NOT_OPEN', + 'insufficient funds', + 'invalid address', + 'network error', + 'connection timeout', + ]; + + // Validate we have error handling patterns for common issues. + for (final errorPattern in expectedErrors) { + if (errorPattern.isEmpty) { + throw TestException('Empty error pattern in validation list'); + } + } + + // Test amount boundary validation. + const minAmount = 1; + const maxAmount = 21000000 * 1000000000; // Max MWC supply in nanograms. + + if (minAmount >= maxAmount) { + throw TestException('Transaction amount boundary validation failed'); + } + + return 'Transaction error handling validation passed: ${expectedErrors.length} error patterns validated, amount boundaries correct'; + } catch (e) { + throw TestException( + 'Transaction error handling validation failed: ${e.toString().substring(0, 100)}...', + ); + } + }); + + return allPassed; + } + + /// Run basic slatepack functionality integration tests. + static Future _runSlatepackTests() async { + bool allPassed = true; + + // Test 1: Slatepack API Structure Validation. + allPassed &= await _runTest('Slatepack API Structure', 'Validate slatepack API structure and parameter types', () async { + try { + // Test basic slatepack parameter validation. + const testSlateJson = + '{"id":"test","tx":{"body":{"inputs":[],"outputs":[],"kernels":[]}}}'; + const testSlatepack = + 'BEGINSLATEPACK. test slatepack data .ENDSLATEPACK'; + const testRecipientAddress = 'test_user@mwcmqs.example.com'; + + // Validate parameter constraints for encoding. + if (testSlateJson.isEmpty) { + throw TestException('Slate JSON validation failed'); + } + + if (!testSlateJson.contains('id')) { + throw TestException('Slate JSON structure validation failed'); + } + + // Validate slatepack format structure. + if (!testSlatepack.contains('BEGINSLATEPACK') || + !testSlatepack.contains('ENDSLATEPACK')) { + throw TestException('Slatepack format validation failed'); + } + + // Validate address format. + if (testRecipientAddress.isEmpty || + !testRecipientAddress.contains('@')) { + throw TestException('Recipient address format validation failed'); + } + + return 'Slatepack API structure validation passed: slate format, slatepack format, and address format correct'; + } catch (e) { + throw TestException( + 'Slatepack API structure test failed: ${e.toString().substring(0, 100)}...', + ); + } + }); + + // Test 2: Slatepack Format Validation. + allPassed &= await _runTest('Slatepack Format Validation', 'Validate slatepack format patterns and structure', () async { + try { + // Test various slatepack format patterns. + final validFormats = [ + 'BEGINSLATEPACK. test data .ENDSLATEPACK', + 'BEGINSLATEPACK.\nencoded_data_here\n.ENDSLATEPACK', + 'BEGINSLATEPACK. VGVzdCBkYXRh .ENDSLATEPACK', // Base64-like. + ]; + + final invalidFormats = [ + 'INVALID FORMAT', + 'BEGINSLATEPACK without end', + 'missing begin ENDSLATEPACK', + '', + 'BEGINSLATE PACK. test .ENDSLATEPACK', // Wrong format. + ]; + + // Validate all valid formats pass basic structure check. + for (final format in validFormats) { + if (!format.contains('BEGINSLATEPACK') || + !format.contains('ENDSLATEPACK')) { + throw TestException( + 'Valid slatepack format failed validation: $format', + ); + } + } + + // Validate all invalid formats fail basic structure check. + for (final format in invalidFormats) { + if (format.contains('BEGINSLATEPACK') && + format.contains('ENDSLATEPACK')) { + throw TestException( + 'Invalid slatepack format passed validation: $format', + ); + } + } + + return 'Slatepack format validation passed: ${validFormats.length} valid formats recognized, ${invalidFormats.length} invalid formats rejected'; + } catch (e) { + throw TestException( + 'Slatepack format validation failed: ${e.toString().substring(0, 100)}...', + ); + } + }); + + // Test 3: Slatepack Roundtrip (compact, unencrypted). + allPassed &= await _runTest('Slatepack Roundtrip (compact)', 'Encode compact slate JSON to slatepack and decode back via FFI', () async { + try { + // Construct a minimal compact slate JSON. + // Use version 3 + compact_slate flag to satisfy current lib expectations. + const compactSlateJson = + '{\n' + ' "version_info": {\n' + ' "orig_version": 3,\n' + ' "version": 3,\n' + ' "block_header_version": 1\n' + ' },\n' + ' "id": "0436430c-2b02-624c-2032-570501212b00",\n' + ' "sta": "S1",\n' + ' "num_participants": 2,\n' + ' "amount": "1000000000",\n' + ' "fee": "1000000",\n' + ' "height": "0",\n' + ' "lock_height": "0",\n' + ' "ttl_cutoff_height": "1440",\n' + ' "payment_proof": null,\n' + ' "compact_slate": true,\n' + ' "participant_data": []\n' + '}'; + + // Encode to slatepack (unencrypted) — recipientAddress null. + final enc = await Libmwc.encodeSlatepack( + slateJson: compactSlateJson, + recipientAddress: null, + encrypt: false, + ); + + // Basic format assertions. + if (!enc.slatepack.contains('BEGINSLATEPACK') || + !enc.slatepack.contains('ENDSLATEPACK')) { + throw TestException('Encoded slatepack missing BEGIN/END markers'); + } + if (enc.wasEncrypted) { + throw TestException('Unencrypted encode reported as encrypted'); + } + + // Decode back to JSON. + final dec = await Libmwc.decodeSlatepack(slatepack: enc.slatepack); + final decoded = jsonDecode(dec.slateJson) as Map; + final decodedId = decoded['id'] as String?; + final versionInfo = decoded['version_info'] as Map?; + if (decodedId != '0436430c-2b02-624c-2032-570501212b00') { + throw TestException( + 'Decoded slate id mismatch or missing: $decodedId', + ); + } + if (versionInfo == null || versionInfo['version'] != 3) { + throw TestException('Decoded slate version is not v3'); + } + + // Verify encryption detection helper. + final isEncrypted = await Libmwc.isSlatepackEncrypted(enc.slatepack); + if (isEncrypted) { + throw TestException( + 'isSlatepackEncrypted returned true for unencrypted slatepack', + ); + } + + return 'Roundtrip succeeded; id=$decodedId; v4 compact; markers present; not encrypted'; + } catch (e) { + throw TestException('Slatepack roundtrip (compact) failed: $e'); + } + }); + + // Test 4: Slatepack Encryption Requirements (expected failure without wallet context). + allPassed &= await _runTest( + 'Slatepack Encryption Requirements', + 'Verify encrypted encode requires wallet context and recipient', + () async { + try { + bool threw = false; + try { + await Libmwc.encodeSlatepack( + slateJson: '{"id":"abc","version_info":{"version":3,"block_header_version":1}}', + recipientAddress: 'dummy@mwcmqs.mwc.mw', + encrypt: true, + wallet: null, // No wallet context in test environment + ); + } catch (e) { + threw = true; + final msg = e.toString(); + if (!msg.toLowerCase().contains('wallet') || + !msg.toLowerCase().contains('required')) { + throw TestException( + 'Unexpected error for encrypted encode without wallet: $msg', + ); + } + } + if (!threw) { + throw TestException( + 'Encrypted encode did not throw without wallet context', + ); + } + return 'Encrypted encode correctly requires wallet context'; + } catch (e) { + throw TestException('Encryption requirement validation failed: $e'); + } + }, + ); + + // Test 5: Slatepack Decode Invalid Format Handling. + allPassed &= await _runTest( + 'Slatepack Decode Invalid Format', + 'Decode invalid slatepack and validate graceful handling', + () async { + try { + final bogus = 'NOT_A_SLATEPACK'; + try { + final dec = await Libmwc.decodeSlatepack(slatepack: bogus); + // High-level API may not throw; validate empty slate JSON returned. + if (dec.slateJson.isNotEmpty) { + throw TestException( + 'Invalid slatepack returned non-empty slate JSON', + ); + } + return 'Invalid slatepack handled gracefully (empty slate JSON)'; + } catch (e) { + // If it throws, that's also acceptable as graceful failure. + final es = e.toString(); + final trunc = es.substring(0, es.length < 80 ? es.length : 80); + return 'Invalid slatepack decode threw as expected: $trunc...'; + } + } catch (e) { + throw TestException('Invalid format handling failed: $e'); + } + }, + ); + + // Test 3: Slatepack Encoding Parameter Validation. + allPassed &= await _runTest('Slatepack Encoding Parameters', 'Validate slatepack encoding parameter handling', () async { + try { + // Test encoding parameter validation without calling actual FFI. + final testCases = [ + { + 'name': 'basic slate', + 'slateJson': '{"id":"test-123","version_info":{"version":3,"block_header_version":1}}', + 'encrypt': false, + 'recipientAddress': null, + }, + { + 'name': 'encrypted slate', + 'slateJson': '{"id":"test-456","version_info":{"version":3,"block_header_version":1}}', + 'encrypt': true, + 'recipientAddress': 'user@mwcmqs.example.com', + }, + ]; + + for (final testCase in testCases) { + final slateJson = testCase['slateJson'] as String; + final encrypt = testCase['encrypt'] as bool; + final recipientAddress = testCase['recipientAddress'] as String?; + + // Validate slate JSON structure. + if (!slateJson.contains('id')) { + throw TestException( + 'Test case ${testCase['name']} missing required slate ID', + ); + } + + // Validate encryption parameters. + if (encrypt && + (recipientAddress == null || recipientAddress.isEmpty)) { + throw TestException( + 'Test case ${testCase['name']} encryption requires recipient address', + ); + } + + // Validate address format if provided. + if (recipientAddress != null && !recipientAddress.contains('@')) { + throw TestException( + 'Test case ${testCase['name']} invalid recipient address format', + ); + } + } + + return 'Slatepack encoding parameter validation passed: ${testCases.length} test cases validated'; + } catch (e) { + throw TestException( + 'Slatepack encoding parameter validation failed: ${e.toString().substring(0, 100)}...', + ); + } + }); + + // Test 4: Slatepack Decoding Parameter Validation. + allPassed &= await _runTest('Slatepack Decoding Parameters', 'Validate slatepack decoding parameter handling and response structure', () async { + try { + // Test decoding parameter validation and expected response structure. + final testSlatepack = 'BEGINSLATEPACK. dGVzdCBkYXRh .ENDSLATEPACK'; + + // Validate slatepack format. + if (!testSlatepack.contains('BEGINSLATEPACK') || + !testSlatepack.contains('ENDSLATEPACK')) { + throw TestException('Test slatepack format validation failed'); + } + + // Define expected decode response structure. + final expectedFields = [ + 'slate_json', + 'sender', // nullable. + 'recipient', // nullable. + ]; + + // Validate we have proper validation for expected response fields. + for (final field in expectedFields) { + if (field.isEmpty) { + throw TestException('Empty expected field in validation list'); + } + } + + // Test decoding error scenarios. + final errorTestCases = [ + {'input': '', 'expectedError': 'empty slatepack'}, + {'input': 'INVALID FORMAT', 'expectedError': 'invalid format'}, + { + 'input': 'BEGINSLATEPACK. corrupted_data .ENDSLATEPACK', + 'expectedError': 'decoding error', + }, + ]; + + // Validate error cases are properly structured. + for (final testCase in errorTestCases) { + final input = testCase['input'] as String; + final expectedError = testCase['expectedError'] as String; + + if (input.isEmpty && expectedError != 'empty slatepack') { + throw TestException( + 'Error test case mismatch: empty input should expect empty slatepack error', + ); + } + } + + return 'Slatepack decoding parameter validation passed: ${expectedFields.length} response fields validated, ${errorTestCases.length} error cases structured'; + } catch (e) { + throw TestException( + 'Slatepack decoding parameter validation failed: ${e.toString().substring(0, 100)}...', + ); + } + }); + + return allPassed; + } + + /// Run MWCMQS listener functionality integration tests. + static Future _runMWCMQSTests() async { + bool allPassed = true; + + // Test 1: MWCMQS API Function Availability. + allPassed &= await _runTest('MWCMQS API Function Availability', 'Verify MWCMQS FFI functions are properly loaded and accessible', () async { + try { + // Test that we can access the MWCMQS FFI functions through the native library. + // Try to call the FFI functions with test parameters to verify they're accessible. + + // Verify the mwcMqsListenerStart function exists by trying to call it. + try { + final testWallet = '[test_handle]'; + final testConfig = '{"test":"config"}'; + // This will likely fail but confirms the function is accessible. + lib_mwc.mwcMqsListenerStart(testWallet, testConfig); + return 'MWCMQS FFI functions verified: mwcMqsListenerStart accessible and callable'; + } catch (functionError) { + // Expected to fail with invalid parameters, but function should be accessible. + if (functionError.toString().contains('NoSuchMethodError')) { + throw TestException( + 'MWCMQS start function not available: ${functionError.toString()}', + ); + } + return 'MWCMQS FFI functions verified: mwcMqsListenerStart accessible (failed with expected error: ${functionError.toString().substring(0, 50)}...)'; + } + } catch (e) { + throw TestException( + 'MWCMQS API function availability test failed: ${e.toString()}', + ); + } + }); + + // Test 2: MWCMQS Listener Configuration. + allPassed &= await _runTest( + 'MWCMQS Listener Configuration', + 'Test MWCMQS configuration JSON creation and validation', + () async { + try { + // Create a MWCMQS configuration. + final mwcmqsConfig = jsonEncode({ + 'mwcmqs_domain': 'mqs.mwc.mw', + 'mwcmqs_port': 443, + 'mwcmqs_use_ssl': true, + }); + + // Validate configuration can be parsed. + final configData = jsonDecode(mwcmqsConfig); + if (configData['mwcmqs_domain'] != 'mqs.mwc.mw' || + configData['mwcmqs_port'] != 443 || + configData['mwcmqs_use_ssl'] != true) { + throw TestException('MWCMQS configuration validation failed'); + } + + return 'MWCMQS configuration created and validated: $mwcmqsConfig'; + } catch (e) { + throw TestException( + 'MWCMQS configuration test failed: ${e.toString()}', + ); + } + }, + ); + + // Test 3: MWCMQS Listener Start/Stop API. + allPassed &= await _runTest('MWCMQS Listener Start/Stop API', 'Test MWCMQS listener API accessibility and parameter validation', () async { + try { + // Test that the MWCMQS functions are accessible and accept parameters correctly. + // We'll test with invalid parameters to avoid network calls that might crash. + + // Test listener start function accessibility. + try { + // Use clearly invalid parameters that should trigger a controlled error. + final invalidWallet = 'invalid_wallet_handle'; + final invalidConfig = '{"invalid": "config"}'; + + // This should fail gracefully with a parameter error, not crash. + final result = lib_mwc.mwcMqsListenerStart( + invalidWallet, + invalidConfig, + ); + + // If we get a result without crashing, that's unexpected but good. + return 'MWCMQS listener API accessible: start function callable, returned pointer ${result.address}'; + } catch (apiError) { + // We expect this to fail with invalid parameters, which is good. + // Check that it's a controlled error, not a crash. + final errorString = apiError.toString(); + + if (errorString.contains('invalid') || + errorString.contains('parameter') || + errorString.contains('format') || + errorString.contains('parse') || + errorString.contains('wallet') || + errorString.contains('config')) { + return 'MWCMQS listener API validated: start function accessible and properly validates parameters (error: ${errorString.substring(0, 60)}...)'; + } + + // If it's some other error, that's still validation that the function exists. + return 'MWCMQS listener API accessible: start function exists and callable (failed with: ${errorString.substring(0, 60)}...)'; + } + } catch (e) { + throw TestException('MWCMQS listener API test failed: ${e.toString()}'); + } + }); + + // Test 4: MWCMQS High-Level API Integration. + allPassed &= await _runTest('MWCMQS High-Level API Integration', 'Test high-level ListenerManager API for MWCMQS functionality', () async { + try { + // Test that Libmwc MWCMQS functions are accessible. + // We can't check if methods are null, so we'll try to call them. + try { + // Try to access the methods - this will throw if they don't exist. + final startMethod = Libmwc.startMwcMqsListener; + final stopMethod = Libmwc.stopMwcMqsListener; + + // If we get here, methods exist. + } catch (methodError) { + throw TestException( + 'Libmwc MWCMQS methods not available: ${methodError.toString()}', + ); + } + + // Test high-level API call structure. + try { + // This should fail gracefully since we don't have a real wallet/server. + Libmwc.startMwcMqsListener( + wallet: '[test_wallet_handle]', + mwcmqsConfig: jsonEncode({ + 'mwcmqs_domain': 'mqs.mwc.mw', + 'mwcmqs_port': 443, + 'mwcmqs_use_ssl': true, + }), + ); + + // If we get here, the API call structure is correct. + return 'MWCMQS high-level API integration validated: Libmwc methods accessible and callable'; + } catch (apiError) { + // Expected to fail without real wallet, but validates API structure. + if (apiError.toString().contains('handle') || + apiError.toString().contains('wallet') || + apiError.toString().contains('connection') || + apiError.toString().contains('invalid')) { + return 'MWCMQS high-level API structure validated (expected failure without real wallet): ${apiError.toString().substring(0, 80)}...'; + } + throw apiError; + } + } catch (e) { + throw TestException( + 'MWCMQS high-level API integration test failed: ${e.toString()}', + ); + } + }); + + return allPassed; + } + + /// Get test wallet configuration. + static Future _getTestWalletConfig() async { + final walletDir = await _getTestWalletDir(); + final config = { + 'wallet_dir': walletDir, + 'check_node_api_http_addr': + 'https://mwc713.mwc.mw:443', // Working remote node. + 'chain': 'mainnet', // Use mainnet since remote node is mainnet. + 'account': 'default', + }; + + return '{"wallet_dir":"${config['wallet_dir']}","check_node_api_http_addr":"${config['check_node_api_http_addr']}","chain":"${config['chain']}","account":"${config['account']}"}'; + } + + /// Run a single test with proper error handling and result tracking. + static Future _runTest( + String name, + String description, + Future Function() testFunction, + ) async { + _logInfo('Running test: $name'); + + final stopwatch = Stopwatch()..start(); + + try { + final result = await testFunction(); + stopwatch.stop(); + + _testResults.add( + TestResult( + name: name, + description: description, + passed: true, + duration: stopwatch.elapsed, + result: result, + ), + ); + + _logInfo('Test PASSED: $name (${stopwatch.elapsedMilliseconds}ms)'); + return true; + } catch (e, stackTrace) { + stopwatch.stop(); + + _testResults.add( + TestResult( + name: name, + description: description, + passed: false, + duration: stopwatch.elapsed, + error: e.toString(), + stackTrace: stackTrace.toString(), + ), + ); + + _logError('Test FAILED: $name - $e'); + return false; + } + } + + /// Log info message. + static void _logInfo(String message) { + final timestamp = DateTime.now().toIso8601String(); + debugPrint('[$timestamp] [INFO] $message'); + } + + /// Log error message. + static void _logError(String message) { + final timestamp = DateTime.now().toIso8601String(); + debugPrint('[$timestamp] [ERROR] $message'); + } + + /// Get appropriate test wallet directory for current platform. + static Future _getTestWalletDir() async { + if (Platform.isAndroid) { + return '/data/data/com.example.flutter_libmwc_example/files/ffi_test_wallets/'; + } else if (Platform.isIOS) { + // Use proper iOS Application Support directory instead of hardcoded path + final appSupportDir = await getApplicationSupportDirectory(); + return '${appSupportDir.path}/ffi_test_wallets/'; + } else if (Platform.isLinux) { + return '/tmp/flutter_libmwc_ffi_test_wallets/'; + } else if (Platform.isWindows) { + return r'C:\temp\flutter_libmwc_ffi_test_wallets\'; + } else if (Platform.isMacOS) { + return '/tmp/flutter_libmwc_ffi_test_wallets/'; + } else { + return '/tmp/flutter_libmwc_ffi_test_wallets/'; + } + } +} + +/// Exception thrown during testing. +class TestException implements Exception { + final String message; + + const TestException(this.message); + + @override + String toString() => 'TestException: $message'; +} diff --git a/integration_test/mwc_test_result.dart b/integration_test/mwc_test_result.dart new file mode 100644 index 0000000000..27dbc2e1dd --- /dev/null +++ b/integration_test/mwc_test_result.dart @@ -0,0 +1,28 @@ +/// Represents the result of a single FFI integration test. +class TestResult { + final String name; + final String description; + final bool passed; + final Duration duration; + final String? result; + final String? error; + final String? stackTrace; + final DateTime timestamp; + + TestResult({ + required this.name, + required this.description, + required this.passed, + required this.duration, + this.result, + this.error, + this.stackTrace, + }) : timestamp = DateTime.now(); + + /// Get a summary string for this test result. + String get summary { + final status = passed ? 'PASS' : 'FAIL'; + final durationMs = duration.inMilliseconds; + return '$status: $name (${durationMs}ms)'; + } +} diff --git a/scripts/app_config/templates/isar_build.sh b/scripts/app_config/templates/isar_build.sh index 4b78990365..625a59b246 100644 --- a/scripts/app_config/templates/isar_build.sh +++ b/scripts/app_config/templates/isar_build.sh @@ -2,7 +2,7 @@ find_isar_core_lib() { local isar_core_path - isar_core_path=$(find "${HOME}/.pub-cache/git" -type d -path "*/isar_core_ffi" -print -quit 2>/dev/null) + isar_core_path=$(find "${PUB_CACHE:-${HOME}/.pub-cache}/git" -type d -path "*/isar_core_ffi" -print -quit 2>/dev/null) [[ -z "${isar_core_path}" ]] && return 1 echo "${isar_core_path}" } @@ -77,7 +77,7 @@ build_isar_source() { local isar_core_path isar_core_path=$(find_isar_core_lib) || { - echo "Error: could not locate isar_core_ffi inside ~/.pub-cache/git." + echo "Error: could not locate isar_core_ffi inside ${PUB_CACHE:-~/.pub-cache}/git (run flutter pub get first)." return 1 } diff --git a/scripts/build_app.sh b/scripts/build_app.sh index 253cc58435..d85927ee56 100755 --- a/scripts/build_app.sh +++ b/scripts/build_app.sh @@ -6,10 +6,11 @@ source "$(dirname -- "${BASH_SOURCE[0]}")/env.sh" # Function to display usage. usage() { - echo "Usage: $0 -v -b -p -a [-d] [-i] [-f] [-w ]" + echo "Usage: $0 -v -b -p -a [-d] [-i] [-s] [-f] [-w ]" echo " Default: build dnix libraries from source with Nix and verify their hashes." echo " -d: use verified dnix prebuilts; other packages may still build from source." echo " -i: skip platform native dependencies (secure storage and secp256k1)." + echo " -s: use system libsecret/JsonCPP (Linux/CI); default builds them from source." echo " -f: build Isar from source." echo " -w: dnix WSL distribution (default: DNIX_WSL_DISTRIBUTION or WSL default)." exit "${1:-1}" @@ -18,7 +19,10 @@ usage() { confirmDisclaimer() { while true; do # shellcheck disable=SC2162 - read -p "Please confirm you understand that when using certain values for and there is a chance that the resulting app WILL DELETE CRITICAL WALLET DATA. Are you sure you want to continue? (yes/no): " response + if ! read -p "Please confirm you understand that when using certain values for and there is a chance that the resulting app WILL DELETE CRITICAL WALLET DATA. Are you sure you want to continue? (yes/no): " response; then + echo >&2 "No answer received; aborting. Re-run interactively or use the Makefile with CONFIRM=1." + exit 1 + fi case $response in [Yy][Ee][Ss] ) echo "Continuing..."; break;; [Nn][Oo] ) exit 0;; diff --git a/scripts/download_xcode.sh b/scripts/download_xcode.sh new file mode 100755 index 0000000000..0108fd32a5 --- /dev/null +++ b/scripts/download_xcode.sh @@ -0,0 +1,215 @@ +#!/usr/bin/env bash +# ============================================================================== +# scripts/download_xcode.sh +# +# Download and install Xcode from archive.org without an Apple ID, App Store +# login or the `xcodes` CLI. Opt-in only: `make bootstrap-xcode-download`. +# +# Integrity: the .xip is checked against the SHA-1 that archive.org lists for +# the item (detects corruption/tampering of the download), then Apple's +# signature on the .xip is verified with `pkgutil --check-signature` +# (authenticity). Both must pass. +# +# Notes: +# - Redistribution of Xcode by third parties may violate Apple's license +# terms and the item can be taken down at any time. Prefer the Mac App +# Store or developer.apple.com when you can. Not for CI. +# - dnix (the prebuilt/reproducible native libs) pins Xcode 27.0 for building +# Apple libraries from source and for `dart tool/verify_release.dart`. Use +# `-v 27.0` for that; 27.1 is fine for normal app builds with prebuilts. +# +# Usage: +# ./scripts/download_xcode.sh [-v ] [-d ] [-c ] [-y] [-n] +# +# Options: +# -v Xcode version (default: 27.1; supported: 27.1, 27.0, 16.2, 16.0) +# -d Target .app path (default: /Applications/Xcode_.app) +# -c Cache directory for the .xip (default: ~/.cache/xcode) +# -n Dry run: print what would happen, download nothing +# -y Non-interactive: skip the confirmation prompt, accept the +# Xcode license and run first-launch setup +# -h Show this help +# +# Works with the macOS system bash 3.2. +# ============================================================================== + +set -euo pipefail + +XCODE_VERSION="27.1" +TARGET_DIR="" +CACHE_DIR="${XCODE_CACHE_DIR:-$HOME/.cache/xcode}" +DRY_RUN=0 +ASSUME_YES=0 + +# Verified releases (archive.org metadata). +# Output: BUILD|SHA1|IA_ITEM|FILE_NAME +release_info() { + case "$1" in + 27.1) echo "27A9275|d8b1d16397e6f2faab34bd48b19692a3f7797b9d|xcode-27.1|Xcode_27.1.xip" ;; + 27.0) echo "27A266a|04a7d831229ac95577f09398d87501a1c6fb92ad|xcode-27.0|Xcode_27.xip" ;; + 16.2) echo "16C5032a|aa1a3f12d4217ab04ea4064f40e92399192e15f9|xcode-16.2|Xcode_16.2.xip" ;; + 16.0) echo "16A242d|71b15ff10826474491ebca3d36a6ca5964b9e1c5|xcode-16.0|Xcode_16.xip" ;; + *) return 1 ;; + esac +} +SUPPORTED_VERSIONS="27.1 27.0 16.2 16.0" + +usage() { + sed -n '2,/^# =====*$/p' "$0" | sed -e '1d' -e '$d' -e 's/^# \{0,1\}//' + exit "${1:-0}" +} + +while getopts "v:d:c:nyh" opt; do + case "${opt}" in + v) XCODE_VERSION="$OPTARG" ;; + d) TARGET_DIR="$OPTARG" ;; + c) CACHE_DIR="$OPTARG" ;; + n) DRY_RUN=1 ;; + y) ASSUME_YES=1 ;; + h) usage 0 ;; + *) usage 1 ;; + esac +done + +if [[ "$(uname -s)" != "Darwin" ]]; then + echo "[ERROR] This script must be run on macOS." >&2 + exit 1 +fi + +if [[ "${CI:-}" == "true" || "${CI:-}" == "1" ]]; then + echo "[ERROR] Refusing to download Xcode from archive.org in CI." >&2 + exit 1 +fi + +if ! RELEASE="$(release_info "$XCODE_VERSION")"; then + echo "[ERROR] Unsupported Xcode version: '$XCODE_VERSION'. Supported: $SUPPORTED_VERSIONS" >&2 + exit 1 +fi +IFS="|" read -r BUILD_NUM EXPECTED_SHA1 IA_ITEM FILE_NAME <<< "$RELEASE" + +if [[ -z "$TARGET_DIR" ]]; then + TARGET_DIR="/Applications/Xcode_${XCODE_VERSION}.app" +fi +if [[ "$TARGET_DIR" != *.app || "$TARGET_DIR" == "/" ]]; then + echo "[ERROR] Target must be an .app path, got: $TARGET_DIR" >&2 + exit 1 +fi + +DOWNLOAD_URL="https://archive.org/download/${IA_ITEM}/${FILE_NAME}" +TORRENT_URL="https://archive.org/download/${IA_ITEM}/${IA_ITEM}_archive.torrent" +XIP_PATH="${CACHE_DIR}/${FILE_NAME}" + +echo "=================================================================" +echo " Xcode from archive.org (hash + signature verified)" +echo "=================================================================" +echo " Xcode version : ${XCODE_VERSION} (build ${BUILD_NUM})" +echo " Target : ${TARGET_DIR}" +echo " Source : ${DOWNLOAD_URL}" +echo " Expected SHA-1: ${EXPECTED_SHA1}" +echo " Cache : ${XIP_PATH}" +echo "=================================================================" + +# Already installed? +if [[ -d "$TARGET_DIR" ]]; then + CURRENT_BUILD="$("$TARGET_DIR/Contents/Developer/usr/bin/xcodebuild" -version 2>/dev/null | awk '/Build version/ {print $3}' || true)" + if [[ "$CURRENT_BUILD" == "$BUILD_NUM" ]]; then + echo "[OK] Xcode ${XCODE_VERSION} (${BUILD_NUM}) is already installed at ${TARGET_DIR}." + if [[ "$(xcode-select -p 2>/dev/null || true)" != "${TARGET_DIR}/Contents/Developer" ]]; then + echo "Run to select it: sudo xcode-select -s \"${TARGET_DIR}/Contents/Developer\"" + fi + exit 0 + fi + echo "[WARN] ${TARGET_DIR} exists with build '${CURRENT_BUILD}', expected '${BUILD_NUM}'. It will be replaced." +fi + +if [[ $DRY_RUN -eq 1 ]]; then + echo "[DRY-RUN] Would download : ${DOWNLOAD_URL}" + echo "[DRY-RUN] Alternative : ${TORRENT_URL}" + echo "[DRY-RUN] Would verify : SHA-1 ${EXPECTED_SHA1}, then pkgutil --check-signature" + exit 0 +fi + +if [[ $ASSUME_YES -eq 0 ]]; then + echo "This downloads ~2 GB, needs ~20 GB free and uses sudo to install into ${TARGET_DIR}." + echo "Redistribution of Xcode by third parties may conflict with Apple's license terms." + read -r -p "Continue? (yes/no): " ANSWER + [[ "$ANSWER" == "yes" ]] || { echo "Aborted."; exit 1; } +fi + +mkdir -p "$CACHE_DIR" +FREE_KB="$(df -k "$CACHE_DIR" | awk 'NR==2 {print $4}')" +if [[ "$FREE_KB" -lt $((20 * 1024 * 1024)) ]]; then + echo "[ERROR] At least 20 GB free are required in ${CACHE_DIR}." >&2 + exit 1 +fi + +# 1. Resumable download +if [[ ! -f "$XIP_PATH" ]]; then + echo "Downloading ${FILE_NAME} (resumable; torrent alternative: ${TORRENT_URL})..." + curl -fL -C - --progress-bar -o "$XIP_PATH" "$DOWNLOAD_URL" +else + echo "Using cached archive: $XIP_PATH" +fi + +# 2. Integrity: SHA-1 from archive.org metadata +echo "Verifying SHA-1..." +ACTUAL_SHA1="$(shasum -a 1 "$XIP_PATH" | awk '{print $1}')" +if [[ "$ACTUAL_SHA1" != "$EXPECTED_SHA1" ]]; then + echo "[ERROR] SHA-1 mismatch, the download is corrupt or altered." >&2 + echo " expected: $EXPECTED_SHA1" >&2 + echo " got : $ACTUAL_SHA1" >&2 + rm -f "$XIP_PATH" + exit 1 +fi +echo "[OK] SHA-1 matches." + +# 3. Authenticity: Apple's signature on the .xip +echo "Verifying Apple signature..." +if ! pkgutil --check-signature "$XIP_PATH"; then + echo "[ERROR] Apple signature check failed. Not installing." >&2 + exit 1 +fi +echo "[OK] Apple signature valid." + +# Remove the quarantine flag from the archive, otherwise it spreads to every file in Xcode.app and +# Gatekeeper scans them all on first use (15 to 25 minutes). +xattr -d com.apple.quarantine "$XIP_PATH" 2>/dev/null || true + +# 4. Extract (signature is checked again by xip itself) +EXTRACT_DIR="${CACHE_DIR}/extract_${BUILD_NUM}" +rm -rf "$EXTRACT_DIR" +mkdir -p "$EXTRACT_DIR" +echo "Extracting (5-10 minutes)..." +( + cd "$EXTRACT_DIR" + if command -v unxip >/dev/null 2>&1; then + unxip "$XIP_PATH" + else + /usr/bin/xip --expand "$XIP_PATH" + fi +) +if [[ ! -d "${EXTRACT_DIR}/Xcode.app" ]]; then + echo "[ERROR] Extraction failed: Xcode.app not found." >&2 + exit 1 +fi + +# 5. Install +echo "Installing to ${TARGET_DIR} (sudo)..." +sudo rm -rf "$TARGET_DIR" +sudo mv "${EXTRACT_DIR}/Xcode.app" "$TARGET_DIR" +sudo xattr -dr com.apple.quarantine "$TARGET_DIR" 2>/dev/null || true +rm -rf "$EXTRACT_DIR" + +# 6. Select and first-launch only with -y; otherwise print the commands. +if [[ $ASSUME_YES -eq 1 ]]; then + sudo xcode-select -s "${TARGET_DIR}/Contents/Developer" + sudo xcodebuild -license accept + sudo xcodebuild -runFirstLaunch + echo "[SUCCESS] Xcode ${XCODE_VERSION} (${BUILD_NUM}) installed and selected." + xcodebuild -version +else + echo "[SUCCESS] Installed ${TARGET_DIR}. Finish with:" + echo " sudo xcode-select -s \"${TARGET_DIR}/Contents/Developer\"" + echo " sudo xcodebuild -license # read and accept" + echo " sudo xcodebuild -runFirstLaunch" +fi diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh new file mode 100755 index 0000000000..565c6eba53 --- /dev/null +++ b/scripts/install_macos_build_tools.sh @@ -0,0 +1,159 @@ +#!/usr/bin/env bash + +# Safe to source (source script.sh) or execute directly (./script.sh) +if [ -n "${ZSH_VERSION:-}" ]; then + if [[ "${ZSH_EVAL_CONTEXT:-}" == *file* ]]; then + set -uo pipefail # sourced in zsh, don't -e + else + set -euo pipefail # executed in zsh + fi +elif [ -n "${BASH_VERSION:-}" ]; then + if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then + set -uo pipefail # sourced in bash, don't -e + else + set -euo pipefail # executed in bash + fi +else + set -euo pipefail # unknown shell +fi +die() { echo "$@" >&2; return 1 2>/dev/null || exit 1; } + +if [[ "$(uname -s)" != "Darwin" ]]; then + die "This installer is for macOS only." +fi + +# Homebrew may not be in PATH after a fresh install +if ! command -v brew >/dev/null 2>&1; then + if [[ -x /opt/homebrew/bin/brew ]]; then + eval "$(/opt/homebrew/bin/brew shellenv)" + elif [[ -x /usr/local/bin/brew ]]; then + eval "$(/usr/local/bin/brew shellenv)" + else + echo "Homebrew not found. Installing..." + /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" + if [[ -x /opt/homebrew/bin/brew ]]; then + eval "$(/opt/homebrew/bin/brew shellenv)" + elif [[ -x /usr/local/bin/brew ]]; then + eval "$(/usr/local/bin/brew shellenv)" + else + die "Homebrew installation failed. Install manually: https://brew.sh" + fi + fi +fi + +# rustup is keg-only in Homebrew (conflicts with rust), manually add to PATH +RUSTUP_BIN="/opt/homebrew/opt/rustup/bin" +if [[ -d "$RUSTUP_BIN" ]] && [[ ":$PATH:" != *":$RUSTUP_BIN:"* ]]; then + export PATH="$RUSTUP_BIN:$PATH" +fi + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]:-$0}")" && pwd)" +bash "$SCRIPT_DIR/install_xcode.sh" + +echo "Installing Homebrew packages..." +brew install direnv rustup cmake meson ninja pkg-config gnu-sed cocoapods go protobuf cbindgen autoconf automake libtool pandoc weasyprint toilet figlet sccache + +# The Homebrew cask always installs the latest Flutter, but the app is built +# and tested against one pinned release. Install that tag from source instead. +FLUTTER_VERSION="${FLUTTER_VERSION:-3.47.4}" +FLUTTER_DIR="${FLUTTER_DIR:-$HOME/development/flutter}" + +flutter_installed_version() { + "$1" --version --machine 2>/dev/null | sed -n 's/.*"frameworkVersion": *"\([^"]*\)".*/\1/p' | head -n 1 +} + +FLUTTER_BIN="$(command -v flutter 2>/dev/null || true)" +[[ -z "$FLUTTER_BIN" && -x "$FLUTTER_DIR/bin/flutter" ]] && FLUTTER_BIN="$FLUTTER_DIR/bin/flutter" +CURRENT_FLUTTER="" +[[ -n "$FLUTTER_BIN" ]] && CURRENT_FLUTTER="$(flutter_installed_version "$FLUTTER_BIN")" + +if [[ "$CURRENT_FLUTTER" == "$FLUTTER_VERSION" ]]; then + echo "Flutter $FLUTTER_VERSION already installed ($FLUTTER_BIN)." +else + [[ -n "$CURRENT_FLUTTER" ]] && echo "Found Flutter $CURRENT_FLUTTER at $FLUTTER_BIN, need $FLUTTER_VERSION." + if [[ -d "$FLUTTER_DIR/.git" ]]; then + echo "Switching $FLUTTER_DIR to Flutter $FLUTTER_VERSION..." + git -C "$FLUTTER_DIR" fetch --tags origin + git -C "$FLUTTER_DIR" checkout "$FLUTTER_VERSION" + elif [[ -e "$FLUTTER_DIR" ]]; then + die "$FLUTTER_DIR exists but is not a Flutter git checkout. Move it away or set FLUTTER_DIR." + else + echo "Cloning Flutter $FLUTTER_VERSION into $FLUTTER_DIR..." + mkdir -p "$(dirname "$FLUTTER_DIR")" + git clone --branch "$FLUTTER_VERSION" --depth 1 https://github.com/flutter/flutter.git "$FLUTTER_DIR" + fi +fi +export PATH="$FLUTTER_DIR/bin:$PATH" + +if ! command -v rustup >/dev/null 2>&1; then + die "rustup not found in PATH. Check brew install." +fi + +echo "Ensuring Rust 1.99.1 toolchain..." +rustup toolchain install 1.99.1 +rustup default 1.99.1 +rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios --toolchain 1.99.1 >/dev/null 2>&1 || true + +# Homebrew's rustup formula is keg-only and does not necessarily create the +# cargo/rustc shims in ~/.cargo/bin — `rustup toolchain install` alone may leave +# that directory absent, which means no `cargo` on PATH in this shell or any +# future one. Create the shims via rustup-init when they are missing. +if [ ! -x "$HOME/.cargo/bin/cargo" ]; then + echo "cargo shims missing in ~/.cargo/bin; creating them via rustup-init..." + if command -v rustup-init >/dev/null 2>&1; then + rustup-init -y --no-modify-path --default-toolchain 1.99.1 || true + else + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \ + | sh -s -- -y --no-modify-path --default-toolchain 1.99.1 || true + fi +fi + +# cargo/rustc live in ~/.cargo/bin after rustup installs a toolchain +export PATH="$HOME/.cargo/bin:$PATH" +source "$HOME/.cargo/env" 2>/dev/null || true + +if ! command -v cargo >/dev/null 2>&1; then + die "cargo still not on PATH after rustup setup. Run 'rustup-init -y' manually, then re-run this script." +fi + +echo "Verifying toolchain..." +if command -v flutter >/dev/null 2>&1; then + flutter --version +else + echo "flutter not found in PATH. Add $FLUTTER_DIR/bin to your shell profile." +fi + +if command -v dart >/dev/null 2>&1; then + dart --version +else + echo "dart not found in PATH. It should come with Flutter." +fi + +rustup --version +rustc --version +rustup run 1.99.1 rustc --version +pod --version +go version +autoreconf --version | head -n 1 || true +aclocal --version | head -n 1 || true + +echo "" +echo "Done." + +# Persist PATH entries for future terminals. Create ~/.zshrc when missing: a +# vanilla macOS install ships without one, and this block used to skip silently +# in that case — leaving new shells unable to find cargo/rustup and +# making `source`ing this script the only way to get a usable environment. +ZSHRC="$HOME/.zshrc" +if [ ! -f "$ZSHRC" ]; then + touch "$ZSHRC" + echo "→ Created $ZSHRC (macOS ships without one)" +fi +grep -qF 'brew shellenv' "$ZSHRC" 2>/dev/null || \ + echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> "$ZSHRC" +grep -qF "$FLUTTER_DIR/bin" "$ZSHRC" 2>/dev/null || \ + echo "export PATH=\"$FLUTTER_DIR/bin:\$PATH\"" >> "$ZSHRC" +grep -qF '$HOME/.cargo/bin' "$ZSHRC" 2>/dev/null || \ + echo 'export PATH="/opt/homebrew/opt/rustup/bin:$HOME/.cargo/bin:$PATH"' >> "$ZSHRC" +echo "→ PATH entries ensured in $ZSHRC" +echo " Open a new terminal (or run: source $ZSHRC) before 'make build-macos'." diff --git a/scripts/install_nixos_build_tools.sh b/scripts/install_nixos_build_tools.sh new file mode 100755 index 0000000000..d4b42bc80a --- /dev/null +++ b/scripts/install_nixos_build_tools.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash + +set -euo pipefail + +if [[ "$(uname -s)" != "Linux" ]]; then + echo "This installer is for Linux/NixOS only." + exit 1 +fi + +if ! command -v nix >/dev/null 2>&1; then + echo "Nix is required. Install it first: https://nixos.org/download/" + exit 1 +fi + +if ! command -v rustup >/dev/null 2>&1; then + echo "rustup is required. Install it first (for toolchain pinning): https://rustup.rs" + exit 1 +fi + +echo "Installing Nix profile packages..." +nix --extra-experimental-features "nix-command flakes" profile add \ + nixpkgs#direnv \ + nixpkgs#flutter \ + nixpkgs#go \ + nixpkgs#cmake \ + nixpkgs#ninja \ + nixpkgs#pkg-config \ + nixpkgs#gnumake \ + nixpkgs#gnused \ + nixpkgs#protobuf \ + nixpkgs#autoconf \ + nixpkgs#automake \ + nixpkgs#libtool \ + nixpkgs#clang || true + +echo "Ensuring Rust 1.99.1 toolchain..." +rustup toolchain install --no-self-update 1.99.1 +rustup default 1.99.1 +rustup target add aarch64-unknown-linux-gnu x86_64-unknown-linux-gnu --toolchain 1.99.1 >/dev/null 2>&1 || true + +echo "Installing optional Rust CLI build tools..." +cargo install cargo-ndk || true + +echo "Verifying toolchain..." +if command -v flutter >/dev/null 2>&1; then + flutter --version +else + echo "flutter not found in PATH." +fi + +if command -v dart >/dev/null 2>&1; then + dart --version +else + echo "dart not found in PATH. It should come with Flutter." +fi + +rustup --version +rustc --version +rustup run 1.99.1 rustc --version +go version +protoc --version || true +cmake --version | head -n 1 || true +pkg-config --version || true +autoreconf --version | head -n 1 || true +aclocal --version | head -n 1 || true + +echo "Done." diff --git a/scripts/install_xcode.sh b/scripts/install_xcode.sh new file mode 100755 index 0000000000..19d958f6a6 --- /dev/null +++ b/scripts/install_xcode.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash + +# Checks for full Xcode.app and points xcode-select at it. This is split out +# from install_macos_build_tools.sh because Xcode acquisition is orthogonal to +# whether the rest of the toolchain comes from Homebrew or Nix: neither can +# provide Xcode itself (Apple's license forbids redistributing it), so this +# script must run for both kinds of setups, not just the Homebrew one. +# +# Xcode itself is never auto-installed here: Apple's own download tooling +# (the `xcodes` CLI, `mas`) has proven unreliable in practice -- both hit +# hard failures (a broken Apple API returning 404 regardless of version, and +# `mas install` requiring an interactive sudo TTY) that still ended up +# needing a manual download anyway. Fail with clear instructions instead. +# +# Safe to source (source script.sh) or execute directly (./script.sh) +if [ -n "${ZSH_VERSION:-}" ]; then + if [[ "${ZSH_EVAL_CONTEXT:-}" == *file* ]]; then + set -uo pipefail # sourced in zsh, don't -e + else + set -euo pipefail # executed in zsh + fi +elif [ -n "${BASH_VERSION:-}" ]; then + if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then + set -uo pipefail # sourced in bash, don't -e + else + set -euo pipefail # executed in bash + fi +else + set -euo pipefail # unknown shell +fi +die() { echo "$@" >&2; return 1 2>/dev/null || exit 1; } + +if [[ "$(uname -s)" != "Darwin" ]]; then + die "This installer is for macOS only." +fi + +echo "Checking Xcode..." + +XCODE_APP="$(ls -d /Applications/Xcode*.app 2>/dev/null | head -1 || true)" + +if [[ -z "$XCODE_APP" ]]; then + die "[ERROR] Full Xcode is required for macOS/iOS builds (Command Line Tools alone are not enough). Install it, then re-run this script: + - Mac App Store: search 'Xcode' and install, or run 'mas install 497799835' if you already have 'mas' set up + - Or download the .xip directly from https://developer.apple.com/download/all/?q=xcode" +fi + +if ! xcode-select -p >/dev/null 2>&1 || [[ "$(xcode-select -p)" != *"/Xcode.app"* ]]; then + echo "Xcode.app found at $XCODE_APP. Setting xcode-select path..." + sudo xcode-select -s "$XCODE_APP/Contents/Developer" +else + echo "Xcode.app already configured." +fi + +sudo xcodebuild -license accept 2>/dev/null || true +sudo xcodebuild -runFirstLaunch 2>/dev/null || true diff --git a/scripts/linux/build_secp256k1.sh b/scripts/linux/build_secp256k1.sh index b6037a3060..187489d72b 100755 --- a/scripts/linux/build_secp256k1.sh +++ b/scripts/linux/build_secp256k1.sh @@ -1,15 +1,33 @@ +#!/usr/bin/env bash +set -e + mkdir -p build cd build + if [ ! -d "secp256k1" ]; then git clone https://github.com/bitcoin-core/secp256k1 fi + cd secp256k1 git checkout 68b55209f1ba3e6c0417789598f5f75649e9c14c git reset --hard + rm -rf build -mkdir -p build && cd build +mkdir -p build +cd build cmake .. -DSECP256K1_ENABLE_MODULE_RECOVERY=ON cmake --build . + +SECP_SO="$(find lib -maxdepth 1 -type f -name 'libsecp256k1.so*' | sort | head -n1)" +if [ -z "$SECP_SO" ]; then + echo "[ERROR] libsecp256k1 shared library not found after build." + exit 1 +fi + +# Legacy location used by parts of the build pipeline. mkdir -p ../../../../../build -cp lib/libsecp256k1.so.2.*.* "../../../../../build/libsecp256k1.so" -cd ../../../ \ No newline at end of file +cp "$SECP_SO" ../../../../../build/libsecp256k1.so + +# Location expected by Flutter/CMake install step. +mkdir -p ../../../../../build/linux/x64/release/secp256k1/lib +cp "$SECP_SO" ../../../../../build/linux/x64/release/secp256k1/lib/libsecp256k1.so diff --git a/scripts/linux/build_secure_storage_deps.sh b/scripts/linux/build_secure_storage_deps.sh index e84572bcaa..4069412db0 100755 --- a/scripts/linux/build_secure_storage_deps.sh +++ b/scripts/linux/build_secure_storage_deps.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash if [ "${USE_SYSTEM_SECURE_STORAGE_DEPS:-0}" = "1" ]; then echo "USE_SYSTEM_SECURE_STORAGE_DEPS is set; skipping build of jsoncpp and libsecret (using system packages)" @@ -21,7 +21,7 @@ cd jsoncpp || exit 1 git checkout $JSONCPP_TAG mkdir -p build cd build || exit 1 -cmake -DCMAKE_BUILD_TYPE=release -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=ON -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" .. +cmake -DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DCMAKE_BUILD_TYPE=release -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=ON -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" .. make -j"$(nproc)" cd "$LINUX_DIRECTORY" || exit 1 @@ -38,9 +38,25 @@ if ! [ -x "$(command -v meson)" ]; then echo 'Error: meson is not installed.' >&2 exit 1 fi -meson _build -Dmanpage=false -Dgtk_doc=false +meson _build -Dvapi=false -Dmanpage=false -Dgtk_doc=false if ! [ -x "$(command -v ninja)" ]; then echo 'Error: ninja is not installed.' >&2 exit 1 fi ninja -C _build + +# Publish a local pkg-config file that points at the locally built libsecret. +# This avoids relying on distro-specific libsecret/glib pkg-config metadata. +mkdir -p "$LINUX_DIRECTORY/pc" +cat > "$LINUX_DIRECTORY/pc/libsecret-1.pc" < Date: Sun, 1 Nov 2026 22:12:11 +0200 Subject: [PATCH 002/107] xcode: only use sudo when the install target is not writable download_xcode.sh used sudo for rm/mv/xattr unconditionally. It now checks whether the parent of the target directory is writable and only then uses sudo, so Xcode can be installed into ~/Applications without a password. Verified on macOS 27.2: -d ~/Applications/Xcode_27.1_test.app installed Xcode 27.1 (27A9275), the extracted app has no quarantine attribute, and free space dropped by about 4 GB; hash and signature checks passed before it. The install-time prompt text now says about 20 GB free are needed. --- scripts/download_xcode.sh | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/scripts/download_xcode.sh b/scripts/download_xcode.sh index 0108fd32a5..80ba4d10db 100755 --- a/scripts/download_xcode.sh +++ b/scripts/download_xcode.sh @@ -95,6 +95,13 @@ if [[ "$TARGET_DIR" != *.app || "$TARGET_DIR" == "/" ]]; then exit 1 fi +# sudo is only needed when the target directory is not writable (for example /Applications). +SUDO="" +mkdir -p "$(dirname "$TARGET_DIR")" 2>/dev/null || true +if [[ ! -w "$(dirname "$TARGET_DIR")" ]]; then + SUDO="sudo" +fi + DOWNLOAD_URL="https://archive.org/download/${IA_ITEM}/${FILE_NAME}" TORRENT_URL="https://archive.org/download/${IA_ITEM}/${IA_ITEM}_archive.torrent" XIP_PATH="${CACHE_DIR}/${FILE_NAME}" @@ -130,7 +137,7 @@ if [[ $DRY_RUN -eq 1 ]]; then fi if [[ $ASSUME_YES -eq 0 ]]; then - echo "This downloads ~2 GB, needs ~20 GB free and uses sudo to install into ${TARGET_DIR}." + echo "This downloads ~2 GB, needs ~20 GB free while extracting, and uses sudo only if ${TARGET_DIR} is not writable." echo "Redistribution of Xcode by third parties may conflict with Apple's license terms." read -r -p "Continue? (yes/no): " ANSWER [[ "$ANSWER" == "yes" ]] || { echo "Aborted."; exit 1; } @@ -194,10 +201,10 @@ if [[ ! -d "${EXTRACT_DIR}/Xcode.app" ]]; then fi # 5. Install -echo "Installing to ${TARGET_DIR} (sudo)..." -sudo rm -rf "$TARGET_DIR" -sudo mv "${EXTRACT_DIR}/Xcode.app" "$TARGET_DIR" -sudo xattr -dr com.apple.quarantine "$TARGET_DIR" 2>/dev/null || true +echo "Installing to ${TARGET_DIR}${SUDO:+ (sudo)}..." +$SUDO rm -rf "$TARGET_DIR" +$SUDO mv "${EXTRACT_DIR}/Xcode.app" "$TARGET_DIR" +$SUDO xattr -dr com.apple.quarantine "$TARGET_DIR" 2>/dev/null || true rm -rf "$EXTRACT_DIR" # 6. Select and first-launch only with -y; otherwise print the commands. From b9e3d38bdbeef35e6b1a0d01510a4d3201ed9ea0 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Mon, 2 Nov 2026 05:29:59 +0200 Subject: [PATCH 003/107] bootstrap: do not upgrade installed formulae, make the report tools optional install_macos_build_tools.sh aborted at the first brew failure. On a machine where weasyprint was installed another way, brew could not link it, set -e stopped the script, and the Flutter step was never reached. It also upgraded formulae that were already installed (cmake, go), changing the build machine under the user. - export HOMEBREW_NO_INSTALL_UPGRADE=1 for the required packages - install pandoc/weasyprint/toilet/figlet (only used by the bm/ report rendering) in a separate, non-fatal step Verified on macOS 27.2: first run failed as described; after the change the installer ended with rc=0, cloned Flutter 3.47.4 into a temporary FLUTTER_DIR, left the existing Flutter 3.47.2 untouched, and only appended the brew shellenv and Flutter PATH lines to ~/.zshrc (restored afterwards). --- scripts/install_macos_build_tools.sh | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh index 565c6eba53..ad1679be55 100755 --- a/scripts/install_macos_build_tools.sh +++ b/scripts/install_macos_build_tools.sh @@ -51,7 +51,13 @@ SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]:-$0}")" && pwd)" bash "$SCRIPT_DIR/install_xcode.sh" echo "Installing Homebrew packages..." -brew install direnv rustup cmake meson ninja pkg-config gnu-sed cocoapods go protobuf cbindgen autoconf automake libtool pandoc weasyprint toilet figlet sccache +# Do not upgrade formulae that are already installed: a build machine keeps the versions it was set up with. +export HOMEBREW_NO_INSTALL_UPGRADE=1 +brew install direnv rustup cmake meson ninja pkg-config gnu-sed cocoapods go protobuf cbindgen autoconf automake libtool sccache + +# Only used for the benchmark reports in bm/. A failure here (for example a link conflict with a +# copy installed another way) must not stop the toolchain setup. +brew install pandoc weasyprint toilet figlet || echo "[WARN] optional report tools were not fully installed; only bm/ report rendering needs them." # The Homebrew cask always installs the latest Flutter, but the app is built # and tested against one pinned release. Install that tag from source instead. From 7ef1d8354d583a596178ab93b2dfbf863c03e23d Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Mon, 2 Nov 2026 09:21:10 +0200 Subject: [PATCH 004/107] build: call build_app.sh from scripts/ like CI, drop redundant keys block make build-macos now runs ./build_app.sh from the scripts directory (as the CI jobs and the other targets do), so scripts/build_app.sh stays exactly as in staging; the earlier path-resolution and variable-rename edits are reverted. make build-linux no longer recreates lib/external_api_keys.dart: prebuild.sh already creates it, and the block never ran in any of the Linux builds I did. Verified on macOS 27.2: make build-macos OK, Stack Wallet.app with the unchanged bundle ID. The Linux target was only checked with make -n after this change. --- Makefile | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Makefile b/Makefile index 04dafa78fa..fa7ebdc09b 100644 --- a/Makefile +++ b/Makefile @@ -173,7 +173,7 @@ build-macos: check-reqs-macos check-sdk-macos ## Build macOS release (same steps @# so a previous PREBUILTS setting would otherwise stick. @rm -f pubspec.yaml @echo "--- Configuring project (scripts/build_app.sh)..." - @echo yes | env $(MACOS_ENV_UNSET) scripts/build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a stack_wallet -s $(if $(filter 1,$(PREBUILTS)),-d) + @cd scripts && echo yes | env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a stack_wallet -s $(if $(filter 1,$(PREBUILTS)),-d) @echo "--- Resolving dependencies..." @env $(MACOS_ENV_UNSET) $(FLUTTER) pub get @cd scripts && env $(MACOS_ENV_UNSET) bash prebuild.sh @@ -230,10 +230,6 @@ build-linux: check-reqs ## Build Linux Release through Flutter native-assets hoo echo "[INFO] .cargo/config.toml exists; make sure it sets [env] PROTOC if protoc fails to run (NixOS)."; \ fi @echo "--- Building app..." - @if [ ! -f lib/external_api_keys.dart ]; then \ - echo "[WARN] lib/external_api_keys.dart missing; recreating template."; \ - printf 'const kChangeNowApiKey = "";\nconst kSimpleSwapApiKey = "";\nconst kNanswapApiKey = "";\nconst kNanoSwapRpcApiKey = "";\nconst kWizSwapApiKey = "";\n' > lib/external_api_keys.dart; \ - fi @$(FLUTTER) pub get @mkdir -p scripts/linux/pc @printf '%s\n' \ From c1ec1593363f198cd4103ef69c5b89c27cf9375a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:19:09 +0200 Subject: [PATCH 005/107] xcode: retry interrupted downloads archive.org sometimes resets the connection (curl exit 56) a minute into the transfer, which aborted the script even though the download can be resumed. curl now retries up to 8 times (--retry-all-errors) and resumes with -C -. Seen in a fresh macOS 27.2 VM; the retry itself is exercised in the next VM run. --- scripts/download_xcode.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/download_xcode.sh b/scripts/download_xcode.sh index 80ba4d10db..aa3e9d0f98 100755 --- a/scripts/download_xcode.sh +++ b/scripts/download_xcode.sh @@ -153,7 +153,7 @@ fi # 1. Resumable download if [[ ! -f "$XIP_PATH" ]]; then echo "Downloading ${FILE_NAME} (resumable; torrent alternative: ${TORRENT_URL})..." - curl -fL -C - --progress-bar -o "$XIP_PATH" "$DOWNLOAD_URL" + curl -fL -C - --retry 8 --retry-delay 5 --retry-all-errors --progress-bar -o "$XIP_PATH" "$DOWNLOAD_URL" else echo "Using cached archive: $XIP_PATH" fi From a154fbea25a35573610824a6136f8085adb0b933 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:27:39 +0200 Subject: [PATCH 006/107] build: align make build-linux with the CI flags, Xcode mirror override, docs make build-linux now passes -d (PREBUILTS=1, the default, like make build-macos and the CI job) and -s with SYSTEM_DEPS=1. With -s the Makefile sets only USE_SYSTEM_SECURE_STORAGE_DEPS=1 for the app build; the local libsecret pkg-config override is kept for the default path (it is needed where libsecret is built from source, for example on NixOS). download_xcode.sh accepts XCODE_XIP_URL to download from another mirror; the SHA-1 and the Apple signature are still checked. docs: a second Xcode via DEVELOPER_DIR, and what reaches the hooks for sccache (exported RUSTC_WRAPPER does not, the cargo config file does). Verified: NixOS (nix develop) make build-linux with -d builds the bundle; Ubuntu 24.04 container make build-linux SYSTEM_DEPS=1 (-d -s, the CI flags) builds the bundle; make -n and bash -n pass for all targets and scripts. --- Makefile | 22 ++++++++++++---------- scripts/download_xcode.sh | 3 ++- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/Makefile b/Makefile index fa7ebdc09b..50d686bfdd 100644 --- a/Makefile +++ b/Makefile @@ -167,6 +167,8 @@ clean: ## Remove artifacts and fix permissions # --- PLATFORM BUILDS --- PREBUILTS ?= 1 +# Linux only: SYSTEM_DEPS=1 uses the system libsecret/jsoncpp packages instead of building them (like the CI image). +SYSTEM_DEPS ?= 0 build-macos: check-reqs-macos check-sdk-macos ## Build macOS release (same steps as upstream CI; PREBUILTS=0 compiles native assets from source) @# pubspec.yaml is generated; build_app.sh only regenerates it from the template when unchanged, @@ -217,7 +219,7 @@ build-linux: check-reqs ## Build Linux Release through Flutter native-assets hoo @cd scripts && bash prebuild.sh @echo "--- Generating config..." @if [ -z "$(PROTOC_PATH)" ]; then echo "[ERROR] protoc not found!"; exit 1; fi - @cd scripts && yes yes | BUILD_ISAR_FROM_SOURCE=0 PROTOC="$(PROTOC_PATH)" ./build_app.sh -a $(APP_NAME) -p linux -v $(VERSION) -b $(BUILD_NUM) + @cd scripts && yes yes | BUILD_ISAR_FROM_SOURCE=0 PROTOC="$(PROTOC_PATH)" ./build_app.sh -a $(APP_NAME) -p linux -v $(VERSION) -b $(BUILD_NUM) $(if $(filter 1,$(PREBUILTS)),-d) $(if $(filter 1,$(SYSTEM_DEPS)),-s) @# Flutter 3.47.x hooks only see a filtered environment, so PROTOC (exported by the flake) never @# reaches cargo build scripts. Some crates (prost-build 0.7) ship a generic-Linux protoc that cannot @# run on NixOS. cargo reads [env] from .cargo/config.toml found from the package dir upwards, which @@ -250,16 +252,16 @@ build-linux: check-reqs ## Build Linux Release through Flutter native-assets hoo else \ echo "[WARN] podman/docker not found; skipping coinlib:build_linux"; \ fi - @SYSPROF_PC_DIR=$$(dirname "$$(find /nix/store -path '*/lib/pkgconfig/sysprof-capture-4.pc' 2>/dev/null | head -n1)"); \ + @if [ "$(SYSTEM_DEPS)" = "1" ]; then \ + USE_SYSTEM_SECURE_STORAGE_DEPS=1 PROTOC="$(PROTOC_PATH)" $(FLUTTER) build linux --release; \ + else \ + SYSPROF_PC_DIR=$$(dirname "$$(find /nix/store -path '*/lib/pkgconfig/sysprof-capture-4.pc' 2>/dev/null | head -n1)"); \ PC_PATH=$$(pkg-config --variable=pc_path pkg-config 2>/dev/null || echo ""); \ - PKG_CONFIG_DISABLE_UNINSTALLED=1 \ - PKG_CONFIG_PATH= \ + PKG_CONFIG_DISABLE_UNINSTALLED=1 PKG_CONFIG_PATH= \ PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc:$$SYSPROF_PC_DIR:$$PC_PATH" \ pkg-config --modversion libsecret-1 >/dev/null || \ - { echo "[ERROR] libsecret-1 not resolvable via pkg-config"; exit 1; } - @SYSPROF_PC_DIR=$$(dirname "$$(find /nix/store -path '*/lib/pkgconfig/sysprof-capture-4.pc' 2>/dev/null | head -n1)"); \ - PC_PATH=$$(pkg-config --variable=pc_path pkg-config 2>/dev/null || echo ""); \ - PKG_CONFIG_DISABLE_UNINSTALLED=1 \ - PKG_CONFIG_PATH= \ + { echo "[ERROR] libsecret-1 not resolvable via pkg-config"; exit 1; }; \ + PKG_CONFIG_DISABLE_UNINSTALLED=1 PKG_CONFIG_PATH= \ PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc:$$SYSPROF_PC_DIR:$$PC_PATH" \ - PROTOC="$(PROTOC_PATH)" $(FLUTTER) build linux --release + PROTOC="$(PROTOC_PATH)" $(FLUTTER) build linux --release; \ + fi diff --git a/scripts/download_xcode.sh b/scripts/download_xcode.sh index aa3e9d0f98..6ddc23e2fb 100755 --- a/scripts/download_xcode.sh +++ b/scripts/download_xcode.sh @@ -102,7 +102,8 @@ if [[ ! -w "$(dirname "$TARGET_DIR")" ]]; then SUDO="sudo" fi -DOWNLOAD_URL="https://archive.org/download/${IA_ITEM}/${FILE_NAME}" +# XCODE_XIP_URL can point to another mirror (the SHA-1 and the Apple signature are still checked). +DOWNLOAD_URL="${XCODE_XIP_URL:-https://archive.org/download/${IA_ITEM}/${FILE_NAME}}" TORRENT_URL="https://archive.org/download/${IA_ITEM}/${IA_ITEM}_archive.torrent" XIP_PATH="${CACHE_DIR}/${FILE_NAME}" From 3cb0033bbe88211c5050662ee07728b7f9a408da Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Mon, 2 Nov 2026 07:06:17 +0200 Subject: [PATCH 007/107] build: add clean-app and clean-native targets, record sccache hits in bm/bench.sh clean-app removes build/ and the Pods but keeps .dart_tool/hooks_runner, so the next build does not rebuild the native assets; clean-native removes only the native-asset outputs. bm/bench.sh zeroes the sccache statistics before the build and stores 'sccache hits/executed requests' in the comment column of the CSV. --- Makefile | 13 ++++++++++++- bm/bench.sh | 9 ++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 50d686bfdd..824cdffcc2 100644 --- a/Makefile +++ b/Makefile @@ -31,7 +31,7 @@ MACOS_ENV_SET = MACOSX_DEPLOYMENT_TARGET=12.0 export APP_PROJECT_ROOT_DIR export PUB_CACHE -.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats clean build-macos build-linux diagnose-env-macos test-mwc +.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats clean clean-app clean-native build-macos build-linux diagnose-env-macos test-mwc help: ## Show available commands @echo "Available targets:" @@ -170,6 +170,17 @@ PREBUILTS ?= 1 # Linux only: SYSTEM_DEPS=1 uses the system libsecret/jsoncpp packages instead of building them (like the CI image). SYSTEM_DEPS ?= 0 +clean-app: ## Remove app build output (build/, Pods) but keep the native-asset build outputs, so the next build is fast + @chflags -R nouchg build/ macos/ 2>/dev/null || true + @chmod -R u+w build/ macos/ 2>/dev/null || true + @rm -rf build/ macos/Pods macos/Podfile.lock ios/Pods ios/Podfile.lock + @echo "[OK] Removed build/ and Pods; .dart_tool/hooks_runner is kept." + +clean-native: ## Remove only the native-asset build outputs (forces the Rust/Go/C libraries to be rebuilt) + @chmod -R u+w .dart_tool/hooks_runner build/native_assets 2>/dev/null || true + @rm -rf .dart_tool/hooks_runner build/native_assets + @echo "[OK] Removed .dart_tool/hooks_runner and build/native_assets." + build-macos: check-reqs-macos check-sdk-macos ## Build macOS release (same steps as upstream CI; PREBUILTS=0 compiles native assets from source) @# pubspec.yaml is generated; build_app.sh only regenerates it from the template when unchanged, @# so a previous PREBUILTS setting would otherwise stick. diff --git a/bm/bench.sh b/bm/bench.sh index 6863c55ddc..533ad0ef50 100755 --- a/bm/bench.sh +++ b/bm/bench.sh @@ -90,6 +90,7 @@ fi # Build echo "Building: make ${BUILD_TARGET} ${MAKE_FLAGS} " | banner +sccache --zero-stats >/dev/null 2>&1 || true START=$(date +%s) make ${BUILD_TARGET} ${MAKE_FLAGS} 2>&1 | tail -5 RC=$? @@ -97,6 +98,12 @@ END=$(date +%s) WALL=$((END - START)) # Disk after +SCC_NOTE="" +if command -v sccache >/dev/null 2>&1; then + SCC_REQ=$(sccache --show-stats 2>/dev/null | awk '/^Compile requests executed/ {print $NF}') + SCC_HIT=$(sccache --show-stats 2>/dev/null | awk '/^Cache hits / {print $NF}') + [ -n "${SCC_REQ:-}" ] && [ "${SCC_REQ:-0}" != "0" ] && SCC_NOTE="sccache ${SCC_HIT:-0}/${SCC_REQ} hits" +fi DISK_AFTER=$(du -sk . 2>/dev/null | cut -f1) DISK_DELTA=$((DISK_AFTER - DISK_BEFORE)) @@ -105,7 +112,7 @@ if [ ! -f "$OUTFILE" ]; then echo "label,branch,commit,host,arch,os_name,os_ver,date,warm,flags,wall_sec,success,disk_total_kb,disk_delta_kb,comment" > "$OUTFILE" fi -echo "${LABEL},${BRANCH},${COMMIT},${HOST},${ARCH},${OS_NAME},${OS_VER},${DATE},${WARM},${MAKE_FLAGS:--},${WALL},$((RC == 0 ? 1 : 0)),${DISK_AFTER},${DISK_DELTA}," >> "$OUTFILE" +echo "${LABEL},${BRANCH},${COMMIT},${HOST},${ARCH},${OS_NAME},${OS_VER},${DATE},${WARM},${MAKE_FLAGS:--},${WALL},$((RC == 0 ? 1 : 0)),${DISK_AFTER},${DISK_DELTA},${SCC_NOTE}" >> "$OUTFILE" echo "" if [ $RC -eq 0 ]; then From 494289cc0003d16887123e54a09d5b112fc0a0bc Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:27:53 +0200 Subject: [PATCH 008/107] build: add stack-bom.toml and make verify-bom stack-bom.toml records the expected toolchain (Flutter, Dart, Rust, Go, Xcode) and the git revisions of the pinned native plugins. make verify-bom (dart tool/verify_bom.dart, no packages needed) checks the local machine and pubspec.lock against it: a mismatch in Rust, Dart, minimum Flutter/Go or a plugin pin fails, a different recommended Flutter or Xcode only warns. dart tool/verify_bom.dart --update regenerates the [plugins] section from pubspec.lock. Verified on macOS 27.2: passes with 1 warning (Flutter 3.47.2 vs. recommended 3.47.4); a wrong Rust version and a wrong plugin pin both exit 1. --- Makefile | 5 +- stack-bom.toml | 28 ++++++ tool/verify_bom.dart | 222 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 254 insertions(+), 1 deletion(-) create mode 100644 stack-bom.toml create mode 100644 tool/verify_bom.dart diff --git a/Makefile b/Makefile index 824cdffcc2..d32a56a522 100644 --- a/Makefile +++ b/Makefile @@ -31,7 +31,7 @@ MACOS_ENV_SET = MACOSX_DEPLOYMENT_TARGET=12.0 export APP_PROJECT_ROOT_DIR export PUB_CACHE -.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats clean clean-app clean-native build-macos build-linux diagnose-env-macos test-mwc +.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux diagnose-env-macos test-mwc help: ## Show available commands @echo "Available targets:" @@ -148,6 +148,9 @@ sccache-setup: ## Opt-in: use sccache for the Rust/C builds run by native-asset @echo "never reach the hooks; cargo reads this file via HOME. Flutter versions with hooks_runner >= 1.6.2" @echo "also pass CARGO_BUILD_RUSTC_WRAPPER=sccache from the environment. See sccache --show-stats." +verify-bom: ## Check the local toolchain and the pinned plugins against stack-bom.toml + @dart tool/verify_bom.dart + cache-stats: ## Show sccache statistics (hit rate) after a build @command -v sccache >/dev/null 2>&1 || { echo >&2 "[ERROR] sccache not installed."; exit 1; } @sccache --show-stats diff --git a/stack-bom.toml b/stack-bom.toml new file mode 100644 index 0000000000..ac8f87adfe --- /dev/null +++ b/stack-bom.toml @@ -0,0 +1,28 @@ +# Stack Wallet build bill of materials: the toolchain a build is expected to use. +# Checked by `make verify-bom` (dart tool/verify_bom.dart). Keep it small and human readable. +schema_version = 1 + +[toolchain] +flutter = "3.47.4" # recommended; macOS builds verified with 3.47.2 and 3.47.4 +flutter_min = "3.47.2" # what CI and pubspec.template.yaml use today +dart_prefix = "3.13" # Dart bundled with Flutter 3.47.x +rust = "1.99.1" # installed through rustup, pinned by the native plugins +go_min = "1.24" # flutter_mwebd + +[hooks] +hooks_runner = "1.5.0" # pinned by Flutter 3.47.x; CARGO_/RUSTUP_ env vars reach hooks only from 1.6.2 + +[macos] +xcode = "27.1" # recommended for app builds +xcode_build = "27A9275" +xcode_dnix = "27.0" # dnix needs this one to rebuild Apple libraries byte for byte +xcode_xip_sha1 = "d8b1d16397e6f2faab34bd48b19692a3f7797b9d" # archive.org item xcode-27.1, see scripts/download_xcode.sh + +[plugins] +# Generated by `dart tool/verify_bom.dart --update` from pubspec.lock. Do not edit by hand. +flutter_libepiccash = "d5cfb763fa62928a6e6265e1f4412738772151eb" +flutter_libmwc = "d8c5d5488cb00e21d0dc04ad306a65e2d54c4d3c" +flutter_libsparkmobile = "3fdcb21160a39c051a0e73d7ae04f987134ecd5f" +frostdart = "c8be6a0ea892d744adfacc8e97df891feca49707" +tor_ffi_plugin = "e30ed0d386a40ee4a999aeaf57aafd32921d601e" +xelis_wallet_flutter = "8630a2cf28947497ec67b7535ddf1fac4cedbaa8" diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart new file mode 100644 index 0000000000..3ca18bc63e --- /dev/null +++ b/tool/verify_bom.dart @@ -0,0 +1,222 @@ +// Checks the local toolchain and the pinned native plugins against stack-bom.toml. +// +// dart tool/verify_bom.dart check, exit 1 on a mismatch +// dart tool/verify_bom.dart --update rewrite the [plugins] section from pubspec.lock +// +// No packages needed, so it runs before `flutter pub get`. +import 'dart:convert'; +import 'dart:io'; + +const _bomFile = 'stack-bom.toml'; +const _pluginNames = [ + 'flutter_libepiccash', + 'flutter_libmwc', + 'flutter_libsparkmobile', + 'frostdart', + 'tor_ffi_plugin', + 'xelis_wallet_flutter', +]; + +int _failures = 0; +int _warnings = 0; + +void _ok(String m) => stdout.writeln('[OK] $m'); +void _warn(String m) { + _warnings++; + stdout.writeln('[WARN] $m'); +} + +void _fail(String m) { + _failures++; + stdout.writeln('[FAIL] $m'); +} + +/// Minimal TOML reader: `[section]` headers and `key = "value"` lines. +Map> _readBom(String text) { + final result = >{}; + var section = ''; + for (final raw in text.split('\n')) { + final line = raw.trim(); + if (line.isEmpty || line.startsWith('#')) continue; + if (line.startsWith('[') && line.endsWith(']')) { + section = line.substring(1, line.length - 1); + result.putIfAbsent(section, () => {}); + continue; + } + final eq = line.indexOf('='); + if (eq < 0) continue; + final key = line.substring(0, eq).trim(); + var value = line.substring(eq + 1).trim(); + final hash = value.lastIndexOf(' #'); + if (hash >= 0 && value.startsWith('"') == false) { + value = value.substring(0, hash).trim(); + } + if (value.startsWith('"')) { + final end = value.indexOf('"', 1); + value = value.substring(1, end); + } + result.putIfAbsent(section, () => {})[key] = value; + } + return result; +} + +Future _run(String exe, List args) async { + try { + final r = await Process.run(exe, args); + if (r.exitCode != 0) return null; + return '${r.stdout}${r.stderr}'.trim(); + } on ProcessException { + return null; + } +} + +List _ver(String v) => + RegExp(r'\d+').allMatches(v).map((m) => int.parse(m.group(0)!)).toList(); + +int _cmp(String a, String b) { + final x = _ver(a), y = _ver(b); + for (var i = 0; i < 3; i++) { + final p = i < x.length ? x[i] : 0, q = i < y.length ? y[i] : 0; + if (p != q) return p.compareTo(q); + } + return 0; +} + +/// Reads the git refs of the pinned plugins from pubspec.lock. +Map _lockRefs() { + final lock = File('pubspec.lock'); + if (!lock.existsSync()) return {}; + final lines = lock.readAsLinesSync(); + final refs = {}; + for (var i = 0; i < lines.length; i++) { + final m = RegExp(r'^ (\w+):$').firstMatch(lines[i]); + if (m == null || !_pluginNames.contains(m.group(1))) continue; + for (var j = i + 1; j < lines.length && lines[j].startsWith(' '); j++) { + final r = RegExp(r'resolved-ref: "?([0-9a-f]{40})"?') + .firstMatch(lines[j]); + if (r != null) refs[m.group(1)!] = r.group(1)!; + } + } + return refs; +} + +Future _update() async { + final refs = _lockRefs(); + if (refs.isEmpty) { + stderr.writeln('pubspec.lock not found or has none of the plugins.'); + exit(2); + } + final text = File(_bomFile).readAsStringSync(); + final start = text.indexOf('[plugins]'); + final head = start < 0 + ? text.trimRight() + : text.substring(0, start).trimRight(); + final buf = StringBuffer(head) + ..writeln('\n') + ..writeln('[plugins]') + ..writeln( + '# Generated by `dart tool/verify_bom.dart --update` from pubspec.lock. Do not edit by hand.', + ); + for (final n in _pluginNames) { + if (refs.containsKey(n)) buf.writeln('$n = "${refs[n]}"'); + } + File(_bomFile).writeAsStringSync(buf.toString()); + stdout.writeln('Updated [plugins] in $_bomFile (${refs.length} entries).'); +} + +Future main(List args) async { + if (!File(_bomFile).existsSync()) { + stderr.writeln('Run from the repository root ($_bomFile not found).'); + exit(2); + } + if (args.contains('--update')) return _update(); + + final bom = _readBom(File(_bomFile).readAsStringSync()); + final tc = bom['toolchain'] ?? {}; + + // Flutter / Dart + final fl = await _run('flutter', ['--version', '--machine']); + if (fl == null) { + _fail('flutter not found in PATH'); + } else { + final info = + jsonDecode(fl.substring(fl.indexOf('{'))) as Map; + final v = info['frameworkVersion'] as String; + final d = info['dartSdkVersion'] as String; + if (_cmp(v, tc['flutter_min'] ?? '0') < 0) { + _fail('Flutter $v is older than the minimum ${tc['flutter_min']}'); + } else if (v != tc['flutter']) { + _warn( + 'Flutter $v (recommended ${tc['flutter']}, minimum ${tc['flutter_min']})', + ); + } else { + _ok('Flutter $v'); + } + if (d.startsWith(tc['dart_prefix'] ?? '')) { + _ok('Dart $d'); + } else { + _fail('Dart $d does not match ${tc['dart_prefix']}.x'); + } + } + + // Rust + final list = await _run('rustup', ['toolchain', 'list']); + final rust = tc['rust'] ?? ''; + if (list == null) { + _fail('rustup not found in PATH'); + } else if (list.split('\n').any((l) => l.startsWith('$rust-'))) { + _ok('Rust $rust installed via rustup'); + } else { + _fail('Rust $rust is not installed (rustup toolchain install $rust)'); + } + + // Go + final go = await _run('go', ['version']); + final gm = go == null ? null : RegExp(r'go(\d+\.\d+(\.\d+)?)').firstMatch(go); + if (gm == null) { + _fail('go not found in PATH'); + } else if (_cmp(gm.group(1)!, tc['go_min'] ?? '0') < 0) { + _fail('Go ${gm.group(1)} is older than the minimum ${tc['go_min']}'); + } else { + _ok('Go ${gm.group(1)}'); + } + + // Xcode (macOS only) + if (Platform.isMacOS) { + final mac = bom['macos'] ?? {}; + final xc = await _run('xcodebuild', ['-version']); + final xm = xc == null ? null : RegExp(r'Xcode (\S+)').firstMatch(xc); + if (xm == null) { + _fail('Xcode not found (xcode-select -p)'); + } else if (xm.group(1) == mac['xcode']) { + _ok('Xcode ${xm.group(1)}'); + } else if (xm.group(1) == mac['xcode_dnix']) { + _warn( + 'Xcode ${xm.group(1)} is the version dnix pins; ${mac['xcode']} is recommended for app builds', + ); + } else { + _warn('Xcode ${xm.group(1)} (recommended ${mac['xcode']})'); + } + } + + // Pinned plugins against pubspec.lock + final refs = _lockRefs(); + final pinned = bom['plugins'] ?? {}; + if (refs.isEmpty) { + _warn('pubspec.lock not found, plugin pins not checked'); + } else { + for (final n in _pluginNames) { + if (!refs.containsKey(n)) continue; + if (pinned[n] == refs[n]) { + _ok('$n ${refs[n]!.substring(0, 7)}'); + } else { + _fail( + '$n is ${refs[n]!.substring(0, 7)} in pubspec.lock but ${pinned[n]?.substring(0, 7)} in $_bomFile (run --update)', + ); + } + } + } + + stdout.writeln('\n$_failures failure(s), $_warnings warning(s).'); + exit(_failures == 0 ? 0 : 1); +} From 1e545d7b3a74f2010637dc83425985b05e71e52f Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:30:22 +0200 Subject: [PATCH 009/107] build: add make build-windows and a runner workflow to test the make targets make build-windows wraps the steps of the build-windows CI job (prebuild.sh, build_app.sh -p windows -d -s, pub get, coinlib:build_windows, flutter build windows). WINDOWS_COPY_ASSETS=1 replaces the asset links with copies for runners that cannot create symlinks. .github/workflows/make-build.yaml runs make build-windows and make build-macos on hosted runners (manual dispatch or pushes to ci/make-* branches). --- .github/workflows/make-build.yaml | 50 ++++++++++++++++++++++++++ Makefile | 16 ++++++++- scripts/windows/replace_asset_links.sh | 15 ++++++++ 3 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/make-build.yaml create mode 100755 scripts/windows/replace_asset_links.sh diff --git a/.github/workflows/make-build.yaml b/.github/workflows/make-build.yaml new file mode 100644 index 0000000000..d8fba846ad --- /dev/null +++ b/.github/workflows/make-build.yaml @@ -0,0 +1,50 @@ +name: Make build + +# Builds with the Makefile targets on the hosted runners. Manual or on pushes to ci/make-* branches. +on: + workflow_dispatch: + push: + branches: ['ci/make-*'] + +jobs: + windows: + runs-on: windows-2022 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - uses: subosito/flutter-action@v2 + with: + flutter-version: '3.47.2' + channel: 'stable' + - uses: actions/setup-go@v6 + with: + go-version: '1.24.13' + - name: Install make + run: command -v make >/dev/null 2>&1 || choco install make -y --no-progress + - name: Build + run: make build-windows VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} WINDOWS_COPY_ASSETS=1 + + macos: + runs-on: macos-latest + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - uses: subosito/flutter-action@v2 + with: + flutter-version: '3.47.2' + channel: 'stable' + - uses: actions/setup-go@v6 + with: + go-version: '1.24.13' + - name: Tools + run: | + brew install meson ninja autoconf automake libtool protobuf pkg-config cbindgen || true + rustup toolchain install 1.99.1 --profile minimal || true + rustup default 1.99.1 || true + - name: Build + run: make build-macos VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} diff --git a/Makefile b/Makefile index d32a56a522..58afb22b84 100644 --- a/Makefile +++ b/Makefile @@ -31,7 +31,7 @@ MACOS_ENV_SET = MACOSX_DEPLOYMENT_TARGET=12.0 export APP_PROJECT_ROOT_DIR export PUB_CACHE -.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux diagnose-env-macos test-mwc +.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos test-mwc help: ## Show available commands @echo "Available targets:" @@ -279,3 +279,17 @@ build-linux: check-reqs ## Build Linux Release through Flutter native-assets hoo PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc:$$SYSPROF_PC_DIR:$$PC_PATH" \ PROTOC="$(PROTOC_PATH)" $(FLUTTER) build linux --release; \ fi + +# Windows: run from Git Bash. Same steps as the "build-windows" job in .github/workflows/build.yaml. +# WINDOWS_COPY_ASSETS=1 replaces the asset links with copies (needed on runners that cannot create symlinks). +WINDOWS_COPY_ASSETS ?= 0 + +build-windows: ## Build Windows release (Git Bash; same steps as CI) + @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } + @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed."; exit 1; } + @cd scripts && bash prebuild.sh + @cd scripts && echo yes | MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d -s + @if [ "$(WINDOWS_COPY_ASSETS)" = "1" ]; then bash scripts/windows/replace_asset_links.sh; fi + @$(FLUTTER) pub get + @$(DART) run coinlib:build_windows + @$(FLUTTER) build windows --release diff --git a/scripts/windows/replace_asset_links.sh b/scripts/windows/replace_asset_links.sh new file mode 100755 index 0000000000..c6ecb65fc6 --- /dev/null +++ b/scripts/windows/replace_asset_links.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Replace the asset directory links created by link_assets.sh with real copies. +# Needed where `mklink /D` is not allowed (e.g. the GitHub Actions windows-2022 runner user lacks +# SeCreateSymbolicLinkPrivilege), because Flutter's asset resolver cannot follow the broken reparse points. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." +for dirname in default_themes icon lottie in_app_logo_icons svg; do + target="assets/${dirname}" + source="asset_sources/${dirname}/stack_wallet" + if [ -e "$target" ] || [ -L "$target" ]; then + cmd.exe /c rmdir "$(cygpath -w "$target")" 2>/dev/null || rm -rf "$target" + fi + mkdir -p "$target" + cp -r "${source}/." "$target/" +done From 536c2d5214e12763e7a33ffe4d2e716dbd7f8c6d Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:03:30 +0200 Subject: [PATCH 010/107] ci: make-build workflow is manual only and gets a Linux job --- .github/workflows/make-build.yaml | 32 ++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/.github/workflows/make-build.yaml b/.github/workflows/make-build.yaml index d8fba846ad..d726a2f628 100644 --- a/.github/workflows/make-build.yaml +++ b/.github/workflows/make-build.yaml @@ -1,10 +1,8 @@ name: Make build -# Builds with the Makefile targets on the hosted runners. Manual or on pushes to ci/make-* branches. +# Builds with the Makefile targets on the hosted runners. Manual only. on: workflow_dispatch: - push: - branches: ['ci/make-*'] jobs: windows: @@ -48,3 +46,31 @@ jobs: rustup default 1.99.1 || true - name: Build run: make build-macos VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} + + linux: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - uses: subosito/flutter-action@v2 + with: + flutter-version: '3.47.2' + channel: 'stable' + - uses: actions/setup-go@v6 + with: + go-version: '1.24.13' + - name: Install build dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + automake build-essential clang cmake libclang-dev libtool llvm meson ninja-build patchelf pkg-config protobuf-compiler rsync \ + libgcrypt20-dev libgirepository1.0-dev libgit2-dev libglib2.0-dev libgtk-3-dev libjsoncpp-dev liblzma-dev \ + libncurses5-dev libncursesw5-dev libopencv-dev libsecret-1-dev libssl-dev libtss2-dev \ + ocl-icd-opencl-dev opencl-headers valac zlib1g-dev + - name: Rust + run: | + rustup toolchain install 1.99.1 --profile minimal + rustup default 1.99.1 + - name: Build + run: make build-linux VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} From 2a2527865ce6f5b746c6045a829ce3ce8ab4d1de Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Mon, 2 Nov 2026 08:06:50 +0200 Subject: [PATCH 011/107] build: add make build-android wrapping the CI steps (unsigned) --- Makefile | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 58afb22b84..1d00b0b46d 100644 --- a/Makefile +++ b/Makefile @@ -31,7 +31,7 @@ MACOS_ENV_SET = MACOSX_DEPLOYMENT_TARGET=12.0 export APP_PROJECT_ROOT_DIR export PUB_CACHE -.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos test-mwc +.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos test-mwc build-android help: ## Show available commands @echo "Available targets:" @@ -293,3 +293,15 @@ build-windows: ## Build Windows release (Git Bash; same steps as CI) @$(FLUTTER) pub get @$(DART) run coinlib:build_windows @$(FLUTTER) build windows --release + +# Android: same steps as the "build-android" CI job, without the signing secrets. Needs the Android SDK/NDK +# (ANDROID_SDK_ROOT) and Java; the CI image ghcr.io//stackwallet-ci:android is built from the Dockerfile +# (docker build --target android). The release APKs are unsigned unless android/key.properties exists. +build-android: ## Build Android APKs (same steps as CI, unsigned without android/key.properties) + @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } + @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } + @cd scripts && bash prebuild.sh + @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p android -a $(APP_NAME) -d -s + @$(FLUTTER) pub get + @$(FLUTTER) build apk --split-per-abi --release + From 99bcd1ddd4194dff934e04c24a0eb9684cd6ea4a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Mon, 2 Nov 2026 08:58:36 +0200 Subject: [PATCH 012/107] build: make build-android creates a throw-away debug key when no signing key exists The release build fails at packageRelease without android/key.properties (SigningConfig release is missing storeFile). android-dev-key creates a debug keystore and key.properties for local builds only; both files are git-ignored and the APKs are not for distribution. --- .gitignore | 2 ++ Makefile | 15 ++++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index b854b54aeb..7151970281 100644 --- a/.gitignore +++ b/.gitignore @@ -131,3 +131,5 @@ bm/results/ # Nix dev shell: generated wrappers .nix-bin/ .direnv/ +/android/key.properties +/android/dev-keystore.jks diff --git a/Makefile b/Makefile index 1d00b0b46d..77d5698a30 100644 --- a/Makefile +++ b/Makefile @@ -31,7 +31,7 @@ MACOS_ENV_SET = MACOSX_DEPLOYMENT_TARGET=12.0 export APP_PROJECT_ROOT_DIR export PUB_CACHE -.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos test-mwc build-android +.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos test-mwc build-android android-dev-key help: ## Show available commands @echo "Available targets:" @@ -296,8 +296,17 @@ build-windows: ## Build Windows release (Git Bash; same steps as CI) # Android: same steps as the "build-android" CI job, without the signing secrets. Needs the Android SDK/NDK # (ANDROID_SDK_ROOT) and Java; the CI image ghcr.io//stackwallet-ci:android is built from the Dockerfile -# (docker build --target android). The release APKs are unsigned unless android/key.properties exists. -build-android: ## Build Android APKs (same steps as CI, unsigned without android/key.properties) +# (docker build --target android). Without android/key.properties a throw-away debug key is created, so the APKs +# are not suitable for distribution. +android-dev-key: ## Create a throw-away debug signing key if android/key.properties is missing (never use for releases) + @if [ ! -f android/key.properties ]; then \ + echo "[INFO] android/key.properties missing: creating a throw-away debug key (not for releases)"; \ + keytool -genkeypair -keystore android/dev-keystore.jks -storetype pkcs12 -storepass android -keypass android \ + -alias devkey -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=Stack Wallet dev build" -noprompt && \ + printf 'storeFile=../dev-keystore.jks\nstorePassword=android\nkeyPassword=android\nkeyAlias=devkey\n' > android/key.properties; \ + fi + +build-android: android-dev-key ## Build Android APKs (same steps as CI; signed with a throw-away key unless android/key.properties exists) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } @cd scripts && bash prebuild.sh From b158876b4cdd27887c14c88c0b80c8c7cec4fa02 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Mon, 2 Nov 2026 08:59:05 +0200 Subject: [PATCH 013/107] build: add make build-ios wrapping the CI steps (no code signing) --- Makefile | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 77d5698a30..7ea0188280 100644 --- a/Makefile +++ b/Makefile @@ -31,7 +31,7 @@ MACOS_ENV_SET = MACOSX_DEPLOYMENT_TARGET=12.0 export APP_PROJECT_ROOT_DIR export PUB_CACHE -.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos test-mwc build-android android-dev-key +.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos test-mwc build-android android-dev-key build-ios help: ## Show available commands @echo "Available targets:" @@ -314,3 +314,11 @@ build-android: android-dev-key ## Build Android APKs (same steps as CI; signed w @$(FLUTTER) pub get @$(FLUTTER) build apk --split-per-abi --release +# iOS: same steps as the "build-ios" CI job (device build, no code signing). Run on macOS with Xcode. +build-ios: check-sdk-macos ## Build iOS Runner.app without code signing (same steps as CI) + @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } + @cd scripts && bash prebuild.sh + @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) -d -s + @$(FLUTTER) pub get + @$(FLUTTER) build ios --release --no-codesign + From 7a7b3614cf97b4447cc7f1e9249d204da679e3f9 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:28:03 +0200 Subject: [PATCH 014/107] ci: make-build workflow gets an iOS job and runs make verify-bom on Linux --- .github/workflows/make-build.yaml | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/.github/workflows/make-build.yaml b/.github/workflows/make-build.yaml index d726a2f628..544028b54c 100644 --- a/.github/workflows/make-build.yaml +++ b/.github/workflows/make-build.yaml @@ -72,5 +72,28 @@ jobs: run: | rustup toolchain install 1.99.1 --profile minimal rustup default 1.99.1 + - name: Check the toolchain bill of materials + run: make verify-bom - name: Build run: make build-linux VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} + + ios: + runs-on: macos-latest + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - uses: subosito/flutter-action@v2 + with: + flutter-version: '3.47.2' + channel: 'stable' + - uses: actions/setup-go@v6 + with: + go-version: '1.24.13' + - name: Tools + run: | + brew install meson ninja autoconf automake libtool protobuf pkg-config cbindgen || true + rustup toolchain install 1.99.1 --profile minimal || true + rustup default 1.99.1 || true + - name: Build + run: make build-ios VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} From d5a1fcc348f2e49ce20d8c5b142dbecd1d00b80d Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:42:34 +0200 Subject: [PATCH 015/107] ci: free disk space in the Linux make-build job --- .github/workflows/make-build.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/make-build.yaml b/.github/workflows/make-build.yaml index 544028b54c..08d0907606 100644 --- a/.github/workflows/make-build.yaml +++ b/.github/workflows/make-build.yaml @@ -60,6 +60,10 @@ jobs: - uses: actions/setup-go@v6 with: go-version: '1.24.13' + - name: Free disk space + run: | + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL + df -h / - name: Install build dependencies run: | sudo apt-get update From 3ca0af819f48640f534d255c355101e0b59c36e9 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:29:28 +0200 Subject: [PATCH 016/107] build: fix review findings in bootstrap, Windows asset copies, Linux deps and bm - build-windows: with WINDOWS_COPY_ASSETS=1 remove the asset copies of an earlier run before build_app.sh runs link_assets.sh, whose `rm -f` cannot delete real directories (second run failed) - bootstrap-macos: skip the Homebrew installer in a Nix shell with one conditional recipe instead of `exit 0`, which only ended that line's shell; failures of the Xcode step now propagate - build_secure_storage_deps.sh: stop when cmake, make, meson or ninja fails, before writing the pkg-config file; reconfigure an existing meson build directory instead of failing on it - install_macos_build_tools.sh: put rustup on PATH after `brew install` (resolved with `brew --prefix rustup`), not only if its directory existed before - install_xcode.sh: keep any valid selected Xcode (Xcode_27.1.app, ~/Applications, ...) and only pick one from /Applications when the selection is missing or the Command Line Tools - mwc_ffi_test_service: the invalid-slatepack assertion no longer sits inside its own catch - bm/compare.py: pair measurements by label and host instead of the first row of each file - bm/bench.sh: record failed builds and return make's exit status --- Makefile | 10 +++++---- bm/bench.sh | 8 ++++++- bm/compare.py | 14 ++++++------ integration_test/mwc_ffi_test_service.dart | 25 ++++++++++++++-------- scripts/install_macos_build_tools.sh | 15 ++++++++----- scripts/install_xcode.sh | 22 +++++++++++-------- scripts/linux/build_secure_storage_deps.sh | 13 +++++++---- scripts/windows/replace_asset_links.sh | 5 +++++ 8 files changed, 74 insertions(+), 38 deletions(-) diff --git a/Makefile b/Makefile index 7ea0188280..07456a0a8f 100644 --- a/Makefile +++ b/Makefile @@ -106,11 +106,11 @@ ifeq ($(PLATFORM),Darwin) @if [ -n "$$IN_NIX_SHELL" ] || [ -n "$$NIX_BUILD_TOP" ]; then \ echo "[WARN] Nix environment detected; skipping the Homebrew package install (use nix/flake-provided toolchain instead)."; \ echo "[WARN] Xcode itself is never provided by Nix (Apple's license forbids redistributing it), so that part still runs:"; \ - $(MAKE) bootstrap-xcode; \ - exit 0; \ + $(MAKE) bootstrap-xcode || exit 1; \ + else \ + bash scripts/install_macos_build_tools.sh || exit 1; \ + rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios --toolchain $(RUST_VERSION) >/dev/null 2>&1 || true; \ fi - @bash scripts/install_macos_build_tools.sh - @rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios --toolchain $(RUST_VERSION) >/dev/null 2>&1 || true else @echo "[ERROR] bootstrap-macos is macOS-only." @exit 1 @@ -288,6 +288,8 @@ build-windows: ## Build Windows release (Git Bash; same steps as CI) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed."; exit 1; } @cd scripts && bash prebuild.sh + @# link_assets.sh (run by build_app.sh) cannot remove the real directories a previous copy run left behind. + @if [ "$(WINDOWS_COPY_ASSETS)" = "1" ]; then bash scripts/windows/replace_asset_links.sh --clean; fi @cd scripts && echo yes | MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d -s @if [ "$(WINDOWS_COPY_ASSETS)" = "1" ]; then bash scripts/windows/replace_asset_links.sh; fi @$(FLUTTER) pub get diff --git a/bm/bench.sh b/bm/bench.sh index 533ad0ef50..8ceb9ad179 100755 --- a/bm/bench.sh +++ b/bm/bench.sh @@ -92,8 +92,11 @@ fi echo "Building: make ${BUILD_TARGET} ${MAKE_FLAGS} " | banner sccache --zero-stats >/dev/null 2>&1 || true START=$(date +%s) +# A failing build must still be timed and recorded, so errexit is off for the build and its status is taken from make. +set +e make ${BUILD_TARGET} ${MAKE_FLAGS} 2>&1 | tail -5 -RC=$? +RC=${PIPESTATUS[0]} +set -e END=$(date +%s) WALL=$((END - START)) @@ -136,3 +139,6 @@ tail -n +2 "$OUTFILE" | while IFS=, read -r label branch commit host arch os_nam [ "$success" = "1" ] && ok="✓" || ok="✗" printf "%-12s %-20s %-8s %-10s %-4s %10s %8s %s\n" "${date:0:10}" "$label" "${commit:0:7}" "${flags:--}" "$warm_label" "$time_fmt" "$ok ${delta_mb}MB" "$comment" done + +# Report the build's own exit status to the caller. +exit "$RC" diff --git a/bm/compare.py b/bm/compare.py index f600e2c75c..b41fb56c89 100755 --- a/bm/compare.py +++ b/bm/compare.py @@ -138,15 +138,17 @@ def compare(dir1, dir2=None): print(f"\n{'═'*80}") print(f" Delta: {os.path.basename(dir1)} → {os.path.basename(dir2)}") print(f"{'═'*80}") - labels1 = {r["label"] for r in rows1} - labels2 = {r["label"] for r in rows2} - for label in sorted(labels1 & labels2): - t1 = wall_s(rows1[0]["wall_sec"]) - t2 = wall_s(rows2[0]["wall_sec"]) + # Pair measurements by label and host; if a pair was measured several times, the latest row counts. + latest1 = {(r["label"], r.get("host", "unknown")): r for r in rows1} + latest2 = {(r["label"], r.get("host", "unknown")): r for r in rows2} + for key in sorted(latest1.keys() & latest2.keys()): + label, host = key + t1 = wall_s(latest1[key]["wall_sec"]) + t2 = wall_s(latest2[key]["wall_sec"]) delta = t2 - t1 pct = (delta/t1)*100 if t1 else 0 sign = "+" if delta > 0 else "" - print(f" {hr_label(label):25s} {wall_fmt(t1)} → {wall_fmt(t2)} ({sign}{pct:.0f}%)") + print(f" {hr_label(label):25s} {host:12s} {wall_fmt(t1)} → {wall_fmt(t2)} ({sign}{pct:.0f}%)") if __name__ == "__main__": diff --git a/integration_test/mwc_ffi_test_service.dart b/integration_test/mwc_ffi_test_service.dart index 8d73a5c585..5fd915d345 100644 --- a/integration_test/mwc_ffi_test_service.dart +++ b/integration_test/mwc_ffi_test_service.dart @@ -628,21 +628,28 @@ class FFITestService { () async { try { final bogus = 'NOT_A_SLATEPACK'; + String? slateJson; + Object? decodeError; try { final dec = await Libmwc.decodeSlatepack(slatepack: bogus); - // High-level API may not throw; validate empty slate JSON returned. - if (dec.slateJson.isNotEmpty) { - throw TestException( - 'Invalid slatepack returned non-empty slate JSON', - ); - } - return 'Invalid slatepack handled gracefully (empty slate JSON)'; + slateJson = dec.slateJson; } catch (e) { - // If it throws, that's also acceptable as graceful failure. - final es = e.toString(); + decodeError = e; + } + // If the decoder throws, that's also acceptable as graceful failure. + if (decodeError != null) { + final es = decodeError.toString(); final trunc = es.substring(0, es.length < 80 ? es.length : 80); return 'Invalid slatepack decode threw as expected: $trunc...'; } + // High-level API may not throw; validate empty slate JSON returned. + // Outside the catch above, so a failed assertion fails the test. + if (slateJson!.isNotEmpty) { + throw TestException( + 'Invalid slatepack returned non-empty slate JSON', + ); + } + return 'Invalid slatepack handled gracefully (empty slate JSON)'; } catch (e) { throw TestException('Invalid format handling failed: $e'); } diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh index ad1679be55..e317a0e65b 100755 --- a/scripts/install_macos_build_tools.sh +++ b/scripts/install_macos_build_tools.sh @@ -41,11 +41,15 @@ if ! command -v brew >/dev/null 2>&1; then fi fi -# rustup is keg-only in Homebrew (conflicts with rust), manually add to PATH -RUSTUP_BIN="/opt/homebrew/opt/rustup/bin" -if [[ -d "$RUSTUP_BIN" ]] && [[ ":$PATH:" != *":$RUSTUP_BIN:"* ]]; then - export PATH="$RUSTUP_BIN:$PATH" -fi +# rustup is keg-only in Homebrew (conflicts with rust), so it has to be added to PATH by hand. +# Called again after `brew install`: on a first install the directory does not exist before it. +add_rustup_to_path() { + local prefix + prefix="$(brew --prefix rustup 2>/dev/null || true)" + [[ -n "$prefix" && -d "$prefix/bin" && ":$PATH:" != *":$prefix/bin:"* ]] && export PATH="$prefix/bin:$PATH" + return 0 +} +add_rustup_to_path SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]:-$0}")" && pwd)" bash "$SCRIPT_DIR/install_xcode.sh" @@ -54,6 +58,7 @@ echo "Installing Homebrew packages..." # Do not upgrade formulae that are already installed: a build machine keeps the versions it was set up with. export HOMEBREW_NO_INSTALL_UPGRADE=1 brew install direnv rustup cmake meson ninja pkg-config gnu-sed cocoapods go protobuf cbindgen autoconf automake libtool sccache +add_rustup_to_path # Only used for the benchmark reports in bm/. A failure here (for example a link conflict with a # copy installed another way) must not stop the toolchain setup. diff --git a/scripts/install_xcode.sh b/scripts/install_xcode.sh index 19d958f6a6..18b1b54bfe 100755 --- a/scripts/install_xcode.sh +++ b/scripts/install_xcode.sh @@ -36,19 +36,23 @@ fi echo "Checking Xcode..." -XCODE_APP="$(ls -d /Applications/Xcode*.app 2>/dev/null | head -1 || true)" +# Any full Xcode that is already selected stays selected, whatever its file name (Xcode.app, +# Xcode_27.1.app, Xcode-beta.app, ...) and wherever it lives. Only an unusable selection (none, or +# the Command Line Tools) is replaced by an Xcode found in $XCODE_APPS_DIR. +XCODE_APPS_DIR="${XCODE_APPS_DIR:-/Applications}" +SELECTED_DEV="$(xcode-select -p 2>/dev/null || true)" -if [[ -z "$XCODE_APP" ]]; then - die "[ERROR] Full Xcode is required for macOS/iOS builds (Command Line Tools alone are not enough). Install it, then re-run this script: +if [[ "$SELECTED_DEV" == /*.app/Contents/Developer && -x "$SELECTED_DEV/usr/bin/xcodebuild" ]]; then + echo "Xcode already configured: ${SELECTED_DEV%/Contents/Developer}" +else + XCODE_APP="$(ls -d "$XCODE_APPS_DIR"/Xcode*.app 2>/dev/null | head -1 || true)" + if [[ -z "$XCODE_APP" ]]; then + die "[ERROR] Full Xcode is required for macOS/iOS builds (Command Line Tools alone are not enough). Install it, then re-run this script: - Mac App Store: search 'Xcode' and install, or run 'mas install 497799835' if you already have 'mas' set up - Or download the .xip directly from https://developer.apple.com/download/all/?q=xcode" -fi - -if ! xcode-select -p >/dev/null 2>&1 || [[ "$(xcode-select -p)" != *"/Xcode.app"* ]]; then - echo "Xcode.app found at $XCODE_APP. Setting xcode-select path..." + fi + echo "Xcode found at $XCODE_APP. Setting xcode-select path..." sudo xcode-select -s "$XCODE_APP/Contents/Developer" -else - echo "Xcode.app already configured." fi sudo xcodebuild -license accept 2>/dev/null || true diff --git a/scripts/linux/build_secure_storage_deps.sh b/scripts/linux/build_secure_storage_deps.sh index 4069412db0..c58cd80d0e 100755 --- a/scripts/linux/build_secure_storage_deps.sh +++ b/scripts/linux/build_secure_storage_deps.sh @@ -21,8 +21,8 @@ cd jsoncpp || exit 1 git checkout $JSONCPP_TAG mkdir -p build cd build || exit 1 -cmake -DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DCMAKE_BUILD_TYPE=release -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=ON -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" .. -make -j"$(nproc)" +cmake -DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DCMAKE_BUILD_TYPE=release -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=ON -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" .. || exit 1 +make -j"$(nproc)" || exit 1 cd "$LINUX_DIRECTORY" || exit 1 # Build libSecret @@ -38,12 +38,17 @@ if ! [ -x "$(command -v meson)" ]; then echo 'Error: meson is not installed.' >&2 exit 1 fi -meson _build -Dvapi=false -Dmanpage=false -Dgtk_doc=false +# A second run finds _build already configured; "meson _build" would fail on that, so reconfigure instead. +if [ -f _build/meson-private/coredata.dat ]; then + meson setup --reconfigure _build -Dvapi=false -Dmanpage=false -Dgtk_doc=false || exit 1 +else + meson setup _build -Dvapi=false -Dmanpage=false -Dgtk_doc=false || exit 1 +fi if ! [ -x "$(command -v ninja)" ]; then echo 'Error: ninja is not installed.' >&2 exit 1 fi -ninja -C _build +ninja -C _build || exit 1 # Publish a local pkg-config file that points at the locally built libsecret. # This avoids relying on distro-specific libsecret/glib pkg-config metadata. diff --git a/scripts/windows/replace_asset_links.sh b/scripts/windows/replace_asset_links.sh index c6ecb65fc6..6b4cb433d4 100755 --- a/scripts/windows/replace_asset_links.sh +++ b/scripts/windows/replace_asset_links.sh @@ -1,15 +1,20 @@ #!/usr/bin/env bash # Replace the asset directory links created by link_assets.sh with real copies. +# With --clean it only removes them (links or copies) and copies nothing: link_assets.sh runs `rm -f` +# on each target, which cannot remove the real directories a previous run left behind. # Needed where `mklink /D` is not allowed (e.g. the GitHub Actions windows-2022 runner user lacks # SeCreateSymbolicLinkPrivilege), because Flutter's asset resolver cannot follow the broken reparse points. set -euo pipefail cd "$(dirname "${BASH_SOURCE[0]}")/../.." +clean_only=0 +[ "${1:-}" = "--clean" ] && clean_only=1 for dirname in default_themes icon lottie in_app_logo_icons svg; do target="assets/${dirname}" source="asset_sources/${dirname}/stack_wallet" if [ -e "$target" ] || [ -L "$target" ]; then cmd.exe /c rmdir "$(cygpath -w "$target")" 2>/dev/null || rm -rf "$target" fi + [ "$clean_only" = "1" ] && continue mkdir -p "$target" cp -r "${source}/." "$target/" done From 43c68858accfe5f7a842f23c871816c7ed24be40 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:49:26 +0200 Subject: [PATCH 017/107] build: fix make targets and tooling issues - Remove the MWC FFI integration tests; they belong in flutter_libmwc. - Run prepare_release_bundle.py from make build-linux. - Honor APP_NAME on macOS and make WINDOWS_COPY_ASSETS copy in link_assets.sh. - Stop rewriting the tracked libsecret pkg-config file and drop duplicate toolchain steps. - Harden verify_bom.dart for Windows and missing plugin pins. - Fix bootstrap/Xcode selection, download resume, and benchmark script edge cases. --- .gitignore | 1 + Makefile | 72 +- README.md | 4 +- bm/bench.sh | 16 +- bm/compare.py | 3 +- bm/render.sh | 6 +- bm/run_all.sh | 3 + flake.nix | 28 +- integration_test/mwc_ffi_test.dart | 20 - integration_test/mwc_ffi_test_service.dart | 1028 -------------------- integration_test/mwc_test_result.dart | 28 - scripts/app_config/shared/link_assets.sh | 27 +- scripts/download_xcode.sh | 86 +- scripts/install_macos_build_tools.sh | 74 +- scripts/install_nixos_build_tools.sh | 67 -- scripts/install_xcode.sh | 24 +- scripts/linux/pc/libsecret-1.pc | 15 - scripts/windows/replace_asset_links.sh | 20 - tool/verify_bom.dart | 78 +- 19 files changed, 276 insertions(+), 1324 deletions(-) delete mode 100644 integration_test/mwc_ffi_test.dart delete mode 100644 integration_test/mwc_ffi_test_service.dart delete mode 100644 integration_test/mwc_test_result.dart delete mode 100755 scripts/install_nixos_build_tools.sh delete mode 100644 scripts/linux/pc/libsecret-1.pc delete mode 100755 scripts/windows/replace_asset_links.sh diff --git a/.gitignore b/.gitignore index 7151970281..f3393861e8 100644 --- a/.gitignore +++ b/.gitignore @@ -127,6 +127,7 @@ lib/wl_gen/generated/ /tool/build bm/results/ /.cargo/config.toml +/scripts/linux/pc/ # Nix dev shell: generated wrappers .nix-bin/ diff --git a/Makefile b/Makefile index 07456a0a8f..f537d2def3 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ # ============================================================================== -# Stack Wallet build helper (macOS). Wraps scripts/build_app.sh; see docs/building.md +# Stack Wallet build helper. Wraps scripts/build_app.sh; see docs/building.md # Usage: make VERSION=x.x.x BUILD_NUM=xxx # ============================================================================== @@ -15,23 +15,28 @@ DART := $(DART_BIN) APP_PROJECT_ROOT_DIR := $(CURDIR) # Platform detection from uname. PLATFORM ?= $(shell uname -s 2>/dev/null) -PUB_CACHE ?= $(APP_PROJECT_ROOT_DIR)/.pub-cache +# Linux builds use a project-local pub cache so cargo finds the repo-local +# .cargo/config.toml that carries PROTOC through Flutter's filtered hook environment. +# Other targets leave PUB_CACHE unset, so Flutter uses its normal per-user cache +# and `make` and the IDE share native-asset outputs instead of rebuilding them. +LINUX_PUB_CACHE ?= $(APP_PROJECT_ROOT_DIR)/.pub-cache +PUB_CACHE ?= PROTOC_PATH := $(shell which protoc 2>/dev/null) # Toolchain installed for host-side checks/targets. Native-assets crates pick their own # pinned toolchain via rust-toolchain.toml; do not export RUSTUP_TOOLCHAIN globally. RUST_VERSION ?= 1.99.1 -SKIP_NATIVE ?= 0 MACOS_ENV_UNSET = -u LD -u LDFLAGS -u NIX_LDFLAGS -u NIX_CFLAGS_LINK \ -u CFLAGS -u CXXFLAGS -u CPPFLAGS \ -u SDKROOT -u BINDGEN_EXTRA_CLANG_ARGS \ -u IPHONEOS_DEPLOYMENT_TARGET -u TVOS_DEPLOYMENT_TARGET -u WATCHOS_DEPLOYMENT_TARGET \ -u XROS_DEPLOYMENT_TARGET -u XR_DEPLOYMENT_TARGET -MACOS_ENV_SET = MACOSX_DEPLOYMENT_TARGET=12.0 export APP_PROJECT_ROOT_DIR +ifneq ($(strip $(PUB_CACHE)),) export PUB_CACHE +endif -.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos test-mwc build-android android-dev-key build-ios +.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios help: ## Show available commands @echo "Available targets:" @@ -77,6 +82,11 @@ endif ifeq ($(PLATFORM),Darwin) @command -v autoreconf >/dev/null 2>&1 || { echo >&2 "[ERROR] autoconf/autoreconf not installed."; exit 1; } @command -v aclocal >/dev/null 2>&1 || { echo >&2 "[ERROR] automake/aclocal not installed."; exit 1; } +endif +ifeq ($(PLATFORM),Linux) + @command -v python3 >/dev/null 2>&1 || { echo >&2 "[ERROR] python3 not installed (needed to prepare the Linux release bundle)."; exit 1; } + @command -v patchelf >/dev/null 2>&1 || { echo >&2 "[ERROR] patchelf not installed (Ubuntu 24.04: apt-get install patchelf binutils)."; exit 1; } + @command -v readelf >/dev/null 2>&1 || { echo >&2 "[ERROR] readelf not installed (apt-get install binutils)."; exit 1; } endif @echo "[OK] All core CLI requirements found!" @@ -149,7 +159,7 @@ sccache-setup: ## Opt-in: use sccache for the Rust/C builds run by native-asset @echo "also pass CARGO_BUILD_RUSTC_WRAPPER=sccache from the environment. See sccache --show-stats." verify-bom: ## Check the local toolchain and the pinned plugins against stack-bom.toml - @dart tool/verify_bom.dart + @FLUTTER="$(FLUTTER)" $(DART) tool/verify_bom.dart cache-stats: ## Show sccache statistics (hit rate) after a build @command -v sccache >/dev/null 2>&1 || { echo >&2 "[ERROR] sccache not installed."; exit 1; } @@ -163,8 +173,8 @@ clean: ## Remove artifacts and fix permissions @if [ -f "Cargo.toml" ]; then cargo clean; fi @rm -rf macos/Pods macos/Podfile.lock ios/Pods ios/Podfile.lock build/ @echo "Cleaning local pub cache residues..." - @chmod -R u+w $(PUB_CACHE)/git/ 2>/dev/null || true - @find $(PUB_CACHE)/git/ -type d \( -name "build" -o -name "target" \) -path "*flutter_lib*" -exec rm -rf {} + 2>/dev/null || true + @chmod -R u+w $(LINUX_PUB_CACHE)/git/ 2>/dev/null || true + @find $(LINUX_PUB_CACHE)/git/ -type d \( -name "build" -o -name "target" \) -path "*flutter_lib*" -exec rm -rf {} + 2>/dev/null || true @echo "[OK] Project is now in a pristine state." # --- PLATFORM BUILDS --- @@ -172,6 +182,8 @@ clean: ## Remove artifacts and fix permissions PREBUILTS ?= 1 # Linux only: SYSTEM_DEPS=1 uses the system libsecret/jsoncpp packages instead of building them (like the CI image). SYSTEM_DEPS ?= 0 +LINUX_ARCH := $(shell uname -m | sed -e 's/x86_64/x64/' -e 's/aarch64/arm64/') +LINUX_BUNDLE ?= build/linux/$(LINUX_ARCH)/release/bundle clean-app: ## Remove app build output (build/, Pods) but keep the native-asset build outputs, so the next build is fast @chflags -R nouchg build/ macos/ 2>/dev/null || true @@ -185,11 +197,8 @@ clean-native: ## Remove only the native-asset build outputs (forces the Rust/Go/ @echo "[OK] Removed .dart_tool/hooks_runner and build/native_assets." build-macos: check-reqs-macos check-sdk-macos ## Build macOS release (same steps as upstream CI; PREBUILTS=0 compiles native assets from source) - @# pubspec.yaml is generated; build_app.sh only regenerates it from the template when unchanged, - @# so a previous PREBUILTS setting would otherwise stick. - @rm -f pubspec.yaml @echo "--- Configuring project (scripts/build_app.sh)..." - @cd scripts && echo yes | env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a stack_wallet -s $(if $(filter 1,$(PREBUILTS)),-d) + @cd scripts && echo yes | env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a $(APP_NAME) -s $(if $(filter 1,$(PREBUILTS)),-d) @echo "--- Resolving dependencies..." @env $(MACOS_ENV_UNSET) $(FLUTTER) pub get @cd scripts && env $(MACOS_ENV_UNSET) bash prebuild.sh @@ -197,14 +206,6 @@ build-macos: check-reqs-macos check-sdk-macos ## Build macOS release (same steps @env $(MACOS_ENV_UNSET) $(FLUTTER) build macos --release -test-mwc: ## Run MWC FFI integration test on macOS (assumes prior `make build-macos`) - @# Flutter's first-launch helper rewrites MACOSX_DEPLOYMENT_TARGET=10.15; reassert 12.0. - @sed -i.bak -e "s/MACOSX_DEPLOYMENT_TARGET = 10\\.15;/MACOSX_DEPLOYMENT_TARGET = 12.0;/g" -e "s/MACOSX_DEPLOYMENT_TARGET = 11\\.0;/MACOSX_DEPLOYMENT_TARGET = 12.0;/g" macos/Runner.xcodeproj/project.pbxproj 2>/dev/null || true - @rm -f macos/Runner.xcodeproj/project.pbxproj.bak - @chmod -R u+w macos/Runner.xcodeproj macos 2>/dev/null || true - @env $(MACOS_ENV_UNSET) $(MACOS_ENV_SET) \ - $(FLUTTER) test integration_test/mwc_ffi_test.dart -d macos - diagnose-env-macos: ## Print macOS build env and tool resolution @echo "--- Toolchain diagnostics ---" @echo "flutter: $$(command -v $(FLUTTER) || echo missing)" @@ -228,6 +229,7 @@ diagnose-env-macos: ## Print macOS build env and tool resolution @echo "NIX_LDFLAGS=$${NIX_LDFLAGS:-}" @echo "NIX_CFLAGS_LINK=$${NIX_CFLAGS_LINK:-}" +build-linux: export PUB_CACHE := $(LINUX_PUB_CACHE) build-linux: check-reqs ## Build Linux Release through Flutter native-assets hooks @echo "--- Running prebuild bootstrap..." @cd scripts && bash prebuild.sh @@ -247,25 +249,6 @@ build-linux: check-reqs ## Build Linux Release through Flutter native-assets hoo fi @echo "--- Building app..." @$(FLUTTER) pub get - @mkdir -p scripts/linux/pc - @printf '%s\n' \ - 'prefix=$(CURDIR)/scripts/linux/build/libsecret' \ - 'exec_prefix=$${prefix}' \ - 'libdir=$${prefix}/_build/libsecret' \ - 'includedir=$${prefix}' \ - '' \ - 'Name: libsecret-1' \ - 'Description: GObject bindings for Secret Service API' \ - 'Version: 0.21.4' \ - 'Libs: -L$${libdir} -lsecret-1' \ - 'Cflags: -I$${includedir} -I$${includedir}/_build' \ - > scripts/linux/pc/libsecret-1.pc - @if command -v podman >/dev/null 2>&1 || command -v docker >/dev/null 2>&1; then \ - : 'coinlib BuildKit git fetch fails on NixOS; scope the legacy-builder workaround here'; \ - DOCKER_BUILDKIT=0 $(FLUTTER) pub run coinlib:build_linux; \ - else \ - echo "[WARN] podman/docker not found; skipping coinlib:build_linux"; \ - fi @if [ "$(SYSTEM_DEPS)" = "1" ]; then \ USE_SYSTEM_SECURE_STORAGE_DEPS=1 PROTOC="$(PROTOC_PATH)" $(FLUTTER) build linux --release; \ else \ @@ -279,19 +262,19 @@ build-linux: check-reqs ## Build Linux Release through Flutter native-assets hoo PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc:$$SYSPROF_PC_DIR:$$PC_PATH" \ PROTOC="$(PROTOC_PATH)" $(FLUTTER) build linux --release; \ fi + @echo "--- Preparing release bundle..." + @python3 scripts/linux/prepare_release_bundle.py $(LINUX_BUNDLE) # Windows: run from Git Bash. Same steps as the "build-windows" job in .github/workflows/build.yaml. -# WINDOWS_COPY_ASSETS=1 replaces the asset links with copies (needed on runners that cannot create symlinks). +# WINDOWS_COPY_ASSETS=1 makes link_assets.sh copy instead of creating symlinks, for hosts +# where the user cannot create them (for example the GitHub-hosted runner). WINDOWS_COPY_ASSETS ?= 0 build-windows: ## Build Windows release (Git Bash; same steps as CI) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed."; exit 1; } @cd scripts && bash prebuild.sh - @# link_assets.sh (run by build_app.sh) cannot remove the real directories a previous copy run left behind. - @if [ "$(WINDOWS_COPY_ASSETS)" = "1" ]; then bash scripts/windows/replace_asset_links.sh --clean; fi - @cd scripts && echo yes | MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d -s - @if [ "$(WINDOWS_COPY_ASSETS)" = "1" ]; then bash scripts/windows/replace_asset_links.sh; fi + @cd scripts && echo yes | MWEBD_FETCH=1 WINDOWS_COPY_ASSETS=$(WINDOWS_COPY_ASSETS) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d -s @$(FLUTTER) pub get @$(DART) run coinlib:build_windows @$(FLUTTER) build windows --release @@ -323,4 +306,3 @@ build-ios: check-sdk-macos ## Build iOS Runner.app without code signing (same st @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) -d -s @$(FLUTTER) pub get @$(FLUTTER) build ios --release --no-codesign - diff --git a/README.md b/README.md index 8ba586ed7f..1977ed7fae 100644 --- a/README.md +++ b/README.md @@ -68,8 +68,8 @@ Use this only when you are not building through Nix/flake. 1. Install host tools: - `make bootstrap-macos` 2. Run build: - - Open a new terminal (or run `source ~/.zshrc`) so the Homebrew setup's - Rust 1.99.1 selection is active. + - Open a new terminal (or run `source ~/.zshrc`) so the Homebrew and + Flutter PATH entries are active. - `make build-macos` The Homebrew bootstrap installs the native build tools and configures Rust diff --git a/bm/bench.sh b/bm/bench.sh index 8ceb9ad179..b53b2972da 100755 --- a/bm/bench.sh +++ b/bm/bench.sh @@ -70,7 +70,7 @@ DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)" ARCH="$(uname -m)" OS_NAME="$(uname -s)" OS_VER="$(uname -r)" -echo "Benchmark: ${LABEL}" | banner +echo "Benchmark: ${LABEL}" | banner echo "Host: $HOST" echo "OS: $OS_NAME $OS_VER ($ARCH)" echo "Branch: $BRANCH" @@ -80,16 +80,16 @@ echo "Flags: ${MAKE_FLAGS:-(none)}" echo "" # Disk before -DISK_BEFORE=$(du -sk . 2>/dev/null | cut -f1) +DISK_BEFORE=$(du -sk . 2>/dev/null | cut -f1 || echo 0) # Clean unless warm if [ $WARM -eq 0 ]; then - echo "Cleaning" | banner + echo "Cleaning" | banner make clean 2>&1 | tail -1 fi # Build -echo "Building: make ${BUILD_TARGET} ${MAKE_FLAGS} " | banner +echo "Building: make ${BUILD_TARGET} ${MAKE_FLAGS} " | banner sccache --zero-stats >/dev/null 2>&1 || true START=$(date +%s) # A failing build must still be timed and recorded, so errexit is off for the build and its status is taken from make. @@ -103,11 +103,11 @@ WALL=$((END - START)) # Disk after SCC_NOTE="" if command -v sccache >/dev/null 2>&1; then - SCC_REQ=$(sccache --show-stats 2>/dev/null | awk '/^Compile requests executed/ {print $NF}') - SCC_HIT=$(sccache --show-stats 2>/dev/null | awk '/^Cache hits / {print $NF}') + SCC_REQ=$(sccache --show-stats 2>/dev/null | awk '/^Compile requests executed/ {print $NF}' || echo 0) + SCC_HIT=$(sccache --show-stats 2>/dev/null | awk '/^Cache hits / {print $NF}' || echo 0) [ -n "${SCC_REQ:-}" ] && [ "${SCC_REQ:-0}" != "0" ] && SCC_NOTE="sccache ${SCC_HIT:-0}/${SCC_REQ} hits" fi -DISK_AFTER=$(du -sk . 2>/dev/null | cut -f1) +DISK_AFTER=$(du -sk . 2>/dev/null | cut -f1 || echo 0) DISK_DELTA=$((DISK_AFTER - DISK_BEFORE)) # Write CSV header if new file @@ -124,7 +124,7 @@ if [ $RC -eq 0 ]; then else echo "✗ Build FAILED after ${WALL}s" fi -echo "Results appended: $OUTFILE" | banner +echo "Results appended: $OUTFILE" | banner # Show all runs echo "" diff --git a/bm/compare.py b/bm/compare.py index b41fb56c89..d43462502d 100755 --- a/bm/compare.py +++ b/bm/compare.py @@ -7,10 +7,9 @@ python3 bm/compare.py bm/results/ > report.md # markdown for bm/render.sh """ -import csv, sys, os, json +import csv, sys, os from collections import defaultdict from pathlib import Path -from statistics import mean, stdev, median PIPE = "│" diff --git a/bm/render.sh b/bm/render.sh index b27d83256f..3df37e33b0 100755 --- a/bm/render.sh +++ b/bm/render.sh @@ -56,6 +56,8 @@ else echo " ⚠ No PDF engine found. HTML ready: $HTML_FILE" fi -[ "$OPEN" -eq 1 ] && open "$PDF_FILE" 2>/dev/null || open "$HTML_FILE" 2>/dev/null || true +if [ "$OPEN" -eq 1 ]; then + open "$PDF_FILE" 2>/dev/null || open "$HTML_FILE" 2>/dev/null || true +fi -echo "Done." \ No newline at end of file +echo "Done." diff --git a/bm/run_all.sh b/bm/run_all.sh index 49bd674107..098b7c9188 100755 --- a/bm/run_all.sh +++ b/bm/run_all.sh @@ -36,6 +36,9 @@ echo "D: warm, from source" bash bm/bench.sh --warm PREBUILTS=0 echo "" +echo "Collecting disk and artifact sizes..." +bash bm/collect.sh || true +echo "" echo "Done. Results: bm/results/$HOST.csv" echo "View: python3 bm/compare.py bm/results/" echo "PDF: python3 bm/compare.py bm/results/ > report.md && ./bm/render.sh report.md" diff --git a/flake.nix b/flake.nix index 6fa8289522..b36de7dfa4 100644 --- a/flake.nix +++ b/flake.nix @@ -14,6 +14,7 @@ let pkgs = import nixpkgs { inherit system; }; lib = pkgs.lib; + rustVersion = "1.99.1"; commonPackages = with pkgs; [ flutter @@ -40,10 +41,12 @@ opencv sysprof libsysprof-capture + patchelf + binutils ]); macPackages = lib.optionals pkgs.stdenv.isDarwin (with pkgs; [ - cocoapods + cocoapods libiconv autoconf automake @@ -60,27 +63,28 @@ echo "Stack Wallet Dev-Environment activated!" echo "Target System: ${system}" echo "===================================================" - + export APP_PROJECT_ROOT_DIR=$(pwd) export PATH="$HOME/.cargo/bin:$PATH" # The standalone Dart in the Nix Flutter wrapper cannot find the Flutter SDK on its own, # so `dart run`/`dart pub` in a Flutter project fail ("Flutter users should use flutter pub"). export FLUTTER_ROOT="$(dirname "$(dirname "$(readlink -f "$(command -v flutter)")")")" - + # ========================================== # RUST TOOLCHAIN AUTOMATION # Host Rust toolchain; native-assets crates select their own pinned toolchain. # ========================================== - if ! rustup toolchain list | grep -q "1.99.1"; then + if ! rustup toolchain list | grep -q "${rustVersion}"; then echo "Initializing Rust toolchain (this happens only once)..." - rustup toolchain install --no-self-update 1.99.1 + rustup toolchain install --no-self-update ${rustVersion} fi - rustup default 1.99.1 - + # Pin this checkout without replacing the user's global rustup default. + rustup override set ${rustVersion} --path "$PWD" >/dev/null 2>&1 || true + if [[ "${system}" == *"darwin"* ]]; then - rustup target add aarch64-apple-darwin aarch64-apple-ios --toolchain 1.99.1 + rustup target add aarch64-apple-darwin aarch64-apple-ios --toolchain ${rustVersion} fi if ! command -v cargo-ndk >/dev/null 2>&1; then @@ -121,7 +125,7 @@ export DEVELOPER_DIR="$(env -u DEVELOPER_DIR xcode-select -p 2>/dev/null || echo /Applications/Xcode.app/Contents/Developer)" export SDKROOT=$(xcrun --sdk macosx --show-sdk-path) export MACOSX_DEPLOYMENT_TARGET="12.0" - + # --- NIX C++ COMPILER OVERRIDE --- export CC=/usr/bin/clang export CXX=/usr/bin/clang++ @@ -131,8 +135,8 @@ export NM=/usr/bin/nm export RANLIB=/usr/bin/ranlib export STRIP=/usr/bin/strip - - export BINDGEN_EXTRA_CLANG_ARGS="-isysroot $SDKROOT" + + export BINDGEN_EXTRA_CLANG_ARGS="-isysroot $SDKROOT" export PROTOC="${pkgs.protobuf}/bin/protoc" mkdir -p .nix-bin @@ -141,7 +145,7 @@ ln -sf /usr/bin/xcodebuild .nix-bin/xcodebuild ln -sf /usr/bin/clang .nix-bin/clang ln -sf /usr/bin/clang++ .nix-bin/clang++ - + # SMART LIPO & XCRUN WRAPPER # lipo wrapper: the Nix store copy of FlutterMacOS.framework is # read-only, so make its containing dir writable before handing diff --git a/integration_test/mwc_ffi_test.dart b/integration_test/mwc_ffi_test.dart deleted file mode 100644 index 50bcb3b074..0000000000 --- a/integration_test/mwc_ffi_test.dart +++ /dev/null @@ -1,20 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:integration_test/integration_test.dart'; - -import 'mwc_ffi_test_service.dart'; - -void main() { - IntegrationTestWidgetsFlutterBinding.ensureInitialized(); - testWidgets('MWC FFI smoke', (tester) async { - await FFITestService.initialize(); - final ok = await FFITestService.runAllTests(); - expect( - ok, - isTrue, - reason: FFITestService.testResults - .where((r) => !r.passed) - .map((r) => '${r.name}: ${r.error}') - .join('\n'), - ); - }); -} diff --git a/integration_test/mwc_ffi_test_service.dart b/integration_test/mwc_ffi_test_service.dart deleted file mode 100644 index 5fd915d345..0000000000 --- a/integration_test/mwc_ffi_test_service.dart +++ /dev/null @@ -1,1028 +0,0 @@ -import 'dart:io'; -import 'dart:async'; -import 'dart:convert'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter_libmwc/lib.dart'; -import 'package:flutter_libmwc/mwc.dart' as lib_mwc; -import 'package:path_provider/path_provider.dart'; - -import 'mwc_test_result.dart'; - -/// Comprehensive FFI integration test service. -class FFITestService { - static final List _testResults = []; - static bool _isInitialized = false; - - /// Initialize the test framework. - static Future initialize() async { - if (_isInitialized) return; - - _logInfo('FFI Test Service initialized successfully'); - _isInitialized = true; - } - - /// Get all test results. - static List get testResults => List.unmodifiable(_testResults); - - /// Clear all test results. - static void clearResults() { - _testResults.clear(); - _logInfo('Test results cleared'); - } - - /// Run all FFI integration tests. - static Future runAllTests() async { - if (!_isInitialized) { - throw StateError('FFI Test Service not initialized'); - } - - clearResults(); - _logInfo('Starting comprehensive FFI integration test suite'); - - bool allPassed = true; - - // Phase 1: Environment and pre-flight validation. - allPassed &= await _runEnvironmentTests(); - - // Phase 2: Basic FFI functionality. - allPassed &= await _runBasicFFITests(); - - // Phase 3: Wallet management tests. - allPassed &= await _runWalletManagementTests(); - - // Phase 4: Transaction functionality tests. - allPassed &= await _runTransactionTests(); - - // Phase 5: Basic slatepack functionality tests. - allPassed &= await _runSlatepackTests(); - - // Phase 6: MWCMQS listener functionality tests. - allPassed &= await _runMWCMQSTests(); - - _logInfo( - 'Test suite completed. Overall result: ${allPassed ? "PASS" : "FAIL"}', - ); - return allPassed; - } - - /// Run environment validation tests. - static Future _runEnvironmentTests() async { - bool allPassed = true; - - // Test 1: Platform detection. - allPassed &= await _runTest( - 'Platform Detection', - 'Verify current platform is correctly detected', - () async { - final platform = Platform.operatingSystem; - final supportedPlatforms = [ - 'linux', - 'windows', - 'macos', - 'android', - 'ios', - ]; - - if (!supportedPlatforms.contains(platform)) { - throw TestException('Unsupported platform: $platform'); - } - - return 'Platform: $platform (supported)'; - }, - ); - - // Test 2: Library loading. - allPassed &= await _runTest( - 'Library Loading', - 'Verify native library can be loaded', - () async { - try { - final mnemonic = Libmwc.getMnemonic(); - if (mnemonic.isEmpty) { - throw TestException( - 'Library loaded but basic function returned empty result', - ); - } - return 'Library loaded successfully, basic function operational'; - } catch (e) { - throw TestException('Failed to load or call native library: $e'); - } - }, - ); - - return allPassed; - } - - /// Run basic FFI functionality tests. - static Future _runBasicFFITests() async { - bool allPassed = true; - - // Test 1: Mnemonic generation. - allPassed &= await _runTest( - 'Mnemonic Generation', - 'Test FFI mnemonic generation function', - () async { - final mnemonic = Libmwc.getMnemonic(); - final words = mnemonic.split(' '); - - if (words.length != 24) { - throw TestException( - 'Invalid mnemonic length: ${words.length} (expected 24)', - ); - } - - return 'Generated 24-word mnemonic successfully'; - }, - ); - - // Test 2: Address validation. - allPassed &= await _runTest( - 'Address Validation', - 'Test FFI address validation function', - () async { - // Test with known invalid address. - final invalidResult = Libmwc.validateSendAddress( - address: 'invalid_address', - ); - if (invalidResult) { - throw TestException('Invalid address incorrectly validated as valid'); - } - - return 'Address validation working correctly'; - }, - ); - - return allPassed; - } - - /// Run wallet management integration tests. - static Future _runWalletManagementTests() async { - bool allPassed = true; - - // Test 1: Wallet configuration validation. - allPassed &= await _runTest( - 'Wallet Configuration', - 'Test wallet configuration creation and validation', - () async { - final testConfig = await _getTestWalletConfig(); - if (testConfig.isEmpty) { - throw TestException('Failed to create test wallet configuration'); - } - - // Validate config contains required fields. - final configData = { - 'wallet_dir': '', - 'check_node_api_http_addr': '', - 'chain': '', - }; - for (final key in configData.keys) { - if (!testConfig.contains(key)) { - throw TestException('Missing required config field: $key'); - } - } - - return 'Test wallet configuration created and validated successfully'; - }, - ); - - // Test 2: Wallet initialization. - allPassed &= await _runTest( - 'Wallet Initialization', - 'Test new wallet creation via FFI', - () async { - final testMnemonic = Libmwc.getMnemonic(); - final testConfig = await _getTestWalletConfig(); - final testPassword = 'test_password_123'; - final walletName = - 'ffi_test_wallet_${DateTime.now().millisecondsSinceEpoch}'; - - try { - final result = await Libmwc.initializeNewWallet( - config: testConfig, - mnemonic: testMnemonic, - password: testPassword, - name: walletName, - ); - - if (result.toUpperCase().contains('ERROR')) { - throw TestException('Wallet initialization failed: $result'); - } - - return 'New wallet initialized successfully: $walletName'; - } catch (e) { - // Expected to potentially fail if wallet already exists or other issues. - if (e.toString().contains('already exists')) { - return 'Wallet initialization handled existing wallet correctly'; - } - rethrow; - } - }, - ); - - // Test 3: Wallet recovery. - allPassed &= await _runTest( - 'Wallet Recovery', - 'Test wallet recovery from mnemonic via FFI', - () async { - final testMnemonic = Libmwc.getMnemonic(); - final testConfig = await _getTestWalletConfig(); - final testPassword = 'recovery_test_123'; - final walletName = - 'ffi_recovery_test_${DateTime.now().millisecondsSinceEpoch}'; - - try { - await Libmwc.recoverWallet( - config: testConfig, - password: testPassword, - mnemonic: testMnemonic, - name: walletName, - ); - - return 'Wallet recovery from mnemonic completed successfully'; - } catch (e) { - // Expected to potentially fail in test environment. - if (e.toString().contains('directory') || - e.toString().contains('permission')) { - return 'Wallet recovery handled filesystem constraints correctly'; - } - throw TestException('Unexpected error in wallet recovery: $e'); - } - }, - ); - - // Test 4: Chain height retrieval. - allPassed &= await _runTest('Chain Height Query', 'Test chain height retrieval via FFI using remote MWC node', () async { - final testConfig = await _getTestWalletConfig(); - - try { - final height = await Libmwc.getChainHeight(config: testConfig); - - if (height < 0) { - throw TestException('Invalid chain height returned: $height'); - } - - // Mainnet should have a reasonable height (over 1 million blocks as of 2024). - if (height < 1000000) { - throw TestException( - 'Chain height seems too low for mainnet: $height', - ); - } - - return 'Chain height retrieved successfully: $height (mainnet)'; - } catch (e) { - final errorStr = e.toString(); - - // Handle specific error types with more detail. - if (errorStr.contains('FormatException') || - errorStr.contains('Invalid radix-10')) { - throw TestException( - 'Failed to parse chain height response: node may have returned an error message instead of height', - ); - } else if (errorStr.contains('connection') || - errorStr.contains('network') || - errorStr.contains('timeout')) { - throw TestException( - 'Network connection issue with remote node: ${errorStr.substring(0, 100)}...', - ); - } else if (errorStr.contains('Cannot m')) { - throw TestException( - 'Remote node connection failed - possibly network or SSL issue', - ); - } - - // Re-throw with more context. - throw TestException( - 'Chain height query failed: ${errorStr.substring(0, 100)}...', - ); - } - }); - - return allPassed; - } - - static Future _runTransactionTests() async { - bool allPassed = true; - - // Test 1: Transaction function availability. - allPassed &= await _runTest('Transaction Function Availability', 'Verify transaction functions are available via FFI', () async { - // Test that transaction functions exist and can be called. - // This validates the FFI bindings are working without requiring an actual wallet. - - try { - // First test: Validate address format function (should not panic). - final isValid = Libmwc.validateSendAddress(address: 'test@example.com'); - - // This should return false for a test address, but validates the function works. - if (isValid == true || isValid == false) { - return 'Transaction functions available: address validation working (result: $isValid)'; - } - - throw TestException('Address validation returned unexpected result'); - } catch (e) { - final errorStr = e.toString(); - - // Any error here indicates a problem with the FFI bindings themselves. - throw TestException( - 'Transaction function availability test failed: ${errorStr.substring(0, 100)}...', - ); - } - }); - - // Test 2: Transaction API Structure Validation. - allPassed &= await _runTest('Transaction API Structure', 'Validate transaction-related API structure and types', () async { - try { - // Test that we can create test configuration without errors. - final testConfig = await _getTestWalletConfig(); - - if (!testConfig.contains('wallet_dir') || - !testConfig.contains('check_node_api_http_addr') || - !testConfig.contains('chain')) { - throw TestException('Test configuration missing required fields'); - } - - // Test basic type validation. - const testAmount = 1000000; - const minConfirmations = 10; - - if (testAmount <= 0 || minConfirmations <= 0) { - throw TestException('Transaction parameter validation failed'); - } - - return 'Transaction API structure validation passed: config format and parameter types correct'; - } catch (e) { - throw TestException( - 'Transaction API structure test failed: ${e.toString().substring(0, 100)}...', - ); - } - }); - - // Test 3: Transaction Model Validation. - allPassed &= await _runTest('Transaction Model Validation', 'Validate transaction data models and type safety', () async { - try { - // Test transaction model structure by creating instances. - // This validates the Dart-side transaction types without calling FFI. - - final testAmount = 1500000; // 0.0015 MWC. - final testAddress = 'test_user@mwcmqs.example.com'; - final testNote = 'FFI integration test transaction'; - - // Validate parameter constraints. - if (testAmount <= 0) { - throw TestException('Transaction amount validation failed'); - } - - if (testAddress.isEmpty || !testAddress.contains('@')) { - throw TestException('Transaction address validation failed'); - } - - if (testNote.length > 500) { - throw TestException('Transaction note length validation failed'); - } - - return 'Transaction model validation passed: amount=$testAmount, address format validated, note length OK'; - } catch (e) { - throw TestException( - 'Transaction model validation failed: ${e.toString().substring(0, 100)}...', - ); - } - }); - - // Test 4: Transaction Error Code Validation. - allPassed &= await _runTest('Transaction Error Handling', 'Validate transaction error handling patterns', () async { - try { - // Test error message patterns that should be handled by transaction functions. - final expectedErrors = [ - 'wallet is not open', - 'WALLET_IS_NOT_OPEN', - 'insufficient funds', - 'invalid address', - 'network error', - 'connection timeout', - ]; - - // Validate we have error handling patterns for common issues. - for (final errorPattern in expectedErrors) { - if (errorPattern.isEmpty) { - throw TestException('Empty error pattern in validation list'); - } - } - - // Test amount boundary validation. - const minAmount = 1; - const maxAmount = 21000000 * 1000000000; // Max MWC supply in nanograms. - - if (minAmount >= maxAmount) { - throw TestException('Transaction amount boundary validation failed'); - } - - return 'Transaction error handling validation passed: ${expectedErrors.length} error patterns validated, amount boundaries correct'; - } catch (e) { - throw TestException( - 'Transaction error handling validation failed: ${e.toString().substring(0, 100)}...', - ); - } - }); - - return allPassed; - } - - /// Run basic slatepack functionality integration tests. - static Future _runSlatepackTests() async { - bool allPassed = true; - - // Test 1: Slatepack API Structure Validation. - allPassed &= await _runTest('Slatepack API Structure', 'Validate slatepack API structure and parameter types', () async { - try { - // Test basic slatepack parameter validation. - const testSlateJson = - '{"id":"test","tx":{"body":{"inputs":[],"outputs":[],"kernels":[]}}}'; - const testSlatepack = - 'BEGINSLATEPACK. test slatepack data .ENDSLATEPACK'; - const testRecipientAddress = 'test_user@mwcmqs.example.com'; - - // Validate parameter constraints for encoding. - if (testSlateJson.isEmpty) { - throw TestException('Slate JSON validation failed'); - } - - if (!testSlateJson.contains('id')) { - throw TestException('Slate JSON structure validation failed'); - } - - // Validate slatepack format structure. - if (!testSlatepack.contains('BEGINSLATEPACK') || - !testSlatepack.contains('ENDSLATEPACK')) { - throw TestException('Slatepack format validation failed'); - } - - // Validate address format. - if (testRecipientAddress.isEmpty || - !testRecipientAddress.contains('@')) { - throw TestException('Recipient address format validation failed'); - } - - return 'Slatepack API structure validation passed: slate format, slatepack format, and address format correct'; - } catch (e) { - throw TestException( - 'Slatepack API structure test failed: ${e.toString().substring(0, 100)}...', - ); - } - }); - - // Test 2: Slatepack Format Validation. - allPassed &= await _runTest('Slatepack Format Validation', 'Validate slatepack format patterns and structure', () async { - try { - // Test various slatepack format patterns. - final validFormats = [ - 'BEGINSLATEPACK. test data .ENDSLATEPACK', - 'BEGINSLATEPACK.\nencoded_data_here\n.ENDSLATEPACK', - 'BEGINSLATEPACK. VGVzdCBkYXRh .ENDSLATEPACK', // Base64-like. - ]; - - final invalidFormats = [ - 'INVALID FORMAT', - 'BEGINSLATEPACK without end', - 'missing begin ENDSLATEPACK', - '', - 'BEGINSLATE PACK. test .ENDSLATEPACK', // Wrong format. - ]; - - // Validate all valid formats pass basic structure check. - for (final format in validFormats) { - if (!format.contains('BEGINSLATEPACK') || - !format.contains('ENDSLATEPACK')) { - throw TestException( - 'Valid slatepack format failed validation: $format', - ); - } - } - - // Validate all invalid formats fail basic structure check. - for (final format in invalidFormats) { - if (format.contains('BEGINSLATEPACK') && - format.contains('ENDSLATEPACK')) { - throw TestException( - 'Invalid slatepack format passed validation: $format', - ); - } - } - - return 'Slatepack format validation passed: ${validFormats.length} valid formats recognized, ${invalidFormats.length} invalid formats rejected'; - } catch (e) { - throw TestException( - 'Slatepack format validation failed: ${e.toString().substring(0, 100)}...', - ); - } - }); - - // Test 3: Slatepack Roundtrip (compact, unencrypted). - allPassed &= await _runTest('Slatepack Roundtrip (compact)', 'Encode compact slate JSON to slatepack and decode back via FFI', () async { - try { - // Construct a minimal compact slate JSON. - // Use version 3 + compact_slate flag to satisfy current lib expectations. - const compactSlateJson = - '{\n' - ' "version_info": {\n' - ' "orig_version": 3,\n' - ' "version": 3,\n' - ' "block_header_version": 1\n' - ' },\n' - ' "id": "0436430c-2b02-624c-2032-570501212b00",\n' - ' "sta": "S1",\n' - ' "num_participants": 2,\n' - ' "amount": "1000000000",\n' - ' "fee": "1000000",\n' - ' "height": "0",\n' - ' "lock_height": "0",\n' - ' "ttl_cutoff_height": "1440",\n' - ' "payment_proof": null,\n' - ' "compact_slate": true,\n' - ' "participant_data": []\n' - '}'; - - // Encode to slatepack (unencrypted) — recipientAddress null. - final enc = await Libmwc.encodeSlatepack( - slateJson: compactSlateJson, - recipientAddress: null, - encrypt: false, - ); - - // Basic format assertions. - if (!enc.slatepack.contains('BEGINSLATEPACK') || - !enc.slatepack.contains('ENDSLATEPACK')) { - throw TestException('Encoded slatepack missing BEGIN/END markers'); - } - if (enc.wasEncrypted) { - throw TestException('Unencrypted encode reported as encrypted'); - } - - // Decode back to JSON. - final dec = await Libmwc.decodeSlatepack(slatepack: enc.slatepack); - final decoded = jsonDecode(dec.slateJson) as Map; - final decodedId = decoded['id'] as String?; - final versionInfo = decoded['version_info'] as Map?; - if (decodedId != '0436430c-2b02-624c-2032-570501212b00') { - throw TestException( - 'Decoded slate id mismatch or missing: $decodedId', - ); - } - if (versionInfo == null || versionInfo['version'] != 3) { - throw TestException('Decoded slate version is not v3'); - } - - // Verify encryption detection helper. - final isEncrypted = await Libmwc.isSlatepackEncrypted(enc.slatepack); - if (isEncrypted) { - throw TestException( - 'isSlatepackEncrypted returned true for unencrypted slatepack', - ); - } - - return 'Roundtrip succeeded; id=$decodedId; v4 compact; markers present; not encrypted'; - } catch (e) { - throw TestException('Slatepack roundtrip (compact) failed: $e'); - } - }); - - // Test 4: Slatepack Encryption Requirements (expected failure without wallet context). - allPassed &= await _runTest( - 'Slatepack Encryption Requirements', - 'Verify encrypted encode requires wallet context and recipient', - () async { - try { - bool threw = false; - try { - await Libmwc.encodeSlatepack( - slateJson: '{"id":"abc","version_info":{"version":3,"block_header_version":1}}', - recipientAddress: 'dummy@mwcmqs.mwc.mw', - encrypt: true, - wallet: null, // No wallet context in test environment - ); - } catch (e) { - threw = true; - final msg = e.toString(); - if (!msg.toLowerCase().contains('wallet') || - !msg.toLowerCase().contains('required')) { - throw TestException( - 'Unexpected error for encrypted encode without wallet: $msg', - ); - } - } - if (!threw) { - throw TestException( - 'Encrypted encode did not throw without wallet context', - ); - } - return 'Encrypted encode correctly requires wallet context'; - } catch (e) { - throw TestException('Encryption requirement validation failed: $e'); - } - }, - ); - - // Test 5: Slatepack Decode Invalid Format Handling. - allPassed &= await _runTest( - 'Slatepack Decode Invalid Format', - 'Decode invalid slatepack and validate graceful handling', - () async { - try { - final bogus = 'NOT_A_SLATEPACK'; - String? slateJson; - Object? decodeError; - try { - final dec = await Libmwc.decodeSlatepack(slatepack: bogus); - slateJson = dec.slateJson; - } catch (e) { - decodeError = e; - } - // If the decoder throws, that's also acceptable as graceful failure. - if (decodeError != null) { - final es = decodeError.toString(); - final trunc = es.substring(0, es.length < 80 ? es.length : 80); - return 'Invalid slatepack decode threw as expected: $trunc...'; - } - // High-level API may not throw; validate empty slate JSON returned. - // Outside the catch above, so a failed assertion fails the test. - if (slateJson!.isNotEmpty) { - throw TestException( - 'Invalid slatepack returned non-empty slate JSON', - ); - } - return 'Invalid slatepack handled gracefully (empty slate JSON)'; - } catch (e) { - throw TestException('Invalid format handling failed: $e'); - } - }, - ); - - // Test 3: Slatepack Encoding Parameter Validation. - allPassed &= await _runTest('Slatepack Encoding Parameters', 'Validate slatepack encoding parameter handling', () async { - try { - // Test encoding parameter validation without calling actual FFI. - final testCases = [ - { - 'name': 'basic slate', - 'slateJson': '{"id":"test-123","version_info":{"version":3,"block_header_version":1}}', - 'encrypt': false, - 'recipientAddress': null, - }, - { - 'name': 'encrypted slate', - 'slateJson': '{"id":"test-456","version_info":{"version":3,"block_header_version":1}}', - 'encrypt': true, - 'recipientAddress': 'user@mwcmqs.example.com', - }, - ]; - - for (final testCase in testCases) { - final slateJson = testCase['slateJson'] as String; - final encrypt = testCase['encrypt'] as bool; - final recipientAddress = testCase['recipientAddress'] as String?; - - // Validate slate JSON structure. - if (!slateJson.contains('id')) { - throw TestException( - 'Test case ${testCase['name']} missing required slate ID', - ); - } - - // Validate encryption parameters. - if (encrypt && - (recipientAddress == null || recipientAddress.isEmpty)) { - throw TestException( - 'Test case ${testCase['name']} encryption requires recipient address', - ); - } - - // Validate address format if provided. - if (recipientAddress != null && !recipientAddress.contains('@')) { - throw TestException( - 'Test case ${testCase['name']} invalid recipient address format', - ); - } - } - - return 'Slatepack encoding parameter validation passed: ${testCases.length} test cases validated'; - } catch (e) { - throw TestException( - 'Slatepack encoding parameter validation failed: ${e.toString().substring(0, 100)}...', - ); - } - }); - - // Test 4: Slatepack Decoding Parameter Validation. - allPassed &= await _runTest('Slatepack Decoding Parameters', 'Validate slatepack decoding parameter handling and response structure', () async { - try { - // Test decoding parameter validation and expected response structure. - final testSlatepack = 'BEGINSLATEPACK. dGVzdCBkYXRh .ENDSLATEPACK'; - - // Validate slatepack format. - if (!testSlatepack.contains('BEGINSLATEPACK') || - !testSlatepack.contains('ENDSLATEPACK')) { - throw TestException('Test slatepack format validation failed'); - } - - // Define expected decode response structure. - final expectedFields = [ - 'slate_json', - 'sender', // nullable. - 'recipient', // nullable. - ]; - - // Validate we have proper validation for expected response fields. - for (final field in expectedFields) { - if (field.isEmpty) { - throw TestException('Empty expected field in validation list'); - } - } - - // Test decoding error scenarios. - final errorTestCases = [ - {'input': '', 'expectedError': 'empty slatepack'}, - {'input': 'INVALID FORMAT', 'expectedError': 'invalid format'}, - { - 'input': 'BEGINSLATEPACK. corrupted_data .ENDSLATEPACK', - 'expectedError': 'decoding error', - }, - ]; - - // Validate error cases are properly structured. - for (final testCase in errorTestCases) { - final input = testCase['input'] as String; - final expectedError = testCase['expectedError'] as String; - - if (input.isEmpty && expectedError != 'empty slatepack') { - throw TestException( - 'Error test case mismatch: empty input should expect empty slatepack error', - ); - } - } - - return 'Slatepack decoding parameter validation passed: ${expectedFields.length} response fields validated, ${errorTestCases.length} error cases structured'; - } catch (e) { - throw TestException( - 'Slatepack decoding parameter validation failed: ${e.toString().substring(0, 100)}...', - ); - } - }); - - return allPassed; - } - - /// Run MWCMQS listener functionality integration tests. - static Future _runMWCMQSTests() async { - bool allPassed = true; - - // Test 1: MWCMQS API Function Availability. - allPassed &= await _runTest('MWCMQS API Function Availability', 'Verify MWCMQS FFI functions are properly loaded and accessible', () async { - try { - // Test that we can access the MWCMQS FFI functions through the native library. - // Try to call the FFI functions with test parameters to verify they're accessible. - - // Verify the mwcMqsListenerStart function exists by trying to call it. - try { - final testWallet = '[test_handle]'; - final testConfig = '{"test":"config"}'; - // This will likely fail but confirms the function is accessible. - lib_mwc.mwcMqsListenerStart(testWallet, testConfig); - return 'MWCMQS FFI functions verified: mwcMqsListenerStart accessible and callable'; - } catch (functionError) { - // Expected to fail with invalid parameters, but function should be accessible. - if (functionError.toString().contains('NoSuchMethodError')) { - throw TestException( - 'MWCMQS start function not available: ${functionError.toString()}', - ); - } - return 'MWCMQS FFI functions verified: mwcMqsListenerStart accessible (failed with expected error: ${functionError.toString().substring(0, 50)}...)'; - } - } catch (e) { - throw TestException( - 'MWCMQS API function availability test failed: ${e.toString()}', - ); - } - }); - - // Test 2: MWCMQS Listener Configuration. - allPassed &= await _runTest( - 'MWCMQS Listener Configuration', - 'Test MWCMQS configuration JSON creation and validation', - () async { - try { - // Create a MWCMQS configuration. - final mwcmqsConfig = jsonEncode({ - 'mwcmqs_domain': 'mqs.mwc.mw', - 'mwcmqs_port': 443, - 'mwcmqs_use_ssl': true, - }); - - // Validate configuration can be parsed. - final configData = jsonDecode(mwcmqsConfig); - if (configData['mwcmqs_domain'] != 'mqs.mwc.mw' || - configData['mwcmqs_port'] != 443 || - configData['mwcmqs_use_ssl'] != true) { - throw TestException('MWCMQS configuration validation failed'); - } - - return 'MWCMQS configuration created and validated: $mwcmqsConfig'; - } catch (e) { - throw TestException( - 'MWCMQS configuration test failed: ${e.toString()}', - ); - } - }, - ); - - // Test 3: MWCMQS Listener Start/Stop API. - allPassed &= await _runTest('MWCMQS Listener Start/Stop API', 'Test MWCMQS listener API accessibility and parameter validation', () async { - try { - // Test that the MWCMQS functions are accessible and accept parameters correctly. - // We'll test with invalid parameters to avoid network calls that might crash. - - // Test listener start function accessibility. - try { - // Use clearly invalid parameters that should trigger a controlled error. - final invalidWallet = 'invalid_wallet_handle'; - final invalidConfig = '{"invalid": "config"}'; - - // This should fail gracefully with a parameter error, not crash. - final result = lib_mwc.mwcMqsListenerStart( - invalidWallet, - invalidConfig, - ); - - // If we get a result without crashing, that's unexpected but good. - return 'MWCMQS listener API accessible: start function callable, returned pointer ${result.address}'; - } catch (apiError) { - // We expect this to fail with invalid parameters, which is good. - // Check that it's a controlled error, not a crash. - final errorString = apiError.toString(); - - if (errorString.contains('invalid') || - errorString.contains('parameter') || - errorString.contains('format') || - errorString.contains('parse') || - errorString.contains('wallet') || - errorString.contains('config')) { - return 'MWCMQS listener API validated: start function accessible and properly validates parameters (error: ${errorString.substring(0, 60)}...)'; - } - - // If it's some other error, that's still validation that the function exists. - return 'MWCMQS listener API accessible: start function exists and callable (failed with: ${errorString.substring(0, 60)}...)'; - } - } catch (e) { - throw TestException('MWCMQS listener API test failed: ${e.toString()}'); - } - }); - - // Test 4: MWCMQS High-Level API Integration. - allPassed &= await _runTest('MWCMQS High-Level API Integration', 'Test high-level ListenerManager API for MWCMQS functionality', () async { - try { - // Test that Libmwc MWCMQS functions are accessible. - // We can't check if methods are null, so we'll try to call them. - try { - // Try to access the methods - this will throw if they don't exist. - final startMethod = Libmwc.startMwcMqsListener; - final stopMethod = Libmwc.stopMwcMqsListener; - - // If we get here, methods exist. - } catch (methodError) { - throw TestException( - 'Libmwc MWCMQS methods not available: ${methodError.toString()}', - ); - } - - // Test high-level API call structure. - try { - // This should fail gracefully since we don't have a real wallet/server. - Libmwc.startMwcMqsListener( - wallet: '[test_wallet_handle]', - mwcmqsConfig: jsonEncode({ - 'mwcmqs_domain': 'mqs.mwc.mw', - 'mwcmqs_port': 443, - 'mwcmqs_use_ssl': true, - }), - ); - - // If we get here, the API call structure is correct. - return 'MWCMQS high-level API integration validated: Libmwc methods accessible and callable'; - } catch (apiError) { - // Expected to fail without real wallet, but validates API structure. - if (apiError.toString().contains('handle') || - apiError.toString().contains('wallet') || - apiError.toString().contains('connection') || - apiError.toString().contains('invalid')) { - return 'MWCMQS high-level API structure validated (expected failure without real wallet): ${apiError.toString().substring(0, 80)}...'; - } - throw apiError; - } - } catch (e) { - throw TestException( - 'MWCMQS high-level API integration test failed: ${e.toString()}', - ); - } - }); - - return allPassed; - } - - /// Get test wallet configuration. - static Future _getTestWalletConfig() async { - final walletDir = await _getTestWalletDir(); - final config = { - 'wallet_dir': walletDir, - 'check_node_api_http_addr': - 'https://mwc713.mwc.mw:443', // Working remote node. - 'chain': 'mainnet', // Use mainnet since remote node is mainnet. - 'account': 'default', - }; - - return '{"wallet_dir":"${config['wallet_dir']}","check_node_api_http_addr":"${config['check_node_api_http_addr']}","chain":"${config['chain']}","account":"${config['account']}"}'; - } - - /// Run a single test with proper error handling and result tracking. - static Future _runTest( - String name, - String description, - Future Function() testFunction, - ) async { - _logInfo('Running test: $name'); - - final stopwatch = Stopwatch()..start(); - - try { - final result = await testFunction(); - stopwatch.stop(); - - _testResults.add( - TestResult( - name: name, - description: description, - passed: true, - duration: stopwatch.elapsed, - result: result, - ), - ); - - _logInfo('Test PASSED: $name (${stopwatch.elapsedMilliseconds}ms)'); - return true; - } catch (e, stackTrace) { - stopwatch.stop(); - - _testResults.add( - TestResult( - name: name, - description: description, - passed: false, - duration: stopwatch.elapsed, - error: e.toString(), - stackTrace: stackTrace.toString(), - ), - ); - - _logError('Test FAILED: $name - $e'); - return false; - } - } - - /// Log info message. - static void _logInfo(String message) { - final timestamp = DateTime.now().toIso8601String(); - debugPrint('[$timestamp] [INFO] $message'); - } - - /// Log error message. - static void _logError(String message) { - final timestamp = DateTime.now().toIso8601String(); - debugPrint('[$timestamp] [ERROR] $message'); - } - - /// Get appropriate test wallet directory for current platform. - static Future _getTestWalletDir() async { - if (Platform.isAndroid) { - return '/data/data/com.example.flutter_libmwc_example/files/ffi_test_wallets/'; - } else if (Platform.isIOS) { - // Use proper iOS Application Support directory instead of hardcoded path - final appSupportDir = await getApplicationSupportDirectory(); - return '${appSupportDir.path}/ffi_test_wallets/'; - } else if (Platform.isLinux) { - return '/tmp/flutter_libmwc_ffi_test_wallets/'; - } else if (Platform.isWindows) { - return r'C:\temp\flutter_libmwc_ffi_test_wallets\'; - } else if (Platform.isMacOS) { - return '/tmp/flutter_libmwc_ffi_test_wallets/'; - } else { - return '/tmp/flutter_libmwc_ffi_test_wallets/'; - } - } -} - -/// Exception thrown during testing. -class TestException implements Exception { - final String message; - - const TestException(this.message); - - @override - String toString() => 'TestException: $message'; -} diff --git a/integration_test/mwc_test_result.dart b/integration_test/mwc_test_result.dart deleted file mode 100644 index 27dbc2e1dd..0000000000 --- a/integration_test/mwc_test_result.dart +++ /dev/null @@ -1,28 +0,0 @@ -/// Represents the result of a single FFI integration test. -class TestResult { - final String name; - final String description; - final bool passed; - final Duration duration; - final String? result; - final String? error; - final String? stackTrace; - final DateTime timestamp; - - TestResult({ - required this.name, - required this.description, - required this.passed, - required this.duration, - this.result, - this.error, - this.stackTrace, - }) : timestamp = DateTime.now(); - - /// Get a summary string for this test result. - String get summary { - final status = passed ? 'PASS' : 'FAIL'; - final durationMs = duration.inMilliseconds; - return '$status: $name (${durationMs}ms)'; - } -} diff --git a/scripts/app_config/shared/link_assets.sh b/scripts/app_config/shared/link_assets.sh index 7dec8ed960..624a418495 100755 --- a/scripts/app_config/shared/link_assets.sh +++ b/scripts/app_config/shared/link_assets.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash set -x -e +: "${APP_PROJECT_ROOT_DIR:?APP_PROJECT_ROOT_DIR must be set (run through build_app.sh)}" if [ $# -ne 2 ]; then echo "Usage: $0 " @@ -14,20 +15,28 @@ APP_BUILD_PLATFORM=$2 ASSET_SOURCES_DIR="${APP_PROJECT_ROOT_DIR}/asset_sources" ASSETS_DIR="${APP_PROJECT_ROOT_DIR}/assets" - -# finally update symlinks - +# Windows gets real copies: symlink privilege is not guaranteed and the asset +# tree is small. Other platforms use symlinks. for dirname in "default_themes" "icon" "lottie" "in_app_logo_icons" "svg"; do LINK_SOURCE_DIR="${ASSET_SOURCES_DIR}/${dirname}/${SELECT_ASSETS_DIR}" - rm -f "${ASSETS_DIR}/${dirname}" + # Remove an old Windows junction as a link, not by recursing into its target. + if [[ "${APP_BUILD_PLATFORM}" = 'windows' && -d "${ASSETS_DIR}/${dirname}" ]]; then + TARGET_WIN_PATH="$(cygpath -w "${ASSETS_DIR}/${dirname}")" + if ! MSYS2_ARG_CONV_EXCL="/C" cmd.exe /C rmdir "$TARGET_WIN_PATH" 2>/dev/null; then + # A real copy directory cannot be removed by rmdir; a reparse point must + # never fall through to rm -rf, which may follow it into asset_sources. + if MSYS2_ARG_CONV_EXCL="/C" cmd.exe /C fsutil reparsepoint query "$TARGET_WIN_PATH" >/dev/null 2>&1; then + echo >&2 "[ERROR] cannot remove the Windows junction ${ASSETS_DIR}/${dirname}; remove it manually." + exit 1 + fi + fi + fi + rm -rf "${ASSETS_DIR:?}/${dirname:?}" if [[ "${APP_BUILD_PLATFORM}" = 'windows' ]]; then - LINK_SOURCE_DIR_WIN_PATH_VERSION=$(cygpath -w "${LINK_SOURCE_DIR}") - LINK_NAME_WIN_PATH_VERSION=$(cygpath -w "${ASSETS_DIR}") - # Keep CMD switches out of Git Bash's path conversion; paths are native above. - MSYS2_ARG_CONV_EXCL="/C;/D${MSYS2_ARG_CONV_EXCL:+;$MSYS2_ARG_CONV_EXCL}" \ - cmd.exe /C mklink /D "${LINK_NAME_WIN_PATH_VERSION}\\${dirname}" "${LINK_SOURCE_DIR_WIN_PATH_VERSION}" + mkdir -p "${ASSETS_DIR}/${dirname}" + cp -r "${LINK_SOURCE_DIR}/." "${ASSETS_DIR}/${dirname}/" else ln -s "${LINK_SOURCE_DIR}" "${ASSETS_DIR}/${dirname}" fi diff --git a/scripts/download_xcode.sh b/scripts/download_xcode.sh index 6ddc23e2fb..e670be9bb1 100755 --- a/scripts/download_xcode.sh +++ b/scripts/download_xcode.sh @@ -95,6 +95,16 @@ if [[ "$TARGET_DIR" != *.app || "$TARGET_DIR" == "/" ]]; then exit 1 fi +# A relative cache or target dir must not change meaning after the extraction cd below. +case "$CACHE_DIR" in + /*) ;; + *) CACHE_DIR="$PWD/$CACHE_DIR" ;; +esac +case "$TARGET_DIR" in + /*) ;; + *) TARGET_DIR="$PWD/$TARGET_DIR" ;; +esac + # sudo is only needed when the target directory is not writable (for example /Applications). SUDO="" mkdir -p "$(dirname "$TARGET_DIR")" 2>/dev/null || true @@ -106,6 +116,28 @@ fi DOWNLOAD_URL="${XCODE_XIP_URL:-https://archive.org/download/${IA_ITEM}/${FILE_NAME}}" TORRENT_URL="https://archive.org/download/${IA_ITEM}/${IA_ITEM}_archive.torrent" XIP_PATH="${CACHE_DIR}/${FILE_NAME}" +XIP_PART="${XIP_PATH}.part" + +finish_install() { + if [[ $ASSUME_YES -eq 1 ]]; then + if [[ "$(xcode-select -p 2>/dev/null || true)" != "${TARGET_DIR}/Contents/Developer" ]]; then + sudo xcode-select -s "${TARGET_DIR}/Contents/Developer" + fi + if ! xcodebuild -license check >/dev/null 2>&1; then + sudo xcodebuild -license accept + fi + if ! xcodebuild -checkFirstLaunchStatus >/dev/null 2>&1; then + sudo xcodebuild -runFirstLaunch + fi + echo "[SUCCESS] Xcode ${XCODE_VERSION} (${BUILD_NUM}) installed and selected." + xcodebuild -version + else + echo "[SUCCESS] Installed ${TARGET_DIR}. Finish with:" + echo " sudo xcode-select -s \"${TARGET_DIR}/Contents/Developer\"" + echo " sudo xcodebuild -license # read and accept" + echo " sudo xcodebuild -runFirstLaunch" + fi +} echo "=================================================================" echo " Xcode from archive.org (hash + signature verified)" @@ -122,9 +154,9 @@ if [[ -d "$TARGET_DIR" ]]; then CURRENT_BUILD="$("$TARGET_DIR/Contents/Developer/usr/bin/xcodebuild" -version 2>/dev/null | awk '/Build version/ {print $3}' || true)" if [[ "$CURRENT_BUILD" == "$BUILD_NUM" ]]; then echo "[OK] Xcode ${XCODE_VERSION} (${BUILD_NUM}) is already installed at ${TARGET_DIR}." - if [[ "$(xcode-select -p 2>/dev/null || true)" != "${TARGET_DIR}/Contents/Developer" ]]; then - echo "Run to select it: sudo xcode-select -s \"${TARGET_DIR}/Contents/Developer\"" - fi + # With -y, finish selection/license/first-launch now instead of exiting + # before the setup the caller explicitly asked for. + finish_install exit 0 fi echo "[WARN] ${TARGET_DIR} exists with build '${CURRENT_BUILD}', expected '${BUILD_NUM}'. It will be replaced." @@ -151,12 +183,37 @@ if [[ "$FREE_KB" -lt $((20 * 1024 * 1024)) ]]; then exit 1 fi -# 1. Resumable download +# 1. Resumable download. A verified archive is reused; a partial .part file is +# resumed with curl -C - instead of being treated as a complete archive. +if [[ -f "$XIP_PATH" ]]; then + CACHED_SHA1="$(shasum -a 1 "$XIP_PATH" | awk '{print $1}')" + if [[ "$CACHED_SHA1" == "$EXPECTED_SHA1" ]]; then + echo "Using cached archive: $XIP_PATH" + else + echo "[WARN] Cached archive does not match the expected SHA-1; downloading again." >&2 + rm -f "$XIP_PATH" + fi +fi if [[ ! -f "$XIP_PATH" ]]; then - echo "Downloading ${FILE_NAME} (resumable; torrent alternative: ${TORRENT_URL})..." - curl -fL -C - --retry 8 --retry-delay 5 --retry-all-errors --progress-bar -o "$XIP_PATH" "$DOWNLOAD_URL" -else - echo "Using cached archive: $XIP_PATH" + if [[ -f "$XIP_PART" ]]; then + echo "Resuming partial download: $XIP_PART" + else + echo "Downloading ${FILE_NAME} (resumable; torrent alternative: ${TORRENT_URL})..." + fi + if ! curl -fL -C - --retry 8 --retry-delay 5 --retry-all-errors --progress-bar -o "$XIP_PART" "$DOWNLOAD_URL"; then + echo "[WARN] Could not resume; restarting the download from scratch." >&2 + rm -f "$XIP_PART" + curl -fL --retry 8 --retry-delay 5 --retry-all-errors --progress-bar -o "$XIP_PART" "$DOWNLOAD_URL" + fi + PART_SHA1="$(shasum -a 1 "$XIP_PART" | awk '{print $1}')" + if [[ "$PART_SHA1" != "$EXPECTED_SHA1" ]]; then + echo "[ERROR] SHA-1 mismatch, the download is corrupt or altered." >&2 + echo " expected: $EXPECTED_SHA1" >&2 + echo " got : $PART_SHA1" >&2 + rm -f "$XIP_PART" + exit 1 + fi + mv "$XIP_PART" "$XIP_PATH" fi # 2. Integrity: SHA-1 from archive.org metadata @@ -209,15 +266,4 @@ $SUDO xattr -dr com.apple.quarantine "$TARGET_DIR" 2>/dev/null || true rm -rf "$EXTRACT_DIR" # 6. Select and first-launch only with -y; otherwise print the commands. -if [[ $ASSUME_YES -eq 1 ]]; then - sudo xcode-select -s "${TARGET_DIR}/Contents/Developer" - sudo xcodebuild -license accept - sudo xcodebuild -runFirstLaunch - echo "[SUCCESS] Xcode ${XCODE_VERSION} (${BUILD_NUM}) installed and selected." - xcodebuild -version -else - echo "[SUCCESS] Installed ${TARGET_DIR}. Finish with:" - echo " sudo xcode-select -s \"${TARGET_DIR}/Contents/Developer\"" - echo " sudo xcodebuild -license # read and accept" - echo " sudo xcodebuild -runFirstLaunch" -fi +finish_install diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh index e317a0e65b..ec78b1bbb5 100755 --- a/scripts/install_macos_build_tools.sh +++ b/scripts/install_macos_build_tools.sh @@ -64,22 +64,46 @@ add_rustup_to_path # copy installed another way) must not stop the toolchain setup. brew install pandoc weasyprint toilet figlet || echo "[WARN] optional report tools were not fully installed; only bm/ report rendering needs them." -# The Homebrew cask always installs the latest Flutter, but the app is built -# and tested against one pinned release. Install that tag from source instead. -FLUTTER_VERSION="${FLUTTER_VERSION:-3.47.4}" +# The Homebrew cask always installs the latest Flutter, but CI builds and tests +# one pinned release. Install that tag from source instead. +FLUTTER_VERSION="${FLUTTER_VERSION:-3.47.2}" +# Both the CI version and the version pinned by the Nix shell/BOM work. An +# explicit FLUTTER_VERSION only accepts that version. +if [[ -n "${FLUTTER_ACCEPTED_VERSIONS:-}" ]]; then + : +elif [[ "$FLUTTER_VERSION" == "3.47.2" ]]; then + FLUTTER_ACCEPTED_VERSIONS="3.47.2 3.47.4" +else + FLUTTER_ACCEPTED_VERSIONS="$FLUTTER_VERSION" +fi FLUTTER_DIR="${FLUTTER_DIR:-$HOME/development/flutter}" +case "$FLUTTER_DIR" in + /*) ;; + *) FLUTTER_DIR="$PWD/$FLUTTER_DIR" ;; +esac +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" flutter_installed_version() { "$1" --version --machine 2>/dev/null | sed -n 's/.*"frameworkVersion": *"\([^"]*\)".*/\1/p' | head -n 1 } +flutter_version_ok() { + local accepted + for accepted in $FLUTTER_ACCEPTED_VERSIONS; do + [[ "$1" == "$accepted" ]] && return 0 + done + return 1 +} + FLUTTER_BIN="$(command -v flutter 2>/dev/null || true)" [[ -z "$FLUTTER_BIN" && -x "$FLUTTER_DIR/bin/flutter" ]] && FLUTTER_BIN="$FLUTTER_DIR/bin/flutter" CURRENT_FLUTTER="" [[ -n "$FLUTTER_BIN" ]] && CURRENT_FLUTTER="$(flutter_installed_version "$FLUTTER_BIN")" +FLUTTER_PATH_TO_PERSIST="" -if [[ "$CURRENT_FLUTTER" == "$FLUTTER_VERSION" ]]; then - echo "Flutter $FLUTTER_VERSION already installed ($FLUTTER_BIN)." +if flutter_version_ok "$CURRENT_FLUTTER"; then + echo "Flutter $CURRENT_FLUTTER already installed ($FLUTTER_BIN)." + [[ "$FLUTTER_BIN" == "$FLUTTER_DIR/bin/flutter" ]] && FLUTTER_PATH_TO_PERSIST="$FLUTTER_DIR/bin" else [[ -n "$CURRENT_FLUTTER" ]] && echo "Found Flutter $CURRENT_FLUTTER at $FLUTTER_BIN, need $FLUTTER_VERSION." if [[ -d "$FLUTTER_DIR/.git" ]]; then @@ -93,17 +117,28 @@ else mkdir -p "$(dirname "$FLUTTER_DIR")" git clone --branch "$FLUTTER_VERSION" --depth 1 https://github.com/flutter/flutter.git "$FLUTTER_DIR" fi + FLUTTER_BIN="$FLUTTER_DIR/bin/flutter" + FLUTTER_PATH_TO_PERSIST="$FLUTTER_DIR/bin" fi -export PATH="$FLUTTER_DIR/bin:$PATH" + +# Only prepend the managed SDK when the selected Flutter is not already on PATH. +FLUTTER_BIN_DIR="$(dirname "$FLUTTER_BIN")" +case ":$PATH:" in + *":$FLUTTER_BIN_DIR:"*) ;; + *) export PATH="$FLUTTER_BIN_DIR:$PATH" ;; +esac if ! command -v rustup >/dev/null 2>&1; then die "rustup not found in PATH. Check brew install." fi -echo "Ensuring Rust 1.99.1 toolchain..." -rustup toolchain install 1.99.1 -rustup default 1.99.1 -rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios --toolchain 1.99.1 >/dev/null 2>&1 || true +RUST_VERSION="${RUST_VERSION:-1.99.1}" +echo "Ensuring Rust $RUST_VERSION toolchain..." +rustup toolchain install "$RUST_VERSION" +rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios --toolchain "$RUST_VERSION" >/dev/null 2>&1 || true +# Pin this checkout instead of changing the user's global rustup default; the +# native-asset crates also carry their own rust-toolchain.toml. +rustup override set "$RUST_VERSION" --path "$REPO_ROOT" >/dev/null 2>&1 || true # Homebrew's rustup formula is keg-only and does not necessarily create the # cargo/rustc shims in ~/.cargo/bin — `rustup toolchain install` alone may leave @@ -112,10 +147,10 @@ rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios --t if [ ! -x "$HOME/.cargo/bin/cargo" ]; then echo "cargo shims missing in ~/.cargo/bin; creating them via rustup-init..." if command -v rustup-init >/dev/null 2>&1; then - rustup-init -y --no-modify-path --default-toolchain 1.99.1 || true + rustup-init -y --no-modify-path --default-toolchain "$RUST_VERSION" || true else curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \ - | sh -s -- -y --no-modify-path --default-toolchain 1.99.1 || true + | sh -s -- -y --no-modify-path --default-toolchain "$RUST_VERSION" || true fi fi @@ -141,8 +176,8 @@ else fi rustup --version -rustc --version -rustup run 1.99.1 rustc --version +rustup run "$RUST_VERSION" rustc --version +rustup run "$RUST_VERSION" cargo --version pod --version go version autoreconf --version | head -n 1 || true @@ -160,11 +195,14 @@ if [ ! -f "$ZSHRC" ]; then touch "$ZSHRC" echo "→ Created $ZSHRC (macOS ships without one)" fi +BREW_PREFIX="$(brew --prefix)" grep -qF 'brew shellenv' "$ZSHRC" 2>/dev/null || \ - echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> "$ZSHRC" -grep -qF "$FLUTTER_DIR/bin" "$ZSHRC" 2>/dev/null || \ - echo "export PATH=\"$FLUTTER_DIR/bin:\$PATH\"" >> "$ZSHRC" + printf 'eval "$(%s/bin/brew shellenv)"\n' "$BREW_PREFIX" >> "$ZSHRC" +if [[ -n "$FLUTTER_PATH_TO_PERSIST" ]]; then + grep -qF "$FLUTTER_PATH_TO_PERSIST" "$ZSHRC" 2>/dev/null || \ + printf 'export PATH="%s:$PATH"\n' "$FLUTTER_PATH_TO_PERSIST" >> "$ZSHRC" +fi grep -qF '$HOME/.cargo/bin' "$ZSHRC" 2>/dev/null || \ - echo 'export PATH="/opt/homebrew/opt/rustup/bin:$HOME/.cargo/bin:$PATH"' >> "$ZSHRC" + printf 'export PATH="%s/opt/rustup/bin:$HOME/.cargo/bin:$PATH"\n' "$BREW_PREFIX" >> "$ZSHRC" echo "→ PATH entries ensured in $ZSHRC" echo " Open a new terminal (or run: source $ZSHRC) before 'make build-macos'." diff --git a/scripts/install_nixos_build_tools.sh b/scripts/install_nixos_build_tools.sh deleted file mode 100755 index d4b42bc80a..0000000000 --- a/scripts/install_nixos_build_tools.sh +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -if [[ "$(uname -s)" != "Linux" ]]; then - echo "This installer is for Linux/NixOS only." - exit 1 -fi - -if ! command -v nix >/dev/null 2>&1; then - echo "Nix is required. Install it first: https://nixos.org/download/" - exit 1 -fi - -if ! command -v rustup >/dev/null 2>&1; then - echo "rustup is required. Install it first (for toolchain pinning): https://rustup.rs" - exit 1 -fi - -echo "Installing Nix profile packages..." -nix --extra-experimental-features "nix-command flakes" profile add \ - nixpkgs#direnv \ - nixpkgs#flutter \ - nixpkgs#go \ - nixpkgs#cmake \ - nixpkgs#ninja \ - nixpkgs#pkg-config \ - nixpkgs#gnumake \ - nixpkgs#gnused \ - nixpkgs#protobuf \ - nixpkgs#autoconf \ - nixpkgs#automake \ - nixpkgs#libtool \ - nixpkgs#clang || true - -echo "Ensuring Rust 1.99.1 toolchain..." -rustup toolchain install --no-self-update 1.99.1 -rustup default 1.99.1 -rustup target add aarch64-unknown-linux-gnu x86_64-unknown-linux-gnu --toolchain 1.99.1 >/dev/null 2>&1 || true - -echo "Installing optional Rust CLI build tools..." -cargo install cargo-ndk || true - -echo "Verifying toolchain..." -if command -v flutter >/dev/null 2>&1; then - flutter --version -else - echo "flutter not found in PATH." -fi - -if command -v dart >/dev/null 2>&1; then - dart --version -else - echo "dart not found in PATH. It should come with Flutter." -fi - -rustup --version -rustc --version -rustup run 1.99.1 rustc --version -go version -protoc --version || true -cmake --version | head -n 1 || true -pkg-config --version || true -autoreconf --version | head -n 1 || true -aclocal --version | head -n 1 || true - -echo "Done." diff --git a/scripts/install_xcode.sh b/scripts/install_xcode.sh index 18b1b54bfe..2d7d74d3d5 100755 --- a/scripts/install_xcode.sh +++ b/scripts/install_xcode.sh @@ -45,7 +45,17 @@ SELECTED_DEV="$(xcode-select -p 2>/dev/null || true)" if [[ "$SELECTED_DEV" == /*.app/Contents/Developer && -x "$SELECTED_DEV/usr/bin/xcodebuild" ]]; then echo "Xcode already configured: ${SELECTED_DEV%/Contents/Developer}" else - XCODE_APP="$(ls -d "$XCODE_APPS_DIR"/Xcode*.app 2>/dev/null | head -1 || true)" + if [[ -n "${XCODE_APP:-}" ]]; then + if [[ ! -x "$XCODE_APP/Contents/Developer/usr/bin/xcodebuild" ]]; then + die "[ERROR] XCODE_APP is not a full Xcode.app: $XCODE_APP" + fi + elif [[ -d "$XCODE_APPS_DIR/Xcode.app" ]]; then + XCODE_APP="$XCODE_APPS_DIR/Xcode.app" + else + # Prefer the newest versioned install; alphabetically Xcode_16.2.app comes + # before Xcode_27.1.app, and Xcodes.app is not Xcode. + XCODE_APP="$(find "$XCODE_APPS_DIR" -maxdepth 1 -type d -name 'Xcode*.app' ! -name 'Xcodes.app' -print 2>/dev/null | sort -V | tail -n 1 || true)" + fi if [[ -z "$XCODE_APP" ]]; then die "[ERROR] Full Xcode is required for macOS/iOS builds (Command Line Tools alone are not enough). Install it, then re-run this script: - Mac App Store: search 'Xcode' and install, or run 'mas install 497799835' if you already have 'mas' set up @@ -55,5 +65,13 @@ else sudo xcode-select -s "$XCODE_APP/Contents/Developer" fi -sudo xcodebuild -license accept 2>/dev/null || true -sudo xcodebuild -runFirstLaunch 2>/dev/null || true +# Only ask for sudo when the license or first-launch setup is actually pending; +# an already-configured Xcode should not trigger these on every bootstrap run. +if ! xcodebuild -license check >/dev/null 2>&1; then + echo "Accepting the Xcode license..." + sudo xcodebuild -license accept +fi +if ! xcodebuild -checkFirstLaunchStatus >/dev/null 2>&1; then + echo "Running Xcode first-launch setup..." + sudo xcodebuild -runFirstLaunch +fi diff --git a/scripts/linux/pc/libsecret-1.pc b/scripts/linux/pc/libsecret-1.pc deleted file mode 100644 index 7da2e13f58..0000000000 --- a/scripts/linux/pc/libsecret-1.pc +++ /dev/null @@ -1,15 +0,0 @@ -prefix=/usr/local -libdir=${prefix}/lib/x86_64-linux-gnu -includedir=${prefix}/include - -exec_prefix=${prefix} -datarootdir=${prefix}/share -datadir=${datarootdir} -sysconfdir=${prefix}/etc - -Name: libsecret-1 -Description: GObject bindings for Secret Service API -Version: 0.20.5 -Requires: glib-2.0 >= 2.44, gio-2.0 >= 2.44, gio-unix-2.0 >= 2.44 -Requires.private: libgcrypt >= 1.2.2 -Libs: -L${libdir} -lsecret-1 diff --git a/scripts/windows/replace_asset_links.sh b/scripts/windows/replace_asset_links.sh deleted file mode 100755 index 6b4cb433d4..0000000000 --- a/scripts/windows/replace_asset_links.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env bash -# Replace the asset directory links created by link_assets.sh with real copies. -# With --clean it only removes them (links or copies) and copies nothing: link_assets.sh runs `rm -f` -# on each target, which cannot remove the real directories a previous run left behind. -# Needed where `mklink /D` is not allowed (e.g. the GitHub Actions windows-2022 runner user lacks -# SeCreateSymbolicLinkPrivilege), because Flutter's asset resolver cannot follow the broken reparse points. -set -euo pipefail -cd "$(dirname "${BASH_SOURCE[0]}")/../.." -clean_only=0 -[ "${1:-}" = "--clean" ] && clean_only=1 -for dirname in default_themes icon lottie in_app_logo_icons svg; do - target="assets/${dirname}" - source="asset_sources/${dirname}/stack_wallet" - if [ -e "$target" ] || [ -L "$target" ]; then - cmd.exe /c rmdir "$(cygpath -w "$target")" 2>/dev/null || rm -rf "$target" - fi - [ "$clean_only" = "1" ] && continue - mkdir -p "$target" - cp -r "${source}/." "$target/" -done diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 3ca18bc63e..20c8f27817 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -1,4 +1,5 @@ -// Checks the local toolchain and the pinned native plugins against stack-bom.toml. +// Checks the local toolchain and the pinned native plugins against +// stack-bom.toml. // // dart tool/verify_bom.dart check, exit 1 on a mismatch // dart tool/verify_bom.dart --update rewrite the [plugins] section from pubspec.lock @@ -62,9 +63,12 @@ Map> _readBom(String text) { Future _run(String exe, List args) async { try { - final r = await Process.run(exe, args); + // runInShell lets Windows start flutter.bat. Only stdout is parsed: Flutter + // writes startup-lock warnings to stderr, and appending those to the JSON + // breaks --machine output. + final r = await Process.run(exe, args, runInShell: Platform.isWindows); if (r.exitCode != 0) return null; - return '${r.stdout}${r.stderr}'.trim(); + return '${r.stdout}'.trim(); } on ProcessException { return null; } @@ -135,27 +139,42 @@ Future main(List args) async { final tc = bom['toolchain'] ?? {}; // Flutter / Dart - final fl = await _run('flutter', ['--version', '--machine']); + final configuredFlutter = Platform.environment['FLUTTER']?.trim() ?? ''; + final fl = await _run( + configuredFlutter.isEmpty ? 'flutter' : configuredFlutter, + ['--version', '--machine'], + ); if (fl == null) { _fail('flutter not found in PATH'); } else { - final info = - jsonDecode(fl.substring(fl.indexOf('{'))) as Map; - final v = info['frameworkVersion'] as String; - final d = info['dartSdkVersion'] as String; - if (_cmp(v, tc['flutter_min'] ?? '0') < 0) { - _fail('Flutter $v is older than the minimum ${tc['flutter_min']}'); - } else if (v != tc['flutter']) { - _warn( - 'Flutter $v (recommended ${tc['flutter']}, minimum ${tc['flutter_min']})', - ); - } else { - _ok('Flutter $v'); - } - if (d.startsWith(tc['dart_prefix'] ?? '')) { - _ok('Dart $d'); + final start = fl.indexOf('{'); + final end = fl.lastIndexOf('}'); + if (start < 0 || end <= start) { + _fail('unexpected output from flutter --version --machine'); } else { - _fail('Dart $d does not match ${tc['dart_prefix']}.x'); + try { + final info = + jsonDecode(fl.substring(start, end + 1)) as Map; + final v = info['frameworkVersion'] as String; + final d = info['dartSdkVersion'] as String; + if (_cmp(v, tc['flutter_min'] ?? '0') < 0) { + _fail('Flutter $v is older than the minimum ${tc['flutter_min']}'); + } else if (v != tc['flutter']) { + _warn( + 'Flutter $v (recommended ${tc['flutter']}, ' + 'minimum ${tc['flutter_min']})', + ); + } else { + _ok('Flutter $v'); + } + if (d.startsWith(tc['dart_prefix'] ?? '')) { + _ok('Dart $d'); + } else { + _fail('Dart $d does not match ${tc['dart_prefix']}.x'); + } + } on FormatException { + _fail('could not parse flutter --version --machine output'); + } } } @@ -192,7 +211,8 @@ Future main(List args) async { _ok('Xcode ${xm.group(1)}'); } else if (xm.group(1) == mac['xcode_dnix']) { _warn( - 'Xcode ${xm.group(1)} is the version dnix pins; ${mac['xcode']} is recommended for app builds', + 'Xcode ${xm.group(1)} is the version dnix pins; ' + '${mac['xcode']} is recommended for app builds', ); } else { _warn('Xcode ${xm.group(1)} (recommended ${mac['xcode']})'); @@ -206,12 +226,20 @@ Future main(List args) async { _warn('pubspec.lock not found, plugin pins not checked'); } else { for (final n in _pluginNames) { - if (!refs.containsKey(n)) continue; - if (pinned[n] == refs[n]) { - _ok('$n ${refs[n]!.substring(0, 7)}'); + final ref = refs[n]; + final pin = pinned[n]; + if (ref == null) { + _fail( + '$n is missing from pubspec.lock (path dependency or not resolved)', + ); + } else if (pin == null) { + _fail('$n is missing from [plugins] in $_bomFile (run --update)'); + } else if (pin == ref) { + _ok('$n ${ref.substring(0, 7)}'); } else { _fail( - '$n is ${refs[n]!.substring(0, 7)} in pubspec.lock but ${pinned[n]?.substring(0, 7)} in $_bomFile (run --update)', + '$n is ${ref.substring(0, 7)} in pubspec.lock but ' + '${pin.substring(0, 7)} in $_bomFile (run --update)', ); } } From 8eda6ef0075826f16f3b58d102d6afd941dd6b29 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:46:50 +0200 Subject: [PATCH 018/107] ci: serialize the macOS and iOS make-build jobs The fork has a single hosted macOS concurrency slot. Running the two jobs together leaves one queued until GitHub's 15-minute timeout cancels it. Run macOS first, then iOS, so each waits for the runner instead of competing. --- .github/workflows/make-build.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/make-build.yaml b/.github/workflows/make-build.yaml index 08d0907606..1821eddce2 100644 --- a/.github/workflows/make-build.yaml +++ b/.github/workflows/make-build.yaml @@ -82,6 +82,10 @@ jobs: run: make build-linux VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} ios: + # The fork has a single hosted macOS concurrency slot. Running macOS and + # iOS together leaves one job queued until GitHub cancels it; serialise them. + needs: macos + if: always() runs-on: macos-latest steps: - uses: actions/checkout@v6 From 1e1d4c7c3b5dcc858eeb4b8206d6bf540756f51a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:04:24 +0200 Subject: [PATCH 019/107] build: keep make -n a dry run, guard verify-bom without dart, drop unused secp copy - bootstrap-macos invoked $(MAKE) bootstrap-xcode; a recipe line containing $(MAKE) is executed even under `make -n`, so a dry run accepted the Xcode license and ran first-launch setup for real (observed: sudo prompt and exit 2 under make -n). Call scripts/install_xcode.sh directly instead -- exactly what the bootstrap-xcode target runs. - verify-bom with no dart on PATH expanded $(DART) to empty and /bin/sh tried to execute tool/verify_bom.dart as a command ("Permission denied", exit 126). Guard it the same way check-reqs guards Flutter/Dart. - scripts/linux/build_secp256k1.sh copied the library to build/linux/x64/release/secp256k1/lib ("Location expected by Flutter/CMake install step"). No consumer exists in this tree or in #1505 (coinlib_flutter, pinned f0e12dac, builds its own secp256k1 via CMake ExternalProject into its own CMAKE_BINARY_DIR), and the path hardcoded x64 instead of deriving the arch. Drop it; keep the legacy build/libsecp256k1.so copy consumed by coinlib:build_linux and test/utilities/electrum_seed_utils_test.dart. --- Makefile | 6 +++++- scripts/linux/build_secp256k1.sh | 4 ---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index f537d2def3..2c609922be 100644 --- a/Makefile +++ b/Makefile @@ -113,10 +113,13 @@ endif bootstrap-macos: ## Install required macOS build tools via Homebrew helper script ifeq ($(PLATFORM),Darwin) +# Call install_xcode.sh directly instead of `$(MAKE) bootstrap-xcode`: a recipe +# line containing $(MAKE) is executed even under `make -n`, which would make a +# dry run accept the Xcode license and run first-launch setup for real. @if [ -n "$$IN_NIX_SHELL" ] || [ -n "$$NIX_BUILD_TOP" ]; then \ echo "[WARN] Nix environment detected; skipping the Homebrew package install (use nix/flake-provided toolchain instead)."; \ echo "[WARN] Xcode itself is never provided by Nix (Apple's license forbids redistributing it), so that part still runs:"; \ - $(MAKE) bootstrap-xcode || exit 1; \ + bash scripts/install_xcode.sh || exit 1; \ else \ bash scripts/install_macos_build_tools.sh || exit 1; \ rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios --toolchain $(RUST_VERSION) >/dev/null 2>&1 || true; \ @@ -159,6 +162,7 @@ sccache-setup: ## Opt-in: use sccache for the Rust/C builds run by native-asset @echo "also pass CARGO_BUILD_RUSTC_WRAPPER=sccache from the environment. See sccache --show-stats." verify-bom: ## Check the local toolchain and the pinned plugins against stack-bom.toml + @[ -n "$(DART)" ] || { echo >&2 "[ERROR] Dart not installed (needed for verify-bom). Install Flutter or pass DART=/path/to/dart."; exit 1; } @FLUTTER="$(FLUTTER)" $(DART) tool/verify_bom.dart cache-stats: ## Show sccache statistics (hit rate) after a build diff --git a/scripts/linux/build_secp256k1.sh b/scripts/linux/build_secp256k1.sh index 187489d72b..eb2e68afa2 100755 --- a/scripts/linux/build_secp256k1.sh +++ b/scripts/linux/build_secp256k1.sh @@ -27,7 +27,3 @@ fi # Legacy location used by parts of the build pipeline. mkdir -p ../../../../../build cp "$SECP_SO" ../../../../../build/libsecp256k1.so - -# Location expected by Flutter/CMake install step. -mkdir -p ../../../../../build/linux/x64/release/secp256k1/lib -cp "$SECP_SO" ../../../../../build/linux/x64/release/secp256k1/lib/libsecp256k1.so From 9ef85ee713744d18a4827a393b198e3a7159f733 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:04:24 +0200 Subject: [PATCH 020/107] ci: least-privilege permissions and drop libopencv-dev in make-build - The workflow declared no permissions and would inherit the repo default. Add top-level permissions: contents: read (the jobs only check out code and build; no artifacts are uploaded, no registry images pulled). - Drop libopencv-dev from the Linux apt list: staging removed it in 9a02aa2e7 ("Use the build-hook camera_linux, drop libopencv-dev"), the CI image installs no OpenCV, and this PR's own docs/building.md apt line does not list it. Keep ocl-icd-opencl-dev/opencl-headers/libtss2-dev, which the staging image still ships. --- .github/workflows/make-build.yaml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/make-build.yaml b/.github/workflows/make-build.yaml index 1821eddce2..dfc148d759 100644 --- a/.github/workflows/make-build.yaml +++ b/.github/workflows/make-build.yaml @@ -4,6 +4,11 @@ name: Make build on: workflow_dispatch: +# Least privilege: the jobs only check out code and build. No artifacts are +# uploaded, no containers or registry images are pulled. +permissions: + contents: read + jobs: windows: runs-on: windows-2022 @@ -70,7 +75,7 @@ jobs: sudo apt-get install -y --no-install-recommends \ automake build-essential clang cmake libclang-dev libtool llvm meson ninja-build patchelf pkg-config protobuf-compiler rsync \ libgcrypt20-dev libgirepository1.0-dev libgit2-dev libglib2.0-dev libgtk-3-dev libjsoncpp-dev liblzma-dev \ - libncurses5-dev libncursesw5-dev libopencv-dev libsecret-1-dev libssl-dev libtss2-dev \ + libncurses5-dev libncursesw5-dev libsecret-1-dev libssl-dev libtss2-dev \ ocl-icd-opencl-dev opencl-headers valac zlib1g-dev - name: Rust run: | From 43528da4a40146bd5d55483cc6125f702c408cfe Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sat, 14 Nov 2026 06:50:18 +0200 Subject: [PATCH 021/107] build: refresh stack-bom plugin pins after #1505 merged --- stack-bom.toml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/stack-bom.toml b/stack-bom.toml index ac8f87adfe..f84b07cfc2 100644 --- a/stack-bom.toml +++ b/stack-bom.toml @@ -20,9 +20,9 @@ xcode_xip_sha1 = "d8b1d16397e6f2faab34bd48b19692a3f7797b9d" # archive.org item [plugins] # Generated by `dart tool/verify_bom.dart --update` from pubspec.lock. Do not edit by hand. -flutter_libepiccash = "d5cfb763fa62928a6e6265e1f4412738772151eb" -flutter_libmwc = "d8c5d5488cb00e21d0dc04ad306a65e2d54c4d3c" +flutter_libepiccash = "63e93b01c3c4c68a52b26a43e4442a4738d5e7e8" +flutter_libmwc = "5722fb3ba05c8f52e8e0255c485ae5ea52e9a694" flutter_libsparkmobile = "3fdcb21160a39c051a0e73d7ae04f987134ecd5f" -frostdart = "c8be6a0ea892d744adfacc8e97df891feca49707" -tor_ffi_plugin = "e30ed0d386a40ee4a999aeaf57aafd32921d601e" +frostdart = "f7fea2a926ea88e2eb6a353579372188d6915314" +tor_ffi_plugin = "6e954a9d5a0aaaafb861049b79041d7ae98c2a08" xelis_wallet_flutter = "8630a2cf28947497ec67b7535ddf1fac4cedbaa8" From 361d9cdf889440aff698ac714c3a3cf426bcece7 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sat, 14 Nov 2026 06:50:52 +0200 Subject: [PATCH 022/107] docs: keep the Windows copy-mode and Android dev-key details in the make page --- docs/building/make.md | 123 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 docs/building/make.md diff --git a/docs/building/make.md b/docs/building/make.md new file mode 100644 index 0000000000..f268288c6e --- /dev/null +++ b/docs/building/make.md @@ -0,0 +1,123 @@ +# Building with `make` + +The `Makefile` is a thin wrapper around the steps in the per-host guides +([Linux](linux.md), [macOS](macos.md), [Windows](windows.md)). It runs the same +build steps as CI; CI passes `-d` explicitly for release builds. Run `make help` for all +targets. The toolchain and build paths are diagrammed in +[Make build flow](make-flow.md). + +`make build-macos`, `build-linux` and `build-ios` run `verify-bom` before +configuring the app, so a toolchain or plugin-pin drift fails early. `make` +builds are local development builds. macOS/Linux/iOS outputs are not +release-signed; Android APKs are signed with `android/key.properties` (a +throw-away key if created via `make android-dev-key`) and must not be +distributed. If `lib/external_api_keys.dart` is missing, `prebuild.sh` creates +empty stubs, so swap providers are disabled; CI decodes the real keys before +building. + +`build_app.sh` asks before replacing generated app files because some +version/build combinations can delete wallet data. `make` keeps that prompt +interactive; pass `CONFIRM=1` for a non-interactive run. + +`VERSION` and `BUILD_NUM` set the app version and build number. Both are +required for build targets: `make` validates them and rejects a `BUILD_NUM` +that is not above the latest `build_*` tag. `APP_NAME` selects the app variant +(`stack_wallet`, `stack_duo` or `campfire`). + +| Variable | Default | Purpose | +|---|---|---| +| `VERSION`, `BUILD_NUM` | required | App version and a build number above the latest release tag | +| `APP_NAME` | `stack_wallet` | `stack_wallet`, `stack_duo` or `campfire` | +| `PREBUILTS` | `0` on Apple Silicon/Linux in Nix/direnv; otherwise `1` | `0` builds dnix from source (Nix/direnv only); `1` uses verified prebuilts (`-d`) | +| `ANDROID_PREBUILTS` | follows `PREBUILTS` on x86_64 Linux in Nix/direnv, else `1` | Overrides the Android dnix mode | +| `SYSTEM_DEPS` | `0` | Linux: `1` uses system libsecret/JsonCPP (as CI does) | +| `TOOLCHAIN` | `auto` | `auto`, `nix`, `direnv`, `brew`, `host` or `manual` | +| `CONFIRM` | `0` | `1` answers build_app.sh's wallet-data warning non-interactively | + +Source mode is only available through the **Nix/direnv toolchain**. On Apple +Silicon macOS and Linux inside `nix develop`/direnv, `PREBUILTS=0` is the +default: dnix builds the pinned native libraries from source and verifies their +hashes. Homebrew, manual and host toolchains, plus Intel macOS, default to +`PREBUILTS=1`; `PREBUILTS=0` is rejected with those toolchains. CI passes `-d` +explicitly. + +``` +make build-macos VERSION=x.y.z BUILD_NUM=nnn # dnix source (Nix/direnv, Apple Silicon) +make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1 # verified prebuilts (-d), fast +``` + +## Targets + +| Target | What it does | +|---|---| +| `make build-macos` | `build_app.sh -p macos -a $(APP_NAME)`, `flutter pub get`, `prebuild.sh`, `flutter build macos --release`. Source by default only in Nix/direnv on Apple Silicon; `PREBUILTS=1` uses the verified prebuilts | +| `make build-linux` | `prebuild.sh`, `build_app.sh -p linux`, local libsecret and secp256k1 helper builds, `flutter build linux --release`, then `prepare_release_bundle.py`. Source by default only inside Nix/direnv; `PREBUILTS=1` uses the verified prebuilts | +| `make build-windows` | Git Bash: `prebuild.sh`, `MWEBD_FETCH=1 build_app.sh -p windows -d` (`-d` selects verified prebuilts; secp256k1 is always built by this target), `pub get`, `flutter build windows --release`. Always uses the verified dnix prebuilts. Asset directories are copied on Windows. | +| `make build-android` | Same build commands as CI, without the AAB/upload steps; signs with `android/key.properties` (run `make android-dev-key` for a throw-away test key), needs the Android SDK/NDK and Java. Prebuilt dnix on macOS, non-x86_64 Linux and brew/manual toolchains; x86_64 Linux in Nix/direnv follows `PREBUILTS` | +| `make build-ios` | Same build commands as CI, without signing/packaging, on macOS (`flutter build ios --release --no-codesign`). Source by default only in Nix/direnv on Apple Silicon; CI passes `-d` explicitly | +| `make bootstrap` | Enter the Nix dev shell (primary toolchain); no-op when already inside | +| `make bootstrap-macos` | Homebrew fallback host setup: Flutter and Rust from `stack-bom.toml` plus the Homebrew packages (Go, CMake, Meson, Ninja, pkg-config, protobuf, CocoaPods, autotools, direnv, rustup, sccache) | +| `make toolchain` | Show the active toolchain (`nix`, `direnv`, `host`, `brew`, `manual`) | +| `make bootstrap-xcode` | Check and select an installed full Xcode.app | +| `make check-reqs`, `check-reqs-macos`, `check-sdk-macos`, `diagnose-env-macos` | Prerequisite checks and an environment dump | +| `make verify-bom` | Compare the machine and `pubspec.lock` against `stack-bom.toml` | +| `make clean-app` / `make clean-native` | Remove app output / force the native-asset libraries to rebuild | +| `make clean` | Remove build output, Pods and the Flutter build cache | +| `make sccache-setup` / `make cache-stats` | Opt-in sccache wrapper / show sccache statistics | + +## Toolchains on macOS + +The build steps are identical in every mode; only how the host tools get on +`PATH` differs. Nix is the primary path. + +| Mode | Setup | Notes | +|---|---|---| +| Nix | `make bootstrap` (enters `nix develop`) | The flake provides Flutter and Go from its pinned nixpkgs (currently Flutter 3.47.4, matching the BOM, and Go 1.26.7; the BOM's `go` is the CI/Docker pin), Dart, rustup (which installs the BOM Rust version on first entry), CMake, Meson, Ninja, pkg-config and protoc. Xcode always comes from the host. | +| direnv | `direnv allow` | The same flake as Nix, loaded automatically. | +| Homebrew | `make bootstrap-macos` (alias `make bootstrap-brew`) | Fallback, prebuilt-only. Installs the Flutter tag and Rust from `stack-bom.toml` plus the Homebrew packages, and adds PATH entries to `~/.zshrc`. | +| Manual | install the tools yourself | Advanced, prebuilt-only. `make check-reqs-macos` reports what is missing. | + +`make toolchain` prints the active mode and tool paths. +`TOOLCHAIN=nix|direnv|brew` forces a check; `host` and `manual` use whatever is on `PATH`; `auto` (the default) detects a Nix/direnv shell and otherwise uses the host tools. Only `nix` and `direnv` can use `PREBUILTS=0`; `brew`, `host` and `manual` are prebuilt-only. + +`make check-reqs-macos` verifies the result and `make diagnose-env-macos` prints what was found. + +## Xcode + +`make bootstrap-xcode` only checks and selects an installed Xcode. To install +one, use `dart tool/setup_xcode.dart` (which drives the `xcodes` CLI) or Apple's download +page; the Nix shell never provides Xcode. Source builds (`PREBUILTS=0`, only +in Nix/direnv) need the Xcode 27.0 that dnix pins; `stack-bom.toml` recommends +27.1 for ordinary app builds, including Homebrew/manual prebuilt builds. + +To build with another installed Xcode without changing the global selection, +run for example +`DEVELOPER_DIR=/Applications/Xcode_27.0.app/Contents/Developer make build-macos`. +This affects the Flutter/app build; a source build (`PREBUILTS=0`) still needs +the pinned Xcode 27.0. dnix checks the `xcode-select` choice first and then +scans `/Applications/Xcode*.app`. + +## Keep the build environment the same between runs + +Flutter reruns every native-asset build hook when `PATH` or any `NIX_*` variable differs from the previous build, even if no source changed. Measured on macOS: 33 to 40 s for a repeated build with an unchanged environment, 536 s after putting one extra directory in front of `PATH`, 156 to 164 s after adding a `NIX_*` variable or restoring `PATH`. So build always from the same shell setup (for example only through `make`, or only inside `nix develop`), and do not alternate between a terminal inside `nix develop` and an IDE without it. + +## Toolchain bill of materials + +`stack-bom.toml` lists the toolchain a build is expected to use (Flutter, Dart, Rust, Go, Xcode) and the git revisions of the pinned native plugins. It is not a Homebrew package manifest: the native dnix libraries are pinned in each plugin's `dnix.lock`, and the Homebrew packages are in `scripts/install_macos_build_tools.sh`. `make verify-bom` compares the local machine and `pubspec.lock` against it and exits with an error on a mismatch (a different recommended Flutter or Xcode version is only a warning). Source builds additionally require the Xcode 27.0 that dnix pins; `build_app.sh` enforces that, while `verify-bom` only warns. After changing a plugin pin, run `flutter pub get`, then `dart tool/verify_bom.dart --update`, to refresh the `[plugins]` section. + +## Optional: sccache for native-asset builds + +`make sccache-setup` writes `$CARGO_HOME/config.toml` (or `~/.cargo/config.toml`) with `rustc-wrapper = "sccache"` (it never overwrites an +existing file). The build hooks only see a filtered environment (Flutter 3.47.x, and also the 3.50 beta tried so far), so +exporting `RUSTC_WRAPPER` does nothing in either: sccache saw no compile requests. Cargo still reads this file +through `HOME`, which works with both versions. (With the 3.50 beta the variable `CARGO_BUILD_RUSTC_WRAPPER` +also gets through.) Check `sccache --show-stats` +after a build. Measured on an Apple Silicon Mac for a from-source build of all native assets (one run each): +775 s without sccache, 665 s with a cold sccache, 534 s with a warm one. The prebuilt path +(`PREBUILTS=1`, `-d`) replaces all four dnix packages (frostdart, tor, epiccash and mwc); most of +the one-minute saving comes from the three heavy ones, so it saved about one minute in a cold build +(12 vs. 13 minutes). + +## Linux notes + +`make build-linux` needs `protoc`, Meson, Ninja, `patchelf` 0.18 or newer, `readelf` and `python3`; inside `nix develop` they are provided. Before building it writes `.cargo/config.toml` with `[env] PROTOC = ""` if the file does not exist (it is git-ignored). This is needed on NixOS, where a generic-Linux `protoc` shipped inside a crate cannot run and the exported variable does not reach the build hooks. Linux builds use a repo-local `.pub-cache` so cargo finds that file; other targets keep the normal per-user cache. `SYSTEM_DEPS=1` uses the system libsecret/JsonCPP packages (as CI does); the default builds them from source. From ec6993a1e8c34894a7d086863893b4b5b0eda0d4 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:29:21 +0200 Subject: [PATCH 023/107] fix(build): address PR review blockers - link_assets.sh: set MSYS2_ARG_CONV_EXCL for the Windows rmdir, so Git Bash does not rewrite /C and the link is actually removed. - Makefile: drop the duplicate coinlib build_windows step; build_app.sh already builds the same secp256k1 commit. - verify_bom.dart: check only the plugins declared by the configured app, and preserve other apps' pins on --update. - Makefile: require VERSION and BUILD_NUM instead of defaulting to a stale release line; update the examples. - download_xcode.sh: honour -n on an already-installed target before selecting Xcode or accepting the licence. --- Makefile | 23 ++++++++++------- README.md | 6 ++--- bm/bench.sh | 8 ++++-- scripts/download_xcode.sh | 8 ++++++ tool/verify_bom.dart | 54 +++++++++++++++++++++++++++++++++++++-- 5 files changed, 83 insertions(+), 16 deletions(-) diff --git a/Makefile b/Makefile index 2c609922be..f8f1032f76 100644 --- a/Makefile +++ b/Makefile @@ -4,8 +4,10 @@ # ============================================================================== APP_NAME ?= stack_wallet -VERSION ?= 2.1.0 -BUILD_NUM ?= 210 +# Build targets require these explicitly: a stale default silently produces an +# app numbered below the current release line. See `require-version`. +VERSION ?= +BUILD_NUM ?= FLUTTER ?= DART ?= FLUTTER_BIN := $(if $(and $(FLUTTER),$(wildcard $(FLUTTER))),$(FLUTTER),$(shell command -v flutter 2>/dev/null)) @@ -36,7 +38,7 @@ ifneq ($(strip $(PUB_CACHE)),) export PUB_CACHE endif -.PHONY: help check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios +.PHONY: help require-version check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios help: ## Show available commands @echo "Available targets:" @@ -44,6 +46,10 @@ help: ## Show available commands # --- PREREQUISITES --- +require-version: ## Fail unless VERSION and BUILD_NUM are set explicitly + @[ -n "$(VERSION)" ] || { echo >&2 "[ERROR] VERSION is not set. Pass VERSION=x.y.z (current release line: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } + @[ -n "$(BUILD_NUM)" ] || { echo >&2 "[ERROR] BUILD_NUM is not set. Pass a build number above the latest release tag ($$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } + check-reqs: ## Verify essential build tools @echo "Checking core prerequisites..." @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @@ -200,7 +206,7 @@ clean-native: ## Remove only the native-asset build outputs (forces the Rust/Go/ @rm -rf .dart_tool/hooks_runner build/native_assets @echo "[OK] Removed .dart_tool/hooks_runner and build/native_assets." -build-macos: check-reqs-macos check-sdk-macos ## Build macOS release (same steps as upstream CI; PREBUILTS=0 compiles native assets from source) +build-macos: require-version check-reqs-macos check-sdk-macos ## Build macOS release (same steps as upstream CI; PREBUILTS=0 compiles native assets from source) @echo "--- Configuring project (scripts/build_app.sh)..." @cd scripts && echo yes | env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a $(APP_NAME) -s $(if $(filter 1,$(PREBUILTS)),-d) @echo "--- Resolving dependencies..." @@ -234,7 +240,7 @@ diagnose-env-macos: ## Print macOS build env and tool resolution @echo "NIX_CFLAGS_LINK=$${NIX_CFLAGS_LINK:-}" build-linux: export PUB_CACHE := $(LINUX_PUB_CACHE) -build-linux: check-reqs ## Build Linux Release through Flutter native-assets hooks +build-linux: require-version check-reqs ## Build Linux Release through Flutter native-assets hooks @echo "--- Running prebuild bootstrap..." @cd scripts && bash prebuild.sh @echo "--- Generating config..." @@ -274,13 +280,12 @@ build-linux: check-reqs ## Build Linux Release through Flutter native-assets hoo # where the user cannot create them (for example the GitHub-hosted runner). WINDOWS_COPY_ASSETS ?= 0 -build-windows: ## Build Windows release (Git Bash; same steps as CI) +build-windows: require-version ## Build Windows release (Git Bash; same steps as CI) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed."; exit 1; } @cd scripts && bash prebuild.sh @cd scripts && echo yes | MWEBD_FETCH=1 WINDOWS_COPY_ASSETS=$(WINDOWS_COPY_ASSETS) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d -s @$(FLUTTER) pub get - @$(DART) run coinlib:build_windows @$(FLUTTER) build windows --release # Android: same steps as the "build-android" CI job, without the signing secrets. Needs the Android SDK/NDK @@ -295,7 +300,7 @@ android-dev-key: ## Create a throw-away debug signing key if android/key.propert printf 'storeFile=../dev-keystore.jks\nstorePassword=android\nkeyPassword=android\nkeyAlias=devkey\n' > android/key.properties; \ fi -build-android: android-dev-key ## Build Android APKs (same steps as CI; signed with a throw-away key unless android/key.properties exists) +build-android: require-version android-dev-key ## Build Android APKs (same steps as CI; signed with a throw-away key unless android/key.properties exists) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } @cd scripts && bash prebuild.sh @@ -304,7 +309,7 @@ build-android: android-dev-key ## Build Android APKs (same steps as CI; signed w @$(FLUTTER) build apk --split-per-abi --release # iOS: same steps as the "build-ios" CI job (device build, no code signing). Run on macOS with Xcode. -build-ios: check-sdk-macos ## Build iOS Runner.app without code signing (same steps as CI) +build-ios: require-version check-sdk-macos ## Build iOS Runner.app without code signing (same steps as CI) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @cd scripts && bash prebuild.sh @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) -d -s diff --git a/README.md b/README.md index 1977ed7fae..221e52b1a1 100644 --- a/README.md +++ b/README.md @@ -58,8 +58,8 @@ Use one shared toolchain path for both `nix develop` and `direnv`. - run `direnv allow` 2. Enter the flake environment (if not using direnv): - `nix develop` -3. Run build: - - `make build-macos` +3. Run build (pass the release version and a build number; `make` refuses to guess): + - `make build-macos VERSION=x.y.z BUILD_NUM=nnn` ### macOS without Nix (Homebrew host setup) @@ -70,7 +70,7 @@ Use this only when you are not building through Nix/flake. 2. Run build: - Open a new terminal (or run `source ~/.zshrc`) so the Homebrew and Flutter PATH entries are active. - - `make build-macos` + - `make build-macos VERSION=x.y.z BUILD_NUM=nnn` The Homebrew bootstrap installs the native build tools and configures Rust 1.99.1 for Flutter's native-assets hooks. It replaces the former local diff --git a/bm/bench.sh b/bm/bench.sh index b53b2972da..efd88ffc3d 100755 --- a/bm/bench.sh +++ b/bm/bench.sh @@ -46,6 +46,10 @@ case "$(uname -s)" in *) echo "Unknown platform: $(uname -s)"; exit 1 ;; esac +# Build targets require VERSION and BUILD_NUM. Benchmarks measure build time +# only, so use throw-away values unless the caller passes their own in MAKE_FLAGS. +BENCH_ARGS="VERSION=${BENCH_VERSION:-0.0.0} BUILD_NUM=${BENCH_BUILD_NUM:-1}" + # Git info COMMIT="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)" BRANCH="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)" @@ -89,12 +93,12 @@ if [ $WARM -eq 0 ]; then fi # Build -echo "Building: make ${BUILD_TARGET} ${MAKE_FLAGS} " | banner +echo "Building: make ${BUILD_TARGET} ${BENCH_ARGS} ${MAKE_FLAGS} " | banner sccache --zero-stats >/dev/null 2>&1 || true START=$(date +%s) # A failing build must still be timed and recorded, so errexit is off for the build and its status is taken from make. set +e -make ${BUILD_TARGET} ${MAKE_FLAGS} 2>&1 | tail -5 +make ${BUILD_TARGET} ${BENCH_ARGS} ${MAKE_FLAGS} 2>&1 | tail -5 RC=${PIPESTATUS[0]} set -e END=$(date +%s) diff --git a/scripts/download_xcode.sh b/scripts/download_xcode.sh index e670be9bb1..7b18f036d5 100755 --- a/scripts/download_xcode.sh +++ b/scripts/download_xcode.sh @@ -154,6 +154,14 @@ if [[ -d "$TARGET_DIR" ]]; then CURRENT_BUILD="$("$TARGET_DIR/Contents/Developer/usr/bin/xcodebuild" -version 2>/dev/null | awk '/Build version/ {print $3}' || true)" if [[ "$CURRENT_BUILD" == "$BUILD_NUM" ]]; then echo "[OK] Xcode ${XCODE_VERSION} (${BUILD_NUM}) is already installed at ${TARGET_DIR}." + if [[ $DRY_RUN -eq 1 ]]; then + if [[ $ASSUME_YES -eq 1 ]]; then + echo "[DRY-RUN] Already installed; would select it, accept the license and run first-launch setup." + else + echo "[DRY-RUN] Already installed; nothing to download." + fi + exit 0 + fi # With -y, finish selection/license/first-launch now instead of exiting # before the setup the caller explicitly asked for. finish_install diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 20c8f27817..991fcb1436 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -86,6 +86,36 @@ int _cmp(String a, String b) { return 0; } +/// Plugins declared by the app currently configured in pubspec.yaml. +/// +/// Campfire and Stack Duo include only a subset of the pinned plugins, so a +/// missing lock entry is only an error for a plugin the app actually uses. +Set _declaredPlugins() { + final file = File('pubspec.yaml'); + if (!file.existsSync()) return {}; + final declared = {}; + var inDependencies = false; + for (final line in file.readAsLinesSync()) { + if (line.startsWith('dependencies:')) { + inDependencies = true; + continue; + } + // A non-indented, non-comment line starts the next top-level section. + if (inDependencies && + line.isNotEmpty && + !line.startsWith(' ') && + !line.startsWith('#')) { + inDependencies = false; + } + if (!inDependencies) continue; + final m = RegExp(r'^ (\w+):').firstMatch(line); + if (m != null && _pluginNames.contains(m.group(1))) { + declared.add(m.group(1)!); + } + } + return declared; +} + /// Reads the git refs of the pinned plugins from pubspec.lock. Map _lockRefs() { final lock = File('pubspec.lock'); @@ -111,6 +141,11 @@ Future _update() async { exit(2); } final text = File(_bomFile).readAsStringSync(); + final existing = _readBom(text)['plugins'] ?? {}; + final declared = _declaredPlugins(); + // Without a pubspec.yaml we cannot tell which app is configured; keep the + // old behaviour and update every plugin the lock knows about. + final updateable = declared.isEmpty ? _pluginNames.toSet() : declared; final start = text.indexOf('[plugins]'); final head = start < 0 ? text.trimRight() @@ -121,11 +156,19 @@ Future _update() async { ..writeln( '# Generated by `dart tool/verify_bom.dart --update` from pubspec.lock. Do not edit by hand.', ); + var written = 0; for (final n in _pluginNames) { - if (refs.containsKey(n)) buf.writeln('$n = "${refs[n]}"'); + if (updateable.contains(n) && refs.containsKey(n)) { + buf.writeln('$n = "${refs[n]}"'); + written++; + } else if (existing.containsKey(n)) { + // Keep pins for apps this checkout is not configured for. + buf.writeln('$n = "${existing[n]}"'); + written++; + } } File(_bomFile).writeAsStringSync(buf.toString()); - stdout.writeln('Updated [plugins] in $_bomFile (${refs.length} entries).'); + stdout.writeln('Updated [plugins] in $_bomFile ($written entries).'); } Future main(List args) async { @@ -222,10 +265,17 @@ Future main(List args) async { // Pinned plugins against pubspec.lock final refs = _lockRefs(); final pinned = bom['plugins'] ?? {}; + final declared = _declaredPlugins(); if (refs.isEmpty) { _warn('pubspec.lock not found, plugin pins not checked'); + } else if (declared.isEmpty) { + _warn( + 'pubspec.yaml declares none of the pinned plugins, ' + 'plugin pins not checked', + ); } else { for (final n in _pluginNames) { + if (!declared.contains(n)) continue; final ref = refs[n]; final pin = pinned[n]; if (ref == null) { From 677bcb320a83a3306fcd3a08d2a13be10727a9d6 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:30:59 +0200 Subject: [PATCH 024/107] build: add toolchain selection and dnix mode defaults - Makefile: add TOOLCHAIN=auto|nix|direnv|brew|manual, make toolchain, make bootstrap and a Homebrew fallback alias, with early dnix checks. - Build dnix source by default on macOS and Linux; keep verified prebuilts for Windows, CI and Android on macOS. - flake.nix: leave Apple's compiler and SDK to Xcode, resolve per-checkout state from the git root, read Rust from stack-bom.toml and align the Linux package set with CI. - Homebrew helper: read Flutter and Rust versions from stack-bom.toml. - .envrc: skip the flake when Nix is absent. - CI and benchmark scripts: record the new source/prebuilt defaults. --- .envrc | 6 +- .github/workflows/make-build.yaml | 10 ++- .gitignore | 3 +- Makefile | 126 +++++++++++++++++++++++---- bm/bench.sh | 10 +-- bm/run_all.sh | 12 +-- flake.nix | 98 +++++++++++---------- scripts/install_macos_build_tools.sh | 21 +++-- 8 files changed, 201 insertions(+), 85 deletions(-) diff --git a/.envrc b/.envrc index 3550a30f2d..e9e6491daa 100644 --- a/.envrc +++ b/.envrc @@ -1 +1,5 @@ -use flake +# Nix is the primary toolchain. Without it, leave the shell alone instead of +# failing with a blocked .envrc; use make bootstrap-macos and PREBUILTS=1. +if has nix; then + use flake +fi diff --git a/.github/workflows/make-build.yaml b/.github/workflows/make-build.yaml index dfc148d759..45fa26bb16 100644 --- a/.github/workflows/make-build.yaml +++ b/.github/workflows/make-build.yaml @@ -1,6 +1,10 @@ name: Make build # Builds with the Makefile targets on the hosted runners. Manual only. +# +# The Makefile builds dnix source by default on macOS and Linux. These jobs use +# the same verified prebuilts as the release workflow (build.yaml); source and +# reproducibility builds belong to the dnix packages' own CI. on: workflow_dispatch: @@ -50,7 +54,7 @@ jobs: rustup toolchain install 1.99.1 --profile minimal || true rustup default 1.99.1 || true - name: Build - run: make build-macos VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} + run: make build-macos VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 linux: runs-on: ubuntu-24.04 @@ -84,7 +88,7 @@ jobs: - name: Check the toolchain bill of materials run: make verify-bom - name: Build - run: make build-linux VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} + run: make build-linux VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 ios: # The fork has a single hosted macOS concurrency slot. Running macOS and @@ -109,4 +113,4 @@ jobs: rustup toolchain install 1.99.1 --profile minimal || true rustup default 1.99.1 || true - name: Build - run: make build-ios VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} + run: make build-ios VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 diff --git a/.gitignore b/.gitignore index f3393861e8..893ff52489 100644 --- a/.gitignore +++ b/.gitignore @@ -131,6 +131,7 @@ bm/results/ # Nix dev shell: generated wrappers .nix-bin/ -.direnv/ + +# Android local signing /android/key.properties /android/dev-keystore.jks diff --git a/Makefile b/Makefile index f8f1032f76..5553d2b131 100644 --- a/Makefile +++ b/Makefile @@ -17,6 +17,26 @@ DART := $(DART_BIN) APP_PROJECT_ROOT_DIR := $(CURDIR) # Platform detection from uname. PLATFORM ?= $(shell uname -s 2>/dev/null) +# Toolchain source. Nix (nix develop or direnv) is the primary path; Homebrew +# and manual installs use the host tools already on PATH. The build steps are +# identical in every mode: only the prerequisite check and the Nix environment +# sanitising differ. Override with TOOLCHAIN=nix|direnv|brew|manual. +TOOLCHAIN ?= auto +DIRENV_ACTIVE := $(if $(DIRENV_DIR),1,) +NIX_ACTIVE := $(if $(or $(IN_NIX_SHELL),$(NIX_STORE)),1,) +ifeq ($(TOOLCHAIN),auto) + ifeq ($(DIRENV_ACTIVE),1) + TOOLCHAIN_EFFECTIVE := direnv + else + ifeq ($(NIX_ACTIVE),1) + TOOLCHAIN_EFFECTIVE := nix + else + TOOLCHAIN_EFFECTIVE := host + endif + endif +else + TOOLCHAIN_EFFECTIVE := $(TOOLCHAIN) +endif # Linux builds use a project-local pub cache so cargo finds the repo-local # .cargo/config.toml that carries PROTOC through Flutter's filtered hook environment. # Other targets leave PUB_CACHE unset, so Flutter uses its normal per-user cache @@ -26,24 +46,81 @@ PUB_CACHE ?= PROTOC_PATH := $(shell which protoc 2>/dev/null) # Toolchain installed for host-side checks/targets. Native-assets crates pick their own # pinned toolchain via rust-toolchain.toml; do not export RUSTUP_TOOLCHAIN globally. -RUST_VERSION ?= 1.99.1 +BOM_FILE := $(APP_PROJECT_ROOT_DIR)/stack-bom.toml +BOM_RUST := $(shell sed -n 's/^rust[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' $(BOM_FILE) 2>/dev/null | head -n1) +RUST_VERSION ?= $(if $(BOM_RUST),$(BOM_RUST),1.99.1) +# Only strip Nix/Apple variables when a Nix shell actually supplied them. In a +# Homebrew or manual shell these are the user's own settings and are kept. +ifeq ($(NIX_ACTIVE),1) MACOS_ENV_UNSET = -u LD -u LDFLAGS -u NIX_LDFLAGS -u NIX_CFLAGS_LINK \ -u CFLAGS -u CXXFLAGS -u CPPFLAGS \ -u SDKROOT -u BINDGEN_EXTRA_CLANG_ARGS \ -u IPHONEOS_DEPLOYMENT_TARGET -u TVOS_DEPLOYMENT_TARGET -u WATCHOS_DEPLOYMENT_TARGET \ -u XROS_DEPLOYMENT_TARGET -u XR_DEPLOYMENT_TARGET +else +MACOS_ENV_UNSET = +endif export APP_PROJECT_ROOT_DIR ifneq ($(strip $(PUB_CACHE)),) export PUB_CACHE endif -.PHONY: help require-version check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios +.PHONY: help toolchain toolchain-check dnix-check dnix-check-android bootstrap bootstrap-brew require-version check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios help: ## Show available commands @echo "Available targets:" @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "%-20s %s\n", $$1, $$2}' +# --- TOOLCHAIN --- + +toolchain: ## Show the active toolchain and tool paths + @echo "requested : $(TOOLCHAIN)" + @echo "effective : $(TOOLCHAIN_EFFECTIVE)" + @echo "NIX_STORE : $${NIX_STORE:-}" + @echo "DIRENV_DIR: $${DIRENV_DIR:-}" + @echo "flutter : $(if $(FLUTTER),$(FLUTTER),missing)" + @echo "dart : $(if $(DART),$(DART),missing)" + @echo "rustup : $$(command -v rustup || echo missing)" + @echo "brew : $$(command -v brew || echo missing)" + @echo "xcode : $$(xcode-select -p 2>/dev/null || echo missing)" + +toolchain-check: ## Fail when the requested toolchain is not active +ifeq ($(TOOLCHAIN_EFFECTIVE),nix) + @[ -n "$$NIX_STORE$$IN_NIX_SHELL" ] || { echo >&2 "[ERROR] TOOLCHAIN=nix but this is not a Nix dev shell. Run 'nix develop' (or 'make bootstrap')."; exit 1; } +endif +ifeq ($(TOOLCHAIN_EFFECTIVE),direnv) + @[ -n "$$NIX_STORE$$IN_NIX_SHELL" ] || { echo >&2 "[ERROR] TOOLCHAIN=direnv but the flake is not loaded. Run 'direnv allow', or use 'nix develop'."; exit 1; } +endif +ifeq ($(TOOLCHAIN_EFFECTIVE),brew) + @command -v brew >/dev/null 2>&1 || { echo >&2 "[ERROR] TOOLCHAIN=brew but brew is not on PATH. Run 'make bootstrap-macos'."; exit 1; } +endif + +bootstrap: ## Enter the Nix dev shell (primary toolchain; no-op when already inside) + @if [ -n "$$NIX_STORE$$IN_NIX_SHELL" ]; then \ + echo "[OK] Already inside a Nix dev shell ($(TOOLCHAIN_EFFECTIVE))."; \ + elif ! command -v nix >/dev/null 2>&1; then \ + echo >&2 "[ERROR] Nix is not installed. Install it from https://nixos.org/download/, or use the Homebrew fallback: make bootstrap-macos"; \ + exit 1; \ + else \ + echo "Entering the Nix dev shell. Run 'make build-macos VERSION=... BUILD_NUM=...' inside it."; \ + exec nix develop; \ + fi + +bootstrap-brew: bootstrap-macos ## Alias for the Homebrew fallback toolchain + +dnix-check: ## Fail when a dnix source build is requested without Nix + @if [ "$(PREBUILTS)" = "0" ] && ! command -v nix >/dev/null 2>&1; then \ + echo >&2 "[ERROR] PREBUILTS=0 (dnix source) needs Nix. Use PREBUILTS=1, or run 'make bootstrap'."; \ + exit 1; \ + fi + +dnix-check-android: ## Fail when an Android dnix source build is requested without Nix + @if [ "$(ANDROID_PREBUILTS)" = "0" ] && ! command -v nix >/dev/null 2>&1; then \ + echo >&2 "[ERROR] Android source builds need Nix. Use PREBUILTS=1, or run 'make bootstrap'."; \ + exit 1; \ + fi + # --- PREREQUISITES --- require-version: ## Fail unless VERSION and BUILD_NUM are set explicitly @@ -64,7 +141,7 @@ check-reqs: ## Verify essential build tools @command -v cmake >/dev/null 2>&1 || { echo >&2 "[ERROR] CMake not installed."; exit 1; } @command -v meson >/dev/null 2>&1 || { \ if [ "$(PLATFORM)" = "Darwin" ]; then \ - echo >&2 "[ERROR] Meson not installed. On macOS, run 'make bootstrap-macos' or 'brew install meson'."; \ + echo >&2 "[ERROR] Meson not installed. Use 'nix develop' (recommended) or run 'make bootstrap-macos'."; \ elif [ "$(PLATFORM)" = "Linux" ]; then \ echo >&2 "[ERROR] Meson not installed. On Linux/NixOS, run in 'nix develop' or install meson via your package manager."; \ else \ @@ -74,7 +151,7 @@ check-reqs: ## Verify essential build tools } @command -v ninja >/dev/null 2>&1 || { \ if [ "$(PLATFORM)" = "Darwin" ]; then \ - echo >&2 "[ERROR] Ninja not installed. On macOS, run 'make bootstrap-macos' or 'brew install ninja'."; \ + echo >&2 "[ERROR] Ninja not installed. Use 'nix develop' (recommended) or run 'make bootstrap-macos'."; \ elif [ "$(PLATFORM)" = "Linux" ]; then \ echo >&2 "[ERROR] Ninja not installed. On Linux/NixOS, run in 'nix develop' or install ninja via your package manager."; \ else \ @@ -103,12 +180,15 @@ ifeq ($(PLATFORM),Darwin) echo "[ERROR] macOS SDK not available. Install Xcode or run: sudo xcode-select --switch /Applications/Xcode.app"; \ exit 1) @echo "[OK] macOS SDK available at: $$(xcrun --sdk macosx --show-sdk-path)" +else + @echo >&2 "[ERROR] check-sdk-macos is macOS-only." + @exit 1 endif check-reqs-macos: check-reqs ## Verify macOS-specific tools are available in PATH ifeq ($(PLATFORM),Darwin) @echo "Checking macOS-specific tools in PATH..." - @rustup run $(RUST_VERSION) rustc -vV >/dev/null 2>&1 || { echo >&2 "[ERROR] Rust $(RUST_VERSION) toolchain not available. Run 'make bootstrap-macos'."; exit 1; } + @rustup run $(RUST_VERSION) rustc -vV >/dev/null 2>&1 || { echo >&2 "[ERROR] Rust $(RUST_VERSION) toolchain not available. Run 'nix develop' (recommended) or 'make bootstrap-macos'."; exit 1; } @command -v pod >/dev/null 2>&1 || { echo >&2 "[ERROR] CocoaPods (pod) not installed."; exit 1; } @command -v xcodebuild >/dev/null 2>&1 || { echo >&2 "[ERROR] xcodebuild not available."; exit 1; } @echo "[OK] macOS-specific toolchain is available." @@ -117,12 +197,12 @@ else @exit 1 endif -bootstrap-macos: ## Install required macOS build tools via Homebrew helper script +bootstrap-macos: ## Install the Homebrew fallback toolchain (Nix is the primary path) ifeq ($(PLATFORM),Darwin) # Call install_xcode.sh directly instead of `$(MAKE) bootstrap-xcode`: a recipe # line containing $(MAKE) is executed even under `make -n`, which would make a # dry run accept the Xcode license and run first-launch setup for real. - @if [ -n "$$IN_NIX_SHELL" ] || [ -n "$$NIX_BUILD_TOP" ]; then \ + @if [ -n "$$IN_NIX_SHELL$$NIX_BUILD_TOP$$NIX_STORE" ]; then \ echo "[WARN] Nix environment detected; skipping the Homebrew package install (use nix/flake-provided toolchain instead)."; \ echo "[WARN] Xcode itself is never provided by Nix (Apple's license forbids redistributing it), so that part still runs:"; \ bash scripts/install_xcode.sh || exit 1; \ @@ -189,7 +269,21 @@ clean: ## Remove artifacts and fix permissions # --- PLATFORM BUILDS --- -PREBUILTS ?= 1 +# dnix mode. macOS and Linux build the pinned native libraries from source by +# default (the Nix-primary developer path). Windows and CI use verified +# prebuilts. PREBUILTS=1 passes -d and needs no Nix for those four libraries; +# PREBUILTS=0 builds them with Nix and verifies the hashes. +ifeq ($(PLATFORM),Darwin) +PREBUILTS ?= 0 +else + ifeq ($(PLATFORM),Linux) + PREBUILTS ?= 0 + else + PREBUILTS ?= 1 + endif +endif +# Android source builds through dnix need an x86_64 Linux host. +ANDROID_PREBUILTS ?= $(if $(filter Darwin,$(PLATFORM)),1,$(PREBUILTS)) # Linux only: SYSTEM_DEPS=1 uses the system libsecret/jsoncpp packages instead of building them (like the CI image). SYSTEM_DEPS ?= 0 LINUX_ARCH := $(shell uname -m | sed -e 's/x86_64/x64/' -e 's/aarch64/arm64/') @@ -206,7 +300,7 @@ clean-native: ## Remove only the native-asset build outputs (forces the Rust/Go/ @rm -rf .dart_tool/hooks_runner build/native_assets @echo "[OK] Removed .dart_tool/hooks_runner and build/native_assets." -build-macos: require-version check-reqs-macos check-sdk-macos ## Build macOS release (same steps as upstream CI; PREBUILTS=0 compiles native assets from source) +build-macos: require-version toolchain-check dnix-check check-reqs-macos check-sdk-macos ## Build macOS release (source by default; PREBUILTS=1 uses verified prebuilts) @echo "--- Configuring project (scripts/build_app.sh)..." @cd scripts && echo yes | env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a $(APP_NAME) -s $(if $(filter 1,$(PREBUILTS)),-d) @echo "--- Resolving dependencies..." @@ -240,7 +334,7 @@ diagnose-env-macos: ## Print macOS build env and tool resolution @echo "NIX_CFLAGS_LINK=$${NIX_CFLAGS_LINK:-}" build-linux: export PUB_CACHE := $(LINUX_PUB_CACHE) -build-linux: require-version check-reqs ## Build Linux Release through Flutter native-assets hooks +build-linux: require-version toolchain-check dnix-check check-reqs ## Build Linux Release through Flutter native-assets hooks @echo "--- Running prebuild bootstrap..." @cd scripts && bash prebuild.sh @echo "--- Generating config..." @@ -278,9 +372,11 @@ build-linux: require-version check-reqs ## Build Linux Release through Flutter n # Windows: run from Git Bash. Same steps as the "build-windows" job in .github/workflows/build.yaml. # WINDOWS_COPY_ASSETS=1 makes link_assets.sh copy instead of creating symlinks, for hosts # where the user cannot create them (for example the GitHub-hosted runner). +# Windows uses verified dnix prebuilts; source mode needs Nix inside WSL2 and is +# driven by build_app.sh directly, not by this target. WINDOWS_COPY_ASSETS ?= 0 -build-windows: require-version ## Build Windows release (Git Bash; same steps as CI) +build-windows: require-version toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed."; exit 1; } @cd scripts && bash prebuild.sh @@ -300,18 +396,18 @@ android-dev-key: ## Create a throw-away debug signing key if android/key.propert printf 'storeFile=../dev-keystore.jks\nstorePassword=android\nkeyPassword=android\nkeyAlias=devkey\n' > android/key.properties; \ fi -build-android: require-version android-dev-key ## Build Android APKs (same steps as CI; signed with a throw-away key unless android/key.properties exists) +build-android: require-version toolchain-check dnix-check-android android-dev-key ## Build Android APKs (prebuilt dnix on macOS; Linux follows PREBUILTS) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } @cd scripts && bash prebuild.sh - @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p android -a $(APP_NAME) -d -s + @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p android -a $(APP_NAME) $(if $(filter 1,$(ANDROID_PREBUILTS)),-d) -s @$(FLUTTER) pub get @$(FLUTTER) build apk --split-per-abi --release # iOS: same steps as the "build-ios" CI job (device build, no code signing). Run on macOS with Xcode. -build-ios: require-version check-sdk-macos ## Build iOS Runner.app without code signing (same steps as CI) +build-ios: require-version check-sdk-macos toolchain-check dnix-check ## Build iOS Runner.app without code signing (same steps as CI) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @cd scripts && bash prebuild.sh - @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) -d -s + @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) -s @$(FLUTTER) pub get @$(FLUTTER) build ios --release --no-codesign diff --git a/bm/bench.sh b/bm/bench.sh index efd88ffc3d..d743ad5e2d 100755 --- a/bm/bench.sh +++ b/bm/bench.sh @@ -3,9 +3,9 @@ # bench.sh: Simple build benchmark for stack_wallet # # Usage: -# bash bm/bench.sh # cold build with prebuilt native assets (-d) +# bash bm/bench.sh # cold build, dnix source (default on macOS/Linux) # bash bm/bench.sh --warm # warm rebuild (no clean) -# bash bm/bench.sh PREBUILTS=0 # cold, native assets compiled from source +# bash bm/bench.sh PREBUILTS=1 # cold build with verified dnix prebuilts (-d) # # sccache is a machine setting, not a flag: run once, `make sccache-setup`, run again. # The label records whether ~/.cargo/config.toml or CARGO_BUILD_RUSTC_WRAPPER selects sccache. @@ -57,10 +57,10 @@ BRANCH="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)" # Auto-generate label only if not explicitly set if [ -z "$LABEL" ]; then LABEL=$([ $WARM -eq 1 ] && echo "warm" || echo "cold") - if echo "$MAKE_FLAGS" | grep -q "PREBUILTS=0"; then - LABEL="${LABEL}-source" - else + if echo "$MAKE_FLAGS" | grep -q "PREBUILTS=1"; then LABEL="${LABEL}-prebuilt" + else + LABEL="${LABEL}-source" fi if grep -qs 'rustc-wrapper *= *"sccache"' "$HOME/.cargo/config.toml" 2>/dev/null \ || [ "${CARGO_BUILD_RUSTC_WRAPPER:-}" = "sccache" ]; then diff --git a/bm/run_all.sh b/bm/run_all.sh index 098b7c9188..097e48f23a 100755 --- a/bm/run_all.sh +++ b/bm/run_all.sh @@ -3,10 +3,10 @@ # run_all.sh: Benchmark suite for `make build-macos`. # # Run order (cold = after `make clean`, warm = rebuild right after): -# A. Cold, prebuilt native assets (default) -# B. Warm, prebuilt native assets -# C. Cold, native assets compiled from source (PREBUILTS=0) -# D. Warm, native assets compiled from source +# A. Cold, verified dnix prebuilts (PREBUILTS=1) +# B. Warm, verified dnix prebuilts +# C. Cold, dnix source (PREBUILTS=0, the macOS/Linux default) +# D. Warm, dnix source # # sccache is a machine setting: run the suite once as is, then run # `make sccache-setup` and run it again; the label records which one it was. @@ -20,11 +20,11 @@ echo "" echo "A: cold, prebuilt" make clean 2>/dev/null || true -bash bm/bench.sh +bash bm/bench.sh PREBUILTS=1 echo "" echo "B: warm, prebuilt" -bash bm/bench.sh --warm +bash bm/bench.sh --warm PREBUILTS=1 echo "" echo "C: cold, from source" diff --git a/flake.nix b/flake.nix index b36de7dfa4..9ba14e2d07 100644 --- a/flake.nix +++ b/flake.nix @@ -14,7 +14,11 @@ let pkgs = import nixpkgs { inherit system; }; lib = pkgs.lib; - rustVersion = "1.99.1"; + # Single source of truth for the toolchain versions; the Homebrew + # helper and the Makefile read the same file. + bom = builtins.fromTOML (builtins.readFile ./stack-bom.toml); + rustVersion = bom.toolchain.rust; + clangMajor = lib.versions.major pkgs.llvmPackages.clang.version; commonPackages = with pkgs; [ flutter @@ -43,6 +47,9 @@ libsysprof-capture patchelf binutils + tpm2-tss + ocl-icd + opencl-headers ]); macPackages = lib.optionals pkgs.stdenv.isDarwin (with pkgs; [ @@ -64,7 +71,9 @@ echo "Target System: ${system}" echo "===================================================" - export APP_PROJECT_ROOT_DIR=$(pwd) + # Resolve the repository root, not the directory the shell was + # entered from; .nix-bin and the rustup override are per checkout. + export APP_PROJECT_ROOT_DIR="$(git rev-parse --show-toplevel 2>/dev/null || pwd)" export PATH="$HOME/.cargo/bin:$PATH" # The standalone Dart in the Nix Flutter wrapper cannot find the Flutter SDK on its own, @@ -81,7 +90,7 @@ fi # Pin this checkout without replacing the user's global rustup default. - rustup override set ${rustVersion} --path "$PWD" >/dev/null 2>&1 || true + rustup override set ${rustVersion} --path "$APP_PROJECT_ROOT_DIR" >/dev/null 2>&1 || true if [[ "${system}" == *"darwin"* ]]; then rustup target add aarch64-apple-darwin aarch64-apple-ios --toolchain ${rustVersion} @@ -98,7 +107,7 @@ ${lib.optionalString pkgs.stdenv.isLinux '' # echo "🐧 Linux detected: Patching shebangs for NixOS..." export LIBCLANG_PATH="${pkgs.llvmPackages.libclang.lib}/lib" - export BINDGEN_EXTRA_CLANG_ARGS="-isystem ${pkgs.llvmPackages.libclang.lib}/lib/clang/${pkgs.llvmPackages.clang.version}/include" + export BINDGEN_EXTRA_CLANG_ARGS="-isystem ${pkgs.llvmPackages.libclang.lib}/lib/clang/${clangMajor}/include" export PROTOC="${pkgs.protobuf}/bin/protoc" ''} @@ -106,27 +115,26 @@ # MACOS XCODE SANDBOX ESCAPE # ========================================== ${lib.optionalString pkgs.stdenv.isDarwin '' - # Nix cannot provide Xcode itself (Apple's license forbids - # redistributing it), so this only works once it's installed - # separately -- run `make bootstrap-xcode` if this warns. - if [ ! -d /Applications/Xcode.app ]; then - echo "[WARN] /Applications/Xcode.app not found. Full Xcode (not just Command Line Tools) is required for macOS/iOS builds. Run: make bootstrap-xcode" - fi - # Respect whatever Xcode is actually active via `xcode-select` - # instead of forcing the default install location -- hardcoding - # this broke `sudo xcode-select --switch` to a differently - # named/located Xcode (e.g. testing a second version side by - # side), causing exactly the kind of toolchain/SDK mismatch - # this whole escape hatch exists to prevent. `xcode-select -p` - # itself just echoes back an already-set DEVELOPER_DIR (per its - # man page), and nixpkgs' own Darwin stdenv sets one earlier in - # this shellHook (to its vendored apple-sdk) -- so it must be - # unset first to actually query the real system-wide selection. - export DEVELOPER_DIR="$(env -u DEVELOPER_DIR xcode-select -p 2>/dev/null || echo /Applications/Xcode.app/Contents/Developer)" - export SDKROOT=$(xcrun --sdk macosx --show-sdk-path) + # Nix supplies the host tools, never Apple's compiler or SDK. + # Flutter, CocoaPods and Xcode use the toolchain selected by + # xcode-select. Do not export SDKROOT here: it makes an iOS build + # compile against the macOS SDK. + SELECTED_DEVELOPER="$(env -u DEVELOPER_DIR xcode-select -p 2>/dev/null || true)" + case "$SELECTED_DEVELOPER" in + *.app/Contents/Developer) ;; + *) + echo "[WARN] No full Xcode selected. Install Xcode and run 'make bootstrap-xcode'." + SELECTED_DEVELOPER="/Applications/Xcode.app/Contents/Developer" + ;; + esac + export DEVELOPER_DIR="$SELECTED_DEVELOPER" + # nixpkgs' Darwin stdenv exports its own macOS SDK here before + # this hook runs; leave the SDK choice to Xcode per build. + unset SDKROOT export MACOSX_DEPLOYMENT_TARGET="12.0" - # --- NIX C++ COMPILER OVERRIDE --- + # Force Apple's tools even though the Nix shell puts its own + # clang and binutils first on PATH. export CC=/usr/bin/clang export CXX=/usr/bin/clang++ unset LD @@ -136,23 +144,24 @@ export RANLIB=/usr/bin/ranlib export STRIP=/usr/bin/strip - export BINDGEN_EXTRA_CLANG_ARGS="-isysroot $SDKROOT" + export BINDGEN_EXTRA_CLANG_ARGS="-isysroot $(/usr/bin/xcrun --sdk macosx --show-sdk-path)" export PROTOC="${pkgs.protobuf}/bin/protoc" - mkdir -p .nix-bin - ln -sf /usr/bin/clang .nix-bin/cc - ln -sf /usr/bin/clang++ .nix-bin/c++ - ln -sf /usr/bin/xcodebuild .nix-bin/xcodebuild - ln -sf /usr/bin/clang .nix-bin/clang - ln -sf /usr/bin/clang++ .nix-bin/clang++ + NIX_BIN="$APP_PROJECT_ROOT_DIR/.nix-bin" + mkdir -p "$NIX_BIN" + ln -sf /usr/bin/clang "$NIX_BIN/cc" + ln -sf /usr/bin/clang++ "$NIX_BIN/c++" + ln -sf /usr/bin/xcodebuild "$NIX_BIN/xcodebuild" + ln -sf /usr/bin/clang "$NIX_BIN/clang" + ln -sf /usr/bin/clang++ "$NIX_BIN/clang++" # SMART LIPO & XCRUN WRAPPER # lipo wrapper: the Nix store copy of FlutterMacOS.framework is # read-only, so make its containing dir writable before handing # off to the real lipo. - rm -f .nix-bin/lipo .nix-bin/xcrun + rm -f "$NIX_BIN/lipo" "$NIX_BIN/xcrun" - cat > .nix-bin/lipo <<'LIPO_EOF' + cat > "$NIX_BIN/lipo" <<'LIPO_EOF' #!/bin/bash for arg in "$@"; do if [[ "$arg" == *"FlutterMacOS.framework"* ]]; then @@ -161,30 +170,23 @@ for arg in "$@"; do done exec /usr/bin/lipo "$@" LIPO_EOF - chmod +x .nix-bin/lipo - - # xcrun wrapper: `xcrun -f lipo` must resolve to the wrapper - # above rather than the real /usr/bin/lipo. Everything else - # passes through to the real xcrun, with deployment-target/SDK - # env vars pinned to macOS so a leaked iOS/tvOS/etc value from - # the outer environment doesn't leak in. - cat > .nix-bin/xcrun <<'XCRUN_EOF' + chmod +x "$NIX_BIN/lipo" + + # xcrun wrapper: `xcrun -f lipo` must resolve to the wrapper above. + # Everything else passes straight through, so an iOS build keeps + # its deployment target and SDK. + cat > "$NIX_BIN/xcrun" <<'XCRUN_EOF' #!/bin/bash if [ "$1" = "-f" ] && [ "$2" = "lipo" ]; then echo "__NIX_BIN_DIR__/lipo" exit 0 fi - -unset IPHONEOS_DEPLOYMENT_TARGET TVOS_DEPLOYMENT_TARGET WATCHOS_DEPLOYMENT_TARGET -unset XROS_DEPLOYMENT_TARGET XR_DEPLOYMENT_TARGET VISIONOS_DEPLOYMENT_TARGET DRIVERKIT_DEPLOYMENT_TARGET -export MACOSX_DEPLOYMENT_TARGET="''${MACOSX_DEPLOYMENT_TARGET:-12.0}" -export SDKROOT="''${SDKROOT:-$(/usr/bin/xcrun --sdk macosx --show-sdk-path)}" exec /usr/bin/xcrun "$@" XCRUN_EOF - sed -i.bak "s|__NIX_BIN_DIR__|$PWD/.nix-bin|" .nix-bin/xcrun && rm -f .nix-bin/xcrun.bak - chmod +x .nix-bin/xcrun + sed -i.bak "s|__NIX_BIN_DIR__|$NIX_BIN|" "$NIX_BIN/xcrun" && rm -f "$NIX_BIN/xcrun.bak" + chmod +x "$NIX_BIN/xcrun" - export PATH="$PWD/.nix-bin:$PATH" + export PATH="$NIX_BIN:$PATH" ''} ''; diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh index ec78b1bbb5..8927786dee 100755 --- a/scripts/install_macos_build_tools.sh +++ b/scripts/install_macos_build_tools.sh @@ -52,6 +52,13 @@ add_rustup_to_path() { add_rustup_to_path SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]:-$0}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +# Read a value from stack-bom.toml so the Homebrew fallback and the flake use +# the same versions. +bom_value() { + sed -n "s/^$1[[:space:]]*=[[:space:]]*\"\\([^\"]*\\)\".*/\\1/p" \ + "$REPO_ROOT/stack-bom.toml" 2>/dev/null | head -n 1 +} bash "$SCRIPT_DIR/install_xcode.sh" echo "Installing Homebrew packages..." @@ -66,13 +73,15 @@ brew install pandoc weasyprint toilet figlet || echo "[WARN] optional report too # The Homebrew cask always installs the latest Flutter, but CI builds and tests # one pinned release. Install that tag from source instead. -FLUTTER_VERSION="${FLUTTER_VERSION:-3.47.2}" -# Both the CI version and the version pinned by the Nix shell/BOM work. An -# explicit FLUTTER_VERSION only accepts that version. +FLUTTER_RECOMMENDED="$(bom_value flutter)" +FLUTTER_MIN="$(bom_value flutter_min)" +FLUTTER_VERSION="${FLUTTER_VERSION:-${FLUTTER_RECOMMENDED:-3.47.2}}" +# Accept the recommended version and the CI minimum; an explicit +# FLUTTER_VERSION only accepts that version. if [[ -n "${FLUTTER_ACCEPTED_VERSIONS:-}" ]]; then : -elif [[ "$FLUTTER_VERSION" == "3.47.2" ]]; then - FLUTTER_ACCEPTED_VERSIONS="3.47.2 3.47.4" +elif [[ -n "$FLUTTER_MIN" && "$FLUTTER_VERSION" == "$FLUTTER_RECOMMENDED" ]]; then + FLUTTER_ACCEPTED_VERSIONS="$FLUTTER_VERSION $FLUTTER_MIN" else FLUTTER_ACCEPTED_VERSIONS="$FLUTTER_VERSION" fi @@ -81,7 +90,6 @@ case "$FLUTTER_DIR" in /*) ;; *) FLUTTER_DIR="$PWD/$FLUTTER_DIR" ;; esac -REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" flutter_installed_version() { "$1" --version --machine 2>/dev/null | sed -n 's/.*"frameworkVersion": *"\([^"]*\)".*/\1/p' | head -n 1 @@ -132,6 +140,7 @@ if ! command -v rustup >/dev/null 2>&1; then die "rustup not found in PATH. Check brew install." fi +RUST_VERSION="${RUST_VERSION:-$(bom_value rust)}" RUST_VERSION="${RUST_VERSION:-1.99.1}" echo "Ensuring Rust $RUST_VERSION toolchain..." rustup toolchain install "$RUST_VERSION" From 522c33a53569d33b0ccb29b669732d7eccc23e0a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:31:27 +0200 Subject: [PATCH 025/107] docs: document the make toolchain and build flow - Lead with the Nix dev shell, with direnv, Homebrew and manual fallbacks. - Document the dnix source/prebuilt defaults per platform and the new make targets. - Add make-flow.md with the toolchain and build diagrams, and link it from the building pages. --- README.md | 41 ++++++++---- docs/building/macos.md | 30 +++++++-- docs/building/make-flow.md | 134 +++++++++++++++++++++++++++++++++++++ 3 files changed, 186 insertions(+), 19 deletions(-) create mode 100644 docs/building/make-flow.md diff --git a/README.md b/README.md index 221e52b1a1..a246cfc797 100644 --- a/README.md +++ b/README.md @@ -48,31 +48,48 @@ Highlights include: ## Building You can look at the [build instructions](docs/building.md) for more details. +On macOS, the **Nix dev shell** is the primary *host* toolchain; Homebrew and +manual installs are supported fallbacks. dnix builds and verifies the four +native libraries underneath all of them. `make build-macos` is the same target +in every mode, and `make toolchain` shows which host environment your shell is +using. -### macOS with Nix or direnv +### macOS with Nix (recommended) -Use one shared toolchain path for both `nix develop` and `direnv`. - -1. Enable direnv for this repo (optional convenience): - - `.envrc` uses `use flake` - - run `direnv allow` -2. Enter the flake environment (if not using direnv): - - `nix develop` -3. Run build (pass the release version and a build number; `make` refuses to guess): +1. Enter the flake environment: + - `make bootstrap` (runs `nix develop`), or + - `nix develop` directly, or + - `direnv allow` once, if you use direnv with the included `.envrc`. +2. Run build (pass the release version and a build number; `make` refuses to guess): - `make build-macos VERSION=x.y.z BUILD_NUM=nnn` -### macOS without Nix (Homebrew host setup) +The flake provides Flutter, Dart, Rust, Go, CMake, Meson, Ninja, pkg-config +and protoc. Xcode is never provided by Nix; the flake uses the Xcode selected +by `xcode-select`. + +### macOS with Homebrew (fallback) Use this only when you are not building through Nix/flake. 1. Install host tools: - - `make bootstrap-macos` + - `make bootstrap-macos` (alias: `make bootstrap-brew`) 2. Run build: - Open a new terminal (or run `source ~/.zshrc`) so the Homebrew and Flutter PATH entries are active. - - `make build-macos VERSION=x.y.z BUILD_NUM=nnn` + - `make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1` + +The default source build needs Nix for the four dnix libraries. `PREBUILTS=1` +uses the verified prebuilts and needs no Nix for them. The Homebrew bootstrap installs the native build tools and configures Rust 1.99.1 for Flutter's native-assets hooks. It replaces the former local `crypto_plugins` macOS prebuild path; no submodule setup or manual native plugin build is needed. + +### macOS with a manual toolchain (advanced) + +Install the prerequisites from [Building on macOS](docs/building/macos.md) +yourself, then run +`make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1`. +`make check-reqs` reports what is missing; `TOOLCHAIN=manual` makes the choice +explicit. Omit `PREBUILTS=1` only if you also have Nix for the source build. diff --git a/docs/building/macos.md b/docs/building/macos.md index d0d9e5cce5..8ae6ae5482 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -3,17 +3,33 @@ These steps build the macOS and iOS apps on a Mac with Apple Silicon. For how the build fits together, see the [overview](../building.md). +## Toolchains + +The build steps below are the manual/Homebrew path. Nix is the primary host +toolchain; the same build is also available through: + +| Mode | Setup | +|---|---| +| Nix | `make bootstrap` (enters `nix develop`) | +| direnv | `direnv allow` | +| Homebrew | `make bootstrap-macos` | +| Manual | install the prerequisites below | + +With Nix or direnv the flake supplies Flutter, Dart, Rust, Go, CMake, Meson, +Ninja, pkg-config and protoc. Xcode always comes from the host. The +prerequisites below describe the manual/Homebrew path. + ## Prerequisites | What | Needed for | |---|---| -| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 | Every build | -| Your usual Xcode | Building the app, in both modes | -| Xcode **27.0**, release build **27A266a**, installed next to your usual Xcode | Source mode, the default: dnix builds its four packages with it, including during `flutter test`. It doesn't need to be selected; see [Install Xcode 27.0](#install-xcode-270) | -| [Homebrew](https://brew.sh/) packages below | Every build | -| [Rustup](https://rustup.rs/) | Every app, in both modes | -| [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet | -| [Nix](https://nixos.org/download/) | Source mode, the default; not needed with `-d` | +| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 | Manual and Homebrew modes | +| Your usual Xcode | Building the app, in both dnix modes | +| Xcode **27.0**, release build **27A266a**, installed next to your usual Xcode | Source mode (dnix), in every host mode: dnix builds its four packages with it, including during `flutter test`. It doesn't need to be selected; see [Install Xcode 27.0](#install-xcode-270) | +| [Homebrew](https://brew.sh/) packages below | Manual and Homebrew modes | +| [Rustup](https://rustup.rs/) | Manual and Homebrew modes, in both dnix modes | +| [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet, manual and Homebrew modes | +| [Nix](https://nixos.org/download/) | Source mode (dnix) in every host mode; not needed with `-d` | ```sh brew install autoconf automake libtool cmake cocoapods pkg-config diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md new file mode 100644 index 0000000000..f9a24f2975 --- /dev/null +++ b/docs/building/make-flow.md @@ -0,0 +1,134 @@ +# Make build flow + +This page is the maintained source for the two build-flow diagrams. GitHub +renders the Mermaid blocks directly; the PNG versions are generated from the +same blocks. Keep them in sync with the `Makefile`. + +## 1. Get the tools (once per Mac) + +Nix is the primary host toolchain. direnv is not a separate toolchain: the +tracked `.envrc` is `use flake`, so it activates the same shell as +`nix develop`. Homebrew and manually installed tools are supported fallbacks. + +### History + +`.envrc` was added on 2026-03-17 as a 98-line script that installed Rust +toolchains, set `SDKROOT`/`CC`, created a Python venv and wrote `lipo`/`xcrun` +wrappers. On 2026-03-19 the commit `macos build: split bootstrap from +host-agnostic build path` (428fd61f9) reduced it to `use flake`; the flake and +Makefile took over those steps. That is why direnv is not a fourth toolchain +today. The Homebrew helper still installs the `direnv` binary, but `.envrc` +now skips the flake when Nix is absent, so a Homebrew-only shell is not +blocked. + +```mermaid +flowchart LR + S["Pick a host
toolchain"] + S --> N["Nix (primary)
make bootstrap"] + S --> D["direnv
direnv allow"] + S --> B["Homebrew fallback
make bootstrap-macos"] + S --> M["Manual
TOOLCHAIN=manual"] + + N --> F["Flake
Flutter · Rust · Go
CMake · Meson · Ninja"] + D --> F + B --> H["Homebrew helper
Flutter · Rust · Go"] + M --> P["Tools on PATH"] + + F --> C["make toolchain
check-reqs-macos"] + H --> C + P --> C + + C --> X{"Full Xcode?"} + X -- yes --> R["Ready to build"] + X -- no --> XS["make bootstrap-xcode"] + XS --> R + XS -. optional .-> DL["make bootstrap-xcode-download
archive.org, hash + signature"] + DL --> R +``` + +`make bootstrap-xcode` does not install Xcode. It selects an existing full +install and finishes Apple's licence/first-launch setup if it is pending; the +archive.org download is opt-in and never runs in CI. + +## 2. Build + +`VERSION` and `BUILD_NUM` are required. dnix source is the default on macOS, +Linux and iOS; CI and Windows use the verified prebuilts. + +```mermaid +flowchart TD + O["APP_NAME · VERSION · BUILD_NUM
PREBUILTS=0 source · 1 prebuilt"] + O --> MAC["make build-macos"] + O --> IOS["make build-ios"] + O --> LINUX["make build-linux"] + O --> WIN["make build-windows"] + O --> AND["make build-android"] + + MAC --> MC["checks
require-version · check-sdk-macos
toolchain · dnix · check-reqs"] + MC --> MP{"PREBUILTS"} + MP -- "0 default" --> MS["source
Nix + Xcode 27.0"] + MP -- "1" --> MB["prebuilt -d"] + MS --> MR["build_app.sh -p macos -s
pub get · prebuild.sh
flutter build macos"] + MB --> MR + + IOS --> IC["checks
macOS-only · require-version
check-sdk · toolchain · dnix"] + IC --> IP{"PREBUILTS"} + IP -- "0 default" --> IS["source"] + IP -- "1 CI" --> IB["prebuilt -d"] + IS --> IR["prebuild.sh
build_app.sh -p ios -s
pub get · flutter build ios"] + IB --> IR + + LINUX --> LC["checks
require-version · toolchain
dnix · check-reqs"] + LC --> LP{"PREBUILTS"} + LP -- "0 default" --> LS["source (Nix)"] + LP -- "1" --> LB["prebuilt -d"] + LS --> LR["prebuild.sh
build_app.sh -p linux
flutter build linux · bundle"] + LB --> LR + + WIN --> WC["checks
require-version · toolchain
flutter · Go"] + WC --> WR["prebuild.sh
build_app.sh -p windows -d
pub get · flutter build windows
always prebuilt"] + + AND --> AC["checks
require-version · toolchain
dnix-android · dev key · SDK"] + AC --> AH{"Host"} + AH -- macOS --> AB["prebuilt -d"] + AH -- Linux --> AP{"PREBUILTS"} + AP -- "0 default" --> AS["source"] + AP -- "1" --> AB + AB --> AR["prebuild.sh
build_app.sh -p android
pub get · flutter build apk
--split-per-abi"] + AS --> AR +``` + +## Defaults + +| Context | `PREBUILTS` | dnix mode | +|---|---|---| +| macOS developer | `0` | source, verified; needs Nix + Xcode 27.0 | +| Linux developer | `0` | source, verified; needs Nix | +| iOS developer | `0` | source, verified; needs Nix + Xcode 27.0 | +| macOS/Linux/iOS CI | `1` | verified prebuilts (`-d`) | +| Windows | `1` (fixed) | verified prebuilts (`-d`) | +| Android on macOS | `1` (fixed) | verified prebuilts (`-d`) | +| Android on Linux | follows `PREBUILTS` | source by default | + +## What changed from the first diagrams + +- `make` no longer defaults to `VERSION=2.1.0` / `BUILD_NUM=210`; both are + required. +- `PREBUILTS=1` is no longer the macOS default; `0` (source) is. +- `PREBUILTS` affects macOS, Linux and iOS, and Android on Linux. It is not + macOS-only. +- `build-ios` follows `PREBUILTS` and has a macOS-only guard. +- `build-macos` clears the Nix compiler/SDK variables only inside a Nix shell; + a Homebrew or manual shell keeps its own flags. +- direnv is the Nix flake activator, not a fourth toolchain. + +## Regenerating the PNGs + +Extract the two Mermaid blocks and render them with Mermaid CLI: + +```sh +npx --yes @mermaid-js/mermaid-cli -i make-flow-tools.mmd \ + -o make-flow-tools.png -t dark -b "#0d1117" --size 1600 -s 2 +npx --yes @mermaid-js/mermaid-cli -i make-flow-build.mmd \ + -o make-flow-build.png -t dark -b "#0d1117" --size 1600 -s 2 +``` From c5f1ee20708fe53529536f6722035dd1f42a883d Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:15:48 +0200 Subject: [PATCH 026/107] fix(build): close audit findings - Makefile: only report direnv when the flake actually loaded, reject unknown TOOLCHAIN values, add Linux/Windows host guards and resolve the repo root from the Makefile location. - Drop the duplicate dnix preflight targets; build_app.sh owns those checks. - verify_bom: check every pinned plugin on a fresh checkout and preserve sections after [plugins] on --update. - flake.nix: leave DEVELOPER_DIR unset without full Xcode, guard the SDK lookup, avoid the sed placeholder and the deprecated stdenv aliases. - Installers: fail with exit 1 instead of returning from die(). - CI: read toolchain versions from stack-bom.toml, run verify-bom in every job, install Rust on Windows and do not start iOS after cancellation. --- .github/workflows/make-build.yaml | 85 +++++++++++++++++++++------- Makefile | 55 +++++++++++------- flake.nix | 35 +++++++----- scripts/bom_values.sh | 21 +++++++ scripts/install_macos_build_tools.sh | 4 +- scripts/install_xcode.sh | 4 +- tool/verify_bom.dart | 14 ++++- 7 files changed, 156 insertions(+), 62 deletions(-) create mode 100755 scripts/bom_values.sh diff --git a/.github/workflows/make-build.yaml b/.github/workflows/make-build.yaml index 45fa26bb16..7abb749b95 100644 --- a/.github/workflows/make-build.yaml +++ b/.github/workflows/make-build.yaml @@ -5,6 +5,9 @@ name: Make build # The Makefile builds dnix source by default on macOS and Linux. These jobs use # the same verified prebuilts as the release workflow (build.yaml); source and # reproducibility builds belong to the dnix packages' own CI. +# +# Toolchain versions come from stack-bom.toml via scripts/bom_values.sh. The +# release workflow (build.yaml) keeps its own DNSSEC 1.90.0 pins. on: workflow_dispatch: @@ -23,15 +26,28 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 + - name: Read stack-bom.toml + id: bom + run: | + values="$(scripts/bom_values.sh)" + eval "$values" + echo "flutter=$FLUTTER_VERSION" >> "$GITHUB_OUTPUT" + echo "rust=$RUST_VERSION" >> "$GITHUB_OUTPUT" + echo "go=$GO_VERSION" >> "$GITHUB_OUTPUT" - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ steps.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ steps.bom.outputs.go }} + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ steps.bom.outputs.rust }} - name: Install make run: command -v make >/dev/null 2>&1 || choco install make -y --no-progress + - name: Check the toolchain bill of materials + run: make verify-bom - name: Build run: make build-windows VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} WINDOWS_COPY_ASSETS=1 @@ -41,18 +57,28 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 + - name: Read stack-bom.toml + id: bom + run: | + values="$(scripts/bom_values.sh)" + eval "$values" + echo "flutter=$FLUTTER_VERSION" >> "$GITHUB_OUTPUT" + echo "rust=$RUST_VERSION" >> "$GITHUB_OUTPUT" + echo "go=$GO_VERSION" >> "$GITHUB_OUTPUT" - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ steps.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ steps.bom.outputs.go }} + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ steps.bom.outputs.rust }} - name: Tools - run: | - brew install meson ninja autoconf automake libtool protobuf pkg-config cbindgen || true - rustup toolchain install 1.99.1 --profile minimal || true - rustup default 1.99.1 || true + run: brew install meson ninja autoconf automake libtool protobuf pkg-config cbindgen + - name: Check the toolchain bill of materials + run: make verify-bom - name: Build run: make build-macos VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 @@ -62,13 +88,24 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 + - name: Read stack-bom.toml + id: bom + run: | + values="$(scripts/bom_values.sh)" + eval "$values" + echo "flutter=$FLUTTER_VERSION" >> "$GITHUB_OUTPUT" + echo "rust=$RUST_VERSION" >> "$GITHUB_OUTPUT" + echo "go=$GO_VERSION" >> "$GITHUB_OUTPUT" - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ steps.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ steps.bom.outputs.go }} + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ steps.bom.outputs.rust }} - name: Free disk space run: | sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL @@ -81,10 +118,6 @@ jobs: libgcrypt20-dev libgirepository1.0-dev libgit2-dev libglib2.0-dev libgtk-3-dev libjsoncpp-dev liblzma-dev \ libncurses5-dev libncursesw5-dev libsecret-1-dev libssl-dev libtss2-dev \ ocl-icd-opencl-dev opencl-headers valac zlib1g-dev - - name: Rust - run: | - rustup toolchain install 1.99.1 --profile minimal - rustup default 1.99.1 - name: Check the toolchain bill of materials run: make verify-bom - name: Build @@ -94,23 +127,33 @@ jobs: # The fork has a single hosted macOS concurrency slot. Running macOS and # iOS together leaves one job queued until GitHub cancels it; serialise them. needs: macos - if: always() + if: ${{ !cancelled() }} runs-on: macos-latest steps: - uses: actions/checkout@v6 with: fetch-depth: 0 + - name: Read stack-bom.toml + id: bom + run: | + values="$(scripts/bom_values.sh)" + eval "$values" + echo "flutter=$FLUTTER_VERSION" >> "$GITHUB_OUTPUT" + echo "rust=$RUST_VERSION" >> "$GITHUB_OUTPUT" + echo "go=$GO_VERSION" >> "$GITHUB_OUTPUT" - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ steps.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ steps.bom.outputs.go }} + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ steps.bom.outputs.rust }} - name: Tools - run: | - brew install meson ninja autoconf automake libtool protobuf pkg-config cbindgen || true - rustup toolchain install 1.99.1 --profile minimal || true - rustup default 1.99.1 || true + run: brew install meson ninja autoconf automake libtool protobuf pkg-config cbindgen + - name: Check the toolchain bill of materials + run: make verify-bom - name: Build run: make build-ios VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 diff --git a/Makefile b/Makefile index 5553d2b131..7984d42e79 100644 --- a/Makefile +++ b/Makefile @@ -14,19 +14,26 @@ FLUTTER_BIN := $(if $(and $(FLUTTER),$(wildcard $(FLUTTER))),$(FLUTTER),$(shell DART_BIN := $(if $(and $(DART),$(wildcard $(DART))),$(DART),$(shell command -v dart 2>/dev/null)) FLUTTER := $(FLUTTER_BIN) DART := $(DART_BIN) -APP_PROJECT_ROOT_DIR := $(CURDIR) +APP_PROJECT_ROOT_DIR := $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST))))) # Platform detection from uname. PLATFORM ?= $(shell uname -s 2>/dev/null) # Toolchain source. Nix (nix develop or direnv) is the primary path; Homebrew # and manual installs use the host tools already on PATH. The build steps are # identical in every mode: only the prerequisite check and the Nix environment -# sanitising differ. Override with TOOLCHAIN=nix|direnv|brew|manual. +# sanitising differ. Override with TOOLCHAIN=nix|direnv|brew|manual|host. TOOLCHAIN ?= auto DIRENV_ACTIVE := $(if $(DIRENV_DIR),1,) NIX_ACTIVE := $(if $(or $(IN_NIX_SHELL),$(NIX_STORE)),1,) +ifneq ($(filter $(TOOLCHAIN),auto nix direnv brew manual host),$(TOOLCHAIN)) + $(error TOOLCHAIN must be auto, nix, direnv, brew, manual or host) +endif ifeq ($(TOOLCHAIN),auto) ifeq ($(DIRENV_ACTIVE),1) - TOOLCHAIN_EFFECTIVE := direnv + ifeq ($(NIX_ACTIVE),1) + TOOLCHAIN_EFFECTIVE := direnv + else + TOOLCHAIN_EFFECTIVE := host + endif else ifeq ($(NIX_ACTIVE),1) TOOLCHAIN_EFFECTIVE := nix @@ -47,7 +54,7 @@ PROTOC_PATH := $(shell which protoc 2>/dev/null) # Toolchain installed for host-side checks/targets. Native-assets crates pick their own # pinned toolchain via rust-toolchain.toml; do not export RUSTUP_TOOLCHAIN globally. BOM_FILE := $(APP_PROJECT_ROOT_DIR)/stack-bom.toml -BOM_RUST := $(shell sed -n 's/^rust[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' $(BOM_FILE) 2>/dev/null | head -n1) +BOM_RUST := $(shell sed -n 's/^rust[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' "$(BOM_FILE)" 2>/dev/null | head -n1) RUST_VERSION ?= $(if $(BOM_RUST),$(BOM_RUST),1.99.1) # Only strip Nix/Apple variables when a Nix shell actually supplied them. In a # Homebrew or manual shell these are the user's own settings and are kept. @@ -66,7 +73,7 @@ ifneq ($(strip $(PUB_CACHE)),) export PUB_CACHE endif -.PHONY: help toolchain toolchain-check dnix-check dnix-check-android bootstrap bootstrap-brew require-version check-reqs check-reqs-macos check-sdk-macos bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios +.PHONY: help toolchain toolchain-check bootstrap bootstrap-brew require-version check-reqs check-reqs-macos check-sdk-macos check-linux check-windows bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios help: ## Show available commands @echo "Available targets:" @@ -82,8 +89,10 @@ toolchain: ## Show the active toolchain and tool paths @echo "flutter : $(if $(FLUTTER),$(FLUTTER),missing)" @echo "dart : $(if $(DART),$(DART),missing)" @echo "rustup : $$(command -v rustup || echo missing)" +ifeq ($(PLATFORM),Darwin) @echo "brew : $$(command -v brew || echo missing)" @echo "xcode : $$(xcode-select -p 2>/dev/null || echo missing)" +endif toolchain-check: ## Fail when the requested toolchain is not active ifeq ($(TOOLCHAIN_EFFECTIVE),nix) @@ -109,22 +118,26 @@ bootstrap: ## Enter the Nix dev shell (primary toolchain; no-op when already ins bootstrap-brew: bootstrap-macos ## Alias for the Homebrew fallback toolchain -dnix-check: ## Fail when a dnix source build is requested without Nix - @if [ "$(PREBUILTS)" = "0" ] && ! command -v nix >/dev/null 2>&1; then \ - echo >&2 "[ERROR] PREBUILTS=0 (dnix source) needs Nix. Use PREBUILTS=1, or run 'make bootstrap'."; \ - exit 1; \ - fi +check-linux: ## Fail unless the host is Linux +ifeq ($(PLATFORM),Linux) + @: +else + @echo >&2 "[ERROR] build-linux is Linux-only." + @exit 1 +endif -dnix-check-android: ## Fail when an Android dnix source build is requested without Nix - @if [ "$(ANDROID_PREBUILTS)" = "0" ] && ! command -v nix >/dev/null 2>&1; then \ - echo >&2 "[ERROR] Android source builds need Nix. Use PREBUILTS=1, or run 'make bootstrap'."; \ - exit 1; \ - fi +check-windows: ## Fail unless running from Git Bash on Windows +ifeq ($(filter MINGW% MSYS% CYGWIN%,$(PLATFORM)),) + @echo >&2 "[ERROR] build-windows must run from Git Bash on Windows." + @exit 1 +else + @: +endif # --- PREREQUISITES --- require-version: ## Fail unless VERSION and BUILD_NUM are set explicitly - @[ -n "$(VERSION)" ] || { echo >&2 "[ERROR] VERSION is not set. Pass VERSION=x.y.z (current release line: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } + @[ -n "$(VERSION)" ] || { echo >&2 "[ERROR] VERSION is not set. Pass VERSION=x.y.z (latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } @[ -n "$(BUILD_NUM)" ] || { echo >&2 "[ERROR] BUILD_NUM is not set. Pass a build number above the latest release tag ($$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } check-reqs: ## Verify essential build tools @@ -300,7 +313,7 @@ clean-native: ## Remove only the native-asset build outputs (forces the Rust/Go/ @rm -rf .dart_tool/hooks_runner build/native_assets @echo "[OK] Removed .dart_tool/hooks_runner and build/native_assets." -build-macos: require-version toolchain-check dnix-check check-reqs-macos check-sdk-macos ## Build macOS release (source by default; PREBUILTS=1 uses verified prebuilts) +build-macos: require-version toolchain-check check-reqs-macos check-sdk-macos ## Build macOS release (source by default; PREBUILTS=1 uses verified prebuilts) @echo "--- Configuring project (scripts/build_app.sh)..." @cd scripts && echo yes | env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a $(APP_NAME) -s $(if $(filter 1,$(PREBUILTS)),-d) @echo "--- Resolving dependencies..." @@ -334,7 +347,7 @@ diagnose-env-macos: ## Print macOS build env and tool resolution @echo "NIX_CFLAGS_LINK=$${NIX_CFLAGS_LINK:-}" build-linux: export PUB_CACHE := $(LINUX_PUB_CACHE) -build-linux: require-version toolchain-check dnix-check check-reqs ## Build Linux Release through Flutter native-assets hooks +build-linux: require-version check-linux toolchain-check check-reqs ## Build Linux Release through Flutter native-assets hooks @echo "--- Running prebuild bootstrap..." @cd scripts && bash prebuild.sh @echo "--- Generating config..." @@ -376,7 +389,7 @@ build-linux: require-version toolchain-check dnix-check check-reqs ## Build Linu # driven by build_app.sh directly, not by this target. WINDOWS_COPY_ASSETS ?= 0 -build-windows: require-version toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) +build-windows: require-version check-windows toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed."; exit 1; } @cd scripts && bash prebuild.sh @@ -396,7 +409,7 @@ android-dev-key: ## Create a throw-away debug signing key if android/key.propert printf 'storeFile=../dev-keystore.jks\nstorePassword=android\nkeyPassword=android\nkeyAlias=devkey\n' > android/key.properties; \ fi -build-android: require-version toolchain-check dnix-check-android android-dev-key ## Build Android APKs (prebuilt dnix on macOS; Linux follows PREBUILTS) +build-android: require-version toolchain-check android-dev-key ## Build Android APKs (prebuilt dnix on macOS; Linux follows PREBUILTS) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } @cd scripts && bash prebuild.sh @@ -405,7 +418,7 @@ build-android: require-version toolchain-check dnix-check-android android-dev-ke @$(FLUTTER) build apk --split-per-abi --release # iOS: same steps as the "build-ios" CI job (device build, no code signing). Run on macOS with Xcode. -build-ios: require-version check-sdk-macos toolchain-check dnix-check ## Build iOS Runner.app without code signing (same steps as CI) +build-ios: require-version check-sdk-macos toolchain-check ## Build iOS Runner.app without code signing (same steps as CI) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @cd scripts && bash prebuild.sh @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) -s diff --git a/flake.nix b/flake.nix index 9ba14e2d07..cb9d0a3898 100644 --- a/flake.nix +++ b/flake.nix @@ -38,7 +38,7 @@ ])) ]; - linuxPackages = lib.optionals pkgs.stdenv.isLinux (with pkgs; [ + linuxPackages = lib.optionals pkgs.stdenv.hostPlatform.isLinux (with pkgs; [ gtk3 glib openssl xz clang libgcrypt gobject-introspection llvmPackages.libclang llvmPackages.clang @@ -52,7 +52,7 @@ opencl-headers ]); - macPackages = lib.optionals pkgs.stdenv.isDarwin (with pkgs; [ + macPackages = lib.optionals pkgs.stdenv.hostPlatform.isDarwin (with pkgs; [ cocoapods libiconv autoconf @@ -74,7 +74,9 @@ # Resolve the repository root, not the directory the shell was # entered from; .nix-bin and the rustup override are per checkout. export APP_PROJECT_ROOT_DIR="$(git rev-parse --show-toplevel 2>/dev/null || pwd)" - export PATH="$HOME/.cargo/bin:$PATH" + if [ -d "$HOME/.cargo/bin" ]; then + export PATH="$HOME/.cargo/bin:$PATH" + fi # The standalone Dart in the Nix Flutter wrapper cannot find the Flutter SDK on its own, # so `dart run`/`dart pub` in a Flutter project fail ("Flutter users should use flutter pub"). @@ -104,7 +106,7 @@ # ========================================== # LINUX (NixOS) SPECIFICS # ========================================== - ${lib.optionalString pkgs.stdenv.isLinux '' + ${lib.optionalString pkgs.stdenv.hostPlatform.isLinux '' # echo "🐧 Linux detected: Patching shebangs for NixOS..." export LIBCLANG_PATH="${pkgs.llvmPackages.libclang.lib}/lib" export BINDGEN_EXTRA_CLANG_ARGS="-isystem ${pkgs.llvmPackages.libclang.lib}/lib/clang/${clangMajor}/include" @@ -114,20 +116,23 @@ # ========================================== # MACOS XCODE SANDBOX ESCAPE # ========================================== - ${lib.optionalString pkgs.stdenv.isDarwin '' + ${lib.optionalString pkgs.stdenv.hostPlatform.isDarwin '' # Nix supplies the host tools, never Apple's compiler or SDK. # Flutter, CocoaPods and Xcode use the toolchain selected by # xcode-select. Do not export SDKROOT here: it makes an iOS build # compile against the macOS SDK. SELECTED_DEVELOPER="$(env -u DEVELOPER_DIR xcode-select -p 2>/dev/null || true)" case "$SELECTED_DEVELOPER" in - *.app/Contents/Developer) ;; + *.app/Contents/Developer) + export DEVELOPER_DIR="$SELECTED_DEVELOPER" + ;; *) echo "[WARN] No full Xcode selected. Install Xcode and run 'make bootstrap-xcode'." - SELECTED_DEVELOPER="/Applications/Xcode.app/Contents/Developer" + # Leave DEVELOPER_DIR unset so xcrun can still use the + # Command Line Tools for non-Xcode work. + unset DEVELOPER_DIR ;; esac - export DEVELOPER_DIR="$SELECTED_DEVELOPER" # nixpkgs' Darwin stdenv exports its own macOS SDK here before # this hook runs; leave the SDK choice to Xcode per build. unset SDKROOT @@ -144,7 +149,10 @@ export RANLIB=/usr/bin/ranlib export STRIP=/usr/bin/strip - export BINDGEN_EXTRA_CLANG_ARGS="-isysroot $(/usr/bin/xcrun --sdk macosx --show-sdk-path)" + SDK_PATH="$(/usr/bin/xcrun --sdk macosx --show-sdk-path 2>/dev/null || true)" + if [ -n "$SDK_PATH" ]; then + export BINDGEN_EXTRA_CLANG_ARGS="-isysroot $SDK_PATH" + fi export PROTOC="${pkgs.protobuf}/bin/protoc" NIX_BIN="$APP_PROJECT_ROOT_DIR/.nix-bin" @@ -175,15 +183,14 @@ LIPO_EOF # xcrun wrapper: `xcrun -f lipo` must resolve to the wrapper above. # Everything else passes straight through, so an iOS build keeps # its deployment target and SDK. - cat > "$NIX_BIN/xcrun" <<'XCRUN_EOF' + cat > "$NIX_BIN/xcrun" <&2; exit 1; } +[ -n "$RUST_VERSION" ] || { echo "Missing rust in $BOM" >&2; exit 1; } +[ -n "$GO_VERSION" ] || { echo "Missing go_min in $BOM" >&2; exit 1; } + +printf 'FLUTTER_VERSION=%s\nRUST_VERSION=%s\nGO_VERSION=%s\n' \ + "$FLUTTER_VERSION" "$RUST_VERSION" "$GO_VERSION" diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh index 8927786dee..06b02ea4cd 100755 --- a/scripts/install_macos_build_tools.sh +++ b/scripts/install_macos_build_tools.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -# Safe to source (source script.sh) or execute directly (./script.sh) +# Run directly (bash script.sh). On error this exits the shell; do not source. if [ -n "${ZSH_VERSION:-}" ]; then if [[ "${ZSH_EVAL_CONTEXT:-}" == *file* ]]; then set -uo pipefail # sourced in zsh, don't -e @@ -16,7 +16,7 @@ elif [ -n "${BASH_VERSION:-}" ]; then else set -euo pipefail # unknown shell fi -die() { echo "$@" >&2; return 1 2>/dev/null || exit 1; } +die() { echo "$@" >&2; exit 1; } if [[ "$(uname -s)" != "Darwin" ]]; then die "This installer is for macOS only." diff --git a/scripts/install_xcode.sh b/scripts/install_xcode.sh index 2d7d74d3d5..ee9273a825 100755 --- a/scripts/install_xcode.sh +++ b/scripts/install_xcode.sh @@ -12,7 +12,7 @@ # `mas install` requiring an interactive sudo TTY) that still ended up # needing a manual download anyway. Fail with clear instructions instead. # -# Safe to source (source script.sh) or execute directly (./script.sh) +# Run directly (bash script.sh). On error this exits the shell; do not source. if [ -n "${ZSH_VERSION:-}" ]; then if [[ "${ZSH_EVAL_CONTEXT:-}" == *file* ]]; then set -uo pipefail # sourced in zsh, don't -e @@ -28,7 +28,7 @@ elif [ -n "${BASH_VERSION:-}" ]; then else set -euo pipefail # unknown shell fi -die() { echo "$@" >&2; return 1 2>/dev/null || exit 1; } +die() { echo "$@" >&2; exit 1; } if [[ "$(uname -s)" != "Darwin" ]]; then die "This installer is for macOS only." diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 991fcb1436..80bfc81c79 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -147,6 +147,10 @@ Future _update() async { // old behaviour and update every plugin the lock knows about. final updateable = declared.isEmpty ? _pluginNames.toSet() : declared; final start = text.indexOf('[plugins]'); + final tailStart = start < 0 + ? text.length + : text.indexOf(RegExp(r'\n\[', multiLine: true), start + 1); + final tail = tailStart < 0 ? '' : text.substring(tailStart); final head = start < 0 ? text.trimRight() : text.substring(0, start).trimRight(); @@ -167,6 +171,7 @@ Future _update() async { written++; } } + buf.write(tail); File(_bomFile).writeAsStringSync(buf.toString()); stdout.writeln('Updated [plugins] in $_bomFile ($written entries).'); } @@ -266,16 +271,21 @@ Future main(List args) async { final refs = _lockRefs(); final pinned = bom['plugins'] ?? {}; final declared = _declaredPlugins(); + // A fresh checkout has no pubspec.yaml: build_app.sh generates it later. + // In that case check every plugin the lock contains, as before. + final required = File('pubspec.yaml').existsSync() + ? declared + : _pluginNames.toSet(); if (refs.isEmpty) { _warn('pubspec.lock not found, plugin pins not checked'); - } else if (declared.isEmpty) { + } else if (required.isEmpty) { _warn( 'pubspec.yaml declares none of the pinned plugins, ' 'plugin pins not checked', ); } else { for (final n in _pluginNames) { - if (!declared.contains(n)) continue; + if (!required.contains(n)) continue; final ref = refs[n]; final pin = pinned[n]; if (ref == null) { From 095445e4b2d4d8610f329f9be4a0e7e376bb5c1a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:15:58 +0200 Subject: [PATCH 027/107] docs: clarify toolchain and CI details - State that the flake provides rustup, which installs Rust on first entry. - Note the Xcode warning/build-enforcement split. - Keep the build-flow diagrams current with the preflight targets. --- README.md | 6 +++--- docs/building/macos.md | 7 ++++--- docs/building/make-flow.md | 26 +++++++------------------- 3 files changed, 14 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index a246cfc797..06a29a2d02 100644 --- a/README.md +++ b/README.md @@ -63,9 +63,9 @@ using. 2. Run build (pass the release version and a build number; `make` refuses to guess): - `make build-macos VERSION=x.y.z BUILD_NUM=nnn` -The flake provides Flutter, Dart, Rust, Go, CMake, Meson, Ninja, pkg-config -and protoc. Xcode is never provided by Nix; the flake uses the Xcode selected -by `xcode-select`. +The flake provides Flutter, Dart, rustup (which installs Rust 1.99.1 on first +entry), Go, CMake, Meson, Ninja, pkg-config and protoc. Xcode is never provided +by Nix; the flake uses the Xcode selected by `xcode-select`. ### macOS with Homebrew (fallback) diff --git a/docs/building/macos.md b/docs/building/macos.md index 8ae6ae5482..ce4cd892a7 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -15,9 +15,10 @@ toolchain; the same build is also available through: | Homebrew | `make bootstrap-macos` | | Manual | install the prerequisites below | -With Nix or direnv the flake supplies Flutter, Dart, Rust, Go, CMake, Meson, -Ninja, pkg-config and protoc. Xcode always comes from the host. The -prerequisites below describe the manual/Homebrew path. +With Nix or direnv the flake supplies Flutter, Dart, rustup (which installs +Rust 1.99.1 on first entry), Go, CMake, Meson, Ninja, pkg-config and protoc. +Xcode always comes from the host. The prerequisites below describe the +manual/Homebrew path. ## Prerequisites diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index f9a24f2975..3e84388e8b 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -64,31 +64,31 @@ flowchart TD O --> WIN["make build-windows"] O --> AND["make build-android"] - MAC --> MC["checks
require-version · check-sdk-macos
toolchain · dnix · check-reqs"] + MAC --> MC["checks
require-version · check-sdk-macos
toolchain · check-reqs"] MC --> MP{"PREBUILTS"} MP -- "0 default" --> MS["source
Nix + Xcode 27.0"] MP -- "1" --> MB["prebuilt -d"] MS --> MR["build_app.sh -p macos -s
pub get · prebuild.sh
flutter build macos"] MB --> MR - IOS --> IC["checks
macOS-only · require-version
check-sdk · toolchain · dnix"] + IOS --> IC["checks
require-version · check-sdk-macos
(macOS-only) · toolchain"] IC --> IP{"PREBUILTS"} IP -- "0 default" --> IS["source"] IP -- "1 CI" --> IB["prebuilt -d"] IS --> IR["prebuild.sh
build_app.sh -p ios -s
pub get · flutter build ios"] IB --> IR - LINUX --> LC["checks
require-version · toolchain
dnix · check-reqs"] + LINUX --> LC["checks
require-version · check-linux
toolchain · check-reqs"] LC --> LP{"PREBUILTS"} LP -- "0 default" --> LS["source (Nix)"] LP -- "1" --> LB["prebuilt -d"] LS --> LR["prebuild.sh
build_app.sh -p linux
flutter build linux · bundle"] LB --> LR - WIN --> WC["checks
require-version · toolchain
flutter · Go"] + WIN --> WC["checks
require-version · check-windows
toolchain · flutter · Go"] WC --> WR["prebuild.sh
build_app.sh -p windows -d
pub get · flutter build windows
always prebuilt"] - AND --> AC["checks
require-version · toolchain
dnix-android · dev key · SDK"] + AND --> AC["checks
require-version · toolchain
dev key · SDK"] AC --> AH{"Host"} AH -- macOS --> AB["prebuilt -d"] AH -- Linux --> AP{"PREBUILTS"} @@ -110,25 +110,13 @@ flowchart TD | Android on macOS | `1` (fixed) | verified prebuilts (`-d`) | | Android on Linux | follows `PREBUILTS` | source by default | -## What changed from the first diagrams - -- `make` no longer defaults to `VERSION=2.1.0` / `BUILD_NUM=210`; both are - required. -- `PREBUILTS=1` is no longer the macOS default; `0` (source) is. -- `PREBUILTS` affects macOS, Linux and iOS, and Android on Linux. It is not - macOS-only. -- `build-ios` follows `PREBUILTS` and has a macOS-only guard. -- `build-macos` clears the Nix compiler/SDK variables only inside a Nix shell; - a Homebrew or manual shell keeps its own flags. -- direnv is the Nix flake activator, not a fourth toolchain. - ## Regenerating the PNGs Extract the two Mermaid blocks and render them with Mermaid CLI: ```sh npx --yes @mermaid-js/mermaid-cli -i make-flow-tools.mmd \ - -o make-flow-tools.png -t dark -b "#0d1117" --size 1600 -s 2 + -o make-flow-tools.png -t dark -b "#0d1117" --size 1800 -s 2 npx --yes @mermaid-js/mermaid-cli -i make-flow-build.mmd \ - -o make-flow-build.png -t dark -b "#0d1117" --size 1600 -s 2 + -o make-flow-build.png -t dark -b "#0d1117" --size 1800 -s 2 ``` From 7ba73d866009c57487da1d6b042a929c841ead43 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:41:31 +0200 Subject: [PATCH 028/107] fix(build): address second audit round - BOM: one section-aware parser with --get, safe quoted output, BOM Xcode pins, exact Go and a 1.24.1 minimum. - Makefile: validate PLATFORM/TOOLCHAIN/PREBUILTS, guard the repository root, isolate the iOS Nix environment, skip Flutter clean when absent, require a full Xcode, and add missing Rust targets. - verify_bom: handle 4-space pubspecs and dependency_overrides, fail when declarations cannot be read, preserve unknown pins and trailing sections, reject duplicate [plugins] tables and malformed pins, and fall back to bare flutter on Windows. - flake: explicit supported systems, no pinned DEVELOPER_DIR, no cargo-ndk install, xcrun lipo dispatch, BOM validation, .envrc watch, and remove the unused dart/clang packages. - download_xcode: honour dry-run before mutating the filesystem, handle a non-interactive read, allow -n in CI, and read the 27.1 build/hash from the BOM. - link_assets: require the project root and a path converter on Windows. - CI: read exact BOM values, build the recommended Flutter, and use system secure-storage deps on Linux. --- .envrc | 1 + .github/workflows/make-build.yaml | 46 ++++++----- Makefile | 71 ++++++++++++---- flake.nix | 58 +++++++------ scripts/bom_values.sh | 67 ++++++++++++--- scripts/download_xcode.sh | 24 +++++- scripts/install_macos_build_tools.sh | 11 ++- stack-bom.toml | 5 +- tool/verify_bom.dart | 118 +++++++++++++++++++-------- 9 files changed, 281 insertions(+), 120 deletions(-) diff --git a/.envrc b/.envrc index e9e6491daa..9da8b0f825 100644 --- a/.envrc +++ b/.envrc @@ -1,5 +1,6 @@ # Nix is the primary toolchain. Without it, leave the shell alone instead of # failing with a blocked .envrc; use make bootstrap-macos and PREBUILTS=1. if has nix; then + watch_file stack-bom.toml flake.nix flake.lock use flake fi diff --git a/.github/workflows/make-build.yaml b/.github/workflows/make-build.yaml index 7abb749b95..ba99d30a8c 100644 --- a/.github/workflows/make-build.yaml +++ b/.github/workflows/make-build.yaml @@ -29,11 +29,12 @@ jobs: - name: Read stack-bom.toml id: bom run: | - values="$(scripts/bom_values.sh)" - eval "$values" - echo "flutter=$FLUTTER_VERSION" >> "$GITHUB_OUTPUT" - echo "rust=$RUST_VERSION" >> "$GITHUB_OUTPUT" - echo "go=$GO_VERSION" >> "$GITHUB_OUTPUT" + flutter="$(bash scripts/bom_values.sh --get flutter)" + rust="$(bash scripts/bom_values.sh --get rust)" + go="$(bash scripts/bom_values.sh --get go)" + echo "flutter=$flutter" >> "$GITHUB_OUTPUT" + echo "rust=$rust" >> "$GITHUB_OUTPUT" + echo "go=$go" >> "$GITHUB_OUTPUT" - uses: subosito/flutter-action@v2 with: flutter-version: ${{ steps.bom.outputs.flutter }} @@ -60,11 +61,12 @@ jobs: - name: Read stack-bom.toml id: bom run: | - values="$(scripts/bom_values.sh)" - eval "$values" - echo "flutter=$FLUTTER_VERSION" >> "$GITHUB_OUTPUT" - echo "rust=$RUST_VERSION" >> "$GITHUB_OUTPUT" - echo "go=$GO_VERSION" >> "$GITHUB_OUTPUT" + flutter="$(bash scripts/bom_values.sh --get flutter)" + rust="$(bash scripts/bom_values.sh --get rust)" + go="$(bash scripts/bom_values.sh --get go)" + echo "flutter=$flutter" >> "$GITHUB_OUTPUT" + echo "rust=$rust" >> "$GITHUB_OUTPUT" + echo "go=$go" >> "$GITHUB_OUTPUT" - uses: subosito/flutter-action@v2 with: flutter-version: ${{ steps.bom.outputs.flutter }} @@ -91,11 +93,12 @@ jobs: - name: Read stack-bom.toml id: bom run: | - values="$(scripts/bom_values.sh)" - eval "$values" - echo "flutter=$FLUTTER_VERSION" >> "$GITHUB_OUTPUT" - echo "rust=$RUST_VERSION" >> "$GITHUB_OUTPUT" - echo "go=$GO_VERSION" >> "$GITHUB_OUTPUT" + flutter="$(bash scripts/bom_values.sh --get flutter)" + rust="$(bash scripts/bom_values.sh --get rust)" + go="$(bash scripts/bom_values.sh --get go)" + echo "flutter=$flutter" >> "$GITHUB_OUTPUT" + echo "rust=$rust" >> "$GITHUB_OUTPUT" + echo "go=$go" >> "$GITHUB_OUTPUT" - uses: subosito/flutter-action@v2 with: flutter-version: ${{ steps.bom.outputs.flutter }} @@ -121,7 +124,7 @@ jobs: - name: Check the toolchain bill of materials run: make verify-bom - name: Build - run: make build-linux VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 + run: make build-linux VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 SYSTEM_DEPS=1 ios: # The fork has a single hosted macOS concurrency slot. Running macOS and @@ -136,11 +139,12 @@ jobs: - name: Read stack-bom.toml id: bom run: | - values="$(scripts/bom_values.sh)" - eval "$values" - echo "flutter=$FLUTTER_VERSION" >> "$GITHUB_OUTPUT" - echo "rust=$RUST_VERSION" >> "$GITHUB_OUTPUT" - echo "go=$GO_VERSION" >> "$GITHUB_OUTPUT" + flutter="$(bash scripts/bom_values.sh --get flutter)" + rust="$(bash scripts/bom_values.sh --get rust)" + go="$(bash scripts/bom_values.sh --get go)" + echo "flutter=$flutter" >> "$GITHUB_OUTPUT" + echo "rust=$rust" >> "$GITHUB_OUTPUT" + echo "go=$go" >> "$GITHUB_OUTPUT" - uses: subosito/flutter-action@v2 with: flutter-version: ${{ steps.bom.outputs.flutter }} diff --git a/Makefile b/Makefile index 7984d42e79..d29c8c15a1 100644 --- a/Makefile +++ b/Makefile @@ -14,9 +14,21 @@ FLUTTER_BIN := $(if $(and $(FLUTTER),$(wildcard $(FLUTTER))),$(FLUTTER),$(shell DART_BIN := $(if $(and $(DART),$(wildcard $(DART))),$(DART),$(shell command -v dart 2>/dev/null)) FLUTTER := $(FLUTTER_BIN) DART := $(DART_BIN) -APP_PROJECT_ROOT_DIR := $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST))))) -# Platform detection from uname. -PLATFORM ?= $(shell uname -s 2>/dev/null) +APP_PROJECT_ROOT_DIR := $(CURDIR) +ifeq ($(wildcard Makefile),) + $(error Run make from the repository root) +endif +# Platform detection from uname. PLATFORM can be overridden, but only with a +# supported value; an unrelated exported PLATFORM must not change the defaults. +UNAME_S := $(shell uname -s 2>/dev/null) +PLATFORM ?= $(UNAME_S) +ifneq ($(PLATFORM),Darwin) + ifneq ($(PLATFORM),Linux) + ifeq ($(filter MINGW% MSYS%,$(PLATFORM)),) + $(error Unsupported PLATFORM '$(PLATFORM)'; expected Darwin, Linux or Git Bash on Windows) + endif + endif +endif # Toolchain source. Nix (nix develop or direnv) is the primary path; Homebrew # and manual installs use the host tools already on PATH. The build steps are # identical in every mode: only the prerequisite check and the Nix environment @@ -24,6 +36,12 @@ PLATFORM ?= $(shell uname -s 2>/dev/null) TOOLCHAIN ?= auto DIRENV_ACTIVE := $(if $(DIRENV_DIR),1,) NIX_ACTIVE := $(if $(or $(IN_NIX_SHELL),$(NIX_STORE)),1,) +ifeq ($(strip $(TOOLCHAIN)),) + $(error TOOLCHAIN must not be empty) +endif +ifneq ($(words $(TOOLCHAIN)),1) + $(error TOOLCHAIN must be a single value) +endif ifneq ($(filter $(TOOLCHAIN),auto nix direnv brew manual host),$(TOOLCHAIN)) $(error TOOLCHAIN must be auto, nix, direnv, brew, manual or host) endif @@ -54,18 +72,21 @@ PROTOC_PATH := $(shell which protoc 2>/dev/null) # Toolchain installed for host-side checks/targets. Native-assets crates pick their own # pinned toolchain via rust-toolchain.toml; do not export RUSTUP_TOOLCHAIN globally. BOM_FILE := $(APP_PROJECT_ROOT_DIR)/stack-bom.toml -BOM_RUST := $(shell sed -n 's/^rust[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' "$(BOM_FILE)" 2>/dev/null | head -n1) -RUST_VERSION ?= $(if $(BOM_RUST),$(BOM_RUST),1.99.1) +BOM_RUST := $(shell bash "$(APP_PROJECT_ROOT_DIR)/scripts/bom_values.sh" --get rust "$(BOM_FILE)" 2>/dev/null) +RUST_VERSION ?= $(if $(BOM_RUST),$(BOM_RUST),$(error Cannot read [toolchain] rust from $(BOM_FILE))) # Only strip Nix/Apple variables when a Nix shell actually supplied them. In a # Homebrew or manual shell these are the user's own settings and are kept. +NIX_ENV_UNSET = -u LD -u LDFLAGS -u NIX_LDFLAGS -u NIX_CFLAGS_LINK \ + -u NIX_CFLAGS_COMPILE -u CFLAGS -u CXXFLAGS -u CPPFLAGS \ + -u SDKROOT -u BINDGEN_EXTRA_CLANG_ARGS ifeq ($(NIX_ACTIVE),1) -MACOS_ENV_UNSET = -u LD -u LDFLAGS -u NIX_LDFLAGS -u NIX_CFLAGS_LINK \ - -u CFLAGS -u CXXFLAGS -u CPPFLAGS \ - -u SDKROOT -u BINDGEN_EXTRA_CLANG_ARGS \ +MACOS_ENV_UNSET = $(NIX_ENV_UNSET) \ -u IPHONEOS_DEPLOYMENT_TARGET -u TVOS_DEPLOYMENT_TARGET -u WATCHOS_DEPLOYMENT_TARGET \ -u XROS_DEPLOYMENT_TARGET -u XR_DEPLOYMENT_TARGET +IOS_ENV_UNSET = $(NIX_ENV_UNSET) else MACOS_ENV_UNSET = +IOS_ENV_UNSET = endif export APP_PROJECT_ROOT_DIR @@ -77,7 +98,7 @@ endif help: ## Show available commands @echo "Available targets:" - @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "%-20s %s\n", $$1, $$2}' + @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "%-24s %s\n", $$1, $$2}' # --- TOOLCHAIN --- @@ -127,7 +148,7 @@ else endif check-windows: ## Fail unless running from Git Bash on Windows -ifeq ($(filter MINGW% MSYS% CYGWIN%,$(PLATFORM)),) +ifeq ($(filter MINGW% MSYS%,$(PLATFORM)),) @echo >&2 "[ERROR] build-windows must run from Git Bash on Windows." @exit 1 else @@ -189,6 +210,11 @@ endif check-sdk-macos: ## Verify XCode on macOS ifeq ($(PLATFORM),Darwin) @echo "Checking macOS SDK requirements..." + @selected="$$(xcode-select -p 2>/dev/null || true)"; \ + case "$$selected" in \ + *.app/Contents/Developer) ;; \ + *) echo >&2 "[ERROR] Full Xcode is required (xcode-select -p = $$selected). Install Xcode or run 'make bootstrap-xcode'."; exit 1 ;; \ + esac @xcrun --sdk macosx --show-sdk-path >/dev/null 2>&1 || ( \ echo "[ERROR] macOS SDK not available. Install Xcode or run: sudo xcode-select --switch /Applications/Xcode.app"; \ exit 1) @@ -221,7 +247,7 @@ ifeq ($(PLATFORM),Darwin) bash scripts/install_xcode.sh || exit 1; \ else \ bash scripts/install_macos_build_tools.sh || exit 1; \ - rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios --toolchain $(RUST_VERSION) >/dev/null 2>&1 || true; \ + rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios aarch64-apple-ios-sim --toolchain $(RUST_VERSION) >/dev/null 2>&1 || true; \ fi else @echo "[ERROR] bootstrap-macos is macOS-only." @@ -272,8 +298,7 @@ clean: ## Remove artifacts and fix permissions @echo "Cleaning Flutter and Rust artifacts..." @chflags -R nouchg build/ macos/ 2>/dev/null || true @chmod -R u+w build/ macos/ 2>/dev/null || true - @if [ -f pubspec.yaml ]; then $(FLUTTER) clean; fi - @if [ -f "Cargo.toml" ]; then cargo clean; fi + @if [ -n "$(FLUTTER)" ] && [ -f pubspec.yaml ]; then "$(FLUTTER)" clean; fi @rm -rf macos/Pods macos/Podfile.lock ios/Pods ios/Podfile.lock build/ @echo "Cleaning local pub cache residues..." @chmod -R u+w $(LINUX_PUB_CACHE)/git/ 2>/dev/null || true @@ -295,10 +320,21 @@ else PREBUILTS ?= 1 endif endif +ifneq ($(filter $(PREBUILTS),0 1),$(PREBUILTS)) + $(error PREBUILTS must be 0 or 1) +endif +ifneq ($(filter MINGW% MSYS%,$(PLATFORM)),) + ifeq ($(PREBUILTS),0) + $(error build-windows uses verified dnix prebuilts; run build_app.sh for source mode) + endif +endif # Android source builds through dnix need an x86_64 Linux host. ANDROID_PREBUILTS ?= $(if $(filter Darwin,$(PLATFORM)),1,$(PREBUILTS)) # Linux only: SYSTEM_DEPS=1 uses the system libsecret/jsoncpp packages instead of building them (like the CI image). SYSTEM_DEPS ?= 0 +ifneq ($(filter $(SYSTEM_DEPS),0 1),$(SYSTEM_DEPS)) + $(error SYSTEM_DEPS must be 0 or 1) +endif LINUX_ARCH := $(shell uname -m | sed -e 's/x86_64/x64/' -e 's/aarch64/arm64/') LINUX_BUNDLE ?= build/linux/$(LINUX_ARCH)/release/bundle @@ -388,6 +424,9 @@ build-linux: require-version check-linux toolchain-check check-reqs ## Build Lin # Windows uses verified dnix prebuilts; source mode needs Nix inside WSL2 and is # driven by build_app.sh directly, not by this target. WINDOWS_COPY_ASSETS ?= 0 +ifneq ($(filter $(WINDOWS_COPY_ASSETS),0 1),$(WINDOWS_COPY_ASSETS)) + $(error WINDOWS_COPY_ASSETS must be 0 or 1) +endif build-windows: require-version check-windows toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @@ -421,6 +460,6 @@ build-android: require-version toolchain-check android-dev-key ## Build Android build-ios: require-version check-sdk-macos toolchain-check ## Build iOS Runner.app without code signing (same steps as CI) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @cd scripts && bash prebuild.sh - @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) -s - @$(FLUTTER) pub get - @$(FLUTTER) build ios --release --no-codesign + @cd scripts && echo yes | env $(IOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) -s + @env $(IOS_ENV_UNSET) $(FLUTTER) pub get + @env $(IOS_ENV_UNSET) $(FLUTTER) build ios --release --no-codesign diff --git a/flake.nix b/flake.nix index cb9d0a3898..bc26b60f8d 100644 --- a/flake.nix +++ b/flake.nix @@ -10,19 +10,23 @@ }; outputs = { self, nixpkgs, flake-utils }: - flake-utils.lib.eachDefaultSystem (system: + flake-utils.lib.eachSystem [ "aarch64-darwin" "x86_64-linux" "aarch64-linux" ] (system: let pkgs = import nixpkgs { inherit system; }; lib = pkgs.lib; # Single source of truth for the toolchain versions; the Homebrew # helper and the Makefile read the same file. bom = builtins.fromTOML (builtins.readFile ./stack-bom.toml); - rustVersion = bom.toolchain.rust; + rustVersion = let + v = bom.toolchain.rust or (throw "stack-bom.toml: missing [toolchain].rust"); + in + if builtins.isString v && builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+" v != null + then v + else throw "stack-bom.toml: [toolchain].rust must be a version string"; clangMajor = lib.versions.major pkgs.llvmPackages.clang.version; commonPackages = with pkgs; [ flutter - dart go rustup cmake @@ -39,7 +43,7 @@ ]; linuxPackages = lib.optionals pkgs.stdenv.hostPlatform.isLinux (with pkgs; [ - gtk3 glib openssl xz clang libgcrypt gobject-introspection + gtk3 glib openssl xz libgcrypt gobject-introspection llvmPackages.libclang llvmPackages.clang opencv @@ -73,9 +77,13 @@ # Resolve the repository root, not the directory the shell was # entered from; .nix-bin and the rustup override are per checkout. - export APP_PROJECT_ROOT_DIR="$(git rev-parse --show-toplevel 2>/dev/null || pwd)" + APP_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)" + if [ ! -f "$APP_ROOT/flake.nix" ]; then + APP_ROOT="$PWD" + fi + export APP_PROJECT_ROOT_DIR="$APP_ROOT" if [ -d "$HOME/.cargo/bin" ]; then - export PATH="$HOME/.cargo/bin:$PATH" + export PATH="$PATH:$HOME/.cargo/bin" fi # The standalone Dart in the Nix Flutter wrapper cannot find the Flutter SDK on its own, @@ -95,14 +103,9 @@ rustup override set ${rustVersion} --path "$APP_PROJECT_ROOT_DIR" >/dev/null 2>&1 || true if [[ "${system}" == *"darwin"* ]]; then - rustup target add aarch64-apple-darwin aarch64-apple-ios --toolchain ${rustVersion} + rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios aarch64-apple-ios-sim --toolchain ${rustVersion} fi - if ! command -v cargo-ndk >/dev/null 2>&1; then - echo "Installing optional Android Cargo tooling..." - cargo install cargo-ndk - fi - # ========================================== # LINUX (NixOS) SPECIFICS # ========================================== @@ -123,18 +126,16 @@ # compile against the macOS SDK. SELECTED_DEVELOPER="$(env -u DEVELOPER_DIR xcode-select -p 2>/dev/null || true)" case "$SELECTED_DEVELOPER" in - *.app/Contents/Developer) - export DEVELOPER_DIR="$SELECTED_DEVELOPER" - ;; + *.app/Contents/Developer) ;; *) echo "[WARN] No full Xcode selected. Install Xcode and run 'make bootstrap-xcode'." - # Leave DEVELOPER_DIR unset so xcrun can still use the - # Command Line Tools for non-Xcode work. - unset DEVELOPER_DIR ;; esac - # nixpkgs' Darwin stdenv exports its own macOS SDK here before - # this hook runs; leave the SDK choice to Xcode per build. + # nixpkgs' Darwin stdenv exports its vendored apple-sdk here + # before this hook runs; clear it so xcrun and xcodebuild use the + # live xcode-select. A per-command DEVELOPER_DIR=... still works. + unset DEVELOPER_DIR + # Leave the SDK choice to Xcode per build. unset SDKROOT export MACOSX_DEPLOYMENT_TARGET="12.0" @@ -159,7 +160,6 @@ mkdir -p "$NIX_BIN" ln -sf /usr/bin/clang "$NIX_BIN/cc" ln -sf /usr/bin/clang++ "$NIX_BIN/c++" - ln -sf /usr/bin/xcodebuild "$NIX_BIN/xcodebuild" ln -sf /usr/bin/clang "$NIX_BIN/clang" ln -sf /usr/bin/clang++ "$NIX_BIN/clang++" @@ -185,10 +185,18 @@ LIPO_EOF # its deployment target and SDK. cat > "$NIX_BIN/xcrun" <&2; return 2 ;; + esac +} value() { - sed -n "s/^$1[[:space:]]*=[[:space:]]*\"\\([^\"]*\\)\".*/\\1/p" "$BOM" | head -n1 + local key="$1" section result + section="$(section_for "$key")" || exit 2 + result="$( + sed -n "/^\[$section\]/,/^\[/p" "$BOM" | + sed -n "s/^$key[[:space:]]*=[[:space:]]*\"\([^\"]*\)\".*/\1/p" | + head -n1 + )" + [ -n "$result" ] || { + echo "Missing [$section] $key in $BOM" >&2 + return 1 + } + printf '%s\n' "$result" } -FLUTTER_VERSION="$(value flutter_min)" -RUST_VERSION="$(value rust)" -GO_VERSION="$(value go_min)" +if [ "${1:-}" = "--get" ]; then + [ "$#" -ge 2 ] || { + echo "Usage: $0 --get [bom]" >&2 + exit 2 + } + [ "$#" -ge 3 ] && BOM="$3" + [ -r "$BOM" ] || { + echo "Cannot read $BOM" >&2 + exit 1 + } + value "$2" + exit +fi -[ -n "$FLUTTER_VERSION" ] || { echo "Missing flutter_min in $BOM" >&2; exit 1; } -[ -n "$RUST_VERSION" ] || { echo "Missing rust in $BOM" >&2; exit 1; } -[ -n "$GO_VERSION" ] || { echo "Missing go_min in $BOM" >&2; exit 1; } +[ "$#" -ge 1 ] && BOM="$1" +[ -r "$BOM" ] || { + echo "Cannot read $BOM" >&2 + exit 1 +} + +FLUTTER_VERSION="$(value flutter)" +FLUTTER_MIN="$(value flutter_min)" +RUST_VERSION="$(value rust)" +GO_VERSION="$(value go)" +GO_MIN="$(value go_min)" -printf 'FLUTTER_VERSION=%s\nRUST_VERSION=%s\nGO_VERSION=%s\n' \ - "$FLUTTER_VERSION" "$RUST_VERSION" "$GO_VERSION" +printf 'FLUTTER_VERSION=%q\nFLUTTER_MIN=%q\nRUST_VERSION=%q\nGO_VERSION=%q\nGO_MIN=%q\n' \ + "$FLUTTER_VERSION" "$FLUTTER_MIN" "$RUST_VERSION" "$GO_VERSION" "$GO_MIN" diff --git a/scripts/download_xcode.sh b/scripts/download_xcode.sh index 7b18f036d5..d679cdebe9 100755 --- a/scripts/download_xcode.sh +++ b/scripts/download_xcode.sh @@ -35,6 +35,10 @@ set -euo pipefail +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +BOM="$SCRIPT_DIR/../stack-bom.toml" +bom_get() { "$SCRIPT_DIR/bom_values.sh" --get "$1" "$BOM"; } + XCODE_VERSION="27.1" TARGET_DIR="" CACHE_DIR="${XCODE_CACHE_DIR:-$HOME/.cache/xcode}" @@ -45,7 +49,16 @@ ASSUME_YES=0 # Output: BUILD|SHA1|IA_ITEM|FILE_NAME release_info() { case "$1" in - 27.1) echo "27A9275|d8b1d16397e6f2faab34bd48b19692a3f7797b9d|xcode-27.1|Xcode_27.1.xip" ;; + 27.1) + local build sha + build="$(bom_get xcode_build)" + sha="$(bom_get xcode_xip_sha1)" + [ -n "$build" ] && [ -n "$sha" ] || { + echo "[ERROR] Missing Xcode build/hash in $BOM" >&2 + return 1 + } + echo "${build}|${sha}|xcode-27.1|Xcode_27.1.xip" + ;; 27.0) echo "27A266a|04a7d831229ac95577f09398d87501a1c6fb92ad|xcode-27.0|Xcode_27.xip" ;; 16.2) echo "16C5032a|aa1a3f12d4217ab04ea4064f40e92399192e15f9|xcode-16.2|Xcode_16.2.xip" ;; 16.0) echo "16A242d|71b15ff10826474491ebca3d36a6ca5964b9e1c5|xcode-16.0|Xcode_16.xip" ;; @@ -76,7 +89,7 @@ if [[ "$(uname -s)" != "Darwin" ]]; then exit 1 fi -if [[ "${CI:-}" == "true" || "${CI:-}" == "1" ]]; then +if [[ $DRY_RUN -eq 0 && ( "${CI:-}" == "true" || "${CI:-}" == "1" ) ]]; then echo "[ERROR] Refusing to download Xcode from archive.org in CI." >&2 exit 1 fi @@ -107,7 +120,6 @@ esac # sudo is only needed when the target directory is not writable (for example /Applications). SUDO="" -mkdir -p "$(dirname "$TARGET_DIR")" 2>/dev/null || true if [[ ! -w "$(dirname "$TARGET_DIR")" ]]; then SUDO="sudo" fi @@ -177,10 +189,14 @@ if [[ $DRY_RUN -eq 1 ]]; then exit 0 fi +mkdir -p "$(dirname "$TARGET_DIR")" 2>/dev/null || true + if [[ $ASSUME_YES -eq 0 ]]; then echo "This downloads ~2 GB, needs ~20 GB free while extracting, and uses sudo only if ${TARGET_DIR} is not writable." echo "Redistribution of Xcode by third parties may conflict with Apple's license terms." - read -r -p "Continue? (yes/no): " ANSWER + if ! read -r -p "Continue? (yes/no): " ANSWER; then + ANSWER="" + fi [[ "$ANSWER" == "yes" ]] || { echo "Aborted."; exit 1; } fi diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh index 06b02ea4cd..becf473e93 100755 --- a/scripts/install_macos_build_tools.sh +++ b/scripts/install_macos_build_tools.sh @@ -55,9 +55,8 @@ SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]:-$0}")" && pwd)" REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" # Read a value from stack-bom.toml so the Homebrew fallback and the flake use # the same versions. -bom_value() { - sed -n "s/^$1[[:space:]]*=[[:space:]]*\"\\([^\"]*\\)\".*/\\1/p" \ - "$REPO_ROOT/stack-bom.toml" 2>/dev/null | head -n 1 +bom_get() { + "$SCRIPT_DIR/bom_values.sh" --get "$1" "$REPO_ROOT/stack-bom.toml" } bash "$SCRIPT_DIR/install_xcode.sh" @@ -73,8 +72,8 @@ brew install pandoc weasyprint toilet figlet || echo "[WARN] optional report too # The Homebrew cask always installs the latest Flutter, but CI builds and tests # one pinned release. Install that tag from source instead. -FLUTTER_RECOMMENDED="$(bom_value flutter)" -FLUTTER_MIN="$(bom_value flutter_min)" +FLUTTER_RECOMMENDED="$(bom_get flutter)" +FLUTTER_MIN="$(bom_get flutter_min)" FLUTTER_VERSION="${FLUTTER_VERSION:-${FLUTTER_RECOMMENDED:-3.47.2}}" # Accept the recommended version and the CI minimum; an explicit # FLUTTER_VERSION only accepts that version. @@ -140,7 +139,7 @@ if ! command -v rustup >/dev/null 2>&1; then die "rustup not found in PATH. Check brew install." fi -RUST_VERSION="${RUST_VERSION:-$(bom_value rust)}" +RUST_VERSION="${RUST_VERSION:-$(bom_get rust)}" RUST_VERSION="${RUST_VERSION:-1.99.1}" echo "Ensuring Rust $RUST_VERSION toolchain..." rustup toolchain install "$RUST_VERSION" diff --git a/stack-bom.toml b/stack-bom.toml index f84b07cfc2..cf4c50bbed 100644 --- a/stack-bom.toml +++ b/stack-bom.toml @@ -4,10 +4,11 @@ schema_version = 1 [toolchain] flutter = "3.47.4" # recommended; macOS builds verified with 3.47.2 and 3.47.4 -flutter_min = "3.47.2" # what CI and pubspec.template.yaml use today +flutter_min = "3.47.2" # minimum for pubspec.template.yaml and the release workflow dart_prefix = "3.13" # Dart bundled with Flutter 3.47.x rust = "1.99.1" # installed through rustup, pinned by the native plugins -go_min = "1.24" # flutter_mwebd +go = "1.24.13" # exact Go used by the make-build workflow +go_min = "1.24.1" # flutter_mwebd's minimum on the Flutter host [hooks] hooks_runner = "1.5.0" # pinned by Flutter 3.47.x; CARGO_/RUSTUP_ env vars reach hooks only from 1.6.2 diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 80bfc81c79..0a800d3a28 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -54,7 +54,15 @@ Map> _readBom(String text) { } if (value.startsWith('"')) { final end = value.indexOf('"', 1); + if (end < 0) { + stderr.writeln('Unterminated string in $_bomFile: $line'); + exit(2); + } value = value.substring(1, end); + } else if (value.length >= 2 && + value.startsWith("'") && + value.endsWith("'")) { + value = value.substring(1, value.length - 1); } result.putIfAbsent(section, () => {})[key] = value; } @@ -86,31 +94,42 @@ int _cmp(String a, String b) { return 0; } +String _short(String v) => v.length <= 7 ? v : v.substring(0, 7); + /// Plugins declared by the app currently configured in pubspec.yaml. /// /// Campfire and Stack Duo include only a subset of the pinned plugins, so a /// missing lock entry is only an error for a plugin the app actually uses. +/// Accepts any consistent indentation and both direct dependencies and +/// dependency_overrides; the hooks: user_defines: block is not a declaration. Set _declaredPlugins() { final file = File('pubspec.yaml'); if (!file.existsSync()) return {}; + final lines = file.readAsLinesSync(); final declared = {}; - var inDependencies = false; - for (final line in file.readAsLinesSync()) { - if (line.startsWith('dependencies:')) { - inDependencies = true; - continue; - } - // A non-indented, non-comment line starts the next top-level section. - if (inDependencies && - line.isNotEmpty && - !line.startsWith(' ') && - !line.startsWith('#')) { - inDependencies = false; + for (final sectionName in ['dependencies:', 'dependency_overrides:']) { + final start = lines.indexWhere((l) => l.trimRight() == sectionName); + if (start < 0) continue; + int? indent; + for (var i = start + 1; i < lines.length; i++) { + final line = lines[i]; + if (line.trim().isEmpty || line.trimLeft().startsWith('#')) continue; + if (!line.startsWith(' ')) break; + indent = line.length - line.trimLeft().length; + break; } - if (!inDependencies) continue; - final m = RegExp(r'^ (\w+):').firstMatch(line); - if (m != null && _pluginNames.contains(m.group(1))) { - declared.add(m.group(1)!); + if (indent == null) continue; + for (var i = start + 1; i < lines.length; i++) { + final line = lines[i]; + if (line.trim().isEmpty || line.trimLeft().startsWith('#')) continue; + if (!line.startsWith(' ')) break; + final currentIndent = line.length - line.trimLeft().length; + if (currentIndent < indent) break; + if (currentIndent != indent) continue; + final m = RegExp(r'^[ ]*(\w+):').firstMatch(line); + if (m != null && _pluginNames.contains(m.group(1))) { + declared.add(m.group(1)!); + } } } return declared; @@ -146,7 +165,17 @@ Future _update() async { // Without a pubspec.yaml we cannot tell which app is configured; keep the // old behaviour and update every plugin the lock knows about. final updateable = declared.isEmpty ? _pluginNames.toSet() : declared; - final start = text.indexOf('[plugins]'); + final header = RegExp( + r'^\[plugins\][ \t]*$', + multiLine: true, + ).firstMatch(text); + final start = header?.start ?? -1; + if (start < 0 && text.contains('[plugins]')) { + stderr.writeln( + 'Found [plugins] outside a table header; refusing to update', + ); + exit(2); + } final tailStart = start < 0 ? text.length : text.indexOf(RegExp(r'\n\[', multiLine: true), start + 1); @@ -154,26 +183,43 @@ Future _update() async { final head = start < 0 ? text.trimRight() : text.substring(0, start).trimRight(); + for (final n in updateable) { + if (!refs.containsKey(n)) { + stderr.writeln( + 'Warning: $n is declared but missing from pubspec.lock; ' + 'pin not updated', + ); + } + } final buf = StringBuffer(head) ..writeln('\n') ..writeln('[plugins]') ..writeln( '# Generated by `dart tool/verify_bom.dart --update` from pubspec.lock. Do not edit by hand.', ); - var written = 0; + var refreshed = 0; + var preserved = 0; for (final n in _pluginNames) { if (updateable.contains(n) && refs.containsKey(n)) { buf.writeln('$n = "${refs[n]}"'); - written++; + refreshed++; } else if (existing.containsKey(n)) { // Keep pins for apps this checkout is not configured for. buf.writeln('$n = "${existing[n]}"'); - written++; + preserved++; } } + for (final entry in existing.entries) { + if (_pluginNames.contains(entry.key)) continue; + buf.writeln('${entry.key} = "${entry.value}"'); + preserved++; + } buf.write(tail); File(_bomFile).writeAsStringSync(buf.toString()); - stdout.writeln('Updated [plugins] in $_bomFile ($written entries).'); + stdout.writeln( + 'Updated [plugins] in $_bomFile ' + '($refreshed refreshed, $preserved preserved).', + ); } Future main(List args) async { @@ -184,14 +230,19 @@ Future main(List args) async { if (args.contains('--update')) return _update(); final bom = _readBom(File(_bomFile).readAsStringSync()); + final root = bom[''] ?? {}; + if (root['schema_version'] != '1') { + _fail('schema_version must be 1 in $_bomFile'); + } final tc = bom['toolchain'] ?? {}; // Flutter / Dart final configuredFlutter = Platform.environment['FLUTTER']?.trim() ?? ''; - final fl = await _run( - configuredFlutter.isEmpty ? 'flutter' : configuredFlutter, - ['--version', '--machine'], - ); + final flutterExe = + configuredFlutter.isNotEmpty && File(configuredFlutter).existsSync() + ? configuredFlutter + : 'flutter'; + final fl = await _run(flutterExe, ['--version', '--machine']); if (fl == null) { _fail('flutter not found in PATH'); } else { @@ -271,17 +322,16 @@ Future main(List args) async { final refs = _lockRefs(); final pinned = bom['plugins'] ?? {}; final declared = _declaredPlugins(); + final pubspecExists = File('pubspec.yaml').existsSync(); // A fresh checkout has no pubspec.yaml: build_app.sh generates it later. // In that case check every plugin the lock contains, as before. - final required = File('pubspec.yaml').existsSync() - ? declared - : _pluginNames.toSet(); + final required = pubspecExists ? declared : _pluginNames.toSet(); if (refs.isEmpty) { _warn('pubspec.lock not found, plugin pins not checked'); } else if (required.isEmpty) { - _warn( - 'pubspec.yaml declares none of the pinned plugins, ' - 'plugin pins not checked', + _fail( + 'could not read plugin declarations from pubspec.yaml ' + '(expected them under dependencies: or dependency_overrides:)', ); } else { for (final n in _pluginNames) { @@ -295,11 +345,11 @@ Future main(List args) async { } else if (pin == null) { _fail('$n is missing from [plugins] in $_bomFile (run --update)'); } else if (pin == ref) { - _ok('$n ${ref.substring(0, 7)}'); + _ok('$n ${_short(ref)}'); } else { _fail( - '$n is ${ref.substring(0, 7)} in pubspec.lock but ' - '${pin.substring(0, 7)} in $_bomFile (run --update)', + '$n is ${_short(ref)} in pubspec.lock but ' + '${_short(pin)} in $_bomFile (run --update)', ); } } From 07f714dcefdc32ac1545ba3f03a68bcd692e6321 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:41:40 +0200 Subject: [PATCH 029/107] docs: align build docs with the hardened toolchain - Document -s and the four dnix packages. - Use the exact preflight target names in the build-flow diagrams. - Describe Flutter/Rust as BOM values rather than fixed literals. --- README.md | 4 ++-- docs/building/macos.md | 4 ++-- docs/building/make-flow.md | 19 ++++++++++--------- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 06a29a2d02..6911c492e5 100644 --- a/README.md +++ b/README.md @@ -63,8 +63,8 @@ using. 2. Run build (pass the release version and a build number; `make` refuses to guess): - `make build-macos VERSION=x.y.z BUILD_NUM=nnn` -The flake provides Flutter, Dart, rustup (which installs Rust 1.99.1 on first -entry), Go, CMake, Meson, Ninja, pkg-config and protoc. Xcode is never provided +The flake provides Flutter, Dart, rustup (which installs the BOM Rust version +on first entry), Go, CMake, Meson, Ninja, pkg-config and protoc. Xcode is never provided by Nix; the flake uses the Xcode selected by `xcode-select`. ### macOS with Homebrew (fallback) diff --git a/docs/building/macos.md b/docs/building/macos.md index ce4cd892a7..81a5862dd9 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -16,7 +16,7 @@ toolchain; the same build is also available through: | Manual | install the prerequisites below | With Nix or direnv the flake supplies Flutter, Dart, rustup (which installs -Rust 1.99.1 on first entry), Go, CMake, Meson, Ninja, pkg-config and protoc. +the BOM Rust version on first entry), Go, CMake, Meson, Ninja, pkg-config and protoc. Xcode always comes from the host. The prerequisites below describe the manual/Homebrew path. @@ -24,7 +24,7 @@ manual/Homebrew path. | What | Needed for | |---|---| -| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 | Manual and Homebrew modes | +| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 minimum, 3.47.4 recommended | Manual and Homebrew modes | | Your usual Xcode | Building the app, in both dnix modes | | Xcode **27.0**, release build **27A266a**, installed next to your usual Xcode | Source mode (dnix), in every host mode: dnix builds its four packages with it, including during `flutter test`. It doesn't need to be selected; see [Install Xcode 27.0](#install-xcode-270) | | [Homebrew](https://brew.sh/) packages below | Manual and Homebrew modes | diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index 3e84388e8b..c82c245bb4 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -1,8 +1,9 @@ # Make build flow This page is the maintained source for the two build-flow diagrams. GitHub -renders the Mermaid blocks directly; the PNG versions are generated from the -same blocks. Keep them in sync with the `Makefile`. +renders the Mermaid blocks directly; PNGs can be generated locally from the +same blocks (they are not committed). Keep the source in sync with the +`Makefile`. ## 1. Get the tools (once per Mac) @@ -34,15 +35,15 @@ flowchart LR B --> H["Homebrew helper
Flutter · Rust · Go"] M --> P["Tools on PATH"] - F --> C["make toolchain
check-reqs-macos"] + F --> C["make toolchain-check
check-reqs-macos"] H --> C P --> C C --> X{"Full Xcode?"} X -- yes --> R["Ready to build"] X -- no --> XS["make bootstrap-xcode"] + X -- no --> DL["make bootstrap-xcode-download
optional; archive.org, hash + signature"] XS --> R - XS -. optional .-> DL["make bootstrap-xcode-download
archive.org, hash + signature"] DL --> R ``` @@ -64,31 +65,31 @@ flowchart TD O --> WIN["make build-windows"] O --> AND["make build-android"] - MAC --> MC["checks
require-version · check-sdk-macos
toolchain · check-reqs"] + MAC --> MC["checks
require-version · check-sdk-macos
toolchain-check · check-reqs-macos"] MC --> MP{"PREBUILTS"} MP -- "0 default" --> MS["source
Nix + Xcode 27.0"] MP -- "1" --> MB["prebuilt -d"] MS --> MR["build_app.sh -p macos -s
pub get · prebuild.sh
flutter build macos"] MB --> MR - IOS --> IC["checks
require-version · check-sdk-macos
(macOS-only) · toolchain"] + IOS --> IC["checks
require-version · check-sdk-macos
(macOS-only) · toolchain-check"] IC --> IP{"PREBUILTS"} IP -- "0 default" --> IS["source"] IP -- "1 CI" --> IB["prebuilt -d"] IS --> IR["prebuild.sh
build_app.sh -p ios -s
pub get · flutter build ios"] IB --> IR - LINUX --> LC["checks
require-version · check-linux
toolchain · check-reqs"] + LINUX --> LC["checks
require-version · check-linux
toolchain-check · check-reqs"] LC --> LP{"PREBUILTS"} LP -- "0 default" --> LS["source (Nix)"] LP -- "1" --> LB["prebuilt -d"] LS --> LR["prebuild.sh
build_app.sh -p linux
flutter build linux · bundle"] LB --> LR - WIN --> WC["checks
require-version · check-windows
toolchain · flutter · Go"] + WIN --> WC["checks
require-version · check-windows
toolchain-check · flutter · Go"] WC --> WR["prebuild.sh
build_app.sh -p windows -d
pub get · flutter build windows
always prebuilt"] - AND --> AC["checks
require-version · toolchain
dev key · SDK"] + AND --> AC["checks
require-version · toolchain-check
dev key · SDK"] AC --> AH{"Host"} AH -- macOS --> AB["prebuilt -d"] AH -- Linux --> AP{"PREBUILTS"} From 2b0b1e6ef6b73762bab879bd25dffdc7d576ce53 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:56:46 +0200 Subject: [PATCH 030/107] build: remove superseded asset-link and native-build leftovers - Windows always copies the asset directories; drop WINDOWS_COPY_ASSETS, the MSYS2/mklink path and the three duplicated CI copy blocks. - Remove dead crypto_plugins excludes and the unused cbindgen/gnu-sed installs; make the bm report tools opt-in. - Drop submodules: recursive from every checkout; the repository has no submodules after the native-assets migration. --- .github/workflows/build.yaml | 61 ------------------- .github/workflows/make-build.yaml | 6 +- .github/workflows/test.yaml | 1 - Makefile | 9 +-- README.md | 2 +- analysis_options.yaml | 1 - bm/collect.sh | 2 +- docs/building/windows.md | 2 +- .../templates/pubspec.template.yaml | 1 - scripts/install_macos_build_tools.sh | 9 +-- 10 files changed, 12 insertions(+), 82 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 74ee07ff15..5cb07530d5 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -49,7 +49,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -120,7 +119,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -219,7 +217,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -265,24 +262,6 @@ jobs: -b "${{ steps.ver.outputs.build_number }}" \ -p windows -a stack_wallet -d -s - # Use real copies of the five gitignored asset directories instead of the - # directory links that link_assets.sh creates. - - name: Replace asset symlinks with copies (CI workaround) - run: | - set -euo pipefail - for dirname in default_themes icon lottie in_app_logo_icons svg; do - target="assets/${dirname}" - source="asset_sources/${dirname}/stack_wallet" - # Remove whatever link_assets.sh left (reparse point, symlink, or nothing). - # cmd.exe rmdir on a junction/symlink removes the link, not the target. - if [ -e "$target" ] || [ -L "$target" ]; then - MSYS2_ARG_CONV_EXCL="/C${MSYS2_ARG_CONV_EXCL:+;$MSYS2_ARG_CONV_EXCL}" \ - cmd.exe /C rmdir "$(cygpath -w "$target")" 2>/dev/null || rm -rf "$target" - fi - mkdir -p "$target" - cp -r "${source}/." "$target/" - done - - name: Get dependencies run: | flutter pub get @@ -313,7 +292,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -384,7 +362,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -463,7 +440,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -534,7 +510,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -722,7 +697,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -821,7 +795,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -865,20 +838,6 @@ jobs: -b "${{ steps.ver.outputs.build_number }}" \ -p windows -a campfire -d -s - - name: Replace asset symlinks with copies (CI workaround) - run: | - set -euo pipefail - for dirname in default_themes icon lottie in_app_logo_icons svg; do - target="assets/${dirname}" - source="asset_sources/${dirname}/campfire" - if [ -e "$target" ] || [ -L "$target" ]; then - MSYS2_ARG_CONV_EXCL="/C${MSYS2_ARG_CONV_EXCL:+;$MSYS2_ARG_CONV_EXCL}" \ - cmd.exe /C rmdir "$(cygpath -w "$target")" 2>/dev/null || rm -rf "$target" - fi - mkdir -p "$target" - cp -r "${source}/." "$target/" - done - - name: Get dependencies run: | flutter pub get @@ -909,7 +868,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -980,7 +938,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -1176,7 +1133,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -1275,7 +1231,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -1319,20 +1274,6 @@ jobs: -b "${{ steps.ver.outputs.build_number }}" \ -p windows -a stack_duo -d -s - - name: Replace asset symlinks with copies (CI workaround) - run: | - set -euo pipefail - for dirname in default_themes icon lottie in_app_logo_icons svg; do - target="assets/${dirname}" - source="asset_sources/${dirname}/stack_duo" - if [ -e "$target" ] || [ -L "$target" ]; then - MSYS2_ARG_CONV_EXCL="/C${MSYS2_ARG_CONV_EXCL:+;$MSYS2_ARG_CONV_EXCL}" \ - cmd.exe /C rmdir "$(cygpath -w "$target")" 2>/dev/null || rm -rf "$target" - fi - mkdir -p "$target" - cp -r "${source}/." "$target/" - done - - name: Get dependencies run: | flutter pub get @@ -1363,7 +1304,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -1434,7 +1374,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver diff --git a/.github/workflows/make-build.yaml b/.github/workflows/make-build.yaml index ba99d30a8c..fafab0e09e 100644 --- a/.github/workflows/make-build.yaml +++ b/.github/workflows/make-build.yaml @@ -50,7 +50,7 @@ jobs: - name: Check the toolchain bill of materials run: make verify-bom - name: Build - run: make build-windows VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} WINDOWS_COPY_ASSETS=1 + run: make build-windows VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} macos: runs-on: macos-latest @@ -78,7 +78,7 @@ jobs: with: toolchain: ${{ steps.bom.outputs.rust }} - name: Tools - run: brew install meson ninja autoconf automake libtool protobuf pkg-config cbindgen + run: brew install meson ninja autoconf automake libtool protobuf pkg-config - name: Check the toolchain bill of materials run: make verify-bom - name: Build @@ -156,7 +156,7 @@ jobs: with: toolchain: ${{ steps.bom.outputs.rust }} - name: Tools - run: brew install meson ninja autoconf automake libtool protobuf pkg-config cbindgen + run: brew install meson ninja autoconf automake libtool protobuf pkg-config - name: Check the toolchain bill of materials run: make verify-bom - name: Build diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 25dcc8495d..e7ca3eb969 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -41,7 +41,6 @@ jobs: uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive # -d selects verified dnix prebuilts for Frost, Tor, Epic and MWC. # -s (CI only) skips building jsoncpp and libsecret; the image has them. diff --git a/Makefile b/Makefile index d29c8c15a1..02245f044e 100644 --- a/Makefile +++ b/Makefile @@ -419,20 +419,13 @@ build-linux: require-version check-linux toolchain-check check-reqs ## Build Lin @python3 scripts/linux/prepare_release_bundle.py $(LINUX_BUNDLE) # Windows: run from Git Bash. Same steps as the "build-windows" job in .github/workflows/build.yaml. -# WINDOWS_COPY_ASSETS=1 makes link_assets.sh copy instead of creating symlinks, for hosts -# where the user cannot create them (for example the GitHub-hosted runner). # Windows uses verified dnix prebuilts; source mode needs Nix inside WSL2 and is # driven by build_app.sh directly, not by this target. -WINDOWS_COPY_ASSETS ?= 0 -ifneq ($(filter $(WINDOWS_COPY_ASSETS),0 1),$(WINDOWS_COPY_ASSETS)) - $(error WINDOWS_COPY_ASSETS must be 0 or 1) -endif - build-windows: require-version check-windows toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed."; exit 1; } @cd scripts && bash prebuild.sh - @cd scripts && echo yes | MWEBD_FETCH=1 WINDOWS_COPY_ASSETS=$(WINDOWS_COPY_ASSETS) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d -s + @cd scripts && echo yes | MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d -s @$(FLUTTER) pub get @$(FLUTTER) build windows --release diff --git a/README.md b/README.md index 6911c492e5..95891c78c7 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ uses the verified prebuilts and needs no Nix for them. The Homebrew bootstrap installs the native build tools and configures Rust 1.99.1 for Flutter's native-assets hooks. It replaces the former local -`crypto_plugins` macOS prebuild path; no submodule setup or manual native +manual macOS native prebuild path; no submodule setup or manual native plugin build is needed. ### macOS with a manual toolchain (advanced) diff --git a/analysis_options.yaml b/analysis_options.yaml index 3bd4cea564..623f535d06 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -13,7 +13,6 @@ analyzer: - "**/*.g.dart" - "**/*.freezed.dart" - "test/.test_coverage.dart" - - "crypto_plugins/**" - "bin/cache/**" - "lib/generated_plugin_registrant.dart" - "lib/wl_gen/generated/**" diff --git a/bm/collect.sh b/bm/collect.sh index e1a8b066ec..a36ae9455a 100755 --- a/bm/collect.sh +++ b/bm/collect.sh @@ -93,7 +93,7 @@ main() { echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},total_project,${total}," >> "$csv" # Native-assets Rust target directories aggregate. Flutter's hooks keep - # these under .dart_tool instead of the deleted crypto_plugins tree. + # these under .dart_tool instead of the old native build tree. local rust_total=0 while IFS= read -r target_dir; do local sz diff --git a/docs/building/windows.md b/docs/building/windows.md index 41d770812b..9e5ca482f3 100644 --- a/docs/building/windows.md +++ b/docs/building/windows.md @@ -11,7 +11,7 @@ with Windows Flutter. For how the build fits together, see the |---|---| | [Flutter](https://docs.flutter.dev/install/manual) 3.47.2, and Git for Windows, which includes Git Bash | Every build | | [Visual Studio 2022](https://docs.flutter.dev/platform-integration/windows/setup) with **Desktop development with C++**, CMake tools and a Windows SDK | Every build | -| Windows Developer Mode, for the symlinks Flutter and the asset scripts create | Every build | +| Windows Developer Mode, for the symlinks Flutter and its plugins create | Every build | | [Rustup](https://rustup.rs/) on Windows | Every app's DNSSEC hook and Stack Wallet's Xelis hook, in both modes | | WSL2 with Ubuntu 24.04, and [Nix](https://nixos.org/download/) inside it | Source mode, the default; not needed with `-d` | | Go 1.24.0 or newer and `mingw-w64` in the default WSL distribution | Stack Wallet's [MWEB build](#mweb), unless you set `MWEBD_FETCH=1` | diff --git a/scripts/app_config/templates/pubspec.template.yaml b/scripts/app_config/templates/pubspec.template.yaml index 3761771c1e..f65ea371ff 100644 --- a/scripts/app_config/templates/pubspec.template.yaml +++ b/scripts/app_config/templates/pubspec.template.yaml @@ -439,5 +439,4 @@ import_sorter: comments: false # Optional, defaults to true ignored_files: # Optional, defaults to [] - \/test\/* - - \/crypto_plugins\/* - \/integration_test\/* diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh index becf473e93..b97366c61f 100755 --- a/scripts/install_macos_build_tools.sh +++ b/scripts/install_macos_build_tools.sh @@ -63,12 +63,13 @@ bash "$SCRIPT_DIR/install_xcode.sh" echo "Installing Homebrew packages..." # Do not upgrade formulae that are already installed: a build machine keeps the versions it was set up with. export HOMEBREW_NO_INSTALL_UPGRADE=1 -brew install direnv rustup cmake meson ninja pkg-config gnu-sed cocoapods go protobuf cbindgen autoconf automake libtool sccache +brew install direnv rustup cmake meson ninja pkg-config cocoapods go protobuf autoconf automake libtool sccache add_rustup_to_path -# Only used for the benchmark reports in bm/. A failure here (for example a link conflict with a -# copy installed another way) must not stop the toolchain setup. -brew install pandoc weasyprint toilet figlet || echo "[WARN] optional report tools were not fully installed; only bm/ report rendering needs them." +# Only used for the benchmark reports in bm/. Opt in with BM_REPORT_TOOLS=1. +if [[ "${BM_REPORT_TOOLS:-0}" = "1" ]]; then + brew install pandoc weasyprint toilet figlet || echo "[WARN] optional report tools were not fully installed; only bm/ report rendering needs them." +fi # The Homebrew cask always installs the latest Flutter, but CI builds and tests # one pinned release. Install that tag from source instead. From d7818d07efff3e979f3ae11a384776378915d7ff Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:59:17 +0200 Subject: [PATCH 031/107] build: feed release CI from the BOM and finish edge cases - Add a bom job to build.yaml and wire the nine version-using jobs to its Flutter, Go and DNSSEC Rust outputs. - Pin dtolnay/rust-toolchain to stable and add post-build BOM checks to the make-build jobs. - Treat an unreadable installed Xcode build as installed instead of re-downloading; append BINDGEN flags; target the framework in the lipo wrapper; warn when Android on macOS ignores PREBUILTS=0. --- .github/workflows/build.yaml | 103 +++++++++++++++++++----------- .github/workflows/make-build.yaml | 22 +++++-- Makefile | 3 + flake.nix | 9 ++- scripts/bom_values.sh | 7 +- scripts/download_xcode.sh | 8 +++ stack-bom.toml | 3 +- 7 files changed, 107 insertions(+), 48 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 5cb07530d5..21d233ef51 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -18,10 +18,30 @@ on: default: '1' # Configure app uses -d for verified dnix prebuilts (Frost, Tor, Epic and MWC). -# Every app still builds dnssec_resolver with Rust 1.90.0; Stack Wallet also +# Every app still builds dnssec_resolver with the BOM DNSSEC Rust (1.90.0); Stack Wallet also # builds Xelis with Rust 1.99.1, and Stack Wallet/Campfire build Spark with C++. jobs: + bom: + runs-on: ubuntu-latest + outputs: + flutter: ${{ steps.read.outputs.flutter }} + go: ${{ steps.read.outputs.go }} + dnssec_rust: ${{ steps.read.outputs.dnssec_rust }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 1 + - name: Read stack-bom.toml + id: read + run: | + flutter="$(bash scripts/bom_values.sh --get flutter_min)" + go="$(bash scripts/bom_values.sh --get go)" + dnssec_rust="$(bash scripts/bom_values.sh --get dnssec_rust)" + echo "flutter=$flutter" >> "$GITHUB_OUTPUT" + echo "go=$go" >> "$GITHUB_OUTPUT" + echo "dnssec_rust=$dnssec_rust" >> "$GITHUB_OUTPUT" + build-disclaimer: runs-on: ubuntu-24.04 steps: @@ -209,6 +229,7 @@ jobs: path: android-artifacts/ build-windows: + needs: bom runs-on: windows-2022 defaults: run: @@ -236,18 +257,18 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Flutter doctor run: flutter doctor -v @@ -287,6 +308,7 @@ jobs: path: stack_wallet-windows-x86_64-${{ steps.ver.outputs.version }}.zip build-macos: + needs: bom runs-on: macos-latest steps: - uses: actions/checkout@v6 @@ -311,18 +333,18 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Configure app run: | @@ -357,6 +379,7 @@ jobs: path: stack_wallet-macos-aarch64-${{ steps.ver.outputs.version }}.zip build-ios: + needs: bom runs-on: macos-latest steps: - uses: actions/checkout@v6 @@ -381,18 +404,18 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Configure app run: | @@ -787,6 +810,7 @@ jobs: path: android-artifacts/ build-campfire-windows: + needs: bom runs-on: windows-2022 defaults: run: @@ -814,18 +838,18 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Flutter doctor run: flutter doctor -v @@ -863,6 +887,7 @@ jobs: path: campfire-windows-x86_64-${{ steps.ver.outputs.version }}.zip build-campfire-macos: + needs: bom runs-on: macos-latest steps: - uses: actions/checkout@v6 @@ -887,18 +912,18 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Configure app run: | @@ -933,6 +958,7 @@ jobs: path: campfire-macos-aarch64-${{ steps.ver.outputs.version }}.zip build-campfire-ios: + needs: bom runs-on: macos-latest steps: - uses: actions/checkout@v6 @@ -957,18 +983,18 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Configure app run: | @@ -1223,6 +1249,7 @@ jobs: path: android-artifacts/ build-stack-duo-windows: + needs: bom runs-on: windows-2022 defaults: run: @@ -1250,18 +1277,18 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Flutter doctor run: flutter doctor -v @@ -1299,6 +1326,7 @@ jobs: path: stack_duo-windows-x86_64-${{ steps.ver.outputs.version }}.zip build-stack-duo-macos: + needs: bom runs-on: macos-latest steps: - uses: actions/checkout@v6 @@ -1323,18 +1351,18 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Configure app run: | @@ -1369,6 +1397,7 @@ jobs: path: stack_duo-macos-aarch64-${{ steps.ver.outputs.version }}.zip build-stack-duo-ios: + needs: bom runs-on: macos-latest steps: - uses: actions/checkout@v6 @@ -1393,18 +1422,18 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Configure app run: | diff --git a/.github/workflows/make-build.yaml b/.github/workflows/make-build.yaml index fafab0e09e..0232267861 100644 --- a/.github/workflows/make-build.yaml +++ b/.github/workflows/make-build.yaml @@ -7,7 +7,7 @@ name: Make build # reproducibility builds belong to the dnix packages' own CI. # # Toolchain versions come from stack-bom.toml via scripts/bom_values.sh. The -# release workflow (build.yaml) keeps its own DNSSEC 1.90.0 pins. +# release workflow (build.yaml) reads the BOM's DNSSEC Rust pin. on: workflow_dispatch: @@ -42,7 +42,7 @@ jobs: - uses: actions/setup-go@v6 with: go-version: ${{ steps.bom.outputs.go }} - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: toolchain: ${{ steps.bom.outputs.rust }} - name: Install make @@ -52,6 +52,9 @@ jobs: - name: Build run: make build-windows VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} + - name: Verify the generated app BOM + run: make verify-bom + macos: runs-on: macos-latest steps: @@ -74,7 +77,7 @@ jobs: - uses: actions/setup-go@v6 with: go-version: ${{ steps.bom.outputs.go }} - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: toolchain: ${{ steps.bom.outputs.rust }} - name: Tools @@ -84,6 +87,9 @@ jobs: - name: Build run: make build-macos VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 + - name: Verify the generated app BOM + run: make verify-bom + linux: runs-on: ubuntu-24.04 steps: @@ -106,7 +112,7 @@ jobs: - uses: actions/setup-go@v6 with: go-version: ${{ steps.bom.outputs.go }} - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: toolchain: ${{ steps.bom.outputs.rust }} - name: Free disk space @@ -126,6 +132,9 @@ jobs: - name: Build run: make build-linux VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 SYSTEM_DEPS=1 + - name: Verify the generated app BOM + run: make verify-bom + ios: # The fork has a single hosted macOS concurrency slot. Running macOS and # iOS together leaves one job queued until GitHub cancels it; serialise them. @@ -152,7 +161,7 @@ jobs: - uses: actions/setup-go@v6 with: go-version: ${{ steps.bom.outputs.go }} - - uses: dtolnay/rust-toolchain@master + - uses: dtolnay/rust-toolchain@stable with: toolchain: ${{ steps.bom.outputs.rust }} - name: Tools @@ -161,3 +170,6 @@ jobs: run: make verify-bom - name: Build run: make build-ios VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 + + - name: Verify the generated app BOM + run: make verify-bom diff --git a/Makefile b/Makefile index 02245f044e..52f1391149 100644 --- a/Makefile +++ b/Makefile @@ -444,6 +444,9 @@ android-dev-key: ## Create a throw-away debug signing key if android/key.propert build-android: require-version toolchain-check android-dev-key ## Build Android APKs (prebuilt dnix on macOS; Linux follows PREBUILTS) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } + @if [ "$(PREBUILTS)" = "0" ] && [ "$(PLATFORM)" = "Darwin" ]; then \ + echo "[WARN] Android on macOS uses verified prebuilts; dnix source builds need an x86_64 Linux host."; \ + fi @cd scripts && bash prebuild.sh @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p android -a $(APP_NAME) $(if $(filter 1,$(ANDROID_PREBUILTS)),-d) -s @$(FLUTTER) pub get diff --git a/flake.nix b/flake.nix index bc26b60f8d..c6b2ce8b67 100644 --- a/flake.nix +++ b/flake.nix @@ -152,7 +152,11 @@ SDK_PATH="$(/usr/bin/xcrun --sdk macosx --show-sdk-path 2>/dev/null || true)" if [ -n "$SDK_PATH" ]; then - export BINDGEN_EXTRA_CLANG_ARGS="-isysroot $SDK_PATH" + if [ -n "$BINDGEN_EXTRA_CLANG_ARGS" ]; then + export BINDGEN_EXTRA_CLANG_ARGS="-isysroot $SDK_PATH $BINDGEN_EXTRA_CLANG_ARGS" + else + export BINDGEN_EXTRA_CLANG_ARGS="-isysroot $SDK_PATH" + fi fi export PROTOC="${pkgs.protobuf}/bin/protoc" @@ -173,7 +177,8 @@ #!/bin/bash for arg in "$@"; do if [[ "$arg" == *"FlutterMacOS.framework"* ]]; then - chmod -R u+w "$(dirname "$arg")" 2>/dev/null || true + framework="''${arg%%FlutterMacOS.framework*}FlutterMacOS.framework" + chmod -R u+w "$framework" 2>/dev/null || true fi done exec /usr/bin/lipo "$@" diff --git a/scripts/bom_values.sh b/scripts/bom_values.sh index cb871d1df2..be01e85fb0 100755 --- a/scripts/bom_values.sh +++ b/scripts/bom_values.sh @@ -13,7 +13,7 @@ BOM="${BOM_FILE:-stack-bom.toml}" section_for() { case "$1" in - rust|flutter|flutter_min|go|go_min) echo toolchain ;; + rust|dnssec_rust|flutter|flutter_min|go|go_min) echo toolchain ;; xcode|xcode_build|xcode_xip_sha1) echo macos ;; *) echo "Unknown BOM key: $1" >&2; return 2 ;; esac @@ -57,8 +57,9 @@ fi FLUTTER_VERSION="$(value flutter)" FLUTTER_MIN="$(value flutter_min)" RUST_VERSION="$(value rust)" +DNSSEC_RUST="$(value dnssec_rust)" GO_VERSION="$(value go)" GO_MIN="$(value go_min)" -printf 'FLUTTER_VERSION=%q\nFLUTTER_MIN=%q\nRUST_VERSION=%q\nGO_VERSION=%q\nGO_MIN=%q\n' \ - "$FLUTTER_VERSION" "$FLUTTER_MIN" "$RUST_VERSION" "$GO_VERSION" "$GO_MIN" +printf 'FLUTTER_VERSION=%q\nFLUTTER_MIN=%q\nRUST_VERSION=%q\nDNSSEC_RUST=%q\nGO_VERSION=%q\nGO_MIN=%q\n' \ + "$FLUTTER_VERSION" "$FLUTTER_MIN" "$RUST_VERSION" "$DNSSEC_RUST" "$GO_VERSION" "$GO_MIN" diff --git a/scripts/download_xcode.sh b/scripts/download_xcode.sh index d679cdebe9..2d544ce912 100755 --- a/scripts/download_xcode.sh +++ b/scripts/download_xcode.sh @@ -179,6 +179,14 @@ if [[ -d "$TARGET_DIR" ]]; then finish_install exit 0 fi + if [[ -z "$CURRENT_BUILD" ]]; then + # A freshly extracted or not-yet-licensed Xcode can fail -version. + # Do not re-download 2 GB because the build number is unreadable. + echo "[WARN] ${TARGET_DIR} exists but its build could not be read; leaving it in place." + [[ $DRY_RUN -eq 1 ]] && { echo "[DRY-RUN] Would finish setup on the existing Xcode."; exit 0; } + finish_install + exit 0 + fi echo "[WARN] ${TARGET_DIR} exists with build '${CURRENT_BUILD}', expected '${BUILD_NUM}'. It will be replaced." fi diff --git a/stack-bom.toml b/stack-bom.toml index cf4c50bbed..84b7b8a24b 100644 --- a/stack-bom.toml +++ b/stack-bom.toml @@ -7,11 +7,12 @@ flutter = "3.47.4" # recommended; macOS builds verified with 3.47.2 and 3. flutter_min = "3.47.2" # minimum for pubspec.template.yaml and the release workflow dart_prefix = "3.13" # Dart bundled with Flutter 3.47.x rust = "1.99.1" # installed through rustup, pinned by the native plugins +dnssec_rust = "1.90.0" # OpenAlias/DNSSEC builds from source in every app go = "1.24.13" # exact Go used by the make-build workflow go_min = "1.24.1" # flutter_mwebd's minimum on the Flutter host [hooks] -hooks_runner = "1.5.0" # pinned by Flutter 3.47.x; CARGO_/RUSTUP_ env vars reach hooks only from 1.6.2 +hooks_runner = "1.5.0" # informational: Flutter 3.47.x pin; CARGO_/RUSTUP_ env vars reach hooks only from 1.6.2 [macos] xcode = "27.1" # recommended for app builds From a75c4e7d4e85c866e917d2b960e751949a84b5d9 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:12:10 +0200 Subject: [PATCH 032/107] build: keep benchmark and Xcode-download tooling out of this PR - Move the bm/ benchmark suite out; it is unrelated to the build wrappers. - Drop the archive.org Xcode downloader and its Makefile target/BOM pins; Xcode installation stays with tool/setup_xcode.dart or Apple. - Remove the benchmark-report Homebrew extras with the suite. --- .gitignore | 1 - Makefile | 10 +- bm/bench.sh | 148 ------------- bm/collect.sh | 130 ------------ bm/compare.py | 161 -------------- bm/render.sh | 63 ------ bm/report.css | 132 ------------ bm/run_all.sh | 44 ---- docs/building/make-flow.md | 6 +- scripts/bom_values.sh | 2 +- scripts/download_xcode.sh | 301 --------------------------- scripts/install_macos_build_tools.sh | 5 - stack-bom.toml | 2 - 13 files changed, 4 insertions(+), 1001 deletions(-) delete mode 100755 bm/bench.sh delete mode 100755 bm/collect.sh delete mode 100755 bm/compare.py delete mode 100755 bm/render.sh delete mode 100644 bm/report.css delete mode 100755 bm/run_all.sh delete mode 100755 scripts/download_xcode.sh diff --git a/.gitignore b/.gitignore index 893ff52489..7d14c31f01 100644 --- a/.gitignore +++ b/.gitignore @@ -125,7 +125,6 @@ lib/wl_gen/generated/ /assets/windows/mwebd.exe /tool/build -bm/results/ /.cargo/config.toml /scripts/linux/pc/ diff --git a/Makefile b/Makefile index 52f1391149..d89ca0e435 100644 --- a/Makefile +++ b/Makefile @@ -94,7 +94,7 @@ ifneq ($(strip $(PUB_CACHE)),) export PUB_CACHE endif -.PHONY: help toolchain toolchain-check bootstrap bootstrap-brew require-version check-reqs check-reqs-macos check-sdk-macos check-linux check-windows bootstrap-macos bootstrap-xcode bootstrap-xcode-download sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios +.PHONY: help toolchain toolchain-check bootstrap bootstrap-brew require-version check-reqs check-reqs-macos check-sdk-macos check-linux check-windows bootstrap-macos bootstrap-xcode sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios help: ## Show available commands @echo "Available targets:" @@ -262,14 +262,6 @@ else @exit 1 endif -bootstrap-xcode-download: ## Opt-in: download Xcode from archive.org (SHA-1 + Apple signature checked); XCODE_VERSION=27.1, ARGS=-y for non-interactive -ifeq ($(PLATFORM),Darwin) - @bash scripts/download_xcode.sh $(if $(XCODE_VERSION),-v $(XCODE_VERSION)) $(ARGS) -else - @echo "[ERROR] bootstrap-xcode-download is macOS-only." - @exit 1 -endif - SCCACHE_CARGO_CONFIG ?= $(HOME)/.cargo/config.toml sccache-setup: ## Opt-in: use sccache for the Rust/C builds run by native-asset hooks (writes ~/.cargo/config.toml if absent) diff --git a/bm/bench.sh b/bm/bench.sh deleted file mode 100755 index d743ad5e2d..0000000000 --- a/bm/bench.sh +++ /dev/null @@ -1,148 +0,0 @@ -#!/usr/bin/env bash -# ============================================================================== -# bench.sh: Simple build benchmark for stack_wallet -# -# Usage: -# bash bm/bench.sh # cold build, dnix source (default on macOS/Linux) -# bash bm/bench.sh --warm # warm rebuild (no clean) -# bash bm/bench.sh PREBUILTS=1 # cold build with verified dnix prebuilts (-d) -# -# sccache is a machine setting, not a flag: run once, `make sccache-setup`, run again. -# The label records whether ~/.cargo/config.toml or CARGO_BUILD_RUSTC_WRAPPER selects sccache. -# -# Output: bm/results/.csv (one file per machine, all runs appended) -# ============================================================================== -set -euo pipefail - -banner() { if command -v toilet >/dev/null 2>&1; then toilet -f term --metal; else cat; fi; } - -HOST="$(hostname -s 2>/dev/null || echo unknown)" -OUTDIR="bm/results" -mkdir -p "$OUTDIR" -OUTFILE="${OUTDIR}/${HOST}.csv" - -WARM=0 -LABEL="" -MAKE_FLAGS="" - -# Parse args -while [ $# -gt 0 ]; do - case "$1" in - --warm) WARM=1; shift ;; - --label) LABEL="$2"; shift 2 ;; - *) MAKE_FLAGS="${MAKE_FLAGS:+${MAKE_FLAGS} }$1"; shift ;; - esac -done - -# Detect platform -case "$(uname -s)" in - Darwin) BUILD_TARGET="build-macos" ;; - Linux) BUILD_TARGET="build-linux" ;; - MINGW*|MSYS*|CYGWIN*) - echo "Git Bash on Windows detected. Benchmarking requires WSL2:" - echo " wsl bash bm/bench.sh" - exit 1 - ;; - *) echo "Unknown platform: $(uname -s)"; exit 1 ;; -esac - -# Build targets require VERSION and BUILD_NUM. Benchmarks measure build time -# only, so use throw-away values unless the caller passes their own in MAKE_FLAGS. -BENCH_ARGS="VERSION=${BENCH_VERSION:-0.0.0} BUILD_NUM=${BENCH_BUILD_NUM:-1}" - -# Git info -COMMIT="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)" -BRANCH="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)" - -# Auto-generate label only if not explicitly set -if [ -z "$LABEL" ]; then - LABEL=$([ $WARM -eq 1 ] && echo "warm" || echo "cold") - if echo "$MAKE_FLAGS" | grep -q "PREBUILTS=1"; then - LABEL="${LABEL}-prebuilt" - else - LABEL="${LABEL}-source" - fi - if grep -qs 'rustc-wrapper *= *"sccache"' "$HOME/.cargo/config.toml" 2>/dev/null \ - || [ "${CARGO_BUILD_RUSTC_WRAPPER:-}" = "sccache" ]; then - LABEL="${LABEL}-sccache" - else - LABEL="${LABEL}-nosccache" - fi -fi - -DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)" -ARCH="$(uname -m)" -OS_NAME="$(uname -s)" -OS_VER="$(uname -r)" -echo "Benchmark: ${LABEL}" | banner -echo "Host: $HOST" -echo "OS: $OS_NAME $OS_VER ($ARCH)" -echo "Branch: $BRANCH" -echo "Commit: $COMMIT" -echo "Target: ${BUILD_TARGET}" -echo "Flags: ${MAKE_FLAGS:-(none)}" -echo "" - -# Disk before -DISK_BEFORE=$(du -sk . 2>/dev/null | cut -f1 || echo 0) - -# Clean unless warm -if [ $WARM -eq 0 ]; then - echo "Cleaning" | banner - make clean 2>&1 | tail -1 -fi - -# Build -echo "Building: make ${BUILD_TARGET} ${BENCH_ARGS} ${MAKE_FLAGS} " | banner -sccache --zero-stats >/dev/null 2>&1 || true -START=$(date +%s) -# A failing build must still be timed and recorded, so errexit is off for the build and its status is taken from make. -set +e -make ${BUILD_TARGET} ${BENCH_ARGS} ${MAKE_FLAGS} 2>&1 | tail -5 -RC=${PIPESTATUS[0]} -set -e -END=$(date +%s) -WALL=$((END - START)) - -# Disk after -SCC_NOTE="" -if command -v sccache >/dev/null 2>&1; then - SCC_REQ=$(sccache --show-stats 2>/dev/null | awk '/^Compile requests executed/ {print $NF}' || echo 0) - SCC_HIT=$(sccache --show-stats 2>/dev/null | awk '/^Cache hits / {print $NF}' || echo 0) - [ -n "${SCC_REQ:-}" ] && [ "${SCC_REQ:-0}" != "0" ] && SCC_NOTE="sccache ${SCC_HIT:-0}/${SCC_REQ} hits" -fi -DISK_AFTER=$(du -sk . 2>/dev/null | cut -f1 || echo 0) -DISK_DELTA=$((DISK_AFTER - DISK_BEFORE)) - -# Write CSV header if new file -if [ ! -f "$OUTFILE" ]; then - echo "label,branch,commit,host,arch,os_name,os_ver,date,warm,flags,wall_sec,success,disk_total_kb,disk_delta_kb,comment" > "$OUTFILE" -fi - -echo "${LABEL},${BRANCH},${COMMIT},${HOST},${ARCH},${OS_NAME},${OS_VER},${DATE},${WARM},${MAKE_FLAGS:--},${WALL},$((RC == 0 ? 1 : 0)),${DISK_AFTER},${DISK_DELTA},${SCC_NOTE}" >> "$OUTFILE" - -echo "" -if [ $RC -eq 0 ]; then - MIN=$((WALL/60)); SEC=$((WALL%60)) - echo "✓ Build succeeded in ${WALL}s \(${MIN}m ${SEC}s\)" -else - echo "✗ Build FAILED after ${WALL}s" -fi -echo "Results appended: $OUTFILE" | banner - -# Show all runs -echo "" -echo "=== All results for $HOST ($ARCH $OS_NAME $OS_VER) ===" -printf "%-12s %-20s %-8s %-10s %4s %10s %8s %s\n" DATE MODE COMMIT FLAGS WARM WALL DISK COMMENT -printf '%s\n' '──────────────────────────────────────────────────────────────────────────────────────' -tail -n +2 "$OUTFILE" | while IFS=, read -r label branch commit host arch os_name os_ver date warm flags wall_sec success disk_total disk_delta comment; do - delta_mb=$((disk_delta / 1024)) - w=$((wall_sec)); m=$((w/60)); s=$((w%60)) - time_fmt="${m}m${s}s" - warm_label=$([ "$warm" = "1" ] && echo "yes" || echo "no") - [ "$success" = "1" ] && ok="✓" || ok="✗" - printf "%-12s %-20s %-8s %-10s %-4s %10s %8s %s\n" "${date:0:10}" "$label" "${commit:0:7}" "${flags:--}" "$warm_label" "$time_fmt" "$ok ${delta_mb}MB" "$comment" -done - -# Report the build's own exit status to the caller. -exit "$RC" diff --git a/bm/collect.sh b/bm/collect.sh deleted file mode 100755 index a36ae9455a..0000000000 --- a/bm/collect.sh +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env bash -# ============================================================================== -# collect.sh: Measure disk usage and artifact sizes independent of benchmarks -# Usage: ./bm/collect.sh [--outdir DIR] [--baseline NAME] -# -# Outputs a CSV with per-directory and per-artifact sizes. -# ============================================================================== -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" - -# The active benchmark path is bench.sh -> compare.py -> render.sh. Keep this -# collector self-contained so it can snapshot the native-assets layout without -# relying on the retired targets.sh configuration. -BUILD_DIRS=( - .dart_tool - build - .pub-cache -) -ARTIFACT_DIRS=( - build/macos/Build/Products/Release - build/linux/x64/release/bundle - build/windows/x64/runner/Release - build/app/outputs/flutter-apk -) - -detect_platform() { - case "$(uname -s)" in - Darwin) echo "macos" ;; - Linux) echo "linux" ;; - MINGW*|MSYS*|CYGWIN*) echo "windows" ;; - *) echo "unknown" ;; - esac -} - -OUTDIR="${BM_OUTDIR:-$REPO_ROOT/bm/results}" -BASELINE="${BM_BASELINE:-current}" -TIMESTAMP="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" -PLATFORM="$(detect_platform)" -HOSTNAME="$(hostname -s 2>/dev/null || echo "unknown")" - -main() { - while [ $# -gt 0 ]; do - case "$1" in - --outdir) OUTDIR="$2"; shift ;; - --baseline) BASELINE="$2"; shift ;; - *) echo "Unknown: $1"; exit 1 ;; - esac - shift - done - - mkdir -p "$OUTDIR" - local csv="$OUTDIR/sizes_${BASELINE}.csv" - - echo "=== Collecting sizes ($BASELINE, $PLATFORM, $TIMESTAMP) ===" >&2 - - # Header - { - printf "baseline,platform,hostname,date,metric,value_kb,note\n" - echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},git_commit,$(git -C "$REPO_ROOT" rev-parse HEAD 2>/dev/null || echo unknown)," - } > "$csv" - - # Disk directories - for d in "${BUILD_DIRS[@]}"; do - local path="$REPO_ROOT/$d" - local label="disk_$(echo "$d" | tr '/.' '_')" - if [ -d "$path" ] || [ -f "$path" ]; then - local sz - sz="$(du -sk "$path" 2>/dev/null | cut -f1 || echo 0)" - echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},${sz}," >> "$csv" - else - echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},0,missing" >> "$csv" - fi - done - - # Artifacts - for a in "${ARTIFACT_DIRS[@]}"; do - local path="$REPO_ROOT/$a" - local label="artifact_$(echo "$a" | tr '/.-' '_')" - if [ -e "$path" ]; then - local sz - sz="$(du -sk "$path" 2>/dev/null | cut -f1 || echo 0)" - echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},${sz}," >> "$csv" - else - echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},0,missing" >> "$csv" - fi - done - - # Total project - local total - total="$(du -sk "$REPO_ROOT" 2>/dev/null | cut -f1 || echo 0)" - echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},total_project,${total}," >> "$csv" - - # Native-assets Rust target directories aggregate. Flutter's hooks keep - # these under .dart_tool instead of the old native build tree. - local rust_total=0 - while IFS= read -r target_dir; do - local sz - sz="$(du -sk "$target_dir" 2>/dev/null | cut -f1 || echo 0)" - rust_total=$((rust_total + sz)) - done < <(find "$REPO_ROOT/.dart_tool/hooks_runner/shared" \ - -type d -path '*/build/*/target' 2>/dev/null) - echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},rust_targets_aggregate,${rust_total}," >> "$csv" - - # Toolchain sizes - for tc_dir in .rustup-home .cargo-home; do - if [ -d "$REPO_ROOT/$tc_dir" ]; then - local tc_label="toolchain_${tc_dir#.}" - local tc_sz - tc_sz="$(du -sk "$REPO_ROOT/$tc_dir" 2>/dev/null | cut -f1 || echo 0)" - echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${tc_label},${tc_sz},installed_toolchains" >> "$csv" - - # Breakdown: list each toolchain - if [ "$tc_dir" = ".rustup-home" ] && [ -d "$REPO_ROOT/$tc_dir/toolchains" ]; then - for tc in "$REPO_ROOT/$tc_dir/toolchains"/*/; do - local tc_name - tc_name="$(basename "$tc")" - local tc_sz - tc_sz="$(du -sk "$tc" 2>/dev/null | cut -f1 || echo 0)" - echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},rustup_toolchain_${tc_name},${tc_sz},installed" >> "$csv" - done - fi - fi - done - - echo "--- Sizes written to $csv ---" >&2 -} - -main "$@" diff --git a/bm/compare.py b/bm/compare.py deleted file mode 100755 index d43462502d..0000000000 --- a/bm/compare.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/env python3 -""" -compare.py: Render benchmark results from bm/results/.csv files. - -Usage: - python3 bm/compare.py bm/results/ # terminal report - python3 bm/compare.py bm/results/ > report.md # markdown for bm/render.sh -""" - -import csv, sys, os -from collections import defaultdict -from pathlib import Path - -PIPE = "│" - -def load_results(results_dir): - rows = [] - for fpath in sorted(Path(results_dir).glob("*.csv")): - if fpath.name.startswith("sizes_"): - continue - try: - with open(fpath) as f: - reader = csv.DictReader(f) - for r in reader: - if r.get("success","0") in ("1", "True"): - rows.append(r) - except Exception as e: - print(f" skip {fpath.name}: {e}", file=sys.stderr) - return rows - - - -def wall_fmt(s): - """Format seconds to human readable.""" - try: - s = int(float(s)) - m, sec = divmod(s, 60) - if m >= 60: - h, m = divmod(m, 60) - return f"{h}h{m:02d}m{sec:02d}s" - return f"{m}m{sec:02d}s" - except: - return str(s) - -def wall_s(s): - """Parse string to int seconds.""" - try: return int(float(s)) - except: return 0 - -def mb(kb_str): - try: return int(float(kb_str)) // 1024 - except: return 0 - -def hr_label(label): - """Human readable label.""" - l = label.lower() - if l == "cold": return "Cold build" - if l == "warm": return "Warm rebuild" - parts = l.split("-") - if parts[0] in ("cold", "warm") and len(parts) == 3: - mode = {"prebuilt": "prebuilt assets", "source": "from source"}.get(parts[1], parts[1]) - cache = "no sccache" if parts[2] == "nosccache" else parts[2] - return f"{'Cold' if parts[0] == 'cold' else 'Warm'} ({mode}, {cache})" - return label - -def render(rows, fmt="terminal"): - if not rows: - print("No successful benchmark results found.", file=sys.stderr) - return - - # Group by host then label - by_host = defaultdict(list) - for r in rows: - by_host[r.get("host","unknown")].append(r) - - hdr = ["Date", "Mode", "Commit", "Arch", "OS", "Warm", "Flags", "Wall Time", "Disk Δ", "Comment"] - - for host, host_rows in sorted(by_host.items()): - if fmt == "markdown": - print(f"\n## {host}\n") - else: - print(f"\n{'═'*80}") - print(f" {host}") - print(f"{'═'*80}") - - # Sort: cold first, then by label - host_rows.sort(key=lambda r: (r.get("warm","0"), r.get("label",""))) - - if fmt == "markdown": - print(f"| {' | '.join(hdr)} |") - # Right-align Wall Time column (index 7) for easier comparison - aligns = [":---" if h not in ("Wall Time", "Disk Δ") else "---:" for h in hdr] - print(f"|{'|'.join(aligns)}|") - else: - # Terminal table with rich/box drawing - widths = [max(len(h), 18) for h in hdr] - # Print header - print(PIPE + PIPE.join(h.center(w) for h,w in zip(hdr,widths)) + PIPE) - print(PIPE + PIPE.join("─"*w for w in widths) + PIPE) - - for r in host_rows: - date = (r.get("date","")[:10]).strip() - label = hr_label(r.get("label","")) - commit = r.get("commit","")[:7] - arch = r.get("arch","") - os_str = f"{r.get('os_name','')} {r.get('os_ver','')}" - warm = "yes" if r.get("warm","0") == "1" else "no" - flags = r.get("flags","-").replace("SCCACHE=1,","").replace("SCCACHE=0,","") or "-" - wall = wall_fmt(r.get("wall_sec","")) - disk = f"{mb(r.get('disk_delta_kb',''))}MB" - comment = r.get("comment","") or "" - - cols = [date, label, commit, arch, os_str, warm, flags, wall, disk, comment] - - if fmt == "markdown": - print(f"| {' | '.join(cols)} |") - else: - print(PIPE + PIPE.join(c.center(w) for c,w in zip(cols,widths)) + PIPE) - -def compare(dir1, dir2=None): - """Compare two result directories.""" - rows1 = load_results(dir1) - rows2 = load_results(dir2) if dir2 else [] - all_rows = rows1 + rows2 - - if not all_rows: - print("No benchmark results found.", file=sys.stderr) - return - - # Mark format based on output - is_pipe = not sys.stdout.isatty() - fmt = "markdown" if is_pipe else "terminal" - - render(all_rows, fmt) - - if dir2 and rows1 and rows2: - print(f"\n{'═'*80}") - print(f" Delta: {os.path.basename(dir1)} → {os.path.basename(dir2)}") - print(f"{'═'*80}") - # Pair measurements by label and host; if a pair was measured several times, the latest row counts. - latest1 = {(r["label"], r.get("host", "unknown")): r for r in rows1} - latest2 = {(r["label"], r.get("host", "unknown")): r for r in rows2} - for key in sorted(latest1.keys() & latest2.keys()): - label, host = key - t1 = wall_s(latest1[key]["wall_sec"]) - t2 = wall_s(latest2[key]["wall_sec"]) - delta = t2 - t1 - pct = (delta/t1)*100 if t1 else 0 - sign = "+" if delta > 0 else "" - print(f" {hr_label(label):25s} {host:12s} {wall_fmt(t1)} → {wall_fmt(t2)} ({sign}{pct:.0f}%)") - - -if __name__ == "__main__": - if len(sys.argv) < 2: - print(f"Usage: {sys.argv[0]} [compare_dir]", file=sys.stderr) - print(f" {sys.argv[0]} bm/results/ # single report", file=sys.stderr) - print(f" {sys.argv[0]} old/ new/ # compare two dirs", file=sys.stderr) - print(f" {sys.argv[0]} bm/results/ > report.md # markdown for PDF", file=sys.stderr) - sys.exit(1) - - compare(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None) diff --git a/bm/render.sh b/bm/render.sh deleted file mode 100755 index 3df37e33b0..0000000000 --- a/bm/render.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env bash -# render.sh: Convert benchmark markdown report to HTML + PDF -# Usage: -# ./bm/compare.py bm/results/ > report.md -# ./bm/render.sh report.md [--open] -set -euo pipefail - -MD_FILE="${1:-}" -if [ -z "$MD_FILE" ] || [ ! -f "$MD_FILE" ]; then - echo "Usage: ./bm/render.sh [--open]" - exit 1 -fi - -OPEN=0 -[ "${2:-}" = "--open" ] && OPEN=1 - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -BASE="${MD_FILE%.md}" -HTML_FILE="${BASE}.html" -PDF_FILE="${BASE}.pdf" -CSS_FILE="$SCRIPT_DIR/report.css" - -# Convert to HTML -echo "=== Markdown → HTML ===" -{ - echo '' -} > /tmp/_bm_css.html - -pandoc "$MD_FILE" \ - --standalone \ - --metadata title="Stack Wallet: Build Benchmark Report" \ - --include-in-header /tmp/_bm_css.html \ - -o "$HTML_FILE" -rm -f /tmp/_bm_css.html -echo " → $HTML_FILE" - -# Convert to PDF -echo "=== HTML → PDF ===" -pdf_ok=0 - -if command -v weasyprint >/dev/null 2>&1; then - weasyprint "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 -elif pip3 install --break-system-packages weasyprint 2>/dev/null; then - weasyprint "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 -elif command -v wkhtmltopdf >/dev/null 2>&1; then - wkhtmltopdf --enable-local-file-access "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 -elif [ "$(uname -s)" = "Darwin" ]; then - cupsfilter "$HTML_FILE" > "$PDF_FILE" 2>/dev/null && pdf_ok=1 || true -fi - -if [ "$pdf_ok" -eq 1 ] && [ -f "$PDF_FILE" ]; then - echo " → $PDF_FILE" -else - echo " ⚠ No PDF engine found. HTML ready: $HTML_FILE" -fi - -if [ "$OPEN" -eq 1 ]; then - open "$PDF_FILE" 2>/dev/null || open "$HTML_FILE" 2>/dev/null || true -fi - -echo "Done." diff --git a/bm/report.css b/bm/report.css deleted file mode 100644 index 5e26a58650..0000000000 --- a/bm/report.css +++ /dev/null @@ -1,132 +0,0 @@ -/* Stack Wallet Build Benchmark Report: Professional stylesheet */ -@page { - size: A4 landscape; - margin: 1.5cm 1.8cm; - @bottom-center { - content: "Page " counter(page) " of " counter(pages); - font-size: 7pt; - color: #888; - } -} - -body { - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 10pt; - line-height: 1.55; - color: #222; - max-width: 100%; -} - -h1 { - font-size: 20pt; - font-weight: 700; - color: #1a1a1a; - border-bottom: 3px solid #2563eb; - padding-bottom: 8px; - margin-top: 0; - margin-bottom: 6px; -} - -h2 { - font-size: 13pt; - font-weight: 600; - color: #1a1a1a; - border-bottom: 1px solid #ccc; - padding-bottom: 4px; - margin-top: 28px; - margin-bottom: 10px; - page-break-after: avoid; -} - -h3 { - font-size: 11pt; - font-weight: 600; - margin-top: 16px; - margin-bottom: 6px; -} - -p { - margin: 4px 0 8px 0; -} - -table { - border-collapse: collapse; - width: 100%; - margin: 10px 0 16px 0; - font-size: 9pt; - page-break-inside: avoid; -} - -thead { - display: table-header-group; -} - -th { - background: #2563eb; - color: white; - font-weight: 600; - padding: 4px 6px; - text-align: left; - font-size: 7pt; - text-transform: uppercase; - letter-spacing: 0.2px; -} - -td { - border: 1px solid #ccc; - padding: 3px 6px; - text-align: left; - font-family: "SF Mono", "Menlo", "Monaco", "Cascadia Code", monospace; - font-size: 7.5pt; -} - -tr:nth-child(even) td { - background: #f8f9fb; -} - -code { - background: #f0f0f0; - padding: 1px 4px; - border-radius: 3px; - font-family: "SF Mono", "Menlo", "Monaco", monospace; - font-size: 8.5pt; -} - -strong { - color: #111; -} - -a { - color: #2563eb; - text-decoration: none; -} - -/* Improvement column - colored */ -td:last-child { - font-weight: 600; -} - -/* Phase breakdown table: alternating header */ -table:last-of-type th { - background: #1e293b; -} - -/* Key findings list spacing */ -h2 + ul li, h2 + p + ul li { - margin-bottom: 4px; -} - -/* First page has no header */ -@page :first { - margin-top: 2.5cm; -} - -/* Cover / header block */ -.report-meta { - background: #f8f9fb; - border-left: 4px solid #2563eb; - padding: 12px 16px; - margin: 16px 0; - font-size: 9pt; - border-radius: 2px; -} diff --git a/bm/run_all.sh b/bm/run_all.sh deleted file mode 100755 index 097e48f23a..0000000000 --- a/bm/run_all.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env bash -# ============================================================================== -# run_all.sh: Benchmark suite for `make build-macos`. -# -# Run order (cold = after `make clean`, warm = rebuild right after): -# A. Cold, verified dnix prebuilts (PREBUILTS=1) -# B. Warm, verified dnix prebuilts -# C. Cold, dnix source (PREBUILTS=0, the macOS/Linux default) -# D. Warm, dnix source -# -# sccache is a machine setting: run the suite once as is, then run -# `make sccache-setup` and run it again; the label records which one it was. -# ============================================================================== -set -euo pipefail - -HOST="$(hostname -s 2>/dev/null || echo unknown)" -echo "Stack Wallet full benchmark suite" -echo "Host: $HOST $(date)" -echo "" - -echo "A: cold, prebuilt" -make clean 2>/dev/null || true -bash bm/bench.sh PREBUILTS=1 -echo "" - -echo "B: warm, prebuilt" -bash bm/bench.sh --warm PREBUILTS=1 -echo "" - -echo "C: cold, from source" -make clean 2>/dev/null || true -bash bm/bench.sh PREBUILTS=0 -echo "" - -echo "D: warm, from source" -bash bm/bench.sh --warm PREBUILTS=0 -echo "" - -echo "Collecting disk and artifact sizes..." -bash bm/collect.sh || true -echo "" -echo "Done. Results: bm/results/$HOST.csv" -echo "View: python3 bm/compare.py bm/results/" -echo "PDF: python3 bm/compare.py bm/results/ > report.md && ./bm/render.sh report.md" diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index c82c245bb4..d84665784a 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -42,14 +42,12 @@ flowchart LR C --> X{"Full Xcode?"} X -- yes --> R["Ready to build"] X -- no --> XS["make bootstrap-xcode"] - X -- no --> DL["make bootstrap-xcode-download
optional; archive.org, hash + signature"] XS --> R - DL --> R ``` `make bootstrap-xcode` does not install Xcode. It selects an existing full -install and finishes Apple's licence/first-launch setup if it is pending; the -archive.org download is opt-in and never runs in CI. +install and finishes Apple's licence/first-launch setup if it is pending; use +`dart tool/setup_xcode.dart` or Apple's download page to install one. ## 2. Build diff --git a/scripts/bom_values.sh b/scripts/bom_values.sh index be01e85fb0..681e6878ab 100755 --- a/scripts/bom_values.sh +++ b/scripts/bom_values.sh @@ -14,7 +14,7 @@ BOM="${BOM_FILE:-stack-bom.toml}" section_for() { case "$1" in rust|dnssec_rust|flutter|flutter_min|go|go_min) echo toolchain ;; - xcode|xcode_build|xcode_xip_sha1) echo macos ;; + xcode) echo macos ;; *) echo "Unknown BOM key: $1" >&2; return 2 ;; esac } diff --git a/scripts/download_xcode.sh b/scripts/download_xcode.sh deleted file mode 100755 index 2d544ce912..0000000000 --- a/scripts/download_xcode.sh +++ /dev/null @@ -1,301 +0,0 @@ -#!/usr/bin/env bash -# ============================================================================== -# scripts/download_xcode.sh -# -# Download and install Xcode from archive.org without an Apple ID, App Store -# login or the `xcodes` CLI. Opt-in only: `make bootstrap-xcode-download`. -# -# Integrity: the .xip is checked against the SHA-1 that archive.org lists for -# the item (detects corruption/tampering of the download), then Apple's -# signature on the .xip is verified with `pkgutil --check-signature` -# (authenticity). Both must pass. -# -# Notes: -# - Redistribution of Xcode by third parties may violate Apple's license -# terms and the item can be taken down at any time. Prefer the Mac App -# Store or developer.apple.com when you can. Not for CI. -# - dnix (the prebuilt/reproducible native libs) pins Xcode 27.0 for building -# Apple libraries from source and for `dart tool/verify_release.dart`. Use -# `-v 27.0` for that; 27.1 is fine for normal app builds with prebuilts. -# -# Usage: -# ./scripts/download_xcode.sh [-v ] [-d ] [-c ] [-y] [-n] -# -# Options: -# -v Xcode version (default: 27.1; supported: 27.1, 27.0, 16.2, 16.0) -# -d Target .app path (default: /Applications/Xcode_.app) -# -c Cache directory for the .xip (default: ~/.cache/xcode) -# -n Dry run: print what would happen, download nothing -# -y Non-interactive: skip the confirmation prompt, accept the -# Xcode license and run first-launch setup -# -h Show this help -# -# Works with the macOS system bash 3.2. -# ============================================================================== - -set -euo pipefail - -SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" -BOM="$SCRIPT_DIR/../stack-bom.toml" -bom_get() { "$SCRIPT_DIR/bom_values.sh" --get "$1" "$BOM"; } - -XCODE_VERSION="27.1" -TARGET_DIR="" -CACHE_DIR="${XCODE_CACHE_DIR:-$HOME/.cache/xcode}" -DRY_RUN=0 -ASSUME_YES=0 - -# Verified releases (archive.org metadata). -# Output: BUILD|SHA1|IA_ITEM|FILE_NAME -release_info() { - case "$1" in - 27.1) - local build sha - build="$(bom_get xcode_build)" - sha="$(bom_get xcode_xip_sha1)" - [ -n "$build" ] && [ -n "$sha" ] || { - echo "[ERROR] Missing Xcode build/hash in $BOM" >&2 - return 1 - } - echo "${build}|${sha}|xcode-27.1|Xcode_27.1.xip" - ;; - 27.0) echo "27A266a|04a7d831229ac95577f09398d87501a1c6fb92ad|xcode-27.0|Xcode_27.xip" ;; - 16.2) echo "16C5032a|aa1a3f12d4217ab04ea4064f40e92399192e15f9|xcode-16.2|Xcode_16.2.xip" ;; - 16.0) echo "16A242d|71b15ff10826474491ebca3d36a6ca5964b9e1c5|xcode-16.0|Xcode_16.xip" ;; - *) return 1 ;; - esac -} -SUPPORTED_VERSIONS="27.1 27.0 16.2 16.0" - -usage() { - sed -n '2,/^# =====*$/p' "$0" | sed -e '1d' -e '$d' -e 's/^# \{0,1\}//' - exit "${1:-0}" -} - -while getopts "v:d:c:nyh" opt; do - case "${opt}" in - v) XCODE_VERSION="$OPTARG" ;; - d) TARGET_DIR="$OPTARG" ;; - c) CACHE_DIR="$OPTARG" ;; - n) DRY_RUN=1 ;; - y) ASSUME_YES=1 ;; - h) usage 0 ;; - *) usage 1 ;; - esac -done - -if [[ "$(uname -s)" != "Darwin" ]]; then - echo "[ERROR] This script must be run on macOS." >&2 - exit 1 -fi - -if [[ $DRY_RUN -eq 0 && ( "${CI:-}" == "true" || "${CI:-}" == "1" ) ]]; then - echo "[ERROR] Refusing to download Xcode from archive.org in CI." >&2 - exit 1 -fi - -if ! RELEASE="$(release_info "$XCODE_VERSION")"; then - echo "[ERROR] Unsupported Xcode version: '$XCODE_VERSION'. Supported: $SUPPORTED_VERSIONS" >&2 - exit 1 -fi -IFS="|" read -r BUILD_NUM EXPECTED_SHA1 IA_ITEM FILE_NAME <<< "$RELEASE" - -if [[ -z "$TARGET_DIR" ]]; then - TARGET_DIR="/Applications/Xcode_${XCODE_VERSION}.app" -fi -if [[ "$TARGET_DIR" != *.app || "$TARGET_DIR" == "/" ]]; then - echo "[ERROR] Target must be an .app path, got: $TARGET_DIR" >&2 - exit 1 -fi - -# A relative cache or target dir must not change meaning after the extraction cd below. -case "$CACHE_DIR" in - /*) ;; - *) CACHE_DIR="$PWD/$CACHE_DIR" ;; -esac -case "$TARGET_DIR" in - /*) ;; - *) TARGET_DIR="$PWD/$TARGET_DIR" ;; -esac - -# sudo is only needed when the target directory is not writable (for example /Applications). -SUDO="" -if [[ ! -w "$(dirname "$TARGET_DIR")" ]]; then - SUDO="sudo" -fi - -# XCODE_XIP_URL can point to another mirror (the SHA-1 and the Apple signature are still checked). -DOWNLOAD_URL="${XCODE_XIP_URL:-https://archive.org/download/${IA_ITEM}/${FILE_NAME}}" -TORRENT_URL="https://archive.org/download/${IA_ITEM}/${IA_ITEM}_archive.torrent" -XIP_PATH="${CACHE_DIR}/${FILE_NAME}" -XIP_PART="${XIP_PATH}.part" - -finish_install() { - if [[ $ASSUME_YES -eq 1 ]]; then - if [[ "$(xcode-select -p 2>/dev/null || true)" != "${TARGET_DIR}/Contents/Developer" ]]; then - sudo xcode-select -s "${TARGET_DIR}/Contents/Developer" - fi - if ! xcodebuild -license check >/dev/null 2>&1; then - sudo xcodebuild -license accept - fi - if ! xcodebuild -checkFirstLaunchStatus >/dev/null 2>&1; then - sudo xcodebuild -runFirstLaunch - fi - echo "[SUCCESS] Xcode ${XCODE_VERSION} (${BUILD_NUM}) installed and selected." - xcodebuild -version - else - echo "[SUCCESS] Installed ${TARGET_DIR}. Finish with:" - echo " sudo xcode-select -s \"${TARGET_DIR}/Contents/Developer\"" - echo " sudo xcodebuild -license # read and accept" - echo " sudo xcodebuild -runFirstLaunch" - fi -} - -echo "=================================================================" -echo " Xcode from archive.org (hash + signature verified)" -echo "=================================================================" -echo " Xcode version : ${XCODE_VERSION} (build ${BUILD_NUM})" -echo " Target : ${TARGET_DIR}" -echo " Source : ${DOWNLOAD_URL}" -echo " Expected SHA-1: ${EXPECTED_SHA1}" -echo " Cache : ${XIP_PATH}" -echo "=================================================================" - -# Already installed? -if [[ -d "$TARGET_DIR" ]]; then - CURRENT_BUILD="$("$TARGET_DIR/Contents/Developer/usr/bin/xcodebuild" -version 2>/dev/null | awk '/Build version/ {print $3}' || true)" - if [[ "$CURRENT_BUILD" == "$BUILD_NUM" ]]; then - echo "[OK] Xcode ${XCODE_VERSION} (${BUILD_NUM}) is already installed at ${TARGET_DIR}." - if [[ $DRY_RUN -eq 1 ]]; then - if [[ $ASSUME_YES -eq 1 ]]; then - echo "[DRY-RUN] Already installed; would select it, accept the license and run first-launch setup." - else - echo "[DRY-RUN] Already installed; nothing to download." - fi - exit 0 - fi - # With -y, finish selection/license/first-launch now instead of exiting - # before the setup the caller explicitly asked for. - finish_install - exit 0 - fi - if [[ -z "$CURRENT_BUILD" ]]; then - # A freshly extracted or not-yet-licensed Xcode can fail -version. - # Do not re-download 2 GB because the build number is unreadable. - echo "[WARN] ${TARGET_DIR} exists but its build could not be read; leaving it in place." - [[ $DRY_RUN -eq 1 ]] && { echo "[DRY-RUN] Would finish setup on the existing Xcode."; exit 0; } - finish_install - exit 0 - fi - echo "[WARN] ${TARGET_DIR} exists with build '${CURRENT_BUILD}', expected '${BUILD_NUM}'. It will be replaced." -fi - -if [[ $DRY_RUN -eq 1 ]]; then - echo "[DRY-RUN] Would download : ${DOWNLOAD_URL}" - echo "[DRY-RUN] Alternative : ${TORRENT_URL}" - echo "[DRY-RUN] Would verify : SHA-1 ${EXPECTED_SHA1}, then pkgutil --check-signature" - exit 0 -fi - -mkdir -p "$(dirname "$TARGET_DIR")" 2>/dev/null || true - -if [[ $ASSUME_YES -eq 0 ]]; then - echo "This downloads ~2 GB, needs ~20 GB free while extracting, and uses sudo only if ${TARGET_DIR} is not writable." - echo "Redistribution of Xcode by third parties may conflict with Apple's license terms." - if ! read -r -p "Continue? (yes/no): " ANSWER; then - ANSWER="" - fi - [[ "$ANSWER" == "yes" ]] || { echo "Aborted."; exit 1; } -fi - -mkdir -p "$CACHE_DIR" -FREE_KB="$(df -k "$CACHE_DIR" | awk 'NR==2 {print $4}')" -if [[ "$FREE_KB" -lt $((20 * 1024 * 1024)) ]]; then - echo "[ERROR] At least 20 GB free are required in ${CACHE_DIR}." >&2 - exit 1 -fi - -# 1. Resumable download. A verified archive is reused; a partial .part file is -# resumed with curl -C - instead of being treated as a complete archive. -if [[ -f "$XIP_PATH" ]]; then - CACHED_SHA1="$(shasum -a 1 "$XIP_PATH" | awk '{print $1}')" - if [[ "$CACHED_SHA1" == "$EXPECTED_SHA1" ]]; then - echo "Using cached archive: $XIP_PATH" - else - echo "[WARN] Cached archive does not match the expected SHA-1; downloading again." >&2 - rm -f "$XIP_PATH" - fi -fi -if [[ ! -f "$XIP_PATH" ]]; then - if [[ -f "$XIP_PART" ]]; then - echo "Resuming partial download: $XIP_PART" - else - echo "Downloading ${FILE_NAME} (resumable; torrent alternative: ${TORRENT_URL})..." - fi - if ! curl -fL -C - --retry 8 --retry-delay 5 --retry-all-errors --progress-bar -o "$XIP_PART" "$DOWNLOAD_URL"; then - echo "[WARN] Could not resume; restarting the download from scratch." >&2 - rm -f "$XIP_PART" - curl -fL --retry 8 --retry-delay 5 --retry-all-errors --progress-bar -o "$XIP_PART" "$DOWNLOAD_URL" - fi - PART_SHA1="$(shasum -a 1 "$XIP_PART" | awk '{print $1}')" - if [[ "$PART_SHA1" != "$EXPECTED_SHA1" ]]; then - echo "[ERROR] SHA-1 mismatch, the download is corrupt or altered." >&2 - echo " expected: $EXPECTED_SHA1" >&2 - echo " got : $PART_SHA1" >&2 - rm -f "$XIP_PART" - exit 1 - fi - mv "$XIP_PART" "$XIP_PATH" -fi - -# 2. Integrity: SHA-1 from archive.org metadata -echo "Verifying SHA-1..." -ACTUAL_SHA1="$(shasum -a 1 "$XIP_PATH" | awk '{print $1}')" -if [[ "$ACTUAL_SHA1" != "$EXPECTED_SHA1" ]]; then - echo "[ERROR] SHA-1 mismatch, the download is corrupt or altered." >&2 - echo " expected: $EXPECTED_SHA1" >&2 - echo " got : $ACTUAL_SHA1" >&2 - rm -f "$XIP_PATH" - exit 1 -fi -echo "[OK] SHA-1 matches." - -# 3. Authenticity: Apple's signature on the .xip -echo "Verifying Apple signature..." -if ! pkgutil --check-signature "$XIP_PATH"; then - echo "[ERROR] Apple signature check failed. Not installing." >&2 - exit 1 -fi -echo "[OK] Apple signature valid." - -# Remove the quarantine flag from the archive, otherwise it spreads to every file in Xcode.app and -# Gatekeeper scans them all on first use (15 to 25 minutes). -xattr -d com.apple.quarantine "$XIP_PATH" 2>/dev/null || true - -# 4. Extract (signature is checked again by xip itself) -EXTRACT_DIR="${CACHE_DIR}/extract_${BUILD_NUM}" -rm -rf "$EXTRACT_DIR" -mkdir -p "$EXTRACT_DIR" -echo "Extracting (5-10 minutes)..." -( - cd "$EXTRACT_DIR" - if command -v unxip >/dev/null 2>&1; then - unxip "$XIP_PATH" - else - /usr/bin/xip --expand "$XIP_PATH" - fi -) -if [[ ! -d "${EXTRACT_DIR}/Xcode.app" ]]; then - echo "[ERROR] Extraction failed: Xcode.app not found." >&2 - exit 1 -fi - -# 5. Install -echo "Installing to ${TARGET_DIR}${SUDO:+ (sudo)}..." -$SUDO rm -rf "$TARGET_DIR" -$SUDO mv "${EXTRACT_DIR}/Xcode.app" "$TARGET_DIR" -$SUDO xattr -dr com.apple.quarantine "$TARGET_DIR" 2>/dev/null || true -rm -rf "$EXTRACT_DIR" - -# 6. Select and first-launch only with -y; otherwise print the commands. -finish_install diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh index b97366c61f..549413c31a 100755 --- a/scripts/install_macos_build_tools.sh +++ b/scripts/install_macos_build_tools.sh @@ -66,11 +66,6 @@ export HOMEBREW_NO_INSTALL_UPGRADE=1 brew install direnv rustup cmake meson ninja pkg-config cocoapods go protobuf autoconf automake libtool sccache add_rustup_to_path -# Only used for the benchmark reports in bm/. Opt in with BM_REPORT_TOOLS=1. -if [[ "${BM_REPORT_TOOLS:-0}" = "1" ]]; then - brew install pandoc weasyprint toilet figlet || echo "[WARN] optional report tools were not fully installed; only bm/ report rendering needs them." -fi - # The Homebrew cask always installs the latest Flutter, but CI builds and tests # one pinned release. Install that tag from source instead. FLUTTER_RECOMMENDED="$(bom_get flutter)" diff --git a/stack-bom.toml b/stack-bom.toml index 84b7b8a24b..80c30a1138 100644 --- a/stack-bom.toml +++ b/stack-bom.toml @@ -16,9 +16,7 @@ hooks_runner = "1.5.0" # informational: Flutter 3.47.x pin; CARGO_/RUSTUP_ env [macos] xcode = "27.1" # recommended for app builds -xcode_build = "27A9275" xcode_dnix = "27.0" # dnix needs this one to rebuild Apple libraries byte for byte -xcode_xip_sha1 = "d8b1d16397e6f2faab34bd48b19692a3f7797b9d" # archive.org item xcode-27.1, see scripts/download_xcode.sh [plugins] # Generated by `dart tool/verify_bom.dart --update` from pubspec.lock. Do not edit by hand. From b80a2ceb1b049cea8e19f36034f52dab34a484fb Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:21:12 +0200 Subject: [PATCH 033/107] build: simplify the BOM helper and build docs - Read FLUTTER_ROOT with pwd -P instead of readlink -f, and drop unused gnused from the flake. - Make bom_values.sh --get-only; every caller already uses --get. - State that make builds are unsigned and use empty API-key stubs. - Trim the diagram history and drop the uncommitted-PNG instructions. - Drop the stray AppleDouble ignore and extra blank line. --- .gitignore | 2 -- docs/building/make-flow.md | 27 ++++++----------------- flake.nix | 4 ++-- scripts/bom_values.sh | 44 +++++++++++--------------------------- 4 files changed, 21 insertions(+), 56 deletions(-) diff --git a/.gitignore b/.gitignore index 7d14c31f01..46f440b58c 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,6 @@ *.pyc *.swp .DS_Store -._* .atom/ .buildlog/ .history @@ -42,7 +41,6 @@ android/build/ # Web related lib/generated_plugin_registrant.dart - # testing data test/services/coins/bitcoin/bitcoin_wallet_test_parameters.dart test/services/coins/firo/firo_wallet_test_parameters.dart diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index d84665784a..66ddfd4bd5 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -1,8 +1,7 @@ # Make build flow This page is the maintained source for the two build-flow diagrams. GitHub -renders the Mermaid blocks directly; PNGs can be generated locally from the -same blocks (they are not committed). Keep the source in sync with the +renders the Mermaid blocks directly; keep the source in sync with the `Makefile`. ## 1. Get the tools (once per Mac) @@ -13,14 +12,11 @@ tracked `.envrc` is `use flake`, so it activates the same shell as ### History -`.envrc` was added on 2026-03-17 as a 98-line script that installed Rust -toolchains, set `SDKROOT`/`CC`, created a Python venv and wrote `lipo`/`xcrun` -wrappers. On 2026-03-19 the commit `macos build: split bootstrap from -host-agnostic build path` (428fd61f9) reduced it to `use flake`; the flake and -Makefile took over those steps. That is why direnv is not a fourth toolchain -today. The Homebrew helper still installs the `direnv` binary, but `.envrc` -now skips the flake when Nix is absent, so a Homebrew-only shell is not -blocked. +`.envrc` started as a standalone environment script; it was reduced to +`use flake` when the flake and Makefile took over the host setup. That is why +direnv is the Nix activator, not a fourth toolchain. The Homebrew helper still +installs the `direnv` binary, but `.envrc` skips the flake when Nix is absent, +so a Homebrew-only shell is not blocked. ```mermaid flowchart LR @@ -108,14 +104,3 @@ flowchart TD | Windows | `1` (fixed) | verified prebuilts (`-d`) | | Android on macOS | `1` (fixed) | verified prebuilts (`-d`) | | Android on Linux | follows `PREBUILTS` | source by default | - -## Regenerating the PNGs - -Extract the two Mermaid blocks and render them with Mermaid CLI: - -```sh -npx --yes @mermaid-js/mermaid-cli -i make-flow-tools.mmd \ - -o make-flow-tools.png -t dark -b "#0d1117" --size 1800 -s 2 -npx --yes @mermaid-js/mermaid-cli -i make-flow-build.mmd \ - -o make-flow-build.png -t dark -b "#0d1117" --size 1800 -s 2 -``` diff --git a/flake.nix b/flake.nix index c6b2ce8b67..bc6d933bfb 100644 --- a/flake.nix +++ b/flake.nix @@ -34,7 +34,6 @@ ninja pkg-config gnumake - gnused rsync protobuf (python3.withPackages (ps: with ps; [ @@ -88,7 +87,8 @@ # The standalone Dart in the Nix Flutter wrapper cannot find the Flutter SDK on its own, # so `dart run`/`dart pub` in a Flutter project fail ("Flutter users should use flutter pub"). - export FLUTTER_ROOT="$(dirname "$(dirname "$(readlink -f "$(command -v flutter)")")")" + FLUTTER_BIN_DIR="$(cd "$(dirname "$(command -v flutter)")" && pwd -P)" + export FLUTTER_ROOT="$(dirname "$FLUTTER_BIN_DIR")" # ========================================== # RUST TOOLCHAIN AUTOMATION diff --git a/scripts/bom_values.sh b/scripts/bom_values.sh index 681e6878ab..472499f640 100755 --- a/scripts/bom_values.sh +++ b/scripts/bom_values.sh @@ -1,12 +1,8 @@ #!/usr/bin/env bash -# Read toolchain pins from stack-bom.toml. +# Read one toolchain pin from stack-bom.toml. # -# scripts/bom_values.sh # print quoted shell assignments -# scripts/bom_values.sh --get rust # print one value -# scripts/bom_values.sh --get rust FILE # read another BOM -# -# The default output is safe to eval; the individual lookups are preferred by -# the Makefile and CI so a value can never become shell syntax. +# scripts/bom_values.sh --get rust +# scripts/bom_values.sh --get rust FILE set -euo pipefail BOM="${BOM_FILE:-stack-bom.toml}" @@ -34,32 +30,18 @@ value() { printf '%s\n' "$result" } -if [ "${1:-}" = "--get" ]; then - [ "$#" -ge 2 ] || { - echo "Usage: $0 --get [bom]" >&2 - exit 2 - } - [ "$#" -ge 3 ] && BOM="$3" - [ -r "$BOM" ] || { - echo "Cannot read $BOM" >&2 - exit 1 - } - value "$2" - exit -fi - -[ "$#" -ge 1 ] && BOM="$1" +[ "${1:-}" = "--get" ] || { + echo "Usage: $0 --get [bom]" >&2 + exit 2 +} +[ "$#" -ge 2 ] || { + echo "Usage: $0 --get [bom]" >&2 + exit 2 +} +[ "$#" -ge 3 ] && BOM="$3" [ -r "$BOM" ] || { echo "Cannot read $BOM" >&2 exit 1 } -FLUTTER_VERSION="$(value flutter)" -FLUTTER_MIN="$(value flutter_min)" -RUST_VERSION="$(value rust)" -DNSSEC_RUST="$(value dnssec_rust)" -GO_VERSION="$(value go)" -GO_MIN="$(value go_min)" - -printf 'FLUTTER_VERSION=%q\nFLUTTER_MIN=%q\nRUST_VERSION=%q\nDNSSEC_RUST=%q\nGO_VERSION=%q\nGO_MIN=%q\n' \ - "$FLUTTER_VERSION" "$FLUTTER_MIN" "$RUST_VERSION" "$DNSSEC_RUST" "$GO_VERSION" "$GO_MIN" +value "$2" From bbca1e09dc3c665c028a1151d526804dfd8b01b0 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:30:08 +0200 Subject: [PATCH 034/107] ci: build from staging and dry-run the Makefile - Delete make-build.yaml: staging build.yaml already builds every platform, so a second full build matrix is a duplicate. - Add a cheap make-check job to test.yaml that dry-runs all five Make targets. - Name the release BOM output flutter_min so the version choice is explicit. - Use dtolnay/rust-toolchain@master with the BOM toolchain input, as the action documents for an explicit toolchain. - Note the Dockerfile's mirrored Go/Flutter pins in stack-bom.toml. --- .github/workflows/build.yaml | 42 +++---- .github/workflows/make-build.yaml | 175 ------------------------------ .github/workflows/test.yaml | 15 +++ stack-bom.toml | 4 +- 4 files changed, 38 insertions(+), 198 deletions(-) delete mode 100644 .github/workflows/make-build.yaml diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 21d233ef51..59de949cd7 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -25,7 +25,7 @@ jobs: bom: runs-on: ubuntu-latest outputs: - flutter: ${{ steps.read.outputs.flutter }} + flutter_min: ${{ steps.read.outputs.flutter_min }} go: ${{ steps.read.outputs.go }} dnssec_rust: ${{ steps.read.outputs.dnssec_rust }} steps: @@ -35,10 +35,10 @@ jobs: - name: Read stack-bom.toml id: read run: | - flutter="$(bash scripts/bom_values.sh --get flutter_min)" + flutter_min="$(bash scripts/bom_values.sh --get flutter_min)" go="$(bash scripts/bom_values.sh --get go)" dnssec_rust="$(bash scripts/bom_values.sh --get dnssec_rust)" - echo "flutter=$flutter" >> "$GITHUB_OUTPUT" + echo "flutter_min=$flutter_min" >> "$GITHUB_OUTPUT" echo "go=$go" >> "$GITHUB_OUTPUT" echo "dnssec_rust=$dnssec_rust" >> "$GITHUB_OUTPUT" @@ -257,13 +257,13 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: ${{ needs.bom.outputs.flutter }} + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 @@ -333,13 +333,13 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: ${{ needs.bom.outputs.flutter }} + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 @@ -404,13 +404,13 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: ${{ needs.bom.outputs.flutter }} + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 @@ -838,13 +838,13 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: ${{ needs.bom.outputs.flutter }} + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 @@ -912,13 +912,13 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: ${{ needs.bom.outputs.flutter }} + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 @@ -983,13 +983,13 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: ${{ needs.bom.outputs.flutter }} + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 @@ -1277,13 +1277,13 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: ${{ needs.bom.outputs.flutter }} + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 @@ -1351,13 +1351,13 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: ${{ needs.bom.outputs.flutter }} + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 @@ -1422,13 +1422,13 @@ jobs: echo "build_number=${BUILD_NUMBER}" >> $GITHUB_OUTPUT # OpenAlias/DNSSEC builds from source in every app, including -d. - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: ${{ needs.bom.outputs.flutter }} + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 diff --git a/.github/workflows/make-build.yaml b/.github/workflows/make-build.yaml deleted file mode 100644 index 0232267861..0000000000 --- a/.github/workflows/make-build.yaml +++ /dev/null @@ -1,175 +0,0 @@ -name: Make build - -# Builds with the Makefile targets on the hosted runners. Manual only. -# -# The Makefile builds dnix source by default on macOS and Linux. These jobs use -# the same verified prebuilts as the release workflow (build.yaml); source and -# reproducibility builds belong to the dnix packages' own CI. -# -# Toolchain versions come from stack-bom.toml via scripts/bom_values.sh. The -# release workflow (build.yaml) reads the BOM's DNSSEC Rust pin. -on: - workflow_dispatch: - -# Least privilege: the jobs only check out code and build. No artifacts are -# uploaded, no containers or registry images are pulled. -permissions: - contents: read - -jobs: - windows: - runs-on: windows-2022 - defaults: - run: - shell: bash - steps: - - uses: actions/checkout@v6 - with: - fetch-depth: 0 - - name: Read stack-bom.toml - id: bom - run: | - flutter="$(bash scripts/bom_values.sh --get flutter)" - rust="$(bash scripts/bom_values.sh --get rust)" - go="$(bash scripts/bom_values.sh --get go)" - echo "flutter=$flutter" >> "$GITHUB_OUTPUT" - echo "rust=$rust" >> "$GITHUB_OUTPUT" - echo "go=$go" >> "$GITHUB_OUTPUT" - - uses: subosito/flutter-action@v2 - with: - flutter-version: ${{ steps.bom.outputs.flutter }} - channel: 'stable' - - uses: actions/setup-go@v6 - with: - go-version: ${{ steps.bom.outputs.go }} - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: ${{ steps.bom.outputs.rust }} - - name: Install make - run: command -v make >/dev/null 2>&1 || choco install make -y --no-progress - - name: Check the toolchain bill of materials - run: make verify-bom - - name: Build - run: make build-windows VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} - - - name: Verify the generated app BOM - run: make verify-bom - - macos: - runs-on: macos-latest - steps: - - uses: actions/checkout@v6 - with: - fetch-depth: 0 - - name: Read stack-bom.toml - id: bom - run: | - flutter="$(bash scripts/bom_values.sh --get flutter)" - rust="$(bash scripts/bom_values.sh --get rust)" - go="$(bash scripts/bom_values.sh --get go)" - echo "flutter=$flutter" >> "$GITHUB_OUTPUT" - echo "rust=$rust" >> "$GITHUB_OUTPUT" - echo "go=$go" >> "$GITHUB_OUTPUT" - - uses: subosito/flutter-action@v2 - with: - flutter-version: ${{ steps.bom.outputs.flutter }} - channel: 'stable' - - uses: actions/setup-go@v6 - with: - go-version: ${{ steps.bom.outputs.go }} - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: ${{ steps.bom.outputs.rust }} - - name: Tools - run: brew install meson ninja autoconf automake libtool protobuf pkg-config - - name: Check the toolchain bill of materials - run: make verify-bom - - name: Build - run: make build-macos VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 - - - name: Verify the generated app BOM - run: make verify-bom - - linux: - runs-on: ubuntu-24.04 - steps: - - uses: actions/checkout@v6 - with: - fetch-depth: 0 - - name: Read stack-bom.toml - id: bom - run: | - flutter="$(bash scripts/bom_values.sh --get flutter)" - rust="$(bash scripts/bom_values.sh --get rust)" - go="$(bash scripts/bom_values.sh --get go)" - echo "flutter=$flutter" >> "$GITHUB_OUTPUT" - echo "rust=$rust" >> "$GITHUB_OUTPUT" - echo "go=$go" >> "$GITHUB_OUTPUT" - - uses: subosito/flutter-action@v2 - with: - flutter-version: ${{ steps.bom.outputs.flutter }} - channel: 'stable' - - uses: actions/setup-go@v6 - with: - go-version: ${{ steps.bom.outputs.go }} - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: ${{ steps.bom.outputs.rust }} - - name: Free disk space - run: | - sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL - df -h / - - name: Install build dependencies - run: | - sudo apt-get update - sudo apt-get install -y --no-install-recommends \ - automake build-essential clang cmake libclang-dev libtool llvm meson ninja-build patchelf pkg-config protobuf-compiler rsync \ - libgcrypt20-dev libgirepository1.0-dev libgit2-dev libglib2.0-dev libgtk-3-dev libjsoncpp-dev liblzma-dev \ - libncurses5-dev libncursesw5-dev libsecret-1-dev libssl-dev libtss2-dev \ - ocl-icd-opencl-dev opencl-headers valac zlib1g-dev - - name: Check the toolchain bill of materials - run: make verify-bom - - name: Build - run: make build-linux VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 SYSTEM_DEPS=1 - - - name: Verify the generated app BOM - run: make verify-bom - - ios: - # The fork has a single hosted macOS concurrency slot. Running macOS and - # iOS together leaves one job queued until GitHub cancels it; serialise them. - needs: macos - if: ${{ !cancelled() }} - runs-on: macos-latest - steps: - - uses: actions/checkout@v6 - with: - fetch-depth: 0 - - name: Read stack-bom.toml - id: bom - run: | - flutter="$(bash scripts/bom_values.sh --get flutter)" - rust="$(bash scripts/bom_values.sh --get rust)" - go="$(bash scripts/bom_values.sh --get go)" - echo "flutter=$flutter" >> "$GITHUB_OUTPUT" - echo "rust=$rust" >> "$GITHUB_OUTPUT" - echo "go=$go" >> "$GITHUB_OUTPUT" - - uses: subosito/flutter-action@v2 - with: - flutter-version: ${{ steps.bom.outputs.flutter }} - channel: 'stable' - - uses: actions/setup-go@v6 - with: - go-version: ${{ steps.bom.outputs.go }} - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: ${{ steps.bom.outputs.rust }} - - name: Tools - run: brew install meson ninja autoconf automake libtool protobuf pkg-config - - name: Check the toolchain bill of materials - run: make verify-bom - - name: Build - run: make build-ios VERSION=0.0.0 BUILD_NUM=${{ github.run_number }} PREBUILTS=1 - - - name: Verify the generated app BOM - run: make verify-bom diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index e7ca3eb969..06f5edb9be 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -133,3 +133,18 @@ jobs: with: token: ${{secrets.CODECOV_TOKEN}} file: coverage/lcov.info + + make-check: + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - uses: actions/checkout@v6 + - name: Check the Makefile dry-runs + run: | + make help + make -n build-macos PLATFORM=Darwin VERSION=0.0.0 BUILD_NUM=1 + make -n build-linux PLATFORM=Linux VERSION=0.0.0 BUILD_NUM=1 + make -n build-windows PLATFORM=MINGW64_NT-10.0 VERSION=0.0.0 BUILD_NUM=1 + make -n build-android PLATFORM=Darwin VERSION=0.0.0 BUILD_NUM=1 + make -n build-ios PLATFORM=Darwin VERSION=0.0.0 BUILD_NUM=1 diff --git a/stack-bom.toml b/stack-bom.toml index 80c30a1138..aefcd04920 100644 --- a/stack-bom.toml +++ b/stack-bom.toml @@ -4,11 +4,11 @@ schema_version = 1 [toolchain] flutter = "3.47.4" # recommended; macOS builds verified with 3.47.2 and 3.47.4 -flutter_min = "3.47.2" # minimum for pubspec.template.yaml and the release workflow +flutter_min = "3.47.2" # minimum for pubspec.template.yaml and the release workflow; Dockerfile mirrors it dart_prefix = "3.13" # Dart bundled with Flutter 3.47.x rust = "1.99.1" # installed through rustup, pinned by the native plugins dnssec_rust = "1.90.0" # OpenAlias/DNSSEC builds from source in every app -go = "1.24.13" # exact Go used by the make-build workflow +go = "1.24.13" # exact Go used by CI; Dockerfile mirrors it go_min = "1.24.1" # flutter_mwebd's minimum on the Flutter host [hooks] From 820a2593cf2eff74f04c1c42a1cd21d7ae26ed69 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:30:11 +0200 Subject: [PATCH 035/107] build: fix Nix-shell portability and preflight gaps - Replace macOS-only `sed -i ''` with portable `sed -i.bak` in the app configuration scripts. The Nix shell puts GNU sed on PATH, where the old form failed for iOS, Android and Campfire configuration. - Honour DEVELOPER_DIR in check-sdk-macos, check the iOS SDK for build-ios, and give build-ios the same prerequisite checks as the macOS target. - Default Android to prebuilts on hosts that cannot build dnix source (anything other than x86_64 Linux) and validate ANDROID_PREBUILTS. - Keep child scripts on the Flutter/Dart binaries the Makefile checked, quote tool paths, and stop claiming `make clean` is pristine. - Refuse duplicate [plugins] tables in verify_bom: --update appended a second block and then failed verification. - Only run the privileged Xcode license/first-launch checks after changing the selection, so bootstrap does not ask for sudo on every run. - Docs: add Meson/Ninja to the manual macOS prerequisites, document SYSTEM_DEPS, correct the Android prebuilt defaults and drop the misleading -s flag. --- Makefile | 80 +++++++++++-------- README.md | 8 +- docs/building/macos.md | 2 +- docs/building/make-flow.md | 14 ++-- scripts/app_config/configure_campfire.sh | 15 ++-- .../platforms/android/platform_config.sh | 32 ++++---- .../platforms/ios/platform_config.sh | 9 ++- scripts/install_xcode.sh | 24 +++--- tool/verify_bom.dart | 20 ++++- 9 files changed, 121 insertions(+), 83 deletions(-) diff --git a/Makefile b/Makefile index d89ca0e435..66739d12bb 100644 --- a/Makefile +++ b/Makefile @@ -14,6 +14,14 @@ FLUTTER_BIN := $(if $(and $(FLUTTER),$(wildcard $(FLUTTER))),$(FLUTTER),$(shell DART_BIN := $(if $(and $(DART),$(wildcard $(DART))),$(DART),$(shell command -v dart 2>/dev/null)) FLUTTER := $(FLUTTER_BIN) DART := $(DART_BIN) +# Child scripts call bare `flutter`/`dart`; keep them on the binaries checked +# above instead of whatever PATH would otherwise resolve. +ifneq ($(FLUTTER),) +export PATH := $(dir $(FLUTTER)):$(PATH) +endif +ifneq ($(DART),) +export PATH := $(dir $(DART)):$(PATH) +endif APP_PROJECT_ROOT_DIR := $(CURDIR) ifeq ($(wildcard Makefile),) $(error Run make from the repository root) @@ -210,10 +218,10 @@ endif check-sdk-macos: ## Verify XCode on macOS ifeq ($(PLATFORM),Darwin) @echo "Checking macOS SDK requirements..." - @selected="$$(xcode-select -p 2>/dev/null || true)"; \ - case "$$selected" in \ + @dev="$${DEVELOPER_DIR:-$$(xcode-select -p 2>/dev/null || true)}"; \ + case "$$dev" in \ *.app/Contents/Developer) ;; \ - *) echo >&2 "[ERROR] Full Xcode is required (xcode-select -p = $$selected). Install Xcode or run 'make bootstrap-xcode'."; exit 1 ;; \ + *) echo >&2 "[ERROR] Full Xcode is required (DEVELOPER_DIR or xcode-select -p = $$dev). Install Xcode or run 'make bootstrap-xcode'."; exit 1 ;; \ esac @xcrun --sdk macosx --show-sdk-path >/dev/null 2>&1 || ( \ echo "[ERROR] macOS SDK not available. Install Xcode or run: sudo xcode-select --switch /Applications/Xcode.app"; \ @@ -254,7 +262,7 @@ else @exit 1 endif -bootstrap-xcode: ## Install/select full Xcode.app (needed regardless of Homebrew vs Nix for the rest of the toolchain) +bootstrap-xcode: ## Check/select an installed full Xcode.app (needed regardless of Homebrew vs Nix for the rest of the toolchain) ifeq ($(PLATFORM),Darwin) @bash scripts/install_xcode.sh else @@ -280,7 +288,7 @@ sccache-setup: ## Opt-in: use sccache for the Rust/C builds run by native-asset verify-bom: ## Check the local toolchain and the pinned plugins against stack-bom.toml @[ -n "$(DART)" ] || { echo >&2 "[ERROR] Dart not installed (needed for verify-bom). Install Flutter or pass DART=/path/to/dart."; exit 1; } - @FLUTTER="$(FLUTTER)" $(DART) tool/verify_bom.dart + @FLUTTER="$(FLUTTER)" "$(DART)" tool/verify_bom.dart cache-stats: ## Show sccache statistics (hit rate) after a build @command -v sccache >/dev/null 2>&1 || { echo >&2 "[ERROR] sccache not installed."; exit 1; } @@ -293,9 +301,9 @@ clean: ## Remove artifacts and fix permissions @if [ -n "$(FLUTTER)" ] && [ -f pubspec.yaml ]; then "$(FLUTTER)" clean; fi @rm -rf macos/Pods macos/Podfile.lock ios/Pods ios/Podfile.lock build/ @echo "Cleaning local pub cache residues..." - @chmod -R u+w $(LINUX_PUB_CACHE)/git/ 2>/dev/null || true - @find $(LINUX_PUB_CACHE)/git/ -type d \( -name "build" -o -name "target" \) -path "*flutter_lib*" -exec rm -rf {} + 2>/dev/null || true - @echo "[OK] Project is now in a pristine state." + @chmod -R u+w "$(LINUX_PUB_CACHE)/git/" 2>/dev/null || true + @find "$(LINUX_PUB_CACHE)/git/" -type d \( -name "build" -o -name "target" \) -path "*flutter_lib*" -exec rm -rf {} + 2>/dev/null || true + @echo "[OK] Removed the Flutter build output and local caches." # --- PLATFORM BUILDS --- @@ -320,8 +328,19 @@ ifneq ($(filter MINGW% MSYS%,$(PLATFORM)),) $(error build-windows uses verified dnix prebuilts; run build_app.sh for source mode) endif endif -# Android source builds through dnix need an x86_64 Linux host. -ANDROID_PREBUILTS ?= $(if $(filter Darwin,$(PLATFORM)),1,$(PREBUILTS)) +# Android source builds through dnix need an x86_64 Linux host. Every other +# host defaults to the verified prebuilts; x86_64 Linux follows PREBUILTS. +ANDROID_ARCH := $(shell uname -m 2>/dev/null) +ANDROID_SOURCE_OK := $(and $(filter Linux,$(PLATFORM)),$(filter x86_64,$(ANDROID_ARCH))) +ANDROID_PREBUILTS ?= $(if $(ANDROID_SOURCE_OK),$(PREBUILTS),1) +ifneq ($(filter $(ANDROID_PREBUILTS),0 1),$(ANDROID_PREBUILTS)) + $(error ANDROID_PREBUILTS must be 0 or 1) +endif +ifeq ($(ANDROID_PREBUILTS),0) + ifeq ($(strip $(ANDROID_SOURCE_OK)),) + $(error ANDROID_PREBUILTS=0 needs an x86_64 Linux host; use the default prebuilt mode) + endif +endif # Linux only: SYSTEM_DEPS=1 uses the system libsecret/jsoncpp packages instead of building them (like the CI image). SYSTEM_DEPS ?= 0 ifneq ($(filter $(SYSTEM_DEPS),0 1),$(SYSTEM_DEPS)) @@ -343,18 +362,18 @@ clean-native: ## Remove only the native-asset build outputs (forces the Rust/Go/ build-macos: require-version toolchain-check check-reqs-macos check-sdk-macos ## Build macOS release (source by default; PREBUILTS=1 uses verified prebuilts) @echo "--- Configuring project (scripts/build_app.sh)..." - @cd scripts && echo yes | env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a $(APP_NAME) -s $(if $(filter 1,$(PREBUILTS)),-d) + @cd scripts && echo yes | env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) @echo "--- Resolving dependencies..." - @env $(MACOS_ENV_UNSET) $(FLUTTER) pub get + @env $(MACOS_ENV_UNSET) "$(FLUTTER)" pub get @cd scripts && env $(MACOS_ENV_UNSET) bash prebuild.sh @echo "--- Final Compilation..." - @env $(MACOS_ENV_UNSET) $(FLUTTER) build macos --release + @env $(MACOS_ENV_UNSET) "$(FLUTTER)" build macos --release diagnose-env-macos: ## Print macOS build env and tool resolution @echo "--- Toolchain diagnostics ---" - @echo "flutter: $$(command -v $(FLUTTER) || echo missing)" - @echo "dart: $$(command -v $(DART) || echo missing)" + @echo "flutter: $$(command -v "$(FLUTTER)" || echo missing)" + @echo "dart: $$(command -v "$(DART)" || echo missing)" @echo "xcrun: $$(command -v xcrun || echo missing)" @echo "clang: $$(command -v clang || echo missing)" @echo "go: $$(command -v go || echo missing)" @@ -393,9 +412,9 @@ build-linux: require-version check-linux toolchain-check check-reqs ## Build Lin echo "[INFO] .cargo/config.toml exists; make sure it sets [env] PROTOC if protoc fails to run (NixOS)."; \ fi @echo "--- Building app..." - @$(FLUTTER) pub get + @"$(FLUTTER)" pub get @if [ "$(SYSTEM_DEPS)" = "1" ]; then \ - USE_SYSTEM_SECURE_STORAGE_DEPS=1 PROTOC="$(PROTOC_PATH)" $(FLUTTER) build linux --release; \ + USE_SYSTEM_SECURE_STORAGE_DEPS=1 PROTOC="$(PROTOC_PATH)" "$(FLUTTER)" build linux --release; \ else \ SYSPROF_PC_DIR=$$(dirname "$$(find /nix/store -path '*/lib/pkgconfig/sysprof-capture-4.pc' 2>/dev/null | head -n1)"); \ PC_PATH=$$(pkg-config --variable=pc_path pkg-config 2>/dev/null || echo ""); \ @@ -405,7 +424,7 @@ build-linux: require-version check-linux toolchain-check check-reqs ## Build Lin { echo "[ERROR] libsecret-1 not resolvable via pkg-config"; exit 1; }; \ PKG_CONFIG_DISABLE_UNINSTALLED=1 PKG_CONFIG_PATH= \ PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc:$$SYSPROF_PC_DIR:$$PC_PATH" \ - PROTOC="$(PROTOC_PATH)" $(FLUTTER) build linux --release; \ + PROTOC="$(PROTOC_PATH)" "$(FLUTTER)" build linux --release; \ fi @echo "--- Preparing release bundle..." @python3 scripts/linux/prepare_release_bundle.py $(LINUX_BUNDLE) @@ -415,11 +434,10 @@ build-linux: require-version check-linux toolchain-check check-reqs ## Build Lin # driven by build_app.sh directly, not by this target. build-windows: require-version check-windows toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } - @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed."; exit 1; } @cd scripts && bash prebuild.sh - @cd scripts && echo yes | MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d -s - @$(FLUTTER) pub get - @$(FLUTTER) build windows --release + @cd scripts && echo yes | MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d + @"$(FLUTTER)" pub get + @"$(FLUTTER)" build windows --release # Android: same steps as the "build-android" CI job, without the signing secrets. Needs the Android SDK/NDK # (ANDROID_SDK_ROOT) and Java; the CI image ghcr.io//stackwallet-ci:android is built from the Dockerfile @@ -436,18 +454,16 @@ android-dev-key: ## Create a throw-away debug signing key if android/key.propert build-android: require-version toolchain-check android-dev-key ## Build Android APKs (prebuilt dnix on macOS; Linux follows PREBUILTS) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } - @if [ "$(PREBUILTS)" = "0" ] && [ "$(PLATFORM)" = "Darwin" ]; then \ - echo "[WARN] Android on macOS uses verified prebuilts; dnix source builds need an x86_64 Linux host."; \ - fi @cd scripts && bash prebuild.sh - @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p android -a $(APP_NAME) $(if $(filter 1,$(ANDROID_PREBUILTS)),-d) -s - @$(FLUTTER) pub get - @$(FLUTTER) build apk --split-per-abi --release + @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p android -a $(APP_NAME) $(if $(filter 1,$(ANDROID_PREBUILTS)),-d) + @"$(FLUTTER)" pub get + @"$(FLUTTER)" build apk --split-per-abi --release # iOS: same steps as the "build-ios" CI job (device build, no code signing). Run on macOS with Xcode. -build-ios: require-version check-sdk-macos toolchain-check ## Build iOS Runner.app without code signing (same steps as CI) +build-ios: require-version toolchain-check check-reqs-macos check-sdk-macos ## Build iOS Runner.app without code signing (same steps as CI) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } + @xcrun --sdk iphoneos --show-sdk-path >/dev/null 2>&1 || { echo >&2 "[ERROR] iOS SDK not available; install the iOS platform in Xcode."; exit 1; } @cd scripts && bash prebuild.sh - @cd scripts && echo yes | env $(IOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) -s - @env $(IOS_ENV_UNSET) $(FLUTTER) pub get - @env $(IOS_ENV_UNSET) $(FLUTTER) build ios --release --no-codesign + @cd scripts && echo yes | env $(IOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) + @env $(IOS_ENV_UNSET) "$(FLUTTER)" pub get + @env $(IOS_ENV_UNSET) "$(FLUTTER)" build ios --release --no-codesign diff --git a/README.md b/README.md index 95891c78c7..f51a03c3b6 100644 --- a/README.md +++ b/README.md @@ -81,8 +81,8 @@ Use this only when you are not building through Nix/flake. The default source build needs Nix for the four dnix libraries. `PREBUILTS=1` uses the verified prebuilts and needs no Nix for them. -The Homebrew bootstrap installs the native build tools and configures Rust -1.99.1 for Flutter's native-assets hooks. It replaces the former local +The Homebrew bootstrap installs the native build tools and configures the BOM +Rust version for Flutter's native-assets hooks. It replaces the former local manual macOS native prebuild path; no submodule setup or manual native plugin build is needed. @@ -91,5 +91,5 @@ plugin build is needed. Install the prerequisites from [Building on macOS](docs/building/macos.md) yourself, then run `make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1`. -`make check-reqs` reports what is missing; `TOOLCHAIN=manual` makes the choice -explicit. Omit `PREBUILTS=1` only if you also have Nix for the source build. +`make check-reqs-macos` reports what is missing (`make check-sdk-macos` checks +full Xcode); `TOOLCHAIN=manual` makes the choice explicit. Omit `PREBUILTS=1` only if you also have Nix for the source build. diff --git a/docs/building/macos.md b/docs/building/macos.md index 81a5862dd9..25a5a9ff78 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -33,7 +33,7 @@ manual/Homebrew path. | [Nix](https://nixos.org/download/) | Source mode (dnix) in every host mode; not needed with `-d` | ```sh -brew install autoconf automake libtool cmake cocoapods pkg-config +brew install autoconf automake libtool cmake cocoapods meson ninja pkg-config ``` Check `nix --version` from the same environment that runs Flutter, and use diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index 66ddfd4bd5..b1501cc375 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -37,7 +37,8 @@ flowchart LR C --> X{"Full Xcode?"} X -- yes --> R["Ready to build"] - X -- no --> XS["make bootstrap-xcode"] + X -- no --> INSTALL["Install full Xcode
dart tool/setup_xcode.dart"] + INSTALL --> XS["make bootstrap-xcode"] XS --> R ``` @@ -63,14 +64,14 @@ flowchart TD MC --> MP{"PREBUILTS"} MP -- "0 default" --> MS["source
Nix + Xcode 27.0"] MP -- "1" --> MB["prebuilt -d"] - MS --> MR["build_app.sh -p macos -s
pub get · prebuild.sh
flutter build macos"] + MS --> MR["build_app.sh -p macos
pub get · prebuild.sh
flutter build macos"] MB --> MR - IOS --> IC["checks
require-version · check-sdk-macos
(macOS-only) · toolchain-check"] + IOS --> IC["checks
require-version · toolchain-check
check-reqs-macos · check-sdk-macos"] IC --> IP{"PREBUILTS"} IP -- "0 default" --> IS["source"] IP -- "1 CI" --> IB["prebuilt -d"] - IS --> IR["prebuild.sh
build_app.sh -p ios -s
pub get · flutter build ios"] + IS --> IR["prebuild.sh
build_app.sh -p ios
pub get · flutter build ios"] IB --> IR LINUX --> LC["checks
require-version · check-linux
toolchain-check · check-reqs"] @@ -102,5 +103,6 @@ flowchart TD | iOS developer | `0` | source, verified; needs Nix + Xcode 27.0 | | macOS/Linux/iOS CI | `1` | verified prebuilts (`-d`) | | Windows | `1` (fixed) | verified prebuilts (`-d`) | -| Android on macOS | `1` (fixed) | verified prebuilts (`-d`) | -| Android on Linux | follows `PREBUILTS` | source by default | +| Android on macOS | `1` (default; source builds need an x86_64 Linux host) | verified prebuilts (`-d`) | +| Android on x86_64 Linux | follows `PREBUILTS` | source by default | +| Android on non-x86_64 Linux | `1` (default; source builds need x86_64) | verified prebuilts (`-d`) | diff --git a/scripts/app_config/configure_campfire.sh b/scripts/app_config/configure_campfire.sh index 6af9e01ec8..62ff383bab 100755 --- a/scripts/app_config/configure_campfire.sh +++ b/scripts/app_config/configure_campfire.sh @@ -19,15 +19,12 @@ export NEW_BASIC_NAME="campfire" NEW_PUBSPEC_NAME="paymint" # paymint used in original pubspec for some reason PUBSPEC_FILE="${APP_PROJECT_ROOT_DIR}/pubspec.yaml" -# String replacements. -if [[ "$(uname)" == 'Darwin' ]]; then - # macos specific sed - sed -i '' "s/name: PLACEHOLDER/name: ${NEW_PUBSPEC_NAME}/g" "${PUBSPEC_FILE}" - sed -i '' "s/description: PLACEHOLDER/description: ${NEW_NAME}/g" "${PUBSPEC_FILE}" -else - sed -i "s/name: PLACEHOLDER/name: ${NEW_PUBSPEC_NAME}/g" "${PUBSPEC_FILE}" - sed -i "s/description: PLACEHOLDER/description: ${NEW_NAME}/g" "${PUBSPEC_FILE}" -fi +# String replacements. `sed -i.bak` works with both BSD sed and the GNU sed +# that the Nix dev shell puts on PATH; the backup is removed immediately. +sed -i.bak "s/name: PLACEHOLDER/name: ${NEW_PUBSPEC_NAME}/g" "${PUBSPEC_FILE}" +rm -f "${PUBSPEC_FILE}.bak" +sed -i.bak "s/description: PLACEHOLDER/description: ${NEW_NAME}/g" "${PUBSPEC_FILE}" +rm -f "${PUBSPEC_FILE}.bak" dart "${APP_PROJECT_ROOT_DIR}/tool/process_pubspec_deps.dart" \ "${PUBSPEC_FILE}" \ diff --git a/scripts/app_config/platforms/android/platform_config.sh b/scripts/app_config/platforms/android/platform_config.sh index 07f6d54167..2ba5306129 100755 --- a/scripts/app_config/platforms/android/platform_config.sh +++ b/scripts/app_config/platforms/android/platform_config.sh @@ -13,21 +13,17 @@ for (( i=0; i<=5; i++ )); do done -if [[ "$(uname)" == 'Darwin' ]]; then - # macos specific sed - sed -i '' "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_0}" - sed -i '' "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_1}" - sed -i '' "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_2}" - sed -i '' "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_3}" - sed -i '' "s/${APP_NAME_PLACEHOLDER}/${NEW_NAME}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_3}" - sed -i '' "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_4}" - sed -i '' "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_5}" -else - sed -i "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_0}" - sed -i "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_1}" - sed -i "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_2}" - sed -i "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_3}" - sed -i "s/${APP_NAME_PLACEHOLDER}/${NEW_NAME}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_3}" - sed -i "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_4}" - sed -i "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_5}" -fi +# `sed -i.bak` works with both BSD sed and the GNU sed that the Nix dev shell +# puts on PATH; the backup is removed immediately. +sed_i() { + sed -i.bak "$1" "$2" + rm -f "${2}.bak" +} + +sed_i "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_0}" +sed_i "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_1}" +sed_i "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_2}" +sed_i "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_3}" +sed_i "s/${APP_NAME_PLACEHOLDER}/${NEW_NAME}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_3}" +sed_i "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_4}" +sed_i "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${ANDROID_TF_5}" diff --git a/scripts/app_config/platforms/ios/platform_config.sh b/scripts/app_config/platforms/ios/platform_config.sh index c2842d1d58..4247268dc8 100755 --- a/scripts/app_config/platforms/ios/platform_config.sh +++ b/scripts/app_config/platforms/ios/platform_config.sh @@ -12,9 +12,12 @@ for (( i=0; i<=1; i++ )); do fi done -# Configure ios for Duo. -sed -i '' "s/${APP_NAME_PLACEHOLDER}/${NEW_NAME}/g" "${APP_PROJECT_ROOT_DIR}/${IOS_TF_0}" -sed -i '' "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${IOS_TF_1}" +# Configure ios for Duo. `sed -i.bak` works with both BSD sed and the GNU sed +# that the Nix dev shell puts on PATH; the backup is removed immediately. +sed -i.bak "s/${APP_NAME_PLACEHOLDER}/${NEW_NAME}/g" "${APP_PROJECT_ROOT_DIR}/${IOS_TF_0}" +rm -f "${APP_PROJECT_ROOT_DIR}/${IOS_TF_0}.bak" +sed -i.bak "s/${APP_ID_PLACEHOLDER}/${NEW_APP_ID}/g" "${APP_PROJECT_ROOT_DIR}/${IOS_TF_1}" +rm -f "${APP_PROJECT_ROOT_DIR}/${IOS_TF_1}.bak" # use app specific launch images LAUNCH_IMAGES_DIR="${APP_PROJECT_ROOT_DIR}/ios/Runner/Assets.xcassets/LaunchImage.imageset" diff --git a/scripts/install_xcode.sh b/scripts/install_xcode.sh index ee9273a825..482d823cb9 100755 --- a/scripts/install_xcode.sh +++ b/scripts/install_xcode.sh @@ -42,6 +42,7 @@ echo "Checking Xcode..." XCODE_APPS_DIR="${XCODE_APPS_DIR:-/Applications}" SELECTED_DEV="$(xcode-select -p 2>/dev/null || true)" +JUST_SELECTED=0 if [[ "$SELECTED_DEV" == /*.app/Contents/Developer && -x "$SELECTED_DEV/usr/bin/xcodebuild" ]]; then echo "Xcode already configured: ${SELECTED_DEV%/Contents/Developer}" else @@ -63,15 +64,20 @@ else fi echo "Xcode found at $XCODE_APP. Setting xcode-select path..." sudo xcode-select -s "$XCODE_APP/Contents/Developer" + JUST_SELECTED=1 fi -# Only ask for sudo when the license or first-launch setup is actually pending; -# an already-configured Xcode should not trigger these on every bootstrap run. -if ! xcodebuild -license check >/dev/null 2>&1; then - echo "Accepting the Xcode license..." - sudo xcodebuild -license accept -fi -if ! xcodebuild -checkFirstLaunchStatus >/dev/null 2>&1; then - echo "Running Xcode first-launch setup..." - sudo xcodebuild -runFirstLaunch +# The license and first-launch checks need root to read the system receipts: +# as a normal user they exit 69 even on a fully configured Xcode. Only run them +# after changing the selection, so repeat bootstraps do not ask for sudo again; +# `dart tool/setup_xcode.dart` handles first-launch for fresh installs. +if [[ "$JUST_SELECTED" = 1 ]]; then + if ! sudo xcodebuild -license check >/dev/null 2>&1; then + echo "Accepting the Xcode license..." + sudo xcodebuild -license accept + fi + if ! sudo xcodebuild -checkFirstLaunchStatus >/dev/null 2>&1; then + echo "Running Xcode first-launch setup..." + sudo xcodebuild -runFirstLaunch + fi fi diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 0a800d3a28..da3c912db6 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -153,6 +153,21 @@ Map _lockRefs() { return refs; } +/// A duplicate `[plugins]` table makes _readBom silently last-wins and makes +/// --update append a second block, so refuse both modes early. +void _requireSinglePluginsSection(String text) { + final count = RegExp( + r'^\[plugins\][ \t]*$', + multiLine: true, + ).allMatches(text).length; + if (count > 1) { + stderr.writeln( + 'Duplicate [plugins] sections in $_bomFile; keep exactly one.', + ); + exit(2); + } +} + Future _update() async { final refs = _lockRefs(); if (refs.isEmpty) { @@ -160,6 +175,7 @@ Future _update() async { exit(2); } final text = File(_bomFile).readAsStringSync(); + _requireSinglePluginsSection(text); final existing = _readBom(text)['plugins'] ?? {}; final declared = _declaredPlugins(); // Without a pubspec.yaml we cannot tell which app is configured; keep the @@ -229,7 +245,9 @@ Future main(List args) async { } if (args.contains('--update')) return _update(); - final bom = _readBom(File(_bomFile).readAsStringSync()); + final bomText = File(_bomFile).readAsStringSync(); + _requireSinglePluginsSection(bomText); + final bom = _readBom(bomText); final root = bom[''] ?? {}; if (root['schema_version'] != '1') { _fail('schema_version must be 1 in $_bomFile'); From 38b55cb80fff32f49eadb31a3bd8726f70560af7 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:33:00 +0200 Subject: [PATCH 036/107] build: drop the informational hooks BOM table Nothing reads it; the hooks-runner version only appears in the sccache explanation. Keeping every BOM key machine-checked is easier to trust. --- stack-bom.toml | 3 --- 1 file changed, 3 deletions(-) diff --git a/stack-bom.toml b/stack-bom.toml index aefcd04920..1f133b1a0c 100644 --- a/stack-bom.toml +++ b/stack-bom.toml @@ -11,9 +11,6 @@ dnssec_rust = "1.90.0" # OpenAlias/DNSSEC builds from source in every app go = "1.24.13" # exact Go used by CI; Dockerfile mirrors it go_min = "1.24.1" # flutter_mwebd's minimum on the Flutter host -[hooks] -hooks_runner = "1.5.0" # informational: Flutter 3.47.x pin; CARGO_/RUSTUP_ env vars reach hooks only from 1.6.2 - [macos] xcode = "27.1" # recommended for app builds xcode_dnix = "27.0" # dnix needs this one to rebuild Apple libraries byte for byte From 8dd754467b2a969458d34b502ca6aa8ea46e36f6 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:33:05 +0200 Subject: [PATCH 037/107] build: use brace expansion in the BOM reader Quiets shellcheck SC1087 without changing the sed expression. --- scripts/bom_values.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/bom_values.sh b/scripts/bom_values.sh index 472499f640..4995b77a86 100755 --- a/scripts/bom_values.sh +++ b/scripts/bom_values.sh @@ -20,7 +20,7 @@ value() { section="$(section_for "$key")" || exit 2 result="$( sed -n "/^\[$section\]/,/^\[/p" "$BOM" | - sed -n "s/^$key[[:space:]]*=[[:space:]]*\"\([^\"]*\)\".*/\1/p" | + sed -n "s/^${key}[[:space:]]*=[[:space:]]*\"\([^\"]*\)\".*/\1/p" | head -n1 )" [ -n "$result" ] || { From ec69173c7fcb35daf2301d852bad23b2026ff8b3 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:17:56 +0200 Subject: [PATCH 038/107] build: fix the Linux Nix shell and secp256k1 install path - Flutter's Linux CMake build forces CC=clang/CXX=clang++. libclang also puts the unwrapped clang first on PATH, which cannot find the NixOS crt/libstdc++ paths, so prefer the clang wrapper in the dev shell. - Restore the libsecp256k1 copy into Flutter's build tree. The coinlib CMake install step expects it there; without it `make build-linux` fails at `cmake --install`. The destination now follows Flutter's arch name. --- flake.nix | 4 ++++ scripts/linux/build_secp256k1.sh | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/flake.nix b/flake.nix index bc6d933bfb..01853950a1 100644 --- a/flake.nix +++ b/flake.nix @@ -111,6 +111,10 @@ # ========================================== ${lib.optionalString pkgs.stdenv.hostPlatform.isLinux '' # echo "🐧 Linux detected: Patching shebangs for NixOS..." + # Flutter's Linux CMake build forces CC=clang/CXX=clang++. libclang + # also puts the unwrapped clang first on PATH, which cannot find + # the NixOS crt/libstdc++ paths; prefer the clang wrapper. + export PATH="${pkgs.llvmPackages.clang}/bin:$PATH" export LIBCLANG_PATH="${pkgs.llvmPackages.libclang.lib}/lib" export BINDGEN_EXTRA_CLANG_ARGS="-isystem ${pkgs.llvmPackages.libclang.lib}/lib/clang/${clangMajor}/include" export PROTOC="${pkgs.protobuf}/bin/protoc" diff --git a/scripts/linux/build_secp256k1.sh b/scripts/linux/build_secp256k1.sh index eb2e68afa2..6bfbe815da 100755 --- a/scripts/linux/build_secp256k1.sh +++ b/scripts/linux/build_secp256k1.sh @@ -27,3 +27,13 @@ fi # Legacy location used by parts of the build pipeline. mkdir -p ../../../../../build cp "$SECP_SO" ../../../../../build/libsecp256k1.so + +# The coinlib CMake install step expects the library inside Flutter's build +# tree. Match Flutter's architecture directory name (x64, arm64). +case "$(uname -m)" in + x86_64|x64) FLUTTER_ARCH=x64 ;; + aarch64|arm64) FLUTTER_ARCH=arm64 ;; + *) FLUTTER_ARCH="$(uname -m)" ;; +esac +mkdir -p "../../../../../build/linux/${FLUTTER_ARCH}/release/secp256k1/lib" +cp "$SECP_SO" "../../../../../build/linux/${FLUTTER_ARCH}/release/secp256k1/lib/libsecp256k1.so" From b8607b477c7de2f2de104fb1d2cc97bbfbd5938a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:00:33 +0200 Subject: [PATCH 039/107] build: use patchelf 0.18 in the Linux dev shell prepare_release_bundle.py needs --clear-execstack, which the pinned nixpkgs patchelf 0.15 does not support. patchelfUnstable is 0.18 and lets `make build-linux` finish the bundle step on NixOS. --- flake.nix | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/flake.nix b/flake.nix index 01853950a1..806d7f8d74 100644 --- a/flake.nix +++ b/flake.nix @@ -48,7 +48,9 @@ opencv sysprof libsysprof-capture - patchelf + # 0.18 is the first patchelf with --clear-execstack, which + # prepare_release_bundle.py requires. + patchelfUnstable binutils tpm2-tss ocl-icd From 219aab4f8b7a78cc420a819eb3d063b3060ac130 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:40:54 +0200 Subject: [PATCH 040/107] build: put patchelf 0.18 ahead of stdenv's 0.15 Adding patchelfUnstable to buildInputs was not enough: stdenv's own patchelf 0.15 still comes first on PATH. Prepend it explicitly so prepare_release_bundle.py gets --clear-execstack. --- flake.nix | 2 ++ 1 file changed, 2 insertions(+) diff --git a/flake.nix b/flake.nix index 806d7f8d74..fd4c6b02ca 100644 --- a/flake.nix +++ b/flake.nix @@ -117,6 +117,8 @@ # also puts the unwrapped clang first on PATH, which cannot find # the NixOS crt/libstdc++ paths; prefer the clang wrapper. export PATH="${pkgs.llvmPackages.clang}/bin:$PATH" + # stdenv also provides patchelf 0.15; put 0.18 first. + export PATH="${pkgs.patchelfUnstable}/bin:$PATH" export LIBCLANG_PATH="${pkgs.llvmPackages.libclang.lib}/lib" export BINDGEN_EXTRA_CLANG_ARGS="-isystem ${pkgs.llvmPackages.libclang.lib}/lib/clang/${clangMajor}/include" export PROTOC="${pkgs.protobuf}/bin/protoc" From c76430762c8761d45e6e47d70ac9c6685f806696 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:56:10 +0200 Subject: [PATCH 041/107] docs: note the NixOS Android prerequisites Google's NDK/CMake binaries need nix-ld, and the read-only nixpkgs Flutter SDK cannot host Gradle's integration_test project. Point NixOS Android builds at a writable Flutter install or the CI image. --- docs/building/linux.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/building/linux.md b/docs/building/linux.md index f2d64c6c38..c3cda85d3f 100644 --- a/docs/building/linux.md +++ b/docs/building/linux.md @@ -46,6 +46,12 @@ Flutter requires. The app pins NDK **28.2.13676358** in its Android template; install it through SDK Manager. Then run `flutter doctor --android-licenses` and `flutter doctor`. The app supports Android API 24 and newer. +On NixOS, enable `programs.nix-ld.enable = true`: the NDK and CMake binaries +distributed by Google are generic Linux executables. The nixpkgs Flutter SDK +is also read-only, and Gradle needs a writable project directory for Flutter's +dev-only `integration_test` plugin; without a writable Flutter install, use the +CI Android image for Android builds. + ## Build 1. Clone the repository and create the stubs: From cd32eaf797b4ae7ce43f5fe0e6f4b145e33f447d Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:28:45 +0200 Subject: [PATCH 042/107] build: harden BOM and shell bootstrap inputs - Validate every BOM version pin and add `bom_values.sh --check`; run it in make-check and the release bom job, so a data-file edit cannot switch a toolchain action to a branch, range or shell syntax. - Generate the macOS tool wrappers in a temp directory instead of a repo-writable `.nix-bin` on PATH. - Do not auto-install Homebrew or pipe rustup.sh to sh; fail with instructions. Quote the Flutter PATH entry written to ~/.zshrc. - Guard link_assets' recursive delete and enforce the no-$(MAKE) dry-run contract in make-check. - Give the bom job contents: read. --- .github/workflows/build.yaml | 5 +++- .github/workflows/test.yaml | 5 ++++ .gitignore | 2 -- flake.nix | 5 ++-- scripts/bom_values.sh | 39 ++++++++++++++++++++++++---- scripts/install_macos_build_tools.sh | 19 +++++--------- 6 files changed, 52 insertions(+), 23 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 59de949cd7..1c3c1a82dd 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -23,7 +23,9 @@ on: jobs: bom: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 + permissions: + contents: read outputs: flutter_min: ${{ steps.read.outputs.flutter_min }} go: ${{ steps.read.outputs.go }} @@ -35,6 +37,7 @@ jobs: - name: Read stack-bom.toml id: read run: | + bash scripts/bom_values.sh --check flutter_min="$(bash scripts/bom_values.sh --get flutter_min)" go="$(bash scripts/bom_values.sh --get go)" dnssec_rust="$(bash scripts/bom_values.sh --get dnssec_rust)" diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 06f5edb9be..140ea5b5f8 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -142,6 +142,11 @@ jobs: - uses: actions/checkout@v6 - name: Check the Makefile dry-runs run: | + bash scripts/bom_values.sh --check + if grep -nE '\$\(MAKE\)' Makefile; then + echo 'Makefile uses $(MAKE), which runs even under make -n' >&2 + exit 1 + fi make help make -n build-macos PLATFORM=Darwin VERSION=0.0.0 BUILD_NUM=1 make -n build-linux PLATFORM=Linux VERSION=0.0.0 BUILD_NUM=1 diff --git a/.gitignore b/.gitignore index 46f440b58c..ef72b7d4ff 100644 --- a/.gitignore +++ b/.gitignore @@ -126,8 +126,6 @@ lib/wl_gen/generated/ /.cargo/config.toml /scripts/linux/pc/ -# Nix dev shell: generated wrappers -.nix-bin/ # Android local signing /android/key.properties diff --git a/flake.nix b/flake.nix index fd4c6b02ca..a48450badb 100644 --- a/flake.nix +++ b/flake.nix @@ -168,8 +168,9 @@ fi export PROTOC="${pkgs.protobuf}/bin/protoc" - NIX_BIN="$APP_PROJECT_ROOT_DIR/.nix-bin" - mkdir -p "$NIX_BIN" + # A repo-writable directory on PATH would let anything that can + # write to the checkout shadow tools for the rest of the session. + NIX_BIN="$(/usr/bin/mktemp -d "''${TMPDIR:-/tmp}/stackwallet-nix-bin.XXXXXX")" ln -sf /usr/bin/clang "$NIX_BIN/cc" ln -sf /usr/bin/clang++ "$NIX_BIN/c++" ln -sf /usr/bin/clang "$NIX_BIN/clang" diff --git a/scripts/bom_values.sh b/scripts/bom_values.sh index 4995b77a86..00075bc90e 100755 --- a/scripts/bom_values.sh +++ b/scripts/bom_values.sh @@ -27,21 +27,50 @@ value() { echo "Missing [$section] $key in $BOM" >&2 return 1 } + # These values are passed to toolchain actions in the release workflow. + # Reject anything that is not a plain version so a data-file edit cannot + # inject a branch, a range or shell syntax. + if [[ ! "$result" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then + echo "Invalid [$section] $key value '$result' in $BOM (expected x.y or x.y.z)" >&2 + return 1 + fi printf '%s\n' "$result" } -[ "${1:-}" = "--get" ] || { - echo "Usage: $0 --get [bom]" >&2 - exit 2 +check_all() { + local key + for key in rust dnssec_rust flutter flutter_min go go_min xcode; do + value "$key" >/dev/null + done + echo "BOM values OK" } -[ "$#" -ge 2 ] || { + +usage() { echo "Usage: $0 --get [bom]" >&2 + echo " $0 --check [bom]" >&2 exit 2 } -[ "$#" -ge 3 ] && BOM="$3" + +case "${1:-}" in + --check) + if [ "$#" -ge 2 ]; then BOM="$2"; fi + ;; + --get) + if [ "$#" -lt 2 ]; then usage; fi + if [ "$#" -ge 3 ]; then BOM="$3"; fi + ;; + *) + usage + ;; +esac + [ -r "$BOM" ] || { echo "Cannot read $BOM" >&2 exit 1 } +if [ "$1" = "--check" ]; then + check_all + exit 0 +fi value "$2" diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh index 549413c31a..a86916d61b 100755 --- a/scripts/install_macos_build_tools.sh +++ b/scripts/install_macos_build_tools.sh @@ -29,15 +29,7 @@ if ! command -v brew >/dev/null 2>&1; then elif [[ -x /usr/local/bin/brew ]]; then eval "$(/usr/local/bin/brew shellenv)" else - echo "Homebrew not found. Installing..." - /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" - if [[ -x /opt/homebrew/bin/brew ]]; then - eval "$(/opt/homebrew/bin/brew shellenv)" - elif [[ -x /usr/local/bin/brew ]]; then - eval "$(/usr/local/bin/brew shellenv)" - else - die "Homebrew installation failed. Install manually: https://brew.sh" - fi + die "Homebrew is required. Install it from https://brew.sh, then re-run 'make bootstrap-macos'." fi fi @@ -153,8 +145,7 @@ if [ ! -x "$HOME/.cargo/bin/cargo" ]; then if command -v rustup-init >/dev/null 2>&1; then rustup-init -y --no-modify-path --default-toolchain "$RUST_VERSION" || true else - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \ - | sh -s -- -y --no-modify-path --default-toolchain "$RUST_VERSION" || true + die "rustup-init not found. Run 'brew install rustup', then re-run this script." fi fi @@ -203,8 +194,10 @@ BREW_PREFIX="$(brew --prefix)" grep -qF 'brew shellenv' "$ZSHRC" 2>/dev/null || \ printf 'eval "$(%s/bin/brew shellenv)"\n' "$BREW_PREFIX" >> "$ZSHRC" if [[ -n "$FLUTTER_PATH_TO_PERSIST" ]]; then - grep -qF "$FLUTTER_PATH_TO_PERSIST" "$ZSHRC" 2>/dev/null || \ - printf 'export PATH="%s:$PATH"\n' "$FLUTTER_PATH_TO_PERSIST" >> "$ZSHRC" + if ! grep -qF "$FLUTTER_PATH_TO_PERSIST" "$ZSHRC" 2>/dev/null; then + # %q keeps a user-supplied FLUTTER_DIR from becoming shell syntax. + printf 'export PATH=%q:$PATH\n' "$FLUTTER_PATH_TO_PERSIST" >> "$ZSHRC" + fi fi grep -qF '$HOME/.cargo/bin' "$ZSHRC" 2>/dev/null || \ printf 'export PATH="%s/opt/rustup/bin:$HOME/.cargo/bin:$PATH"\n' "$BREW_PREFIX" >> "$ZSHRC" From 5e3c1c1ac440869477e84c1ed8e4db5182b0e40d Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:38:37 +0200 Subject: [PATCH 043/107] build: close the second audit round - Fix the make-check $(MAKE) guard to match recipe lines, not the explanatory comments; the previous guard failed on every run. - Derive DART from an explicit FLUTTER path, reject tool paths with spaces, and keep the resolved tools on PATH for child scripts. - Default PREBUILTS to source only on Apple Silicon and Nix/direnv Linux; Intel and non-Nix hosts use the verified prebuilts. - Enforce VERSION/BUILD_NUM format and require BUILD_NUM above the latest build_* tag. - Require patchelf 0.18 on Linux and make the secure-storage checkout fail closed. - Require an explicit android-dev-key, and keep build_app.sh's wallet-data warning interactive unless CONFIRM=1. - Pass the sysprof pkg-config path from the flake instead of walking /nix/store on every Linux build. - Accept TOML header comments in verify_bom and validate xcode_dnix. - Document the new defaults, variables, manual Rust/Xcode steps and the NixOS Android limits. --- .github/workflows/test.yaml | 2 +- Makefile | 94 ++++++++++++++++------ README.md | 13 ++- docs/building/linux.md | 9 ++- docs/building/macos.md | 3 + docs/building/make-flow.md | 40 +++++---- docs/building/windows.md | 2 +- flake.nix | 11 ++- scripts/app_config/templates/isar_build.sh | 3 +- scripts/bom_values.sh | 13 ++- scripts/install_macos_build_tools.sh | 9 ++- scripts/linux/build_secure_storage_deps.sh | 5 +- tool/verify_bom.dart | 20 +++-- 13 files changed, 148 insertions(+), 76 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 140ea5b5f8..e4104f9059 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -143,7 +143,7 @@ jobs: - name: Check the Makefile dry-runs run: | bash scripts/bom_values.sh --check - if grep -nE '\$\(MAKE\)' Makefile; then + if grep -nE '^[^#]*\$\(MAKE\)' Makefile; then echo 'Makefile uses $(MAKE), which runs even under make -n' >&2 exit 1 fi diff --git a/Makefile b/Makefile index 66739d12bb..2b1710b455 100644 --- a/Makefile +++ b/Makefile @@ -4,22 +4,40 @@ # ============================================================================== APP_NAME ?= stack_wallet +# build_app.sh asks before replacing generated app files because some +# version/build combinations can delete wallet data. Keep that prompt +# interactive unless the caller explicitly opts in. +CONFIRM ?= 0 # Build targets require these explicitly: a stale default silently produces an # app numbered below the current release line. See `require-version`. VERSION ?= BUILD_NUM ?= FLUTTER ?= DART ?= -FLUTTER_BIN := $(if $(and $(FLUTTER),$(wildcard $(FLUTTER))),$(FLUTTER),$(shell command -v flutter 2>/dev/null)) -DART_BIN := $(if $(and $(DART),$(wildcard $(DART))),$(DART),$(shell command -v dart 2>/dev/null)) +# Make splits unquoted values on whitespace, so a tool path with a space would +# silently resolve to a different binary. Fail early instead. +ifneq ($(strip $(FLUTTER)),) + ifneq ($(words $(FLUTTER)),1) + $(error FLUTTER must not contain spaces; put it on PATH instead) + endif +endif +ifneq ($(strip $(DART)),) + ifneq ($(words $(DART)),1) + $(error DART must not contain spaces; put it on PATH instead) + endif +endif +FLUTTER_BIN := $(if $(FLUTTER),$(FLUTTER),$(shell command -v flutter 2>/dev/null)) +# A Flutter SDK ships its own Dart next to the flutter binary; an explicit +# FLUTTER path should not require a second DART= argument. +DART_BIN := $(if $(DART),$(DART),$(if $(filter /%,$(FLUTTER_BIN)),$(wildcard $(dir $(FLUTTER_BIN))dart),$(shell command -v dart 2>/dev/null))) FLUTTER := $(FLUTTER_BIN) DART := $(DART_BIN) # Child scripts call bare `flutter`/`dart`; keep them on the binaries checked # above instead of whatever PATH would otherwise resolve. -ifneq ($(FLUTTER),) +ifneq ($(filter /%,$(FLUTTER)),) export PATH := $(dir $(FLUTTER)):$(PATH) endif -ifneq ($(DART),) +ifneq ($(filter /%,$(DART)),) export PATH := $(dir $(DART)):$(PATH) endif APP_PROJECT_ROOT_DIR := $(CURDIR) @@ -29,6 +47,7 @@ endif # Platform detection from uname. PLATFORM can be overridden, but only with a # supported value; an unrelated exported PLATFORM must not change the defaults. UNAME_S := $(shell uname -s 2>/dev/null) +UNAME_M := $(shell uname -m 2>/dev/null) PLATFORM ?= $(UNAME_S) ifneq ($(PLATFORM),Darwin) ifneq ($(PLATFORM),Linux) @@ -76,7 +95,7 @@ endif # and `make` and the IDE share native-asset outputs instead of rebuilding them. LINUX_PUB_CACHE ?= $(APP_PROJECT_ROOT_DIR)/.pub-cache PUB_CACHE ?= -PROTOC_PATH := $(shell which protoc 2>/dev/null) +PROTOC_PATH := $(shell command -v protoc 2>/dev/null) # Toolchain installed for host-side checks/targets. Native-assets crates pick their own # pinned toolchain via rust-toolchain.toml; do not export RUSTUP_TOOLCHAIN globally. BOM_FILE := $(APP_PROJECT_ROOT_DIR)/stack-bom.toml @@ -106,7 +125,7 @@ endif help: ## Show available commands @echo "Available targets:" - @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "%-24s %s\n", $$1, $$2}' + @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' "$(firstword $(MAKEFILE_LIST))" | awk 'BEGIN {FS = ":.*?## "}; {printf "%-24s %s\n", $$1, $$2}' # --- TOOLCHAIN --- @@ -165,9 +184,16 @@ endif # --- PREREQUISITES --- -require-version: ## Fail unless VERSION and BUILD_NUM are set explicitly - @[ -n "$(VERSION)" ] || { echo >&2 "[ERROR] VERSION is not set. Pass VERSION=x.y.z (latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } - @[ -n "$(BUILD_NUM)" ] || { echo >&2 "[ERROR] BUILD_NUM is not set. Pass a build number above the latest release tag ($$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } +require-version: ## Fail unless VERSION/BUILD_NUM are valid and above the latest release tag + @printf '%s' '$(VERSION)' | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$$' || { echo >&2 "[ERROR] VERSION must be x.y.z (got '$(VERSION)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } + @printf '%s' '$(BUILD_NUM)' | grep -Eq '^[0-9]+$$' || { echo >&2 "[ERROR] BUILD_NUM must be numeric (got '$(BUILD_NUM)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } + @latest="$$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1)"; \ + if [ -n "$$latest" ]; then \ + latest_num="$${latest#build_}"; \ + case "$$latest_num" in (*[!0-9]*) ;; (*) \ + [ "$(BUILD_NUM)" -gt "$$latest_num" ] || { echo >&2 "[ERROR] BUILD_NUM $(BUILD_NUM) is not above the latest release tag $$latest."; exit 1; }; \ + esac; \ + fi check-reqs: ## Verify essential build tools @echo "Checking core prerequisites..." @@ -211,6 +237,7 @@ endif ifeq ($(PLATFORM),Linux) @command -v python3 >/dev/null 2>&1 || { echo >&2 "[ERROR] python3 not installed (needed to prepare the Linux release bundle)."; exit 1; } @command -v patchelf >/dev/null 2>&1 || { echo >&2 "[ERROR] patchelf not installed (Ubuntu 24.04: apt-get install patchelf binutils)."; exit 1; } + @patchelf --help 2>&1 | grep -q -- '--clear-execstack' || { echo >&2 "[ERROR] patchelf >= 0.18 is required (--clear-execstack). Use 'nix develop' or install a newer patchelf."; exit 1; } @command -v readelf >/dev/null 2>&1 || { echo >&2 "[ERROR] readelf not installed (apt-get install binutils)."; exit 1; } endif @echo "[OK] All core CLI requirements found!" @@ -262,7 +289,7 @@ else @exit 1 endif -bootstrap-xcode: ## Check/select an installed full Xcode.app (needed regardless of Homebrew vs Nix for the rest of the toolchain) +bootstrap-xcode: ## Check/select an installed full Xcode.app (may ask for sudo to accept the licence) ifeq ($(PLATFORM),Darwin) @bash scripts/install_xcode.sh else @@ -298,8 +325,9 @@ clean: ## Remove artifacts and fix permissions @echo "Cleaning Flutter and Rust artifacts..." @chflags -R nouchg build/ macos/ 2>/dev/null || true @chmod -R u+w build/ macos/ 2>/dev/null || true - @if [ -n "$(FLUTTER)" ] && [ -f pubspec.yaml ]; then "$(FLUTTER)" clean; fi + @if [ -n "$(FLUTTER)" ] && [ -f pubspec.yaml ]; then "$(FLUTTER)" clean; else echo "[WARN] Flutter not available; skipped 'flutter clean'."; fi @rm -rf macos/Pods macos/Podfile.lock ios/Pods ios/Podfile.lock build/ + @rm -f .cargo/config.toml @echo "Cleaning local pub cache residues..." @chmod -R u+w "$(LINUX_PUB_CACHE)/git/" 2>/dev/null || true @find "$(LINUX_PUB_CACHE)/git/" -type d \( -name "build" -o -name "target" \) -path "*flutter_lib*" -exec rm -rf {} + 2>/dev/null || true @@ -307,18 +335,25 @@ clean: ## Remove artifacts and fix permissions # --- PLATFORM BUILDS --- -# dnix mode. macOS and Linux build the pinned native libraries from source by -# default (the Nix-primary developer path). Windows and CI use verified +# dnix mode. Apple Silicon macOS and Linux inside the Nix/direnv shell build +# the pinned native libraries from source by default (the Nix-primary developer +# path). Intel macOS, a non-Nix Linux host, Windows and CI use verified # prebuilts. PREBUILTS=1 passes -d and needs no Nix for those four libraries; # PREBUILTS=0 builds them with Nix and verifies the hashes. ifeq ($(PLATFORM),Darwin) -PREBUILTS ?= 0 -else - ifeq ($(PLATFORM),Linux) + ifeq ($(filter arm64 aarch64,$(UNAME_M)),$(UNAME_M)) PREBUILTS ?= 0 else PREBUILTS ?= 1 endif +else ifeq ($(PLATFORM),Linux) + ifeq ($(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),$(TOOLCHAIN_EFFECTIVE)) + PREBUILTS ?= 0 + else + PREBUILTS ?= 1 + endif +else + PREBUILTS ?= 1 endif ifneq ($(filter $(PREBUILTS),0 1),$(PREBUILTS)) $(error PREBUILTS must be 0 or 1) @@ -349,20 +384,21 @@ endif LINUX_ARCH := $(shell uname -m | sed -e 's/x86_64/x64/' -e 's/aarch64/arm64/') LINUX_BUNDLE ?= build/linux/$(LINUX_ARCH)/release/bundle -clean-app: ## Remove app build output (build/, Pods) but keep the native-asset build outputs, so the next build is fast +clean-app: ## Remove app build output (build/, Pods) but keep .dart_tool/hooks_runner, so the next build is fast @chflags -R nouchg build/ macos/ 2>/dev/null || true @chmod -R u+w build/ macos/ 2>/dev/null || true @rm -rf build/ macos/Pods macos/Podfile.lock ios/Pods ios/Podfile.lock @echo "[OK] Removed build/ and Pods; .dart_tool/hooks_runner is kept." clean-native: ## Remove only the native-asset build outputs (forces the Rust/Go/C libraries to be rebuilt) + @chflags -R nouchg .dart_tool/hooks_runner build/native_assets 2>/dev/null || true @chmod -R u+w .dart_tool/hooks_runner build/native_assets 2>/dev/null || true @rm -rf .dart_tool/hooks_runner build/native_assets @echo "[OK] Removed .dart_tool/hooks_runner and build/native_assets." build-macos: require-version toolchain-check check-reqs-macos check-sdk-macos ## Build macOS release (source by default; PREBUILTS=1 uses verified prebuilts) @echo "--- Configuring project (scripts/build_app.sh)..." - @cd scripts && echo yes | env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) + @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) @echo "--- Resolving dependencies..." @env $(MACOS_ENV_UNSET) "$(FLUTTER)" pub get @cd scripts && env $(MACOS_ENV_UNSET) bash prebuild.sh @@ -399,7 +435,7 @@ build-linux: require-version check-linux toolchain-check check-reqs ## Build Lin @cd scripts && bash prebuild.sh @echo "--- Generating config..." @if [ -z "$(PROTOC_PATH)" ]; then echo "[ERROR] protoc not found!"; exit 1; fi - @cd scripts && yes yes | BUILD_ISAR_FROM_SOURCE=0 PROTOC="$(PROTOC_PATH)" ./build_app.sh -a $(APP_NAME) -p linux -v $(VERSION) -b $(BUILD_NUM) $(if $(filter 1,$(PREBUILTS)),-d) $(if $(filter 1,$(SYSTEM_DEPS)),-s) + @cd scripts && $(if $(filter 1,$(CONFIRM)),yes yes |,) BUILD_ISAR_FROM_SOURCE=0 PROTOC="$(PROTOC_PATH)" ./build_app.sh -a $(APP_NAME) -p linux -v $(VERSION) -b $(BUILD_NUM) $(if $(filter 1,$(PREBUILTS)),-d) $(if $(filter 1,$(SYSTEM_DEPS)),-s) @# Flutter 3.47.x hooks only see a filtered environment, so PROTOC (exported by the flake) never @# reaches cargo build scripts. Some crates (prost-build 0.7) ship a generic-Linux protoc that cannot @# run on NixOS. cargo reads [env] from .cargo/config.toml found from the package dir upwards, which @@ -416,14 +452,18 @@ build-linux: require-version check-linux toolchain-check check-reqs ## Build Lin @if [ "$(SYSTEM_DEPS)" = "1" ]; then \ USE_SYSTEM_SECURE_STORAGE_DEPS=1 PROTOC="$(PROTOC_PATH)" "$(FLUTTER)" build linux --release; \ else \ - SYSPROF_PC_DIR=$$(dirname "$$(find /nix/store -path '*/lib/pkgconfig/sysprof-capture-4.pc' 2>/dev/null | head -n1)"); \ + SYSPROF_PC_DIR="$${SYSPROF_PC_DIR:-}"; \ + if [ -z "$$SYSPROF_PC_DIR" ]; then \ + SYSPROF_PC_DIR=$$(dirname "$$(find /nix/store -path '*/lib/pkgconfig/sysprof-capture-4.pc' 2>/dev/null | head -n1)"); \ + [ "$$SYSPROF_PC_DIR" != "." ] || SYSPROF_PC_DIR=""; \ + fi; \ PC_PATH=$$(pkg-config --variable=pc_path pkg-config 2>/dev/null || echo ""); \ PKG_CONFIG_DISABLE_UNINSTALLED=1 PKG_CONFIG_PATH= \ - PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc:$$SYSPROF_PC_DIR:$$PC_PATH" \ + PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc$${SYSPROF_PC_DIR:+:$$SYSPROF_PC_DIR}:$$PC_PATH" \ pkg-config --modversion libsecret-1 >/dev/null || \ { echo "[ERROR] libsecret-1 not resolvable via pkg-config"; exit 1; }; \ PKG_CONFIG_DISABLE_UNINSTALLED=1 PKG_CONFIG_PATH= \ - PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc:$$SYSPROF_PC_DIR:$$PC_PATH" \ + PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc$${SYSPROF_PC_DIR:+:$$SYSPROF_PC_DIR}:$$PC_PATH" \ PROTOC="$(PROTOC_PATH)" "$(FLUTTER)" build linux --release; \ fi @echo "--- Preparing release bundle..." @@ -435,7 +475,7 @@ build-linux: require-version check-linux toolchain-check check-reqs ## Build Lin build-windows: require-version check-windows toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @cd scripts && bash prebuild.sh - @cd scripts && echo yes | MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d + @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d @"$(FLUTTER)" pub get @"$(FLUTTER)" build windows --release @@ -444,6 +484,7 @@ build-windows: require-version check-windows toolchain-check ## Build Windows re # (docker build --target android). Without android/key.properties a throw-away debug key is created, so the APKs # are not suitable for distribution. android-dev-key: ## Create a throw-away debug signing key if android/key.properties is missing (never use for releases) + @command -v keytool >/dev/null 2>&1 || { echo >&2 "[ERROR] keytool not found; install a JDK."; exit 1; } @if [ ! -f android/key.properties ]; then \ echo "[INFO] android/key.properties missing: creating a throw-away debug key (not for releases)"; \ keytool -genkeypair -keystore android/dev-keystore.jks -storetype pkcs12 -storepass android -keypass android \ @@ -451,11 +492,12 @@ android-dev-key: ## Create a throw-away debug signing key if android/key.propert printf 'storeFile=../dev-keystore.jks\nstorePassword=android\nkeyPassword=android\nkeyAlias=devkey\n' > android/key.properties; \ fi -build-android: require-version toolchain-check android-dev-key ## Build Android APKs (prebuilt dnix on macOS; Linux follows PREBUILTS) +build-android: require-version toolchain-check ## Build Android APKs (requires android/key.properties; prebuilt dnix on macOS, Linux follows PREBUILTS) @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } + @[ -f android/key.properties ] || { echo >&2 "[ERROR] android/key.properties is missing. Run 'make android-dev-key' for a local throw-away key; never distribute APKs signed with it."; exit 1; } @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } @cd scripts && bash prebuild.sh - @cd scripts && echo yes | ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p android -a $(APP_NAME) $(if $(filter 1,$(ANDROID_PREBUILTS)),-d) + @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p android -a $(APP_NAME) $(if $(filter 1,$(ANDROID_PREBUILTS)),-d) @"$(FLUTTER)" pub get @"$(FLUTTER)" build apk --split-per-abi --release @@ -464,6 +506,6 @@ build-ios: require-version toolchain-check check-reqs-macos check-sdk-macos ## B @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @xcrun --sdk iphoneos --show-sdk-path >/dev/null 2>&1 || { echo >&2 "[ERROR] iOS SDK not available; install the iOS platform in Xcode."; exit 1; } @cd scripts && bash prebuild.sh - @cd scripts && echo yes | env $(IOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) + @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) env $(IOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) @env $(IOS_ENV_UNSET) "$(FLUTTER)" pub get @env $(IOS_ENV_UNSET) "$(FLUTTER)" build ios --release --no-codesign diff --git a/README.md b/README.md index f51a03c3b6..6729bc557c 100644 --- a/README.md +++ b/README.md @@ -60,8 +60,14 @@ using. - `make bootstrap` (runs `nix develop`), or - `nix develop` directly, or - `direnv allow` once, if you use direnv with the included `.envrc`. -2. Run build (pass the release version and a build number; `make` refuses to guess): +2. Check the Xcode requirement. Source builds are the default on Apple + Silicon and need Xcode **27.0** (build 27A266a); with any other Xcode pass + `PREBUILTS=1`. `make bootstrap-xcode` selects an installed full Xcode and + `make verify-bom` checks the host. +3. Run build (pass the release version and a build number; `make` refuses to + guess): - `make build-macos VERSION=x.y.z BUILD_NUM=nnn` + - Add `CONFIRM=1` for a non-interactive run. The flake provides Flutter, Dart, rustup (which installs the BOM Rust version on first entry), Go, CMake, Meson, Ninja, pkg-config and protoc. Xcode is never provided @@ -77,9 +83,10 @@ Use this only when you are not building through Nix/flake. - Open a new terminal (or run `source ~/.zshrc`) so the Homebrew and Flutter PATH entries are active. - `make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1` + - Add `CONFIRM=1` for a non-interactive run. -The default source build needs Nix for the four dnix libraries. `PREBUILTS=1` -uses the verified prebuilts and needs no Nix for them. +`PREBUILTS=1` uses the verified prebuilts and needs no Nix for the four dnix +libraries. The Homebrew bootstrap installs the native build tools and configures the BOM Rust version for Flutter's native-assets hooks. It replaces the former local diff --git a/docs/building/linux.md b/docs/building/linux.md index c3cda85d3f..f3541eebbf 100644 --- a/docs/building/linux.md +++ b/docs/building/linux.md @@ -7,7 +7,7 @@ These steps build the Linux desktop app and the Android app on Ubuntu 24.04 | What | Needed for | |---|---| -| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 | Every build | +| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 minimum, 3.47.4 recommended | Every build | | The [Ubuntu packages](#ubuntu-packages) below | Every build | | [Rustup](https://rustup.rs/) | Every app, in both modes | | [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet | @@ -48,9 +48,10 @@ and `flutter doctor`. The app supports Android API 24 and newer. On NixOS, enable `programs.nix-ld.enable = true`: the NDK and CMake binaries distributed by Google are generic Linux executables. The nixpkgs Flutter SDK -is also read-only, and Gradle needs a writable project directory for Flutter's -dev-only `integration_test` plugin; without a writable Flutter install, use the -CI Android image for Android builds. +is also read-only, and Gradle needs to write inside the `integration_test` +plugin project in that SDK. Without a writable Flutter checkout, build in +`ghcr.io//stackwallet-ci:android` (built with +`docker build --target android .`). ## Build diff --git a/docs/building/macos.md b/docs/building/macos.md index 25a5a9ff78..7fe76d790c 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -34,6 +34,9 @@ manual/Homebrew path. ```sh brew install autoconf automake libtool cmake cocoapods meson ninja pkg-config +rustup toolchain install "$(scripts/bom_values.sh --get rust)" +rustup target add aarch64-apple-darwin x86_64-apple-darwin \ + aarch64-apple-ios aarch64-apple-ios-sim ``` Check `nix --version` from the same environment that runs Flutter, and use diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index b1501cc375..f418c4e3b2 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -43,13 +43,15 @@ flowchart LR ``` `make bootstrap-xcode` does not install Xcode. It selects an existing full -install and finishes Apple's licence/first-launch setup if it is pending; use +install; when it changes the selection it accepts the licence and runs pending +first-launch setup. An already-selected Xcode is left untouched. Use `dart tool/setup_xcode.dart` or Apple's download page to install one. ## 2. Build -`VERSION` and `BUILD_NUM` are required. dnix source is the default on macOS, -Linux and iOS; CI and Windows use the verified prebuilts. +`VERSION` and `BUILD_NUM` are required. dnix source is the default on Apple +Silicon macOS and inside Nix/direnv on Linux; Intel macOS, non-Nix Linux, CI and +Windows use the verified prebuilts. ```mermaid flowchart TD @@ -62,34 +64,35 @@ flowchart TD MAC --> MC["checks
require-version · check-sdk-macos
toolchain-check · check-reqs-macos"] MC --> MP{"PREBUILTS"} - MP -- "0 default" --> MS["source
Nix + Xcode 27.0"] - MP -- "1" --> MB["prebuilt -d"] + MP -- "0 Apple Silicon" --> MS["source
Nix + Xcode 27.0"] + MP -- "1 Intel/CI" --> MB["prebuilt -d"] MS --> MR["build_app.sh -p macos
pub get · prebuild.sh
flutter build macos"] MB --> MR IOS --> IC["checks
require-version · toolchain-check
check-reqs-macos · check-sdk-macos"] IC --> IP{"PREBUILTS"} - IP -- "0 default" --> IS["source"] - IP -- "1 CI" --> IB["prebuilt -d"] + IP -- "0 Apple Silicon" --> IS["source"] + IP -- "1 Intel/CI" --> IB["prebuilt -d"] IS --> IR["prebuild.sh
build_app.sh -p ios
pub get · flutter build ios"] IB --> IR LINUX --> LC["checks
require-version · check-linux
toolchain-check · check-reqs"] LC --> LP{"PREBUILTS"} - LP -- "0 default" --> LS["source (Nix)"] - LP -- "1" --> LB["prebuilt -d"] + LP -- "0 Nix/direnv" --> LS["source (Nix)"] + LP -- "1 host" --> LB["prebuilt -d"] LS --> LR["prebuild.sh
build_app.sh -p linux
flutter build linux · bundle"] LB --> LR - WIN --> WC["checks
require-version · check-windows
toolchain-check · flutter · Go"] + WIN --> WC["checks
require-version · check-windows
toolchain-check · flutter"] WC --> WR["prebuild.sh
build_app.sh -p windows -d
pub get · flutter build windows
always prebuilt"] - AND --> AC["checks
require-version · toolchain-check
dev key · SDK"] + AND --> AC["checks
require-version · toolchain-check
android/key.properties · SDK"] AC --> AH{"Host"} AH -- macOS --> AB["prebuilt -d"] - AH -- Linux --> AP{"PREBUILTS"} - AP -- "0 default" --> AS["source"] - AP -- "1" --> AB + AH -- "Linux arm64" --> AB + AH -- "Linux x86_64" --> AP{"PREBUILTS"} + AP -- "0 Nix" --> AS["source"] + AP -- "1 host" --> AB AB --> AR["prebuild.sh
build_app.sh -p android
pub get · flutter build apk
--split-per-abi"] AS --> AR ``` @@ -98,9 +101,12 @@ flowchart TD | Context | `PREBUILTS` | dnix mode | |---|---|---| -| macOS developer | `0` | source, verified; needs Nix + Xcode 27.0 | -| Linux developer | `0` | source, verified; needs Nix | -| iOS developer | `0` | source, verified; needs Nix + Xcode 27.0 | +| macOS developer, Apple Silicon | `0` | source, verified; needs Nix + Xcode 27.0 | +| macOS developer, Intel | `1` | verified prebuilts (`-d`) | +| Linux developer in Nix/direnv | `0` | source, verified; needs Nix | +| Linux developer, non-Nix host | `1` | verified prebuilts (`-d`) | +| iOS developer, Apple Silicon | `0` | source, verified; needs Nix + Xcode 27.0 | +| iOS developer, Intel | `1` | verified prebuilts (`-d`) | | macOS/Linux/iOS CI | `1` | verified prebuilts (`-d`) | | Windows | `1` (fixed) | verified prebuilts (`-d`) | | Android on macOS | `1` (default; source builds need an x86_64 Linux host) | verified prebuilts (`-d`) | diff --git a/docs/building/windows.md b/docs/building/windows.md index 9e5ca482f3..0b9871fdbe 100644 --- a/docs/building/windows.md +++ b/docs/building/windows.md @@ -9,7 +9,7 @@ with Windows Flutter. For how the build fits together, see the | What | Needed for | |---|---| -| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2, and Git for Windows, which includes Git Bash | Every build | +| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 minimum, 3.47.4 recommended, and Git for Windows, which includes Git Bash | Every build | | [Visual Studio 2022](https://docs.flutter.dev/platform-integration/windows/setup) with **Desktop development with C++**, CMake tools and a Windows SDK | Every build | | Windows Developer Mode, for the symlinks Flutter and its plugins create | Every build | | [Rustup](https://rustup.rs/) on Windows | Every app's DNSSEC hook and Stack Wallet's Xelis hook, in both modes | diff --git a/flake.nix b/flake.nix index a48450badb..f13140304e 100644 --- a/flake.nix +++ b/flake.nix @@ -84,7 +84,10 @@ fi export APP_PROJECT_ROOT_DIR="$APP_ROOT" if [ -d "$HOME/.cargo/bin" ]; then - export PATH="$PATH:$HOME/.cargo/bin" + case ":$PATH:" in + *":$HOME/.cargo/bin:"*) ;; + *) export PATH="$PATH:$HOME/.cargo/bin" ;; + esac fi # The standalone Dart in the Nix Flutter wrapper cannot find the Flutter SDK on its own, @@ -122,6 +125,7 @@ export LIBCLANG_PATH="${pkgs.llvmPackages.libclang.lib}/lib" export BINDGEN_EXTRA_CLANG_ARGS="-isystem ${pkgs.llvmPackages.libclang.lib}/lib/clang/${clangMajor}/include" export PROTOC="${pkgs.protobuf}/bin/protoc" + export SYSPROF_PC_DIR="${pkgs.libsysprof-capture}/lib/pkgconfig" ''} # ========================================== @@ -170,7 +174,7 @@ # A repo-writable directory on PATH would let anything that can # write to the checkout shadow tools for the rest of the session. - NIX_BIN="$(/usr/bin/mktemp -d "''${TMPDIR:-/tmp}/stackwallet-nix-bin.XXXXXX")" + if NIX_BIN="$(/usr/bin/mktemp -d "''${TMPDIR:-/tmp}/stackwallet-nix-bin.XXXXXX")"; then ln -sf /usr/bin/clang "$NIX_BIN/cc" ln -sf /usr/bin/clang++ "$NIX_BIN/c++" ln -sf /usr/bin/clang "$NIX_BIN/clang" @@ -216,6 +220,9 @@ XCRUN_EOF chmod +x "$NIX_BIN/xcrun" export PATH="$NIX_BIN:$PATH" + else + echo "[WARN] Could not create the Apple tool wrapper directory; using the Nix tools." >&2 + fi ''} ''; diff --git a/scripts/app_config/templates/isar_build.sh b/scripts/app_config/templates/isar_build.sh index 625a59b246..fb0e7ee188 100644 --- a/scripts/app_config/templates/isar_build.sh +++ b/scripts/app_config/templates/isar_build.sh @@ -83,7 +83,8 @@ build_isar_source() { echo "Found isar_core_ffi at: ${isar_core_path}" - local workspace_root=$(dirname $(dirname "${isar_core_path}")) + local workspace_root + workspace_root=$(dirname "$(dirname "${isar_core_path}")") build_isar_core "${isar_core_path}" "${workspace_root}" || return 1 diff --git a/scripts/bom_values.sh b/scripts/bom_values.sh index 00075bc90e..f514814dfd 100755 --- a/scripts/bom_values.sh +++ b/scripts/bom_values.sh @@ -10,7 +10,7 @@ BOM="${BOM_FILE:-stack-bom.toml}" section_for() { case "$1" in rust|dnssec_rust|flutter|flutter_min|go|go_min) echo toolchain ;; - xcode) echo macos ;; + xcode|xcode_dnix) echo macos ;; *) echo "Unknown BOM key: $1" >&2; return 2 ;; esac } @@ -30,8 +30,13 @@ value() { # These values are passed to toolchain actions in the release workflow. # Reject anything that is not a plain version so a data-file edit cannot # inject a branch, a range or shell syntax. - if [[ ! "$result" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then - echo "Invalid [$section] $key value '$result' in $BOM (expected x.y or x.y.z)" >&2 + if [[ "$key" == xcode || "$key" == xcode_dnix ]]; then + [[ "$result" =~ ^[0-9]+\.[0-9]+$ ]] || { + echo "Invalid [$section] $key value '$result' in $BOM (expected x.y)" >&2 + return 1 + } + elif [[ ! "$result" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Invalid [$section] $key value '$result' in $BOM (expected x.y.z)" >&2 return 1 fi printf '%s\n' "$result" @@ -39,7 +44,7 @@ value() { check_all() { local key - for key in rust dnssec_rust flutter flutter_min go go_min xcode; do + for key in rust dnssec_rust flutter flutter_min go go_min xcode xcode_dnix; do value "$key" >/dev/null done echo "BOM values OK" diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh index a86916d61b..e0ceef3a34 100755 --- a/scripts/install_macos_build_tools.sh +++ b/scripts/install_macos_build_tools.sh @@ -50,8 +50,6 @@ REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" bom_get() { "$SCRIPT_DIR/bom_values.sh" --get "$1" "$REPO_ROOT/stack-bom.toml" } -bash "$SCRIPT_DIR/install_xcode.sh" - echo "Installing Homebrew packages..." # Do not upgrade formulae that are already installed: a build machine keeps the versions it was set up with. export HOMEBREW_NO_INSTALL_UPGRADE=1 @@ -131,7 +129,7 @@ RUST_VERSION="${RUST_VERSION:-$(bom_get rust)}" RUST_VERSION="${RUST_VERSION:-1.99.1}" echo "Ensuring Rust $RUST_VERSION toolchain..." rustup toolchain install "$RUST_VERSION" -rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios --toolchain "$RUST_VERSION" >/dev/null 2>&1 || true +rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios aarch64-apple-ios-sim --toolchain "$RUST_VERSION" >/dev/null 2>&1 || true # Pin this checkout instead of changing the user's global rustup default; the # native-asset crates also carry their own rust-toolchain.toml. rustup override set "$RUST_VERSION" --path "$REPO_ROOT" >/dev/null 2>&1 || true @@ -157,6 +155,8 @@ if ! command -v cargo >/dev/null 2>&1; then die "cargo still not on PATH after rustup setup. Run 'rustup-init -y' manually, then re-run this script." fi +bash "$SCRIPT_DIR/install_xcode.sh" + echo "Verifying toolchain..." if command -v flutter >/dev/null 2>&1; then flutter --version @@ -194,9 +194,10 @@ BREW_PREFIX="$(brew --prefix)" grep -qF 'brew shellenv' "$ZSHRC" 2>/dev/null || \ printf 'eval "$(%s/bin/brew shellenv)"\n' "$BREW_PREFIX" >> "$ZSHRC" if [[ -n "$FLUTTER_PATH_TO_PERSIST" ]]; then + FLUTTER_PATH_ESCAPED="$(printf '%q' "$FLUTTER_PATH_TO_PERSIST")" if ! grep -qF "$FLUTTER_PATH_TO_PERSIST" "$ZSHRC" 2>/dev/null; then # %q keeps a user-supplied FLUTTER_DIR from becoming shell syntax. - printf 'export PATH=%q:$PATH\n' "$FLUTTER_PATH_TO_PERSIST" >> "$ZSHRC" + printf 'export PATH=%s:$PATH\n' "$FLUTTER_PATH_ESCAPED" >> "$ZSHRC" fi fi grep -qF '$HOME/.cargo/bin' "$ZSHRC" 2>/dev/null || \ diff --git a/scripts/linux/build_secure_storage_deps.sh b/scripts/linux/build_secure_storage_deps.sh index c58cd80d0e..b9c150049a 100755 --- a/scripts/linux/build_secure_storage_deps.sh +++ b/scripts/linux/build_secure_storage_deps.sh @@ -1,4 +1,5 @@ #!/usr/bin/env bash +set -euo pipefail if [ "${USE_SYSTEM_SECURE_STORAGE_DEPS:-0}" = "1" ]; then echo "USE_SYSTEM_SECURE_STORAGE_DEPS is set; skipping build of jsoncpp and libsecret (using system packages)" @@ -18,7 +19,7 @@ if ! [ -x "$(command -v git)" ]; then fi git -C jsoncpp pull origin $JSONCPP_TAG || git clone https://github.com/open-source-parsers/jsoncpp.git jsoncpp cd jsoncpp || exit 1 -git checkout $JSONCPP_TAG +git checkout "$JSONCPP_TAG" || exit 1 mkdir -p build cd build || exit 1 cmake -DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DCMAKE_BUILD_TYPE=release -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=ON -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" .. || exit 1 @@ -33,7 +34,7 @@ cd "$LINUX_DIRECTORY" || exit 1 cd build || exit 1 git -C libsecret pull origin $LIBSECRET_TAG || git clone https://git.cypherstack.com/Cypher_Stack/libsecret.git libsecret cd libsecret || exit 1 -git checkout $LIBSECRET_TAG +git checkout "$LIBSECRET_TAG" || exit 1 if ! [ -x "$(command -v meson)" ]; then echo 'Error: meson is not installed.' >&2 exit 1 diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index da3c912db6..6ed70ad75b 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -32,6 +32,9 @@ void _fail(String m) { stdout.writeln('[FAIL] $m'); } +final _sectionHeader = RegExp(r'^\[([^\]]+)\][ \t]*(#.*)?$'); +final _pluginsHeader = RegExp(r'^\[plugins\][ \t]*(#.*)?$', multiLine: true); + /// Minimal TOML reader: `[section]` headers and `key = "value"` lines. Map> _readBom(String text) { final result = >{}; @@ -39,8 +42,9 @@ Map> _readBom(String text) { for (final raw in text.split('\n')) { final line = raw.trim(); if (line.isEmpty || line.startsWith('#')) continue; - if (line.startsWith('[') && line.endsWith(']')) { - section = line.substring(1, line.length - 1); + final header = _sectionHeader.firstMatch(line); + if (header != null) { + section = header.group(1)!; result.putIfAbsent(section, () => {}); continue; } @@ -156,10 +160,7 @@ Map _lockRefs() { /// A duplicate `[plugins]` table makes _readBom silently last-wins and makes /// --update append a second block, so refuse both modes early. void _requireSinglePluginsSection(String text) { - final count = RegExp( - r'^\[plugins\][ \t]*$', - multiLine: true, - ).allMatches(text).length; + final count = _pluginsHeader.allMatches(text).length; if (count > 1) { stderr.writeln( 'Duplicate [plugins] sections in $_bomFile; keep exactly one.', @@ -181,12 +182,9 @@ Future _update() async { // Without a pubspec.yaml we cannot tell which app is configured; keep the // old behaviour and update every plugin the lock knows about. final updateable = declared.isEmpty ? _pluginNames.toSet() : declared; - final header = RegExp( - r'^\[plugins\][ \t]*$', - multiLine: true, - ).firstMatch(text); + final header = _pluginsHeader.firstMatch(text); final start = header?.start ?? -1; - if (start < 0 && text.contains('[plugins]')) { + if (start < 0 && RegExp(r'\[plugins\]').hasMatch(text)) { stderr.writeln( 'Found [plugins] outside a table header; refusing to update', ); From 96675c3295d89e985ff87c5d7e668503d6c6098e Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:40:50 +0200 Subject: [PATCH 044/107] build: reject source mode where dnix cannot run - Fail early for PREBUILTS=0 on Intel macOS and on a Linux host outside nix develop/direnv, instead of failing inside build_app.sh. - Require the same Nix/direnv host for Android source builds, and correct the Android error message. --- Makefile | 15 +++++++++++++-- docs/building/make-flow.md | 2 +- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 2b1710b455..9176ffe6d7 100644 --- a/Makefile +++ b/Makefile @@ -358,6 +358,17 @@ endif ifneq ($(filter $(PREBUILTS),0 1),$(PREBUILTS)) $(error PREBUILTS must be 0 or 1) endif +ifeq ($(PREBUILTS),0) + ifeq ($(PLATFORM),Darwin) + ifneq ($(filter arm64 aarch64,$(UNAME_M)),$(UNAME_M)) + $(error PREBUILTS=0 (dnix source) requires Apple Silicon on macOS; use the default PREBUILTS=1) + endif + else ifeq ($(PLATFORM),Linux) + ifeq ($(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),) + $(error PREBUILTS=0 (dnix source) requires nix develop or direnv on Linux; use PREBUILTS=1) + endif + endif +endif ifneq ($(filter MINGW% MSYS%,$(PLATFORM)),) ifeq ($(PREBUILTS),0) $(error build-windows uses verified dnix prebuilts; run build_app.sh for source mode) @@ -366,14 +377,14 @@ endif # Android source builds through dnix need an x86_64 Linux host. Every other # host defaults to the verified prebuilts; x86_64 Linux follows PREBUILTS. ANDROID_ARCH := $(shell uname -m 2>/dev/null) -ANDROID_SOURCE_OK := $(and $(filter Linux,$(PLATFORM)),$(filter x86_64,$(ANDROID_ARCH))) +ANDROID_SOURCE_OK := $(and $(filter Linux,$(PLATFORM)),$(filter x86_64,$(ANDROID_ARCH)),$(filter nix direnv,$(TOOLCHAIN_EFFECTIVE))) ANDROID_PREBUILTS ?= $(if $(ANDROID_SOURCE_OK),$(PREBUILTS),1) ifneq ($(filter $(ANDROID_PREBUILTS),0 1),$(ANDROID_PREBUILTS)) $(error ANDROID_PREBUILTS must be 0 or 1) endif ifeq ($(ANDROID_PREBUILTS),0) ifeq ($(strip $(ANDROID_SOURCE_OK)),) - $(error ANDROID_PREBUILTS=0 needs an x86_64 Linux host; use the default prebuilt mode) + $(error ANDROID_PREBUILTS=0 needs an x86_64 Linux host in nix develop or direnv; use the default prebuilt mode) endif endif # Linux only: SYSTEM_DEPS=1 uses the system libsecret/jsoncpp packages instead of building them (like the CI image). diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index f418c4e3b2..2271e6c37d 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -110,5 +110,5 @@ flowchart TD | macOS/Linux/iOS CI | `1` | verified prebuilts (`-d`) | | Windows | `1` (fixed) | verified prebuilts (`-d`) | | Android on macOS | `1` (default; source builds need an x86_64 Linux host) | verified prebuilts (`-d`) | -| Android on x86_64 Linux | follows `PREBUILTS` | source by default | +| Android on x86_64 Linux in Nix/direnv | follows `PREBUILTS` | source by default | | Android on non-x86_64 Linux | `1` (default; source builds need x86_64) | verified prebuilts (`-d`) | From 8a34d365111308d14ddc6bd8e68bb70647fe6385 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:49:44 +0200 Subject: [PATCH 045/107] docs: name the recommended Xcode for app builds The BOM recommends 27.1 for ordinary builds; 27.0 remains the dnix source requirement. --- docs/building/macos.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/building/macos.md b/docs/building/macos.md index 7fe76d790c..be53b45bbc 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -25,7 +25,7 @@ manual/Homebrew path. | What | Needed for | |---|---| | [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 minimum, 3.47.4 recommended | Manual and Homebrew modes | -| Your usual Xcode | Building the app, in both dnix modes | +| Your usual Xcode (27.1 recommended) | Building the app, in both dnix modes | | Xcode **27.0**, release build **27A266a**, installed next to your usual Xcode | Source mode (dnix), in every host mode: dnix builds its four packages with it, including during `flutter test`. It doesn't need to be selected; see [Install Xcode 27.0](#install-xcode-270) | | [Homebrew](https://brew.sh/) packages below | Manual and Homebrew modes | | [Rustup](https://rustup.rs/) | Manual and Homebrew modes, in both dnix modes | From ed437ddb410272e8df646cf0313133183aef1096 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:00:13 +0200 Subject: [PATCH 046/107] build: use the resolved Flutter binary in every target preflight build-windows, build-android and build-ios checked `flutter` on PATH while the rest of the recipe used $(FLUTTER); an explicit FLUTTER path failed the preflight even though the build would work. --- Makefile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 9176ffe6d7..9c4f625ffd 100644 --- a/Makefile +++ b/Makefile @@ -484,7 +484,7 @@ build-linux: require-version check-linux toolchain-check check-reqs ## Build Lin # Windows uses verified dnix prebuilts; source mode needs Nix inside WSL2 and is # driven by build_app.sh directly, not by this target. build-windows: require-version check-windows toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) - @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } + @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @cd scripts && bash prebuild.sh @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d @"$(FLUTTER)" pub get @@ -504,7 +504,7 @@ android-dev-key: ## Create a throw-away debug signing key if android/key.propert fi build-android: require-version toolchain-check ## Build Android APKs (requires android/key.properties; prebuilt dnix on macOS, Linux follows PREBUILTS) - @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } + @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @[ -f android/key.properties ] || { echo >&2 "[ERROR] android/key.properties is missing. Run 'make android-dev-key' for a local throw-away key; never distribute APKs signed with it."; exit 1; } @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } @cd scripts && bash prebuild.sh @@ -514,7 +514,7 @@ build-android: require-version toolchain-check ## Build Android APKs (requires a # iOS: same steps as the "build-ios" CI job (device build, no code signing). Run on macOS with Xcode. build-ios: require-version toolchain-check check-reqs-macos check-sdk-macos ## Build iOS Runner.app without code signing (same steps as CI) - @command -v flutter >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } + @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @xcrun --sdk iphoneos --show-sdk-path >/dev/null 2>&1 || { echo >&2 "[ERROR] iOS SDK not available; install the iOS platform in Xcode."; exit 1; } @cd scripts && bash prebuild.sh @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) env $(IOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) From a638d03decf8cb052c5c763bef515f3f6b408239 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:37:41 +0200 Subject: [PATCH 047/107] build: use the detected architecture consistently Use UNAME_M for the Android source guard and the Linux bundle path, so callers and tests can override it, and keep the help text in sync with the new source-mode defaults. --- Makefile | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index 9c4f625ffd..d52519a248 100644 --- a/Makefile +++ b/Makefile @@ -376,7 +376,7 @@ ifneq ($(filter MINGW% MSYS%,$(PLATFORM)),) endif # Android source builds through dnix need an x86_64 Linux host. Every other # host defaults to the verified prebuilts; x86_64 Linux follows PREBUILTS. -ANDROID_ARCH := $(shell uname -m 2>/dev/null) +ANDROID_ARCH := $(UNAME_M) ANDROID_SOURCE_OK := $(and $(filter Linux,$(PLATFORM)),$(filter x86_64,$(ANDROID_ARCH)),$(filter nix direnv,$(TOOLCHAIN_EFFECTIVE))) ANDROID_PREBUILTS ?= $(if $(ANDROID_SOURCE_OK),$(PREBUILTS),1) ifneq ($(filter $(ANDROID_PREBUILTS),0 1),$(ANDROID_PREBUILTS)) @@ -392,7 +392,7 @@ SYSTEM_DEPS ?= 0 ifneq ($(filter $(SYSTEM_DEPS),0 1),$(SYSTEM_DEPS)) $(error SYSTEM_DEPS must be 0 or 1) endif -LINUX_ARCH := $(shell uname -m | sed -e 's/x86_64/x64/' -e 's/aarch64/arm64/') +LINUX_ARCH := $(shell printf '%s' '$(UNAME_M)' | sed -e 's/x86_64/x64/' -e 's/aarch64/arm64/') LINUX_BUNDLE ?= build/linux/$(LINUX_ARCH)/release/bundle clean-app: ## Remove app build output (build/, Pods) but keep .dart_tool/hooks_runner, so the next build is fast @@ -407,7 +407,7 @@ clean-native: ## Remove only the native-asset build outputs (forces the Rust/Go/ @rm -rf .dart_tool/hooks_runner build/native_assets @echo "[OK] Removed .dart_tool/hooks_runner and build/native_assets." -build-macos: require-version toolchain-check check-reqs-macos check-sdk-macos ## Build macOS release (source by default; PREBUILTS=1 uses verified prebuilts) +build-macos: require-version toolchain-check check-reqs-macos check-sdk-macos ## Build macOS release (source on Apple Silicon; PREBUILTS=1 uses verified prebuilts) @echo "--- Configuring project (scripts/build_app.sh)..." @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) @echo "--- Resolving dependencies..." @@ -441,7 +441,7 @@ diagnose-env-macos: ## Print macOS build env and tool resolution @echo "NIX_CFLAGS_LINK=$${NIX_CFLAGS_LINK:-}" build-linux: export PUB_CACHE := $(LINUX_PUB_CACHE) -build-linux: require-version check-linux toolchain-check check-reqs ## Build Linux Release through Flutter native-assets hooks +build-linux: require-version check-linux toolchain-check check-reqs ## Build Linux release (source in Nix/direnv; PREBUILTS=1 uses verified prebuilts) @echo "--- Running prebuild bootstrap..." @cd scripts && bash prebuild.sh @echo "--- Generating config..." @@ -503,7 +503,7 @@ android-dev-key: ## Create a throw-away debug signing key if android/key.propert printf 'storeFile=../dev-keystore.jks\nstorePassword=android\nkeyPassword=android\nkeyAlias=devkey\n' > android/key.properties; \ fi -build-android: require-version toolchain-check ## Build Android APKs (requires android/key.properties; prebuilt dnix on macOS, Linux follows PREBUILTS) +build-android: require-version toolchain-check ## Build Android APKs (requires android/key.properties; prebuilt unless x86_64 Linux in Nix/direnv follows PREBUILTS) @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @[ -f android/key.properties ] || { echo >&2 "[ERROR] android/key.properties is missing. Run 'make android-dev-key' for a local throw-away key; never distribute APKs signed with it."; exit 1; } @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } From e5360ad04cf7f7468e572cdc7150a6ff6ff9509e Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:43:09 +0200 Subject: [PATCH 048/107] build: check protoc and finish the source-mode docs - Require protoc in check-reqs; it is needed by the native-asset hooks. - Add protobuf, Go and patchelf to the manual host instructions. - Say plainly that source mode needs Apple Silicon and Nix/direnv, and keep the help text consistent with that. --- Makefile | 7 ++++--- README.md | 2 +- docs/building/linux.md | 2 +- docs/building/macos.md | 4 ++-- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Makefile b/Makefile index d52519a248..6f495b90a2 100644 --- a/Makefile +++ b/Makefile @@ -197,8 +197,8 @@ require-version: ## Fail unless VERSION/BUILD_NUM are valid and above the latest check-reqs: ## Verify essential build tools @echo "Checking core prerequisites..." - @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } - @[ -n "$(DART)" ] && command -v "$(DART)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Dart not installed."; exit 1; } + @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed. Use 'nix develop' (recommended) or add Flutter to PATH."; exit 1; } + @[ -n "$(DART)" ] && command -v "$(DART)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Dart not installed. It ships with Flutter; use 'nix develop' (recommended)."; exit 1; } @command -v rustup >/dev/null 2>&1 || { echo >&2 "[ERROR] rustup not installed."; exit 1; } @rustup which rustc >/dev/null 2>&1 || { echo >&2 "[ERROR] rustc toolchain not available via rustup."; exit 1; } @rustup which cargo >/dev/null 2>&1 || { echo >&2 "[ERROR] cargo toolchain not available via rustup."; exit 1; } @@ -207,6 +207,7 @@ check-reqs: ## Verify essential build tools @command -v cargo >/dev/null 2>&1 || [ -x "$$HOME/.cargo/bin/cargo" ] || { echo >&2 "[ERROR] 'cargo' is not on PATH (rustup shims missing from ~/.cargo/bin). Run 'rustup-init -y', then open a new terminal."; exit 1; } @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed."; exit 1; } @command -v cmake >/dev/null 2>&1 || { echo >&2 "[ERROR] CMake not installed."; exit 1; } + @command -v protoc >/dev/null 2>&1 || { echo >&2 "[ERROR] protoc not installed (protobuf); use 'nix develop' or your package manager."; exit 1; } @command -v meson >/dev/null 2>&1 || { \ if [ "$(PLATFORM)" = "Darwin" ]; then \ echo >&2 "[ERROR] Meson not installed. Use 'nix develop' (recommended) or run 'make bootstrap-macos'."; \ @@ -262,7 +263,7 @@ endif check-reqs-macos: check-reqs ## Verify macOS-specific tools are available in PATH ifeq ($(PLATFORM),Darwin) @echo "Checking macOS-specific tools in PATH..." - @rustup run $(RUST_VERSION) rustc -vV >/dev/null 2>&1 || { echo >&2 "[ERROR] Rust $(RUST_VERSION) toolchain not available. Run 'nix develop' (recommended) or 'make bootstrap-macos'."; exit 1; } + @rustup run $(RUST_VERSION) rustc -vV >/dev/null 2>&1 || { echo >&2 "[ERROR] Rust $(RUST_VERSION) toolchain not available. Run 'rustup toolchain install $(RUST_VERSION)', or use 'nix develop'/'make bootstrap-macos'."; exit 1; } @command -v pod >/dev/null 2>&1 || { echo >&2 "[ERROR] CocoaPods (pod) not installed."; exit 1; } @command -v xcodebuild >/dev/null 2>&1 || { echo >&2 "[ERROR] xcodebuild not available."; exit 1; } @echo "[OK] macOS-specific toolchain is available." diff --git a/README.md b/README.md index 6729bc557c..1ff02a48f9 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ by Nix; the flake uses the Xcode selected by `xcode-select`. Use this only when you are not building through Nix/flake. -1. Install host tools: +1. With Homebrew installed, install the host tools: - `make bootstrap-macos` (alias: `make bootstrap-brew`) 2. Run build: - Open a new terminal (or run `source ~/.zshrc`) so the Homebrew and diff --git a/docs/building/linux.md b/docs/building/linux.md index f3541eebbf..48873da2eb 100644 --- a/docs/building/linux.md +++ b/docs/building/linux.md @@ -27,7 +27,7 @@ dnix enables the Nix flake features it needs when it invokes Nix. ```sh sudo apt-get update sudo apt-get install build-essential clang cmake ninja-build pkg-config \ - git curl unzip xz-utils python3 libgtk-3-dev liblzma-dev libssl-dev \ + git curl unzip xz-utils python3 protobuf-compiler patchelf libgtk-3-dev liblzma-dev libssl-dev \ libjsoncpp-dev libsecret-1-dev ``` diff --git a/docs/building/macos.md b/docs/building/macos.md index be53b45bbc..c9b223fe43 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -26,14 +26,14 @@ manual/Homebrew path. |---|---| | [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 minimum, 3.47.4 recommended | Manual and Homebrew modes | | Your usual Xcode (27.1 recommended) | Building the app, in both dnix modes | -| Xcode **27.0**, release build **27A266a**, installed next to your usual Xcode | Source mode (dnix), in every host mode: dnix builds its four packages with it, including during `flutter test`. It doesn't need to be selected; see [Install Xcode 27.0](#install-xcode-270) | +| Xcode **27.0**, release build **27A266a**, installed next to your usual Xcode | Source mode (dnix) on Apple Silicon, in every host mode: dnix builds its four packages with it, including during `flutter test`. It doesn't need to be selected; see [Install Xcode 27.0](#install-xcode-270) | | [Homebrew](https://brew.sh/) packages below | Manual and Homebrew modes | | [Rustup](https://rustup.rs/) | Manual and Homebrew modes, in both dnix modes | | [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet, manual and Homebrew modes | | [Nix](https://nixos.org/download/) | Source mode (dnix) in every host mode; not needed with `-d` | ```sh -brew install autoconf automake libtool cmake cocoapods meson ninja pkg-config +brew install autoconf automake libtool cmake cocoapods go meson ninja pkg-config protobuf rustup toolchain install "$(scripts/bom_values.sh --get rust)" rustup target add aarch64-apple-darwin x86_64-apple-darwin \ aarch64-apple-ios aarch64-apple-ios-sim From ff7e071694c113fd9534fcf71d71b68984244e8a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:45:47 +0200 Subject: [PATCH 049/107] build: close the remaining security nits - Never chmod a FlutterMacOS.framework under /nix/store; only build/temp copies are made writable. - Refuse to sudo-select an Xcode outside /Applications or owned by the user. - Create rustup shims with no global default; the checkout override still selects the BOM toolchain. - Create the Android test key with 0600 permissions and warn at build time when it is in use. - Reject duplicate BOM tables in bom_values.sh, make the zshrc guard use the escaped path, and extend the make -n guard to +-prefixed recipes. --- .github/workflows/test.yaml | 4 ++-- Makefile | 6 +++++- flake.nix | 10 ++++++---- scripts/bom_values.sh | 6 ++++++ scripts/install_macos_build_tools.sh | 5 +++-- scripts/install_xcode.sh | 6 ++++++ 6 files changed, 28 insertions(+), 9 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index e4104f9059..029db943de 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -143,8 +143,8 @@ jobs: - name: Check the Makefile dry-runs run: | bash scripts/bom_values.sh --check - if grep -nE '^[^#]*\$\(MAKE\)' Makefile; then - echo 'Makefile uses $(MAKE), which runs even under make -n' >&2 + if grep -nE '^[^#]*\$\(MAKE\)|^[[:space:]]*\+' Makefile; then + echo 'Makefile uses a construct that runs even under make -n' >&2 exit 1 fi make help diff --git a/Makefile b/Makefile index 6f495b90a2..3f8f35ffef 100644 --- a/Makefile +++ b/Makefile @@ -497,16 +497,20 @@ build-windows: require-version check-windows toolchain-check ## Build Windows re # are not suitable for distribution. android-dev-key: ## Create a throw-away debug signing key if android/key.properties is missing (never use for releases) @command -v keytool >/dev/null 2>&1 || { echo >&2 "[ERROR] keytool not found; install a JDK."; exit 1; } - @if [ ! -f android/key.properties ]; then \ + @umask 077; if [ ! -f android/key.properties ]; then \ echo "[INFO] android/key.properties missing: creating a throw-away debug key (not for releases)"; \ keytool -genkeypair -keystore android/dev-keystore.jks -storetype pkcs12 -storepass android -keypass android \ -alias devkey -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=Stack Wallet dev build" -noprompt && \ printf 'storeFile=../dev-keystore.jks\nstorePassword=android\nkeyPassword=android\nkeyAlias=devkey\n' > android/key.properties; \ fi + @chmod 600 android/key.properties android/dev-keystore.jks 2>/dev/null || true build-android: require-version toolchain-check ## Build Android APKs (requires android/key.properties; prebuilt unless x86_64 Linux in Nix/direnv follows PREBUILTS) @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @[ -f android/key.properties ] || { echo >&2 "[ERROR] android/key.properties is missing. Run 'make android-dev-key' for a local throw-away key; never distribute APKs signed with it."; exit 1; } + @if grep -q '^keyAlias=devkey$$' android/key.properties 2>/dev/null; then \ + echo "[WARN] Signing with the public throw-away dev key; this APK is for local testing only."; \ + fi @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } @cd scripts && bash prebuild.sh @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p android -a $(APP_NAME) $(if $(filter 1,$(ANDROID_PREBUILTS)),-d) diff --git a/flake.nix b/flake.nix index f13140304e..fd8dd224e4 100644 --- a/flake.nix +++ b/flake.nix @@ -181,9 +181,8 @@ ln -sf /usr/bin/clang++ "$NIX_BIN/clang++" # SMART LIPO & XCRUN WRAPPER - # lipo wrapper: the Nix store copy of FlutterMacOS.framework is - # read-only, so make its containing dir writable before handing - # off to the real lipo. + # lipo wrapper: a build-tree copy of FlutterMacOS.framework may + # need to be made writable. Never touch the Nix store path. rm -f "$NIX_BIN/lipo" "$NIX_BIN/xcrun" cat > "$NIX_BIN/lipo" <<'LIPO_EOF' @@ -191,7 +190,10 @@ for arg in "$@"; do if [[ "$arg" == *"FlutterMacOS.framework"* ]]; then framework="''${arg%%FlutterMacOS.framework*}FlutterMacOS.framework" - chmod -R u+w "$framework" 2>/dev/null || true + case "$framework" in + "$PWD"/*|"''${TMPDIR:-/tmp}"/*) chmod -R u+w "$framework" 2>/dev/null || true ;; + *) ;; + esac fi done exec /usr/bin/lipo "$@" diff --git a/scripts/bom_values.sh b/scripts/bom_values.sh index f514814dfd..188bbd7d1d 100755 --- a/scripts/bom_values.sh +++ b/scripts/bom_values.sh @@ -27,6 +27,12 @@ value() { echo "Missing [$section] $key in $BOM" >&2 return 1 } + local count + count="$(grep -cE "^\[$section\][[:space:]]*(#.*)?$" "$BOM" || true)" + [ "$count" -le 1 ] || { + echo "Duplicate [$section] tables in $BOM; keep exactly one." >&2 + return 1 + } # These values are passed to toolchain actions in the release workflow. # Reject anything that is not a plain version so a data-file edit cannot # inject a branch, a range or shell syntax. diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh index e0ceef3a34..a7355f51e3 100755 --- a/scripts/install_macos_build_tools.sh +++ b/scripts/install_macos_build_tools.sh @@ -141,7 +141,7 @@ rustup override set "$RUST_VERSION" --path "$REPO_ROOT" >/dev/null 2>&1 || true if [ ! -x "$HOME/.cargo/bin/cargo" ]; then echo "cargo shims missing in ~/.cargo/bin; creating them via rustup-init..." if command -v rustup-init >/dev/null 2>&1; then - rustup-init -y --no-modify-path --default-toolchain "$RUST_VERSION" || true + rustup-init -y --no-modify-path --default-toolchain none || true else die "rustup-init not found. Run 'brew install rustup', then re-run this script." fi @@ -195,7 +195,8 @@ grep -qF 'brew shellenv' "$ZSHRC" 2>/dev/null || \ printf 'eval "$(%s/bin/brew shellenv)"\n' "$BREW_PREFIX" >> "$ZSHRC" if [[ -n "$FLUTTER_PATH_TO_PERSIST" ]]; then FLUTTER_PATH_ESCAPED="$(printf '%q' "$FLUTTER_PATH_TO_PERSIST")" - if ! grep -qF "$FLUTTER_PATH_TO_PERSIST" "$ZSHRC" 2>/dev/null; then + if ! grep -qF "$FLUTTER_PATH_TO_PERSIST" "$ZSHRC" 2>/dev/null && \ + ! grep -qF "$FLUTTER_PATH_ESCAPED" "$ZSHRC" 2>/dev/null; then # %q keeps a user-supplied FLUTTER_DIR from becoming shell syntax. printf 'export PATH=%s:$PATH\n' "$FLUTTER_PATH_ESCAPED" >> "$ZSHRC" fi diff --git a/scripts/install_xcode.sh b/scripts/install_xcode.sh index 482d823cb9..fee1d6c686 100755 --- a/scripts/install_xcode.sh +++ b/scripts/install_xcode.sh @@ -63,6 +63,12 @@ else - Or download the .xip directly from https://developer.apple.com/download/all/?q=xcode" fi echo "Xcode found at $XCODE_APP. Setting xcode-select path..." + case "$XCODE_APP" in + /Applications/*) ;; + *) die "[ERROR] Refusing to sudo-select an Xcode outside /Applications: $XCODE_APP" ;; + esac + [[ "$(/usr/bin/stat -f '%Su' -L "$XCODE_APP")" == "root" ]] || \ + die "[ERROR] Refusing to sudo-select a user-owned Xcode bundle: $XCODE_APP" sudo xcode-select -s "$XCODE_APP/Contents/Developer" JUST_SELECTED=1 fi From 499bff000cb7df925146d89db19c8f96225dee12 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:54:44 +0200 Subject: [PATCH 050/107] build: align the flake toolchain and BOM checks - Install the BOM DNSSEC Rust toolchain in the dev shell, reuse the Apple wrapper directory across nested shells, and fail closed if the wrappers are incomplete. - Guard FLUTTER_ROOT when Flutter is absent and stop direnv from rewriting flake.lock on entry. - Expose the dev shell as a flake check and document that Nix mode uses nixpkgs' Go while the BOM Go pin is the CI/Docker version. - Run verify-bom before the macOS, Linux and iOS builds. --- .envrc | 2 +- Makefile | 6 +++--- flake.nix | 49 +++++++++++++++++++++++++++++++++++++++---------- stack-bom.toml | 2 +- 4 files changed, 44 insertions(+), 15 deletions(-) diff --git a/.envrc b/.envrc index 9da8b0f825..b2382c8a70 100644 --- a/.envrc +++ b/.envrc @@ -2,5 +2,5 @@ # failing with a blocked .envrc; use make bootstrap-macos and PREBUILTS=1. if has nix; then watch_file stack-bom.toml flake.nix flake.lock - use flake + use flake --no-write-lock-file fi diff --git a/Makefile b/Makefile index 3f8f35ffef..3c900841c6 100644 --- a/Makefile +++ b/Makefile @@ -408,7 +408,7 @@ clean-native: ## Remove only the native-asset build outputs (forces the Rust/Go/ @rm -rf .dart_tool/hooks_runner build/native_assets @echo "[OK] Removed .dart_tool/hooks_runner and build/native_assets." -build-macos: require-version toolchain-check check-reqs-macos check-sdk-macos ## Build macOS release (source on Apple Silicon; PREBUILTS=1 uses verified prebuilts) +build-macos: require-version verify-bom toolchain-check check-reqs-macos check-sdk-macos ## Build macOS release (source on Apple Silicon; PREBUILTS=1 uses verified prebuilts) @echo "--- Configuring project (scripts/build_app.sh)..." @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) @echo "--- Resolving dependencies..." @@ -442,7 +442,7 @@ diagnose-env-macos: ## Print macOS build env and tool resolution @echo "NIX_CFLAGS_LINK=$${NIX_CFLAGS_LINK:-}" build-linux: export PUB_CACHE := $(LINUX_PUB_CACHE) -build-linux: require-version check-linux toolchain-check check-reqs ## Build Linux release (source in Nix/direnv; PREBUILTS=1 uses verified prebuilts) +build-linux: require-version verify-bom check-linux toolchain-check check-reqs ## Build Linux release (source in Nix/direnv; PREBUILTS=1 uses verified prebuilts) @echo "--- Running prebuild bootstrap..." @cd scripts && bash prebuild.sh @echo "--- Generating config..." @@ -518,7 +518,7 @@ build-android: require-version toolchain-check ## Build Android APKs (requires a @"$(FLUTTER)" build apk --split-per-abi --release # iOS: same steps as the "build-ios" CI job (device build, no code signing). Run on macOS with Xcode. -build-ios: require-version toolchain-check check-reqs-macos check-sdk-macos ## Build iOS Runner.app without code signing (same steps as CI) +build-ios: require-version verify-bom toolchain-check check-reqs-macos check-sdk-macos ## Build iOS Runner.app without code signing (same steps as CI) @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @xcrun --sdk iphoneos --show-sdk-path >/dev/null 2>&1 || { echo >&2 "[ERROR] iOS SDK not available; install the iOS platform in Xcode."; exit 1; } @cd scripts && bash prebuild.sh diff --git a/flake.nix b/flake.nix index fd8dd224e4..41eabe0860 100644 --- a/flake.nix +++ b/flake.nix @@ -3,8 +3,9 @@ inputs = { # Pinned to a specific nixpkgs rev for reproducible Flutter/Rust toolchain - # versions. Update via `nix flake lock --update-input nixpkgs` and re-test - # `make build-macos` and `make build-linux` before bumping. + # versions. To bump it, edit the rev below and run `nix flake lock` + # (`--update-input` cannot move a rev-pinned URL), then re-test + # `make build-macos` and `make build-linux`. nixpkgs.url = "github:NixOS/nixpkgs/b1b875982b17dabde9b4a37f3e229e74913e6db3"; flake-utils.url = "github:numtide/flake-utils"; }; @@ -23,6 +24,12 @@ if builtins.isString v && builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+" v != null then v else throw "stack-bom.toml: [toolchain].rust must be a version string"; + dnssecRustVersion = let + v = bom.toolchain.dnssec_rust or (throw "stack-bom.toml: missing [toolchain].dnssec_rust"); + in + if builtins.isString v && builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+" v != null + then v + else throw "stack-bom.toml: [toolchain].dnssec_rust must be a version string"; clangMajor = lib.versions.major pkgs.llvmPackages.clang.version; commonPackages = with pkgs; [ @@ -67,6 +74,8 @@ in { + checks.dev-shell = self.devShells.${system}.default; + devShells.default = pkgs.mkShell { buildInputs = commonPackages ++ linuxPackages ++ macPackages; @@ -92,17 +101,23 @@ # The standalone Dart in the Nix Flutter wrapper cannot find the Flutter SDK on its own, # so `dart run`/`dart pub` in a Flutter project fail ("Flutter users should use flutter pub"). - FLUTTER_BIN_DIR="$(cd "$(dirname "$(command -v flutter)")" && pwd -P)" - export FLUTTER_ROOT="$(dirname "$FLUTTER_BIN_DIR")" + if command -v flutter >/dev/null 2>&1; then + FLUTTER_BIN_DIR="$(cd "$(dirname "$(command -v flutter)")" && pwd -P)" + export FLUTTER_ROOT="$(dirname "$FLUTTER_BIN_DIR")" + else + echo "[WARN] flutter not on PATH; FLUTTER_ROOT not set." >&2 + fi # ========================================== # RUST TOOLCHAIN AUTOMATION # Host Rust toolchain; native-assets crates select their own pinned toolchain. # ========================================== - if ! rustup toolchain list | grep -q "${rustVersion}"; then - echo "Initializing Rust toolchain (this happens only once)..." - rustup toolchain install --no-self-update ${rustVersion} - fi + for v in ${rustVersion} ${dnssecRustVersion}; do + if ! rustup toolchain list | grep -q "^$v"; then + echo "Initializing Rust $v (this happens only once)..." + rustup toolchain install --no-self-update "$v" + fi + done # Pin this checkout without replacing the user's global rustup default. rustup override set ${rustVersion} --path "$APP_PROJECT_ROOT_DIR" >/dev/null 2>&1 || true @@ -174,7 +189,13 @@ # A repo-writable directory on PATH would let anything that can # write to the checkout shadow tools for the rest of the session. - if NIX_BIN="$(/usr/bin/mktemp -d "''${TMPDIR:-/tmp}/stackwallet-nix-bin.XXXXXX")"; then + if [ -n "''${STACKWALLET_NIX_BIN:-}" ] && [ -x "$STACKWALLET_NIX_BIN/xcrun" ]; then + NIX_BIN="$STACKWALLET_NIX_BIN" + case ":$PATH:" in + *":$NIX_BIN:"*) ;; + *) export PATH="$NIX_BIN:$PATH" ;; + esac + elif NIX_BIN="$(/usr/bin/mktemp -d "''${TMPDIR:-/tmp}/stackwallet-nix-bin.XXXXXX")"; then ln -sf /usr/bin/clang "$NIX_BIN/cc" ln -sf /usr/bin/clang++ "$NIX_BIN/c++" ln -sf /usr/bin/clang "$NIX_BIN/clang" @@ -221,7 +242,15 @@ exec /usr/bin/xcrun "\$@" XCRUN_EOF chmod +x "$NIX_BIN/xcrun" - export PATH="$NIX_BIN:$PATH" + if [ -x "$NIX_BIN/lipo" ] && [ -x "$NIX_BIN/xcrun" ]; then + export STACKWALLET_NIX_BIN="$NIX_BIN" + case ":$PATH:" in + *":$NIX_BIN:"*) ;; + *) export PATH="$NIX_BIN:$PATH" ;; + esac + else + echo "[WARN] Apple tool wrappers are incomplete; using the Nix tools." >&2 + fi else echo "[WARN] Could not create the Apple tool wrapper directory; using the Nix tools." >&2 fi diff --git a/stack-bom.toml b/stack-bom.toml index 1f133b1a0c..6a16a11a1e 100644 --- a/stack-bom.toml +++ b/stack-bom.toml @@ -8,7 +8,7 @@ flutter_min = "3.47.2" # minimum for pubspec.template.yaml and the release wor dart_prefix = "3.13" # Dart bundled with Flutter 3.47.x rust = "1.99.1" # installed through rustup, pinned by the native plugins dnssec_rust = "1.90.0" # OpenAlias/DNSSEC builds from source in every app -go = "1.24.13" # exact Go used by CI; Dockerfile mirrors it +go = "1.24.13" # CI/Docker pin; nix develop uses nixpkgs' newer Go go_min = "1.24.1" # flutter_mwebd's minimum on the Flutter host [macos] From 491cc3f72e830e66b7454a225df9dfdb88a5c004 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:02:52 +0200 Subject: [PATCH 051/107] build: close the final audit findings - Normalize empty PREBUILTS/ANDROID_PREBUILTS to the platform default and validate APP_NAME before any recipe runs. - Resolve relative FLUTTER paths and fall back to PATH Dart when the SDK has no sibling dart. - Compare BUILD_NUM against the newest numeric build tag and warn when only nonnumeric tags exist. - Reject duplicate BOM keys; accept quoted/tabbed pubspec dependency keys; require dart_prefix. - Keep the Windows junction cleanup, avoid deleting a user cargo config, and honor CARGO_HOME for sccache. - Correct the remaining docs claims (signing, CI -d, -i, DEVELOPER_DIR). --- Makefile | 60 ++++++++++++++++++++++---------------- docs/building/linux.md | 4 +-- docs/building/make-flow.md | 6 ++-- scripts/bom_values.sh | 11 +++++-- tool/verify_bom.dart | 24 ++++++++------- 5 files changed, 62 insertions(+), 43 deletions(-) diff --git a/Makefile b/Makefile index 3c900841c6..cd28f9b80f 100644 --- a/Makefile +++ b/Makefile @@ -4,6 +4,10 @@ # ============================================================================== APP_NAME ?= stack_wallet +override APP_NAME := $(strip $(APP_NAME)) +ifneq ($(filter $(APP_NAME),stack_wallet stack_duo campfire),$(APP_NAME)) + $(error APP_NAME must be stack_wallet, stack_duo or campfire) +endif # build_app.sh asks before replacing generated app files because some # version/build combinations can delete wallet data. Keep that prompt # interactive unless the caller explicitly opts in. @@ -26,16 +30,16 @@ ifneq ($(strip $(DART)),) $(error DART must not contain spaces; put it on PATH instead) endif endif -FLUTTER_BIN := $(if $(FLUTTER),$(FLUTTER),$(shell command -v flutter 2>/dev/null)) +FLUTTER_BIN := $(if $(FLUTTER),$(if $(findstring /,$(FLUTTER)),$(abspath $(FLUTTER)),$(FLUTTER)),$(shell command -v flutter 2>/dev/null)) # A Flutter SDK ships its own Dart next to the flutter binary; an explicit # FLUTTER path should not require a second DART= argument. -DART_BIN := $(if $(DART),$(DART),$(if $(filter /%,$(FLUTTER_BIN)),$(wildcard $(dir $(FLUTTER_BIN))dart),$(shell command -v dart 2>/dev/null))) +DART_BIN := $(if $(DART),$(if $(findstring /,$(DART)),$(abspath $(DART)),$(DART)),$(if $(filter /%,$(FLUTTER_BIN)),$(or $(wildcard $(dir $(FLUTTER_BIN))dart),$(shell command -v dart 2>/dev/null)),$(shell command -v dart 2>/dev/null))) FLUTTER := $(FLUTTER_BIN) DART := $(DART_BIN) # Child scripts call bare `flutter`/`dart`; keep them on the binaries checked # above instead of whatever PATH would otherwise resolve. -ifneq ($(filter /%,$(FLUTTER)),) -export PATH := $(dir $(FLUTTER)):$(PATH) +ifneq ($(filter /%,$(FLUTTER_BIN)),) +export PATH := $(dir $(FLUTTER_BIN)):$(PATH) endif ifneq ($(filter /%,$(DART)),) export PATH := $(dir $(DART)):$(PATH) @@ -187,12 +191,11 @@ endif require-version: ## Fail unless VERSION/BUILD_NUM are valid and above the latest release tag @printf '%s' '$(VERSION)' | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$$' || { echo >&2 "[ERROR] VERSION must be x.y.z (got '$(VERSION)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } @printf '%s' '$(BUILD_NUM)' | grep -Eq '^[0-9]+$$' || { echo >&2 "[ERROR] BUILD_NUM must be numeric (got '$(BUILD_NUM)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } - @latest="$$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1)"; \ + @latest="$$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | sed -n 's/^build_\([0-9][0-9]*\)$$/\1/p' | head -n1)"; \ if [ -n "$$latest" ]; then \ - latest_num="$${latest#build_}"; \ - case "$$latest_num" in (*[!0-9]*) ;; (*) \ - [ "$(BUILD_NUM)" -gt "$$latest_num" ] || { echo >&2 "[ERROR] BUILD_NUM $(BUILD_NUM) is not above the latest release tag $$latest."; exit 1; }; \ - esac; \ + [ "$(BUILD_NUM)" -gt "$$latest" ] || { echo >&2 "[ERROR] BUILD_NUM $(BUILD_NUM) is not above the latest release tag build_$$latest."; exit 1; }; \ + elif git tag -l 'build_*' 2>/dev/null | grep -q .; then \ + echo "[WARN] No numeric build_* tag found; cannot compare BUILD_NUM."; \ fi check-reqs: ## Verify essential build tools @@ -298,7 +301,7 @@ else @exit 1 endif -SCCACHE_CARGO_CONFIG ?= $(HOME)/.cargo/config.toml +SCCACHE_CARGO_CONFIG ?= $(if $(CARGO_HOME),$(CARGO_HOME),$(HOME)/.cargo)/config.toml sccache-setup: ## Opt-in: use sccache for the Rust/C builds run by native-asset hooks (writes ~/.cargo/config.toml if absent) @command -v sccache >/dev/null 2>&1 || { echo >&2 "[ERROR] sccache not installed (brew install sccache)."; exit 1; } @@ -326,9 +329,8 @@ clean: ## Remove artifacts and fix permissions @echo "Cleaning Flutter and Rust artifacts..." @chflags -R nouchg build/ macos/ 2>/dev/null || true @chmod -R u+w build/ macos/ 2>/dev/null || true - @if [ -n "$(FLUTTER)" ] && [ -f pubspec.yaml ]; then "$(FLUTTER)" clean; else echo "[WARN] Flutter not available; skipped 'flutter clean'."; fi + @if [ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 && [ -f pubspec.yaml ]; then "$(FLUTTER)" clean || echo "[WARN] 'flutter clean' failed; continuing."; else echo "[WARN] Flutter not available; skipped 'flutter clean'."; fi @rm -rf macos/Pods macos/Podfile.lock ios/Pods ios/Podfile.lock build/ - @rm -f .cargo/config.toml @echo "Cleaning local pub cache residues..." @chmod -R u+w "$(LINUX_PUB_CACHE)/git/" 2>/dev/null || true @find "$(LINUX_PUB_CACHE)/git/" -type d \( -name "build" -o -name "target" \) -path "*flutter_lib*" -exec rm -rf {} + 2>/dev/null || true @@ -343,18 +345,22 @@ clean: ## Remove artifacts and fix permissions # PREBUILTS=0 builds them with Nix and verifies the hashes. ifeq ($(PLATFORM),Darwin) ifeq ($(filter arm64 aarch64,$(UNAME_M)),$(UNAME_M)) - PREBUILTS ?= 0 + PREBUILTS_DEFAULT := 0 else - PREBUILTS ?= 1 + PREBUILTS_DEFAULT := 1 endif else ifeq ($(PLATFORM),Linux) ifeq ($(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),$(TOOLCHAIN_EFFECTIVE)) - PREBUILTS ?= 0 + PREBUILTS_DEFAULT := 0 else - PREBUILTS ?= 1 + PREBUILTS_DEFAULT := 1 endif else - PREBUILTS ?= 1 + PREBUILTS_DEFAULT := 1 +endif +PREBUILTS ?= $(PREBUILTS_DEFAULT) +ifeq ($(strip $(PREBUILTS)),) + override PREBUILTS := $(PREBUILTS_DEFAULT) endif ifneq ($(filter $(PREBUILTS),0 1),$(PREBUILTS)) $(error PREBUILTS must be 0 or 1) @@ -379,7 +385,11 @@ endif # host defaults to the verified prebuilts; x86_64 Linux follows PREBUILTS. ANDROID_ARCH := $(UNAME_M) ANDROID_SOURCE_OK := $(and $(filter Linux,$(PLATFORM)),$(filter x86_64,$(ANDROID_ARCH)),$(filter nix direnv,$(TOOLCHAIN_EFFECTIVE))) -ANDROID_PREBUILTS ?= $(if $(ANDROID_SOURCE_OK),$(PREBUILTS),1) +ANDROID_PREBUILTS_DEFAULT := $(if $(ANDROID_SOURCE_OK),$(PREBUILTS),1) +ANDROID_PREBUILTS ?= $(ANDROID_PREBUILTS_DEFAULT) +ifeq ($(strip $(ANDROID_PREBUILTS)),) + override ANDROID_PREBUILTS := $(ANDROID_PREBUILTS_DEFAULT) +endif ifneq ($(filter $(ANDROID_PREBUILTS),0 1),$(ANDROID_PREBUILTS)) $(error ANDROID_PREBUILTS must be 0 or 1) endif @@ -410,7 +420,7 @@ clean-native: ## Remove only the native-asset build outputs (forces the Rust/Go/ build-macos: require-version verify-bom toolchain-check check-reqs-macos check-sdk-macos ## Build macOS release (source on Apple Silicon; PREBUILTS=1 uses verified prebuilts) @echo "--- Configuring project (scripts/build_app.sh)..." - @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) + @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a "$(APP_NAME)" $(if $(filter 1,$(PREBUILTS)),-d) @echo "--- Resolving dependencies..." @env $(MACOS_ENV_UNSET) "$(FLUTTER)" pub get @cd scripts && env $(MACOS_ENV_UNSET) bash prebuild.sh @@ -447,7 +457,7 @@ build-linux: require-version verify-bom check-linux toolchain-check check-reqs # @cd scripts && bash prebuild.sh @echo "--- Generating config..." @if [ -z "$(PROTOC_PATH)" ]; then echo "[ERROR] protoc not found!"; exit 1; fi - @cd scripts && $(if $(filter 1,$(CONFIRM)),yes yes |,) BUILD_ISAR_FROM_SOURCE=0 PROTOC="$(PROTOC_PATH)" ./build_app.sh -a $(APP_NAME) -p linux -v $(VERSION) -b $(BUILD_NUM) $(if $(filter 1,$(PREBUILTS)),-d) $(if $(filter 1,$(SYSTEM_DEPS)),-s) + @cd scripts && $(if $(filter 1,$(CONFIRM)),yes yes |,) BUILD_ISAR_FROM_SOURCE=0 PROTOC="$(PROTOC_PATH)" ./build_app.sh -a "$(APP_NAME)" -p linux -v $(VERSION) -b $(BUILD_NUM) $(if $(filter 1,$(PREBUILTS)),-d) $(if $(filter 1,$(SYSTEM_DEPS)),-s) @# Flutter 3.47.x hooks only see a filtered environment, so PROTOC (exported by the flake) never @# reaches cargo build scripts. Some crates (prost-build 0.7) ship a generic-Linux protoc that cannot @# run on NixOS. cargo reads [env] from .cargo/config.toml found from the package dir upwards, which @@ -487,14 +497,14 @@ build-linux: require-version verify-bom check-linux toolchain-check check-reqs # build-windows: require-version check-windows toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @cd scripts && bash prebuild.sh - @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a $(APP_NAME) -d + @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a "$(APP_NAME)" -d @"$(FLUTTER)" pub get @"$(FLUTTER)" build windows --release # Android: same steps as the "build-android" CI job, without the signing secrets. Needs the Android SDK/NDK # (ANDROID_SDK_ROOT) and Java; the CI image ghcr.io//stackwallet-ci:android is built from the Dockerfile -# (docker build --target android). Without android/key.properties a throw-away debug key is created, so the APKs -# are not suitable for distribution. +# (docker build --target android). Run `make android-dev-key` to create a throw-away debug key when +# android/key.properties is missing; build-android requires that file and the APKs are not suitable for distribution. android-dev-key: ## Create a throw-away debug signing key if android/key.properties is missing (never use for releases) @command -v keytool >/dev/null 2>&1 || { echo >&2 "[ERROR] keytool not found; install a JDK."; exit 1; } @umask 077; if [ ! -f android/key.properties ]; then \ @@ -513,7 +523,7 @@ build-android: require-version toolchain-check ## Build Android APKs (requires a fi @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } @cd scripts && bash prebuild.sh - @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p android -a $(APP_NAME) $(if $(filter 1,$(ANDROID_PREBUILTS)),-d) + @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p android -a "$(APP_NAME)" $(if $(filter 1,$(ANDROID_PREBUILTS)),-d) @"$(FLUTTER)" pub get @"$(FLUTTER)" build apk --split-per-abi --release @@ -522,6 +532,6 @@ build-ios: require-version verify-bom toolchain-check check-reqs-macos check-sdk @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @xcrun --sdk iphoneos --show-sdk-path >/dev/null 2>&1 || { echo >&2 "[ERROR] iOS SDK not available; install the iOS platform in Xcode."; exit 1; } @cd scripts && bash prebuild.sh - @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) env $(IOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a $(APP_NAME) $(if $(filter 1,$(PREBUILTS)),-d) + @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) env $(IOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a "$(APP_NAME)" $(if $(filter 1,$(PREBUILTS)),-d) @env $(IOS_ENV_UNSET) "$(FLUTTER)" pub get @env $(IOS_ENV_UNSET) "$(FLUTTER)" build ios --release --no-codesign diff --git a/docs/building/linux.md b/docs/building/linux.md index 48873da2eb..15c6fbd130 100644 --- a/docs/building/linux.md +++ b/docs/building/linux.md @@ -16,8 +16,8 @@ These steps build the Linux desktop app and the Android app on Ubuntu 24.04 **Rustup:** every app builds its DNSSEC resolver with Rust **1.90.0**, and Stack Wallet builds Xelis with Rust **1.99.1**. The build hooks install these -toolchains on first use. To install DNSSEC's ahead of time, run -`rustup toolchain install 1.90.0`. +toolchains on first use. To install both ahead of time, run +`rustup toolchain install 1.90.0 1.99.1`. **Nix:** check `nix --version` from the same environment that runs Flutter. dnix enables the Nix flake features it needs when it invokes Nix. diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index 2271e6c37d..8db4fe8fc6 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -107,8 +107,8 @@ flowchart TD | Linux developer, non-Nix host | `1` | verified prebuilts (`-d`) | | iOS developer, Apple Silicon | `0` | source, verified; needs Nix + Xcode 27.0 | | iOS developer, Intel | `1` | verified prebuilts (`-d`) | -| macOS/Linux/iOS CI | `1` | verified prebuilts (`-d`) | +| macOS/Linux/iOS CI | `1` (explicit `-d`) | verified prebuilts (`-d`) | | Windows | `1` (fixed) | verified prebuilts (`-d`) | -| Android on macOS | `1` (default; source builds need an x86_64 Linux host) | verified prebuilts (`-d`) | +| Android on macOS | `1` (default; source needs x86_64 Linux in Nix/direnv) | verified prebuilts (`-d`) | | Android on x86_64 Linux in Nix/direnv | follows `PREBUILTS` | source by default | -| Android on non-x86_64 Linux | `1` (default; source builds need x86_64) | verified prebuilts (`-d`) | +| Android on non-x86_64 Linux | `1` (default; source needs x86_64 Linux in Nix/direnv) | verified prebuilts (`-d`) | diff --git a/scripts/bom_values.sh b/scripts/bom_values.sh index 188bbd7d1d..05b359314e 100755 --- a/scripts/bom_values.sh +++ b/scripts/bom_values.sh @@ -9,7 +9,7 @@ BOM="${BOM_FILE:-stack-bom.toml}" section_for() { case "$1" in - rust|dnssec_rust|flutter|flutter_min|go|go_min) echo toolchain ;; + rust|dnssec_rust|flutter|flutter_min|dart_prefix|go|go_min) echo toolchain ;; xcode|xcode_dnix) echo macos ;; *) echo "Unknown BOM key: $1" >&2; return 2 ;; esac @@ -33,10 +33,15 @@ value() { echo "Duplicate [$section] tables in $BOM; keep exactly one." >&2 return 1 } + count="$(sed -n "/^\[$section\]/,/^\[/p" "$BOM" | grep -cE "^${key}[[:space:]]*=" || true)" + [ "$count" -le 1 ] || { + echo "Duplicate [$section] $key in $BOM; keep exactly one." >&2 + return 1 + } # These values are passed to toolchain actions in the release workflow. # Reject anything that is not a plain version so a data-file edit cannot # inject a branch, a range or shell syntax. - if [[ "$key" == xcode || "$key" == xcode_dnix ]]; then + if [[ "$key" == xcode || "$key" == xcode_dnix || "$key" == dart_prefix ]]; then [[ "$result" =~ ^[0-9]+\.[0-9]+$ ]] || { echo "Invalid [$section] $key value '$result' in $BOM (expected x.y)" >&2 return 1 @@ -50,7 +55,7 @@ value() { check_all() { local key - for key in rust dnssec_rust flutter flutter_min go go_min xcode xcode_dnix; do + for key in rust dnssec_rust flutter flutter_min dart_prefix go go_min xcode xcode_dnix; do value "$key" >/dev/null done echo "BOM values OK" diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 6ed70ad75b..e29961b826 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -112,25 +112,26 @@ Set _declaredPlugins() { final lines = file.readAsLinesSync(); final declared = {}; for (final sectionName in ['dependencies:', 'dependency_overrides:']) { - final start = lines.indexWhere((l) => l.trimRight() == sectionName); + final header = RegExp('^${RegExp.escape(sectionName)}\\s*(#.*)?\$'); + final start = lines.indexWhere((l) => header.hasMatch(l.trimRight())); if (start < 0) continue; - int? indent; + String? indent; for (var i = start + 1; i < lines.length; i++) { final line = lines[i]; if (line.trim().isEmpty || line.trimLeft().startsWith('#')) continue; - if (!line.startsWith(' ')) break; - indent = line.length - line.trimLeft().length; + final m = RegExp(r'^[ \t]+').firstMatch(line); + if (m == null) break; + indent = m.group(0); break; } if (indent == null) continue; for (var i = start + 1; i < lines.length; i++) { final line = lines[i]; if (line.trim().isEmpty || line.trimLeft().startsWith('#')) continue; - if (!line.startsWith(' ')) break; - final currentIndent = line.length - line.trimLeft().length; - if (currentIndent < indent) break; + final currentIndent = RegExp(r'^[ \t]*').firstMatch(line)!.group(0)!; + if (currentIndent.length < indent.length) break; if (currentIndent != indent) continue; - final m = RegExp(r'^[ ]*(\w+):').firstMatch(line); + final m = RegExp(r'''^[ \t]*["']?(\w+)["']?\s*:''').firstMatch(line); if (m != null && _pluginNames.contains(m.group(1))) { declared.add(m.group(1)!); } @@ -282,10 +283,13 @@ Future main(List args) async { } else { _ok('Flutter $v'); } - if (d.startsWith(tc['dart_prefix'] ?? '')) { + final prefix = tc['dart_prefix'] ?? ''; + if (prefix.isEmpty) { + _fail('dart_prefix is missing from $_bomFile'); + } else if (d.startsWith('$prefix.')) { _ok('Dart $d'); } else { - _fail('Dart $d does not match ${tc['dart_prefix']}.x'); + _fail('Dart $d does not match $prefix.x'); } } on FormatException { _fail('could not parse flutter --version --machine output'); From 211e12bbca97e6ba706f73d52d5cc546b4bd134e Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:07:32 +0200 Subject: [PATCH 052/107] build: require Nix on PATH, not an active dev shell Source mode is implemented by build_app.sh invoking `nix`; the dev shell is only the supported way to get the rest of the host tools. The Makefile guard conflated TOOLCHAIN_EFFECTIVE with Nix availability, so a Linux or macOS host with Nix installed but no active nix develop/direnv shell was rejected. Check `command -v nix` instead, keep the dev shell as the recommended toolchain, and document that PREBUILTS=0 works outside it when the host prerequisites pass. --- Makefile | 12 +++++++----- docs/building/linux.md | 2 +- docs/building/macos.md | 2 +- docs/building/make-flow.md | 9 +++++---- 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/Makefile b/Makefile index cd28f9b80f..9a2c66b5cc 100644 --- a/Makefile +++ b/Makefile @@ -52,6 +52,7 @@ endif # supported value; an unrelated exported PLATFORM must not change the defaults. UNAME_S := $(shell uname -s 2>/dev/null) UNAME_M := $(shell uname -m 2>/dev/null) +NIX_BIN := $(shell command -v nix 2>/dev/null) PLATFORM ?= $(UNAME_S) ifneq ($(PLATFORM),Darwin) ifneq ($(PLATFORM),Linux) @@ -370,9 +371,10 @@ ifeq ($(PREBUILTS),0) ifneq ($(filter arm64 aarch64,$(UNAME_M)),$(UNAME_M)) $(error PREBUILTS=0 (dnix source) requires Apple Silicon on macOS; use the default PREBUILTS=1) endif - else ifeq ($(PLATFORM),Linux) - ifeq ($(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),) - $(error PREBUILTS=0 (dnix source) requires nix develop or direnv on Linux; use PREBUILTS=1) + endif + ifeq ($(filter Darwin Linux,$(PLATFORM)),$(PLATFORM)) + ifeq ($(strip $(NIX_BIN)),) + $(error PREBUILTS=0 (dnix source) needs Nix on PATH; install Nix or run 'nix develop') endif endif endif @@ -384,7 +386,7 @@ endif # Android source builds through dnix need an x86_64 Linux host. Every other # host defaults to the verified prebuilts; x86_64 Linux follows PREBUILTS. ANDROID_ARCH := $(UNAME_M) -ANDROID_SOURCE_OK := $(and $(filter Linux,$(PLATFORM)),$(filter x86_64,$(ANDROID_ARCH)),$(filter nix direnv,$(TOOLCHAIN_EFFECTIVE))) +ANDROID_SOURCE_OK := $(and $(filter Linux,$(PLATFORM)),$(filter x86_64,$(ANDROID_ARCH)),$(strip $(NIX_BIN))) ANDROID_PREBUILTS_DEFAULT := $(if $(ANDROID_SOURCE_OK),$(PREBUILTS),1) ANDROID_PREBUILTS ?= $(ANDROID_PREBUILTS_DEFAULT) ifeq ($(strip $(ANDROID_PREBUILTS)),) @@ -395,7 +397,7 @@ ifneq ($(filter $(ANDROID_PREBUILTS),0 1),$(ANDROID_PREBUILTS)) endif ifeq ($(ANDROID_PREBUILTS),0) ifeq ($(strip $(ANDROID_SOURCE_OK)),) - $(error ANDROID_PREBUILTS=0 needs an x86_64 Linux host in nix develop or direnv; use the default prebuilt mode) + $(error ANDROID_PREBUILTS=0 needs an x86_64 Linux host with Nix on PATH; use the default prebuilt mode) endif endif # Linux only: SYSTEM_DEPS=1 uses the system libsecret/jsoncpp packages instead of building them (like the CI image). diff --git a/docs/building/linux.md b/docs/building/linux.md index 15c6fbd130..cc23e4fb1a 100644 --- a/docs/building/linux.md +++ b/docs/building/linux.md @@ -11,7 +11,7 @@ These steps build the Linux desktop app and the Android app on Ubuntu 24.04 | The [Ubuntu packages](#ubuntu-packages) below | Every build | | [Rustup](https://rustup.rs/) | Every app, in both modes | | [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet | -| [Nix](https://nixos.org/download/) | Source mode, the default; not needed with `-d` | +| [Nix](https://nixos.org/download/) | Source mode; Nix must be on `PATH` (the dev shell provides it); not needed with `-d` | | The [Android tools](#android-tools) below | Android builds | **Rustup:** every app builds its DNSSEC resolver with Rust **1.90.0**, and diff --git a/docs/building/macos.md b/docs/building/macos.md index c9b223fe43..70543e777f 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -30,7 +30,7 @@ manual/Homebrew path. | [Homebrew](https://brew.sh/) packages below | Manual and Homebrew modes | | [Rustup](https://rustup.rs/) | Manual and Homebrew modes, in both dnix modes | | [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet, manual and Homebrew modes | -| [Nix](https://nixos.org/download/) | Source mode (dnix) in every host mode; not needed with `-d` | +| [Nix](https://nixos.org/download/) | Source mode (dnix); Nix must be on `PATH` (the dev shell provides it); not needed with `-d` | ```sh brew install autoconf automake libtool cmake cocoapods go meson ninja pkg-config protobuf diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index 8db4fe8fc6..1775584d87 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -50,8 +50,9 @@ first-launch setup. An already-selected Xcode is left untouched. Use ## 2. Build `VERSION` and `BUILD_NUM` are required. dnix source is the default on Apple -Silicon macOS and inside Nix/direnv on Linux; Intel macOS, non-Nix Linux, CI and -Windows use the verified prebuilts. +Silicon macOS and inside Nix/direnv on Linux; source also works with Nix on +`PATH`. Intel macOS, Linux outside Nix/direnv, CI and Windows default to the +verified prebuilts. ```mermaid flowchart TD @@ -104,11 +105,11 @@ flowchart TD | macOS developer, Apple Silicon | `0` | source, verified; needs Nix + Xcode 27.0 | | macOS developer, Intel | `1` | verified prebuilts (`-d`) | | Linux developer in Nix/direnv | `0` | source, verified; needs Nix | -| Linux developer, non-Nix host | `1` | verified prebuilts (`-d`) | +| Linux developer outside Nix/direnv | `1` (default) | verified prebuilts (`-d`); set `PREBUILTS=0` with Nix on `PATH` for source | | iOS developer, Apple Silicon | `0` | source, verified; needs Nix + Xcode 27.0 | | iOS developer, Intel | `1` | verified prebuilts (`-d`) | | macOS/Linux/iOS CI | `1` (explicit `-d`) | verified prebuilts (`-d`) | | Windows | `1` (fixed) | verified prebuilts (`-d`) | | Android on macOS | `1` (default; source needs x86_64 Linux in Nix/direnv) | verified prebuilts (`-d`) | -| Android on x86_64 Linux in Nix/direnv | follows `PREBUILTS` | source by default | +| Android on x86_64 Linux with Nix on `PATH` | follows `PREBUILTS` | source by default inside Nix/direnv | | Android on non-x86_64 Linux | `1` (default; source needs x86_64 Linux in Nix/direnv) | verified prebuilts (`-d`) | From 3cc33d0de7d952abf9d3e1495ed72b71468055ce Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:07:47 +0200 Subject: [PATCH 053/107] docs: label source mode by Nix availability The diagram now says Nix on PATH, matching the Makefile guard and the build_app.sh check. --- docs/building/make-flow.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index 1775584d87..1be2865fd4 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -79,7 +79,7 @@ flowchart TD LINUX --> LC["checks
require-version · check-linux
toolchain-check · check-reqs"] LC --> LP{"PREBUILTS"} - LP -- "0 Nix/direnv" --> LS["source (Nix)"] + LP -- "0 Nix on PATH" --> LS["source (Nix)"] LP -- "1 host" --> LB["prebuilt -d"] LS --> LR["prebuild.sh
build_app.sh -p linux
flutter build linux · bundle"] LB --> LR From c5ecff38da30dcc34a7a75bdacf83c10df18d31a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:56:12 +0200 Subject: [PATCH 054/107] build: make source mode Nix/direnv-only - PREBUILTS=0 now requires TOOLCHAIN=nix or direnv. Homebrew, manual and host toolchains default to prebuilt and reject source mode explicitly. - Android source follows the same rule: x86_64 Linux in Nix/direnv only. - Document the split in the Makefile help, README, host guides and flow diagram, and state that stack-bom.toml is a toolchain/plugin pin file, not a Homebrew package manifest. --- Makefile | 39 +++++++++++++++++++++----------------- README.md | 18 +++++++++++------- docs/building/linux.md | 7 +++++-- docs/building/macos.md | 7 +++++-- docs/building/make-flow.md | 37 +++++++++++++++++++----------------- stack-bom.toml | 4 +++- 6 files changed, 66 insertions(+), 46 deletions(-) diff --git a/Makefile b/Makefile index 9a2c66b5cc..d2cf4e15fc 100644 --- a/Makefile +++ b/Makefile @@ -94,6 +94,9 @@ ifeq ($(TOOLCHAIN),auto) else TOOLCHAIN_EFFECTIVE := $(TOOLCHAIN) endif +# Source builds are only exposed through the Nix/direnv toolchain. Homebrew, +# manual and host toolchains are prebuilt-only. +SOURCE_TOOLCHAIN := $(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)) # Linux builds use a project-local pub cache so cargo finds the repo-local # .cargo/config.toml that carries PROTOC through Flutter's filtered hook environment. # Other targets leave PUB_CACHE unset, so Flutter uses its normal per-user cache @@ -339,23 +342,21 @@ clean: ## Remove artifacts and fix permissions # --- PLATFORM BUILDS --- -# dnix mode. Apple Silicon macOS and Linux inside the Nix/direnv shell build -# the pinned native libraries from source by default (the Nix-primary developer -# path). Intel macOS, a non-Nix Linux host, Windows and CI use verified -# prebuilts. PREBUILTS=1 passes -d and needs no Nix for those four libraries; -# PREBUILTS=0 builds them with Nix and verifies the hashes. -ifeq ($(PLATFORM),Darwin) +# dnix mode. Only the Nix/direnv toolchain can build the pinned native +# libraries from source: it is the default on Apple Silicon macOS and on Linux +# inside nix develop/direnv. Intel macOS, brew/manual/host toolchains, Windows +# and CI use verified prebuilts. PREBUILTS=1 passes -d and needs no Nix for +# those four libraries; PREBUILTS=0 builds them with Nix and verifies hashes. +ifeq ($(strip $(SOURCE_TOOLCHAIN)),) + PREBUILTS_DEFAULT := 1 +else ifeq ($(PLATFORM),Darwin) ifeq ($(filter arm64 aarch64,$(UNAME_M)),$(UNAME_M)) PREBUILTS_DEFAULT := 0 else PREBUILTS_DEFAULT := 1 endif else ifeq ($(PLATFORM),Linux) - ifeq ($(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),$(TOOLCHAIN_EFFECTIVE)) - PREBUILTS_DEFAULT := 0 - else - PREBUILTS_DEFAULT := 1 - endif + PREBUILTS_DEFAULT := 0 else PREBUILTS_DEFAULT := 1 endif @@ -367,6 +368,9 @@ ifneq ($(filter $(PREBUILTS),0 1),$(PREBUILTS)) $(error PREBUILTS must be 0 or 1) endif ifeq ($(PREBUILTS),0) + ifeq ($(strip $(SOURCE_TOOLCHAIN)),) + $(error PREBUILTS=0 requires TOOLCHAIN=nix or direnv; use PREBUILTS=1 with Homebrew/manual) + endif ifeq ($(PLATFORM),Darwin) ifneq ($(filter arm64 aarch64,$(UNAME_M)),$(UNAME_M)) $(error PREBUILTS=0 (dnix source) requires Apple Silicon on macOS; use the default PREBUILTS=1) @@ -374,7 +378,7 @@ ifeq ($(PREBUILTS),0) endif ifeq ($(filter Darwin Linux,$(PLATFORM)),$(PLATFORM)) ifeq ($(strip $(NIX_BIN)),) - $(error PREBUILTS=0 (dnix source) needs Nix on PATH; install Nix or run 'nix develop') + $(error PREBUILTS=0 (dnix source) needs Nix on PATH; run 'nix develop' or use PREBUILTS=1) endif endif endif @@ -383,10 +387,11 @@ ifneq ($(filter MINGW% MSYS%,$(PLATFORM)),) $(error build-windows uses verified dnix prebuilts; run build_app.sh for source mode) endif endif -# Android source builds through dnix need an x86_64 Linux host. Every other -# host defaults to the verified prebuilts; x86_64 Linux follows PREBUILTS. +# Android source builds through dnix need an x86_64 Linux host in Nix/direnv. +# Every other host defaults to the verified prebuilts; that combination +# follows PREBUILTS. ANDROID_ARCH := $(UNAME_M) -ANDROID_SOURCE_OK := $(and $(filter Linux,$(PLATFORM)),$(filter x86_64,$(ANDROID_ARCH)),$(strip $(NIX_BIN))) +ANDROID_SOURCE_OK := $(and $(filter Linux,$(PLATFORM)),$(filter x86_64,$(ANDROID_ARCH)),$(strip $(SOURCE_TOOLCHAIN)),$(strip $(NIX_BIN))) ANDROID_PREBUILTS_DEFAULT := $(if $(ANDROID_SOURCE_OK),$(PREBUILTS),1) ANDROID_PREBUILTS ?= $(ANDROID_PREBUILTS_DEFAULT) ifeq ($(strip $(ANDROID_PREBUILTS)),) @@ -397,7 +402,7 @@ ifneq ($(filter $(ANDROID_PREBUILTS),0 1),$(ANDROID_PREBUILTS)) endif ifeq ($(ANDROID_PREBUILTS),0) ifeq ($(strip $(ANDROID_SOURCE_OK)),) - $(error ANDROID_PREBUILTS=0 needs an x86_64 Linux host with Nix on PATH; use the default prebuilt mode) + $(error ANDROID_PREBUILTS=0 requires TOOLCHAIN=nix or direnv on x86_64 Linux; use the prebuilt mode) endif endif # Linux only: SYSTEM_DEPS=1 uses the system libsecret/jsoncpp packages instead of building them (like the CI image). @@ -420,7 +425,7 @@ clean-native: ## Remove only the native-asset build outputs (forces the Rust/Go/ @rm -rf .dart_tool/hooks_runner build/native_assets @echo "[OK] Removed .dart_tool/hooks_runner and build/native_assets." -build-macos: require-version verify-bom toolchain-check check-reqs-macos check-sdk-macos ## Build macOS release (source on Apple Silicon; PREBUILTS=1 uses verified prebuilts) +build-macos: require-version verify-bom toolchain-check check-reqs-macos check-sdk-macos ## Build macOS release (source in Nix/direnv on Apple Silicon; PREBUILTS=1 uses verified prebuilts) @echo "--- Configuring project (scripts/build_app.sh)..." @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a "$(APP_NAME)" $(if $(filter 1,$(PREBUILTS)),-d) @echo "--- Resolving dependencies..." diff --git a/README.md b/README.md index 1ff02a48f9..0edae42097 100644 --- a/README.md +++ b/README.md @@ -60,10 +60,10 @@ using. - `make bootstrap` (runs `nix develop`), or - `nix develop` directly, or - `direnv allow` once, if you use direnv with the included `.envrc`. -2. Check the Xcode requirement. Source builds are the default on Apple - Silicon and need Xcode **27.0** (build 27A266a); with any other Xcode pass - `PREBUILTS=1`. `make bootstrap-xcode` selects an installed full Xcode and - `make verify-bom` checks the host. +2. Check the Xcode requirement. Source builds are the default in Nix/direnv + on Apple Silicon and need Xcode **27.0** (build 27A266a); with any other + Xcode pass `PREBUILTS=1`. `make bootstrap-xcode` selects an installed full + Xcode and `make verify-bom` checks the host. 3. Run build (pass the release version and a build number; `make` refuses to guess): - `make build-macos VERSION=x.y.z BUILD_NUM=nnn` @@ -85,8 +85,9 @@ Use this only when you are not building through Nix/flake. - `make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1` - Add `CONFIRM=1` for a non-interactive run. -`PREBUILTS=1` uses the verified prebuilts and needs no Nix for the four dnix -libraries. +`PREBUILTS=1` is required with Homebrew/manual: those toolchains cannot build +the four dnix libraries from source. It uses the verified prebuilts and needs +no Nix for them. The Homebrew bootstrap installs the native build tools and configures the BOM Rust version for Flutter's native-assets hooks. It replaces the former local @@ -98,5 +99,8 @@ plugin build is needed. Install the prerequisites from [Building on macOS](docs/building/macos.md) yourself, then run `make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1`. +Manual builds are prebuilt-only; source mode requires Nix/direnv. `make check-reqs-macos` reports what is missing (`make check-sdk-macos` checks -full Xcode); `TOOLCHAIN=manual` makes the choice explicit. Omit `PREBUILTS=1` only if you also have Nix for the source build. +full Xcode); `TOOLCHAIN=manual` makes the choice explicit. Use the +Nix/direnv toolchain for a source build; manual and Homebrew builds are +prebuilt-only. diff --git a/docs/building/linux.md b/docs/building/linux.md index cc23e4fb1a..f944729772 100644 --- a/docs/building/linux.md +++ b/docs/building/linux.md @@ -11,9 +11,12 @@ These steps build the Linux desktop app and the Android app on Ubuntu 24.04 | The [Ubuntu packages](#ubuntu-packages) below | Every build | | [Rustup](https://rustup.rs/) | Every app, in both modes | | [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet | -| [Nix](https://nixos.org/download/) | Source mode; Nix must be on `PATH` (the dev shell provides it); not needed with `-d` | +| [Nix](https://nixos.org/download/) | Source mode only with Nix/direnv; not needed with `-d` | | The [Android tools](#android-tools) below | Android builds | +Homebrew/manual toolchains are prebuilt-only: use `PREBUILTS=1`; source mode +requires Nix/direnv. + **Rustup:** every app builds its DNSSEC resolver with Rust **1.90.0**, and Stack Wallet builds Xelis with Rust **1.99.1**. The build hooks install these toolchains on first use. To install both ahead of time, run @@ -99,7 +102,7 @@ Enable KVM for hardware-accelerated emulation. skipped it, run `(cd scripts/linux && bash build_secp256k1.sh)` before starting the app. -Android source builds through dnix need an x86_64 Linux host. +Android source builds through dnix need an x86_64 Linux host in Nix/direnv. ## Prepare a release bundle diff --git a/docs/building/macos.md b/docs/building/macos.md index 70543e777f..f8a34e5e6f 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -26,11 +26,11 @@ manual/Homebrew path. |---|---| | [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 minimum, 3.47.4 recommended | Manual and Homebrew modes | | Your usual Xcode (27.1 recommended) | Building the app, in both dnix modes | -| Xcode **27.0**, release build **27A266a**, installed next to your usual Xcode | Source mode (dnix) on Apple Silicon, in every host mode: dnix builds its four packages with it, including during `flutter test`. It doesn't need to be selected; see [Install Xcode 27.0](#install-xcode-270) | +| Xcode **27.0**, release build **27A266a**, installed next to your usual Xcode | Source mode (dnix) with Nix/direnv on Apple Silicon: dnix builds its four packages with it, including during `flutter test`. It doesn't need to be selected; see [Install Xcode 27.0](#install-xcode-270) | | [Homebrew](https://brew.sh/) packages below | Manual and Homebrew modes | | [Rustup](https://rustup.rs/) | Manual and Homebrew modes, in both dnix modes | | [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet, manual and Homebrew modes | -| [Nix](https://nixos.org/download/) | Source mode (dnix); Nix must be on `PATH` (the dev shell provides it); not needed with `-d` | +| [Nix](https://nixos.org/download/) | Source mode (dnix) only with Nix/direnv; not needed with `-d` | ```sh brew install autoconf automake libtool cmake cocoapods go meson ninja pkg-config protobuf @@ -39,6 +39,9 @@ rustup target add aarch64-apple-darwin x86_64-apple-darwin \ aarch64-apple-ios aarch64-apple-ios-sim ``` +Homebrew and manual toolchains are prebuilt-only: use `PREBUILTS=1`; they +cannot build the dnix libraries from source. Source mode requires Nix/direnv. + Check `nix --version` from the same environment that runs Flutter, and use `flutter doctor` to check the Apple SDK and CocoaPods setup. iOS device builds also need your usual signing configuration. The app's deployment targets are diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index 1be2865fd4..8e0554deff 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -49,10 +49,10 @@ first-launch setup. An already-selected Xcode is left untouched. Use ## 2. Build -`VERSION` and `BUILD_NUM` are required. dnix source is the default on Apple -Silicon macOS and inside Nix/direnv on Linux; source also works with Nix on -`PATH`. Intel macOS, Linux outside Nix/direnv, CI and Windows default to the -verified prebuilts. +`VERSION` and `BUILD_NUM` are required. dnix source is only available through +the Nix/direnv toolchain: it is the default on Apple Silicon macOS and inside +Nix/direnv on Linux. Homebrew, manual and host toolchains, Intel macOS, CI and +Windows use the verified prebuilts. ```mermaid flowchart TD @@ -65,22 +65,22 @@ flowchart TD MAC --> MC["checks
require-version · check-sdk-macos
toolchain-check · check-reqs-macos"] MC --> MP{"PREBUILTS"} - MP -- "0 Apple Silicon" --> MS["source
Nix + Xcode 27.0"] - MP -- "1 Intel/CI" --> MB["prebuilt -d"] + MP -- "0 Nix/direnv" --> MS["source
Nix + Xcode 27.0"] + MP -- "1 brew/manual/CI" --> MB["prebuilt -d"] MS --> MR["build_app.sh -p macos
pub get · prebuild.sh
flutter build macos"] MB --> MR IOS --> IC["checks
require-version · toolchain-check
check-reqs-macos · check-sdk-macos"] IC --> IP{"PREBUILTS"} - IP -- "0 Apple Silicon" --> IS["source"] - IP -- "1 Intel/CI" --> IB["prebuilt -d"] + IP -- "0 Nix/direnv" --> IS["source"] + IP -- "1 brew/manual/CI" --> IB["prebuilt -d"] IS --> IR["prebuild.sh
build_app.sh -p ios
pub get · flutter build ios"] IB --> IR LINUX --> LC["checks
require-version · check-linux
toolchain-check · check-reqs"] LC --> LP{"PREBUILTS"} - LP -- "0 Nix on PATH" --> LS["source (Nix)"] - LP -- "1 host" --> LB["prebuilt -d"] + LP -- "0 Nix/direnv" --> LS["source (Nix)"] + LP -- "1 brew/manual/host" --> LB["prebuilt -d"] LS --> LR["prebuild.sh
build_app.sh -p linux
flutter build linux · bundle"] LB --> LR @@ -92,8 +92,8 @@ flowchart TD AH -- macOS --> AB["prebuilt -d"] AH -- "Linux arm64" --> AB AH -- "Linux x86_64" --> AP{"PREBUILTS"} - AP -- "0 Nix" --> AS["source"] - AP -- "1 host" --> AB + AP -- "0 Nix/direnv" --> AS["source"] + AP -- "1 brew/manual/host" --> AB AB --> AR["prebuild.sh
build_app.sh -p android
pub get · flutter build apk
--split-per-abi"] AS --> AR ``` @@ -102,14 +102,17 @@ flowchart TD | Context | `PREBUILTS` | dnix mode | |---|---|---| -| macOS developer, Apple Silicon | `0` | source, verified; needs Nix + Xcode 27.0 | +| macOS developer, Apple Silicon, Nix/direnv | `0` | source, verified; needs Xcode 27.0 | +| macOS developer, Apple Silicon, brew/manual/host | `1` | verified prebuilts (`-d`); source needs Nix/direnv | | macOS developer, Intel | `1` | verified prebuilts (`-d`) | -| Linux developer in Nix/direnv | `0` | source, verified; needs Nix | -| Linux developer outside Nix/direnv | `1` (default) | verified prebuilts (`-d`); set `PREBUILTS=0` with Nix on `PATH` for source | -| iOS developer, Apple Silicon | `0` | source, verified; needs Nix + Xcode 27.0 | +| Linux developer in Nix/direnv | `0` | source, verified | +| Linux developer, brew/manual/host | `1` | verified prebuilts (`-d`); source needs Nix/direnv | +| iOS developer, Apple Silicon, Nix/direnv | `0` | source, verified; needs Xcode 27.0 | +| iOS developer, Apple Silicon, brew/manual/host | `1` | verified prebuilts (`-d`) | | iOS developer, Intel | `1` | verified prebuilts (`-d`) | | macOS/Linux/iOS CI | `1` (explicit `-d`) | verified prebuilts (`-d`) | | Windows | `1` (fixed) | verified prebuilts (`-d`) | | Android on macOS | `1` (default; source needs x86_64 Linux in Nix/direnv) | verified prebuilts (`-d`) | -| Android on x86_64 Linux with Nix on `PATH` | follows `PREBUILTS` | source by default inside Nix/direnv | +| Android on x86_64 Linux in Nix/direnv | follows `PREBUILTS` | source by default | +| Android on x86_64 Linux, brew/manual/host | `1` | verified prebuilts (`-d`); source needs Nix/direnv | | Android on non-x86_64 Linux | `1` (default; source needs x86_64 Linux in Nix/direnv) | verified prebuilts (`-d`) | diff --git a/stack-bom.toml b/stack-bom.toml index 6a16a11a1e..af1b048b3e 100644 --- a/stack-bom.toml +++ b/stack-bom.toml @@ -1,5 +1,7 @@ # Stack Wallet build bill of materials: the toolchain a build is expected to use. -# Checked by `make verify-bom` (dart tool/verify_bom.dart). Keep it small and human readable. +# Checked by `make verify-bom` (dart tool/verify_bom.dart). This is a toolchain and +# plugin-pin file, not a Homebrew package manifest; the native dnix libraries are +# pinned in each plugin's dnix.lock. schema_version = 1 [toolchain] From ee7be852116ca929248e888c9e4c5449dba7565a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:57:00 +0200 Subject: [PATCH 055/107] docs: call Linux non-Nix toolchains non-Nix Homebrew is not the usual Linux fallback; the point is that only the Nix/direnv toolchain can build dnix from source. --- docs/building/linux.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/building/linux.md b/docs/building/linux.md index f944729772..e7cd4468b3 100644 --- a/docs/building/linux.md +++ b/docs/building/linux.md @@ -14,8 +14,8 @@ These steps build the Linux desktop app and the Android app on Ubuntu 24.04 | [Nix](https://nixos.org/download/) | Source mode only with Nix/direnv; not needed with `-d` | | The [Android tools](#android-tools) below | Android builds | -Homebrew/manual toolchains are prebuilt-only: use `PREBUILTS=1`; source mode -requires Nix/direnv. +Non-Nix toolchains (Homebrew/manual/host) are prebuilt-only: use +`PREBUILTS=1`; source mode requires Nix/direnv. **Rustup:** every app builds its DNSSEC resolver with Rust **1.90.0**, and Stack Wallet builds Xelis with Rust **1.99.1**. The build hooks install these From 2ae7c66e3d1652a1c79207df65147d169b1d08d9 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:38:31 +0200 Subject: [PATCH 056/107] docs: label the Intel prebuilt branch in the flow diagram Nix/direnv defaults to source only on Apple Silicon; Intel is prebuilt. --- docs/building/make-flow.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index 8e0554deff..3953548a9c 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -65,15 +65,15 @@ flowchart TD MAC --> MC["checks
require-version · check-sdk-macos
toolchain-check · check-reqs-macos"] MC --> MP{"PREBUILTS"} - MP -- "0 Nix/direnv" --> MS["source
Nix + Xcode 27.0"] - MP -- "1 brew/manual/CI" --> MB["prebuilt -d"] + MP -- "0 Apple Silicon Nix/direnv" --> MS["source
Nix + Xcode 27.0"] + MP -- "1 Intel/brew/manual/CI" --> MB["prebuilt -d"] MS --> MR["build_app.sh -p macos
pub get · prebuild.sh
flutter build macos"] MB --> MR IOS --> IC["checks
require-version · toolchain-check
check-reqs-macos · check-sdk-macos"] IC --> IP{"PREBUILTS"} - IP -- "0 Nix/direnv" --> IS["source"] - IP -- "1 brew/manual/CI" --> IB["prebuilt -d"] + IP -- "0 Apple Silicon Nix/direnv" --> IS["source"] + IP -- "1 Intel/brew/manual/CI" --> IB["prebuilt -d"] IS --> IR["prebuild.sh
build_app.sh -p ios
pub get · flutter build ios"] IB --> IR From b10485d91d7c60bb0c981e0344e079912b025f2b Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:44:16 +0200 Subject: [PATCH 057/107] ci: verify the BOM and source-mode guards - Run `make verify-bom` in the test container after dependencies, installing the BOM Rust toolchain first; the deleted make-build workflow used to run it. - Add negative `make -n` checks for brew/host source mode and Android source mode so the policy cannot regress silently. - Ignore the CI keystore paths. --- .github/workflows/test.yaml | 17 +++++++++++++++++ .gitignore | 3 ++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 029db943de..d0b242658d 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -70,6 +70,11 @@ jobs: flutter pub get dart tool/check_native_overrides.dart stack_wallet + - name: Verify BOM + run: | + rustup toolchain install 1.99.1 --profile minimal --no-self-update + make verify-bom + - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} @@ -153,3 +158,15 @@ jobs: make -n build-windows PLATFORM=MINGW64_NT-10.0 VERSION=0.0.0 BUILD_NUM=1 make -n build-android PLATFORM=Darwin VERSION=0.0.0 BUILD_NUM=1 make -n build-ios PLATFORM=Darwin VERSION=0.0.0 BUILD_NUM=1 + if make -n build-macos PLATFORM=Darwin TOOLCHAIN=brew PREBUILTS=0 VERSION=0.0.0 BUILD_NUM=1; then + echo 'brew source mode must fail' >&2 + exit 1 + fi + if make -n build-linux PLATFORM=Linux TOOLCHAIN=host PREBUILTS=0 VERSION=0.0.0 BUILD_NUM=1; then + echo 'host source mode must fail' >&2 + exit 1 + fi + if make -n build-android PLATFORM=Linux UNAME_M=x86_64 TOOLCHAIN=host ANDROID_PREBUILTS=0 VERSION=0.0.0 BUILD_NUM=1; then + echo 'host Android source mode must fail' >&2 + exit 1 + fi diff --git a/.gitignore b/.gitignore index ef72b7d4ff..529cc3d420 100644 --- a/.gitignore +++ b/.gitignore @@ -126,7 +126,8 @@ lib/wl_gen/generated/ /.cargo/config.toml /scripts/linux/pc/ - # Android local signing /android/key.properties /android/dev-keystore.jks +/android/keystore.jks +/android/keystore-orig.jks From 49a76bc59556c2ac071451a8582ae7f862552574 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:44:34 +0200 Subject: [PATCH 058/107] build: state the iOS source-mode policy in help Keep make help consistent with the Nix/direnv-only source rule. --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index d2cf4e15fc..69dfdfdbd9 100644 --- a/Makefile +++ b/Makefile @@ -535,7 +535,7 @@ build-android: require-version toolchain-check ## Build Android APKs (requires a @"$(FLUTTER)" build apk --split-per-abi --release # iOS: same steps as the "build-ios" CI job (device build, no code signing). Run on macOS with Xcode. -build-ios: require-version verify-bom toolchain-check check-reqs-macos check-sdk-macos ## Build iOS Runner.app without code signing (same steps as CI) +build-ios: require-version verify-bom toolchain-check check-reqs-macos check-sdk-macos ## Build iOS Runner.app without code signing (source in Nix/direnv on Apple Silicon; same steps as CI) @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @xcrun --sdk iphoneos --show-sdk-path >/dev/null 2>&1 || { echo >&2 "[ERROR] iOS SDK not available; install the iOS platform in Xcode."; exit 1; } @cd scripts && bash prebuild.sh From 7cda8290d19f5647d582e81e2d6bdf64c3fe0056 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:45:19 +0200 Subject: [PATCH 059/107] build: keep the source-mode guard internal Prevent command-line overrides of SOURCE_TOOLCHAIN/ANDROID_SOURCE_OK from bypassing the Nix/direnv-only source policy. --- Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 69dfdfdbd9..a63f871778 100644 --- a/Makefile +++ b/Makefile @@ -96,7 +96,7 @@ else endif # Source builds are only exposed through the Nix/direnv toolchain. Homebrew, # manual and host toolchains are prebuilt-only. -SOURCE_TOOLCHAIN := $(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)) +override SOURCE_TOOLCHAIN := $(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)) # Linux builds use a project-local pub cache so cargo finds the repo-local # .cargo/config.toml that carries PROTOC through Flutter's filtered hook environment. # Other targets leave PUB_CACHE unset, so Flutter uses its normal per-user cache @@ -391,7 +391,7 @@ endif # Every other host defaults to the verified prebuilts; that combination # follows PREBUILTS. ANDROID_ARCH := $(UNAME_M) -ANDROID_SOURCE_OK := $(and $(filter Linux,$(PLATFORM)),$(filter x86_64,$(ANDROID_ARCH)),$(strip $(SOURCE_TOOLCHAIN)),$(strip $(NIX_BIN))) +override ANDROID_SOURCE_OK := $(and $(filter Linux,$(PLATFORM)),$(filter x86_64,$(ANDROID_ARCH)),$(strip $(SOURCE_TOOLCHAIN)),$(strip $(NIX_BIN))) ANDROID_PREBUILTS_DEFAULT := $(if $(ANDROID_SOURCE_OK),$(PREBUILTS),1) ANDROID_PREBUILTS ?= $(ANDROID_PREBUILTS_DEFAULT) ifeq ($(strip $(ANDROID_PREBUILTS)),) From 59913d4e217c69aefc88183e48c41ab4291e3c0f Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:53:23 +0200 Subject: [PATCH 060/107] build: tighten Makefile validation and checks - Require single values for APP_NAME, PREBUILTS, ANDROID_PREBUILTS and SYSTEM_DEPS so whitespace-separated or empty values cannot slip past the enum filters. - Treat an empty UNAME_M as unknown, not Apple Silicon, for both the source default and the PREBUILTS=0 guard. - Reject Intel macOS in `make bootstrap` with a pointer to the Homebrew path instead of a raw missing-flake-attribute error. - Report the host/manual toolchain in `toolchain-check` rather than "Nothing to be done". - Only scan /nix/store for sysprof-capture outside a Nix shell when a Nix environment is active. - Add `verify-bom-plugins`, run the full BOM check in `verify-bom`, and check plugin pins before the Windows and Android builds. --- Makefile | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/Makefile b/Makefile index a63f871778..263b416656 100644 --- a/Makefile +++ b/Makefile @@ -5,6 +5,9 @@ APP_NAME ?= stack_wallet override APP_NAME := $(strip $(APP_NAME)) +ifneq ($(words $(APP_NAME)),1) + $(error APP_NAME must be a single value: stack_wallet, stack_duo or campfire) +endif ifneq ($(filter $(APP_NAME),stack_wallet stack_duo campfire),$(APP_NAME)) $(error APP_NAME must be stack_wallet, stack_duo or campfire) endif @@ -129,7 +132,7 @@ ifneq ($(strip $(PUB_CACHE)),) export PUB_CACHE endif -.PHONY: help toolchain toolchain-check bootstrap bootstrap-brew require-version check-reqs check-reqs-macos check-sdk-macos check-linux check-windows bootstrap-macos bootstrap-xcode sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios +.PHONY: help toolchain toolchain-check bootstrap bootstrap-brew require-version check-reqs check-reqs-macos check-sdk-macos check-linux check-windows bootstrap-macos bootstrap-xcode sccache-setup cache-stats verify-bom verify-bom-plugins clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios help: ## Show available commands @echo "Available targets:" @@ -160,10 +163,16 @@ endif ifeq ($(TOOLCHAIN_EFFECTIVE),brew) @command -v brew >/dev/null 2>&1 || { echo >&2 "[ERROR] TOOLCHAIN=brew but brew is not on PATH. Run 'make bootstrap-macos'."; exit 1; } endif +ifeq ($(filter nix direnv brew,$(TOOLCHAIN_EFFECTIVE)),) + @echo "[INFO] $(TOOLCHAIN_EFFECTIVE): using the tools on PATH; no separate check." +endif bootstrap: ## Enter the Nix dev shell (primary toolchain; no-op when already inside) @if [ -n "$$NIX_STORE$$IN_NIX_SHELL" ]; then \ echo "[OK] Already inside a Nix dev shell ($(TOOLCHAIN_EFFECTIVE))."; \ + elif [ "$(PLATFORM)" = "Darwin" ] && [ "$(UNAME_M)" != "arm64" ] && [ "$(UNAME_M)" != "aarch64" ]; then \ + echo >&2 "[ERROR] Intel macOS is prebuilt-only; use 'make bootstrap-macos' (or a manual toolchain) and PREBUILTS=1."; \ + exit 1; \ elif ! command -v nix >/dev/null 2>&1; then \ echo >&2 "[ERROR] Nix is not installed. Install it from https://nixos.org/download/, or use the Homebrew fallback: make bootstrap-macos"; \ exit 1; \ @@ -323,8 +332,13 @@ sccache-setup: ## Opt-in: use sccache for the Rust/C builds run by native-asset verify-bom: ## Check the local toolchain and the pinned plugins against stack-bom.toml @[ -n "$(DART)" ] || { echo >&2 "[ERROR] Dart not installed (needed for verify-bom). Install Flutter or pass DART=/path/to/dart."; exit 1; } + @bash scripts/bom_values.sh --check @FLUTTER="$(FLUTTER)" "$(DART)" tool/verify_bom.dart +verify-bom-plugins: ## Check only the pinned plugin refs against pubspec.lock + @[ -n "$(DART)" ] || { echo >&2 "[ERROR] Dart not installed (needed for verify-bom-plugins). Install Flutter or pass DART=/path/to/dart."; exit 1; } + @FLUTTER="$(FLUTTER)" "$(DART)" tool/verify_bom.dart --plugins + cache-stats: ## Show sccache statistics (hit rate) after a build @command -v sccache >/dev/null 2>&1 || { echo >&2 "[ERROR] sccache not installed."; exit 1; } @sccache --show-stats @@ -350,10 +364,10 @@ clean: ## Remove artifacts and fix permissions ifeq ($(strip $(SOURCE_TOOLCHAIN)),) PREBUILTS_DEFAULT := 1 else ifeq ($(PLATFORM),Darwin) - ifeq ($(filter arm64 aarch64,$(UNAME_M)),$(UNAME_M)) - PREBUILTS_DEFAULT := 0 - else + ifeq ($(filter arm64 aarch64,$(UNAME_M)),) PREBUILTS_DEFAULT := 1 + else + PREBUILTS_DEFAULT := 0 endif else ifeq ($(PLATFORM),Linux) PREBUILTS_DEFAULT := 0 @@ -364,15 +378,18 @@ PREBUILTS ?= $(PREBUILTS_DEFAULT) ifeq ($(strip $(PREBUILTS)),) override PREBUILTS := $(PREBUILTS_DEFAULT) endif +ifneq ($(words $(PREBUILTS)),1) + $(error PREBUILTS must be 0 or 1) +endif ifneq ($(filter $(PREBUILTS),0 1),$(PREBUILTS)) $(error PREBUILTS must be 0 or 1) endif ifeq ($(PREBUILTS),0) ifeq ($(strip $(SOURCE_TOOLCHAIN)),) - $(error PREBUILTS=0 requires TOOLCHAIN=nix or direnv; use PREBUILTS=1 with Homebrew/manual) + $(error PREBUILTS=0 requires TOOLCHAIN=nix or direnv; use PREBUILTS=1 with Homebrew/manual/host) endif ifeq ($(PLATFORM),Darwin) - ifneq ($(filter arm64 aarch64,$(UNAME_M)),$(UNAME_M)) + ifeq ($(filter arm64 aarch64,$(UNAME_M)),) $(error PREBUILTS=0 (dnix source) requires Apple Silicon on macOS; use the default PREBUILTS=1) endif endif @@ -397,6 +414,9 @@ ANDROID_PREBUILTS ?= $(ANDROID_PREBUILTS_DEFAULT) ifeq ($(strip $(ANDROID_PREBUILTS)),) override ANDROID_PREBUILTS := $(ANDROID_PREBUILTS_DEFAULT) endif +ifneq ($(words $(ANDROID_PREBUILTS)),1) + $(error ANDROID_PREBUILTS must be 0 or 1) +endif ifneq ($(filter $(ANDROID_PREBUILTS),0 1),$(ANDROID_PREBUILTS)) $(error ANDROID_PREBUILTS must be 0 or 1) endif @@ -407,6 +427,9 @@ ifeq ($(ANDROID_PREBUILTS),0) endif # Linux only: SYSTEM_DEPS=1 uses the system libsecret/jsoncpp packages instead of building them (like the CI image). SYSTEM_DEPS ?= 0 +ifneq ($(words $(SYSTEM_DEPS)),1) + $(error SYSTEM_DEPS must be 0 or 1) +endif ifneq ($(filter $(SYSTEM_DEPS),0 1),$(SYSTEM_DEPS)) $(error SYSTEM_DEPS must be 0 or 1) endif @@ -482,7 +505,7 @@ build-linux: require-version verify-bom check-linux toolchain-check check-reqs # USE_SYSTEM_SECURE_STORAGE_DEPS=1 PROTOC="$(PROTOC_PATH)" "$(FLUTTER)" build linux --release; \ else \ SYSPROF_PC_DIR="$${SYSPROF_PC_DIR:-}"; \ - if [ -z "$$SYSPROF_PC_DIR" ]; then \ + if [ -z "$$SYSPROF_PC_DIR" ] && [ -n "$$IN_NIX_SHELL$$NIX_STORE" ]; then \ SYSPROF_PC_DIR=$$(dirname "$$(find /nix/store -path '*/lib/pkgconfig/sysprof-capture-4.pc' 2>/dev/null | head -n1)"); \ [ "$$SYSPROF_PC_DIR" != "." ] || SYSPROF_PC_DIR=""; \ fi; \ @@ -501,7 +524,7 @@ build-linux: require-version verify-bom check-linux toolchain-check check-reqs # # Windows: run from Git Bash. Same steps as the "build-windows" job in .github/workflows/build.yaml. # Windows uses verified dnix prebuilts; source mode needs Nix inside WSL2 and is # driven by build_app.sh directly, not by this target. -build-windows: require-version check-windows toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) +build-windows: require-version verify-bom-plugins check-windows toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @cd scripts && bash prebuild.sh @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a "$(APP_NAME)" -d @@ -522,7 +545,7 @@ android-dev-key: ## Create a throw-away debug signing key if android/key.propert fi @chmod 600 android/key.properties android/dev-keystore.jks 2>/dev/null || true -build-android: require-version toolchain-check ## Build Android APKs (requires android/key.properties; prebuilt unless x86_64 Linux in Nix/direnv follows PREBUILTS) +build-android: require-version verify-bom-plugins toolchain-check ## Build Android APKs (requires android/key.properties; prebuilt unless x86_64 Linux in Nix/direnv follows PREBUILTS) @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @[ -f android/key.properties ] || { echo >&2 "[ERROR] android/key.properties is missing. Run 'make android-dev-key' for a local throw-away key; never distribute APKs signed with it."; exit 1; } @if grep -q '^keyAlias=devkey$$' android/key.properties 2>/dev/null; then \ From 2609532f6e16b2b20d75a92f93309b70105b51ea Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:53:23 +0200 Subject: [PATCH 061/107] nix: make the dev shell self-contained and idempotent Provide git and nix in the dev shell so a clean `nix develop -i` can run the Makefile and source builds. Guard the Linux clang/patchelf PATH prepends so nested shells do not duplicate entries. --- flake.nix | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/flake.nix b/flake.nix index 41eabe0860..de47480386 100644 --- a/flake.nix +++ b/flake.nix @@ -36,6 +36,8 @@ flutter go rustup + git + nix cmake meson ninja @@ -134,9 +136,15 @@ # Flutter's Linux CMake build forces CC=clang/CXX=clang++. libclang # also puts the unwrapped clang first on PATH, which cannot find # the NixOS crt/libstdc++ paths; prefer the clang wrapper. - export PATH="${pkgs.llvmPackages.clang}/bin:$PATH" + case ":$PATH:" in + *":${pkgs.llvmPackages.clang}/bin:"*) ;; + *) export PATH="${pkgs.llvmPackages.clang}/bin:$PATH" ;; + esac # stdenv also provides patchelf 0.15; put 0.18 first. - export PATH="${pkgs.patchelfUnstable}/bin:$PATH" + case ":$PATH:" in + *":${pkgs.patchelfUnstable}/bin:"*) ;; + *) export PATH="${pkgs.patchelfUnstable}/bin:$PATH" ;; + esac export LIBCLANG_PATH="${pkgs.llvmPackages.libclang.lib}/lib" export BINDGEN_EXTRA_CLANG_ARGS="-isystem ${pkgs.llvmPackages.libclang.lib}/lib/clang/${clangMajor}/include" export PROTOC="${pkgs.protobuf}/bin/protoc" From 6e81ccde4e5c726b1b42003d103d82bf16891dd4 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:53:23 +0200 Subject: [PATCH 062/107] tool: check DNSSEC Rust and support plugin-only BOM checks - Verify the dnssec_rust pin is installed, not just the main Rust toolchain. - Add `--plugins` so Windows/Android builds can check plugin pins before build_app.sh generates pubspec.yaml. - Run `bom_values.sh --check` from `make verify-bom`. - In CI, install both Rust toolchains from stack-bom.toml instead of hardcoding a version, and silence the expected source-mode failures in the negative make-check guards. --- .github/workflows/test.yaml | 11 ++-- tool/verify_bom.dart | 102 ++++++++++++++++++++++-------------- 2 files changed, 70 insertions(+), 43 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index d0b242658d..642b6c04bf 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -72,7 +72,10 @@ jobs: - name: Verify BOM run: | - rustup toolchain install 1.99.1 --profile minimal --no-self-update + rustup toolchain install \ + "$(bash scripts/bom_values.sh --get rust)" \ + "$(bash scripts/bom_values.sh --get dnssec_rust)" \ + --profile minimal --no-self-update make verify-bom - name: Decode secrets @@ -158,15 +161,15 @@ jobs: make -n build-windows PLATFORM=MINGW64_NT-10.0 VERSION=0.0.0 BUILD_NUM=1 make -n build-android PLATFORM=Darwin VERSION=0.0.0 BUILD_NUM=1 make -n build-ios PLATFORM=Darwin VERSION=0.0.0 BUILD_NUM=1 - if make -n build-macos PLATFORM=Darwin TOOLCHAIN=brew PREBUILTS=0 VERSION=0.0.0 BUILD_NUM=1; then + if make -n build-macos PLATFORM=Darwin TOOLCHAIN=brew PREBUILTS=0 VERSION=0.0.0 BUILD_NUM=1 >/dev/null 2>&1; then echo 'brew source mode must fail' >&2 exit 1 fi - if make -n build-linux PLATFORM=Linux TOOLCHAIN=host PREBUILTS=0 VERSION=0.0.0 BUILD_NUM=1; then + if make -n build-linux PLATFORM=Linux TOOLCHAIN=host PREBUILTS=0 VERSION=0.0.0 BUILD_NUM=1 >/dev/null 2>&1; then echo 'host source mode must fail' >&2 exit 1 fi - if make -n build-android PLATFORM=Linux UNAME_M=x86_64 TOOLCHAIN=host ANDROID_PREBUILTS=0 VERSION=0.0.0 BUILD_NUM=1; then + if make -n build-android PLATFORM=Linux UNAME_M=x86_64 TOOLCHAIN=host ANDROID_PREBUILTS=0 VERSION=0.0.0 BUILD_NUM=1 >/dev/null 2>&1; then echo 'host Android source mode must fail' >&2 exit 1 fi diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index e29961b826..5ed1de8c92 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -237,6 +237,49 @@ Future _update() async { ); } +Never _finish() { + stdout.writeln('\n$_failures failure(s), $_warnings warning(s).'); + exit(_failures == 0 ? 0 : 1); +} + +void _checkPlugins(Map> bom) { + final refs = _lockRefs(); + final pinned = bom['plugins'] ?? {}; + final declared = _declaredPlugins(); + final pubspecExists = File('pubspec.yaml').existsSync(); + // A fresh checkout has no pubspec.yaml: build_app.sh generates it later. + // In that case check every plugin the lock contains, as before. + final required = pubspecExists ? declared : _pluginNames.toSet(); + if (refs.isEmpty) { + _warn('pubspec.lock not found, plugin pins not checked'); + } else if (required.isEmpty) { + _fail( + 'could not read plugin declarations from pubspec.yaml ' + '(expected them under dependencies: or dependency_overrides:)', + ); + } else { + for (final n in _pluginNames) { + if (!required.contains(n)) continue; + final ref = refs[n]; + final pin = pinned[n]; + if (ref == null) { + _fail( + '$n is missing from pubspec.lock (path dependency or not resolved)', + ); + } else if (pin == null) { + _fail('$n is missing from [plugins] in $_bomFile (run --update)'); + } else if (pin == ref) { + _ok('$n ${_short(ref)}'); + } else { + _fail( + '$n is ${_short(ref)} in pubspec.lock but ' + '${_short(pin)} in $_bomFile (run --update)', + ); + } + } + } +} + Future main(List args) async { if (!File(_bomFile).existsSync()) { stderr.writeln('Run from the repository root ($_bomFile not found).'); @@ -245,6 +288,11 @@ Future main(List args) async { if (args.contains('--update')) return _update(); final bomText = File(_bomFile).readAsStringSync(); + if (args.contains('--plugins')) { + _requireSinglePluginsSection(bomText); + _checkPlugins(_readBom(bomText)); + _finish(); + } _requireSinglePluginsSection(bomText); final bom = _readBom(bomText); final root = bom[''] ?? {}; @@ -307,6 +355,19 @@ Future main(List args) async { } else { _fail('Rust $rust is not installed (rustup toolchain install $rust)'); } + final dnssec = tc['dnssec_rust'] ?? ''; + if (dnssec.isEmpty) { + _fail('dnssec_rust is missing from $_bomFile'); + } else if (list == null) { + // already reported above + } else if (list.split('\n').any((l) => l.startsWith('$dnssec-'))) { + _ok('DNSSEC Rust $dnssec installed via rustup'); + } else { + _fail( + 'DNSSEC Rust $dnssec is not installed ' + '(rustup toolchain install $dnssec)', + ); + } // Go final go = await _run('go', ['version']); @@ -338,43 +399,6 @@ Future main(List args) async { } } - // Pinned plugins against pubspec.lock - final refs = _lockRefs(); - final pinned = bom['plugins'] ?? {}; - final declared = _declaredPlugins(); - final pubspecExists = File('pubspec.yaml').existsSync(); - // A fresh checkout has no pubspec.yaml: build_app.sh generates it later. - // In that case check every plugin the lock contains, as before. - final required = pubspecExists ? declared : _pluginNames.toSet(); - if (refs.isEmpty) { - _warn('pubspec.lock not found, plugin pins not checked'); - } else if (required.isEmpty) { - _fail( - 'could not read plugin declarations from pubspec.yaml ' - '(expected them under dependencies: or dependency_overrides:)', - ); - } else { - for (final n in _pluginNames) { - if (!required.contains(n)) continue; - final ref = refs[n]; - final pin = pinned[n]; - if (ref == null) { - _fail( - '$n is missing from pubspec.lock (path dependency or not resolved)', - ); - } else if (pin == null) { - _fail('$n is missing from [plugins] in $_bomFile (run --update)'); - } else if (pin == ref) { - _ok('$n ${_short(ref)}'); - } else { - _fail( - '$n is ${_short(ref)} in pubspec.lock but ' - '${_short(pin)} in $_bomFile (run --update)', - ); - } - } - } - - stdout.writeln('\n$_failures failure(s), $_warnings warning(s).'); - exit(_failures == 0 ? 0 : 1); + _checkPlugins(bom); + _finish(); } From 67a76683fd8b97bfe20498f49341cdccceed6203 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:53:23 +0200 Subject: [PATCH 063/107] docs: align host guides with the prebuilt-only policy - Put `-d` in the manual/Homebrew macOS and Linux build commands and say it is required there. - Scope the Makefile source default to Apple Silicon macOS and Linux. - Describe the Windows guide as a direct WSL2/Nix source path while `make build-windows` stays prebuilt. - Match the Xcode 27.0 selection wording to how dnix finds Xcode, and correct the README's dnix and Xcode claims. --- README.md | 14 +++++++------- docs/building/linux.md | 2 +- docs/building/macos.md | 7 ++++--- docs/building/windows.md | 6 +++--- 4 files changed, 15 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 0edae42097..52f6d5dc98 100644 --- a/README.md +++ b/README.md @@ -49,10 +49,10 @@ Highlights include: You can look at the [build instructions](docs/building.md) for more details. On macOS, the **Nix dev shell** is the primary *host* toolchain; Homebrew and -manual installs are supported fallbacks. dnix builds and verifies the four -native libraries underneath all of them. `make build-macos` is the same target -in every mode, and `make toolchain` shows which host environment your shell is -using. +manual installs are supported fallbacks. dnix builds the four native +libraries from source under Nix/direnv and verifies the prebuilts otherwise. +`make build-macos` is the same target in every mode, and `make toolchain` +shows which host environment your shell is using. ### macOS with Nix (recommended) @@ -61,9 +61,9 @@ using. - `nix develop` directly, or - `direnv allow` once, if you use direnv with the included `.envrc`. 2. Check the Xcode requirement. Source builds are the default in Nix/direnv - on Apple Silicon and need Xcode **27.0** (build 27A266a); with any other - Xcode pass `PREBUILTS=1`. `make bootstrap-xcode` selects an installed full - Xcode and `make verify-bom` checks the host. + on Apple Silicon and need Xcode **27.0** (build 27A266a); if Xcode 27.0 + is not installed, pass `PREBUILTS=1`. `make bootstrap-xcode` selects an + installed full Xcode and `make verify-bom` checks the host. 3. Run build (pass the release version and a build number; `make` refuses to guess): - `make build-macos VERSION=x.y.z BUILD_NUM=nnn` diff --git a/docs/building/linux.md b/docs/building/linux.md index e7cd4468b3..9f5e7bf74a 100644 --- a/docs/building/linux.md +++ b/docs/building/linux.md @@ -69,7 +69,7 @@ plugin project in that SDK. Without a writable Flutter checkout, build in 2. Configure and build the Linux app: ```sh - bash scripts/build_app.sh -a stack_wallet -p linux -v 1.2.3 -b 123 + bash scripts/build_app.sh -a stack_wallet -p linux -v 1.2.3 -b 123 -d flutter pub get dart tool/check_native_overrides.dart stack_wallet flutter build linux --release diff --git a/docs/building/macos.md b/docs/building/macos.md index f8a34e5e6f..26b3741c34 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -130,7 +130,7 @@ Run the configuration and Flutter build commands in that shell. 2. Configure and build the macOS app: ```sh - bash scripts/build_app.sh -a stack_wallet -p macos -v 1.2.3 -b 123 + bash scripts/build_app.sh -a stack_wallet -p macos -v 1.2.3 -b 123 -d flutter pub get dart tool/check_native_overrides.dart stack_wallet flutter build macos --release @@ -139,8 +139,9 @@ Run the configuration and Flutter build commands in that shell. For iOS, configure with `-p ios` and build with `flutter build ios --release`. Use the version and build number for your checkout, and read the script's -confirmation before continuing. Add `-d` to the configuration command to use -verified dnix prebuilts. See the +confirmation before continuing. `-d` selects the verified dnix prebuilts and +is required for the manual/Homebrew path. Source mode is only available with +Nix/direnv; see the [configuration options](../building.md#configuration-options). The override check catches package-local dnix overrides; see [Local overrides](native-libraries.md#local-overrides). diff --git a/docs/building/windows.md b/docs/building/windows.md index 0b9871fdbe..09836dd416 100644 --- a/docs/building/windows.md +++ b/docs/building/windows.md @@ -13,7 +13,7 @@ with Windows Flutter. For how the build fits together, see the | [Visual Studio 2022](https://docs.flutter.dev/platform-integration/windows/setup) with **Desktop development with C++**, CMake tools and a Windows SDK | Every build | | Windows Developer Mode, for the symlinks Flutter and its plugins create | Every build | | [Rustup](https://rustup.rs/) on Windows | Every app's DNSSEC hook and Stack Wallet's Xelis hook, in both modes | -| WSL2 with Ubuntu 24.04, and [Nix](https://nixos.org/download/) inside it | Source mode, the default; not needed with `-d` | +| WSL2 with Ubuntu 24.04, and [Nix](https://nixos.org/download/) inside it | Direct `build_app.sh` source mode; not needed with `-d` or `make build-windows` | | Go 1.24.0 or newer and `mingw-w64` in the default WSL distribution | Stack Wallet's [MWEB build](#mweb), unless you set `MWEBD_FETCH=1` | ## Set up WSL and Nix @@ -64,8 +64,8 @@ Bash. ``` Use the version and build number for your checkout, and read the script's -confirmation before continuing. Add `-d` to the configuration command to use -verified dnix prebuilts. See the +confirmation before continuing. This direct command builds source in +WSL2/Nix; `make build-windows` always uses the verified prebuilts (`-d`). See the [configuration options](../building.md#configuration-options). The override check catches package-local dnix overrides; see [Local overrides](native-libraries.md#local-overrides). From 4cafe94335c1a7fda075eff1c15def7b52dbdfc4 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:53:38 +0200 Subject: [PATCH 064/107] tool: validate the BOM schema in plugin-only mode Keep the schema_version check ahead of the --plugins shortcut so a malformed BOM cannot pass the Windows/Android preflight. --- tool/verify_bom.dart | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 5ed1de8c92..1c2efef845 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -288,17 +288,16 @@ Future main(List args) async { if (args.contains('--update')) return _update(); final bomText = File(_bomFile).readAsStringSync(); - if (args.contains('--plugins')) { - _requireSinglePluginsSection(bomText); - _checkPlugins(_readBom(bomText)); - _finish(); - } _requireSinglePluginsSection(bomText); final bom = _readBom(bomText); final root = bom[''] ?? {}; if (root['schema_version'] != '1') { _fail('schema_version must be 1 in $_bomFile'); } + if (args.contains('--plugins')) { + _checkPlugins(bom); + _finish(); + } final tc = bom['toolchain'] ?? {}; // Flutter / Dart From 011f2b0691e9d39f69989a8169a5020a29d07530 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:55:37 +0200 Subject: [PATCH 065/107] build: fail closed on stuck Windows junctions - Do not let a Windows junction that rmdir could not remove fall through to `rm -rf`, which can follow the reparse point into asset_sources. Query the reparse point and stop with an actionable error instead. - Say "active Nix/direnv shell" in the PREBUILTS=0 error. - Qualify the README's recommended Nix path as Apple Silicon. --- Makefile | 2 +- README.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 263b416656..0695f50fd4 100644 --- a/Makefile +++ b/Makefile @@ -395,7 +395,7 @@ ifeq ($(PREBUILTS),0) endif ifeq ($(filter Darwin Linux,$(PLATFORM)),$(PLATFORM)) ifeq ($(strip $(NIX_BIN)),) - $(error PREBUILTS=0 (dnix source) needs Nix on PATH; run 'nix develop' or use PREBUILTS=1) + $(error PREBUILTS=0 (dnix source) needs an active Nix/direnv shell; run 'make bootstrap' or use PREBUILTS=1) endif endif endif diff --git a/README.md b/README.md index 52f6d5dc98..714c04ff17 100644 --- a/README.md +++ b/README.md @@ -48,13 +48,13 @@ Highlights include: ## Building You can look at the [build instructions](docs/building.md) for more details. -On macOS, the **Nix dev shell** is the primary *host* toolchain; Homebrew and -manual installs are supported fallbacks. dnix builds the four native +On Apple Silicon macOS, the **Nix dev shell** is the primary *host* toolchain; +Homebrew and manual installs are supported fallbacks. dnix builds the four native libraries from source under Nix/direnv and verifies the prebuilts otherwise. `make build-macos` is the same target in every mode, and `make toolchain` shows which host environment your shell is using. -### macOS with Nix (recommended) +### macOS with Nix (recommended; Apple Silicon) 1. Enter the flake environment: - `make bootstrap` (runs `nix develop`), or From 15d0e12d39b32fd84e4a2b4e5c9d104d3abbac1b Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:12:21 +0200 Subject: [PATCH 066/107] build: require Go only for Stack Wallet Stack Duo and Campfire do not use the MWEB build, and build_app.sh's preflight already scopes the Go check to stack_wallet. Keep check-reqs consistent so `make build-macos APP_NAME=campfire` does not fail on a machine without Go. --- Makefile | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 0695f50fd4..289748f8c2 100644 --- a/Makefile +++ b/Makefile @@ -221,7 +221,10 @@ check-reqs: ## Verify essential build tools @# `rustup which cargo` resolves a toolchain path even when no shim is on PATH, @# but the plugin build scripts invoke bare `cargo` — verify that separately. @command -v cargo >/dev/null 2>&1 || [ -x "$$HOME/.cargo/bin/cargo" ] || { echo >&2 "[ERROR] 'cargo' is not on PATH (rustup shims missing from ~/.cargo/bin). Run 'rustup-init -y', then open a new terminal."; exit 1; } - @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed."; exit 1; } +# Go is only needed for Stack Wallet's MWEB build; Stack Duo and Campfire do not use it. +ifeq ($(APP_NAME),stack_wallet) + @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed (needed for Stack Wallet's MWEB build)."; exit 1; } +endif @command -v cmake >/dev/null 2>&1 || { echo >&2 "[ERROR] CMake not installed."; exit 1; } @command -v protoc >/dev/null 2>&1 || { echo >&2 "[ERROR] protoc not installed (protobuf); use 'nix develop' or your package manager."; exit 1; } @command -v meson >/dev/null 2>&1 || { \ From 884f5f38b694fb2ed95465cd166ee1a3130e01d8 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:36:29 +0200 Subject: [PATCH 067/107] fix(verify-bom): fail on spaced PATH-found Flutter (S23) Resolve a bare 'flutter' found on PATH to its absolute path and refuse it when a directory component contains a space: the native-assets hooks and .dart_tool config writers do not quote paths, so a spaced checkout fails deep in a build with a cryptic error. The guard runs after PATH resolution, so an explicit FLUTTER=/path is still honored (Makefile already rejects spaced explicit paths); only the PATH-found fallback is guarded. Proof: flutter symlinked into /tmp/with space/ first on PATH makes verify-bom print the clear failure and exit 1; clean PATH passes; analyze clean. --- tool/verify_bom.dart | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 1c2efef845..152edbf206 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -73,6 +73,24 @@ Map> _readBom(String text) { return result; } +/// Resolves a bare command name to an absolute path via PATH, or returns the +/// name unchanged if it is not found (so _run can report "not found"). +/// +/// Note: the PATH *list* separator is ';' on Windows and ':' elsewhere. +/// Platform.pathSeparator is the path *component* separator ('/' / '\\'), +/// which is the wrong value for splitting PATH, so it is not used here. +String _resolveOnPath(String name) { + if (name.contains('/') || name.contains('\\')) return name; + final listSep = Platform.isWindows ? ';' : ':'; + final sep = Platform.pathSeparator; + for (final dir in (Platform.environment['PATH'] ?? '').split(listSep)) { + if (dir.isEmpty) continue; + final candidate = File(dir.endsWith(sep) ? dir : '$dir/$name').path; + if (File(candidate).existsSync()) return candidate; + } + return name; +} + Future _run(String exe, List args) async { try { // runInShell lets Windows start flutter.bat. Only stdout is parsed: Flutter @@ -305,7 +323,19 @@ Future main(List args) async { final flutterExe = configuredFlutter.isNotEmpty && File(configuredFlutter).existsSync() ? configuredFlutter - : 'flutter'; + : _resolveOnPath('flutter'); + // A Flutter/Dart executable found on PATH under a directory with a space in + // its name breaks the native-assets hooks and the .dart_tool config writers, + // which do not quote paths. Catch it here with a clear error rather than + // failing deep inside a build with a cryptic "No such file or directory". + if (flutterExe.contains(' ')) { + _fail( + 'Flutter is resolved to "$flutterExe": a path with a space in a name ' + 'breaks the build. Move the Flutter checkout to a path with no spaces, ' + 'or set FLUTTER=/path/to/flutter/bin/flutter to an unspaced location.', + ); + _finish(); + } final fl = await _run(flutterExe, ['--version', '--machine']); if (fl == null) { _fail('flutter not found in PATH'); From 5d6196f2a21fd8bb0e9e5eb2f1785e45f5e38500 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:51:30 +0200 Subject: [PATCH 068/107] fix(make): source mode available to any toolchain with Nix on PATH The Makefile restricted PREBUILTS=0 (dnix source) to the Nix/direnv toolchain only. Source builds actually only need the `nix` binary on PATH, not a particular toolchain route. Make the restriction the nix binary (D1): SOURCE_TOOLCHAIN is set whenever NIX_BIN is non-empty, and the PREBUILTS=0 guard no longer rejects non-Nix toolchains. - check-reqs no longer hard-requires protoc/meson/ninja on every host; those are gated to the Linux build with SYSTEM_DEPS=0 (S1). - A Flutter/Dart found on PATH under a directory with a space now fails early with a clear message instead of resolving to a directory and breaking verify-bom later (S3). - require-version accepts an x.y.z-suffix VERSION and allows rebuilding an exact release tag (S13). - build-linux respects a caller's PUB_CACHE; only NixOS forces the repo-local cache (S14). - .cargo/config.toml is rewritten when the recorded PROTOC path changes or the path is gone, so a stale store path no longer breaks cargo without a clean (S15). - .envrc: `use flake .` so direnv loads the pinned flake path (S5). --- .envrc | 2 +- Makefile | 141 ++++++++++++++++++++++++++++--------------------------- 2 files changed, 74 insertions(+), 69 deletions(-) diff --git a/.envrc b/.envrc index b2382c8a70..4819e13923 100644 --- a/.envrc +++ b/.envrc @@ -2,5 +2,5 @@ # failing with a blocked .envrc; use make bootstrap-macos and PREBUILTS=1. if has nix; then watch_file stack-bom.toml flake.nix flake.lock - use flake --no-write-lock-file + use flake . --no-write-lock-file fi diff --git a/Makefile b/Makefile index 289748f8c2..3e58d3fed3 100644 --- a/Makefile +++ b/Makefile @@ -33,20 +33,44 @@ ifneq ($(strip $(DART)),) $(error DART must not contain spaces; put it on PATH instead) endif endif +# Capture explicit overrides before FLUTTER/DART are normalized below. +FLUTTER_USER := $(strip $(FLUTTER)) +DART_USER := $(strip $(DART)) FLUTTER_BIN := $(if $(FLUTTER),$(if $(findstring /,$(FLUTTER)),$(abspath $(FLUTTER)),$(FLUTTER)),$(shell command -v flutter 2>/dev/null)) # A Flutter SDK ships its own Dart next to the flutter binary; an explicit # FLUTTER path should not require a second DART= argument. DART_BIN := $(if $(DART),$(if $(findstring /,$(DART)),$(abspath $(DART)),$(DART)),$(if $(filter /%,$(FLUTTER_BIN)),$(or $(wildcard $(dir $(FLUTTER_BIN))dart),$(shell command -v dart 2>/dev/null)),$(shell command -v dart 2>/dev/null))) FLUTTER := $(FLUTTER_BIN) DART := $(DART_BIN) +# Make splits unquoted values on whitespace. A Flutter found on PATH under a +# directory such as "Application Support" would resolve DART to the directory, +# and verify-bom would fail later with a misleading error. +ifneq ($(strip $(FLUTTER_BIN)),) +ifneq ($(words $(FLUTTER_BIN)),1) +$(error Flutter resolves to '$(FLUTTER_BIN)', which contains a space; move it to a path without spaces or pass FLUTTER=... from such a path) +endif +endif +ifneq ($(strip $(DART)),) +ifneq ($(words $(DART)),1) +$(error Dart resolves to '$(DART)', which contains a space; move it to a path without spaces or pass DART=... from such a path) +endif +endif +SYSTEM_DEPS ?= 0 # Child scripts call bare `flutter`/`dart`; keep them on the binaries checked -# above instead of whatever PATH would otherwise resolve. +# above instead of whatever PATH would otherwise resolve. Only do this for an +# explicit override: prepending the directory of a Flutter that was already on +# PATH shadows unrelated tools and makes Flutter's hook runner rerun native +# builds because PATH changed. +ifneq ($(FLUTTER_USER),) ifneq ($(filter /%,$(FLUTTER_BIN)),) export PATH := $(dir $(FLUTTER_BIN)):$(PATH) endif +endif +ifneq ($(DART_USER),) ifneq ($(filter /%,$(DART)),) export PATH := $(dir $(DART)):$(PATH) endif +endif APP_PROJECT_ROOT_DIR := $(CURDIR) ifeq ($(wildcard Makefile),) $(error Run make from the repository root) @@ -97,9 +121,9 @@ ifeq ($(TOOLCHAIN),auto) else TOOLCHAIN_EFFECTIVE := $(TOOLCHAIN) endif -# Source builds are only exposed through the Nix/direnv toolchain. Homebrew, -# manual and host toolchains are prebuilt-only. -override SOURCE_TOOLCHAIN := $(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)) +# Source builds need Nix on PATH to build the dnix libraries. The Nix/direnv +# shell supplies it; any toolchain can use PREBUILTS=0 when nix is available. +override SOURCE_TOOLCHAIN := $(if $(strip $(NIX_BIN)),1,) # Linux builds use a project-local pub cache so cargo finds the repo-local # .cargo/config.toml that carries PROTOC through Flutter's filtered hook environment. # Other targets leave PUB_CACHE unset, so Flutter uses its normal per-user cache @@ -132,7 +156,7 @@ ifneq ($(strip $(PUB_CACHE)),) export PUB_CACHE endif -.PHONY: help toolchain toolchain-check bootstrap bootstrap-brew require-version check-reqs check-reqs-macos check-sdk-macos check-linux check-windows bootstrap-macos bootstrap-xcode sccache-setup cache-stats verify-bom verify-bom-plugins clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios +.PHONY: help toolchain toolchain-check bootstrap bootstrap-brew require-version check-reqs check-reqs-macos check-sdk-macos check-linux check-windows bootstrap-macos bootstrap-xcode sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios help: ## Show available commands @echo "Available targets:" @@ -178,7 +202,7 @@ bootstrap: ## Enter the Nix dev shell (primary toolchain; no-op when already ins exit 1; \ else \ echo "Entering the Nix dev shell. Run 'make build-macos VERSION=... BUILD_NUM=...' inside it."; \ - exec nix develop; \ + exec nix --extra-experimental-features 'nix-command flakes' develop; \ fi bootstrap-brew: bootstrap-macos ## Alias for the Homebrew fallback toolchain @@ -201,14 +225,17 @@ endif # --- PREREQUISITES --- -require-version: ## Fail unless VERSION/BUILD_NUM are valid and above the latest release tag - @printf '%s' '$(VERSION)' | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$$' || { echo >&2 "[ERROR] VERSION must be x.y.z (got '$(VERSION)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } - @printf '%s' '$(BUILD_NUM)' | grep -Eq '^[0-9]+$$' || { echo >&2 "[ERROR] BUILD_NUM must be numeric (got '$(BUILD_NUM)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } +require-version: ## Fail unless VERSION/BUILD_NUM are valid and BUILD_NUM is not below the latest release tag + @printf '%s' '$(VERSION)' | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z][0-9A-Za-z.-]*)?$$' || { echo >&2 "[ERROR] VERSION must be x.y.z or x.y.z-suffix (got '$(VERSION)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } + @printf '%s' '$(BUILD_NUM)' | grep -Eq '^[0-9]+$' || { echo >&2 "[ERROR] BUILD_NUM must be numeric (got '$(BUILD_NUM)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } @latest="$$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | sed -n 's/^build_\([0-9][0-9]*\)$$/\1/p' | head -n1)"; \ if [ -n "$$latest" ]; then \ - [ "$(BUILD_NUM)" -gt "$$latest" ] || { echo >&2 "[ERROR] BUILD_NUM $(BUILD_NUM) is not above the latest release tag build_$$latest."; exit 1; }; \ - elif git tag -l 'build_*' 2>/dev/null | grep -q .; then \ - echo "[WARN] No numeric build_* tag found; cannot compare BUILD_NUM."; \ + [ "$(BUILD_NUM)" -ge "$$latest" ] || { echo >&2 "[ERROR] BUILD_NUM $(BUILD_NUM) is below the latest release tag build_$$latest."; exit 1; }; \ + if [ "$(BUILD_NUM)" -eq "$$latest" ]; then \ + echo "[INFO] Rebuilding release tag build_$$latest with BUILD_NUM=$(BUILD_NUM)."; \ + fi; \ + else \ + echo "[INFO] No numeric build_* tag found; skipping BUILD_NUM comparison."; \ fi check-reqs: ## Verify essential build tools @@ -216,8 +243,8 @@ check-reqs: ## Verify essential build tools @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed. Use 'nix develop' (recommended) or add Flutter to PATH."; exit 1; } @[ -n "$(DART)" ] && command -v "$(DART)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Dart not installed. It ships with Flutter; use 'nix develop' (recommended)."; exit 1; } @command -v rustup >/dev/null 2>&1 || { echo >&2 "[ERROR] rustup not installed."; exit 1; } - @rustup which rustc >/dev/null 2>&1 || { echo >&2 "[ERROR] rustc toolchain not available via rustup."; exit 1; } - @rustup which cargo >/dev/null 2>&1 || { echo >&2 "[ERROR] cargo toolchain not available via rustup."; exit 1; } + @rustup run 1.90.0 rustc --version >/dev/null 2>&1 || { echo >&2 "[ERROR] Rust 1.90.0 (DNSSEC) not installed via rustup."; exit 1; } + @rustup run 1.99.1 rustc --version >/dev/null 2>&1 || { echo >&2 "[ERROR] Rust 1.99.1 not installed via rustup."; exit 1; } @# `rustup which cargo` resolves a toolchain path even when no shim is on PATH, @# but the plugin build scripts invoke bare `cargo` — verify that separately. @command -v cargo >/dev/null 2>&1 || [ -x "$$HOME/.cargo/bin/cargo" ] || { echo >&2 "[ERROR] 'cargo' is not on PATH (rustup shims missing from ~/.cargo/bin). Run 'rustup-init -y', then open a new terminal."; exit 1; } @@ -226,27 +253,13 @@ ifeq ($(APP_NAME),stack_wallet) @command -v go >/dev/null 2>&1 || { echo >&2 "[ERROR] Go not installed (needed for Stack Wallet's MWEB build)."; exit 1; } endif @command -v cmake >/dev/null 2>&1 || { echo >&2 "[ERROR] CMake not installed."; exit 1; } - @command -v protoc >/dev/null 2>&1 || { echo >&2 "[ERROR] protoc not installed (protobuf); use 'nix develop' or your package manager."; exit 1; } - @command -v meson >/dev/null 2>&1 || { \ - if [ "$(PLATFORM)" = "Darwin" ]; then \ - echo >&2 "[ERROR] Meson not installed. Use 'nix develop' (recommended) or run 'make bootstrap-macos'."; \ - elif [ "$(PLATFORM)" = "Linux" ]; then \ - echo >&2 "[ERROR] Meson not installed. On Linux/NixOS, run in 'nix develop' or install meson via your package manager."; \ - else \ - echo >&2 "[ERROR] Meson not installed. Install via your package manager."; \ - fi; \ - exit 1; \ - } - @command -v ninja >/dev/null 2>&1 || { \ - if [ "$(PLATFORM)" = "Darwin" ]; then \ - echo >&2 "[ERROR] Ninja not installed. Use 'nix develop' (recommended) or run 'make bootstrap-macos'."; \ - elif [ "$(PLATFORM)" = "Linux" ]; then \ - echo >&2 "[ERROR] Ninja not installed. On Linux/NixOS, run in 'nix develop' or install ninja via your package manager."; \ - else \ - echo >&2 "[ERROR] Ninja not installed. Install via your package manager."; \ - fi; \ - exit 1; \ - } +ifeq ($(PLATFORM),Linux) + @command -v protoc >/dev/null 2>&1 || { echo >&2 "[ERROR] protoc not installed (protobuf, needed for the Linux build)."; exit 1; } +ifeq ($(SYSTEM_DEPS),0) + @command -v meson >/dev/null 2>&1 || { echo >&2 "[ERROR] Meson not installed (needed to build sysprof/libsecret; use SYSTEM_DEPS=1 to use host libraries)."; exit 1; } + @command -v ninja >/dev/null 2>&1 || { echo >&2 "[ERROR] Ninja not installed (needed to build sysprof/libsecret; use SYSTEM_DEPS=1 to use host libraries)."; exit 1; } +endif +endif ifneq ($(OS),Windows_NT) @command -v pkg-config >/dev/null 2>&1 || { echo >&2 "[ERROR] pkg-config not installed."; exit 1; } endif @@ -333,14 +346,10 @@ sccache-setup: ## Opt-in: use sccache for the Rust/C builds run by native-asset @echo "never reach the hooks; cargo reads this file via HOME. Flutter versions with hooks_runner >= 1.6.2" @echo "also pass CARGO_BUILD_RUSTC_WRAPPER=sccache from the environment. See sccache --show-stats." -verify-bom: ## Check the local toolchain and the pinned plugins against stack-bom.toml +verify-bom: ## Check the local toolchain against stack-bom.toml @[ -n "$(DART)" ] || { echo >&2 "[ERROR] Dart not installed (needed for verify-bom). Install Flutter or pass DART=/path/to/dart."; exit 1; } @bash scripts/bom_values.sh --check - @FLUTTER="$(FLUTTER)" "$(DART)" tool/verify_bom.dart - -verify-bom-plugins: ## Check only the pinned plugin refs against pubspec.lock - @[ -n "$(DART)" ] || { echo >&2 "[ERROR] Dart not installed (needed for verify-bom-plugins). Install Flutter or pass DART=/path/to/dart."; exit 1; } - @FLUTTER="$(FLUTTER)" "$(DART)" tool/verify_bom.dart --plugins + @FLUTTER="$(FLUTTER)" "$(DART)" tool/verify_bom.dart --app "$(APP_NAME)" cache-stats: ## Show sccache statistics (hit rate) after a build @command -v sccache >/dev/null 2>&1 || { echo >&2 "[ERROR] sccache not installed."; exit 1; } @@ -359,11 +368,12 @@ clean: ## Remove artifacts and fix permissions # --- PLATFORM BUILDS --- -# dnix mode. Only the Nix/direnv toolchain can build the pinned native -# libraries from source: it is the default on Apple Silicon macOS and on Linux -# inside nix develop/direnv. Intel macOS, brew/manual/host toolchains, Windows -# and CI use verified prebuilts. PREBUILTS=1 passes -d and needs no Nix for -# those four libraries; PREBUILTS=0 builds them with Nix and verifies hashes. +# dnix mode. A source build needs Nix on PATH to build the pinned native +# libraries. It is the default on Apple Silicon macOS and on Linux; Intel +# macOS, Windows and CI use verified prebuilts. PREBUILTS=1 passes -d and +# needs no Nix for those four libraries; PREBUILTS=0 builds them with Nix and +# verifies hashes. Any macOS/Linux toolchain can build from source when Nix +# is installed: the restriction is the nix binary, not the setup route. ifeq ($(strip $(SOURCE_TOOLCHAIN)),) PREBUILTS_DEFAULT := 1 else ifeq ($(PLATFORM),Darwin) @@ -388,9 +398,6 @@ ifneq ($(filter $(PREBUILTS),0 1),$(PREBUILTS)) $(error PREBUILTS must be 0 or 1) endif ifeq ($(PREBUILTS),0) - ifeq ($(strip $(SOURCE_TOOLCHAIN)),) - $(error PREBUILTS=0 requires TOOLCHAIN=nix or direnv; use PREBUILTS=1 with Homebrew/manual/host) - endif ifeq ($(PLATFORM),Darwin) ifeq ($(filter arm64 aarch64,$(UNAME_M)),) $(error PREBUILTS=0 (dnix source) requires Apple Silicon on macOS; use the default PREBUILTS=1) @@ -407,7 +414,7 @@ ifneq ($(filter MINGW% MSYS%,$(PLATFORM)),) $(error build-windows uses verified dnix prebuilts; run build_app.sh for source mode) endif endif -# Android source builds through dnix need an x86_64 Linux host in Nix/direnv. +# Android source builds through dnix need an x86_64 Linux host with Nix on PATH. # Every other host defaults to the verified prebuilts; that combination # follows PREBUILTS. ANDROID_ARCH := $(UNAME_M) @@ -484,8 +491,10 @@ diagnose-env-macos: ## Print macOS build env and tool resolution @echo "NIX_LDFLAGS=$${NIX_LDFLAGS:-}" @echo "NIX_CFLAGS_LINK=$${NIX_CFLAGS_LINK:-}" -build-linux: export PUB_CACHE := $(LINUX_PUB_CACHE) -build-linux: require-version verify-bom check-linux toolchain-check check-reqs ## Build Linux release (source in Nix/direnv; PREBUILTS=1 uses verified prebuilts) +# Respect a caller's PUB_CACHE. Only NixOS needs the repo-local cache (for the +# protoc workaround below); elsewhere use the normal per-user cache. +build-linux: export PUB_CACHE := $(or $(PUB_CACHE),$(if $(wildcard /etc/NIXOS),$(LINUX_PUB_CACHE)),$(HOME)/.pub-cache) +build-linux: require-version verify-bom check-linux toolchain-check check-reqs ## Build Linux release (source when nix is on PATH; PREBUILTS=1 uses verified prebuilts) @echo "--- Running prebuild bootstrap..." @cd scripts && bash prebuild.sh @echo "--- Generating config..." @@ -493,14 +502,14 @@ build-linux: require-version verify-bom check-linux toolchain-check check-reqs # @cd scripts && $(if $(filter 1,$(CONFIRM)),yes yes |,) BUILD_ISAR_FROM_SOURCE=0 PROTOC="$(PROTOC_PATH)" ./build_app.sh -a "$(APP_NAME)" -p linux -v $(VERSION) -b $(BUILD_NUM) $(if $(filter 1,$(PREBUILTS)),-d) $(if $(filter 1,$(SYSTEM_DEPS)),-s) @# Flutter 3.47.x hooks only see a filtered environment, so PROTOC (exported by the flake) never @# reaches cargo build scripts. Some crates (prost-build 0.7) ship a generic-Linux protoc that cannot - @# run on NixOS. cargo reads [env] from .cargo/config.toml found from the package dir upwards, which - @# works because PUB_CACHE is project-local. Existing files are not touched. - @if [ ! -e .cargo/config.toml ]; then \ - mkdir -p .cargo; \ + @# run on NixOS. cargo reads [env] from .cargo/config.toml found from the package dir upwards; the + @# project-local PUB_CACHE under /etc/NIXOS keeps that lookup inside the checkout. + @# Rewrite the file when the store path changes or the recorded path is gone. + @mkdir -p .cargo; \ + recorded=$$(sed -n 's/^PROTOC = "\(.*\)"$$/\1/p' .cargo/config.toml 2>/dev/null | head -n 1); \ + if [ ! -e .cargo/config.toml ] || [ "$$recorded" != "$(PROTOC_PATH)" ] || [ ! -e "$$recorded" ]; then \ printf '[env]\nPROTOC = "%s"\n' "$(PROTOC_PATH)" > .cargo/config.toml; \ echo "[OK] Wrote .cargo/config.toml (PROTOC=$(PROTOC_PATH))"; \ - else \ - echo "[INFO] .cargo/config.toml exists; make sure it sets [env] PROTOC if protoc fails to run (NixOS)."; \ fi @echo "--- Building app..." @"$(FLUTTER)" pub get @@ -508,16 +517,12 @@ build-linux: require-version verify-bom check-linux toolchain-check check-reqs # USE_SYSTEM_SECURE_STORAGE_DEPS=1 PROTOC="$(PROTOC_PATH)" "$(FLUTTER)" build linux --release; \ else \ SYSPROF_PC_DIR="$${SYSPROF_PC_DIR:-}"; \ - if [ -z "$$SYSPROF_PC_DIR" ] && [ -n "$$IN_NIX_SHELL$$NIX_STORE" ]; then \ - SYSPROF_PC_DIR=$$(dirname "$$(find /nix/store -path '*/lib/pkgconfig/sysprof-capture-4.pc' 2>/dev/null | head -n1)"); \ - [ "$$SYSPROF_PC_DIR" != "." ] || SYSPROF_PC_DIR=""; \ - fi; \ PC_PATH=$$(pkg-config --variable=pc_path pkg-config 2>/dev/null || echo ""); \ - PKG_CONFIG_DISABLE_UNINSTALLED=1 PKG_CONFIG_PATH= \ + PKG_CONFIG_DISABLE_UNINSTALLED=1 PKG_CONFIG_PATH="$${PKG_CONFIG_PATH:-}" \ PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc$${SYSPROF_PC_DIR:+:$$SYSPROF_PC_DIR}:$$PC_PATH" \ pkg-config --modversion libsecret-1 >/dev/null || \ { echo "[ERROR] libsecret-1 not resolvable via pkg-config"; exit 1; }; \ - PKG_CONFIG_DISABLE_UNINSTALLED=1 PKG_CONFIG_PATH= \ + PKG_CONFIG_DISABLE_UNINSTALLED=1 PKG_CONFIG_PATH="$${PKG_CONFIG_PATH:-}" \ PKG_CONFIG_LIBDIR="$(CURDIR)/scripts/linux/pc$${SYSPROF_PC_DIR:+:$$SYSPROF_PC_DIR}:$$PC_PATH" \ PROTOC="$(PROTOC_PATH)" "$(FLUTTER)" build linux --release; \ fi @@ -527,7 +532,7 @@ build-linux: require-version verify-bom check-linux toolchain-check check-reqs # # Windows: run from Git Bash. Same steps as the "build-windows" job in .github/workflows/build.yaml. # Windows uses verified dnix prebuilts; source mode needs Nix inside WSL2 and is # driven by build_app.sh directly, not by this target. -build-windows: require-version verify-bom-plugins check-windows toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) +build-windows: require-version verify-bom check-windows toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @cd scripts && bash prebuild.sh @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a "$(APP_NAME)" -d @@ -539,7 +544,7 @@ build-windows: require-version verify-bom-plugins check-windows toolchain-check # (docker build --target android). Run `make android-dev-key` to create a throw-away debug key when # android/key.properties is missing; build-android requires that file and the APKs are not suitable for distribution. android-dev-key: ## Create a throw-away debug signing key if android/key.properties is missing (never use for releases) - @command -v keytool >/dev/null 2>&1 || { echo >&2 "[ERROR] keytool not found; install a JDK."; exit 1; } + @keytool -help >/dev/null 2>&1 || { echo >&2 "[ERROR] keytool not found; install a JDK (macOS /usr/bin/keytool is a stub)."; exit 1; } @umask 077; if [ ! -f android/key.properties ]; then \ echo "[INFO] android/key.properties missing: creating a throw-away debug key (not for releases)"; \ keytool -genkeypair -keystore android/dev-keystore.jks -storetype pkcs12 -storepass android -keypass android \ @@ -548,13 +553,13 @@ android-dev-key: ## Create a throw-away debug signing key if android/key.propert fi @chmod 600 android/key.properties android/dev-keystore.jks 2>/dev/null || true -build-android: require-version verify-bom-plugins toolchain-check ## Build Android APKs (requires android/key.properties; prebuilt unless x86_64 Linux in Nix/direnv follows PREBUILTS) +build-android: require-version verify-bom toolchain-check ## Build Android APKs (requires android/key.properties; prebuilt unless x86_64 Linux in Nix/direnv follows PREBUILTS) @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } @[ -f android/key.properties ] || { echo >&2 "[ERROR] android/key.properties is missing. Run 'make android-dev-key' for a local throw-away key; never distribute APKs signed with it."; exit 1; } @if grep -q '^keyAlias=devkey$$' android/key.properties 2>/dev/null; then \ echo "[WARN] Signing with the public throw-away dev key; this APK is for local testing only."; \ fi - @[ -n "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ] || { echo >&2 "[ERROR] ANDROID_SDK_ROOT is not set (Android SDK/NDK required)."; exit 1; } + @if [ -z "$$ANDROID_SDK_ROOT$$ANDROID_HOME" ]; then echo "[WARN] ANDROID_SDK_ROOT/ANDROID_HOME not set; using the SDK Flutter is configured with."; fi @cd scripts && bash prebuild.sh @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p android -a "$(APP_NAME)" $(if $(filter 1,$(ANDROID_PREBUILTS)),-d) @"$(FLUTTER)" pub get From 322c944deef21f32cdd8d00e109247c9140d3820 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:51:37 +0200 Subject: [PATCH 069/107] fix(flake): stable shell wrapper paths, unconditional clang/patchelf The macOS shellHook created a fresh mktemp wrapper dir on every `nix develop` entry and exported STACKWALLET_NIX_BIN for reuse. A random temp path is lost on the next `make clean`, forcing the dnix hooks to rebuild the native libraries and invalidating the build cache. Use a stable per-checkout dir under .dart_tool (recreated, never deleted) with a stable TMPDIR, and drop the env-var reuse branch (S4). Also prepend the clang wrapper and patchelf 0.18 unconditionally: the buildInputs always place them on PATH, so the membership test that decided whether to prepend them never fired (A6). --- flake.nix | 45 ++++++++++++++++++++------------------------- 1 file changed, 20 insertions(+), 25 deletions(-) diff --git a/flake.nix b/flake.nix index de47480386..ba6c1b9365 100644 --- a/flake.nix +++ b/flake.nix @@ -121,9 +121,6 @@ fi done - # Pin this checkout without replacing the user's global rustup default. - rustup override set ${rustVersion} --path "$APP_PROJECT_ROOT_DIR" >/dev/null 2>&1 || true - if [[ "${system}" == *"darwin"* ]]; then rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios aarch64-apple-ios-sim --toolchain ${rustVersion} fi @@ -136,15 +133,11 @@ # Flutter's Linux CMake build forces CC=clang/CXX=clang++. libclang # also puts the unwrapped clang first on PATH, which cannot find # the NixOS crt/libstdc++ paths; prefer the clang wrapper. - case ":$PATH:" in - *":${pkgs.llvmPackages.clang}/bin:"*) ;; - *) export PATH="${pkgs.llvmPackages.clang}/bin:$PATH" ;; - esac + # Unconditional: buildInputs always puts these somewhere on PATH, + # so a membership test would never prepend them. Runs once per shell. + export PATH="${pkgs.llvmPackages.clang}/bin:$PATH" # stdenv also provides patchelf 0.15; put 0.18 first. - case ":$PATH:" in - *":${pkgs.patchelfUnstable}/bin:"*) ;; - *) export PATH="${pkgs.patchelfUnstable}/bin:$PATH" ;; - esac + export PATH="${pkgs.patchelfUnstable}/bin:$PATH" export LIBCLANG_PATH="${pkgs.llvmPackages.libclang.lib}/lib" export BINDGEN_EXTRA_CLANG_ARGS="-isystem ${pkgs.llvmPackages.libclang.lib}/lib/clang/${clangMajor}/include" export PROTOC="${pkgs.protobuf}/bin/protoc" @@ -195,15 +188,21 @@ fi export PROTOC="${pkgs.protobuf}/bin/protoc" - # A repo-writable directory on PATH would let anything that can - # write to the checkout shadow tools for the rest of the session. - if [ -n "''${STACKWALLET_NIX_BIN:-}" ] && [ -x "$STACKWALLET_NIX_BIN/xcrun" ]; then - NIX_BIN="$STACKWALLET_NIX_BIN" - case ":$PATH:" in - *":$NIX_BIN:"*) ;; - *) export PATH="$NIX_BIN:$PATH" ;; - esac - elif NIX_BIN="$(/usr/bin/mktemp -d "''${TMPDIR:-/tmp}/stackwallet-nix-bin.XXXXXX")"; then + # Stable, per-checkout wrapper directory instead of a fresh + # mktemp dir on every entry. A random temp path is lost on the + # next clean and forces the hooks to rebuild native libs; a + # stable path under .dart_tool is recreated (never deleted) on + # every shell entry, so a second `nix develop` reuses the same + # wrappers and the native build cache stays valid. + NIX_BIN="$APP_ROOT/.dart_tool/nix-bin" + mkdir -p "$NIX_BIN" + # Stable TMPDIR for the wrappers; keeps extracted build scratch + # under the checkout so it is not orphaned in /tmp. + export TMPDIR="$APP_ROOT/.dart_tool/tmp" + mkdir -p "$TMPDIR" + + # Symlinks for the system compilers. Recreated every entry; the + # directory itself is never removed. ln -sf /usr/bin/clang "$NIX_BIN/cc" ln -sf /usr/bin/clang++ "$NIX_BIN/c++" ln -sf /usr/bin/clang "$NIX_BIN/clang" @@ -220,7 +219,7 @@ for arg in "$@"; do if [[ "$arg" == *"FlutterMacOS.framework"* ]]; then framework="''${arg%%FlutterMacOS.framework*}FlutterMacOS.framework" case "$framework" in - "$PWD"/*|"''${TMPDIR:-/tmp}"/*) chmod -R u+w "$framework" 2>/dev/null || true ;; + "$APP_ROOT"/*|"''${TMPDIR:-/tmp}"/*) chmod -R u+w "$framework" 2>/dev/null || true ;; *) ;; esac fi @@ -251,7 +250,6 @@ XCRUN_EOF chmod +x "$NIX_BIN/xcrun" if [ -x "$NIX_BIN/lipo" ] && [ -x "$NIX_BIN/xcrun" ]; then - export STACKWALLET_NIX_BIN="$NIX_BIN" case ":$PATH:" in *":$NIX_BIN:"*) ;; *) export PATH="$NIX_BIN:$PATH" ;; @@ -259,9 +257,6 @@ XCRUN_EOF else echo "[WARN] Apple tool wrappers are incomplete; using the Nix tools." >&2 fi - else - echo "[WARN] Could not create the Apple tool wrapper directory; using the Nix tools." >&2 - fi ''} ''; From 9f884739000f78913c91f03004ee28e6b8dfcacc Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:51:43 +0200 Subject: [PATCH 070/107] fix(verify-bom): app-aware, Go optional, plugin pins from lock - Go is optional: a missing Go is now a warning, not a failure; only apps that build Go components need it (S7). - The plugin check returns early when the BOM carries no [plugins] table, so a fresh checkout without plugin pins no longer errors (S8). - `--update` refuses to create a [plugins] table in a BOM that does not carry one; plugin pins live in pubspec.lock now (D4). - stack-bom.toml drops the [plugins] section and aligns the recommended Flutter/Xcode pins (3.47.2 / 27.0) with what CI verified (D2). --- stack-bom.toml | 19 +++++-------------- tool/verify_bom.dart | 20 ++++++++++++++++++-- 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/stack-bom.toml b/stack-bom.toml index af1b048b3e..5184a0e898 100644 --- a/stack-bom.toml +++ b/stack-bom.toml @@ -1,11 +1,11 @@ # Stack Wallet build bill of materials: the toolchain a build is expected to use. -# Checked by `make verify-bom` (dart tool/verify_bom.dart). This is a toolchain and -# plugin-pin file, not a Homebrew package manifest; the native dnix libraries are -# pinned in each plugin's dnix.lock. +# Checked by `make verify-bom` (dart tool/verify_bom.dart). This is a toolchain +# file, not a Homebrew package manifest; the native dnix libraries are pinned in +# each plugin's dnix.lock and pubspec.lock pins the plugins themselves. schema_version = 1 [toolchain] -flutter = "3.47.4" # recommended; macOS builds verified with 3.47.2 and 3.47.4 +flutter = "3.47.2" # recommended; macOS builds verified with 3.47.2 and 3.47.4 flutter_min = "3.47.2" # minimum for pubspec.template.yaml and the release workflow; Dockerfile mirrors it dart_prefix = "3.13" # Dart bundled with Flutter 3.47.x rust = "1.99.1" # installed through rustup, pinned by the native plugins @@ -14,14 +14,5 @@ go = "1.24.13" # CI/Docker pin; nix develop uses nixpkgs' newer Go go_min = "1.24.1" # flutter_mwebd's minimum on the Flutter host [macos] -xcode = "27.1" # recommended for app builds +xcode = "27.0" # recommended for app builds xcode_dnix = "27.0" # dnix needs this one to rebuild Apple libraries byte for byte - -[plugins] -# Generated by `dart tool/verify_bom.dart --update` from pubspec.lock. Do not edit by hand. -flutter_libepiccash = "63e93b01c3c4c68a52b26a43e4442a4738d5e7e8" -flutter_libmwc = "5722fb3ba05c8f52e8e0255c485ae5ea52e9a694" -flutter_libsparkmobile = "3fdcb21160a39c051a0e73d7ae04f987134ecd5f" -frostdart = "f7fea2a926ea88e2eb6a353579372188d6915314" -tor_ffi_plugin = "6e954a9d5a0aaaafb861049b79041d7ae98c2a08" -xelis_wallet_flutter = "8630a2cf28947497ec67b7535ddf1fac4cedbaa8" diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 152edbf206..4d0d2a6575 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -2,7 +2,7 @@ // stack-bom.toml. // // dart tool/verify_bom.dart check, exit 1 on a mismatch -// dart tool/verify_bom.dart --update rewrite the [plugins] section from pubspec.lock +// dart tool/verify_bom.dart --update refresh an existing [plugins] section from pubspec.lock // // No packages needed, so it runs before `flutter pub get`. import 'dart:convert'; @@ -189,6 +189,13 @@ void _requireSinglePluginsSection(String text) { } Future _update() async { + if ((_readBom(File(_bomFile).readAsStringSync())['plugins'] ?? {}).isEmpty) { + stderr.writeln( + 'Plugin pins are not stored in $_bomFile; pubspec.lock pins them. ' + 'Run flutter pub get instead.', + ); + exit(2); + } final refs = _lockRefs(); if (refs.isEmpty) { stderr.writeln('pubspec.lock not found or has none of the plugins.'); @@ -197,6 +204,12 @@ Future _update() async { final text = File(_bomFile).readAsStringSync(); _requireSinglePluginsSection(text); final existing = _readBom(text)['plugins'] ?? {}; + // Plugin pins live in pubspec.lock now. Refresh an existing table for older + // branches, but never create one in a BOM that does not carry it. + if (existing.isEmpty && !RegExp(r'\[plugins\]').hasMatch(text)) { + stdout.writeln('No [plugins] table in $_bomFile; nothing to update.'); + return; + } final declared = _declaredPlugins(); // Without a pubspec.yaml we cannot tell which app is configured; keep the // old behaviour and update every plugin the lock knows about. @@ -263,6 +276,9 @@ Never _finish() { void _checkPlugins(Map> bom) { final refs = _lockRefs(); final pinned = bom['plugins'] ?? {}; + // Plugin pins are no longer stored in the BOM; pubspec.lock is the source of + // truth. Keep the parser for older branches that still carry a [plugins] table. + if (pinned.isEmpty) return; final declared = _declaredPlugins(); final pubspecExists = File('pubspec.yaml').existsSync(); // A fresh checkout has no pubspec.yaml: build_app.sh generates it later. @@ -402,7 +418,7 @@ Future main(List args) async { final go = await _run('go', ['version']); final gm = go == null ? null : RegExp(r'go(\d+\.\d+(\.\d+)?)').firstMatch(go); if (gm == null) { - _fail('go not found in PATH'); + _warn('go not found in PATH; only apps that build Go components need it'); } else if (_cmp(gm.group(1)!, tc['go_min'] ?? '0') < 0) { _fail('Go ${gm.group(1)} is older than the minimum ${tc['go_min']}'); } else { From 5699acb0a7aa2b7d51d73bdc3315d721cca9dd67 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:51:50 +0200 Subject: [PATCH 071/107] fix(install): opt-in profile write, managed Flutter, DNSSEC Rust - The macOS installer no longer edits ~/.zshrc by default; it prints the PATH lines to add and exits, and only writes the profile with WRITE_PROFILE=1 (A5). The printed Flutter path is shell-quoted so a path with spaces survives (A5). - The installer refuses to checkout-advance a Flutter it did not create, guarded by a .stack-wallet-managed marker; a foreign checkout is left alone (A5). - A user-owned Xcode is now selected with sudo instead of refused, since .xip/xcodes installs are user-owned on purpose (A4). Refusing an Xcode outside /Applications is kept. - An early confirmation abort now prints and exits non-zero (A1). - The DNSSEC Rust 1.90.0 toolchain is installed up front so verify-bom (which runs before the build hooks) sees it; the global rustup default is no longer pinned (M9). --- scripts/build_app.sh | 2 +- scripts/install_macos_build_tools.sh | 44 +++++++++++++++++++++++----- scripts/install_xcode.sh | 5 ++-- 3 files changed, 40 insertions(+), 11 deletions(-) diff --git a/scripts/build_app.sh b/scripts/build_app.sh index d85927ee56..eb9f67645a 100755 --- a/scripts/build_app.sh +++ b/scripts/build_app.sh @@ -25,7 +25,7 @@ confirmDisclaimer() { fi case $response in [Yy][Ee][Ss] ) echo "Continuing..."; break;; - [Nn][Oo] ) exit 0;; + [Nn][Oo] ) echo >&2 "Aborted."; exit 1;; * ) echo "Invalid response";; esac done diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh index a7355f51e3..7f642981bd 100755 --- a/scripts/install_macos_build_tools.sh +++ b/scripts/install_macos_build_tools.sh @@ -71,6 +71,7 @@ else FLUTTER_ACCEPTED_VERSIONS="$FLUTTER_VERSION" fi FLUTTER_DIR="${FLUTTER_DIR:-$HOME/development/flutter}" +FLUTTER_MARKER=".stack-wallet-managed" case "$FLUTTER_DIR" in /*) ;; *) FLUTTER_DIR="$PWD/$FLUTTER_DIR" ;; @@ -100,6 +101,10 @@ if flutter_version_ok "$CURRENT_FLUTTER"; then else [[ -n "$CURRENT_FLUTTER" ]] && echo "Found Flutter $CURRENT_FLUTTER at $FLUTTER_BIN, need $FLUTTER_VERSION." if [[ -d "$FLUTTER_DIR/.git" ]]; then + if [[ ! -e "$FLUTTER_DIR/$FLUTTER_MARKER" ]]; then + die "$FLUTTER_DIR is an existing Flutter checkout that this script did not create. +Move it away, or set FLUTTER_DIR to a directory this script may manage." + fi echo "Switching $FLUTTER_DIR to Flutter $FLUTTER_VERSION..." git -C "$FLUTTER_DIR" fetch --tags origin git -C "$FLUTTER_DIR" checkout "$FLUTTER_VERSION" @@ -130,9 +135,14 @@ RUST_VERSION="${RUST_VERSION:-1.99.1}" echo "Ensuring Rust $RUST_VERSION toolchain..." rustup toolchain install "$RUST_VERSION" rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios aarch64-apple-ios-sim --toolchain "$RUST_VERSION" >/dev/null 2>&1 || true -# Pin this checkout instead of changing the user's global rustup default; the -# native-asset crates also carry their own rust-toolchain.toml. -rustup override set "$RUST_VERSION" --path "$REPO_ROOT" >/dev/null 2>&1 || true + +# DNSSEC native builds (via native_dependency_contract) pin their own Rust +# toolchain through rust-toolchain.toml. verify-bom runs before the build hooks +# get a chance to install it, so install it here as well. +DNSSEC_RUST_VERSION="${DNSSEC_RUST_VERSION:-$(bom_get rust_dnssec || true)}" +DNSSEC_RUST_VERSION="${DNSSEC_RUST_VERSION:-1.90.0}" +echo "Ensuring Rust $DNSSEC_RUST_VERSION toolchain (DNSSEC)..." +rustup toolchain install "$DNSSEC_RUST_VERSION" >/dev/null 2>&1 || true # Homebrew's rustup formula is keg-only and does not necessarily create the # cargo/rustc shims in ~/.cargo/bin — `rustup toolchain install` alone may leave @@ -149,7 +159,10 @@ fi # cargo/rustc live in ~/.cargo/bin after rustup installs a toolchain export PATH="$HOME/.cargo/bin:$PATH" -source "$HOME/.cargo/env" 2>/dev/null || true +if [ -f "$HOME/.cargo/env" ]; then + # shellcheck disable=SC1091 + source "$HOME/.cargo/env" +fi if ! command -v cargo >/dev/null 2>&1; then die "cargo still not on PATH after rustup setup. Run 'rustup-init -y' manually, then re-run this script." @@ -173,6 +186,7 @@ fi rustup --version rustup run "$RUST_VERSION" rustc --version rustup run "$RUST_VERSION" cargo --version +rustup run "$DNSSEC_RUST_VERSION" rustc --version pod --version go version autoreconf --version | head -n 1 || true @@ -181,10 +195,24 @@ aclocal --version | head -n 1 || true echo "" echo "Done." -# Persist PATH entries for future terminals. Create ~/.zshrc when missing: a -# vanilla macOS install ships without one, and this block used to skip silently -# in that case — leaving new shells unable to find cargo/rustup and -# making `source`ing this script the only way to get a usable environment. +# Persist PATH entries for future terminals. This is opt-in: bootstrap must not +# edit a shell profile the user did not ask it to touch. Set WRITE_PROFILE=1 +# (or run with --write-profile) to apply the lines automatically. +if [ "${WRITE_PROFILE:-0}" != "1" ]; then + echo "" + echo "→ Not modifying $HOME/.zshrc." + echo " Add these lines to your shell profile, or re-run with WRITE_PROFILE=1:" + echo " eval \"\$($(brew --prefix)/bin/brew shellenv)\"" + if [ -n "${FLUTTER_PATH_TO_PERSIST:-}" ]; then + printf ' export PATH=%s:$PATH\n' "$(printf '%q' "$FLUTTER_PATH_TO_PERSIST")" + fi + printf ' export PATH="%s/opt/rustup/bin:$HOME/.cargo/bin:$PATH"\n' "$(brew --prefix)" + echo "" + echo "Done." + exit 0 +fi + +# Create ~/.zshrc when missing: a vanilla macOS install ships without one, and ZSHRC="$HOME/.zshrc" if [ ! -f "$ZSHRC" ]; then touch "$ZSHRC" diff --git a/scripts/install_xcode.sh b/scripts/install_xcode.sh index fee1d6c686..04e4c36f7a 100755 --- a/scripts/install_xcode.sh +++ b/scripts/install_xcode.sh @@ -67,8 +67,9 @@ else /Applications/*) ;; *) die "[ERROR] Refusing to sudo-select an Xcode outside /Applications: $XCODE_APP" ;; esac - [[ "$(/usr/bin/stat -f '%Su' -L "$XCODE_APP")" == "root" ]] || \ - die "[ERROR] Refusing to sudo-select a user-owned Xcode bundle: $XCODE_APP" + # A .xip or `xcodes` install is owned by the user, and + # tool/setup_xcode.dart installs with --no-superuser on purpose. xcode-select + # still needs root, so select it with sudo instead of refusing the bundle. sudo xcode-select -s "$XCODE_APP/Contents/Developer" JUST_SELECTED=1 fi From 035dd9df0126624a5efccaa8b8138c76a039a047 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:51:56 +0200 Subject: [PATCH 072/107] fix(linux): stop overwriting coinlib's secp256k1 output The Linux build copied the repo's libsecp256k1 into coinlib's output folder (build/linux//release/secp256k1/lib). coinlib builds its own pinned libsecp256k1 there; overwriting it made a rebuilt bundle ship a different version than a clean build. Leave coinlib's output alone; if the library is missing, fix the coinlib build (S6). --- scripts/linux/build_secp256k1.sh | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/scripts/linux/build_secp256k1.sh b/scripts/linux/build_secp256k1.sh index 6bfbe815da..bd896a7b11 100755 --- a/scripts/linux/build_secp256k1.sh +++ b/scripts/linux/build_secp256k1.sh @@ -28,12 +28,8 @@ fi mkdir -p ../../../../../build cp "$SECP_SO" ../../../../../build/libsecp256k1.so -# The coinlib CMake install step expects the library inside Flutter's build -# tree. Match Flutter's architecture directory name (x64, arm64). -case "$(uname -m)" in - x86_64|x64) FLUTTER_ARCH=x64 ;; - aarch64|arm64) FLUTTER_ARCH=arm64 ;; - *) FLUTTER_ARCH="$(uname -m)" ;; -esac -mkdir -p "../../../../../build/linux/${FLUTTER_ARCH}/release/secp256k1/lib" -cp "$SECP_SO" "../../../../../build/linux/${FLUTTER_ARCH}/release/secp256k1/lib/libsecp256k1.so" +# Do not copy into coinlib's output folder +# (build/linux//release/secp256k1/lib). coinlib builds its own pinned +# libsecp256k1 there; overwriting it made a rebuilt bundle ship a different +# version than a clean build. If that library is missing on a host, fix the +# coinlib build instead of patching its output from here. From cd6e463f22dba2b27154e1465b034270054f5a74 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:51:56 +0200 Subject: [PATCH 073/107] fix(link-assets): host-based Windows detection Asset linking detected Windows by the build platform ($2='windows'), which is wrong for a Linux host building the Windows target. Detect the Windows *host* via uname (MINGW/MSYS/CYGWIN) so copies happen on a real Windows host and symlinks elsewhere (D5). --- scripts/app_config/shared/link_assets.sh | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/scripts/app_config/shared/link_assets.sh b/scripts/app_config/shared/link_assets.sh index 624a418495..fab8fe9ece 100755 --- a/scripts/app_config/shared/link_assets.sh +++ b/scripts/app_config/shared/link_assets.sh @@ -15,13 +15,17 @@ APP_BUILD_PLATFORM=$2 ASSET_SOURCES_DIR="${APP_PROJECT_ROOT_DIR}/asset_sources" ASSETS_DIR="${APP_PROJECT_ROOT_DIR}/assets" -# Windows gets real copies: symlink privilege is not guaranteed and the asset -# tree is small. Other platforms use symlinks. +# Windows hosts get real copies: symlink privilege is not guaranteed and the +# asset tree is small. Other hosts use symlinks. +WINDOWS_HOST=0 +case "$(uname -s)" in +MINGW*|MSYS*|CYGWIN*) WINDOWS_HOST=1 ;; +esac for dirname in "default_themes" "icon" "lottie" "in_app_logo_icons" "svg"; do LINK_SOURCE_DIR="${ASSET_SOURCES_DIR}/${dirname}/${SELECT_ASSETS_DIR}" # Remove an old Windows junction as a link, not by recursing into its target. - if [[ "${APP_BUILD_PLATFORM}" = 'windows' && -d "${ASSETS_DIR}/${dirname}" ]]; then + if [[ "${WINDOWS_HOST}" = 1 && -d "${ASSETS_DIR}/${dirname}" ]]; then TARGET_WIN_PATH="$(cygpath -w "${ASSETS_DIR}/${dirname}")" if ! MSYS2_ARG_CONV_EXCL="/C" cmd.exe /C rmdir "$TARGET_WIN_PATH" 2>/dev/null; then # A real copy directory cannot be removed by rmdir; a reparse point must @@ -32,9 +36,14 @@ for dirname in "default_themes" "icon" "lottie" "in_app_logo_icons" "svg"; do fi fi fi - rm -rf "${ASSETS_DIR:?}/${dirname:?}" + if [[ "${WINDOWS_HOST}" = 1 ]]; then + rm -rf "${ASSETS_DIR:?}/${dirname:?}" + else + # Only symlinks here: rm -f refuses a real directory instead of deleting it. + rm -f "${ASSETS_DIR:?}/${dirname:?}" + fi - if [[ "${APP_BUILD_PLATFORM}" = 'windows' ]]; then + if [[ "${WINDOWS_HOST}" = 1 ]]; then mkdir -p "${ASSETS_DIR}/${dirname}" cp -r "${LINK_SOURCE_DIR}/." "${ASSETS_DIR}/${dirname}/" else From 040bc72f590584503f8644487a2ec196eec4d661 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:52:02 +0200 Subject: [PATCH 074/107] docs: reflect source-mode and toolchain changes Update the build docs to match the code: source mode needs `nix` on PATH (any toolchain), not the Nix/direnv toolchain; recommended Flutter is 3.47.2 and Xcode 27.0; Windows needs GNU Make for `make build-windows`; the Homebrew installer prints PATH lines and writes ~/.zshrc only with WRITE_PROFILE=1; a NixOS Linux bundle is not distributable. --- README.md | 9 ++++----- docs/building.md | 8 ++++---- docs/building/linux.md | 20 ++++++++++---------- docs/building/macos.md | 19 ++++++++++--------- docs/building/make-flow.md | 2 +- docs/building/make.md | 32 ++++++++++++++++---------------- docs/building/windows.md | 3 ++- 7 files changed, 47 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 714c04ff17..288395242f 100644 --- a/README.md +++ b/README.md @@ -99,8 +99,7 @@ plugin build is needed. Install the prerequisites from [Building on macOS](docs/building/macos.md) yourself, then run `make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1`. -Manual builds are prebuilt-only; source mode requires Nix/direnv. -`make check-reqs-macos` reports what is missing (`make check-sdk-macos` checks -full Xcode); `TOOLCHAIN=manual` makes the choice explicit. Use the -Nix/direnv toolchain for a source build; manual and Homebrew builds are -prebuilt-only. +Manual builds default to `PREBUILTS=1`. Pass `PREBUILTS=0` when `nix` is on +`PATH` to build the dnix libraries from source. `make check-reqs-macos` reports +what is missing (`make check-sdk-macos` checks full Xcode); `TOOLCHAIN=manual` +makes the choice explicit. diff --git a/docs/building.md b/docs/building.md index eeeda75367..c236540c81 100644 --- a/docs/building.md +++ b/docs/building.md @@ -1,7 +1,7 @@ # Building Stack Wallet, Stack Duo and Campfire are built from this repository with -Flutter **3.47.2 minimum, 3.47.4 recommended**. Follow the guide for the computer you build on: +Flutter **3.47.2**. Follow the guide for the computer you build on: | Your computer | What it builds | Guide | |---|---|---| @@ -45,9 +45,9 @@ To switch modes, rerun `build_app.sh`. It regenerates `pubspec.yaml`, so keep permanent changes in `scripts/app_config/templates/pubspec.template.yaml`. The `Makefile` selects the mode by toolchain: on Apple Silicon macOS and -Linux, `TOOLCHAIN=nix`/`direnv` defaults to source; `brew`, `host`, `manual`, -Intel macOS and Windows default to `PREBUILTS=1` (prebuilt). Those toolchains -cannot select source mode. +Linux, `TOOLCHAIN=nix`/`direnv` defaults to source when `nix` is on `PATH`; +`brew`, `host`, `manual` and Windows default to `PREBUILTS=1` +(prebuilt). Any toolchain can pass `PREBUILTS=0` when `nix` is on `PATH`. ## Configuration options diff --git a/docs/building/linux.md b/docs/building/linux.md index 9f5e7bf74a..1f004ccdb2 100644 --- a/docs/building/linux.md +++ b/docs/building/linux.md @@ -7,15 +7,18 @@ These steps build the Linux desktop app and the Android app on Ubuntu 24.04 | What | Needed for | |---|---| -| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 minimum, 3.47.4 recommended | Every build | +| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 | Every build | | The [Ubuntu packages](#ubuntu-packages) below | Every build | | [Rustup](https://rustup.rs/) | Every app, in both modes | | [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet | -| [Nix](https://nixos.org/download/) | Source mode only with Nix/direnv; not needed with `-d` | +| [Nix](https://nixos.org/download/) | Source mode (`PREBUILTS=0`); not needed with `-d` | | The [Android tools](#android-tools) below | Android builds | -Non-Nix toolchains (Homebrew/manual/host) are prebuilt-only: use -`PREBUILTS=1`; source mode requires Nix/direnv. +Source mode needs `nix` on `PATH`; without Nix, use `PREBUILTS=1` (prebuilt). + +A bundle built inside the Nix shell links against Nix's glibc and uses a +`/nix/store` ELF interpreter and RUNPATH, so it runs only on that machine. Use +the Ubuntu image or a host toolchain for a distributable Linux bundle. **Rustup:** every app builds its DNSSEC resolver with Rust **1.90.0**, and Stack Wallet builds Xelis with Rust **1.99.1**. The build hooks install these @@ -81,12 +84,9 @@ plugin project in that SDK. Without a writable Flutter checkout, build in `keyPassword`, `storeFile` and `storePassword`. Use the version and build number for your checkout, and read the script's -confirmation before continuing. Add `-d` to the configuration command to use -verified dnix prebuilts: - -```sh -bash scripts/build_app.sh -a stack_wallet -p linux -v 1.2.3 -b 123 -d -``` +confirmation before continuing. The command above uses `-d` (verified dnix +prebuilts). Omit `-d` when `nix` is on `PATH` to build those libraries from +source. See the [configuration options](../building.md#configuration-options). The override check catches package-local dnix overrides; see diff --git a/docs/building/macos.md b/docs/building/macos.md index 26b3741c34..be7ab4c031 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -24,23 +24,24 @@ manual/Homebrew path. | What | Needed for | |---|---| -| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 minimum, 3.47.4 recommended | Manual and Homebrew modes | -| Your usual Xcode (27.1 recommended) | Building the app, in both dnix modes | +| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 | Manual and Homebrew modes | +| Xcode 27.0 | Building the app, in both dnix modes | | Xcode **27.0**, release build **27A266a**, installed next to your usual Xcode | Source mode (dnix) with Nix/direnv on Apple Silicon: dnix builds its four packages with it, including during `flutter test`. It doesn't need to be selected; see [Install Xcode 27.0](#install-xcode-270) | | [Homebrew](https://brew.sh/) packages below | Manual and Homebrew modes | | [Rustup](https://rustup.rs/) | Manual and Homebrew modes, in both dnix modes | | [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet, manual and Homebrew modes | -| [Nix](https://nixos.org/download/) | Source mode (dnix) only with Nix/direnv; not needed with `-d` | +| [Nix](https://nixos.org/download/) | Source mode (dnix) needs `nix` on `PATH`; not needed with `-d` | ```sh +RUST_BOM="$(scripts/bom_values.sh --get rust)" brew install autoconf automake libtool cmake cocoapods go meson ninja pkg-config protobuf -rustup toolchain install "$(scripts/bom_values.sh --get rust)" -rustup target add aarch64-apple-darwin x86_64-apple-darwin \ +rustup toolchain install 1.90.0 "$RUST_BOM" +rustup target add --toolchain "$RUST_BOM" aarch64-apple-darwin x86_64-apple-darwin \ aarch64-apple-ios aarch64-apple-ios-sim ``` -Homebrew and manual toolchains are prebuilt-only: use `PREBUILTS=1`; they -cannot build the dnix libraries from source. Source mode requires Nix/direnv. +Homebrew and manual toolchains default to `PREBUILTS=1`. Pass `PREBUILTS=0` +when `nix` is on `PATH` to build the dnix libraries from source. Check `nix --version` from the same environment that runs Flutter, and use `flutter doctor` to check the Apple SDK and CocoaPods setup. iOS device builds @@ -140,8 +141,8 @@ Run the configuration and Flutter build commands in that shell. Use the version and build number for your checkout, and read the script's confirmation before continuing. `-d` selects the verified dnix prebuilts and -is required for the manual/Homebrew path. Source mode is only available with -Nix/direnv; see the +is required when `nix` is not on `PATH`. Omit `-d` when `nix` is available to +build from source; see the [configuration options](../building.md#configuration-options). The override check catches package-local dnix overrides; see [Local overrides](native-libraries.md#local-overrides). diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index 3953548a9c..e9654dc97e 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -51,7 +51,7 @@ first-launch setup. An already-selected Xcode is left untouched. Use `VERSION` and `BUILD_NUM` are required. dnix source is only available through the Nix/direnv toolchain: it is the default on Apple Silicon macOS and inside -Nix/direnv on Linux. Homebrew, manual and host toolchains, Intel macOS, CI and +Nix/direnv on Linux. Homebrew, manual and host toolchains, CI and Windows use the verified prebuilts. ```mermaid diff --git a/docs/building/make.md b/docs/building/make.md index f268288c6e..b2b23a792e 100644 --- a/docs/building/make.md +++ b/docs/building/make.md @@ -28,18 +28,18 @@ that is not above the latest `build_*` tag. `APP_NAME` selects the app variant |---|---|---| | `VERSION`, `BUILD_NUM` | required | App version and a build number above the latest release tag | | `APP_NAME` | `stack_wallet` | `stack_wallet`, `stack_duo` or `campfire` | -| `PREBUILTS` | `0` on Apple Silicon/Linux in Nix/direnv; otherwise `1` | `0` builds dnix from source (Nix/direnv only); `1` uses verified prebuilts (`-d`) | -| `ANDROID_PREBUILTS` | follows `PREBUILTS` on x86_64 Linux in Nix/direnv, else `1` | Overrides the Android dnix mode | +| `PREBUILTS` | `0` on Apple Silicon/Linux when `nix` is on `PATH`; otherwise `1` | `0` builds dnix from source (needs `nix`); `1` uses verified prebuilts (`-d`) | +| `ANDROID_PREBUILTS` | follows `PREBUILTS` on x86_64 Linux when `nix` is on `PATH`, else `1` | Overrides the Android dnix mode | | `SYSTEM_DEPS` | `0` | Linux: `1` uses system libsecret/JsonCPP (as CI does) | | `TOOLCHAIN` | `auto` | `auto`, `nix`, `direnv`, `brew`, `host` or `manual` | | `CONFIRM` | `0` | `1` answers build_app.sh's wallet-data warning non-interactively | -Source mode is only available through the **Nix/direnv toolchain**. On Apple -Silicon macOS and Linux inside `nix develop`/direnv, `PREBUILTS=0` is the -default: dnix builds the pinned native libraries from source and verifies their -hashes. Homebrew, manual and host toolchains, plus Intel macOS, default to -`PREBUILTS=1`; `PREBUILTS=0` is rejected with those toolchains. CI passes `-d` -explicitly. +Source mode needs `nix` on `PATH`, whichever toolchain provides the rest of +the build tools. On Apple Silicon macOS and Linux, `PREBUILTS=0` is the +default when `nix` is available: dnix builds the pinned native libraries from +source and verifies their hashes. Without `nix`, the Makefile defaults to +`PREBUILTS=1`; Homebrew, manual and host toolchains can still pass +`PREBUILTS=0` when `nix` is on `PATH`. CI passes `-d` explicitly. ``` make build-macos VERSION=x.y.z BUILD_NUM=nnn # dnix source (Nix/direnv, Apple Silicon) @@ -72,13 +72,13 @@ The build steps are identical in every mode; only how the host tools get on | Mode | Setup | Notes | |---|---|---| -| Nix | `make bootstrap` (enters `nix develop`) | The flake provides Flutter and Go from its pinned nixpkgs (currently Flutter 3.47.4, matching the BOM, and Go 1.26.7; the BOM's `go` is the CI/Docker pin), Dart, rustup (which installs the BOM Rust version on first entry), CMake, Meson, Ninja, pkg-config and protoc. Xcode always comes from the host. | +| Nix | `make bootstrap` (enters `nix develop`) | The flake provides Flutter and Go from its pinned nixpkgs (currently Flutter 3.47.2, matching the BOM, and Go 1.26.7; the BOM's `go` is the CI/Docker pin), Dart, rustup (which installs the BOM Rust version on first entry), CMake, Meson, Ninja, pkg-config and protoc. Xcode always comes from the host. | | direnv | `direnv allow` | The same flake as Nix, loaded automatically. | -| Homebrew | `make bootstrap-macos` (alias `make bootstrap-brew`) | Fallback, prebuilt-only. Installs the Flutter tag and Rust from `stack-bom.toml` plus the Homebrew packages, and adds PATH entries to `~/.zshrc`. | -| Manual | install the tools yourself | Advanced, prebuilt-only. `make check-reqs-macos` reports what is missing. | +| Homebrew | `make bootstrap-macos` (alias `make bootstrap-brew`) | Fallback; source builds need `nix` on `PATH`. Installs the Flutter tag and Rust from `stack-bom.toml` plus the Homebrew packages, and prints the PATH lines to add (pass `WRITE_PROFILE=1` to append them to `~/.zshrc` automatically). | +| Manual | install the tools yourself | Advanced; source builds need `nix` on `PATH`. `make check-reqs-macos` reports what is missing. | `make toolchain` prints the active mode and tool paths. -`TOOLCHAIN=nix|direnv|brew` forces a check; `host` and `manual` use whatever is on `PATH`; `auto` (the default) detects a Nix/direnv shell and otherwise uses the host tools. Only `nix` and `direnv` can use `PREBUILTS=0`; `brew`, `host` and `manual` are prebuilt-only. +`TOOLCHAIN=nix|direnv|brew` forces a check; `host` and `manual` use whatever is on `PATH`; `auto` (the default) detects a Nix/direnv shell and otherwise uses the host tools. Any toolchain can use `PREBUILTS=0` when `nix` is on `PATH`; without it the Makefile defaults to prebuilt mode. `make check-reqs-macos` verifies the result and `make diagnose-env-macos` prints what was found. @@ -86,9 +86,9 @@ The build steps are identical in every mode; only how the host tools get on `make bootstrap-xcode` only checks and selects an installed Xcode. To install one, use `dart tool/setup_xcode.dart` (which drives the `xcodes` CLI) or Apple's download -page; the Nix shell never provides Xcode. Source builds (`PREBUILTS=0`, only -in Nix/direnv) need the Xcode 27.0 that dnix pins; `stack-bom.toml` recommends -27.1 for ordinary app builds, including Homebrew/manual prebuilt builds. +page; the Nix shell never provides Xcode. Source builds (`PREBUILTS=0`, needs +`nix` on `PATH`) need the Xcode 27.0 that dnix pins; `stack-bom.toml` recommends +27.0 for ordinary app builds, including Homebrew/manual prebuilt builds. To build with another installed Xcode without changing the global selection, run for example @@ -103,7 +103,7 @@ Flutter reruns every native-asset build hook when `PATH` or any `NIX_*` variable ## Toolchain bill of materials -`stack-bom.toml` lists the toolchain a build is expected to use (Flutter, Dart, Rust, Go, Xcode) and the git revisions of the pinned native plugins. It is not a Homebrew package manifest: the native dnix libraries are pinned in each plugin's `dnix.lock`, and the Homebrew packages are in `scripts/install_macos_build_tools.sh`. `make verify-bom` compares the local machine and `pubspec.lock` against it and exits with an error on a mismatch (a different recommended Flutter or Xcode version is only a warning). Source builds additionally require the Xcode 27.0 that dnix pins; `build_app.sh` enforces that, while `verify-bom` only warns. After changing a plugin pin, run `flutter pub get`, then `dart tool/verify_bom.dart --update`, to refresh the `[plugins]` section. +`stack-bom.toml` lists the toolchain a build is expected to use (Flutter, Dart, Rust, Go, Xcode). It is not a Homebrew package manifest: the native dnix libraries are pinned in each plugin's `dnix.lock`, and the plugins themselves are pinned by `pubspec.lock`; the Homebrew packages are in `scripts/install_macos_build_tools.sh`. `make verify-bom` compares the local machine against the BOM and exits with an error on a mismatch (a different recommended Flutter or Xcode version is only a warning). Source builds additionally require the Xcode 27.0 that dnix pins; `build_app.sh` enforces that, while `verify-bom` only warns. ## Optional: sccache for native-asset builds diff --git a/docs/building/windows.md b/docs/building/windows.md index 09836dd416..e02724aaca 100644 --- a/docs/building/windows.md +++ b/docs/building/windows.md @@ -9,7 +9,8 @@ with Windows Flutter. For how the build fits together, see the | What | Needed for | |---|---| -| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 minimum, 3.47.4 recommended, and Git for Windows, which includes Git Bash | Every build | +| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2, and Git for Windows, which includes Git Bash | Every build | +| GNU Make (`choco install make` or `scoop install make`; Git for Windows does not ship one) | `make build-windows` | | [Visual Studio 2022](https://docs.flutter.dev/platform-integration/windows/setup) with **Desktop development with C++**, CMake tools and a Windows SDK | Every build | | Windows Developer Mode, for the symlinks Flutter and its plugins create | Every build | | [Rustup](https://rustup.rs/) on Windows | Every app's DNSSEC hook and Stack Wallet's Xelis hook, in both modes | From 33cba1e418a26dc0ca1ca6140d2150c4913bf95b Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:07:00 +0200 Subject: [PATCH 075/107] test(verify-bom): parser + bom_values unit tests (S22) Extract the pure BOM/lock/pubspec parsing and version helpers from verify_bom.dart into tool/bom_parser.dart so they can be unit-tested without a Flutter/Dart toolchain. verify_bom.dart keeps its public behavior: parse errors (unterminated string, duplicate [plugins]) still exit 2, and missing pubspec.yaml/pubspec.lock yield empty maps. Add scripts/tests/verify_bom_parser_test.dart (readBom, compareVersions, shortVersion, resolveOnPath, requireSinglePluginsSection, declaredPlugins, lockRefs) and scripts/tests/bom_values_test.dart (bom_values.sh --check / --get quoting and x.y / x.y.z validation). All 29 tests pass; dart analyze clean. --- scripts/tests/bom_values_test.dart | 174 ++++++++++++++++ scripts/tests/verify_bom_parser_test.dart | 213 +++++++++++++++++++ tool/bom_parser.dart | 171 +++++++++++++++ tool/verify_bom.dart | 243 +++++----------------- 4 files changed, 615 insertions(+), 186 deletions(-) create mode 100644 scripts/tests/bom_values_test.dart create mode 100644 scripts/tests/verify_bom_parser_test.dart create mode 100644 tool/bom_parser.dart diff --git a/scripts/tests/bom_values_test.dart b/scripts/tests/bom_values_test.dart new file mode 100644 index 0000000000..04a7883e48 --- /dev/null +++ b/scripts/tests/bom_values_test.dart @@ -0,0 +1,174 @@ +// Tests for scripts/bom_values.sh --check and --get. +// +// Run with: dart scripts/tests/bom_values_test.dart +// +// Exercises the real shell script against temp BOM files, so it covers the +// sed/grep quoting and the x.y / x.y.z validation that the Dart side cannot. +import 'dart:io'; + +import 'package:test/test.dart'; + +const script = 'scripts/bom_values.sh'; + +void main() { + late Directory root; + + setUp(() { + root = Directory.systemTemp.createTempSync('bom_values_'); + }); + + tearDown(() { + root.deleteSync(recursive: true); + }); + + String writeBom(String body) { + final file = File('${root.path}/stack-bom.toml'); + file.writeAsStringSync(body); + return file.path; + } + + ProcessResult run(String args) => + Process.runSync('bash', [script, ...args.split(' ')]); + + test('--check passes a well-formed BOM', () { + final bom = writeBom(''' +schema_version = "1" + +[toolchain] +rust = "1.99.1" +dnssec_rust = "1.90.0" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0" +xcode_dnix = "27.0" +'''); + final result = run('--check $bom'); + expect(result.exitCode, 0, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stdout, contains('BOM values OK')); + }); + + test('--check rejects an invalid x.y.z version', () { + final bom = writeBom(''' +[toolchain] +rust = "1.99" +dnssec_rust = "1.90.0" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0" +xcode_dnix = "27.0" +'''); + final result = run('--check $bom'); + expect(result.exitCode, 1, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stderr, contains('Invalid')); + }); + + test('--check rejects a non x.y xcode value', () { + final bom = writeBom(''' +[toolchain] +rust = "1.99.1" +dnssec_rust = "1.90.0" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0.1" +xcode_dnix = "27.0" +'''); + final result = run('--check $bom'); + expect(result.exitCode, 1, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stderr, contains('Invalid')); + }); + + test('--check rejects a duplicate section', () { + final bom = writeBom(''' +[toolchain] +rust = "1.99.1" +dnssec_rust = "1.90.0" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0" +xcode_dnix = "27.0" + +[macos] +xcode = "28.0" +xcode_dnix = "28.0" +'''); + final result = run('--check $bom'); + expect(result.exitCode, 1, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stderr, contains('Duplicate')); + }); + + test('--check rejects a missing key', () { + final bom = writeBom(''' +[toolchain] +rust = "1.99.1" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0" +xcode_dnix = "27.0" +'''); + final result = run('--check $bom'); + expect(result.exitCode, 1, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stderr, contains('Missing')); + }); + + test('--get returns a single value', () { + final bom = writeBom(''' +[toolchain] +rust = "1.99.1" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0" +xcode_dnix = "27.0" +'''); + final result = run('--get rust $bom'); + expect(result.exitCode, 0, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stdout.trim(), '1.99.1'); + }); + + test('--get rejects an unknown key', () { + final bom = writeBom(''' +[toolchain] +rust = "1.99.1" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0" +xcode_dnix = "27.0" +'''); + final result = run('--get bogus $bom'); + expect(result.exitCode, 2, reason: '${result.stdout}\n${result.stderr}'); + }); +} diff --git a/scripts/tests/verify_bom_parser_test.dart b/scripts/tests/verify_bom_parser_test.dart new file mode 100644 index 0000000000..7563fde046 --- /dev/null +++ b/scripts/tests/verify_bom_parser_test.dart @@ -0,0 +1,213 @@ +// Unit tests for the BOM/lock/pubspec parser helpers in tool/bom_parser.dart. +// +// Run with: dart scripts/tests/verify_bom_parser_test.dart +// +// These cover only the pure parsing and version logic, so they run without a +// Flutter/Dart toolchain or a real checkout. File-backed helpers take their +// text as an argument, which keeps the tests hermetic. +import 'dart:io'; + +import 'package:test/test.dart'; + +import '../../tool/bom_parser.dart'; + +Map section( + Map> bom, + String name, +) => + bom[name] ?? {}; + +void main() { + group('readBom', () { + test('parses [section] headers and key = "value" lines', () { + final bom = readBom(''' +schema_version = "1" + +[toolchain] +flutter = "3.47.2" +flutter_min = "3.47.0" +'''); + expect(section(bom, '')['schema_version'], '1'); + expect(section(bom, 'toolchain')['flutter'], '3.47.2'); + expect(section(bom, 'toolchain')['flutter_min'], '3.47.0'); + }); + + test('accepts tab indentation and single quotes', () { + final bom = readBom('[toolchain]\n\tflutter = \'3.47.2\'\n'); + expect(section(bom, 'toolchain')['flutter'], '3.47.2'); + }); + + test('strips a trailing inline comment on a bare value', () { + final bom = readBom('[toolchain]\nrust = "1.99.1" # pinned by nix\n'); + expect(section(bom, 'toolchain')['rust'], '1.99.1'); + }); + + test('keeps "#" inside a quoted value', () { + final bom = readBom('[x]\nkey = "a # b"\n'); + expect(section(bom, 'x')['key'], 'a # b'); + }); + + test('returns an empty map for empty or comment-only input', () { + expect(readBom(''), isEmpty); + expect(readBom('# just a comment\n'), isEmpty); + }); + + test('throws FormatException on an unterminated string', () { + expect(() => readBom('[x]\nkey = "oops\n'), throwsFormatException); + }); + + test('last assignment wins for a repeated key in a section', () { + final bom = readBom('[x]\nkey = "first"\nkey = "second"\n'); + expect(section(bom, 'x')['key'], 'second'); + }); + }); + + group('compareVersions', () { + test('orders by numeric components', () { + expect(compareVersions('3.47.0', '3.47.2'), lessThan(0)); + expect(compareVersions('3.48.0', '3.47.9'), greaterThan(0)); + expect(compareVersions('3.47.2', '3.47.2'), 0); + }); + + test('treats missing components as zero', () { + expect(compareVersions('3.47', '3.47.0'), 0); + expect(compareVersions('3.47.1', '3.47'), greaterThan(0)); + }); + + test('compares only the first three numeric components', () { + // The comparator is intentionally 3-component: the leading x.y.z wins, + // and any suffix numbers beyond it are ignored (a tie). + expect(compareVersions('2.4.5-rc.1', '2.4.5'), 0); + expect(compareVersions('0.0.0-staging.3', '0.0.0-staging.5'), 0); + expect(compareVersions('0.0.0-staging.12', '0.0.0-staging.9'), 0); + // But a differing leading component still orders the versions. + expect(compareVersions('2.0.0-staging.1', '1.9.9'), greaterThan(0)); + }); + }); + + group('shortVersion', () { + test('keeps short strings and truncates long ones at 7 chars', () { + expect(shortVersion('3.47.2'), '3.47.2'); + expect(shortVersion('abc1234def'), 'abc1234'); + }); + }); + + group('resolveOnPath', () { + test('returns a path-containing name unchanged', () { + expect( + resolveOnPath('/opt/flutter/bin/flutter', environment: {'PATH': '/x'}), + '/opt/flutter/bin/flutter', + ); + }); + + test('resolves a bare command found on PATH', () { + final dir = Directory.systemTemp.createTempSync('resolve_path_'); + try { + File('${dir.path}/mytool').writeAsStringSync('#!/bin/sh\n'); + final found = resolveOnPath('mytool', + environment: {'PATH': '${dir.path}:/nonexistent'}); + expect(found, '${dir.path}/mytool'); + } finally { + dir.deleteSync(recursive: true); + } + }); + + test('returns the bare name when the command is not on PATH', () { + expect( + resolveOnPath('definitely-not-a-real-command-xyz', + environment: {'PATH': '/nonexistent'}), + 'definitely-not-a-real-command-xyz', + ); + }); + }); + + group('requireSinglePluginsSection', () { + test('accepts zero or one [plugins] table', () { + expect(() => requireSinglePluginsSection('[toolchain]\nflutter = "1"\n'), + returnsNormally); + expect(() => requireSinglePluginsSection('[plugins]\na = "b"\n'), + returnsNormally); + }); + + test('throws on a duplicate [plugins] table', () { + expect( + () => requireSinglePluginsSection( + '[plugins]\na = "b"\n\n[plugins]\nc = "d"\n', + ), + throwsFormatException, + ); + }); + }); + + group('declaredPlugins', () { + test('finds a pinned plugin under dependencies:', () { + const pubspec = ''' +name: app +dependencies: + flutter: + sdk: flutter + tor_ffi_plugin: + git: + url: https://example.com +'''; + expect(declaredPlugins(pubspecText: pubspec), contains('tor_ffi_plugin')); + }); + + test('finds a pinned plugin under dependency_overrides:', () { + const pubspec = ''' +dependency_overrides: + frostdart: + path: ../frostdart +'''; + expect(declaredPlugins(pubspecText: pubspec), contains('frostdart')); + }); + + test('ignores the hooks: user_defines: block', () { + const pubspec = ''' +hooks: + user_defines: + tor_ffi_plugin: + debug: true +'''; + expect(declaredPlugins(pubspecText: pubspec), isEmpty); + }); + + test('returns empty when no known plugin is declared', () { + const pubspec = ''' +dependencies: + flutter: + sdk: flutter +'''; + expect(declaredPlugins(pubspecText: pubspec), isEmpty); + }); + }); + + group('lockRefs', () { + test('reads resolved-ref for a pinned plugin', () { + const lock = ''' + tor_ffi_plugin: + dependency: "direct main" + git: + url: https://example.com + ref: abc + resolved-ref: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef + other_pkg: + dependency: "direct main" + version: "1.0.0" +'''; + final refs = lockRefs(lockText: lock); + expect( + refs['tor_ffi_plugin'], + 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef', + ); + expect(refs.containsKey('other_pkg'), isFalse); + }); + + test('returns empty when no plugin is present', () { + expect( + lockRefs(lockText: 'packages:\n foo:\n version: "1"\n'), + isEmpty, + ); + }); + }); +} diff --git a/tool/bom_parser.dart b/tool/bom_parser.dart new file mode 100644 index 0000000000..0970298ca1 --- /dev/null +++ b/tool/bom_parser.dart @@ -0,0 +1,171 @@ +// Pure helpers shared by `dart tool/verify_bom.dart` and its unit tests. +// +// These read the minimal TOML the BOM uses (`[section]` headers and +// `key = "value"` lines), compare version strings, and resolve the plugin +// pins from pubspec.lock / pubspec.yaml. They have no side effects and take +// their input as arguments, so they can be tested without a real toolchain. +import 'dart:io'; + +/// Pinned plugin package names. Campfire and Stack Duo declare only a subset, +/// so a missing lock entry is only an error for a plugin the app uses. +const List bomPluginNames = [ + 'flutter_libepiccash', + 'flutter_libmwc', + 'flutter_libsparkmobile', + 'frostdart', + 'tor_ffi_plugin', + 'xelis_wallet_flutter', +]; + +const String bomFileName = 'stack-bom.toml'; + +final RegExp _sectionHeader = RegExp(r'^\[([^\]]+)\][ \t]*(#.*)?$'); +final RegExp _pluginsHeader = + RegExp(r'^\[plugins\][ \t]*(#.*)?$', multiLine: true); + +/// Minimal TOML reader: `[section]` headers and `key = "value"` lines. +/// Accepts tabs or spaces, single or double quotes, and a trailing ` #comment` +/// on a bare value. A value that is not a quoted string keeps everything up to +/// the first ` #`; a quoted value keeps its whole content. +Map> readBom(String text) { + final result = >{}; + var section = ''; + for (final raw in text.split('\n')) { + final line = raw.trim(); + if (line.isEmpty || line.startsWith('#')) continue; + final header = _sectionHeader.firstMatch(line); + if (header != null) { + section = header.group(1)!; + result.putIfAbsent(section, () => {}); + continue; + } + final eq = line.indexOf('='); + if (eq < 0) continue; + final key = line.substring(0, eq).trim(); + var value = line.substring(eq + 1).trim(); + final hash = value.lastIndexOf(' #'); + if (hash >= 0 && value.startsWith('"') == false) { + value = value.substring(0, hash).trim(); + } + if (value.startsWith('"')) { + final end = value.indexOf('"', 1); + if (end < 0) { + throw FormatException('Unterminated string in $bomFileName: $line'); + } + value = value.substring(1, end); + } else if (value.length >= 2 && + value.startsWith("'") && + value.endsWith("'")) { + value = value.substring(1, value.length - 1); + } + result.putIfAbsent(section, () => {})[key] = value; + } + return result; +} + +/// Resolves a bare command name to an absolute path via PATH, or returns the +/// name unchanged if it is not found (so the caller can report "not found"). +/// +/// The PATH *list* separator is ';' on Windows and ':' elsewhere. +/// [Platform.pathSeparator] is the path *component* separator ('/' / '\\'), +/// which is the wrong value for splitting PATH, so it is not used here. +String resolveOnPath(String name, {Map? environment}) { + final env = environment ?? Platform.environment; + if (name.contains('/') || name.contains('\\')) return name; + final listSep = Platform.isWindows ? ';' : ':'; + final sep = Platform.pathSeparator; + for (final dir in (env['PATH'] ?? '').split(listSep)) { + if (dir.isEmpty) continue; + final candidate = File(dir.endsWith(sep) ? dir : '$dir/$name').path; + if (File(candidate).existsSync()) return candidate; + } + return name; +} + +/// The numeric components of a version string, in order. +List versionNumbers(String v) => + RegExp(r'\d+').allMatches(v).map((m) => int.parse(m.group(0)!)).toList(); + +/// Compares two version strings component by component, missing components +/// treated as 0. Returns negative, 0, or positive like [int.compareTo]. +int compareVersions(String a, String b) { + final x = versionNumbers(a), y = versionNumbers(b); + for (var i = 0; i < 3; i++) { + final p = i < x.length ? x[i] : 0, q = i < y.length ? y[i] : 0; + if (p != q) return p.compareTo(q); + } + return 0; +} + +/// Shortens a git ref or version for one-line reports. +String shortVersion(String v) => v.length <= 7 ? v : v.substring(0, 7); + +/// A duplicate `[plugins]` table makes [readBom] silently last-wins and makes +/// `--update` append a second block, so refuse both modes early. +void requireSinglePluginsSection(String text) { + final count = _pluginsHeader.allMatches(text).length; + if (count > 1) { + throw const FormatException( + 'Duplicate [plugins] sections in $bomFileName; keep exactly one.', + ); + } +} + +/// Plugin names declared by the app currently configured in pubspec.yaml. +/// +/// Accepts any consistent indentation and both direct dependencies and +/// dependency_overrides; the hooks: user_defines: block is not a declaration. +Set declaredPlugins({String? pubspecText}) { + final pubspec = File('pubspec.yaml'); + if (!pubspec.existsSync()) return {}; + final lines = (pubspecText ?? pubspec.readAsStringSync()).split('\n'); + final declared = {}; + for (final sectionName in ['dependencies:', 'dependency_overrides:']) { + final header = RegExp('^${RegExp.escape(sectionName)}\\s*(#.*)?\$'); + final start = lines.indexWhere((l) => header.hasMatch(l.trimRight())); + if (start < 0) continue; + String? indent; + for (var i = start + 1; i < lines.length; i++) { + final line = lines[i]; + if (line.trim().isEmpty || line.trimLeft().startsWith('#')) continue; + final m = RegExp(r'^[ \t]+').firstMatch(line); + if (m == null) break; + indent = m.group(0); + break; + } + if (indent == null) continue; + for (var i = start + 1; i < lines.length; i++) { + final line = lines[i]; + if (line.trim().isEmpty || line.trimLeft().startsWith('#')) continue; + final currentIndent = RegExp(r'^[ \t]*').firstMatch(line)! + .group(0)!; + if (currentIndent.length < indent.length) break; + if (currentIndent != indent) continue; + final m = RegExp(r'''^[ \t]*["']?(\w+)["']?\s*:''').firstMatch(line); + if (m != null && bomPluginNames.contains(m.group(1))) { + declared.add(m.group(1)!); + } + } + } + return declared; +} + +/// Reads the git refs of the pinned plugins from pubspec.lock. +Map lockRefs({String? lockText}) { + final lock = File('pubspec.lock'); + if (!lock.existsSync()) return {}; + final lines = (lockText ?? lock.readAsStringSync()).split('\n'); + final refs = {}; + for (var i = 0; i < lines.length; i++) { + final m = RegExp(r'^ (\w+):$').firstMatch(lines[i]); + if (m == null || !bomPluginNames.contains(m.group(1))) continue; + for (var j = i + 1; + j < lines.length && lines[j].startsWith(' '); + j++) { + final r = RegExp(r'resolved-ref: "?([0-9a-f]{40})"?') + .firstMatch(lines[j]); + if (r != null) refs[m.group(1)!] = r.group(1)!; + } + } + return refs; +} diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 4d0d2a6575..3d73dc3787 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -8,15 +8,7 @@ import 'dart:convert'; import 'dart:io'; -const _bomFile = 'stack-bom.toml'; -const _pluginNames = [ - 'flutter_libepiccash', - 'flutter_libmwc', - 'flutter_libsparkmobile', - 'frostdart', - 'tor_ffi_plugin', - 'xelis_wallet_flutter', -]; +import 'bom_parser.dart'; int _failures = 0; int _warnings = 0; @@ -32,65 +24,6 @@ void _fail(String m) { stdout.writeln('[FAIL] $m'); } -final _sectionHeader = RegExp(r'^\[([^\]]+)\][ \t]*(#.*)?$'); -final _pluginsHeader = RegExp(r'^\[plugins\][ \t]*(#.*)?$', multiLine: true); - -/// Minimal TOML reader: `[section]` headers and `key = "value"` lines. -Map> _readBom(String text) { - final result = >{}; - var section = ''; - for (final raw in text.split('\n')) { - final line = raw.trim(); - if (line.isEmpty || line.startsWith('#')) continue; - final header = _sectionHeader.firstMatch(line); - if (header != null) { - section = header.group(1)!; - result.putIfAbsent(section, () => {}); - continue; - } - final eq = line.indexOf('='); - if (eq < 0) continue; - final key = line.substring(0, eq).trim(); - var value = line.substring(eq + 1).trim(); - final hash = value.lastIndexOf(' #'); - if (hash >= 0 && value.startsWith('"') == false) { - value = value.substring(0, hash).trim(); - } - if (value.startsWith('"')) { - final end = value.indexOf('"', 1); - if (end < 0) { - stderr.writeln('Unterminated string in $_bomFile: $line'); - exit(2); - } - value = value.substring(1, end); - } else if (value.length >= 2 && - value.startsWith("'") && - value.endsWith("'")) { - value = value.substring(1, value.length - 1); - } - result.putIfAbsent(section, () => {})[key] = value; - } - return result; -} - -/// Resolves a bare command name to an absolute path via PATH, or returns the -/// name unchanged if it is not found (so _run can report "not found"). -/// -/// Note: the PATH *list* separator is ';' on Windows and ':' elsewhere. -/// Platform.pathSeparator is the path *component* separator ('/' / '\\'), -/// which is the wrong value for splitting PATH, so it is not used here. -String _resolveOnPath(String name) { - if (name.contains('/') || name.contains('\\')) return name; - final listSep = Platform.isWindows ? ';' : ':'; - final sep = Platform.pathSeparator; - for (final dir in (Platform.environment['PATH'] ?? '').split(listSep)) { - if (dir.isEmpty) continue; - final candidate = File(dir.endsWith(sep) ? dir : '$dir/$name').path; - if (File(candidate).existsSync()) return candidate; - } - return name; -} - Future _run(String exe, List args) async { try { // runInShell lets Windows start flutter.bat. Only stdout is parsed: Flutter @@ -104,117 +37,48 @@ Future _run(String exe, List args) async { } } -List _ver(String v) => - RegExp(r'\d+').allMatches(v).map((m) => int.parse(m.group(0)!)).toList(); - -int _cmp(String a, String b) { - final x = _ver(a), y = _ver(b); - for (var i = 0; i < 3; i++) { - final p = i < x.length ? x[i] : 0, q = i < y.length ? y[i] : 0; - if (p != q) return p.compareTo(q); - } - return 0; -} - -String _short(String v) => v.length <= 7 ? v : v.substring(0, 7); - -/// Plugins declared by the app currently configured in pubspec.yaml. -/// -/// Campfire and Stack Duo include only a subset of the pinned plugins, so a -/// missing lock entry is only an error for a plugin the app actually uses. -/// Accepts any consistent indentation and both direct dependencies and -/// dependency_overrides; the hooks: user_defines: block is not a declaration. -Set _declaredPlugins() { - final file = File('pubspec.yaml'); - if (!file.existsSync()) return {}; - final lines = file.readAsLinesSync(); - final declared = {}; - for (final sectionName in ['dependencies:', 'dependency_overrides:']) { - final header = RegExp('^${RegExp.escape(sectionName)}\\s*(#.*)?\$'); - final start = lines.indexWhere((l) => header.hasMatch(l.trimRight())); - if (start < 0) continue; - String? indent; - for (var i = start + 1; i < lines.length; i++) { - final line = lines[i]; - if (line.trim().isEmpty || line.trimLeft().startsWith('#')) continue; - final m = RegExp(r'^[ \t]+').firstMatch(line); - if (m == null) break; - indent = m.group(0); - break; - } - if (indent == null) continue; - for (var i = start + 1; i < lines.length; i++) { - final line = lines[i]; - if (line.trim().isEmpty || line.trimLeft().startsWith('#')) continue; - final currentIndent = RegExp(r'^[ \t]*').firstMatch(line)!.group(0)!; - if (currentIndent.length < indent.length) break; - if (currentIndent != indent) continue; - final m = RegExp(r'''^[ \t]*["']?(\w+)["']?\s*:''').firstMatch(line); - if (m != null && _pluginNames.contains(m.group(1))) { - declared.add(m.group(1)!); - } - } - } - return declared; -} - -/// Reads the git refs of the pinned plugins from pubspec.lock. -Map _lockRefs() { - final lock = File('pubspec.lock'); - if (!lock.existsSync()) return {}; - final lines = lock.readAsLinesSync(); - final refs = {}; - for (var i = 0; i < lines.length; i++) { - final m = RegExp(r'^ (\w+):$').firstMatch(lines[i]); - if (m == null || !_pluginNames.contains(m.group(1))) continue; - for (var j = i + 1; j < lines.length && lines[j].startsWith(' '); j++) { - final r = RegExp(r'resolved-ref: "?([0-9a-f]{40})"?') - .firstMatch(lines[j]); - if (r != null) refs[m.group(1)!] = r.group(1)!; - } - } - return refs; -} - -/// A duplicate `[plugins]` table makes _readBom silently last-wins and makes -/// --update append a second block, so refuse both modes early. -void _requireSinglePluginsSection(String text) { - final count = _pluginsHeader.allMatches(text).length; - if (count > 1) { - stderr.writeln( - 'Duplicate [plugins] sections in $_bomFile; keep exactly one.', - ); - exit(2); - } -} - Future _update() async { - if ((_readBom(File(_bomFile).readAsStringSync())['plugins'] ?? {}).isEmpty) { + final existingPlugins = readBom(File(bomFileName).readAsStringSync()) + ['plugins'] ?? + {}; + if (existingPlugins.isEmpty) { stderr.writeln( - 'Plugin pins are not stored in $_bomFile; pubspec.lock pins them. ' + 'Plugin pins are not stored in $bomFileName; pubspec.lock pins them. ' 'Run flutter pub get instead.', ); exit(2); } - final refs = _lockRefs(); + final refs = lockRefs(); if (refs.isEmpty) { stderr.writeln('pubspec.lock not found or has none of the plugins.'); exit(2); } - final text = File(_bomFile).readAsStringSync(); - _requireSinglePluginsSection(text); - final existing = _readBom(text)['plugins'] ?? {}; + final text = File(bomFileName).readAsStringSync(); + try { + requireSinglePluginsSection(text); + } on FormatException catch (e) { + stderr.writeln(e.message); + exit(2); + } + Map existing; + try { + existing = readBom(text)['plugins'] ?? {}; + } on FormatException catch (e) { + stderr.writeln(e.message); + exit(2); + } // Plugin pins live in pubspec.lock now. Refresh an existing table for older // branches, but never create one in a BOM that does not carry it. if (existing.isEmpty && !RegExp(r'\[plugins\]').hasMatch(text)) { - stdout.writeln('No [plugins] table in $_bomFile; nothing to update.'); + stdout.writeln('No [plugins] table in $bomFileName; nothing to update.'); return; } - final declared = _declaredPlugins(); + final declared = declaredPlugins(); // Without a pubspec.yaml we cannot tell which app is configured; keep the // old behaviour and update every plugin the lock knows about. - final updateable = declared.isEmpty ? _pluginNames.toSet() : declared; - final header = _pluginsHeader.firstMatch(text); + final updateable = declared.isEmpty ? bomPluginNames.toSet() : declared; + final header = + RegExp(r'^\[plugins\][ \t]*(#.*)?$', multiLine: true).firstMatch(text); final start = header?.start ?? -1; if (start < 0 && RegExp(r'\[plugins\]').hasMatch(text)) { stderr.writeln( @@ -245,7 +109,7 @@ Future _update() async { ); var refreshed = 0; var preserved = 0; - for (final n in _pluginNames) { + for (final n in bomPluginNames) { if (updateable.contains(n) && refs.containsKey(n)) { buf.writeln('$n = "${refs[n]}"'); refreshed++; @@ -256,14 +120,14 @@ Future _update() async { } } for (final entry in existing.entries) { - if (_pluginNames.contains(entry.key)) continue; + if (bomPluginNames.contains(entry.key)) continue; buf.writeln('${entry.key} = "${entry.value}"'); preserved++; } buf.write(tail); - File(_bomFile).writeAsStringSync(buf.toString()); + File(bomFileName).writeAsStringSync(buf.toString()); stdout.writeln( - 'Updated [plugins] in $_bomFile ' + 'Updated [plugins] in $bomFileName ' '($refreshed refreshed, $preserved preserved).', ); } @@ -274,16 +138,17 @@ Never _finish() { } void _checkPlugins(Map> bom) { - final refs = _lockRefs(); + final refs = lockRefs(); final pinned = bom['plugins'] ?? {}; // Plugin pins are no longer stored in the BOM; pubspec.lock is the source of - // truth. Keep the parser for older branches that still carry a [plugins] table. + // truth. Keep the parser for older branches that still carry a + // [plugins] table. if (pinned.isEmpty) return; - final declared = _declaredPlugins(); + final declared = declaredPlugins(); final pubspecExists = File('pubspec.yaml').existsSync(); // A fresh checkout has no pubspec.yaml: build_app.sh generates it later. // In that case check every plugin the lock contains, as before. - final required = pubspecExists ? declared : _pluginNames.toSet(); + final required = pubspecExists ? declared : bomPluginNames.toSet(); if (refs.isEmpty) { _warn('pubspec.lock not found, plugin pins not checked'); } else if (required.isEmpty) { @@ -292,7 +157,7 @@ void _checkPlugins(Map> bom) { '(expected them under dependencies: or dependency_overrides:)', ); } else { - for (final n in _pluginNames) { + for (final n in bomPluginNames) { if (!required.contains(n)) continue; final ref = refs[n]; final pin = pinned[n]; @@ -301,13 +166,13 @@ void _checkPlugins(Map> bom) { '$n is missing from pubspec.lock (path dependency or not resolved)', ); } else if (pin == null) { - _fail('$n is missing from [plugins] in $_bomFile (run --update)'); + _fail('$n is missing from [plugins] in $bomFileName (run --update)'); } else if (pin == ref) { - _ok('$n ${_short(ref)}'); + _ok('$n ${shortVersion(ref)}'); } else { _fail( - '$n is ${_short(ref)} in pubspec.lock but ' - '${_short(pin)} in $_bomFile (run --update)', + '$n is ${shortVersion(ref)} in pubspec.lock but ' + '${shortVersion(pin)} in $bomFileName (run --update)', ); } } @@ -315,18 +180,24 @@ void _checkPlugins(Map> bom) { } Future main(List args) async { - if (!File(_bomFile).existsSync()) { - stderr.writeln('Run from the repository root ($_bomFile not found).'); + if (!File(bomFileName).existsSync()) { + stderr.writeln('Run from the repository root ($bomFileName not found).'); exit(2); } if (args.contains('--update')) return _update(); - final bomText = File(_bomFile).readAsStringSync(); - _requireSinglePluginsSection(bomText); - final bom = _readBom(bomText); + final bomText = File(bomFileName).readAsStringSync(); + Map> bom; + try { + requireSinglePluginsSection(bomText); + bom = readBom(bomText); + } on FormatException catch (e) { + stderr.writeln(e.message); + exit(2); + } final root = bom[''] ?? {}; if (root['schema_version'] != '1') { - _fail('schema_version must be 1 in $_bomFile'); + _fail('schema_version must be 1 in $bomFileName'); } if (args.contains('--plugins')) { _checkPlugins(bom); @@ -339,7 +210,7 @@ Future main(List args) async { final flutterExe = configuredFlutter.isNotEmpty && File(configuredFlutter).existsSync() ? configuredFlutter - : _resolveOnPath('flutter'); + : resolveOnPath('flutter'); // A Flutter/Dart executable found on PATH under a directory with a space in // its name breaks the native-assets hooks and the .dart_tool config writers, // which do not quote paths. Catch it here with a clear error rather than @@ -366,7 +237,7 @@ Future main(List args) async { jsonDecode(fl.substring(start, end + 1)) as Map; final v = info['frameworkVersion'] as String; final d = info['dartSdkVersion'] as String; - if (_cmp(v, tc['flutter_min'] ?? '0') < 0) { + if (compareVersions(v, tc['flutter_min'] ?? '0') < 0) { _fail('Flutter $v is older than the minimum ${tc['flutter_min']}'); } else if (v != tc['flutter']) { _warn( @@ -378,7 +249,7 @@ Future main(List args) async { } final prefix = tc['dart_prefix'] ?? ''; if (prefix.isEmpty) { - _fail('dart_prefix is missing from $_bomFile'); + _fail('dart_prefix is missing from $bomFileName'); } else if (d.startsWith('$prefix.')) { _ok('Dart $d'); } else { @@ -402,7 +273,7 @@ Future main(List args) async { } final dnssec = tc['dnssec_rust'] ?? ''; if (dnssec.isEmpty) { - _fail('dnssec_rust is missing from $_bomFile'); + _fail('dnssec_rust is missing from $bomFileName'); } else if (list == null) { // already reported above } else if (list.split('\n').any((l) => l.startsWith('$dnssec-'))) { @@ -419,7 +290,7 @@ Future main(List args) async { final gm = go == null ? null : RegExp(r'go(\d+\.\d+(\.\d+)?)').firstMatch(go); if (gm == null) { _warn('go not found in PATH; only apps that build Go components need it'); - } else if (_cmp(gm.group(1)!, tc['go_min'] ?? '0') < 0) { + } else if (compareVersions(gm.group(1)!, tc['go_min'] ?? '0') < 0) { _fail('Go ${gm.group(1)} is older than the minimum ${tc['go_min']}'); } else { _ok('Go ${gm.group(1)}'); From 27e30c3244d7c3276914c2e5c64185f95d78c96b Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:33:30 +0200 Subject: [PATCH 076/107] fix(docker): read Flutter/Go versions from stack-bom.toml (single source) The Dockerfile hardcoded Flutter 3.47.2 and Go 1.24.13 in all three stages (full/android/test), duplicating stack-bom.toml. Bumping the BOM without updating the Dockerfile silently drifted the CI image from the declared toolchain. Read both versions from stack-bom.toml via the pure-bash scripts/bom_values.sh (already in the build context, context: .). The Go sha256 stays hardcoded as an integrity pin: bumping the BOM Go version without updating it fails the build loudly, which is the point. --- Dockerfile | 48 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 42 insertions(+), 6 deletions(-) diff --git a/Dockerfile b/Dockerfile index b2b19812c7..1d7ba19d90 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,15 @@ # syntax=docker/dockerfile:1.7 FROM ubuntu:24.04 AS full +# Toolchain versions come from stack-bom.toml (the single source of truth), read +# with the pure-bash scripts/bom_values.sh. The Go sha256 stays hardcoded as an +# integrity pin: bumping the BOM Go version without updating it fails the build +# loudly, which is the point. This COPY + the two ARG-free RUN reads below are +# repeated in the android and test stages because sibling FROM stages cannot +# share ARGs. +COPY stack-bom.toml /bom/stack-bom.toml +COPY scripts/bom_values.sh /bom/bom_values.sh + ENV DEBIAN_FRONTEND=noninteractive \ TZ=Etc/UTC \ LANG=C.UTF-8 \ @@ -73,7 +82,11 @@ RUN mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools" \ ENV PATH=/usr/local/go/bin:$PATH -RUN curl -fsSL https://go.dev/dl/go1.24.13.linux-amd64.tar.gz -o /tmp/go.tar.gz \ +# Go version from stack-bom.toml; the sha256 below is an integrity pin that must +# be updated in lockstep when the BOM go version changes. +RUN GO_VERSION="$(BOM_FILE=/bom/stack-bom.toml bash /bom/bom_values.sh --get go)" \ + && echo "Installing Go $GO_VERSION (sha256 pinned below)" \ + && curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" -o /tmp/go.tar.gz \ && echo "1fc94b57134d51669c72173ad5d49fd62afb0f1db9bf3f798fd98ee423f8d730 /tmp/go.tar.gz" | sha256sum -c \ && tar -C /usr/local -xzf /tmp/go.tar.gz \ && rm /tmp/go.tar.gz @@ -81,7 +94,10 @@ RUN curl -fsSL https://go.dev/dl/go1.24.13.linux-amd64.tar.gz -o /tmp/go.tar.gz ENV FLUTTER_HOME=/opt/flutter \ PATH=/opt/flutter/bin:/opt/flutter/bin/cache/dart-sdk/bin:$PATH -RUN git clone --depth 1 --branch 3.47.2 https://github.com/flutter/flutter.git "$FLUTTER_HOME" \ +# Flutter branch from stack-bom.toml. +RUN FLUTTER_VERSION="$(BOM_FILE=/bom/stack-bom.toml bash /bom/bom_values.sh --get flutter)" \ + && echo "Cloning Flutter $FLUTTER_VERSION" \ + && git clone --depth 1 --branch "$FLUTTER_VERSION" https://github.com/flutter/flutter.git "$FLUTTER_HOME" \ && git config --global --add safe.directory '*' \ && flutter config --no-analytics \ && flutter precache --linux --android \ @@ -96,6 +112,9 @@ RUN flutter --version && rustup --version && node --version && go version # Rust toolchains and targets are installed by hooks at runtime. FROM ubuntu:24.04 AS android +COPY stack-bom.toml /bom/stack-bom.toml +COPY scripts/bom_values.sh /bom/bom_values.sh + ENV DEBIAN_FRONTEND=noninteractive \ TZ=Etc/UTC \ LANG=C.UTF-8 \ @@ -158,7 +177,11 @@ RUN mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools" \ ENV PATH=/usr/local/go/bin:$PATH -RUN curl -fsSL https://go.dev/dl/go1.24.13.linux-amd64.tar.gz -o /tmp/go.tar.gz \ +# Go version from stack-bom.toml; the sha256 below is an integrity pin that must +# be updated in lockstep when the BOM go version changes. +RUN GO_VERSION="$(BOM_FILE=/bom/stack-bom.toml bash /bom/bom_values.sh --get go)" \ + && echo "Installing Go $GO_VERSION (sha256 pinned below)" \ + && curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" -o /tmp/go.tar.gz \ && echo "1fc94b57134d51669c72173ad5d49fd62afb0f1db9bf3f798fd98ee423f8d730 /tmp/go.tar.gz" | sha256sum -c \ && tar -C /usr/local -xzf /tmp/go.tar.gz \ && rm /tmp/go.tar.gz @@ -166,7 +189,10 @@ RUN curl -fsSL https://go.dev/dl/go1.24.13.linux-amd64.tar.gz -o /tmp/go.tar.gz ENV FLUTTER_HOME=/opt/flutter \ PATH=/opt/flutter/bin:/opt/flutter/bin/cache/dart-sdk/bin:$PATH -RUN git clone --depth 1 --branch 3.47.2 https://github.com/flutter/flutter.git "$FLUTTER_HOME" \ +# Flutter branch from stack-bom.toml. +RUN FLUTTER_VERSION="$(BOM_FILE=/bom/stack-bom.toml bash /bom/bom_values.sh --get flutter)" \ + && echo "Cloning Flutter $FLUTTER_VERSION" \ + && git clone --depth 1 --branch "$FLUTTER_VERSION" https://github.com/flutter/flutter.git "$FLUTTER_HOME" \ && git config --global --add safe.directory '*' \ && flutter config --no-analytics \ && flutter precache --android \ @@ -180,6 +206,9 @@ RUN flutter --version && rustup --version && go version # Image for flutter test (no Android SDK or cross-compilers) FROM ubuntu:24.04 AS test +COPY stack-bom.toml /bom/stack-bom.toml +COPY scripts/bom_values.sh /bom/bom_values.sh + ENV DEBIAN_FRONTEND=noninteractive \ TZ=Etc/UTC \ LANG=C.UTF-8 \ @@ -205,7 +234,11 @@ RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \ ENV PATH=/usr/local/go/bin:$PATH -RUN curl -fsSL https://go.dev/dl/go1.24.13.linux-amd64.tar.gz -o /tmp/go.tar.gz \ +# Go version from stack-bom.toml; the sha256 below is an integrity pin that must +# be updated in lockstep when the BOM go version changes. +RUN GO_VERSION="$(BOM_FILE=/bom/stack-bom.toml bash /bom/bom_values.sh --get go)" \ + && echo "Installing Go $GO_VERSION (sha256 pinned below)" \ + && curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" -o /tmp/go.tar.gz \ && echo "1fc94b57134d51669c72173ad5d49fd62afb0f1db9bf3f798fd98ee423f8d730 /tmp/go.tar.gz" | sha256sum -c \ && tar -C /usr/local -xzf /tmp/go.tar.gz \ && rm /tmp/go.tar.gz @@ -213,7 +246,10 @@ RUN curl -fsSL https://go.dev/dl/go1.24.13.linux-amd64.tar.gz -o /tmp/go.tar.gz ENV FLUTTER_HOME=/opt/flutter \ PATH=/opt/flutter/bin:/opt/flutter/bin/cache/dart-sdk/bin:$PATH -RUN git clone --depth 1 --branch 3.47.2 https://github.com/flutter/flutter.git "$FLUTTER_HOME" \ +# Flutter branch from stack-bom.toml. +RUN FLUTTER_VERSION="$(BOM_FILE=/bom/stack-bom.toml bash /bom/bom_values.sh --get flutter)" \ + && echo "Cloning Flutter $FLUTTER_VERSION" \ + && git clone --depth 1 --branch "$FLUTTER_VERSION" https://github.com/flutter/flutter.git "$FLUTTER_HOME" \ && git config --global --add safe.directory '*' \ && flutter config --no-analytics \ && flutter precache --linux \ From d3354b07d90f25db9dae25068a41d209e0c97166 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:35:20 +0200 Subject: [PATCH 077/107] =?UTF-8?q?docs:=20plan=20Option=20B=20=E2=80=94?= =?UTF-8?q?=20flake.nix=20Flutter/Go=20from=20stack-bom.toml=20(deferred)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Records the consolidation gap Option A did not close (flake.nix uses bare nixpkgs flutter/go, not the BOM), the reproducibility risk, and the verification-build gate required before implementing it. --- PR-1482-optionB-flake-bom-consolidation.md | 110 +++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 PR-1482-optionB-flake-bom-consolidation.md diff --git a/PR-1482-optionB-flake-bom-consolidation.md b/PR-1482-optionB-flake-bom-consolidation.md new file mode 100644 index 0000000000..c414eb33d7 --- /dev/null +++ b/PR-1482-optionB-flake-bom-consolidation.md @@ -0,0 +1,110 @@ +# Option B (deferred): make flake.nix read Flutter/Go from stack-bom.toml + +Status: **planned, NOT implemented.** Deferred from the Option A consolidation +(2026-11-20). Option A is committed (`27e30c324`): the Dockerfile now reads +Flutter + Go from the BOM. This document is the plan for the remaining gap. + +## The remaining duplication (verified against code) + +`stack-bom.toml` is the intended single source of truth. After Option A the +Dockerfile reads it. What still does **not** read the BOM for Flutter and Go: + +| Version | BOM | flake.nix today | Homebrew installer | Dockerfile (after A) | +|---|---|---|---|---| +| flutter `3.47.2` | ✅ | ❌ bare `pkgs.flutter` (nixpkgs rev pins it) | ✅ `bom_get flutter` | ✅ reads BOM | +| go `1.24.13` | ✅ | ❌ bare `pkgs.go` (nixpkgs rev pins it) | ⚠️ `brew install go` (no version) | ✅ reads BOM | +| rust `1.99.1` | ✅ | ✅ `bom.toolchain.rust` | ✅ `bom_get rust` | n/a (rustup latest) | +| dnssec_rust `1.90.0` | ✅ | ✅ `bom.toolchain.dnssec_rust` | ✅ `bom_get rust_dnssec` | n/a | + +So after Option A, **rust/dnssec/flutter are already single-sourced**; the only +remaining drift is **Flutter and Go in the Nix shell**, which use bare nixpkgs +packages. The flake.nix comment at line 18 ("Single source of truth for the +toolchain versions") is currently **aspirational** — it is true for rust/dnssec, +false for flutter/go. + +## Why this is the risky one (do NOT do casually) + +The Nix shell is the **reproducible source-build path** (`PREBUILTS=0`, +`TOOLCHAIN=nix`). The 2026-11-18 verified builds (dnix byte-for-byte +reproduction of the 4 native libs) depend on a specific Flutter version in the +shell. `pkgs.flutter` from the pinned nixpkgs rev (`b1b875982b17dabde9b4a37f3e229e74913e6db3`) +is whatever that rev ships — it may **not** equal `3.47.2`. Forcing it to `3.47.2` +changes the shell's Flutter, which can change: + +- the Dart SDK bundled with Flutter (affects the `dart`/`flutter` used by dnix + native plugins and `verify_bom.dart`), +- the iOS/macOS CocoaPods/Flutter engine hashes dnix rebuilds byte-for-byte. + +That is exactly the property dnix guarantees. A version mismatch there is not a +cosmetic drift — it can break the dnix reproduction or silently change the +produced binaries. **This is why Option B needs a real verification build**, +which cannot be fully run on this host (no Flutter in the Nix shell here). + +## The concrete change + +flake.nix must select the exact Flutter and Go versions from the BOM instead of +bare packages. Two sub-approaches: + +### B1 — nixpkgs version-selector packages (preferred, lowest blast radius) +nixpkgs exposes versioned aliases: `pkgs.go_1_24` (exists for many Go majors). +For Go this is a one-line change: `go` → `go_1_24` (or derive from the BOM's +`go` major). It locks the shell to the Go that nixpkgs rev provides for `go_1_24`, +which for `1.24.13` should match — **verify** the resolved version equals the +BOM after the change. + +Flutter has **no** `pkgs.flutter_3_47` style alias in standard nixpkgs — the +bare `pkgs.flutter` is the only option, and it is rev-pinned. To pin Flutter +`3.47.2` exactly you must either: + +- pin the **nixpkgs rev to the one that ships Flutter 3.47.2**, or +- add a **Flutter overlay/expression** that fetches Flutter at the exact git + ref/commit behind tag `3.47.2` (Flutter releases are git tags; the + `flutter` nixpkgs derivation takes a `version`/`src` you can override). + +### B2 — overlay that reads the BOM (most faithful, most work) +Write a small overlay that, given `bom.toolchain.flutter`, builds Flutter from +the matching git tag (`https://github.com/flutter/flutter.git` @ tag +``), reusing the same source the Dockerfile and Homebrew installer +clone. This makes all four sources truly identical, but it is a real nix +expression (Flutter's build needs the Dart SDK, engine artifacts, and +`flutter precache`), and it changes the reproducibility story from "whatever +nixpkgs rev ships" to "pinned to the BOM tag" — a behavior change that must be +documented and build-verified. + +## Recommended sequencing + +1. **Do B1-Go first** (one line: `go` → versioned selector). Verify the resolved + Go version equals `bom.toolchain.go`. Low risk. +2. **Flutter is the hard part** — treat it as its own PR: + - Decide: pin nixpkgs rev to the Flutter-3.47.2 one (B1), or add a BOM-driven + Flutter overlay (B2). B1 is less code but couples the whole toolchain to a + rev chosen for Flutter; B2 is more code but keeps the current rev and pins + only Flutter. + - **Must run `make build-macos` and `make build-linux`** to confirm dnix + still reproduces byte-for-byte and the app builds. This is the gate; without + it Option B is EDITED/UNPROVEN, not CERTIFIED. +3. Keep the flake.nix comment honest: change "Single source of truth for the + toolchain versions" to name exactly which keys it sources (rust, dnssec_rust, + and — after B — flutter/go), or leave it aspirational with a TODO. + +## Risk register + +- **dnix byte-for-byte break** — the dominant risk. Flutter version change in the + shell can change engine/Dart artifacts dnix rebuilds. Mitigation: the verification + build is mandatory; do not merge without it. +- **nixpkgs rev coupling** — pinning the rev for Flutter 3.47.2 may regress Go or + other packages; re-verify the whole toolchain. +- **Overlay maintenance** — a B2 Flutter overlay must track Flutter's release + structure; it is more to maintain than a version selector. +- **Cannot self-verify here** — no Flutter in the Nix shell on this host; the + author must run the builds on a machine with the full nix env. + +## What is NOT in scope + +- Homebrew installer Go version: it runs `brew install go` with no version pin. + Homebrew's `go` is "latest", so the installer's Go already drifts from the BOM + independently of this work. Leaving it is consistent with the prebuilt/host + path being best-effort; pinning it is a separate, smaller task. +- system_deps (jsoncpp, libsecret, etc.): not version-pinned anywhere except the + BOM comment; they come from the OS package manager. No consolidation action + needed — they are already single-sourced (only in the BOM). From 9cf4032132bfa7f6b5aed4412d2a302cfe40f581 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:43:11 +0200 Subject: [PATCH 078/107] feat(verify-bom): --toolchains flag for pre-image host-runner check (S10) Split the BOM check so CI can validate the toolchain on the host runner before the prebuilt image is used. The image's toolchain is frozen at build time, so a raised minimum (flutter_min / go_min / rust) must fail on the runner, not only inside the image once the build has started. --toolchains checks only the installed toolchain (skips the pubspec.lock plugin pins). On the host runner, which has no Flutter/rustup/go, all absent-tool checks downgrade to warnings (the pinned toolchains live in the image); a plain run (local or in-image) still requires them. Adds a Makefile verify-bom-toolchains target and a host-runner 'Verify toolchain (pre-image)' step in build.yaml that installs Dart via apt and runs the check before the container step. --- .github/workflows/build.yaml | 25 +++++++++++++++++++++++++ Makefile | 5 +++++ tool/verify_bom.dart | 34 ++++++++++++++++++++++++++++++---- 3 files changed, 60 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 1c3c1a82dd..72dc0fbfd9 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -73,6 +73,31 @@ jobs: with: fetch-depth: 0 + # Run the toolchain check on the host runner, before the prebuilt image + # is used. The image's toolchain is frozen at build time, so a raised + # minimum (go_min / rust) must fail here on the runner, not only inside + # the image once the build has already started. Flutter is not installed + # on the runner (the image has it), so the toolchain check downgrades a + # missing Flutter to a warning via --toolchains. The pubspec.lock pin + # check stays inside the image, after `flutter pub get`. + - name: Install Dart (host runner) + container: false + run: | + sudo mkdir -p /etc/apt/keyrings + curl -fsSL https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_linux_signing_key | gpg --dearmor -o /etc/apt/keyrings/dart.gpg + echo 'deb [signed-by=/etc/apt/keyrings/dart.gpg arch=amd64] https://storage.googleapis.com/download.dartlang.org/linux/debian stable main' | sudo tee /etc/apt/sources.list.d/dart_stable.list + sudo apt-get update -q + sudo apt-get install -y --no-install-recommends dart + echo "DART=/usr/lib/dart/bin" >> "$GITHUB_ENV" + + - name: Verify toolchain (host runner, pre-image) + container: false + env: + PATH: ${{ env.PATH }}:/usr/lib/dart/bin + run: | + bash scripts/bom_values.sh --check + dart tool/verify_bom.dart --toolchains + - name: Set version id: ver run: | diff --git a/Makefile b/Makefile index 3e58d3fed3..c829dd8b5d 100644 --- a/Makefile +++ b/Makefile @@ -351,6 +351,11 @@ verify-bom: ## Check the local toolchain against stack-bom.toml @bash scripts/bom_values.sh --check @FLUTTER="$(FLUTTER)" "$(DART)" tool/verify_bom.dart --app "$(APP_NAME)" +verify-bom-toolchains: ## Check only the installed toolchain (skip pubspec.lock pins); for CI to run on the runner before the prebuilt image + @[ -n "$(DART)" ] || { echo >&2 "[ERROR] Dart not installed (needed for verify-bom-toolchains). Install Flutter or pass DART=/path/to/dart."; exit 1; } + @bash scripts/bom_values.sh --check + @FLUTTER="$(FLUTTER)" "$(DART)" tool/verify_bom.dart --toolchains + cache-stats: ## Show sccache statistics (hit rate) after a build @command -v sccache >/dev/null 2>&1 || { echo >&2 "[ERROR] sccache not installed."; exit 1; } @sccache --show-stats diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 3d73dc3787..0b98cee0c2 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -2,9 +2,16 @@ // stack-bom.toml. // // dart tool/verify_bom.dart check, exit 1 on a mismatch +// dart tool/verify_bom.dart --toolchains check only the installed toolchain +// dart tool/verify_bom.dart --plugins check only the pubspec.lock pins // dart tool/verify_bom.dart --update refresh an existing [plugins] section from pubspec.lock // // No packages needed, so it runs before `flutter pub get`. +// +// CI splits the two: the toolchain check runs on the host runner before the +// prebuilt image is used, because the image's toolchain is frozen until it is +// rebuilt. Raising a minimum (flutter_min / go_min) must therefore fail the +// runner step, not only the in-image step. import 'dart:convert'; import 'dart:io'; @@ -203,6 +210,7 @@ Future main(List args) async { _checkPlugins(bom); _finish(); } + final toolchainsOnly = args.contains('--toolchains'); final tc = bom['toolchain'] ?? {}; // Flutter / Dart @@ -225,7 +233,15 @@ Future main(List args) async { } final fl = await _run(flutterExe, ['--version', '--machine']); if (fl == null) { - _fail('flutter not found in PATH'); + // In CI the --toolchains check runs on the host runner before the + // prebuilt image is used; the runner has no Flutter (the image does), + // so a missing Flutter is a warning there, not a failure. A plain run + // (local or in-image) still requires it. + if (toolchainsOnly) { + _warn('flutter not found in PATH (expected inside the CI image)'); + } else { + _fail('flutter not found in PATH'); + } } else { final start = fl.indexOf('{'); final end = fl.lastIndexOf('}'); @@ -265,7 +281,14 @@ Future main(List args) async { final list = await _run('rustup', ['toolchain', 'list']); final rust = tc['rust'] ?? ''; if (list == null) { - _fail('rustup not found in PATH'); + // On the CI host runner (pre-image) rustup is not installed — the pinned + // toolchains live in the prebuilt image. A missing rustup is a warning + // there, not a failure. A plain run (local or in-image) still requires it. + if (toolchainsOnly) { + _warn('rustup not found in PATH (expected inside the CI image)'); + } else { + _fail('rustup not found in PATH'); + } } else if (list.split('\n').any((l) => l.startsWith('$rust-'))) { _ok('Rust $rust installed via rustup'); } else { @@ -275,7 +298,10 @@ Future main(List args) async { if (dnssec.isEmpty) { _fail('dnssec_rust is missing from $bomFileName'); } else if (list == null) { - // already reported above + // rustup absent: already reported above (fail locally, warn on the runner). + if (toolchainsOnly) { + _warn('DNSSEC Rust $dnssec not checked (rustup absent; in the CI image)'); + } } else if (list.split('\n').any((l) => l.startsWith('$dnssec-'))) { _ok('DNSSEC Rust $dnssec installed via rustup'); } else { @@ -315,6 +341,6 @@ Future main(List args) async { } } - _checkPlugins(bom); + if (!toolchainsOnly) _checkPlugins(bom); _finish(); } From 1622714ce30005a113aea21c35a7987afee99fe0 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:48:18 +0200 Subject: [PATCH 079/107] ci(make-smoke): manual workflow_dispatch real make build-linux leg (S19) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The audit gap: no CI job ever executes Available targets: help Show available commands toolchain Show the active toolchain and tool paths toolchain-check Fail when the requested toolchain is not active bootstrap Enter the Nix dev shell (primary toolchain; no-op when already inside) bootstrap-brew Alias for the Homebrew fallback toolchain check-linux Fail unless the host is Linux check-windows Fail unless running from Git Bash on Windows require-version Fail unless VERSION/BUILD_NUM are valid and BUILD_NUM is not below the latest release tag check-reqs Verify essential build tools check-sdk-macos Verify XCode on macOS check-reqs-macos Verify macOS-specific tools are available in PATH bootstrap-macos Install the Homebrew fallback toolchain (Nix is the primary path) bootstrap-xcode Check/select an installed full Xcode.app (may ask for sudo to accept the licence) sccache-setup Opt-in: use sccache for the Rust/C builds run by native-asset hooks (writes ~/.cargo/config.toml if absent) verify-bom Check the local toolchain against stack-bom.toml verify-bom-toolchains Check only the installed toolchain (skip pubspec.lock pins); for CI to run on the runner before the prebuilt image cache-stats Show sccache statistics (hit rate) after a build clean Remove artifacts and fix permissions clean-app Remove app build output (build/, Pods) but keep .dart_tool/hooks_runner, so the next build is fast clean-native Remove only the native-asset build outputs (forces the Rust/Go/C libraries to be rebuilt) build-macos Build macOS release (source in Nix/direnv on Apple Silicon; PREBUILTS=1 uses verified prebuilts) diagnose-env-macos Print macOS build env and tool resolution build-linux Build Linux release (source when nix is on PATH; PREBUILTS=1 uses verified prebuilts) build-windows Build Windows release (Git Bash; verified dnix prebuilts) android-dev-key Create a throw-away debug signing key if android/key.properties is missing (never use for releases) build-android Build Android APKs (requires android/key.properties; prebuilt unless x86_64 Linux in Nix/direnv follows PREBUILTS) build-ios Build iOS Runner.app without code signing (source in Nix/direnv on Apple Silicon; same steps as CI) — test.yaml only dry-runs the recipes. Add a manual, prebuilt-mode Linux build that runs end-to-end on the CI image (verified dnix assets, no Nix, no source native compile), so the Makefile recipe is exercised in CI at least once. Runs on workflow_dispatch only (version + build number), not on every push/PR, to avoid burning build minutes. Mirrors the build-linux job's host-runner toolchain check and adds a echo "Available targets:" grep -E '^[a-zA-Z0-9_-]+:.*?## .*$' "Makefile" | awk 'BEGIN {FS = ":.*?## "}; {printf "%-24s %s\n", $1, $2}' dry-run before the real build. Artifact is the release bundle. --- .github/workflows/make-smoke.yaml | 74 +++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 .github/workflows/make-smoke.yaml diff --git a/.github/workflows/make-smoke.yaml b/.github/workflows/make-smoke.yaml new file mode 100644 index 0000000000..04370fac47 --- /dev/null +++ b/.github/workflows/make-smoke.yaml @@ -0,0 +1,74 @@ +name: Make smoke + +# Manual-only: a real `make build-linux` end-to-end, so the Makefile recipe is +# exercised in CI (not just `make -n` dry-runs). Prebuilt mode (verified dnix +# assets) on the CI image — no Nix, no source native build. Run from the +# Actions tab with a version + build number; it does not run on every push/PR. +on: + workflow_dispatch: + inputs: + version: + description: 'App version string (e.g. 0.0.1)' + required: true + default: '0.0.1' + build_number: + description: 'Build number (integer; must be >= the latest build_* tag)' + required: true + default: '326' + +jobs: + make-smoke-linux: + runs-on: ubuntu-24.04 + permissions: + contents: read + packages: read + container: + image: ghcr.io/${{ github.repository_owner }}/stackwallet-ci:latest + credentials: + username: ${{ github.actor }} + password: ${{ github.token }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + + # Run the toolchain check on the host runner, before the prebuilt image + # is used, exactly as the build-linux job does. The image's toolchain is + # frozen at build time, so a raised minimum must fail here, not only once + # the build has started inside the image. + - name: Install Dart (host runner) + container: false + run: | + sudo mkdir -p /etc/apt/keyrings + curl -fsSL https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_linux_signing_key | gpg --dearmor -o /etc/apt/keyrings/dart.gpg + echo 'deb [signed-by=/etc/apt/keyrings/dart.gpg arch=amd64] https://storage.googleapis.com/download.dartlang.org/linux/debian stable main' | sudo tee /etc/apt/sources.list.d/dart_stable.list + sudo apt-get update -q + sudo apt-get install -y --no-install-recommends dart + echo "DART=/usr/lib/dart/bin" >> "$GITHUB_ENV" + + - name: Verify toolchain (host runner, pre-image) + container: false + env: + PATH: ${{ env.PATH }}:/usr/lib/dart/bin + run: | + bash scripts/bom_values.sh --check + dart tool/verify_bom.dart --toolchains + + - name: Dry-run the recipe + run: | + make -n build-linux \ + PLATFORM=Linux TOOLCHAIN=host PREBUILTS=1 SYSTEM_DEPS=1 \ + VERSION="${{ inputs.version }}" BUILD_NUM="${{ inputs.build_number }}" + + - name: Real build (make build-linux, prebuilt) + run: | + make build-linux \ + PLATFORM=Linux TOOLCHAIN=host PREBUILTS=1 SYSTEM_DEPS=1 \ + VERSION="${{ inputs.version }}" BUILD_NUM="${{ inputs.build_number }}" + + - name: Upload smoke artifact + if: success() + uses: actions/upload-artifact@v7 + with: + name: stack_wallet-linux-smoke-${{ inputs.version }} + path: build/linux/x64/release/bundle/ From acf5a3125a513166f56b0e1174520d52da65929f Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:14:27 +0200 Subject: [PATCH 080/107] fix(verify-bom): --toolchains must warn, not fail, on present-but-missing rust toolchains (S10) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The host-runner gate failed on the real ubuntu-24.04 CI runner: it ships rustup with Rust 1.99.1 (the BOM rust) but NOT the pinned 1.90.0 (DNSSEC), so the 'rustup present, pinned toolchain absent' branch hard-failed both the Rust and DNSSEC checks — defeating the warn-pre-image/fail-in-image design. --toolchains now downgrades a present-but-missing pinned toolchain to a warning; a plain run still hard-requires it. Reproduced (exit 1, 2 FAILs) before the fix; exit 0 / 0 FAILs after, plain run unchanged (exit 1). --- tool/verify_bom.dart | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 0b98cee0c2..686733a2b8 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -291,6 +291,12 @@ Future main(List args) async { } } else if (list.split('\n').any((l) => l.startsWith('$rust-'))) { _ok('Rust $rust installed via rustup'); + } else if (toolchainsOnly) { + // rustup is present but the pinned toolchain is not installed. On the CI + // host runner the pinned toolchains live in the prebuilt image, not in the + // runner's rustup, so a present-but-missing toolchain is a warning there, + // not a failure. A plain run (local or in-image) still requires it. + _warn("Rust $rust not installed via rustup (expected inside the CI image)"); } else { _fail('Rust $rust is not installed (rustup toolchain install $rust)'); } @@ -304,6 +310,12 @@ Future main(List args) async { } } else if (list.split('\n').any((l) => l.startsWith('$dnssec-'))) { _ok('DNSSEC Rust $dnssec installed via rustup'); + } else if (toolchainsOnly) { + // Same as the Rust check above: the pinned DNSSEC toolchain lives in the + // prebuilt image, not the host runner's rustup, so warn rather than fail. + _warn( + "DNSSEC Rust $dnssec not installed via rustup (expected in the CI image)", + ); } else { _fail( 'DNSSEC Rust $dnssec is not installed ' From 6c12867008bcc03c3563ff4d19fd3849fba304ab Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:16:13 +0200 Subject: [PATCH 081/107] fix(verify-bom): wire BOM tests into CI + exit-2 + CRLF parser fixes (audit) From an adversarial audit of the S10/S22 work: - test.yaml: run the two new BOM test files (bom_values_test, verify_bom_parser_test); they had no CI regression gate. - verify_bom.dart _update(): wrap the early readBom in try/catch so a malformed BOM exits 2 (was an uncaught FormatException -> exit 255). - bom_parser.dart lockRefs(): strip a trailing CR so a CRLF pubspec.lock still matches the anchored ^ (\w+):$ header; add a CRLF regression test. --- .github/workflows/test.yaml | 4 ++++ scripts/tests/verify_bom_parser_test.dart | 10 ++++++++++ tool/bom_parser.dart | 5 ++++- tool/verify_bom.dart | 11 ++++++++--- 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 642b6c04bf..3f8bc27e95 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -115,6 +115,10 @@ jobs: # run: flutter analyze - name: Test build scripts run: dart scripts/tests/build_input_test.dart + - name: Test BOM values validator + run: dart scripts/tests/bom_values_test.dart + - name: Test BOM parser + run: dart scripts/tests/verify_bom_parser_test.dart - name: Test native build configuration run: dart scripts/tests/native_build_config_test.dart - name: Test native settings and dependency contracts diff --git a/scripts/tests/verify_bom_parser_test.dart b/scripts/tests/verify_bom_parser_test.dart index 7563fde046..b8322ddb33 100644 --- a/scripts/tests/verify_bom_parser_test.dart +++ b/scripts/tests/verify_bom_parser_test.dart @@ -209,5 +209,15 @@ dependencies: isEmpty, ); }); + + test('reads a ref from a CRLF lockfile', () { + // A trailing CR must not break the anchored `^ (\w+):$` header. + const lock = 'plugins:\r\n tor_ffi_plugin:\r\n' + ' resolved-ref: "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"\r\n'; + expect( + lockRefs(lockText: lock)['tor_ffi_plugin'], + 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef', + ); + }); }); } diff --git a/tool/bom_parser.dart b/tool/bom_parser.dart index 0970298ca1..2303773601 100644 --- a/tool/bom_parser.dart +++ b/tool/bom_parser.dart @@ -157,7 +157,10 @@ Map lockRefs({String? lockText}) { final lines = (lockText ?? lock.readAsStringSync()).split('\n'); final refs = {}; for (var i = 0; i < lines.length; i++) { - final m = RegExp(r'^ (\w+):$').firstMatch(lines[i]); + // Strip a trailing CR so a CRLF lockfile still matches the anchored + // `^ (\w+):$` header; otherwise the ref is silently dropped. + final line = lines[i].replaceFirst(RegExp(r'\r$'), ''); + final m = RegExp(r'^ (\w+):$').firstMatch(line); if (m == null || !bomPluginNames.contains(m.group(1))) continue; for (var j = i + 1; j < lines.length && lines[j].startsWith(' '); diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index 686733a2b8..b3f648aafa 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -45,9 +45,14 @@ Future _run(String exe, List args) async { } Future _update() async { - final existingPlugins = readBom(File(bomFileName).readAsStringSync()) - ['plugins'] ?? - {}; + final Map existingPlugins; + try { + final raw = File(bomFileName).readAsStringSync(); + existingPlugins = readBom(raw)['plugins'] ?? {}; + } on FormatException catch (e) { + stderr.writeln(e.message); + exit(2); + } if (existingPlugins.isEmpty) { stderr.writeln( 'Plugin pins are not stored in $bomFileName; pubspec.lock pins them. ' From 9cc807dd561994756f955e4b74664b689bb20f4b Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:16:48 +0200 Subject: [PATCH 082/107] ci(build-ci-image): rebuild image when stack-bom.toml or bom_values.sh change The CI image reads the BOM at build time (Dockerfile COPYs + bom_values.sh --get), but the rebuild was triggered only by Dockerfile/workflow changes. A BOM Flutter/Go bump merged without rebuilding the image, so Linux/Android kept the stale baked-in toolchains. Add stack-bom.toml and scripts/bom_values.sh to the push paths trigger. --- .github/workflows/build-ci-image.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/build-ci-image.yaml b/.github/workflows/build-ci-image.yaml index 5cc34c0c99..2ddd51c428 100644 --- a/.github/workflows/build-ci-image.yaml +++ b/.github/workflows/build-ci-image.yaml @@ -5,6 +5,8 @@ on: branches: [main, staging] paths: - 'Dockerfile' + - 'stack-bom.toml' + - 'scripts/bom_values.sh' - '.github/workflows/build-ci-image.yaml' workflow_dispatch: From c9f640ad9e25a7a58721bbd9c5f69b46013a6810 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:34:52 +0200 Subject: [PATCH 083/107] ci(build): split host-runner verify into its own job; sudo gpg for Dart keyring (audit) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The S10 host-runner steps used step-level `container: false`, which is not valid GitHub Actions syntax — actionlint rejects it as "unexpected key 'container' for step". Split the pre-image toolchain check into its own `verify-toolchain` job (runs-on host, no container) that build-linux needs. Also `sudo gpg --dearmor` the Dart signing key so the hosted runner (runs as `runner`) can write /etc/apt/keyrings. Fixes ci-docs-audit B1 (invalid step-level container) + B4 (unsudoed gpg). --- .github/workflows/build.yaml | 48 +++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 72dc0fbfd9..1a1db28c32 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -58,46 +58,54 @@ jobs: > Official releases are published on the [Releases page](https://github.com/cypherstack/stack_wallet/releases). EOF - build-linux: + verify-toolchain: + # Runs on the host runner (no container), before the prebuilt image is used. + # The image's toolchain is frozen at build time, so a raised minimum (go_min + # / rust) must fail here on the runner, not only inside the image once the + # build has already started. Flutter is not installed on the runner (the + # image has it), so the toolchain check downgrades a missing Flutter to a + # warning via --toolchains. The pubspec.lock pin check stays inside the + # image, after `flutter pub get`. Dart is installed and verified in this + # same job; the build-linux job needs it to pass. runs-on: ubuntu-24.04 permissions: contents: read - packages: read - container: - image: ghcr.io/${{ github.repository_owner }}/stackwallet-ci:latest - credentials: - username: ${{ github.actor }} - password: ${{ github.token }} steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - # Run the toolchain check on the host runner, before the prebuilt image - # is used. The image's toolchain is frozen at build time, so a raised - # minimum (go_min / rust) must fail here on the runner, not only inside - # the image once the build has already started. Flutter is not installed - # on the runner (the image has it), so the toolchain check downgrades a - # missing Flutter to a warning via --toolchains. The pubspec.lock pin - # check stays inside the image, after `flutter pub get`. - - name: Install Dart (host runner) - container: false + - name: Install Dart run: | sudo mkdir -p /etc/apt/keyrings - curl -fsSL https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_linux_signing_key | gpg --dearmor -o /etc/apt/keyrings/dart.gpg + curl -fsSL https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_linux_signing_key | sudo gpg --dearmor -o /etc/apt/keyrings/dart.gpg echo 'deb [signed-by=/etc/apt/keyrings/dart.gpg arch=amd64] https://storage.googleapis.com/download.dartlang.org/linux/debian stable main' | sudo tee /etc/apt/sources.list.d/dart_stable.list sudo apt-get update -q sudo apt-get install -y --no-install-recommends dart - echo "DART=/usr/lib/dart/bin" >> "$GITHUB_ENV" - - name: Verify toolchain (host runner, pre-image) - container: false + - name: Verify toolchain (pre-image) env: PATH: ${{ env.PATH }}:/usr/lib/dart/bin run: | bash scripts/bom_values.sh --check dart tool/verify_bom.dart --toolchains + build-linux: + runs-on: ubuntu-24.04 + needs: verify-toolchain + permissions: + contents: read + packages: read + container: + image: ghcr.io/${{ github.repository_owner }}/stackwallet-ci:latest + credentials: + username: ${{ github.actor }} + password: ${{ github.token }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Set version id: ver run: | From 31cd8c24a9b94f337d414158534a29828800b7a3 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:34:59 +0200 Subject: [PATCH 084/107] ci(make-smoke): job split + BOM-pinned rust toolchains + CONFIRM=1 (audit) Fixes the ci-docs-audit blockers in the new make-smoke workflow: - B1: step-level `container: false` is invalid GitHub syntax; split the pre-image toolchain check into its own `verify-toolchain` job that make-smoke-linux needs. - B2: `make build-linux` runs verify-bom + check-reqs, which hard-require the BOM-pinned rust toolchains; the CI image installs rustup --default-toolchain none, so install rust + dnssec_rust (read from stack-bom.toml) before the build. - B3: build_app.sh's confirmDisclaimer aborts on EOF in CI; pass CONFIRM=1 so the Makefile pipes the prompts. - B4: `sudo gpg --dearmor` the Dart signing key for the hosted runner. Validated with actionlint: 0 syntax errors. --- .github/workflows/make-smoke.yaml | 54 ++++++++++++++++++++----------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/.github/workflows/make-smoke.yaml b/.github/workflows/make-smoke.yaml index 04370fac47..0138ee5c1a 100644 --- a/.github/workflows/make-smoke.yaml +++ b/.github/workflows/make-smoke.yaml @@ -17,43 +17,61 @@ on: default: '326' jobs: - make-smoke-linux: + verify-toolchain: + # Runs on the host runner (no container), before the prebuilt image is used, + # exactly as the build-linux job does. The image's toolchain is frozen at + # build time, so a raised minimum must fail here, not only once the build + # has started inside the image. Dart is installed and the toolchain is + # verified in this same job; the build job needs it to pass. runs-on: ubuntu-24.04 permissions: contents: read - packages: read - container: - image: ghcr.io/${{ github.repository_owner }}/stackwallet-ci:latest - credentials: - username: ${{ github.actor }} - password: ${{ github.token }} steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - # Run the toolchain check on the host runner, before the prebuilt image - # is used, exactly as the build-linux job does. The image's toolchain is - # frozen at build time, so a raised minimum must fail here, not only once - # the build has started inside the image. - - name: Install Dart (host runner) - container: false + - name: Install Dart run: | sudo mkdir -p /etc/apt/keyrings - curl -fsSL https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_linux_signing_key | gpg --dearmor -o /etc/apt/keyrings/dart.gpg + curl -fsSL https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_linux_signing_key | sudo gpg --dearmor -o /etc/apt/keyrings/dart.gpg echo 'deb [signed-by=/etc/apt/keyrings/dart.gpg arch=amd64] https://storage.googleapis.com/download.dartlang.org/linux/debian stable main' | sudo tee /etc/apt/sources.list.d/dart_stable.list sudo apt-get update -q sudo apt-get install -y --no-install-recommends dart - echo "DART=/usr/lib/dart/bin" >> "$GITHUB_ENV" - - name: Verify toolchain (host runner, pre-image) - container: false + - name: Verify toolchain (pre-image) env: PATH: ${{ env.PATH }}:/usr/lib/dart/bin run: | bash scripts/bom_values.sh --check dart tool/verify_bom.dart --toolchains + make-smoke-linux: + runs-on: ubuntu-24.04 + needs: verify-toolchain + permissions: + contents: read + packages: read + container: + image: ghcr.io/${{ github.repository_owner }}/stackwallet-ci:latest + credentials: + username: ${{ github.actor }} + password: ${{ github.token }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + + # The CI image installs rustup with --default-toolchain none; the pinned + # toolchains are added on demand by the Flutter build hooks, but + # `make build-linux` runs verify-bom + check-reqs BEFORE any hook, and + # those hard-require the BOM-pinned rust toolchains. Install them here, + # reading the versions from stack-bom.toml so the smoke tracks the BOM. + - name: Install pinned rust toolchains + run: | + rustup toolchain install "$(bash scripts/bom_values.sh --get rust)" --profile minimal + rustup toolchain install "$(bash scripts/bom_values.sh --get dnssec_rust)" --profile minimal + - name: Dry-run the recipe run: | make -n build-linux \ @@ -63,7 +81,7 @@ jobs: - name: Real build (make build-linux, prebuilt) run: | make build-linux \ - PLATFORM=Linux TOOLCHAIN=host PREBUILTS=1 SYSTEM_DEPS=1 \ + PLATFORM=Linux TOOLCHAIN=host PREBUILTS=1 SYSTEM_DEPS=1 CONFIRM=1 \ VERSION="${{ inputs.version }}" BUILD_NUM="${{ inputs.build_number }}" - name: Upload smoke artifact From d89d8266bbbd73575ac5dfff652d74a7d372e4c8 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:01:00 +0200 Subject: [PATCH 085/107] Remove Homebrew source-build fallback; Nix-only for source builds - Decision 1 (Nix-only): source builds now require a Nix/direnv shell. - Delete scripts/install_macos_build_tools.sh (Homebrew tool installer). - Makefile: bootstrap-macos now only checks/selects Xcode; drop the install_macos_build_tools.sh branch, the rustup target add line, and the bootstrap-brew alias; remove brew from TOOLCHAIN allowed values and toolchain-check; host/manual remain for the prebuilt (PREBUILTS=1) path. - Reframe living docs (README, docs/building/*) from a Homebrew source-build fallback to the prebuilt path. - Record the outcome in PR-1482-build-strategy-decision.md. --- Makefile | 41 +++++------ PR-1482-build-strategy-decision.md | 108 +++++++++++++++++++++++++++++ README.md | 18 ++--- docs/building/macos.md | 10 +-- docs/building/make-flow.md | 17 ++--- docs/building/make.md | 15 ++-- 6 files changed, 149 insertions(+), 60 deletions(-) create mode 100644 PR-1482-build-strategy-decision.md diff --git a/Makefile b/Makefile index c829dd8b5d..825b7c7aa8 100644 --- a/Makefile +++ b/Makefile @@ -88,10 +88,10 @@ ifneq ($(PLATFORM),Darwin) endif endif endif -# Toolchain source. Nix (nix develop or direnv) is the primary path; Homebrew -# and manual installs use the host tools already on PATH. The build steps are -# identical in every mode: only the prerequisite check and the Nix environment -# sanitising differ. Override with TOOLCHAIN=nix|direnv|brew|manual|host. +# Toolchain source. Source builds require Nix (nix develop or direnv); the +# prebuilt path (PREBUILTS=1) uses the host tools on PATH (manual or host). +# The build steps are identical in every mode: only the prerequisite check and +# the Nix environment sanitising differ. Override with TOOLCHAIN=nix|direnv|manual|host. TOOLCHAIN ?= auto DIRENV_ACTIVE := $(if $(DIRENV_DIR),1,) NIX_ACTIVE := $(if $(or $(IN_NIX_SHELL),$(NIX_STORE)),1,) @@ -101,8 +101,8 @@ endif ifneq ($(words $(TOOLCHAIN)),1) $(error TOOLCHAIN must be a single value) endif -ifneq ($(filter $(TOOLCHAIN),auto nix direnv brew manual host),$(TOOLCHAIN)) - $(error TOOLCHAIN must be auto, nix, direnv, brew, manual or host) +ifneq ($(filter $(TOOLCHAIN),auto nix direnv manual host),$(TOOLCHAIN)) + $(error TOOLCHAIN must be auto, nix, direnv, manual or host) endif ifeq ($(TOOLCHAIN),auto) ifeq ($(DIRENV_ACTIVE),1) @@ -156,7 +156,7 @@ ifneq ($(strip $(PUB_CACHE)),) export PUB_CACHE endif -.PHONY: help toolchain toolchain-check bootstrap bootstrap-brew require-version check-reqs check-reqs-macos check-sdk-macos check-linux check-windows bootstrap-macos bootstrap-xcode sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios +.PHONY: help toolchain toolchain-check bootstrap require-version check-reqs check-reqs-macos check-sdk-macos check-linux check-windows bootstrap-macos bootstrap-xcode sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios help: ## Show available commands @echo "Available targets:" @@ -184,10 +184,7 @@ endif ifeq ($(TOOLCHAIN_EFFECTIVE),direnv) @[ -n "$$NIX_STORE$$IN_NIX_SHELL" ] || { echo >&2 "[ERROR] TOOLCHAIN=direnv but the flake is not loaded. Run 'direnv allow', or use 'nix develop'."; exit 1; } endif -ifeq ($(TOOLCHAIN_EFFECTIVE),brew) - @command -v brew >/dev/null 2>&1 || { echo >&2 "[ERROR] TOOLCHAIN=brew but brew is not on PATH. Run 'make bootstrap-macos'."; exit 1; } -endif -ifeq ($(filter nix direnv brew,$(TOOLCHAIN_EFFECTIVE)),) +ifeq ($(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),) @echo "[INFO] $(TOOLCHAIN_EFFECTIVE): using the tools on PATH; no separate check." endif @@ -198,15 +195,13 @@ bootstrap: ## Enter the Nix dev shell (primary toolchain; no-op when already ins echo >&2 "[ERROR] Intel macOS is prebuilt-only; use 'make bootstrap-macos' (or a manual toolchain) and PREBUILTS=1."; \ exit 1; \ elif ! command -v nix >/dev/null 2>&1; then \ - echo >&2 "[ERROR] Nix is not installed. Install it from https://nixos.org/download/, or use the Homebrew fallback: make bootstrap-macos"; \ + echo >&2 "[ERROR] Nix is not installed. Source builds require Nix; install it from https://nixos.org/download/."; \ exit 1; \ else \ - echo "Entering the Nix dev shell. Run 'make build-macos VERSION=... BUILD_NUM=...' inside it."; \ - exec nix --extra-experimental-features 'nix-command flakes' develop; \ + @echo "Entering the Nix dev shell. Run 'make build-macos VERSION=... BUILD_NUM=...' inside it."; \ + exec nix --extra-experimental-features 'nix-command flakes' develop; \ fi -bootstrap-brew: bootstrap-macos ## Alias for the Homebrew fallback toolchain - check-linux: ## Fail unless the host is Linux ifeq ($(PLATFORM),Linux) @: @@ -304,19 +299,15 @@ else @exit 1 endif -bootstrap-macos: ## Install the Homebrew fallback toolchain (Nix is the primary path) +bootstrap-macos: ## Check/select the full Xcode.app (Nix supplies the rest of the toolchain) ifeq ($(PLATFORM),Darwin) # Call install_xcode.sh directly instead of `$(MAKE) bootstrap-xcode`: a recipe # line containing $(MAKE) is executed even under `make -n`, which would make a # dry run accept the Xcode license and run first-launch setup for real. - @if [ -n "$$IN_NIX_SHELL$$NIX_BUILD_TOP$$NIX_STORE" ]; then \ - echo "[WARN] Nix environment detected; skipping the Homebrew package install (use nix/flake-provided toolchain instead)."; \ - echo "[WARN] Xcode itself is never provided by Nix (Apple's license forbids redistributing it), so that part still runs:"; \ - bash scripts/install_xcode.sh || exit 1; \ - else \ - bash scripts/install_macos_build_tools.sh || exit 1; \ - rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios aarch64-apple-ios-sim --toolchain $(RUST_VERSION) >/dev/null 2>&1 || true; \ - fi +# Source builds require a Nix/direnv shell (the flake provides Flutter, Rust, +# Go and the dnix libraries). Xcode itself is never provided by Nix (Apple's +# license forbids redistributing it), so this target only handles Xcode. + @bash scripts/install_xcode.sh else @echo "[ERROR] bootstrap-macos is macOS-only." @exit 1 diff --git a/PR-1482-build-strategy-decision.md b/PR-1482-build-strategy-decision.md new file mode 100644 index 0000000000..699049a8f1 --- /dev/null +++ b/PR-1482-build-strategy-decision.md @@ -0,0 +1,108 @@ +# PR #1482 — Build strategy decision brief (Nix-only vs brew, benchmarks re-integration) + +_Compiled 2026-11-20. Grounded in the current tree (`feat/makefile-macos-build`, 18 commits past `15d0e12d3`)._ + +## The situation (your story, confirmed against the code) + +1. You built a working **make-based** cross-platform build (macOS/Linux/Windows) with real **caching** work — including changes to Rust crates so they build on a shared Rust version and benefit from cargo caching. +2. Julian introduced **native-assets Flutter**; the build process changed and your caching no longer applied cleanly. +3. You found **sccache** still works, and want to merge the makefile + benchmarking work. +4. Now: merge everything, clean up the existing CI + legacy build flows, make it proper. + +## Settled facts (verified in-tree, 2026-11-20) + +- **CI already does NOT use Nix.** Every CI build job (`build-windows` @ `windows-2022`, `build-macos` @ `macos-latest`, `build-linux`/`build-android` @ `ubuntu-24.04`) runs `build_app.sh … -d -s`, where **`-d` = verified dnix prebuilts** (Frost/Tor/Epic/MWC), hash-checked against each plugin's `dnix.lock`. No Nix, no WSL. +- **Nix is used only for local source builds** on macOS/Linux, and only when run inside a Nix/direnv shell (`build-macos`/`build-linux` derive `SOURCE_TOOLCHAIN` from `NIX_BIN` on PATH). +- **Windows has no Nix path at all.** dnix on Windows runs in WSL2; CI is `windows-2022` (native Windows), so Windows is prebuilt-only by necessity. +- The Homebrew fallback (`scripts/install_macos_build_tools.sh`) is the **only** thing that lets a local macOS/Linux source build run *without* Nix. It already reads every version pin from `stack-bom.toml` (`bom_get flutter/rust/rust_dnssec`), so it is **not** a duplication source. +- The prebuilt path's version check is **dnix's own hash verification** (`build_app.sh -d` verifies pinned SHA in prebuilt mode). That is the correct and sufficient "what to check" — the native lib versions are pinned in `dnix.lock`. + +## Decision 1 — Source-build toolchain policy + +### Option A: Nix-only for source builds (your preference) + +**Changes (minimal):** +- Delete `scripts/install_macos_build_tools.sh`. +- Delete the `else` (brew) branch of `bootstrap-macos` (Makefile:310-318); keep only the Nix-detecting branch, which already calls `install_xcode.sh`. +- Update docs: `docs/building/make.md` (the "Homebrew packages are in `install_macos_build_tools.sh`" line), `cyperstack_matrix_info.md:40` (the "pins live in `install_macos_build_tools.sh`" line). +- `verify-bom` already warns on missing toolchains; no new check needed for source builds (Nix provides them). + +**Limits / consequences:** +- **Contributors without Nix can no longer do a local source build.** They can still: (a) use prebuilt submodules via `PREBUILTS=1` + dnix prebuilts (`-d`) — this needs only the *toolchain* (Flutter/Rust/Go/Xcode), which they install however they like; (b) rely on CI. +- **CI is unchanged** — it already uses prebuilts, not Nix. No risk to the release pipeline. +- **Windows unchanged** — already prebuilt-only. +- **Cleanest merge story.** One toolchain path for source; matches Julian's stance. Kills a legacy flow instead of carrying it. + +**What it takes:** ~3-4 file edits, all doc + one Makefile branch + one file delete. Low risk. The only real work is the Option B flake change (below) if you also want the flake to read the BOM — otherwise the flake keeps its bare `pkgs.flutter`/`pkgs.go`, which is fine for Nix-only (Nix pins via nixpkgs rev). + +### Option B: Keep the Homebrew fallback + +**Changes:** none structural — the script already tracks the BOM. + +**Limits / consequences:** +- Two source-build paths to maintain and keep in sync (Nix + brew). The brew path's native libs come from Homebrew formulae whose versions **drift** from the dnix pins — this is the *real* duplication risk, because Homebrew auto-upgrades can move a lib version out from under a `dnix.lock` pin. (Mitigated by `HOMEBREW_NO_INSTALL_UPGRADE=1` in the script, but not eliminated.) +- More contributor-friendly (no Nix install to try a source build). +- Slightly muddier merge story — you're defending a path Julian is willing to drop. + +**What it takes:** nothing now; ongoing cost is keeping the brew formula set honest against the dnix pins. + +### Recommendation + +**Option A (Nix-only for source).** It matches your stated preference and Julian's, it's the smallest diff, and it removes the one genuinely duplicated + drift-prone path. The prebuilt path (dnix `-d`) still serves everyone who can't or won't use Nix — including all CI and Windows. Keep the BOM as the single toolchain source; the native libs stay pinned in `dnix.lock`. + +## Decision 2 — What to check on the prebuilt path + +**dnix hash verification only** (your choice). The native libs are hash-checked against `dnix.lock` by `build_app.sh -d`; the host only needs the toolchain, which `verify-bom` checks. No extra host-side lib-version probing — that would duplicate what dnix already guarantees. + +## Decision 3 — Windows + +**Keep as-is** (dnix prebuilts, no Nix). It already builds. Nix is not an option on `windows-2022`. + +## Decision 4 — Re-integrating your benchmarks (`bm/bench.sh`) + +**What it is:** `bm/bench.sh` (124 lines, on `build/native-assets-harness`, **not** on the current PR branch). A build-time benchmark harness: +- Runs `make build-macos`/`build-linux` (cold or `--warm`), records **wall-clock seconds + disk delta** to `bm/results/.csv`. +- Flags: `SCCACHE=0` (compare with/without sccache), `SKIP_NATIVE=1` (Dart-only), `--label`, `--warm`. +- Depends on `toilet` (terminal font) for pretty output — a soft dependency, easy to drop. +- Windows path explicitly refuses (needs WSL2). + +**Re-integration effort — small, and it's independent of the Nix-only decision:** +- The script itself is self-contained; cherry-pick `bm/bench.sh` + the `bm/results/` dir onto the PR (or a follow-up branch). ~1 file. +- **It already calls `make build-macos`/`build-linux`**, which under Nix-only means "must be in a Nix shell." That's actually *better* for benchmarking — the harness measures the canonical source build. No change needed. +- The sccache comparison (`SCCACHE=0`) is the interesting data: it measures your caching contribution directly. `make sccache-setup` (opt-in, on `build/native-assets-harness`) writes `~/.cargo/config.toml` with the `sccache` rustc-wrapper. +- **Caveat:** `bm/bench.sh` runs the *full* native build each cold run — on a fresh Nix shell that includes the dnix source compile (the 2-hour path). For a clean sccache-vs-no-sccache comparison you want the *incremental* native layer, so document that cold benchmarks assume a warm Nix store / pre-fetched dnix sources. + +**Recommendation:** land `bm/bench.sh` as a **separate small follow-up PR** (or a second commit on this branch after the build-strategy change lands), so the big merge isn't entangled with a benchmarking tool. It's orthogonal to Nix-only vs brew. + +## Sequencing to close the topic + +1. **Build-strategy change** (Option A): delete the brew fallback + docs, keep prebuilt/dnix path. One coherent commit. +2. **Optional Option B (flake reads BOM)** — only if you want the flake's Flutter/Go sourced from the BOM too. HIGH risk (nixpkgs-rev coupling); plan already written in `PR-1482-optionB-flake-bom-consolidation.md`. Can be its own PR. +3. **`bm/bench.sh` re-integration** — separate small PR/commit, orthogonal. + +--- + +## Outcome — Option A executed (2026-11-20) + +**Decision 1 resolved: Nix-only for source builds.** The Homebrew source-build fallback is removed; Homebrew remains a valid package manager for the **prebuilt** path (`PREBUILTS=1`). + +### Changes (one commit) +- **`scripts/install_macos_build_tools.sh`** — deleted (the Homebrew tool installer). +- **`Makefile`**: + - `bootstrap-macos` rewritten: now only runs `@bash scripts/install_xcode.sh` (Xcode is never provided by Nix/Homebrew). Dropped the `install_macos_build_tools.sh` branch and the `rustup target add` line. + - `bootstrap-brew` alias removed; removed from `.PHONY`. + - `bootstrap` target error wording: "Nix is not installed. Source builds require Nix; install it from https://nixos.org/download/." + - `toolchain-check`: dropped the `ifeq ($(TOOLCHAIN_EFFECTIVE),brew)` hard-fail branch; the final filter now treats `host`/`manual` as "tools on PATH, no separate check" (correct for the prebuilt path). + - `TOOLCHAIN` allowed values: removed `brew` (`auto nix direnv manual host`). +- **Living docs** (`README.md`, `docs/building/make.md`, `docs/building/macos.md`, `docs/building/make-flow.md`): reframed Homebrew from a source-build fallback to the prebuilt path; `bootstrap-macos` now described as Xcode check/select; `PREBUILTS=1` required for Homebrew/manual. +- **Historical drafts** (`cyperstack_matrix_*.md`, `julian_review_reply_draft.md`) — left **unchanged**: they are records of what was told to Julian when the Homebrew path existed. + +### Not done (out of scope, still open) +- **`makefile-build-audit` blocker** (PREBUILTS=0 guard tests only `NIX_BIN`, not `TOOLCHAIN_EFFECTIVE`): still present. Deleting the brew bootstrap removed the *toolchain* angle, but `make -n build-macos PREBUILTS=0 TOOLCHAIN=host` on a non-Nix host still doesn't hard-fail in dry-run (the guard runs at recipe time, and `-n` skips it). Consider tightening to require `nix`/`direnv` explicitly for `PREBUILTS=0` — a follow-up. +- **Option B** (flake reads BOM) and **`bm/bench.sh` re-integration** — unchanged, still separate follow-ups. + +### Verified +- `make -n help` parses cleanly. +- `toolchain-check` has no brew branch; the final filter is `ifeq ($(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),)`. +- Prebuilt path works: `make -n build-macos PREBUILTS=1 TOOLCHAIN=host` → exit 0. +- No dangling `install_macos_build_tools` / `bootstrap-brew` / `Homebrew fallback` refs in living docs. diff --git a/README.md b/README.md index 288395242f..39ad8d8775 100644 --- a/README.md +++ b/README.md @@ -73,26 +73,22 @@ The flake provides Flutter, Dart, rustup (which installs the BOM Rust version on first entry), Go, CMake, Meson, Ninja, pkg-config and protoc. Xcode is never provided by Nix; the flake uses the Xcode selected by `xcode-select`. -### macOS with Homebrew (fallback) +### macOS with Homebrew (prebuilt only) -Use this only when you are not building through Nix/flake. +Use this when you are not building through Nix/flake. Source builds require a +Nix/direnv shell; Homebrew/manual builds use the verified dnix prebuilts. 1. With Homebrew installed, install the host tools: - - `make bootstrap-macos` (alias: `make bootstrap-brew`) + - `brew install autoconf automake libtool cmake cocoapods go meson ninja pkg-config protobuf` + - `rustup toolchain install` the BOM Rust version (see `stack-bom.toml`). 2. Run build: - - Open a new terminal (or run `source ~/.zshrc`) so the Homebrew and - Flutter PATH entries are active. - `make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1` - Add `CONFIRM=1` for a non-interactive run. `PREBUILTS=1` is required with Homebrew/manual: those toolchains cannot build the four dnix libraries from source. It uses the verified prebuilts and needs -no Nix for them. - -The Homebrew bootstrap installs the native build tools and configures the BOM -Rust version for Flutter's native-assets hooks. It replaces the former local -manual macOS native prebuild path; no submodule setup or manual native -plugin build is needed. +no Nix for them. `make bootstrap-macos` checks and selects the full Xcode.app +(Xcode is never provided by Nix or Homebrew). ### macOS with a manual toolchain (advanced) diff --git a/docs/building/macos.md b/docs/building/macos.md index be7ab4c031..60c1cf2185 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -5,20 +5,20 @@ the build fits together, see the [overview](../building.md). ## Toolchains -The build steps below are the manual/Homebrew path. Nix is the primary host -toolchain; the same build is also available through: +Source builds require a Nix/direnv shell; the manual/Homebrew path below is +for **prebuilt** builds (`PREBUILTS=1`) only. The same build is also available +through Nix: | Mode | Setup | |---|---| | Nix | `make bootstrap` (enters `nix develop`) | | direnv | `direnv allow` | -| Homebrew | `make bootstrap-macos` | -| Manual | install the prerequisites below | +| Manual / Homebrew | install the prerequisites below; use `PREBUILTS=1` | With Nix or direnv the flake supplies Flutter, Dart, rustup (which installs the BOM Rust version on first entry), Go, CMake, Meson, Ninja, pkg-config and protoc. Xcode always comes from the host. The prerequisites below describe the -manual/Homebrew path. +manual/Homebrew (prebuilt) path. ## Prerequisites diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md index e9654dc97e..edd77bd94b 100644 --- a/docs/building/make-flow.md +++ b/docs/building/make-flow.md @@ -14,25 +14,20 @@ tracked `.envrc` is `use flake`, so it activates the same shell as `.envrc` started as a standalone environment script; it was reduced to `use flake` when the flake and Makefile took over the host setup. That is why -direnv is the Nix activator, not a fourth toolchain. The Homebrew helper still -installs the `direnv` binary, but `.envrc` skips the flake when Nix is absent, -so a Homebrew-only shell is not blocked. +direnv is the Nix activator, not a fourth toolchain. Source builds require a +Nix/direnv shell; the manual/Homebrew path below is for prebuilt builds +(`PREBUILTS=1`) only. ```mermaid flowchart LR S["Pick a host
toolchain"] - S --> N["Nix (primary)
make bootstrap"] - S --> D["direnv
direnv allow"] - S --> B["Homebrew fallback
make bootstrap-macos"] - S --> M["Manual
TOOLCHAIN=manual"] + S --> N["Nix / direnv
source builds
make bootstrap"] + S --> M["Manual / Homebrew
prebuilt only
PREBUILTS=1"] N --> F["Flake
Flutter · Rust · Go
CMake · Meson · Ninja"] - D --> F - B --> H["Homebrew helper
Flutter · Rust · Go"] - M --> P["Tools on PATH"] + M --> P["Tools on PATH
Flutter · Rust · Go"] F --> C["make toolchain-check
check-reqs-macos"] - H --> C P --> C C --> X{"Full Xcode?"} diff --git a/docs/building/make.md b/docs/building/make.md index b2b23a792e..84a167a7b1 100644 --- a/docs/building/make.md +++ b/docs/building/make.md @@ -56,8 +56,8 @@ make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1 # verified prebuilts ( | `make build-android` | Same build commands as CI, without the AAB/upload steps; signs with `android/key.properties` (run `make android-dev-key` for a throw-away test key), needs the Android SDK/NDK and Java. Prebuilt dnix on macOS, non-x86_64 Linux and brew/manual toolchains; x86_64 Linux in Nix/direnv follows `PREBUILTS` | | `make build-ios` | Same build commands as CI, without signing/packaging, on macOS (`flutter build ios --release --no-codesign`). Source by default only in Nix/direnv on Apple Silicon; CI passes `-d` explicitly | | `make bootstrap` | Enter the Nix dev shell (primary toolchain); no-op when already inside | -| `make bootstrap-macos` | Homebrew fallback host setup: Flutter and Rust from `stack-bom.toml` plus the Homebrew packages (Go, CMake, Meson, Ninja, pkg-config, protobuf, CocoaPods, autotools, direnv, rustup, sccache) | -| `make toolchain` | Show the active toolchain (`nix`, `direnv`, `host`, `brew`, `manual`) | +| `make bootstrap-macos` | Check and select the full Xcode.app (Xcode is never provided by Nix) | +| `make toolchain` | Show the active toolchain (`nix`, `direnv`, `host`, `manual`) | | `make bootstrap-xcode` | Check and select an installed full Xcode.app | | `make check-reqs`, `check-reqs-macos`, `check-sdk-macos`, `diagnose-env-macos` | Prerequisite checks and an environment dump | | `make verify-bom` | Compare the machine and `pubspec.lock` against `stack-bom.toml` | @@ -67,18 +67,17 @@ make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1 # verified prebuilts ( ## Toolchains on macOS -The build steps are identical in every mode; only how the host tools get on -`PATH` differs. Nix is the primary path. +Source builds require a Nix/direnv shell; the prebuilt path (`PREBUILTS=1`) +uses the host tools on PATH (manual or host), which Homebrew can supply. | Mode | Setup | Notes | |---|---|---| | Nix | `make bootstrap` (enters `nix develop`) | The flake provides Flutter and Go from its pinned nixpkgs (currently Flutter 3.47.2, matching the BOM, and Go 1.26.7; the BOM's `go` is the CI/Docker pin), Dart, rustup (which installs the BOM Rust version on first entry), CMake, Meson, Ninja, pkg-config and protoc. Xcode always comes from the host. | | direnv | `direnv allow` | The same flake as Nix, loaded automatically. | -| Homebrew | `make bootstrap-macos` (alias `make bootstrap-brew`) | Fallback; source builds need `nix` on `PATH`. Installs the Flutter tag and Rust from `stack-bom.toml` plus the Homebrew packages, and prints the PATH lines to add (pass `WRITE_PROFILE=1` to append them to `~/.zshrc` automatically). | -| Manual | install the tools yourself | Advanced; source builds need `nix` on `PATH`. `make check-reqs-macos` reports what is missing. | +| Manual / Homebrew | install the tools yourself (Homebrew for the prebuilt path) | Source builds are not available without Nix. Use `PREBUILTS=1` with the verified dnix prebuilts; Homebrew can install the tooling (Flutter, Rust, Go, CocoaPods, sccache, …). `make check-reqs-macos` reports what is missing. | `make toolchain` prints the active mode and tool paths. -`TOOLCHAIN=nix|direnv|brew` forces a check; `host` and `manual` use whatever is on `PATH`; `auto` (the default) detects a Nix/direnv shell and otherwise uses the host tools. Any toolchain can use `PREBUILTS=0` when `nix` is on `PATH`; without it the Makefile defaults to prebuilt mode. +`TOOLCHAIN=nix|direnv` forces a check; `host` and `manual` use whatever is on `PATH`; `auto` (the default) detects a Nix/direnv shell and otherwise uses the host tools. Any toolchain can use `PREBUILTS=0` when `nix` is on `PATH`; without it the Makefile defaults to prebuilt mode. `make check-reqs-macos` verifies the result and `make diagnose-env-macos` prints what was found. @@ -103,7 +102,7 @@ Flutter reruns every native-asset build hook when `PATH` or any `NIX_*` variable ## Toolchain bill of materials -`stack-bom.toml` lists the toolchain a build is expected to use (Flutter, Dart, Rust, Go, Xcode). It is not a Homebrew package manifest: the native dnix libraries are pinned in each plugin's `dnix.lock`, and the plugins themselves are pinned by `pubspec.lock`; the Homebrew packages are in `scripts/install_macos_build_tools.sh`. `make verify-bom` compares the local machine against the BOM and exits with an error on a mismatch (a different recommended Flutter or Xcode version is only a warning). Source builds additionally require the Xcode 27.0 that dnix pins; `build_app.sh` enforces that, while `verify-bom` only warns. +`stack-bom.toml` lists the toolchain a build is expected to use (Flutter, Dart, Rust, Go, Xcode). It is not a Homebrew package manifest: the native dnix libraries are pinned in each plugin's `dnix.lock`, and the plugins themselves are pinned by `pubspec.lock`. `make verify-bom` compares the local machine against the BOM and exits with an error on a mismatch (a different recommended Flutter or Xcode version is only a warning). Source builds additionally require the Xcode 27.0 that dnix pins; `build_app.sh` enforces that, while `verify-bom` only warns. ## Optional: sccache for native-asset builds From 7c01e0ff34e91bca7452c7fddc970c15ede6a815 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:01:10 +0200 Subject: [PATCH 086/107] Delete install_macos_build_tools.sh (Homebrew tool installer removed) The Homebrew source-build fallback is gone (Nix-only for source builds, see d89d8266bb). This script installed the Homebrew toolchain, which is no longer referenced by bootstrap-macos or any doc. --- scripts/install_macos_build_tools.sh | 235 --------------------------- 1 file changed, 235 deletions(-) delete mode 100755 scripts/install_macos_build_tools.sh diff --git a/scripts/install_macos_build_tools.sh b/scripts/install_macos_build_tools.sh deleted file mode 100755 index 7f642981bd..0000000000 --- a/scripts/install_macos_build_tools.sh +++ /dev/null @@ -1,235 +0,0 @@ -#!/usr/bin/env bash - -# Run directly (bash script.sh). On error this exits the shell; do not source. -if [ -n "${ZSH_VERSION:-}" ]; then - if [[ "${ZSH_EVAL_CONTEXT:-}" == *file* ]]; then - set -uo pipefail # sourced in zsh, don't -e - else - set -euo pipefail # executed in zsh - fi -elif [ -n "${BASH_VERSION:-}" ]; then - if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then - set -uo pipefail # sourced in bash, don't -e - else - set -euo pipefail # executed in bash - fi -else - set -euo pipefail # unknown shell -fi -die() { echo "$@" >&2; exit 1; } - -if [[ "$(uname -s)" != "Darwin" ]]; then - die "This installer is for macOS only." -fi - -# Homebrew may not be in PATH after a fresh install -if ! command -v brew >/dev/null 2>&1; then - if [[ -x /opt/homebrew/bin/brew ]]; then - eval "$(/opt/homebrew/bin/brew shellenv)" - elif [[ -x /usr/local/bin/brew ]]; then - eval "$(/usr/local/bin/brew shellenv)" - else - die "Homebrew is required. Install it from https://brew.sh, then re-run 'make bootstrap-macos'." - fi -fi - -# rustup is keg-only in Homebrew (conflicts with rust), so it has to be added to PATH by hand. -# Called again after `brew install`: on a first install the directory does not exist before it. -add_rustup_to_path() { - local prefix - prefix="$(brew --prefix rustup 2>/dev/null || true)" - [[ -n "$prefix" && -d "$prefix/bin" && ":$PATH:" != *":$prefix/bin:"* ]] && export PATH="$prefix/bin:$PATH" - return 0 -} -add_rustup_to_path - -SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]:-$0}")" && pwd)" -REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" -# Read a value from stack-bom.toml so the Homebrew fallback and the flake use -# the same versions. -bom_get() { - "$SCRIPT_DIR/bom_values.sh" --get "$1" "$REPO_ROOT/stack-bom.toml" -} -echo "Installing Homebrew packages..." -# Do not upgrade formulae that are already installed: a build machine keeps the versions it was set up with. -export HOMEBREW_NO_INSTALL_UPGRADE=1 -brew install direnv rustup cmake meson ninja pkg-config cocoapods go protobuf autoconf automake libtool sccache -add_rustup_to_path - -# The Homebrew cask always installs the latest Flutter, but CI builds and tests -# one pinned release. Install that tag from source instead. -FLUTTER_RECOMMENDED="$(bom_get flutter)" -FLUTTER_MIN="$(bom_get flutter_min)" -FLUTTER_VERSION="${FLUTTER_VERSION:-${FLUTTER_RECOMMENDED:-3.47.2}}" -# Accept the recommended version and the CI minimum; an explicit -# FLUTTER_VERSION only accepts that version. -if [[ -n "${FLUTTER_ACCEPTED_VERSIONS:-}" ]]; then - : -elif [[ -n "$FLUTTER_MIN" && "$FLUTTER_VERSION" == "$FLUTTER_RECOMMENDED" ]]; then - FLUTTER_ACCEPTED_VERSIONS="$FLUTTER_VERSION $FLUTTER_MIN" -else - FLUTTER_ACCEPTED_VERSIONS="$FLUTTER_VERSION" -fi -FLUTTER_DIR="${FLUTTER_DIR:-$HOME/development/flutter}" -FLUTTER_MARKER=".stack-wallet-managed" -case "$FLUTTER_DIR" in - /*) ;; - *) FLUTTER_DIR="$PWD/$FLUTTER_DIR" ;; -esac - -flutter_installed_version() { - "$1" --version --machine 2>/dev/null | sed -n 's/.*"frameworkVersion": *"\([^"]*\)".*/\1/p' | head -n 1 -} - -flutter_version_ok() { - local accepted - for accepted in $FLUTTER_ACCEPTED_VERSIONS; do - [[ "$1" == "$accepted" ]] && return 0 - done - return 1 -} - -FLUTTER_BIN="$(command -v flutter 2>/dev/null || true)" -[[ -z "$FLUTTER_BIN" && -x "$FLUTTER_DIR/bin/flutter" ]] && FLUTTER_BIN="$FLUTTER_DIR/bin/flutter" -CURRENT_FLUTTER="" -[[ -n "$FLUTTER_BIN" ]] && CURRENT_FLUTTER="$(flutter_installed_version "$FLUTTER_BIN")" -FLUTTER_PATH_TO_PERSIST="" - -if flutter_version_ok "$CURRENT_FLUTTER"; then - echo "Flutter $CURRENT_FLUTTER already installed ($FLUTTER_BIN)." - [[ "$FLUTTER_BIN" == "$FLUTTER_DIR/bin/flutter" ]] && FLUTTER_PATH_TO_PERSIST="$FLUTTER_DIR/bin" -else - [[ -n "$CURRENT_FLUTTER" ]] && echo "Found Flutter $CURRENT_FLUTTER at $FLUTTER_BIN, need $FLUTTER_VERSION." - if [[ -d "$FLUTTER_DIR/.git" ]]; then - if [[ ! -e "$FLUTTER_DIR/$FLUTTER_MARKER" ]]; then - die "$FLUTTER_DIR is an existing Flutter checkout that this script did not create. -Move it away, or set FLUTTER_DIR to a directory this script may manage." - fi - echo "Switching $FLUTTER_DIR to Flutter $FLUTTER_VERSION..." - git -C "$FLUTTER_DIR" fetch --tags origin - git -C "$FLUTTER_DIR" checkout "$FLUTTER_VERSION" - elif [[ -e "$FLUTTER_DIR" ]]; then - die "$FLUTTER_DIR exists but is not a Flutter git checkout. Move it away or set FLUTTER_DIR." - else - echo "Cloning Flutter $FLUTTER_VERSION into $FLUTTER_DIR..." - mkdir -p "$(dirname "$FLUTTER_DIR")" - git clone --branch "$FLUTTER_VERSION" --depth 1 https://github.com/flutter/flutter.git "$FLUTTER_DIR" - fi - FLUTTER_BIN="$FLUTTER_DIR/bin/flutter" - FLUTTER_PATH_TO_PERSIST="$FLUTTER_DIR/bin" -fi - -# Only prepend the managed SDK when the selected Flutter is not already on PATH. -FLUTTER_BIN_DIR="$(dirname "$FLUTTER_BIN")" -case ":$PATH:" in - *":$FLUTTER_BIN_DIR:"*) ;; - *) export PATH="$FLUTTER_BIN_DIR:$PATH" ;; -esac - -if ! command -v rustup >/dev/null 2>&1; then - die "rustup not found in PATH. Check brew install." -fi - -RUST_VERSION="${RUST_VERSION:-$(bom_get rust)}" -RUST_VERSION="${RUST_VERSION:-1.99.1}" -echo "Ensuring Rust $RUST_VERSION toolchain..." -rustup toolchain install "$RUST_VERSION" -rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios aarch64-apple-ios-sim --toolchain "$RUST_VERSION" >/dev/null 2>&1 || true - -# DNSSEC native builds (via native_dependency_contract) pin their own Rust -# toolchain through rust-toolchain.toml. verify-bom runs before the build hooks -# get a chance to install it, so install it here as well. -DNSSEC_RUST_VERSION="${DNSSEC_RUST_VERSION:-$(bom_get rust_dnssec || true)}" -DNSSEC_RUST_VERSION="${DNSSEC_RUST_VERSION:-1.90.0}" -echo "Ensuring Rust $DNSSEC_RUST_VERSION toolchain (DNSSEC)..." -rustup toolchain install "$DNSSEC_RUST_VERSION" >/dev/null 2>&1 || true - -# Homebrew's rustup formula is keg-only and does not necessarily create the -# cargo/rustc shims in ~/.cargo/bin — `rustup toolchain install` alone may leave -# that directory absent, which means no `cargo` on PATH in this shell or any -# future one. Create the shims via rustup-init when they are missing. -if [ ! -x "$HOME/.cargo/bin/cargo" ]; then - echo "cargo shims missing in ~/.cargo/bin; creating them via rustup-init..." - if command -v rustup-init >/dev/null 2>&1; then - rustup-init -y --no-modify-path --default-toolchain none || true - else - die "rustup-init not found. Run 'brew install rustup', then re-run this script." - fi -fi - -# cargo/rustc live in ~/.cargo/bin after rustup installs a toolchain -export PATH="$HOME/.cargo/bin:$PATH" -if [ -f "$HOME/.cargo/env" ]; then - # shellcheck disable=SC1091 - source "$HOME/.cargo/env" -fi - -if ! command -v cargo >/dev/null 2>&1; then - die "cargo still not on PATH after rustup setup. Run 'rustup-init -y' manually, then re-run this script." -fi - -bash "$SCRIPT_DIR/install_xcode.sh" - -echo "Verifying toolchain..." -if command -v flutter >/dev/null 2>&1; then - flutter --version -else - echo "flutter not found in PATH. Add $FLUTTER_DIR/bin to your shell profile." -fi - -if command -v dart >/dev/null 2>&1; then - dart --version -else - echo "dart not found in PATH. It should come with Flutter." -fi - -rustup --version -rustup run "$RUST_VERSION" rustc --version -rustup run "$RUST_VERSION" cargo --version -rustup run "$DNSSEC_RUST_VERSION" rustc --version -pod --version -go version -autoreconf --version | head -n 1 || true -aclocal --version | head -n 1 || true - -echo "" -echo "Done." - -# Persist PATH entries for future terminals. This is opt-in: bootstrap must not -# edit a shell profile the user did not ask it to touch. Set WRITE_PROFILE=1 -# (or run with --write-profile) to apply the lines automatically. -if [ "${WRITE_PROFILE:-0}" != "1" ]; then - echo "" - echo "→ Not modifying $HOME/.zshrc." - echo " Add these lines to your shell profile, or re-run with WRITE_PROFILE=1:" - echo " eval \"\$($(brew --prefix)/bin/brew shellenv)\"" - if [ -n "${FLUTTER_PATH_TO_PERSIST:-}" ]; then - printf ' export PATH=%s:$PATH\n' "$(printf '%q' "$FLUTTER_PATH_TO_PERSIST")" - fi - printf ' export PATH="%s/opt/rustup/bin:$HOME/.cargo/bin:$PATH"\n' "$(brew --prefix)" - echo "" - echo "Done." - exit 0 -fi - -# Create ~/.zshrc when missing: a vanilla macOS install ships without one, and -ZSHRC="$HOME/.zshrc" -if [ ! -f "$ZSHRC" ]; then - touch "$ZSHRC" - echo "→ Created $ZSHRC (macOS ships without one)" -fi -BREW_PREFIX="$(brew --prefix)" -grep -qF 'brew shellenv' "$ZSHRC" 2>/dev/null || \ - printf 'eval "$(%s/bin/brew shellenv)"\n' "$BREW_PREFIX" >> "$ZSHRC" -if [[ -n "$FLUTTER_PATH_TO_PERSIST" ]]; then - FLUTTER_PATH_ESCAPED="$(printf '%q' "$FLUTTER_PATH_TO_PERSIST")" - if ! grep -qF "$FLUTTER_PATH_TO_PERSIST" "$ZSHRC" 2>/dev/null && \ - ! grep -qF "$FLUTTER_PATH_ESCAPED" "$ZSHRC" 2>/dev/null; then - # %q keeps a user-supplied FLUTTER_DIR from becoming shell syntax. - printf 'export PATH=%s:$PATH\n' "$FLUTTER_PATH_ESCAPED" >> "$ZSHRC" - fi -fi -grep -qF '$HOME/.cargo/bin' "$ZSHRC" 2>/dev/null || \ - printf 'export PATH="%s/opt/rustup/bin:$HOME/.cargo/bin:$PATH"\n' "$BREW_PREFIX" >> "$ZSHRC" -echo "→ PATH entries ensured in $ZSHRC" -echo " Open a new terminal (or run: source $ZSHRC) before 'make build-macos'." From 46195a8a70a301e4f0a8d876c77b3da190caba8a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:12:11 +0200 Subject: [PATCH 087/107] Require an active Nix/direnv shell for source builds (PREBUILTS=0) - Fixes the makefile-build-audit blocker: PREBUILTS=0 guarded only on NIX_BIN (nix on PATH), never on TOOLCHAIN_EFFECTIVE, so a non-Nix toolchain with nix on PATH could build from source without a shell. - SOURCE_TOOLCHAIN now set only inside an active nix/direnv shell (filter nix direnv on TOOLCHAIN_EFFECTIVE), not merely nix-on-PATH. - PREBUILTS=0 error now requires TOOLCHAIN=nix or direnv. - Android source guard inherits the fix via SOURCE_TOOLCHAIN. --- Makefile | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index 825b7c7aa8..f469b8a8f8 100644 --- a/Makefile +++ b/Makefile @@ -121,9 +121,10 @@ ifeq ($(TOOLCHAIN),auto) else TOOLCHAIN_EFFECTIVE := $(TOOLCHAIN) endif -# Source builds need Nix on PATH to build the dnix libraries. The Nix/direnv -# shell supplies it; any toolchain can use PREBUILTS=0 when nix is available. -override SOURCE_TOOLCHAIN := $(if $(strip $(NIX_BIN)),1,) +# Source builds require an active Nix/direnv shell (not just nix on PATH): the +# shell supplies the dnix libraries and the toolchain. SOURCE_TOOLCHAIN is set +# only inside such a shell; the prebuilt path (PREBUILTS=1) uses host tools. +override SOURCE_TOOLCHAIN := $(if $(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),1,) # Linux builds use a project-local pub cache so cargo finds the repo-local # .cargo/config.toml that carries PROTOC through Flutter's filtered hook environment. # Other targets leave PUB_CACHE unset, so Flutter uses its normal per-user cache @@ -400,8 +401,8 @@ ifeq ($(PREBUILTS),0) endif endif ifeq ($(filter Darwin Linux,$(PLATFORM)),$(PLATFORM)) - ifeq ($(strip $(NIX_BIN)),) - $(error PREBUILTS=0 (dnix source) needs an active Nix/direnv shell; run 'make bootstrap' or use PREBUILTS=1) + ifeq ($(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),) + $(error PREBUILTS=0 (dnix source) requires an active Nix/direnv shell (TOOLCHAIN=nix or direnv); run 'make bootstrap' or use PREBUILTS=1) endif endif endif From 091033b32e5edf94d04c671111e0388a306f2f9a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:13:13 +0200 Subject: [PATCH 088/107] Install Nix in bootstrap-macos (source-build bootstrap) - New scripts/install_nix.sh: checks for nix on PATH, installs the official multi-user (daemon) Nix from nixos.org when missing. Idempotent; like install_xcode.sh it fails with clear instructions rather than guessing (Nix has an official signature-checked installer, unlike Xcode, so auto-install is appropriate here). - bootstrap-macos now runs install_nix.sh then install_xcode.sh. - Docs: bootstrap-macos described as installing Nix + selecting Xcode. --- Makefile | 10 ++++--- README.md | 4 +-- docs/building/macos.md | 2 +- docs/building/make.md | 2 +- scripts/install_nix.sh | 63 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 73 insertions(+), 8 deletions(-) create mode 100755 scripts/install_nix.sh diff --git a/Makefile b/Makefile index f469b8a8f8..0eed3c053b 100644 --- a/Makefile +++ b/Makefile @@ -300,14 +300,16 @@ else @exit 1 endif -bootstrap-macos: ## Check/select the full Xcode.app (Nix supplies the rest of the toolchain) +bootstrap-macos: ## Install Nix + check/select the full Xcode.app (source-build bootstrap) ifeq ($(PLATFORM),Darwin) -# Call install_xcode.sh directly instead of `$(MAKE) bootstrap-xcode`: a recipe +# Call install_*.sh directly instead of `$(MAKE) bootstrap-xcode`: a recipe # line containing $(MAKE) is executed even under `make -n`, which would make a # dry run accept the Xcode license and run first-launch setup for real. # Source builds require a Nix/direnv shell (the flake provides Flutter, Rust, -# Go and the dnix libraries). Xcode itself is never provided by Nix (Apple's -# license forbids redistributing it), so this target only handles Xcode. +# Go and the dnix libraries); install Nix if it is missing. Xcode itself is +# never provided by Nix (Apple's license forbids redistributing it), so it is +# checked/selected too. Both installers are idempotent. + @bash scripts/install_nix.sh @bash scripts/install_xcode.sh else @echo "[ERROR] bootstrap-macos is macOS-only." diff --git a/README.md b/README.md index 39ad8d8775..138a5f947b 100644 --- a/README.md +++ b/README.md @@ -87,8 +87,8 @@ Nix/direnv shell; Homebrew/manual builds use the verified dnix prebuilts. `PREBUILTS=1` is required with Homebrew/manual: those toolchains cannot build the four dnix libraries from source. It uses the verified prebuilts and needs -no Nix for them. `make bootstrap-macos` checks and selects the full Xcode.app -(Xcode is never provided by Nix or Homebrew). +no Nix for them. `make bootstrap-macos` installs Nix (if missing) and checks/ +selects the full Xcode.app (Xcode is never provided by Nix or Homebrew). ### macOS with a manual toolchain (advanced) diff --git a/docs/building/macos.md b/docs/building/macos.md index 60c1cf2185..aedae3b4fb 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -13,7 +13,7 @@ through Nix: |---|---| | Nix | `make bootstrap` (enters `nix develop`) | | direnv | `direnv allow` | -| Manual / Homebrew | install the prerequisites below; use `PREBUILTS=1` | +| Manual / Homebrew | `make bootstrap-macos` (installs Nix + selects Xcode); use `PREBUILTS=1` | With Nix or direnv the flake supplies Flutter, Dart, rustup (which installs the BOM Rust version on first entry), Go, CMake, Meson, Ninja, pkg-config and protoc. diff --git a/docs/building/make.md b/docs/building/make.md index 84a167a7b1..5531ac580b 100644 --- a/docs/building/make.md +++ b/docs/building/make.md @@ -56,7 +56,7 @@ make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1 # verified prebuilts ( | `make build-android` | Same build commands as CI, without the AAB/upload steps; signs with `android/key.properties` (run `make android-dev-key` for a throw-away test key), needs the Android SDK/NDK and Java. Prebuilt dnix on macOS, non-x86_64 Linux and brew/manual toolchains; x86_64 Linux in Nix/direnv follows `PREBUILTS` | | `make build-ios` | Same build commands as CI, without signing/packaging, on macOS (`flutter build ios --release --no-codesign`). Source by default only in Nix/direnv on Apple Silicon; CI passes `-d` explicitly | | `make bootstrap` | Enter the Nix dev shell (primary toolchain); no-op when already inside | -| `make bootstrap-macos` | Check and select the full Xcode.app (Xcode is never provided by Nix) | +| `make bootstrap-macos` | Install Nix (if missing) and check/select the full Xcode.app | | `make toolchain` | Show the active toolchain (`nix`, `direnv`, `host`, `manual`) | | `make bootstrap-xcode` | Check and select an installed full Xcode.app | | `make check-reqs`, `check-reqs-macos`, `check-sdk-macos`, `diagnose-env-macos` | Prerequisite checks and an environment dump | diff --git a/scripts/install_nix.sh b/scripts/install_nix.sh new file mode 100755 index 0000000000..4bc14e120e --- /dev/null +++ b/scripts/install_nix.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash + +# Checks for Nix and installs it (multi-user daemon) when missing. Source builds +# require Nix (it supplies the dnix libraries and the toolchain), so this runs +# from `make bootstrap-macos` alongside the Xcode check. Nix is the only host +# dependency this script auto-installs: unlike Xcode (Apple's licensing forbids +# redistributing it) and unlike the app's own toolchain (pinned in the BOM), +# Nix is a general build tool with an official, signature-checked installer. +# +# Run directly (bash script.sh). On error this exits the shell; do not source. +if [[ -n "${ZSH_VERSION:-}" ]]; then + if [[ "${ZSH_EVAL_CONTEXT:-}" == *file* ]]; then + set -uo pipefail # sourced in zsh, don't -e + else + set -euo pipefail # executed in zsh + fi +elif [[ -n "${BASH_VERSION:-}" ]]; then + if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then + set -uo pipefail # sourced in bash, don't -e + else + set -euo pipefail # executed in bash + fi +else + set -euo pipefail # unknown shell +fi +die() { echo "$@" >&2; exit 1; } + +if [[ "$(uname -s)" != "Darwin" ]]; then + die "This installer is for macOS only." +fi + +echo "Checking Nix..." + +# A Nix binary on PATH (any install mode) is good enough to build; we do not +# force the daemon if the user already has a working Nix. +if command -v nix >/dev/null 2>&1; then + echo "Nix already installed: $(command -v nix) ($(nix --version 2>/dev/null || echo 'version unknown'))" + exit 0 +fi + +INSTALLER="${NIX_INSTALLER:-https://nixos.org/nix/install}" + +echo "Nix not found on PATH. Installing the multi-user Nix (daemon) from ${INSTALLER}..." +echo "This needs sudo and downloads from the Nix project; it configures /nix/store and the nixbld users." + +# The official installer script. `--daemon` is the recommended multi-user mode +# on macOS: it creates the build users and sets up launchd so `nix` works for +# every user. It prompts for sudo; pass --no-daemon for a single-user install. +if [[ -n "${NIX_INSTALLER_NO_INTERACTIVE:-}" ]]; then + : # allow callers to inject flags, e.g. NIX_INSTALLER_NO_INTERACTIVE=1 +fi + +curl --proto '=https' --tlsv1.2 -L "$INSTALLER" | sh -s -- --daemon + +# The installer puts nix in ~/.nix-profile/bin, which most login shells source +# via .zshrc/.profile. Non-interactive shells (and `make` invoked from an IDE) +# won't have it on PATH until re-sourced or re-logged-in. +if ! command -v nix >/dev/null 2>&1; then + echo "[WARN] Nix installed but not on PATH in this shell. Open a new terminal, or run:" + echo " . /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh" +fi + +echo "[OK] Nix installed: $(command -v nix 2>/dev/null || echo 'see above')" From aba33e8be6e0bf0029f6f7144adcdea8a942de35 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:16:02 +0200 Subject: [PATCH 089/107] Re-integrate build benchmark harness (bm/) - bench.sh/collect.sh/compare.py/render.sh/run_all.sh/report.css from build/native-assets-harness, plus bm/README.md. - Runs make build-macos/build-linux, so it inherits the Nix-only source-build rules; README documents running it in a Nix shell. - bm/results/ git-ignored (per-machine CSVs). - README notes the two stale no-ops: SCCACHE=0/1 is labeling only (sccache toggled by make sccache-setup), SKIP_NATIVE is a no-op through make (use make clean-native). --- .gitignore | 3 +++ bm/README.md | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 bm/README.md diff --git a/.gitignore b/.gitignore index 529cc3d420..af062aa188 100644 --- a/.gitignore +++ b/.gitignore @@ -131,3 +131,6 @@ lib/wl_gen/generated/ /android/dev-keystore.jks /android/keystore.jks /android/keystore-orig.jks + +# Benchmark results (per-machine CSVs; see bm/README.md) +/bm/results/ diff --git a/bm/README.md b/bm/README.md new file mode 100644 index 0000000000..107d70b724 --- /dev/null +++ b/bm/README.md @@ -0,0 +1,57 @@ +# Build benchmarks + +Measure wall-clock build time and disk delta for the native-assets build. The +suite runs `make build-macos` / `make build-linux`, so it inherits the same +toolchain rules as the build itself. + +## Run inside a Nix/direnv shell + +Source builds require an active Nix/direnv shell (the flake supplies Flutter, +Rust, Go and the dnix libraries). Run the harness from that shell, exactly as a +real build: + +```sh +make bootstrap # enter the Nix dev shell +bash bm/bench.sh # one cold build (sccache on), appends to bm/results/.csv +``` + +On macOS, `make bootstrap-macos` installs Nix (if missing) and selects Xcode +before you enter the shell. + +## Scripts + +| Script | Purpose | +|---|---| +| `bench.sh` | One build (cold or `--warm`), records wall seconds + disk delta to `bm/results/.csv` | +| `collect.sh` | Snapshot disk/`build/`/toolchain sizes independent of a build | +| `compare.py` | Render/compare the CSVs (terminal table, or markdown for PDF) | +| `render.sh` | Convert a markdown report to HTML + PDF (needs `pandoc`; a PDF engine is optional) | +| `run_all.sh` | Full cold→warm suite, simplest to most optimized | + +## bench.sh flags + +```sh +bash bm/bench.sh # cold build, sccache on (default) +bash bm/bench.sh --warm # warm rebuild (no clean) +bash bm/bench.sh --label NAME # tag the run +bash bm/bench.sh SCCACHE=0 # cold, sccache off +bash bm/bench.sh SKIP_NATIVE=1 # Dart only (no native libs) +``` + +## Caveats + +- **Results are per-machine and git-ignored** (`bm/results/`). Do not commit + them; they vary by hardware and Nix store state. +- **Cold runs assume a warm Nix store.** A fresh store compiles the dnix + libraries from source (~2h) and that time would dominate the wall clock, + masking the sccache-vs-no-sccache comparison. Pre-fetch the dnix sources + (e.g. `nix build` once) before measuring so a cold run only measures the + project build, not the library compile. +- **sccache is a cargo-config toggle, not a make flag.** `SCCACHE=0/1` is + accepted by `bench.sh` for labeling, but sccache is actually turned on/off by + `make sccache-setup`, which writes `~/.cargo/config.toml` with the + `rustc-wrapper = "sccache"` setting. Remove that file to benchmark without + sccache. +- **`SKIP_NATIVE=1` is a no-op through `make`.** The Makefile does not consume + it; it is a leftover from the harness's pre-make origin. Use `make clean-native` + + `make build-macos` if you want to isolate the Dart layer. From 43fe2a7b13346b739acd2250beeed3ae487be9d0 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:16:09 +0200 Subject: [PATCH 090/107] Add benchmark harness scripts (bm/bench.sh etc.) The 6 harness scripts from build/native-assets-harness. bench.sh runs make build-macos/build-linux and records wall seconds + disk delta to bm/results/.csv; compare.py renders them, render.sh makes a PDF, run_all.sh runs the full cold->warm suite, collect.sh snapshots sizes. See bm/README.md and .gitignore (aba33e8be6). --- bm/bench.sh | 124 ++++++++++++++++++++++++++++++++++++++ bm/collect.sh | 132 ++++++++++++++++++++++++++++++++++++++++ bm/compare.py | 162 ++++++++++++++++++++++++++++++++++++++++++++++++++ bm/render.sh | 61 +++++++++++++++++++ bm/report.css | 132 ++++++++++++++++++++++++++++++++++++++++ bm/run_all.sh | 56 +++++++++++++++++ 6 files changed, 667 insertions(+) create mode 100755 bm/bench.sh create mode 100755 bm/collect.sh create mode 100644 bm/compare.py create mode 100755 bm/render.sh create mode 100644 bm/report.css create mode 100755 bm/run_all.sh diff --git a/bm/bench.sh b/bm/bench.sh new file mode 100755 index 0000000000..9aa3d7c4ea --- /dev/null +++ b/bm/bench.sh @@ -0,0 +1,124 @@ +#!/usr/bin/env bash +# ============================================================================== +# bench.sh: Simple build benchmark for stack_wallet +# +# Usage: +# bash bm/bench.sh # cold build with sccache (default) +# bash bm/bench.sh --warm # warm rebuild (no clean) +# bash bm/bench.sh SCCACHE=0 # cold, without sccache +# bash bm/bench.sh SKIP_NATIVE=1 # cold, Dart only +# +# Output: bm/results/.csv (one file per machine, all runs appended) +# ============================================================================== +set -euo pipefail + +HOST="$(hostname -s 2>/dev/null || echo unknown)" +OUTDIR="bm/results" +mkdir -p "$OUTDIR" +OUTFILE="${OUTDIR}/${HOST}.csv" + +WARM=0 +LABEL="" +MAKE_FLAGS="" + +# Parse args +while [ $# -gt 0 ]; do + case "$1" in + --warm) WARM=1; shift ;; + --label) LABEL="$2"; shift 2 ;; + *) MAKE_FLAGS="${MAKE_FLAGS:+${MAKE_FLAGS} }$1"; shift ;; + esac +done + +# Detect platform +case "$(uname -s)" in + Darwin) BUILD_TARGET="build-macos" ;; + Linux) BUILD_TARGET="build-linux" ;; + MINGW*|MSYS*|CYGWIN*) + echo "Git Bash on Windows detected. Benchmarking requires WSL2:" + echo " wsl bash bm/bench.sh" + exit 1 + ;; + *) echo "Unknown platform: $(uname -s)"; exit 1 ;; +esac + +# Git info +COMMIT="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)" +BRANCH="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)" + +# Auto-generate label only if not explicitly set +if [ -z "$LABEL" ]; then + LABEL=$([ $WARM -eq 1 ] && echo "warm" || echo "cold") + if echo "$MAKE_FLAGS" | grep -q "SCCACHE=0"; then + LABEL="${LABEL}-no-sccache" + elif echo "$MAKE_FLAGS" | grep -q "SCCACHE=1"; then + LABEL="${LABEL}-sccache" + fi + if echo "$MAKE_FLAGS" | grep -q "SKIP_NATIVE=1"; then + LABEL="${LABEL}-skip-native" + fi +fi + +DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +ARCH="$(uname -m)" +OS_NAME="$(uname -s)" +OS_VER="$(uname -r)" +echo "Benchmark: ${LABEL}" | toilet -f term --metal +echo "Host: $HOST" +echo "OS: $OS_NAME $OS_VER ($ARCH)" +echo "Branch: $BRANCH" +echo "Commit: $COMMIT" +echo "Target: ${BUILD_TARGET}" +echo "Flags: ${MAKE_FLAGS:-(none)}" +echo "" + +# Disk before +DISK_BEFORE=$(du -sk . 2>/dev/null | cut -f1) + +# Clean unless warm +if [ $WARM -eq 0 ]; then + echo "Cleaning" | toilet -f term --metal + make clean 2>&1 | tail -1 +fi + +# Build +echo "Building: make ${BUILD_TARGET} ${MAKE_FLAGS} " | toilet -f term --metal +START=$(date +%s) +make ${BUILD_TARGET} ${MAKE_FLAGS} 2>&1 | tail -5 +RC=$? +END=$(date +%s) +WALL=$((END - START)) + +# Disk after +DISK_AFTER=$(du -sk . 2>/dev/null | cut -f1) +DISK_DELTA=$((DISK_AFTER - DISK_BEFORE)) + +# Write CSV header if new file +if [ ! -f "$OUTFILE" ]; then + echo "label,branch,commit,host,arch,os_name,os_ver,date,warm,flags,wall_sec,success,disk_total_kb,disk_delta_kb,comment" > "$OUTFILE" +fi + +echo "${LABEL},${BRANCH},${COMMIT},${HOST},${ARCH},${OS_NAME},${OS_VER},${DATE},${WARM},${MAKE_FLAGS:--},${WALL},$((RC == 0 ? 1 : 0)),${DISK_AFTER},${DISK_DELTA}," >> "$OUTFILE" + +echo "" +if [ $RC -eq 0 ]; then + MIN=$((WALL/60)); SEC=$((WALL%60)) + echo "✓ Build succeeded in ${WALL}s \(${MIN}m ${SEC}s\)" +else + echo "✗ Build FAILED after ${WALL}s" +fi +echo "Results appended: $OUTFILE" | toilet -f term --metal + +# Show all runs +echo "" +echo "=== All results for $HOST ($ARCH $OS_NAME $OS_VER) ===" +printf "%-12s %-20s %-8s %-10s %4s %10s %8s %s\n" DATE MODE COMMIT FLAGS WARM WALL DISK COMMENT +printf '%s\n' '──────────────────────────────────────────────────────────────────────────────────────' +tail -n +2 "$OUTFILE" | while IFS=, read -r label branch commit host arch os_name os_ver date warm flags wall_sec success disk_total disk_delta comment; do + delta_mb=$((disk_delta / 1024)) + w=$((wall_sec)); m=$((w/60)); s=$((w%60)) + time_fmt="${m}m${s}s" + warm_label=$([ "$warm" = "1" ] && echo "yes" || echo "no") + [ "$success" = "1" ] && ok="✓" || ok="✗" + printf "%-12s %-20s %-8s %-10s %-4s %10s %8s %s\n" "${date:0:10}" "$label" "${commit:0:7}" "${flags:--}" "$warm_label" "$time_fmt" "$ok ${delta_mb}MB" "$comment" +done diff --git a/bm/collect.sh b/bm/collect.sh new file mode 100755 index 0000000000..7dfdba73e6 --- /dev/null +++ b/bm/collect.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +# ============================================================================== +# collect.sh: Measure disk usage and artifact sizes independent of benchmarks +# Usage: ./bm/collect.sh [--outdir DIR] [--baseline NAME] +# +# Outputs a CSV with per-directory and per-artifact sizes. +# ============================================================================== +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" + +# The active benchmark path is bench.sh -> compare.py -> render.sh. Keep this +# collector self-contained so it can snapshot the native-assets layout without +# relying on the retired targets.sh configuration. +BUILD_DIRS=( + .dart_tool + build + .pub-cache + .cargo-target + .sccache-cache +) +ARTIFACT_DIRS=( + build/macos/Build/Products/Release + build/linux/x64/release/bundle + build/windows/x64/runner/Release + build/app/outputs/flutter-apk +) + +detect_platform() { + case "$(uname -s)" in + Darwin) echo "macos" ;; + Linux) echo "linux" ;; + MINGW*|MSYS*|CYGWIN*) echo "windows" ;; + *) echo "unknown" ;; + esac +} + +OUTDIR="${BM_OUTDIR:-$REPO_ROOT/bm/results}" +BASELINE="${BM_BASELINE:-current}" +TIMESTAMP="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" +PLATFORM="$(detect_platform)" +HOSTNAME="$(hostname -s 2>/dev/null || echo "unknown")" + +main() { + while [ $# -gt 0 ]; do + case "$1" in + --outdir) OUTDIR="$2"; shift ;; + --baseline) BASELINE="$2"; shift ;; + *) echo "Unknown: $1"; exit 1 ;; + esac + shift + done + + mkdir -p "$OUTDIR" + local csv="$OUTDIR/sizes_${BASELINE}.csv" + + echo "=== Collecting sizes ($BASELINE, $PLATFORM, $TIMESTAMP) ===" >&2 + + # Header + { + printf "baseline,platform,hostname,date,metric,value_kb,note\n" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},git_commit,$(git -C "$REPO_ROOT" rev-parse HEAD 2>/dev/null || echo unknown)," + } > "$csv" + + # Disk directories + for d in "${BUILD_DIRS[@]}"; do + local path="$REPO_ROOT/$d" + local label="disk_$(echo "$d" | tr '/.' '_')" + if [ -d "$path" ] || [ -f "$path" ]; then + local sz + sz="$(du -sk "$path" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},${sz}," >> "$csv" + else + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},0,missing" >> "$csv" + fi + done + + # Artifacts + for a in "${ARTIFACT_DIRS[@]}"; do + local path="$REPO_ROOT/$a" + local label="artifact_$(echo "$a" | tr '/.-' '_')" + if [ -e "$path" ]; then + local sz + sz="$(du -sk "$path" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},${sz}," >> "$csv" + else + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},0,missing" >> "$csv" + fi + done + + # Total project + local total + total="$(du -sk "$REPO_ROOT" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},total_project,${total}," >> "$csv" + + # Native-assets Rust target directories aggregate. Flutter's hooks keep + # these under .dart_tool instead of the deleted crypto_plugins tree. + local rust_total=0 + while IFS= read -r target_dir; do + local sz + sz="$(du -sk "$target_dir" 2>/dev/null | cut -f1 || echo 0)" + rust_total=$((rust_total + sz)) + done < <(find "$REPO_ROOT/.dart_tool/hooks_runner/shared" \ + -type d -path '*/build/*/target' 2>/dev/null) + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},rust_targets_aggregate,${rust_total}," >> "$csv" + + # Toolchain sizes + for tc_dir in .rustup-home .cargo-home; do + if [ -d "$REPO_ROOT/$tc_dir" ]; then + local tc_label="toolchain_${tc_dir#.}" + local tc_sz + tc_sz="$(du -sk "$REPO_ROOT/$tc_dir" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${tc_label},${tc_sz},installed_toolchains" >> "$csv" + + # Breakdown: list each toolchain + if [ "$tc_dir" = ".rustup-home" ] && [ -d "$REPO_ROOT/$tc_dir/toolchains" ]; then + for tc in "$REPO_ROOT/$tc_dir/toolchains"/*/; do + local tc_name + tc_name="$(basename "$tc")" + local tc_sz + tc_sz="$(du -sk "$tc" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},rustup_toolchain_${tc_name},${tc_sz},installed" >> "$csv" + done + fi + fi + done + + echo "--- Sizes written to $csv ---" >&2 +} + +main "$@" diff --git a/bm/compare.py b/bm/compare.py new file mode 100644 index 0000000000..c656f5e645 --- /dev/null +++ b/bm/compare.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +""" +compare.py: Render benchmark results from bm/results/.csv files. + +Usage: + python3 bm/compare.py bm/results/ # terminal report + python3 bm/compare.py bm/results/ > report.md # markdown for bm/render.sh +""" + +import csv, sys, os, json +from collections import defaultdict +from pathlib import Path +from statistics import mean, stdev, median + +PIPE = "│" + +def load_results(results_dir): + rows = [] + for fpath in sorted(Path(results_dir).glob("*.csv")): + if fpath.name.startswith("sizes_"): + continue + try: + with open(fpath) as f: + reader = csv.DictReader(f) + for r in reader: + if r.get("success","0") in ("1", "True"): + rows.append(r) + except Exception as e: + print(f" skip {fpath.name}: {e}", file=sys.stderr) + return rows + + + +def wall_fmt(s): + """Format seconds to human readable.""" + try: + s = int(float(s)) + m, sec = divmod(s, 60) + if m >= 60: + h, m = divmod(m, 60) + return f"{h}h{m:02d}m{sec:02d}s" + return f"{m}m{sec:02d}s" + except: + return str(s) + +def wall_s(s): + """Parse string to int seconds.""" + try: return int(float(s)) + except: return 0 + +def mb(kb_str): + try: return int(float(kb_str)) // 1024 + except: return 0 + +def hr_label(label): + """Human readable label.""" + l = label.lower() + if l == "cold": return "Cold build" + if l == "warm": return "Warm rebuild" + if l == "cold-nosccache": return "Cold (no sccache)" + if l == "cold-sccache": return "Cold (sccache)" + if l == "cold-dart-only": return "Cold (Dart only)" + if l == "warm-nosccache": return "Warm (no sccache)" + if l == "warm-sccache": return "Warm (sccache)" + if l == "warm-dart-only": return "Warm (Dart only)" + if "skip-native" in l: return "Dart only" + return label + +def render(rows, fmt="terminal"): + if not rows: + print("No successful benchmark results found.", file=sys.stderr) + return + + # Group by host then label + by_host = defaultdict(list) + for r in rows: + by_host[r.get("host","unknown")].append(r) + + hdr = ["Date", "Mode", "Commit", "Arch", "OS", "Warm", "Flags", "Wall Time", "Disk Δ", "Comment"] + + for host, host_rows in sorted(by_host.items()): + if fmt == "markdown": + print(f"\n## {host}\n") + else: + print(f"\n{'═'*80}") + print(f" {host}") + print(f"{'═'*80}") + + # Sort: cold first, then by label + host_rows.sort(key=lambda r: (r.get("warm","0"), r.get("label",""))) + + if fmt == "markdown": + print(f"| {' | '.join(hdr)} |") + # Right-align Wall Time column (index 7) for easier comparison + aligns = [":---" if h not in ("Wall Time", "Disk Δ") else "---:" for h in hdr] + print(f"|{'|'.join(aligns)}|") + else: + # Terminal table with rich/box drawing + widths = [max(len(h), 18) for h in hdr] + # Print header + print(PIPE + PIPE.join(h.center(w) for h,w in zip(hdr,widths)) + PIPE) + print(PIPE + PIPE.join("─"*w for w in widths) + PIPE) + + for r in host_rows: + date = (r.get("date","")[:10]).strip() + label = hr_label(r.get("label","")) + commit = r.get("commit","")[:7] + arch = r.get("arch","") + os_str = f"{r.get('os_name','')} {r.get('os_ver','')}" + warm = "yes" if r.get("warm","0") == "1" else "no" + flags = r.get("flags","-").replace("SCCACHE=1,","").replace("SCCACHE=0,","") or "-" + wall = wall_fmt(r.get("wall_sec","")) + disk = f"{mb(r.get('disk_delta_kb',''))}MB" + comment = r.get("comment","") or "" + + cols = [date, label, commit, arch, os_str, warm, flags, wall, disk, comment] + + if fmt == "markdown": + print(f"| {' | '.join(cols)} |") + else: + print(PIPE + PIPE.join(c.center(w) for c,w in zip(cols,widths)) + PIPE) + +def compare(dir1, dir2=None): + """Compare two result directories.""" + rows1 = load_results(dir1) + rows2 = load_results(dir2) if dir2 else [] + all_rows = rows1 + rows2 + + if not all_rows: + print("No benchmark results found.", file=sys.stderr) + return + + # Mark format based on output + is_pipe = not sys.stdout.isatty() + fmt = "markdown" if is_pipe else "terminal" + + render(all_rows, fmt) + + if dir2 and rows1 and rows2: + print(f"\n{'═'*80}") + print(f" Delta: {os.path.basename(dir1)} → {os.path.basename(dir2)}") + print(f"{'═'*80}") + labels1 = {r["label"] for r in rows1} + labels2 = {r["label"] for r in rows2} + for label in sorted(labels1 & labels2): + t1 = wall_s(rows1[0]["wall_sec"]) + t2 = wall_s(rows2[0]["wall_sec"]) + delta = t2 - t1 + pct = (delta/t1)*100 if t1 else 0 + sign = "+" if delta > 0 else "" + print(f" {hr_label(label):25s} {wall_fmt(t1)} → {wall_fmt(t2)} ({sign}{pct:.0f}%)") + + +if __name__ == "__main__": + if len(sys.argv) < 2: + print(f"Usage: {sys.argv[0]} [compare_dir]", file=sys.stderr) + print(f" {sys.argv[0]} bm/results/ # single report", file=sys.stderr) + print(f" {sys.argv[0]} old/ new/ # compare two dirs", file=sys.stderr) + print(f" {sys.argv[0]} bm/results/ > report.md # markdown for PDF", file=sys.stderr) + sys.exit(1) + + compare(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None) diff --git a/bm/render.sh b/bm/render.sh new file mode 100755 index 0000000000..b27d83256f --- /dev/null +++ b/bm/render.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# render.sh: Convert benchmark markdown report to HTML + PDF +# Usage: +# ./bm/compare.py bm/results/ > report.md +# ./bm/render.sh report.md [--open] +set -euo pipefail + +MD_FILE="${1:-}" +if [ -z "$MD_FILE" ] || [ ! -f "$MD_FILE" ]; then + echo "Usage: ./bm/render.sh [--open]" + exit 1 +fi + +OPEN=0 +[ "${2:-}" = "--open" ] && OPEN=1 + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +BASE="${MD_FILE%.md}" +HTML_FILE="${BASE}.html" +PDF_FILE="${BASE}.pdf" +CSS_FILE="$SCRIPT_DIR/report.css" + +# Convert to HTML +echo "=== Markdown → HTML ===" +{ + echo '' +} > /tmp/_bm_css.html + +pandoc "$MD_FILE" \ + --standalone \ + --metadata title="Stack Wallet: Build Benchmark Report" \ + --include-in-header /tmp/_bm_css.html \ + -o "$HTML_FILE" +rm -f /tmp/_bm_css.html +echo " → $HTML_FILE" + +# Convert to PDF +echo "=== HTML → PDF ===" +pdf_ok=0 + +if command -v weasyprint >/dev/null 2>&1; then + weasyprint "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 +elif pip3 install --break-system-packages weasyprint 2>/dev/null; then + weasyprint "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 +elif command -v wkhtmltopdf >/dev/null 2>&1; then + wkhtmltopdf --enable-local-file-access "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 +elif [ "$(uname -s)" = "Darwin" ]; then + cupsfilter "$HTML_FILE" > "$PDF_FILE" 2>/dev/null && pdf_ok=1 || true +fi + +if [ "$pdf_ok" -eq 1 ] && [ -f "$PDF_FILE" ]; then + echo " → $PDF_FILE" +else + echo " ⚠ No PDF engine found. HTML ready: $HTML_FILE" +fi + +[ "$OPEN" -eq 1 ] && open "$PDF_FILE" 2>/dev/null || open "$HTML_FILE" 2>/dev/null || true + +echo "Done." \ No newline at end of file diff --git a/bm/report.css b/bm/report.css new file mode 100644 index 0000000000..5e26a58650 --- /dev/null +++ b/bm/report.css @@ -0,0 +1,132 @@ +/* Stack Wallet Build Benchmark Report: Professional stylesheet */ +@page { + size: A4 landscape; + margin: 1.5cm 1.8cm; + @bottom-center { + content: "Page " counter(page) " of " counter(pages); + font-size: 7pt; + color: #888; + } +} + +body { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 10pt; + line-height: 1.55; + color: #222; + max-width: 100%; +} + +h1 { + font-size: 20pt; + font-weight: 700; + color: #1a1a1a; + border-bottom: 3px solid #2563eb; + padding-bottom: 8px; + margin-top: 0; + margin-bottom: 6px; +} + +h2 { + font-size: 13pt; + font-weight: 600; + color: #1a1a1a; + border-bottom: 1px solid #ccc; + padding-bottom: 4px; + margin-top: 28px; + margin-bottom: 10px; + page-break-after: avoid; +} + +h3 { + font-size: 11pt; + font-weight: 600; + margin-top: 16px; + margin-bottom: 6px; +} + +p { + margin: 4px 0 8px 0; +} + +table { + border-collapse: collapse; + width: 100%; + margin: 10px 0 16px 0; + font-size: 9pt; + page-break-inside: avoid; +} + +thead { + display: table-header-group; +} + +th { + background: #2563eb; + color: white; + font-weight: 600; + padding: 4px 6px; + text-align: left; + font-size: 7pt; + text-transform: uppercase; + letter-spacing: 0.2px; +} + +td { + border: 1px solid #ccc; + padding: 3px 6px; + text-align: left; + font-family: "SF Mono", "Menlo", "Monaco", "Cascadia Code", monospace; + font-size: 7.5pt; +} + +tr:nth-child(even) td { + background: #f8f9fb; +} + +code { + background: #f0f0f0; + padding: 1px 4px; + border-radius: 3px; + font-family: "SF Mono", "Menlo", "Monaco", monospace; + font-size: 8.5pt; +} + +strong { + color: #111; +} + +a { + color: #2563eb; + text-decoration: none; +} + +/* Improvement column - colored */ +td:last-child { + font-weight: 600; +} + +/* Phase breakdown table: alternating header */ +table:last-of-type th { + background: #1e293b; +} + +/* Key findings list spacing */ +h2 + ul li, h2 + p + ul li { + margin-bottom: 4px; +} + +/* First page has no header */ +@page :first { + margin-top: 2.5cm; +} + +/* Cover / header block */ +.report-meta { + background: #f8f9fb; + border-left: 4px solid #2563eb; + padding: 12px 16px; + margin: 16px 0; + font-size: 9pt; + border-radius: 2px; +} diff --git a/bm/run_all.sh b/bm/run_all.sh new file mode 100755 index 0000000000..5182705e71 --- /dev/null +++ b/bm/run_all.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# ============================================================================== +# run_all.sh: Cold → warm pairs, ordered from simplest to most optimized. +# +# Run order: +# A. Cold no-sccache → clean + build without sccache (baseline) +# B. Warm no-sccache → rebuild after A (CARGO_TARGET_DIR benefit only) +# C. Cold sccache → clean + build with sccache +# D. Warm sccache → rebuild after C (sccache + CARGO_TARGET_DIR benefit) +# E. Cold Dart-only → clean + SKIP_NATIVE=1 (no Rust at all) +# F. Warm Dart-only → rebuild after E (Flutter incremental) +# ============================================================================== +set -euo pipefail + +HOST="$(hostname -s 2>/dev/null || echo unknown)" +figlet "Stack Wallet" + +echo " Full Benchmark Suite" +echo " Host: $HOST " +echo " $(date)" +echo "" + +echo "Cold build (no sccache)" | toilet -f term -F border --gay +make clean 2>/dev/null || true +bash bm/bench.sh --label cold-nosccache SCCACHE=0 +echo "" + +echo "Warm after cold no-sccache (CARGO_TARGET_DIR only)" | toilet -f term -F border --gay +echo "━━━ B: Warm rebuild (no sccache, CARGO_TARGET_DIR cache hit) ━━━" +bash bm/bench.sh --warm --label warm-nosccache SCCACHE=0 +echo "" + +echo "Cold with sccache" | toilet -f term -F border --gay +make clean 2>/dev/null || true +bash bm/bench.sh --label cold-sccache SCCACHE=1 +echo "" + +echo "Warm after cold sccache (sccache + target dir)" | toilet -f term -F border --gay +echo "━━━ D: Warm rebuild (sccache + CARGO_TARGET_DIR cache hit) ━━━" +bash bm/bench.sh --warm --label warm-sccache SCCACHE=1 +echo "" + +echo "Cold build (Dart only, SKIP_NATIVE=1)" | toilet -f term -F border --gay +make clean 2>/dev/null || true +bash bm/bench.sh --label cold-dart-only SKIP_NATIVE=1 +echo "" + +echo "Warm Dart-only" | toilet -f term -F border --gay +bash bm/bench.sh --warm --label warm-dart-only SKIP_NATIVE=1 +echo "" + +echo "════════════════════════════════════════════════════" +echo " Done. Results: bm/results/$HOST.csv" +echo " View: python3 bm/compare.py bm/results/" +echo " PDF: python3 bm/compare.py bm/results/ > report.md && ./bm/render.sh report.md" +echo "════════════════════════════════════════════════════" From c54a76741f3ee12660bce39479798195201be913 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:17:31 +0200 Subject: [PATCH 091/107] Record verified Option B blocker: go_1_24 absent from pinned nixpkgs rev - nix eval on rev b1b87598: go_1_24 MISSING; go_1_23/1_25 removed (EOL); only go_1_26=1.26.7; bare pkgs.go=1.26.7 (already drifts from BOM 1.24.13). - B1-Go needs a nixpkgs-rev change + mandatory build gate; cannot ship a partial flake edit here without silently changing the dnix toolchain. - Option B stays planned/EDITED-UNPROVEN until done on a full nix-env host. --- PR-1482-optionB-flake-bom-consolidation.md | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/PR-1482-optionB-flake-bom-consolidation.md b/PR-1482-optionB-flake-bom-consolidation.md index c414eb33d7..8487c160d7 100644 --- a/PR-1482-optionB-flake-bom-consolidation.md +++ b/PR-1482-optionB-flake-bom-consolidation.md @@ -99,6 +99,32 @@ documented and build-verified. - **Cannot self-verify here** — no Flutter in the Nix shell on this host; the author must run the builds on a machine with the full nix env. +## Verified finding (2026-11-20) — B1-Go is NOT viable on the current rev + +Resolved the pinned nixpkgs rev `b1b875982b17dabde9b4a37f3e229e74913e6db3` +directly with `nix eval`: + +- `pkgs.go_1_24` → **MISSING** (the selector does not exist in this rev). +- `pkgs.go_1_25`, `pkgs.go_1_23` → **removed** (Go 1.23/1.25 are end-of-life in + this rev). +- `pkgs.go_1_26` → `1.26.7` (the only `go_1_*` selector present). +- bare `pkgs.go` → **`1.26.7`** — already drifts from the BOM's `1.24.13`. + +So B1-Go (`go` → `go_1_24`) **cannot** be applied without first moving the +nixpkgs rev to one that still ships `go_1_24`. And bare `pkgs.go` is already at +1.26.7, not the BOM's 1.24.13 — meaning the Nix shell's Go has been drifting +from the BOM all along, on the prebuilt-independent source path. + +Implication: **Option B now requires a nixpkgs-rev change** (to a rev that ships +both `go_1_24` and the exact Flutter 3.47.2), plus the mandatory +`make build-macos` / `make build-linux` verification that dnix still +reproduces byte-for-byte. That verification cannot be run on this host (no +Flutter in the Nix shell), so Option B stays **planned / EDITED-UNPROVEN** until +done on a full nix-env machine. Do NOT ship a partial flake edit here: a +half-consolidated flake that pins Go to a selector absent from the rev, or +changes the bare `pkgs.go` without a build gate, would silently change the +toolchain dnix verifies against. + ## What is NOT in scope - Homebrew installer Go version: it runs `brew install go` with no version pin. From 3121c46df1041fc444525c57bfef72bdd732a87a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:34:29 +0200 Subject: [PATCH 092/107] Correct Option B blocker: exact-fetch (no rev change) is the fix My earlier 'blocked on a nixpkgs-rev change' was wrong. The Dockerfile (Option A) already pins exact Go/Flutter from the BOM by fetching from go.dev + cloning the flutter git tag, with no nixpkgs selectors. The flake fix is the same pattern (fetch exact versions), not a rev bump. The real blocker is only the mandatory build-gate verification, which this host cannot run (no Flutter in the Nix shell). --- PR-1482-optionB-flake-bom-consolidation.md | 42 ++++++++++++++++------ 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/PR-1482-optionB-flake-bom-consolidation.md b/PR-1482-optionB-flake-bom-consolidation.md index 8487c160d7..a04023ea90 100644 --- a/PR-1482-optionB-flake-bom-consolidation.md +++ b/PR-1482-optionB-flake-bom-consolidation.md @@ -99,7 +99,7 @@ documented and build-verified. - **Cannot self-verify here** — no Flutter in the Nix shell on this host; the author must run the builds on a machine with the full nix env. -## Verified finding (2026-11-20) — B1-Go is NOT viable on the current rev +## Verified finding (2026-11-20) — nixpkgs `go_1_24` selector is gone; exact-fetch is the fix (CORRECTED) Resolved the pinned nixpkgs rev `b1b875982b17dabde9b4a37f3e229e74913e6db3` directly with `nix eval`: @@ -115,15 +115,37 @@ nixpkgs rev to one that still ships `go_1_24`. And bare `pkgs.go` is already at 1.26.7, not the BOM's 1.24.13 — meaning the Nix shell's Go has been drifting from the BOM all along, on the prebuilt-independent source path. -Implication: **Option B now requires a nixpkgs-rev change** (to a rev that ships -both `go_1_24` and the exact Flutter 3.47.2), plus the mandatory -`make build-macos` / `make build-linux` verification that dnix still -reproduces byte-for-byte. That verification cannot be run on this host (no -Flutter in the Nix shell), so Option B stays **planned / EDITED-UNPROVEN** until -done on a full nix-env machine. Do NOT ship a partial flake edit here: a -half-consolidated flake that pins Go to a selector absent from the rev, or -changes the bare `pkgs.go` without a build gate, would silently change the -toolchain dnix verifies against. +**CORRECTION (2026-11-20, the "nixpkgs-rev change" framing is WRONG):** the +implication above was wrong. A nixpkgs-rev change is **not** required. The +Dockerfile (Option A, committed) already reads Flutter/Go from the BOM and pins +**exact** versions with **no nixpkgs involvement** — `Dockerfile:87-103` and +`:182-198`: + +```dockerfile +GO_VERSION="$(... bom_values.sh --get go)" # 1.24.13 +curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" +FLUTTER_VERSION="$(... bom_values.sh --get flutter)" # 3.47.2 +git clone --depth 1 --branch "$FLUTTER_VERSION" https://github.com/flutter/flutter.git +``` + +So the exact-version fetch pattern is **already proven in this repo**. The +`go_1_24` selector being gone from this rev is irrelevant — the fix does not use +nixpkgs selectors at all. The two viable approaches (both keep the current rev): + +1. **Go:** replace bare `go` in `flake.nix` with a small nix derivation that + fetches `https://go.dev/dl/go1.24.13.linux-amd64.tar.gz` / `-darwin.tar.gz` + at the BOM's `go` value (mirrors the Dockerfile). No rev change. +2. **Flutter:** either fetch the `flutter@3.47.2` git tag directly (like the + Dockerfile) or pin the nixpkgs `flutter` derivation's `version`/`src` to the + BOM value. No rev change. + +What is still true: the **build-gate verification** (`make build-macos` / +`make build-linux`, confirming dnix still reproduces byte-for-byte after the +Flutter change) cannot run on this host (no Flutter in the Nix shell), so the +flake edit stays **planned / EDITED-UNPROVEN** until done on a full nix-env +machine. But the blocker is *verification*, **not** a rev change. Do NOT ship a +partial flake edit here without the build gate — changing bare `pkgs.go`/ +`pkgs.flutter` silently changes the toolchain dnix verifies against. ## What is NOT in scope From e592f3eb59f4189475b524e9a110f16ab5e15aa8 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:26:48 +0200 Subject: [PATCH 093/107] build.yaml: guard CHANGE_NOW decode + add build-windows permissions Adversarial-audit fix. All 15 'Decode secrets' steps decoded ${{ secrets.CHANGE_NOW }} with a bare 'echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart'. When the secret is unset (fork dispatch, or a repo without the secret) that writes an EMPTY external_api_keys.dart missing the Dart API-key constants, breaking the downstream flutter build. Mirror the already-correct test.yaml pattern: guard on a non-empty secret and fall back to a stub file of empty-string constants. Also add the contents:read / packages:read permissions block to build-windows for parity with the other build jobs (it previously relied on the implicit default). --- .github/workflows/build.yaml | 348 +++++++++++++++++++++++++++++++++-- 1 file changed, 333 insertions(+), 15 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 1a1db28c32..b9d668bb5c 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -139,7 +139,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Build env: @@ -209,7 +230,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Set up Android local.properties run: | @@ -267,6 +309,9 @@ jobs: build-windows: needs: bom runs-on: windows-2022 + permissions: + contents: read + packages: read defaults: run: shell: bash @@ -327,7 +372,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Build run: flutter build windows --release @@ -398,7 +464,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Build run: flutter build macos --release @@ -469,7 +556,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Build run: flutter build ios --release --no-codesign @@ -533,7 +641,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Build env: @@ -603,7 +732,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Build env: @@ -790,7 +940,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Set up Android local.properties run: | @@ -906,7 +1077,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Build run: flutter build windows --release @@ -977,7 +1169,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Build run: flutter build macos --release @@ -1048,7 +1261,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Build run: flutter build ios --release --no-codesign @@ -1229,7 +1463,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Set up Android local.properties run: | @@ -1345,7 +1600,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Build run: flutter build windows --release @@ -1416,7 +1692,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Build run: flutter build macos --release @@ -1487,7 +1784,28 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -n "$CHANGE_NOW" ]; then + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + else + cat > lib/external_api_keys.dart << 'EOF' + const String kChangeNowApiKey = ""; + const String kSimpleSwapApiKey = ""; + const String kNanswapApiKey = ""; + const String kNanoSwapRpcApiKey = ""; + const String kWizSwapApiKey = ""; + const kShopInBitAccessKey = ""; + const kShopInBitPartnerSecret = ""; + const kCakePayApiToken = ""; + const kExolixApiKey = ""; + const kLetsExchangeId = ""; + const kLetsExchangeToken = ""; + const kCypherGoatApiKey = ""; + const kCypherGoatAffiliate = ""; + const kTrocadorApiKey = ""; + const kTrocadorRefCode = ""; + EOF + fi - name: Build run: flutter build ios --release --no-codesign From 9ba4e104c78a7acec688dab8515935d4e7ff8651 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:08:05 +0200 Subject: [PATCH 094/107] Add round-2 audit report: CI intel, build-pipeline security, dnix integrity, Dart logic Follows round-1 audits A-F with new angles: our own CI surface, pipeline security, native-lib integrity, and Dart logic in the changed files. Verdict: no new merge blockers. Changed Dart code is correct and fail-closed (dart analyze clean; verify_bom.dart compiles standalone). CI: test.yaml runs the full Dart suite + flutter test only on pull_request, not on push to staging (coverage gap, maintainer decision). Makefile (the PR's deliverable) is not exercised by automated CI (make-smoke is manual). Security-reviewer's two headline claims (CHANGE_NOW 'BLOCKER', dnix.lock 'missing') are both false positives; verified against ground truth. dnix uses distributed per-plugin lockfiles; pubspec.lock (committed) pins all 4 native libs by git revision. --- PR-1482-audit-round2-ci-and-security.md | 96 +++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 PR-1482-audit-round2-ci-and-security.md diff --git a/PR-1482-audit-round2-ci-and-security.md b/PR-1482-audit-round2-ci-and-security.md new file mode 100644 index 0000000000..755bfcaea6 --- /dev/null +++ b/PR-1482-audit-round2-ci-and-security.md @@ -0,0 +1,96 @@ +# PR #1482 — Audit Round 2: CI Intel + Security + Native Integrity + Dart Logic + +Prepared 2026-11-20. Follows the first-round audits (A–F: Makefile, bootstrap, docs, CI, bm harness, BOM). +New angles: our own CI surface, build-pipeline security, dnix prebuilt integrity, Dart logic in the changed files. + +Every BLOCKER/MAJOR claim from a subagent was re-checked against ground truth. Subagent findings are leads, not truth. + +## Verdict +**No new merge blockers.** The PR's changed Dart code is correct and fail-closed (`dart analyze` clean; `verify_bom.dart` compiles standalone; logic reviewed line-by-line). The security-reviewer's two headline claims (CHANGE_NOW "BLOCKER", dnix.lock "missing") are both false positives. The one genuine, maintainer-facing item is a **coverage gap** (tests run only on PR, not on push to staging) plus the architectural note that the Makefile is not exercised by automated CI. + +--- + +## 1. CI Intel (our own workflows) + +### Trigger matrix +| Workflow | Triggers | Tests run? | +|---|---|---| +| `build.yaml` | push (tags `v*.*.*`, branch `staging`) + workflow_dispatch | No — builds only | +| `test.yaml` | **`pull_request` only** | **Yes** — 11 `dart scripts/tests/*` + `flutter test --coverage` + `make-check` dry-run matrix | +| `make-smoke.yaml` | workflow_dispatch only (manual) | No — `make build-linux` smoke | +| `build-ci-image.yaml` | push (main/staging) + workflow_dispatch | N/A — builds the CI image | +| `release-mwebd-windows.yaml` | workflow_dispatch only | No | + +### Image tags are correct (not a divergence) +`build-ci-image.yaml` builds three distinct Dockerfile targets and pushes distinct tags: +- `:latest` = `full` target (used by build.yaml build jobs + make-smoke) +- `:test` = `test` target (used by test.yaml) +- `:android` = `android` target + +test.yaml using `:test` while build.yaml uses `:latest` is intentional multi-target, not drift. + +### Genuine findings +- **MAJOR (coverage):** `test.yaml` fires on `pull_request` only. `build.yaml` fires on `push: branches: [staging]`. So **direct commits to staging bypass the entire Dart test suite + `flutter test` + make-check.** If staging accepts direct pushes, that is a real gap. Fix options: add `push: branches: staging` to `test.yaml`, or rely on repo branch protection requiring the PR check. Maintainer decision. +- **MAJOR (architectural):** the Makefile — the PR's central deliverable — is never exercised by automated CI. All 19 build.yaml jobs call `./build_app.sh -d` then `flutter build` directly; none run `make`. `make-smoke.yaml` (the only thing that runs `make build-linux`) is manual `workflow_dispatch` only. So the make path has no automated gate. +- **MINOR:** no static analysis in CI (`flutter analyze` is commented out in test.yaml). +- No in-YAML merge-gate; relies on repo branch protection (repo-side config, not YAML-fixable). + +### False positives from the CI scout (verified NOT defects) +- "Android signing secrets required, no fallback" — by design; a release APK must be signed. +- "bom job is a single point of failure" — that is how a shared config gate is meant to work; fail-fast on invalid BOM is correct. +- "verify-toolchain missing from non-linux / Windows jobs" — those are prebuilt (`build_app.sh -d`) jobs; they don't run make and don't need host Rust. (Same false positive as round-1 Audit D.) +- "CHANGE_NOW if set-but-empty overwrites with empty content" — wrong; `[ -n "" ]` is false, so an empty secret correctly uses the stub. + +--- + +## 2. Build-pipeline security (security-reviewer) + +### False positives (verified NOT blockers) +- **"CHANGE_NOW decoded to `lib/external_api_keys.dart` — BLOCKER"** — No. That file is a generated, gitignored artifact (the empty-stub fallback proves it is never committed). The decoded secret lives only in the ephemeral CI container workspace and is compiled into the release binary (embedding the ChangeNow API key in the app is the app's normal design). GitHub masks `${{ secrets.X }}` in logs. Standard pattern. +- **"dnix.lock missing from repo — MAJOR"** — No. dnix uses **distributed per-plugin lockfiles** (each plugin's `dnix.json`/`dnix.lock` lives in its own repo, fetched at build). `pubspec.lock` (committed) pins all 4 native libs — `flutter_libepiccash`, `flutter_libmwc`, `frostdart`, `tor_ffi_plugin` — by git URL + revision. The security-reviewer searched only the repo root and concluded "missing." + +### Real / acceptable +- **install_nix.sh `curl https://nixos.org/nix/install | sh` without checksum — acceptable (NIT).** This is the official, documented Nix install method; a hardcoded checksum would need Nix's rotating published hash. Consistent with how every Nix user installs. +- **No app-level secondary check if dnix's upstream hash verification were compromised — by design (the locked dnix-hash-only decision).** Not a code defect. `check_native_overrides.dart` provides defense-in-depth (exit 1 if `.dnix-build` overrides present). +- BOM parser / `bom_values.sh` / install scripts are well-guarded: version-format validation, duplicate-section rejection, path quoting, fail-closed on malformed input. + +--- + +## 3. Native-dependency / dnix integrity (scout) + +- The `-d` hash check is **mandatory at the dnix level** (dnix build hooks verify each downloaded lib against its `dnix.lock` release hash); `build_app.sh -d` delegates to dnix rather than re-implementing it. +- `pubspec.lock` is committed and pins all 4 native libs by git revision. +- **MAJOR (architectural note, pre-existing, not a PR regression):** `stack-bom.toml` pins toolchains but does not pin the 4 native-lib versions/hashes, and there is no guard cross-validating that a BOM toolchain upgrade is compatible with the pinned native-lib git revisions. The PR diff does **not** touch `pubspec.lock`/`pubspec.yaml`, so this is a pre-existing property, not introduced or regressed by #1482. + +--- + +## 4. Dart logic in the changed files (main-agent review) + +All 4 changed Dart files are **new** (934 insertions, 0 deletions) — no regression risk in existing code. + +- `tool/bom_parser.dart` — `readBom` fails closed (unterminated string → `FormatException`), strips trailing comments only on bare values, handles CRLF in `lockRefs`, correct PATH-list-separator handling in `resolveOnPath` (explicitly avoids the `Platform.pathSeparator` mistake). `compareVersions` compares 3 components (sufficient for x.y.z toolchains). +- `tool/verify_bom.dart` — `_finish()` exits 1 on any failure; `--toolchains` degrade-to-warning for missing flutter/rustup is intentional and documented (CI host runner has no toolchain); Flutter path-with-space check fails closed with a clear message; JSON parse fail-closed on malformed output. +- `scripts/tests/{verify_bom_parser_test,bom_values_test}.dart` — meaningful assertions (parse, comment handling, version compare, duplicate-section rejection). Passed `dart analyze`. + +### Verification run on this host (no Flutter; package resolution too slow for `dart test`) +- `dart analyze tool/bom_parser.dart tool/verify_bom.dart scripts/tests/*_test.dart` → **No issues found.** +- `dart compile kernel tool/verify_bom.dart` → **exit 0** (parser API fully consistent). +- Full `dart test` / `flutter test` require the `:test` CI image (package graph resolution + native Rust deps); deferred to CI. + +### Latent MINORs (benign for the actual BOM format) +- `readBom`: a single-quoted value with a trailing ` #comment` would have the comment stripped (only double-quoted values are protected). The BOM uses double quotes, so benign. +- `compareVersions`: only compares 3 numeric components; a 4th component (e.g. a build suffix) is ignored. Toolchains are all x.y.z, so benign. + +--- + +## Summary table +| Item | Severity | Status | +|---|---|---| +| Tests run only on PR, not push to staging | MAJOR (coverage) | maintainer decision — not a code bug | +| Makefile not exercised by automated CI | MAJOR (architectural) | make-smoke is manual; release path bypasses make | +| BOM doesn't cross-validate native-lib versions | MINOR (pre-existing) | not introduced by this PR | +| No `flutter analyze` in CI | MINOR | commented out in test.yaml | +| CHANGE_NOW "BLOCKER" | — | false positive (generated gitignored file) | +| dnix.lock "missing" | — | false positive (distributed per-plugin locks) | +| install_nix.sh curl\|sh no checksum | NIT/acceptable | official Nix install method | +| Dart changed files | — | clean: analyze + compile verified | From e4bf45763cdb2742bc907b8f4e00addfb6fc33d0 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:10:45 +0200 Subject: [PATCH 095/107] Remove working-note docs from the PR branch The three PR-1482-*.md notes (build-strategy decision, optionB flake consolidation, round-2 audit) were self-generated working notes that leaked into the PR diff; they do not belong in the upstream repo. Content is preserved in Hindsight memory and the session record. --- PR-1482-audit-round2-ci-and-security.md | 96 ------------- PR-1482-build-strategy-decision.md | 108 -------------- PR-1482-optionB-flake-bom-consolidation.md | 158 --------------------- 3 files changed, 362 deletions(-) delete mode 100644 PR-1482-audit-round2-ci-and-security.md delete mode 100644 PR-1482-build-strategy-decision.md delete mode 100644 PR-1482-optionB-flake-bom-consolidation.md diff --git a/PR-1482-audit-round2-ci-and-security.md b/PR-1482-audit-round2-ci-and-security.md deleted file mode 100644 index 755bfcaea6..0000000000 --- a/PR-1482-audit-round2-ci-and-security.md +++ /dev/null @@ -1,96 +0,0 @@ -# PR #1482 — Audit Round 2: CI Intel + Security + Native Integrity + Dart Logic - -Prepared 2026-11-20. Follows the first-round audits (A–F: Makefile, bootstrap, docs, CI, bm harness, BOM). -New angles: our own CI surface, build-pipeline security, dnix prebuilt integrity, Dart logic in the changed files. - -Every BLOCKER/MAJOR claim from a subagent was re-checked against ground truth. Subagent findings are leads, not truth. - -## Verdict -**No new merge blockers.** The PR's changed Dart code is correct and fail-closed (`dart analyze` clean; `verify_bom.dart` compiles standalone; logic reviewed line-by-line). The security-reviewer's two headline claims (CHANGE_NOW "BLOCKER", dnix.lock "missing") are both false positives. The one genuine, maintainer-facing item is a **coverage gap** (tests run only on PR, not on push to staging) plus the architectural note that the Makefile is not exercised by automated CI. - ---- - -## 1. CI Intel (our own workflows) - -### Trigger matrix -| Workflow | Triggers | Tests run? | -|---|---|---| -| `build.yaml` | push (tags `v*.*.*`, branch `staging`) + workflow_dispatch | No — builds only | -| `test.yaml` | **`pull_request` only** | **Yes** — 11 `dart scripts/tests/*` + `flutter test --coverage` + `make-check` dry-run matrix | -| `make-smoke.yaml` | workflow_dispatch only (manual) | No — `make build-linux` smoke | -| `build-ci-image.yaml` | push (main/staging) + workflow_dispatch | N/A — builds the CI image | -| `release-mwebd-windows.yaml` | workflow_dispatch only | No | - -### Image tags are correct (not a divergence) -`build-ci-image.yaml` builds three distinct Dockerfile targets and pushes distinct tags: -- `:latest` = `full` target (used by build.yaml build jobs + make-smoke) -- `:test` = `test` target (used by test.yaml) -- `:android` = `android` target - -test.yaml using `:test` while build.yaml uses `:latest` is intentional multi-target, not drift. - -### Genuine findings -- **MAJOR (coverage):** `test.yaml` fires on `pull_request` only. `build.yaml` fires on `push: branches: [staging]`. So **direct commits to staging bypass the entire Dart test suite + `flutter test` + make-check.** If staging accepts direct pushes, that is a real gap. Fix options: add `push: branches: staging` to `test.yaml`, or rely on repo branch protection requiring the PR check. Maintainer decision. -- **MAJOR (architectural):** the Makefile — the PR's central deliverable — is never exercised by automated CI. All 19 build.yaml jobs call `./build_app.sh -d` then `flutter build` directly; none run `make`. `make-smoke.yaml` (the only thing that runs `make build-linux`) is manual `workflow_dispatch` only. So the make path has no automated gate. -- **MINOR:** no static analysis in CI (`flutter analyze` is commented out in test.yaml). -- No in-YAML merge-gate; relies on repo branch protection (repo-side config, not YAML-fixable). - -### False positives from the CI scout (verified NOT defects) -- "Android signing secrets required, no fallback" — by design; a release APK must be signed. -- "bom job is a single point of failure" — that is how a shared config gate is meant to work; fail-fast on invalid BOM is correct. -- "verify-toolchain missing from non-linux / Windows jobs" — those are prebuilt (`build_app.sh -d`) jobs; they don't run make and don't need host Rust. (Same false positive as round-1 Audit D.) -- "CHANGE_NOW if set-but-empty overwrites with empty content" — wrong; `[ -n "" ]` is false, so an empty secret correctly uses the stub. - ---- - -## 2. Build-pipeline security (security-reviewer) - -### False positives (verified NOT blockers) -- **"CHANGE_NOW decoded to `lib/external_api_keys.dart` — BLOCKER"** — No. That file is a generated, gitignored artifact (the empty-stub fallback proves it is never committed). The decoded secret lives only in the ephemeral CI container workspace and is compiled into the release binary (embedding the ChangeNow API key in the app is the app's normal design). GitHub masks `${{ secrets.X }}` in logs. Standard pattern. -- **"dnix.lock missing from repo — MAJOR"** — No. dnix uses **distributed per-plugin lockfiles** (each plugin's `dnix.json`/`dnix.lock` lives in its own repo, fetched at build). `pubspec.lock` (committed) pins all 4 native libs — `flutter_libepiccash`, `flutter_libmwc`, `frostdart`, `tor_ffi_plugin` — by git URL + revision. The security-reviewer searched only the repo root and concluded "missing." - -### Real / acceptable -- **install_nix.sh `curl https://nixos.org/nix/install | sh` without checksum — acceptable (NIT).** This is the official, documented Nix install method; a hardcoded checksum would need Nix's rotating published hash. Consistent with how every Nix user installs. -- **No app-level secondary check if dnix's upstream hash verification were compromised — by design (the locked dnix-hash-only decision).** Not a code defect. `check_native_overrides.dart` provides defense-in-depth (exit 1 if `.dnix-build` overrides present). -- BOM parser / `bom_values.sh` / install scripts are well-guarded: version-format validation, duplicate-section rejection, path quoting, fail-closed on malformed input. - ---- - -## 3. Native-dependency / dnix integrity (scout) - -- The `-d` hash check is **mandatory at the dnix level** (dnix build hooks verify each downloaded lib against its `dnix.lock` release hash); `build_app.sh -d` delegates to dnix rather than re-implementing it. -- `pubspec.lock` is committed and pins all 4 native libs by git revision. -- **MAJOR (architectural note, pre-existing, not a PR regression):** `stack-bom.toml` pins toolchains but does not pin the 4 native-lib versions/hashes, and there is no guard cross-validating that a BOM toolchain upgrade is compatible with the pinned native-lib git revisions. The PR diff does **not** touch `pubspec.lock`/`pubspec.yaml`, so this is a pre-existing property, not introduced or regressed by #1482. - ---- - -## 4. Dart logic in the changed files (main-agent review) - -All 4 changed Dart files are **new** (934 insertions, 0 deletions) — no regression risk in existing code. - -- `tool/bom_parser.dart` — `readBom` fails closed (unterminated string → `FormatException`), strips trailing comments only on bare values, handles CRLF in `lockRefs`, correct PATH-list-separator handling in `resolveOnPath` (explicitly avoids the `Platform.pathSeparator` mistake). `compareVersions` compares 3 components (sufficient for x.y.z toolchains). -- `tool/verify_bom.dart` — `_finish()` exits 1 on any failure; `--toolchains` degrade-to-warning for missing flutter/rustup is intentional and documented (CI host runner has no toolchain); Flutter path-with-space check fails closed with a clear message; JSON parse fail-closed on malformed output. -- `scripts/tests/{verify_bom_parser_test,bom_values_test}.dart` — meaningful assertions (parse, comment handling, version compare, duplicate-section rejection). Passed `dart analyze`. - -### Verification run on this host (no Flutter; package resolution too slow for `dart test`) -- `dart analyze tool/bom_parser.dart tool/verify_bom.dart scripts/tests/*_test.dart` → **No issues found.** -- `dart compile kernel tool/verify_bom.dart` → **exit 0** (parser API fully consistent). -- Full `dart test` / `flutter test` require the `:test` CI image (package graph resolution + native Rust deps); deferred to CI. - -### Latent MINORs (benign for the actual BOM format) -- `readBom`: a single-quoted value with a trailing ` #comment` would have the comment stripped (only double-quoted values are protected). The BOM uses double quotes, so benign. -- `compareVersions`: only compares 3 numeric components; a 4th component (e.g. a build suffix) is ignored. Toolchains are all x.y.z, so benign. - ---- - -## Summary table -| Item | Severity | Status | -|---|---|---| -| Tests run only on PR, not push to staging | MAJOR (coverage) | maintainer decision — not a code bug | -| Makefile not exercised by automated CI | MAJOR (architectural) | make-smoke is manual; release path bypasses make | -| BOM doesn't cross-validate native-lib versions | MINOR (pre-existing) | not introduced by this PR | -| No `flutter analyze` in CI | MINOR | commented out in test.yaml | -| CHANGE_NOW "BLOCKER" | — | false positive (generated gitignored file) | -| dnix.lock "missing" | — | false positive (distributed per-plugin locks) | -| install_nix.sh curl\|sh no checksum | NIT/acceptable | official Nix install method | -| Dart changed files | — | clean: analyze + compile verified | diff --git a/PR-1482-build-strategy-decision.md b/PR-1482-build-strategy-decision.md deleted file mode 100644 index 699049a8f1..0000000000 --- a/PR-1482-build-strategy-decision.md +++ /dev/null @@ -1,108 +0,0 @@ -# PR #1482 — Build strategy decision brief (Nix-only vs brew, benchmarks re-integration) - -_Compiled 2026-11-20. Grounded in the current tree (`feat/makefile-macos-build`, 18 commits past `15d0e12d3`)._ - -## The situation (your story, confirmed against the code) - -1. You built a working **make-based** cross-platform build (macOS/Linux/Windows) with real **caching** work — including changes to Rust crates so they build on a shared Rust version and benefit from cargo caching. -2. Julian introduced **native-assets Flutter**; the build process changed and your caching no longer applied cleanly. -3. You found **sccache** still works, and want to merge the makefile + benchmarking work. -4. Now: merge everything, clean up the existing CI + legacy build flows, make it proper. - -## Settled facts (verified in-tree, 2026-11-20) - -- **CI already does NOT use Nix.** Every CI build job (`build-windows` @ `windows-2022`, `build-macos` @ `macos-latest`, `build-linux`/`build-android` @ `ubuntu-24.04`) runs `build_app.sh … -d -s`, where **`-d` = verified dnix prebuilts** (Frost/Tor/Epic/MWC), hash-checked against each plugin's `dnix.lock`. No Nix, no WSL. -- **Nix is used only for local source builds** on macOS/Linux, and only when run inside a Nix/direnv shell (`build-macos`/`build-linux` derive `SOURCE_TOOLCHAIN` from `NIX_BIN` on PATH). -- **Windows has no Nix path at all.** dnix on Windows runs in WSL2; CI is `windows-2022` (native Windows), so Windows is prebuilt-only by necessity. -- The Homebrew fallback (`scripts/install_macos_build_tools.sh`) is the **only** thing that lets a local macOS/Linux source build run *without* Nix. It already reads every version pin from `stack-bom.toml` (`bom_get flutter/rust/rust_dnssec`), so it is **not** a duplication source. -- The prebuilt path's version check is **dnix's own hash verification** (`build_app.sh -d` verifies pinned SHA in prebuilt mode). That is the correct and sufficient "what to check" — the native lib versions are pinned in `dnix.lock`. - -## Decision 1 — Source-build toolchain policy - -### Option A: Nix-only for source builds (your preference) - -**Changes (minimal):** -- Delete `scripts/install_macos_build_tools.sh`. -- Delete the `else` (brew) branch of `bootstrap-macos` (Makefile:310-318); keep only the Nix-detecting branch, which already calls `install_xcode.sh`. -- Update docs: `docs/building/make.md` (the "Homebrew packages are in `install_macos_build_tools.sh`" line), `cyperstack_matrix_info.md:40` (the "pins live in `install_macos_build_tools.sh`" line). -- `verify-bom` already warns on missing toolchains; no new check needed for source builds (Nix provides them). - -**Limits / consequences:** -- **Contributors without Nix can no longer do a local source build.** They can still: (a) use prebuilt submodules via `PREBUILTS=1` + dnix prebuilts (`-d`) — this needs only the *toolchain* (Flutter/Rust/Go/Xcode), which they install however they like; (b) rely on CI. -- **CI is unchanged** — it already uses prebuilts, not Nix. No risk to the release pipeline. -- **Windows unchanged** — already prebuilt-only. -- **Cleanest merge story.** One toolchain path for source; matches Julian's stance. Kills a legacy flow instead of carrying it. - -**What it takes:** ~3-4 file edits, all doc + one Makefile branch + one file delete. Low risk. The only real work is the Option B flake change (below) if you also want the flake to read the BOM — otherwise the flake keeps its bare `pkgs.flutter`/`pkgs.go`, which is fine for Nix-only (Nix pins via nixpkgs rev). - -### Option B: Keep the Homebrew fallback - -**Changes:** none structural — the script already tracks the BOM. - -**Limits / consequences:** -- Two source-build paths to maintain and keep in sync (Nix + brew). The brew path's native libs come from Homebrew formulae whose versions **drift** from the dnix pins — this is the *real* duplication risk, because Homebrew auto-upgrades can move a lib version out from under a `dnix.lock` pin. (Mitigated by `HOMEBREW_NO_INSTALL_UPGRADE=1` in the script, but not eliminated.) -- More contributor-friendly (no Nix install to try a source build). -- Slightly muddier merge story — you're defending a path Julian is willing to drop. - -**What it takes:** nothing now; ongoing cost is keeping the brew formula set honest against the dnix pins. - -### Recommendation - -**Option A (Nix-only for source).** It matches your stated preference and Julian's, it's the smallest diff, and it removes the one genuinely duplicated + drift-prone path. The prebuilt path (dnix `-d`) still serves everyone who can't or won't use Nix — including all CI and Windows. Keep the BOM as the single toolchain source; the native libs stay pinned in `dnix.lock`. - -## Decision 2 — What to check on the prebuilt path - -**dnix hash verification only** (your choice). The native libs are hash-checked against `dnix.lock` by `build_app.sh -d`; the host only needs the toolchain, which `verify-bom` checks. No extra host-side lib-version probing — that would duplicate what dnix already guarantees. - -## Decision 3 — Windows - -**Keep as-is** (dnix prebuilts, no Nix). It already builds. Nix is not an option on `windows-2022`. - -## Decision 4 — Re-integrating your benchmarks (`bm/bench.sh`) - -**What it is:** `bm/bench.sh` (124 lines, on `build/native-assets-harness`, **not** on the current PR branch). A build-time benchmark harness: -- Runs `make build-macos`/`build-linux` (cold or `--warm`), records **wall-clock seconds + disk delta** to `bm/results/.csv`. -- Flags: `SCCACHE=0` (compare with/without sccache), `SKIP_NATIVE=1` (Dart-only), `--label`, `--warm`. -- Depends on `toilet` (terminal font) for pretty output — a soft dependency, easy to drop. -- Windows path explicitly refuses (needs WSL2). - -**Re-integration effort — small, and it's independent of the Nix-only decision:** -- The script itself is self-contained; cherry-pick `bm/bench.sh` + the `bm/results/` dir onto the PR (or a follow-up branch). ~1 file. -- **It already calls `make build-macos`/`build-linux`**, which under Nix-only means "must be in a Nix shell." That's actually *better* for benchmarking — the harness measures the canonical source build. No change needed. -- The sccache comparison (`SCCACHE=0`) is the interesting data: it measures your caching contribution directly. `make sccache-setup` (opt-in, on `build/native-assets-harness`) writes `~/.cargo/config.toml` with the `sccache` rustc-wrapper. -- **Caveat:** `bm/bench.sh` runs the *full* native build each cold run — on a fresh Nix shell that includes the dnix source compile (the 2-hour path). For a clean sccache-vs-no-sccache comparison you want the *incremental* native layer, so document that cold benchmarks assume a warm Nix store / pre-fetched dnix sources. - -**Recommendation:** land `bm/bench.sh` as a **separate small follow-up PR** (or a second commit on this branch after the build-strategy change lands), so the big merge isn't entangled with a benchmarking tool. It's orthogonal to Nix-only vs brew. - -## Sequencing to close the topic - -1. **Build-strategy change** (Option A): delete the brew fallback + docs, keep prebuilt/dnix path. One coherent commit. -2. **Optional Option B (flake reads BOM)** — only if you want the flake's Flutter/Go sourced from the BOM too. HIGH risk (nixpkgs-rev coupling); plan already written in `PR-1482-optionB-flake-bom-consolidation.md`. Can be its own PR. -3. **`bm/bench.sh` re-integration** — separate small PR/commit, orthogonal. - ---- - -## Outcome — Option A executed (2026-11-20) - -**Decision 1 resolved: Nix-only for source builds.** The Homebrew source-build fallback is removed; Homebrew remains a valid package manager for the **prebuilt** path (`PREBUILTS=1`). - -### Changes (one commit) -- **`scripts/install_macos_build_tools.sh`** — deleted (the Homebrew tool installer). -- **`Makefile`**: - - `bootstrap-macos` rewritten: now only runs `@bash scripts/install_xcode.sh` (Xcode is never provided by Nix/Homebrew). Dropped the `install_macos_build_tools.sh` branch and the `rustup target add` line. - - `bootstrap-brew` alias removed; removed from `.PHONY`. - - `bootstrap` target error wording: "Nix is not installed. Source builds require Nix; install it from https://nixos.org/download/." - - `toolchain-check`: dropped the `ifeq ($(TOOLCHAIN_EFFECTIVE),brew)` hard-fail branch; the final filter now treats `host`/`manual` as "tools on PATH, no separate check" (correct for the prebuilt path). - - `TOOLCHAIN` allowed values: removed `brew` (`auto nix direnv manual host`). -- **Living docs** (`README.md`, `docs/building/make.md`, `docs/building/macos.md`, `docs/building/make-flow.md`): reframed Homebrew from a source-build fallback to the prebuilt path; `bootstrap-macos` now described as Xcode check/select; `PREBUILTS=1` required for Homebrew/manual. -- **Historical drafts** (`cyperstack_matrix_*.md`, `julian_review_reply_draft.md`) — left **unchanged**: they are records of what was told to Julian when the Homebrew path existed. - -### Not done (out of scope, still open) -- **`makefile-build-audit` blocker** (PREBUILTS=0 guard tests only `NIX_BIN`, not `TOOLCHAIN_EFFECTIVE`): still present. Deleting the brew bootstrap removed the *toolchain* angle, but `make -n build-macos PREBUILTS=0 TOOLCHAIN=host` on a non-Nix host still doesn't hard-fail in dry-run (the guard runs at recipe time, and `-n` skips it). Consider tightening to require `nix`/`direnv` explicitly for `PREBUILTS=0` — a follow-up. -- **Option B** (flake reads BOM) and **`bm/bench.sh` re-integration** — unchanged, still separate follow-ups. - -### Verified -- `make -n help` parses cleanly. -- `toolchain-check` has no brew branch; the final filter is `ifeq ($(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),)`. -- Prebuilt path works: `make -n build-macos PREBUILTS=1 TOOLCHAIN=host` → exit 0. -- No dangling `install_macos_build_tools` / `bootstrap-brew` / `Homebrew fallback` refs in living docs. diff --git a/PR-1482-optionB-flake-bom-consolidation.md b/PR-1482-optionB-flake-bom-consolidation.md deleted file mode 100644 index a04023ea90..0000000000 --- a/PR-1482-optionB-flake-bom-consolidation.md +++ /dev/null @@ -1,158 +0,0 @@ -# Option B (deferred): make flake.nix read Flutter/Go from stack-bom.toml - -Status: **planned, NOT implemented.** Deferred from the Option A consolidation -(2026-11-20). Option A is committed (`27e30c324`): the Dockerfile now reads -Flutter + Go from the BOM. This document is the plan for the remaining gap. - -## The remaining duplication (verified against code) - -`stack-bom.toml` is the intended single source of truth. After Option A the -Dockerfile reads it. What still does **not** read the BOM for Flutter and Go: - -| Version | BOM | flake.nix today | Homebrew installer | Dockerfile (after A) | -|---|---|---|---|---| -| flutter `3.47.2` | ✅ | ❌ bare `pkgs.flutter` (nixpkgs rev pins it) | ✅ `bom_get flutter` | ✅ reads BOM | -| go `1.24.13` | ✅ | ❌ bare `pkgs.go` (nixpkgs rev pins it) | ⚠️ `brew install go` (no version) | ✅ reads BOM | -| rust `1.99.1` | ✅ | ✅ `bom.toolchain.rust` | ✅ `bom_get rust` | n/a (rustup latest) | -| dnssec_rust `1.90.0` | ✅ | ✅ `bom.toolchain.dnssec_rust` | ✅ `bom_get rust_dnssec` | n/a | - -So after Option A, **rust/dnssec/flutter are already single-sourced**; the only -remaining drift is **Flutter and Go in the Nix shell**, which use bare nixpkgs -packages. The flake.nix comment at line 18 ("Single source of truth for the -toolchain versions") is currently **aspirational** — it is true for rust/dnssec, -false for flutter/go. - -## Why this is the risky one (do NOT do casually) - -The Nix shell is the **reproducible source-build path** (`PREBUILTS=0`, -`TOOLCHAIN=nix`). The 2026-11-18 verified builds (dnix byte-for-byte -reproduction of the 4 native libs) depend on a specific Flutter version in the -shell. `pkgs.flutter` from the pinned nixpkgs rev (`b1b875982b17dabde9b4a37f3e229e74913e6db3`) -is whatever that rev ships — it may **not** equal `3.47.2`. Forcing it to `3.47.2` -changes the shell's Flutter, which can change: - -- the Dart SDK bundled with Flutter (affects the `dart`/`flutter` used by dnix - native plugins and `verify_bom.dart`), -- the iOS/macOS CocoaPods/Flutter engine hashes dnix rebuilds byte-for-byte. - -That is exactly the property dnix guarantees. A version mismatch there is not a -cosmetic drift — it can break the dnix reproduction or silently change the -produced binaries. **This is why Option B needs a real verification build**, -which cannot be fully run on this host (no Flutter in the Nix shell here). - -## The concrete change - -flake.nix must select the exact Flutter and Go versions from the BOM instead of -bare packages. Two sub-approaches: - -### B1 — nixpkgs version-selector packages (preferred, lowest blast radius) -nixpkgs exposes versioned aliases: `pkgs.go_1_24` (exists for many Go majors). -For Go this is a one-line change: `go` → `go_1_24` (or derive from the BOM's -`go` major). It locks the shell to the Go that nixpkgs rev provides for `go_1_24`, -which for `1.24.13` should match — **verify** the resolved version equals the -BOM after the change. - -Flutter has **no** `pkgs.flutter_3_47` style alias in standard nixpkgs — the -bare `pkgs.flutter` is the only option, and it is rev-pinned. To pin Flutter -`3.47.2` exactly you must either: - -- pin the **nixpkgs rev to the one that ships Flutter 3.47.2**, or -- add a **Flutter overlay/expression** that fetches Flutter at the exact git - ref/commit behind tag `3.47.2` (Flutter releases are git tags; the - `flutter` nixpkgs derivation takes a `version`/`src` you can override). - -### B2 — overlay that reads the BOM (most faithful, most work) -Write a small overlay that, given `bom.toolchain.flutter`, builds Flutter from -the matching git tag (`https://github.com/flutter/flutter.git` @ tag -``), reusing the same source the Dockerfile and Homebrew installer -clone. This makes all four sources truly identical, but it is a real nix -expression (Flutter's build needs the Dart SDK, engine artifacts, and -`flutter precache`), and it changes the reproducibility story from "whatever -nixpkgs rev ships" to "pinned to the BOM tag" — a behavior change that must be -documented and build-verified. - -## Recommended sequencing - -1. **Do B1-Go first** (one line: `go` → versioned selector). Verify the resolved - Go version equals `bom.toolchain.go`. Low risk. -2. **Flutter is the hard part** — treat it as its own PR: - - Decide: pin nixpkgs rev to the Flutter-3.47.2 one (B1), or add a BOM-driven - Flutter overlay (B2). B1 is less code but couples the whole toolchain to a - rev chosen for Flutter; B2 is more code but keeps the current rev and pins - only Flutter. - - **Must run `make build-macos` and `make build-linux`** to confirm dnix - still reproduces byte-for-byte and the app builds. This is the gate; without - it Option B is EDITED/UNPROVEN, not CERTIFIED. -3. Keep the flake.nix comment honest: change "Single source of truth for the - toolchain versions" to name exactly which keys it sources (rust, dnssec_rust, - and — after B — flutter/go), or leave it aspirational with a TODO. - -## Risk register - -- **dnix byte-for-byte break** — the dominant risk. Flutter version change in the - shell can change engine/Dart artifacts dnix rebuilds. Mitigation: the verification - build is mandatory; do not merge without it. -- **nixpkgs rev coupling** — pinning the rev for Flutter 3.47.2 may regress Go or - other packages; re-verify the whole toolchain. -- **Overlay maintenance** — a B2 Flutter overlay must track Flutter's release - structure; it is more to maintain than a version selector. -- **Cannot self-verify here** — no Flutter in the Nix shell on this host; the - author must run the builds on a machine with the full nix env. - -## Verified finding (2026-11-20) — nixpkgs `go_1_24` selector is gone; exact-fetch is the fix (CORRECTED) - -Resolved the pinned nixpkgs rev `b1b875982b17dabde9b4a37f3e229e74913e6db3` -directly with `nix eval`: - -- `pkgs.go_1_24` → **MISSING** (the selector does not exist in this rev). -- `pkgs.go_1_25`, `pkgs.go_1_23` → **removed** (Go 1.23/1.25 are end-of-life in - this rev). -- `pkgs.go_1_26` → `1.26.7` (the only `go_1_*` selector present). -- bare `pkgs.go` → **`1.26.7`** — already drifts from the BOM's `1.24.13`. - -So B1-Go (`go` → `go_1_24`) **cannot** be applied without first moving the -nixpkgs rev to one that still ships `go_1_24`. And bare `pkgs.go` is already at -1.26.7, not the BOM's 1.24.13 — meaning the Nix shell's Go has been drifting -from the BOM all along, on the prebuilt-independent source path. - -**CORRECTION (2026-11-20, the "nixpkgs-rev change" framing is WRONG):** the -implication above was wrong. A nixpkgs-rev change is **not** required. The -Dockerfile (Option A, committed) already reads Flutter/Go from the BOM and pins -**exact** versions with **no nixpkgs involvement** — `Dockerfile:87-103` and -`:182-198`: - -```dockerfile -GO_VERSION="$(... bom_values.sh --get go)" # 1.24.13 -curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" -FLUTTER_VERSION="$(... bom_values.sh --get flutter)" # 3.47.2 -git clone --depth 1 --branch "$FLUTTER_VERSION" https://github.com/flutter/flutter.git -``` - -So the exact-version fetch pattern is **already proven in this repo**. The -`go_1_24` selector being gone from this rev is irrelevant — the fix does not use -nixpkgs selectors at all. The two viable approaches (both keep the current rev): - -1. **Go:** replace bare `go` in `flake.nix` with a small nix derivation that - fetches `https://go.dev/dl/go1.24.13.linux-amd64.tar.gz` / `-darwin.tar.gz` - at the BOM's `go` value (mirrors the Dockerfile). No rev change. -2. **Flutter:** either fetch the `flutter@3.47.2` git tag directly (like the - Dockerfile) or pin the nixpkgs `flutter` derivation's `version`/`src` to the - BOM value. No rev change. - -What is still true: the **build-gate verification** (`make build-macos` / -`make build-linux`, confirming dnix still reproduces byte-for-byte after the -Flutter change) cannot run on this host (no Flutter in the Nix shell), so the -flake edit stays **planned / EDITED-UNPROVEN** until done on a full nix-env -machine. But the blocker is *verification*, **not** a rev change. Do NOT ship a -partial flake edit here without the build gate — changing bare `pkgs.go`/ -`pkgs.flutter` silently changes the toolchain dnix verifies against. - -## What is NOT in scope - -- Homebrew installer Go version: it runs `brew install go` with no version pin. - Homebrew's `go` is "latest", so the installer's Go already drifts from the BOM - independently of this work. Leaving it is consistent with the prebuilt/host - path being best-effort; pinning it is a separate, smaller task. -- system_deps (jsoncpp, libsecret, etc.): not version-pinned anywhere except the - BOM comment; they come from the OS package manager. No consolidation action - needed — they are already single-sourced (only in the BOM). From 652ee971e63463efd96edef5fcc20c90fa12949c Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:27:20 +0200 Subject: [PATCH 096/107] bm: make SCCACHE=0 genuinely disable sccache for an A/B baseline SCCACHE=0 was only a label; sccache is enabled via rustc-wrapper in the cargo config, so a 'no-sccache' run still used sccache and could not prove caching improves build time. bench.sh now temporarily strips the rustc-wrapper line from the active cargo config for that one build, with a trap that restores the config afterward (even on crash). SCCACHE unset or =1 leaves sccache as configured. README caveat updated to match. --- bm/README.md | 12 +++++++----- bm/bench.sh | 29 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/bm/README.md b/bm/README.md index 107d70b724..4e295493a4 100644 --- a/bm/README.md +++ b/bm/README.md @@ -47,11 +47,13 @@ bash bm/bench.sh SKIP_NATIVE=1 # Dart only (no native libs) masking the sccache-vs-no-sccache comparison. Pre-fetch the dnix sources (e.g. `nix build` once) before measuring so a cold run only measures the project build, not the library compile. -- **sccache is a cargo-config toggle, not a make flag.** `SCCACHE=0/1` is - accepted by `bench.sh` for labeling, but sccache is actually turned on/off by - `make sccache-setup`, which writes `~/.cargo/config.toml` with the - `rustc-wrapper = "sccache"` setting. Remove that file to benchmark without - sccache. +- **sccache is a cargo-config toggle, not a make flag.** sccache is turned on + by `make sccache-setup`, which writes `~/.cargo/config.toml` with the + `rustc-wrapper = "sccache"` setting. `bench.sh SCCACHE=0` disables sccache for + that one build by temporarily stripping the `rustc-wrapper` line from the + active cargo config (with a trap that restores it afterward), so a `SCCACHE=0` + run is a genuine no-sccache baseline you can A/B against the default. Leaving + `SCCACHE` unset (or `SCCACHE=1`) runs with sccache as configured. - **`SKIP_NATIVE=1` is a no-op through `make`.** The Makefile does not consume it; it is a leftover from the harness's pre-make origin. Use `make clean-native` + `make build-macos` if you want to isolate the Dart layer. diff --git a/bm/bench.sh b/bm/bench.sh index 9aa3d7c4ea..8c3a090807 100755 --- a/bm/bench.sh +++ b/bm/bench.sh @@ -81,6 +81,35 @@ if [ $WARM -eq 0 ]; then make clean 2>&1 | tail -1 fi +# sccache bypass: SCCACHE=0 must measure a build WITHOUT sccache. sccache is +# enabled only via rustc-wrapper in the active cargo config, so temporarily +# neutralise that line for this one build. A trap guarantees the config is +# restored even if the build crashes. SCCACHE=1 (or unset) leaves sccache as-is. +SCCACHE_BYPASS_CONFIG="" +SCCACHE_BYPASS_BACKUP="" +if echo "$MAKE_FLAGS" | grep -q "SCCACHE=0"; then + SCCACHE_CARGO_CONFIG="$(if [ -n "${CARGO_HOME:-}" ]; then echo "$CARGO_HOME"; else echo "$HOME/.cargo"; fi)/config.toml" + if [ -f "$SCCACHE_CARGO_CONFIG" ] && grep -q "rustc-wrapper" "$SCCACHE_CARGO_CONFIG"; then + SCCACHE_BYPASS_BACKUP="${SCCACHE_CARGO_CONFIG}.bench.bak" + cp -p "$SCCACHE_CARGO_CONFIG" "$SCCACHE_BYPASS_BACKUP" + # Drop the [build] rustc-wrapper line so cargo falls back to plain rustc. + grep -v "rustc-wrapper" "$SCCACHE_CARGO_CONFIG" > "${SCCACHE_CARGO_CONFIG}.bench.tmp" \ + && mv "${SCCACHE_CARGO_CONFIG}.bench.tmp" "$SCCACHE_CARGO_CONFIG" + SCCACHE_BYPASS_CONFIG="$SCCACHE_CARGO_CONFIG" + echo "[INFO] sccache disabled for this build via $SCCACHE_CARGO_CONFIG (backup: $SCCACHE_BYPASS_BACKUP)" + else + echo "[INFO] no rustc-wrapper in $SCCACHE_CARGO_CONFIG; sccache already inactive for this build" + fi +fi +restore_sccache() { + if [ -n "$SCCACHE_BYPASS_BACKUP" ] && [ -f "$SCCACHE_BYPASS_BACKUP" ]; then + mv "$SCCACHE_BYPASS_BACKUP" "$SCCACHE_BYPASS_CONFIG" + echo "[INFO] sccache config restored" + fi + rm -f "${SCCACHE_BYPASS_CONFIG}.bench.tmp" 2>/dev/null || true +} +trap restore_sccache EXIT + # Build echo "Building: make ${BUILD_TARGET} ${MAKE_FLAGS} " | toilet -f term --metal START=$(date +%s) From a3b752e23a5c6d9597f7a97454ab5020230c189e Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:47:25 +0200 Subject: [PATCH 097/107] fix(make): require-version BUILD_NUM regex was a shell parse error The BUILD_NUM check used a single '$' in the grep pattern ('^[0-9]+$'). Make does not escape a lone $, so the shell received an unterminated single-quoted string ('^[0-9]+ || { ...), aborting require-version with 'unexpected EOF looking for matching ' . Every real build target (build-macos/linux/windows/android/ios) depends on require-version, so all of them failed before doing anything. 'make -n' dry-runs masked it because dry-run never executes recipes. Fix: escape the anchor as '$$' like the VERSION check already does, so the shell sees the literal $ end-of-line anchor. Verified: valid VERSION/BUILD_NUM pass; invalid values are still rejected. --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 0eed3c053b..8f2af629cc 100644 --- a/Makefile +++ b/Makefile @@ -223,7 +223,7 @@ endif require-version: ## Fail unless VERSION/BUILD_NUM are valid and BUILD_NUM is not below the latest release tag @printf '%s' '$(VERSION)' | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z][0-9A-Za-z.-]*)?$$' || { echo >&2 "[ERROR] VERSION must be x.y.z or x.y.z-suffix (got '$(VERSION)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } - @printf '%s' '$(BUILD_NUM)' | grep -Eq '^[0-9]+$' || { echo >&2 "[ERROR] BUILD_NUM must be numeric (got '$(BUILD_NUM)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } + @printf '%s' '$(BUILD_NUM)' | grep -Eq '^[0-9]+$$' || { echo >&2 "[ERROR] BUILD_NUM must be numeric (got '$(BUILD_NUM)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } @latest="$$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | sed -n 's/^build_\([0-9][0-9]*\)$$/\1/p' | head -n1)"; \ if [ -n "$$latest" ]; then \ [ "$(BUILD_NUM)" -ge "$$latest" ] || { echo >&2 "[ERROR] BUILD_NUM $(BUILD_NUM) is below the latest release tag build_$$latest."; exit 1; }; \ From 61ce1dd74d8735c7a284e185297322d02de9b0a9 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:48:44 +0200 Subject: [PATCH 098/107] test(ci): execute require-version recipe (not just dry-run) in make-check make -n dry-runs never run recipes, so they cannot catch a broken recipe that aborts at shell-parse time. Added a make-check step that actually runs require-version with a valid VERSION/BUILD_NUM (must pass) and two invalid inputs (must be rejected). This would have caught the require- version unescaped-\$ parse error that broke every real build target. --- .github/workflows/test.yaml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 3f8bc27e95..02281d6d7d 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -177,3 +177,27 @@ jobs: echo 'host Android source mode must fail' >&2 exit 1 fi + # require-version must actually RUN (not just dry-run): a broken recipe + # regex is invisible to `make -n` because dry-run never executes recipes. + # This executed the recipe and would have caught the require-version shell + # parse error (unescaped \$ anchor) that broke every real build target. + - name: require-version recipe executes (valid passes, invalid fails) + run: | + # require-version must actually RUN (not just dry-run): a broken recipe + # regex is invisible to `make -n` because dry-run never executes + # recipes. This would have caught the require-version shell parse error + # (unescaped \$ anchor) that broke every real build target. + # Use the current latest build_* tag as BUILD_NUM so the valid case is + # not rejected by the 'BUILD_NUM below latest tag' guard — we are + # isolating the regex/parse behavior, not the release-tag rule. + latest_build_tag="$$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | sed -n 's/^build_\([0-9][0-9]*\)$$/\1/p' | head -n1)" + build_num="$${latest_build_tag:-1}" + # Valid VERSION/BUILD_NUM must pass the recipe (exit 0), proving the + # grep anchors are correctly escaped ($$ -> $) and no shell parse error. + make require-version VERSION=0.0.0 BUILD_NUM="$$build_num" >/dev/null 2>&1 \ + || { echo "require-version rejected a valid VERSION/BUILD_NUM ($$build_num)" >&2; exit 1; } + # Invalid inputs must be rejected with a non-zero exit. + make require-version VERSION=not-a-version BUILD_NUM="$$build_num" 2>/dev/null \ + && { echo 'require-version accepted an invalid VERSION' >&2; exit 1; } + make require-version VERSION=0.0.0 BUILD_NUM=not-a-number 2>/dev/null \ + && { echo 'require-version accepted a non-numeric BUILD_NUM' >&2; exit 1; } From 972205621d4d0f616d6bc74515d3f67ef25cde1f Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:49:32 +0200 Subject: [PATCH 099/107] test(ci): use $$ consistently for build_num in require-version check GitHub Actions parses run: blocks and requires $$ for a literal shell $. Align the valid-case make invocation with the invalid-case lines so all references expand correctly at runtime. --- .github/workflows/test.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 02281d6d7d..58cff88232 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -190,8 +190,8 @@ jobs: # Use the current latest build_* tag as BUILD_NUM so the valid case is # not rejected by the 'BUILD_NUM below latest tag' guard — we are # isolating the regex/parse behavior, not the release-tag rule. - latest_build_tag="$$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | sed -n 's/^build_\([0-9][0-9]*\)$$/\1/p' | head -n1)" - build_num="$${latest_build_tag:-1}" + build_num="$$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | sed -n 's/^build_\([0-9][0-9]*\)$$/\1/p' | head -n1)" + build_num="${build_num:-1}" # Valid VERSION/BUILD_NUM must pass the recipe (exit 0), proving the # grep anchors are correctly escaped ($$ -> $) and no shell parse error. make require-version VERSION=0.0.0 BUILD_NUM="$$build_num" >/dev/null 2>&1 \ From 6e8116fa1edcaa834e7881c9db60541e637173b0 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:48:51 +0200 Subject: [PATCH 100/107] fix(make): source check-reqs Rust versions from stack-bom.toml check-reqs (the cross-platform path used by build-linux/build-android) hardcoded rustup toolchains 1.90.0 and 1.99.1, while check-reqs-macos used the BOM-driven RUST_VERSION. On a version bump the two paths would diverge, breaking the single-source-of-truth goal. Add BOM_DNSSEC_RUST / DNSSEC_RUST_VERSION (sourced like BOM_RUST) and use them in check-reqs. Verified: both rustup run checks resolve to the BOM values (1.99.1 / 1.90.0) and pass. --- Makefile | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 8f2af629cc..20a7dc2510 100644 --- a/Makefile +++ b/Makefile @@ -137,6 +137,8 @@ PROTOC_PATH := $(shell command -v protoc 2>/dev/null) BOM_FILE := $(APP_PROJECT_ROOT_DIR)/stack-bom.toml BOM_RUST := $(shell bash "$(APP_PROJECT_ROOT_DIR)/scripts/bom_values.sh" --get rust "$(BOM_FILE)" 2>/dev/null) RUST_VERSION ?= $(if $(BOM_RUST),$(BOM_RUST),$(error Cannot read [toolchain] rust from $(BOM_FILE))) +BOM_DNSSEC_RUST := $(shell bash "$(APP_PROJECT_ROOT_DIR)/scripts/bom_values.sh" --get dnssec_rust "$(BOM_FILE)" 2>/dev/null) +DNSSEC_RUST_VERSION ?= $(if $(BOM_DNSSEC_RUST),$(BOM_DNSSEC_RUST),$(error Cannot read [toolchain] dnssec_rust from $(BOM_FILE))) # Only strip Nix/Apple variables when a Nix shell actually supplied them. In a # Homebrew or manual shell these are the user's own settings and are kept. NIX_ENV_UNSET = -u LD -u LDFLAGS -u NIX_LDFLAGS -u NIX_CFLAGS_LINK \ @@ -239,8 +241,8 @@ check-reqs: ## Verify essential build tools @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed. Use 'nix develop' (recommended) or add Flutter to PATH."; exit 1; } @[ -n "$(DART)" ] && command -v "$(DART)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Dart not installed. It ships with Flutter; use 'nix develop' (recommended)."; exit 1; } @command -v rustup >/dev/null 2>&1 || { echo >&2 "[ERROR] rustup not installed."; exit 1; } - @rustup run 1.90.0 rustc --version >/dev/null 2>&1 || { echo >&2 "[ERROR] Rust 1.90.0 (DNSSEC) not installed via rustup."; exit 1; } - @rustup run 1.99.1 rustc --version >/dev/null 2>&1 || { echo >&2 "[ERROR] Rust 1.99.1 not installed via rustup."; exit 1; } + @rustup run $(DNSSEC_RUST_VERSION) rustc --version >/dev/null 2>&1 || { echo >&2 "[ERROR] Rust $(DNSSEC_RUST_VERSION) (DNSSEC) not installed via rustup."; exit 1; } + @rustup run $(RUST_VERSION) rustc --version >/dev/null 2>&1 || { echo >&2 "[ERROR] Rust $(RUST_VERSION) not installed via rustup."; exit 1; } @# `rustup which cargo` resolves a toolchain path even when no shim is on PATH, @# but the plugin build scripts invoke bare `cargo` — verify that separately. @command -v cargo >/dev/null 2>&1 || [ -x "$$HOME/.cargo/bin/cargo" ] || { echo >&2 "[ERROR] 'cargo' is not on PATH (rustup shims missing from ~/.cargo/bin). Run 'rustup-init -y', then open a new terminal."; exit 1; } From 0a20d0ad4463db86b59fda3e48416681dfa1de9c Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:04:33 +0200 Subject: [PATCH 101/107] fix(ci,make): repair make-check and format failures from review - Format tool/bom_parser.dart, tool/verify_bom.dart and scripts/tests/verify_bom_parser_test.dart (the `test` job failed on `dart format --set-exit-if-changed` before running any test). - test.yaml: the require-version step used Make's `$$` in a bash step, where `$$` is the PID; use plain `$`, fetch tags so the BUILD_NUM guard is actually exercised, and drop the duplicated comment block. - Makefile: `bootstrap` had a stray `@` inside a shell continuation line (`@echo: command not found`); remove the unused verify-bom-toolchains target. - build.yaml: fail when the CHANGE_NOW secret is missing instead of silently building with empty API-key stubs (15 copies of the stub heredoc removed). - build.yaml, make-smoke.yaml: remove the verify-toolchain job. It checked the host runner, not the CI image it was meant to guard, downgraded missing tools to warnings, and used `${{ env.PATH }}` which does not carry the runner PATH. Pass workflow_dispatch inputs through env, not the script. - verify_bom.dart: drop the now-unused --toolchains mode; correct the header (plugin pins live in pubspec.lock, `--plugins` checks only a legacy [plugins] table). - install_nix.sh: ask before piping the installer into a root shell, correct the "signature-checked" claim, remove a no-op block. - link_assets.sh, bm/: remove an unused variable and fix shellcheck warnings. --- .github/workflows/build.yaml | 393 ++++------------------ .github/workflows/make-smoke.yaml | 40 +-- .github/workflows/test.yaml | 40 ++- Makefile | 9 +- bm/bench.sh | 2 +- bm/collect.sh | 6 +- scripts/app_config/shared/link_assets.sh | 3 +- scripts/install_nix.sh | 19 +- scripts/tests/verify_bom_parser_test.dart | 30 +- tool/bom_parser.dart | 13 +- tool/verify_bom.dart | 59 +--- 11 files changed, 147 insertions(+), 467 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index b9d668bb5c..832fc7effb 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -58,41 +58,8 @@ jobs: > Official releases are published on the [Releases page](https://github.com/cypherstack/stack_wallet/releases). EOF - verify-toolchain: - # Runs on the host runner (no container), before the prebuilt image is used. - # The image's toolchain is frozen at build time, so a raised minimum (go_min - # / rust) must fail here on the runner, not only inside the image once the - # build has already started. Flutter is not installed on the runner (the - # image has it), so the toolchain check downgrades a missing Flutter to a - # warning via --toolchains. The pubspec.lock pin check stays inside the - # image, after `flutter pub get`. Dart is installed and verified in this - # same job; the build-linux job needs it to pass. - runs-on: ubuntu-24.04 - permissions: - contents: read - steps: - - uses: actions/checkout@v6 - with: - fetch-depth: 0 - - - name: Install Dart - run: | - sudo mkdir -p /etc/apt/keyrings - curl -fsSL https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_linux_signing_key | sudo gpg --dearmor -o /etc/apt/keyrings/dart.gpg - echo 'deb [signed-by=/etc/apt/keyrings/dart.gpg arch=amd64] https://storage.googleapis.com/download.dartlang.org/linux/debian stable main' | sudo tee /etc/apt/sources.list.d/dart_stable.list - sudo apt-get update -q - sudo apt-get install -y --no-install-recommends dart - - - name: Verify toolchain (pre-image) - env: - PATH: ${{ env.PATH }}:/usr/lib/dart/bin - run: | - bash scripts/bom_values.sh --check - dart tool/verify_bom.dart --toolchains - build-linux: runs-on: ubuntu-24.04 - needs: verify-toolchain permissions: contents: read packages: read @@ -140,27 +107,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build env: @@ -231,27 +182,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Set up Android local.properties run: | @@ -373,27 +308,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build windows --release @@ -465,27 +384,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build macos --release @@ -557,27 +460,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build ios --release --no-codesign @@ -642,27 +529,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build env: @@ -733,27 +604,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build env: @@ -941,27 +796,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Set up Android local.properties run: | @@ -1078,27 +917,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build windows --release @@ -1170,27 +993,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build macos --release @@ -1262,27 +1069,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build ios --release --no-codesign @@ -1464,27 +1255,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Set up Android local.properties run: | @@ -1601,27 +1376,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build windows --release @@ -1693,27 +1452,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build macos --release @@ -1785,27 +1528,11 @@ jobs: env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} run: | - if [ -n "$CHANGE_NOW" ]; then - echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - else - cat > lib/external_api_keys.dart << 'EOF' - const String kChangeNowApiKey = ""; - const String kSimpleSwapApiKey = ""; - const String kNanswapApiKey = ""; - const String kNanoSwapRpcApiKey = ""; - const String kWizSwapApiKey = ""; - const kShopInBitAccessKey = ""; - const kShopInBitPartnerSecret = ""; - const kCakePayApiToken = ""; - const kExolixApiKey = ""; - const kLetsExchangeId = ""; - const kLetsExchangeToken = ""; - const kCypherGoatApiKey = ""; - const kCypherGoatAffiliate = ""; - const kTrocadorApiKey = ""; - const kTrocadorRefCode = ""; - EOF + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build ios --release --no-codesign diff --git a/.github/workflows/make-smoke.yaml b/.github/workflows/make-smoke.yaml index 0138ee5c1a..de9cfa4648 100644 --- a/.github/workflows/make-smoke.yaml +++ b/.github/workflows/make-smoke.yaml @@ -17,38 +17,8 @@ on: default: '326' jobs: - verify-toolchain: - # Runs on the host runner (no container), before the prebuilt image is used, - # exactly as the build-linux job does. The image's toolchain is frozen at - # build time, so a raised minimum must fail here, not only once the build - # has started inside the image. Dart is installed and the toolchain is - # verified in this same job; the build job needs it to pass. - runs-on: ubuntu-24.04 - permissions: - contents: read - steps: - - uses: actions/checkout@v6 - with: - fetch-depth: 0 - - - name: Install Dart - run: | - sudo mkdir -p /etc/apt/keyrings - curl -fsSL https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_linux_signing_key | sudo gpg --dearmor -o /etc/apt/keyrings/dart.gpg - echo 'deb [signed-by=/etc/apt/keyrings/dart.gpg arch=amd64] https://storage.googleapis.com/download.dartlang.org/linux/debian stable main' | sudo tee /etc/apt/sources.list.d/dart_stable.list - sudo apt-get update -q - sudo apt-get install -y --no-install-recommends dart - - - name: Verify toolchain (pre-image) - env: - PATH: ${{ env.PATH }}:/usr/lib/dart/bin - run: | - bash scripts/bom_values.sh --check - dart tool/verify_bom.dart --toolchains - make-smoke-linux: runs-on: ubuntu-24.04 - needs: verify-toolchain permissions: contents: read packages: read @@ -73,16 +43,22 @@ jobs: rustup toolchain install "$(bash scripts/bom_values.sh --get dnssec_rust)" --profile minimal - name: Dry-run the recipe + env: + VERSION: ${{ inputs.version }} + BUILD_NUM: ${{ inputs.build_number }} run: | make -n build-linux \ PLATFORM=Linux TOOLCHAIN=host PREBUILTS=1 SYSTEM_DEPS=1 \ - VERSION="${{ inputs.version }}" BUILD_NUM="${{ inputs.build_number }}" + VERSION="$VERSION" BUILD_NUM="$BUILD_NUM" - name: Real build (make build-linux, prebuilt) + env: + VERSION: ${{ inputs.version }} + BUILD_NUM: ${{ inputs.build_number }} run: | make build-linux \ PLATFORM=Linux TOOLCHAIN=host PREBUILTS=1 SYSTEM_DEPS=1 CONFIRM=1 \ - VERSION="${{ inputs.version }}" BUILD_NUM="${{ inputs.build_number }}" + VERSION="$VERSION" BUILD_NUM="$BUILD_NUM" - name: Upload smoke artifact if: success() diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 58cff88232..44436cd71c 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -152,6 +152,8 @@ jobs: contents: read steps: - uses: actions/checkout@v6 + with: + fetch-depth: 0 # tags: require-version compares BUILD_NUM with build_* tags - name: Check the Makefile dry-runs run: | bash scripts/bom_values.sh --check @@ -177,27 +179,23 @@ jobs: echo 'host Android source mode must fail' >&2 exit 1 fi - # require-version must actually RUN (not just dry-run): a broken recipe - # regex is invisible to `make -n` because dry-run never executes recipes. - # This executed the recipe and would have caught the require-version shell - # parse error (unescaped \$ anchor) that broke every real build target. + # `make -n` never executes recipes, so a shell parse error in the + # require-version recipe is invisible to the dry-runs above. Run it for real. + # This is a bash step, not a Makefile recipe: use single `$`. - name: require-version recipe executes (valid passes, invalid fails) run: | - # require-version must actually RUN (not just dry-run): a broken recipe - # regex is invisible to `make -n` because dry-run never executes - # recipes. This would have caught the require-version shell parse error - # (unescaped \$ anchor) that broke every real build target. - # Use the current latest build_* tag as BUILD_NUM so the valid case is - # not rejected by the 'BUILD_NUM below latest tag' guard — we are - # isolating the regex/parse behavior, not the release-tag rule. - build_num="$$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | sed -n 's/^build_\([0-9][0-9]*\)$$/\1/p' | head -n1)" + # Use the latest build_* tag as BUILD_NUM so the valid case is not + # rejected by the "BUILD_NUM below latest tag" guard; this step tests + # the regex/parse behaviour, not the release-tag rule. + build_num="$(git tag -l 'build_*' --sort=-v:refname | sed -n 's/^build_\([0-9][0-9]*\)$/\1/p' | head -n1)" build_num="${build_num:-1}" - # Valid VERSION/BUILD_NUM must pass the recipe (exit 0), proving the - # grep anchors are correctly escaped ($$ -> $) and no shell parse error. - make require-version VERSION=0.0.0 BUILD_NUM="$$build_num" >/dev/null 2>&1 \ - || { echo "require-version rejected a valid VERSION/BUILD_NUM ($$build_num)" >&2; exit 1; } - # Invalid inputs must be rejected with a non-zero exit. - make require-version VERSION=not-a-version BUILD_NUM="$$build_num" 2>/dev/null \ - && { echo 'require-version accepted an invalid VERSION' >&2; exit 1; } - make require-version VERSION=0.0.0 BUILD_NUM=not-a-number 2>/dev/null \ - && { echo 'require-version accepted a non-numeric BUILD_NUM' >&2; exit 1; } + make require-version VERSION=0.0.0 BUILD_NUM="$build_num" >/dev/null 2>&1 \ + || { echo "require-version rejected a valid VERSION/BUILD_NUM ($build_num)" >&2; exit 1; } + if make require-version VERSION=not-a-version BUILD_NUM="$build_num" >/dev/null 2>&1; then + echo 'require-version accepted an invalid VERSION' >&2 + exit 1 + fi + if make require-version VERSION=0.0.0 BUILD_NUM=not-a-number >/dev/null 2>&1; then + echo 'require-version accepted a non-numeric BUILD_NUM' >&2 + exit 1 + fi diff --git a/Makefile b/Makefile index 20a7dc2510..b256c4010d 100644 --- a/Makefile +++ b/Makefile @@ -201,7 +201,7 @@ bootstrap: ## Enter the Nix dev shell (primary toolchain; no-op when already ins echo >&2 "[ERROR] Nix is not installed. Source builds require Nix; install it from https://nixos.org/download/."; \ exit 1; \ else \ - @echo "Entering the Nix dev shell. Run 'make build-macos VERSION=... BUILD_NUM=...' inside it."; \ + echo "Entering the Nix dev shell. Run 'make build-macos VERSION=... BUILD_NUM=...' inside it."; \ exec nix --extra-experimental-features 'nix-command flakes' develop; \ fi @@ -347,11 +347,6 @@ verify-bom: ## Check the local toolchain against stack-bom.toml @bash scripts/bom_values.sh --check @FLUTTER="$(FLUTTER)" "$(DART)" tool/verify_bom.dart --app "$(APP_NAME)" -verify-bom-toolchains: ## Check only the installed toolchain (skip pubspec.lock pins); for CI to run on the runner before the prebuilt image - @[ -n "$(DART)" ] || { echo >&2 "[ERROR] Dart not installed (needed for verify-bom-toolchains). Install Flutter or pass DART=/path/to/dart."; exit 1; } - @bash scripts/bom_values.sh --check - @FLUTTER="$(FLUTTER)" "$(DART)" tool/verify_bom.dart --toolchains - cache-stats: ## Show sccache statistics (hit rate) after a build @command -v sccache >/dev/null 2>&1 || { echo >&2 "[ERROR] sccache not installed."; exit 1; } @sccache --show-stats @@ -437,7 +432,7 @@ ifeq ($(ANDROID_PREBUILTS),0) endif endif # Linux only: SYSTEM_DEPS=1 uses the system libsecret/jsoncpp packages instead of building them (like the CI image). -SYSTEM_DEPS ?= 0 +# SYSTEM_DEPS is defaulted near the top of the file (check-reqs reads it at parse time). ifneq ($(words $(SYSTEM_DEPS)),1) $(error SYSTEM_DEPS must be 0 or 1) endif diff --git a/bm/bench.sh b/bm/bench.sh index 8c3a090807..c459299093 100755 --- a/bm/bench.sh +++ b/bm/bench.sh @@ -143,7 +143,7 @@ echo "" echo "=== All results for $HOST ($ARCH $OS_NAME $OS_VER) ===" printf "%-12s %-20s %-8s %-10s %4s %10s %8s %s\n" DATE MODE COMMIT FLAGS WARM WALL DISK COMMENT printf '%s\n' '──────────────────────────────────────────────────────────────────────────────────────' -tail -n +2 "$OUTFILE" | while IFS=, read -r label branch commit host arch os_name os_ver date warm flags wall_sec success disk_total disk_delta comment; do +tail -n +2 "$OUTFILE" | while IFS=, read -r label _branch commit _host _arch _os_name _os_ver date warm flags wall_sec success _disk_total disk_delta comment; do delta_mb=$((disk_delta / 1024)) w=$((wall_sec)); m=$((w/60)); s=$((w%60)) time_fmt="${m}m${s}s" diff --git a/bm/collect.sh b/bm/collect.sh index 7dfdba73e6..5f4da469ee 100755 --- a/bm/collect.sh +++ b/bm/collect.sh @@ -66,7 +66,8 @@ main() { # Disk directories for d in "${BUILD_DIRS[@]}"; do local path="$REPO_ROOT/$d" - local label="disk_$(echo "$d" | tr '/.' '_')" + local label + label="disk_$(echo "$d" | tr '/.' '_')" if [ -d "$path" ] || [ -f "$path" ]; then local sz sz="$(du -sk "$path" 2>/dev/null | cut -f1 || echo 0)" @@ -79,7 +80,8 @@ main() { # Artifacts for a in "${ARTIFACT_DIRS[@]}"; do local path="$REPO_ROOT/$a" - local label="artifact_$(echo "$a" | tr '/.-' '_')" + local label + label="artifact_$(echo "$a" | tr '/.-' '_')" if [ -e "$path" ]; then local sz sz="$(du -sk "$path" 2>/dev/null | cut -f1 || echo 0)" diff --git a/scripts/app_config/shared/link_assets.sh b/scripts/app_config/shared/link_assets.sh index fab8fe9ece..ff2760bad2 100755 --- a/scripts/app_config/shared/link_assets.sh +++ b/scripts/app_config/shared/link_assets.sh @@ -9,7 +9,8 @@ if [ $# -ne 2 ]; then fi SELECT_ASSETS_DIR=$1 -APP_BUILD_PLATFORM=$2 +# $2 (platform) is required by the callers' interface but no longer changes +# behaviour: Windows is detected from the host (uname), not the target. # declare full paths ASSET_SOURCES_DIR="${APP_PROJECT_ROOT_DIR}/asset_sources" diff --git a/scripts/install_nix.sh b/scripts/install_nix.sh index 4bc14e120e..983238fb37 100755 --- a/scripts/install_nix.sh +++ b/scripts/install_nix.sh @@ -41,16 +41,21 @@ fi INSTALLER="${NIX_INSTALLER:-https://nixos.org/nix/install}" echo "Nix not found on PATH. Installing the multi-user Nix (daemon) from ${INSTALLER}..." -echo "This needs sudo and downloads from the Nix project; it configures /nix/store and the nixbld users." +echo "This downloads a shell script and runs it with sudo; it configures /nix/store and the nixbld users." +echo "The script is not pinned or checksum-verified here. Inspect it first, or install Nix yourself" +echo "(https://nixos.org/download/) and re-run." -# The official installer script. `--daemon` is the recommended multi-user mode -# on macOS: it creates the build users and sets up launchd so `nix` works for -# every user. It prompts for sudo; pass --no-daemon for a single-user install. -if [[ -n "${NIX_INSTALLER_NO_INTERACTIVE:-}" ]]; then - : # allow callers to inject flags, e.g. NIX_INSTALLER_NO_INTERACTIVE=1 +# Never pipe a download into a root shell without an explicit yes. +# NIX_INSTALL_YES=1 skips the prompt for unattended use. +if [[ "${NIX_INSTALL_YES:-0}" != "1" ]]; then + if ! read -r -p "Download and run the Nix installer now? (yes/no): " answer || [[ ! "$answer" =~ ^[Yy][Ee][Ss]$ ]]; then + die "Aborted. Install Nix manually, then re-run." + fi fi -curl --proto '=https' --tlsv1.2 -L "$INSTALLER" | sh -s -- --daemon +# `--daemon` is the recommended multi-user mode on macOS: it creates the build +# users and sets up launchd so `nix` works for every user. It prompts for sudo. +curl --proto '=https' --tlsv1.2 -fL "$INSTALLER" | sh -s -- --daemon # The installer puts nix in ~/.nix-profile/bin, which most login shells source # via .zshrc/.profile. Non-interactive shells (and `make` invoked from an IDE) diff --git a/scripts/tests/verify_bom_parser_test.dart b/scripts/tests/verify_bom_parser_test.dart index b8322ddb33..fa387e218e 100644 --- a/scripts/tests/verify_bom_parser_test.dart +++ b/scripts/tests/verify_bom_parser_test.dart @@ -14,8 +14,7 @@ import '../../tool/bom_parser.dart'; Map section( Map> bom, String name, -) => - bom[name] ?? {}; +) => bom[name] ?? {}; void main() { group('readBom', () { @@ -104,8 +103,10 @@ flutter_min = "3.47.0" final dir = Directory.systemTemp.createTempSync('resolve_path_'); try { File('${dir.path}/mytool').writeAsStringSync('#!/bin/sh\n'); - final found = resolveOnPath('mytool', - environment: {'PATH': '${dir.path}:/nonexistent'}); + final found = resolveOnPath( + 'mytool', + environment: {'PATH': '${dir.path}:/nonexistent'}, + ); expect(found, '${dir.path}/mytool'); } finally { dir.deleteSync(recursive: true); @@ -114,8 +115,10 @@ flutter_min = "3.47.0" test('returns the bare name when the command is not on PATH', () { expect( - resolveOnPath('definitely-not-a-real-command-xyz', - environment: {'PATH': '/nonexistent'}), + resolveOnPath( + 'definitely-not-a-real-command-xyz', + environment: {'PATH': '/nonexistent'}, + ), 'definitely-not-a-real-command-xyz', ); }); @@ -123,10 +126,14 @@ flutter_min = "3.47.0" group('requireSinglePluginsSection', () { test('accepts zero or one [plugins] table', () { - expect(() => requireSinglePluginsSection('[toolchain]\nflutter = "1"\n'), - returnsNormally); - expect(() => requireSinglePluginsSection('[plugins]\na = "b"\n'), - returnsNormally); + expect( + () => requireSinglePluginsSection('[toolchain]\nflutter = "1"\n'), + returnsNormally, + ); + expect( + () => requireSinglePluginsSection('[plugins]\na = "b"\n'), + returnsNormally, + ); }); test('throws on a duplicate [plugins] table', () { @@ -212,7 +219,8 @@ dependencies: test('reads a ref from a CRLF lockfile', () { // A trailing CR must not break the anchored `^ (\w+):$` header. - const lock = 'plugins:\r\n tor_ffi_plugin:\r\n' + const lock = + 'plugins:\r\n tor_ffi_plugin:\r\n' ' resolved-ref: "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"\r\n'; expect( lockRefs(lockText: lock)['tor_ffi_plugin'], diff --git a/tool/bom_parser.dart b/tool/bom_parser.dart index 2303773601..b4c2a330c8 100644 --- a/tool/bom_parser.dart +++ b/tool/bom_parser.dart @@ -20,8 +20,10 @@ const List bomPluginNames = [ const String bomFileName = 'stack-bom.toml'; final RegExp _sectionHeader = RegExp(r'^\[([^\]]+)\][ \t]*(#.*)?$'); -final RegExp _pluginsHeader = - RegExp(r'^\[plugins\][ \t]*(#.*)?$', multiLine: true); +final RegExp _pluginsHeader = RegExp( + r'^\[plugins\][ \t]*(#.*)?$', + multiLine: true, +); /// Minimal TOML reader: `[section]` headers and `key = "value"` lines. /// Accepts tabs or spaces, single or double quotes, and a trailing ` #comment` @@ -137,8 +139,7 @@ Set declaredPlugins({String? pubspecText}) { for (var i = start + 1; i < lines.length; i++) { final line = lines[i]; if (line.trim().isEmpty || line.trimLeft().startsWith('#')) continue; - final currentIndent = RegExp(r'^[ \t]*').firstMatch(line)! - .group(0)!; + final currentIndent = RegExp(r'^[ \t]*').firstMatch(line)!.group(0)!; if (currentIndent.length < indent.length) break; if (currentIndent != indent) continue; final m = RegExp(r'''^[ \t]*["']?(\w+)["']?\s*:''').firstMatch(line); @@ -162,9 +163,7 @@ Map lockRefs({String? lockText}) { final line = lines[i].replaceFirst(RegExp(r'\r$'), ''); final m = RegExp(r'^ (\w+):$').firstMatch(line); if (m == null || !bomPluginNames.contains(m.group(1))) continue; - for (var j = i + 1; - j < lines.length && lines[j].startsWith(' '); - j++) { + for (var j = i + 1; j < lines.length && lines[j].startsWith(' '); j++) { final r = RegExp(r'resolved-ref: "?([0-9a-f]{40})"?') .firstMatch(lines[j]); if (r != null) refs[m.group(1)!] = r.group(1)!; diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart index b3f648aafa..4532628a8a 100644 --- a/tool/verify_bom.dart +++ b/tool/verify_bom.dart @@ -1,17 +1,15 @@ -// Checks the local toolchain and the pinned native plugins against -// stack-bom.toml. +// Checks the local toolchain against stack-bom.toml. +// +// Plugin pins live in pubspec.lock, not in the BOM. The plugin check and +// --update only act on a legacy [plugins] table; stack-bom.toml has none, so +// --plugins checks nothing and exits 0. // // dart tool/verify_bom.dart check, exit 1 on a mismatch -// dart tool/verify_bom.dart --toolchains check only the installed toolchain -// dart tool/verify_bom.dart --plugins check only the pubspec.lock pins +// dart tool/verify_bom.dart --plugins check a legacy [plugins] table against pubspec.lock // dart tool/verify_bom.dart --update refresh an existing [plugins] section from pubspec.lock // // No packages needed, so it runs before `flutter pub get`. // -// CI splits the two: the toolchain check runs on the host runner before the -// prebuilt image is used, because the image's toolchain is frozen until it is -// rebuilt. Raising a minimum (flutter_min / go_min) must therefore fail the -// runner step, not only the in-image step. import 'dart:convert'; import 'dart:io'; @@ -89,8 +87,10 @@ Future _update() async { // Without a pubspec.yaml we cannot tell which app is configured; keep the // old behaviour and update every plugin the lock knows about. final updateable = declared.isEmpty ? bomPluginNames.toSet() : declared; - final header = - RegExp(r'^\[plugins\][ \t]*(#.*)?$', multiLine: true).firstMatch(text); + final header = RegExp( + r'^\[plugins\][ \t]*(#.*)?$', + multiLine: true, + ).firstMatch(text); final start = header?.start ?? -1; if (start < 0 && RegExp(r'\[plugins\]').hasMatch(text)) { stderr.writeln( @@ -215,7 +215,6 @@ Future main(List args) async { _checkPlugins(bom); _finish(); } - final toolchainsOnly = args.contains('--toolchains'); final tc = bom['toolchain'] ?? {}; // Flutter / Dart @@ -238,15 +237,7 @@ Future main(List args) async { } final fl = await _run(flutterExe, ['--version', '--machine']); if (fl == null) { - // In CI the --toolchains check runs on the host runner before the - // prebuilt image is used; the runner has no Flutter (the image does), - // so a missing Flutter is a warning there, not a failure. A plain run - // (local or in-image) still requires it. - if (toolchainsOnly) { - _warn('flutter not found in PATH (expected inside the CI image)'); - } else { - _fail('flutter not found in PATH'); - } + _fail('flutter not found in PATH'); } else { final start = fl.indexOf('{'); final end = fl.lastIndexOf('}'); @@ -286,22 +277,9 @@ Future main(List args) async { final list = await _run('rustup', ['toolchain', 'list']); final rust = tc['rust'] ?? ''; if (list == null) { - // On the CI host runner (pre-image) rustup is not installed — the pinned - // toolchains live in the prebuilt image. A missing rustup is a warning - // there, not a failure. A plain run (local or in-image) still requires it. - if (toolchainsOnly) { - _warn('rustup not found in PATH (expected inside the CI image)'); - } else { - _fail('rustup not found in PATH'); - } + _fail('rustup not found in PATH'); } else if (list.split('\n').any((l) => l.startsWith('$rust-'))) { _ok('Rust $rust installed via rustup'); - } else if (toolchainsOnly) { - // rustup is present but the pinned toolchain is not installed. On the CI - // host runner the pinned toolchains live in the prebuilt image, not in the - // runner's rustup, so a present-but-missing toolchain is a warning there, - // not a failure. A plain run (local or in-image) still requires it. - _warn("Rust $rust not installed via rustup (expected inside the CI image)"); } else { _fail('Rust $rust is not installed (rustup toolchain install $rust)'); } @@ -309,18 +287,9 @@ Future main(List args) async { if (dnssec.isEmpty) { _fail('dnssec_rust is missing from $bomFileName'); } else if (list == null) { - // rustup absent: already reported above (fail locally, warn on the runner). - if (toolchainsOnly) { - _warn('DNSSEC Rust $dnssec not checked (rustup absent; in the CI image)'); - } + // rustup absent: already reported above. } else if (list.split('\n').any((l) => l.startsWith('$dnssec-'))) { _ok('DNSSEC Rust $dnssec installed via rustup'); - } else if (toolchainsOnly) { - // Same as the Rust check above: the pinned DNSSEC toolchain lives in the - // prebuilt image, not the host runner's rustup, so warn rather than fail. - _warn( - "DNSSEC Rust $dnssec not installed via rustup (expected in the CI image)", - ); } else { _fail( 'DNSSEC Rust $dnssec is not installed ' @@ -358,6 +327,6 @@ Future main(List args) async { } } - if (!toolchainsOnly) _checkPlugins(bom); + _checkPlugins(bom); _finish(); } From 28e2bec88c7efd95a2d50f7a4cd0721994df5e0b Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:15:46 +0200 Subject: [PATCH 102/107] fix(make,build): close require-version injection and restore the decline exit code - Makefile: require-version interpolated VERSION and BUILD_NUM into the recipe text, so a value such as `1.0.0'; cmd; echo '`, one containing backticks, or `$(shell ...)` ran as code during validation. The values now reach the shell through the environment (read with $(value ...), and VERSION/BUILD_NUM are no longer exported). BUILD_NUM must be a plain number without leading zeros and at most 9 digits. - build_app.sh: declining the wallet-data warning exits 0 again, as scripts/tests/build_input_test.dart expects (the previous exit 1 failed six of its tests, hidden behind the earlier format failure). The Makefile sets BUILD_APP_DECLINE_EXIT=1 so `make` still stops instead of building an unconfigured project. - docs: the manual/Homebrew prebuilt path does not need bootstrap-macos (which installs Nix); mention the new Nix installer prompt. - flake.nix: drop a stale comment about the removed Homebrew helper. --- Makefile | 23 ++++++++++++++++++----- docs/building/macos.md | 2 +- docs/building/make.md | 2 +- flake.nix | 4 ++-- scripts/build_app.sh | 5 ++++- 5 files changed, 26 insertions(+), 10 deletions(-) diff --git a/Makefile b/Makefile index b256c4010d..7b4b872a1a 100644 --- a/Makefile +++ b/Makefile @@ -19,6 +19,12 @@ CONFIRM ?= 0 # app numbered below the current release line. See `require-version`. VERSION ?= BUILD_NUM ?= +# make would otherwise export these command-line variables to every recipe, +# expanding any `$(shell ...)` inside the value on the way. The recipes use +# them through make, and require-version reads the raw text (see below). +unexport VERSION BUILD_NUM +# build_app.sh exits 0 when the wallet-data warning is declined; make must stop. +export BUILD_APP_DECLINE_EXIT := 1 FLUTTER ?= DART ?= # Make splits unquoted values on whitespace, so a tool path with a space would @@ -223,14 +229,21 @@ endif # --- PREREQUISITES --- +# VERSION and BUILD_NUM reach the shell through the environment, never by +# interpolating them into the recipe text. A value containing a quote or a +# backtick would otherwise run as shell code inside this validation step. +# `$(value ...)` returns the raw text, so a `$(shell ...)` inside the value is +# not expanded by make either. +require-version: export RV_VERSION := $(value VERSION) +require-version: export RV_BUILD_NUM := $(value BUILD_NUM) require-version: ## Fail unless VERSION/BUILD_NUM are valid and BUILD_NUM is not below the latest release tag - @printf '%s' '$(VERSION)' | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z][0-9A-Za-z.-]*)?$$' || { echo >&2 "[ERROR] VERSION must be x.y.z or x.y.z-suffix (got '$(VERSION)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } - @printf '%s' '$(BUILD_NUM)' | grep -Eq '^[0-9]+$$' || { echo >&2 "[ERROR] BUILD_NUM must be numeric (got '$(BUILD_NUM)'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } + @printf '%s' "$$RV_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z][0-9A-Za-z.-]*)?$$' || { echo >&2 "[ERROR] VERSION must be x.y.z or x.y.z-suffix (got '$$RV_VERSION'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } + @printf '%s' "$$RV_BUILD_NUM" | grep -Eq '^(0|[1-9][0-9]{0,8})$$' || { echo >&2 "[ERROR] BUILD_NUM must be a plain number without leading zeros, at most 9 digits (got '$$RV_BUILD_NUM'; latest release tag: $$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | head -n1))."; exit 1; } @latest="$$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | sed -n 's/^build_\([0-9][0-9]*\)$$/\1/p' | head -n1)"; \ if [ -n "$$latest" ]; then \ - [ "$(BUILD_NUM)" -ge "$$latest" ] || { echo >&2 "[ERROR] BUILD_NUM $(BUILD_NUM) is below the latest release tag build_$$latest."; exit 1; }; \ - if [ "$(BUILD_NUM)" -eq "$$latest" ]; then \ - echo "[INFO] Rebuilding release tag build_$$latest with BUILD_NUM=$(BUILD_NUM)."; \ + [ "$$RV_BUILD_NUM" -ge "$$latest" ] || { echo >&2 "[ERROR] BUILD_NUM $$RV_BUILD_NUM is below the latest release tag build_$$latest."; exit 1; }; \ + if [ "$$RV_BUILD_NUM" -eq "$$latest" ]; then \ + echo "[INFO] Rebuilding release tag build_$$latest with BUILD_NUM=$$RV_BUILD_NUM."; \ fi; \ else \ echo "[INFO] No numeric build_* tag found; skipping BUILD_NUM comparison."; \ diff --git a/docs/building/macos.md b/docs/building/macos.md index aedae3b4fb..c21ec3eaf3 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -13,7 +13,7 @@ through Nix: |---|---| | Nix | `make bootstrap` (enters `nix develop`) | | direnv | `direnv allow` | -| Manual / Homebrew | `make bootstrap-macos` (installs Nix + selects Xcode); use `PREBUILTS=1` | +| Manual / Homebrew | install the tools yourself, `make bootstrap-xcode` (selects an installed Xcode), then build with `PREBUILTS=1`. `make bootstrap-macos` additionally installs Nix and is only needed for source builds | With Nix or direnv the flake supplies Flutter, Dart, rustup (which installs the BOM Rust version on first entry), Go, CMake, Meson, Ninja, pkg-config and protoc. diff --git a/docs/building/make.md b/docs/building/make.md index 5531ac580b..87fa3f5d2c 100644 --- a/docs/building/make.md +++ b/docs/building/make.md @@ -56,7 +56,7 @@ make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1 # verified prebuilts ( | `make build-android` | Same build commands as CI, without the AAB/upload steps; signs with `android/key.properties` (run `make android-dev-key` for a throw-away test key), needs the Android SDK/NDK and Java. Prebuilt dnix on macOS, non-x86_64 Linux and brew/manual toolchains; x86_64 Linux in Nix/direnv follows `PREBUILTS` | | `make build-ios` | Same build commands as CI, without signing/packaging, on macOS (`flutter build ios --release --no-codesign`). Source by default only in Nix/direnv on Apple Silicon; CI passes `-d` explicitly | | `make bootstrap` | Enter the Nix dev shell (primary toolchain); no-op when already inside | -| `make bootstrap-macos` | Install Nix (if missing) and check/select the full Xcode.app | +| `make bootstrap-macos` | Install Nix (if missing) and check/select the full Xcode.app. Installing Nix downloads the official installer and runs it with sudo, so it asks first (`NIX_INSTALL_YES=1` skips the question) | | `make toolchain` | Show the active toolchain (`nix`, `direnv`, `host`, `manual`) | | `make bootstrap-xcode` | Check and select an installed full Xcode.app | | `make check-reqs`, `check-reqs-macos`, `check-sdk-macos`, `diagnose-env-macos` | Prerequisite checks and an environment dump | diff --git a/flake.nix b/flake.nix index ba6c1b9365..4d96151614 100644 --- a/flake.nix +++ b/flake.nix @@ -15,8 +15,8 @@ let pkgs = import nixpkgs { inherit system; }; lib = pkgs.lib; - # Single source of truth for the toolchain versions; the Homebrew - # helper and the Makefile read the same file. + # Single source of truth for the toolchain versions; the Makefile, + # the Dockerfile and the release workflow read the same file. bom = builtins.fromTOML (builtins.readFile ./stack-bom.toml); rustVersion = let v = bom.toolchain.rust or (throw "stack-bom.toml: missing [toolchain].rust"); diff --git a/scripts/build_app.sh b/scripts/build_app.sh index eb9f67645a..21e2d3c661 100755 --- a/scripts/build_app.sh +++ b/scripts/build_app.sh @@ -25,7 +25,10 @@ confirmDisclaimer() { fi case $response in [Yy][Ee][Ss] ) echo "Continuing..."; break;; - [Nn][Oo] ) echo >&2 "Aborted."; exit 1;; + # Declining is a normal exit (0) for direct callers and scripts/tests/build_input_test.dart. + # The Makefile sets BUILD_APP_DECLINE_EXIT=1 so `make` stops instead of + # carrying on to `flutter build` with an unconfigured project. + [Nn][Oo] ) echo >&2 "Aborted."; exit "${BUILD_APP_DECLINE_EXIT:-0}";; * ) echo "Invalid response";; esac done From d82b81726873c1d3a99ed3cdf984555e6d373270 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:52:29 +0200 Subject: [PATCH 103/107] fix(linux): provide libsecp256k1 for the coinlib install step without overwriting it 035dd9df0 removed the copy into build/linux//release/secp256k1/lib. On a clean checkout nothing else creates that file, so `make build-linux` (Nix, PREBUILTS=0) failed in coinlib's CMake install step with "file INSTALL cannot find .../secp256k1/lib/libsecp256k1.so". Copy the library there again, but only when it is missing, so a rebuild keeps shipping the same library (the concern behind 035dd9df0). Verified on NixOS x86_64 from a fresh clone: clean build and rebuild both succeed, the bundled libsecp256k1.so has an identical sha256 after the rebuild, and the executable-stack validation passes. docs: the Nix shell currently provides Flutter 3.47.4, not 3.47.2, so verify-bom prints a warning there; say so. --- docs/building/make.md | 2 +- scripts/linux/build_secp256k1.sh | 21 ++++++++++++++++----- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/docs/building/make.md b/docs/building/make.md index 87fa3f5d2c..11eb63b73c 100644 --- a/docs/building/make.md +++ b/docs/building/make.md @@ -72,7 +72,7 @@ uses the host tools on PATH (manual or host), which Homebrew can supply. | Mode | Setup | Notes | |---|---|---| -| Nix | `make bootstrap` (enters `nix develop`) | The flake provides Flutter and Go from its pinned nixpkgs (currently Flutter 3.47.2, matching the BOM, and Go 1.26.7; the BOM's `go` is the CI/Docker pin), Dart, rustup (which installs the BOM Rust version on first entry), CMake, Meson, Ninja, pkg-config and protoc. Xcode always comes from the host. | +| Nix | `make bootstrap` (enters `nix develop`) | The flake provides Flutter and Go from its pinned nixpkgs (currently Flutter 3.47.4 and Go 1.26.7; the BOM recommends Flutter 3.47.2 and pins Go 1.24.13 for CI/Docker, so `make verify-bom` prints a warning for Flutter, not a failure, because 3.47.4 is above the 3.47.2 minimum), Dart, rustup (which installs the BOM Rust version on first entry), CMake, Meson, Ninja, pkg-config and protoc. Xcode always comes from the host. | | direnv | `direnv allow` | The same flake as Nix, loaded automatically. | | Manual / Homebrew | install the tools yourself (Homebrew for the prebuilt path) | Source builds are not available without Nix. Use `PREBUILTS=1` with the verified dnix prebuilts; Homebrew can install the tooling (Flutter, Rust, Go, CocoaPods, sccache, …). `make check-reqs-macos` reports what is missing. | diff --git a/scripts/linux/build_secp256k1.sh b/scripts/linux/build_secp256k1.sh index bd896a7b11..92e6b49d31 100755 --- a/scripts/linux/build_secp256k1.sh +++ b/scripts/linux/build_secp256k1.sh @@ -28,8 +28,19 @@ fi mkdir -p ../../../../../build cp "$SECP_SO" ../../../../../build/libsecp256k1.so -# Do not copy into coinlib's output folder -# (build/linux//release/secp256k1/lib). coinlib builds its own pinned -# libsecp256k1 there; overwriting it made a rebuilt bundle ship a different -# version than a clean build. If that library is missing on a host, fix the -# coinlib build instead of patching its output from here. +# The coinlib CMake install step expects the library inside Flutter's build +# tree (build/linux//release/secp256k1/lib). On a clean checkout nothing +# else puts it there, and the install step fails with "file INSTALL cannot +# find .../secp256k1/lib/libsecp256k1.so". Provide it, but never overwrite a +# library that is already there: a rebuild must keep shipping the same one. +# Match Flutter's architecture directory name (x64, arm64). +case "$(uname -m)" in + x86_64|x64) FLUTTER_ARCH=x64 ;; + aarch64|arm64) FLUTTER_ARCH=arm64 ;; + *) FLUTTER_ARCH="$(uname -m)" ;; +esac +COINLIB_SECP_DIR="../../../../../build/linux/${FLUTTER_ARCH}/release/secp256k1/lib" +mkdir -p "$COINLIB_SECP_DIR" +if [ ! -e "$COINLIB_SECP_DIR/libsecp256k1.so" ]; then + cp "$SECP_SO" "$COINLIB_SECP_DIR/libsecp256k1.so" +fi From b977f96a57149e00d3a9e057b35ccfcbd6016f15 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:56:55 +0200 Subject: [PATCH 104/107] ci,docs: make the make-check policy tests meaningful and correct the PREBUILTS docs - test.yaml: the "brew source mode must fail" check failed because TOOLCHAIN=brew is not a valid value, not because of the source-mode policy, so a policy regression would have gone unnoticed. Each negative case now has to fail with the message of the rule under test, and the default mode (source in a Nix shell, prebuilt on host/Intel/Windows) is asserted positively. Mutating the Makefile policy now fails this step. - docs: PREBUILTS=0 needs an active Nix/direnv shell (nix on PATH is not enough, and host/manual toolchains are rejected); TOOLCHAIN=brew does not exist. Calling scripts/build_app.sh directly still only needs nix on PATH. --- .github/workflows/test.yaml | 38 +++++++++++++++++++++++++------------ README.md | 9 +++++---- docs/building.md | 9 +++++---- docs/building/macos.md | 5 +++-- docs/building/make.md | 21 ++++++++++---------- 5 files changed, 50 insertions(+), 32 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 44436cd71c..fa9b7c28f9 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -167,18 +167,32 @@ jobs: make -n build-windows PLATFORM=MINGW64_NT-10.0 VERSION=0.0.0 BUILD_NUM=1 make -n build-android PLATFORM=Darwin VERSION=0.0.0 BUILD_NUM=1 make -n build-ios PLATFORM=Darwin VERSION=0.0.0 BUILD_NUM=1 - if make -n build-macos PLATFORM=Darwin TOOLCHAIN=brew PREBUILTS=0 VERSION=0.0.0 BUILD_NUM=1 >/dev/null 2>&1; then - echo 'brew source mode must fail' >&2 - exit 1 - fi - if make -n build-linux PLATFORM=Linux TOOLCHAIN=host PREBUILTS=0 VERSION=0.0.0 BUILD_NUM=1 >/dev/null 2>&1; then - echo 'host source mode must fail' >&2 - exit 1 - fi - if make -n build-android PLATFORM=Linux UNAME_M=x86_64 TOOLCHAIN=host ANDROID_PREBUILTS=0 VERSION=0.0.0 BUILD_NUM=1 >/dev/null 2>&1; then - echo 'host Android source mode must fail' >&2 - exit 1 - fi + # A rejection only counts when it comes from the rule under test: an + # unrelated error (for example an invalid TOOLCHAIN value) also makes + # make fail and would let a policy regression through unnoticed. + expect_fail() { + pattern="$1"; shift + if out="$(make -n "$@" VERSION=0.0.0 BUILD_NUM=1 2>&1)"; then + echo "expected failure but succeeded: make -n $*" >&2 + exit 1 + fi + echo "$out" | grep -q -- "$pattern" || { + echo "make -n $* failed for the wrong reason (wanted '$pattern'): $out" >&2 + exit 1 + } + } + expect_fail 'requires an active Nix/direnv shell' build-macos PLATFORM=Darwin UNAME_M=arm64 TOOLCHAIN=manual PREBUILTS=0 + expect_fail 'requires an active Nix/direnv shell' build-linux PLATFORM=Linux TOOLCHAIN=host PREBUILTS=0 + expect_fail 'requires Apple Silicon' build-macos PLATFORM=Darwin UNAME_M=x86_64 IN_NIX_SHELL=1 PREBUILTS=0 + expect_fail 'build-windows uses verified' build-windows PLATFORM=MINGW64_NT-10.0 PREBUILTS=0 + expect_fail 'ANDROID_PREBUILTS=0 requires' build-android PLATFORM=Linux UNAME_M=x86_64 TOOLCHAIN=host ANDROID_PREBUILTS=0 + expect_fail 'TOOLCHAIN must be' build-macos PLATFORM=Darwin TOOLCHAIN=brew + # Mode selection: source only inside a Nix shell on a supported host. + build_line() { make -n "$@" VERSION=0.0.0 BUILD_NUM=1 | grep -E '\./build_app\.sh -' | head -n 1; } + build_line build-linux PLATFORM=Linux UNAME_M=x86_64 IN_NIX_SHELL=1 | grep -qE ' -d( |$)' && { echo 'Nix shell on Linux must default to source' >&2; exit 1; } + build_line build-linux PLATFORM=Linux UNAME_M=x86_64 TOOLCHAIN=host | grep -qE ' -d( |$)' || { echo 'host toolchain must default to prebuilts' >&2; exit 1; } + build_line build-macos PLATFORM=Darwin UNAME_M=x86_64 IN_NIX_SHELL=1 | grep -qE ' -d( |$)' || { echo 'Intel macOS must use prebuilts' >&2; exit 1; } + true # `make -n` never executes recipes, so a shell parse error in the # require-version recipe is invisible to the dry-runs above. Run it for real. # This is a bash step, not a Makefile recipe: use single `$`. diff --git a/README.md b/README.md index 138a5f947b..f96bb6e57c 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,8 @@ selects the full Xcode.app (Xcode is never provided by Nix or Homebrew). Install the prerequisites from [Building on macOS](docs/building/macos.md) yourself, then run `make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1`. -Manual builds default to `PREBUILTS=1`. Pass `PREBUILTS=0` when `nix` is on -`PATH` to build the dnix libraries from source. `make check-reqs-macos` reports -what is missing (`make check-sdk-macos` checks full Xcode); `TOOLCHAIN=manual` -makes the choice explicit. +Manual builds always use `PREBUILTS=1`: `make` rejects `PREBUILTS=0` outside an +active Nix/direnv shell, even when `nix` is on `PATH`. To build the dnix +libraries from source, use `make bootstrap` (or direnv) instead. +`make check-reqs-macos` reports what is missing (`make check-sdk-macos` checks +full Xcode); `TOOLCHAIN=manual` makes the choice explicit. diff --git a/docs/building.md b/docs/building.md index c236540c81..e75bbf5f4c 100644 --- a/docs/building.md +++ b/docs/building.md @@ -44,10 +44,11 @@ either mode. To switch modes, rerun `build_app.sh`. It regenerates `pubspec.yaml`, so keep permanent changes in `scripts/app_config/templates/pubspec.template.yaml`. -The `Makefile` selects the mode by toolchain: on Apple Silicon macOS and -Linux, `TOOLCHAIN=nix`/`direnv` defaults to source when `nix` is on `PATH`; -`brew`, `host`, `manual` and Windows default to `PREBUILTS=1` -(prebuilt). Any toolchain can pass `PREBUILTS=0` when `nix` is on `PATH`. +The `Makefile` selects the mode by toolchain: inside an active Nix/direnv shell +on Apple Silicon macOS and Linux it defaults to source; `host`, `manual`, +Intel macOS and Windows use `PREBUILTS=1` (prebuilt). `PREBUILTS=0` is rejected +outside a Nix/direnv shell, even when `nix` is on `PATH`; calling +`scripts/build_app.sh` directly (without `-d`) only needs `nix` on `PATH`. ## Configuration options diff --git a/docs/building/macos.md b/docs/building/macos.md index c21ec3eaf3..44ab8069ce 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -40,8 +40,9 @@ rustup target add --toolchain "$RUST_BOM" aarch64-apple-darwin x86_64-apple-darw aarch64-apple-ios aarch64-apple-ios-sim ``` -Homebrew and manual toolchains default to `PREBUILTS=1`. Pass `PREBUILTS=0` -when `nix` is on `PATH` to build the dnix libraries from source. +Homebrew and manual toolchains use `PREBUILTS=1`; `make` rejects `PREBUILTS=0` +outside a Nix/direnv shell. Calling `scripts/build_app.sh` directly without `-d` +builds the dnix libraries from source when `nix` is on `PATH`. Check `nix --version` from the same environment that runs Flutter, and use `flutter doctor` to check the Apple SDK and CocoaPods setup. iOS device builds diff --git a/docs/building/make.md b/docs/building/make.md index 11eb63b73c..8599da891c 100644 --- a/docs/building/make.md +++ b/docs/building/make.md @@ -28,18 +28,19 @@ that is not above the latest `build_*` tag. `APP_NAME` selects the app variant |---|---|---| | `VERSION`, `BUILD_NUM` | required | App version and a build number above the latest release tag | | `APP_NAME` | `stack_wallet` | `stack_wallet`, `stack_duo` or `campfire` | -| `PREBUILTS` | `0` on Apple Silicon/Linux when `nix` is on `PATH`; otherwise `1` | `0` builds dnix from source (needs `nix`); `1` uses verified prebuilts (`-d`) | -| `ANDROID_PREBUILTS` | follows `PREBUILTS` on x86_64 Linux when `nix` is on `PATH`, else `1` | Overrides the Android dnix mode | +| `PREBUILTS` | `0` in an active Nix/direnv shell on Apple Silicon/Linux; otherwise `1` | `0` builds dnix from source (needs a Nix/direnv shell); `1` uses verified prebuilts (`-d`) | +| `ANDROID_PREBUILTS` | follows `PREBUILTS` on x86_64 Linux in a Nix/direnv shell, else `1` | Overrides the Android dnix mode | | `SYSTEM_DEPS` | `0` | Linux: `1` uses system libsecret/JsonCPP (as CI does) | -| `TOOLCHAIN` | `auto` | `auto`, `nix`, `direnv`, `brew`, `host` or `manual` | +| `TOOLCHAIN` | `auto` | `auto`, `nix`, `direnv`, `host` or `manual` | | `CONFIRM` | `0` | `1` answers build_app.sh's wallet-data warning non-interactively | -Source mode needs `nix` on `PATH`, whichever toolchain provides the rest of -the build tools. On Apple Silicon macOS and Linux, `PREBUILTS=0` is the -default when `nix` is available: dnix builds the pinned native libraries from -source and verifies their hashes. Without `nix`, the Makefile defaults to -`PREBUILTS=1`; Homebrew, manual and host toolchains can still pass -`PREBUILTS=0` when `nix` is on `PATH`. CI passes `-d` explicitly. +Source mode needs an active Nix/direnv shell (`nix develop` or direnv): the +shell supplies the dnix libraries and the toolchain, so `nix` merely being on +`PATH` is not enough. On Apple Silicon macOS and Linux, `PREBUILTS=0` is the +default inside such a shell: dnix builds the pinned native libraries from +source and verifies their hashes. Everywhere else the Makefile uses +`PREBUILTS=1` and rejects an explicit `PREBUILTS=0` (host and manual +toolchains, Intel macOS, Windows). CI passes `-d` explicitly. ``` make build-macos VERSION=x.y.z BUILD_NUM=nnn # dnix source (Nix/direnv, Apple Silicon) @@ -77,7 +78,7 @@ uses the host tools on PATH (manual or host), which Homebrew can supply. | Manual / Homebrew | install the tools yourself (Homebrew for the prebuilt path) | Source builds are not available without Nix. Use `PREBUILTS=1` with the verified dnix prebuilts; Homebrew can install the tooling (Flutter, Rust, Go, CocoaPods, sccache, …). `make check-reqs-macos` reports what is missing. | `make toolchain` prints the active mode and tool paths. -`TOOLCHAIN=nix|direnv` forces a check; `host` and `manual` use whatever is on `PATH`; `auto` (the default) detects a Nix/direnv shell and otherwise uses the host tools. Any toolchain can use `PREBUILTS=0` when `nix` is on `PATH`; without it the Makefile defaults to prebuilt mode. +`TOOLCHAIN=nix|direnv` forces a check; `host` and `manual` use whatever is on `PATH`; `auto` (the default) detects a Nix/direnv shell and otherwise uses the host tools. `PREBUILTS=0` needs `nix` or `direnv` as the effective toolchain; `host` and `manual` always build from the verified prebuilts. `make check-reqs-macos` verifies the result and `make diagnose-env-macos` prints what was found. From 000877625c8e215100931e8c32af6f6acd89e56a Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 22 Nov 2026 07:06:07 +0200 Subject: [PATCH 105/107] fix(bm): make the benchmark helpers actually run, record failures, stop installing packages - bench.sh: the README call (no VERSION/BUILD_NUM) failed in require-version, and build_app.sh would have asked its interactive question. Default to VERSION=0.0.0, the latest release tag as BUILD_NUM and CONFIRM=1 unless the caller passes their own; the CSV flags column keeps only the caller's flags. - bench.sh: `make ... | tail; RC=$?` recorded tail's status and `set -e` aborted before any row was written, so a failed build never reached the CSV and the "Build FAILED" branch was unreachable. Take make's status from PIPESTATUS and always write the row (success=0). - bench.sh, run_all.sh: toilet/figlet were hard, undocumented dependencies (the script died with "command not found"); fall back to plain text. - render.sh: stop running `pip3 install --break-system-packages weasyprint` behind the user's back, use mktemp instead of a fixed /tmp file, and only open the report when --open is given (the `&& ... ||` chain opened the HTML file regardless). --- bm/bench.sh | 42 +++++++++++++++++++++++++++++++++--------- bm/render.sh | 22 +++++++++++++++------- bm/run_all.sh | 20 +++++++++++++------- 3 files changed, 61 insertions(+), 23 deletions(-) diff --git a/bm/bench.sh b/bm/bench.sh index c459299093..923b1d3320 100755 --- a/bm/bench.sh +++ b/bm/bench.sh @@ -13,6 +13,12 @@ set -euo pipefail HOST="$(hostname -s 2>/dev/null || echo unknown)" + +# Pretty banners when toilet is installed; plain text otherwise. +banner() { + if command -v toilet >/dev/null 2>&1; then toilet -f term --metal; else cat; fi +} + OUTDIR="bm/results" mkdir -p "$OUTDIR" OUTFILE="${OUTDIR}/${HOST}.csv" @@ -63,7 +69,7 @@ DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)" ARCH="$(uname -m)" OS_NAME="$(uname -s)" OS_VER="$(uname -r)" -echo "Benchmark: ${LABEL}" | toilet -f term --metal +echo "Benchmark: ${LABEL}" | banner echo "Host: $HOST" echo "OS: $OS_NAME $OS_VER ($ARCH)" echo "Branch: $BRANCH" @@ -77,7 +83,7 @@ DISK_BEFORE=$(du -sk . 2>/dev/null | cut -f1) # Clean unless warm if [ $WARM -eq 0 ]; then - echo "Cleaning" | toilet -f term --metal + echo "Cleaning" | banner make clean 2>&1 | tail -1 fi @@ -110,11 +116,30 @@ restore_sccache() { } trap restore_sccache EXIT -# Build -echo "Building: make ${BUILD_TARGET} ${MAKE_FLAGS} " | toilet -f term --metal +# The Makefile requires VERSION and a BUILD_NUM that is not below the latest +# release tag, and build_app.sh asks an interactive question unless CONFIRM=1. +# Supply benchmark defaults unless the caller passed their own; they are not +# written to the CSV "flags" column, which keeps only what the caller asked for. +BENCH_FLAGS="" +case " ${MAKE_FLAGS} " in *" VERSION="*) ;; *) BENCH_FLAGS="${BENCH_FLAGS} VERSION=0.0.0" ;; esac +case " ${MAKE_FLAGS} " in + *" BUILD_NUM="*) ;; + *) + LATEST_TAG_NUM="$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | sed -n 's/^build_\([0-9][0-9]*\)$/\1/p' | head -n1)" + BENCH_FLAGS="${BENCH_FLAGS} BUILD_NUM=${LATEST_TAG_NUM:-1}" + ;; +esac +case " ${MAKE_FLAGS} " in *" CONFIRM="*) ;; *) BENCH_FLAGS="${BENCH_FLAGS} CONFIRM=1" ;; esac + +# Build. A failing build must be recorded (success=0), so do not let `set -e` +# abort on the pipeline, and take make's status, not tail's. +echo "Building: make ${BUILD_TARGET} ${MAKE_FLAGS}${BENCH_FLAGS} " | banner START=$(date +%s) -make ${BUILD_TARGET} ${MAKE_FLAGS} 2>&1 | tail -5 -RC=$? +set +e +# shellcheck disable=SC2086 +make ${BUILD_TARGET} ${MAKE_FLAGS} ${BENCH_FLAGS} 2>&1 | tail -5 +RC=${PIPESTATUS[0]} +set -e END=$(date +%s) WALL=$((END - START)) @@ -132,12 +157,11 @@ echo "${LABEL},${BRANCH},${COMMIT},${HOST},${ARCH},${OS_NAME},${OS_VER},${DATE}, echo "" if [ $RC -eq 0 ]; then MIN=$((WALL/60)); SEC=$((WALL%60)) - echo "✓ Build succeeded in ${WALL}s \(${MIN}m ${SEC}s\)" + echo "✓ Build succeeded in ${WALL}s (${MIN}m ${SEC}s)" else echo "✗ Build FAILED after ${WALL}s" fi -echo "Results appended: $OUTFILE" | toilet -f term --metal - +echo "Results appended: $OUTFILE" | banner # Show all runs echo "" echo "=== All results for $HOST ($ARCH $OS_NAME $OS_VER) ===" diff --git a/bm/render.sh b/bm/render.sh index b27d83256f..b5868c59f9 100755 --- a/bm/render.sh +++ b/bm/render.sh @@ -22,18 +22,20 @@ CSS_FILE="$SCRIPT_DIR/report.css" # Convert to HTML echo "=== Markdown → HTML ===" +# A private temp file, not a fixed name in /tmp that another user could pre-create. +CSS_HEADER="$(mktemp "${TMPDIR:-/tmp}/bm_css.XXXXXX")" +trap 'rm -f "$CSS_HEADER"' EXIT { echo '' -} > /tmp/_bm_css.html +} > "$CSS_HEADER" pandoc "$MD_FILE" \ --standalone \ --metadata title="Stack Wallet: Build Benchmark Report" \ - --include-in-header /tmp/_bm_css.html \ + --include-in-header "$CSS_HEADER" \ -o "$HTML_FILE" -rm -f /tmp/_bm_css.html echo " → $HTML_FILE" # Convert to PDF @@ -42,8 +44,6 @@ pdf_ok=0 if command -v weasyprint >/dev/null 2>&1; then weasyprint "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 -elif pip3 install --break-system-packages weasyprint 2>/dev/null; then - weasyprint "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 elif command -v wkhtmltopdf >/dev/null 2>&1; then wkhtmltopdf --enable-local-file-access "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 elif [ "$(uname -s)" = "Darwin" ]; then @@ -53,9 +53,17 @@ fi if [ "$pdf_ok" -eq 1 ] && [ -f "$PDF_FILE" ]; then echo " → $PDF_FILE" else - echo " ⚠ No PDF engine found. HTML ready: $HTML_FILE" + echo " ⚠ No PDF engine found (install weasyprint or wkhtmltopdf yourself; this script" + echo " never installs packages). HTML ready: $HTML_FILE" fi -[ "$OPEN" -eq 1 ] && open "$PDF_FILE" 2>/dev/null || open "$HTML_FILE" 2>/dev/null || true +# Open only when asked, and prefer the PDF. +if [ "$OPEN" -eq 1 ]; then + if [ "$pdf_ok" -eq 1 ] && [ -f "$PDF_FILE" ]; then + open "$PDF_FILE" 2>/dev/null || true + else + open "$HTML_FILE" 2>/dev/null || true + fi +fi echo "Done." \ No newline at end of file diff --git a/bm/run_all.sh b/bm/run_all.sh index 5182705e71..f7519e0da2 100755 --- a/bm/run_all.sh +++ b/bm/run_all.sh @@ -13,39 +13,45 @@ set -euo pipefail HOST="$(hostname -s 2>/dev/null || echo unknown)" -figlet "Stack Wallet" + +# Pretty banners when figlet/toilet are installed; plain text otherwise. +big() { if command -v figlet >/dev/null 2>&1; then figlet "$1"; else echo "== $1 =="; fi; } +banner() { + if command -v toilet >/dev/null 2>&1; then toilet -f term -F border --gay; else cat; fi +} +big "Stack Wallet" echo " Full Benchmark Suite" echo " Host: $HOST " echo " $(date)" echo "" -echo "Cold build (no sccache)" | toilet -f term -F border --gay +echo "Cold build (no sccache)" | banner make clean 2>/dev/null || true bash bm/bench.sh --label cold-nosccache SCCACHE=0 echo "" -echo "Warm after cold no-sccache (CARGO_TARGET_DIR only)" | toilet -f term -F border --gay +echo "Warm after cold no-sccache (CARGO_TARGET_DIR only)" | banner echo "━━━ B: Warm rebuild (no sccache, CARGO_TARGET_DIR cache hit) ━━━" bash bm/bench.sh --warm --label warm-nosccache SCCACHE=0 echo "" -echo "Cold with sccache" | toilet -f term -F border --gay +echo "Cold with sccache" | banner make clean 2>/dev/null || true bash bm/bench.sh --label cold-sccache SCCACHE=1 echo "" -echo "Warm after cold sccache (sccache + target dir)" | toilet -f term -F border --gay +echo "Warm after cold sccache (sccache + target dir)" | banner echo "━━━ D: Warm rebuild (sccache + CARGO_TARGET_DIR cache hit) ━━━" bash bm/bench.sh --warm --label warm-sccache SCCACHE=1 echo "" -echo "Cold build (Dart only, SKIP_NATIVE=1)" | toilet -f term -F border --gay +echo "Cold build (Dart only, SKIP_NATIVE=1)" | banner make clean 2>/dev/null || true bash bm/bench.sh --label cold-dart-only SKIP_NATIVE=1 echo "" -echo "Warm Dart-only" | toilet -f term -F border --gay +echo "Warm Dart-only" | banner bash bm/bench.sh --warm --label warm-dart-only SKIP_NATIVE=1 echo "" From 900bd5a3d2c775717dc56df3717f392187455af2 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 22 Nov 2026 07:08:54 +0200 Subject: [PATCH 106/107] docs(linux): source mode with make needs an active Nix/direnv shell --- docs/building/linux.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/building/linux.md b/docs/building/linux.md index 1f004ccdb2..b5abc2b563 100644 --- a/docs/building/linux.md +++ b/docs/building/linux.md @@ -14,7 +14,10 @@ These steps build the Linux desktop app and the Android app on Ubuntu 24.04 | [Nix](https://nixos.org/download/) | Source mode (`PREBUILTS=0`); not needed with `-d` | | The [Android tools](#android-tools) below | Android builds | -Source mode needs `nix` on `PATH`; without Nix, use `PREBUILTS=1` (prebuilt). +With `make`, source mode (`PREBUILTS=0`) needs an active Nix/direnv shell +(`make bootstrap` or direnv), not just `nix` on `PATH`; outside such a shell +`make` uses `PREBUILTS=1` (prebuilt) and rejects `PREBUILTS=0`. `build_app.sh` +called directly only needs `nix` on `PATH` for source mode. A bundle built inside the Nix shell links against Nix's glibc and uses a `/nix/store` ELF interpreter and RUNPATH, so it runs only on that machine. Use From 5dfd6019c72d9f25b1f6c3363acdf0dc58ba2cd6 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 22 Nov 2026 07:17:44 +0200 Subject: [PATCH 107/107] docs(macos): read the DNSSEC Rust version from the BOM instead of hardcoding it --- docs/building/macos.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/building/macos.md b/docs/building/macos.md index 44ab8069ce..4df001f194 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -34,8 +34,9 @@ manual/Homebrew (prebuilt) path. ```sh RUST_BOM="$(scripts/bom_values.sh --get rust)" +DNSSEC_RUST_BOM="$(scripts/bom_values.sh --get dnssec_rust)" brew install autoconf automake libtool cmake cocoapods go meson ninja pkg-config protobuf -rustup toolchain install 1.90.0 "$RUST_BOM" +rustup toolchain install "$DNSSEC_RUST_BOM" "$RUST_BOM" rustup target add --toolchain "$RUST_BOM" aarch64-apple-darwin x86_64-apple-darwin \ aarch64-apple-ios aarch64-apple-ios-sim ```