diff --git a/.envrc b/.envrc new file mode 100644 index 0000000000..4819e13923 --- /dev/null +++ b/.envrc @@ -0,0 +1,6 @@ +# Nix is the primary toolchain. Without it, leave the shell alone instead of +# failing with a blocked .envrc; use make bootstrap-macos and PREBUILTS=1. +if has nix; then + watch_file stack-bom.toml flake.nix flake.lock + use flake . --no-write-lock-file +fi diff --git a/.github/workflows/build-ci-image.yaml b/.github/workflows/build-ci-image.yaml index 5cc34c0c99..2ddd51c428 100644 --- a/.github/workflows/build-ci-image.yaml +++ b/.github/workflows/build-ci-image.yaml @@ -5,6 +5,8 @@ on: branches: [main, staging] paths: - 'Dockerfile' + - 'stack-bom.toml' + - 'scripts/bom_values.sh' - '.github/workflows/build-ci-image.yaml' workflow_dispatch: diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 74ee07ff15..832fc7effb 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -18,10 +18,33 @@ on: default: '1' # Configure app uses -d for verified dnix prebuilts (Frost, Tor, Epic and MWC). -# Every app still builds dnssec_resolver with Rust 1.90.0; Stack Wallet also +# Every app still builds dnssec_resolver with the BOM DNSSEC Rust (1.90.0); Stack Wallet also # builds Xelis with Rust 1.99.1, and Stack Wallet/Campfire build Spark with C++. jobs: + bom: + runs-on: ubuntu-24.04 + permissions: + contents: read + outputs: + flutter_min: ${{ steps.read.outputs.flutter_min }} + go: ${{ steps.read.outputs.go }} + dnssec_rust: ${{ steps.read.outputs.dnssec_rust }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 1 + - name: Read stack-bom.toml + id: read + run: | + bash scripts/bom_values.sh --check + flutter_min="$(bash scripts/bom_values.sh --get flutter_min)" + go="$(bash scripts/bom_values.sh --get go)" + dnssec_rust="$(bash scripts/bom_values.sh --get dnssec_rust)" + echo "flutter_min=$flutter_min" >> "$GITHUB_OUTPUT" + echo "go=$go" >> "$GITHUB_OUTPUT" + echo "dnssec_rust=$dnssec_rust" >> "$GITHUB_OUTPUT" + build-disclaimer: runs-on: ubuntu-24.04 steps: @@ -49,7 +72,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -84,7 +106,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build env: @@ -120,7 +147,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -155,7 +181,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Set up Android local.properties run: | @@ -211,7 +242,11 @@ jobs: path: android-artifacts/ build-windows: + needs: bom runs-on: windows-2022 + permissions: + contents: read + packages: read defaults: run: shell: bash @@ -219,7 +254,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -241,16 +275,16 @@ jobs: # OpenAlias/DNSSEC builds from source in every app, including -d. - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Flutter doctor run: flutter doctor -v @@ -265,24 +299,6 @@ jobs: -b "${{ steps.ver.outputs.build_number }}" \ -p windows -a stack_wallet -d -s - # Use real copies of the five gitignored asset directories instead of the - # directory links that link_assets.sh creates. - - name: Replace asset symlinks with copies (CI workaround) - run: | - set -euo pipefail - for dirname in default_themes icon lottie in_app_logo_icons svg; do - target="assets/${dirname}" - source="asset_sources/${dirname}/stack_wallet" - # Remove whatever link_assets.sh left (reparse point, symlink, or nothing). - # cmd.exe rmdir on a junction/symlink removes the link, not the target. - if [ -e "$target" ] || [ -L "$target" ]; then - MSYS2_ARG_CONV_EXCL="/C${MSYS2_ARG_CONV_EXCL:+;$MSYS2_ARG_CONV_EXCL}" \ - cmd.exe /C rmdir "$(cygpath -w "$target")" 2>/dev/null || rm -rf "$target" - fi - mkdir -p "$target" - cp -r "${source}/." "$target/" - done - - name: Get dependencies run: | flutter pub get @@ -291,7 +307,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build windows --release @@ -308,12 +329,12 @@ jobs: path: stack_wallet-windows-x86_64-${{ steps.ver.outputs.version }}.zip build-macos: + needs: bom runs-on: macos-latest steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -335,16 +356,16 @@ jobs: # OpenAlias/DNSSEC builds from source in every app, including -d. - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Configure app run: | @@ -362,7 +383,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build macos --release @@ -379,12 +405,12 @@ jobs: path: stack_wallet-macos-aarch64-${{ steps.ver.outputs.version }}.zip build-ios: + needs: bom runs-on: macos-latest steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -406,16 +432,16 @@ jobs: # OpenAlias/DNSSEC builds from source in every app, including -d. - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Configure app run: | @@ -433,7 +459,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build ios --release --no-codesign @@ -463,7 +494,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -498,7 +528,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build env: @@ -534,7 +569,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -569,7 +603,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build env: @@ -722,7 +761,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -757,7 +795,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Set up Android local.properties run: | @@ -813,6 +856,7 @@ jobs: path: android-artifacts/ build-campfire-windows: + needs: bom runs-on: windows-2022 defaults: run: @@ -821,7 +865,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -843,16 +886,16 @@ jobs: # OpenAlias/DNSSEC builds from source in every app, including -d. - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Flutter doctor run: flutter doctor -v @@ -865,20 +908,6 @@ jobs: -b "${{ steps.ver.outputs.build_number }}" \ -p windows -a campfire -d -s - - name: Replace asset symlinks with copies (CI workaround) - run: | - set -euo pipefail - for dirname in default_themes icon lottie in_app_logo_icons svg; do - target="assets/${dirname}" - source="asset_sources/${dirname}/campfire" - if [ -e "$target" ] || [ -L "$target" ]; then - MSYS2_ARG_CONV_EXCL="/C${MSYS2_ARG_CONV_EXCL:+;$MSYS2_ARG_CONV_EXCL}" \ - cmd.exe /C rmdir "$(cygpath -w "$target")" 2>/dev/null || rm -rf "$target" - fi - mkdir -p "$target" - cp -r "${source}/." "$target/" - done - - name: Get dependencies run: | flutter pub get @@ -887,7 +916,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build windows --release @@ -904,12 +938,12 @@ jobs: path: campfire-windows-x86_64-${{ steps.ver.outputs.version }}.zip build-campfire-macos: + needs: bom runs-on: macos-latest steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -931,16 +965,16 @@ jobs: # OpenAlias/DNSSEC builds from source in every app, including -d. - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Configure app run: | @@ -958,7 +992,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build macos --release @@ -975,12 +1014,12 @@ jobs: path: campfire-macos-aarch64-${{ steps.ver.outputs.version }}.zip build-campfire-ios: + needs: bom runs-on: macos-latest steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -1002,16 +1041,16 @@ jobs: # OpenAlias/DNSSEC builds from source in every app, including -d. - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Configure app run: | @@ -1029,7 +1068,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build ios --release --no-codesign @@ -1176,7 +1220,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -1211,7 +1254,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Set up Android local.properties run: | @@ -1267,6 +1315,7 @@ jobs: path: android-artifacts/ build-stack-duo-windows: + needs: bom runs-on: windows-2022 defaults: run: @@ -1275,7 +1324,6 @@ jobs: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -1297,16 +1345,16 @@ jobs: # OpenAlias/DNSSEC builds from source in every app, including -d. - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Flutter doctor run: flutter doctor -v @@ -1319,20 +1367,6 @@ jobs: -b "${{ steps.ver.outputs.build_number }}" \ -p windows -a stack_duo -d -s - - name: Replace asset symlinks with copies (CI workaround) - run: | - set -euo pipefail - for dirname in default_themes icon lottie in_app_logo_icons svg; do - target="assets/${dirname}" - source="asset_sources/${dirname}/stack_duo" - if [ -e "$target" ] || [ -L "$target" ]; then - MSYS2_ARG_CONV_EXCL="/C${MSYS2_ARG_CONV_EXCL:+;$MSYS2_ARG_CONV_EXCL}" \ - cmd.exe /C rmdir "$(cygpath -w "$target")" 2>/dev/null || rm -rf "$target" - fi - mkdir -p "$target" - cp -r "${source}/." "$target/" - done - - name: Get dependencies run: | flutter pub get @@ -1341,7 +1375,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build windows --release @@ -1358,12 +1397,12 @@ jobs: path: stack_duo-windows-x86_64-${{ steps.ver.outputs.version }}.zip build-stack-duo-macos: + needs: bom runs-on: macos-latest steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -1385,16 +1424,16 @@ jobs: # OpenAlias/DNSSEC builds from source in every app, including -d. - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Configure app run: | @@ -1412,7 +1451,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build macos --release @@ -1429,12 +1473,12 @@ jobs: path: stack_duo-macos-aarch64-${{ steps.ver.outputs.version }}.zip build-stack-duo-ios: + needs: bom runs-on: macos-latest steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive - name: Set version id: ver @@ -1456,16 +1500,16 @@ jobs: # OpenAlias/DNSSEC builds from source in every app, including -d. - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.90.0 + toolchain: ${{ needs.bom.outputs.dnssec_rust }} - uses: subosito/flutter-action@v2 with: - flutter-version: '3.47.2' + flutter-version: ${{ needs.bom.outputs.flutter_min }} channel: 'stable' - uses: actions/setup-go@v6 with: - go-version: '1.24.13' + go-version: ${{ needs.bom.outputs.go }} - name: Configure app run: | @@ -1483,7 +1527,12 @@ jobs: - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} - run: echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart + run: | + if [ -z "$CHANGE_NOW" ]; then + echo "::error::CHANGE_NOW secret is not set; refusing to build with empty API keys" >&2 + exit 1 + fi + echo "$CHANGE_NOW" | base64 --decode > lib/external_api_keys.dart - name: Build run: flutter build ios --release --no-codesign diff --git a/.github/workflows/make-smoke.yaml b/.github/workflows/make-smoke.yaml new file mode 100644 index 0000000000..de9cfa4648 --- /dev/null +++ b/.github/workflows/make-smoke.yaml @@ -0,0 +1,68 @@ +name: Make smoke + +# Manual-only: a real `make build-linux` end-to-end, so the Makefile recipe is +# exercised in CI (not just `make -n` dry-runs). Prebuilt mode (verified dnix +# assets) on the CI image — no Nix, no source native build. Run from the +# Actions tab with a version + build number; it does not run on every push/PR. +on: + workflow_dispatch: + inputs: + version: + description: 'App version string (e.g. 0.0.1)' + required: true + default: '0.0.1' + build_number: + description: 'Build number (integer; must be >= the latest build_* tag)' + required: true + default: '326' + +jobs: + make-smoke-linux: + runs-on: ubuntu-24.04 + permissions: + contents: read + packages: read + container: + image: ghcr.io/${{ github.repository_owner }}/stackwallet-ci:latest + credentials: + username: ${{ github.actor }} + password: ${{ github.token }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + + # The CI image installs rustup with --default-toolchain none; the pinned + # toolchains are added on demand by the Flutter build hooks, but + # `make build-linux` runs verify-bom + check-reqs BEFORE any hook, and + # those hard-require the BOM-pinned rust toolchains. Install them here, + # reading the versions from stack-bom.toml so the smoke tracks the BOM. + - name: Install pinned rust toolchains + run: | + rustup toolchain install "$(bash scripts/bom_values.sh --get rust)" --profile minimal + rustup toolchain install "$(bash scripts/bom_values.sh --get dnssec_rust)" --profile minimal + + - name: Dry-run the recipe + env: + VERSION: ${{ inputs.version }} + BUILD_NUM: ${{ inputs.build_number }} + run: | + make -n build-linux \ + PLATFORM=Linux TOOLCHAIN=host PREBUILTS=1 SYSTEM_DEPS=1 \ + VERSION="$VERSION" BUILD_NUM="$BUILD_NUM" + + - name: Real build (make build-linux, prebuilt) + env: + VERSION: ${{ inputs.version }} + BUILD_NUM: ${{ inputs.build_number }} + run: | + make build-linux \ + PLATFORM=Linux TOOLCHAIN=host PREBUILTS=1 SYSTEM_DEPS=1 CONFIRM=1 \ + VERSION="$VERSION" BUILD_NUM="$BUILD_NUM" + + - name: Upload smoke artifact + if: success() + uses: actions/upload-artifact@v7 + with: + name: stack_wallet-linux-smoke-${{ inputs.version }} + path: build/linux/x64/release/bundle/ diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 25dcc8495d..fa9b7c28f9 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -41,7 +41,6 @@ jobs: uses: actions/checkout@v6 with: fetch-depth: 0 - submodules: recursive # -d selects verified dnix prebuilts for Frost, Tor, Epic and MWC. # -s (CI only) skips building jsoncpp and libsecret; the image has them. @@ -71,6 +70,14 @@ jobs: flutter pub get dart tool/check_native_overrides.dart stack_wallet + - name: Verify BOM + run: | + rustup toolchain install \ + "$(bash scripts/bom_values.sh --get rust)" \ + "$(bash scripts/bom_values.sh --get dnssec_rust)" \ + --profile minimal --no-self-update + make verify-bom + - name: Decode secrets env: CHANGE_NOW: ${{ secrets.CHANGE_NOW }} @@ -108,6 +115,10 @@ jobs: # run: flutter analyze - name: Test build scripts run: dart scripts/tests/build_input_test.dart + - name: Test BOM values validator + run: dart scripts/tests/bom_values_test.dart + - name: Test BOM parser + run: dart scripts/tests/verify_bom_parser_test.dart - name: Test native build configuration run: dart scripts/tests/native_build_config_test.dart - name: Test native settings and dependency contracts @@ -134,3 +145,71 @@ 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: | + bash scripts/bom_values.sh --check + 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 an active Nix/direnv shell' build-macos PLATFORM=Darwin UNAME_M=arm64 TOOLCHAIN=manual PREBUILTS=0 + expect_fail 'requires an active Nix/direnv shell' build-linux PLATFORM=Linux TOOLCHAIN=host PREBUILTS=0 + expect_fail 'requires Apple Silicon' build-macos PLATFORM=Darwin UNAME_M=x86_64 IN_NIX_SHELL=1 PREBUILTS=0 + expect_fail 'build-windows uses verified' build-windows PLATFORM=MINGW64_NT-10.0 PREBUILTS=0 + expect_fail 'ANDROID_PREBUILTS=0 requires' build-android PLATFORM=Linux UNAME_M=x86_64 TOOLCHAIN=host ANDROID_PREBUILTS=0 + expect_fail 'TOOLCHAIN must be' build-macos PLATFORM=Darwin TOOLCHAIN=brew + # Mode selection: source only inside a Nix shell on a supported host. + build_line() { make -n "$@" VERSION=0.0.0 BUILD_NUM=1 | grep -E '\./build_app\.sh -' | head -n 1; } + build_line build-linux PLATFORM=Linux UNAME_M=x86_64 IN_NIX_SHELL=1 | grep -qE ' -d( |$)' && { echo 'Nix shell on Linux must default to source' >&2; exit 1; } + build_line build-linux PLATFORM=Linux UNAME_M=x86_64 TOOLCHAIN=host | grep -qE ' -d( |$)' || { echo 'host toolchain must default to prebuilts' >&2; exit 1; } + build_line build-macos PLATFORM=Darwin UNAME_M=x86_64 IN_NIX_SHELL=1 | grep -qE ' -d( |$)' || { echo 'Intel macOS must use prebuilts' >&2; exit 1; } + true + # `make -n` never executes recipes, so a shell parse error in the + # require-version recipe is invisible to the dry-runs above. Run it for real. + # This is a bash step, not a Makefile recipe: use single `$`. + - 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..af062aa188 100644 --- a/.gitignore +++ b/.gitignore @@ -35,6 +35,9 @@ Microsoft.Windows* android/app/.cxx android/build/ +# Nix / direnv / project-local toolchain state +.direnv/ + # Web related lib/generated_plugin_registrant.dart @@ -120,3 +123,14 @@ lib/wl_gen/generated/ /assets/windows/mwebd.exe /tool/build +/.cargo/config.toml +/scripts/linux/pc/ + +# Android local signing +/android/key.properties +/android/dev-keystore.jks +/android/keystore.jks +/android/keystore-orig.jks + +# Benchmark results (per-machine CSVs; see bm/README.md) +/bm/results/ diff --git a/Dockerfile b/Dockerfile index b2b19812c7..1d7ba19d90 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,15 @@ # syntax=docker/dockerfile:1.7 FROM ubuntu:24.04 AS full +# Toolchain versions come from stack-bom.toml (the single source of truth), read +# with the pure-bash scripts/bom_values.sh. The Go sha256 stays hardcoded as an +# integrity pin: bumping the BOM Go version without updating it fails the build +# loudly, which is the point. This COPY + the two ARG-free RUN reads below are +# repeated in the android and test stages because sibling FROM stages cannot +# share ARGs. +COPY stack-bom.toml /bom/stack-bom.toml +COPY scripts/bom_values.sh /bom/bom_values.sh + ENV DEBIAN_FRONTEND=noninteractive \ TZ=Etc/UTC \ LANG=C.UTF-8 \ @@ -73,7 +82,11 @@ RUN mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools" \ ENV PATH=/usr/local/go/bin:$PATH -RUN curl -fsSL https://go.dev/dl/go1.24.13.linux-amd64.tar.gz -o /tmp/go.tar.gz \ +# Go version from stack-bom.toml; the sha256 below is an integrity pin that must +# be updated in lockstep when the BOM go version changes. +RUN GO_VERSION="$(BOM_FILE=/bom/stack-bom.toml bash /bom/bom_values.sh --get go)" \ + && echo "Installing Go $GO_VERSION (sha256 pinned below)" \ + && curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" -o /tmp/go.tar.gz \ && echo "1fc94b57134d51669c72173ad5d49fd62afb0f1db9bf3f798fd98ee423f8d730 /tmp/go.tar.gz" | sha256sum -c \ && tar -C /usr/local -xzf /tmp/go.tar.gz \ && rm /tmp/go.tar.gz @@ -81,7 +94,10 @@ RUN curl -fsSL https://go.dev/dl/go1.24.13.linux-amd64.tar.gz -o /tmp/go.tar.gz ENV FLUTTER_HOME=/opt/flutter \ PATH=/opt/flutter/bin:/opt/flutter/bin/cache/dart-sdk/bin:$PATH -RUN git clone --depth 1 --branch 3.47.2 https://github.com/flutter/flutter.git "$FLUTTER_HOME" \ +# Flutter branch from stack-bom.toml. +RUN FLUTTER_VERSION="$(BOM_FILE=/bom/stack-bom.toml bash /bom/bom_values.sh --get flutter)" \ + && echo "Cloning Flutter $FLUTTER_VERSION" \ + && git clone --depth 1 --branch "$FLUTTER_VERSION" https://github.com/flutter/flutter.git "$FLUTTER_HOME" \ && git config --global --add safe.directory '*' \ && flutter config --no-analytics \ && flutter precache --linux --android \ @@ -96,6 +112,9 @@ RUN flutter --version && rustup --version && node --version && go version # Rust toolchains and targets are installed by hooks at runtime. FROM ubuntu:24.04 AS android +COPY stack-bom.toml /bom/stack-bom.toml +COPY scripts/bom_values.sh /bom/bom_values.sh + ENV DEBIAN_FRONTEND=noninteractive \ TZ=Etc/UTC \ LANG=C.UTF-8 \ @@ -158,7 +177,11 @@ RUN mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools" \ ENV PATH=/usr/local/go/bin:$PATH -RUN curl -fsSL https://go.dev/dl/go1.24.13.linux-amd64.tar.gz -o /tmp/go.tar.gz \ +# Go version from stack-bom.toml; the sha256 below is an integrity pin that must +# be updated in lockstep when the BOM go version changes. +RUN GO_VERSION="$(BOM_FILE=/bom/stack-bom.toml bash /bom/bom_values.sh --get go)" \ + && echo "Installing Go $GO_VERSION (sha256 pinned below)" \ + && curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" -o /tmp/go.tar.gz \ && echo "1fc94b57134d51669c72173ad5d49fd62afb0f1db9bf3f798fd98ee423f8d730 /tmp/go.tar.gz" | sha256sum -c \ && tar -C /usr/local -xzf /tmp/go.tar.gz \ && rm /tmp/go.tar.gz @@ -166,7 +189,10 @@ RUN curl -fsSL https://go.dev/dl/go1.24.13.linux-amd64.tar.gz -o /tmp/go.tar.gz ENV FLUTTER_HOME=/opt/flutter \ PATH=/opt/flutter/bin:/opt/flutter/bin/cache/dart-sdk/bin:$PATH -RUN git clone --depth 1 --branch 3.47.2 https://github.com/flutter/flutter.git "$FLUTTER_HOME" \ +# Flutter branch from stack-bom.toml. +RUN FLUTTER_VERSION="$(BOM_FILE=/bom/stack-bom.toml bash /bom/bom_values.sh --get flutter)" \ + && echo "Cloning Flutter $FLUTTER_VERSION" \ + && git clone --depth 1 --branch "$FLUTTER_VERSION" https://github.com/flutter/flutter.git "$FLUTTER_HOME" \ && git config --global --add safe.directory '*' \ && flutter config --no-analytics \ && flutter precache --android \ @@ -180,6 +206,9 @@ RUN flutter --version && rustup --version && go version # Image for flutter test (no Android SDK or cross-compilers) FROM ubuntu:24.04 AS test +COPY stack-bom.toml /bom/stack-bom.toml +COPY scripts/bom_values.sh /bom/bom_values.sh + ENV DEBIAN_FRONTEND=noninteractive \ TZ=Etc/UTC \ LANG=C.UTF-8 \ @@ -205,7 +234,11 @@ RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \ ENV PATH=/usr/local/go/bin:$PATH -RUN curl -fsSL https://go.dev/dl/go1.24.13.linux-amd64.tar.gz -o /tmp/go.tar.gz \ +# Go version from stack-bom.toml; the sha256 below is an integrity pin that must +# be updated in lockstep when the BOM go version changes. +RUN GO_VERSION="$(BOM_FILE=/bom/stack-bom.toml bash /bom/bom_values.sh --get go)" \ + && echo "Installing Go $GO_VERSION (sha256 pinned below)" \ + && curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" -o /tmp/go.tar.gz \ && echo "1fc94b57134d51669c72173ad5d49fd62afb0f1db9bf3f798fd98ee423f8d730 /tmp/go.tar.gz" | sha256sum -c \ && tar -C /usr/local -xzf /tmp/go.tar.gz \ && rm /tmp/go.tar.gz @@ -213,7 +246,10 @@ RUN curl -fsSL https://go.dev/dl/go1.24.13.linux-amd64.tar.gz -o /tmp/go.tar.gz ENV FLUTTER_HOME=/opt/flutter \ PATH=/opt/flutter/bin:/opt/flutter/bin/cache/dart-sdk/bin:$PATH -RUN git clone --depth 1 --branch 3.47.2 https://github.com/flutter/flutter.git "$FLUTTER_HOME" \ +# Flutter branch from stack-bom.toml. +RUN FLUTTER_VERSION="$(BOM_FILE=/bom/stack-bom.toml bash /bom/bom_values.sh --get flutter)" \ + && echo "Cloning Flutter $FLUTTER_VERSION" \ + && git clone --depth 1 --branch "$FLUTTER_VERSION" https://github.com/flutter/flutter.git "$FLUTTER_HOME" \ && git config --global --add safe.directory '*' \ && flutter config --no-analytics \ && flutter precache --linux \ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000..7b4b872a1a --- /dev/null +++ b/Makefile @@ -0,0 +1,584 @@ +# ============================================================================== +# Stack Wallet build helper. Wraps scripts/build_app.sh; see docs/building.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 ?= +DART ?= +# Make splits unquoted values on whitespace, so a tool path with a space would +# silently resolve to a different binary. Fail early instead. +ifneq ($(strip $(FLUTTER)),) + ifneq ($(words $(FLUTTER)),1) + $(error FLUTTER must not contain spaces; put it on PATH instead) + endif +endif +ifneq ($(strip $(DART)),) + ifneq ($(words $(DART)),1) + $(error DART must not contain spaces; put it on PATH instead) + endif +endif +# Capture explicit overrides before FLUTTER/DART are normalized below. +FLUTTER_USER := $(strip $(FLUTTER)) +DART_USER := $(strip $(DART)) +FLUTTER_BIN := $(if $(FLUTTER),$(if $(findstring /,$(FLUTTER)),$(abspath $(FLUTTER)),$(FLUTTER)),$(shell command -v flutter 2>/dev/null)) +# A Flutter SDK ships its own Dart next to the flutter binary; an explicit +# FLUTTER path should not require a second DART= argument. +DART_BIN := $(if $(DART),$(if $(findstring /,$(DART)),$(abspath $(DART)),$(DART)),$(if $(filter /%,$(FLUTTER_BIN)),$(or $(wildcard $(dir $(FLUTTER_BIN))dart),$(shell command -v dart 2>/dev/null)),$(shell command -v dart 2>/dev/null))) +FLUTTER := $(FLUTTER_BIN) +DART := $(DART_BIN) +# Make splits unquoted values on whitespace. A Flutter found on PATH under a +# directory such as "Application Support" would resolve DART to the directory, +# and verify-bom would fail later with a misleading error. +ifneq ($(strip $(FLUTTER_BIN)),) +ifneq ($(words $(FLUTTER_BIN)),1) +$(error Flutter resolves to '$(FLUTTER_BIN)', which contains a space; move it to a path without spaces or pass FLUTTER=... from such a path) +endif +endif +ifneq ($(strip $(DART)),) +ifneq ($(words $(DART)),1) +$(error Dart resolves to '$(DART)', which contains a space; move it to a path without spaces or pass DART=... from such a path) +endif +endif +SYSTEM_DEPS ?= 0 +# Child scripts call bare `flutter`/`dart`; keep them on the binaries checked +# above instead of whatever PATH would otherwise resolve. Only do this for an +# explicit override: prepending the directory of a Flutter that was already on +# PATH shadows unrelated tools and makes Flutter's hook runner rerun native +# builds because PATH changed. +ifneq ($(FLUTTER_USER),) +ifneq ($(filter /%,$(FLUTTER_BIN)),) +export PATH := $(dir $(FLUTTER_BIN)):$(PATH) +endif +endif +ifneq ($(DART_USER),) +ifneq ($(filter /%,$(DART)),) +export PATH := $(dir $(DART)):$(PATH) +endif +endif +APP_PROJECT_ROOT_DIR := $(CURDIR) +ifeq ($(wildcard Makefile),) + $(error Run make from the repository root) +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 +# Toolchain source. Source builds require Nix (nix develop or direnv); the +# prebuilt path (PREBUILTS=1) uses the host tools on PATH (manual or host). +# The build steps are identical in every mode: only the prerequisite check and +# the Nix environment sanitising differ. Override with TOOLCHAIN=nix|direnv|manual|host. +TOOLCHAIN ?= auto +DIRENV_ACTIVE := $(if $(DIRENV_DIR),1,) +NIX_ACTIVE := $(if $(or $(IN_NIX_SHELL),$(NIX_STORE)),1,) +ifeq ($(strip $(TOOLCHAIN)),) + $(error TOOLCHAIN must not be empty) +endif +ifneq ($(words $(TOOLCHAIN)),1) + $(error TOOLCHAIN must be a single value) +endif +ifneq ($(filter $(TOOLCHAIN),auto nix direnv manual host),$(TOOLCHAIN)) + $(error TOOLCHAIN must be auto, nix, direnv, manual or host) +endif +ifeq ($(TOOLCHAIN),auto) + ifeq ($(DIRENV_ACTIVE),1) + ifeq ($(NIX_ACTIVE),1) + TOOLCHAIN_EFFECTIVE := direnv + else + TOOLCHAIN_EFFECTIVE := host + endif + else + ifeq ($(NIX_ACTIVE),1) + TOOLCHAIN_EFFECTIVE := nix + else + TOOLCHAIN_EFFECTIVE := host + endif + endif +else + TOOLCHAIN_EFFECTIVE := $(TOOLCHAIN) +endif +# Source builds require an active Nix/direnv shell (not just nix on PATH): the +# shell supplies the dnix libraries and the toolchain. SOURCE_TOOLCHAIN is set +# only inside such a shell; the prebuilt path (PREBUILTS=1) uses host tools. +override SOURCE_TOOLCHAIN := $(if $(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),1,) +# Linux builds use a project-local pub cache so cargo finds the repo-local +# .cargo/config.toml that carries PROTOC through Flutter's filtered hook environment. +# Other targets leave PUB_CACHE unset, so Flutter uses its normal per-user cache +# 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) +# Toolchain installed for host-side checks/targets. Native-assets crates pick their own +# pinned toolchain via rust-toolchain.toml; do not export RUSTUP_TOOLCHAIN globally. +BOM_FILE := $(APP_PROJECT_ROOT_DIR)/stack-bom.toml +BOM_RUST := $(shell bash "$(APP_PROJECT_ROOT_DIR)/scripts/bom_values.sh" --get rust "$(BOM_FILE)" 2>/dev/null) +RUST_VERSION ?= $(if $(BOM_RUST),$(BOM_RUST),$(error Cannot read [toolchain] rust from $(BOM_FILE))) +BOM_DNSSEC_RUST := $(shell bash "$(APP_PROJECT_ROOT_DIR)/scripts/bom_values.sh" --get dnssec_rust "$(BOM_FILE)" 2>/dev/null) +DNSSEC_RUST_VERSION ?= $(if $(BOM_DNSSEC_RUST),$(BOM_DNSSEC_RUST),$(error Cannot read [toolchain] dnssec_rust from $(BOM_FILE))) +# Only strip Nix/Apple variables when a Nix shell actually supplied them. In a +# Homebrew or manual shell these are the user's own settings and are kept. +NIX_ENV_UNSET = -u LD -u LDFLAGS -u NIX_LDFLAGS -u NIX_CFLAGS_LINK \ + -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 require-version check-reqs check-reqs-macos check-sdk-macos check-linux check-windows bootstrap-macos bootstrap-xcode sccache-setup cache-stats verify-bom clean clean-app clean-native build-macos build-linux build-windows diagnose-env-macos build-android android-dev-key build-ios + +help: ## Show available commands + @echo "Available targets:" + @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' "$(firstword $(MAKEFILE_LIST))" | awk 'BEGIN {FS = ":.*?## "}; {printf "%-24s %s\n", $$1, $$2}' + +# --- TOOLCHAIN --- + +toolchain: ## Show the active toolchain and tool paths + @echo "requested : $(TOOLCHAIN)" + @echo "effective : $(TOOLCHAIN_EFFECTIVE)" + @echo "NIX_STORE : $${NIX_STORE:-}" + @echo "DIRENV_DIR: $${DIRENV_DIR:-}" + @echo "flutter : $(if $(FLUTTER),$(FLUTTER),missing)" + @echo "dart : $(if $(DART),$(DART),missing)" + @echo "rustup : $$(command -v rustup || echo missing)" +ifeq ($(PLATFORM),Darwin) + @echo "brew : $$(command -v brew || echo missing)" + @echo "xcode : $$(xcode-select -p 2>/dev/null || echo missing)" +endif + +toolchain-check: ## Fail when the requested toolchain is not active +ifeq ($(TOOLCHAIN_EFFECTIVE),nix) + @[ -n "$$NIX_STORE$$IN_NIX_SHELL" ] || { echo >&2 "[ERROR] TOOLCHAIN=nix but this is not a Nix dev shell. Run 'nix develop' (or 'make bootstrap')."; exit 1; } +endif +ifeq ($(TOOLCHAIN_EFFECTIVE),direnv) + @[ -n "$$NIX_STORE$$IN_NIX_SHELL" ] || { echo >&2 "[ERROR] TOOLCHAIN=direnv but the flake is not loaded. Run 'direnv allow', or use 'nix develop'."; exit 1; } +endif +ifeq ($(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),) + @echo "[INFO] $(TOOLCHAIN_EFFECTIVE): using the tools on PATH; no separate check." +endif + +bootstrap: ## Enter the Nix dev shell (primary toolchain; no-op when already inside) + @if [ -n "$$NIX_STORE$$IN_NIX_SHELL" ]; then \ + echo "[OK] Already inside a Nix dev shell ($(TOOLCHAIN_EFFECTIVE))."; \ + elif [ "$(PLATFORM)" = "Darwin" ] && [ "$(UNAME_M)" != "arm64" ] && [ "$(UNAME_M)" != "aarch64" ]; then \ + echo >&2 "[ERROR] Intel macOS is prebuilt-only; use 'make bootstrap-macos' (or a manual toolchain) and PREBUILTS=1."; \ + exit 1; \ + elif ! command -v nix >/dev/null 2>&1; then \ + echo >&2 "[ERROR] Nix is not installed. Source builds require Nix; install it from https://nixos.org/download/."; \ + exit 1; \ + else \ + echo "Entering the Nix dev shell. Run 'make build-macos VERSION=... BUILD_NUM=...' inside it."; \ + exec nix --extra-experimental-features 'nix-command flakes' develop; \ + 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: ## 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; } + @[ -n "$(DART)" ] && command -v "$(DART)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Dart not installed. It ships with Flutter; use 'nix develop' (recommended)."; exit 1; } + @command -v rustup >/dev/null 2>&1 || { echo >&2 "[ERROR] rustup not installed."; exit 1; } + @rustup run $(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 or run 'make bootstrap-xcode'."; exit 1 ;; \ + esac + @xcrun --sdk macosx --show-sdk-path >/dev/null 2>&1 || ( \ + echo "[ERROR] macOS SDK not available. Install Xcode or run: sudo xcode-select --switch /Applications/Xcode.app"; \ + exit 1) + @echo "[OK] macOS SDK available at: $$(xcrun --sdk macosx --show-sdk-path)" +else + @echo >&2 "[ERROR] check-sdk-macos is macOS-only." + @exit 1 +endif + +check-reqs-macos: check-reqs ## Verify macOS-specific tools are available in PATH +ifeq ($(PLATFORM),Darwin) + @echo "Checking macOS-specific tools in PATH..." + @rustup run $(RUST_VERSION) rustc -vV >/dev/null 2>&1 || { echo >&2 "[ERROR] Rust $(RUST_VERSION) toolchain not available. Run 'rustup toolchain install $(RUST_VERSION)', or use 'nix develop'/'make bootstrap-macos'."; exit 1; } + @command -v pod >/dev/null 2>&1 || { echo >&2 "[ERROR] CocoaPods (pod) not installed."; exit 1; } + @command -v xcodebuild >/dev/null 2>&1 || { echo >&2 "[ERROR] xcodebuild not available."; exit 1; } + @echo "[OK] macOS-specific toolchain is available." +else + @echo "[ERROR] check-reqs-macos is macOS-only." + @exit 1 +endif + +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 + +SCCACHE_CARGO_CONFIG ?= $(if $(CARGO_HOME),$(CARGO_HOME),$(HOME)/.cargo)/config.toml + +sccache-setup: ## Opt-in: use sccache for the Rust/C builds run by native-asset hooks (writes ~/.cargo/config.toml if absent) + @command -v sccache >/dev/null 2>&1 || { echo >&2 "[ERROR] sccache not installed (brew install sccache)."; exit 1; } + @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." + +verify-bom: ## Check the local toolchain against stack-bom.toml + @[ -n "$(DART)" ] || { echo >&2 "[ERROR] Dart not installed (needed for verify-bom). Install Flutter or pass DART=/path/to/dart."; exit 1; } + @bash scripts/bom_values.sh --check + @FLUTTER="$(FLUTTER)" "$(DART)" tool/verify_bom.dart --app "$(APP_NAME)" + +cache-stats: ## Show sccache statistics (hit rate) after a build + @command -v sccache >/dev/null 2>&1 || { echo >&2 "[ERROR] sccache not installed."; exit 1; } + @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 $(SOURCE_TOOLCHAIN)),) + 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 ($(filter nix direnv,$(TOOLCHAIN_EFFECTIVE)),) + $(error PREBUILTS=0 (dnix source) requires an active Nix/direnv shell (TOOLCHAIN=nix or direnv); run 'make bootstrap' or use PREBUILTS=1) + endif + endif +endif +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 $(SOURCE_TOOLCHAIN)),$(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 TOOLCHAIN=nix or direnv on x86_64 Linux; use the prebuilt mode) + endif +endif +# Linux only: SYSTEM_DEPS=1 uses the system libsecret/jsoncpp packages instead of building them (like the CI image). +# 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 verify-bom toolchain-check check-reqs-macos check-sdk-macos ## Build macOS release (source in Nix/direnv on Apple Silicon; PREBUILTS=1 uses verified prebuilts) + @echo "--- Configuring project (scripts/build_app.sh)..." + @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) env $(MACOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p macos -a "$(APP_NAME)" $(if $(filter 1,$(PREBUILTS)),-d) + @echo "--- Resolving dependencies..." + @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 verify-bom check-linux toolchain-check check-reqs ## Build Linux release (source when nix is on PATH; PREBUILTS=1 uses verified prebuilts) + @echo "--- Running prebuild bootstrap..." + @cd scripts && bash prebuild.sh + @echo "--- Generating config..." + @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 verify-bom check-windows toolchain-check ## Build Windows release (Git Bash; verified dnix prebuilts) + @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } + @cd scripts && bash prebuild.sh + @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) MWEBD_FETCH=1 ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p windows -a "$(APP_NAME)" -d + @"$(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 verify-bom toolchain-check ## Build Android APKs (requires android/key.properties; prebuilt unless x86_64 Linux in Nix/direnv follows PREBUILTS) + @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } + @[ -f android/key.properties ] || { echo >&2 "[ERROR] android/key.properties is missing. Run 'make android-dev-key' for a local throw-away key; never distribute APKs signed with it."; exit 1; } + @if grep -q '^keyAlias=devkey$$' android/key.properties 2>/dev/null; then \ + echo "[WARN] Signing with the public throw-away dev key; this APK is for local testing only."; \ + fi + @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 verify-bom toolchain-check check-reqs-macos check-sdk-macos ## Build iOS Runner.app without code signing (source in Nix/direnv on Apple Silicon; same steps as CI) + @[ -n "$(FLUTTER)" ] && command -v "$(FLUTTER)" >/dev/null 2>&1 || { echo >&2 "[ERROR] Flutter not installed."; exit 1; } + @xcrun --sdk iphoneos --show-sdk-path >/dev/null 2>&1 || { echo >&2 "[ERROR] iOS SDK not available; install the iOS platform in Xcode."; exit 1; } + @cd scripts && bash prebuild.sh + @cd scripts && $(if $(filter 1,$(CONFIRM)),echo yes |,) env $(IOS_ENV_UNSET) ./build_app.sh -v $(VERSION) -b $(BUILD_NUM) -p ios -a "$(APP_NAME)" $(if $(filter 1,$(PREBUILTS)),-d) + @env $(IOS_ENV_UNSET) "$(FLUTTER)" pub get + @env $(IOS_ENV_UNSET) "$(FLUTTER)" build ios --release --no-codesign diff --git a/README.md b/README.md index 70bf3f836f..f96bb6e57c 100644 --- a/README.md +++ b/README.md @@ -48,3 +48,55 @@ Highlights include: ## Building You can look at the [build instructions](docs/building.md) for more details. +On Apple Silicon macOS, the **Nix dev shell** is the primary *host* toolchain; +Homebrew and manual installs are supported fallbacks. dnix builds the four native +libraries from source under Nix/direnv and verifies the prebuilts otherwise. +`make build-macos` is the same target in every mode, and `make toolchain` +shows which host environment your shell is using. + +### macOS with Nix (recommended; Apple Silicon) + +1. Enter the flake environment: + - `make bootstrap` (runs `nix develop`), or + - `nix develop` directly, or + - `direnv allow` once, if you use direnv with the included `.envrc`. +2. Check the Xcode requirement. Source builds are the default in Nix/direnv + on Apple Silicon and need Xcode **27.0** (build 27A266a); if Xcode 27.0 + is not installed, pass `PREBUILTS=1`. `make bootstrap-xcode` selects an + installed full Xcode and `make verify-bom` checks the host. +3. Run build (pass the release version and a build number; `make` refuses to + guess): + - `make build-macos VERSION=x.y.z BUILD_NUM=nnn` + - Add `CONFIRM=1` for a non-interactive run. + +The flake provides Flutter, Dart, rustup (which installs the BOM Rust version +on first entry), Go, CMake, Meson, Ninja, pkg-config and protoc. Xcode is never provided +by Nix; the flake uses the Xcode selected by `xcode-select`. + +### macOS with Homebrew (prebuilt only) + +Use this when you are not building through Nix/flake. Source builds require a +Nix/direnv shell; Homebrew/manual builds use the verified dnix prebuilts. + +1. With Homebrew installed, install the host tools: + - `brew install autoconf automake libtool cmake cocoapods go meson ninja pkg-config protobuf` + - `rustup toolchain install` the BOM Rust version (see `stack-bom.toml`). +2. Run build: + - `make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1` + - Add `CONFIRM=1` for a non-interactive run. + +`PREBUILTS=1` is required with Homebrew/manual: those toolchains cannot build +the four dnix libraries from source. It uses the verified prebuilts and needs +no Nix for them. `make bootstrap-macos` installs Nix (if missing) and checks/ +selects the full Xcode.app (Xcode is never provided by Nix or Homebrew). + +### macOS with a manual toolchain (advanced) + +Install the prerequisites from [Building on macOS](docs/building/macos.md) +yourself, then run +`make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1`. +Manual builds always use `PREBUILTS=1`: `make` rejects `PREBUILTS=0` outside an +active Nix/direnv shell, even when `nix` is on `PATH`. To build the dnix +libraries from source, use `make bootstrap` (or direnv) instead. +`make check-reqs-macos` reports what is missing (`make check-sdk-macos` checks +full Xcode); `TOOLCHAIN=manual` makes the choice explicit. diff --git a/analysis_options.yaml b/analysis_options.yaml index 3bd4cea564..623f535d06 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -13,7 +13,6 @@ analyzer: - "**/*.g.dart" - "**/*.freezed.dart" - "test/.test_coverage.dart" - - "crypto_plugins/**" - "bin/cache/**" - "lib/generated_plugin_registrant.dart" - "lib/wl_gen/generated/**" diff --git a/bm/README.md b/bm/README.md new file mode 100644 index 0000000000..4e295493a4 --- /dev/null +++ b/bm/README.md @@ -0,0 +1,59 @@ +# Build benchmarks + +Measure wall-clock build time and disk delta for the native-assets build. The +suite runs `make build-macos` / `make build-linux`, so it inherits the same +toolchain rules as the build itself. + +## Run inside a Nix/direnv shell + +Source builds require an active Nix/direnv shell (the flake supplies Flutter, +Rust, Go and the dnix libraries). Run the harness from that shell, exactly as a +real build: + +```sh +make bootstrap # enter the Nix dev shell +bash bm/bench.sh # one cold build (sccache on), appends to bm/results/.csv +``` + +On macOS, `make bootstrap-macos` installs Nix (if missing) and selects Xcode +before you enter the shell. + +## Scripts + +| Script | Purpose | +|---|---| +| `bench.sh` | One build (cold or `--warm`), records wall seconds + disk delta to `bm/results/.csv` | +| `collect.sh` | Snapshot disk/`build/`/toolchain sizes independent of a build | +| `compare.py` | Render/compare the CSVs (terminal table, or markdown for PDF) | +| `render.sh` | Convert a markdown report to HTML + PDF (needs `pandoc`; a PDF engine is optional) | +| `run_all.sh` | Full cold→warm suite, simplest to most optimized | + +## bench.sh flags + +```sh +bash bm/bench.sh # cold build, sccache on (default) +bash bm/bench.sh --warm # warm rebuild (no clean) +bash bm/bench.sh --label NAME # tag the run +bash bm/bench.sh SCCACHE=0 # cold, sccache off +bash bm/bench.sh SKIP_NATIVE=1 # Dart only (no native libs) +``` + +## Caveats + +- **Results are per-machine and git-ignored** (`bm/results/`). Do not commit + them; they vary by hardware and Nix store state. +- **Cold runs assume a warm Nix store.** A fresh store compiles the dnix + libraries from source (~2h) and that time would dominate the wall clock, + masking the sccache-vs-no-sccache comparison. Pre-fetch the dnix sources + (e.g. `nix build` once) before measuring so a cold run only measures the + project build, not the library compile. +- **sccache is a cargo-config toggle, not a make flag.** sccache is turned on + by `make sccache-setup`, which writes `~/.cargo/config.toml` with the + `rustc-wrapper = "sccache"` setting. `bench.sh SCCACHE=0` disables sccache for + that one build by temporarily stripping the `rustc-wrapper` line from the + active cargo config (with a trap that restores it afterward), so a `SCCACHE=0` + run is a genuine no-sccache baseline you can A/B against the default. Leaving + `SCCACHE` unset (or `SCCACHE=1`) runs with sccache as configured. +- **`SKIP_NATIVE=1` is a no-op through `make`.** The Makefile does not consume + it; it is a leftover from the harness's pre-make origin. Use `make clean-native` + + `make build-macos` if you want to isolate the Dart layer. diff --git a/bm/bench.sh b/bm/bench.sh new file mode 100755 index 0000000000..923b1d3320 --- /dev/null +++ b/bm/bench.sh @@ -0,0 +1,177 @@ +#!/usr/bin/env bash +# ============================================================================== +# bench.sh: Simple build benchmark for stack_wallet +# +# Usage: +# bash bm/bench.sh # cold build with sccache (default) +# bash bm/bench.sh --warm # warm rebuild (no clean) +# bash bm/bench.sh SCCACHE=0 # cold, without sccache +# bash bm/bench.sh SKIP_NATIVE=1 # cold, Dart only +# +# Output: bm/results/.csv (one file per machine, all runs appended) +# ============================================================================== +set -euo pipefail + +HOST="$(hostname -s 2>/dev/null || echo unknown)" + +# Pretty banners when toilet is installed; plain text otherwise. +banner() { + if command -v toilet >/dev/null 2>&1; then toilet -f term --metal; else cat; fi +} + +OUTDIR="bm/results" +mkdir -p "$OUTDIR" +OUTFILE="${OUTDIR}/${HOST}.csv" + +WARM=0 +LABEL="" +MAKE_FLAGS="" + +# Parse args +while [ $# -gt 0 ]; do + case "$1" in + --warm) WARM=1; shift ;; + --label) LABEL="$2"; shift 2 ;; + *) MAKE_FLAGS="${MAKE_FLAGS:+${MAKE_FLAGS} }$1"; shift ;; + esac +done + +# Detect platform +case "$(uname -s)" in + Darwin) BUILD_TARGET="build-macos" ;; + Linux) BUILD_TARGET="build-linux" ;; + MINGW*|MSYS*|CYGWIN*) + echo "Git Bash on Windows detected. Benchmarking requires WSL2:" + echo " wsl bash bm/bench.sh" + exit 1 + ;; + *) echo "Unknown platform: $(uname -s)"; exit 1 ;; +esac + +# Git info +COMMIT="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)" +BRANCH="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)" + +# Auto-generate label only if not explicitly set +if [ -z "$LABEL" ]; then + LABEL=$([ $WARM -eq 1 ] && echo "warm" || echo "cold") + if echo "$MAKE_FLAGS" | grep -q "SCCACHE=0"; then + LABEL="${LABEL}-no-sccache" + elif echo "$MAKE_FLAGS" | grep -q "SCCACHE=1"; then + LABEL="${LABEL}-sccache" + fi + if echo "$MAKE_FLAGS" | grep -q "SKIP_NATIVE=1"; then + LABEL="${LABEL}-skip-native" + fi +fi + +DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +ARCH="$(uname -m)" +OS_NAME="$(uname -s)" +OS_VER="$(uname -r)" +echo "Benchmark: ${LABEL}" | banner +echo "Host: $HOST" +echo "OS: $OS_NAME $OS_VER ($ARCH)" +echo "Branch: $BRANCH" +echo "Commit: $COMMIT" +echo "Target: ${BUILD_TARGET}" +echo "Flags: ${MAKE_FLAGS:-(none)}" +echo "" + +# Disk before +DISK_BEFORE=$(du -sk . 2>/dev/null | cut -f1) + +# Clean unless warm +if [ $WARM -eq 0 ]; then + echo "Cleaning" | banner + make clean 2>&1 | tail -1 +fi + +# sccache bypass: SCCACHE=0 must measure a build WITHOUT sccache. sccache is +# enabled only via rustc-wrapper in the active cargo config, so temporarily +# neutralise that line for this one build. A trap guarantees the config is +# restored even if the build crashes. SCCACHE=1 (or unset) leaves sccache as-is. +SCCACHE_BYPASS_CONFIG="" +SCCACHE_BYPASS_BACKUP="" +if echo "$MAKE_FLAGS" | grep -q "SCCACHE=0"; then + SCCACHE_CARGO_CONFIG="$(if [ -n "${CARGO_HOME:-}" ]; then echo "$CARGO_HOME"; else echo "$HOME/.cargo"; fi)/config.toml" + if [ -f "$SCCACHE_CARGO_CONFIG" ] && grep -q "rustc-wrapper" "$SCCACHE_CARGO_CONFIG"; then + SCCACHE_BYPASS_BACKUP="${SCCACHE_CARGO_CONFIG}.bench.bak" + cp -p "$SCCACHE_CARGO_CONFIG" "$SCCACHE_BYPASS_BACKUP" + # Drop the [build] rustc-wrapper line so cargo falls back to plain rustc. + grep -v "rustc-wrapper" "$SCCACHE_CARGO_CONFIG" > "${SCCACHE_CARGO_CONFIG}.bench.tmp" \ + && mv "${SCCACHE_CARGO_CONFIG}.bench.tmp" "$SCCACHE_CARGO_CONFIG" + SCCACHE_BYPASS_CONFIG="$SCCACHE_CARGO_CONFIG" + echo "[INFO] sccache disabled for this build via $SCCACHE_CARGO_CONFIG (backup: $SCCACHE_BYPASS_BACKUP)" + else + echo "[INFO] no rustc-wrapper in $SCCACHE_CARGO_CONFIG; sccache already inactive for this build" + fi +fi +restore_sccache() { + if [ -n "$SCCACHE_BYPASS_BACKUP" ] && [ -f "$SCCACHE_BYPASS_BACKUP" ]; then + mv "$SCCACHE_BYPASS_BACKUP" "$SCCACHE_BYPASS_CONFIG" + echo "[INFO] sccache config restored" + fi + rm -f "${SCCACHE_BYPASS_CONFIG}.bench.tmp" 2>/dev/null || true +} +trap restore_sccache EXIT + +# The Makefile requires VERSION and a BUILD_NUM that is not below the latest +# release tag, and build_app.sh asks an interactive question unless CONFIRM=1. +# Supply benchmark defaults unless the caller passed their own; they are not +# written to the CSV "flags" column, which keeps only what the caller asked for. +BENCH_FLAGS="" +case " ${MAKE_FLAGS} " in *" VERSION="*) ;; *) BENCH_FLAGS="${BENCH_FLAGS} VERSION=0.0.0" ;; esac +case " ${MAKE_FLAGS} " in + *" BUILD_NUM="*) ;; + *) + LATEST_TAG_NUM="$(git tag -l 'build_*' --sort=-v:refname 2>/dev/null | sed -n 's/^build_\([0-9][0-9]*\)$/\1/p' | head -n1)" + BENCH_FLAGS="${BENCH_FLAGS} BUILD_NUM=${LATEST_TAG_NUM:-1}" + ;; +esac +case " ${MAKE_FLAGS} " in *" CONFIRM="*) ;; *) BENCH_FLAGS="${BENCH_FLAGS} CONFIRM=1" ;; esac + +# Build. A failing build must be recorded (success=0), so do not let `set -e` +# abort on the pipeline, and take make's status, not tail's. +echo "Building: make ${BUILD_TARGET} ${MAKE_FLAGS}${BENCH_FLAGS} " | banner +START=$(date +%s) +set +e +# shellcheck disable=SC2086 +make ${BUILD_TARGET} ${MAKE_FLAGS} ${BENCH_FLAGS} 2>&1 | tail -5 +RC=${PIPESTATUS[0]} +set -e +END=$(date +%s) +WALL=$((END - START)) + +# Disk after +DISK_AFTER=$(du -sk . 2>/dev/null | cut -f1) +DISK_DELTA=$((DISK_AFTER - DISK_BEFORE)) + +# Write CSV header if new file +if [ ! -f "$OUTFILE" ]; then + echo "label,branch,commit,host,arch,os_name,os_ver,date,warm,flags,wall_sec,success,disk_total_kb,disk_delta_kb,comment" > "$OUTFILE" +fi + +echo "${LABEL},${BRANCH},${COMMIT},${HOST},${ARCH},${OS_NAME},${OS_VER},${DATE},${WARM},${MAKE_FLAGS:--},${WALL},$((RC == 0 ? 1 : 0)),${DISK_AFTER},${DISK_DELTA}," >> "$OUTFILE" + +echo "" +if [ $RC -eq 0 ]; then + MIN=$((WALL/60)); SEC=$((WALL%60)) + echo "✓ Build succeeded in ${WALL}s (${MIN}m ${SEC}s)" +else + echo "✗ Build FAILED after ${WALL}s" +fi +echo "Results appended: $OUTFILE" | banner +# Show all runs +echo "" +echo "=== All results for $HOST ($ARCH $OS_NAME $OS_VER) ===" +printf "%-12s %-20s %-8s %-10s %4s %10s %8s %s\n" DATE MODE COMMIT FLAGS WARM WALL DISK COMMENT +printf '%s\n' '──────────────────────────────────────────────────────────────────────────────────────' +tail -n +2 "$OUTFILE" | while IFS=, read -r label _branch commit _host _arch _os_name _os_ver date warm flags wall_sec success _disk_total disk_delta comment; do + delta_mb=$((disk_delta / 1024)) + w=$((wall_sec)); m=$((w/60)); s=$((w%60)) + time_fmt="${m}m${s}s" + warm_label=$([ "$warm" = "1" ] && echo "yes" || echo "no") + [ "$success" = "1" ] && ok="✓" || ok="✗" + printf "%-12s %-20s %-8s %-10s %-4s %10s %8s %s\n" "${date:0:10}" "$label" "${commit:0:7}" "${flags:--}" "$warm_label" "$time_fmt" "$ok ${delta_mb}MB" "$comment" +done diff --git a/bm/collect.sh b/bm/collect.sh new file mode 100755 index 0000000000..5f4da469ee --- /dev/null +++ b/bm/collect.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# ============================================================================== +# collect.sh: Measure disk usage and artifact sizes independent of benchmarks +# Usage: ./bm/collect.sh [--outdir DIR] [--baseline NAME] +# +# Outputs a CSV with per-directory and per-artifact sizes. +# ============================================================================== +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" + +# The active benchmark path is bench.sh -> compare.py -> render.sh. Keep this +# collector self-contained so it can snapshot the native-assets layout without +# relying on the retired targets.sh configuration. +BUILD_DIRS=( + .dart_tool + build + .pub-cache + .cargo-target + .sccache-cache +) +ARTIFACT_DIRS=( + build/macos/Build/Products/Release + build/linux/x64/release/bundle + build/windows/x64/runner/Release + build/app/outputs/flutter-apk +) + +detect_platform() { + case "$(uname -s)" in + Darwin) echo "macos" ;; + Linux) echo "linux" ;; + MINGW*|MSYS*|CYGWIN*) echo "windows" ;; + *) echo "unknown" ;; + esac +} + +OUTDIR="${BM_OUTDIR:-$REPO_ROOT/bm/results}" +BASELINE="${BM_BASELINE:-current}" +TIMESTAMP="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" +PLATFORM="$(detect_platform)" +HOSTNAME="$(hostname -s 2>/dev/null || echo "unknown")" + +main() { + while [ $# -gt 0 ]; do + case "$1" in + --outdir) OUTDIR="$2"; shift ;; + --baseline) BASELINE="$2"; shift ;; + *) echo "Unknown: $1"; exit 1 ;; + esac + shift + done + + mkdir -p "$OUTDIR" + local csv="$OUTDIR/sizes_${BASELINE}.csv" + + echo "=== Collecting sizes ($BASELINE, $PLATFORM, $TIMESTAMP) ===" >&2 + + # Header + { + printf "baseline,platform,hostname,date,metric,value_kb,note\n" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},git_commit,$(git -C "$REPO_ROOT" rev-parse HEAD 2>/dev/null || echo unknown)," + } > "$csv" + + # Disk directories + for d in "${BUILD_DIRS[@]}"; do + local path="$REPO_ROOT/$d" + local label + label="disk_$(echo "$d" | tr '/.' '_')" + if [ -d "$path" ] || [ -f "$path" ]; then + local sz + sz="$(du -sk "$path" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},${sz}," >> "$csv" + else + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},0,missing" >> "$csv" + fi + done + + # Artifacts + for a in "${ARTIFACT_DIRS[@]}"; do + local path="$REPO_ROOT/$a" + local label + label="artifact_$(echo "$a" | tr '/.-' '_')" + if [ -e "$path" ]; then + local sz + sz="$(du -sk "$path" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},${sz}," >> "$csv" + else + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${label},0,missing" >> "$csv" + fi + done + + # Total project + local total + total="$(du -sk "$REPO_ROOT" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},total_project,${total}," >> "$csv" + + # Native-assets Rust target directories aggregate. Flutter's hooks keep + # these under .dart_tool instead of the deleted crypto_plugins tree. + local rust_total=0 + while IFS= read -r target_dir; do + local sz + sz="$(du -sk "$target_dir" 2>/dev/null | cut -f1 || echo 0)" + rust_total=$((rust_total + sz)) + done < <(find "$REPO_ROOT/.dart_tool/hooks_runner/shared" \ + -type d -path '*/build/*/target' 2>/dev/null) + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},rust_targets_aggregate,${rust_total}," >> "$csv" + + # Toolchain sizes + for tc_dir in .rustup-home .cargo-home; do + if [ -d "$REPO_ROOT/$tc_dir" ]; then + local tc_label="toolchain_${tc_dir#.}" + local tc_sz + tc_sz="$(du -sk "$REPO_ROOT/$tc_dir" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},${tc_label},${tc_sz},installed_toolchains" >> "$csv" + + # Breakdown: list each toolchain + if [ "$tc_dir" = ".rustup-home" ] && [ -d "$REPO_ROOT/$tc_dir/toolchains" ]; then + for tc in "$REPO_ROOT/$tc_dir/toolchains"/*/; do + local tc_name + tc_name="$(basename "$tc")" + local tc_sz + tc_sz="$(du -sk "$tc" 2>/dev/null | cut -f1 || echo 0)" + echo "${BASELINE},${PLATFORM},${HOSTNAME},${TIMESTAMP},rustup_toolchain_${tc_name},${tc_sz},installed" >> "$csv" + done + fi + fi + done + + echo "--- Sizes written to $csv ---" >&2 +} + +main "$@" diff --git a/bm/compare.py b/bm/compare.py new file mode 100644 index 0000000000..c656f5e645 --- /dev/null +++ b/bm/compare.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +""" +compare.py: Render benchmark results from bm/results/.csv files. + +Usage: + python3 bm/compare.py bm/results/ # terminal report + python3 bm/compare.py bm/results/ > report.md # markdown for bm/render.sh +""" + +import csv, sys, os, json +from collections import defaultdict +from pathlib import Path +from statistics import mean, stdev, median + +PIPE = "│" + +def load_results(results_dir): + rows = [] + for fpath in sorted(Path(results_dir).glob("*.csv")): + if fpath.name.startswith("sizes_"): + continue + try: + with open(fpath) as f: + reader = csv.DictReader(f) + for r in reader: + if r.get("success","0") in ("1", "True"): + rows.append(r) + except Exception as e: + print(f" skip {fpath.name}: {e}", file=sys.stderr) + return rows + + + +def wall_fmt(s): + """Format seconds to human readable.""" + try: + s = int(float(s)) + m, sec = divmod(s, 60) + if m >= 60: + h, m = divmod(m, 60) + return f"{h}h{m:02d}m{sec:02d}s" + return f"{m}m{sec:02d}s" + except: + return str(s) + +def wall_s(s): + """Parse string to int seconds.""" + try: return int(float(s)) + except: return 0 + +def mb(kb_str): + try: return int(float(kb_str)) // 1024 + except: return 0 + +def hr_label(label): + """Human readable label.""" + l = label.lower() + if l == "cold": return "Cold build" + if l == "warm": return "Warm rebuild" + if l == "cold-nosccache": return "Cold (no sccache)" + if l == "cold-sccache": return "Cold (sccache)" + if l == "cold-dart-only": return "Cold (Dart only)" + if l == "warm-nosccache": return "Warm (no sccache)" + if l == "warm-sccache": return "Warm (sccache)" + if l == "warm-dart-only": return "Warm (Dart only)" + if "skip-native" in l: return "Dart only" + return label + +def render(rows, fmt="terminal"): + if not rows: + print("No successful benchmark results found.", file=sys.stderr) + return + + # Group by host then label + by_host = defaultdict(list) + for r in rows: + by_host[r.get("host","unknown")].append(r) + + hdr = ["Date", "Mode", "Commit", "Arch", "OS", "Warm", "Flags", "Wall Time", "Disk Δ", "Comment"] + + for host, host_rows in sorted(by_host.items()): + if fmt == "markdown": + print(f"\n## {host}\n") + else: + print(f"\n{'═'*80}") + print(f" {host}") + print(f"{'═'*80}") + + # Sort: cold first, then by label + host_rows.sort(key=lambda r: (r.get("warm","0"), r.get("label",""))) + + if fmt == "markdown": + print(f"| {' | '.join(hdr)} |") + # Right-align Wall Time column (index 7) for easier comparison + aligns = [":---" if h not in ("Wall Time", "Disk Δ") else "---:" for h in hdr] + print(f"|{'|'.join(aligns)}|") + else: + # Terminal table with rich/box drawing + widths = [max(len(h), 18) for h in hdr] + # Print header + print(PIPE + PIPE.join(h.center(w) for h,w in zip(hdr,widths)) + PIPE) + print(PIPE + PIPE.join("─"*w for w in widths) + PIPE) + + for r in host_rows: + date = (r.get("date","")[:10]).strip() + label = hr_label(r.get("label","")) + commit = r.get("commit","")[:7] + arch = r.get("arch","") + os_str = f"{r.get('os_name','')} {r.get('os_ver','')}" + warm = "yes" if r.get("warm","0") == "1" else "no" + flags = r.get("flags","-").replace("SCCACHE=1,","").replace("SCCACHE=0,","") or "-" + wall = wall_fmt(r.get("wall_sec","")) + disk = f"{mb(r.get('disk_delta_kb',''))}MB" + comment = r.get("comment","") or "" + + cols = [date, label, commit, arch, os_str, warm, flags, wall, disk, comment] + + if fmt == "markdown": + print(f"| {' | '.join(cols)} |") + else: + print(PIPE + PIPE.join(c.center(w) for c,w in zip(cols,widths)) + PIPE) + +def compare(dir1, dir2=None): + """Compare two result directories.""" + rows1 = load_results(dir1) + rows2 = load_results(dir2) if dir2 else [] + all_rows = rows1 + rows2 + + if not all_rows: + print("No benchmark results found.", file=sys.stderr) + return + + # Mark format based on output + is_pipe = not sys.stdout.isatty() + fmt = "markdown" if is_pipe else "terminal" + + render(all_rows, fmt) + + if dir2 and rows1 and rows2: + print(f"\n{'═'*80}") + print(f" Delta: {os.path.basename(dir1)} → {os.path.basename(dir2)}") + print(f"{'═'*80}") + labels1 = {r["label"] for r in rows1} + labels2 = {r["label"] for r in rows2} + for label in sorted(labels1 & labels2): + t1 = wall_s(rows1[0]["wall_sec"]) + t2 = wall_s(rows2[0]["wall_sec"]) + delta = t2 - t1 + pct = (delta/t1)*100 if t1 else 0 + sign = "+" if delta > 0 else "" + print(f" {hr_label(label):25s} {wall_fmt(t1)} → {wall_fmt(t2)} ({sign}{pct:.0f}%)") + + +if __name__ == "__main__": + if len(sys.argv) < 2: + print(f"Usage: {sys.argv[0]} [compare_dir]", file=sys.stderr) + print(f" {sys.argv[0]} bm/results/ # single report", file=sys.stderr) + print(f" {sys.argv[0]} old/ new/ # compare two dirs", file=sys.stderr) + print(f" {sys.argv[0]} bm/results/ > report.md # markdown for PDF", file=sys.stderr) + sys.exit(1) + + compare(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None) diff --git a/bm/render.sh b/bm/render.sh new file mode 100755 index 0000000000..b5868c59f9 --- /dev/null +++ b/bm/render.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# render.sh: Convert benchmark markdown report to HTML + PDF +# Usage: +# ./bm/compare.py bm/results/ > report.md +# ./bm/render.sh report.md [--open] +set -euo pipefail + +MD_FILE="${1:-}" +if [ -z "$MD_FILE" ] || [ ! -f "$MD_FILE" ]; then + echo "Usage: ./bm/render.sh [--open]" + exit 1 +fi + +OPEN=0 +[ "${2:-}" = "--open" ] && OPEN=1 + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +BASE="${MD_FILE%.md}" +HTML_FILE="${BASE}.html" +PDF_FILE="${BASE}.pdf" +CSS_FILE="$SCRIPT_DIR/report.css" + +# Convert to HTML +echo "=== Markdown → HTML ===" +# A private temp file, not a fixed name in /tmp that another user could pre-create. +CSS_HEADER="$(mktemp "${TMPDIR:-/tmp}/bm_css.XXXXXX")" +trap 'rm -f "$CSS_HEADER"' EXIT +{ + echo '' +} > "$CSS_HEADER" + +pandoc "$MD_FILE" \ + --standalone \ + --metadata title="Stack Wallet: Build Benchmark Report" \ + --include-in-header "$CSS_HEADER" \ + -o "$HTML_FILE" +echo " → $HTML_FILE" + +# Convert to PDF +echo "=== HTML → PDF ===" +pdf_ok=0 + +if command -v weasyprint >/dev/null 2>&1; then + weasyprint "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 +elif command -v wkhtmltopdf >/dev/null 2>&1; then + wkhtmltopdf --enable-local-file-access "$HTML_FILE" "$PDF_FILE" 2>/dev/null && pdf_ok=1 +elif [ "$(uname -s)" = "Darwin" ]; then + cupsfilter "$HTML_FILE" > "$PDF_FILE" 2>/dev/null && pdf_ok=1 || true +fi + +if [ "$pdf_ok" -eq 1 ] && [ -f "$PDF_FILE" ]; then + echo " → $PDF_FILE" +else + echo " ⚠ No PDF engine found (install weasyprint or wkhtmltopdf yourself; this script" + echo " never installs packages). HTML ready: $HTML_FILE" +fi + +# Open only when asked, and prefer the PDF. +if [ "$OPEN" -eq 1 ]; then + if [ "$pdf_ok" -eq 1 ] && [ -f "$PDF_FILE" ]; then + open "$PDF_FILE" 2>/dev/null || true + else + open "$HTML_FILE" 2>/dev/null || true + fi +fi + +echo "Done." \ No newline at end of file diff --git a/bm/report.css b/bm/report.css new file mode 100644 index 0000000000..5e26a58650 --- /dev/null +++ b/bm/report.css @@ -0,0 +1,132 @@ +/* Stack Wallet Build Benchmark Report: Professional stylesheet */ +@page { + size: A4 landscape; + margin: 1.5cm 1.8cm; + @bottom-center { + content: "Page " counter(page) " of " counter(pages); + font-size: 7pt; + color: #888; + } +} + +body { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 10pt; + line-height: 1.55; + color: #222; + max-width: 100%; +} + +h1 { + font-size: 20pt; + font-weight: 700; + color: #1a1a1a; + border-bottom: 3px solid #2563eb; + padding-bottom: 8px; + margin-top: 0; + margin-bottom: 6px; +} + +h2 { + font-size: 13pt; + font-weight: 600; + color: #1a1a1a; + border-bottom: 1px solid #ccc; + padding-bottom: 4px; + margin-top: 28px; + margin-bottom: 10px; + page-break-after: avoid; +} + +h3 { + font-size: 11pt; + font-weight: 600; + margin-top: 16px; + margin-bottom: 6px; +} + +p { + margin: 4px 0 8px 0; +} + +table { + border-collapse: collapse; + width: 100%; + margin: 10px 0 16px 0; + font-size: 9pt; + page-break-inside: avoid; +} + +thead { + display: table-header-group; +} + +th { + background: #2563eb; + color: white; + font-weight: 600; + padding: 4px 6px; + text-align: left; + font-size: 7pt; + text-transform: uppercase; + letter-spacing: 0.2px; +} + +td { + border: 1px solid #ccc; + padding: 3px 6px; + text-align: left; + font-family: "SF Mono", "Menlo", "Monaco", "Cascadia Code", monospace; + font-size: 7.5pt; +} + +tr:nth-child(even) td { + background: #f8f9fb; +} + +code { + background: #f0f0f0; + padding: 1px 4px; + border-radius: 3px; + font-family: "SF Mono", "Menlo", "Monaco", monospace; + font-size: 8.5pt; +} + +strong { + color: #111; +} + +a { + color: #2563eb; + text-decoration: none; +} + +/* Improvement column - colored */ +td:last-child { + font-weight: 600; +} + +/* Phase breakdown table: alternating header */ +table:last-of-type th { + background: #1e293b; +} + +/* Key findings list spacing */ +h2 + ul li, h2 + p + ul li { + margin-bottom: 4px; +} + +/* First page has no header */ +@page :first { + margin-top: 2.5cm; +} + +/* Cover / header block */ +.report-meta { + background: #f8f9fb; + border-left: 4px solid #2563eb; + padding: 12px 16px; + margin: 16px 0; + font-size: 9pt; + border-radius: 2px; +} diff --git a/bm/run_all.sh b/bm/run_all.sh new file mode 100755 index 0000000000..f7519e0da2 --- /dev/null +++ b/bm/run_all.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# ============================================================================== +# run_all.sh: Cold → warm pairs, ordered from simplest to most optimized. +# +# Run order: +# A. Cold no-sccache → clean + build without sccache (baseline) +# B. Warm no-sccache → rebuild after A (CARGO_TARGET_DIR benefit only) +# C. Cold sccache → clean + build with sccache +# D. Warm sccache → rebuild after C (sccache + CARGO_TARGET_DIR benefit) +# E. Cold Dart-only → clean + SKIP_NATIVE=1 (no Rust at all) +# F. Warm Dart-only → rebuild after E (Flutter incremental) +# ============================================================================== +set -euo pipefail + +HOST="$(hostname -s 2>/dev/null || echo unknown)" + +# Pretty banners when figlet/toilet are installed; plain text otherwise. +big() { if command -v figlet >/dev/null 2>&1; then figlet "$1"; else echo "== $1 =="; fi; } +banner() { + if command -v toilet >/dev/null 2>&1; then toilet -f term -F border --gay; else cat; fi +} +big "Stack Wallet" + +echo " Full Benchmark Suite" +echo " Host: $HOST " +echo " $(date)" +echo "" + +echo "Cold build (no sccache)" | banner +make clean 2>/dev/null || true +bash bm/bench.sh --label cold-nosccache SCCACHE=0 +echo "" + +echo "Warm after cold no-sccache (CARGO_TARGET_DIR only)" | banner +echo "━━━ B: Warm rebuild (no sccache, CARGO_TARGET_DIR cache hit) ━━━" +bash bm/bench.sh --warm --label warm-nosccache SCCACHE=0 +echo "" + +echo "Cold with sccache" | banner +make clean 2>/dev/null || true +bash bm/bench.sh --label cold-sccache SCCACHE=1 +echo "" + +echo "Warm after cold sccache (sccache + target dir)" | banner +echo "━━━ D: Warm rebuild (sccache + CARGO_TARGET_DIR cache hit) ━━━" +bash bm/bench.sh --warm --label warm-sccache SCCACHE=1 +echo "" + +echo "Cold build (Dart only, SKIP_NATIVE=1)" | banner +make clean 2>/dev/null || true +bash bm/bench.sh --label cold-dart-only SKIP_NATIVE=1 +echo "" + +echo "Warm Dart-only" | banner +bash bm/bench.sh --warm --label warm-dart-only SKIP_NATIVE=1 +echo "" + +echo "════════════════════════════════════════════════════" +echo " Done. Results: bm/results/$HOST.csv" +echo " View: python3 bm/compare.py bm/results/" +echo " PDF: python3 bm/compare.py bm/results/ > report.md && ./bm/render.sh report.md" +echo "════════════════════════════════════════════════════" diff --git a/docs/building.md b/docs/building.md index 7d02e7ca65..e75bbf5f4c 100644 --- a/docs/building.md +++ b/docs/building.md @@ -44,6 +44,12 @@ either mode. To switch modes, rerun `build_app.sh`. It regenerates `pubspec.yaml`, so keep permanent changes in `scripts/app_config/templates/pubspec.template.yaml`. +The `Makefile` selects the mode by toolchain: inside an active Nix/direnv shell +on Apple Silicon macOS and Linux it defaults to source; `host`, `manual`, +Intel macOS and Windows use `PREBUILTS=1` (prebuilt). `PREBUILTS=0` is rejected +outside a Nix/direnv shell, even when `nix` is on `PATH`; calling +`scripts/build_app.sh` directly (without `-d`) only needs `nix` on `PATH`. + ## Configuration options `-a`, `-p`, `-v` and `-b` are required: @@ -53,8 +59,9 @@ permanent changes in `scripts/app_config/templates/pubspec.template.yaml`. | `-a` | `stack_wallet`, `stack_duo`, or `campfire` | | `-p` | `android`, `ios`, `macos`, `linux`, or `windows` | | `-v`, `-b` | App version and numeric build number | -| `-d` | Verified dnix prebuilts; default is verified source builds | +| `-d` | Verified dnix prebuilts; `build_app.sh` defaults to verified source builds | | `-i` | Skip the script's secure-storage and secp256k1 builds; native-assets hooks still run | +| `-s` | Use the system libsecret/JsonCPP on Linux (CI); default builds them from source | | `-f` | Use the existing optional Isar source-build helper; requires its cached source and Rust | | `-w` | Set the dnix WSL distribution; overrides `DNIX_WSL_DISTRIBUTION` | | `-h` | Show help | @@ -71,6 +78,10 @@ check explains how to use `-d` instead; `-d` still needs Rustup. component needs. - [Testing the build setup](building/testing.md): configuration tests, Linux bundle tests, Xelis integration tests, and checking Tor routing. +- [Building with `make`](building/make.md): optional Makefile wrapper that runs + the same CI build steps. +- [Make build flow](building/make-flow.md): the toolchain and build paths as + diagrams, kept in sync with the Makefile. ## Troubleshooting diff --git a/docs/building/linux.md b/docs/building/linux.md index f2d64c6c38..b5abc2b563 100644 --- a/docs/building/linux.md +++ b/docs/building/linux.md @@ -11,13 +11,22 @@ These steps build the Linux desktop app and the Android app on Ubuntu 24.04 | The [Ubuntu packages](#ubuntu-packages) below | Every build | | [Rustup](https://rustup.rs/) | Every app, in both modes | | [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet | -| [Nix](https://nixos.org/download/) | Source mode, the default; not needed with `-d` | +| [Nix](https://nixos.org/download/) | Source mode (`PREBUILTS=0`); not needed with `-d` | | The [Android tools](#android-tools) below | Android builds | +With `make`, source mode (`PREBUILTS=0`) needs an active Nix/direnv shell +(`make bootstrap` or direnv), not just `nix` on `PATH`; outside such a shell +`make` uses `PREBUILTS=1` (prebuilt) and rejects `PREBUILTS=0`. `build_app.sh` +called directly only needs `nix` on `PATH` for source mode. + +A bundle built inside the Nix shell links against Nix's glibc and uses a +`/nix/store` ELF interpreter and RUNPATH, so it runs only on that machine. Use +the Ubuntu image or a host toolchain for a distributable Linux bundle. + **Rustup:** every app builds its DNSSEC resolver with Rust **1.90.0**, and Stack Wallet builds Xelis with Rust **1.99.1**. The build hooks install these -toolchains on first use. To install DNSSEC's ahead of time, run -`rustup toolchain install 1.90.0`. +toolchains on first use. To install both ahead of time, run +`rustup toolchain install 1.90.0 1.99.1`. **Nix:** check `nix --version` from the same environment that runs Flutter. dnix enables the Nix flake features it needs when it invokes Nix. @@ -27,7 +36,7 @@ dnix enables the Nix flake features it needs when it invokes Nix. ```sh sudo apt-get update sudo apt-get install build-essential clang cmake ninja-build pkg-config \ - git curl unzip xz-utils python3 libgtk-3-dev liblzma-dev libssl-dev \ + git curl unzip xz-utils python3 protobuf-compiler patchelf libgtk-3-dev liblzma-dev libssl-dev \ libjsoncpp-dev libsecret-1-dev ``` @@ -46,6 +55,13 @@ Flutter requires. The app pins NDK **28.2.13676358** in its Android template; install it through SDK Manager. Then run `flutter doctor --android-licenses` and `flutter doctor`. The app supports Android API 24 and newer. +On NixOS, enable `programs.nix-ld.enable = true`: the NDK and CMake binaries +distributed by Google are generic Linux executables. The nixpkgs Flutter SDK +is also read-only, and Gradle needs to write inside the `integration_test` +plugin project in that SDK. Without a writable Flutter checkout, build in +`ghcr.io//stackwallet-ci:android` (built with +`docker build --target android .`). + ## Build 1. Clone the repository and create the stubs: @@ -59,7 +75,7 @@ and `flutter doctor`. The app supports Android API 24 and newer. 2. Configure and build the Linux app: ```sh - bash scripts/build_app.sh -a stack_wallet -p linux -v 1.2.3 -b 123 + bash scripts/build_app.sh -a stack_wallet -p linux -v 1.2.3 -b 123 -d flutter pub get dart tool/check_native_overrides.dart stack_wallet flutter build linux --release @@ -71,12 +87,9 @@ and `flutter doctor`. The app supports Android API 24 and newer. `keyPassword`, `storeFile` and `storePassword`. Use the version and build number for your checkout, and read the script's -confirmation before continuing. Add `-d` to the configuration command to use -verified dnix prebuilts: - -```sh -bash scripts/build_app.sh -a stack_wallet -p linux -v 1.2.3 -b 123 -d -``` +confirmation before continuing. The command above uses `-d` (verified dnix +prebuilts). Omit `-d` when `nix` is on `PATH` to build those libraries from +source. See the [configuration options](../building.md#configuration-options). The override check catches package-local dnix overrides; see @@ -92,7 +105,7 @@ Enable KVM for hardware-accelerated emulation. skipped it, run `(cd scripts/linux && bash build_secp256k1.sh)` before starting the app. -Android source builds through dnix need an x86_64 Linux host. +Android source builds through dnix need an x86_64 Linux host in Nix/direnv. ## Prepare a release bundle diff --git a/docs/building/macos.md b/docs/building/macos.md index d0d9e5cce5..4df001f194 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -3,22 +3,48 @@ These steps build the macOS and iOS apps on a Mac with Apple Silicon. For how the build fits together, see the [overview](../building.md). +## Toolchains + +Source builds require a Nix/direnv shell; the manual/Homebrew path below is +for **prebuilt** builds (`PREBUILTS=1`) only. The same build is also available +through Nix: + +| Mode | Setup | +|---|---| +| Nix | `make bootstrap` (enters `nix develop`) | +| direnv | `direnv allow` | +| Manual / Homebrew | install the tools yourself, `make bootstrap-xcode` (selects an installed Xcode), then build with `PREBUILTS=1`. `make bootstrap-macos` additionally installs Nix and is only needed for source builds | + +With Nix or direnv the flake supplies Flutter, Dart, rustup (which installs +the BOM Rust version on first entry), Go, CMake, Meson, Ninja, pkg-config and protoc. +Xcode always comes from the host. The prerequisites below describe the +manual/Homebrew (prebuilt) path. + ## Prerequisites | What | Needed for | |---|---| -| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 | Every build | -| Your usual Xcode | Building the app, in both modes | -| Xcode **27.0**, release build **27A266a**, installed next to your usual Xcode | Source mode, the default: dnix builds its four packages with it, including during `flutter test`. It doesn't need to be selected; see [Install Xcode 27.0](#install-xcode-270) | -| [Homebrew](https://brew.sh/) packages below | Every build | -| [Rustup](https://rustup.rs/) | Every app, in both modes | -| [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet | -| [Nix](https://nixos.org/download/) | Source mode, the default; not needed with `-d` | +| [Flutter](https://docs.flutter.dev/install/manual) 3.47.2 | Manual and Homebrew modes | +| Xcode 27.0 | Building the app, in both dnix modes | +| Xcode **27.0**, release build **27A266a**, installed next to your usual Xcode | Source mode (dnix) with Nix/direnv on Apple Silicon: dnix builds its four packages with it, including during `flutter test`. It doesn't need to be selected; see [Install Xcode 27.0](#install-xcode-270) | +| [Homebrew](https://brew.sh/) packages below | Manual and Homebrew modes | +| [Rustup](https://rustup.rs/) | Manual and Homebrew modes, in both dnix modes | +| [Go](https://go.dev/doc/install) 1.24.1 or newer | Stack Wallet, manual and Homebrew modes | +| [Nix](https://nixos.org/download/) | Source mode (dnix) needs `nix` on `PATH`; not needed with `-d` | ```sh -brew install autoconf automake libtool cmake cocoapods pkg-config +RUST_BOM="$(scripts/bom_values.sh --get rust)" +DNSSEC_RUST_BOM="$(scripts/bom_values.sh --get dnssec_rust)" +brew install autoconf automake libtool cmake cocoapods go meson ninja pkg-config protobuf +rustup toolchain install "$DNSSEC_RUST_BOM" "$RUST_BOM" +rustup target add --toolchain "$RUST_BOM" aarch64-apple-darwin x86_64-apple-darwin \ + aarch64-apple-ios aarch64-apple-ios-sim ``` +Homebrew and manual toolchains use `PREBUILTS=1`; `make` rejects `PREBUILTS=0` +outside a Nix/direnv shell. Calling `scripts/build_app.sh` directly without `-d` +builds the dnix libraries from source when `nix` is on `PATH`. + Check `nix --version` from the same environment that runs Flutter, and use `flutter doctor` to check the Apple SDK and CocoaPods setup. iOS device builds also need your usual signing configuration. The app's deployment targets are @@ -107,7 +133,7 @@ Run the configuration and Flutter build commands in that shell. 2. Configure and build the macOS app: ```sh - bash scripts/build_app.sh -a stack_wallet -p macos -v 1.2.3 -b 123 + bash scripts/build_app.sh -a stack_wallet -p macos -v 1.2.3 -b 123 -d flutter pub get dart tool/check_native_overrides.dart stack_wallet flutter build macos --release @@ -116,8 +142,9 @@ Run the configuration and Flutter build commands in that shell. For iOS, configure with `-p ios` and build with `flutter build ios --release`. Use the version and build number for your checkout, and read the script's -confirmation before continuing. Add `-d` to the configuration command to use -verified dnix prebuilts. See the +confirmation before continuing. `-d` selects the verified dnix prebuilts and +is required when `nix` is not on `PATH`. Omit `-d` when `nix` is available to +build from source; see the [configuration options](../building.md#configuration-options). The override check catches package-local dnix overrides; see [Local overrides](native-libraries.md#local-overrides). diff --git a/docs/building/make-flow.md b/docs/building/make-flow.md new file mode 100644 index 0000000000..edd77bd94b --- /dev/null +++ b/docs/building/make-flow.md @@ -0,0 +1,113 @@ +# Make build flow + +This page is the maintained source for the two build-flow diagrams. GitHub +renders the Mermaid blocks directly; keep the source in sync with the +`Makefile`. + +## 1. Get the tools (once per Mac) + +Nix is the primary host toolchain. direnv is not a separate toolchain: the +tracked `.envrc` is `use flake`, so it activates the same shell as +`nix develop`. Homebrew and manually installed tools are supported fallbacks. + +### History + +`.envrc` started as a standalone environment script; it was reduced to +`use flake` when the flake and Makefile took over the host setup. That is why +direnv is the Nix activator, not a fourth toolchain. Source builds require a +Nix/direnv shell; the manual/Homebrew path below is for prebuilt builds +(`PREBUILTS=1`) only. + +```mermaid +flowchart LR + S["Pick a host
toolchain"] + S --> N["Nix / direnv
source builds
make bootstrap"] + S --> M["Manual / Homebrew
prebuilt only
PREBUILTS=1"] + + N --> F["Flake
Flutter · Rust · Go
CMake · Meson · Ninja"] + M --> P["Tools on PATH
Flutter · Rust · Go"] + + F --> C["make toolchain-check
check-reqs-macos"] + P --> C + + C --> X{"Full Xcode?"} + X -- yes --> R["Ready to build"] + X -- no --> INSTALL["Install full Xcode
dart tool/setup_xcode.dart"] + INSTALL --> XS["make bootstrap-xcode"] + XS --> R +``` + +`make bootstrap-xcode` does not install Xcode. It selects an existing full +install; when it changes the selection it accepts the licence and runs pending +first-launch setup. An already-selected Xcode is left untouched. Use +`dart tool/setup_xcode.dart` or Apple's download page to install one. + +## 2. Build + +`VERSION` and `BUILD_NUM` are required. dnix source is only available through +the Nix/direnv toolchain: it is the default on Apple Silicon macOS and inside +Nix/direnv on Linux. Homebrew, manual and host toolchains, CI and +Windows use the verified prebuilts. + +```mermaid +flowchart TD + O["APP_NAME · VERSION · BUILD_NUM
PREBUILTS=0 source · 1 prebuilt"] + O --> MAC["make build-macos"] + O --> IOS["make build-ios"] + O --> LINUX["make build-linux"] + O --> WIN["make build-windows"] + O --> AND["make build-android"] + + MAC --> MC["checks
require-version · check-sdk-macos
toolchain-check · check-reqs-macos"] + MC --> MP{"PREBUILTS"} + MP -- "0 Apple Silicon Nix/direnv" --> MS["source
Nix + Xcode 27.0"] + MP -- "1 Intel/brew/manual/CI" --> MB["prebuilt -d"] + MS --> MR["build_app.sh -p macos
pub get · prebuild.sh
flutter build macos"] + MB --> MR + + IOS --> IC["checks
require-version · toolchain-check
check-reqs-macos · check-sdk-macos"] + IC --> IP{"PREBUILTS"} + IP -- "0 Apple Silicon Nix/direnv" --> IS["source"] + IP -- "1 Intel/brew/manual/CI" --> IB["prebuilt -d"] + IS --> IR["prebuild.sh
build_app.sh -p ios
pub get · flutter build ios"] + IB --> IR + + LINUX --> LC["checks
require-version · check-linux
toolchain-check · check-reqs"] + LC --> LP{"PREBUILTS"} + LP -- "0 Nix/direnv" --> LS["source (Nix)"] + LP -- "1 brew/manual/host" --> LB["prebuilt -d"] + LS --> LR["prebuild.sh
build_app.sh -p linux
flutter build linux · bundle"] + LB --> LR + + WIN --> WC["checks
require-version · check-windows
toolchain-check · flutter"] + WC --> WR["prebuild.sh
build_app.sh -p windows -d
pub get · flutter build windows
always prebuilt"] + + AND --> AC["checks
require-version · toolchain-check
android/key.properties · SDK"] + AC --> AH{"Host"} + AH -- macOS --> AB["prebuilt -d"] + AH -- "Linux arm64" --> AB + AH -- "Linux x86_64" --> AP{"PREBUILTS"} + AP -- "0 Nix/direnv" --> AS["source"] + AP -- "1 brew/manual/host" --> AB + AB --> AR["prebuild.sh
build_app.sh -p android
pub get · flutter build apk
--split-per-abi"] + AS --> AR +``` + +## Defaults + +| Context | `PREBUILTS` | dnix mode | +|---|---|---| +| macOS developer, Apple Silicon, Nix/direnv | `0` | source, verified; needs Xcode 27.0 | +| macOS developer, Apple Silicon, brew/manual/host | `1` | verified prebuilts (`-d`); source needs Nix/direnv | +| macOS developer, Intel | `1` | verified prebuilts (`-d`) | +| Linux developer in Nix/direnv | `0` | source, verified | +| Linux developer, brew/manual/host | `1` | verified prebuilts (`-d`); source needs Nix/direnv | +| iOS developer, Apple Silicon, Nix/direnv | `0` | source, verified; needs Xcode 27.0 | +| iOS developer, Apple Silicon, brew/manual/host | `1` | verified prebuilts (`-d`) | +| iOS developer, Intel | `1` | verified prebuilts (`-d`) | +| macOS/Linux/iOS CI | `1` (explicit `-d`) | verified prebuilts (`-d`) | +| Windows | `1` (fixed) | verified prebuilts (`-d`) | +| Android on macOS | `1` (default; source needs x86_64 Linux in Nix/direnv) | verified prebuilts (`-d`) | +| Android on x86_64 Linux in Nix/direnv | follows `PREBUILTS` | source by default | +| Android on x86_64 Linux, brew/manual/host | `1` | verified prebuilts (`-d`); source needs Nix/direnv | +| Android on non-x86_64 Linux | `1` (default; source needs x86_64 Linux in Nix/direnv) | verified prebuilts (`-d`) | diff --git a/docs/building/make.md b/docs/building/make.md new file mode 100644 index 0000000000..8599da891c --- /dev/null +++ b/docs/building/make.md @@ -0,0 +1,123 @@ +# Building with `make` + +The `Makefile` is a thin wrapper around the steps in the per-host guides +([Linux](linux.md), [macOS](macos.md), [Windows](windows.md)). It runs the same +build steps as CI; CI passes `-d` explicitly for release builds. Run `make help` for all +targets. The toolchain and build paths are diagrammed in +[Make build flow](make-flow.md). + +`make build-macos`, `build-linux` and `build-ios` run `verify-bom` before +configuring the app, so a toolchain or plugin-pin drift fails early. `make` +builds are local development builds. macOS/Linux/iOS outputs are not +release-signed; Android APKs are signed with `android/key.properties` (a +throw-away key if created via `make android-dev-key`) and must not be +distributed. If `lib/external_api_keys.dart` is missing, `prebuild.sh` creates +empty stubs, so swap providers are disabled; CI decodes the real keys before +building. + +`build_app.sh` asks before replacing generated app files because some +version/build combinations can delete wallet data. `make` keeps that prompt +interactive; pass `CONFIRM=1` for a non-interactive run. + +`VERSION` and `BUILD_NUM` set the app version and build number. Both are +required for build targets: `make` validates them and rejects a `BUILD_NUM` +that is not above the latest `build_*` tag. `APP_NAME` selects the app variant +(`stack_wallet`, `stack_duo` or `campfire`). + +| Variable | Default | Purpose | +|---|---|---| +| `VERSION`, `BUILD_NUM` | required | App version and a build number above the latest release tag | +| `APP_NAME` | `stack_wallet` | `stack_wallet`, `stack_duo` or `campfire` | +| `PREBUILTS` | `0` in an active Nix/direnv shell on Apple Silicon/Linux; otherwise `1` | `0` builds dnix from source (needs a Nix/direnv shell); `1` uses verified prebuilts (`-d`) | +| `ANDROID_PREBUILTS` | follows `PREBUILTS` on x86_64 Linux in a Nix/direnv shell, else `1` | Overrides the Android dnix mode | +| `SYSTEM_DEPS` | `0` | Linux: `1` uses system libsecret/JsonCPP (as CI does) | +| `TOOLCHAIN` | `auto` | `auto`, `nix`, `direnv`, `host` or `manual` | +| `CONFIRM` | `0` | `1` answers build_app.sh's wallet-data warning non-interactively | + +Source mode needs an active Nix/direnv shell (`nix develop` or direnv): the +shell supplies the dnix libraries and the toolchain, so `nix` merely being on +`PATH` is not enough. On Apple Silicon macOS and Linux, `PREBUILTS=0` is the +default inside such a shell: dnix builds the pinned native libraries from +source and verifies their hashes. Everywhere else the Makefile uses +`PREBUILTS=1` and rejects an explicit `PREBUILTS=0` (host and manual +toolchains, Intel macOS, Windows). CI passes `-d` explicitly. + +``` +make build-macos VERSION=x.y.z BUILD_NUM=nnn # dnix source (Nix/direnv, Apple Silicon) +make build-macos VERSION=x.y.z BUILD_NUM=nnn PREBUILTS=1 # verified prebuilts (-d), fast +``` + +## Targets + +| Target | What it does | +|---|---| +| `make build-macos` | `build_app.sh -p macos -a $(APP_NAME)`, `flutter pub get`, `prebuild.sh`, `flutter build macos --release`. Source by default only in Nix/direnv on Apple Silicon; `PREBUILTS=1` uses the verified prebuilts | +| `make build-linux` | `prebuild.sh`, `build_app.sh -p linux`, local libsecret and secp256k1 helper builds, `flutter build linux --release`, then `prepare_release_bundle.py`. Source by default only inside Nix/direnv; `PREBUILTS=1` uses the verified prebuilts | +| `make build-windows` | Git Bash: `prebuild.sh`, `MWEBD_FETCH=1 build_app.sh -p windows -d` (`-d` selects verified prebuilts; secp256k1 is always built by this target), `pub get`, `flutter build windows --release`. Always uses the verified dnix prebuilts. Asset directories are copied on Windows. | +| `make build-android` | Same build commands as CI, without the AAB/upload steps; signs with `android/key.properties` (run `make android-dev-key` for a throw-away test key), needs the Android SDK/NDK and Java. Prebuilt dnix on macOS, non-x86_64 Linux and brew/manual toolchains; x86_64 Linux in Nix/direnv follows `PREBUILTS` | +| `make build-ios` | Same build commands as CI, without signing/packaging, on macOS (`flutter build ios --release --no-codesign`). Source by default only in Nix/direnv on Apple Silicon; CI passes `-d` explicitly | +| `make bootstrap` | Enter the Nix dev shell (primary toolchain); no-op when already inside | +| `make bootstrap-macos` | Install Nix (if missing) and check/select the full Xcode.app. Installing Nix downloads the official installer and runs it with sudo, so it asks first (`NIX_INSTALL_YES=1` skips the question) | +| `make toolchain` | Show the active toolchain (`nix`, `direnv`, `host`, `manual`) | +| `make bootstrap-xcode` | Check and select an installed full Xcode.app | +| `make check-reqs`, `check-reqs-macos`, `check-sdk-macos`, `diagnose-env-macos` | Prerequisite checks and an environment dump | +| `make verify-bom` | Compare the machine and `pubspec.lock` against `stack-bom.toml` | +| `make clean-app` / `make clean-native` | Remove app output / force the native-asset libraries to rebuild | +| `make clean` | Remove build output, Pods and the Flutter build cache | +| `make sccache-setup` / `make cache-stats` | Opt-in sccache wrapper / show sccache statistics | + +## Toolchains on macOS + +Source builds require a Nix/direnv shell; the prebuilt path (`PREBUILTS=1`) +uses the host tools on PATH (manual or host), which Homebrew can supply. + +| Mode | Setup | Notes | +|---|---|---| +| Nix | `make bootstrap` (enters `nix develop`) | The flake provides Flutter and Go from its pinned nixpkgs (currently Flutter 3.47.4 and Go 1.26.7; the BOM recommends Flutter 3.47.2 and pins Go 1.24.13 for CI/Docker, so `make verify-bom` prints a warning for Flutter, not a failure, because 3.47.4 is above the 3.47.2 minimum), Dart, rustup (which installs the BOM Rust version on first entry), CMake, Meson, Ninja, pkg-config and protoc. Xcode always comes from the host. | +| direnv | `direnv allow` | The same flake as Nix, loaded automatically. | +| Manual / Homebrew | install the tools yourself (Homebrew for the prebuilt path) | Source builds are not available without Nix. Use `PREBUILTS=1` with the verified dnix prebuilts; Homebrew can install the tooling (Flutter, Rust, Go, CocoaPods, sccache, …). `make check-reqs-macos` reports what is missing. | + +`make toolchain` prints the active mode and tool paths. +`TOOLCHAIN=nix|direnv` forces a check; `host` and `manual` use whatever is on `PATH`; `auto` (the default) detects a Nix/direnv shell and otherwise uses the host tools. `PREBUILTS=0` needs `nix` or `direnv` as the effective toolchain; `host` and `manual` always build from the verified prebuilts. + +`make check-reqs-macos` verifies the result and `make diagnose-env-macos` prints what was found. + +## Xcode + +`make bootstrap-xcode` only checks and selects an installed Xcode. To install +one, use `dart tool/setup_xcode.dart` (which drives the `xcodes` CLI) or Apple's download +page; the Nix shell never provides Xcode. Source builds (`PREBUILTS=0`, needs +`nix` on `PATH`) need the Xcode 27.0 that dnix pins; `stack-bom.toml` recommends +27.0 for ordinary app builds, including Homebrew/manual prebuilt builds. + +To build with another installed Xcode without changing the global selection, +run for example +`DEVELOPER_DIR=/Applications/Xcode_27.0.app/Contents/Developer make build-macos`. +This affects the Flutter/app build; a source build (`PREBUILTS=0`) still needs +the pinned Xcode 27.0. dnix checks the `xcode-select` choice first and then +scans `/Applications/Xcode*.app`. + +## Keep the build environment the same between runs + +Flutter reruns every native-asset build hook when `PATH` or any `NIX_*` variable differs from the previous build, even if no source changed. Measured on macOS: 33 to 40 s for a repeated build with an unchanged environment, 536 s after putting one extra directory in front of `PATH`, 156 to 164 s after adding a `NIX_*` variable or restoring `PATH`. So build always from the same shell setup (for example only through `make`, or only inside `nix develop`), and do not alternate between a terminal inside `nix develop` and an IDE without it. + +## Toolchain bill of materials + +`stack-bom.toml` lists the toolchain a build is expected to use (Flutter, Dart, Rust, Go, Xcode). It is not a Homebrew package manifest: the native dnix libraries are pinned in each plugin's `dnix.lock`, and the plugins themselves are pinned by `pubspec.lock`. `make verify-bom` compares the local machine against the BOM and exits with an error on a mismatch (a different recommended Flutter or Xcode version is only a warning). Source builds additionally require the Xcode 27.0 that dnix pins; `build_app.sh` enforces that, while `verify-bom` only warns. + +## Optional: sccache for native-asset builds + +`make sccache-setup` writes `$CARGO_HOME/config.toml` (or `~/.cargo/config.toml`) with `rustc-wrapper = "sccache"` (it never overwrites an +existing file). The build hooks only see a filtered environment (Flutter 3.47.x, and also the 3.50 beta tried so far), so +exporting `RUSTC_WRAPPER` does nothing in either: sccache saw no compile requests. Cargo still reads this file +through `HOME`, which works with both versions. (With the 3.50 beta the variable `CARGO_BUILD_RUSTC_WRAPPER` +also gets through.) Check `sccache --show-stats` +after a build. Measured on an Apple Silicon Mac for a from-source build of all native assets (one run each): +775 s without sccache, 665 s with a cold sccache, 534 s with a warm one. The prebuilt path +(`PREBUILTS=1`, `-d`) replaces all four dnix packages (frostdart, tor, epiccash and mwc); most of +the one-minute saving comes from the three heavy ones, so it saved about one minute in a cold build +(12 vs. 13 minutes). + +## Linux notes + +`make build-linux` needs `protoc`, Meson, Ninja, `patchelf` 0.18 or newer, `readelf` and `python3`; inside `nix develop` they are provided. Before building it writes `.cargo/config.toml` with `[env] PROTOC = ""` if the file does not exist (it is git-ignored). This is needed on NixOS, where a generic-Linux `protoc` shipped inside a crate cannot run and the exported variable does not reach the build hooks. Linux builds use a repo-local `.pub-cache` so cargo finds that file; other targets keep the normal per-user cache. `SYSTEM_DEPS=1` uses the system libsecret/JsonCPP packages (as CI does); the default builds them from source. diff --git a/docs/building/windows.md b/docs/building/windows.md index 41d770812b..e02724aaca 100644 --- a/docs/building/windows.md +++ b/docs/building/windows.md @@ -10,10 +10,11 @@ with Windows Flutter. For how the build fits together, see the | What | Needed for | |---|---| | [Flutter](https://docs.flutter.dev/install/manual) 3.47.2, and Git for Windows, which includes Git Bash | Every build | +| GNU Make (`choco install make` or `scoop install make`; Git for Windows does not ship one) | `make build-windows` | | [Visual Studio 2022](https://docs.flutter.dev/platform-integration/windows/setup) with **Desktop development with C++**, CMake tools and a Windows SDK | Every build | -| Windows Developer Mode, for the symlinks Flutter and the asset scripts create | Every build | +| Windows Developer Mode, for the symlinks Flutter and its plugins create | Every build | | [Rustup](https://rustup.rs/) on Windows | Every app's DNSSEC hook and Stack Wallet's Xelis hook, in both modes | -| WSL2 with Ubuntu 24.04, and [Nix](https://nixos.org/download/) inside it | Source mode, the default; not needed with `-d` | +| WSL2 with Ubuntu 24.04, and [Nix](https://nixos.org/download/) inside it | Direct `build_app.sh` source mode; not needed with `-d` or `make build-windows` | | Go 1.24.0 or newer and `mingw-w64` in the default WSL distribution | Stack Wallet's [MWEB build](#mweb), unless you set `MWEBD_FETCH=1` | ## Set up WSL and Nix @@ -64,8 +65,8 @@ Bash. ``` Use the version and build number for your checkout, and read the script's -confirmation before continuing. Add `-d` to the configuration command to use -verified dnix prebuilts. See the +confirmation before continuing. This direct command builds source in +WSL2/Nix; `make build-windows` always uses the verified prebuilts (`-d`). See the [configuration options](../building.md#configuration-options). The override check catches package-local dnix overrides; see [Local overrides](native-libraries.md#local-overrides). 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..4d96151614 --- /dev/null +++ b/flake.nix @@ -0,0 +1,266 @@ +{ + 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; + # Single source of truth for the toolchain versions; the Makefile, + # the Dockerfile and the release workflow read the same file. + bom = builtins.fromTOML (builtins.readFile ./stack-bom.toml); + rustVersion = let + v = bom.toolchain.rust or (throw "stack-bom.toml: missing [toolchain].rust"); + in + if builtins.isString v && builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+" v != null + then v + else throw "stack-bom.toml: [toolchain].rust must be a version string"; + dnssecRustVersion = let + v = bom.toolchain.dnssec_rust or (throw "stack-bom.toml: missing [toolchain].dnssec_rust"); + in + if builtins.isString v && builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+" v != null + then v + else throw "stack-bom.toml: [toolchain].dnssec_rust must be a version string"; + clangMajor = lib.versions.major pkgs.llvmPackages.clang.version; + + commonPackages = with pkgs; [ + flutter + go + rustup + 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; + + 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" + ''} + + # ========================================== + # 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 and run 'make bootstrap-xcode'." + ;; + esac + # 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/app_config/shared/link_assets.sh b/scripts/app_config/shared/link_assets.sh index 7dec8ed960..ff2760bad2 100755 --- a/scripts/app_config/shared/link_assets.sh +++ b/scripts/app_config/shared/link_assets.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash set -x -e +: "${APP_PROJECT_ROOT_DIR:?APP_PROJECT_ROOT_DIR must be set (run through build_app.sh)}" if [ $# -ne 2 ]; then echo "Usage: $0 " @@ -8,26 +9,44 @@ if [ $# -ne 2 ]; then fi SELECT_ASSETS_DIR=$1 -APP_BUILD_PLATFORM=$2 +# $2 (platform) is required by the callers' interface but no longer changes +# behaviour: Windows is detected from the host (uname), not the target. # declare full paths ASSET_SOURCES_DIR="${APP_PROJECT_ROOT_DIR}/asset_sources" ASSETS_DIR="${APP_PROJECT_ROOT_DIR}/assets" - -# finally update symlinks - +# Windows hosts get real copies: symlink privilege is not guaranteed and the +# asset tree is small. Other hosts use symlinks. +WINDOWS_HOST=0 +case "$(uname -s)" in +MINGW*|MSYS*|CYGWIN*) WINDOWS_HOST=1 ;; +esac for dirname in "default_themes" "icon" "lottie" "in_app_logo_icons" "svg"; do LINK_SOURCE_DIR="${ASSET_SOURCES_DIR}/${dirname}/${SELECT_ASSETS_DIR}" - rm -f "${ASSETS_DIR}/${dirname}" + # Remove an old Windows junction as a link, not by recursing into its target. + if [[ "${WINDOWS_HOST}" = 1 && -d "${ASSETS_DIR}/${dirname}" ]]; then + TARGET_WIN_PATH="$(cygpath -w "${ASSETS_DIR}/${dirname}")" + if ! MSYS2_ARG_CONV_EXCL="/C" cmd.exe /C rmdir "$TARGET_WIN_PATH" 2>/dev/null; then + # A real copy directory cannot be removed by rmdir; a reparse point must + # never fall through to rm -rf, which may follow it into asset_sources. + if MSYS2_ARG_CONV_EXCL="/C" cmd.exe /C fsutil reparsepoint query "$TARGET_WIN_PATH" >/dev/null 2>&1; then + echo >&2 "[ERROR] cannot remove the Windows junction ${ASSETS_DIR}/${dirname}; remove it manually." + exit 1 + fi + fi + fi + if [[ "${WINDOWS_HOST}" = 1 ]]; then + rm -rf "${ASSETS_DIR:?}/${dirname:?}" + else + # Only symlinks here: rm -f refuses a real directory instead of deleting it. + rm -f "${ASSETS_DIR:?}/${dirname:?}" + fi - if [[ "${APP_BUILD_PLATFORM}" = 'windows' ]]; then - LINK_SOURCE_DIR_WIN_PATH_VERSION=$(cygpath -w "${LINK_SOURCE_DIR}") - LINK_NAME_WIN_PATH_VERSION=$(cygpath -w "${ASSETS_DIR}") - # Keep CMD switches out of Git Bash's path conversion; paths are native above. - MSYS2_ARG_CONV_EXCL="/C;/D${MSYS2_ARG_CONV_EXCL:+;$MSYS2_ARG_CONV_EXCL}" \ - cmd.exe /C mklink /D "${LINK_NAME_WIN_PATH_VERSION}\\${dirname}" "${LINK_SOURCE_DIR_WIN_PATH_VERSION}" + if [[ "${WINDOWS_HOST}" = 1 ]]; then + mkdir -p "${ASSETS_DIR}/${dirname}" + cp -r "${LINK_SOURCE_DIR}/." "${ASSETS_DIR}/${dirname}/" else ln -s "${LINK_SOURCE_DIR}" "${ASSETS_DIR}/${dirname}" fi diff --git a/scripts/app_config/templates/isar_build.sh b/scripts/app_config/templates/isar_build.sh index 4b78990365..fb0e7ee188 100644 --- a/scripts/app_config/templates/isar_build.sh +++ b/scripts/app_config/templates/isar_build.sh @@ -2,7 +2,7 @@ find_isar_core_lib() { local isar_core_path - isar_core_path=$(find "${HOME}/.pub-cache/git" -type d -path "*/isar_core_ffi" -print -quit 2>/dev/null) + isar_core_path=$(find "${PUB_CACHE:-${HOME}/.pub-cache}/git" -type d -path "*/isar_core_ffi" -print -quit 2>/dev/null) [[ -z "${isar_core_path}" ]] && return 1 echo "${isar_core_path}" } @@ -77,13 +77,14 @@ build_isar_source() { local isar_core_path isar_core_path=$(find_isar_core_lib) || { - echo "Error: could not locate isar_core_ffi inside ~/.pub-cache/git." + echo "Error: could not locate isar_core_ffi inside ${PUB_CACHE:-~/.pub-cache}/git (run flutter pub get first)." return 1 } echo "Found isar_core_ffi at: ${isar_core_path}" - local workspace_root=$(dirname $(dirname "${isar_core_path}")) + local workspace_root + workspace_root=$(dirname "$(dirname "${isar_core_path}")") build_isar_core "${isar_core_path}" "${workspace_root}" || return 1 diff --git a/scripts/app_config/templates/pubspec.template.yaml b/scripts/app_config/templates/pubspec.template.yaml index 3761771c1e..f65ea371ff 100644 --- a/scripts/app_config/templates/pubspec.template.yaml +++ b/scripts/app_config/templates/pubspec.template.yaml @@ -439,5 +439,4 @@ import_sorter: comments: false # Optional, defaults to true ignored_files: # Optional, defaults to [] - \/test\/* - - \/crypto_plugins\/* - \/integration_test\/* diff --git a/scripts/bom_values.sh b/scripts/bom_values.sh new file mode 100755 index 0000000000..05b359314e --- /dev/null +++ b/scripts/bom_values.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# Read one toolchain pin from stack-bom.toml. +# +# scripts/bom_values.sh --get rust +# scripts/bom_values.sh --get rust FILE +set -euo pipefail + +BOM="${BOM_FILE:-stack-bom.toml}" + +section_for() { + case "$1" in + rust|dnssec_rust|flutter|flutter_min|dart_prefix|go|go_min) echo toolchain ;; + xcode|xcode_dnix) echo macos ;; + *) echo "Unknown BOM key: $1" >&2; return 2 ;; + esac +} + +value() { + local key="$1" section result + section="$(section_for "$key")" || exit 2 + result="$( + sed -n "/^\[$section\]/,/^\[/p" "$BOM" | + sed -n "s/^${key}[[:space:]]*=[[:space:]]*\"\([^\"]*\)\".*/\1/p" | + head -n1 + )" + [ -n "$result" ] || { + echo "Missing [$section] $key in $BOM" >&2 + return 1 + } + local count + count="$(grep -cE "^\[$section\][[:space:]]*(#.*)?$" "$BOM" || true)" + [ "$count" -le 1 ] || { + echo "Duplicate [$section] tables in $BOM; keep exactly one." >&2 + return 1 + } + count="$(sed -n "/^\[$section\]/,/^\[/p" "$BOM" | grep -cE "^${key}[[:space:]]*=" || true)" + [ "$count" -le 1 ] || { + echo "Duplicate [$section] $key in $BOM; keep exactly one." >&2 + return 1 + } + # These values are passed to toolchain actions in the release workflow. + # Reject anything that is not a plain version so a data-file edit cannot + # inject a branch, a range or shell syntax. + if [[ "$key" == xcode || "$key" == xcode_dnix || "$key" == dart_prefix ]]; then + [[ "$result" =~ ^[0-9]+\.[0-9]+$ ]] || { + echo "Invalid [$section] $key value '$result' in $BOM (expected x.y)" >&2 + return 1 + } + elif [[ ! "$result" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Invalid [$section] $key value '$result' in $BOM (expected x.y.z)" >&2 + return 1 + fi + printf '%s\n' "$result" +} + +check_all() { + local key + for key in rust dnssec_rust flutter flutter_min dart_prefix go go_min xcode xcode_dnix; do + value "$key" >/dev/null + done + echo "BOM values OK" +} + +usage() { + echo "Usage: $0 --get [bom]" >&2 + echo " $0 --check [bom]" >&2 + exit 2 +} + +case "${1:-}" in + --check) + if [ "$#" -ge 2 ]; then BOM="$2"; fi + ;; + --get) + if [ "$#" -lt 2 ]; then usage; fi + if [ "$#" -ge 3 ]; then BOM="$3"; fi + ;; + *) + usage + ;; +esac + +[ -r "$BOM" ] || { + echo "Cannot read $BOM" >&2 + exit 1 +} + +if [ "$1" = "--check" ]; then + check_all + exit 0 +fi +value "$2" diff --git a/scripts/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/install_nix.sh b/scripts/install_nix.sh new file mode 100755 index 0000000000..983238fb37 --- /dev/null +++ b/scripts/install_nix.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash + +# Checks for Nix and installs it (multi-user daemon) when missing. Source builds +# require Nix (it supplies the dnix libraries and the toolchain), so this runs +# from `make bootstrap-macos` alongside the Xcode check. Nix is the only host +# dependency this script auto-installs: unlike Xcode (Apple's licensing forbids +# redistributing it) and unlike the app's own toolchain (pinned in the BOM), +# Nix is a general build tool with an official, signature-checked installer. +# +# Run directly (bash script.sh). On error this exits the shell; do not source. +if [[ -n "${ZSH_VERSION:-}" ]]; then + if [[ "${ZSH_EVAL_CONTEXT:-}" == *file* ]]; then + set -uo pipefail # sourced in zsh, don't -e + else + set -euo pipefail # executed in zsh + fi +elif [[ -n "${BASH_VERSION:-}" ]]; then + if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then + set -uo pipefail # sourced in bash, don't -e + else + set -euo pipefail # executed in bash + fi +else + set -euo pipefail # unknown shell +fi +die() { echo "$@" >&2; exit 1; } + +if [[ "$(uname -s)" != "Darwin" ]]; then + die "This installer is for macOS only." +fi + +echo "Checking Nix..." + +# A Nix binary on PATH (any install mode) is good enough to build; we do not +# force the daemon if the user already has a working Nix. +if command -v nix >/dev/null 2>&1; then + echo "Nix already installed: $(command -v nix) ($(nix --version 2>/dev/null || echo 'version unknown'))" + exit 0 +fi + +INSTALLER="${NIX_INSTALLER:-https://nixos.org/nix/install}" + +echo "Nix not found on PATH. Installing the multi-user Nix (daemon) from ${INSTALLER}..." +echo "This downloads a shell script and runs it with sudo; it configures /nix/store and the nixbld users." +echo "The script is not pinned or checksum-verified here. Inspect it first, or install Nix yourself" +echo "(https://nixos.org/download/) and re-run." + +# 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 on macOS: it creates the build +# users and sets up launchd so `nix` works for every user. It prompts for sudo. +curl --proto '=https' --tlsv1.2 -fL "$INSTALLER" | sh -s -- --daemon + +# The installer puts nix in ~/.nix-profile/bin, which most login shells source +# via .zshrc/.profile. Non-interactive shells (and `make` invoked from an IDE) +# won't have it on PATH until re-sourced or re-logged-in. +if ! command -v nix >/dev/null 2>&1; then + echo "[WARN] Nix installed but not on PATH in this shell. Open a new terminal, or run:" + echo " . /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh" +fi + +echo "[OK] Nix installed: $(command -v nix 2>/dev/null || echo 'see above')" 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 diff --git a/scripts/prebuild.sh b/scripts/prebuild.sh index df9eadddb4..c7ff329859 100755 --- a/scripts/prebuild.sh +++ b/scripts/prebuild.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash set -e cd -- "$(dirname -- "${BASH_SOURCE[0]}")" diff --git a/scripts/tests/bom_values_test.dart b/scripts/tests/bom_values_test.dart new file mode 100644 index 0000000000..04a7883e48 --- /dev/null +++ b/scripts/tests/bom_values_test.dart @@ -0,0 +1,174 @@ +// Tests for scripts/bom_values.sh --check and --get. +// +// Run with: dart scripts/tests/bom_values_test.dart +// +// Exercises the real shell script against temp BOM files, so it covers the +// sed/grep quoting and the x.y / x.y.z validation that the Dart side cannot. +import 'dart:io'; + +import 'package:test/test.dart'; + +const script = 'scripts/bom_values.sh'; + +void main() { + late Directory root; + + setUp(() { + root = Directory.systemTemp.createTempSync('bom_values_'); + }); + + tearDown(() { + root.deleteSync(recursive: true); + }); + + String writeBom(String body) { + final file = File('${root.path}/stack-bom.toml'); + file.writeAsStringSync(body); + return file.path; + } + + ProcessResult run(String args) => + Process.runSync('bash', [script, ...args.split(' ')]); + + test('--check passes a well-formed BOM', () { + final bom = writeBom(''' +schema_version = "1" + +[toolchain] +rust = "1.99.1" +dnssec_rust = "1.90.0" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0" +xcode_dnix = "27.0" +'''); + final result = run('--check $bom'); + expect(result.exitCode, 0, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stdout, contains('BOM values OK')); + }); + + test('--check rejects an invalid x.y.z version', () { + final bom = writeBom(''' +[toolchain] +rust = "1.99" +dnssec_rust = "1.90.0" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0" +xcode_dnix = "27.0" +'''); + final result = run('--check $bom'); + expect(result.exitCode, 1, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stderr, contains('Invalid')); + }); + + test('--check rejects a non x.y xcode value', () { + final bom = writeBom(''' +[toolchain] +rust = "1.99.1" +dnssec_rust = "1.90.0" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0.1" +xcode_dnix = "27.0" +'''); + final result = run('--check $bom'); + expect(result.exitCode, 1, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stderr, contains('Invalid')); + }); + + test('--check rejects a duplicate section', () { + final bom = writeBom(''' +[toolchain] +rust = "1.99.1" +dnssec_rust = "1.90.0" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0" +xcode_dnix = "27.0" + +[macos] +xcode = "28.0" +xcode_dnix = "28.0" +'''); + final result = run('--check $bom'); + expect(result.exitCode, 1, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stderr, contains('Duplicate')); + }); + + test('--check rejects a missing key', () { + final bom = writeBom(''' +[toolchain] +rust = "1.99.1" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0" +xcode_dnix = "27.0" +'''); + final result = run('--check $bom'); + expect(result.exitCode, 1, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stderr, contains('Missing')); + }); + + test('--get returns a single value', () { + final bom = writeBom(''' +[toolchain] +rust = "1.99.1" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0" +xcode_dnix = "27.0" +'''); + final result = run('--get rust $bom'); + expect(result.exitCode, 0, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stdout.trim(), '1.99.1'); + }); + + test('--get rejects an unknown key', () { + final bom = writeBom(''' +[toolchain] +rust = "1.99.1" +flutter = "3.47.2" +flutter_min = "3.47.0" +dart_prefix = "3.10" +go = "1.27.4" +go_min = "1.27.0" + +[macos] +xcode = "27.0" +xcode_dnix = "27.0" +'''); + final result = run('--get bogus $bom'); + expect(result.exitCode, 2, reason: '${result.stdout}\n${result.stderr}'); + }); +} diff --git a/scripts/tests/verify_bom_parser_test.dart b/scripts/tests/verify_bom_parser_test.dart new file mode 100644 index 0000000000..fa387e218e --- /dev/null +++ b/scripts/tests/verify_bom_parser_test.dart @@ -0,0 +1,231 @@ +// Unit tests for the BOM/lock/pubspec parser helpers in tool/bom_parser.dart. +// +// Run with: dart scripts/tests/verify_bom_parser_test.dart +// +// These cover only the pure parsing and version logic, so they run without a +// Flutter/Dart toolchain or a real checkout. File-backed helpers take their +// text as an argument, which keeps the tests hermetic. +import 'dart:io'; + +import 'package:test/test.dart'; + +import '../../tool/bom_parser.dart'; + +Map section( + Map> bom, + String name, +) => bom[name] ?? {}; + +void main() { + group('readBom', () { + test('parses [section] headers and key = "value" lines', () { + final bom = readBom(''' +schema_version = "1" + +[toolchain] +flutter = "3.47.2" +flutter_min = "3.47.0" +'''); + expect(section(bom, '')['schema_version'], '1'); + expect(section(bom, 'toolchain')['flutter'], '3.47.2'); + expect(section(bom, 'toolchain')['flutter_min'], '3.47.0'); + }); + + test('accepts tab indentation and single quotes', () { + final bom = readBom('[toolchain]\n\tflutter = \'3.47.2\'\n'); + expect(section(bom, 'toolchain')['flutter'], '3.47.2'); + }); + + test('strips a trailing inline comment on a bare value', () { + final bom = readBom('[toolchain]\nrust = "1.99.1" # pinned by nix\n'); + expect(section(bom, 'toolchain')['rust'], '1.99.1'); + }); + + test('keeps "#" inside a quoted value', () { + final bom = readBom('[x]\nkey = "a # b"\n'); + expect(section(bom, 'x')['key'], 'a # b'); + }); + + test('returns an empty map for empty or comment-only input', () { + expect(readBom(''), isEmpty); + expect(readBom('# just a comment\n'), isEmpty); + }); + + test('throws FormatException on an unterminated string', () { + expect(() => readBom('[x]\nkey = "oops\n'), throwsFormatException); + }); + + test('last assignment wins for a repeated key in a section', () { + final bom = readBom('[x]\nkey = "first"\nkey = "second"\n'); + expect(section(bom, 'x')['key'], 'second'); + }); + }); + + group('compareVersions', () { + test('orders by numeric components', () { + expect(compareVersions('3.47.0', '3.47.2'), lessThan(0)); + expect(compareVersions('3.48.0', '3.47.9'), greaterThan(0)); + expect(compareVersions('3.47.2', '3.47.2'), 0); + }); + + test('treats missing components as zero', () { + expect(compareVersions('3.47', '3.47.0'), 0); + expect(compareVersions('3.47.1', '3.47'), greaterThan(0)); + }); + + test('compares only the first three numeric components', () { + // The comparator is intentionally 3-component: the leading x.y.z wins, + // and any suffix numbers beyond it are ignored (a tie). + expect(compareVersions('2.4.5-rc.1', '2.4.5'), 0); + expect(compareVersions('0.0.0-staging.3', '0.0.0-staging.5'), 0); + expect(compareVersions('0.0.0-staging.12', '0.0.0-staging.9'), 0); + // But a differing leading component still orders the versions. + expect(compareVersions('2.0.0-staging.1', '1.9.9'), greaterThan(0)); + }); + }); + + group('shortVersion', () { + test('keeps short strings and truncates long ones at 7 chars', () { + expect(shortVersion('3.47.2'), '3.47.2'); + expect(shortVersion('abc1234def'), 'abc1234'); + }); + }); + + group('resolveOnPath', () { + test('returns a path-containing name unchanged', () { + expect( + resolveOnPath('/opt/flutter/bin/flutter', environment: {'PATH': '/x'}), + '/opt/flutter/bin/flutter', + ); + }); + + test('resolves a bare command found on PATH', () { + final dir = Directory.systemTemp.createTempSync('resolve_path_'); + try { + File('${dir.path}/mytool').writeAsStringSync('#!/bin/sh\n'); + final found = resolveOnPath( + 'mytool', + environment: {'PATH': '${dir.path}:/nonexistent'}, + ); + expect(found, '${dir.path}/mytool'); + } finally { + dir.deleteSync(recursive: true); + } + }); + + test('returns the bare name when the command is not on PATH', () { + expect( + resolveOnPath( + 'definitely-not-a-real-command-xyz', + environment: {'PATH': '/nonexistent'}, + ), + 'definitely-not-a-real-command-xyz', + ); + }); + }); + + group('requireSinglePluginsSection', () { + test('accepts zero or one [plugins] table', () { + expect( + () => requireSinglePluginsSection('[toolchain]\nflutter = "1"\n'), + returnsNormally, + ); + expect( + () => requireSinglePluginsSection('[plugins]\na = "b"\n'), + returnsNormally, + ); + }); + + test('throws on a duplicate [plugins] table', () { + expect( + () => requireSinglePluginsSection( + '[plugins]\na = "b"\n\n[plugins]\nc = "d"\n', + ), + throwsFormatException, + ); + }); + }); + + group('declaredPlugins', () { + test('finds a pinned plugin under dependencies:', () { + const pubspec = ''' +name: app +dependencies: + flutter: + sdk: flutter + tor_ffi_plugin: + git: + url: https://example.com +'''; + expect(declaredPlugins(pubspecText: pubspec), contains('tor_ffi_plugin')); + }); + + test('finds a pinned plugin under dependency_overrides:', () { + const pubspec = ''' +dependency_overrides: + frostdart: + path: ../frostdart +'''; + expect(declaredPlugins(pubspecText: pubspec), contains('frostdart')); + }); + + test('ignores the hooks: user_defines: block', () { + const pubspec = ''' +hooks: + user_defines: + tor_ffi_plugin: + debug: true +'''; + expect(declaredPlugins(pubspecText: pubspec), isEmpty); + }); + + test('returns empty when no known plugin is declared', () { + const pubspec = ''' +dependencies: + flutter: + sdk: flutter +'''; + expect(declaredPlugins(pubspecText: pubspec), isEmpty); + }); + }); + + group('lockRefs', () { + test('reads resolved-ref for a pinned plugin', () { + const lock = ''' + tor_ffi_plugin: + dependency: "direct main" + git: + url: https://example.com + ref: abc + resolved-ref: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef + other_pkg: + dependency: "direct main" + version: "1.0.0" +'''; + final refs = lockRefs(lockText: lock); + expect( + refs['tor_ffi_plugin'], + 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef', + ); + expect(refs.containsKey('other_pkg'), isFalse); + }); + + test('returns empty when no plugin is present', () { + expect( + lockRefs(lockText: 'packages:\n foo:\n version: "1"\n'), + isEmpty, + ); + }); + + test('reads a ref from a CRLF lockfile', () { + // A trailing CR must not break the anchored `^ (\w+):$` header. + const lock = + 'plugins:\r\n tor_ffi_plugin:\r\n' + ' resolved-ref: "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"\r\n'; + expect( + lockRefs(lockText: lock)['tor_ffi_plugin'], + 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef', + ); + }); + }); +} diff --git a/stack-bom.toml b/stack-bom.toml new file mode 100644 index 0000000000..5184a0e898 --- /dev/null +++ b/stack-bom.toml @@ -0,0 +1,18 @@ +# Stack Wallet build bill of materials: the toolchain a build is expected to use. +# Checked by `make verify-bom` (dart tool/verify_bom.dart). This is a toolchain +# file, not a Homebrew package manifest; the native dnix libraries are pinned in +# each plugin's dnix.lock and pubspec.lock pins the plugins themselves. +schema_version = 1 + +[toolchain] +flutter = "3.47.2" # recommended; macOS builds verified with 3.47.2 and 3.47.4 +flutter_min = "3.47.2" # minimum for pubspec.template.yaml and the release workflow; Dockerfile mirrors it +dart_prefix = "3.13" # Dart bundled with Flutter 3.47.x +rust = "1.99.1" # installed through rustup, pinned by the native plugins +dnssec_rust = "1.90.0" # OpenAlias/DNSSEC builds from source in every app +go = "1.24.13" # CI/Docker pin; nix develop uses nixpkgs' newer Go +go_min = "1.24.1" # flutter_mwebd's minimum on the Flutter host + +[macos] +xcode = "27.0" # recommended for app builds +xcode_dnix = "27.0" # dnix needs this one to rebuild Apple libraries byte for byte diff --git a/tool/bom_parser.dart b/tool/bom_parser.dart new file mode 100644 index 0000000000..b4c2a330c8 --- /dev/null +++ b/tool/bom_parser.dart @@ -0,0 +1,173 @@ +// Pure helpers shared by `dart tool/verify_bom.dart` and its unit tests. +// +// These read the minimal TOML the BOM uses (`[section]` headers and +// `key = "value"` lines), compare version strings, and resolve the plugin +// pins from pubspec.lock / pubspec.yaml. They have no side effects and take +// their input as arguments, so they can be tested without a real toolchain. +import 'dart:io'; + +/// Pinned plugin package names. Campfire and Stack Duo declare only a subset, +/// so a missing lock entry is only an error for a plugin the app uses. +const List bomPluginNames = [ + 'flutter_libepiccash', + 'flutter_libmwc', + 'flutter_libsparkmobile', + 'frostdart', + 'tor_ffi_plugin', + 'xelis_wallet_flutter', +]; + +const String bomFileName = 'stack-bom.toml'; + +final RegExp _sectionHeader = RegExp(r'^\[([^\]]+)\][ \t]*(#.*)?$'); +final RegExp _pluginsHeader = RegExp( + r'^\[plugins\][ \t]*(#.*)?$', + multiLine: true, +); + +/// Minimal TOML reader: `[section]` headers and `key = "value"` lines. +/// Accepts tabs or spaces, single or double quotes, and a trailing ` #comment` +/// on a bare value. A value that is not a quoted string keeps everything up to +/// the first ` #`; a quoted value keeps its whole content. +Map> readBom(String text) { + final result = >{}; + var section = ''; + for (final raw in text.split('\n')) { + final line = raw.trim(); + if (line.isEmpty || line.startsWith('#')) continue; + final header = _sectionHeader.firstMatch(line); + if (header != null) { + section = header.group(1)!; + result.putIfAbsent(section, () => {}); + continue; + } + final eq = line.indexOf('='); + if (eq < 0) continue; + final key = line.substring(0, eq).trim(); + var value = line.substring(eq + 1).trim(); + final hash = value.lastIndexOf(' #'); + if (hash >= 0 && value.startsWith('"') == false) { + value = value.substring(0, hash).trim(); + } + if (value.startsWith('"')) { + final end = value.indexOf('"', 1); + if (end < 0) { + throw FormatException('Unterminated string in $bomFileName: $line'); + } + value = value.substring(1, end); + } else if (value.length >= 2 && + value.startsWith("'") && + value.endsWith("'")) { + value = value.substring(1, value.length - 1); + } + result.putIfAbsent(section, () => {})[key] = value; + } + return result; +} + +/// Resolves a bare command name to an absolute path via PATH, or returns the +/// name unchanged if it is not found (so the caller can report "not found"). +/// +/// The PATH *list* separator is ';' on Windows and ':' elsewhere. +/// [Platform.pathSeparator] is the path *component* separator ('/' / '\\'), +/// which is the wrong value for splitting PATH, so it is not used here. +String resolveOnPath(String name, {Map? environment}) { + final env = environment ?? Platform.environment; + if (name.contains('/') || name.contains('\\')) return name; + final listSep = Platform.isWindows ? ';' : ':'; + final sep = Platform.pathSeparator; + for (final dir in (env['PATH'] ?? '').split(listSep)) { + if (dir.isEmpty) continue; + final candidate = File(dir.endsWith(sep) ? dir : '$dir/$name').path; + if (File(candidate).existsSync()) return candidate; + } + return name; +} + +/// The numeric components of a version string, in order. +List versionNumbers(String v) => + RegExp(r'\d+').allMatches(v).map((m) => int.parse(m.group(0)!)).toList(); + +/// Compares two version strings component by component, missing components +/// treated as 0. Returns negative, 0, or positive like [int.compareTo]. +int compareVersions(String a, String b) { + final x = versionNumbers(a), y = versionNumbers(b); + for (var i = 0; i < 3; i++) { + final p = i < x.length ? x[i] : 0, q = i < y.length ? y[i] : 0; + if (p != q) return p.compareTo(q); + } + return 0; +} + +/// Shortens a git ref or version for one-line reports. +String shortVersion(String v) => v.length <= 7 ? v : v.substring(0, 7); + +/// A duplicate `[plugins]` table makes [readBom] silently last-wins and makes +/// `--update` append a second block, so refuse both modes early. +void requireSinglePluginsSection(String text) { + final count = _pluginsHeader.allMatches(text).length; + if (count > 1) { + throw const FormatException( + 'Duplicate [plugins] sections in $bomFileName; keep exactly one.', + ); + } +} + +/// Plugin names declared by the app currently configured in pubspec.yaml. +/// +/// Accepts any consistent indentation and both direct dependencies and +/// dependency_overrides; the hooks: user_defines: block is not a declaration. +Set declaredPlugins({String? pubspecText}) { + final pubspec = File('pubspec.yaml'); + if (!pubspec.existsSync()) return {}; + final lines = (pubspecText ?? pubspec.readAsStringSync()).split('\n'); + final declared = {}; + for (final sectionName in ['dependencies:', 'dependency_overrides:']) { + final header = RegExp('^${RegExp.escape(sectionName)}\\s*(#.*)?\$'); + final start = lines.indexWhere((l) => header.hasMatch(l.trimRight())); + if (start < 0) continue; + String? indent; + for (var i = start + 1; i < lines.length; i++) { + final line = lines[i]; + if (line.trim().isEmpty || line.trimLeft().startsWith('#')) continue; + final m = RegExp(r'^[ \t]+').firstMatch(line); + if (m == null) break; + indent = m.group(0); + break; + } + if (indent == null) continue; + for (var i = start + 1; i < lines.length; i++) { + final line = lines[i]; + if (line.trim().isEmpty || line.trimLeft().startsWith('#')) continue; + final currentIndent = RegExp(r'^[ \t]*').firstMatch(line)!.group(0)!; + if (currentIndent.length < indent.length) break; + if (currentIndent != indent) continue; + final m = RegExp(r'''^[ \t]*["']?(\w+)["']?\s*:''').firstMatch(line); + if (m != null && bomPluginNames.contains(m.group(1))) { + declared.add(m.group(1)!); + } + } + } + return declared; +} + +/// Reads the git refs of the pinned plugins from pubspec.lock. +Map lockRefs({String? lockText}) { + final lock = File('pubspec.lock'); + if (!lock.existsSync()) return {}; + final lines = (lockText ?? lock.readAsStringSync()).split('\n'); + final refs = {}; + for (var i = 0; i < lines.length; i++) { + // Strip a trailing CR so a CRLF lockfile still matches the anchored + // `^ (\w+):$` header; otherwise the ref is silently dropped. + final line = lines[i].replaceFirst(RegExp(r'\r$'), ''); + final m = RegExp(r'^ (\w+):$').firstMatch(line); + if (m == null || !bomPluginNames.contains(m.group(1))) continue; + for (var j = i + 1; j < lines.length && lines[j].startsWith(' '); j++) { + final r = RegExp(r'resolved-ref: "?([0-9a-f]{40})"?') + .firstMatch(lines[j]); + if (r != null) refs[m.group(1)!] = r.group(1)!; + } + } + return refs; +} diff --git a/tool/verify_bom.dart b/tool/verify_bom.dart new file mode 100644 index 0000000000..4532628a8a --- /dev/null +++ b/tool/verify_bom.dart @@ -0,0 +1,332 @@ +// Checks the local toolchain against stack-bom.toml. +// +// Plugin pins live in pubspec.lock, not in the BOM. The plugin check and +// --update only act on a legacy [plugins] table; stack-bom.toml has none, so +// --plugins checks nothing and exits 0. +// +// dart tool/verify_bom.dart check, exit 1 on a mismatch +// dart tool/verify_bom.dart --plugins check a legacy [plugins] table against pubspec.lock +// dart tool/verify_bom.dart --update refresh an existing [plugins] section from pubspec.lock +// +// No packages needed, so it runs before `flutter pub get`. +// +import 'dart:convert'; +import 'dart:io'; + +import 'bom_parser.dart'; + +int _failures = 0; +int _warnings = 0; + +void _ok(String m) => stdout.writeln('[OK] $m'); +void _warn(String m) { + _warnings++; + stdout.writeln('[WARN] $m'); +} + +void _fail(String m) { + _failures++; + stdout.writeln('[FAIL] $m'); +} + +Future _run(String exe, List args) async { + try { + // runInShell lets Windows start flutter.bat. Only stdout is parsed: Flutter + // writes startup-lock warnings to stderr, and appending those to the JSON + // breaks --machine output. + final r = await Process.run(exe, args, runInShell: Platform.isWindows); + if (r.exitCode != 0) return null; + return '${r.stdout}'.trim(); + } on ProcessException { + return null; + } +} + +Future _update() async { + final Map existingPlugins; + try { + final raw = File(bomFileName).readAsStringSync(); + existingPlugins = readBom(raw)['plugins'] ?? {}; + } on FormatException catch (e) { + stderr.writeln(e.message); + exit(2); + } + if (existingPlugins.isEmpty) { + stderr.writeln( + 'Plugin pins are not stored in $bomFileName; pubspec.lock pins them. ' + 'Run flutter pub get instead.', + ); + exit(2); + } + final refs = lockRefs(); + if (refs.isEmpty) { + stderr.writeln('pubspec.lock not found or has none of the plugins.'); + exit(2); + } + final text = File(bomFileName).readAsStringSync(); + try { + requireSinglePluginsSection(text); + } on FormatException catch (e) { + stderr.writeln(e.message); + exit(2); + } + Map existing; + try { + existing = readBom(text)['plugins'] ?? {}; + } on FormatException catch (e) { + stderr.writeln(e.message); + exit(2); + } + // Plugin pins live in pubspec.lock now. Refresh an existing table for older + // branches, but never create one in a BOM that does not carry it. + if (existing.isEmpty && !RegExp(r'\[plugins\]').hasMatch(text)) { + stdout.writeln('No [plugins] table in $bomFileName; nothing to update.'); + return; + } + final declared = declaredPlugins(); + // Without a pubspec.yaml we cannot tell which app is configured; keep the + // old behaviour and update every plugin the lock knows about. + final updateable = declared.isEmpty ? bomPluginNames.toSet() : declared; + final header = RegExp( + r'^\[plugins\][ \t]*(#.*)?$', + multiLine: true, + ).firstMatch(text); + final start = header?.start ?? -1; + if (start < 0 && RegExp(r'\[plugins\]').hasMatch(text)) { + stderr.writeln( + 'Found [plugins] outside a table header; refusing to update', + ); + exit(2); + } + final tailStart = start < 0 + ? text.length + : text.indexOf(RegExp(r'\n\[', multiLine: true), start + 1); + final tail = tailStart < 0 ? '' : text.substring(tailStart); + final head = start < 0 + ? text.trimRight() + : text.substring(0, start).trimRight(); + for (final n in updateable) { + if (!refs.containsKey(n)) { + stderr.writeln( + 'Warning: $n is declared but missing from pubspec.lock; ' + 'pin not updated', + ); + } + } + final buf = StringBuffer(head) + ..writeln('\n') + ..writeln('[plugins]') + ..writeln( + '# Generated by `dart tool/verify_bom.dart --update` from pubspec.lock. Do not edit by hand.', + ); + var refreshed = 0; + var preserved = 0; + for (final n in bomPluginNames) { + if (updateable.contains(n) && refs.containsKey(n)) { + buf.writeln('$n = "${refs[n]}"'); + refreshed++; + } else if (existing.containsKey(n)) { + // Keep pins for apps this checkout is not configured for. + buf.writeln('$n = "${existing[n]}"'); + preserved++; + } + } + for (final entry in existing.entries) { + if (bomPluginNames.contains(entry.key)) continue; + buf.writeln('${entry.key} = "${entry.value}"'); + preserved++; + } + buf.write(tail); + File(bomFileName).writeAsStringSync(buf.toString()); + stdout.writeln( + 'Updated [plugins] in $bomFileName ' + '($refreshed refreshed, $preserved preserved).', + ); +} + +Never _finish() { + stdout.writeln('\n$_failures failure(s), $_warnings warning(s).'); + exit(_failures == 0 ? 0 : 1); +} + +void _checkPlugins(Map> bom) { + final refs = lockRefs(); + final pinned = bom['plugins'] ?? {}; + // Plugin pins are no longer stored in the BOM; pubspec.lock is the source of + // truth. Keep the parser for older branches that still carry a + // [plugins] table. + if (pinned.isEmpty) return; + final declared = declaredPlugins(); + final pubspecExists = File('pubspec.yaml').existsSync(); + // A fresh checkout has no pubspec.yaml: build_app.sh generates it later. + // In that case check every plugin the lock contains, as before. + final required = pubspecExists ? declared : bomPluginNames.toSet(); + if (refs.isEmpty) { + _warn('pubspec.lock not found, plugin pins not checked'); + } else if (required.isEmpty) { + _fail( + 'could not read plugin declarations from pubspec.yaml ' + '(expected them under dependencies: or dependency_overrides:)', + ); + } else { + for (final n in bomPluginNames) { + if (!required.contains(n)) continue; + final ref = refs[n]; + final pin = pinned[n]; + if (ref == null) { + _fail( + '$n is missing from pubspec.lock (path dependency or not resolved)', + ); + } else if (pin == null) { + _fail('$n is missing from [plugins] in $bomFileName (run --update)'); + } else if (pin == ref) { + _ok('$n ${shortVersion(ref)}'); + } else { + _fail( + '$n is ${shortVersion(ref)} in pubspec.lock but ' + '${shortVersion(pin)} in $bomFileName (run --update)', + ); + } + } + } +} + +Future main(List args) async { + if (!File(bomFileName).existsSync()) { + stderr.writeln('Run from the repository root ($bomFileName not found).'); + exit(2); + } + if (args.contains('--update')) return _update(); + + final bomText = File(bomFileName).readAsStringSync(); + Map> bom; + try { + requireSinglePluginsSection(bomText); + bom = readBom(bomText); + } on FormatException catch (e) { + stderr.writeln(e.message); + exit(2); + } + final root = bom[''] ?? {}; + if (root['schema_version'] != '1') { + _fail('schema_version must be 1 in $bomFileName'); + } + if (args.contains('--plugins')) { + _checkPlugins(bom); + _finish(); + } + final tc = bom['toolchain'] ?? {}; + + // Flutter / Dart + final configuredFlutter = Platform.environment['FLUTTER']?.trim() ?? ''; + final flutterExe = + configuredFlutter.isNotEmpty && File(configuredFlutter).existsSync() + ? configuredFlutter + : resolveOnPath('flutter'); + // A Flutter/Dart executable found on PATH under a directory with a space in + // its name breaks the native-assets hooks and the .dart_tool config writers, + // which do not quote paths. Catch it here with a clear error rather than + // failing deep inside a build with a cryptic "No such file or directory". + if (flutterExe.contains(' ')) { + _fail( + 'Flutter is resolved to "$flutterExe": a path with a space in a name ' + 'breaks the build. Move the Flutter checkout to a path with no spaces, ' + 'or set FLUTTER=/path/to/flutter/bin/flutter to an unspaced location.', + ); + _finish(); + } + final fl = await _run(flutterExe, ['--version', '--machine']); + if (fl == null) { + _fail('flutter not found in PATH'); + } else { + final start = fl.indexOf('{'); + final end = fl.lastIndexOf('}'); + if (start < 0 || end <= start) { + _fail('unexpected output from flutter --version --machine'); + } else { + try { + final info = + jsonDecode(fl.substring(start, end + 1)) as Map; + final v = info['frameworkVersion'] as String; + final d = info['dartSdkVersion'] as String; + if (compareVersions(v, tc['flutter_min'] ?? '0') < 0) { + _fail('Flutter $v is older than the minimum ${tc['flutter_min']}'); + } else if (v != tc['flutter']) { + _warn( + 'Flutter $v (recommended ${tc['flutter']}, ' + 'minimum ${tc['flutter_min']})', + ); + } else { + _ok('Flutter $v'); + } + final prefix = tc['dart_prefix'] ?? ''; + if (prefix.isEmpty) { + _fail('dart_prefix is missing from $bomFileName'); + } else if (d.startsWith('$prefix.')) { + _ok('Dart $d'); + } else { + _fail('Dart $d does not match $prefix.x'); + } + } on FormatException { + _fail('could not parse flutter --version --machine output'); + } + } + } + + // Rust + final list = await _run('rustup', ['toolchain', 'list']); + final rust = tc['rust'] ?? ''; + if (list == null) { + _fail('rustup not found in PATH'); + } else if (list.split('\n').any((l) => l.startsWith('$rust-'))) { + _ok('Rust $rust installed via rustup'); + } else { + _fail('Rust $rust is not installed (rustup toolchain install $rust)'); + } + final dnssec = tc['dnssec_rust'] ?? ''; + if (dnssec.isEmpty) { + _fail('dnssec_rust is missing from $bomFileName'); + } else if (list == null) { + // rustup absent: already reported above. + } else if (list.split('\n').any((l) => l.startsWith('$dnssec-'))) { + _ok('DNSSEC Rust $dnssec installed via rustup'); + } else { + _fail( + 'DNSSEC Rust $dnssec is not installed ' + '(rustup toolchain install $dnssec)', + ); + } + + // Go + final go = await _run('go', ['version']); + final gm = go == null ? null : RegExp(r'go(\d+\.\d+(\.\d+)?)').firstMatch(go); + if (gm == null) { + _warn('go not found in PATH; only apps that build Go components need it'); + } else if (compareVersions(gm.group(1)!, tc['go_min'] ?? '0') < 0) { + _fail('Go ${gm.group(1)} is older than the minimum ${tc['go_min']}'); + } else { + _ok('Go ${gm.group(1)}'); + } + + // Xcode (macOS only) + if (Platform.isMacOS) { + final mac = bom['macos'] ?? {}; + final xc = await _run('xcodebuild', ['-version']); + final xm = xc == null ? null : RegExp(r'Xcode (\S+)').firstMatch(xc); + if (xm == null) { + _fail('Xcode not found (xcode-select -p)'); + } else if (xm.group(1) == mac['xcode']) { + _ok('Xcode ${xm.group(1)}'); + } else if (xm.group(1) == mac['xcode_dnix']) { + _warn( + 'Xcode ${xm.group(1)} is the version dnix pins; ' + '${mac['xcode']} is recommended for app builds', + ); + } else { + _warn('Xcode ${xm.group(1)} (recommended ${mac['xcode']})'); + } + } + + _checkPlugins(bom); + _finish(); +}