From c7bbd77e815d4de986751c7b7dd19a3ddc2cf8a2 Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 22 Nov 2026 07:56:01 +0200 Subject: [PATCH 1/2] build: Nix flake and make targets for reproducible local builds A Nix flake is the toolchain and a Makefile wraps scripts/build_app.sh and `flutter build`. Every build needs Nix: the four dnix packages are either compiled from source (PREBUILTS=0, the default on Apple Silicon and Linux) or taken as verified prebuilts (PREBUILTS=1). Windows (Git Bash) has no Nix and always uses the prebuilts. Flake - flake.nix, flake.lock and .envrc (`use flake`) provide Flutter, Go, rustup, sccache, CMake, Meson, Ninja, pkg-config, protoc and the Linux/macOS build dependencies for Apple Silicon macOS and Linux. - On Linux the shell drops mkShell's `-rpath $out/lib` from NIX_LDFLAGS, which would otherwise put the checkout path into every binary's RUNPATH. - The versions are written down once, at the top of flake.nix: the two Rust toolchains (installed by the shell on first entry) and the Xcode that dnix source builds need. The shell exports them as STACK_*_VERSION for the Makefile. Makefile - build-macos, build-ios, build-linux, build-windows, build-android. - Without an active Nix shell make stops and says what to run; there is no escape hatch except Windows. - VERSION and BUILD_NUM are required; BUILD_NUM may not be below the latest build_* tag. Both reach the shell through the environment, never by interpolation into the recipe text. - bootstrap-nix installs Nix on macOS and on Linux (multi-user with systemd, else single-user; asks before running the downloaded installer as root) and enables the nix-command and flakes features. - Requirements on macOS: bootstrap-macos (bootstrap-nix plus a full Xcode), bootstrap-xcode, the opt-in bootstrap-xcode-download (archive.org, SHA-1 and Apple signature checked, refuses CI, aborts on a mismatch before it extracts anything), check-reqs*, check-sdk-macos (also requires the pinned Xcode for source builds) and diagnose-env-macos. - clean, clean-app, clean-native, sccache-setup and cache-stats. - CONFIRM=1 answers the wallet-data prompt of build_app.sh; the Makefile also sets BUILD_APP_DECLINE_EXIT=1 so declining stops make. Scripts - build_app.sh: EOF on the confirmation prompt aborts instead of looping; declining exits with $BUILD_APP_DECLINE_EXIT (default 0, as before). - configure_campfire.sh, android and ios platform_config.sh: `sed -i.bak` works with BSD sed and the GNU sed the Nix shell puts first on PATH. - linux: build_secure_storage_deps.sh generates a pkg-config file for the locally built libsecret (the tracked one hardcoded /usr/local) and build_secp256k1.sh provides the library coinlib's CMake install step expects, without overwriting an existing one. Benchmarks (bm/, plain text) - bench.sh: cold/warm, --clean app|native|full, --sccache on|off (the cargo config is restored afterwards, also after a crash), sccache hit/miss counters; matrix.sh runs six standard scenarios; report.sh prints the table. CI: a make-check job validates the Makefile (dry-runs, the Nix requirement and the source-mode policy with the reason for each rejection, and a real run of require-version). Docs: docs/building/make.md, including how Linux is built and why a Nix-built bundle is for the machine that built it, not for distribution. --- .envrc | 6 + .github/workflows/test.yaml | 75 +++ .gitignore | 14 + Makefile | 533 ++++++++++++++++++ bm/README.md | 34 ++ bm/bench.sh | 103 ++++ bm/matrix.sh | 24 + bm/report.sh | 21 + docs/building.md | 3 + docs/building/make.md | 105 ++++ flake.lock | 61 ++ flake.nix | 279 +++++++++ scripts/app_config/configure_campfire.sh | 15 +- .../platforms/android/platform_config.sh | 32 +- .../platforms/ios/platform_config.sh | 9 +- scripts/build_app.sh | 13 +- scripts/download_xcode.sh | 288 ++++++++++ scripts/install_nix.sh | 80 +++ scripts/install_xcode.sh | 90 +++ scripts/linux/build_secp256k1.sh | 37 +- scripts/linux/build_secure_storage_deps.sh | 36 +- scripts/linux/pc/libsecret-1.pc | 15 - 22 files changed, 1815 insertions(+), 58 deletions(-) create mode 100644 .envrc create mode 100644 Makefile create mode 100644 bm/README.md create mode 100755 bm/bench.sh create mode 100755 bm/matrix.sh create mode 100755 bm/report.sh create mode 100644 docs/building/make.md create mode 100644 flake.lock create mode 100644 flake.nix create mode 100755 scripts/download_xcode.sh create mode 100755 scripts/install_nix.sh create mode 100755 scripts/install_xcode.sh delete mode 100644 scripts/linux/pc/libsecret-1.pc diff --git a/.envrc b/.envrc new file mode 100644 index 0000000000..5de0dba01a --- /dev/null +++ b/.envrc @@ -0,0 +1,6 @@ +# The Nix flake is the toolchain: direnv loads the same shell as `nix develop`. +# Without Nix, leave the shell alone; `make bootstrap-macos` installs it on a Mac. +if has nix; then + watch_file flake.nix flake.lock + use flake . --no-write-lock-file +fi diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 25dcc8495d..54815af06e 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -134,3 +134,78 @@ 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 + with: + fetch-depth: 0 # tags: require-version compares BUILD_NUM with build_* tags + - name: Check the Makefile dry-runs + run: | + if grep -nE '^[^#]*\$\(MAKE\)|^[[:space:]]*\+' Makefile; then + echo 'Makefile uses a construct that 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 + 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 + # 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 the Nix dev shell' build-macos PLATFORM=Darwin UNAME_M=arm64 PREBUILTS=0 + expect_fail 'requires the Nix dev shell' build-linux PLATFORM=Linux 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 ANDROID_PREBUILTS=0 + # Every build needs Nix: without a Nix shell toolchain-check stops with an + # explanation, inside one (IN_NIX_SHELL) it passes, and Windows (Git Bash) is exempt. + for plat in Linux Darwin; do + if out="$(make toolchain-check PLATFORM=$plat UNAME_M=arm64 2>&1)"; then echo "$plat without Nix must fail" >&2; exit 1; fi + echo "$out" | grep -q 'No Nix shell is active' || { echo "wrong reason on $plat: $out" >&2; exit 1; } + make toolchain-check PLATFORM=$plat UNAME_M=arm64 IN_NIX_SHELL=1 >/dev/null + done + make toolchain-check PLATFORM=MINGW64_NT-10.0 >/dev/null + if out="$(make toolchain-check PLATFORM=Darwin UNAME_M=x86_64 IN_NIX_SHELL=1 2>&1)"; then echo 'Intel macOS has no Nix shell' >&2; exit 1; fi + # 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 | grep -qE ' -d( |$)' || { echo 'outside the Nix shell the default must be 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 `$`. + - name: require-version recipe executes (valid passes, invalid fails) + run: | + # 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}" + 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/.gitignore b/.gitignore index 1b5b2b46cc..a949f2f668 100644 --- a/.gitignore +++ b/.gitignore @@ -120,3 +120,17 @@ lib/wl_gen/generated/ /assets/windows/mwebd.exe /tool/build + +# Nix / direnv and local build state for `make` +.direnv/ +/.cargo/config.toml +/scripts/linux/pc/ + +# Android local signing (make android-dev-key) +/android/key.properties +/android/dev-keystore.jks +/android/keystore.jks +/android/keystore-orig.jks + +# Benchmark results (bm/bench.sh) +/bm/results/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000..61a5235a66 --- /dev/null +++ b/Makefile @@ -0,0 +1,533 @@ +# ============================================================================== +# Stack Wallet build helper. Wraps scripts/build_app.sh; see docs/building/make.md +# Usage: make VERSION=x.x.x BUILD_NUM=xxx +# ============================================================================== + +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 +# 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 ?= +# 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 ?= +FLUTTER_USER := $(strip $(FLUTTER)) +FLUTTER_BIN := $(if $(FLUTTER),$(if $(findstring /,$(FLUTTER)),$(abspath $(FLUTTER)),$(FLUTTER)),$(shell command -v flutter 2>/dev/null)) +FLUTTER := $(FLUTTER_BIN) +# A Flutter found on PATH under a directory such as "Application Support" would +# be split by make on the space and resolve to a different path. +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 +SYSTEM_DEPS ?= 0 +# Child scripts call bare `flutter`/`dart`; keep them on the binaries checked +# 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 +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) +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) + ifeq ($(filter MINGW% MSYS%,$(PLATFORM)),) + $(error Unsupported PLATFORM '$(PLATFORM)'; expected Darwin, Linux or Git Bash on Windows) + endif + endif +endif +# Every build needs Nix: the flake is the toolchain, whether the four dnix packages are +# built from source (PREBUILTS=0) or taken as verified prebuilts (PREBUILTS=1). The one +# exception is Windows (Git Bash), which has no Nix and always uses the prebuilts. +NIX_ACTIVE := $(if $(or $(IN_NIX_SHELL),$(NIX_STORE)),1,) +NIX_REQUIRED := $(if $(filter MINGW% MSYS%,$(PLATFORM)),,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 +# 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 command -v protoc 2>/dev/null) +# Rust toolchains checked by `make check-reqs`. Native-assets crates pick their +# own pinned toolchain via rust-toolchain.toml; do not export RUSTUP_TOOLCHAIN. +# The pinned versions are defined once, in flake.nix, and exported by the dev shell. +RUST_VERSION ?= $(STACK_RUST_VERSION) +DNSSEC_RUST_VERSION ?= $(STACK_DNSSEC_RUST_VERSION) +XCODE_VERSION ?= $(STACK_XCODE_VERSION) +# Strip the Nix/Apple variables the dev shell sets before running the app build. +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 = $(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 +ifneq ($(strip $(PUB_CACHE)),) +export PUB_CACHE +endif + +.PHONY: help toolchain toolchain-check bootstrap bootstrap-nix bootstrap-macos bootstrap-xcode bootstrap-xcode-download require-version check-reqs check-reqs-macos check-sdk-macos check-linux check-windows sccache-setup cache-stats clean clean-app clean-native diagnose-env-macos build-macos build-linux build-windows build-android android-dev-key build-ios + +help: ## Show available commands + @echo "Available targets:" + @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' "$(firstword $(MAKEFILE_LIST))" | awk 'BEGIN {FS = ":.*?## "}; {printf "%-24s %s\n", $$1, $$2}' + +# --- TOOLCHAIN --- + +toolchain: ## Show whether the Nix shell is active, the pinned versions and the tool paths + @echo "nix shell : $(if $(NIX_ACTIVE),active,not active)" + @echo "pinned : rust $(or $(RUST_VERSION),-), dnssec rust $(or $(DNSSEC_RUST_VERSION),-), xcode $(or $(XCODE_VERSION),-)" + @echo "flutter : $(if $(FLUTTER),$(FLUTTER),missing)" + @echo "rustup : $$(command -v rustup || echo missing)" + @echo "sccache : $$(command -v sccache || echo missing)" +ifeq ($(PLATFORM),Darwin) + @echo "xcode : $$(xcode-select -p 2>/dev/null || echo missing)" +endif + +toolchain-check: ## Fail unless the Nix dev shell is active (Windows/Git Bash is exempt) +ifeq ($(NIX_REQUIRED),1) +ifeq ($(PLATFORM)$(filter arm64 aarch64,$(UNAME_M)),Darwin) + @echo >&2 "[ERROR] The flake supports Apple Silicon macOS and Linux; Intel macOS has no Nix shell."; exit 1 +endif + @[ -n "$$NIX_STORE$$IN_NIX_SHELL" ] || { \ + echo >&2 "[ERROR] No Nix shell is active. Builds need Nix: run 'make bootstrap' (or 'direnv allow')."; \ + echo >&2 " Nix is not installed yet? 'make bootstrap-nix' installs it (macOS: 'make bootstrap-macos' adds Xcode)."; \ + exit 1; } +else + @echo "[INFO] Windows (Git Bash): no Nix; using the tools on PATH and the verified prebuilts." +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."; \ + elif [ "$(PLATFORM)" = "Darwin" ] && [ "$(UNAME_M)" != "arm64" ] && [ "$(UNAME_M)" != "aarch64" ]; then \ + echo >&2 "[ERROR] The flake supports Apple Silicon macOS and Linux; Intel macOS has no Nix shell."; \ + exit 1; \ + elif ! command -v nix >/dev/null 2>&1; then \ + echo >&2 "[ERROR] Nix is not installed. Every build needs Nix: run '"'"'make bootstrap-nix'"'"' (or see 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; \ + fi + +check-linux: ## Fail unless the host is Linux +ifeq ($(PLATFORM),Linux) + @: +else + @echo >&2 "[ERROR] build-linux is Linux-only." + @exit 1 +endif + +check-windows: ## Fail unless running from Git Bash on Windows +ifeq ($(filter MINGW% MSYS%,$(PLATFORM)),) + @echo >&2 "[ERROR] build-windows must run from Git Bash on Windows." + @exit 1 +else + @: +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' "$$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 \ + [ "$$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."; \ + fi + +check-reqs: toolchain-check ## Verify essential build tools + @echo "Checking core prerequisites..." + @[ -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; } + @command -v rustup >/dev/null 2>&1 || { echo >&2 "[ERROR] rustup not installed."; 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; } +# 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; } +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 +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; } + @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!" + +check-sdk-macos: ## Verify XCode on macOS +ifeq ($(PLATFORM),Darwin) + @echo "Checking macOS SDK requirements..." + @dev="$${DEVELOPER_DIR:-$$(xcode-select -p 2>/dev/null || true)}"; \ + case "$$dev" in \ + *.app/Contents/Developer) ;; \ + *) echo >&2 "[ERROR] Full Xcode is required (DEVELOPER_DIR or xcode-select -p = $$dev). Install Xcode and select it with: sudo xcode-select -s /Applications/Xcode.app/Contents/Developer"; 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) + @echo "[OK] macOS SDK available at: $$(xcrun --sdk macosx --show-sdk-path)" + @if [ "$(PREBUILTS)" = "0" ]; then \ + pin="$(XCODE_VERSION)"; found=0; \ + for app in /Applications/Xcode*.app; do \ + [ -x "$$app/Contents/Developer/usr/bin/xcodebuild" ] || continue; \ + [ "$$(DEVELOPER_DIR="$$app/Contents/Developer" xcodebuild -version 2>/dev/null | sed -n 's/^Xcode \([0-9.]*\).*/\1/p' | head -n1)" = "$$pin" ] && found=1; \ + done; \ + [ "$$found" = 1 ] || { echo >&2 "[ERROR] dnix source builds (PREBUILTS=0) need Xcode $$pin in /Applications (it need not be selected). Install it: make bootstrap-xcode-download XCODE_VERSION=$$pin"; exit 1; }; \ + echo "[OK] Xcode $$pin is installed for dnix source builds."; \ + fi +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 'rustup toolchain install $(RUST_VERSION)', or use 'nix develop'."; 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-nix: ## Install Nix (macOS or Linux; asks before running the downloaded installer as root) + @bash scripts/install_nix.sh + +bootstrap-macos: ## Install Nix + check/select the full Xcode.app (source-build bootstrap) +ifeq ($(PLATFORM),Darwin) +# 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); 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." + @exit 1 +endif + +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 + @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 ?= $(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 is not installed (it is part of the Nix dev shell: make bootstrap)."; 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 [ -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/ + @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] Removed the Flutter build output and local caches." + +# --- PLATFORM BUILDS --- + +# 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 $(NIX_ACTIVE)),) + PREBUILTS_DEFAULT := 1 +else ifeq ($(PLATFORM),Darwin) + ifeq ($(filter arm64 aarch64,$(UNAME_M)),) + PREBUILTS_DEFAULT := 1 + else + PREBUILTS_DEFAULT := 0 + endif +else ifeq ($(PLATFORM),Linux) + PREBUILTS_DEFAULT := 0 +else + PREBUILTS_DEFAULT := 1 +endif +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 ($(PLATFORM),Darwin) + ifeq ($(filter arm64 aarch64,$(UNAME_M)),) + $(error PREBUILTS=0 (dnix source) requires Apple Silicon on macOS; use the default PREBUILTS=1) + endif + endif + ifeq ($(filter Darwin Linux,$(PLATFORM)),$(PLATFORM)) + ifeq ($(strip $(NIX_ACTIVE)),) + $(error PREBUILTS=0 (dnix source) requires the Nix dev shell; run 'make bootstrap') + 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) + endif +endif +# 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) +override ANDROID_SOURCE_OK := $(and $(filter Linux,$(PLATFORM)),$(filter x86_64,$(ANDROID_ARCH)),$(strip $(NIX_ACTIVE)),$(strip $(NIX_BIN))) +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 ($(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 +ifeq ($(ANDROID_PREBUILTS),0) + ifeq ($(strip $(ANDROID_SOURCE_OK)),) + $(error ANDROID_PREBUILTS=0 requires the Nix dev shell 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). +# 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 +ifneq ($(filter $(SYSTEM_DEPS),0 1),$(SYSTEM_DEPS)) + $(error SYSTEM_DEPS must be 0 or 1) +endif +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 + @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 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..." + @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 + + +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:-}" + +# 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 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..." + @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) + @# 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; 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))"; \ + fi + @echo "--- Building app..." + @"$(FLUTTER)" pub get + @if [ "$(SYSTEM_DEPS)" = "1" ]; then \ + USE_SYSTEM_SECURE_STORAGE_DEPS=1 PROTOC="$(PROTOC_PATH)" "$(FLUTTER)" build linux --release; \ + else \ + SYSPROF_PC_DIR="$${SYSPROF_PC_DIR:-}"; \ + PC_PATH=$$(pkg-config --variable=pc_path pkg-config 2>/dev/null || echo ""); \ + 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_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..." + @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 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) + @[ -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 + @"$(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). 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) + @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 \ + -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 + @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 + @"$(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 (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 + @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/bm/README.md b/bm/README.md new file mode 100644 index 0000000000..c66246f1b8 --- /dev/null +++ b/bm/README.md @@ -0,0 +1,34 @@ +# Build and cache benchmarks + +Plain text, terminal only. Run everything from the shell you normally build in (for +example `nix develop`): Flutter reruns its native hooks whenever `PATH` or a `NIX_*` +variable changes, so runs from different shells measure different things. + +| Script | What it does | +|---|---| +| `bm/bench.sh` | times one `make build-macos` / `make build-linux` run and appends a row to `bm/results/.csv` (ignored by git) | +| `bm/matrix.sh` | runs six standard scenarios in a row (cold/warm × sccache off/on, `clean-app`, `clean-native`) and prints the report | +| `bm/report.sh` | prints the CSV as a table with each run compared to the first | + +```sh +make sccache-setup # once: sccache for the hooks' Rust/C builds +bash bm/bench.sh --sccache off # cold build without sccache +bash bm/bench.sh --clean native # rebuild only the native libraries +bash bm/bench.sh --label prebuilts PREBUILTS=1 +bash bm/matrix.sh && bash bm/report.sh +``` + +Each row records the clean mode, whether sccache was on, the make flags, wall seconds, +success, disk growth and sccache hits/misses. A failed build is recorded with +`success=0`. + +Notes on what can and cannot be cached: +- With Flutter 3.47.x the hooks only see sccache through the `rustc-wrapper` line in + `~/.cargo/config.toml` (what `make sccache-setup` writes). `--sccache off` removes that + line for one run and restores it afterwards. Flutter versions with `hooks_runner` 1.6.2 or + newer also accept `CARGO_BUILD_RUSTC_WRAPPER=sccache` from the environment. +- `make clean-app` keeps `.dart_tool/hooks_runner`, so the next build skips the native + libraries; `make clean-native` removes exactly those. The difference between the two + scenarios is the cost of the native builds. +- A shared `CARGO_TARGET_DIR` does not work (`native_toolchain_rust` passes `--target-dir`), + and `RUSTC_WRAPPER` or `RUSTFLAGS` exported in the shell never reach the hooks on 3.47.x. diff --git a/bm/bench.sh b/bm/bench.sh new file mode 100755 index 0000000000..6c0caf42c3 --- /dev/null +++ b/bm/bench.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# Time one `make build-*` run and append a row to bm/results/.csv. +# +# bash bm/bench.sh cold: `make clean`, then build, sccache as configured +# bash bm/bench.sh --warm build again without cleaning +# bash bm/bench.sh --clean app `make clean-app` first (keeps .dart_tool/hooks_runner) +# bash bm/bench.sh --clean native `make clean-native` first (rebuilds Rust/Go/C libraries) +# bash bm/bench.sh --sccache off run without the sccache rustc-wrapper (config restored after) +# bash bm/bench.sh --sccache on require it (run `make sccache-setup` first) +# bash bm/bench.sh --label some-name PREBUILTS=1 +# +# Anything else is passed to make. VERSION, BUILD_NUM and CONFIRM=1 get defaults. +# With sccache installed, its hit/miss counters are reset before and read after the build. +set -euo pipefail + +clean=full; sccache=keep; label=""; flags="" +while [ $# -gt 0 ]; do + case "$1" in + --warm) clean=none ;; + --clean) clean="$2"; shift ;; + --sccache) sccache="$2"; shift ;; + --label) label="$2"; shift ;; + *) flags="${flags:+$flags }$1" ;; + esac + shift +done +case "$clean" in full|app|native|none) ;; *) echo "--clean: full|app|native|none" >&2; exit 2 ;; esac +case "$sccache" in keep|on|off) ;; *) echo "--sccache: on|off|keep" >&2; exit 2 ;; esac +[ -n "$label" ] || label="$clean-sccache-$sccache" + +case "$(uname -s)" in + Darwin) target=build-macos ;; + Linux) target=build-linux ;; + *) echo "bench.sh supports macOS and Linux (use WSL2 on Windows)" >&2; exit 1 ;; +esac + +# The Makefile needs VERSION and a BUILD_NUM that is not below the latest release +# tag, and build_app.sh asks a question unless CONFIRM=1. +extra="" +case " $flags " in *" VERSION="*) ;; *) extra="$extra VERSION=0.0.0" ;; esac +case " $flags " in + *" BUILD_NUM="*) ;; + *) + tag_num="$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | sed -n 's/^build_\([0-9][0-9]*\)$/\1/p' | head -n1)" + extra="$extra BUILD_NUM=${tag_num:-1}" + ;; +esac +case " $flags " in *" CONFIRM="*) ;; *) extra="$extra CONFIRM=1" ;; esac + +# --- sccache on/off. Flutter 3.47.x hooks only see sccache through the rustc-wrapper +# line in the cargo config, so "off" removes that line for this run and a trap puts the +# file back, also when the build crashes. +cargo_cfg="${CARGO_HOME:-$HOME/.cargo}/config.toml" +has_wrapper() { [ -f "$cargo_cfg" ] && grep -q 'rustc-wrapper' "$cargo_cfg"; } +backup="" +restore() { [ -n "$backup" ] && [ -f "$backup" ] && mv "$backup" "$cargo_cfg" && echo "[bench] cargo config restored"; return 0; } +trap restore EXIT +if [ "$sccache" = off ] && has_wrapper; then + backup="$cargo_cfg.bench.bak" + cp -p "$cargo_cfg" "$backup" + grep -v 'rustc-wrapper' "$backup" > "$cargo_cfg" + echo "[bench] sccache disabled via $cargo_cfg (backup: $backup)" +elif [ "$sccache" = on ] && ! has_wrapper; then + echo "[bench] --sccache on, but $cargo_cfg has no rustc-wrapper; run: make sccache-setup" >&2 + exit 1 +fi +have_sccache=0; command -v sccache >/dev/null 2>&1 && have_sccache=1 +[ "$have_sccache" = 1 ] && sccache --zero-stats >/dev/null 2>&1 || true + +host="$(hostname -s 2>/dev/null || echo unknown)" +out="bm/results/$host.csv" +mkdir -p bm/results +[ -f "$out" ] || echo "date,label,commit,host,arch,os,clean,sccache,flags,wall_sec,success,disk_delta_kb,cache_hits,cache_misses" > "$out" + +case "$clean" in + full) make clean >/dev/null 2>&1 ;; + app) make clean-app >/dev/null 2>&1 ;; + native) make clean-native >/dev/null 2>&1 ;; +esac +disk_kb() { du -sk . 2>/dev/null | cut -f1; } +disk_before="$(disk_kb)" +start="$(date +%s)" + +# A failed build is a result too: keep going so the row is written. +set +e +# shellcheck disable=SC2086 +make "$target" $flags $extra 2>&1 | tail -n 5 +status=${PIPESTATUS[0]} +set -e +wall=$(( $(date +%s) - start )) + +hits="-"; misses="-" +if [ "$have_sccache" = 1 ]; then + stats="$(sccache --show-stats 2>/dev/null || true)" + hits="$(printf '%s\n' "$stats" | awk '/^Cache hits[[:space:]]+[0-9]+/ {print $3; exit}')" + misses="$(printf '%s\n' "$stats" | awk '/^Cache misses[[:space:]]+[0-9]+/ {print $3; exit}')" + hits="${hits:--}"; misses="${misses:--}" +fi + +echo "$(date -u +%Y-%m-%dT%H:%M:%SZ),$label,$(git rev-parse --short HEAD 2>/dev/null || echo unknown),$host,$(uname -m),$(uname -s),$clean,$sccache,${flags:--},$wall,$((status == 0)),$(( $(disk_kb) - disk_before )),$hits,$misses" >> "$out" + +if [ "$status" = 0 ]; then echo "[bench] ok in ${wall}s (sccache hits/misses: $hits/$misses)"; else echo "[bench] build FAILED after ${wall}s" >&2; fi +exit "$status" diff --git a/bm/matrix.sh b/bm/matrix.sh new file mode 100755 index 0000000000..6e9a466230 --- /dev/null +++ b/bm/matrix.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Run the standard cache comparison one scenario after another and print the report. +# Takes about an hour on a laptop (several full builds). Extra arguments go to every run, +# for example `bash bm/matrix.sh PREBUILTS=1`. +# +# 1 cold, no sccache the baseline +# 2 warm, no sccache rebuild with nothing cleaned (Flutter's own caches only) +# 3 cold, sccache first run fills the cache; needs `make sccache-setup` +# 4 warm, sccache same, nothing cleaned +# 5 clean-app, sccache build/ and Pods removed, hooks_runner kept +# 6 clean-native, sccache native libraries rebuilt, everything else kept (sccache hits) +set -uo pipefail + +run() { echo "=== $1"; shift; bash bm/bench.sh "$@" || echo "(run failed, continuing)"; } + +run "1/6 cold, no sccache" --label cold-nosccache --clean full --sccache off "$@" +run "2/6 warm, no sccache" --label warm-nosccache --clean none --sccache off "$@" +run "3/6 cold, sccache" --label cold-sccache --clean full --sccache on "$@" +run "4/6 warm, sccache" --label warm-sccache --clean none --sccache on "$@" +run "5/6 clean-app, sccache" --label cleanapp-sccache --clean app --sccache on "$@" +run "6/6 clean-native, sccache" --label cleannative-sccache --clean native --sccache on "$@" + +echo +bash bm/report.sh diff --git a/bm/report.sh b/bm/report.sh new file mode 100755 index 0000000000..b5b63e63b4 --- /dev/null +++ b/bm/report.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Print bm/results/.csv (or the file you pass) as a plain-text table, with each +# run's wall time compared to the first successful run in the file. +# +# bash bm/report.sh [bm/results/host.csv] +set -euo pipefail + +csv="${1:-bm/results/$(hostname -s 2>/dev/null || echo unknown).csv}" +[ -f "$csv" ] || { echo "no results yet: $csv (run bm/bench.sh or bm/matrix.sh)" >&2; exit 1; } + +awk -F, ' + NR == 1 { next } + { + wall = $10 + 0; ok = $11 + if (ok == 1 && base == 0) base = wall + delta = (ok == 1 && base > 0) ? sprintf("%+.0f%%", (wall - base) * 100 / base) : "-" + status = (ok == 1) ? "ok" : "FAILED" + printf "%-24s %-7s %-7s %6ds %-7s %7s %s/%s %s\n", $2, $7, $8, wall, status, delta, $13, $14, $9 + } + BEGIN { printf "%-24s %-7s %-7s %7s %-7s %7s %s %s\n", "label", "clean", "sccache", "wall", "status", "vs 1st", "hits/miss", "flags" } +' "$csv" diff --git a/docs/building.md b/docs/building.md index 7d02e7ca65..63edfbb7df 100644 --- a/docs/building.md +++ b/docs/building.md @@ -12,6 +12,9 @@ Flutter **3.47.2**. Follow the guide for the computer you build on: Allow at least 100 GB of free disk space. Source builds fill a Nix store as well as Flutter and native compiler caches. +For a Nix-based setup with one command per target, see +[Building with make](building/make.md). + ## How a build works 1. Install the prerequisites listed in your guide, including the SDKs for diff --git a/docs/building/make.md b/docs/building/make.md new file mode 100644 index 0000000000..f3a791371b --- /dev/null +++ b/docs/building/make.md @@ -0,0 +1,105 @@ +# Building with make + +The `Makefile` is a thin wrapper around `scripts/build_app.sh` and `flutter build`. It +checks that the requirements are met, runs the same steps as the other guides and picks the +dnix mode for you. **Every build needs Nix**: the flake (`flake.nix`) is the toolchain, and +the four dnix packages are either compiled from source (`PREBUILTS=0`) or taken as verified +prebuilts (`PREBUILTS=1`). Windows (Git Bash) is the one exception: it has no Nix and always +uses the prebuilts. + +## Quick start + +```sh +make bootstrap-macos # macOS: install Nix (asks first) and select a full Xcode + # Linux: make bootstrap-nix (see "Linux" below) +make bootstrap # enter the Nix dev shell (or: direnv allow) +make build-macos VERSION=x.y.z BUILD_NUM=nnn +``` + +`VERSION` and `BUILD_NUM` are required; `BUILD_NUM` must not be below the latest `build_*` +release tag. Without an active Nix shell `make` stops and says what to run. + +The flake supports Apple Silicon macOS and Linux (x86_64, aarch64). It provides Flutter, Go, +rustup, sccache, CMake, Meson, Ninja, pkg-config and protoc from a pinned nixpkgs, and +installs the Rust toolchains on first entry. Xcode always comes from the host. + +## Versions + +The versions live in one place, the top of `flake.nix`: the two Rust toolchains and the Xcode +that dnix source builds need. The dev shell installs the Rust versions and exports all three +as `STACK_RUST_VERSION`, `STACK_DNSSEC_RUST_VERSION` and `STACK_XCODE_VERSION`, which +`make check-reqs` and `make toolchain` read. Flutter and Go come from the pinned nixpkgs; to +change them, change the nixpkgs revision in `flake.nix` and run `nix flake lock`. The Nix shell +provides Flutter 3.47.4 while upstream CI uses 3.47.2 (nixpkgs never packaged 3.47.2). + +## Requirements on macOS + +| Target | What it does | +|---|---| +| `bootstrap-nix` | installs Nix on macOS or Linux with the official installer (asks before it runs a downloaded script as root; `NIX_INSTALL_YES=1` skips the question) and enables the `nix-command` and `flakes` features | +| `bootstrap-macos` | `bootstrap-nix`, then checks or selects the full Xcode | +| `bootstrap-xcode` | selects an installed full Xcode, accepts the licence and runs first-launch setup when it changes the selection | +| `bootstrap-xcode-download` | opt-in: downloads Xcode from archive.org with an SHA-1 check and Apple's signature check (`XCODE_VERSION=27.0`, `ARGS=-y` to skip prompts); refuses to run in CI and aborts on a hash mismatch before it extracts anything | +| `check-reqs`, `check-reqs-macos`, `check-sdk-macos`, `diagnose-env-macos` | test the requirements (Nix shell, tools, pinned Rust toolchains, Xcode and SDK) and print the environment | + +dnix source builds need the pinned Xcode (27.0) installed next to your usual one; it need not +be selected. `check-sdk-macos` fails with the fix when it is missing and `PREBUILTS=0`. + +## Linux (Ubuntu and others) + +```sh +make bootstrap-nix # installs Nix (multi-user with systemd, else single-user) +make bootstrap # enter the Nix dev shell (or: direnv allow) +make build-linux VERSION=x.y.z BUILD_NUM=nnn +``` + +In CI or scripts use `nix develop --command make build-linux ...` instead of an interactive +shell. The flake supplies every build dependency (GTK, libsecret, protoc, the C/C++ and Rust +toolchains), so no `apt` packages are needed. + +A bundle built this way is **for the machine that built it, not for distribution**: its ELF +interpreter and `RUNPATH` point into `/nix/store`, so it only starts where those exact store +paths exist. Use the Nix build to develop, test and verify reproducibly. For a release that +runs on a stock Ubuntu, build without Nix as described in the [Linux guide](linux.md) (the CI +image and `-s` system libraries), or package the Nix closure (AppImage, Flatpak). + +## Targets + +| Target | What it does | +|---|---| +| `build-macos`, `build-ios` | `build_app.sh`, `flutter pub get`, `prebuild.sh`, `flutter build` (iOS without code signing) | +| `build-linux` | the same, plus the libsecret and secp256k1 helpers and `prepare_release_bundle.py` | +| `build-windows` | Git Bash; the same with verified prebuilts (`-d`); no Nix | +| `build-android` | APKs; needs the Android SDK and `android/key.properties` (`make android-dev-key` makes a throw-away test key, never use it for releases) | +| `bootstrap`, `toolchain` | enter the Nix shell; show whether it is active, the pinned versions and the tool paths | +| `clean`, `clean-app`, `clean-native` | remove everything, or build output only (keeps `.dart_tool/hooks_runner`), or the native libraries only | +| `sccache-setup`, `cache-stats` | opt-in sccache for the hooks' Rust/C builds, and its hit rate | + +## Variables + +| Variable | Default | Meaning | +|---|---|---| +| `VERSION`, `BUILD_NUM` | required | app version and build number | +| `APP_NAME` | `stack_wallet` | `stack_wallet`, `stack_duo` or `campfire` | +| `PREBUILTS` | `0` on Apple Silicon and Linux | `0` builds the four dnix packages from source and verifies their hashes; `1` uses the verified prebuilts (`-d`) | +| `ANDROID_PREBUILTS` | follows `PREBUILTS` on x86_64 Linux, else `1` | dnix mode for Android | +| `SYSTEM_DEPS` | `0` | Linux: `1` uses system libsecret and JsonCPP (as CI does) | +| `CONFIRM` | `0` | `1` answers the wallet-data warning of `build_app.sh` non-interactively | +| `FLUTTER` | from `PATH` | explicit Flutter binary | + +`PREBUILTS=0` needs the Nix shell and, on macOS, Apple Silicon; Windows rejects it. Calling +`scripts/build_app.sh` directly without `-d` only needs `nix` on `PATH`. + +## Caches and benchmarks + +`make sccache-setup` writes `~/.cargo/config.toml` with `rustc-wrapper = "sccache"` if the +file does not exist, because Flutter 3.47.x hooks see sccache only that way; remove the file +to turn it off. `make cache-stats` shows the hit rate. The `bm/` scripts measure what each +cache is worth: see [bm/README.md](../../bm/README.md). + +## Notes + +- If Flutter's hooks rerun every native build, the environment changed between runs (`PATH` + or a `NIX_*` variable). Build always from the same shell. +- On NixOS the Android build needs `programs.nix-ld.enable = true` and a writable Flutter SDK; + see the [Linux guide](linux.md). 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..97dd47927f --- /dev/null +++ b/flake.nix @@ -0,0 +1,279 @@ +{ + description = "Stack Wallet Build Environment"; + + inputs = { + # Pinned to a specific nixpkgs rev for reproducible Flutter/Rust toolchain + # 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"; + }; + + outputs = { self, nixpkgs, flake-utils }: + flake-utils.lib.eachSystem [ "aarch64-darwin" "x86_64-linux" "aarch64-linux" ] (system: + let + pkgs = import nixpkgs { inherit system; }; + lib = pkgs.lib; + # The versions this repository builds with. This is the only place they are + # written down: the dev shell installs the Rust toolchains and exports all of + # them as STACK_* variables, which the Makefile reads. Flutter and Go come from + # the pinned nixpkgs above (nixpkgs never packaged Flutter 3.47.2; upstream CI + # uses 3.47.2, the Nix shell provides 3.47.4). + rustVersion = "1.99.1"; # Xelis and the other native-asset crates + dnssecRustVersion = "1.90.0"; # OpenAlias/DNSSEC resolver, built from source in every app + xcodeVersion = "27.0"; # dnix source builds need exactly this Xcode installed (side by side is fine) + clangMajor = lib.versions.major pkgs.llvmPackages.clang.version; + + commonPackages = with pkgs; [ + flutter + go + rustup + sccache + git + nix + cmake + meson + ninja + pkg-config + gnumake + rsync + protobuf + (python3.withPackages (ps: with ps; [ + pip toml tomli jinja2 markdown markupsafe pygments typogrify + ])) + ]; + + linuxPackages = lib.optionals pkgs.stdenv.hostPlatform.isLinux (with pkgs; [ + gtk3 glib openssl xz libgcrypt gobject-introspection + llvmPackages.libclang + llvmPackages.clang + opencv + sysprof + libsysprof-capture + # 0.18 is the first patchelf with --clear-execstack, which + # prepare_release_bundle.py requires. + patchelfUnstable + binutils + tpm2-tss + ocl-icd + opencl-headers + ]); + + macPackages = lib.optionals pkgs.stdenv.hostPlatform.isDarwin (with pkgs; [ + cocoapods + libiconv + autoconf + automake + libtool + ]); + + in + { + checks.dev-shell = self.devShells.${system}.default; + + devShells.default = pkgs.mkShell { + buildInputs = commonPackages ++ linuxPackages ++ macPackages; + + # Read by the Makefile (`make check-reqs`, `make toolchain`). + STACK_RUST_VERSION = rustVersion; + STACK_DNSSEC_RUST_VERSION = dnssecRustVersion; + STACK_XCODE_VERSION = xcodeVersion; + + shellHook = '' + echo "===================================================" + echo "Stack Wallet Dev-Environment activated!" + echo "Target System: ${system}" + echo "===================================================" + + # Resolve the repository root, not the directory the shell was + # entered from; .nix-bin and the rustup override are per checkout. + 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 + 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, + # so `dart run`/`dart pub` in a Flutter project fail ("Flutter users should use flutter pub"). + 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. + # ========================================== + 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 + + if [[ "${system}" == *"darwin"* ]]; then + rustup target add aarch64-apple-darwin x86_64-apple-darwin aarch64-apple-ios aarch64-apple-ios-sim --toolchain ${rustVersion} + fi + + # ========================================== + # LINUX (NixOS) SPECIFICS + # ========================================== + ${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. + # 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. + 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" + export SYSPROF_PC_DIR="${pkgs.libsysprof-capture}/lib/pkgconfig" + # mkShell adds `-rpath $out/lib` and $out is /outputs/out, so every + # binary linked in this shell would carry the checkout path in its RUNPATH + # (not reproducible, and a leak of the build directory). Nothing is installed + # there, so drop it. + if [ -n "''${out:-}" ]; then + export NIX_LDFLAGS="$(printf '%s' "$NIX_LDFLAGS" | sed "s| *-rpath $out/lib||g")" + fi + ''} + + # ========================================== + # MACOS XCODE SANDBOX ESCAPE + # ========================================== + ${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) ;; + *) + echo "[WARN] No full Xcode selected. Install Xcode, then run: sudo xcode-select -s /Applications/Xcode.app/Contents/Developer" + ;; + esac + # dnix source builds need exactly Xcode ${xcodeVersion} installed; it need not be selected. + dnix_xcode_found=0 + for app in /Applications/Xcode*.app; do + [ -x "$app/Contents/Developer/usr/bin/xcodebuild" ] || continue + [ "$(DEVELOPER_DIR="$app/Contents/Developer" xcodebuild -version 2>/dev/null | sed -n 's/^Xcode \([0-9.]*\).*/\1/p' | head -n1)" = "${xcodeVersion}" ] && dnix_xcode_found=1 + done + [ "$dnix_xcode_found" = 1 ] || echo "[WARN] Xcode ${xcodeVersion} not found in /Applications; dnix source builds (PREBUILTS=0) need it: make bootstrap-xcode-download XCODE_VERSION=${xcodeVersion}" + # 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" + + # 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 + 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 + + SDK_PATH="$(/usr/bin/xcrun --sdk macosx --show-sdk-path 2>/dev/null || true)" + if [ -n "$SDK_PATH" ]; then + 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" + + # 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" + ln -sf /usr/bin/clang++ "$NIX_BIN/clang++" + + # SMART LIPO & XCRUN WRAPPER + # 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' +#!/bin/bash +for arg in "$@"; do + if [[ "$arg" == *"FlutterMacOS.framework"* ]]; then + framework="''${arg%%FlutterMacOS.framework*}FlutterMacOS.framework" + case "$framework" in + "$APP_ROOT"/*|"''${TMPDIR:-/tmp}"/*) chmod -R u+w "$framework" 2>/dev/null || true ;; + *) ;; + esac + fi +done +exec /usr/bin/lipo "$@" +LIPO_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" <&2 + fi + ''} + + ''; + }; + } + ); +} 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/build_app.sh b/scripts/build_app.sh index 253cc58435..21e2d3c661 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,10 +19,16 @@ 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;; + # 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 diff --git a/scripts/download_xcode.sh b/scripts/download_xcode.sh new file mode 100755 index 0000000000..69bae8eaef --- /dev/null +++ b/scripts/download_xcode.sh @@ -0,0 +1,288 @@ +#!/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 [[ $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_nix.sh b/scripts/install_nix.sh new file mode 100755 index 0000000000..8a7c9ee3f7 --- /dev/null +++ b/scripts/install_nix.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash + +# Checks for Nix and installs it when missing, on macOS and on Linux. Every build +# needs Nix (the flake is the toolchain), so this runs from `make bootstrap-nix` +# and, on a Mac, from `make bootstrap-macos` alongside the Xcode check. Nix is the +# only host dependency this script installs itself: Xcode cannot be redistributed +# (Apple's licence), and the rest of the toolchain comes from the flake. The +# installer is downloaded and run as root, so the script asks first; it does not +# pin or checksum the installer script. +# +# 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; } + +# macOS and Linux (Ubuntu, Debian, Fedora, ...). The multi-user installer needs +# systemd on Linux; without it (containers, WSL1) fall back to a single-user install. +case "$(uname -s)" in + Darwin) INSTALL_MODE=--daemon ;; + Linux) + if [ -d /run/systemd/system ]; then INSTALL_MODE=--daemon; else INSTALL_MODE=--no-daemon; fi + ;; + *) die "This installer supports macOS and Linux only." ;; +esac + +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 Nix (${INSTALL_MODE#--}) from ${INSTALLER}..." +echo "This downloads a shell script and runs it with sudo; it creates /nix and, for a multi-user install, 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." + +# 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 + +# `--daemon` is the recommended multi-user mode: it creates the build users and sets up +# launchd/systemd so `nix` works for every user. The flake needs the nix-command and flakes +# features; enable them in the installed nix.conf so `direnv`'s `use flake` works too. +# --yes: we asked above, do not ask again. +conf="$(mktemp "${TMPDIR:-/tmp}/nix-extra-conf.XXXXXX")" +trap 'rm -f "$conf"' EXIT +echo "experimental-features = nix-command flakes" > "$conf" +curl --proto '=https' --tlsv1.2 -fL "$INSTALLER" | sh -s -- "$INSTALL_MODE" --yes --nix-extra-conf-file "$conf" + +# 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 (single-user: . ~/.nix-profile/etc/profile.d/nix.sh)" +fi + +echo "[OK] Nix installed: $(command -v nix 2>/dev/null || echo 'see above')" diff --git a/scripts/install_xcode.sh b/scripts/install_xcode.sh new file mode 100755 index 0000000000..04e4c36f7a --- /dev/null +++ b/scripts/install_xcode.sh @@ -0,0 +1,90 @@ +#!/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. +# +# 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 Xcode..." + +# 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)" + +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 + 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 + - 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 + # 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 + +# 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/scripts/linux/build_secp256k1.sh b/scripts/linux/build_secp256k1.sh index b6037a3060..92e6b49d31 100755 --- a/scripts/linux/build_secp256k1.sh +++ b/scripts/linux/build_secp256k1.sh @@ -1,15 +1,46 @@ +#!/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 + +# 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 diff --git a/scripts/linux/build_secure_storage_deps.sh b/scripts/linux/build_secure_storage_deps.sh index e84572bcaa..b9c150049a 100755 --- a/scripts/linux/build_secure_storage_deps.sh +++ b/scripts/linux/build_secure_storage_deps.sh @@ -1,4 +1,5 @@ -#!/bin/bash +#!/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,11 +19,11 @@ 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_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 @@ -33,14 +34,35 @@ 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 fi -meson _build -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. +mkdir -p "$LINUX_DIRECTORY/pc" +cat > "$LINUX_DIRECTORY/pc/libsecret-1.pc" <= 2.44, gio-2.0 >= 2.44, gio-unix-2.0 >= 2.44 -Requires.private: libgcrypt >= 1.2.2 -Libs: -L${libdir} -lsecret-1 From bc12c7e8b609cdd15ec29bbdfd0d422e8d07286f Mon Sep 17 00:00:00 2001 From: parasew <9727+parasew@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:55:17 +0200 Subject: [PATCH 2/2] docs(make): say which build is for what (local, CI development, official releases) --- docs/building/make.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/building/make.md b/docs/building/make.md index f3a791371b..d565113066 100644 --- a/docs/building/make.md +++ b/docs/building/make.md @@ -7,6 +7,24 @@ the four dnix packages are either compiled from source (`PREBUILTS=0`) or taken prebuilts (`PREBUILTS=1`). Windows (Git Bash) is the one exception: it has no Nix and always uses the prebuilts. +## Which build is for what + +Stack Wallet is built in three different ways. This page is about the first one. + +| | For | How | Nix | +|---|---|---|---| +| **Local builds** | testers, anyone who wants to reproduce a build or make their own | `make build-*` in the Nix shell (this page) | always | +| **CI development builds** | automatic builds of `staging` and of version tags | `.github/workflows/build.yaml`: the CI Docker image (Ubuntu 24.04) or a hosted runner, `build_app.sh ... -d -s`, then `flutter build` | no | +| **Official releases** | the Stack Wallet team | not defined in this repository | unknown | + +Local builds and CI builds share the same core (`scripts/build_app.sh`, the dnix packages and +`flutter build`); they differ in where the toolchain comes from: the flake here, the CI image +and setup actions there. The CI workflow calls its output unverified development builds. + +A local build is not a release. A Linux bundle built in the Nix shell only runs where its +`/nix/store` paths exist (see "Linux" below), the app is not signed, and the API keys are empty +stubs unless you provide your own `lib/external_api_keys.dart`. + ## Quick start ```sh