diff --git a/.github/workflows/ci-master.yml b/.github/workflows/ci-master.yml index 7bbcc1268a..6bce717a55 100644 --- a/.github/workflows/ci-master.yml +++ b/.github/workflows/ci-master.yml @@ -25,7 +25,7 @@ jobs: - name: Install Required Packages run: | sudo apt-get update - sudo apt-get install -y libboost-all-dev libdb-dev libdb++-dev libevent-dev bison + sudo apt-get install -y libboost-all-dev libdb-dev libdb++-dev libevent-dev bison cmake - name: Create Distribution Tarball run: | ./autogen.sh @@ -44,12 +44,82 @@ jobs: with: name: ${{ env.SOURCE_ARTIFACT }} path: ${{ env.SOURCE_ARTIFACT_DIR }} - build-linux: - name: Build for Linux + build-linux-cmake: + name: Build for Linux (CMake) + runs-on: ubuntu-latest + env: + ARTIFACT_DIR: linux-cmake-binaries + TEST_LOG_ARTIFACT_DIR: test-logs + steps: + - name: Set up Python 3.8 + uses: actions/setup-python@v4 + with: + python-version: '3.8' + - name: Checkout + uses: actions/checkout@v4 + - name: Install Required Packages + run: | + sudo apt-get update + sudo apt-get install -y python3-zmq cmake build-essential + - name: Verify ZMQ Installation + run: | + python3 -m pip install --upgrade pip + python3 -m pip install pyzmq + - name: Download Dependencies + run: make -C depends download + - name: Build Dependencies + run: make -C depends -j$(nproc) + - name: Build Firo + run: | + mkdir build + export HOST_TRIPLET=$(depends/config.guess) + cmake -DCMAKE_TOOLCHAIN_FILE=$(realpath depends/$HOST_TRIPLET/toolchain.cmake) -DBUILD_CLI=ON -DBUILD_TESTS=ON -DBUILD_GUI=ON -S$(realpath .) -B$(realpath build) + cd build && make -j$(nproc) + - name: Run Unit Tests + run: | + cd build && make test + - name: Run RPC Tests + env: + TIMEOUT: 600 + run: | + cp -rf build/bin/* build/src/ + qa/pull-tester/rpc-tests.py -extended + - name: Prepare Files for Artifact + run: | + mkdir -p $ARTIFACT_DIR + mv build/bin/{firo-cli,firo-tx,firod,firo-qt} $ARTIFACT_DIR + - name: Upload Artifact + uses: actions/upload-artifact@v4 + with: + name: linux-cmake-binaries + path: ${{ env.ARTIFACT_DIR }} + - name: Prepare Test Logs for Artifact + if: failure() + run: | + tor_log=$(find . -path '*/tor/test-suite.log' -type f || true) + firo_log=$(find . -path '*/src/test-suite.log' -type f || true) + + mkdir -p $TEST_LOG_ARTIFACT_DIR + + if test -f $tor_log; then + mv $tor_log $TEST_LOG_ARTIFACT_DIR/tor.log + fi + + if test -f $firo_log; then + mv $firo_log $TEST_LOG_ARTIFACT_DIR/firo.log + fi + - name: Upload Test Logs Artifact + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-cmake-logs + path: ${{ env.TEST_LOG_ARTIFACT_DIR }} + build-linux-autotools: + name: Build for Linux (Autotools) needs: create-source-distribution runs-on: ubuntu-latest env: - ARTIFACT_DIR: linux-binaries + ARTIFACT_DIR: linux-autotools-binaries TEST_LOG_ARTIFACT_DIR: test-logs steps: - name: Set up Python 3.8 @@ -97,7 +167,7 @@ jobs: - name: Upload Artifact uses: actions/upload-artifact@v4 with: - name: linux-binaries + name: linux-autotools-binaries path: ${{ env.ARTIFACT_DIR }} - name: Prepare Test Logs for Artifact if: failure() @@ -118,14 +188,14 @@ jobs: if: failure() uses: actions/upload-artifact@v4 with: - name: test-logs + name: test-autotools-logs path: ${{ env.TEST_LOG_ARTIFACT_DIR }} - build-windows: - name: Build for Windows + build-windows-autotools: + name: Build for Windows (Autotools) needs: create-source-distribution runs-on: ubuntu-latest env: - ARTIFACT_DIR: windows-binaries + ARTIFACT_DIR: windows-autotools-binaries steps: - name: Getting Source uses: actions/download-artifact@v4 @@ -160,14 +230,98 @@ jobs: - name: Upload Artifact uses: actions/upload-artifact@v4 with: - name: windows-binaries + name: windows-autotools-binaries + path: ${{ env.ARTIFACT_DIR }} + build-windows-cmake: + name: Build for Windows (CMake) + runs-on: ubuntu-latest + env: + ARTIFACT_DIR: windows-cmake-binaries + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Install Required Packages + run: | + sudo apt-get update + sudo apt-get install -y g++-mingw-w64-x86-64 gcc-mingw-w64-x86-64 cmake + - name: Switch MinGW GCC and G++ to POSIX Threading + run: | + sudo update-alternatives --set x86_64-w64-mingw32-gcc /usr/bin/x86_64-w64-mingw32-gcc-posix + sudo update-alternatives --set x86_64-w64-mingw32-g++ /usr/bin/x86_64-w64-mingw32-g++-posix + - name: Download Dependencies + run: make -C depends download + - name: Build Dependencies + run: make -C depends -j$(nproc) HOST=x86_64-w64-mingw32 + - name: Build Firo + run: | + mkdir build + export HOST_TRIPLET=$(x86_64-w64-mingw32-gcc -dumpmachine) + cmake -DCMAKE_TOOLCHAIN_FILE=$(realpath depends/$HOST_TRIPLET/toolchain.cmake) -DBUILD_CLI=ON -DBUILD_TESTS=OFF -DBUILD_GUI=ON -S$(realpath .) -B$(realpath build) + cd build && make -j$(nproc) + - name: Prepare Files for Artifact + run: | + mkdir -p $ARTIFACT_DIR + mv build/bin/{firo-cli.exe,firo-tx.exe,firod.exe,firo-qt.exe} $ARTIFACT_DIR + - name: Upload Artifact + uses: actions/upload-artifact@v4 + with: + name: windows-cmake-binaries + path: ${{ env.ARTIFACT_DIR }} + build-mac-cmake: + name: Build for macOS (CMake) + runs-on: macos-latest + env: + ARTIFACT_DIR: mac-cmake-binaries + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Use Xcode instead of Command Line Tools + run: sudo xcode-select -s /Applications/Xcode.app/Contents/Developer + - name: Set NJOBS variable + run: | + NCPU=$(sysctl -n hw.ncpu) + JOBS=$((NCPU / 2 > 1 ? NCPU / 2 : 1)) # Use half, but at least 1 + echo "NJOBS=$JOBS" >> $GITHUB_ENV # Persist NJOBS across steps + echo "Using $JOBS jobs for parallel builds." + # -j$(sysctl -n hw.activecpu) fails. due to high load on macOS, and crappy github runners. + - name: Install Required Packages + run: | + if ! command -v pkg-config &> /dev/null; then + echo "pkg-config not found, installing..." + brew install pkg-config + else + echo "pkg-config is already installed" + fi + brew install automake coreutils python-setuptools cmake make + # Workaround for macOS: https://github.com/actions/runner/issues/2958 + - name: Install setuptools + run: sudo -H pip install setuptools + - name: Download Dependencies + run: make -C depends download + - name: Build Dependencies + run: | + make -C depends -j$NJOBS + - name: Build Firo + run: | + mkdir build + export HOST_TRIPLET=$(depends/config.guess) + cmake -DCMAKE_TOOLCHAIN_FILE=$(pwd)/depends/$HOST_TRIPLET/toolchain.cmake -DBUILD_CLI=ON -DBUILD_TESTS=OFF -DBUILD_GUI=ON -S$(pwd) -B$(pwd)/build + cd build && make -j$NJOBS + - name: Prepare Files for Artifact + run: | + mkdir -p $ARTIFACT_DIR + mv build/bin/{firo-cli,firo-tx,firod,firo-qt} $ARTIFACT_DIR + - name: Upload Artifact + uses: actions/upload-artifact@v4 + with: + name: mac-cmake-binaries path: ${{ env.ARTIFACT_DIR }} - build-mac: - name: Build for macOS + build-mac-autotools: + name: Build for macOS (Autotools) needs: create-source-distribution runs-on: macos-latest env: - ARTIFACT_DIR: mac-binaries + ARTIFACT_DIR: mac-autotools-binaries steps: - name: Getting Source uses: actions/download-artifact@v4 @@ -208,5 +362,5 @@ jobs: - name: Upload Artifact uses: actions/upload-artifact@v4 with: - name: mac-binaries + name: mac-autotools-binaries path: ${{ env.ARTIFACT_DIR }} \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000000..c650807d4c --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,929 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +# Ubuntu 22.04 LTS Jammy Jellyfish, https://wiki.ubuntu.com/Releases, EOSS in June 2027: +# - CMake 3.22.1, https://packages.ubuntu.com/jammy/cmake +# +# Centos Stream 9, https://www.centos.org/cl-vs-cs/#end-of-life, EOL in May 2027: +# - CMake 3.26.5, https://mirror.stream.centos.org/9-stream/AppStream/x86_64/os/Packages/ +cmake_minimum_required(VERSION 3.22) + +if (${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR}) + message(FATAL_ERROR "In-source builds are not allowed.") +endif() + +#============================= +# Project / Package metadata +#============================= +set(CLIENT_NAME "Firo Core") +set(CLIENT_VERSION_MAJOR 0) +set(CLIENT_VERSION_MINOR 14) +set(CLIENT_VERSION_REVISION 14) +set(CLIENT_VERSION_BUILD 1) +set(CLIENT_VERSION_RC 0) +set(CLIENT_VERSION_IS_RELEASE "false") +set(COPYRIGHT_YEAR "2024") + +# During the enabling of the CXX and CXXOBJ languages, we modify +# CMake's compiler/linker invocation strings by appending the content +# of the user-defined `APPEND_*` variables, which allows overriding +# any flag. We also ensure that the APPEND_* flags are considered +# during CMake's tests, which use the `try_compile()` command. +# +# CMake's docs state that the `CMAKE_TRY_COMPILE_PLATFORM_VARIABLES` +# variable "is meant to be set by CMake's platform information modules +# for the current toolchain, or by a toolchain file." We do our best +# to set it before the `project()` command. +set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES + CMAKE_CXX_COMPILE_OBJECT + CMAKE_OBJCXX_COMPILE_OBJECT + CMAKE_CXX_LINK_EXECUTABLE +) + +project(FiroCore + VERSION ${CLIENT_VERSION_MAJOR}.${CLIENT_VERSION_MINOR}.${CLIENT_VERSION_REVISION} + DESCRIPTION "Firo client software" + HOMEPAGE_URL "https://firo.org/" + LANGUAGES NONE +) + +set(FIRO_DAEMON_NAME firod) +set(FIRO_GUI_NAME firo-qt) +set(FIRO_CLI_NAME firo-cli) +set(FIRO_TX_NAME firo-tx) + +set(CLIENT_VERSION_STRING ${PROJECT_VERSION}) +if(CLIENT_VERSION_RC GREATER 0) + string(APPEND CLIENT_VERSION_STRING "rc${CLIENT_VERSION_RC}") +endif() + +set(COPYRIGHT_HOLDERS "The %s developers") +set(COPYRIGHT_HOLDERS_FINAL "The ${CLIENT_NAME} developers") +set(CLIENT_BUGREPORT "https://github.com/firoorg/firo/issues") + +#============================= +# Set Project-wide output folders +#============================= +if(NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin) +endif() +if(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib) +endif() +if(NOT CMAKE_ARCHIVE_OUTPUT_DIRECTORY) + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib) +endif() + +#============================= +# Language setup +#============================= +if(CMAKE_SYSTEM_NAME STREQUAL "Darwin" AND NOT CMAKE_HOST_APPLE) + # We do not use the install_name_tool when cross-compiling for macOS. + # So disable this tool check in further enable_language() commands. + set(CMAKE_PLATFORM_HAS_INSTALLNAME FALSE) +endif() +enable_language(CXX) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +enable_language(C) +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED ON) +set(CMAKE_C_EXTENSIONS ON) + +list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/module) + +#============================= +# Include utility functions +#============================= +include(cmake/utilities.cmake) + +#============================= +# Configurable options +#============================= +include(CMakeDependentOption) +# When adding a new option, end the with a full stop for consistency. +option(BUILD_DAEMON "Build ${FIRO_DAEMON_NAME} executable." ON) +option(BUILD_GUI "Build ${FIRO_GUI_NAME} executable." ON) +option(BUILD_CLI "Build ${FIRO_CLI_NAME} executable." ON) + + +option(BUILD_UTIL_CHAINSTATE "Build experimental firo-chainstate executable." OFF) +option(BUILD_KERNEL_LIB "Build experimental firokernel library." ${BUILD_UTIL_CHAINSTATE}) + +option(ENABLE_WALLET "Enable wallet." ON) +cmake_dependent_option(BUILD_TESTS "Build tests." OFF "ENABLE_WALLET" OFF) +option(BUILD_TX "Build ${FIRO_TX_NAME} executable." ${BUILD_CLI}) +option(WITH_BDB "Enable Berkeley DB (BDB) wallet support." OFF) +cmake_dependent_option(WARN_INCOMPATIBLE_BDB "Warn when using a Berkeley DB (BDB) version other than 4.8." ON "WITH_BDB" OFF) +if(WITH_BDB) + find_package(BerkeleyDB 4.8 MODULE REQUIRED) + set(USE_BDB ON) + if(NOT BerkeleyDB_VERSION VERSION_EQUAL 4.8) + message(WARNING "Found Berkeley DB (BDB) other than 4.8.\n" + "BDB (legacy) wallets opened by this build will not be portable!" + ) + if(WARN_INCOMPATIBLE_BDB) + message(WARNING "If this is intended, pass \"-DWARN_INCOMPATIBLE_BDB=OFF\".\n" + "Passing \"-DWITH_BDB=OFF\" will suppress this warning." + ) + endif() + endif() +endif() + +option(ENABLE_HARDENING "Attempt to harden the resulting executables." ON) +option(REDUCE_EXPORTS "Attempt to reduce exported symbols in the resulting executables." OFF) +option(WERROR "Treat compiler warnings as errors." OFF) +option(WITH_CCACHE "Attempt to use ccache for compiling." ON) +option(ENABLE_CRASH_HOOKS "Hook into exception/signal/assert handling to gather stack traces (default is off)" OFF) + +if(ENABLE_CRASH_HOOKS) + message(STATUS "Crash hooks enabled") + # Define symbol ENABLE_CRASH_HOOKS for the compiler + add_compile_definitions(ENABLE_CRASH_HOOKS=1) +endif() + +include(CheckCXXCompilerFlag) + +# Check if the linker supports wrapping __cxa_allocate_exception: +check_cxx_compiler_flag("-Wl,-wrap=__cxa_allocate_exception" LINK_WRAP_SUPPORTED) + +if(LINK_WRAP_SUPPORTED) + message(STATUS "Linker supports -Wl,-wrap flag") + # Define symbol to use the wrapped C++ ABI for exception stacktraces + add_compile_definitions(CRASH_HOOKS_WRAPPED_CXX_ABI=1) + set(CRASH_HOOKS_WRAPPED_CXX_ABI ON CACHE BOOL "Use wrapped C++ ABI for exception stacktraces") + # Wrap internal C++ ABI's so that we can attach stacktraces to exceptions + if(WIN32) + set(LDFLAGS_WRAP_EXCEPTIONS -Wl,-wrap,__cxa_allocate_exception -Wl,-wrap,__cxa_free_exception -Wl,-wrap,_assert -Wl,-wrap,_wassert) + else() + set(LDFLAGS_WRAP_EXCEPTIONS -Wl,-wrap,__cxa_allocate_exception -Wl,-wrap,__cxa_free_exception -Wl,-wrap,__assert_fail) + endif() + message(STATUS "Linker flags to wrap exceptions: ${LDFLAGS_WRAP_EXCEPTIONS}") +else() + message(STATUS "Linker does not support -Wl,-wrap flag") +endif() + +if(MINGW) + # Check if the compiler supports the -Wa,-mbig-obj flag (needed on some MinGW targets) + check_cxx_compiler_flag("-Wa,-mbig-obj" HAS_MBIGO_FLAG) + if(HAS_MBIGO_FLAG) + message(STATUS "Compiler supports -Wa,-mbig-obj; appending to CXX flags") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wa,-mbig-obj") + else() + message(STATUS "Compiler does not support -Wa,-mbig-obj") + endif() +endif() + +option(WITH_ZMQ "Enable ZMQ notifications." ON) +if(WITH_ZMQ) + message(STATUS "ZMQ notifications enabled.") + add_compile_definitions(ENABLE_ZMQ=1) + find_package(ZeroMQ 4.0.0 MODULE REQUIRED) +else() + message(STATUS "ZMQ notifications disabled.") + add_compile_definitions(ENABLE_ZMQ=0) +endif() + +option(WITH_USDT "Enable tracepoints for Userspace, Statically Defined Tracing." OFF) +if(WITH_USDT) + find_package(USDT MODULE REQUIRED) +endif() + +cmake_dependent_option(ENABLE_EXTERNAL_SIGNER "Enable external signer support." ON "NOT WIN32" OFF) + +cmake_dependent_option(WITH_QRENCODE "Enable QR code support." ON "BUILD_GUI" OFF) +if(WITH_QRENCODE) + find_package(QRencode MODULE REQUIRED) + set(USE_QRCODE TRUE) +endif() + +cmake_dependent_option(WITH_DBUS "Enable DBus support." ON "CMAKE_SYSTEM_NAME STREQUAL \"Linux\" AND BUILD_GUI" OFF) + + +cmake_dependent_option(BUILD_GUI_TESTS "Build test_firo-qt executable." ON "BUILD_GUI;BUILD_TESTS" OFF) +if(BUILD_GUI) + set(qt_components Core Gui Widgets LinguistTools) + if(ENABLE_WALLET) + list(APPEND qt_components Network) + endif() + if(WITH_DBUS) + if(WIN32) + message(WARNING "Not possible to use DBUS on Windows. Not setting USE_DBUS preprocessor macro.") + else() + list(APPEND qt_components DBus) + set(USE_DBUS TRUE) + message(INFO "USE_DBUS : ${USE_DBUS}") + endif() + else() + message(INFO "DBUS is off. Not setting USE_DBUS preprocessor macro.") + endif() + if(BUILD_GUI_TESTS) + list(APPEND qt_components Test) + endif() + find_package(Qt 5.11.3 MODULE REQUIRED + COMPONENTS ${qt_components} + ) + unset(qt_components) +endif() + +option(BUILD_BENCH "Build bench_firo executable." OFF) +option(BUILD_FUZZ_BINARY "Build fuzz binary." OFF) +option(BUILD_FOR_FUZZING "Build for fuzzing. Enabling this will disable all other targets and override BUILD_FUZZ_BINARY." OFF) + +option(INSTALL_MAN "Install man pages." ON) + +set(APPEND_CPPFLAGS "" CACHE STRING "Preprocessor flags that are appended to the command line after all other flags added by the build system. This variable is intended for debugging and special builds.") +set(APPEND_CFLAGS "" CACHE STRING "C compiler flags that are appended to the command line after all other flags added by the build system. This variable is intended for debugging and special builds.") +set(APPEND_CXXFLAGS "" CACHE STRING "(Objective) C++ compiler flags that are appended to the command line after all other flags added by the build system. This variable is intended for debugging and special builds.") +set(APPEND_LDFLAGS "" CACHE STRING "Linker flags that are appended to the command line after all other flags added by the build system. This variable is intended for debugging and special builds.") +# Appending to this low-level rule variables is the only way to +# guarantee that the flags appear at the end of the command line. +string(APPEND CMAKE_CXX_COMPILE_OBJECT " ${APPEND_CPPFLAGS} ${APPEND_CXXFLAGS}") +string(APPEND CMAKE_CXX_CREATE_SHARED_LIBRARY " ${APPEND_LDFLAGS}") +string(APPEND CMAKE_CXX_LINK_EXECUTABLE " ${APPEND_LDFLAGS}") + +set(configure_warnings) + +include(CheckPIESupported) +check_pie_supported(OUTPUT_VARIABLE check_pie_output LANGUAGES CXX) +if(CMAKE_CXX_LINK_PIE_SUPPORTED) + set(CMAKE_POSITION_INDEPENDENT_CODE ON) +elseif(NOT WIN32) + # The warning is superfluous for Windows. + message(WARNING "PIE is not supported at link time: ${check_pie_output}") + list(APPEND configure_warnings "Position independent code disabled.") +endif() +unset(check_pie_output) + +# The core_interface library aims to encapsulate common build flags. +# It is a usage requirement for all targets except for secp256k1, which +# gets its flags by other means. +add_library(core_interface INTERFACE) +add_library(core_interface_relwithdebinfo INTERFACE) +add_library(core_interface_debug INTERFACE) +target_link_libraries(core_interface INTERFACE + $<$:core_interface_relwithdebinfo> + $<$:core_interface_debug> +) +target_compile_definitions(core_interface + INTERFACE + HAVE_CONFIG_H=1) + +if(BUILD_FOR_FUZZING) + message(WARNING "BUILD_FOR_FUZZING=ON will disable all other targets and force BUILD_FUZZ_BINARY=ON.") + set(BUILD_DAEMON OFF) + set(BUILD_CLI OFF) + set(BUILD_TX OFF) + set(BUILD_UTIL OFF) + set(BUILD_UTIL_CHAINSTATE OFF) + set(BUILD_KERNEL_LIB OFF) + set(BUILD_GUI OFF) + set(ENABLE_EXTERNAL_SIGNER OFF) + set(WITH_ZMQ OFF) + set(BUILD_TESTS OFF) + set(BUILD_GUI_TESTS OFF) + set(BUILD_BENCH OFF) + set(BUILD_FUZZ_BINARY ON) + + target_compile_definitions(core_interface INTERFACE + FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + ) +endif() + +include(ProcessConfigurations) +include(CheckFunctionExists) + +include(TryAppendCXXFlags) +include(TryAppendLinkerFlag) + +if(WIN32) + #[=[ + This build system supports two ways to build binaries for Windows. + + 1. Building on Windows using MSVC. + Implementation notes: + - /DWIN32 and /D_WINDOWS definitions are included into the CMAKE_CXX_FLAGS_INIT + and CMAKE_CXX_FLAGS_INIT variables by default. + - A run-time library is selected using the CMAKE_MSVC_RUNTIME_LIBRARY variable. + - MSVC-specific options, for example, /Zc:__cplusplus, are additionally required. + + 2. Cross-compiling using MinGW. + Implementation notes: + - WIN32 and _WINDOWS definitions must be provided explicitly. + - A run-time library must be specified explicitly using _MT definition. + ]=] + + target_compile_definitions(core_interface INTERFACE + _WIN32_WINNT=0x0601 + _WIN32_IE=0x0501 + WIN32_LEAN_AND_MEAN + NOMINMAX + ) + + if(MSVC) + if(VCPKG_TARGET_TRIPLET MATCHES "-static") + set(msvc_library_linkage "") + else() + set(msvc_library_linkage "DLL") + endif() + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>${msvc_library_linkage}") + unset(msvc_library_linkage) + + target_compile_definitions(core_interface INTERFACE + _UNICODE;UNICODE + ) + target_compile_options(core_interface INTERFACE + /utf-8 + /Zc:preprocessor + /Zc:__cplusplus + /sdl + ) + # Improve parallelism in MSBuild. + # See: https://devblogs.microsoft.com/cppblog/improved-parallelism-in-msbuild/. + list(APPEND CMAKE_VS_GLOBALS "UseMultiToolTask=true") + endif() + + if(MINGW) + target_compile_definitions(core_interface INTERFACE + WIN32 + _WINDOWS + _MT + ) + # Avoid the use of aligned vector instructions when building for Windows. + # See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54412. + try_append_cxx_flags("-Wa,-muse-unaligned-vector-move" TARGET core_interface SKIP_LINK) + try_append_linker_flag("-static" TARGET core_interface) + # We require Windows 7 (NT 6.1) or later. + try_append_linker_flag("-Wl,--major-subsystem-version,6" TARGET core_interface) + try_append_linker_flag("-Wl,--minor-subsystem-version,1" TARGET core_interface) + endif() +endif() + +# Use 64-bit off_t on 32-bit Linux. +if (CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_SIZEOF_VOID_P EQUAL 4) + # Ensure 64-bit offsets are used for filesystem accesses for 32-bit compilation. + target_compile_definitions(core_interface INTERFACE + _FILE_OFFSET_BITS=64 + ) +endif() + +if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + target_compile_definitions(core_interface INTERFACE OBJC_OLD_DISPATCH_PROTOTYPES=0) + # These flags are specific to ld64, and may cause issues with other linkers. + # For example: GNU ld will interpret -dead_strip as -de and then try and use + # "ad_strip" as the symbol for the entry point. + try_append_linker_flag("-Wl,-dead_strip" TARGET core_interface) + try_append_linker_flag("-Wl,-dead_strip_dylibs" TARGET core_interface) + if(CMAKE_HOST_APPLE) + try_append_linker_flag("-Wl,-headerpad_max_install_names" TARGET core_interface) + endif() +endif() + +set(THREADS_PREFER_PTHREAD_FLAG ON) +find_package(Threads REQUIRED) +target_link_libraries(core_interface INTERFACE + Threads::Threads +) + +add_library(sanitize_interface INTERFACE) +target_link_libraries(core_interface INTERFACE sanitize_interface) +if(SANITIZERS) + # First check if the compiler accepts flags. If an incompatible pair like + # -fsanitize=address,thread is used here, this check will fail. This will also + # fail if a bad argument is passed, e.g. -fsanitize=undfeined + try_append_cxx_flags("-fsanitize=${SANITIZERS}" TARGET sanitize_interface + RESULT_VAR cxx_supports_sanitizers + SKIP_LINK + ) + if(NOT cxx_supports_sanitizers) + message(FATAL_ERROR "Compiler did not accept requested flags.") + endif() + + # Some compilers (e.g. GCC) require additional libraries like libasan, + # libtsan, libubsan, etc. Make sure linking still works with the sanitize + # flag. This is a separate check so we can give a better error message when + # the sanitize flags are supported by the compiler but the actual sanitizer + # libs are missing. + try_append_linker_flag("-fsanitize=${SANITIZERS}" VAR SANITIZER_LDFLAGS + SOURCE " + #include + #include + extern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { return 0; } + __attribute__((weak)) // allow for libFuzzer linking + int main() { return 0; } + " + RESULT_VAR linker_supports_sanitizers + ) + if(NOT linker_supports_sanitizers) + message(FATAL_ERROR "Linker did not accept requested flags, you are missing required libraries.") + endif() +endif() +target_link_options(sanitize_interface INTERFACE ${SANITIZER_LDFLAGS}) + +if(BUILD_FUZZ_BINARY) + include(CheckSourceCompilesAndLinks) + check_cxx_source_links_with_flags("${SANITIZER_LDFLAGS}" " + #include + #include + extern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { return 0; } + // No main() function. + " FUZZ_BINARY_LINKS_WITHOUT_MAIN_FUNCTION + ) +endif() + +include(AddBoostIfNeeded) +add_boost_if_needed() + +if(BUILD_DAEMON OR BUILD_GUI OR BUILD_CLI OR BUILD_TESTS OR BUILD_BENCH OR BUILD_FUZZ_BINARY) + find_package(Libevent 2.1.8 MODULE REQUIRED) +endif() + +# Find bls-dash library +find_library(BLS_DASH_LIBRARY + NAMES bls-dash + REQUIRED +) + +if(${BLS_DASH_LIBRARY} STREQUAL "BLS_DASH_LIBRARY-NOTFOUND") + message(FATAL_ERROR "bls-dash library not found") +else() + message(STATUS "Found bls-dash library: ${BLS_DASH_LIBRARY}") +endif() + +# Find tor library +find_library(TOR_LIBRARY + NAMES tor + REQUIRED +) + +# Find OpenSSL library +find_package(OpenSSL 1.1.1 REQUIRED) + +# Find MiniUPNP library +find_library(MINIUPNP_LIBRARY + NAMES miniupnpc + REQUIRED +) + +# Find GMP library +find_package(GMP 6.2.1 REQUIRED) + +# Find zlib library +find_library(ZLIB_LIBRARY + NAMES z + REQUIRED +) + +if(${TOR_LIBRARY} STREQUAL "TOR_LIBRARY-NOTFOUND") + message(FATAL_ERROR "tor library not found") +else() + message(STATUS "Found tor library: ${TOR_LIBRARY}") +endif() + +if(ENABLE_CRASH_HOOKS) +# Check for the presence of the backtrace library +find_library(BACKTRACE_LIBRARY + NAMES backtrace + REQUIRED +) +message(STATUS "Found backtrace library: ${BACKTRACE_LIBRARY}") +endif() + +include(cmake/introspection.cmake) +#################### +# Check functions and define +include(CheckIncludeFile) +include(CheckSymbolExists) + +# Check for headers +CHECK_INCLUDE_FILE(endian.h HAVE_ENDIAN_H) +CHECK_INCLUDE_FILE(sys/endian.h HAVE_SYS_ENDIAN_H) + +# Setup test code header section +if(HAVE_ENDIAN_H) + set(ENDIAN_HEADER "endian.h") + add_compile_definitions(HAVE_ENDIAN_H=1) +elseif(HAVE_SYS_ENDIAN_H) + set(ENDIAN_HEADER "sys/endian.h") + add_compile_definitions(HAVE_SYS_ENDIAN_H=1) +endif(HAVE_ENDIAN_H) + +# Functions to check +set(ENDIAN_FUNCTIONS + le16toh le32toh le64toh + htole16 htole32 htole64 + be16toh be32toh be64toh + htobe16 htobe32 htobe64 +) + +# Check each function +foreach(func ${ENDIAN_FUNCTIONS}) + string(TOUPPER "HAVE_DECL_${func}" var_name) + check_symbol_exists(${func} "${ENDIAN_HEADER}" ${var_name}) + if(${var_name}) + add_compile_definitions(${var_name}=1) + else() + add_compile_definitions(${var_name}=0) + endif() +endforeach() + +# Check for byteswap.h header +CHECK_INCLUDE_FILE(byteswap.h HAVE_BYTESWAP_H) + +# Setup test code header section +if(HAVE_BYTESWAP_H) + set(BYTESWAP_HEADER "byteswap.h") + add_compile_definitions(HAVE_BYTESWAP_H=1) +endif(HAVE_BYTESWAP_H) + +# Functions to check +set(BSWAP_FUNCTIONS + bswap_16 bswap_32 bswap_64 +) + +# Check each function +foreach(func ${BSWAP_FUNCTIONS}) + string(TOUPPER "HAVE_DECL_${func}" var_name) + check_symbol_exists(${func} "${BYTESWAP_HEADER}" ${var_name}) + if(${var_name}) + add_compile_definitions(${var_name}=1) + else() + add_compile_definitions(${var_name}=0) + endif() +endforeach() + +# strnlen +CHECK_INCLUDE_FILE(string.h HAVE_STRING_H) +if(HAVE_STRING_H) + check_function_exists_and_define(strnlen "string.h" HAVE_DECL_STRNLEN) +endif(HAVE_STRING_H) + +# Functions to check +set(BUILTIN_FUNCTIONS + __builtin_clz + __builtin_clzl + __builtin_clzll +) + +# Check each function +foreach(func ${BUILTIN_FUNCTIONS}) + string(TOUPPER "HAVE_DECL_${func}" var_name) + set(TEST_SOURCE_CODE " + int main() { + int x = 0; + (void)${func}(x); + return 0; + } + ") + check_cxx_source_compiles("${TEST_SOURCE_CODE}" ${var_name}) + if(${var_name}) + add_compile_definitions(${var_name}=1) + else() + add_compile_definitions(${var_name}=0) + endif() +endforeach() + +check_cxx_source_compiles( + "#if __cplusplus >= 201703L + int main() { + [[maybe_unused]] int x = 42; + return 0; + } + #else + #error \"Requires C++17\" + #endif" + HAVE_MAYBE_UNUSED +) +if(${HAVE_MAYBE_UNUSED}) + message(STATUS "Compiler supports maybe_unused" ) + add_compile_definitions(HAVE_MAYBE_UNUSED=1) +else() + message(WARNING "Compiler does not support maybe_unused") + check_cxx_source_compiles( + "int main() { + __attribute__((unused)) int x = 42; + return 0; + }" + HAVE_ATTRIBUTE_UNUSED + ) + if(${HAVE_ATTRIBUTE_UNUSED}) + message(STATUS "Compiler supports __attribute__((unused))" ) + add_compile_definitions(HAVE_ATTRIBUTE_UNUSED=1) + else() + message(WARNING "Compiler does not support __attribute__((unused))") + message(WARNING "Please use a compiler that supports C++17 or __attribute__((unused))") + endif() +endif() + +include(cmake/ccache.cmake) + +add_library(warn_interface INTERFACE) +target_link_libraries(core_interface INTERFACE warn_interface) +if(MSVC) + try_append_cxx_flags("/W3" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("/wd4018" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("/wd4244" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("/wd4267" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("/wd4715" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("/wd4805" TARGET warn_interface SKIP_LINK) + target_compile_definitions(warn_interface INTERFACE + _CRT_SECURE_NO_WARNINGS + _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING + ) +else() + try_append_cxx_flags("-Wall" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wextra" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wgnu" TARGET warn_interface SKIP_LINK) + # Some compilers will ignore -Wformat-security without -Wformat, so just combine the two here. + try_append_cxx_flags("-Wformat -Wformat-security" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wvla" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wshadow-field" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wthread-safety" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wloop-analysis" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wredundant-decls" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wunused-member-function" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wdate-time" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wconditional-uninitialized" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wduplicated-branches" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wduplicated-cond" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wlogical-op" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Woverloaded-virtual" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wsuggest-override" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wimplicit-fallthrough" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wunreachable-code" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wdocumentation" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wself-assign" TARGET warn_interface SKIP_LINK) + try_append_cxx_flags("-Wundef" TARGET warn_interface SKIP_LINK) + + # Some compilers (gcc) ignore unknown -Wno-* options, but warn about all + # unknown options if any other warning is produced. Test the -Wfoo case, and + # set the -Wno-foo case if it works. + try_append_cxx_flags("-Wunused-parameter" TARGET warn_interface SKIP_LINK + IF_CHECK_PASSED "-Wno-unused-parameter" + ) +endif() + +configure_file(cmake/script/Coverage.cmake Coverage.cmake USE_SOURCE_PERMISSIONS COPYONLY) +configure_file(cmake/script/CoverageFuzz.cmake CoverageFuzz.cmake USE_SOURCE_PERMISSIONS COPYONLY) +configure_file(cmake/script/CoverageInclude.cmake.in CoverageInclude.cmake USE_SOURCE_PERMISSIONS @ONLY) + +# Don't allow extended (non-ASCII) symbols in identifiers. This is easier for code review. +try_append_cxx_flags("-fno-extended-identifiers" TARGET core_interface SKIP_LINK) + +try_append_cxx_flags("-ffile-prefix-map=A=B" TARGET core_interface SKIP_LINK + IF_CHECK_PASSED "-ffile-prefix-map=${PROJECT_SOURCE_DIR}/src=." +) + +# Currently all versions of gcc are subject to a class of bugs, see the +# gccbug_90348 test case (only reproduces on GCC 11 and earlier) and +# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111843. To work around that, set +# -fstack-reuse=none for all gcc builds. (Only gcc understands this flag). +try_append_cxx_flags("-fstack-reuse=none" TARGET core_interface) + +if(ENABLE_HARDENING) + add_library(hardening_interface INTERFACE) + target_link_libraries(core_interface INTERFACE hardening_interface) + if(MSVC) + try_append_linker_flag("/DYNAMICBASE" TARGET hardening_interface) + try_append_linker_flag("/HIGHENTROPYVA" TARGET hardening_interface) + try_append_linker_flag("/NXCOMPAT" TARGET hardening_interface) + else() + + # _FORTIFY_SOURCE requires that there is some level of optimization, + # otherwise it does nothing and just creates a compiler warning. + try_append_cxx_flags("-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3" + RESULT_VAR cxx_supports_fortify_source + SOURCE "int main() { + # if !defined __OPTIMIZE__ || __OPTIMIZE__ <= 0 + #error + #endif + }" + ) + if(cxx_supports_fortify_source) + target_compile_options(hardening_interface INTERFACE + -U_FORTIFY_SOURCE + -D_FORTIFY_SOURCE=3 + ) + endif() + unset(cxx_supports_fortify_source) + + try_append_cxx_flags("-Wstack-protector" TARGET hardening_interface SKIP_LINK) + try_append_cxx_flags("-fstack-protector-all" TARGET hardening_interface) + try_append_cxx_flags("-fcf-protection=full" TARGET hardening_interface) + + if(MINGW) + # stack-clash-protection doesn't compile with GCC 10 and earlier. + # In any case, it is a no-op for Windows. + # See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90458 for more details. + else() + try_append_cxx_flags("-fstack-clash-protection" TARGET hardening_interface) + endif() + + if(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "arm64") + if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + try_append_cxx_flags("-mbranch-protection=bti" TARGET hardening_interface SKIP_LINK) + else() + try_append_cxx_flags("-mbranch-protection=standard" TARGET hardening_interface SKIP_LINK) + endif() + endif() + + try_append_linker_flag("-Wl,--enable-reloc-section" TARGET hardening_interface) + try_append_linker_flag("-Wl,--dynamicbase" TARGET hardening_interface) + try_append_linker_flag("-Wl,--nxcompat" TARGET hardening_interface) + try_append_linker_flag("-Wl,--high-entropy-va" TARGET hardening_interface) + try_append_linker_flag("-Wl,-z,relro" TARGET hardening_interface) + try_append_linker_flag("-Wl,-z,now" TARGET hardening_interface) + try_append_linker_flag("-Wl,-z,separate-code" TARGET hardening_interface) + if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + try_append_linker_flag("-Wl,-fixup_chains" TARGET hardening_interface) + endif() + endif() +endif() + +if(REDUCE_EXPORTS) + set(CMAKE_CXX_VISIBILITY_PRESET hidden) + try_append_linker_flag("-Wl,--exclude-libs,ALL" TARGET core_interface) + try_append_linker_flag("-Wl,-no_exported_symbols" VAR CMAKE_EXE_LINKER_FLAGS) +endif() + +if(WERROR) + if(MSVC) + set(werror_flag "/WX") + else() + set(werror_flag "-Werror") + endif() + try_append_cxx_flags(${werror_flag} TARGET core_interface SKIP_LINK RESULT_VAR compiler_supports_werror) + if(NOT compiler_supports_werror) + message(FATAL_ERROR "WERROR set but ${werror_flag} is not usable.") + endif() + unset(werror_flag) +endif() + +find_package(Python3 3.10 COMPONENTS Interpreter) +if(Python3_EXECUTABLE) + set(PYTHON_COMMAND ${Python3_EXECUTABLE}) +else() + list(APPEND configure_warnings + "Minimum required Python not found. Utils and rpcauth tests are disabled." + ) +endif() + +target_compile_definitions(core_interface INTERFACE ${DEPENDS_COMPILE_DEFINITIONS}) +target_compile_definitions(core_interface_relwithdebinfo INTERFACE ${DEPENDS_COMPILE_DEFINITIONS_RELWITHDEBINFO}) +target_compile_definitions(core_interface_debug INTERFACE ${DEPENDS_COMPILE_DEFINITIONS_DEBUG}) + +# If the {CXX,LD}FLAGS environment variables are defined during building depends +# and configuring this build system, their content might be duplicated. +if(DEFINED ENV{CXXFLAGS}) + deduplicate_flags(CMAKE_CXX_FLAGS) +endif() +if(DEFINED ENV{LDFLAGS}) + deduplicate_flags(CMAKE_EXE_LINKER_FLAGS) +endif() + +if(BUILD_TESTS) + enable_testing() +endif() + +if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.29) + # have "make test" depend on "make all" + set(CMAKE_SKIP_TEST_ALL_DEPENDENCY FALSE) +endif() + +# TODO: The `CMAKE_SKIP_BUILD_RPATH` variable setting can be deleted +# in the future after reordering Guix script commands to +# perform binary checks after the installation step. +# Relevant discussions: +# - https://github.com/hebasto/firo/pull/236#issuecomment-2183120953 +# - https://github.com/firo/firo/pull/30312#issuecomment-2191235833 +set(CMAKE_SKIP_BUILD_RPATH TRUE) +set(CMAKE_SKIP_INSTALL_RPATH TRUE) + +if(BUILD_TESTS) + # Create test configuration file + # This file is used by the test framework to configure the tests. + # It is generated in the build directory and copied to the source directory + # so that it can be used by the test framework. + # The test framework will use the configuration file to determine which + # features are enabled and which tests should be run. + # used by the test framework to determine which features are enabled + function(create_test_config) + set(abs_top_srcdir ${PROJECT_SOURCE_DIR}) + set(abs_top_builddir ${PROJECT_BINARY_DIR}) + set(EXEEXT ${CMAKE_EXECUTABLE_SUFFIX}) + message(WARNING "CMAKE_EXECUTABLE_SUFFIX : ${CMAKE_EXECUTABLE_SUFFIX}") + message(WARNING "WITH_ZMQ : ${WITH_ZMQ}") + + macro(set_configure_variable var conf_var) + if(${var}) + set(${conf_var}_TRUE "") + else() + set(${conf_var}_TRUE "#") + endif() + endmacro() + + # Core binaries + set_configure_variable(BUILD_DAEMON ENABLE_BITCOIND) + set_configure_variable(BUILD_CLI BUILD_BITCOIN_UTIL) + + # Wallet support + set_configure_variable(ENABLE_WALLET ENABLE_WALLET) + + # Features + set_configure_variable(WITH_ZMQ ENABLE_ZMQ) + + configure_file(${PROJECT_SOURCE_DIR}/qa/pull-tester/tests_config.py.in ${PROJECT_SOURCE_DIR}/qa/pull-tester/tests_config.py USE_SOURCE_PERMISSIONS @ONLY) + endfunction() + + create_test_config() + + file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/functional) + file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/fuzz) + file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/util) + + file(GLOB_RECURSE functional_tests RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} functional/*) + foreach(script ${functional_tests} fuzz/test_runner.py util/rpcauth-test.py util/test_runner.py) + if(CMAKE_HOST_WIN32) + set(symlink) + else() + set(symlink SYMBOLIC) + endif() + file(CREATE_LINK ${CMAKE_CURRENT_SOURCE_DIR}/${script} ${CMAKE_CURRENT_BINARY_DIR}/${script} COPY_ON_ERROR ${symlink}) + endforeach() + unset(functional_tests) +endif(BUILD_TESTS) +add_subdirectory(doc) + +include(cmake/crc32c.cmake) +include(cmake/leveldb.cmake) +add_subdirectory(src) + +include(cmake/tests.cmake) + +include(Maintenance) +setup_split_debug_script() +add_maintenance_targets() +add_windows_deploy_target() +add_macos_deploy_target() + +include_directories(${CMAKE_SOURCE_DIR}/src) + +message("\n") +message("Configure summary") +message("=================") +message("Executables:") +message(" firod ............................ ${BUILD_DAEMON}") +message(" firo-qt (GUI) .................... ${BUILD_GUI}") +message(" firo-cli ......................... ${BUILD_CLI}") +message(" firo-tx .......................... ${BUILD_TX}") +message(" firo-chainstate (experimental) ... ${BUILD_UTIL_CHAINSTATE}") +message(" libfirokernel (experimental) ..... ${BUILD_KERNEL_LIB}") +message("Optional features:") +message(" wallet support ...................... ${ENABLE_WALLET}") +if(ENABLE_WALLET) + message(" - legacy wallets (Berkeley DB) ..... ${WITH_BDB}") +endif() +message(" external signer ..................... ${ENABLE_EXTERNAL_SIGNER}") +message(" ZeroMQ .............................. ${WITH_ZMQ}") +message(" USDT tracing ........................ ${WITH_USDT}") +message(" QR code (GUI) ....................... ${WITH_QRENCODE}") +message(" DBus (GUI, Linux only) .............. ${WITH_DBUS}") +message("Tests:") +message(" test_firo ........................ ${BUILD_TESTS}") +message(" test_firo-qt ..................... ${BUILD_GUI_TESTS}") +message(" bench_firo ....................... ${BUILD_BENCH}") +message(" fuzz binary ......................... ${BUILD_FUZZ_BINARY}") +message("") +if(CMAKE_CROSSCOMPILING) + set(cross_status "TRUE, for ${CMAKE_SYSTEM_NAME}, ${CMAKE_SYSTEM_PROCESSOR}") +else() + set(cross_status "FALSE") +endif() +message("Cross compiling ....................... ${cross_status}") +message("C++ compiler .......................... ${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION}, ${CMAKE_CXX_COMPILER}") +include(FlagsSummary) +flags_summary() +message("Attempt to harden executables ......... ${ENABLE_HARDENING}") +message("Treat compiler warnings as errors ..... ${WERROR}") +message("Use ccache for compiling .............. ${WITH_CCACHE}") +message("Enable crash hooks .................... ${ENABLE_CRASH_HOOKS}") +message("\n") +if(configure_warnings) + message(" ******\n") + foreach(warning IN LISTS configure_warnings) + message(WARNING "${warning}") + endforeach() + message(" ******\n") +endif() + +# We want all build properties to be encapsulated properly. +include(WarnAboutGlobalProperties) + +# Generate archive files +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Firo client software") +set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README.md") +set(CPACK_VERBATIM_VARIABLES YES) +include(CPack) \ No newline at end of file diff --git a/Makefile.am b/Makefile.am index bb10f090fb..1fbcb00400 100644 --- a/Makefile.am +++ b/Makefile.am @@ -4,6 +4,7 @@ ACLOCAL_AMFLAGS = -I build-aux/m4 SUBDIRS = src +AM_CPPFLAGS = -I$(top_srcdir)/src .PHONY: deploy FORCE .INTERMEDIATE: $(OSX_TEMP_ISO) diff --git a/README.md b/README.md index f421ef0201..6daf99f5d4 100644 --- a/README.md +++ b/README.md @@ -130,7 +130,7 @@ sudo pacman -Sy sudo pacman -S git base-devel python cmake ``` -## Build Firo +## Build Firo with autotools 1. Download the source: @@ -172,6 +172,87 @@ make check If the build succeeded, two binaries will be generated in `/src`: `firod` and `firo-cli`. If you chose to build the GUI, `firo-qt` will be also generated in the `qt` folder. +## Build Firo with CMake + +This document provides instructions for building Firo using the new CMake-based build system. + +### Prerequisites (macOS Specific) +Ensure [Homebrew](https://brew.sh/) is installed as per the [macOS build guide](https://github.com/firoorg/firo/blob/master/doc/build-macos.md). + +--- + +### Build Instructions + +#### 1. Build Dependencies +```bash +cd depends +make -j$(nproc) +cd .. +``` +#### 2. Configure and Build + +```bash +mkdir build && cd build +cmake .. \ + -DCMAKE_TOOLCHAIN_FILE=$(pwd)/../depends/x86_64-pc-linux-gnu/toolchain.cmake \ + -DBUILD_CLI=ON \ + -DBUILD_GUI=ON \ + -DBUILD_TESTS=ON +make -j$(nproc) +``` +#### 3. Run GUI Client + +``` +./bin/firo-qt +``` + +### CMake Options Reference + +| Flag | Description | Default | +|------|-------------|---------| +| `BUILD_DAEMON` | Build `firod` executable | `ON` | +| `BUILD_GUI` | Build `firo-qt` GUI client | `ON` | +| `BUILD_CLI` | Build `firo-tx` and other command-line tools | `ON` | +| `ENABLE_WALLET` | Enable wallet functionality | `ON` | +| `BUILD_TESTS` | Build test suite | `OFF` | +| `BUILD_TX` | Build `firo-tx` transaction tool | Subset of `BUILD_CLI` | +| `ENABLE_CRASH_HOOKS` | Enable crash reporting/stack traces | `OFF` | +| `WITH_ZMQ` | Enable ZeroMQ notifications | `ON` | + +### Supported Cross-Compilation Targets + +| Host Target | Platform | +|--------------------------|---------------------------| +| `x86_64-w64-mingw32` | Windows 64-bit | +| `aarch64-apple-darwin` | macOS | +| `arm-linux-gnueabihf` | Linux ARM 32-bit | +| `aarch64-linux-gnu` | Linux ARM 64-bit | + +#### Usage Example: +```bash +# Build dependencies for Windows 64-bit +cd depends +make HOST=x86_64-w64-mingw32 -j$(nproc) +cd .. +``` +### Cross-Compilation +To build for other platforms, specify `HOST` variable. +```bash + +mkdir build && cd build +cmake .. \ + -DCMAKE_TOOLCHAIN_FILE=$(pwd)/../depends/x86_64-w64-mingw32/toolchain.cmake \ + -DBUILD_CLI=ON \ + -DBUILD_GUI=ON \ + -DBUILD_TESTS=ON +make -j$(nproc) + +``` + +### Notes + * The toolchain path in `CMAKE_TOOLCHAIN_FILE`must match your target architecture. + * `BUILD_TX` is automatically enabled if `BUILD_CLI=ON` is enabled. + ## macOS Build Instructions and Notes See [doc/build-macos.md](doc/build-macos.md) for instructions on building on macOS. @@ -188,6 +269,15 @@ See [doc/build-windows.md](doc/build-windows.md) for instructions on building on Now that you have your self-built or precompiled binaries, it's time to run Firo! Depending by your skill level and/or setup, you might want to use the command line tool or the graphic user interface. If you have problems or need support, [contact the community](https://firo.org/community/social/). +# Install Firo + +After building with `CMake`, generate `.sh` file with `make package`. Once you run `make package` you should have `./FiroCore-VERSION_MAJOR.VERSION_MINOR.VERSION_REVISION-Linux.sh` in your build directory. + +For example, you can install `Firo` on your `/usr/bin` with: +``` +./FiroCore-0.14.14-Linux.sh --prefix=/usr/bin --exclude-subdir +``` + # Contributors ## Code Contributors diff --git a/cmake/bitcoin-build-config.h.in b/cmake/bitcoin-build-config.h.in new file mode 100644 index 0000000000..363f3815e7 --- /dev/null +++ b/cmake/bitcoin-build-config.h.in @@ -0,0 +1,153 @@ +// Copyright (c) 2023-present The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or https://opensource.org/license/mit/. + +#ifndef BITCOIN_CONFIG_H +#define BITCOIN_CONFIG_H + +/* Version Build */ +#define CLIENT_VERSION_BUILD @CLIENT_VERSION_BUILD@ + +/* Version is release */ +#define CLIENT_VERSION_IS_RELEASE @CLIENT_VERSION_IS_RELEASE@ + +/* Major version */ +#define CLIENT_VERSION_MAJOR @CLIENT_VERSION_MAJOR@ + +/* Minor version */ +#define CLIENT_VERSION_MINOR @CLIENT_VERSION_MINOR@ + +/* Revision version */ +#define CLIENT_VERSION_REVISION @CLIENT_VERSION_REVISION@ + +/* Copyright holder(s) before %s replacement */ +#define COPYRIGHT_HOLDERS "@COPYRIGHT_HOLDERS@" + +/* Copyright holder(s) */ +#define COPYRIGHT_HOLDERS_FINAL "@COPYRIGHT_HOLDERS_FINAL@" + +/* Replacement for %s in copyright holders string */ +#define COPYRIGHT_HOLDERS_SUBSTITUTION "@CLIENT_NAME@" + +/* Copyright year */ +#define COPYRIGHT_YEAR @COPYRIGHT_YEAR@ + +/* Define this symbol to build code that uses ARMv8 SHA-NI intrinsics */ +#cmakedefine ENABLE_ARM_SHANI 1 + +/* Define this symbol to build code that uses AVX2 intrinsics */ +#cmakedefine ENABLE_AVX2 1 + +/* Define if external signer support is enabled */ +#cmakedefine ENABLE_EXTERNAL_SIGNER 1 + +/* Define this symbol to build code that uses SSE4.1 intrinsics */ +#cmakedefine ENABLE_SSE41 1 + +/* Define to 1 to enable tracepoints for Userspace, Statically Defined Tracing + */ +#cmakedefine ENABLE_TRACING 1 + +/* Define to 1 to enable wallet functions. */ +#cmakedefine ENABLE_WALLET 1 + +/* Define this symbol to build code that uses x86 SHA-NI intrinsics */ +#cmakedefine ENABLE_X86_SHANI 1 + +/* Define to 1 if you have the declaration of `fork', and to 0 if you don't. + */ +#cmakedefine01 HAVE_DECL_FORK + +/* Define to 1 if you have the declaration of `freeifaddrs', and to 0 if you + don't. */ +#cmakedefine01 HAVE_DECL_FREEIFADDRS + +/* Define to 1 if you have the declaration of `getifaddrs', and to 0 if you + don't. */ +#cmakedefine01 HAVE_DECL_GETIFADDRS + +/* Define to 1 if you have the declaration of `pipe2', and to 0 if you don't. + */ +#cmakedefine01 HAVE_DECL_PIPE2 + +/* Define to 1 if you have the declaration of `setsid', and to 0 if you don't. + */ +#cmakedefine01 HAVE_DECL_SETSID + +/* Define to 1 if fdatasync is available. */ +#cmakedefine HAVE_FDATASYNC 1 + +/* Define this symbol if the BSD getentropy system call is available with + sys/random.h */ +#cmakedefine HAVE_GETENTROPY_RAND 1 + +/* Define this symbol if the Linux getrandom function call is available */ +#cmakedefine HAVE_GETRANDOM 1 + +/* Define this symbol if you have malloc_info */ +#cmakedefine HAVE_MALLOC_INFO 1 + +/* Define this symbol if you have mallopt with M_ARENA_MAX */ +#cmakedefine HAVE_MALLOPT_ARENA_MAX 1 + +/* Define to 1 if O_CLOEXEC flag is available. */ +#cmakedefine01 HAVE_O_CLOEXEC + +/* Define this symbol if you have posix_fallocate */ +#cmakedefine HAVE_POSIX_FALLOCATE 1 + +/* Define this symbol if platform supports unix domain sockets */ +#cmakedefine HAVE_SOCKADDR_UN 1 + +/* Define this symbol to build code that uses getauxval */ +#cmakedefine HAVE_STRONG_GETAUXVAL 1 + +/* Define this symbol if the BSD sysctl() is available */ +#cmakedefine HAVE_SYSCTL 1 + +/* Define this symbol if the BSD sysctl(KERN_ARND) is available */ +#cmakedefine HAVE_SYSCTL_ARND 1 + +/* Define to 1 if std::system or ::wsystem is available. */ +#cmakedefine HAVE_SYSTEM 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_PRCTL_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_RESOURCES_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_VMMETER_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_VM_VM_PARAM_H 1 + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "@CLIENT_BUGREPORT@" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "@CLIENT_NAME@" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "@PROJECT_HOMEPAGE_URL@" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "@CLIENT_VERSION_STRING@" + +/* Define to 1 if strerror_r returns char *. */ +#cmakedefine STRERROR_R_CHAR_P 1 + +/* Define if BDB support should be compiled in */ +#cmakedefine USE_BDB 1 + +/* Define if dbus support should be compiled in */ +#cmakedefine USE_DBUS 1 + +/* Define if QR support should be compiled in */ +#cmakedefine USE_QRCODE 1 + +/* Define if sqlite support should be compiled in */ +#cmakedefine USE_SQLITE 1 + +#endif //BITCOIN_CONFIG_H diff --git a/cmake/ccache.cmake b/cmake/ccache.cmake new file mode 100644 index 0000000000..d1cc204c8e --- /dev/null +++ b/cmake/ccache.cmake @@ -0,0 +1,28 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +if(NOT MSVC) + find_program(CCACHE_EXECUTABLE ccache) + if(CCACHE_EXECUTABLE) + execute_process( + COMMAND readlink -f ${CMAKE_CXX_COMPILER} + OUTPUT_VARIABLE compiler_resolved_link + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + if(CCACHE_EXECUTABLE STREQUAL compiler_resolved_link AND NOT WITH_CCACHE) + list(APPEND configure_warnings + "Disabling ccache was attempted using -DWITH_CCACHE=${WITH_CCACHE}, but ccache masquerades as the compiler." + ) + set(WITH_CCACHE ON) + elseif(WITH_CCACHE) + list(APPEND CMAKE_C_COMPILER_LAUNCHER ${CCACHE_EXECUTABLE}) + list(APPEND CMAKE_CXX_COMPILER_LAUNCHER ${CCACHE_EXECUTABLE}) + endif() + else() + set(WITH_CCACHE OFF) + endif() +endif() + +mark_as_advanced(CCACHE_EXECUTABLE) diff --git a/cmake/cov_tool_wrapper.sh.in b/cmake/cov_tool_wrapper.sh.in new file mode 100644 index 0000000000..f6b7ff3419 --- /dev/null +++ b/cmake/cov_tool_wrapper.sh.in @@ -0,0 +1,5 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +exec @COV_TOOL@ "$@" diff --git a/cmake/crc32c.cmake b/cmake/crc32c.cmake new file mode 100644 index 0000000000..16fde7f95d --- /dev/null +++ b/cmake/crc32c.cmake @@ -0,0 +1,123 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +# This file is part of the transition from Autotools to CMake. Once CMake +# support has been merged we should switch to using the upstream CMake +# buildsystem. + +include(CheckCXXSourceCompiles) + +# Check for __builtin_prefetch support in the compiler. +check_cxx_source_compiles(" + int main() { + char data = 0; + const char* address = &data; + __builtin_prefetch(address, 0, 0); + return 0; + } + " HAVE_BUILTIN_PREFETCH +) + +# Check for _mm_prefetch support in the compiler. +check_cxx_source_compiles(" + #if defined(_MSC_VER) + #include + #else + #include + #endif + + int main() { + char data = 0; + const char* address = &data; + _mm_prefetch(address, _MM_HINT_NTA); + return 0; + } + " HAVE_MM_PREFETCH +) + +# Check for SSE4.2 support in the compiler. +if(MSVC) + set(SSE42_CXXFLAGS /arch:AVX) +else() + set(SSE42_CXXFLAGS -msse4.2) +endif() +check_cxx_source_compiles_with_flags("${SSE42_CXXFLAGS}" " + #include + #if defined(_MSC_VER) + #include + #elif defined(__GNUC__) && defined(__SSE4_2__) + #include + #endif + + int main() { + uint64_t l = 0; + l = _mm_crc32_u8(l, 0); + l = _mm_crc32_u32(l, 0); + l = _mm_crc32_u64(l, 0); + return l; + } + " HAVE_SSE42 +) + +# Check for ARMv8 w/ CRC and CRYPTO extensions support in the compiler. +set(ARM64_CRC_CXXFLAGS -march=armv8-a+crc+crypto) +check_cxx_source_compiles_with_flags("${ARM64_CRC_CXXFLAGS}" " + #include + #include + + int main() { + #ifdef __aarch64__ + __crc32cb(0, 0); __crc32ch(0, 0); __crc32cw(0, 0); __crc32cd(0, 0); + vmull_p64(0, 0); + #else + #error crc32c library does not support hardware acceleration on 32-bit ARM + #endif + return 0; + } + " HAVE_ARM64_CRC32C +) + +add_library(crc32c_common INTERFACE) +target_compile_definitions(crc32c_common INTERFACE + HAVE_BUILTIN_PREFETCH=$ + HAVE_MM_PREFETCH=$ + HAVE_STRONG_GETAUXVAL=$ + BYTE_ORDER_BIG_ENDIAN=$ + HAVE_SSE42=$ + HAVE_ARM64_CRC32C=$ +) +target_link_libraries(crc32c_common INTERFACE + core_interface +) + +add_library(crc32c STATIC EXCLUDE_FROM_ALL + ${PROJECT_SOURCE_DIR}/src/crc32c/src/crc32c.cc + ${PROJECT_SOURCE_DIR}/src/crc32c/src/crc32c_portable.cc +) +target_include_directories(crc32c + PUBLIC + $ +) +target_link_libraries(crc32c PRIVATE crc32c_common) +set_target_properties(crc32c PROPERTIES EXPORT_COMPILE_COMMANDS OFF) + +if(HAVE_SSE42) + add_library(crc32c_sse42 STATIC EXCLUDE_FROM_ALL + ${PROJECT_SOURCE_DIR}/src/crc32c/src/crc32c_sse42.cc + ) + target_compile_options(crc32c_sse42 PRIVATE ${SSE42_CXXFLAGS}) + target_link_libraries(crc32c_sse42 PRIVATE crc32c_common) + set_target_properties(crc32c_sse42 PROPERTIES EXPORT_COMPILE_COMMANDS OFF) + target_link_libraries(crc32c PRIVATE crc32c_sse42) +endif() + +if(HAVE_ARM64_CRC32C) + add_library(crc32c_arm64 STATIC EXCLUDE_FROM_ALL + ${PROJECT_SOURCE_DIR}/src/crc32c/src/crc32c_arm64.cc + ) + target_compile_options(crc32c_arm64 PRIVATE ${ARM64_CRC_CXXFLAGS}) + target_link_libraries(crc32c_arm64 PRIVATE crc32c_common) + set_target_properties(crc32c_arm64 PROPERTIES EXPORT_COMPILE_COMMANDS OFF) + target_link_libraries(crc32c PRIVATE crc32c_arm64) +endif() diff --git a/cmake/introspection.cmake b/cmake/introspection.cmake new file mode 100644 index 0000000000..29c93869a7 --- /dev/null +++ b/cmake/introspection.cmake @@ -0,0 +1,227 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include(CheckCXXSourceCompiles) +include(CheckCXXSymbolExists) +include(CheckIncludeFileCXX) + +# The following HAVE_{HEADER}_H variables go to the bitcoin-build-config.h header. +check_include_file_cxx(sys/prctl.h HAVE_SYS_PRCTL_H) +check_include_file_cxx(sys/resources.h HAVE_SYS_RESOURCES_H) +check_include_file_cxx(sys/vmmeter.h HAVE_SYS_VMMETER_H) +check_include_file_cxx(vm/vm_param.h HAVE_VM_VM_PARAM_H) + +check_cxx_symbol_exists(O_CLOEXEC "fcntl.h" HAVE_O_CLOEXEC) +check_cxx_symbol_exists(fdatasync "unistd.h" HAVE_FDATASYNC) +check_cxx_symbol_exists(fork "unistd.h" HAVE_DECL_FORK) +check_cxx_symbol_exists(pipe2 "unistd.h" HAVE_DECL_PIPE2) +check_cxx_symbol_exists(setsid "unistd.h" HAVE_DECL_SETSID) + +check_include_file_cxx(sys/types.h HAVE_SYS_TYPES_H) +check_include_file_cxx(ifaddrs.h HAVE_IFADDRS_H) +if(HAVE_SYS_TYPES_H AND HAVE_IFADDRS_H) + include(TestAppendRequiredLibraries) + test_append_socket_library(core_interface) +endif() + +include(TestAppendRequiredLibraries) +test_append_atomic_library(core_interface) + +check_cxx_symbol_exists(std::system "cstdlib" HAVE_STD_SYSTEM) +check_cxx_symbol_exists(::_wsystem "stdlib.h" HAVE__WSYSTEM) +if(HAVE_STD_SYSTEM OR HAVE__WSYSTEM) + set(HAVE_SYSTEM 1) +endif() + +check_cxx_source_compiles(" + #include + + int main() + { + char buf[100]; + char* p{strerror_r(0, buf, sizeof buf)}; + (void)p; + } + " STRERROR_R_CHAR_P +) + +# Check for malloc_info (for memory statistics information in getmemoryinfo). +check_cxx_symbol_exists(malloc_info "malloc.h" HAVE_MALLOC_INFO) + +# Check for mallopt(M_ARENA_MAX) (to set glibc arenas). +check_cxx_source_compiles(" + #include + + int main() + { + mallopt(M_ARENA_MAX, 1); + } + " HAVE_MALLOPT_ARENA_MAX +) + +# Check for posix_fallocate(). +check_cxx_source_compiles(" + // same as in src/util/fs_helpers.cpp + #ifdef __linux__ + #ifdef _POSIX_C_SOURCE + #undef _POSIX_C_SOURCE + #endif + #define _POSIX_C_SOURCE 200112L + #endif // __linux__ + #include + + int main() + { + return posix_fallocate(0, 0, 0); + } + " HAVE_POSIX_FALLOCATE +) + +# Check for strong getauxval() support in the system headers. +check_cxx_source_compiles(" + #include + + int main() + { + getauxval(AT_HWCAP); + } + " HAVE_STRONG_GETAUXVAL +) + +# Check for UNIX sockets. +check_cxx_source_compiles(" + #include + #include + + int main() + { + struct sockaddr_un addr; + addr.sun_family = AF_UNIX; + } + " HAVE_SOCKADDR_UN +) + +# Check for different ways of gathering OS randomness: +# - Linux getrandom() +check_cxx_source_compiles(" + #include + + int main() + { + getrandom(nullptr, 32, 0); + } + " HAVE_GETRANDOM +) + +# - BSD getentropy() +check_cxx_source_compiles(" + #include + + int main() + { + getentropy(nullptr, 32); + } + " HAVE_GETENTROPY_RAND +) + + +# - BSD sysctl() +check_cxx_source_compiles(" + #include + #include + + #ifdef __linux__ + #error Don't use sysctl on Linux, it's deprecated even when it works + #endif + + int main() + { + sysctl(nullptr, 2, nullptr, nullptr, nullptr, 0); + } + " HAVE_SYSCTL +) + +# - BSD sysctl(KERN_ARND) +check_cxx_source_compiles(" + #include + #include + + #ifdef __linux__ + #error Don't use sysctl on Linux, it's deprecated even when it works + #endif + + int main() + { + static int name[2] = {CTL_KERN, KERN_ARND}; + sysctl(name, 2, nullptr, nullptr, nullptr, 0); + } + " HAVE_SYSCTL_ARND +) + +if(NOT MSVC) + include(CheckSourceCompilesAndLinks) + + # Check for SSE4.1 intrinsics. + set(SSE41_CXXFLAGS -msse4.1) + check_cxx_source_compiles_with_flags("${SSE41_CXXFLAGS}" " + #include + + int main() + { + __m128i a = _mm_set1_epi32(0); + __m128i b = _mm_set1_epi32(1); + __m128i r = _mm_blend_epi16(a, b, 0xFF); + return _mm_extract_epi32(r, 3); + } + " HAVE_SSE41 + ) + set(ENABLE_SSE41 ${HAVE_SSE41}) + + # Check for AVX2 intrinsics. + set(AVX2_CXXFLAGS -mavx -mavx2) + check_cxx_source_compiles_with_flags("${AVX2_CXXFLAGS}" " + #include + + int main() + { + __m256i l = _mm256_set1_epi32(0); + return _mm256_extract_epi32(l, 7); + } + " HAVE_AVX2 + ) + set(ENABLE_AVX2 ${HAVE_AVX2}) + + # Check for x86 SHA-NI intrinsics. + set(X86_SHANI_CXXFLAGS -msse4 -msha) + check_cxx_source_compiles_with_flags("${X86_SHANI_CXXFLAGS}" " + #include + + int main() + { + __m128i i = _mm_set1_epi32(0); + __m128i j = _mm_set1_epi32(1); + __m128i k = _mm_set1_epi32(2); + return _mm_extract_epi32(_mm_sha256rnds2_epu32(i, j, k), 0); + } + " HAVE_X86_SHANI + ) + set(ENABLE_X86_SHANI ${HAVE_X86_SHANI}) + + # Check for ARMv8 SHA-NI intrinsics. + set(ARM_SHANI_CXXFLAGS -march=armv8-a+crypto) + check_cxx_source_compiles_with_flags("${ARM_SHANI_CXXFLAGS}" " + #include + + int main() + { + uint32x4_t a, b, c; + vsha256h2q_u32(a, b, c); + vsha256hq_u32(a, b, c); + vsha256su0q_u32(a, b); + vsha256su1q_u32(a, b, c); + } + " HAVE_ARM_SHANI + ) + set(ENABLE_ARM_SHANI ${HAVE_ARM_SHANI}) +endif() diff --git a/cmake/leveldb.cmake b/cmake/leveldb.cmake new file mode 100644 index 0000000000..823a5d8e3d --- /dev/null +++ b/cmake/leveldb.cmake @@ -0,0 +1,105 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +# This file is part of the transition from Autotools to CMake. Once CMake +# support has been merged we should switch to using the upstream CMake +# buildsystem. + +include(CheckCXXSymbolExists) +check_cxx_symbol_exists(F_FULLFSYNC "fcntl.h" HAVE_FULLFSYNC) + +add_library(leveldb STATIC EXCLUDE_FROM_ALL + ${PROJECT_SOURCE_DIR}/src/leveldb/db/builder.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/c.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/db_impl.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/db_iter.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/dbformat.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/dumpfile.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/filename.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/log_reader.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/log_writer.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/memtable.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/repair.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/table_cache.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/version_edit.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/version_set.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/db/write_batch.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/table/block.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/table/block_builder.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/table/filter_block.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/table/format.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/table/iterator.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/table/merger.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/table/table.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/table/table_builder.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/table/two_level_iterator.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/util/arena.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/util/bloom.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/util/cache.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/util/coding.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/util/comparator.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/util/crc32c.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/util/env.cc + $<$>:${PROJECT_SOURCE_DIR}/src/leveldb/util/env_posix.cc> + $<$:${PROJECT_SOURCE_DIR}/src/leveldb/util/env_windows.cc> + ${PROJECT_SOURCE_DIR}/src/leveldb/util/filter_policy.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/util/hash.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/util/histogram.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/util/logging.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/util/options.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/util/status.cc + ${PROJECT_SOURCE_DIR}/src/leveldb/helpers/memenv/memenv.cc +) + +target_compile_definitions(leveldb + PRIVATE + HAVE_SNAPPY=0 + HAVE_CRC32C=1 + HAVE_FDATASYNC=$ + HAVE_FULLFSYNC=$ + HAVE_O_CLOEXEC=$ + FALLTHROUGH_INTENDED=[[fallthrough]] + LEVELDB_IS_BIG_ENDIAN=$ + $<$>:LEVELDB_PLATFORM_POSIX> + $<$:LEVELDB_PLATFORM_WINDOWS> + $<$:_UNICODE;UNICODE> +) +if(MINGW) + target_compile_definitions(leveldb + PRIVATE + __USE_MINGW_ANSI_STDIO=1 + ) +endif() + +target_include_directories(leveldb + PRIVATE + $ + PUBLIC + $ +) + +add_library(nowarn_leveldb_interface INTERFACE) +if(MSVC) + target_compile_options(nowarn_leveldb_interface INTERFACE + /wd4722 + ) + target_compile_definitions(nowarn_leveldb_interface INTERFACE + _CRT_NONSTDC_NO_WARNINGS + ) +else() + target_compile_options(nowarn_leveldb_interface INTERFACE + -Wno-conditional-uninitialized + -Wno-suggest-override + ) +endif() + +target_link_libraries(leveldb PRIVATE + core_interface + nowarn_leveldb_interface + crc32c +) + +set_target_properties(leveldb PROPERTIES + EXPORT_COMPILE_COMMANDS OFF +) diff --git a/cmake/module/AddBoostIfNeeded.cmake b/cmake/module/AddBoostIfNeeded.cmake new file mode 100644 index 0000000000..72c645817f --- /dev/null +++ b/cmake/module/AddBoostIfNeeded.cmake @@ -0,0 +1,131 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +function(add_boost_if_needed) + #[=[ + TODO: Not all targets, which will be added in the future, require + Boost. Therefore, a proper check will be appropriate here. + + Implementation notes: + Although only Boost headers are used to build Bitcoin Core, + we still leverage a standard CMake's approach to handle + dependencies, i.e., the Boost::headers "library". + A command target_link_libraries(target PRIVATE Boost::headers) + will propagate Boost::headers usage requirements to the target. + For Boost::headers such usage requirements is an include + directory and other added INTERFACE properties. + ]=] + + # We cannot rely on find_package(Boost ...) to work properly without + # Boost_NO_BOOST_CMAKE set until we require a more recent Boost because + # upstream did not ship proper CMake files until 1.82.0. + # Until then, we rely on CMake's FindBoost module. + # See: https://cmake.org/cmake/help/latest/policy/CMP0167.html + if(POLICY CMP0167) + cmake_policy(SET CMP0167 OLD) + endif() + set(Boost_NO_BOOST_CMAKE OFF) + set(_boost_components atomic chrono filesystem program_options system thread) + if(BUILD_TESTS) + list(APPEND _boost_components unit_test_framework) + endif() + find_package(Boost 1.81.0 REQUIRED COMPONENTS ${_boost_components}) + + include(CheckCXXSourceCompiles) + set(CMAKE_REQUIRED_INCLUDES ${Boost_INCLUDE_DIRS}) + set(CMAKE_REQUIRED_LIBRARIES ${Boost_LIBRARIES}) + # Test source code + set(SLEEPTEST_SOURCE_CODE " + #include + #include + + int main() { + #if BOOST_VERSION >= 105000 && (!defined(BOOST_HAS_NANOSLEEP) || BOOST_VERSION >= 105200) + boost::this_thread::sleep_for(boost::chrono::milliseconds(0)); + return 0; + #else + choke me + #endif + } + ") + + # Check if the test source code compiles + check_cxx_source_compiles("${SLEEPTEST_SOURCE_CODE}" HAVE_WORKING_BOOST_SLEEP_FOR) + + # Define the macro if the test passed + if(HAVE_WORKING_BOOST_SLEEP_FOR) + add_compile_definitions(HAVE_WORKING_BOOST_SLEEP_FOR=1) + else() + # testing for boost::this_thread::sleep(boost::posix_time::milliseconds(n)); + set(SLEEPTEST_SOURCE_CODE " + #include + #include + + int main() { + #if BOOST_VERSION >= 105000 && (!defined(BOOST_HAS_NANOSLEEP) || BOOST_VERSION >= 105200) + boost::this_thread::sleep(boost::chrono::milliseconds(0)); + return 0; + #else + choke me + #endif + } + ") + # Check if the test source code compiles + check_cxx_source_compiles("${SLEEPTEST_SOURCE_CODE}" HAVE_WORKING_BOOST_SLEEP) + if(HAVE_WORKING_BOOST_SLEEP) + add_compile_definitions(HAVE_WORKING_BOOST_SLEEP=1) + else() + message(FATAL_ERROR "Couldn't find a working boost sleep_for or sleep function. Please check your Boost.") + endif() + endif() + + mark_as_advanced(Boost_INCLUDE_DIR) + set_target_properties(Boost::headers PROPERTIES IMPORTED_GLOBAL TRUE) + target_compile_definitions(Boost::headers INTERFACE + # We don't use multi_index serialization. + BOOST_MULTI_INDEX_DISABLE_SERIALIZATION + ) + if(DEFINED VCPKG_TARGET_TRIPLET) + # Workaround for https://github.com/microsoft/vcpkg/issues/36955. + target_compile_definitions(Boost::headers INTERFACE + BOOST_NO_USER_CONFIG + ) + endif() + + # Prevent use of std::unary_function, which was removed in C++17, + # and will generate warnings with newer compilers for Boost + # older than 1.80. + # See: https://github.com/boostorg/config/pull/430. + set(CMAKE_REQUIRED_DEFINITIONS -DBOOST_NO_CXX98_FUNCTION_BASE) + set(CMAKE_REQUIRED_INCLUDES ${Boost_INCLUDE_DIR}) + include(CMakePushCheckState) + cmake_push_check_state() + include(TryAppendCXXFlags) + set(CMAKE_REQUIRED_FLAGS ${working_compiler_werror_flag}) + set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) + check_cxx_source_compiles(" + #include + " NO_DIAGNOSTICS_BOOST_NO_CXX98_FUNCTION_BASE + ) + cmake_pop_check_state() + if(NO_DIAGNOSTICS_BOOST_NO_CXX98_FUNCTION_BASE) + target_compile_definitions(Boost::headers INTERFACE + BOOST_NO_CXX98_FUNCTION_BASE + ) + else() + set(CMAKE_REQUIRED_DEFINITIONS) + endif() + + # Some package managers, such as vcpkg, vendor Boost.Test separately + # from the rest of the headers, so we have to check for it individually. + if(BUILD_TESTS AND DEFINED VCPKG_TARGET_TRIPLET) + list(APPEND CMAKE_REQUIRED_DEFINITIONS -DBOOST_TEST_NO_MAIN) + include(CheckIncludeFileCXX) + check_include_file_cxx(boost/test/included/unit_test.hpp HAVE_BOOST_INCLUDED_UNIT_TEST_H) + if(NOT HAVE_BOOST_INCLUDED_UNIT_TEST_H) + message(FATAL_ERROR "Building test_bitcoin executable requested but boost/test/included/unit_test.hpp header not available.") + endif() + endif() + +endfunction() diff --git a/cmake/module/AddWindowsResources.cmake b/cmake/module/AddWindowsResources.cmake new file mode 100644 index 0000000000..a9b4f51f73 --- /dev/null +++ b/cmake/module/AddWindowsResources.cmake @@ -0,0 +1,14 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include_guard(GLOBAL) + +macro(add_windows_resources target rc_file) + if(WIN32) + target_sources(${target} PRIVATE ${rc_file}) + set_property(SOURCE ${rc_file} + APPEND PROPERTY COMPILE_DEFINITIONS WINDRES_PREPROC + ) + endif() +endmacro() diff --git a/cmake/module/CheckSourceCompilesAndLinks.cmake b/cmake/module/CheckSourceCompilesAndLinks.cmake new file mode 100644 index 0000000000..88c897d524 --- /dev/null +++ b/cmake/module/CheckSourceCompilesAndLinks.cmake @@ -0,0 +1,39 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include_guard(GLOBAL) +include(CheckCXXSourceCompiles) +include(CMakePushCheckState) + +# This avoids running the linker. +set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) + +macro(check_cxx_source_links source) + set(CMAKE_TRY_COMPILE_TARGET_TYPE EXECUTABLE) + check_cxx_source_compiles("${source}" ${ARGN}) + set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) +endmacro() + +macro(check_cxx_source_compiles_with_flags flags source) + cmake_push_check_state(RESET) + set(CMAKE_REQUIRED_FLAGS ${flags}) + list(JOIN CMAKE_REQUIRED_FLAGS " " CMAKE_REQUIRED_FLAGS) + check_cxx_source_compiles("${source}" ${ARGN}) + cmake_pop_check_state() +endmacro() + +macro(check_cxx_source_links_with_flags flags source) + cmake_push_check_state(RESET) + set(CMAKE_REQUIRED_FLAGS ${flags}) + list(JOIN CMAKE_REQUIRED_FLAGS " " CMAKE_REQUIRED_FLAGS) + check_cxx_source_links("${source}" ${ARGN}) + cmake_pop_check_state() +endmacro() + +macro(check_cxx_source_links_with_libs libs source) + cmake_push_check_state(RESET) + set(CMAKE_REQUIRED_LIBRARIES "${libs}") + check_cxx_source_links("${source}" ${ARGN}) + cmake_pop_check_state() +endmacro() diff --git a/cmake/module/FindBerkeleyDB.cmake b/cmake/module/FindBerkeleyDB.cmake new file mode 100644 index 0000000000..03a3cce10c --- /dev/null +++ b/cmake/module/FindBerkeleyDB.cmake @@ -0,0 +1,133 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +#[=======================================================================[ +FindBerkeleyDB +-------------- + +Finds the Berkeley DB headers and library. + +Imported Targets +^^^^^^^^^^^^^^^^ + +This module provides imported target ``BerkeleyDB::BerkeleyDB``, if +Berkeley DB has been found. + +Result Variables +^^^^^^^^^^^^^^^^ + +This module defines the following variables: + +``BerkeleyDB_FOUND`` + "True" if Berkeley DB found. + +``BerkeleyDB_VERSION`` + The MAJOR.MINOR version of Berkeley DB found. + +#]=======================================================================] + +set(_BerkeleyDB_homebrew_prefix) +if(CMAKE_HOST_APPLE) + find_program(HOMEBREW_EXECUTABLE brew) + if(HOMEBREW_EXECUTABLE) + # The Homebrew package manager installs the berkeley-db* packages as + # "keg-only", which means they are not symlinked into the default prefix. + # To find such a package, the find_path() and find_library() commands + # need additional path hints that are computed by Homebrew itself. + execute_process( + COMMAND ${HOMEBREW_EXECUTABLE} --prefix berkeley-db@4 + OUTPUT_VARIABLE _BerkeleyDB_homebrew_prefix + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + endif() +endif() + +find_path(BerkeleyDB_INCLUDE_DIR + NAMES db_cxx.h + HINTS ${_BerkeleyDB_homebrew_prefix}/include + PATH_SUFFIXES 4.8 48 db4.8 4 db4 5.3 db5.3 5 db5 +) +mark_as_advanced(BerkeleyDB_INCLUDE_DIR) +unset(_BerkeleyDB_homebrew_prefix) + +if(NOT BerkeleyDB_LIBRARY) + if(VCPKG_TARGET_TRIPLET) + # The vcpkg package manager installs the berkeleydb package with the same name + # of release and debug libraries. Therefore, the default search paths set by + # vcpkg's toolchain file cannot be used to search libraries as the debug one + # will always be found. + set(CMAKE_FIND_USE_CMAKE_PATH FALSE) + endif() + + get_filename_component(_BerkeleyDB_lib_hint "${BerkeleyDB_INCLUDE_DIR}" DIRECTORY) + + find_library(BerkeleyDB_LIBRARY_RELEASE + NAMES db_cxx-4.8 db4_cxx db48 db_cxx-5.3 db_cxx-5 db_cxx libdb48 + NAMES_PER_DIR + HINTS ${_BerkeleyDB_lib_hint} + PATH_SUFFIXES lib + ) + mark_as_advanced(BerkeleyDB_LIBRARY_RELEASE) + + find_library(BerkeleyDB_LIBRARY_DEBUG + NAMES db_cxx-4.8 db4_cxx db48 db_cxx-5.3 db_cxx-5 db_cxx libdb48 + NAMES_PER_DIR + HINTS ${_BerkeleyDB_lib_hint} + PATH_SUFFIXES debug/lib + ) + mark_as_advanced(BerkeleyDB_LIBRARY_DEBUG) + + unset(_BerkeleyDB_lib_hint) + unset(CMAKE_FIND_USE_CMAKE_PATH) + + include(SelectLibraryConfigurations) + select_library_configurations(BerkeleyDB) + # The select_library_configurations() command sets BerkeleyDB_FOUND, but we + # want the one from the find_package_handle_standard_args() command below. + unset(BerkeleyDB_FOUND) +endif() + +if(BerkeleyDB_INCLUDE_DIR) + file(STRINGS "${BerkeleyDB_INCLUDE_DIR}/db.h" _BerkeleyDB_version_strings REGEX "^#define[\t ]+DB_VERSION_(MAJOR|MINOR|PATCH)[ \t]+[0-9]+.*") + string(REGEX REPLACE ".*#define[\t ]+DB_VERSION_MAJOR[ \t]+([0-9]+).*" "\\1" _BerkeleyDB_version_major "${_BerkeleyDB_version_strings}") + string(REGEX REPLACE ".*#define[\t ]+DB_VERSION_MINOR[ \t]+([0-9]+).*" "\\1" _BerkeleyDB_version_minor "${_BerkeleyDB_version_strings}") + string(REGEX REPLACE ".*#define[\t ]+DB_VERSION_PATCH[ \t]+([0-9]+).*" "\\1" _BerkeleyDB_version_patch "${_BerkeleyDB_version_strings}") + unset(_BerkeleyDB_version_strings) + # The MAJOR.MINOR.PATCH version will be logged in the following find_package_handle_standard_args() command. + set(_BerkeleyDB_full_version ${_BerkeleyDB_version_major}.${_BerkeleyDB_version_minor}.${_BerkeleyDB_version_patch}) + set(BerkeleyDB_VERSION ${_BerkeleyDB_version_major}.${_BerkeleyDB_version_minor}) + unset(_BerkeleyDB_version_major) + unset(_BerkeleyDB_version_minor) + unset(_BerkeleyDB_version_patch) +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(BerkeleyDB + REQUIRED_VARS BerkeleyDB_LIBRARY BerkeleyDB_INCLUDE_DIR + VERSION_VAR _BerkeleyDB_full_version +) +unset(_BerkeleyDB_full_version) + +if(BerkeleyDB_FOUND AND NOT TARGET BerkeleyDB::BerkeleyDB) + add_library(BerkeleyDB::BerkeleyDB UNKNOWN IMPORTED) + set_target_properties(BerkeleyDB::BerkeleyDB PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${BerkeleyDB_INCLUDE_DIR}" + ) + if(BerkeleyDB_LIBRARY_RELEASE) + set_property(TARGET BerkeleyDB::BerkeleyDB APPEND PROPERTY + IMPORTED_CONFIGURATIONS RELEASE + ) + set_target_properties(BerkeleyDB::BerkeleyDB PROPERTIES + IMPORTED_LOCATION_RELEASE "${BerkeleyDB_LIBRARY_RELEASE}" + ) + endif() + if(BerkeleyDB_LIBRARY_DEBUG) + set_property(TARGET BerkeleyDB::BerkeleyDB APPEND PROPERTY + IMPORTED_CONFIGURATIONS DEBUG) + set_target_properties(BerkeleyDB::BerkeleyDB PROPERTIES + IMPORTED_LOCATION_DEBUG "${BerkeleyDB_LIBRARY_DEBUG}" + ) + endif() +endif() diff --git a/cmake/module/FindGMP.cmake b/cmake/module/FindGMP.cmake new file mode 100644 index 0000000000..0e658c05dd --- /dev/null +++ b/cmake/module/FindGMP.cmake @@ -0,0 +1,50 @@ +# Try to find the GNU Multiple Precision Arithmetic Library (GMP) +# See http://gmplib.org/ + +if (GMP_INCLUDES AND GMP_LIBRARIES) + set(GMP_FIND_QUIETLY TRUE) +endif (GMP_INCLUDES AND GMP_LIBRARIES) + +find_path(GMP_INCLUDES + NAMES + gmp.h + HINTS + $ENV{GMPDIR} + ${INCLUDE_INSTALL_DIR} + ${LIB_INSTALL_DIR} + ${PC_GMP_LIBRARY_DIRS} + /usr/lib + /usr/local/lib +) + +find_library(GMP_LIBRARIES + NAMES gmp + HINTS + $ENV{GMPDIR} + ${LIB_INSTALL_DIR} + ${PC_GMP_LIBRARY_DIRS} + /usr/lib + /usr/local/lib +) + + +if(GMP_LIBRARIES AND GMP_INCLUDES) + message(STATUS "Found GMP: ${GMP_LIBRARIES}") + message(STATUS "GMP includes: ${GMP_INCLUDES}") + file(STRINGS "${GMP_INCLUDES}/gmp.h" gmp_version_str REGEX "^#define[\t ]+__GNU_MP_VERSION[\t ]+[0-9]+") + string(REGEX REPLACE "^#define[\t ]+__GNU_MP_VERSION[\t ]+([0-9]+).*" "\\1" GMP_VERSION_MAJOR "${gmp_version_str}") + + file(STRINGS "${GMP_INCLUDES}/gmp.h" gmp_version_str REGEX "^#define[\t ]+__GNU_MP_VERSION_MINOR[\t ]+[0-9]+") + string(REGEX REPLACE "^#define[\t ]+__GNU_MP_VERSION_MINOR[\t ]+([0-9]+).*" "\\1" GMP_VERSION_MINOR "${gmp_version_str}") + + set(GMP_VERSION "${GMP_VERSION_MAJOR}.${GMP_VERSION_MINOR}") + message(STATUS "GMP_VERSION_MAJOR : ${GMP_VERSION_MAJOR}") + message(STATUS "GMP_VERSION_MINOR : ${GMP_VERSION_MINOR}") +else() + message(FATAL_ERROR "Could not find GMP") +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(GMP DEFAULT_MSG + GMP_INCLUDES GMP_LIBRARIES) +mark_as_advanced(GMP_INCLUDES GMP_LIBRARIES) \ No newline at end of file diff --git a/cmake/module/FindLibevent.cmake b/cmake/module/FindLibevent.cmake new file mode 100644 index 0000000000..72e4572b61 --- /dev/null +++ b/cmake/module/FindLibevent.cmake @@ -0,0 +1,86 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +#[=======================================================================[ +FindLibevent +------------ + +Finds the Libevent headers and libraries. + +This is a wrapper around find_package()/pkg_check_modules() commands that: + - facilitates searching in various build environments + - prints a standard log message + +#]=======================================================================] + +# Check whether evhttp_connection_get_peer expects const char**. +# See https://github.com/libevent/libevent/commit/a18301a2bb160ff7c3ffaf5b7653c39ffe27b385 +function(check_evhttp_connection_get_peer target) + include(CMakePushCheckState) + cmake_push_check_state(RESET) + set(CMAKE_REQUIRED_LIBRARIES ${target}) + include(CheckCXXSourceCompiles) + check_cxx_source_compiles(" + #include + #include + + int main() + { + evhttp_connection* conn = (evhttp_connection*)1; + const char* host; + uint16_t port; + evhttp_connection_get_peer(conn, &host, &port); + } + " HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR + ) + cmake_pop_check_state() + target_compile_definitions(${target} INTERFACE + $<$:HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR> + ) +endfunction() + +set(_libevent_components core extra) +if(NOT WIN32 AND NOT MINGW) + list(APPEND _libevent_components pthreads) +endif() + +find_package(Libevent ${Libevent_FIND_VERSION} QUIET + NO_MODULE +) + +include(FindPackageHandleStandardArgs) +if(Libevent_FOUND) + find_package(Libevent ${Libevent_FIND_VERSION} QUIET + REQUIRED COMPONENTS ${_libevent_components} + NO_MODULE + ) + find_package_handle_standard_args(Libevent + REQUIRED_VARS Libevent_DIR + VERSION_VAR Libevent_VERSION + ) + check_evhttp_connection_get_peer(libevent::extra) +else() + find_package(PkgConfig REQUIRED) + foreach(component IN LISTS _libevent_components) + pkg_check_modules(libevent_${component} + REQUIRED QUIET + IMPORTED_TARGET GLOBAL + libevent_${component}>=${Libevent_FIND_VERSION} + ) + if(TARGET PkgConfig::libevent_${component} AND NOT TARGET libevent::${component}) + add_library(libevent::${component} ALIAS PkgConfig::libevent_${component}) + endif() + endforeach() + find_package_handle_standard_args(Libevent + REQUIRED_VARS libevent_core_LIBRARY_DIRS + VERSION_VAR libevent_core_VERSION + ) + check_evhttp_connection_get_peer(PkgConfig::libevent_extra) +endif() + +unset(_libevent_components) + +mark_as_advanced(Libevent_DIR) +mark_as_advanced(_event_h) +mark_as_advanced(_event_lib) diff --git a/cmake/module/FindQRencode.cmake b/cmake/module/FindQRencode.cmake new file mode 100644 index 0000000000..39e3b8b679 --- /dev/null +++ b/cmake/module/FindQRencode.cmake @@ -0,0 +1,71 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +#[=======================================================================[ +FindQRencode +------------ + +Finds the QRencode header and library. + +This is a wrapper around find_package()/pkg_check_modules() commands that: + - facilitates searching in various build environments + - prints a standard log message + +#]=======================================================================] + +find_package(PkgConfig QUIET) +if(PKG_CONFIG_FOUND) + pkg_check_modules(PC_QRencode QUIET libqrencode) +endif() + +find_path(QRencode_INCLUDE_DIR + NAMES qrencode.h + PATHS ${PC_QRencode_INCLUDE_DIRS} +) + +find_library(QRencode_LIBRARY_RELEASE + NAMES qrencode + PATHS ${PC_QRencode_LIBRARY_DIRS} +) +find_library(QRencode_LIBRARY_DEBUG + NAMES qrencoded qrencode + PATHS ${PC_QRencode_LIBRARY_DIRS} +) +include(SelectLibraryConfigurations) +select_library_configurations(QRencode) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(QRencode + REQUIRED_VARS QRencode_LIBRARY QRencode_INCLUDE_DIR + VERSION_VAR PC_QRencode_VERSION +) + +if(QRencode_FOUND) + if(NOT TARGET QRencode::QRencode) + add_library(QRencode::QRencode UNKNOWN IMPORTED) + endif() + if(QRencode_LIBRARY_RELEASE) + set_property(TARGET QRencode::QRencode APPEND PROPERTY + IMPORTED_CONFIGURATIONS RELEASE + ) + set_target_properties(QRencode::QRencode PROPERTIES + IMPORTED_LOCATION_RELEASE "${QRencode_LIBRARY_RELEASE}" + ) + endif() + if(QRencode_LIBRARY_DEBUG) + set_property(TARGET QRencode::QRencode APPEND PROPERTY + IMPORTED_CONFIGURATIONS DEBUG + ) + set_target_properties(QRencode::QRencode PROPERTIES + IMPORTED_LOCATION_DEBUG "${QRencode_LIBRARY_DEBUG}" + ) + endif() + set_target_properties(QRencode::QRencode PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${QRencode_INCLUDE_DIR}" + ) +endif() + +mark_as_advanced( + QRencode_INCLUDE_DIR +) diff --git a/cmake/module/FindQt.cmake b/cmake/module/FindQt.cmake new file mode 100644 index 0000000000..4450056ab1 --- /dev/null +++ b/cmake/module/FindQt.cmake @@ -0,0 +1,186 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +#[=======================================================================[ +FindQt +------ + +Finds the Qt headers and libraries. + +This is a wrapper around find_package() command that: + - facilitates searching in various build environments + - prints a standard log message + +#]=======================================================================] + +set(_qt_homebrew_prefix) +if(CMAKE_HOST_APPLE) + find_program(HOMEBREW_EXECUTABLE brew) + if(HOMEBREW_EXECUTABLE) + execute_process( + COMMAND ${HOMEBREW_EXECUTABLE} --prefix qt@${Qt_FIND_VERSION_MAJOR} + OUTPUT_VARIABLE _qt_homebrew_prefix + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + endif() +endif() + +# Save CMAKE_FIND_ROOT_PATH_MODE_LIBRARY state. +unset(_qt_find_root_path_mode_library_saved) +if(DEFINED CMAKE_FIND_ROOT_PATH_MODE_LIBRARY) + set(_qt_find_root_path_mode_library_saved ${CMAKE_FIND_ROOT_PATH_MODE_LIBRARY}) +endif() + +# The Qt config files internally use find_library() calls for all +# dependencies to ensure their availability. In turn, the find_library() +# inspects the well-known locations on the file system; therefore, it must +# be able to find platform-specific system libraries, for example: +# /usr/x86_64-w64-mingw32/lib/libm.a or /usr/arm-linux-gnueabihf/lib/libm.a. +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH) + +find_package(Qt${Qt_FIND_VERSION_MAJOR} ${Qt_FIND_VERSION} + COMPONENTS ${Qt_FIND_COMPONENTS} + HINTS ${_qt_homebrew_prefix} + PATH_SUFFIXES Qt${Qt_FIND_VERSION_MAJOR} # Required on OpenBSD systems. +) +unset(_qt_homebrew_prefix) + +# Restore CMAKE_FIND_ROOT_PATH_MODE_LIBRARY state. +if(DEFINED _qt_find_root_path_mode_library_saved) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ${_qt_find_root_path_mode_library_saved}) + unset(_qt_find_root_path_mode_library_saved) +else() + unset(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY) +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Qt + REQUIRED_VARS Qt${Qt_FIND_VERSION_MAJOR}_DIR + VERSION_VAR Qt${Qt_FIND_VERSION_MAJOR}_VERSION +) + +foreach(component IN LISTS Qt_FIND_COMPONENTS ITEMS "") + mark_as_advanced(Qt${Qt_FIND_VERSION_MAJOR}${component}_DIR) +endforeach() + +# Prioritize finding static libraries +set(_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES}) +set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${_CMAKE_FIND_LIBRARY_SUFFIXES}) + +find_library(LIB_QTLIBPNG NAMES qtlibpng REQUIRED) +message(STATUS "Found Qt5 dependency: qtlibpng : ${LIB_QTLIBPNG}") + +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND NOT MINGW) + find_library(LIB_FONTCONFIG NAMES fontconfig REQUIRED) + message(STATUS "Found Qt5 dependency: fontconfig : ${LIB_FONTCONFIG}") + + find_library(LIB_EXPAT NAMES expat REQUIRED) + message(STATUS "Found Qt5 dependency: expat : ${LIB_EXPAT}") + + find_library(LIB_FREETYPE NAMES freetype REQUIRED) + message(STATUS "Found Qt5 dependency: freetype : ${LIB_FREETYPE}") + + find_library(LIB_XCB_EWMH NAMES xcb-ewmh REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-ewmh : ${LIB_XCB_EWMH}") + + find_library(LIB_XCB_ICCCM NAMES xcb-icccm REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-icccm : ${LIB_XCB_ICCCM}") + + find_library(LIB_XCB_IMAGE NAMES xcb-image REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-image : ${LIB_XCB_IMAGE}") + + find_library(LIB_XCB_KEYSYMS NAMES xcb-keysyms REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-keysyms : ${LIB_XCB_KEYSYMS}") + + find_library(LIB_XCB_RANDR NAMES xcb-randr REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-randr : ${LIB_XCB_RANDR}") + + find_library(LIB_XCB_RENDER_UTIL NAMES xcb-render-util REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-render-util : ${LIB_XCB_RENDER_UTIL}") + + find_library(LIB_XCB_RENDER NAMES xcb-render REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-render : ${LIB_XCB_RENDER}") + + find_library(LIB_XCB_SHAPE NAMES xcb-shape REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-shape : ${LIB_XCB_SHAPE}") + + find_library(LIB_XCB_SHM NAMES xcb-shm REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-shm : ${LIB_XCB_SHM}") + + find_library(LIB_XCB_SYNC NAMES xcb-sync REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-sync : ${LIB_XCB_SYNC}") + + find_library(LIB_XCB_UTIL NAMES xcb-util REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-util : ${LIB_XCB_UTIL}") + + find_library(LIB_XCB_XFIXES NAMES xcb-xfixes REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-xfixes : ${LIB_XCB_XFIXES}") + + find_library(LIB_XCB_XINERAMA NAMES xcb-xinerama REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-xinerama : ${LIB_XCB_XINERAMA}") + + find_library(LIB_XCB_XKB NAMES xcb-xkb REQUIRED) + message(STATUS "Found Qt5 dependency: xcb-xkb : ${LIB_XCB_XKB}") + + find_library(LIB_XCB NAMES xcb REQUIRED) + message(STATUS "Found Qt5 dependency: xcb : ${LIB_XCB}") + + find_library(LIB_XKBCOMMON_X11 NAMES xkbcommon-x11 REQUIRED) + message(STATUS "Found Qt5 dependency: xkbcommon-x11 : ${LIB_XKBCOMMON_X11}") + + find_library(LIB_XKBCOMMON NAMES xkbcommon REQUIRED) + message(STATUS "Found Qt5 dependency: xkbcommon : ${LIB_XKBCOMMON}") + + find_library(LIB_XAU NAMES Xau REQUIRED) + message(STATUS "Found Qt5 dependency: Xau : ${LIB_XAU}") + +endif() + +find_library(LIB_QTHARFBUZZ NAMES qtharfbuzz REQUIRED) +message(STATUS "Found Qt5 dependency: qtharfbuzz : ${LIB_QTHARFBUZZ}") + +find_library(LIB_QTPCR2 NAMES qtpcre2 REQUIRED) +message(STATUS "Found Qt5 dependency: qtpcre2 : ${LIB_QTPCR2}") + +find_library(LIB_Z NAMES z REQUIRED) +message(STATUS "Found Qt5 dependency: z : ${LIB_Z}") + +# Qt5 dependencies libraries, order is important, should be last +add_library(Qt5_Dependencies + INTERFACE +) +target_link_libraries(Qt5_Dependencies + INTERFACE + ${LIB_QTLIBPNG} + ${LIB_QTHARFBUZZ} + ${LIB_QTPCR2} + $<$:${LIB_FONTCONFIG}> + $<$:${LIB_FREETYPE}> + $<$:${LIB_EXPAT}> + $<$:${LIB_XCB_EWMH}> + $<$:${LIB_XCB_ICCCM}> + $<$:${LIB_XCB_IMAGE}> + $<$:${LIB_XCB_KEYSYMS}> + $<$:${LIB_XCB_RANDR}> + $<$:${LIB_XCB_RENDER_UTIL}> + $<$:${LIB_XCB_RENDER}> + $<$:${LIB_XCB_SHAPE}> + $<$:${LIB_XCB_SHM}> + $<$:${LIB_XCB_SYNC}> + $<$:${LIB_XCB_UTIL}> + $<$:${LIB_XCB_XFIXES}> + $<$:${LIB_XCB_XINERAMA}> + $<$:${LIB_XCB_XKB}> + $<$:${LIB_XCB}> + $<$:${LIB_XKBCOMMON_X11}> + $<$:${LIB_XKBCOMMON}> + $<$:${LIB_XAU}> + ${LIB_Z} +) + +add_library(Qt5::Dependencies ALIAS Qt5_Dependencies) + +# Restore CMAKE_FIND_LIBRARY_SUFFIXES state. +set(CMAKE_FIND_LIBRARY_SUFFIXES ${_CMAKE_FIND_LIBRARY_SUFFIXES}) diff --git a/cmake/module/FindUSDT.cmake b/cmake/module/FindUSDT.cmake new file mode 100644 index 0000000000..0be7c28ff5 --- /dev/null +++ b/cmake/module/FindUSDT.cmake @@ -0,0 +1,67 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +#[=======================================================================[ +FindUSDT +-------- + +Finds the Userspace, Statically Defined Tracing header(s). + +Imported Targets +^^^^^^^^^^^^^^^^ + +This module provides imported target ``USDT::headers``, if +USDT has been found. + +Result Variables +^^^^^^^^^^^^^^^^ + +This module defines the following variables: + +``USDT_FOUND`` + "True" if USDT found. + +#]=======================================================================] + +find_path(USDT_INCLUDE_DIR + NAMES sys/sdt.h +) +mark_as_advanced(USDT_INCLUDE_DIR) + +if(USDT_INCLUDE_DIR) + include(CMakePushCheckState) + cmake_push_check_state(RESET) + + include(CheckCXXSourceCompiles) + set(CMAKE_REQUIRED_INCLUDES ${USDT_INCLUDE_DIR}) + check_cxx_source_compiles(" + // Setting SDT_USE_VARIADIC lets systemtap (sys/sdt.h) know that we want to use + // the optional variadic macros to define tracepoints. + #define SDT_USE_VARIADIC 1 + #include + + int main() + { + STAP_PROBEV(context, event); + int a, b, c, d, e, f, g; + STAP_PROBEV(context, event, a, b, c, d, e, f, g); + } + " HAVE_USDT_H + ) + + cmake_pop_check_state() +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(USDT + REQUIRED_VARS USDT_INCLUDE_DIR HAVE_USDT_H +) + +if(USDT_FOUND AND NOT TARGET USDT::headers) + add_library(USDT::headers INTERFACE IMPORTED) + set_target_properties(USDT::headers PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${USDT_INCLUDE_DIR}" + ) + set(ENABLE_TRACING TRUE) +endif() diff --git a/cmake/module/FindZeroMQ.cmake b/cmake/module/FindZeroMQ.cmake new file mode 100644 index 0000000000..05837001fa --- /dev/null +++ b/cmake/module/FindZeroMQ.cmake @@ -0,0 +1,43 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +#[=======================================================================[ +FindZeroMQ +---------- + +Finds the ZeroMQ headers and library. + +This is a wrapper around find_package()/pkg_check_modules() commands that: + - facilitates searching in various build environments + - prints a standard log message + +#]=======================================================================] + +include(FindPackageHandleStandardArgs) +find_package(ZeroMQ ${ZeroMQ_FIND_VERSION} NO_MODULE QUIET) +if(NOT TARGET zeromq) + if(ZeroMQ_FOUND) + find_package_handle_standard_args(ZeroMQ + REQUIRED_VARS ZeroMQ_DIR + VERSION_VAR ZeroMQ_VERSION + ) + if(TARGET libzmq) + add_library(zeromq ALIAS libzmq) + elseif(TARGET libzmq-static) + add_library(zeromq ALIAS libzmq-static) + endif() + mark_as_advanced(ZeroMQ_DIR) + else() + find_package(PkgConfig REQUIRED) + pkg_check_modules(libzmq QUIET + IMPORTED_TARGET + libzmq>=${ZeroMQ_FIND_VERSION} + ) + find_package_handle_standard_args(ZeroMQ + REQUIRED_VARS libzmq_LIBRARY_DIRS + VERSION_VAR libzmq_VERSION + ) + add_library(zeromq ALIAS PkgConfig::libzmq) + endif() +endif() diff --git a/cmake/module/FlagsSummary.cmake b/cmake/module/FlagsSummary.cmake new file mode 100644 index 0000000000..91d1df90d9 --- /dev/null +++ b/cmake/module/FlagsSummary.cmake @@ -0,0 +1,74 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include_guard(GLOBAL) + +function(indent_message header content indent_num) + if(indent_num GREATER 0) + string(REPEAT " " ${indent_num} indentation) + string(REPEAT "." ${indent_num} tail) + string(REGEX REPLACE "${tail}$" "" header "${header}") + endif() + message("${indentation}${header} ${content}") +endfunction() + +# Print tools' flags on best-effort. Include the abstracted +# CMake flags that we touch ourselves. +function(print_flags_per_config config indent_num) + string(TOUPPER "${config}" config_uppercase) + + include(GetTargetInterface) + get_target_interface(definitions "${config}" core_interface COMPILE_DEFINITIONS) + indent_message("Preprocessor defined macros ..........." "${definitions}" ${indent_num}) + + string(STRIP "${CMAKE_CXX_COMPILER_ARG1} ${CMAKE_CXX_FLAGS}" combined_cxx_flags) + string(STRIP "${combined_cxx_flags} ${CMAKE_CXX_FLAGS_${config_uppercase}}" combined_cxx_flags) + string(STRIP "${combined_cxx_flags} ${CMAKE_CXX${CMAKE_CXX_STANDARD}_STANDARD_COMPILE_OPTION}" combined_cxx_flags) + if(CMAKE_POSITION_INDEPENDENT_CODE) + string(JOIN " " combined_cxx_flags ${combined_cxx_flags} ${CMAKE_CXX_COMPILE_OPTIONS_PIC}) + endif() + get_target_interface(core_cxx_flags "${config}" core_interface COMPILE_OPTIONS) + string(STRIP "${combined_cxx_flags} ${core_cxx_flags}" combined_cxx_flags) + string(STRIP "${combined_cxx_flags} ${APPEND_CPPFLAGS}" combined_cxx_flags) + string(STRIP "${combined_cxx_flags} ${APPEND_CXXFLAGS}" combined_cxx_flags) + indent_message("C++ compiler flags ...................." "${combined_cxx_flags}" ${indent_num}) + + string(STRIP "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_${config_uppercase}}" combined_linker_flags) + string(STRIP "${combined_linker_flags} ${CMAKE_EXE_LINKER_FLAGS}" combined_linker_flags) + get_target_interface(common_link_options "${config}" core_interface LINK_OPTIONS) + string(STRIP "${combined_linker_flags} ${common_link_options}" combined_linker_flags) + if(CMAKE_CXX_LINK_PIE_SUPPORTED) + string(JOIN " " combined_linker_flags ${combined_linker_flags} ${CMAKE_CXX_LINK_OPTIONS_PIE}) + endif() + string(STRIP "${combined_linker_flags} ${APPEND_LDFLAGS}" combined_linker_flags) + indent_message("Linker flags .........................." "${combined_linker_flags}" ${indent_num}) +endfunction() + +function(flags_summary) + get_property(is_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + if(is_multi_config) + list(JOIN CMAKE_CONFIGURATION_TYPES ", " configs) + message("Available build configurations ........ ${configs}") + if(CMAKE_GENERATOR MATCHES "Visual Studio") + set(default_config "Debug") + else() + list(GET CMAKE_CONFIGURATION_TYPES 0 default_config) + endif() + message("Default build configuration ........... ${default_config}") + foreach(config IN LISTS CMAKE_CONFIGURATION_TYPES) + message("") + message("'${config}' build configuration:") + print_flags_per_config("${config}" 2) + endforeach() + else() + message("CMAKE_BUILD_TYPE ...................... ${CMAKE_BUILD_TYPE}") + print_flags_per_config("${CMAKE_BUILD_TYPE}" 0) + endif() + message("") + message([=[ +NOTE: The summary above may not exactly match the final applied build flags + if any additional CMAKE_* or environment variables have been modified. + To see the exact flags applied, build with the --verbose option. +]=]) +endfunction() diff --git a/cmake/module/GenerateHeaders.cmake b/cmake/module/GenerateHeaders.cmake new file mode 100644 index 0000000000..c69007acb6 --- /dev/null +++ b/cmake/module/GenerateHeaders.cmake @@ -0,0 +1,21 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +function(generate_header_from_json json_source_relpath) + add_custom_command( + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${json_source_relpath}.h + COMMAND ${CMAKE_COMMAND} -DJSON_SOURCE_PATH=${CMAKE_CURRENT_SOURCE_DIR}/${json_source_relpath} -DHEADER_PATH=${CMAKE_CURRENT_BINARY_DIR}/${json_source_relpath}.h -P ${PROJECT_SOURCE_DIR}/cmake/script/GenerateHeaderFromJson.cmake + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${json_source_relpath} ${PROJECT_SOURCE_DIR}/cmake/script/GenerateHeaderFromJson.cmake + VERBATIM + ) +endfunction() + +function(generate_header_from_raw raw_source_relpath raw_namespace) + add_custom_command( + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${raw_source_relpath}.h + COMMAND ${CMAKE_COMMAND} -DRAW_SOURCE_PATH=${CMAKE_CURRENT_SOURCE_DIR}/${raw_source_relpath} -DHEADER_PATH=${CMAKE_CURRENT_BINARY_DIR}/${raw_source_relpath}.h -DRAW_NAMESPACE=${raw_namespace} -P ${PROJECT_SOURCE_DIR}/cmake/script/GenerateHeaderFromRaw.cmake + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${raw_source_relpath} ${PROJECT_SOURCE_DIR}/cmake/script/GenerateHeaderFromRaw.cmake + VERBATIM + ) +endfunction() diff --git a/cmake/module/GenerateSetupNsi.cmake b/cmake/module/GenerateSetupNsi.cmake new file mode 100644 index 0000000000..f9f4014e4b --- /dev/null +++ b/cmake/module/GenerateSetupNsi.cmake @@ -0,0 +1,18 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +function(generate_setup_nsi) + set(abs_top_srcdir ${PROJECT_SOURCE_DIR}) + set(abs_top_builddir ${PROJECT_BINARY_DIR}) + set(CLIENT_URL ${PROJECT_HOMEPAGE_URL}) + set(CLIENT_TARNAME "firo") + set(BITCOIN_GUI_NAME "firo-qt") + set(BITCOIN_DAEMON_NAME "firod") + set(BITCOIN_CLI_NAME "firo-cli") + set(BITCOIN_TX_NAME "firo-tx") + set(BITCOIN_WALLET_TOOL_NAME "firo-wallet") + set(BITCOIN_TEST_NAME "test_firo") + set(EXEEXT ${CMAKE_EXECUTABLE_SUFFIX}) + configure_file(${PROJECT_SOURCE_DIR}/share/setup.nsi.in ${PROJECT_BINARY_DIR}/firo-win64-setup.nsi USE_SOURCE_PERMISSIONS @ONLY) +endfunction() diff --git a/cmake/module/GetTargetInterface.cmake b/cmake/module/GetTargetInterface.cmake new file mode 100644 index 0000000000..1e455d456b --- /dev/null +++ b/cmake/module/GetTargetInterface.cmake @@ -0,0 +1,53 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include_guard(GLOBAL) + +# Evaluates config-specific generator expressions in a list. +# Recognizable patterns are: +# - $<$:[value]> +# - $<$>:[value]> +function(evaluate_generator_expressions list config) + set(input ${${list}}) + set(result) + foreach(token IN LISTS input) + if(token MATCHES "\\$<\\$]+)>:([^>]+)>") + if(CMAKE_MATCH_1 STREQUAL config) + list(APPEND result ${CMAKE_MATCH_2}) + endif() + elseif(token MATCHES "\\$<\\$]+)>>:([^>]+)>") + if(NOT CMAKE_MATCH_1 STREQUAL config) + list(APPEND result ${CMAKE_MATCH_2}) + endif() + else() + list(APPEND result ${token}) + endif() + endforeach() + set(${list} ${result} PARENT_SCOPE) +endfunction() + + +# Gets target's interface properties recursively. +function(get_target_interface var config target property) + get_target_property(result ${target} INTERFACE_${property}) + if(result) + evaluate_generator_expressions(result "${config}") + list(JOIN result " " result) + else() + set(result) + endif() + + get_target_property(dependencies ${target} INTERFACE_LINK_LIBRARIES) + if(dependencies) + evaluate_generator_expressions(dependencies "${config}") + foreach(dependency IN LISTS dependencies) + if(TARGET ${dependency}) + get_target_interface(dep_result "${config}" ${dependency} ${property}) + string(STRIP "${result} ${dep_result}" result) + endif() + endforeach() + endif() + + set(${var} "${result}" PARENT_SCOPE) +endfunction() diff --git a/cmake/module/InstallBinaryComponent.cmake b/cmake/module/InstallBinaryComponent.cmake new file mode 100644 index 0000000000..c7b2ed9ae6 --- /dev/null +++ b/cmake/module/InstallBinaryComponent.cmake @@ -0,0 +1,26 @@ +# Copyright (c) 2025-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include_guard(GLOBAL) +include(GNUInstallDirs) + +function(install_binary_component component) + cmake_parse_arguments(PARSE_ARGV 1 + IC # prefix + "HAS_MANPAGE" # options + "" # one_value_keywords + "" # multi_value_keywords + ) + set(target_name ${component}) + install(TARGETS ${target_name} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + COMPONENT ${component} + ) + if(INSTALL_MAN AND IC_HAS_MANPAGE) + install(FILES ${PROJECT_SOURCE_DIR}/doc/man/${target_name}.1 + DESTINATION ${CMAKE_INSTALL_MANDIR}/man1 + COMPONENT ${component} + ) + endif() +endfunction() diff --git a/cmake/module/Maintenance.cmake b/cmake/module/Maintenance.cmake new file mode 100644 index 0000000000..a1dde44575 --- /dev/null +++ b/cmake/module/Maintenance.cmake @@ -0,0 +1,151 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include_guard(GLOBAL) + +function(setup_split_debug_script) + if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Linux") + set(OBJCOPY ${CMAKE_OBJCOPY}) + set(STRIP ${CMAKE_STRIP}) + configure_file( + contrib/devtools/split-debug.sh.in split-debug.sh + FILE_PERMISSIONS OWNER_READ OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE + WORLD_READ + @ONLY + ) + endif() +endfunction() + +function(add_maintenance_targets) + if(NOT PYTHON_COMMAND) + return() + endif() + + if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + set(exe_format MACHO) + elseif(WIN32) + set(exe_format PE) + else() + set(exe_format ELF) + endif() + + # In CMake, the components of the compiler invocation are separated into distinct variables: + # - CMAKE_CXX_COMPILER: the full path to the compiler binary itself (e.g., /usr/bin/clang++). + # - CMAKE_CXX_COMPILER_ARG1: a string containing initial compiler options (e.g., --target=x86_64-apple-darwin -nostdlibinc). + # By concatenating these variables, we form the complete command line to be passed to a Python script via the CXX environment variable. + string(STRIP "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}" cxx_compiler_command) + add_custom_target(test-security-check + COMMAND ${CMAKE_COMMAND} -E env CXX=${cxx_compiler_command} CXXFLAGS=${CMAKE_CXX_FLAGS} LDFLAGS=${CMAKE_EXE_LINKER_FLAGS} ${PYTHON_COMMAND} ${PROJECT_SOURCE_DIR}/contrib/devtools/test-security-check.py TestSecurityChecks.test_${exe_format} + COMMAND ${CMAKE_COMMAND} -E env CXX=${cxx_compiler_command} CXXFLAGS=${CMAKE_CXX_FLAGS} LDFLAGS=${CMAKE_EXE_LINKER_FLAGS} ${PYTHON_COMMAND} ${PROJECT_SOURCE_DIR}/contrib/devtools/test-symbol-check.py TestSymbolChecks.test_${exe_format} + VERBATIM + ) + + foreach(target IN ITEMS firod firo-qt firo-cli firo-tx firo-util firo-wallet test_firo bench_firo) + if(TARGET ${target}) + list(APPEND executables $) + endif() + endforeach() + + add_custom_target(check-symbols + COMMAND ${CMAKE_COMMAND} -E echo "Running symbol and dynamic library checks..." + COMMAND ${PYTHON_COMMAND} ${PROJECT_SOURCE_DIR}/contrib/devtools/symbol-check.py ${executables} + VERBATIM + ) + + if(ENABLE_HARDENING) + add_custom_target(check-security + COMMAND ${CMAKE_COMMAND} -E echo "Checking binary security..." + COMMAND ${PYTHON_COMMAND} ${PROJECT_SOURCE_DIR}/contrib/devtools/security-check.py ${executables} + VERBATIM + ) + else() + add_custom_target(check-security) + endif() +endfunction() + +function(add_windows_deploy_target) + if(MINGW AND TARGET firo-qt AND TARGET firod AND TARGET firo-cli AND TARGET firo-tx AND TARGET firo-wallet AND TARGET firo-util AND TARGET test_firo) + # TODO: Consider replacing this code with the CPack NSIS Generator. + # See https://cmake.org/cmake/help/latest/cpack_gen/nsis.html + include(GenerateSetupNsi) + generate_setup_nsi() + add_custom_command( + OUTPUT ${PROJECT_BINARY_DIR}/firo-win64-setup.exe + COMMAND ${CMAKE_COMMAND} -E make_directory ${PROJECT_BINARY_DIR}/release + COMMAND ${CMAKE_STRIP} $ -o ${PROJECT_BINARY_DIR}/release/$ + COMMAND ${CMAKE_STRIP} $ -o ${PROJECT_BINARY_DIR}/release/$ + COMMAND ${CMAKE_STRIP} $ -o ${PROJECT_BINARY_DIR}/release/$ + COMMAND ${CMAKE_STRIP} $ -o ${PROJECT_BINARY_DIR}/release/$ + COMMAND ${CMAKE_STRIP} $ -o ${PROJECT_BINARY_DIR}/release/$ + COMMAND ${CMAKE_STRIP} $ -o ${PROJECT_BINARY_DIR}/release/$ + COMMAND ${CMAKE_STRIP} $ -o ${PROJECT_BINARY_DIR}/release/$ + COMMAND makensis -V2 ${PROJECT_BINARY_DIR}/firo-win64-setup.nsi + VERBATIM + ) + add_custom_target(deploy DEPENDS ${PROJECT_BINARY_DIR}/firo-win64-setup.exe) + endif() +endfunction() + +function(add_macos_deploy_target) + if(CMAKE_SYSTEM_NAME STREQUAL "Darwin" AND TARGET firo-qt) + set(macos_app "Firo-Qt.app") + # Populate Contents subdirectory. + configure_file(${PROJECT_SOURCE_DIR}/share/qt/Info.plist.in ${macos_app}/Contents/Info.plist NO_SOURCE_PERMISSIONS) + file(CONFIGURE OUTPUT ${macos_app}/Contents/PkgInfo CONTENT "APPL????") + # Populate Contents/Resources subdirectory. + file(CONFIGURE OUTPUT ${macos_app}/Contents/Resources/empty.lproj CONTENT "") + configure_file(${PROJECT_SOURCE_DIR}/src/qt/res/icons/firo.icns ${macos_app}/Contents/Resources/firo.icns NO_SOURCE_PERMISSIONS COPYONLY) + file(CONFIGURE OUTPUT ${macos_app}/Contents/Resources/Base.lproj/InfoPlist.strings + CONTENT "{ CFBundleDisplayName = \"@CLIENT_NAME@\"; CFBundleName = \"@CLIENT_NAME@\"; }" + ) + + add_custom_command( + OUTPUT ${PROJECT_BINARY_DIR}/${macos_app}/Contents/MacOS/Firo-Qt + COMMAND ${CMAKE_COMMAND} --install ${PROJECT_BINARY_DIR} --config $ --component GUI --prefix ${macos_app}/Contents/MacOS --strip + COMMAND ${CMAKE_COMMAND} -E rename ${macos_app}/Contents/MacOS/bin/$ ${macos_app}/Contents/MacOS/Firo-Qt + COMMAND ${CMAKE_COMMAND} -E rm -rf ${macos_app}/Contents/MacOS/bin + VERBATIM + ) + + string(REPLACE " " "-" osx_volname ${CLIENT_NAME}) + if(CMAKE_HOST_APPLE) + add_custom_command( + OUTPUT ${PROJECT_BINARY_DIR}/${osx_volname}.zip + COMMAND ${PYTHON_COMMAND} ${PROJECT_SOURCE_DIR}/contrib/macdeploy/macdeployqtplus ${macos_app} ${osx_volname} -translations-dir=${QT_TRANSLATIONS_DIR} -zip + DEPENDS ${PROJECT_BINARY_DIR}/${macos_app}/Contents/MacOS/Firo-Qt + VERBATIM + ) + add_custom_target(deploydir + DEPENDS ${PROJECT_BINARY_DIR}/${osx_volname}.zip + ) + add_custom_target(deploy + DEPENDS ${PROJECT_BINARY_DIR}/${osx_volname}.zip + ) + else() + add_custom_command( + OUTPUT ${PROJECT_BINARY_DIR}/dist/${macos_app}/Contents/MacOS/Firo-Qt + COMMAND OBJDUMP=${CMAKE_OBJDUMP} ${PYTHON_COMMAND} ${PROJECT_SOURCE_DIR}/contrib/macdeploy/macdeployqtplus ${macos_app} ${osx_volname} -translations-dir=${QT_TRANSLATIONS_DIR} + DEPENDS ${PROJECT_BINARY_DIR}/${macos_app}/Contents/MacOS/Firo-Qt + VERBATIM + ) + add_custom_target(deploydir + DEPENDS ${PROJECT_BINARY_DIR}/dist/${macos_app}/Contents/MacOS/Firo-Qt + ) + + find_program(ZIP_COMMAND zip REQUIRED) + add_custom_command( + OUTPUT ${PROJECT_BINARY_DIR}/dist/${osx_volname}.zip + WORKING_DIRECTORY dist + COMMAND ${PROJECT_SOURCE_DIR}/cmake/script/macos_zip.sh ${ZIP_COMMAND} ${osx_volname}.zip + VERBATIM + ) + add_custom_target(deploy + DEPENDS ${PROJECT_BINARY_DIR}/dist/${osx_volname}.zip + ) + endif() + add_dependencies(deploydir firo-qt) + add_dependencies(deploy deploydir) + endif() +endfunction() diff --git a/cmake/module/ProcessConfigurations.cmake b/cmake/module/ProcessConfigurations.cmake new file mode 100644 index 0000000000..7e2fc0080e --- /dev/null +++ b/cmake/module/ProcessConfigurations.cmake @@ -0,0 +1,175 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include_guard(GLOBAL) + +include(TryAppendCXXFlags) + +macro(normalize_string string) + string(REGEX REPLACE " +" " " ${string} "${${string}}") + string(STRIP "${${string}}" ${string}) +endmacro() + +function(are_flags_overridden flags_var result_var) + normalize_string(${flags_var}) + normalize_string(${flags_var}_INIT) + if(${flags_var} STREQUAL ${flags_var}_INIT) + set(${result_var} FALSE PARENT_SCOPE) + else() + set(${result_var} TRUE PARENT_SCOPE) + endif() +endfunction() + + +# Removes duplicated flags. The relative order of flags is preserved. +# If duplicates are encountered, only the last instance is preserved. +function(deduplicate_flags flags) + separate_arguments(${flags}) + list(REVERSE ${flags}) + list(REMOVE_DUPLICATES ${flags}) + list(REVERSE ${flags}) + list(JOIN ${flags} " " result) + set(${flags} "${result}" PARENT_SCOPE) +endfunction() + + +function(get_all_configs output) + get_property(is_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + if(is_multi_config) + set(all_configs ${CMAKE_CONFIGURATION_TYPES}) + else() + get_property(all_configs CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS) + if(NOT all_configs) + # See https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#default-and-custom-configurations + set(all_configs Debug Release RelWithDebInfo MinSizeRel) + endif() + endif() + set(${output} "${all_configs}" PARENT_SCOPE) +endfunction() + + +#[=[ +Set the default build configuration. + +See: https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#build-configurations. + +On single-configuration generators, this function sets the CMAKE_BUILD_TYPE variable to +the default build configuration, which can be overridden by the user at configure time if needed. + +On multi-configuration generators, this function rearranges the CMAKE_CONFIGURATION_TYPES list, +ensuring that the default build configuration appears first while maintaining the order of the +remaining configurations. The user can choose a build configuration at build time. +]=] +function(set_default_config config) + get_all_configs(all_configs) + if(NOT ${config} IN_LIST all_configs) + message(FATAL_ERROR "The default config is \"${config}\", but must be one of ${all_configs}.") + endif() + + list(REMOVE_ITEM all_configs ${config}) + list(PREPEND all_configs ${config}) + + get_property(is_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + if(is_multi_config) + get_property(help_string CACHE CMAKE_CONFIGURATION_TYPES PROPERTY HELPSTRING) + set(CMAKE_CONFIGURATION_TYPES "${all_configs}" CACHE STRING "${help_string}" FORCE) + # Also see https://gitlab.kitware.com/cmake/cmake/-/issues/19512. + set(CMAKE_TRY_COMPILE_CONFIGURATION "${config}" PARENT_SCOPE) + else() + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY + STRINGS "${all_configs}" + ) + if(NOT CMAKE_BUILD_TYPE) + message(STATUS "Setting build type to \"${config}\" as none was specified") + get_property(help_string CACHE CMAKE_BUILD_TYPE PROPERTY HELPSTRING) + set(CMAKE_BUILD_TYPE "${config}" CACHE STRING "${help_string}" FORCE) + endif() + set(CMAKE_TRY_COMPILE_CONFIGURATION "${CMAKE_BUILD_TYPE}" PARENT_SCOPE) + endif() +endfunction() + +function(remove_cxx_flag_from_all_configs flag) + get_all_configs(all_configs) + foreach(config IN LISTS all_configs) + string(TOUPPER "${config}" config_uppercase) + set(flags "${CMAKE_CXX_FLAGS_${config_uppercase}}") + separate_arguments(flags) + list(FILTER flags EXCLUDE REGEX "${flag}") + list(JOIN flags " " new_flags) + set(CMAKE_CXX_FLAGS_${config_uppercase} "${new_flags}" PARENT_SCOPE) + set(CMAKE_CXX_FLAGS_${config_uppercase} "${new_flags}" + CACHE STRING + "Flags used by the CXX compiler during ${config_uppercase} builds." + FORCE + ) + endforeach() +endfunction() + +function(replace_cxx_flag_in_config config old_flag new_flag) + string(TOUPPER "${config}" config_uppercase) + string(REGEX REPLACE "(^| )${old_flag}( |$)" "\\1${new_flag}\\2" new_flags "${CMAKE_CXX_FLAGS_${config_uppercase}}") + set(CMAKE_CXX_FLAGS_${config_uppercase} "${new_flags}" PARENT_SCOPE) + set(CMAKE_CXX_FLAGS_${config_uppercase} "${new_flags}" + CACHE STRING + "Flags used by the CXX compiler during ${config_uppercase} builds." + FORCE + ) +endfunction() + +set_default_config(RelWithDebInfo) + +# Redefine/adjust per-configuration flags. +target_compile_definitions(core_interface_debug INTERFACE + DEBUG + DEBUG_LOCKORDER + DEBUG_LOCKCONTENTION + RPC_DOC_CHECK + ABORT_ON_FAILED_ASSUME +) +# We leave assertions on. +if(MSVC) + remove_cxx_flag_from_all_configs(/DNDEBUG) +else() + remove_cxx_flag_from_all_configs(-DNDEBUG) + + # Adjust flags used by the CXX compiler during RELEASE builds. + # Prefer -O2 optimization level. (-O3 is CMake's default for Release for many compilers.) + replace_cxx_flag_in_config(Release -O3 -O2) + + are_flags_overridden(CMAKE_CXX_FLAGS_DEBUG cxx_flags_debug_overridden) + if(NOT cxx_flags_debug_overridden) + # Redefine flags used by the CXX compiler during DEBUG builds. + try_append_cxx_flags("-g3" RESULT_VAR compiler_supports_g3) + if(compiler_supports_g3) + replace_cxx_flag_in_config(Debug -g -g3) + endif() + unset(compiler_supports_g3) + + try_append_cxx_flags("-ftrapv" RESULT_VAR compiler_supports_ftrapv) + if(compiler_supports_ftrapv) + string(PREPEND CMAKE_CXX_FLAGS_DEBUG "-ftrapv ") + endif() + unset(compiler_supports_ftrapv) + + string(PREPEND CMAKE_CXX_FLAGS_DEBUG "-O0 ") + + set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}" + CACHE STRING + "Flags used by the CXX compiler during DEBUG builds." + FORCE + ) + endif() + unset(cxx_flags_debug_overridden) +endif() + +set(CMAKE_CXX_FLAGS_COVERAGE "-g -Og --coverage") +set(CMAKE_OBJCXX_FLAGS_COVERAGE "-g -Og --coverage") +set(CMAKE_EXE_LINKER_FLAGS_COVERAGE "--coverage") +set(CMAKE_SHARED_LINKER_FLAGS_COVERAGE "--coverage") +get_property(is_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(is_multi_config) + if(NOT "Coverage" IN_LIST CMAKE_CONFIGURATION_TYPES) + list(APPEND CMAKE_CONFIGURATION_TYPES Coverage) + endif() +endif() diff --git a/cmake/module/TestAppendRequiredLibraries.cmake b/cmake/module/TestAppendRequiredLibraries.cmake new file mode 100644 index 0000000000..26981aeeea --- /dev/null +++ b/cmake/module/TestAppendRequiredLibraries.cmake @@ -0,0 +1,106 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include_guard(GLOBAL) + +# Illumos/SmartOS requires linking with -lsocket if +# using getifaddrs & freeifaddrs. +# See: +# - https://github.com/bitcoin/bitcoin/pull/21486 +# - https://smartos.org/man/3socket/getifaddrs +function(test_append_socket_library target) + if (NOT TARGET ${target}) + message(FATAL_ERROR "${CMAKE_CURRENT_FUNCTION}() called with non-existent target \"${target}\".") + endif() + + set(check_socket_source " + #include + #include + + int main() { + struct ifaddrs* ifaddr; + getifaddrs(&ifaddr); + freeifaddrs(ifaddr); + } + ") + + include(CheckSourceCompilesAndLinks) + check_cxx_source_links("${check_socket_source}" IFADDR_LINKS_WITHOUT_LIBSOCKET) + if(NOT IFADDR_LINKS_WITHOUT_LIBSOCKET) + check_cxx_source_links_with_libs(socket "${check_socket_source}" IFADDR_NEEDS_LINK_TO_LIBSOCKET) + if(IFADDR_NEEDS_LINK_TO_LIBSOCKET) + target_link_libraries(${target} INTERFACE socket) + else() + message(FATAL_ERROR "Cannot figure out how to use getifaddrs/freeifaddrs.") + endif() + endif() + set(HAVE_DECL_GETIFADDRS TRUE PARENT_SCOPE) + set(HAVE_DECL_FREEIFADDRS TRUE PARENT_SCOPE) +endfunction() + +# Clang, when building for 32-bit, +# and linking against libstdc++, requires linking with +# -latomic if using the C++ atomic library. +# Can be tested with: clang++ -std=c++20 test.cpp -m32 +# +# Sourced from http://bugs.debian.org/797228 +function(test_append_atomic_library target) + if (NOT TARGET ${target}) + message(FATAL_ERROR "${CMAKE_CURRENT_FUNCTION}() called with non-existent target \"${target}\".") + endif() + + set(check_atomic_source " + #include + #include + #include + + using namespace std::chrono_literals; + + int main() { + std::atomic lock{true}; + lock.exchange(false); + + std::atomic t{0s}; + t.store(2s); + auto t1 = t.load(); + t.compare_exchange_strong(t1, 3s); + + std::atomic d{}; + d.store(3.14); + auto d1 = d.load(); + + std::atomic a{}; + int64_t v = 5; + int64_t r = a.fetch_add(v); + return static_cast(r); + } + ") + + include(CheckSourceCompilesAndLinks) + check_cxx_source_links("${check_atomic_source}" STD_ATOMIC_LINKS_WITHOUT_LIBATOMIC) + if(STD_ATOMIC_LINKS_WITHOUT_LIBATOMIC) + return() + endif() + + check_cxx_source_links_with_libs(atomic "${check_atomic_source}" STD_ATOMIC_NEEDS_LINK_TO_LIBATOMIC) + if(STD_ATOMIC_NEEDS_LINK_TO_LIBATOMIC) + target_link_libraries(${target} INTERFACE atomic) + else() + message(FATAL_ERROR "Cannot figure out how to use std::atomic.") + endif() +endfunction() + +include(CheckSymbolExists) +include(CheckFunctionExists) +include(CheckIncludeFile) +macro(check_function_exists_and_define FUNC_NAME HEADER_NAME MACRO_NAME) + check_cxx_symbol_exists(${FUNC_NAME} ${HEADER_NAME} ${MACRO_NAME}) + if(${MACRO_NAME}) + message(STATUS "Defined ${MACRO_NAME} = 1") + add_compile_definitions(${MACRO_NAME}=1) + else() + message(STATUS "Defined ${MACRO_NAME} = 0") + add_compile_definitions(${MACRO_NAME}=0) + endif() +endmacro() \ No newline at end of file diff --git a/cmake/module/TryAppendCXXFlags.cmake b/cmake/module/TryAppendCXXFlags.cmake new file mode 100644 index 0000000000..c07455e89e --- /dev/null +++ b/cmake/module/TryAppendCXXFlags.cmake @@ -0,0 +1,125 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include_guard(GLOBAL) +include(CheckCXXSourceCompiles) + +#[=[ +Add language-wide flags, which will be passed to all invocations of the compiler. +This includes invocations that drive compiling and those that drive linking. + +Usage examples: + + try_append_cxx_flags("-Wformat -Wformat-security" VAR warn_cxx_flags) + + + try_append_cxx_flags("-Wsuggest-override" VAR warn_cxx_flags + SOURCE "struct A { virtual void f(); }; struct B : A { void f() final; };" + ) + + + try_append_cxx_flags("-fsanitize=${SANITIZERS}" TARGET core_interface + RESULT_VAR cxx_supports_sanitizers + ) + if(NOT cxx_supports_sanitizers) + message(FATAL_ERROR "Compiler did not accept requested flags.") + endif() + + + try_append_cxx_flags("-Wunused-parameter" TARGET core_interface + IF_CHECK_PASSED "-Wno-unused-parameter" + ) + + +In configuration output, this function prints a string by the following pattern: + + -- Performing Test CXX_SUPPORTS_[flags] + -- Performing Test CXX_SUPPORTS_[flags] - Success + +]=] +function(try_append_cxx_flags flags) + cmake_parse_arguments(PARSE_ARGV 1 + TACXXF # prefix + "SKIP_LINK" # options + "TARGET;VAR;SOURCE;RESULT_VAR" # one_value_keywords + "IF_CHECK_PASSED" # multi_value_keywords + ) + + set(flags_as_string "${flags}") + separate_arguments(flags) + + string(MAKE_C_IDENTIFIER "${flags_as_string}" id_string) + string(TOUPPER "${id_string}" id_string) + + set(source "int main() { return 0; }") + if(DEFINED TACXXF_SOURCE AND NOT TACXXF_SOURCE STREQUAL source) + set(source "${TACXXF_SOURCE}") + string(SHA256 source_hash "${source}") + string(SUBSTRING ${source_hash} 0 4 source_hash_head) + string(APPEND id_string _${source_hash_head}) + endif() + + # This avoids running a linker. + set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) + set(CMAKE_REQUIRED_FLAGS "${flags_as_string} ${working_compiler_werror_flag}") + set(compiler_result CXX_SUPPORTS_${id_string}) + check_cxx_source_compiles("${source}" ${compiler_result}) + + if(${compiler_result}) + if(DEFINED TACXXF_IF_CHECK_PASSED) + if(DEFINED TACXXF_TARGET) + target_compile_options(${TACXXF_TARGET} INTERFACE ${TACXXF_IF_CHECK_PASSED}) + endif() + if(DEFINED TACXXF_VAR) + string(STRIP "${${TACXXF_VAR}} ${TACXXF_IF_CHECK_PASSED}" ${TACXXF_VAR}) + endif() + else() + if(DEFINED TACXXF_TARGET) + target_compile_options(${TACXXF_TARGET} INTERFACE ${flags}) + endif() + if(DEFINED TACXXF_VAR) + string(STRIP "${${TACXXF_VAR}} ${flags_as_string}" ${TACXXF_VAR}) + endif() + endif() + endif() + + if(DEFINED TACXXF_VAR) + set(${TACXXF_VAR} "${${TACXXF_VAR}}" PARENT_SCOPE) + endif() + + if(DEFINED TACXXF_RESULT_VAR) + set(${TACXXF_RESULT_VAR} "${${compiler_result}}" PARENT_SCOPE) + endif() + + if(NOT ${compiler_result} OR TACXXF_SKIP_LINK) + return() + endif() + + # This forces running a linker. + set(CMAKE_TRY_COMPILE_TARGET_TYPE EXECUTABLE) + set(CMAKE_REQUIRED_FLAGS "${flags_as_string}") + set(CMAKE_REQUIRED_LINK_OPTIONS ${working_linker_werror_flag}) + set(linker_result LINKER_SUPPORTS_${id_string}) + check_cxx_source_compiles("${source}" ${linker_result}) + + if(${linker_result}) + if(DEFINED TACXXF_IF_CHECK_PASSED) + if(DEFINED TACXXF_TARGET) + target_link_options(${TACXXF_TARGET} INTERFACE ${TACXXF_IF_CHECK_PASSED}) + endif() + else() + if(DEFINED TACXXF_TARGET) + target_link_options(${TACXXF_TARGET} INTERFACE ${flags}) + endif() + endif() + else() + message(WARNING "'${flags_as_string}' fail(s) to link.") + endif() +endfunction() + +if(MSVC) + try_append_cxx_flags("/WX /options:strict" VAR working_compiler_werror_flag SKIP_LINK) +else() + try_append_cxx_flags("-Werror" VAR working_compiler_werror_flag SKIP_LINK) +endif() diff --git a/cmake/module/TryAppendLinkerFlag.cmake b/cmake/module/TryAppendLinkerFlag.cmake new file mode 100644 index 0000000000..8cbd83678d --- /dev/null +++ b/cmake/module/TryAppendLinkerFlag.cmake @@ -0,0 +1,78 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include_guard(GLOBAL) +include(CheckCXXSourceCompiles) + +#[=[ +Usage example: + + try_append_linker_flag("-Wl,--major-subsystem-version,6" TARGET core_interface) + + +In configuration output, this function prints a string by the following pattern: + + -- Performing Test LINKER_SUPPORTS_[flag] + -- Performing Test LINKER_SUPPORTS_[flag] - Success + +]=] +function(try_append_linker_flag flag) + cmake_parse_arguments(PARSE_ARGV 1 + TALF # prefix + "" # options + "TARGET;VAR;SOURCE;RESULT_VAR" # one_value_keywords + "IF_CHECK_PASSED" # multi_value_keywords + ) + + string(MAKE_C_IDENTIFIER "${flag}" result) + string(TOUPPER "${result}" result) + string(PREPEND result LINKER_SUPPORTS_) + + set(source "int main() { return 0; }") + if(DEFINED TALF_SOURCE AND NOT TALF_SOURCE STREQUAL source) + set(source "${TALF_SOURCE}") + string(SHA256 source_hash "${source}") + string(SUBSTRING ${source_hash} 0 4 source_hash_head) + string(APPEND result _${source_hash_head}) + endif() + + # This forces running a linker. + set(CMAKE_TRY_COMPILE_TARGET_TYPE EXECUTABLE) + set(CMAKE_REQUIRED_LINK_OPTIONS ${flag} ${working_linker_werror_flag}) + check_cxx_source_compiles("${source}" ${result}) + + if(${result}) + if(DEFINED TALF_IF_CHECK_PASSED) + if(DEFINED TALF_TARGET) + target_link_options(${TALF_TARGET} INTERFACE ${TALF_IF_CHECK_PASSED}) + endif() + if(DEFINED TALF_VAR) + string(STRIP "${${TALF_VAR}} ${TALF_IF_CHECK_PASSED}" ${TALF_VAR}) + endif() + else() + if(DEFINED TALF_TARGET) + target_link_options(${TALF_TARGET} INTERFACE ${flag}) + endif() + if(DEFINED TALF_VAR) + string(STRIP "${${TALF_VAR}} ${flag}" ${TALF_VAR}) + endif() + endif() + endif() + + if(DEFINED TALF_VAR) + set(${TALF_VAR} "${${TALF_VAR}}" PARENT_SCOPE) + endif() + + if(DEFINED TALF_RESULT_VAR) + set(${TALF_RESULT_VAR} "${${result}}" PARENT_SCOPE) + endif() +endfunction() + +if(MSVC) + try_append_linker_flag("/WX" VAR working_linker_werror_flag) +elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + try_append_linker_flag("-Wl,-fatal_warnings" VAR working_linker_werror_flag) +else() + try_append_linker_flag("-Wl,--fatal-warnings" VAR working_linker_werror_flag) +endif() diff --git a/cmake/module/WarnAboutGlobalProperties.cmake b/cmake/module/WarnAboutGlobalProperties.cmake new file mode 100644 index 0000000000..faa56a2a7f --- /dev/null +++ b/cmake/module/WarnAboutGlobalProperties.cmake @@ -0,0 +1,36 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include_guard(GLOBAL) + +# Avoid the directory-wide add_definitions() and add_compile_definitions() commands. +# Instead, prefer the target-specific target_compile_definitions() one. +get_directory_property(global_compile_definitions COMPILE_DEFINITIONS) +if(global_compile_definitions) + message(AUTHOR_WARNING "The directory's COMPILE_DEFINITIONS property is not empty: ${global_compile_definitions}") +endif() + +# Avoid the directory-wide add_compile_options() command. +# Instead, prefer the target-specific target_compile_options() one. +get_directory_property(global_compile_options COMPILE_OPTIONS) +if(global_compile_options) + message(AUTHOR_WARNING "The directory's COMPILE_OPTIONS property is not empty: ${global_compile_options}") +endif() + +# Avoid the directory-wide add_link_options() command. +# Instead, prefer the target-specific target_link_options() one. +get_directory_property(global_link_options LINK_OPTIONS) +if(global_link_options) + message(AUTHOR_WARNING "The directory's LINK_OPTIONS property is not empty: ${global_link_options}") +endif() + +# Avoid the directory-wide link_libraries() command. +# Instead, prefer the target-specific target_link_libraries() one. +file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/dummy_cxx_source.cpp "#error") +add_library(check_loose_linked_libraries OBJECT EXCLUDE_FROM_ALL ${CMAKE_CURRENT_BINARY_DIR}/dummy_cxx_source.cpp) +set_target_properties(check_loose_linked_libraries PROPERTIES EXPORT_COMPILE_COMMANDS OFF) +get_target_property(global_linked_libraries check_loose_linked_libraries LINK_LIBRARIES) +if(global_linked_libraries) + message(AUTHOR_WARNING "There are libraries linked with `link_libraries` commands: ${global_linked_libraries}") +endif() diff --git a/cmake/module/WindowsSystemConfiguration.cmake b/cmake/module/WindowsSystemConfiguration.cmake new file mode 100644 index 0000000000..d4c95b950e --- /dev/null +++ b/cmake/module/WindowsSystemConfiguration.cmake @@ -0,0 +1,78 @@ +# WindowsSystemConfiguration.cmake + +if(WIN32) + + add_library(windows_system INTERFACE) + target_link_libraries(windows_system INTERFACE + ws2_32 iphlpapi userenv + dwmapi uxtheme shlwapi + wtsapi32 imm32 netapi32 + $<$:dbghelp> + version winmm crypt32 bcrypt + ole32 oleaut32 uuid + comdlg32 advapi32 + shell32 gdi32 user32 + kernel32 winspool + ) + + find_library(LIBEVENT_EXTRA event_extra REQUIRED) + find_library(LIBEVENT_CORE event_core REQUIRED) + + if(MINGW) + message(STATUS "Configuring extra DLL copy steps for MinGW runtime dependencies (${MINGW_ARCH}-bit).") + + # Determine architecture-specific settings + if(MINGW_ARCH STREQUAL "64") + set(MINGW_TRIPLET "x86_64-w64-mingw32") + set(LIBGCC_DLL "libgcc_s_seh-1.dll") + elseif(MINGW_ARCH STREQUAL "32") + set(MINGW_TRIPLET "i686-w64-mingw32") + set(LIBGCC_DLL "libgcc_s_dw2-1.dll") + else() + message(FATAL_ERROR "Unsupported MINGW_ARCH: ${MINGW_ARCH}. Must be 32 or 64.") + endif() + + # List the DLL names you require with architecture-specific libgcc + set(NEEDED_DLLS + "${LIBGCC_DLL}" + "libssp-0.dll" + "libstdc++-6.dll" + "libwinpthread-1.dll" + ) + + # Use the compiler's -print-file-name option to determine the correct path for each DLL. + # We use CMAKE_C_COMPILER as it should be set to the appropriate MinGW gcc. + set(FOUND_DLLS "") + foreach(dll ${NEEDED_DLLS}) + execute_process( + COMMAND ${CMAKE_C_COMPILER} -print-file-name=${dll} + OUTPUT_VARIABLE DLL_PATH + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + if(NOT DLL_PATH OR DLL_PATH STREQUAL "${dll}") + message(FATAL_ERROR "Could not determine path for DLL: ${dll} using ${CMAKE_C_COMPILER}") + else() + message(STATUS "Found ${dll} at ${DLL_PATH}") + list(APPEND FOUND_DLLS ${DLL_PATH}) + endif() + endforeach() + + # Set the output binary directory (adjust if needed) + set(PROJECT_BIN_DIR "${CMAKE_BINARY_DIR}/bin") + + # Create a custom target to copy the DLLs to the bin folder. + add_custom_target(copy_mingw_dlls ALL + COMMAND ${CMAKE_COMMAND} -E make_directory "${PROJECT_BIN_DIR}" + COMMAND ${CMAKE_COMMAND} -E echo "Copying MinGW ${MINGW_ARCH}-bit runtime DLLs to ${PROJECT_BIN_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different ${FOUND_DLLS} "${PROJECT_BIN_DIR}" + COMMENT "Copying required MinGW ${MINGW_ARCH}-bit DLLs to binary folder." + ) + + # Optionally, make your executables depend on the copy target + # add_dependencies(firo-cli copy_mingw_dlls) + + # Install the DLLs to the install package bin folder + install(FILES ${FOUND_DLLS} DESTINATION bin) + endif() + +endif() \ No newline at end of file diff --git a/cmake/script/Coverage.cmake b/cmake/script/Coverage.cmake new file mode 100644 index 0000000000..72587a5eb6 --- /dev/null +++ b/cmake/script/Coverage.cmake @@ -0,0 +1,89 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include(${CMAKE_CURRENT_LIST_DIR}/CoverageInclude.cmake) + +set(functional_test_runner test/functional/test_runner.py) +if(EXTENDED_FUNCTIONAL_TESTS) + list(APPEND functional_test_runner --extended) +endif() +if(DEFINED JOBS) + list(APPEND CMAKE_CTEST_COMMAND -j ${JOBS}) + list(APPEND functional_test_runner -j ${JOBS}) +endif() + +execute_process( + COMMAND ${CMAKE_CTEST_COMMAND} --build-config Coverage + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --capture --directory src --test-name test_bitcoin --output-file test_bitcoin.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --zerocounters --directory src + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_FILTER_COMMAND} test_bitcoin.info test_bitcoin_filtered.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --add-tracefile test_bitcoin_filtered.info --output-file test_bitcoin_filtered.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --add-tracefile baseline_filtered.info --add-tracefile test_bitcoin_filtered.info --output-file test_bitcoin_coverage.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${GENHTML_COMMAND} test_bitcoin_coverage.info --output-directory test_bitcoin.coverage + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) + +execute_process( + COMMAND ${functional_test_runner} + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --capture --directory src --test-name functional-tests --output-file functional_test.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --zerocounters --directory src + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_FILTER_COMMAND} functional_test.info functional_test_filtered.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --add-tracefile functional_test_filtered.info --output-file functional_test_filtered.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --add-tracefile baseline_filtered.info --add-tracefile test_bitcoin_filtered.info --add-tracefile functional_test_filtered.info --output-file total_coverage.info + COMMAND ${GREP_EXECUTABLE} "%" + COMMAND ${AWK_EXECUTABLE} "{ print substr($3,2,50) \"/\" $5 }" + OUTPUT_FILE coverage_percent.txt + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${GENHTML_COMMAND} total_coverage.info --output-directory total.coverage + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) diff --git a/cmake/script/CoverageFuzz.cmake b/cmake/script/CoverageFuzz.cmake new file mode 100644 index 0000000000..0558805394 --- /dev/null +++ b/cmake/script/CoverageFuzz.cmake @@ -0,0 +1,53 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include(${CMAKE_CURRENT_LIST_DIR}/CoverageInclude.cmake) + +if(NOT DEFINED FUZZ_CORPORA_DIR) + set(FUZZ_CORPORA_DIR ${CMAKE_CURRENT_SOURCE_DIR}/qa-assets/fuzz_corpora) +endif() + +set(fuzz_test_runner test/fuzz/test_runner.py ${FUZZ_CORPORA_DIR}) +if(DEFINED JOBS) + list(APPEND fuzz_test_runner -j ${JOBS}) +endif() + +execute_process( + COMMAND ${fuzz_test_runner} --loglevel DEBUG + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --capture --directory src --test-name fuzz-tests --output-file fuzz.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --zerocounters --directory src + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_FILTER_COMMAND} fuzz.info fuzz_filtered.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --add-tracefile fuzz_filtered.info --output-file fuzz_filtered.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --add-tracefile baseline_filtered.info --add-tracefile fuzz_filtered.info --output-file fuzz_coverage.info + COMMAND ${GREP_EXECUTABLE} "%" + COMMAND ${AWK_EXECUTABLE} "{ print substr($3,2,50) \"/\" $5 }" + OUTPUT_FILE coverage_percent.txt + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${GENHTML_COMMAND} fuzz_coverage.info --output-directory fuzz.coverage + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) diff --git a/cmake/script/CoverageInclude.cmake.in b/cmake/script/CoverageInclude.cmake.in new file mode 100644 index 0000000000..928c19953d --- /dev/null +++ b/cmake/script/CoverageInclude.cmake.in @@ -0,0 +1,58 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +if("@CMAKE_CXX_COMPILER_ID@" STREQUAL "Clang") + find_program(LLVM_COV_EXECUTABLE llvm-cov REQUIRED) + set(COV_TOOL "${LLVM_COV_EXECUTABLE} gcov") +else() + find_program(GCOV_EXECUTABLE gcov REQUIRED) + set(COV_TOOL "${GCOV_EXECUTABLE}") +endif() + +# COV_TOOL is used to replace a placeholder. +configure_file( + cmake/cov_tool_wrapper.sh.in ${CMAKE_CURRENT_LIST_DIR}/cov_tool_wrapper.sh + FILE_PERMISSIONS OWNER_READ OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE + WORLD_READ + @ONLY +) + +find_program(LCOV_EXECUTABLE lcov REQUIRED) +separate_arguments(LCOV_OPTS) +set(LCOV_COMMAND ${LCOV_EXECUTABLE} --gcov-tool ${CMAKE_CURRENT_LIST_DIR}/cov_tool_wrapper.sh ${LCOV_OPTS}) + +find_program(GENHTML_EXECUTABLE genhtml REQUIRED) +set(GENHTML_COMMAND ${GENHTML_EXECUTABLE} --show-details ${LCOV_OPTS}) + +find_program(GREP_EXECUTABLE grep REQUIRED) +find_program(AWK_EXECUTABLE awk REQUIRED) + +set(LCOV_FILTER_COMMAND ./filter-lcov.py) +list(APPEND LCOV_FILTER_COMMAND -p "/usr/local/") +list(APPEND LCOV_FILTER_COMMAND -p "/usr/include/") +list(APPEND LCOV_FILTER_COMMAND -p "/usr/lib/") +list(APPEND LCOV_FILTER_COMMAND -p "/usr/lib64/") +list(APPEND LCOV_FILTER_COMMAND -p "src/leveldb/") +list(APPEND LCOV_FILTER_COMMAND -p "src/crc32c/") +list(APPEND LCOV_FILTER_COMMAND -p "src/bench/") +list(APPEND LCOV_FILTER_COMMAND -p "src/crypto/ctaes") +list(APPEND LCOV_FILTER_COMMAND -p "src/secp256k1") +list(APPEND LCOV_FILTER_COMMAND -p "depends") + +execute_process( + COMMAND ${LCOV_COMMAND} --capture --initial --directory src --output-file baseline.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_FILTER_COMMAND} baseline.info baseline_filtered.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) +execute_process( + COMMAND ${LCOV_COMMAND} --add-tracefile baseline_filtered.info --output-file baseline_filtered.info + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMAND_ERROR_IS_FATAL ANY +) diff --git a/cmake/script/GenerateBuildInfo.cmake b/cmake/script/GenerateBuildInfo.cmake new file mode 100644 index 0000000000..d3ee2eb062 --- /dev/null +++ b/cmake/script/GenerateBuildInfo.cmake @@ -0,0 +1,113 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +macro(fatal_error) + message(FATAL_ERROR "\n" + "Usage:\n" + " cmake -D BUILD_INFO_HEADER_PATH= [-D SOURCE_DIR=] -P ${CMAKE_CURRENT_LIST_FILE}\n" + "All specified paths must be absolute ones.\n" + ) +endmacro() + +if(DEFINED BUILD_INFO_HEADER_PATH AND IS_ABSOLUTE "${BUILD_INFO_HEADER_PATH}") + if(EXISTS "${BUILD_INFO_HEADER_PATH}") + file(STRINGS ${BUILD_INFO_HEADER_PATH} INFO LIMIT_COUNT 1) + endif() +else() + fatal_error() +endif() + +if(DEFINED SOURCE_DIR) + if(IS_ABSOLUTE "${SOURCE_DIR}" AND IS_DIRECTORY "${SOURCE_DIR}") + set(WORKING_DIR ${SOURCE_DIR}) + else() + fatal_error() + endif() +else() + set(WORKING_DIR ${CMAKE_CURRENT_SOURCE_DIR}) +endif() + +set(GIT_TAG) +set(GIT_COMMIT) +if(NOT "$ENV{BITCOIN_GENBUILD_NO_GIT}" STREQUAL "1") + find_package(Git QUIET) + if(Git_FOUND) + execute_process( + COMMAND ${GIT_EXECUTABLE} rev-parse --is-inside-work-tree + WORKING_DIRECTORY ${WORKING_DIR} + OUTPUT_VARIABLE IS_INSIDE_WORK_TREE + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + if(IS_INSIDE_WORK_TREE) + # Clean 'dirty' status of touched files that haven't been modified. + execute_process( + COMMAND ${GIT_EXECUTABLE} diff + WORKING_DIRECTORY ${WORKING_DIR} + OUTPUT_QUIET + ERROR_QUIET + ) + + execute_process( + COMMAND ${GIT_EXECUTABLE} describe --abbrev=0 + WORKING_DIRECTORY ${WORKING_DIR} + OUTPUT_VARIABLE MOST_RECENT_TAG + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + + execute_process( + COMMAND ${GIT_EXECUTABLE} rev-list -1 ${MOST_RECENT_TAG} + WORKING_DIRECTORY ${WORKING_DIR} + OUTPUT_VARIABLE MOST_RECENT_TAG_COMMIT + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + + execute_process( + COMMAND ${GIT_EXECUTABLE} rev-parse HEAD + WORKING_DIRECTORY ${WORKING_DIR} + OUTPUT_VARIABLE HEAD_COMMIT + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + + execute_process( + COMMAND ${GIT_EXECUTABLE} diff-index --quiet HEAD -- + WORKING_DIRECTORY ${WORKING_DIR} + RESULT_VARIABLE IS_DIRTY + ) + + if(HEAD_COMMIT STREQUAL MOST_RECENT_TAG_COMMIT AND NOT IS_DIRTY) + # If latest commit is tagged and not dirty, then use the tag name. + set(GIT_TAG ${MOST_RECENT_TAG}) + else() + # Otherwise, generate suffix from git, i.e. string like "0e0a5173fae3-dirty". + execute_process( + COMMAND ${GIT_EXECUTABLE} rev-parse --short=12 HEAD + WORKING_DIRECTORY ${WORKING_DIR} + OUTPUT_VARIABLE GIT_COMMIT + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + if(IS_DIRTY) + string(APPEND GIT_COMMIT "-dirty") + endif() + endif() + endif() + endif() +endif() + +if(GIT_TAG) + set(NEWINFO "#define BUILD_GIT_TAG \"${GIT_TAG}\"") +elseif(GIT_COMMIT) + set(NEWINFO "#define BUILD_GIT_COMMIT \"${GIT_COMMIT}\"") +else() + set(NEWINFO "// No build information available") +endif() + +# Only update the header if necessary. +if(NOT "${INFO}" STREQUAL "${NEWINFO}") + file(WRITE ${BUILD_INFO_HEADER_PATH} "${NEWINFO}\n") +endif() diff --git a/cmake/script/GenerateHeaderFromJson.cmake b/cmake/script/GenerateHeaderFromJson.cmake new file mode 100644 index 0000000000..5d3482f5f1 --- /dev/null +++ b/cmake/script/GenerateHeaderFromJson.cmake @@ -0,0 +1,34 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +message(STATUS "Generating header ${HEADER_PATH} from ${JSON_SOURCE_PATH}") + +# Generate a header file from a JSON file containing a hex dump +function(generate_json_header JSON_SOURCE_PATH HEADER_PATH) + # Use get_filename_component instead of cmake_path + get_filename_component(json_source_basename "${JSON_SOURCE_PATH}" NAME_WE) + + # Create directory + get_filename_component(header_dir "${HEADER_PATH}" DIRECTORY) + file(MAKE_DIRECTORY "${header_dir}") + + # Read and convert to hex + file(READ ${JSON_SOURCE_PATH} hex_content HEX) + string(REGEX REPLACE ".." "0x\\0, " formatted_bytes "${hex_content}") + + # Generate content + set(header_content + "namespace json_tests{ + static unsigned const char ${json_source_basename}[] = { + ${formatted_bytes} + }; + };" + ) + + # Atomic write using temporary file + file(WRITE "${HEADER_PATH}.new" "${header_content}") + file(RENAME "${HEADER_PATH}.new" "${HEADER_PATH}") +endfunction() + +generate_json_header(${JSON_SOURCE_PATH} ${HEADER_PATH}) diff --git a/cmake/script/GenerateHeaderFromRaw.cmake b/cmake/script/GenerateHeaderFromRaw.cmake new file mode 100644 index 0000000000..638876ecea --- /dev/null +++ b/cmake/script/GenerateHeaderFromRaw.cmake @@ -0,0 +1,23 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +cmake_path(GET RAW_SOURCE_PATH STEM raw_source_basename) + +file(READ ${RAW_SOURCE_PATH} hex_content HEX) +string(REGEX REPLACE "................" "\\0\n" formatted_bytes "${hex_content}") +string(REGEX REPLACE "[^\n][^\n]" "std::byte{0x\\0}, " formatted_bytes "${formatted_bytes}") + +set(header_content +"#include +#include + +namespace ${RAW_NAMESPACE} { +inline constexpr std::byte detail_${raw_source_basename}_raw[] { +${formatted_bytes} +}; + +inline constexpr std::span ${raw_source_basename}{detail_${raw_source_basename}_raw}; +} +") +file(WRITE ${HEADER_PATH} "${header_content}") diff --git a/cmake/script/macos_zip.sh b/cmake/script/macos_zip.sh new file mode 100755 index 0000000000..cc51699dc9 --- /dev/null +++ b/cmake/script/macos_zip.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +export LC_ALL=C + +if [ -n "$SOURCE_DATE_EPOCH" ]; then + find . -exec touch -d "@$SOURCE_DATE_EPOCH" {} + +fi + +find . | sort | "$1" -X@ "$2" diff --git a/cmake/tests.cmake b/cmake/tests.cmake new file mode 100644 index 0000000000..6bb5bf2544 --- /dev/null +++ b/cmake/tests.cmake @@ -0,0 +1,9 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +if(TARGET bitcoin-util AND TARGET bitcoin-tx AND PYTHON_COMMAND) + add_test(NAME util_test_runner + COMMAND ${CMAKE_COMMAND} -E env BITCOINUTIL=$ BITCOINTX=$ ${PYTHON_COMMAND} ${PROJECT_BINARY_DIR}/test/util/test_runner.py + ) +endif() \ No newline at end of file diff --git a/cmake/utilities.cmake b/cmake/utilities.cmake new file mode 100644 index 0000000000..2255c13d88 --- /dev/null +++ b/cmake/utilities.cmake @@ -0,0 +1,25 @@ +# Copyright (c) 2025-present The Firo Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +function(apply_wrapped_exception_flags target_name) + if(ENABLE_CRASH_HOOKS AND CRASH_HOOKS_WRAPPED_CXX_ABI) + # We need to wrap exceptions to catch them in the crash handler + # We need to pass both compile flags and link flags to ensure that the wrapped exceptions are used in all cases + target_compile_options(${target_name} PRIVATE ${LDFLAGS_WRAP_EXCEPTIONS}) + # Apple linker does not support -Wl,--wrap= + if(NOT APPLE) + target_link_options(${target_name} PRIVATE ${LDFLAGS_WRAP_EXCEPTIONS}) + endif() + endif() +endfunction() + +# Set platform-specific output name for an executable target +# Usage: set_platform_output_name(target_name base_name_variable) +function(set_platform_output_name target_name base_name_variable) + if(WIN32) + set_target_properties(${target_name} PROPERTIES OUTPUT_NAME "${${base_name_variable}}.exe") + else() + set_target_properties(${target_name} PROPERTIES OUTPUT_NAME "${${base_name_variable}}") + endif() +endfunction() \ No newline at end of file diff --git a/depends/Makefile b/depends/Makefile index c892ee25ac..74ffec8121 100644 --- a/depends/Makefile +++ b/depends/Makefile @@ -180,7 +180,7 @@ $(host_arch)_$(host_os)_native_toolchain?=$($(host_os)_native_toolchain) include funcs.mk -final_build_id_long+=$(shell $(build_SHA256SUM) config.site.in) +final_build_id_long+=$(shell $(build_SHA256SUM) config.site.in toolchain.cmake.in) final_build_id+=$(shell echo -n "$(final_build_id_long)" | $(build_SHA256SUM) | cut -c-$(HASH_LENGTH)) $(host_prefix)/.stamp_$(final_build_id): $(native_packages) $(packages) $(AT)rm -rf $(@D) @@ -188,6 +188,7 @@ $(host_prefix)/.stamp_$(final_build_id): $(native_packages) $(packages) $(AT)echo copying packages: $^ $(AT)echo to: $(@D) $(AT)cd $(@D); $(foreach package,$^, tar xf $($(package)_cached); ) + $(AT)echo To build Firo with these packages, pass \'--toolchain $(@D)/toolchain.cmake\' to the first CMake invocation. $(AT)touch $@ # $PATH is not preserved between ./configure and make by convention. Its @@ -243,6 +244,50 @@ $(host_prefix)/share/config.site : config.site.in $(host_prefix)/.stamp_$(final_ $< > $@ $(AT)touch $@ +ifeq ($(host),$(build)) + crosscompiling=FALSE +else + crosscompiling=TRUE +endif + +$(host_prefix)/toolchain.cmake : toolchain.cmake.in $(host_prefix)/.stamp_$(final_build_id) + @mkdir -p $(@D) + sed -e 's|@depends_crosscompiling@|$(crosscompiling)|' \ + -e 's|@host_system_name@|$($(host_os)_cmake_system_name)|' \ + -e 's|@host_system_version@|$($(host_os)_cmake_system_version)|' \ + -e 's|@host_arch@|$(host_arch)|' \ + -e 's|@CC@|$(host_CC)|' \ + -e 's|@CXX@|$(host_CXX)|' \ + -e 's|@OSX_SDK@|$(OSX_SDK)|' \ + -e 's|@AR@|$(host_AR)|' \ + -e 's|@RANLIB@|$(host_RANLIB)|' \ + -e 's|@STRIP@|$(host_STRIP)|' \ + -e 's|@OBJCOPY@|$(host_OBJCOPY)|' \ + -e 's|@OBJDUMP@|$(host_OBJDUMP)|' \ + -e 's|@depends_prefix@|$(host_prefix)|' \ + -e 's|@CFLAGS@|$(strip $(host_CFLAGS))|' \ + -e 's|@CFLAGS_RELEASE@|$(strip $(host_release_CFLAGS))|' \ + -e 's|@CFLAGS_DEBUG@|$(strip $(host_debug_CFLAGS))|' \ + -e 's|@CXXFLAGS@|$(strip $(host_CXXFLAGS))|' \ + -e 's|@CXXFLAGS_RELEASE@|$(strip $(host_release_CXXFLAGS))|' \ + -e 's|@CXXFLAGS_DEBUG@|$(strip $(host_debug_CXXFLAGS))|' \ + -e 's|@CPPFLAGS@|$(strip $(host_CPPFLAGS))|' \ + -e 's|@CPPFLAGS_RELEASE@|$(strip $(host_release_CPPFLAGS))|' \ + -e 's|@CPPFLAGS_DEBUG@|$(strip $(host_debug_CPPFLAGS))|' \ + -e 's|@LDFLAGS@|$(strip $(host_LDFLAGS))|' \ + -e 's|@LDFLAGS_RELEASE@|$(strip $(host_release_LDFLAGS))|' \ + -e 's|@LDFLAGS_DEBUG@|$(strip $(host_debug_LDFLAGS))|' \ + -e 's|@qt_packages@|$(qt_packages_)|' \ + -e 's|@qrencode_packages@|$(qrencode_packages_)|' \ + -e 's|@zmq_packages@|$(zmq_packages_)|' \ + -e 's|@wallet_packages@|$(wallet_packages_)|' \ + -e 's|@bdb_packages@|$(bdb_packages_)|' \ + -e 's|@sqlite_packages@|$(sqlite_packages_)|' \ + -e 's|@usdt_packages@|$(usdt_packages_)|' \ + -e 's|@no_harden@|$(NO_HARDEN)|' \ + -e 's|@multiprocess@|$(MULTIPROCESS)|' \ + $< > $@ + touch $@ define check_or_remove_cached mkdir -p $(BASE_CACHE)/$(host)/$(package) && cd $(BASE_CACHE)/$(host)/$(package); \ @@ -266,6 +311,7 @@ check-sources: $(host_prefix)/share/config.site: check-packages check-packages: check-sources +$(host_prefix)/toolchain.cmake: check-packages clean-all: clean @rm -rf $(SOURCES_PATH) x86_64* i686* mips* arm* aarch64* powerpc* riscv32* riscv64* s390x* @@ -273,7 +319,7 @@ clean-all: clean clean: @rm -rf $(WORK_PATH) $(BASE_CACHE) $(BUILD) -install: check-packages $(host_prefix)/share/config.site +install: check-packages $(host_prefix)/share/config.site $(host_prefix)/toolchain.cmake download-one: check-sources $(all_sources) diff --git a/depends/config.guess b/depends/config.guess index dc0a6b2997..48a684601b 100755 --- a/depends/config.guess +++ b/depends/config.guess @@ -1,12 +1,14 @@ #! /bin/sh # Attempt to guess a canonical system name. -# Copyright 1992-2021 Free Software Foundation, Inc. +# Copyright 1992-2024 Free Software Foundation, Inc. -timestamp='2021-05-24' +# shellcheck disable=SC2006,SC2268 # see below for rationale + +timestamp='2024-07-27' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 3 of the License, or +# the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but @@ -32,12 +34,20 @@ timestamp='2021-05-24' # Please send patches to . -me=$(echo "$0" | sed -e 's,.*/,,') +# The "shellcheck disable" line above the timestamp inhibits complaints +# about features and limitations of the classic Bourne shell that were +# superseded or lifted in POSIX. However, this script identifies a wide +# variety of pre-POSIX systems that do not have POSIX shells at all, and +# even some reasonably current systems (Solaris 10 as case-in-point) still +# have a pre-POSIX /bin/sh. + + +me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] -Output the configuration name of the system \`$me' is run on. +Output the configuration name of the system '$me' is run on. Options: -h, --help print this help, then exit @@ -50,13 +60,13 @@ version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. -Copyright 1992-2021 Free Software Foundation, Inc. +Copyright 1992-2024 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" -Try \`$me --help' for more information." +Try '$me --help' for more information." # Parse command line while test $# -gt 0 ; do @@ -84,13 +94,16 @@ if test $# != 0; then exit 1 fi +# Just in case it came from the environment. +GUESS= + # CC_FOR_BUILD -- compiler used by this script. Note that the use of a # compiler to aid in system detection is discouraged as it requires # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. -# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still -# use `HOST_CC' if defined, but it is deprecated. +# Historically, 'CC_FOR_BUILD' used to be named 'HOST_CC'. We still +# use 'HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. @@ -102,17 +115,17 @@ set_cc_for_build() { # prevent multiple calls if $tmp is already set test "$tmp" && return 0 : "${TMPDIR=/tmp}" - # shellcheck disable=SC2039 - { tmp=$( (umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null) && test -n "$tmp" && test -d "$tmp" ; } || + # shellcheck disable=SC2039,SC3028 + { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir "$tmp" 2>/dev/null) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir "$tmp" 2>/dev/null) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } dummy=$tmp/dummy case ${CC_FOR_BUILD-},${HOST_CC-},${CC-} in ,,) echo "int x;" > "$dummy.c" - for driver in cc gcc c89 c99 ; do + for driver in cc gcc c17 c99 c89 ; do if ($driver -c -o "$dummy.o" "$dummy.c") >/dev/null 2>&1 ; then - CC_FOR_BUILD="$driver" + CC_FOR_BUILD=$driver break fi done @@ -131,10 +144,10 @@ if test -f /.attbin/uname ; then PATH=$PATH:/.attbin ; export PATH fi -UNAME_MACHINE=$( (uname -m) 2>/dev/null) || UNAME_MACHINE=unknown -UNAME_RELEASE=$( (uname -r) 2>/dev/null) || UNAME_RELEASE=unknown -UNAME_SYSTEM=$( (uname -s) 2>/dev/null) || UNAME_SYSTEM=unknown -UNAME_VERSION=$( (uname -v) 2>/dev/null) || UNAME_VERSION=unknown +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown case $UNAME_SYSTEM in Linux|GNU|GNU/*) @@ -142,6 +155,9 @@ Linux|GNU|GNU/*) set_cc_for_build cat <<-EOF > "$dummy.c" + #if defined(__ANDROID__) + LIBC=android + #else #include #if defined(__UCLIBC__) LIBC=uclibc @@ -149,6 +165,8 @@ Linux|GNU|GNU/*) LIBC=dietlibc #elif defined(__GLIBC__) LIBC=gnu + #elif defined(__LLVM_LIBC__) + LIBC=llvm #else #include /* First heuristic to detect musl libc. */ @@ -156,8 +174,10 @@ Linux|GNU|GNU/*) LIBC=musl #endif #endif + #endif EOF - eval "$($CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^LIBC' | sed 's, ,,g')" + cc_set_libc=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^LIBC' | sed 's, ,,g'` + eval "$cc_set_libc" # Second heuristic to detect musl libc. if [ "$LIBC" = unknown ] && @@ -188,10 +208,10 @@ case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in # # Note: NetBSD doesn't particularly care about the vendor # portion of the name. We always set it to "unknown". - UNAME_MACHINE_ARCH=$( (uname -p 2>/dev/null || \ + UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \ /sbin/sysctl -n hw.machine_arch 2>/dev/null || \ /usr/sbin/sysctl -n hw.machine_arch 2>/dev/null || \ - echo unknown)) + echo unknown)` case $UNAME_MACHINE_ARCH in aarch64eb) machine=aarch64_be-unknown ;; armeb) machine=armeb-unknown ;; @@ -200,11 +220,11 @@ case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in sh3eb) machine=sh-unknown ;; sh5el) machine=sh5le-unknown ;; earmv*) - arch=$(echo "$UNAME_MACHINE_ARCH" | sed -e 's,^e\(armv[0-9]\).*$,\1,') - endian=$(echo "$UNAME_MACHINE_ARCH" | sed -ne 's,^.*\(eb\)$,\1,p') - machine="${arch}${endian}"-unknown + arch=`echo "$UNAME_MACHINE_ARCH" | sed -e 's,^e\(armv[0-9]\).*$,\1,'` + endian=`echo "$UNAME_MACHINE_ARCH" | sed -ne 's,^.*\(eb\)$,\1,p'` + machine=${arch}${endian}-unknown ;; - *) machine="$UNAME_MACHINE_ARCH"-unknown ;; + *) machine=$UNAME_MACHINE_ARCH-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently (or will in the future) and ABI. @@ -232,7 +252,7 @@ case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in case $UNAME_MACHINE_ARCH in earm*) expr='s/^earmv[0-9]/-eabi/;s/eb$//' - abi=$(echo "$UNAME_MACHINE_ARCH" | sed -e "$expr") + abi=`echo "$UNAME_MACHINE_ARCH" | sed -e "$expr"` ;; esac # The OS release @@ -245,76 +265,76 @@ case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in release='-gnu' ;; *) - release=$(echo "$UNAME_RELEASE" | sed -e 's/[-_].*//' | cut -d. -f1,2) + release=`echo "$UNAME_RELEASE" | sed -e 's/[-_].*//' | cut -d. -f1,2` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. - echo "$machine-${os}${release}${abi-}" - exit ;; + GUESS=$machine-${os}${release}${abi-} + ;; *:Bitrig:*:*) - UNAME_MACHINE_ARCH=$(arch | sed 's/Bitrig.//') - echo "$UNAME_MACHINE_ARCH"-unknown-bitrig"$UNAME_RELEASE" - exit ;; + UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` + GUESS=$UNAME_MACHINE_ARCH-unknown-bitrig$UNAME_RELEASE + ;; *:OpenBSD:*:*) - UNAME_MACHINE_ARCH=$(arch | sed 's/OpenBSD.//') - echo "$UNAME_MACHINE_ARCH"-unknown-openbsd"$UNAME_RELEASE" - exit ;; + UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` + GUESS=$UNAME_MACHINE_ARCH-unknown-openbsd$UNAME_RELEASE + ;; *:SecBSD:*:*) - UNAME_MACHINE_ARCH=$(arch | sed 's/SecBSD.//') - echo "$UNAME_MACHINE_ARCH"-unknown-secbsd"$UNAME_RELEASE" - exit ;; + UNAME_MACHINE_ARCH=`arch | sed 's/SecBSD.//'` + GUESS=$UNAME_MACHINE_ARCH-unknown-secbsd$UNAME_RELEASE + ;; *:LibertyBSD:*:*) - UNAME_MACHINE_ARCH=$(arch | sed 's/^.*BSD\.//') - echo "$UNAME_MACHINE_ARCH"-unknown-libertybsd"$UNAME_RELEASE" - exit ;; + UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'` + GUESS=$UNAME_MACHINE_ARCH-unknown-libertybsd$UNAME_RELEASE + ;; *:MidnightBSD:*:*) - echo "$UNAME_MACHINE"-unknown-midnightbsd"$UNAME_RELEASE" - exit ;; + GUESS=$UNAME_MACHINE-unknown-midnightbsd$UNAME_RELEASE + ;; *:ekkoBSD:*:*) - echo "$UNAME_MACHINE"-unknown-ekkobsd"$UNAME_RELEASE" - exit ;; + GUESS=$UNAME_MACHINE-unknown-ekkobsd$UNAME_RELEASE + ;; *:SolidBSD:*:*) - echo "$UNAME_MACHINE"-unknown-solidbsd"$UNAME_RELEASE" - exit ;; + GUESS=$UNAME_MACHINE-unknown-solidbsd$UNAME_RELEASE + ;; *:OS108:*:*) - echo "$UNAME_MACHINE"-unknown-os108_"$UNAME_RELEASE" - exit ;; + GUESS=$UNAME_MACHINE-unknown-os108_$UNAME_RELEASE + ;; macppc:MirBSD:*:*) - echo powerpc-unknown-mirbsd"$UNAME_RELEASE" - exit ;; + GUESS=powerpc-unknown-mirbsd$UNAME_RELEASE + ;; *:MirBSD:*:*) - echo "$UNAME_MACHINE"-unknown-mirbsd"$UNAME_RELEASE" - exit ;; + GUESS=$UNAME_MACHINE-unknown-mirbsd$UNAME_RELEASE + ;; *:Sortix:*:*) - echo "$UNAME_MACHINE"-unknown-sortix - exit ;; + GUESS=$UNAME_MACHINE-unknown-sortix + ;; *:Twizzler:*:*) - echo "$UNAME_MACHINE"-unknown-twizzler - exit ;; + GUESS=$UNAME_MACHINE-unknown-twizzler + ;; *:Redox:*:*) - echo "$UNAME_MACHINE"-unknown-redox - exit ;; + GUESS=$UNAME_MACHINE-unknown-redox + ;; mips:OSF1:*.*) - echo mips-dec-osf1 - exit ;; + GUESS=mips-dec-osf1 + ;; alpha:OSF1:*:*) # Reset EXIT trap before exiting to avoid spurious non-zero exit code. trap '' 0 case $UNAME_RELEASE in *4.0) - UNAME_RELEASE=$(/usr/sbin/sizer -v | awk '{print $3}') + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) - UNAME_RELEASE=$(/usr/sbin/sizer -v | awk '{print $4}') + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on # OSF/1 and Tru64 systems produced since 1995. I hope that # covers most systems running today. This code pipes the CPU # types through head -n 1, so we only detect the type of CPU 0. - ALPHA_CPU_TYPE=$(/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1) + ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` case $ALPHA_CPU_TYPE in "EV4 (21064)") UNAME_MACHINE=alpha ;; @@ -352,65 +372,69 @@ case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. - echo "$UNAME_MACHINE"-dec-osf"$(echo "$UNAME_RELEASE" | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz)" - exit ;; + OSF_REL=`echo "$UNAME_RELEASE" | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` + GUESS=$UNAME_MACHINE-dec-osf$OSF_REL + ;; Amiga*:UNIX_System_V:4.0:*) - echo m68k-unknown-sysv4 - exit ;; + GUESS=m68k-unknown-sysv4 + ;; *:[Aa]miga[Oo][Ss]:*:*) - echo "$UNAME_MACHINE"-unknown-amigaos - exit ;; + GUESS=$UNAME_MACHINE-unknown-amigaos + ;; *:[Mm]orph[Oo][Ss]:*:*) - echo "$UNAME_MACHINE"-unknown-morphos - exit ;; + GUESS=$UNAME_MACHINE-unknown-morphos + ;; *:OS/390:*:*) - echo i370-ibm-openedition - exit ;; + GUESS=i370-ibm-openedition + ;; *:z/VM:*:*) - echo s390-ibm-zvmoe - exit ;; + GUESS=s390-ibm-zvmoe + ;; *:OS400:*:*) - echo powerpc-ibm-os400 - exit ;; + GUESS=powerpc-ibm-os400 + ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) - echo arm-acorn-riscix"$UNAME_RELEASE" - exit ;; + GUESS=arm-acorn-riscix$UNAME_RELEASE + ;; arm*:riscos:*:*|arm*:RISCOS:*:*) - echo arm-unknown-riscos - exit ;; + GUESS=arm-unknown-riscos + ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) - echo hppa1.1-hitachi-hiuxmpp - exit ;; + GUESS=hppa1.1-hitachi-hiuxmpp + ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. - if test "$( (/bin/universe) 2>/dev/null)" = att ; then - echo pyramid-pyramid-sysv3 - else - echo pyramid-pyramid-bsd - fi - exit ;; + case `(/bin/universe) 2>/dev/null` in + att) GUESS=pyramid-pyramid-sysv3 ;; + *) GUESS=pyramid-pyramid-bsd ;; + esac + ;; NILE*:*:*:dcosx) - echo pyramid-pyramid-svr4 - exit ;; + GUESS=pyramid-pyramid-svr4 + ;; DRS?6000:unix:4.0:6*) - echo sparc-icl-nx6 - exit ;; + GUESS=sparc-icl-nx6 + ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) - case $(/usr/bin/uname -p) in - sparc) echo sparc-icl-nx7; exit ;; - esac ;; + case `/usr/bin/uname -p` in + sparc) GUESS=sparc-icl-nx7 ;; + esac + ;; s390x:SunOS:*:*) - echo "$UNAME_MACHINE"-ibm-solaris2"$(echo "$UNAME_RELEASE" | sed -e 's/[^.]*//')" - exit ;; + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` + GUESS=$UNAME_MACHINE-ibm-solaris2$SUN_REL + ;; sun4H:SunOS:5.*:*) - echo sparc-hal-solaris2"$(echo "$UNAME_RELEASE"|sed -e 's/[^.]*//')" - exit ;; + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` + GUESS=sparc-hal-solaris2$SUN_REL + ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) - echo sparc-sun-solaris2"$(echo "$UNAME_RELEASE" | sed -e 's/[^.]*//')" - exit ;; + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` + GUESS=sparc-sun-solaris2$SUN_REL + ;; i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) - echo i386-pc-auroraux"$UNAME_RELEASE" - exit ;; + GUESS=i386-pc-auroraux$UNAME_RELEASE + ;; i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) set_cc_for_build SUN_ARCH=i386 @@ -419,47 +443,50 @@ case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in # This test works for both compilers. if test "$CC_FOR_BUILD" != no_compiler_found; then if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ - (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ + (CCOPTS="" $CC_FOR_BUILD -m64 -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then SUN_ARCH=x86_64 fi fi - echo "$SUN_ARCH"-pc-solaris2"$(echo "$UNAME_RELEASE"|sed -e 's/[^.]*//')" - exit ;; + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` + GUESS=$SUN_ARCH-pc-solaris2$SUN_REL + ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. - echo sparc-sun-solaris3"$(echo "$UNAME_RELEASE"|sed -e 's/[^.]*//')" - exit ;; + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` + GUESS=sparc-sun-solaris3$SUN_REL + ;; sun4*:SunOS:*:*) - case $(/usr/bin/arch -k) in + case `/usr/bin/arch -k` in Series*|S4*) - UNAME_RELEASE=$(uname -v) + UNAME_RELEASE=`uname -v` ;; esac - # Japanese Language versions have a version number like `4.1.3-JL'. - echo sparc-sun-sunos"$(echo "$UNAME_RELEASE"|sed -e 's/-/_/')" - exit ;; + # Japanese Language versions have a version number like '4.1.3-JL'. + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/-/_/'` + GUESS=sparc-sun-sunos$SUN_REL + ;; sun3*:SunOS:*:*) - echo m68k-sun-sunos"$UNAME_RELEASE" - exit ;; + GUESS=m68k-sun-sunos$UNAME_RELEASE + ;; sun*:*:4.2BSD:*) - UNAME_RELEASE=$( (sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null) + UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x$UNAME_RELEASE" = x && UNAME_RELEASE=3 - case $(/bin/arch) in + case `/bin/arch` in sun3) - echo m68k-sun-sunos"$UNAME_RELEASE" + GUESS=m68k-sun-sunos$UNAME_RELEASE ;; sun4) - echo sparc-sun-sunos"$UNAME_RELEASE" + GUESS=sparc-sun-sunos$UNAME_RELEASE ;; esac - exit ;; + ;; aushp:SunOS:*:*) - echo sparc-auspex-sunos"$UNAME_RELEASE" - exit ;; + GUESS=sparc-auspex-sunos$UNAME_RELEASE + ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor @@ -469,41 +496,41 @@ case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) - echo m68k-atari-mint"$UNAME_RELEASE" - exit ;; + GUESS=m68k-atari-mint$UNAME_RELEASE + ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) - echo m68k-atari-mint"$UNAME_RELEASE" - exit ;; + GUESS=m68k-atari-mint$UNAME_RELEASE + ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) - echo m68k-atari-mint"$UNAME_RELEASE" - exit ;; + GUESS=m68k-atari-mint$UNAME_RELEASE + ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) - echo m68k-milan-mint"$UNAME_RELEASE" - exit ;; + GUESS=m68k-milan-mint$UNAME_RELEASE + ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) - echo m68k-hades-mint"$UNAME_RELEASE" - exit ;; + GUESS=m68k-hades-mint$UNAME_RELEASE + ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) - echo m68k-unknown-mint"$UNAME_RELEASE" - exit ;; + GUESS=m68k-unknown-mint$UNAME_RELEASE + ;; m68k:machten:*:*) - echo m68k-apple-machten"$UNAME_RELEASE" - exit ;; + GUESS=m68k-apple-machten$UNAME_RELEASE + ;; powerpc:machten:*:*) - echo powerpc-apple-machten"$UNAME_RELEASE" - exit ;; + GUESS=powerpc-apple-machten$UNAME_RELEASE + ;; RISC*:Mach:*:*) - echo mips-dec-mach_bsd4.3 - exit ;; + GUESS=mips-dec-mach_bsd4.3 + ;; RISC*:ULTRIX:*:*) - echo mips-dec-ultrix"$UNAME_RELEASE" - exit ;; + GUESS=mips-dec-ultrix$UNAME_RELEASE + ;; VAX*:ULTRIX*:*:*) - echo vax-dec-ultrix"$UNAME_RELEASE" - exit ;; + GUESS=vax-dec-ultrix$UNAME_RELEASE + ;; 2020:CLIX:*:* | 2430:CLIX:*:*) - echo clipper-intergraph-clix"$UNAME_RELEASE" - exit ;; + GUESS=clipper-intergraph-clix$UNAME_RELEASE + ;; mips:*:*:UMIPS | mips:*:*:RISCos) set_cc_for_build sed 's/^ //' << EOF > "$dummy.c" @@ -528,85 +555,87 @@ case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in } EOF $CC_FOR_BUILD -o "$dummy" "$dummy.c" && - dummyarg=$(echo "$UNAME_RELEASE" | sed -n 's/\([0-9]*\).*/\1/p') && - SYSTEM_NAME=$("$dummy" "$dummyarg") && + dummyarg=`echo "$UNAME_RELEASE" | sed -n 's/\([0-9]*\).*/\1/p'` && + SYSTEM_NAME=`"$dummy" "$dummyarg"` && { echo "$SYSTEM_NAME"; exit; } - echo mips-mips-riscos"$UNAME_RELEASE" - exit ;; + GUESS=mips-mips-riscos$UNAME_RELEASE + ;; Motorola:PowerMAX_OS:*:*) - echo powerpc-motorola-powermax - exit ;; + GUESS=powerpc-motorola-powermax + ;; Motorola:*:4.3:PL8-*) - echo powerpc-harris-powermax - exit ;; + GUESS=powerpc-harris-powermax + ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) - echo powerpc-harris-powermax - exit ;; + GUESS=powerpc-harris-powermax + ;; Night_Hawk:Power_UNIX:*:*) - echo powerpc-harris-powerunix - exit ;; + GUESS=powerpc-harris-powerunix + ;; m88k:CX/UX:7*:*) - echo m88k-harris-cxux7 - exit ;; + GUESS=m88k-harris-cxux7 + ;; m88k:*:4*:R4*) - echo m88k-motorola-sysv4 - exit ;; + GUESS=m88k-motorola-sysv4 + ;; m88k:*:3*:R3*) - echo m88k-motorola-sysv3 - exit ;; + GUESS=m88k-motorola-sysv3 + ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures - UNAME_PROCESSOR=$(/usr/bin/uname -p) + UNAME_PROCESSOR=`/usr/bin/uname -p` if test "$UNAME_PROCESSOR" = mc88100 || test "$UNAME_PROCESSOR" = mc88110 then if test "$TARGET_BINARY_INTERFACE"x = m88kdguxelfx || \ test "$TARGET_BINARY_INTERFACE"x = x then - echo m88k-dg-dgux"$UNAME_RELEASE" + GUESS=m88k-dg-dgux$UNAME_RELEASE else - echo m88k-dg-dguxbcs"$UNAME_RELEASE" + GUESS=m88k-dg-dguxbcs$UNAME_RELEASE fi else - echo i586-dg-dgux"$UNAME_RELEASE" + GUESS=i586-dg-dgux$UNAME_RELEASE fi - exit ;; + ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) - echo m88k-dolphin-sysv3 - exit ;; + GUESS=m88k-dolphin-sysv3 + ;; M88*:*:R3*:*) # Delta 88k system running SVR3 - echo m88k-motorola-sysv3 - exit ;; + GUESS=m88k-motorola-sysv3 + ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) - echo m88k-tektronix-sysv3 - exit ;; + GUESS=m88k-tektronix-sysv3 + ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) - echo m68k-tektronix-bsd - exit ;; + GUESS=m68k-tektronix-bsd + ;; *:IRIX*:*:*) - echo mips-sgi-irix"$(echo "$UNAME_RELEASE"|sed -e 's/-/_/g')" - exit ;; + IRIX_REL=`echo "$UNAME_RELEASE" | sed -e 's/-/_/g'` + GUESS=mips-sgi-irix$IRIX_REL + ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. - echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id - exit ;; # Note that: echo "'$(uname -s)'" gives 'AIX ' + GUESS=romp-ibm-aix # uname -m gives an 8 hex-code CPU id + ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) - echo i386-ibm-aix - exit ;; + GUESS=i386-ibm-aix + ;; ia64:AIX:*:*) if test -x /usr/bin/oslevel ; then - IBM_REV=$(/usr/bin/oslevel) + IBM_REV=`/usr/bin/oslevel` else - IBM_REV="$UNAME_VERSION.$UNAME_RELEASE" + IBM_REV=$UNAME_VERSION.$UNAME_RELEASE fi - echo "$UNAME_MACHINE"-ibm-aix"$IBM_REV" - exit ;; + GUESS=$UNAME_MACHINE-ibm-aix$IBM_REV + ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then set_cc_for_build sed 's/^ //' << EOF > "$dummy.c" #include - main() + int + main () { if (!__power_pc()) exit(1); @@ -614,63 +643,63 @@ EOF exit(0); } EOF - if $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=$("$dummy") + if $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` then - echo "$SYSTEM_NAME" + GUESS=$SYSTEM_NAME else - echo rs6000-ibm-aix3.2.5 + GUESS=rs6000-ibm-aix3.2.5 fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then - echo rs6000-ibm-aix3.2.4 + GUESS=rs6000-ibm-aix3.2.4 else - echo rs6000-ibm-aix3.2 + GUESS=rs6000-ibm-aix3.2 fi - exit ;; + ;; *:AIX:*:[4567]) - IBM_CPU_ID=$(/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }') + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El "$IBM_CPU_ID" | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if test -x /usr/bin/lslpp ; then - IBM_REV=$(/usr/bin/lslpp -Lqc bos.rte.libc | - awk -F: '{ print $3 }' | sed s/[0-9]*$/0/) + IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc | \ + awk -F: '{ print $3 }' | sed s/[0-9]*$/0/` else - IBM_REV="$UNAME_VERSION.$UNAME_RELEASE" + IBM_REV=$UNAME_VERSION.$UNAME_RELEASE fi - echo "$IBM_ARCH"-ibm-aix"$IBM_REV" - exit ;; + GUESS=$IBM_ARCH-ibm-aix$IBM_REV + ;; *:AIX:*:*) - echo rs6000-ibm-aix - exit ;; + GUESS=rs6000-ibm-aix + ;; ibmrt:4.4BSD:*|romp-ibm:4.4BSD:*) - echo romp-ibm-bsd4.4 - exit ;; + GUESS=romp-ibm-bsd4.4 + ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and - echo romp-ibm-bsd"$UNAME_RELEASE" # 4.3 with uname added to - exit ;; # report: romp-ibm BSD 4.3 + GUESS=romp-ibm-bsd$UNAME_RELEASE # 4.3 with uname added to + ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) - echo rs6000-bull-bosx - exit ;; + GUESS=rs6000-bull-bosx + ;; DPX/2?00:B.O.S.:*:*) - echo m68k-bull-sysv3 - exit ;; + GUESS=m68k-bull-sysv3 + ;; 9000/[34]??:4.3bsd:1.*:*) - echo m68k-hp-bsd - exit ;; + GUESS=m68k-hp-bsd + ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) - echo m68k-hp-bsd4.4 - exit ;; + GUESS=m68k-hp-bsd4.4 + ;; 9000/[34678]??:HP-UX:*:*) - HPUX_REV=$(echo "$UNAME_RELEASE"|sed -e 's/[^.]*.[0B]*//') + HPUX_REV=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*.[0B]*//'` case $UNAME_MACHINE in 9000/31?) HP_ARCH=m68000 ;; 9000/[34]??) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if test -x /usr/bin/getconf; then - sc_cpu_version=$(/usr/bin/getconf SC_CPU_VERSION 2>/dev/null) - sc_kernel_bits=$(/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null) + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case $sc_cpu_version in 523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0 528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1 @@ -690,7 +719,8 @@ EOF #include #include - int main () + int + main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); @@ -717,7 +747,7 @@ EOF exit (0); } EOF - (CCOPTS="" $CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null) && HP_ARCH=$("$dummy") + (CCOPTS="" $CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null) && HP_ARCH=`"$dummy"` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac @@ -742,12 +772,12 @@ EOF HP_ARCH=hppa64 fi fi - echo "$HP_ARCH"-hp-hpux"$HPUX_REV" - exit ;; + GUESS=$HP_ARCH-hp-hpux$HPUX_REV + ;; ia64:HP-UX:*:*) - HPUX_REV=$(echo "$UNAME_RELEASE"|sed -e 's/[^.]*.[0B]*//') - echo ia64-hp-hpux"$HPUX_REV" - exit ;; + HPUX_REV=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*.[0B]*//'` + GUESS=ia64-hp-hpux$HPUX_REV + ;; 3050*:HI-UX:*:*) set_cc_for_build sed 's/^ //' << EOF > "$dummy.c" @@ -775,38 +805,38 @@ EOF exit (0); } EOF - $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=$("$dummy") && + $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` && { echo "$SYSTEM_NAME"; exit; } - echo unknown-hitachi-hiuxwe2 - exit ;; + GUESS=unknown-hitachi-hiuxwe2 + ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:*) - echo hppa1.1-hp-bsd - exit ;; + GUESS=hppa1.1-hp-bsd + ;; 9000/8??:4.3bsd:*:*) - echo hppa1.0-hp-bsd - exit ;; + GUESS=hppa1.0-hp-bsd + ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) - echo hppa1.0-hp-mpeix - exit ;; + GUESS=hppa1.0-hp-mpeix + ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:*) - echo hppa1.1-hp-osf - exit ;; + GUESS=hppa1.1-hp-osf + ;; hp8??:OSF1:*:*) - echo hppa1.0-hp-osf - exit ;; + GUESS=hppa1.0-hp-osf + ;; i*86:OSF1:*:*) if test -x /usr/sbin/sysversion ; then - echo "$UNAME_MACHINE"-unknown-osf1mk + GUESS=$UNAME_MACHINE-unknown-osf1mk else - echo "$UNAME_MACHINE"-unknown-osf1 + GUESS=$UNAME_MACHINE-unknown-osf1 fi - exit ;; + ;; parisc*:Lites*:*:*) - echo hppa1.1-hp-lites - exit ;; + GUESS=hppa1.1-hp-lites + ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) - echo c1-convex-bsd - exit ;; + GUESS=c1-convex-bsd + ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd @@ -814,17 +844,18 @@ EOF fi exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) - echo c34-convex-bsd - exit ;; + GUESS=c34-convex-bsd + ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) - echo c38-convex-bsd - exit ;; + GUESS=c38-convex-bsd + ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) - echo c4-convex-bsd - exit ;; + GUESS=c4-convex-bsd + ;; CRAY*Y-MP:*:*:*) - echo ymp-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' - exit ;; + CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` + GUESS=ymp-cray-unicos$CRAY_REL + ;; CRAY*[A-Z]90:*:*:*) echo "$UNAME_MACHINE"-cray-unicos"$UNAME_RELEASE" \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ @@ -832,114 +863,155 @@ EOF -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) - echo t90-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' - exit ;; + CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` + GUESS=t90-cray-unicos$CRAY_REL + ;; CRAY*T3E:*:*:*) - echo alphaev5-cray-unicosmk"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' - exit ;; + CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` + GUESS=alphaev5-cray-unicosmk$CRAY_REL + ;; CRAY*SV1:*:*:*) - echo sv1-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' - exit ;; + CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` + GUESS=sv1-cray-unicos$CRAY_REL + ;; *:UNICOS/mp:*:*) - echo craynv-cray-unicosmp"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' - exit ;; + CRAY_REL=`echo "$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'` + GUESS=craynv-cray-unicosmp$CRAY_REL + ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) - FUJITSU_PROC=$(uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz) - FUJITSU_SYS=$(uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///') - FUJITSU_REL=$(echo "$UNAME_RELEASE" | sed -e 's/ /_/') - echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" - exit ;; + FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` + FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` + FUJITSU_REL=`echo "$UNAME_RELEASE" | sed -e 's/ /_/'` + GUESS=${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL} + ;; 5000:UNIX_System_V:4.*:*) - FUJITSU_SYS=$(uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///') - FUJITSU_REL=$(echo "$UNAME_RELEASE" | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/') - echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" - exit ;; + FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` + FUJITSU_REL=`echo "$UNAME_RELEASE" | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'` + GUESS=sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL} + ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) - echo "$UNAME_MACHINE"-pc-bsdi"$UNAME_RELEASE" - exit ;; + GUESS=$UNAME_MACHINE-pc-bsdi$UNAME_RELEASE + ;; sparc*:BSD/OS:*:*) - echo sparc-unknown-bsdi"$UNAME_RELEASE" - exit ;; + GUESS=sparc-unknown-bsdi$UNAME_RELEASE + ;; *:BSD/OS:*:*) - echo "$UNAME_MACHINE"-unknown-bsdi"$UNAME_RELEASE" - exit ;; + GUESS=$UNAME_MACHINE-unknown-bsdi$UNAME_RELEASE + ;; arm:FreeBSD:*:*) - UNAME_PROCESSOR=$(uname -p) + UNAME_PROCESSOR=`uname -p` set_cc_for_build if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then - echo "${UNAME_PROCESSOR}"-unknown-freebsd"$(echo ${UNAME_RELEASE}|sed -e 's/[-(].*//')"-gnueabi + FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` + GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL-gnueabi else - echo "${UNAME_PROCESSOR}"-unknown-freebsd"$(echo ${UNAME_RELEASE}|sed -e 's/[-(].*//')"-gnueabihf + FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` + GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL-gnueabihf fi - exit ;; + ;; *:FreeBSD:*:*) - UNAME_PROCESSOR=$(/usr/bin/uname -p) + UNAME_PROCESSOR=`uname -p` case $UNAME_PROCESSOR in amd64) UNAME_PROCESSOR=x86_64 ;; i386) UNAME_PROCESSOR=i586 ;; esac - echo "$UNAME_PROCESSOR"-unknown-freebsd"$(echo "$UNAME_RELEASE"|sed -e 's/[-(].*//')" - exit ;; + FREEBSD_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` + GUESS=$UNAME_PROCESSOR-unknown-freebsd$FREEBSD_REL + ;; i*:CYGWIN*:*) - echo "$UNAME_MACHINE"-pc-cygwin - exit ;; + GUESS=$UNAME_MACHINE-pc-cygwin + ;; *:MINGW64*:*) - echo "$UNAME_MACHINE"-pc-mingw64 - exit ;; + GUESS=$UNAME_MACHINE-pc-mingw64 + ;; *:MINGW*:*) - echo "$UNAME_MACHINE"-pc-mingw32 - exit ;; + GUESS=$UNAME_MACHINE-pc-mingw32 + ;; *:MSYS*:*) - echo "$UNAME_MACHINE"-pc-msys - exit ;; + GUESS=$UNAME_MACHINE-pc-msys + ;; i*:PW*:*) - echo "$UNAME_MACHINE"-pc-pw32 - exit ;; + GUESS=$UNAME_MACHINE-pc-pw32 + ;; + *:SerenityOS:*:*) + GUESS=$UNAME_MACHINE-pc-serenity + ;; *:Interix*:*) case $UNAME_MACHINE in x86) - echo i586-pc-interix"$UNAME_RELEASE" - exit ;; + GUESS=i586-pc-interix$UNAME_RELEASE + ;; authenticamd | genuineintel | EM64T) - echo x86_64-unknown-interix"$UNAME_RELEASE" - exit ;; + GUESS=x86_64-unknown-interix$UNAME_RELEASE + ;; IA64) - echo ia64-unknown-interix"$UNAME_RELEASE" - exit ;; + GUESS=ia64-unknown-interix$UNAME_RELEASE + ;; esac ;; i*:UWIN*:*) - echo "$UNAME_MACHINE"-pc-uwin - exit ;; + GUESS=$UNAME_MACHINE-pc-uwin + ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) - echo x86_64-pc-cygwin - exit ;; + GUESS=x86_64-pc-cygwin + ;; prep*:SunOS:5.*:*) - echo powerpcle-unknown-solaris2"$(echo "$UNAME_RELEASE"|sed -e 's/[^.]*//')" - exit ;; + SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'` + GUESS=powerpcle-unknown-solaris2$SUN_REL + ;; *:GNU:*:*) # the GNU system - echo "$(echo "$UNAME_MACHINE"|sed -e 's,[-/].*$,,')-unknown-$LIBC$(echo "$UNAME_RELEASE"|sed -e 's,/.*$,,')" - exit ;; + GNU_ARCH=`echo "$UNAME_MACHINE" | sed -e 's,[-/].*$,,'` + GNU_REL=`echo "$UNAME_RELEASE" | sed -e 's,/.*$,,'` + GUESS=$GNU_ARCH-unknown-$LIBC$GNU_REL + ;; *:GNU/*:*:*) # other systems with GNU libc and userland - echo "$UNAME_MACHINE-unknown-$(echo "$UNAME_SYSTEM" | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]")$(echo "$UNAME_RELEASE"|sed -e 's/[-(].*//')-$LIBC" - exit ;; + GNU_SYS=`echo "$UNAME_SYSTEM" | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"` + GNU_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` + GUESS=$UNAME_MACHINE-unknown-$GNU_SYS$GNU_REL-$LIBC + ;; + x86_64:[Mm]anagarm:*:*|i?86:[Mm]anagarm:*:*) + GUESS="$UNAME_MACHINE-pc-managarm-mlibc" + ;; + *:[Mm]anagarm:*:*) + GUESS="$UNAME_MACHINE-unknown-managarm-mlibc" + ;; *:Minix:*:*) - echo "$UNAME_MACHINE"-unknown-minix - exit ;; + GUESS=$UNAME_MACHINE-unknown-minix + ;; aarch64:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + set_cc_for_build + CPU=$UNAME_MACHINE + LIBCABI=$LIBC + if test "$CC_FOR_BUILD" != no_compiler_found; then + ABI=64 + sed 's/^ //' << EOF > "$dummy.c" + #ifdef __ARM_EABI__ + #ifdef __ARM_PCS_VFP + ABI=eabihf + #else + ABI=eabi + #endif + #endif +EOF + cc_set_abi=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^ABI' | sed 's, ,,g'` + eval "$cc_set_abi" + case $ABI in + eabi | eabihf) CPU=armv8l; LIBCABI=$LIBC$ABI ;; + esac + fi + GUESS=$CPU-unknown-linux-$LIBCABI + ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; alpha:Linux:*:*) - case $(sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' /proc/cpuinfo 2>/dev/null) in + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' /proc/cpuinfo 2>/dev/null` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; @@ -950,63 +1022,72 @@ EOF esac objdump --private-headers /bin/sh | grep -q ld.so.1 if test "$?" = 0 ; then LIBC=gnulibc1 ; fi - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; - arc:Linux:*:* | arceb:Linux:*:* | arc64:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + arc:Linux:*:* | arceb:Linux:*:* | arc32:Linux:*:* | arc64:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; arm*:Linux:*:*) set_cc_for_build if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_EABI__ then - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC else if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"eabi + GUESS=$UNAME_MACHINE-unknown-linux-${LIBC}eabi else - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"eabihf + GUESS=$UNAME_MACHINE-unknown-linux-${LIBC}eabihf fi fi - exit ;; + ;; avr32*:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; cris:Linux:*:*) - echo "$UNAME_MACHINE"-axis-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-axis-linux-$LIBC + ;; crisv32:Linux:*:*) - echo "$UNAME_MACHINE"-axis-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-axis-linux-$LIBC + ;; e2k:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; frv:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; hexagon:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; i*86:Linux:*:*) - echo "$UNAME_MACHINE"-pc-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-pc-linux-$LIBC + ;; ia64:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; k1om:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; - loongarch32:Linux:*:* | loongarch64:Linux:*:* | loongarchx32:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + kvx:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + kvx:cos:*:*) + GUESS=$UNAME_MACHINE-unknown-cos + ;; + kvx:mbr:*:*) + GUESS=$UNAME_MACHINE-unknown-mbr + ;; + loongarch32:Linux:*:* | loongarch64:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; m32r*:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; m68*:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; mips:Linux:*:* | mips64:Linux:*:*) set_cc_for_build IS_GLIBC=0 @@ -1051,138 +1132,150 @@ EOF #endif #endif EOF - eval "$($CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^CPU\|^MIPS_ENDIAN\|^LIBCABI')" + cc_set_vars=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^CPU\|^MIPS_ENDIAN\|^LIBCABI'` + eval "$cc_set_vars" test "x$CPU" != x && { echo "$CPU${MIPS_ENDIAN}-unknown-linux-$LIBCABI"; exit; } ;; mips64el:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; openrisc*:Linux:*:*) - echo or1k-unknown-linux-"$LIBC" - exit ;; + GUESS=or1k-unknown-linux-$LIBC + ;; or32:Linux:*:* | or1k*:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; padre:Linux:*:*) - echo sparc-unknown-linux-"$LIBC" - exit ;; + GUESS=sparc-unknown-linux-$LIBC + ;; parisc64:Linux:*:* | hppa64:Linux:*:*) - echo hppa64-unknown-linux-"$LIBC" - exit ;; + GUESS=hppa64-unknown-linux-$LIBC + ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level - case $(grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2) in - PA7*) echo hppa1.1-unknown-linux-"$LIBC" ;; - PA8*) echo hppa2.0-unknown-linux-"$LIBC" ;; - *) echo hppa-unknown-linux-"$LIBC" ;; + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) GUESS=hppa1.1-unknown-linux-$LIBC ;; + PA8*) GUESS=hppa2.0-unknown-linux-$LIBC ;; + *) GUESS=hppa-unknown-linux-$LIBC ;; esac - exit ;; + ;; ppc64:Linux:*:*) - echo powerpc64-unknown-linux-"$LIBC" - exit ;; + GUESS=powerpc64-unknown-linux-$LIBC + ;; ppc:Linux:*:*) - echo powerpc-unknown-linux-"$LIBC" - exit ;; + GUESS=powerpc-unknown-linux-$LIBC + ;; ppc64le:Linux:*:*) - echo powerpc64le-unknown-linux-"$LIBC" - exit ;; + GUESS=powerpc64le-unknown-linux-$LIBC + ;; ppcle:Linux:*:*) - echo powerpcle-unknown-linux-"$LIBC" - exit ;; + GUESS=powerpcle-unknown-linux-$LIBC + ;; riscv32:Linux:*:* | riscv32be:Linux:*:* | riscv64:Linux:*:* | riscv64be:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; s390:Linux:*:* | s390x:Linux:*:*) - echo "$UNAME_MACHINE"-ibm-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-ibm-linux-$LIBC + ;; sh64*:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; sh*:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; sparc:Linux:*:* | sparc64:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; tile*:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; vax:Linux:*:*) - echo "$UNAME_MACHINE"-dec-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-dec-linux-$LIBC + ;; x86_64:Linux:*:*) set_cc_for_build + CPU=$UNAME_MACHINE LIBCABI=$LIBC if test "$CC_FOR_BUILD" != no_compiler_found; then - if (echo '#ifdef __ILP32__'; echo IS_X32; echo '#endif') | \ - (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ - grep IS_X32 >/dev/null - then - LIBCABI="$LIBC"x32 - fi + ABI=64 + sed 's/^ //' << EOF > "$dummy.c" + #ifdef __i386__ + ABI=x86 + #else + #ifdef __ILP32__ + ABI=x32 + #endif + #endif +EOF + cc_set_abi=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^ABI' | sed 's, ,,g'` + eval "$cc_set_abi" + case $ABI in + x86) CPU=i686 ;; + x32) LIBCABI=${LIBC}x32 ;; + esac fi - echo "$UNAME_MACHINE"-pc-linux-"$LIBCABI" - exit ;; + GUESS=$CPU-pc-linux-$LIBCABI + ;; xtensa*:Linux:*:*) - echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" - exit ;; + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. - echo i386-sequent-sysv4 - exit ;; + GUESS=i386-sequent-sysv4 + ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. - echo "$UNAME_MACHINE"-pc-sysv4.2uw"$UNAME_VERSION" - exit ;; + GUESS=$UNAME_MACHINE-pc-sysv4.2uw$UNAME_VERSION + ;; i*86:OS/2:*:*) - # If we were able to find `uname', then EMX Unix compatibility + # If we were able to find 'uname', then EMX Unix compatibility # is probably installed. - echo "$UNAME_MACHINE"-pc-os2-emx - exit ;; + GUESS=$UNAME_MACHINE-pc-os2-emx + ;; i*86:XTS-300:*:STOP) - echo "$UNAME_MACHINE"-unknown-stop - exit ;; + GUESS=$UNAME_MACHINE-unknown-stop + ;; i*86:atheos:*:*) - echo "$UNAME_MACHINE"-unknown-atheos - exit ;; + GUESS=$UNAME_MACHINE-unknown-atheos + ;; i*86:syllable:*:*) - echo "$UNAME_MACHINE"-pc-syllable - exit ;; + GUESS=$UNAME_MACHINE-pc-syllable + ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) - echo i386-unknown-lynxos"$UNAME_RELEASE" - exit ;; + GUESS=i386-unknown-lynxos$UNAME_RELEASE + ;; i*86:*DOS:*:*) - echo "$UNAME_MACHINE"-pc-msdosdjgpp - exit ;; + GUESS=$UNAME_MACHINE-pc-msdosdjgpp + ;; i*86:*:4.*:*) - UNAME_REL=$(echo "$UNAME_RELEASE" | sed 's/\/MP$//') + UNAME_REL=`echo "$UNAME_RELEASE" | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then - echo "$UNAME_MACHINE"-univel-sysv"$UNAME_REL" + GUESS=$UNAME_MACHINE-univel-sysv$UNAME_REL else - echo "$UNAME_MACHINE"-pc-sysv"$UNAME_REL" + GUESS=$UNAME_MACHINE-pc-sysv$UNAME_REL fi - exit ;; + ;; i*86:*:5:[678]*) # UnixWare 7.x, OpenUNIX and OpenServer 6. - case $(/bin/uname -X | grep "^Machine") in + case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac - echo "$UNAME_MACHINE-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}" - exit ;; + GUESS=$UNAME_MACHINE-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then - UNAME_REL=$(sed -n 's/.*Version //p' /dev/null >/dev/null ; then - UNAME_REL=$( (/bin/uname -X|grep Release|sed -e 's/.*= //')) + UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 @@ -1190,11 +1283,11 @@ EOF && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 - echo "$UNAME_MACHINE"-pc-sco"$UNAME_REL" + GUESS=$UNAME_MACHINE-pc-sco$UNAME_REL else - echo "$UNAME_MACHINE"-pc-sysv32 + GUESS=$UNAME_MACHINE-pc-sysv32 fi - exit ;; + ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about @@ -1202,37 +1295,37 @@ EOF # Note: whatever this is, it MUST be the same as what config.sub # prints for the "djgpp" host, or else GDB configure will decide that # this is a cross-build. - echo i586-pc-msdosdjgpp - exit ;; + GUESS=i586-pc-msdosdjgpp + ;; Intel:Mach:3*:*) - echo i386-pc-mach3 - exit ;; + GUESS=i386-pc-mach3 + ;; paragon:*:*:*) - echo i860-intel-osf1 - exit ;; + GUESS=i860-intel-osf1 + ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then - echo i860-stardent-sysv"$UNAME_RELEASE" # Stardent Vistra i860-SVR4 + GUESS=i860-stardent-sysv$UNAME_RELEASE # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. - echo i860-unknown-sysv"$UNAME_RELEASE" # Unknown i860-SVR4 + GUESS=i860-unknown-sysv$UNAME_RELEASE # Unknown i860-SVR4 fi - exit ;; + ;; mini*:CTIX:SYS*5:*) # "miniframe" - echo m68010-convergent-sysv - exit ;; + GUESS=m68010-convergent-sysv + ;; mc68k:UNIX:SYSTEM5:3.51m) - echo m68k-convergent-sysv - exit ;; + GUESS=m68k-convergent-sysv + ;; M680?0:D-NIX:5.3:*) - echo m68k-diab-dnix - exit ;; + GUESS=m68k-diab-dnix + ;; M68*:*:R3V[5678]*:*) test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ - && OS_REL=.$(sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid) + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ @@ -1243,7 +1336,7 @@ EOF NCR*:*:4.2:* | MPRAS*:*:4.2:*) OS_REL='.3' test -r /etc/.relid \ - && OS_REL=.$(sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid) + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ @@ -1251,118 +1344,121 @@ EOF /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) - echo m68k-unknown-lynxos"$UNAME_RELEASE" - exit ;; + GUESS=m68k-unknown-lynxos$UNAME_RELEASE + ;; mc68030:UNIX_System_V:4.*:*) - echo m68k-atari-sysv4 - exit ;; + GUESS=m68k-atari-sysv4 + ;; TSUNAMI:LynxOS:2.*:*) - echo sparc-unknown-lynxos"$UNAME_RELEASE" - exit ;; + GUESS=sparc-unknown-lynxos$UNAME_RELEASE + ;; rs6000:LynxOS:2.*:*) - echo rs6000-unknown-lynxos"$UNAME_RELEASE" - exit ;; + GUESS=rs6000-unknown-lynxos$UNAME_RELEASE + ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) - echo powerpc-unknown-lynxos"$UNAME_RELEASE" - exit ;; + GUESS=powerpc-unknown-lynxos$UNAME_RELEASE + ;; SM[BE]S:UNIX_SV:*:*) - echo mips-dde-sysv"$UNAME_RELEASE" - exit ;; + GUESS=mips-dde-sysv$UNAME_RELEASE + ;; RM*:ReliantUNIX-*:*:*) - echo mips-sni-sysv4 - exit ;; + GUESS=mips-sni-sysv4 + ;; RM*:SINIX-*:*:*) - echo mips-sni-sysv4 - exit ;; + GUESS=mips-sni-sysv4 + ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then - UNAME_MACHINE=$( (uname -p) 2>/dev/null) - echo "$UNAME_MACHINE"-sni-sysv4 + UNAME_MACHINE=`(uname -p) 2>/dev/null` + GUESS=$UNAME_MACHINE-sni-sysv4 else - echo ns32k-sni-sysv + GUESS=ns32k-sni-sysv fi - exit ;; - PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + ;; + PENTIUM:*:4.0*:*) # Unisys 'ClearPath HMP IX 4000' SVR4/MP effort # says - echo i586-unisys-sysv4 - exit ;; + GUESS=i586-unisys-sysv4 + ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm - echo hppa1.1-stratus-sysv4 - exit ;; + GUESS=hppa1.1-stratus-sysv4 + ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. - echo i860-stratus-sysv4 - exit ;; + GUESS=i860-stratus-sysv4 + ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. - echo "$UNAME_MACHINE"-stratus-vos - exit ;; + GUESS=$UNAME_MACHINE-stratus-vos + ;; *:VOS:*:*) # From Paul.Green@stratus.com. - echo hppa1.1-stratus-vos - exit ;; + GUESS=hppa1.1-stratus-vos + ;; mc68*:A/UX:*:*) - echo m68k-apple-aux"$UNAME_RELEASE" - exit ;; + GUESS=m68k-apple-aux$UNAME_RELEASE + ;; news*:NEWS-OS:6*:*) - echo mips-sony-newsos6 - exit ;; + GUESS=mips-sony-newsos6 + ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if test -d /usr/nec; then - echo mips-nec-sysv"$UNAME_RELEASE" + GUESS=mips-nec-sysv$UNAME_RELEASE else - echo mips-unknown-sysv"$UNAME_RELEASE" + GUESS=mips-unknown-sysv$UNAME_RELEASE fi - exit ;; + ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. - echo powerpc-be-beos - exit ;; + GUESS=powerpc-be-beos + ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. - echo powerpc-apple-beos - exit ;; + GUESS=powerpc-apple-beos + ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. - echo i586-pc-beos - exit ;; + GUESS=i586-pc-beos + ;; BePC:Haiku:*:*) # Haiku running on Intel PC compatible. - echo i586-pc-haiku - exit ;; - x86_64:Haiku:*:*) - echo x86_64-unknown-haiku - exit ;; + GUESS=i586-pc-haiku + ;; + ppc:Haiku:*:*) # Haiku running on Apple PowerPC + GUESS=powerpc-apple-haiku + ;; + *:Haiku:*:*) # Haiku modern gcc (not bound by BeOS compat) + GUESS=$UNAME_MACHINE-unknown-haiku + ;; SX-4:SUPER-UX:*:*) - echo sx4-nec-superux"$UNAME_RELEASE" - exit ;; + GUESS=sx4-nec-superux$UNAME_RELEASE + ;; SX-5:SUPER-UX:*:*) - echo sx5-nec-superux"$UNAME_RELEASE" - exit ;; + GUESS=sx5-nec-superux$UNAME_RELEASE + ;; SX-6:SUPER-UX:*:*) - echo sx6-nec-superux"$UNAME_RELEASE" - exit ;; + GUESS=sx6-nec-superux$UNAME_RELEASE + ;; SX-7:SUPER-UX:*:*) - echo sx7-nec-superux"$UNAME_RELEASE" - exit ;; + GUESS=sx7-nec-superux$UNAME_RELEASE + ;; SX-8:SUPER-UX:*:*) - echo sx8-nec-superux"$UNAME_RELEASE" - exit ;; + GUESS=sx8-nec-superux$UNAME_RELEASE + ;; SX-8R:SUPER-UX:*:*) - echo sx8r-nec-superux"$UNAME_RELEASE" - exit ;; + GUESS=sx8r-nec-superux$UNAME_RELEASE + ;; SX-ACE:SUPER-UX:*:*) - echo sxace-nec-superux"$UNAME_RELEASE" - exit ;; + GUESS=sxace-nec-superux$UNAME_RELEASE + ;; Power*:Rhapsody:*:*) - echo powerpc-apple-rhapsody"$UNAME_RELEASE" - exit ;; + GUESS=powerpc-apple-rhapsody$UNAME_RELEASE + ;; *:Rhapsody:*:*) - echo "$UNAME_MACHINE"-apple-rhapsody"$UNAME_RELEASE" - exit ;; + GUESS=$UNAME_MACHINE-apple-rhapsody$UNAME_RELEASE + ;; arm64:Darwin:*:*) - echo aarch64-apple-darwin"$UNAME_RELEASE" - exit ;; + GUESS=aarch64-apple-darwin$UNAME_RELEASE + ;; *:Darwin:*:*) - UNAME_PROCESSOR=$(uname -p) + UNAME_PROCESSOR=`uname -p` case $UNAME_PROCESSOR in unknown) UNAME_PROCESSOR=powerpc ;; esac @@ -1396,43 +1492,43 @@ EOF # uname -m returns i386 or x86_64 UNAME_PROCESSOR=$UNAME_MACHINE fi - echo "$UNAME_PROCESSOR"-apple-darwin"$UNAME_RELEASE" - exit ;; + GUESS=$UNAME_PROCESSOR-apple-darwin$UNAME_RELEASE + ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) - UNAME_PROCESSOR=$(uname -p) + UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = x86; then UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi - echo "$UNAME_PROCESSOR"-"$UNAME_MACHINE"-nto-qnx"$UNAME_RELEASE" - exit ;; + GUESS=$UNAME_PROCESSOR-$UNAME_MACHINE-nto-qnx$UNAME_RELEASE + ;; *:QNX:*:4*) - echo i386-pc-qnx - exit ;; + GUESS=i386-pc-qnx + ;; NEO-*:NONSTOP_KERNEL:*:*) - echo neo-tandem-nsk"$UNAME_RELEASE" - exit ;; + GUESS=neo-tandem-nsk$UNAME_RELEASE + ;; NSE-*:NONSTOP_KERNEL:*:*) - echo nse-tandem-nsk"$UNAME_RELEASE" - exit ;; + GUESS=nse-tandem-nsk$UNAME_RELEASE + ;; NSR-*:NONSTOP_KERNEL:*:*) - echo nsr-tandem-nsk"$UNAME_RELEASE" - exit ;; + GUESS=nsr-tandem-nsk$UNAME_RELEASE + ;; NSV-*:NONSTOP_KERNEL:*:*) - echo nsv-tandem-nsk"$UNAME_RELEASE" - exit ;; + GUESS=nsv-tandem-nsk$UNAME_RELEASE + ;; NSX-*:NONSTOP_KERNEL:*:*) - echo nsx-tandem-nsk"$UNAME_RELEASE" - exit ;; + GUESS=nsx-tandem-nsk$UNAME_RELEASE + ;; *:NonStop-UX:*:*) - echo mips-compaq-nonstopux - exit ;; + GUESS=mips-compaq-nonstopux + ;; BS2000:POSIX*:*:*) - echo bs2000-siemens-sysv - exit ;; + GUESS=bs2000-siemens-sysv + ;; DS/*:UNIX_System_V:*:*) - echo "$UNAME_MACHINE"-"$UNAME_SYSTEM"-"$UNAME_RELEASE" - exit ;; + GUESS=$UNAME_MACHINE-$UNAME_SYSTEM-$UNAME_RELEASE + ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 @@ -1440,64 +1536,78 @@ EOF if test "${cputype-}" = 386; then UNAME_MACHINE=i386 elif test "x${cputype-}" != x; then - UNAME_MACHINE="$cputype" + UNAME_MACHINE=$cputype fi - echo "$UNAME_MACHINE"-unknown-plan9 - exit ;; + GUESS=$UNAME_MACHINE-unknown-plan9 + ;; *:TOPS-10:*:*) - echo pdp10-unknown-tops10 - exit ;; + GUESS=pdp10-unknown-tops10 + ;; *:TENEX:*:*) - echo pdp10-unknown-tenex - exit ;; + GUESS=pdp10-unknown-tenex + ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) - echo pdp10-dec-tops20 - exit ;; + GUESS=pdp10-dec-tops20 + ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) - echo pdp10-xkl-tops20 - exit ;; + GUESS=pdp10-xkl-tops20 + ;; *:TOPS-20:*:*) - echo pdp10-unknown-tops20 - exit ;; + GUESS=pdp10-unknown-tops20 + ;; *:ITS:*:*) - echo pdp10-unknown-its - exit ;; + GUESS=pdp10-unknown-its + ;; SEI:*:*:SEIUX) - echo mips-sei-seiux"$UNAME_RELEASE" - exit ;; + GUESS=mips-sei-seiux$UNAME_RELEASE + ;; *:DragonFly:*:*) - echo "$UNAME_MACHINE"-unknown-dragonfly"$(echo "$UNAME_RELEASE"|sed -e 's/[-(].*//')" - exit ;; + DRAGONFLY_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` + GUESS=$UNAME_MACHINE-unknown-dragonfly$DRAGONFLY_REL + ;; *:*VMS:*:*) - UNAME_MACHINE=$( (uname -p) 2>/dev/null) + UNAME_MACHINE=`(uname -p) 2>/dev/null` case $UNAME_MACHINE in - A*) echo alpha-dec-vms ; exit ;; - I*) echo ia64-dec-vms ; exit ;; - V*) echo vax-dec-vms ; exit ;; + A*) GUESS=alpha-dec-vms ;; + I*) GUESS=ia64-dec-vms ;; + V*) GUESS=vax-dec-vms ;; esac ;; *:XENIX:*:SysV) - echo i386-pc-xenix - exit ;; + GUESS=i386-pc-xenix + ;; i*86:skyos:*:*) - echo "$UNAME_MACHINE"-pc-skyos"$(echo "$UNAME_RELEASE" | sed -e 's/ .*$//')" - exit ;; + SKYOS_REL=`echo "$UNAME_RELEASE" | sed -e 's/ .*$//'` + GUESS=$UNAME_MACHINE-pc-skyos$SKYOS_REL + ;; i*86:rdos:*:*) - echo "$UNAME_MACHINE"-pc-rdos - exit ;; + GUESS=$UNAME_MACHINE-pc-rdos + ;; + i*86:Fiwix:*:*) + GUESS=$UNAME_MACHINE-pc-fiwix + ;; *:AROS:*:*) - echo "$UNAME_MACHINE"-unknown-aros - exit ;; + GUESS=$UNAME_MACHINE-unknown-aros + ;; x86_64:VMkernel:*:*) - echo "$UNAME_MACHINE"-unknown-esx - exit ;; + GUESS=$UNAME_MACHINE-unknown-esx + ;; amd64:Isilon\ OneFS:*:*) - echo x86_64-unknown-onefs - exit ;; + GUESS=x86_64-unknown-onefs + ;; *:Unleashed:*:*) - echo "$UNAME_MACHINE"-unknown-unleashed"$UNAME_RELEASE" - exit ;; + GUESS=$UNAME_MACHINE-unknown-unleashed$UNAME_RELEASE + ;; + *:Ironclad:*:*) + GUESS=$UNAME_MACHINE-unknown-ironclad + ;; esac +# Do we have a guess based on uname results? +if test "x$GUESS" != x; then + echo "$GUESS" + exit +fi + # No uname command or uname output not recognized. set_cc_for_build cat > "$dummy.c" < "$dummy.c" </dev/null); + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; if (version < 4) printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); else @@ -1629,7 +1740,7 @@ main () } EOF -$CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null && SYSTEM_NAME=$($dummy) && +$CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null && SYSTEM_NAME=`"$dummy"` && { echo "$SYSTEM_NAME"; exit; } # Apollos put the system type in the environment. @@ -1659,9 +1770,11 @@ and https://git.savannah.gnu.org/cgit/config.git/plain/config.sub EOF -year=$(echo $timestamp | sed 's,-.*,,') +our_year=`echo $timestamp | sed 's,-.*,,'` +thisyear=`date +%Y` # shellcheck disable=SC2003 -if test "$(expr "$(date +%Y)" - "$year")" -lt 3 ; then +script_age=`expr "$thisyear" - "$our_year"` +if test "$script_age" -lt 3 ; then cat >&2 </dev/null || echo unknown) -uname -r = $( (uname -r) 2>/dev/null || echo unknown) -uname -s = $( (uname -s) 2>/dev/null || echo unknown) -uname -v = $( (uname -v) 2>/dev/null || echo unknown) +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` -/usr/bin/uname -p = $( (/usr/bin/uname -p) 2>/dev/null) -/bin/uname -X = $( (/bin/uname -X) 2>/dev/null) +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` -hostinfo = $( (hostinfo) 2>/dev/null) -/bin/universe = $( (/bin/universe) 2>/dev/null) -/usr/bin/arch -k = $( (/usr/bin/arch -k) 2>/dev/null) -/bin/arch = $( (/bin/arch) 2>/dev/null) -/usr/bin/oslevel = $( (/usr/bin/oslevel) 2>/dev/null) -/usr/convex/getsysinfo = $( (/usr/convex/getsysinfo) 2>/dev/null) +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = "$UNAME_MACHINE" UNAME_RELEASE = "$UNAME_RELEASE" diff --git a/depends/config.sub b/depends/config.sub index 7384e9198b..4aaae46f6f 100755 --- a/depends/config.sub +++ b/depends/config.sub @@ -1,12 +1,14 @@ #! /bin/sh # Configuration validation subroutine script. -# Copyright 1992-2021 Free Software Foundation, Inc. +# Copyright 1992-2024 Free Software Foundation, Inc. -timestamp='2021-04-30' +# shellcheck disable=SC2006,SC2268,SC2162 # see below for rationale + +timestamp='2024-05-27' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 3 of the License, or +# the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but @@ -50,7 +52,14 @@ timestamp='2021-04-30' # CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM # It is wrong to echo any other type of specification. -me=$(echo "$0" | sed -e 's,.*/,,') +# The "shellcheck disable" line above the timestamp inhibits complaints +# about features and limitations of the classic Bourne shell that were +# superseded or lifted in POSIX. However, this script identifies a wide +# variety of pre-POSIX systems that do not have POSIX shells at all, and +# even some reasonably current systems (Solaris 10 as case-in-point) still +# have a pre-POSIX /bin/sh. + +me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] CPU-MFR-OPSYS or ALIAS @@ -67,13 +76,13 @@ Report bugs and patches to ." version="\ GNU config.sub ($timestamp) -Copyright 1992-2021 Free Software Foundation, Inc. +Copyright 1992-2024 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" -Try \`$me --help' for more information." +Try '$me --help' for more information." # Parse command line while test $# -gt 0 ; do @@ -111,15 +120,16 @@ case $# in esac # Split fields of configuration type -# shellcheck disable=SC2162 +saved_IFS=$IFS IFS="-" read field1 field2 field3 field4 <&2 + echo "Invalid configuration '$1': more than four components" >&2 exit 1 ;; *-*-*-*) @@ -131,10 +141,21 @@ case $1 in # parts maybe_os=$field2-$field3 case $maybe_os in - nto-qnx* | linux-* | uclinux-uclibc* \ - | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* \ - | netbsd*-eabi* | kopensolaris*-gnu* | cloudabi*-eabi* \ - | storm-chaos* | os2-emx* | rtmk-nova*) + cloudabi*-eabi* \ + | kfreebsd*-gnu* \ + | knetbsd*-gnu* \ + | kopensolaris*-gnu* \ + | linux-* \ + | managarm-* \ + | netbsd*-eabi* \ + | netbsd*-gnu* \ + | nto-qnx* \ + | os2-emx* \ + | rtmk-nova* \ + | storm-chaos* \ + | uclinux-gnu* \ + | uclinux-uclibc* \ + | windows-* ) basic_machine=$field1 basic_os=$maybe_os ;; @@ -149,8 +170,12 @@ case $1 in esac ;; *-*) - # A lone config we happen to match not fitting any pattern case $field1-$field2 in + # Shorthands that happen to contain a single dash + convex-c[12] | convex-c3[248]) + basic_machine=$field2-convex + basic_os= + ;; decstation-3100) basic_machine=mips-dec basic_os= @@ -158,24 +183,88 @@ case $1 in *-*) # Second component is usually, but not always the OS case $field2 in - # Prevent following clause from handling this valid os + # Do not treat sunos as a manufacturer sun*os*) basic_machine=$field1 basic_os=$field2 ;; # Manufacturers - dec* | mips* | sequent* | encore* | pc533* | sgi* | sony* \ - | att* | 7300* | 3300* | delta* | motorola* | sun[234]* \ - | unicom* | ibm* | next | hp | isi* | apollo | altos* \ - | convergent* | ncr* | news | 32* | 3600* | 3100* \ - | hitachi* | c[123]* | convex* | sun | crds | omron* | dg \ - | ultra | tti* | harris | dolphin | highlevel | gould \ - | cbm | ns | masscomp | apple | axis | knuth | cray \ - | microblaze* | sim | cisco \ - | oki | wec | wrs | winbond) + 3100* \ + | 32* \ + | 3300* \ + | 3600* \ + | 7300* \ + | acorn \ + | altos* \ + | apollo \ + | apple \ + | atari \ + | att* \ + | axis \ + | be \ + | bull \ + | cbm \ + | ccur \ + | cisco \ + | commodore \ + | convergent* \ + | convex* \ + | cray \ + | crds \ + | dec* \ + | delta* \ + | dg \ + | digital \ + | dolphin \ + | encore* \ + | gould \ + | harris \ + | highlevel \ + | hitachi* \ + | hp \ + | ibm* \ + | intergraph \ + | isi* \ + | knuth \ + | masscomp \ + | microblaze* \ + | mips* \ + | motorola* \ + | ncr* \ + | news \ + | next \ + | ns \ + | oki \ + | omron* \ + | pc533* \ + | rebel \ + | rom68k \ + | rombug \ + | semi \ + | sequent* \ + | siemens \ + | sgi* \ + | siemens \ + | sim \ + | sni \ + | sony* \ + | stratus \ + | sun \ + | sun[234]* \ + | tektronix \ + | tti* \ + | ultra \ + | unicom* \ + | wec \ + | winbond \ + | wrs) basic_machine=$field1-$field2 basic_os= ;; + zephyr*) + basic_machine=$field1-unknown + basic_os=$field2 + ;; *) basic_machine=$field1 basic_os=$field2 @@ -256,26 +345,6 @@ case $1 in basic_machine=arm-unknown basic_os=cegcc ;; - convex-c1) - basic_machine=c1-convex - basic_os=bsd - ;; - convex-c2) - basic_machine=c2-convex - basic_os=bsd - ;; - convex-c32) - basic_machine=c32-convex - basic_os=bsd - ;; - convex-c34) - basic_machine=c34-convex - basic_os=bsd - ;; - convex-c38) - basic_machine=c38-convex - basic_os=bsd - ;; cray) basic_machine=j90-cray basic_os=unicos @@ -698,15 +767,26 @@ case $basic_machine in vendor=dec basic_os=tops20 ;; - delta | 3300 | motorola-3300 | motorola-delta \ - | 3300-motorola | delta-motorola) + delta | 3300 | delta-motorola | 3300-motorola | motorola-delta | motorola-3300) cpu=m68k vendor=motorola ;; - dpx2*) + # This used to be dpx2*, but that gets the RS6000-based + # DPX/20 and the x86-based DPX/2-100 wrong. See + # https://oldskool.silicium.org/stations/bull_dpx20.htm + # https://www.feb-patrimoine.com/english/bull_dpx2.htm + # https://www.feb-patrimoine.com/english/unix_and_bull.htm + dpx2 | dpx2[23]00 | dpx2[23]xx) cpu=m68k vendor=bull - basic_os=sysv3 + ;; + dpx2100 | dpx21xx) + cpu=i386 + vendor=bull + ;; + dpx20) + cpu=rs6000 + vendor=bull ;; encore | umax | mmax) cpu=ns32k @@ -769,22 +849,22 @@ case $basic_machine in vendor=hp ;; i*86v32) - cpu=$(echo "$1" | sed -e 's/86.*/86/') + cpu=`echo "$1" | sed -e 's/86.*/86/'` vendor=pc basic_os=sysv32 ;; i*86v4*) - cpu=$(echo "$1" | sed -e 's/86.*/86/') + cpu=`echo "$1" | sed -e 's/86.*/86/'` vendor=pc basic_os=sysv4 ;; i*86v) - cpu=$(echo "$1" | sed -e 's/86.*/86/') + cpu=`echo "$1" | sed -e 's/86.*/86/'` vendor=pc basic_os=sysv ;; i*86sol2) - cpu=$(echo "$1" | sed -e 's/86.*/86/') + cpu=`echo "$1" | sed -e 's/86.*/86/'` vendor=pc basic_os=solaris2 ;; @@ -821,18 +901,6 @@ case $basic_machine in next | m*-next) cpu=m68k vendor=next - case $basic_os in - openstep*) - ;; - nextstep*) - ;; - ns2*) - basic_os=nextstep2 - ;; - *) - basic_os=nextstep3 - ;; - esac ;; np1) cpu=np1 @@ -917,16 +985,17 @@ case $basic_machine in ;; leon-*|leon[3-9]-*) cpu=sparc - vendor=$(echo "$basic_machine" | sed 's/-.*//') + vendor=`echo "$basic_machine" | sed 's/-.*//'` ;; *-*) - # shellcheck disable=SC2162 + saved_IFS=$IFS IFS="-" read cpu vendor <&2 + echo "Invalid configuration '$1': machine '$cpu-$vendor' not recognized" 1>&2 exit 1 ;; esac @@ -1284,38 +1491,44 @@ esac # Decode manufacturer-specific aliases for certain operating systems. -if test x$basic_os != x +if test x"$basic_os" != x then -# First recognize some ad-hoc caes, or perhaps split kernel-os, or else just +# First recognize some ad-hoc cases, or perhaps split kernel-os, or else just # set os. +obj= case $basic_os in gnu/linux*) kernel=linux - os=$(echo $basic_os | sed -e 's|gnu/linux|gnu|') + os=`echo "$basic_os" | sed -e 's|gnu/linux|gnu|'` ;; os2-emx) kernel=os2 - os=$(echo $basic_os | sed -e 's|os2-emx|emx|') + os=`echo "$basic_os" | sed -e 's|os2-emx|emx|'` ;; nto-qnx*) kernel=nto - os=$(echo $basic_os | sed -e 's|nto-qnx|qnx|') + os=`echo "$basic_os" | sed -e 's|nto-qnx|qnx|'` ;; *-*) - # shellcheck disable=SC2162 + saved_IFS=$IFS IFS="-" read kernel os <&2 + fi + ;; *) - echo Invalid configuration \`"$1"\': OS \`"$os"\' not recognized 1>&2 + echo "Invalid configuration '$1': OS '$os' not recognized" 1>&2 + exit 1 + ;; +esac + +case $obj in + aout* | coff* | elf* | pe*) + ;; + '') + # empty is fine + ;; + *) + echo "Invalid configuration '$1': Machine code format '$obj' not recognized" 1>&2 + exit 1 + ;; +esac + +# Here we handle the constraint that a (synthetic) cpu and os are +# valid only in combination with each other and nowhere else. +case $cpu-$os in + # The "javascript-unknown-ghcjs" triple is used by GHC; we + # accept it here in order to tolerate that, but reject any + # variations. + javascript-ghcjs) + ;; + javascript-* | *-ghcjs) + echo "Invalid configuration '$1': cpu '$cpu' is not valid with os '$os$obj'" 1>&2 exit 1 ;; esac # As a final step for OS-related things, validate the OS-kernel combination # (given a valid OS), if there is a kernel. -case $kernel-$os in - linux-gnu* | linux-dietlibc* | linux-android* | linux-newlib* | linux-musl* | linux-uclibc* ) +case $kernel-$os-$obj in + linux-gnu*- | linux-android*- | linux-dietlibc*- | linux-llvm*- \ + | linux-mlibc*- | linux-musl*- | linux-newlib*- \ + | linux-relibc*- | linux-uclibc*- | linux-ohos*- ) + ;; + uclinux-uclibc*- | uclinux-gnu*- ) + ;; + managarm-mlibc*- | managarm-kernel*- ) ;; - uclinux-uclibc* ) + windows*-msvc*-) ;; - -dietlibc* | -newlib* | -musl* | -uclibc* ) + -dietlibc*- | -llvm*- | -mlibc*- | -musl*- | -newlib*- | -relibc*- \ + | -uclibc*- ) # These are just libc implementations, not actual OSes, and thus # require a kernel. - echo "Invalid configuration \`$1': libc \`$os' needs explicit kernel." 1>&2 + echo "Invalid configuration '$1': libc '$os' needs explicit kernel." 1>&2 exit 1 ;; - kfreebsd*-gnu* | kopensolaris*-gnu*) + -kernel*- ) + echo "Invalid configuration '$1': '$os' needs explicit kernel." 1>&2 + exit 1 ;; - vxworks-simlinux | vxworks-simwindows | vxworks-spe) + *-kernel*- ) + echo "Invalid configuration '$1': '$kernel' does not support '$os'." 1>&2 + exit 1 ;; - nto-qnx*) + *-msvc*- ) + echo "Invalid configuration '$1': '$os' needs 'windows'." 1>&2 + exit 1 ;; - os2-emx) + kfreebsd*-gnu*- | knetbsd*-gnu*- | netbsd*-gnu*- | kopensolaris*-gnu*-) + ;; + vxworks-simlinux- | vxworks-simwindows- | vxworks-spe-) + ;; + nto-qnx*-) ;; - *-eabi* | *-gnueabi*) + os2-emx-) ;; - -*) + rtmk-nova-) + ;; + *-eabi*- | *-gnueabi*-) + ;; + none--*) + # None (no kernel, i.e. freestanding / bare metal), + # can be paired with an machine code file format + ;; + -*-) # Blank kernel with real OS is always fine. ;; - *-*) - echo "Invalid configuration \`$1': Kernel \`$kernel' not known to work with OS \`$os'." 1>&2 + --*) + # Blank kernel and OS with real machine code file format is always fine. + ;; + *-*-*) + echo "Invalid configuration '$1': Kernel '$kernel' not known to work with OS '$os'." 1>&2 exit 1 ;; esac @@ -1783,7 +2273,7 @@ case $vendor in *-riscix*) vendor=acorn ;; - *-sunos*) + *-sunos* | *-solaris*) vendor=sun ;; *-cnk* | *-aix*) @@ -1853,7 +2343,7 @@ case $vendor in ;; esac -echo "$cpu-$vendor-${kernel:+$kernel-}$os" +echo "$cpu-$vendor${kernel:+-$kernel}${os:+-$os}${obj:+-$obj}" exit # Local variables: diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 859ac1af28..65e26441eb 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -8,7 +8,7 @@ $(package)_dependencies=native_b2 define $(package)_set_vars $(package)_config_opts_release=variant=release $(package)_config_opts_debug=variant=debug -$(package)_config_opts=--layout=tagged --build-type=complete --user-config=user-config.jam +$(package)_config_opts=--layout=system --user-config=user-config.jam $(package)_config_opts+=threading=multi link=static -sNO_COMPRESSION=1 $(package)_config_opts_linux=target-os=linux threadapi=pthread runtime-link=shared $(package)_config_opts_darwin=target-os=darwin runtime-link=shared @@ -22,7 +22,7 @@ $(package)_toolset_$(host_os)=clang else $(package)_toolset_$(host_os)=gcc endif -$(package)_config_libraries=chrono,filesystem,program_options,system,thread,test +$(package)_config_libraries=atomic,chrono,filesystem,program_options,system,thread,test $(package)_cxxflags+=-std=c++17 $(package)_cxxflags_linux=-fPIC $(package)_cxxflags_android=-fPIC diff --git a/depends/packages/dbus.mk b/depends/packages/dbus.mk index 90ddcb923f..4a67f26b2e 100644 --- a/depends/packages/dbus.mk +++ b/depends/packages/dbus.mk @@ -1,12 +1,12 @@ package=dbus -$(package)_version=1.10.14 -$(package)_download_path=http://dbus.freedesktop.org/releases/dbus -$(package)_file_name=$(package)-$($(package)_version).tar.gz -$(package)_sha256_hash=23238f70353e38ce5ca183ebc9525c0d97ac00ef640ad29cf794782af6e6a083 +$(package)_version=1.16.2 +$(package)_download_path=https://dbus.freedesktop.org/releases/dbus +$(package)_file_name=$(package)-$($(package)_version).tar.xz +$(package)_sha256_hash=0ba2a1a4b16afe7bceb2c07e9ce99a8c2c3508e5dec290dbb643384bd6beb7e2 $(package)_dependencies=expat define $(package)_set_vars - $(package)_config_opts=--disable-tests --disable-doxygen-docs --disable-xml-docs --disable-static --without-x + $(package)_config_opts=--disable-tests --disable-doxygen-docs --disable-xml-docs --without-x endef define $(package)_config_cmds diff --git a/depends/packages/expat.mk b/depends/packages/expat.mk index 08804dae55..768b4c25bc 100644 --- a/depends/packages/expat.mk +++ b/depends/packages/expat.mk @@ -1,11 +1,11 @@ package=expat -$(package)_version=2.1.1 -$(package)_download_path=https://github.com/libexpat/libexpat/releases/download/R_2_2_6/ +$(package)_version=2.7.1 +$(package)_download_path=https://github.com/libexpat/libexpat/releases/download/R_2_7_1/ $(package)_file_name=$(package)-$($(package)_version).tar.bz2 -$(package)_sha256_hash=aff584e5a2f759dcfc6d48671e9529f6afe1e30b0cd6a4cec200cbe3f793de67 +$(package)_sha256_hash=45c98ae1e9b5127325d25186cf8c511fa814078e9efeae7987a574b482b79b3d define $(package)_set_vars -$(package)_config_opts=--disable-static +$(package)_config_opts= endef define $(package)_config_cmds diff --git a/depends/packages/fontconfig.mk b/depends/packages/fontconfig.mk index 128599ba77..854c13d308 100644 --- a/depends/packages/fontconfig.mk +++ b/depends/packages/fontconfig.mk @@ -6,7 +6,7 @@ $(package)_sha256_hash=b449a3e10c47e1d1c7a6ec6e2016cca73d3bd68fbbd4f0ae5cc6b573f $(package)_dependencies=freetype expat define $(package)_set_vars - $(package)_config_opts=--disable-docs --disable-static --disable-libxml2 --disable-iconv + $(package)_config_opts=--disable-docs --enable-static --disable-libxml2 --disable-iconv $(package)_config_opts += --disable-dependency-tracking --enable-option-checking endef diff --git a/depends/packages/freetype.mk b/depends/packages/freetype.mk index a1584608e1..50a4c83654 100644 --- a/depends/packages/freetype.mk +++ b/depends/packages/freetype.mk @@ -1,11 +1,11 @@ package=freetype -$(package)_version=2.7.1 +$(package)_version=2.13.3 $(package)_download_path=https://download.savannah.gnu.org/releases/$(package) -$(package)_file_name=$(package)-$($(package)_version).tar.bz2 -$(package)_sha256_hash=3a3bb2c4e15ffb433f2032f50a5b5a92558206822e22bfe8cbe339af4aa82f88 +$(package)_file_name=$(package)-$($(package)_version).tar.xz +$(package)_sha256_hash=0550350666d427c74daeb85d5ac7bb353acba5f76956395995311a9c6f063289 define $(package)_set_vars - $(package)_config_opts=--without-zlib --without-png --without-harfbuzz --without-bzip2 --disable-static + $(package)_config_opts=--without-zlib --without-png --without-harfbuzz --without-bzip2 $(package)_config_opts += --enable-option-checking $(package)_config_opts_linux=--with-pic endef diff --git a/depends/packages/gmp.mk b/depends/packages/gmp.mk index b1659aa16a..86d6d94a7f 100644 --- a/depends/packages/gmp.mk +++ b/depends/packages/gmp.mk @@ -9,6 +9,7 @@ define $(package)_set_vars $(package)_config_opts+=--enable-cxx --enable-fat --with-pic --disable-shared $(package)_cflags_armv7l_linux+=-march=armv7-a $(package)_config_opts_arm_darwin+=--build=$(subst arm,aarch64,$(BUILD)) --host=$(subst arm,aarch64,$(HOST)) +$(package)_config_opts_mingw32+=CC_FOR_BUILD=gcc gmp_cv_prog_exeext_for_build= endef define $(package)_config_cmds diff --git a/depends/packages/libICE.mk b/depends/packages/libICE.mk index fc60323b1c..c391a6a42b 100644 --- a/depends/packages/libICE.mk +++ b/depends/packages/libICE.mk @@ -1,12 +1,12 @@ package=libICE -$(package)_version=1.0.9 +$(package)_version=1.1.2 $(package)_download_path=http://xorg.freedesktop.org/releases/individual/lib/ -$(package)_file_name=$(package)-$($(package)_version).tar.bz2 -$(package)_sha256_hash=8f7032f2c1c64352b5423f6b48a8ebdc339cc63064af34d66a6c9aa79759e202 +$(package)_file_name=$(package)-$($(package)_version).tar.xz +$(package)_sha256_hash=974e4ed414225eb3c716985df9709f4da8d22a67a2890066bc6dfc89ad298625 $(package)_dependencies=xtrans xproto define $(package)_set_vars - $(package)_config_opts=--disable-static --disable-docs --disable-specs --without-xsltproc + $(package)_config_opts=--disable-docs --disable-specs --without-xsltproc $(package)_config_opts_linux=--with-pic endef diff --git a/depends/packages/libSM.mk b/depends/packages/libSM.mk index 0f9307ca76..2cefd9164f 100644 --- a/depends/packages/libSM.mk +++ b/depends/packages/libSM.mk @@ -1,12 +1,12 @@ package=libSM -$(package)_version=1.2.2 +$(package)_version=1.2.6 $(package)_download_path=http://xorg.freedesktop.org/releases/individual/lib/ -$(package)_file_name=$(package)-$($(package)_version).tar.bz2 -$(package)_sha256_hash=0baca8c9f5d934450a70896c4ad38d06475521255ca63b717a6510fdb6e287bd +$(package)_file_name=$(package)-$($(package)_version).tar.xz +$(package)_sha256_hash=be7c0abdb15cbfd29ac62573c1c82e877f9d4047ad15321e7ea97d1e43d835be $(package)_dependencies=xtrans xproto libICE define $(package)_set_vars - $(package)_config_opts=--without-libuuid --without-xsltproc --disable-docs --disable-static + $(package)_config_opts=--without-libuuid --without-xsltproc --disable-docs $(package)_config_opts_linux=--with-pic endef diff --git a/depends/packages/libX11.mk b/depends/packages/libX11.mk index 178d592ee6..22c8d0b79b 100644 --- a/depends/packages/libX11.mk +++ b/depends/packages/libX11.mk @@ -1,12 +1,12 @@ package=libX11 -$(package)_version=1.6.2 +$(package)_version=1.8.12 $(package)_download_path=http://xorg.freedesktop.org/releases/individual/lib/ -$(package)_file_name=$(package)-$($(package)_version).tar.bz2 -$(package)_sha256_hash=2aa027e837231d2eeea90f3a4afe19948a6eb4c8b2bec0241eba7dbc8106bd16 +$(package)_file_name=$(package)-$($(package)_version).tar.xz +$(package)_sha256_hash=fa026f9bb0124f4d6c808f9aef4057aad65e7b35d8ff43951cef0abe06bb9a9a $(package)_dependencies=libxcb xtrans xextproto xproto define $(package)_set_vars -$(package)_config_opts=--disable-xkb --disable-static +$(package)_config_opts=--disable-xkb $(package)_config_opts_linux=--with-pic endef diff --git a/depends/packages/libXau.mk b/depends/packages/libXau.mk index e87df2e4de..ca0be3fabe 100644 --- a/depends/packages/libXau.mk +++ b/depends/packages/libXau.mk @@ -1,8 +1,8 @@ package=libXau -$(package)_version=1.0.8 +$(package)_version=1.0.12 $(package)_download_path=http://xorg.freedesktop.org/releases/individual/lib/ -$(package)_file_name=$(package)-$($(package)_version).tar.bz2 -$(package)_sha256_hash=fdd477320aeb5cdd67272838722d6b7d544887dfe7de46e1e7cc0c27c2bea4f2 +$(package)_file_name=$(package)-$($(package)_version).tar.xz +$(package)_sha256_hash=74d0e4dfa3d39ad8939e99bda37f5967aba528211076828464d2777d477fc0fb $(package)_dependencies=xproto define $(package)_set_vars diff --git a/depends/packages/libXext.mk b/depends/packages/libXext.mk index 4db836066f..6b031737b3 100644 --- a/depends/packages/libXext.mk +++ b/depends/packages/libXext.mk @@ -1,12 +1,12 @@ package=libXext -$(package)_version=1.3.2 +$(package)_version=1.3.6 $(package)_download_path=http://xorg.freedesktop.org/releases/individual/lib/ -$(package)_file_name=$(package)-$($(package)_version).tar.bz2 -$(package)_sha256_hash=f829075bc646cdc085fa25d98d5885d83b1759ceb355933127c257e8e50432e0 +$(package)_file_name=$(package)-$($(package)_version).tar.xz +$(package)_sha256_hash=edb59fa23994e405fdc5b400afdf5820ae6160b94f35e3dc3da4457a16e89753 $(package)_dependencies=xproto xextproto libX11 libXau define $(package)_set_vars - $(package)_config_opts=--disable-static + $(package)_config_opts= endef define $(package)_config_cmds diff --git a/depends/packages/libxcb.mk b/depends/packages/libxcb.mk index 036eaf6560..5bbcab8437 100644 --- a/depends/packages/libxcb.mk +++ b/depends/packages/libxcb.mk @@ -7,7 +7,7 @@ $(package)_dependencies=xcb_proto libXau $(package)_patches = remove_pthread_stubs.patch define $(package)_set_vars -$(package)_config_opts=--disable-static --disable-devel-docs --without-doxygen --without-launchd +$(package)_config_opts=--disable-devel-docs --without-doxygen --without-launchd $(package)_config_opts += --disable-dependency-tracking --enable-option-checking # Disable unneeded extensions. # More info is available from: https://doc.qt.io/qt-5.15/linux-requirements.html diff --git a/depends/packages/libxcb_util.mk b/depends/packages/libxcb_util.mk index 6f1b9cd7c6..5fad32a884 100644 --- a/depends/packages/libxcb_util.mk +++ b/depends/packages/libxcb_util.mk @@ -1,8 +1,8 @@ package=libxcb_util -$(package)_version=0.4.0 +$(package)_version=0.4.1 $(package)_download_path=https://xcb.freedesktop.org/dist -$(package)_file_name=xcb-util-$($(package)_version).tar.bz2 -$(package)_sha256_hash=46e49469cb3b594af1d33176cd7565def2be3fa8be4371d62271fabb5eae50e9 +$(package)_file_name=xcb-util-$($(package)_version).tar.xz +$(package)_sha256_hash=5abe3bbbd8e54f0fa3ec945291b7e8fa8cfd3cccc43718f8758430f94126e512 $(package)_dependencies=libxcb define $(package)_set_vars diff --git a/depends/packages/libxcb_util_image.mk b/depends/packages/libxcb_util_image.mk index d12d67e8e8..fe8891ccab 100644 --- a/depends/packages/libxcb_util_image.mk +++ b/depends/packages/libxcb_util_image.mk @@ -1,12 +1,12 @@ package=libxcb_util_image -$(package)_version=0.4.0 +$(package)_version=0.4.1 $(package)_download_path=https://xcb.freedesktop.org/dist -$(package)_file_name=xcb-util-image-$($(package)_version).tar.bz2 -$(package)_sha256_hash=2db96a37d78831d643538dd1b595d7d712e04bdccf8896a5e18ce0f398ea2ffc +$(package)_file_name=xcb-util-image-$($(package)_version).tar.xz +$(package)_sha256_hash=ccad8ee5dadb1271fd4727ad14d9bd77a64e505608766c4e98267d9aede40d3d $(package)_dependencies=libxcb libxcb_util define $(package)_set_vars -$(package)_config_opts=--disable-static --disable-devel-docs --without-doxygen +$(package)_config_opts=--disable-devel-docs --without-doxygen $(package)_config_opts+= --disable-dependency-tracking --enable-option-checking endef diff --git a/depends/packages/libxcb_util_keysyms.mk b/depends/packages/libxcb_util_keysyms.mk index d4f72dedbe..b114fbed7e 100644 --- a/depends/packages/libxcb_util_keysyms.mk +++ b/depends/packages/libxcb_util_keysyms.mk @@ -1,12 +1,12 @@ package=libxcb_util_keysyms -$(package)_version=0.4.0 +$(package)_version=0.4.1 $(package)_download_path=https://xcb.freedesktop.org/dist -$(package)_file_name=xcb-util-keysyms-$($(package)_version).tar.bz2 -$(package)_sha256_hash=0ef8490ff1dede52b7de533158547f8b454b241aa3e4dcca369507f66f216dd9 +$(package)_file_name=xcb-util-keysyms-$($(package)_version).tar.xz +$(package)_sha256_hash=7c260a5294412aed429df1da2f8afd3bd07b7cba3fec772fba15a613a6d5c638 $(package)_dependencies=libxcb xproto define $(package)_set_vars -$(package)_config_opts=--disable-static --disable-devel-docs --without-doxygen +$(package)_config_opts=--disable-devel-docs --without-doxygen $(package)_config_opts += --disable-dependency-tracking --enable-option-checking endef diff --git a/depends/packages/libxcb_util_render.mk b/depends/packages/libxcb_util_render.mk index 28f1fb073c..905f932239 100644 --- a/depends/packages/libxcb_util_render.mk +++ b/depends/packages/libxcb_util_render.mk @@ -1,12 +1,12 @@ package=libxcb_util_render -$(package)_version=0.3.9 +$(package)_version=0.3.10 $(package)_download_path=https://xcb.freedesktop.org/dist -$(package)_file_name=xcb-util-renderutil-$($(package)_version).tar.bz2 -$(package)_sha256_hash=c6e97e48fb1286d6394dddb1c1732f00227c70bd1bedb7d1acabefdd340bea5b +$(package)_file_name=xcb-util-renderutil-$($(package)_version).tar.xz +$(package)_sha256_hash=3e15d4f0e22d8ddbfbb9f5d77db43eacd7a304029bf25a6166cc63caa96d04ba $(package)_dependencies=libxcb define $(package)_set_vars -$(package)_config_opts=--disable-static --disable-devel-docs --without-doxygen +$(package)_config_opts=--disable-devel-docs --without-doxygen $(package)_config_opts += --disable-dependency-tracking --enable-option-checking endef diff --git a/depends/packages/libxcb_util_wm.mk b/depends/packages/libxcb_util_wm.mk index 3b905ba4ec..f80f0eb27d 100644 --- a/depends/packages/libxcb_util_wm.mk +++ b/depends/packages/libxcb_util_wm.mk @@ -1,12 +1,12 @@ package=libxcb_util_wm -$(package)_version=0.4.1 +$(package)_version=0.4.2 $(package)_download_path=https://xcb.freedesktop.org/dist -$(package)_file_name=xcb-util-wm-$($(package)_version).tar.bz2 -$(package)_sha256_hash=28bf8179640eaa89276d2b0f1ce4285103d136be6c98262b6151aaee1d3c2a3f +$(package)_file_name=xcb-util-wm-$($(package)_version).tar.xz +$(package)_sha256_hash=62c34e21d06264687faea7edbf63632c9f04d55e72114aa4a57bb95e4f888a0b $(package)_dependencies=libxcb define $(package)_set_vars -$(package)_config_opts=--disable-static --disable-devel-docs --without-doxygen +$(package)_config_opts=--disable-devel-docs --without-doxygen $(package)_config_opts += --disable-dependency-tracking --enable-option-checking endef diff --git a/depends/packages/libxkbcommon.mk b/depends/packages/libxkbcommon.mk index bcdcf671f7..b8634e9aa5 100644 --- a/depends/packages/libxkbcommon.mk +++ b/depends/packages/libxkbcommon.mk @@ -11,7 +11,7 @@ $(package)_dependencies=libxcb # a different build system (Meson) define $(package)_set_vars $(package)_config_opts = --enable-option-checking --disable-dependency-tracking -$(package)_config_opts += --disable-static --disable-docs +$(package)_config_opts += --disable-docs $(package)_cflags += -Wno-error=array-bounds endef diff --git a/depends/packages/native_ccache.mk b/depends/packages/native_ccache.mk index 4ed61a49e9..b098455c44 100644 --- a/depends/packages/native_ccache.mk +++ b/depends/packages/native_ccache.mk @@ -1,8 +1,8 @@ package=native_ccache -$(package)_version=3.3.3 +$(package)_version=3.6 $(package)_download_path=https://samba.org/ftp/ccache $(package)_file_name=ccache-$($(package)_version).tar.bz2 -$(package)_sha256_hash=2985bc5e32ebe38d2958d508eb54ddcad39eed909489c0c2988035214597ca54 +$(package)_sha256_hash=c23ecf1253e0d12c9da9dda9567a88a606d46f93d9982b8b1a423d6f238bd435 define $(package)_set_vars $(package)_config_opts= diff --git a/depends/packages/native_cctools.mk b/depends/packages/native_cctools.mk index d169eb6723..06df35cef1 100644 --- a/depends/packages/native_cctools.mk +++ b/depends/packages/native_cctools.mk @@ -1,8 +1,8 @@ package=native_cctools -$(package)_version=2ef2e931cf641547eb8a68cfebde61003587c9fd +$(package)_version=877.8-ld64-253.9-1 $(package)_download_path=https://github.com/tpoechtrager/cctools-port/archive -$(package)_file_name=$($(package)_version).tar.gz -$(package)_sha256_hash=6b73269efdf5c58a070e7357b66ee760501388549d6a12b423723f45888b074b +$(package)_file_name=cctools-$($(package)_version).tar.gz +$(package)_sha256_hash=c88b0631b1d7bb5186dd6466a62f5220dc6191f2b2d9c7c122b327385e734aaf $(package)_build_subdir=cctools $(package)_dependencies=native_libtapi diff --git a/depends/packages/native_clang.mk b/depends/packages/native_clang.mk index 25ac77c1a3..9792038cf3 100644 --- a/depends/packages/native_clang.mk +++ b/depends/packages/native_clang.mk @@ -1,14 +1,14 @@ package=native_clang -$(package)_version=10.0.1 +$(package)_version=19.1.7 $(package)_download_path=https://github.com/llvm/llvm-project/releases/download/llvmorg-$($(package)_version) ifneq (,$(findstring aarch64,$(BUILD))) $(package)_download_file=clang+llvm-$($(package)_version)-aarch64-linux-gnu.tar.xz $(package)_file_name=clang+llvm-$($(package)_version)-aarch64-linux-gnu.tar.xz -$(package)_sha256_hash=90dc69a4758ca15cd0ffa45d07fbf5bf4309d47d2c7745a9f0735ecffde9c31f +$(package)_sha256_hash=a73d9326e5d756e3937df6a9f621664d76403b59119f741901106b387e53a6ae else -$(package)_download_file=clang+llvm-$($(package)_version)-x86_64-linux-gnu-ubuntu-16.04.tar.xz -$(package)_file_name=clang+llvm-$($(package)_version)-x86_64-linux-gnu-ubuntu-16.04.tar.xz -$(package)_sha256_hash=48b83ef827ac2c213d5b64f5ad7ed082c8bcb712b46644e0dc5045c6f462c231 +$(package)_download_file=LLVM-$($(package)_version)-Linux-X64.tar.xz +$(package)_file_name=LLVM-$($(package)_version)-Linux-X64.tar.xz +$(package)_sha256_hash=4a5ec53951a584ed36f80240f6fbf8fdd46b4cf6c7ee87cc2d5018dc37caf679 endif define $(package)_preprocess_cmds diff --git a/depends/packages/native_protobuf.mk b/depends/packages/native_protobuf.mk index 1de8c37d36..c0736e1574 100644 --- a/depends/packages/native_protobuf.mk +++ b/depends/packages/native_protobuf.mk @@ -1,8 +1,8 @@ package=native_protobuf -$(package)_version=2.6.1 +$(package)_version=30.2 $(package)_download_path=https://github.com/google/protobuf/releases/download/v$($(package)_version) -$(package)_file_name=protobuf-$($(package)_version).tar.bz2 -$(package)_sha256_hash=ee445612d544d885ae240ffbcbf9267faa9f593b7b101f21d58beceb92661910 +$(package)_file_name=protobuf-$($(package)_version).tar.gz +$(package)_sha256_hash=fb06709acc393cc36f87c251bb28a5500a2e12936d4346099f2c6240f6c7a941 define $(package)_set_vars $(package)_config_opts=--disable-shared --without-zlib diff --git a/depends/packages/packages.mk b/depends/packages/packages.mk index 574bf3b276..3d8aa4aa16 100644 --- a/depends/packages/packages.mk +++ b/depends/packages/packages.mk @@ -10,6 +10,9 @@ qt_mingw32_packages=qt bdb_packages=bdb sqlite_packages=sqlite +qrencode_packages=qrencode + +zmq_packages=zeromq upnp_packages=miniupnpc diff --git a/depends/packages/qrencode.mk b/depends/packages/qrencode.mk index 8ca42bf60e..71275858d7 100644 --- a/depends/packages/qrencode.mk +++ b/depends/packages/qrencode.mk @@ -1,20 +1,24 @@ package=qrencode -$(package)_version=3.4.4 +$(package)_version=4.1.1 $(package)_download_path=https://fukuchi.org/works/qrencode/ -$(package)_file_name=qrencode-$(qrencode_version).tar.bz2 -$(package)_sha256_hash=efe5188b1ddbcbf98763b819b146be6a90481aac30cfc8d858ab78a19cde1fa5 +$(package)_file_name=$(package)-$($(package)_version).tar.gz +$(package)_sha256_hash=da448ed4f52aba6bcb0cd48cac0dd51b8692bccc4cd127431402fca6f8171e8e +$(package)_patches=cmake_fixups.patch define $(package)_set_vars -$(package)_config_opts=--disable-shared -without-tools --disable-sdltest -$(package)_config_opts_linux=--with-pic +$(package)_config_opts := -DWITH_TOOLS=NO -DWITH_TESTS=NO -DGPROF=OFF -DCOVERAGE=OFF +$(package)_config_opts += -DCMAKE_DISABLE_FIND_PACKAGE_PNG=TRUE -DWITHOUT_PNG=ON +$(package)_config_opts += -DCMAKE_DISABLE_FIND_PACKAGE_ICONV=TRUE +$(package)_cflags += -Wno-int-conversion -Wno-implicit-function-declaration endef define $(package)_preprocess_cmds - cp -f $(BASEDIR)/config.guess $(BASEDIR)/config.sub use + patch -p1 < $($(package)_patch_dir)/cmake_fixups.patch endef + define $(package)_config_cmds - $($(package)_autoconf) + $($(package)_cmake) -S . -B . endef define $(package)_build_cmds @@ -24,3 +28,7 @@ endef define $(package)_stage_cmds $(MAKE) DESTDIR=$($(package)_staging_dir) install endef + +define $(package)_postprocess_cmds + rm -rf share +endef \ No newline at end of file diff --git a/depends/packages/qt.mk b/depends/packages/qt.mk index 039d15bcb8..12e1d388d3 100644 --- a/depends/packages/qt.mk +++ b/depends/packages/qt.mk @@ -24,6 +24,7 @@ $(package)_patches += guix_cross_lib_path.patch $(package)_patches += fix-macos-linker.patch $(package)_patches += memory_resource.patch $(package)_patches += windows_lto.patch +$(package)_patches += fix-libpng.patch $(package)_qttranslations_file_name=qttranslations-$($(package)_suffix) $(package)_qttranslations_sha256_hash=a31785948c640b7c66d9fe2db4993728ca07f64e41c560b3625ad191b276ff20 @@ -52,6 +53,7 @@ $(package)_config_opts += -no-evdev $(package)_config_opts += -no-gif $(package)_config_opts += -no-glib $(package)_config_opts += -no-icu +$(package)_config_opts += -no-zstd $(package)_config_opts += -no-ico $(package)_config_opts += -no-iconv $(package)_config_opts += -no-kms @@ -249,6 +251,7 @@ define $(package)_preprocess_cmds patch -p1 -i $($(package)_patch_dir)/fast_fixed_dtoa_no_optimize.patch && \ patch -p1 -i $($(package)_patch_dir)/guix_cross_lib_path.patch && \ patch -p1 -i $($(package)_patch_dir)/windows_lto.patch && \ + patch -p1 -i $($(package)_patch_dir)/fix-libpng.patch && \ mkdir -p qtbase/mkspecs/macx-clang-linux &&\ cp -f qtbase/mkspecs/macx-clang/qplatformdefs.h qtbase/mkspecs/macx-clang-linux/ &&\ cp -f $($(package)_patch_dir)/mac-qmake.conf qtbase/mkspecs/macx-clang-linux/qmake.conf && \ @@ -276,12 +279,11 @@ define $(package)_build_cmds endef define $(package)_stage_cmds - $(MAKE) -C qtbase/src INSTALL_ROOT=$($(package)_staging_dir) $(addsuffix -install_subtargets,$(addprefix sub-,$($(package)_qt_libs))) && \ - $(MAKE) -C qttools/src/linguist INSTALL_ROOT=$($(package)_staging_dir) $(addsuffix -install_subtargets,$(addprefix sub-,$($(package)_linguist_tools))) && \ + $(MAKE) -C qtbase INSTALL_ROOT=$($(package)_staging_dir) install && \ + $(MAKE) -C qttools INSTALL_ROOT=$($(package)_staging_dir) install && \ $(MAKE) -C qttranslations INSTALL_ROOT=$($(package)_staging_dir) install_subtargets endef define $(package)_postprocess_cmds - rm -rf native/mkspecs/ native/lib/ lib/cmake/ && \ rm -f lib/lib*.la endef diff --git a/depends/packages/xproto.mk b/depends/packages/xproto.mk index 50a90b2685..c148017660 100644 --- a/depends/packages/xproto.mk +++ b/depends/packages/xproto.mk @@ -1,8 +1,8 @@ package=xproto -$(package)_version=7.0.26 +$(package)_version=7.0.31 $(package)_download_path=http://xorg.freedesktop.org/releases/individual/proto $(package)_file_name=$(package)-$($(package)_version).tar.bz2 -$(package)_sha256_hash=636162c1759805a5a0114a369dffdeccb8af8c859ef6e1445f26a4e6e046514f +$(package)_sha256_hash=c6f9747da0bd3a95f86b17fb8dd5e717c8f3ab7f0ece3ba1b247899ec1ef7747 define $(package)_set_vars $(package)_config_opts=--disable-shared diff --git a/depends/packages/xtrans.mk b/depends/packages/xtrans.mk index 99eefa6d5e..5ae39e5631 100644 --- a/depends/packages/xtrans.mk +++ b/depends/packages/xtrans.mk @@ -1,12 +1,12 @@ package=xtrans -$(package)_version=1.3.4 +$(package)_version=1.6.0 $(package)_download_path=http://xorg.freedesktop.org/releases/individual/lib/ -$(package)_file_name=$(package)-$($(package)_version).tar.bz2 -$(package)_sha256_hash=054d4ee3efd52508c753e9f7bc655ef185a29bd2850dd9e2fc2ccc33544f583a +$(package)_file_name=$(package)-$($(package)_version).tar.xz +$(package)_sha256_hash=faafea166bf2451a173d9d593352940ec6404145c5d1da5c213423ce4d359e92 $(package)_dependencies= define $(package)_set_vars -$(package)_config_opts_linux=--with-pic --disable-static +$(package)_config_opts_linux=--with-pic endef define $(package)_config_cmds diff --git a/depends/packages/zeromq.mk b/depends/packages/zeromq.mk index 3b7f3690a4..5246cc9568 100644 --- a/depends/packages/zeromq.mk +++ b/depends/packages/zeromq.mk @@ -1,8 +1,8 @@ package=zeromq -$(package)_version=4.3.1 +$(package)_version=4.3.5 $(package)_download_path=https://github.com/zeromq/libzmq/releases/download/v$($(package)_version)/ $(package)_file_name=$(package)-$($(package)_version).tar.gz -$(package)_sha256_hash=bcbabe1e2c7d0eec4ed612e10b94b112dd5f06fcefa994a0c79a45d835cd21eb +$(package)_sha256_hash=6653ef5910f17954861fe72332e68b03ca6e4d9c7160eb3a8de5a5a913bfab43 $(package)_patches=remove_libstd_link.patch define $(package)_set_vars diff --git a/depends/packages/zlib.mk b/depends/packages/zlib.mk index 589490800f..379bf96a2b 100644 --- a/depends/packages/zlib.mk +++ b/depends/packages/zlib.mk @@ -1,8 +1,8 @@ package=zlib -$(package)_version=1.2.11 +$(package)_version=1.3.1 $(package)_download_path=http://www.zlib.net $(package)_file_name=$(package)-$($(package)_version).tar.gz -$(package)_sha256_hash=c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1 +$(package)_sha256_hash=9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23 define $(package)_set_vars $(package)_build_opts= CC="$($(package)_cc)" diff --git a/depends/patches/qrencode/cmake_fixups.patch b/depends/patches/qrencode/cmake_fixups.patch new file mode 100644 index 0000000000..7518d756cb --- /dev/null +++ b/depends/patches/qrencode/cmake_fixups.patch @@ -0,0 +1,23 @@ +cmake: set minimum version to 3.5 + +Correct some dev warning output. + +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 773e037..a558145 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -1,4 +1,4 @@ +-cmake_minimum_required(VERSION 3.1.0) ++cmake_minimum_required(VERSION 3.5) + + project(QRencode VERSION 4.1.1 LANGUAGES C) + +@@ -20,7 +20,7 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") + set(CMAKE_THREAD_PREFER_PTHREAD ON) + find_package(Threads) + find_package(PNG) +-find_package(Iconv) ++find_package(ICONV) + + if(CMAKE_USE_PTHREADS_INIT) + add_definitions(-DHAVE_LIBPTHREAD=1) diff --git a/depends/patches/qt/fix-libpng.patch b/depends/patches/qt/fix-libpng.patch new file mode 100644 index 0000000000..21427f8224 --- /dev/null +++ b/depends/patches/qt/fix-libpng.patch @@ -0,0 +1,3656 @@ +diff --git old/qtbase/src/3rdparty/libpng/ANNOUNCE new/qtbase/src/3rdparty/libpng/ANNOUNCE +index ecf9c7043b0..800446b059b 100644 +--- old/qtbase/src/3rdparty/libpng/ANNOUNCE ++++ new/qtbase/src/3rdparty/libpng/ANNOUNCE +@@ -1,5 +1,5 @@ +-libpng 1.6.37 - April 14, 2019 +-============================== ++libpng 1.6.41 - January 24, 2024 ++================================ + + This is a public release of libpng, intended for use in production code. + +@@ -9,13 +9,13 @@ Files available for download + + Source files with LF line endings (for Unix/Linux): + +- * libpng-1.6.37.tar.xz (LZMA-compressed, recommended) +- * libpng-1.6.37.tar.gz ++ * libpng-1.6.41.tar.xz (LZMA-compressed, recommended) ++ * libpng-1.6.41.tar.gz (deflate-compressed) + + Source files with CRLF line endings (for Windows): + +- * lp1637.7z (LZMA-compressed, recommended) +- * lp1637.zip ++ * lpng1641.7z (LZMA-compressed, recommended) ++ * lpng1641.zip (deflate-compressed) + + Other information: + +@@ -25,20 +25,39 @@ Other information: + * TRADEMARK.md + + +-Changes since the previous public release (version 1.6.36) +----------------------------------------------------------- +- +- * Fixed a use-after-free vulnerability (CVE-2019-7317) in png_image_free. +- * Fixed a memory leak in the ARM NEON implementation of png_do_expand_palette. +- * Fixed a memory leak in pngtest.c. +- * Fixed two vulnerabilities (CVE-2018-14048, CVE-2018-14550) in +- contrib/pngminus; refactor. +- * Changed the license of contrib/pngminus to MIT; refresh makefile and docs. +- (Contributed by Willem van Schaik) +- * Fixed a typo in the libpng license v2. +- (Contributed by Miguel Ojeda) +- * Added makefiles for AddressSanitizer-enabled builds. +- * Cleaned up various makefiles. ++Changes from version 1.6.40 to version 1.6.41 ++--------------------------------------------- ++ ++ * Added SIMD-optimized code for the Loongarch LSX hardware. ++ (Contributed by GuXiWei, JinBo and ZhangLixia) ++ * Fixed the run-time discovery of MIPS MSA hardware. ++ (Contributed by Sui Jingfeng) ++ * Fixed an off-by-one error in the function `png_do_check_palette_indexes`, ++ which failed to recognize errors that might have existed in the first ++ column of a broken palette-encoded image. This was a benign regression ++ accidentally introduced in libpng-1.6.33. No pixel was harmed. ++ (Contributed by Adam Richter; reviewed by John Bowler) ++ * Fixed, improved and modernized the contrib/pngminus programs, i.e., ++ png2pnm.c and pnm2png.c ++ * Removed old and peculiar portability hacks that were meant to silence ++ warnings issued by gcc version 7.1 alone. ++ (Contributed by John Bowler) ++ * Fixed and modernized the CMake file, and raised the minimum required ++ CMake version from 3.1 to 3.6. ++ (Contributed by Clinton Ingram, Timothy Lyanguzov, Tyler Kropp, et al.) ++ * Allowed the configure script to disable the building of auxiliary tools ++ and tests, thus catching up with the CMake file. ++ (Contributed by Carlo Bramini) ++ * Fixed a build issue on Mac. ++ (Contributed by Zixu Wang) ++ * Moved the Autoconf macro files to scripts/autoconf. ++ * Moved the CMake files (except for the main CMakeLists.txt) to ++ scripts/cmake and moved the list of their contributing authors to ++ scripts/cmake/AUTHORS.md ++ * Updated the CI configurations and scripts. ++ * Relicensed the CI scripts to the MIT License. ++ * Improved the test coverage. ++ (Contributed by John Bowler) + + + Send comments/corrections/commendations to png-mng-implement at lists.sf.net. +diff --git old/qtbase/src/3rdparty/libpng/CHANGES new/qtbase/src/3rdparty/libpng/CHANGES +index f0b0a9342c3..2d9a57e439e 100644 +--- old/qtbase/src/3rdparty/libpng/CHANGES ++++ new/qtbase/src/3rdparty/libpng/CHANGES +@@ -204,7 +204,7 @@ Version 0.97 [January, 1998] + Added simple sRGB support (Glenn R-P) + Easier conditional compiling, e.g., + define PNG_READ/WRITE_NOT_FULLY_SUPPORTED; +- all configurable options can be selected from command-line instead ++ all configurable options can be selected from command line instead + of having to edit pngconf.h (Glenn R-P) + Fixed memory leak in pngwrite.c (free info_ptr->text) (Glenn R-P) + Added more conditions for png_do_background, to avoid changing +@@ -942,7 +942,7 @@ Version 1.0.8 [July 24, 2000] + Version 1.0.9beta1 [November 10, 2000] + Fixed typo in scripts/makefile.hpux + Updated makevms.com in scripts and contrib/* and contrib/* (Martin Zinser) +- Fixed seqence-point bug in contrib/pngminus/png2pnm (Martin Zinser) ++ Fixed sequence-point bug in contrib/pngminus/png2pnm (Martin Zinser) + Changed "cdrom.com" in documentation to "libpng.org" + Revised pnggccrd.c to get it all working, and updated makefile.gcmmx (Greg). + Changed type of "params" from voidp to png_voidp in png_read|write_png(). +@@ -2295,7 +2295,7 @@ Version 1.4.0beta58 [May 14, 2009] + Clarified usage of sig_bit versus sig_bit_p in example.c (Vincent Torri) + + Version 1.4.0beta59 [May 15, 2009] +- Reformated sources in libpng style (3-space intentation, comment format) ++ Reformatted sources in libpng style (3-space indentation, comment format) + Fixed typo in libpng docs (PNG_FILTER_AVE should be PNG_FILTER_AVG) + Added sections about the git repository and our coding style to the + documentation +@@ -2661,7 +2661,7 @@ Version 1.4.1beta06 [January 28, 2010] + + Version 1.4.1beta07 [February 6, 2010] + Folded some long lines in the source files. +- Added defineable PNG_USER_CHUNK_CACHE_MAX, PNG_USER_CHUNK_MALLOC_MAX, ++ Added definable PNG_USER_CHUNK_CACHE_MAX, PNG_USER_CHUNK_MALLOC_MAX, + and a PNG_USER_LIMITS_SUPPORTED flag. + Eliminated use of png_ptr->irowbytes and reused the slot in png_ptr as + png_ptr->png_user_chunk_malloc_max. +@@ -3886,7 +3886,7 @@ Version 1.6.0beta06 [January 24, 2012] + Version 1.6.0beta07 [January 28, 2012] + Eliminated Intel icc/icl compiler warnings. The Intel (GCC derived) + compiler issues slightly different warnings from those issued by the +- current vesions of GCC. This eliminates those warnings by ++ current versions of GCC. This eliminates those warnings by + adding/removing casts and small code rewrites. + Updated configure.ac from autoupdate: added --enable-werror option. + Also some layout regularization and removal of introduced tab characters +@@ -3919,7 +3919,7 @@ Version 1.6.0beta08 [February 1, 2012] + version checking to configure.ac + Improved pngstest speed by not doing redundant tests and add const to + the background parameter of png_image_finish_read. The --background +- option is now done automagically only when required, so that commandline ++ option is now done automagically only when required, so that command-line + option no longer exists. + Cleaned up pngpriv.h to consistently declare all functions and data. + Also eliminated PNG_CONST_DATA, which is apparently not needed but we +@@ -4052,7 +4052,7 @@ Version 1.6.0beta16 [March 6, 2012] + (in fact this is harmless, but the PNG data produced may be sub-optimal). + + Version 1.6.0beta17 [March 10, 2012] +- Fixed PNG_LIBPNG_BUILD_BASE_TYPE definition. ++ Fixed PNG_LIBPNG_BUILD_BASE_TYPE definition. + Reject all iCCP chunks after the first, even if the first one is invalid. + Deflate/inflate was reworked to move common zlib calls into single + functions [rw]util.c. A new shared keyword check routine was also added +@@ -4962,7 +4962,7 @@ Version 1.6.13beta01 [July 4, 2014] + Changed "if defined(__ARM_NEON__)" to + "if (defined(__ARM_NEON__) || defined(__ARM_NEON))" (James Wu). + Fixed clang no-warning builds: png_digit was defined but never used. +- ++ + Version 1.6.13beta02 [July 21, 2014] + Fixed an incorrect separator ("/" should be "\") in scripts/makefile.vcwin32 + (bug report from Wolfgang S. Kechel). Bug was introduced in libpng-1.6.11. +@@ -5453,7 +5453,7 @@ Version 1.6.21beta01 [December 11, 2015] + Version 1.6.21beta02 [December 14, 2015] + Moved png_check_keyword() from pngwutil.c to pngset.c + Removed LE/BE dependencies in pngvalid, to 'fix' the current problem +- in the BigEndian tests by not testing it, making the BE code the same ++ in the BigEndian tests by not testing it, making the BE code the same + as the LE version. + Fixes to pngvalid for various reduced build configurations (eliminate unused + statics) and a fix for the case in rgb_to_gray when the digitize option +@@ -5517,7 +5517,7 @@ Version 1.6.22beta03 [March 9, 2016] + Added a common-law trademark notice and export control information + to the LICENSE file, png.h, and the man page. + Restored "& 0xff" in png_save_uint_16() and png_save_uint_32() that +- were accidentally removed from libpng-1.6.17. ++ were accidentally removed from libpng-1.6.17. + Changed PNG_INFO_cHNK and PNG_FREE_cHNK from 0xnnnn to 0xnnnnU in png.h + (Robert C. Seacord). + Removed dubious "#if INT_MAX" test from png.h that was added to +@@ -5927,7 +5927,7 @@ Version 1.6.32beta03 [August 2, 2017] + (Bug report from the OSS-fuzz project). + + Version 1.6.32beta04 [August 2, 2017] +- Replaced local eXIf_buf with info_ptr-eXIf_buf in png_handle_eXIf(). ++ Replaced local eXIf_buf with info_ptr->eXIf_buf in png_handle_eXIf(). + Update libpng.3 and libpng-manual.txt about eXIf functions. + + Version 1.6.32beta05 [August 2, 2017] +@@ -5950,7 +5950,7 @@ Version 1.6.32beta09 [August 3, 2017] + Require cmake-2.8.8 in CMakeLists.txt. Revised symlink creation, + no longer using deprecated cmake LOCATION feature (Clifford Yapp). + Fixed five-byte error in the calculation of IDAT maximum possible size. +- ++ + Version 1.6.32beta10 [August 5, 2017] + Moved chunk-length check into a png_check_chunk_length() private + function (Suggested by Max Stepin). +@@ -6103,6 +6103,64 @@ Version 1.6.37 [April 14, 2019] + Added makefiles for AddressSanitizer-enabled builds. + Cleaned up various makefiles. + ++Version 1.6.38 [September 14, 2022] ++ Added configurations and scripts for continuous integration. ++ Fixed various errors in the handling of tRNS, hIST and eXIf. ++ Implemented many stability improvements across all platforms. ++ Updated the internal documentation. ++ ++Version 1.6.39 [November 20, 2022] ++ Changed the error handler of oversized chunks (i.e. larger than ++ PNG_USER_CHUNK_MALLOC_MAX) from png_chunk_error to png_benign_error. ++ Fixed a buffer overflow error in contrib/tools/pngfix. ++ Fixed a memory leak (CVE-2019-6129) in contrib/tools/pngcp. ++ Disabled the ARM Neon optimizations by default in the CMake file, ++ following the default behavior of the configure script. ++ Allowed configure.ac to work with the trunk version of autoconf. ++ Removed the support for "install" targets from the legacy makefiles; ++ removed the obsolete makefile.cegcc. ++ Cleaned up the code and updated the internal documentation. ++ ++Version 1.6.40 [June 21, 2023] ++ Fixed the eXIf chunk multiplicity checks. ++ Fixed a memory leak in pCAL processing. ++ Corrected the validity report about tRNS inside png_get_valid(). ++ Fixed various build issues on *BSD, Mac and Windows. ++ Updated the configurations and the scripts for continuous integration. ++ Cleaned up the code, the build scripts, and the documentation. ++ ++Version 1.6.41 [January 24, 2024] ++ Added SIMD-optimized code for the Loongarch LSX hardware. ++ (Contributed by GuXiWei, JinBo and ZhangLixia) ++ Fixed the run-time discovery of MIPS MSA hardware. ++ (Contributed by Sui Jingfeng) ++ Fixed an off-by-one error in the function `png_do_check_palette_indexes`, ++ which failed to recognize errors that might have existed in the first ++ column of a broken palette-encoded image. This was a benign regression ++ accidentally introduced in libpng-1.6.33. No pixel was harmed. ++ (Contributed by Adam Richter; reviewed by John Bowler) ++ Fixed, improved and modernized the contrib/pngminus programs, i.e., ++ png2pnm.c and pnm2png.c ++ Removed old and peculiar portability hacks that were meant to silence ++ warnings issued by gcc version 7.1 alone. ++ (Contributed by John Bowler) ++ Fixed and modernized the CMake file, and raised the minimum required ++ CMake version from 3.1 to 3.6. ++ (Contributed by Clinton Ingram, Timothy Lyanguzov, Tyler Kropp, et al.) ++ Allowed the configure script to disable the building of auxiliary tools ++ and tests, thus catching up with the CMake file. ++ (Contributed by Carlo Bramini) ++ Fixed a build issue on Mac. ++ (Contributed by Zixu Wang) ++ Moved the Autoconf macro files to scripts/autoconf. ++ Moved the CMake files (except for the main CMakeLists.txt) to ++ scripts/cmake and moved the list of their contributing authors to ++ scripts/cmake/AUTHORS.md ++ Updated the CI configurations and scripts. ++ Relicensed the CI scripts to the MIT License. ++ Improved the test coverage. ++ (Contributed by John Bowler) ++ + Send comments/corrections/commendations to png-mng-implement at lists.sf.net. + Subscription is required; visit + https://lists.sourceforge.net/lists/listinfo/png-mng-implement +diff --git old/qtbase/src/3rdparty/libpng/INSTALL new/qtbase/src/3rdparty/libpng/INSTALL +index 4c170225150..042d7292912 100644 +--- old/qtbase/src/3rdparty/libpng/INSTALL ++++ new/qtbase/src/3rdparty/libpng/INSTALL +@@ -128,16 +128,18 @@ Your directory structure should look like this: + README + *.h, *.c => libpng source files + CMakeLists.txt => "cmake" script ++ ci ++ ci_*.sh + configuration files: + configure.ac, configure, Makefile.am, Makefile.in, + autogen.sh, config.guess, ltmain.sh, missing, libpng.pc.in, + libpng-config.in, aclocal.m4, config.h.in, config.sub, +- depcomp, install-sh, mkinstalldirs, test-pngtest.sh ++ depcomp, install-sh, mkinstalldirs, test-pngtest.sh, etc. + contrib + arm-neon, conftest, examples, gregbook, libtests, pngminim, + pngminus, pngsuite, tools, visupng + projects +- cbuilder5, owatcom, visualc71, vstudio, xcode ++ owatcom, visualc71, vstudio + scripts + makefile.* + *.def (module definition files) +@@ -145,7 +147,7 @@ Your directory structure should look like this: + pngtest.png + etc. + zlib +- README, *.h, *.c contrib, etc. ++ README, *.h, *.c, contrib, etc. + + If the line endings in the files look funny, you may wish to get the other + distribution of libpng. It is available in both tar.gz (UNIX style line +@@ -153,28 +155,27 @@ endings) and zip (DOS style line endings) formats. + + VI. Building with project files + +-If you are building libpng with MSVC, you can enter the +-libpng projects\visualc71 or vstudio directory and follow the instructions +-in README.txt. ++If you are building libpng with Microsoft Visual Studio, you can enter ++the directory projects\visualc71 or projects\vstudio and follow the ++instructions in README.txt. + +-Otherwise enter the zlib directory and follow the instructions in zlib/README, +-then come back here and run "configure" or choose the appropriate +-makefile.sys in the scripts directory. ++Otherwise, enter the zlib directory and follow the instructions in ++zlib/README, then come back here and run "configure" or choose the ++appropriate makefile in the scripts directory. + + VII. Building with makefiles + + Copy the file (or files) that you need from the + scripts directory into this directory, for example + +-MSDOS example: ++UNIX example: + +- copy scripts\makefile.msc makefile +- copy scripts\pnglibconf.h.prebuilt pnglibconf.h ++ cp scripts/makefile.std Makefile ++ make + +-UNIX example: ++Windows example: + +- cp scripts/makefile.std makefile +- cp scripts/pnglibconf.h.prebuilt pnglibconf.h ++ nmake -f scripts\makefile.vcwin32 + + Read the makefile to see if you need to change any source or + target directories to match your preferences. +@@ -191,36 +192,33 @@ test. For more confidence, you can run another test by typing + Also, you can run "pngtest -m contrib/pngsuite/*.png" and compare + your output with the result shown in contrib/pngsuite/README. + +-Most of the makefiles will allow you to run "make install" to +-put the library in its final resting place (if you want to +-do that, run "make install" in the zlib directory first if necessary). +-Some also allow you to run "make test-installed" after you have +-run "make install". +- +-VIII. Configuring libpng for 16-bit platforms ++Most of the makefiles used to allow you to run "make install" to put ++the library in its final resting place, but that feature is no longer ++supported. The only tested and supported manners to install libpng are ++the conventional build and install procedures driven by the configure ++script or by the CMake file. + +-You will want to look into zconf.h to tell zlib (and thus libpng) that +-it cannot allocate more than 64K at a time. Even if you can, the memory +-won't be accessible. So limit zlib and libpng to 64K by defining MAXSEG_64K. ++VIII. Configuring for DOS and other 16-bit platforms + +-IX. Configuring for DOS ++Officially, the support for 16-bit platforms has been removed. + + For DOS users who only have access to the lower 640K, you will + have to limit zlib's memory usage via a png_set_compression_mem_level() + call. See zlib.h or zconf.h in the zlib library for more information. + +-X. Configuring for Medium Model ++You may be or may not be in luck if you target the "large" memory model, ++but all the smaller models ("small", "compact" and "medium") are known ++to be unworkable. For DOS users who have access beyond the lower 640K, ++a "flat" 32-bit DOS model (such as DJGPP) is strongly recommended. + +-Libpng's support for medium model has been tested on most of the popular +-compilers. Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets +-defined, and FAR gets defined to far in pngconf.h, and you should be +-all set. Everything in the library (except for zlib's structure) is +-expecting far data. You must use the typedefs with the p or pp on +-the end for pointers (or at least look at them and be careful). Make +-note that the rows of data are defined as png_bytepp, which is +-an "unsigned char far * far *". ++For DOS users who only have access to the lower 640K, you will have to ++limit zlib's memory usage via a png_set_compression_mem_level() call. ++You will also have to look into zconf.h to tell zlib (and thus libpng) ++that it cannot allocate more than 64K at a time. Even if you can, the ++memory won't be accessible. Therefore, you should limit zlib and libpng ++to 64K by defining MAXSEG_64K. + +-XI. Prepending a prefix to exported symbols ++IX. Prepending a prefix to exported symbols + + Starting with libpng-1.6.0, you can configure libpng (when using the + "configure" script) to prefix all exported symbols by means of the +@@ -231,7 +229,7 @@ identifier). This creates a set of macros in pnglibconf.h, so this is + transparent to applications; their function calls get transformed by + the macros to use the modified names. + +-XII. Configuring for compiler xxx: ++X. Configuring for compiler xxx: + + All includes for libpng are in pngconf.h. If you need to add, change + or delete an include, this is the place to do it. +@@ -243,7 +241,7 @@ As of libpng-1.5.0, pngpriv.h also includes three other private header + files, pngstruct.h, pnginfo.h, and pngdebug.h, which contain material + that previously appeared in the public headers. + +-XIII. Removing unwanted object code ++XI. Removing unwanted object code + + There are a bunch of #define's in pngconf.h that control what parts of + libpng are compiled. All the defines end in _SUPPORTED. If you are +@@ -282,7 +280,7 @@ library to fail if they call functions not available in your library. + The size of the library itself should not be an issue, because only + those sections that are actually used will be loaded into memory. + +-XIV. Enabling or disabling hardware optimizations ++XII. Enabling or disabling hardware optimizations + + Certain hardware capabilities, such as the Intel SSE instructions, + are normally detected at run time. Enable them with configure options +@@ -332,7 +330,7 @@ or disable them all at once with + + cmake . -DPNG_HARDWARE_OPTIMIZATIONS=no + +-XV. Changes to the build and configuration of libpng in libpng-1.5.x ++XIII. Changes to the build and configuration of libpng in libpng-1.5.x + + Details of internal changes to the library code can be found in the CHANGES + file and in the GIT repository logs. These will be of no concern to the vast +@@ -423,7 +421,7 @@ $PREFIX/include directory). Do not edit pnglibconf.h after you have built + libpng, because than the settings would not accurately reflect the settings + that were used to build libpng. + +-XVI. Setjmp/longjmp issues ++XIV. Setjmp/longjmp issues + + Libpng uses setjmp()/longjmp() for error handling. Unfortunately setjmp() + is known to be not thread-safe on some platforms and we don't know of +@@ -441,7 +439,7 @@ This requires setjmp/longjmp, so you must either build the library + with PNG_SETJMP_SUPPORTED defined, or with PNG_SIMPLIFIED_READ_SUPPORTED + and PNG_SIMPLIFIED_WRITE_SUPPORTED undefined. + +-XVII. Common linking failures ++XV. Common linking failures + + If your application fails to find libpng or zlib entries while linking: + +@@ -453,12 +451,13 @@ If your application fails to find libpng or zlib entries while linking: + If you are using the vstudio project, observe the WARNING in + project/vstudio/README.txt. + +-XVIII. Other sources of information about libpng: ++XVI. Other sources of information about libpng: + + Further information can be found in the README and libpng-manual.txt + files, in the individual makefiles, in png.h, and the manual pages + libpng.3 and png.5. + ++Copyright (c) 2022 Cosmin Truta + Copyright (c) 1998-2002,2006-2016 Glenn Randers-Pehrson + This document is released under the libpng license. + For conditions of distribution and use, see the disclaimer +diff --git old/qtbase/src/3rdparty/libpng/LICENSE new/qtbase/src/3rdparty/libpng/LICENSE +index e0c5b531cf5..25f298f0fcf 100644 +--- old/qtbase/src/3rdparty/libpng/LICENSE ++++ new/qtbase/src/3rdparty/libpng/LICENSE +@@ -4,8 +4,8 @@ COPYRIGHT NOTICE, DISCLAIMER, and LICENSE + PNG Reference Library License version 2 + --------------------------------------- + +- * Copyright (c) 1995-2019 The PNG Reference Library Authors. +- * Copyright (c) 2018-2019 Cosmin Truta. ++ * Copyright (c) 1995-2024 The PNG Reference Library Authors. ++ * Copyright (c) 2018-2024 Cosmin Truta. + * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson. + * Copyright (c) 1996-1997 Andreas Dilger. + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +diff --git old/qtbase/src/3rdparty/libpng/README new/qtbase/src/3rdparty/libpng/README +index cfc1f0e3dc9..1f51a808f7f 100644 +--- old/qtbase/src/3rdparty/libpng/README ++++ new/qtbase/src/3rdparty/libpng/README +@@ -1,178 +1,177 @@ +-README for libpng version 1.6.37 - April 14, 2019 +-================================================= +- +-See the note about version numbers near the top of png.h. +-See INSTALL for instructions on how to install libpng. +- +-Libpng comes in several distribution formats. Get libpng-*.tar.gz or +-libpng-*.tar.xz or if you want UNIX-style line endings in the text +-files, or lpng*.7z or lpng*.zip if you want DOS-style line endings. +- +-Version 0.89 was the first official release of libpng. Don't let the +-fact that it's the first release fool you. The libpng library has been +-in extensive use and testing since mid-1995. By late 1997 it had +-finally gotten to the stage where there hadn't been significant +-changes to the API in some time, and people have a bad feeling about +-libraries with versions < 1.0. Version 1.0.0 was released in +-March 1998. +- +-**** +-Note that some of the changes to the png_info structure render this +-version of the library binary incompatible with libpng-0.89 or +-earlier versions if you are using a shared library. The type of the +-"filler" parameter for png_set_filler() has changed from png_byte to +-png_uint_32, which will affect shared-library applications that use +-this function. ++README for libpng version 1.6.41 ++================================ + +-To avoid problems with changes to the internals of the png info_struct, +-new APIs have been made available in 0.95 to avoid direct application +-access to info_ptr. These functions are the png_set_ and +-png_get_ functions. These functions should be used when +-accessing/storing the info_struct data, rather than manipulating it +-directly, to avoid such problems in the future. ++See the note about version numbers near the top of `png.h`. ++See `INSTALL` for instructions on how to install libpng. + +-It is important to note that the APIs did not make current programs +-that access the info struct directly incompatible with the new +-library, through libpng-1.2.x. In libpng-1.4.x, which was meant to +-be a transitional release, members of the png_struct and the +-info_struct can still be accessed, but the compiler will issue a +-warning about deprecated usage. Since libpng-1.5.0, direct access +-to these structs is not allowed, and the definitions of the structs +-reside in private pngstruct.h and pnginfo.h header files that are not +-accessible to applications. It is strongly suggested that new +-programs use the new APIs (as shown in example.c and pngtest.c), and +-older programs be converted to the new format, to facilitate upgrades +-in the future. +-**** +- +-Additions since 0.90 include the ability to compile libpng as a +-Windows DLL, and new APIs for accessing data in the info struct. +-Experimental functions include the ability to set weighting and cost +-factors for row filter selection, direct reads of integers from buffers +-on big-endian processors that support misaligned data access, faster +-methods of doing alpha composition, and more accurate 16->8 bit color +-conversion. ++Libpng comes in several distribution formats. Get `libpng-*.tar.gz` ++or `libpng-*.tar.xz` if you want UNIX-style line endings in the text ++files, or `lpng*.7z` or `lpng*.zip` if you want DOS-style line endings. + +-The additions since 0.89 include the ability to read from a PNG stream +-which has had some (or all) of the signature bytes read by the calling +-application. This also allows the reading of embedded PNG streams that +-do not have the PNG file signature. As well, it is now possible to set +-the library action on the detection of chunk CRC errors. It is possible +-to set different actions based on whether the CRC error occurred in a +-critical or an ancillary chunk. ++For a detailed description on using libpng, read `libpng-manual.txt`. ++For examples of libpng in a program, see `example.c` and `pngtest.c`. ++For usage information and restrictions (what little they are) on libpng, ++see `png.h`. For a description on using zlib (the compression library ++used by libpng) and zlib's restrictions, see `zlib.h`. + +-For a detailed description on using libpng, read libpng-manual.txt. +-For examples of libpng in a program, see example.c and pngtest.c. For +-usage information and restrictions (what little they are) on libpng, +-see png.h. For a description on using zlib (the compression library +-used by libpng) and zlib's restrictions, see zlib.h +- +-I have included a general makefile, as well as several machine and +-compiler specific ones, but you may have to modify one for your own +-needs. +- +-You should use zlib 1.0.4 or later to run this, but it MAY work with ++You should use zlib 1.0.4 or later to run this, but it _may_ work with + versions as old as zlib 0.95. Even so, there are bugs in older zlib + versions which can cause the output of invalid compression streams for + some images. + + You should also note that zlib is a compression library that is useful + for more things than just PNG files. You can use zlib as a drop-in +-replacement for fread() and fwrite(), if you are so inclined. ++replacement for `fread()` and `fwrite()`, if you are so inclined. + + zlib should be available at the same place that libpng is, or at +-https://zlib.net. ++https://zlib.net . + + You may also want a copy of the PNG specification. It is available + as an RFC, a W3C Recommendation, and an ISO/IEC Standard. You can find + these at http://www.libpng.org/pub/png/pngdocs.html . + +-This code is currently being archived at libpng.sourceforge.io in the +-[DOWNLOAD] area, and at http://libpng.download/src . ++This code is currently being archived at https://libpng.sourceforge.io ++in the download area, and at http://libpng.download/src . + + This release, based in a large way on Glenn's, Guy's and Andreas' + earlier work, was created and will be supported by myself and the PNG + development group. + +-Send comments/corrections/commendations to png-mng-implement at +-lists.sourceforge.net (subscription required; visit ++Send comments, corrections and commendations to `png-mng-implement` ++at `lists.sourceforge.net`. (Subscription is required; visit + https://lists.sourceforge.net/lists/listinfo/png-mng-implement +-to subscribe). +- +-Send general questions about the PNG specification to png-mng-misc +-at lists.sourceforge.net (subscription required; visit +-https://lists.sourceforge.net/lists/listinfo/png-mng-misc to +-subscribe). +- +-Files in this distribution: +- +- ANNOUNCE => Announcement of this version, with recent changes +- AUTHORS => List of contributing authors +- CHANGES => Description of changes between libpng versions +- KNOWNBUG => List of known bugs and deficiencies +- LICENSE => License to use and redistribute libpng +- README => This file +- TODO => Things not implemented in the current library +- TRADEMARK => Trademark information +- example.c => Example code for using libpng functions +- libpng.3 => manual page for libpng (includes libpng-manual.txt) +- libpng-manual.txt => Description of libpng and its functions +- libpngpf.3 => manual page for libpng's private functions +- png.5 => manual page for the PNG format +- png.c => Basic interface functions common to library +- png.h => Library function and interface declarations (public) +- pngpriv.h => Library function and interface declarations (private) +- pngconf.h => System specific library configuration (public) +- pngstruct.h => png_struct declaration (private) +- pnginfo.h => png_info struct declaration (private) +- pngdebug.h => debugging macros (private) +- pngerror.c => Error/warning message I/O functions +- pngget.c => Functions for retrieving info from struct +- pngmem.c => Memory handling functions +- pngbar.png => PNG logo, 88x31 +- pngnow.png => PNG logo, 98x31 +- pngpread.c => Progressive reading functions +- pngread.c => Read data/helper high-level functions +- pngrio.c => Lowest-level data read I/O functions +- pngrtran.c => Read data transformation functions +- pngrutil.c => Read data utility functions +- pngset.c => Functions for storing data into the info_struct +- pngtest.c => Library test program +- pngtest.png => Library test sample image +- pngtrans.c => Common data transformation functions +- pngwio.c => Lowest-level write I/O functions +- pngwrite.c => High-level write functions +- pngwtran.c => Write data transformations +- pngwutil.c => Write utility functions +- arm => Contains optimized code for the ARM platform +- powerpc => Contains optimized code for the PowerPC platform +- contrib => Contributions +- arm-neon => Optimized code for ARM-NEON platform +- powerpc-vsx => Optimized code for POWERPC-VSX platform +- examples => Example programs +- gregbook => source code for PNG reading and writing, from +- Greg Roelofs' "PNG: The Definitive Guide", +- O'Reilly, 1999 +- libtests => Test programs +- mips-msa => Optimized code for MIPS-MSA platform +- pngminim => Minimal decoder, encoder, and progressive decoder +- programs demonstrating use of pngusr.dfa +- pngminus => Simple pnm2png and png2pnm programs +- pngsuite => Test images +- testpngs +- tools => Various tools +- visupng => Contains a MSVC workspace for VisualPng +- intel => Optimized code for INTEL-SSE2 platform +- mips => Optimized code for MIPS platform +- projects => Contains project files and workspaces for +- building a DLL +- owatcom => Contains a WATCOM project for building libpng +- visualc71 => Contains a Microsoft Visual C++ (MSVC) +- workspace for building libpng and zlib +- vstudio => Contains a Microsoft Visual C++ (MSVC) +- workspace for building libpng and zlib +- scripts => Directory containing scripts for building libpng: +- (see scripts/README.txt for the list of scripts) ++to subscribe.) ++ ++Send general questions about the PNG specification to `png-mng-misc` ++at `lists.sourceforge.net`. (Subscription is required; visit ++https://lists.sourceforge.net/lists/listinfo/png-mng-misc ++to subscribe.) ++ ++Historical notes ++---------------- ++ ++The libpng library has been in extensive use and testing since mid-1995. ++Version 0.89, published a year later, was the first official release. ++By late 1997, it had finally gotten to the stage where there hadn't ++been significant changes to the API in some time, and people have a bad ++feeling about libraries with versions below 1.0. Version 1.0.0 was ++released in March 1998. ++ ++Note that some of the changes to the `png_info` structure render this ++version of the library binary incompatible with libpng-0.89 or ++earlier versions if you are using a shared library. The type of the ++`filler` parameter for `png_set_filler()` has changed from `png_byte` ++to `png_uint_32`, which will affect shared-library applications that ++use this function. ++ ++To avoid problems with changes to the internals of the `info_struct`, ++new APIs have been made available in 0.95 to avoid direct application ++access to `info_ptr`. These functions are the `png_set_` and ++`png_get_` functions. These functions should be used when ++accessing/storing the `info_struct` data, rather than manipulating it ++directly, to avoid such problems in the future. ++ ++It is important to note that the APIs did not make current programs ++that access the info struct directly incompatible with the new ++library, through libpng-1.2.x. In libpng-1.4.x, which was meant to ++be a transitional release, members of the `png_struct` and the ++`info_struct` can still be accessed, but the compiler will issue a ++warning about deprecated usage. Since libpng-1.5.0, direct access ++to these structs is not allowed, and the definitions of the structs ++reside in private `pngstruct.h` and `pnginfo.h` header files that are ++not accessible to applications. It is strongly suggested that new ++programs use the new APIs (as shown in `example.c` and `pngtest.c`), ++and older programs be converted to the new format, to facilitate ++upgrades in the future. ++ ++The additions since 0.89 include the ability to read from a PNG stream ++which has had some (or all) of the signature bytes read by the calling ++application. This also allows the reading of embedded PNG streams that ++do not have the PNG file signature. As well, it is now possible to set ++the library action on the detection of chunk CRC errors. It is possible ++to set different actions based on whether the CRC error occurred in a ++critical or an ancillary chunk. ++ ++The additions since 0.90 include the ability to compile libpng as a ++Windows DLL, and new APIs for accessing data in the `info_struct`. ++Experimental functions included the ability to set weighting and cost ++factors for row filter selection, direct reads of integers from buffers ++on big-endian processors that support misaligned data access, faster ++methods of doing alpha composition, and more accurate 16-to-8 bit color ++conversion. Some of these experimental functions, such as the weighted ++filter heuristics, have since been removed. ++ ++Files included in this distribution ++----------------------------------- ++ ++ ANNOUNCE => Announcement of this version, with recent changes ++ AUTHORS => List of contributing authors ++ CHANGES => Description of changes between libpng versions ++ INSTALL => Instructions to install libpng ++ LICENSE => License to use and redistribute libpng ++ README => This file ++ TODO => Things not implemented in the current library ++ TRADEMARK => Trademark information ++ example.c => Example code for using libpng functions ++ libpng.3 => Manual page for libpng (includes libpng-manual.txt) ++ libpng-manual.txt => Description of libpng and its functions ++ libpngpf.3 => Manual page for libpng's private functions (deprecated) ++ png.5 => Manual page for the PNG format ++ png.c => Basic interface functions common to library ++ png.h => Library function and interface declarations (public) ++ pngpriv.h => Library function and interface declarations (private) ++ pngconf.h => System specific library configuration (public) ++ pngstruct.h => png_struct declaration (private) ++ pnginfo.h => png_info struct declaration (private) ++ pngdebug.h => debugging macros (private) ++ pngerror.c => Error/warning message I/O functions ++ pngget.c => Functions for retrieving info from struct ++ pngmem.c => Memory handling functions ++ pngbar.png => PNG logo, 88x31 ++ pngnow.png => PNG logo, 98x31 ++ pngpread.c => Progressive reading functions ++ pngread.c => Read data/helper high-level functions ++ pngrio.c => Lowest-level data read I/O functions ++ pngrtran.c => Read data transformation functions ++ pngrutil.c => Read data utility functions ++ pngset.c => Functions for storing data into the info_struct ++ pngtest.c => Library test program ++ pngtest.png => Library test sample image ++ pngtrans.c => Common data transformation functions ++ pngwio.c => Lowest-level write I/O functions ++ pngwrite.c => High-level write functions ++ pngwtran.c => Write data transformations ++ pngwutil.c => Write utility functions ++ arm/ => Optimized code for the ARM platform ++ intel/ => Optimized code for the INTEL-SSE2 platform ++ mips/ => Optimized code for the MIPS platform ++ powerpc/ => Optimized code for the PowerPC platform ++ ci/ => Scripts for continuous integration ++ contrib/ => External contributions ++ arm-neon/ => Optimized code for the ARM-NEON platform ++ mips-msa/ => Optimized code for the MIPS-MSA platform ++ powerpc-vsx/ => Optimized code for the POWERPC-VSX platform ++ examples/ => Examples of libpng usage ++ gregbook/ => Source code for PNG reading and writing, from ++ "PNG: The Definitive Guide" by Greg Roelofs, ++ O'Reilly, 1999 ++ libtests/ => Test programs ++ oss-fuzz/ => Files used by the OSS-Fuzz project for fuzz-testing ++ libpng ++ pngminim/ => Minimal decoder, encoder, and progressive decoder ++ programs demonstrating the use of pngusr.dfa ++ pngminus/ => Simple pnm2png and png2pnm programs ++ pngsuite/ => Test images ++ testpngs/ => Test images ++ tools/ => Various tools ++ visupng/ => VisualPng, a Windows viewer for PNG images ++ projects/ => Project files and workspaces for various IDEs ++ owatcom/ => OpenWatcom project ++ visualc71/ => Microsoft Visual C++ 7.1 workspace ++ vstudio/ => Microsoft Visual Studio workspace ++ scripts/ => Scripts and makefiles for building libpng ++ (see scripts/README.txt for the complete list) ++ tests/ => Test scripts + + Good luck, and happy coding! + +diff --git old/qtbase/src/3rdparty/libpng/libpng-manual.txt new/qtbase/src/3rdparty/libpng/libpng-manual.txt +index 5dad92fbf74..dbb60af61d1 100644 +--- old/qtbase/src/3rdparty/libpng/libpng-manual.txt ++++ new/qtbase/src/3rdparty/libpng/libpng-manual.txt +@@ -1,6 +1,6 @@ + libpng-manual.txt - A description on how to use and modify libpng + +- Copyright (c) 2018-2019 Cosmin Truta ++ Copyright (c) 2018-2024 Cosmin Truta + Copyright (c) 1998-2018 Glenn Randers-Pehrson + + This document is released under the libpng license. +@@ -9,9 +9,9 @@ libpng-manual.txt - A description on how to use and modify libpng + + Based on: + +- libpng version 1.6.36, December 2018, through 1.6.37 - April 2019 ++ libpng version 1.6.36, December 2018, through 1.6.41 - January 2024 + Updated and distributed by Cosmin Truta +- Copyright (c) 2018-2019 Cosmin Truta ++ Copyright (c) 2018-2024 Cosmin Truta + + libpng versions 0.97, January 1998, through 1.6.35 - July 2018 + Updated and distributed by Glenn Randers-Pehrson +@@ -877,7 +877,7 @@ described below (the latter being the two common names for associated alpha + color channels). Note that PNG files always contain non-associated color + channels; png_set_alpha_mode() with one of the modes causes the decoder to + convert the pixels to an associated form before returning them to your +-application. ++application. + + Since it is not necessary to perform arithmetic on opaque color values so + long as they are not to be resampled and are in the final color space it is +@@ -1792,7 +1792,7 @@ the information. If, instead, you want to convert the image to an opaque + version with no alpha channel use png_set_background; see below. + + As of libpng version 1.5.2, almost all useful expansions are supported, the +-major ommissions are conversion of grayscale to indexed images (which can be ++major omissions are conversion of grayscale to indexed images (which can be + done trivially in the application) and conversion of indexed to grayscale (which + can be done by a trivial manipulation of the palette.) + +diff --git old/qtbase/src/3rdparty/libpng/libpng.pro new/qtbase/src/3rdparty/libpng/libpng.pro +index b71dfefd200..cd81c7af893 100644 +--- old/qtbase/src/3rdparty/libpng/libpng.pro ++++ new/qtbase/src/3rdparty/libpng/libpng.pro +@@ -11,7 +11,11 @@ MODULE_EXT_HEADERS = png.h pngconf.h + + load(qt_helper_lib) + +-DEFINES += PNG_ARM_NEON_OPT=0 PNG_POWERPC_VSX_OPT=0 ++DEFINES += PNG_ARM_NEON_OPT=0 \ ++ PNG_POWERPC_VSX_OPT=0 \ ++ PNG_IMPEXP= \ ++ _CRT_SECURE_NO_DEPRECATE ++ + SOURCES += \ + png.c \ + pngerror.c \ +diff --git old/qtbase/src/3rdparty/libpng/png.c new/qtbase/src/3rdparty/libpng/png.c +index 757c755f97c..e411381f8f9 100644 +--- old/qtbase/src/3rdparty/libpng/png.c ++++ new/qtbase/src/3rdparty/libpng/png.c +@@ -1,7 +1,7 @@ + + /* png.c - location for general purpose libpng functions + * +- * Copyright (c) 2018-2019 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -14,27 +14,7 @@ + #include "pngpriv.h" + + /* Generate a compiler error if there is an old png.h in the search path. */ +-typedef png_libpng_version_1_6_37 Your_png_h_is_not_version_1_6_37; +- +-#ifdef __GNUC__ +-/* The version tests may need to be added to, but the problem warning has +- * consistently been fixed in GCC versions which obtain wide-spread release. +- * The problem is that many versions of GCC rearrange comparison expressions in +- * the optimizer in such a way that the results of the comparison will change +- * if signed integer overflow occurs. Such comparisons are not permitted in +- * ANSI C90, however GCC isn't clever enough to work out that that do not occur +- * below in png_ascii_from_fp and png_muldiv, so it produces a warning with +- * -Wextra. Unfortunately this is highly dependent on the optimizer and the +- * machine architecture so the warning comes and goes unpredictably and is +- * impossible to "fix", even were that a good idea. +- */ +-#if __GNUC__ == 7 && __GNUC_MINOR__ == 1 +-#define GCC_STRICT_OVERFLOW 1 +-#endif /* GNU 7.1.x */ +-#endif /* GNU */ +-#ifndef GCC_STRICT_OVERFLOW +-#define GCC_STRICT_OVERFLOW 0 +-#endif ++typedef png_libpng_version_1_6_41 Your_png_h_is_not_version_1_6_41; + + /* Tells libpng that we have already handled the first "num_bytes" bytes + * of the PNG file signature. If the PNG data is embedded into another +@@ -73,21 +53,21 @@ png_set_sig_bytes(png_structrp png_ptr, int num_bytes) + int PNGAPI + png_sig_cmp(png_const_bytep sig, size_t start, size_t num_to_check) + { +- png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10}; ++ static const png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10}; + + if (num_to_check > 8) + num_to_check = 8; + + else if (num_to_check < 1) +- return (-1); ++ return -1; + + if (start > 7) +- return (-1); ++ return -1; + + if (start + num_to_check > 8) + num_to_check = 8 - start; + +- return ((int)(memcmp(&sig[start], &png_signature[start], num_to_check))); ++ return memcmp(&sig[start], &png_signature[start], num_to_check); + } + + #endif /* READ */ +@@ -447,7 +427,6 @@ png_info_init_3,(png_infopp ptr_ptr, size_t png_info_struct_size), + memset(info_ptr, 0, (sizeof *info_ptr)); + } + +-/* The following API is not called internally */ + void PNGAPI + png_data_freer(png_const_structrp png_ptr, png_inforp info_ptr, + int freer, png_uint_32 mask) +@@ -686,9 +665,9 @@ png_voidp PNGAPI + png_get_io_ptr(png_const_structrp png_ptr) + { + if (png_ptr == NULL) +- return (NULL); ++ return NULL; + +- return (png_ptr->io_ptr); ++ return png_ptr->io_ptr; + } + + #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) +@@ -720,7 +699,7 @@ png_init_io(png_structrp png_ptr, png_FILE_p fp) + * + * Where UNSIGNED_MAX is the appropriate maximum unsigned value, so when the + * negative integral value is added the result will be an unsigned value +- * correspnding to the 2's complement representation. ++ * corresponding to the 2's complement representation. + */ + void PNGAPI + png_save_int_32(png_bytep buf, png_int_32 i) +@@ -752,7 +731,7 @@ png_convert_to_rfc1123_buffer(char out[29], png_const_timep ptime) + + { + size_t pos = 0; +- char number_buf[5]; /* enough for a four-digit year */ ++ char number_buf[5] = {0, 0, 0, 0, 0}; /* enough for a four-digit year */ + + # define APPEND_STRING(string) pos = png_safecat(out, 29, pos, (string)) + # define APPEND_NUMBER(format, value)\ +@@ -815,8 +794,8 @@ png_get_copyright(png_const_structrp png_ptr) + return PNG_STRING_COPYRIGHT + #else + return PNG_STRING_NEWLINE \ +- "libpng version 1.6.37" PNG_STRING_NEWLINE \ +- "Copyright (c) 2018-2019 Cosmin Truta" PNG_STRING_NEWLINE \ ++ "libpng version 1.6.41" PNG_STRING_NEWLINE \ ++ "Copyright (c) 2018-2024 Cosmin Truta" PNG_STRING_NEWLINE \ + "Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson" \ + PNG_STRING_NEWLINE \ + "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \ +@@ -977,7 +956,7 @@ png_reset_zstream(png_structrp png_ptr) + return Z_STREAM_ERROR; + + /* WARNING: this resets the window bits to the maximum! */ +- return (inflateReset(&png_ptr->zstream)); ++ return inflateReset(&png_ptr->zstream); + } + #endif /* READ */ + +@@ -986,7 +965,7 @@ png_uint_32 PNGAPI + png_access_version_number(void) + { + /* Version of *.c files used when building libpng */ +- return((png_uint_32)PNG_LIBPNG_VER); ++ return (png_uint_32)PNG_LIBPNG_VER; + } + + #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) +@@ -1843,12 +1822,12 @@ png_icc_profile_error(png_const_structrp png_ptr, png_colorspacerp colorspace, + # ifdef PNG_WARNINGS_SUPPORTED + else + { +- char number[PNG_NUMBER_BUFFER_SIZE]; /* +24 = 114*/ ++ char number[PNG_NUMBER_BUFFER_SIZE]; /* +24 = 114 */ + + pos = png_safecat(message, (sizeof message), pos, + png_format_number(number, number+(sizeof number), + PNG_NUMBER_FORMAT_x, value)); +- pos = png_safecat(message, (sizeof message), pos, "h: "); /*+2 = 116*/ ++ pos = png_safecat(message, (sizeof message), pos, "h: "); /* +2 = 116 */ + } + # endif + /* The 'reason' is an arbitrary message, allow +79 maximum 195 */ +@@ -2710,7 +2689,7 @@ png_check_IHDR(png_const_structrp png_ptr, + + int /* PRIVATE */ + png_check_fp_number(png_const_charp string, size_t size, int *statep, +- png_size_tp whereami) ++ size_t *whereami) + { + int state = *statep; + size_t i = *whereami; +@@ -2891,14 +2870,6 @@ png_pow10(int power) + /* Function to format a floating point value in ASCII with a given + * precision. + */ +-#if GCC_STRICT_OVERFLOW +-#pragma GCC diagnostic push +-/* The problem arises below with exp_b10, which can never overflow because it +- * comes, originally, from frexp and is therefore limited to a range which is +- * typically +/-710 (log2(DBL_MAX)/log2(DBL_MIN)). +- */ +-#pragma GCC diagnostic warning "-Wstrict-overflow=2" +-#endif /* GCC_STRICT_OVERFLOW */ + void /* PRIVATE */ + png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, size_t size, + double fp, unsigned int precision) +@@ -3220,10 +3191,6 @@ png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, size_t size, + /* Here on buffer too small. */ + png_error(png_ptr, "ASCII conversion buffer too small"); + } +-#if GCC_STRICT_OVERFLOW +-#pragma GCC diagnostic pop +-#endif /* GCC_STRICT_OVERFLOW */ +- + # endif /* FLOATING_POINT */ + + # ifdef PNG_FIXED_POINT_SUPPORTED +@@ -3251,7 +3218,7 @@ png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii, + if (num <= 0x80000000) /* else overflowed */ + { + unsigned int ndigits = 0, first = 16 /* flag value */; +- char digits[10]; ++ char digits[10] = {0}; + + while (num) + { +@@ -3336,15 +3303,6 @@ png_fixed(png_const_structrp png_ptr, double fp, png_const_charp text) + * the nearest .00001). Overflow and divide by zero are signalled in + * the result, a boolean - true on success, false on overflow. + */ +-#if GCC_STRICT_OVERFLOW /* from above */ +-/* It is not obvious which comparison below gets optimized in such a way that +- * signed overflow would change the result; looking through the code does not +- * reveal any tests which have the form GCC complains about, so presumably the +- * optimizer is moving an add or subtract into the 'if' somewhere. +- */ +-#pragma GCC diagnostic push +-#pragma GCC diagnostic warning "-Wstrict-overflow=2" +-#endif /* GCC_STRICT_OVERFLOW */ + int + png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times, + png_int_32 divisor) +@@ -3459,9 +3417,6 @@ png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times, + + return 0; + } +-#if GCC_STRICT_OVERFLOW +-#pragma GCC diagnostic pop +-#endif /* GCC_STRICT_OVERFLOW */ + #endif /* READ_GAMMA || INCH_CONVERSIONS */ + + #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_INCH_CONVERSIONS_SUPPORTED) +diff --git old/qtbase/src/3rdparty/libpng/png.h new/qtbase/src/3rdparty/libpng/png.h +index 139eb0dc0f3..d78c7799341 100644 +--- old/qtbase/src/3rdparty/libpng/png.h ++++ new/qtbase/src/3rdparty/libpng/png.h +@@ -1,9 +1,9 @@ + + /* png.h - header file for PNG reference library + * +- * libpng version 1.6.37 - April 14, 2019 ++ * libpng version 1.6.41 + * +- * Copyright (c) 2018-2019 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -15,7 +15,7 @@ + * libpng versions 0.89, June 1996, through 0.96, May 1997: Andreas Dilger + * libpng versions 0.97, January 1998, through 1.6.35, July 2018: + * Glenn Randers-Pehrson +- * libpng versions 1.6.36, December 2018, through 1.6.37, April 2019: ++ * libpng versions 1.6.36, December 2018, through 1.6.41, January 2024: + * Cosmin Truta + * See also "Contributing Authors", below. + */ +@@ -27,8 +27,8 @@ + * PNG Reference Library License version 2 + * --------------------------------------- + * +- * * Copyright (c) 1995-2019 The PNG Reference Library Authors. +- * * Copyright (c) 2018-2019 Cosmin Truta. ++ * * Copyright (c) 1995-2024 The PNG Reference Library Authors. ++ * * Copyright (c) 2018-2024 Cosmin Truta. + * * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson. + * * Copyright (c) 1996-1997 Andreas Dilger. + * * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -239,7 +239,7 @@ + * ... + * 1.5.30 15 10530 15.so.15.30[.0] + * ... +- * 1.6.37 16 10637 16.so.16.37[.0] ++ * 1.6.41 16 10641 16.so.16.41[.0] + * + * Henceforth the source version will match the shared-library major and + * minor numbers; the shared-library major version number will be used for +@@ -278,8 +278,8 @@ + */ + + /* Version information for png.h - this should match the version in png.c */ +-#define PNG_LIBPNG_VER_STRING "1.6.37" +-#define PNG_HEADER_VERSION_STRING " libpng version 1.6.37 - April 14, 2019\n" ++#define PNG_LIBPNG_VER_STRING "1.6.41" ++#define PNG_HEADER_VERSION_STRING " libpng version " PNG_LIBPNG_VER_STRING "\n" + + #define PNG_LIBPNG_VER_SONUM 16 + #define PNG_LIBPNG_VER_DLLNUM 16 +@@ -287,7 +287,7 @@ + /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */ + #define PNG_LIBPNG_VER_MAJOR 1 + #define PNG_LIBPNG_VER_MINOR 6 +-#define PNG_LIBPNG_VER_RELEASE 37 ++#define PNG_LIBPNG_VER_RELEASE 41 + + /* This should be zero for a public release, or non-zero for a + * development version. [Deprecated] +@@ -318,7 +318,7 @@ + * From version 1.0.1 it is: + * XXYYZZ, where XX=major, YY=minor, ZZ=release + */ +-#define PNG_LIBPNG_VER 10637 /* 1.6.37 */ ++#define PNG_LIBPNG_VER 10641 /* 1.6.41 */ + + /* Library configuration: these options cannot be changed after + * the library has been built. +@@ -428,7 +428,7 @@ extern "C" { + /* This triggers a compiler error in png.c, if png.c and png.h + * do not agree upon the version number. + */ +-typedef char* png_libpng_version_1_6_37; ++typedef char* png_libpng_version_1_6_41; + + /* Basic control structions. Read libpng-manual.txt or libpng.3 for more info. + * +@@ -849,7 +849,7 @@ PNG_FUNCTION(void, (PNGCAPI *png_longjmp_ptr), PNGARG((jmp_buf, int)), typedef); + #define PNG_TRANSFORM_GRAY_TO_RGB 0x2000 /* read only */ + /* Added to libpng-1.5.4 */ + #define PNG_TRANSFORM_EXPAND_16 0x4000 /* read only */ +-#if INT_MAX >= 0x8000 /* else this might break */ ++#if ~0U > 0xffffU /* or else this might break on a 16-bit machine */ + #define PNG_TRANSFORM_SCALE_16 0x8000 /* read only */ + #endif + +@@ -908,15 +908,15 @@ PNG_EXPORT(2, void, png_set_sig_bytes, (png_structrp png_ptr, int num_bytes)); + /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a + * PNG file. Returns zero if the supplied bytes match the 8-byte PNG + * signature, and non-zero otherwise. Having num_to_check == 0 or +- * start > 7 will always fail (ie return non-zero). ++ * start > 7 will always fail (i.e. return non-zero). + */ + PNG_EXPORT(3, int, png_sig_cmp, (png_const_bytep sig, size_t start, + size_t num_to_check)); + + /* Simple signature checking function. This is the same as calling +- * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n). ++ * png_check_sig(sig, n) := (png_sig_cmp(sig, 0, n) != 0). + */ +-#define png_check_sig(sig, n) !png_sig_cmp((sig), 0, (n)) ++#define png_check_sig(sig, n) (png_sig_cmp((sig), 0, (n)) != 0) + + /* Allocate and initialize png_ptr struct for reading, and any other memory. */ + PNG_EXPORTA(4, png_structp, png_create_read_struct, +@@ -1446,7 +1446,7 @@ PNG_EXPORT(66, void, png_set_crc_action, (png_structrp png_ptr, int crit_action, + * mainly useful for testing, as the defaults should work with most users. + * Those users who are tight on memory or want faster performance at the + * expense of compression can modify them. See the compression library +- * header file (zlib.h) for an explination of the compression functions. ++ * header file (zlib.h) for an explanation of the compression functions. + */ + + /* Set the filtering method(s) used by libpng. Currently, the only valid +@@ -1501,7 +1501,7 @@ PNG_FIXED_EXPORT(209, void, png_set_filter_heuristics_fixed, + * 0 - 9, corresponding directly to the zlib compression levels 0 - 9 + * (0 - no compression, 9 - "maximal" compression). Note that tests have + * shown that zlib compression levels 3-6 usually perform as well as level 9 +- * for PNG images, and do considerably fewer caclulations. In the future, ++ * for PNG images, and do considerably fewer calculations. In the future, + * these values may not correspond directly to the zlib compression levels. + */ + #ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED +@@ -1730,12 +1730,9 @@ PNG_EXPORT(97, void, png_free, (png_const_structrp png_ptr, png_voidp ptr)); + PNG_EXPORT(98, void, png_free_data, (png_const_structrp png_ptr, + png_inforp info_ptr, png_uint_32 free_me, int num)); + +-/* Reassign responsibility for freeing existing data, whether allocated ++/* Reassign the responsibility for freeing existing data, whether allocated + * by libpng or by the application; this works on the png_info structure passed +- * in, it does not change the state for other png_info structures. +- * +- * It is unlikely that this function works correctly as of 1.6.0 and using it +- * may result either in memory leaks or double free of allocated data. ++ * in, without changing the state for other png_info structures. + */ + PNG_EXPORT(99, void, png_data_freer, (png_const_structrp png_ptr, + png_inforp info_ptr, int freer, png_uint_32 mask)); +@@ -3207,11 +3204,18 @@ PNG_EXPORT(245, int, png_image_write_to_memory, (png_imagep image, void *memory, + #ifdef PNG_MIPS_MSA_API_SUPPORTED + # define PNG_MIPS_MSA 6 /* HARDWARE: MIPS Msa SIMD instructions supported */ + #endif +-#define PNG_IGNORE_ADLER32 8 ++#ifdef PNG_DISABLE_ADLER32_CHECK_SUPPORTED ++# define PNG_IGNORE_ADLER32 8 /* SOFTWARE: disable Adler32 check on IDAT */ ++#endif + #ifdef PNG_POWERPC_VSX_API_SUPPORTED +-# define PNG_POWERPC_VSX 10 /* HARDWARE: PowerPC VSX SIMD instructions supported */ ++# define PNG_POWERPC_VSX 10 /* HARDWARE: PowerPC VSX SIMD instructions ++ * supported */ + #endif +-#define PNG_OPTION_NEXT 12 /* Next option - numbers must be even */ ++#ifdef PNG_MIPS_MMI_API_SUPPORTED ++# define PNG_MIPS_MMI 12 /* HARDWARE: MIPS MMI SIMD instructions supported */ ++#endif ++ ++#define PNG_OPTION_NEXT 14 /* Next option - numbers must be even */ + + /* Return values: NOTE: there are four values and 'off' is *not* zero */ + #define PNG_OPTION_UNSET 0 /* Unset - defaults to off */ +diff --git old/qtbase/src/3rdparty/libpng/pngconf.h new/qtbase/src/3rdparty/libpng/pngconf.h +index 927a769dbee..30c1aad52d7 100644 +--- old/qtbase/src/3rdparty/libpng/pngconf.h ++++ new/qtbase/src/3rdparty/libpng/pngconf.h +@@ -1,9 +1,9 @@ + + /* pngconf.h - machine-configurable file for libpng + * +- * libpng version 1.6.37 ++ * libpng version 1.6.41 + * +- * Copyright (c) 2018-2019 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2016,2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -180,8 +180,8 @@ + * compiler-specific macros to the values required to change the calling + * conventions of the various functions. + */ +-#if defined(_Windows) || defined(_WINDOWS) || defined(WIN32) ||\ +- defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) ++#if defined(_WIN32) || defined(__WIN32__) || defined(__NT__) || \ ++ defined(__CYGWIN__) + /* Windows system (DOS doesn't support DLLs). Includes builds under Cygwin or + * MinGW on any architecture currently supported by Windows. Also includes + * Watcom builds but these need special treatment because they are not +diff --git old/qtbase/src/3rdparty/libpng/pngerror.c new/qtbase/src/3rdparty/libpng/pngerror.c +index ec3a709b9d2..29ebda79437 100644 +--- old/qtbase/src/3rdparty/libpng/pngerror.c ++++ new/qtbase/src/3rdparty/libpng/pngerror.c +@@ -1,7 +1,7 @@ + + /* pngerror.c - stub functions for i/o and memory allocation + * +- * Copyright (c) 2018 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -255,7 +255,7 @@ void + png_warning_parameter_unsigned(png_warning_parameters p, int number, int format, + png_alloc_size_t value) + { +- char buffer[PNG_NUMBER_BUFFER_SIZE]; ++ char buffer[PNG_NUMBER_BUFFER_SIZE] = {0}; + png_warning_parameter(p, number, PNG_FORMAT_NUMBER(buffer, format, value)); + } + +@@ -265,7 +265,7 @@ png_warning_parameter_signed(png_warning_parameters p, int number, int format, + { + png_alloc_size_t u; + png_charp str; +- char buffer[PNG_NUMBER_BUFFER_SIZE]; ++ char buffer[PNG_NUMBER_BUFFER_SIZE] = {0}; + + /* Avoid overflow by doing the negate in a png_alloc_size_t: */ + u = (png_alloc_size_t)value; +@@ -858,7 +858,7 @@ png_get_error_ptr(png_const_structrp png_ptr) + if (png_ptr == NULL) + return NULL; + +- return ((png_voidp)png_ptr->error_ptr); ++ return (png_voidp)png_ptr->error_ptr; + } + + +@@ -933,31 +933,25 @@ png_safe_warning(png_structp png_nonconst_ptr, png_const_charp warning_message) + #endif + + int /* PRIVATE */ +-png_safe_execute(png_imagep image_in, int (*function)(png_voidp), png_voidp arg) ++png_safe_execute(png_imagep image, int (*function)(png_voidp), png_voidp arg) + { +- volatile png_imagep image = image_in; +- volatile int result; +- volatile png_voidp saved_error_buf; ++ png_voidp saved_error_buf = image->opaque->error_buf; + jmp_buf safe_jmpbuf; ++ int result; + +- /* Safely execute function(arg) with png_error returning to this function. */ +- saved_error_buf = image->opaque->error_buf; +- result = setjmp(safe_jmpbuf) == 0; +- +- if (result != 0) ++ /* Safely execute function(arg), with png_error returning back here. */ ++ if (setjmp(safe_jmpbuf) == 0) + { +- + image->opaque->error_buf = safe_jmpbuf; + result = function(arg); ++ image->opaque->error_buf = saved_error_buf; ++ return result; + } + ++ /* On png_error, return via longjmp, pop the jmpbuf, and free the image. */ + image->opaque->error_buf = saved_error_buf; +- +- /* And do the cleanup prior to any failure return. */ +- if (result == 0) +- png_image_free(image); +- +- return result; ++ png_image_free(image); ++ return 0; + } + #endif /* SIMPLIFIED READ || SIMPLIFIED_WRITE */ + #endif /* READ || WRITE */ +diff --git old/qtbase/src/3rdparty/libpng/pngget.c new/qtbase/src/3rdparty/libpng/pngget.c +index 5abf1efd9f7..1084b268ff9 100644 +--- old/qtbase/src/3rdparty/libpng/pngget.c ++++ new/qtbase/src/3rdparty/libpng/pngget.c +@@ -1,7 +1,7 @@ + + /* pngget.c - retrieval of values from info struct + * +- * Copyright (c) 2018 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -21,18 +21,29 @@ png_get_valid(png_const_structrp png_ptr, png_const_inforp info_ptr, + png_uint_32 flag) + { + if (png_ptr != NULL && info_ptr != NULL) +- return(info_ptr->valid & flag); ++ { ++#ifdef PNG_READ_tRNS_SUPPORTED ++ /* png_handle_PLTE() may have canceled a valid tRNS chunk but left the ++ * 'valid' flag for the detection of duplicate chunks. Do not report a ++ * valid tRNS chunk in this case. ++ */ ++ if (flag == PNG_INFO_tRNS && png_ptr->num_trans == 0) ++ return 0; ++#endif + +- return(0); ++ return info_ptr->valid & flag; ++ } ++ ++ return 0; + } + + size_t PNGAPI + png_get_rowbytes(png_const_structrp png_ptr, png_const_inforp info_ptr) + { + if (png_ptr != NULL && info_ptr != NULL) +- return(info_ptr->rowbytes); ++ return info_ptr->rowbytes; + +- return(0); ++ return 0; + } + + #ifdef PNG_INFO_IMAGE_SUPPORTED +@@ -40,9 +51,9 @@ png_bytepp PNGAPI + png_get_rows(png_const_structrp png_ptr, png_const_inforp info_ptr) + { + if (png_ptr != NULL && info_ptr != NULL) +- return(info_ptr->row_pointers); ++ return info_ptr->row_pointers; + +- return(0); ++ return 0; + } + #endif + +@@ -54,7 +65,7 @@ png_get_image_width(png_const_structrp png_ptr, png_const_inforp info_ptr) + if (png_ptr != NULL && info_ptr != NULL) + return info_ptr->width; + +- return (0); ++ return 0; + } + + png_uint_32 PNGAPI +@@ -63,7 +74,7 @@ png_get_image_height(png_const_structrp png_ptr, png_const_inforp info_ptr) + if (png_ptr != NULL && info_ptr != NULL) + return info_ptr->height; + +- return (0); ++ return 0; + } + + png_byte PNGAPI +@@ -72,7 +83,7 @@ png_get_bit_depth(png_const_structrp png_ptr, png_const_inforp info_ptr) + if (png_ptr != NULL && info_ptr != NULL) + return info_ptr->bit_depth; + +- return (0); ++ return 0; + } + + png_byte PNGAPI +@@ -81,7 +92,7 @@ png_get_color_type(png_const_structrp png_ptr, png_const_inforp info_ptr) + if (png_ptr != NULL && info_ptr != NULL) + return info_ptr->color_type; + +- return (0); ++ return 0; + } + + png_byte PNGAPI +@@ -90,7 +101,7 @@ png_get_filter_type(png_const_structrp png_ptr, png_const_inforp info_ptr) + if (png_ptr != NULL && info_ptr != NULL) + return info_ptr->filter_type; + +- return (0); ++ return 0; + } + + png_byte PNGAPI +@@ -99,7 +110,7 @@ png_get_interlace_type(png_const_structrp png_ptr, png_const_inforp info_ptr) + if (png_ptr != NULL && info_ptr != NULL) + return info_ptr->interlace_type; + +- return (0); ++ return 0; + } + + png_byte PNGAPI +@@ -108,7 +119,7 @@ png_get_compression_type(png_const_structrp png_ptr, png_const_inforp info_ptr) + if (png_ptr != NULL && info_ptr != NULL) + return info_ptr->compression_type; + +- return (0); ++ return 0; + } + + png_uint_32 PNGAPI +@@ -116,21 +127,20 @@ png_get_x_pixels_per_meter(png_const_structrp png_ptr, png_const_inforp + info_ptr) + { + #ifdef PNG_pHYs_SUPPORTED ++ png_debug(1, "in png_get_x_pixels_per_meter"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_pHYs) != 0) +- { +- png_debug1(1, "in %s retrieval function", +- "png_get_x_pixels_per_meter"); +- +- if (info_ptr->phys_unit_type == PNG_RESOLUTION_METER) +- return (info_ptr->x_pixels_per_unit); +- } ++ { ++ if (info_ptr->phys_unit_type == PNG_RESOLUTION_METER) ++ return info_ptr->x_pixels_per_unit; ++ } + #else + PNG_UNUSED(png_ptr) + PNG_UNUSED(info_ptr) + #endif + +- return (0); ++ return 0; + } + + png_uint_32 PNGAPI +@@ -138,42 +148,41 @@ png_get_y_pixels_per_meter(png_const_structrp png_ptr, png_const_inforp + info_ptr) + { + #ifdef PNG_pHYs_SUPPORTED ++ png_debug(1, "in png_get_y_pixels_per_meter"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_pHYs) != 0) + { +- png_debug1(1, "in %s retrieval function", +- "png_get_y_pixels_per_meter"); +- + if (info_ptr->phys_unit_type == PNG_RESOLUTION_METER) +- return (info_ptr->y_pixels_per_unit); ++ return info_ptr->y_pixels_per_unit; + } + #else + PNG_UNUSED(png_ptr) + PNG_UNUSED(info_ptr) + #endif + +- return (0); ++ return 0; + } + + png_uint_32 PNGAPI + png_get_pixels_per_meter(png_const_structrp png_ptr, png_const_inforp info_ptr) + { + #ifdef PNG_pHYs_SUPPORTED ++ png_debug(1, "in png_get_pixels_per_meter"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_pHYs) != 0) + { +- png_debug1(1, "in %s retrieval function", "png_get_pixels_per_meter"); +- + if (info_ptr->phys_unit_type == PNG_RESOLUTION_METER && + info_ptr->x_pixels_per_unit == info_ptr->y_pixels_per_unit) +- return (info_ptr->x_pixels_per_unit); ++ return info_ptr->x_pixels_per_unit; + } + #else + PNG_UNUSED(png_ptr) + PNG_UNUSED(info_ptr) + #endif + +- return (0); ++ return 0; + } + + #ifdef PNG_FLOATING_POINT_SUPPORTED +@@ -182,21 +191,21 @@ png_get_pixel_aspect_ratio(png_const_structrp png_ptr, png_const_inforp + info_ptr) + { + #ifdef PNG_READ_pHYs_SUPPORTED ++ png_debug(1, "in png_get_pixel_aspect_ratio"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_pHYs) != 0) + { +- png_debug1(1, "in %s retrieval function", "png_get_aspect_ratio"); +- + if (info_ptr->x_pixels_per_unit != 0) +- return ((float)((float)info_ptr->y_pixels_per_unit +- /(float)info_ptr->x_pixels_per_unit)); ++ return (float)info_ptr->y_pixels_per_unit ++ / (float)info_ptr->x_pixels_per_unit; + } + #else + PNG_UNUSED(png_ptr) + PNG_UNUSED(info_ptr) + #endif + +- return ((float)0.0); ++ return (float)0.0; + } + #endif + +@@ -206,6 +215,8 @@ png_get_pixel_aspect_ratio_fixed(png_const_structrp png_ptr, + png_const_inforp info_ptr) + { + #ifdef PNG_READ_pHYs_SUPPORTED ++ png_debug(1, "in png_get_pixel_aspect_ratio_fixed"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_pHYs) != 0 && + info_ptr->x_pixels_per_unit > 0 && info_ptr->y_pixels_per_unit > 0 && +@@ -214,8 +225,6 @@ png_get_pixel_aspect_ratio_fixed(png_const_structrp png_ptr, + { + png_fixed_point res; + +- png_debug1(1, "in %s retrieval function", "png_get_aspect_ratio_fixed"); +- + /* The following casts work because a PNG 4 byte integer only has a valid + * range of 0..2^31-1; otherwise the cast might overflow. + */ +@@ -236,80 +245,80 @@ png_int_32 PNGAPI + png_get_x_offset_microns(png_const_structrp png_ptr, png_const_inforp info_ptr) + { + #ifdef PNG_oFFs_SUPPORTED ++ png_debug(1, "in png_get_x_offset_microns"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_oFFs) != 0) + { +- png_debug1(1, "in %s retrieval function", "png_get_x_offset_microns"); +- + if (info_ptr->offset_unit_type == PNG_OFFSET_MICROMETER) +- return (info_ptr->x_offset); ++ return info_ptr->x_offset; + } + #else + PNG_UNUSED(png_ptr) + PNG_UNUSED(info_ptr) + #endif + +- return (0); ++ return 0; + } + + png_int_32 PNGAPI + png_get_y_offset_microns(png_const_structrp png_ptr, png_const_inforp info_ptr) + { + #ifdef PNG_oFFs_SUPPORTED ++ png_debug(1, "in png_get_y_offset_microns"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_oFFs) != 0) + { +- png_debug1(1, "in %s retrieval function", "png_get_y_offset_microns"); +- + if (info_ptr->offset_unit_type == PNG_OFFSET_MICROMETER) +- return (info_ptr->y_offset); ++ return info_ptr->y_offset; + } + #else + PNG_UNUSED(png_ptr) + PNG_UNUSED(info_ptr) + #endif + +- return (0); ++ return 0; + } + + png_int_32 PNGAPI + png_get_x_offset_pixels(png_const_structrp png_ptr, png_const_inforp info_ptr) + { + #ifdef PNG_oFFs_SUPPORTED ++ png_debug(1, "in png_get_x_offset_pixels"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_oFFs) != 0) + { +- png_debug1(1, "in %s retrieval function", "png_get_x_offset_pixels"); +- + if (info_ptr->offset_unit_type == PNG_OFFSET_PIXEL) +- return (info_ptr->x_offset); ++ return info_ptr->x_offset; + } + #else + PNG_UNUSED(png_ptr) + PNG_UNUSED(info_ptr) + #endif + +- return (0); ++ return 0; + } + + png_int_32 PNGAPI + png_get_y_offset_pixels(png_const_structrp png_ptr, png_const_inforp info_ptr) + { + #ifdef PNG_oFFs_SUPPORTED ++ png_debug(1, "in png_get_y_offset_pixels"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_oFFs) != 0) + { +- png_debug1(1, "in %s retrieval function", "png_get_y_offset_pixels"); +- + if (info_ptr->offset_unit_type == PNG_OFFSET_PIXEL) +- return (info_ptr->y_offset); ++ return info_ptr->y_offset; + } + #else + PNG_UNUSED(png_ptr) + PNG_UNUSED(info_ptr) + #endif + +- return (0); ++ return 0; + } + + #ifdef PNG_INCH_CONVERSIONS_SUPPORTED +@@ -423,11 +432,11 @@ png_get_pHYs_dpi(png_const_structrp png_ptr, png_const_inforp info_ptr, + { + png_uint_32 retval = 0; + ++ png_debug1(1, "in %s retrieval function", "pHYs"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_pHYs) != 0) + { +- png_debug1(1, "in %s retrieval function", "pHYs"); +- + if (res_x != NULL) + { + *res_x = info_ptr->x_pixels_per_unit; +@@ -453,7 +462,7 @@ png_get_pHYs_dpi(png_const_structrp png_ptr, png_const_inforp info_ptr, + } + } + +- return (retval); ++ return retval; + } + #endif /* pHYs */ + #endif /* INCH_CONVERSIONS */ +@@ -467,9 +476,9 @@ png_byte PNGAPI + png_get_channels(png_const_structrp png_ptr, png_const_inforp info_ptr) + { + if (png_ptr != NULL && info_ptr != NULL) +- return(info_ptr->channels); ++ return info_ptr->channels; + +- return (0); ++ return 0; + } + + #ifdef PNG_READ_SUPPORTED +@@ -477,9 +486,9 @@ png_const_bytep PNGAPI + png_get_signature(png_const_structrp png_ptr, png_const_inforp info_ptr) + { + if (png_ptr != NULL && info_ptr != NULL) +- return(info_ptr->signature); ++ return info_ptr->signature; + +- return (NULL); ++ return NULL; + } + #endif + +@@ -488,17 +497,17 @@ png_uint_32 PNGAPI + png_get_bKGD(png_const_structrp png_ptr, png_inforp info_ptr, + png_color_16p *background) + { ++ png_debug1(1, "in %s retrieval function", "bKGD"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_bKGD) != 0 && + background != NULL) + { +- png_debug1(1, "in %s retrieval function", "bKGD"); +- + *background = &(info_ptr->background); +- return (PNG_INFO_bKGD); ++ return PNG_INFO_bKGD; + } + +- return (0); ++ return 0; + } + #endif + +@@ -513,6 +522,8 @@ png_get_cHRM(png_const_structrp png_ptr, png_const_inforp info_ptr, + double *white_x, double *white_y, double *red_x, double *red_y, + double *green_x, double *green_y, double *blue_x, double *blue_y) + { ++ png_debug1(1, "in %s retrieval function", "cHRM"); ++ + /* Quiet API change: this code used to only return the end points if a cHRM + * chunk was present, but the end points can also come from iCCP or sRGB + * chunks, so in 1.6.0 the png_get_ APIs return the end points regardless and +@@ -522,8 +533,6 @@ png_get_cHRM(png_const_structrp png_ptr, png_const_inforp info_ptr, + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0) + { +- png_debug1(1, "in %s retrieval function", "cHRM"); +- + if (white_x != NULL) + *white_x = png_float(png_ptr, + info_ptr->colorspace.end_points_xy.whitex, "cHRM white X"); +@@ -548,10 +557,10 @@ png_get_cHRM(png_const_structrp png_ptr, png_const_inforp info_ptr, + if (blue_y != NULL) + *blue_y = png_float(png_ptr, info_ptr->colorspace.end_points_xy.bluey, + "cHRM blue Y"); +- return (PNG_INFO_cHRM); ++ return PNG_INFO_cHRM; + } + +- return (0); ++ return 0; + } + + png_uint_32 PNGAPI +@@ -560,11 +569,11 @@ png_get_cHRM_XYZ(png_const_structrp png_ptr, png_const_inforp info_ptr, + double *green_Y, double *green_Z, double *blue_X, double *blue_Y, + double *blue_Z) + { ++ png_debug1(1, "in %s retrieval function", "cHRM_XYZ(float)"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0) + { +- png_debug1(1, "in %s retrieval function", "cHRM_XYZ(float)"); +- + if (red_X != NULL) + *red_X = png_float(png_ptr, info_ptr->colorspace.end_points_XYZ.red_X, + "cHRM red X"); +@@ -592,10 +601,10 @@ png_get_cHRM_XYZ(png_const_structrp png_ptr, png_const_inforp info_ptr, + if (blue_Z != NULL) + *blue_Z = png_float(png_ptr, + info_ptr->colorspace.end_points_XYZ.blue_Z, "cHRM blue Z"); +- return (PNG_INFO_cHRM); ++ return PNG_INFO_cHRM; + } + +- return (0); ++ return 0; + } + # endif + +@@ -608,11 +617,11 @@ png_get_cHRM_XYZ_fixed(png_const_structrp png_ptr, png_const_inforp info_ptr, + png_fixed_point *int_blue_X, png_fixed_point *int_blue_Y, + png_fixed_point *int_blue_Z) + { ++ png_debug1(1, "in %s retrieval function", "cHRM_XYZ"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0) + { +- png_debug1(1, "in %s retrieval function", "cHRM_XYZ"); +- + if (int_red_X != NULL) + *int_red_X = info_ptr->colorspace.end_points_XYZ.red_X; + if (int_red_Y != NULL) +@@ -631,10 +640,10 @@ png_get_cHRM_XYZ_fixed(png_const_structrp png_ptr, png_const_inforp info_ptr, + *int_blue_Y = info_ptr->colorspace.end_points_XYZ.blue_Y; + if (int_blue_Z != NULL) + *int_blue_Z = info_ptr->colorspace.end_points_XYZ.blue_Z; +- return (PNG_INFO_cHRM); ++ return PNG_INFO_cHRM; + } + +- return (0); ++ return 0; + } + + png_uint_32 PNGAPI +@@ -664,10 +673,10 @@ png_get_cHRM_fixed(png_const_structrp png_ptr, png_const_inforp info_ptr, + *blue_x = info_ptr->colorspace.end_points_xy.bluex; + if (blue_y != NULL) + *blue_y = info_ptr->colorspace.end_points_xy.bluey; +- return (PNG_INFO_cHRM); ++ return PNG_INFO_cHRM; + } + +- return (0); ++ return 0; + } + # endif + #endif +@@ -685,10 +694,10 @@ png_get_gAMA_fixed(png_const_structrp png_ptr, png_const_inforp info_ptr, + file_gamma != NULL) + { + *file_gamma = info_ptr->colorspace.gamma; +- return (PNG_INFO_gAMA); ++ return PNG_INFO_gAMA; + } + +- return (0); ++ return 0; + } + # endif + +@@ -705,10 +714,10 @@ png_get_gAMA(png_const_structrp png_ptr, png_const_inforp info_ptr, + { + *file_gamma = png_float(png_ptr, info_ptr->colorspace.gamma, + "png_get_gAMA"); +- return (PNG_INFO_gAMA); ++ return PNG_INFO_gAMA; + } + +- return (0); ++ return 0; + } + # endif + #endif +@@ -724,10 +733,10 @@ png_get_sRGB(png_const_structrp png_ptr, png_const_inforp info_ptr, + (info_ptr->valid & PNG_INFO_sRGB) != 0 && file_srgb_intent != NULL) + { + *file_srgb_intent = info_ptr->colorspace.rendering_intent; +- return (PNG_INFO_sRGB); ++ return PNG_INFO_sRGB; + } + +- return (0); ++ return 0; + } + #endif + +@@ -751,10 +760,10 @@ png_get_iCCP(png_const_structrp png_ptr, png_inforp info_ptr, + */ + if (compression_type != NULL) + *compression_type = PNG_COMPRESSION_TYPE_BASE; +- return (PNG_INFO_iCCP); ++ return PNG_INFO_iCCP; + } + +- return (0); ++ return 0; + + } + #endif +@@ -764,13 +773,15 @@ int PNGAPI + png_get_sPLT(png_const_structrp png_ptr, png_inforp info_ptr, + png_sPLT_tpp spalettes) + { ++ png_debug1(1, "in %s retrieval function", "sPLT"); ++ + if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL) + { + *spalettes = info_ptr->splt_palettes; + return info_ptr->splt_palettes_num; + } + +- return (0); ++ return 0; + } + #endif + +@@ -796,10 +807,10 @@ png_get_eXIf_1(png_const_structrp png_ptr, png_const_inforp info_ptr, + { + *num_exif = info_ptr->num_exif; + *exif = info_ptr->exif; +- return (PNG_INFO_eXIf); ++ return PNG_INFO_eXIf; + } + +- return (0); ++ return 0; + } + #endif + +@@ -814,10 +825,10 @@ png_get_hIST(png_const_structrp png_ptr, png_inforp info_ptr, + (info_ptr->valid & PNG_INFO_hIST) != 0 && hist != NULL) + { + *hist = info_ptr->hist; +- return (PNG_INFO_hIST); ++ return PNG_INFO_hIST; + } + +- return (0); ++ return 0; + } + #endif + +@@ -830,7 +841,7 @@ png_get_IHDR(png_const_structrp png_ptr, png_const_inforp info_ptr, + png_debug1(1, "in %s retrieval function", "IHDR"); + + if (png_ptr == NULL || info_ptr == NULL) +- return (0); ++ return 0; + + if (width != NULL) + *width = info_ptr->width; +@@ -862,7 +873,7 @@ png_get_IHDR(png_const_structrp png_ptr, png_const_inforp info_ptr, + info_ptr->bit_depth, info_ptr->color_type, info_ptr->interlace_type, + info_ptr->compression_type, info_ptr->filter_type); + +- return (1); ++ return 1; + } + + #ifdef PNG_oFFs_SUPPORTED +@@ -879,10 +890,10 @@ png_get_oFFs(png_const_structrp png_ptr, png_const_inforp info_ptr, + *offset_x = info_ptr->x_offset; + *offset_y = info_ptr->y_offset; + *unit_type = (int)info_ptr->offset_unit_type; +- return (PNG_INFO_oFFs); ++ return PNG_INFO_oFFs; + } + +- return (0); ++ return 0; + } + #endif + +@@ -906,10 +917,10 @@ png_get_pCAL(png_const_structrp png_ptr, png_inforp info_ptr, + *nparams = (int)info_ptr->pcal_nparams; + *units = info_ptr->pcal_units; + *params = info_ptr->pcal_params; +- return (PNG_INFO_pCAL); ++ return PNG_INFO_pCAL; + } + +- return (0); ++ return 0; + } + #endif + +@@ -921,6 +932,8 @@ png_uint_32 PNGAPI + png_get_sCAL_fixed(png_const_structrp png_ptr, png_const_inforp info_ptr, + int *unit, png_fixed_point *width, png_fixed_point *height) + { ++ png_debug1(1, "in %s retrieval function", "sCAL"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_sCAL) != 0) + { +@@ -932,10 +945,10 @@ png_get_sCAL_fixed(png_const_structrp png_ptr, png_const_inforp info_ptr, + *width = png_fixed(png_ptr, atof(info_ptr->scal_s_width), "sCAL width"); + *height = png_fixed(png_ptr, atof(info_ptr->scal_s_height), + "sCAL height"); +- return (PNG_INFO_sCAL); ++ return PNG_INFO_sCAL; + } + +- return(0); ++ return 0; + } + # endif /* FLOATING_ARITHMETIC */ + # endif /* FIXED_POINT */ +@@ -944,32 +957,36 @@ png_uint_32 PNGAPI + png_get_sCAL(png_const_structrp png_ptr, png_const_inforp info_ptr, + int *unit, double *width, double *height) + { ++ png_debug1(1, "in %s retrieval function", "sCAL(float)"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_sCAL) != 0) + { + *unit = info_ptr->scal_unit; + *width = atof(info_ptr->scal_s_width); + *height = atof(info_ptr->scal_s_height); +- return (PNG_INFO_sCAL); ++ return PNG_INFO_sCAL; + } + +- return(0); ++ return 0; + } + # endif /* FLOATING POINT */ + png_uint_32 PNGAPI + png_get_sCAL_s(png_const_structrp png_ptr, png_const_inforp info_ptr, + int *unit, png_charpp width, png_charpp height) + { ++ png_debug1(1, "in %s retrieval function", "sCAL(str)"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_sCAL) != 0) + { + *unit = info_ptr->scal_unit; + *width = info_ptr->scal_s_width; + *height = info_ptr->scal_s_height; +- return (PNG_INFO_sCAL); ++ return PNG_INFO_sCAL; + } + +- return(0); ++ return 0; + } + #endif /* sCAL */ + +@@ -1004,7 +1021,7 @@ png_get_pHYs(png_const_structrp png_ptr, png_const_inforp info_ptr, + } + } + +- return (retval); ++ return retval; + } + #endif /* pHYs */ + +@@ -1020,10 +1037,10 @@ png_get_PLTE(png_const_structrp png_ptr, png_inforp info_ptr, + *palette = info_ptr->palette; + *num_palette = info_ptr->num_palette; + png_debug1(3, "num_palette = %d", *num_palette); +- return (PNG_INFO_PLTE); ++ return PNG_INFO_PLTE; + } + +- return (0); ++ return 0; + } + + #ifdef PNG_sBIT_SUPPORTED +@@ -1037,10 +1054,10 @@ png_get_sBIT(png_const_structrp png_ptr, png_inforp info_ptr, + (info_ptr->valid & PNG_INFO_sBIT) != 0 && sig_bit != NULL) + { + *sig_bit = &(info_ptr->sig_bit); +- return (PNG_INFO_sBIT); ++ return PNG_INFO_sBIT; + } + +- return (0); ++ return 0; + } + #endif + +@@ -1051,7 +1068,7 @@ png_get_text(png_const_structrp png_ptr, png_inforp info_ptr, + { + if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0) + { +- png_debug1(1, "in 0x%lx retrieval function", ++ png_debug1(1, "in text retrieval function, chunk typeid = 0x%lx", + (unsigned long)png_ptr->chunk_name); + + if (text_ptr != NULL) +@@ -1066,7 +1083,7 @@ png_get_text(png_const_structrp png_ptr, png_inforp info_ptr, + if (num_text != NULL) + *num_text = 0; + +- return(0); ++ return 0; + } + #endif + +@@ -1081,10 +1098,10 @@ png_get_tIME(png_const_structrp png_ptr, png_inforp info_ptr, + (info_ptr->valid & PNG_INFO_tIME) != 0 && mod_time != NULL) + { + *mod_time = &(info_ptr->mod_time); +- return (PNG_INFO_tIME); ++ return PNG_INFO_tIME; + } + +- return (0); ++ return 0; + } + #endif + +@@ -1094,11 +1111,12 @@ png_get_tRNS(png_const_structrp png_ptr, png_inforp info_ptr, + png_bytep *trans_alpha, int *num_trans, png_color_16p *trans_color) + { + png_uint_32 retval = 0; ++ ++ png_debug1(1, "in %s retrieval function", "tRNS"); ++ + if (png_ptr != NULL && info_ptr != NULL && + (info_ptr->valid & PNG_INFO_tRNS) != 0) + { +- png_debug1(1, "in %s retrieval function", "tRNS"); +- + if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + { + if (trans_alpha != NULL) +@@ -1130,7 +1148,7 @@ png_get_tRNS(png_const_structrp png_ptr, png_inforp info_ptr, + } + } + +- return (retval); ++ return retval; + } + #endif + +@@ -1145,13 +1163,13 @@ png_get_unknown_chunks(png_const_structrp png_ptr, png_inforp info_ptr, + return info_ptr->unknown_chunks_num; + } + +- return (0); ++ return 0; + } + #endif + + #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED + png_byte PNGAPI +-png_get_rgb_to_gray_status (png_const_structrp png_ptr) ++png_get_rgb_to_gray_status(png_const_structrp png_ptr) + { + return (png_byte)(png_ptr ? png_ptr->rgb_to_gray_status : 0); + } +@@ -1192,27 +1210,27 @@ png_get_compression_buffer_size(png_const_structrp png_ptr) + /* These functions were added to libpng 1.2.6 and were enabled + * by default in libpng-1.4.0 */ + png_uint_32 PNGAPI +-png_get_user_width_max (png_const_structrp png_ptr) ++png_get_user_width_max(png_const_structrp png_ptr) + { + return (png_ptr ? png_ptr->user_width_max : 0); + } + + png_uint_32 PNGAPI +-png_get_user_height_max (png_const_structrp png_ptr) ++png_get_user_height_max(png_const_structrp png_ptr) + { + return (png_ptr ? png_ptr->user_height_max : 0); + } + + /* This function was added to libpng 1.4.0 */ + png_uint_32 PNGAPI +-png_get_chunk_cache_max (png_const_structrp png_ptr) ++png_get_chunk_cache_max(png_const_structrp png_ptr) + { + return (png_ptr ? png_ptr->user_chunk_cache_max : 0); + } + + /* This function was added to libpng 1.4.1 */ + png_alloc_size_t PNGAPI +-png_get_chunk_malloc_max (png_const_structrp png_ptr) ++png_get_chunk_malloc_max(png_const_structrp png_ptr) + { + return (png_ptr ? png_ptr->user_chunk_malloc_max : 0); + } +@@ -1221,13 +1239,13 @@ png_get_chunk_malloc_max (png_const_structrp png_ptr) + /* These functions were added to libpng 1.4.0 */ + #ifdef PNG_IO_STATE_SUPPORTED + png_uint_32 PNGAPI +-png_get_io_state (png_const_structrp png_ptr) ++png_get_io_state(png_const_structrp png_ptr) + { + return png_ptr->io_state; + } + + png_uint_32 PNGAPI +-png_get_io_chunk_type (png_const_structrp png_ptr) ++png_get_io_chunk_type(png_const_structrp png_ptr) + { + return png_ptr->chunk_name; + } +@@ -1241,7 +1259,7 @@ png_get_palette_max(png_const_structp png_ptr, png_const_infop info_ptr) + if (png_ptr != NULL && info_ptr != NULL) + return png_ptr->num_palette_max; + +- return (-1); ++ return -1; + } + # endif + #endif +diff --git old/qtbase/src/3rdparty/libpng/pnglibconf.h new/qtbase/src/3rdparty/libpng/pnglibconf.h +index e1e27e957ea..d768a8ef087 100644 +--- old/qtbase/src/3rdparty/libpng/pnglibconf.h ++++ new/qtbase/src/3rdparty/libpng/pnglibconf.h +@@ -1,8 +1,8 @@ + /* pnglibconf.h - library build configuration */ + +-/* libpng version 1.6.37 */ ++/* libpng version 1.6.41 */ + +-/* Copyright (c) 2018-2019 Cosmin Truta */ ++/* Copyright (c) 2018-2024 Cosmin Truta */ + /* Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson */ + + /* This code is released under the libpng license. */ +@@ -27,6 +27,7 @@ + #define PNG_COLORSPACE_SUPPORTED + #define PNG_CONSOLE_IO_SUPPORTED + #define PNG_CONVERT_tIME_SUPPORTED ++/*#undef PNG_DISABLE_ADLER32_CHECK_SUPPORTED*/ + #define PNG_EASY_ACCESS_SUPPORTED + /*#undef PNG_ERROR_NUMBERS_SUPPORTED*/ + #define PNG_ERROR_TEXT_SUPPORTED +@@ -41,6 +42,10 @@ + #define PNG_INCH_CONVERSIONS_SUPPORTED + #define PNG_INFO_IMAGE_SUPPORTED + #define PNG_IO_STATE_SUPPORTED ++/*#undef PNG_MIPS_MMI_API_SUPPORTED*/ ++/*#undef PNG_MIPS_MMI_CHECK_SUPPORTED*/ ++/*#undef PNG_MIPS_MSA_API_SUPPORTED*/ ++/*#undef PNG_MIPS_MSA_CHECK_SUPPORTED*/ + #define PNG_MNG_FEATURES_SUPPORTED + #define PNG_POINTER_INDEXING_SUPPORTED + /*#undef PNG_POWERPC_VSX_API_SUPPORTED*/ +diff --git old/qtbase/src/3rdparty/libpng/pngpread.c new/qtbase/src/3rdparty/libpng/pngpread.c +index e283627b77c..be640f77a9b 100644 +--- old/qtbase/src/3rdparty/libpng/pngpread.c ++++ new/qtbase/src/3rdparty/libpng/pngpread.c +@@ -1,7 +1,7 @@ + + /* pngpread.c - read a png file in push mode + * +- * Copyright (c) 2018 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -145,10 +145,10 @@ png_push_read_sig(png_structrp png_ptr, png_inforp info_ptr) + num_to_check); + png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes + num_to_check); + +- if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check)) ++ if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check) != 0) + { + if (num_checked < 4 && +- png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4)) ++ png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4) != 0) + png_error(png_ptr, "Not a PNG file"); + + else +@@ -1089,7 +1089,7 @@ png_voidp PNGAPI + png_get_progressive_ptr(png_const_structrp png_ptr) + { + if (png_ptr == NULL) +- return (NULL); ++ return NULL; + + return png_ptr->io_ptr; + } +diff --git old/qtbase/src/3rdparty/libpng/pngpriv.h new/qtbase/src/3rdparty/libpng/pngpriv.h +index 2ab9b70d736..3a3e9d3564d 100644 +--- old/qtbase/src/3rdparty/libpng/pngpriv.h ++++ new/qtbase/src/3rdparty/libpng/pngpriv.h +@@ -1,7 +1,7 @@ + + /* pngpriv.h - private declarations for use inside libpng + * +- * Copyright (c) 2018-2019 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -23,12 +23,6 @@ + #ifndef PNGPRIV_H + #define PNGPRIV_H + +-#ifdef _MSC_VER +-# ifndef _CRT_SECURE_NO_DEPRECATE +-# define _CRT_SECURE_NO_DEPRECATE +-# endif +-#endif +- + /* Feature Test Macros. The following are defined here to ensure that correctly + * implemented libraries reveal the APIs libpng needs to build and hide those + * that are not needed and potentially damaging to the compilation. +@@ -180,7 +174,7 @@ + # else /* !defined __ARM_NEON__ */ + /* The 'intrinsics' code simply won't compile without this -mfpu=neon: + */ +-# if !defined(__aarch64__) ++# if !defined(__aarch64__) && !defined(_M_ARM64) + /* The assembler code currently does not work on ARM64 */ + # define PNG_ARM_NEON_IMPLEMENTATION 2 + # endif /* __aarch64__ */ +@@ -191,6 +185,8 @@ + /* Use the intrinsics code by default. */ + # define PNG_ARM_NEON_IMPLEMENTATION 1 + # endif ++#else /* PNG_ARM_NEON_OPT == 0 */ ++# define PNG_ARM_NEON_IMPLEMENTATION 0 + #endif /* PNG_ARM_NEON_OPT > 0 */ + + #ifndef PNG_MIPS_MSA_OPT +@@ -201,6 +197,18 @@ + # endif + #endif + ++#ifndef PNG_MIPS_MMI_OPT ++# ifdef PNG_MIPS_MMI ++# if defined(__mips_loongson_mmi) && (_MIPS_SIM == _ABI64) && defined(PNG_ALIGNED_MEMORY_SUPPORTED) ++# define PNG_MIPS_MMI_OPT 1 ++# else ++# define PNG_MIPS_MMI_OPT 0 ++# endif ++# else ++# define PNG_MIPS_MMI_OPT 0 ++# endif ++#endif ++ + #ifndef PNG_POWERPC_VSX_OPT + # if defined(__PPC64__) && defined(__ALTIVEC__) && defined(__VSX__) + # define PNG_POWERPC_VSX_OPT 2 +@@ -209,6 +217,14 @@ + # endif + #endif + ++#ifndef PNG_LOONGARCH_LSX_OPT ++# if defined(__loongarch_sx) ++# define PNG_LOONGARCH_LSX_OPT 1 ++# else ++# define PNG_LOONGARCH_LSX_OPT 0 ++# endif ++#endif ++ + #ifndef PNG_INTEL_SSE_OPT + # ifdef PNG_INTEL_SSE + /* Only check for SSE if the build configuration has been modified to +@@ -252,7 +268,6 @@ + #endif + + #if PNG_MIPS_MSA_OPT > 0 +-# define PNG_FILTER_OPTIMIZATIONS png_init_filter_functions_msa + # ifndef PNG_MIPS_MSA_IMPLEMENTATION + # if defined(__mips_msa) + # if defined(__clang__) +@@ -268,14 +283,41 @@ + + # ifndef PNG_MIPS_MSA_IMPLEMENTATION + # define PNG_MIPS_MSA_IMPLEMENTATION 1 ++# define PNG_FILTER_OPTIMIZATIONS png_init_filter_functions_mips + # endif ++#else ++# define PNG_MIPS_MSA_IMPLEMENTATION 0 + #endif /* PNG_MIPS_MSA_OPT > 0 */ + ++#if PNG_MIPS_MMI_OPT > 0 ++# ifndef PNG_MIPS_MMI_IMPLEMENTATION ++# if defined(__mips_loongson_mmi) && (_MIPS_SIM == _ABI64) ++# define PNG_MIPS_MMI_IMPLEMENTATION 2 ++# else /* !defined __mips_loongson_mmi || _MIPS_SIM != _ABI64 */ ++# define PNG_MIPS_MMI_IMPLEMENTATION 0 ++# endif /* __mips_loongson_mmi && _MIPS_SIM == _ABI64 */ ++# endif /* !PNG_MIPS_MMI_IMPLEMENTATION */ ++ ++# if PNG_MIPS_MMI_IMPLEMENTATION > 0 ++# define PNG_FILTER_OPTIMIZATIONS png_init_filter_functions_mips ++# endif ++#else ++# define PNG_MIPS_MMI_IMPLEMENTATION 0 ++#endif /* PNG_MIPS_MMI_OPT > 0 */ ++ + #if PNG_POWERPC_VSX_OPT > 0 + # define PNG_FILTER_OPTIMIZATIONS png_init_filter_functions_vsx + # define PNG_POWERPC_VSX_IMPLEMENTATION 1 ++#else ++# define PNG_POWERPC_VSX_IMPLEMENTATION 0 + #endif + ++#if PNG_LOONGARCH_LSX_OPT > 0 ++# define PNG_FILTER_OPTIMIZATIONS png_init_filter_functions_lsx ++# define PNG_LOONGARCH_LSX_IMPLEMENTATION 1 ++#else ++# define PNG_LOONGARCH_LSX_IMPLEMENTATION 0 ++#endif + + /* Is this a build of a DLL where compilation of the object modules requires + * different preprocessor settings to those required for a simple library? If +@@ -314,11 +356,6 @@ + # endif + #endif /* Setting PNG_BUILD_DLL if required */ + +-/* Modfied for usage in Qt: Do not export the libpng APIs */ +-#ifdef PNG_BUILD_DLL +-#undef PNG_BUILD_DLL +-#endif +- + /* See pngconf.h for more details: the builder of the library may set this on + * the command line to the right thing for the specific compilation system or it + * may be automagically set above (at present we know of no system where it does +@@ -503,16 +540,7 @@ + static_cast(static_cast(value)) + #else + # define png_voidcast(type, value) (value) +-# ifdef _WIN64 +-# ifdef __GNUC__ +- typedef unsigned long long png_ptruint; +-# else +- typedef unsigned __int64 png_ptruint; +-# endif +-# else +- typedef unsigned long png_ptruint; +-# endif +-# define png_constcast(type, value) ((type)(png_ptruint)(const void*)(value)) ++# define png_constcast(type, value) ((type)(void*)(const void*)(value)) + # define png_aligncast(type, value) ((void*)(value)) + # define png_aligncastconst(type, value) ((const void*)(value)) + #endif /* __cplusplus */ +@@ -528,18 +556,8 @@ + */ + # include + +-# if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \ +- defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC) +- /* We need to check that hasn't already been included earlier +- * as it seems it doesn't agree with , yet we should really use +- * if possible. +- */ +-# if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__) +-# include +-# endif +-# else +-# include +-# endif ++# include ++ + # if defined(_AMIGA) && defined(__SASC) && defined(_M68881) + /* Amiga SAS/C: We must include builtin FPU functions when compiling using + * MATH=68881 +@@ -554,12 +572,8 @@ + # include + #endif + +-#if defined(WIN32) || defined(_Windows) || defined(_WINDOWS) || \ +- defined(_WIN32) || defined(__WIN32__) +-# include /* defines _WINDOWS_ macro */ +-# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP) +-# define _WINRT_ /* Define a macro for Windows Runtime builds */ +-# endif ++#if defined(_WIN32) || defined(__WIN32__) || defined(__NT__) ++# include + #endif + #endif /* PNG_VERSION_INFO_ONLY */ + +@@ -568,24 +582,20 @@ + * functions that are passed far data must be model-independent. + */ + +-/* Memory model/platform independent fns */ ++/* Platform-independent functions */ + #ifndef PNG_ABORT +-# if (defined(_WINDOWS_) || defined(_WIN32_WCE)) && !defined(_WINRT_) +-# define PNG_ABORT() ExitProcess(0) +-# else +-# define PNG_ABORT() abort() +-# endif ++# define PNG_ABORT() abort() + #endif + + /* These macros may need to be architecture dependent. */ +-#define PNG_ALIGN_NONE 0 /* do not use data alignment */ +-#define PNG_ALIGN_ALWAYS 1 /* assume unaligned accesses are OK */ ++#define PNG_ALIGN_NONE 0 /* do not use data alignment */ ++#define PNG_ALIGN_ALWAYS 1 /* assume unaligned accesses are OK */ + #ifdef offsetof +-# define PNG_ALIGN_OFFSET 2 /* use offsetof to determine alignment */ ++# define PNG_ALIGN_OFFSET 2 /* use offsetof to determine alignment */ + #else + # define PNG_ALIGN_OFFSET -1 /* prevent the use of this */ + #endif +-#define PNG_ALIGN_SIZE 3 /* use sizeof to determine alignment */ ++#define PNG_ALIGN_SIZE 3 /* use sizeof to determine alignment */ + + #ifndef PNG_ALIGN_TYPE + /* Default to using aligned access optimizations and requiring alignment to a +@@ -599,26 +609,25 @@ + /* This is used because in some compiler implementations non-aligned + * structure members are supported, so the offsetof approach below fails. + * Set PNG_ALIGN_SIZE=0 for compiler combinations where unaligned access +- * is good for performance. Do not do this unless you have tested the result +- * and understand it. ++ * is good for performance. Do not do this unless you have tested the ++ * result and understand it. + */ +-# define png_alignof(type) (sizeof (type)) ++# define png_alignof(type) (sizeof(type)) + #else + # if PNG_ALIGN_TYPE == PNG_ALIGN_OFFSET +-# define png_alignof(type) offsetof(struct{char c; type t;}, t) ++# define png_alignof(type) offsetof(struct{char c; type t;}, t) + # else +-# if PNG_ALIGN_TYPE == PNG_ALIGN_ALWAYS +-# define png_alignof(type) (1) +-# endif +- /* Else leave png_alignof undefined to prevent use thereof */ ++# if PNG_ALIGN_TYPE == PNG_ALIGN_ALWAYS ++# define png_alignof(type) 1 ++# endif ++ /* Else leave png_alignof undefined to prevent use thereof */ + # endif + #endif + +-/* This implicitly assumes alignment is always to a power of 2. */ ++/* This implicitly assumes alignment is always a multiple of 2. */ + #ifdef png_alignof +-# define png_isaligned(ptr, type)\ +- (((type)((const char*)ptr-(const char*)0) & \ +- (type)(png_alignof(type)-1)) == 0) ++# define png_isaligned(ptr, type) \ ++ (((type)(size_t)((const void*)(ptr)) & (type)(png_alignof(type)-1)) == 0) + #else + # define png_isaligned(ptr, type) 0 + #endif +@@ -649,7 +658,7 @@ + #define PNG_BACKGROUND_IS_GRAY 0x800U + #define PNG_HAVE_PNG_SIGNATURE 0x1000U + #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000U /* Have another chunk after IDAT */ +- /* 0x4000U (unused) */ ++#define PNG_WROTE_eXIf 0x4000U + #define PNG_IS_READ_STRUCT 0x8000U /* Else is a write struct */ + + /* Flags for the transformations the PNG library does on the image data */ +@@ -1329,7 +1338,7 @@ PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth4_neon,(png_row_infop + row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); + #endif + +-#if PNG_MIPS_MSA_OPT > 0 ++#if PNG_MIPS_MSA_IMPLEMENTATION == 1 + PNG_INTERNAL_FUNCTION(void,png_read_filter_row_up_msa,(png_row_infop row_info, + png_bytep row, png_const_bytep prev_row),PNG_EMPTY); + PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub3_msa,(png_row_infop +@@ -1346,6 +1355,23 @@ PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth4_msa,(png_row_infop + row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); + #endif + ++#if PNG_MIPS_MMI_IMPLEMENTATION > 0 ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_up_mmi,(png_row_infop row_info, ++ png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub3_mmi,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub4_mmi,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg3_mmi,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg4_mmi,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth3_mmi,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth4_mmi,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++#endif ++ + #if PNG_POWERPC_VSX_OPT > 0 + PNG_INTERNAL_FUNCTION(void,png_read_filter_row_up_vsx,(png_row_infop row_info, + png_bytep row, png_const_bytep prev_row),PNG_EMPTY); +@@ -1378,6 +1404,23 @@ PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth4_sse2,(png_row_infop + row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); + #endif + ++#if PNG_LOONGARCH_LSX_IMPLEMENTATION == 1 ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_up_lsx,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub3_lsx,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_sub4_lsx,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg3_lsx,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_avg4_lsx,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth3_lsx,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++PNG_INTERNAL_FUNCTION(void,png_read_filter_row_paeth4_lsx,(png_row_infop ++ row_info, png_bytep row, png_const_bytep prev_row),PNG_EMPTY); ++#endif ++ + /* Choose the best filter to use and filter the row data */ + PNG_INTERNAL_FUNCTION(void,png_write_find_filter,(png_structrp png_ptr, + png_row_infop row_info),PNG_EMPTY); +@@ -1933,7 +1976,7 @@ PNG_INTERNAL_FUNCTION(void,png_ascii_from_fixed,(png_const_structrp png_ptr, + */ + #define PNG_FP_INVALID 512 /* Available for callers as a distinct value */ + +-/* Result codes for the parser (boolean - true meants ok, false means ++/* Result codes for the parser (boolean - true means ok, false means + * not ok yet.) + */ + #define PNG_FP_MAYBE 0 /* The number may be valid in the future */ +@@ -1969,7 +2012,7 @@ PNG_INTERNAL_FUNCTION(void,png_ascii_from_fixed,(png_const_structrp png_ptr, + * the problem character.) This has not been tested within libpng. + */ + PNG_INTERNAL_FUNCTION(int,png_check_fp_number,(png_const_charp string, +- size_t size, int *statep, png_size_tp whereami),PNG_EMPTY); ++ size_t size, int *statep, size_t *whereami),PNG_EMPTY); + + /* This is the same but it checks a complete string and returns true + * only if it just contains a floating point number. As of 1.5.4 this +@@ -2117,17 +2160,27 @@ PNG_INTERNAL_FUNCTION(void, png_init_filter_functions_neon, + (png_structp png_ptr, unsigned int bpp), PNG_EMPTY); + #endif + +-#if PNG_MIPS_MSA_OPT > 0 +-PNG_INTERNAL_FUNCTION(void, png_init_filter_functions_msa, ++#if PNG_MIPS_MSA_IMPLEMENTATION == 1 ++PNG_INTERNAL_FUNCTION(void, png_init_filter_functions_mips, + (png_structp png_ptr, unsigned int bpp), PNG_EMPTY); + #endif + ++# if PNG_MIPS_MMI_IMPLEMENTATION > 0 ++PNG_INTERNAL_FUNCTION(void, png_init_filter_functions_mips, ++ (png_structp png_ptr, unsigned int bpp), PNG_EMPTY); ++# endif ++ + # if PNG_INTEL_SSE_IMPLEMENTATION > 0 + PNG_INTERNAL_FUNCTION(void, png_init_filter_functions_sse2, + (png_structp png_ptr, unsigned int bpp), PNG_EMPTY); + # endif + #endif + ++#if PNG_LOONGARCH_LSX_OPT > 0 ++PNG_INTERNAL_FUNCTION(void, png_init_filter_functions_lsx, ++ (png_structp png_ptr, unsigned int bpp), PNG_EMPTY); ++#endif ++ + PNG_INTERNAL_FUNCTION(png_uint_32, png_check_keyword, (png_structrp png_ptr, + png_const_charp key, png_bytep new_key), PNG_EMPTY); + +diff --git old/qtbase/src/3rdparty/libpng/pngread.c new/qtbase/src/3rdparty/libpng/pngread.c +index 8fa7d9f1628..008a41856b6 100644 +--- old/qtbase/src/3rdparty/libpng/pngread.c ++++ new/qtbase/src/3rdparty/libpng/pngread.c +@@ -1,7 +1,7 @@ + + /* pngread.c - read a PNG file + * +- * Copyright (c) 2018-2019 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -568,7 +568,7 @@ png_read_row(png_structrp png_ptr, png_bytep row, png_bytep dsp_row) + #endif + + #ifdef PNG_READ_TRANSFORMS_SUPPORTED +- if (png_ptr->transformations) ++ if (png_ptr->transformations || png_ptr->num_palette_max >= 0) + png_do_read_transformations(png_ptr, &row_info); + #endif + +@@ -785,7 +785,7 @@ png_read_end(png_structrp png_ptr, png_inforp info_ptr) + #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED + /* Report invalid palette index; added at libng-1.5.10 */ + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && +- png_ptr->num_palette_max > png_ptr->num_palette) ++ png_ptr->num_palette_max >= png_ptr->num_palette) + png_benign_error(png_ptr, "Read palette index exceeding num_palette"); + #endif + +@@ -1049,6 +1049,8 @@ void PNGAPI + png_read_png(png_structrp png_ptr, png_inforp info_ptr, + int transforms, voidp params) + { ++ png_debug(1, "in png_read_png"); ++ + if (png_ptr == NULL || info_ptr == NULL) + return; + +@@ -3452,7 +3454,6 @@ png_image_read_background(png_voidp argument) + + for (pass = 0; pass < passes; ++pass) + { +- png_bytep row = png_voidcast(png_bytep, display->first_row); + unsigned int startx, stepx, stepy; + png_uint_32 y; + +@@ -3557,8 +3558,6 @@ png_image_read_background(png_voidp argument) + + inrow += 2; /* gray and alpha channel */ + } +- +- row += display->row_bytes; + } + } + } +@@ -3765,13 +3764,13 @@ png_image_read_direct(png_voidp argument) + mode = PNG_ALPHA_PNG; + output_gamma = PNG_DEFAULT_sRGB; + } +- ++ + if ((change & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0) + { + mode = PNG_ALPHA_OPTIMIZED; + change &= ~PNG_FORMAT_FLAG_ASSOCIATED_ALPHA; + } +- ++ + /* If 'do_local_background' is set check for the presence of gamma + * correction; this is part of the work-round for the libpng bug + * described above. +diff --git old/qtbase/src/3rdparty/libpng/pngrtran.c new/qtbase/src/3rdparty/libpng/pngrtran.c +index 9a8fad9f4aa..16474741aac 100644 +--- old/qtbase/src/3rdparty/libpng/pngrtran.c ++++ new/qtbase/src/3rdparty/libpng/pngrtran.c +@@ -1,7 +1,7 @@ + + /* pngrtran.c - transforms the data in a row for PNG readers + * +- * Copyright (c) 2018-2019 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -21,7 +21,7 @@ + #ifdef PNG_ARM_NEON_IMPLEMENTATION + # if PNG_ARM_NEON_IMPLEMENTATION == 1 + # define PNG_ARM_NEON_INTRINSICS_AVAILABLE +-# if defined(_MSC_VER) && defined(_M_ARM64) ++# if defined(_MSC_VER) && !defined(__clang__) && defined(_M_ARM64) + # include + # else + # include +@@ -290,7 +290,7 @@ png_set_alpha_mode_fixed(png_structrp png_ptr, int mode, + int compose = 0; + png_fixed_point file_gamma; + +- png_debug(1, "in png_set_alpha_mode"); ++ png_debug(1, "in png_set_alpha_mode_fixed"); + + if (png_rtran_ok(png_ptr, 0) == 0) + return; +@@ -970,7 +970,7 @@ void PNGFAPI + png_set_rgb_to_gray_fixed(png_structrp png_ptr, int error_action, + png_fixed_point red, png_fixed_point green) + { +- png_debug(1, "in png_set_rgb_to_gray"); ++ png_debug(1, "in png_set_rgb_to_gray_fixed"); + + /* Need the IHDR here because of the check on color_type below. */ + /* TODO: fix this */ +diff --git old/qtbase/src/3rdparty/libpng/pngrutil.c new/qtbase/src/3rdparty/libpng/pngrutil.c +index 4db3de990bd..d31dc21dae8 100644 +--- old/qtbase/src/3rdparty/libpng/pngrutil.c ++++ new/qtbase/src/3rdparty/libpng/pngrutil.c +@@ -1,7 +1,7 @@ + + /* pngrutil.c - utilities to read a PNG file + * +- * Copyright (c) 2018 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -26,7 +26,7 @@ png_get_uint_31(png_const_structrp png_ptr, png_const_bytep buf) + if (uval > PNG_UINT_31_MAX) + png_error(png_ptr, "PNG unsigned integer out of range"); + +- return (uval); ++ return uval; + } + + #if defined(PNG_READ_gAMA_SUPPORTED) || defined(PNG_READ_cHRM_SUPPORTED) +@@ -140,7 +140,7 @@ png_read_sig(png_structrp png_ptr, png_inforp info_ptr) + if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check) != 0) + { + if (num_checked < 4 && +- png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4)) ++ png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4) != 0) + png_error(png_ptr, "Not a PNG file"); + else + png_error(png_ptr, "PNG file corrupted by ASCII conversion"); +@@ -171,7 +171,7 @@ png_read_chunk_header(png_structrp png_ptr) + /* Put the chunk name into png_ptr->chunk_name. */ + png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(buf+4); + +- png_debug2(0, "Reading %lx chunk, length = %lu", ++ png_debug2(0, "Reading chunk typeid = 0x%lx, length = %lu", + (unsigned long)png_ptr->chunk_name, (unsigned long)length); + + /* Reset the crc and run it over the chunk name. */ +@@ -238,10 +238,10 @@ png_crc_finish(png_structrp png_ptr, png_uint_32 skip) + else + png_chunk_error(png_ptr, "CRC error"); + +- return (1); ++ return 1; + } + +- return (0); ++ return 0; + } + + /* Compare the CRC stored in the PNG file with that calculated by libpng from +@@ -277,11 +277,11 @@ png_crc_error(png_structrp png_ptr) + if (need_crc != 0) + { + crc = png_get_uint_32(crc_bytes); +- return ((int)(crc != png_ptr->crc)); ++ return crc != png_ptr->crc; + } + + else +- return (0); ++ return 0; + } + + #if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\ +@@ -301,7 +301,6 @@ png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size, int warn) + + if (buffer != NULL && new_size > png_ptr->read_buffer_size) + { +- png_ptr->read_buffer = NULL; + png_ptr->read_buffer = NULL; + png_ptr->read_buffer_size = 0; + png_free(png_ptr, buffer); +@@ -422,8 +421,7 @@ png_inflate_claim(png_structrp png_ptr, png_uint_32 owner) + png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED; + } + +-#if ZLIB_VERNUM >= 0x1290 && \ +- defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_IGNORE_ADLER32) ++#ifdef PNG_DISABLE_ADLER32_CHECK_SUPPORTED + if (((png_ptr->options >> PNG_IGNORE_ADLER32) & 3) == PNG_OPTION_ON) + /* Turn off validation of the ADLER32 checksum in IDAT chunks */ + ret = inflateValidate(&png_ptr->zstream, 0); +@@ -2076,14 +2074,17 @@ png_handle_eXIf(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) + png_byte buf[1]; + png_crc_read(png_ptr, buf, 1); + info_ptr->eXIf_buf[i] = buf[0]; +- if (i == 1 && buf[0] != 'M' && buf[0] != 'I' +- && info_ptr->eXIf_buf[0] != buf[0]) ++ if (i == 1) + { +- png_crc_finish(png_ptr, length); +- png_chunk_benign_error(png_ptr, "incorrect byte-order specifier"); +- png_free(png_ptr, info_ptr->eXIf_buf); +- info_ptr->eXIf_buf = NULL; +- return; ++ if ((buf[0] != 'M' && buf[0] != 'I') || ++ (info_ptr->eXIf_buf[0] != buf[0])) ++ { ++ png_crc_finish(png_ptr, length - 2); ++ png_chunk_benign_error(png_ptr, "incorrect byte-order specifier"); ++ png_free(png_ptr, info_ptr->eXIf_buf); ++ info_ptr->eXIf_buf = NULL; ++ return; ++ } + } + } + +@@ -2124,8 +2125,9 @@ png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) + + num = length / 2 ; + +- if (num != (unsigned int) png_ptr->num_palette || +- num > (unsigned int) PNG_MAX_PALETTE_LENGTH) ++ if (length != num * 2 || ++ num != (unsigned int)png_ptr->num_palette || ++ num > (unsigned int)PNG_MAX_PALETTE_LENGTH) + { + png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); +@@ -3183,7 +3185,7 @@ png_check_chunk_length(png_const_structrp png_ptr, png_uint_32 length) + { + png_debug2(0," length = %lu, limit = %lu", + (unsigned long)length,(unsigned long)limit); +- png_chunk_error(png_ptr, "chunk data is too large"); ++ png_benign_error(png_ptr, "chunk data is too large"); + } + } + +@@ -4619,14 +4621,13 @@ defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) + */ + { + png_bytep temp = png_ptr->big_row_buf + 32; +- int extra = (int)((temp - (png_bytep)0) & 0x0f); ++ size_t extra = (size_t)temp & 0x0f; + png_ptr->row_buf = temp - extra - 1/*filter byte*/; + + temp = png_ptr->big_prev_row + 32; +- extra = (int)((temp - (png_bytep)0) & 0x0f); ++ extra = (size_t)temp & 0x0f; + png_ptr->prev_row = temp - extra - 1/*filter byte*/; + } +- + #else + /* Use 31 bytes of padding before and 17 bytes after row_buf. */ + png_ptr->row_buf = png_ptr->big_row_buf + 31; +diff --git old/qtbase/src/3rdparty/libpng/pngset.c new/qtbase/src/3rdparty/libpng/pngset.c +index ec75dbe3690..eb1c8c7a35a 100644 +--- old/qtbase/src/3rdparty/libpng/pngset.c ++++ new/qtbase/src/3rdparty/libpng/pngset.c +@@ -1,7 +1,7 @@ + + /* pngset.c - storage of image information into info struct + * +- * Copyright (c) 2018 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -137,46 +137,40 @@ png_set_cHRM_XYZ(png_const_structrp png_ptr, png_inforp info_ptr, double red_X, + #ifdef PNG_eXIf_SUPPORTED + void PNGAPI + png_set_eXIf(png_const_structrp png_ptr, png_inforp info_ptr, +- png_bytep eXIf_buf) ++ png_bytep exif) + { + png_warning(png_ptr, "png_set_eXIf does not work; use png_set_eXIf_1"); + PNG_UNUSED(info_ptr) +- PNG_UNUSED(eXIf_buf) ++ PNG_UNUSED(exif) + } + + void PNGAPI + png_set_eXIf_1(png_const_structrp png_ptr, png_inforp info_ptr, +- png_uint_32 num_exif, png_bytep eXIf_buf) ++ png_uint_32 num_exif, png_bytep exif) + { +- int i; ++ png_bytep new_exif; + + png_debug1(1, "in %s storage function", "eXIf"); + +- if (png_ptr == NULL || info_ptr == NULL) ++ if (png_ptr == NULL || info_ptr == NULL || ++ (png_ptr->mode & PNG_WROTE_eXIf) != 0) + return; + +- if (info_ptr->exif) +- { +- png_free(png_ptr, info_ptr->exif); +- info_ptr->exif = NULL; +- } +- +- info_ptr->num_exif = num_exif; +- +- info_ptr->exif = png_voidcast(png_bytep, png_malloc_warn(png_ptr, +- info_ptr->num_exif)); ++ new_exif = png_voidcast(png_bytep, png_malloc_warn(png_ptr, num_exif)); + +- if (info_ptr->exif == NULL) ++ if (new_exif == NULL) + { + png_warning(png_ptr, "Insufficient memory for eXIf chunk data"); + return; + } + +- info_ptr->free_me |= PNG_FREE_EXIF; ++ memcpy(new_exif, exif, (size_t)num_exif); + +- for (i = 0; i < (int) info_ptr->num_exif; i++) +- info_ptr->exif[i] = eXIf_buf[i]; ++ png_free_data(png_ptr, info_ptr, PNG_FREE_EXIF, 0); + ++ info_ptr->num_exif = num_exif; ++ info_ptr->exif = new_exif; ++ info_ptr->free_me |= PNG_FREE_EXIF; + info_ptr->valid |= PNG_INFO_eXIf; + } + #endif /* eXIf */ +@@ -237,15 +231,13 @@ png_set_hIST(png_const_structrp png_ptr, png_inforp info_ptr, + if (info_ptr->hist == NULL) + { + png_warning(png_ptr, "Insufficient memory for hIST chunk data"); +- + return; + } + +- info_ptr->free_me |= PNG_FREE_HIST; +- + for (i = 0; i < info_ptr->num_palette; i++) + info_ptr->hist[i] = hist[i]; + ++ info_ptr->free_me |= PNG_FREE_HIST; + info_ptr->valid |= PNG_INFO_hIST; + } + #endif +@@ -367,6 +359,8 @@ png_set_pCAL(png_const_structrp png_ptr, png_inforp info_ptr, + + memcpy(info_ptr->pcal_purpose, purpose, length); + ++ info_ptr->free_me |= PNG_FREE_PCAL; ++ + png_debug(3, "storing X0, X1, type, and nparams in info"); + info_ptr->pcal_X0 = X0; + info_ptr->pcal_X1 = X1; +@@ -383,7 +377,6 @@ png_set_pCAL(png_const_structrp png_ptr, png_inforp info_ptr, + if (info_ptr->pcal_units == NULL) + { + png_warning(png_ptr, "Insufficient memory for pCAL units"); +- + return; + } + +@@ -395,7 +388,6 @@ png_set_pCAL(png_const_structrp png_ptr, png_inforp info_ptr, + if (info_ptr->pcal_params == NULL) + { + png_warning(png_ptr, "Insufficient memory for pCAL params"); +- + return; + } + +@@ -413,7 +405,6 @@ png_set_pCAL(png_const_structrp png_ptr, png_inforp info_ptr, + if (info_ptr->pcal_params[i] == NULL) + { + png_warning(png_ptr, "Insufficient memory for pCAL parameter"); +- + return; + } + +@@ -421,7 +412,6 @@ png_set_pCAL(png_const_structrp png_ptr, png_inforp info_ptr, + } + + info_ptr->valid |= PNG_INFO_pCAL; +- info_ptr->free_me |= PNG_FREE_PCAL; + } + #endif + +@@ -478,18 +468,17 @@ png_set_sCAL_s(png_const_structrp png_ptr, png_inforp info_ptr, + + if (info_ptr->scal_s_height == NULL) + { +- png_free (png_ptr, info_ptr->scal_s_width); ++ png_free(png_ptr, info_ptr->scal_s_width); + info_ptr->scal_s_width = NULL; + + png_warning(png_ptr, "Memory allocation failed while processing sCAL"); +- + return; + } + + memcpy(info_ptr->scal_s_height, sheight, lengthh); + +- info_ptr->valid |= PNG_INFO_sCAL; + info_ptr->free_me |= PNG_FREE_SCAL; ++ info_ptr->valid |= PNG_INFO_sCAL; + } + + # ifdef PNG_FLOATING_POINT_SUPPORTED +@@ -625,11 +614,10 @@ png_set_PLTE(png_structrp png_ptr, png_inforp info_ptr, + if (num_palette > 0) + memcpy(png_ptr->palette, palette, (unsigned int)num_palette * + (sizeof (png_color))); ++ + info_ptr->palette = png_ptr->palette; + info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette; +- + info_ptr->free_me |= PNG_FREE_PLTE; +- + info_ptr->valid |= PNG_INFO_PLTE; + } + +@@ -775,11 +763,11 @@ png_set_text_2(png_const_structrp png_ptr, png_inforp info_ptr, + { + int i; + +- png_debug1(1, "in %lx storage function", png_ptr == NULL ? 0xabadca11U : +- (unsigned long)png_ptr->chunk_name); ++ png_debug1(1, "in text storage function, chunk typeid = 0x%lx", ++ png_ptr == NULL ? 0xabadca11UL : (unsigned long)png_ptr->chunk_name); + + if (png_ptr == NULL || info_ptr == NULL || num_text <= 0 || text_ptr == NULL) +- return(0); ++ return 0; + + /* Make sure we have enough space in the "text" array in info_struct + * to hold all of the incoming text_ptr objects. This compare can't overflow +@@ -959,7 +947,7 @@ png_set_text_2(png_const_structrp png_ptr, png_inforp info_ptr, + png_debug1(3, "transferred text chunk %d", info_ptr->num_text); + } + +- return(0); ++ return 0; + } + #endif + +@@ -1019,6 +1007,9 @@ png_set_tRNS(png_structrp png_ptr, png_inforp info_ptr, + info_ptr->trans_alpha = png_voidcast(png_bytep, + png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH)); + memcpy(info_ptr->trans_alpha, trans_alpha, (size_t)num_trans); ++ ++ info_ptr->free_me |= PNG_FREE_TRNS; ++ info_ptr->valid |= PNG_INFO_tRNS; + } + png_ptr->trans_alpha = info_ptr->trans_alpha; + } +@@ -1051,8 +1042,8 @@ png_set_tRNS(png_structrp png_ptr, png_inforp info_ptr, + + if (num_trans != 0) + { +- info_ptr->valid |= PNG_INFO_tRNS; + info_ptr->free_me |= PNG_FREE_TRNS; ++ info_ptr->valid |= PNG_INFO_tRNS; + } + } + #endif +@@ -1072,6 +1063,8 @@ png_set_sPLT(png_const_structrp png_ptr, + { + png_sPLT_tp np; + ++ png_debug1(1, "in %s storage function", "sPLT"); ++ + if (png_ptr == NULL || info_ptr == NULL || nentries <= 0 || entries == NULL) + return; + +@@ -1086,11 +1079,11 @@ png_set_sPLT(png_const_structrp png_ptr, + { + /* Out of memory or too many chunks */ + png_chunk_report(png_ptr, "too many sPLT chunks", PNG_CHUNK_WRITE_ERROR); +- + return; + } + + png_free(png_ptr, info_ptr->splt_palettes); ++ + info_ptr->splt_palettes = np; + info_ptr->free_me |= PNG_FREE_SPLT; + +@@ -1244,11 +1237,11 @@ png_set_unknown_chunks(png_const_structrp png_ptr, + { + png_chunk_report(png_ptr, "too many unknown chunks", + PNG_CHUNK_WRITE_ERROR); +- + return; + } + + png_free(png_ptr, info_ptr->unknown_chunks); ++ + info_ptr->unknown_chunks = np; /* safe because it is initialized */ + info_ptr->free_me |= PNG_FREE_UNKN; + +@@ -1326,7 +1319,7 @@ png_set_unknown_chunk_location(png_const_structrp png_ptr, png_inforp info_ptr, + + #ifdef PNG_MNG_FEATURES_SUPPORTED + png_uint_32 PNGAPI +-png_permit_mng_features (png_structrp png_ptr, png_uint_32 mng_features) ++png_permit_mng_features(png_structrp png_ptr, png_uint_32 mng_features) + { + png_debug(1, "in png_permit_mng_features"); + +@@ -1546,7 +1539,7 @@ void PNGAPI + png_set_rows(png_const_structrp png_ptr, png_inforp info_ptr, + png_bytepp row_pointers) + { +- png_debug1(1, "in %s storage function", "rows"); ++ png_debug(1, "in png_set_rows"); + + if (png_ptr == NULL || info_ptr == NULL) + return; +@@ -1565,6 +1558,8 @@ png_set_rows(png_const_structrp png_ptr, png_inforp info_ptr, + void PNGAPI + png_set_compression_buffer_size(png_structrp png_ptr, size_t size) + { ++ png_debug(1, "in png_set_compression_buffer_size"); ++ + if (png_ptr == NULL) + return; + +@@ -1633,9 +1628,11 @@ png_set_invalid(png_const_structrp png_ptr, png_inforp info_ptr, int mask) + #ifdef PNG_SET_USER_LIMITS_SUPPORTED + /* This function was added to libpng 1.2.6 */ + void PNGAPI +-png_set_user_limits (png_structrp png_ptr, png_uint_32 user_width_max, ++png_set_user_limits(png_structrp png_ptr, png_uint_32 user_width_max, + png_uint_32 user_height_max) + { ++ png_debug(1, "in png_set_user_limits"); ++ + /* Images with dimensions larger than these limits will be + * rejected by png_set_IHDR(). To accept any PNG datastream + * regardless of dimensions, set both limits to 0x7fffffff. +@@ -1649,17 +1646,21 @@ png_set_user_limits (png_structrp png_ptr, png_uint_32 user_width_max, + + /* This function was added to libpng 1.4.0 */ + void PNGAPI +-png_set_chunk_cache_max (png_structrp png_ptr, png_uint_32 user_chunk_cache_max) ++png_set_chunk_cache_max(png_structrp png_ptr, png_uint_32 user_chunk_cache_max) + { ++ png_debug(1, "in png_set_chunk_cache_max"); ++ + if (png_ptr != NULL) + png_ptr->user_chunk_cache_max = user_chunk_cache_max; + } + + /* This function was added to libpng 1.4.1 */ + void PNGAPI +-png_set_chunk_malloc_max (png_structrp png_ptr, ++png_set_chunk_malloc_max(png_structrp png_ptr, + png_alloc_size_t user_chunk_malloc_max) + { ++ png_debug(1, "in png_set_chunk_malloc_max"); ++ + if (png_ptr != NULL) + png_ptr->user_chunk_malloc_max = user_chunk_malloc_max; + } +diff --git old/qtbase/src/3rdparty/libpng/pngstruct.h new/qtbase/src/3rdparty/libpng/pngstruct.h +index 8bdc7ce46db..e591d94d587 100644 +--- old/qtbase/src/3rdparty/libpng/pngstruct.h ++++ new/qtbase/src/3rdparty/libpng/pngstruct.h +@@ -1,7 +1,7 @@ + + /* pngstruct.h - header file for PNG reference library + * +- * Copyright (c) 2018-2019 Cosmin Truta ++ * Copyright (c) 2018-2022 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -334,18 +334,8 @@ struct png_struct_def + size_t current_buffer_size; /* amount of data now in current_buffer */ + int process_mode; /* what push library is currently doing */ + int cur_palette; /* current push library palette index */ +- + #endif /* PROGRESSIVE_READ */ + +-#if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__) +-/* For the Borland special 64K segment handler */ +- png_bytepp offset_table_ptr; +- png_bytep offset_table; +- png_uint_16 offset_table_number; +- png_uint_16 offset_table_count; +- png_uint_16 offset_table_count_free; +-#endif +- + #ifdef PNG_READ_QUANTIZE_SUPPORTED + png_bytep palette_lookup; /* lookup table for quantizing */ + png_bytep quantize_index; /* index translation for palette files */ +diff --git old/qtbase/src/3rdparty/libpng/pngtrans.c new/qtbase/src/3rdparty/libpng/pngtrans.c +index 1100f46ebec..62cb21edf1f 100644 +--- old/qtbase/src/3rdparty/libpng/pngtrans.c ++++ new/qtbase/src/3rdparty/libpng/pngtrans.c +@@ -1,7 +1,7 @@ + + /* pngtrans.c - transforms the data in a row (used by both readers and writers) + * +- * Copyright (c) 2018 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -103,10 +103,10 @@ png_set_interlace_handling(png_structrp png_ptr) + if (png_ptr != 0 && png_ptr->interlaced != 0) + { + png_ptr->transformations |= PNG_INTERLACE; +- return (7); ++ return 7; + } + +- return (1); ++ return 1; + } + #endif + +@@ -498,6 +498,8 @@ png_do_strip_channel(png_row_infop row_info, png_bytep row, int at_start) + png_bytep dp = row; /* destination pointer */ + png_bytep ep = row + row_info->rowbytes; /* One beyond end of row */ + ++ png_debug(1, "in png_do_strip_channel"); ++ + /* At the start sp will point to the first byte to copy and dp to where + * it is copied to. ep always points just beyond the end of the row, so + * the loop simply copies (channels-1) channels until sp reaches ep. +@@ -698,6 +700,8 @@ png_do_bgr(png_row_infop row_info, png_bytep row) + void /* PRIVATE */ + png_do_check_palette_indexes(png_structrp png_ptr, png_row_infop row_info) + { ++ png_debug(1, "in png_do_check_palette_indexes"); ++ + if (png_ptr->num_palette < (1 << row_info->bit_depth) && + png_ptr->num_palette > 0) /* num_palette can be 0 in MNG files */ + { +@@ -708,7 +712,7 @@ png_do_check_palette_indexes(png_structrp png_ptr, png_row_infop row_info) + * forms produced on either GCC or MSVC. + */ + int padding = PNG_PADBITS(row_info->pixel_depth, row_info->width); +- png_bytep rp = png_ptr->row_buf + row_info->rowbytes - 1; ++ png_bytep rp = png_ptr->row_buf + row_info->rowbytes; + + switch (row_info->bit_depth) + { +@@ -833,7 +837,7 @@ png_voidp PNGAPI + png_get_user_transform_ptr(png_const_structrp png_ptr) + { + if (png_ptr == NULL) +- return (NULL); ++ return NULL; + + return png_ptr->user_transform_ptr; + } +diff --git old/qtbase/src/3rdparty/libpng/pngwrite.c new/qtbase/src/3rdparty/libpng/pngwrite.c +index 59377a4ddea..77e412f43d5 100644 +--- old/qtbase/src/3rdparty/libpng/pngwrite.c ++++ new/qtbase/src/3rdparty/libpng/pngwrite.c +@@ -1,7 +1,7 @@ + + /* pngwrite.c - general routines to write a PNG file + * +- * Copyright (c) 2018-2019 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -75,10 +75,10 @@ write_unknown_chunks(png_structrp png_ptr, png_const_inforp info_ptr, + * library. If you have a new chunk to add, make a function to write it, + * and put it in the correct location here. If you want the chunk written + * after the image data, put it in png_write_end(). I strongly encourage +- * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing +- * the chunk, as that will keep the code from breaking if you want to just +- * write a plain PNG file. If you have long comments, I suggest writing +- * them in png_write_end(), and compressing them. ++ * you to supply a PNG_INFO_ flag, and check info_ptr->valid before ++ * writing the chunk, as that will keep the code from breaking if you want ++ * to just write a plain PNG file. If you have long comments, I suggest ++ * writing them in png_write_end(), and compressing them. + */ + void PNGAPI + png_write_info_before_PLTE(png_structrp png_ptr, png_const_inforp info_ptr) +@@ -239,7 +239,10 @@ png_write_info(png_structrp png_ptr, png_const_inforp info_ptr) + + #ifdef PNG_WRITE_eXIf_SUPPORTED + if ((info_ptr->valid & PNG_INFO_eXIf) != 0) ++ { + png_write_eXIf(png_ptr, info_ptr->exif, info_ptr->num_exif); ++ png_ptr->mode |= PNG_WROTE_eXIf; ++ } + #endif + + #ifdef PNG_WRITE_hIST_SUPPORTED +@@ -366,7 +369,8 @@ png_write_end(png_structrp png_ptr, png_inforp info_ptr) + png_error(png_ptr, "No IDATs written into file"); + + #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED +- if (png_ptr->num_palette_max > png_ptr->num_palette) ++ if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && ++ png_ptr->num_palette_max >= png_ptr->num_palette) + png_benign_error(png_ptr, "Wrote palette index exceeding num_palette"); + #endif + +@@ -439,8 +443,9 @@ png_write_end(png_structrp png_ptr, png_inforp info_ptr) + #endif + + #ifdef PNG_WRITE_eXIf_SUPPORTED +- if ((info_ptr->valid & PNG_INFO_eXIf) != 0) +- png_write_eXIf(png_ptr, info_ptr->exif, info_ptr->num_exif); ++ if ((info_ptr->valid & PNG_INFO_eXIf) != 0 && ++ (png_ptr->mode & PNG_WROTE_eXIf) == 0) ++ png_write_eXIf(png_ptr, info_ptr->exif, info_ptr->num_exif); + #endif + + #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED +@@ -489,6 +494,16 @@ png_convert_from_time_t(png_timep ptime, time_t ttime) + png_debug(1, "in png_convert_from_time_t"); + + tbuf = gmtime(&ttime); ++ if (tbuf == NULL) ++ { ++ /* TODO: add a safe function which takes a png_ptr argument and raises ++ * a png_error if the ttime argument is invalid and the call to gmtime ++ * fails as a consequence. ++ */ ++ memset(ptime, 0, sizeof(*ptime)); ++ return; ++ } ++ + png_convert_from_struct_tm(ptime, tbuf); + } + #endif +@@ -700,12 +715,12 @@ png_write_row(png_structrp png_ptr, png_const_bytep row) + /* 1.5.6: moved from png_struct to be a local structure: */ + png_row_info row_info; + +- if (png_ptr == NULL) +- return; +- + png_debug2(1, "in png_write_row (row %u, pass %d)", + png_ptr->row_number, png_ptr->pass); + ++ if (png_ptr == NULL) ++ return; ++ + /* Initialize transformations and other stuff if first time */ + if (png_ptr->row_number == 0 && png_ptr->pass == 0) + { +@@ -1196,6 +1211,8 @@ png_set_compression_strategy(png_structrp png_ptr, int strategy) + void PNGAPI + png_set_compression_window_bits(png_structrp png_ptr, int window_bits) + { ++ png_debug(1, "in png_set_compression_window_bits"); ++ + if (png_ptr == NULL) + return; + +@@ -1279,6 +1296,8 @@ png_set_text_compression_strategy(png_structrp png_ptr, int strategy) + void PNGAPI + png_set_text_compression_window_bits(png_structrp png_ptr, int window_bits) + { ++ png_debug(1, "in png_set_text_compression_window_bits"); ++ + if (png_ptr == NULL) + return; + +@@ -1316,6 +1335,8 @@ png_set_text_compression_method(png_structrp png_ptr, int method) + void PNGAPI + png_set_write_status_fn(png_structrp png_ptr, png_write_status_ptr write_row_fn) + { ++ png_debug(1, "in png_set_write_status_fn"); ++ + if (png_ptr == NULL) + return; + +@@ -1343,6 +1364,8 @@ void PNGAPI + png_write_png(png_structrp png_ptr, png_inforp info_ptr, + int transforms, voidp params) + { ++ png_debug(1, "in png_write_png"); ++ + if (png_ptr == NULL || info_ptr == NULL) + return; + +diff --git old/qtbase/src/3rdparty/libpng/pngwutil.c new/qtbase/src/3rdparty/libpng/pngwutil.c +index 16345e4c0ba..14cc4ce367f 100644 +--- old/qtbase/src/3rdparty/libpng/pngwutil.c ++++ new/qtbase/src/3rdparty/libpng/pngwutil.c +@@ -1,7 +1,7 @@ + + /* pngwutil.c - utilities to write a PNG file + * +- * Copyright (c) 2018 Cosmin Truta ++ * Copyright (c) 2018-2024 Cosmin Truta + * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson + * Copyright (c) 1996-1997 Andreas Dilger + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. +@@ -1747,7 +1747,7 @@ png_write_pCAL(png_structrp png_ptr, png_charp purpose, png_int_32 X0, + { + png_uint_32 purpose_len; + size_t units_len, total_len; +- png_size_tp params_len; ++ size_t *params_len; + png_byte buf[10]; + png_byte new_purpose[80]; + int i; +@@ -1769,7 +1769,7 @@ png_write_pCAL(png_structrp png_ptr, png_charp purpose, png_int_32 X0, + png_debug1(3, "pCAL units length = %d", (int)units_len); + total_len = purpose_len + units_len + 10; + +- params_len = (png_size_tp)png_malloc(png_ptr, ++ params_len = (size_t *)png_malloc(png_ptr, + (png_alloc_size_t)((png_alloc_size_t)nparams * (sizeof (size_t)))); + + /* Find the length of each parameter, making sure we don't count the +@@ -2311,7 +2311,7 @@ png_setup_sub_row(png_structrp png_ptr, png_uint_32 bpp, + break; + } + +- return (sum); ++ return sum; + } + + static void /* PRIVATE */ +@@ -2361,7 +2361,7 @@ png_setup_up_row(png_structrp png_ptr, size_t row_bytes, size_t lmins) + break; + } + +- return (sum); ++ return sum; + } + static void /* PRIVATE */ + png_setup_up_row_only(png_structrp png_ptr, size_t row_bytes) +@@ -2417,7 +2417,7 @@ png_setup_avg_row(png_structrp png_ptr, png_uint_32 bpp, + break; + } + +- return (sum); ++ return sum; + } + static void /* PRIVATE */ + png_setup_avg_row_only(png_structrp png_ptr, png_uint_32 bpp, +@@ -2500,7 +2500,7 @@ png_setup_paeth_row(png_structrp png_ptr, png_uint_32 bpp, + break; + } + +- return (sum); ++ return sum; + } + static void /* PRIVATE */ + png_setup_paeth_row_only(png_structrp png_ptr, png_uint_32 bpp, +diff --git old/qtbase/src/3rdparty/libpng/qt_attribution.json new/qtbase/src/3rdparty/libpng/qt_attribution.json +index 612aa67791f..3d0df998833 100644 +--- old/qtbase/src/3rdparty/libpng/qt_attribution.json ++++ new/qtbase/src/3rdparty/libpng/qt_attribution.json +@@ -6,21 +6,24 @@ + + "Description": "libpng is the official PNG reference library.", + "Homepage": "http://www.libpng.org/pub/png/libpng.html", +- "Version": "1.6.37", ++ "Version": "1.6.41", ++ "DownloadLocation": "https://download.sourceforge.net/libpng/libpng-1.6.41.tar.xz", + "License": "libpng License and PNG Reference Library version 2", + "LicenseId": "Libpng AND libpng-2.0", + "LicenseFile": "LICENSE", +- "Copyright": "Copyright (c) 1998-2018 Glenn Randers-Pehrson ++ "Copyright": "Copyright (c) 1995-2024 The PNG Reference Library Authors ++Copyright (c) 2000-2024 Cosmin Truta ++Copyright (c) 1998-2018 Glenn Randers-Pehrson ++Copyright (c) 1996-1997 Andreas Dilger ++Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + Copyright (c) 2000-2017 Simon-Pierre Cadieux + Copyright (c) 2000-2017 Eric S. Raymond + Copyright (c) 2000-2017 Mans Rullgard +-Copyright (c) 2000-2019 Cosmin Truta + Copyright (c) 2000-2017 Gilles Vollant + Copyright (c) 2000-2017 James Yu + Copyright (c) 2000-2017 Mandar Sahastrabuddhe + Copyright (c) 1998-2000 Tom Lane + Copyright (c) 1998-2000 Willem van Schaik +-Copyright (c) 1996-1997 Andreas Dilger + Copyright (c) 1996-1997 John Bowler + Copyright (c) 1996-1997 Kevin Bracey + Copyright (c) 1996-1997 Sam Bushell +@@ -29,6 +32,5 @@ Copyright (c) 1996-1997 Greg Roelofs + Copyright (c) 1996-1997 Tom Tanner + Copyright (c) 1995-1996 Dave Martindale + Copyright (c) 1995-1996 Paul Schmidt +-Copyright (c) 1995-1996 Tim Wegner +-Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." ++Copyright (c) 1995-1996 Tim Wegner" + } +diff --git old/qtbase/src/3rdparty/libpng/qtpatches.diff new/qtbase/src/3rdparty/libpng/qtpatches.diff +deleted file mode 100644 +index 272532cdd86..00000000000 +--- old/qtbase/src/3rdparty/libpng/qtpatches.diff ++++ /dev/null +@@ -1,65 +0,0 @@ +-diff --git a/src/3rdparty/libpng/pngpriv.h b/src/3rdparty/libpng/pngpriv.h +-index 583c26f9bd..2ab9b70d73 100644 +---- a/src/3rdparty/libpng/pngpriv.h +-+++ b/src/3rdparty/libpng/pngpriv.h +-@@ -23,6 +23,12 @@ +- #ifndef PNGPRIV_H +- #define PNGPRIV_H +- +-+#ifdef _MSC_VER +-+# ifndef _CRT_SECURE_NO_DEPRECATE +-+# define _CRT_SECURE_NO_DEPRECATE +-+# endif +-+#endif +-+ +- /* Feature Test Macros. The following are defined here to ensure that correctly +- * implemented libraries reveal the APIs libpng needs to build and hide those +- * that are not needed and potentially damaging to the compilation. +-@@ -308,6 +314,11 @@ +- # endif +- #endif /* Setting PNG_BUILD_DLL if required */ +- +-+/* Modfied for usage in Qt: Do not export the libpng APIs */ +-+#ifdef PNG_BUILD_DLL +-+#undef PNG_BUILD_DLL +-+#endif +-+ +- /* See pngconf.h for more details: the builder of the library may set this on +- * the command line to the right thing for the specific compilation system or it +- * may be automagically set above (at present we know of no system where it does +-@@ -546,6 +557,9 @@ +- #if defined(WIN32) || defined(_Windows) || defined(_WINDOWS) || \ +- defined(_WIN32) || defined(__WIN32__) +- # include /* defines _WINDOWS_ macro */ +-+# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_APP || WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP) +-+# define _WINRT_ /* Define a macro for Windows Runtime builds */ +-+# endif +- #endif +- #endif /* PNG_VERSION_INFO_ONLY */ +- +-@@ -556,7 +570,7 @@ +- +- /* Memory model/platform independent fns */ +- #ifndef PNG_ABORT +--# ifdef _WINDOWS_ +-+# if (defined(_WINDOWS_) || defined(_WIN32_WCE)) && !defined(_WINRT_) +- # define PNG_ABORT() ExitProcess(0) +- # else +- # define PNG_ABORT() abort() +-diff --git a/src/3rdparty/libpng/pngrutil.c b/src/3rdparty/libpng/pngrutil.c +-index d5fa08c397..4db3de990b 100644 +---- a/src/3rdparty/libpng/pngrutil.c +-+++ b/src/3rdparty/libpng/pngrutil.c +-@@ -2087,10 +2087,8 @@ png_handle_eXIf(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) +- } +- } +- +-- if (png_crc_finish(png_ptr, 0) != 0) +-- return; +-- +-- png_set_eXIf_1(png_ptr, info_ptr, length, info_ptr->eXIf_buf); +-+ if (png_crc_finish(png_ptr, 0) == 0) +-+ png_set_eXIf_1(png_ptr, info_ptr, length, info_ptr->eXIf_buf); +- +- png_free(png_ptr, info_ptr->eXIf_buf); +- info_ptr->eXIf_buf = NULL; diff --git a/depends/toolchain.cmake.in b/depends/toolchain.cmake.in new file mode 100644 index 0000000000..df84362aad --- /dev/null +++ b/depends/toolchain.cmake.in @@ -0,0 +1,171 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +# This file is expected to be highly volatile and may still change substantially. + +# If CMAKE_SYSTEM_NAME is set within a toolchain file, CMake will also +# set CMAKE_CROSSCOMPILING to TRUE, even if CMAKE_SYSTEM_NAME matches +# CMAKE_HOST_SYSTEM_NAME. To avoid potential misconfiguration of CMake, +# it is best not to touch CMAKE_SYSTEM_NAME unless cross-compiling is +# intended. +if(@depends_crosscompiling@) + set(CMAKE_SYSTEM_NAME @host_system_name@) + set(CMAKE_SYSTEM_VERSION @host_system_version@) + set(CMAKE_SYSTEM_PROCESSOR @host_arch@) +endif() + +if(NOT DEFINED CMAKE_C_FLAGS_INIT) + set(CMAKE_C_FLAGS_INIT "@CFLAGS@") +endif() +if(NOT DEFINED CMAKE_C_FLAGS_RELWITHDEBINFO_INIT) + set(CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "@CFLAGS_RELEASE@") +endif() +if(NOT DEFINED CMAKE_C_FLAGS_DEBUG_INIT) + set(CMAKE_C_FLAGS_DEBUG_INIT "@CFLAGS_DEBUG@") +endif() + +if(NOT DEFINED CMAKE_C_COMPILER) + set(CMAKE_C_COMPILER @CC@) +endif() + +if(NOT DEFINED CMAKE_CXX_FLAGS_INIT) + set(CMAKE_CXX_FLAGS_INIT "@CXXFLAGS@") + set(CMAKE_OBJCXX_FLAGS_INIT "@CXXFLAGS@") +endif() +if(NOT DEFINED CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT) + set(CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "@CXXFLAGS_RELEASE@") + set(CMAKE_OBJCXX_FLAGS_RELWITHDEBINFO_INIT "@CXXFLAGS_RELEASE@") +endif() +if(NOT DEFINED CMAKE_CXX_FLAGS_DEBUG_INIT) + set(CMAKE_CXX_FLAGS_DEBUG_INIT "@CXXFLAGS_DEBUG@") + set(CMAKE_OBJCXX_FLAGS_DEBUG_INIT "@CXXFLAGS_DEBUG@") +endif() + +if(NOT DEFINED CMAKE_CXX_COMPILER) + set(CMAKE_CXX_COMPILER @CXX@) + set(CMAKE_OBJCXX_COMPILER ${CMAKE_CXX_COMPILER}) +endif() + +# Detect if we're using the MingW toolchain +if(CMAKE_CXX_COMPILER MATCHES "mingw") + set(WIN32 TRUE CACHE INTERNAL "Building for Win32 platform") + set(MINGW TRUE CACHE INTERNAL "Using MingW toolchain") + if(CMAKE_CXX_COMPILER MATCHES "i686-w64-mingw32") + set(MINGW_ARCH "32" CACHE INTERNAL "Using 32-bit MingW toolchain") + message(STATUS "Using 32-bit MingW toolchain.") + elseif(CMAKE_CXX_COMPILER MATCHES "x86_64-w64-mingw32") + set(MINGW_ARCH "64" CACHE INTERNAL "Using 64-bit MingW toolchain") + message(STATUS "Using 64-bit MingW toolchain.") + endif() +else() + set(MINGW FALSE CACHE INTERNAL "Not using MingW toolchain") +endif() + +# The DEPENDS_COMPILE_DEFINITIONS* variables are to be treated as lists. +set(DEPENDS_COMPILE_DEFINITIONS @CPPFLAGS@) +set(DEPENDS_COMPILE_DEFINITIONS_RELWITHDEBINFO @CPPFLAGS_RELEASE@) +set(DEPENDS_COMPILE_DEFINITIONS_DEBUG @CPPFLAGS_DEBUG@) + +if(NOT DEFINED CMAKE_EXE_LINKER_FLAGS_INIT) + set(CMAKE_EXE_LINKER_FLAGS_INIT "@LDFLAGS@") +endif() +if(NOT DEFINED CMAKE_SHARED_LINKER_FLAGS_INIT) + set(CMAKE_SHARED_LINKER_FLAGS_INIT "@LDFLAGS@") +endif() +if(NOT DEFINED CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO_INIT) + set(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO_INIT "@LDFLAGS_RELEASE@") +endif() +if(NOT DEFINED CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO_INIT) + set(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO_INIT "@LDFLAGS_RELEASE@") +endif() +if(NOT DEFINED CMAKE_EXE_LINKER_FLAGS_DEBUG_INIT) + set(CMAKE_EXE_LINKER_FLAGS_DEBUG_INIT "@LDFLAGS_DEBUG@") +endif() +if(NOT DEFINED CMAKE_SHARED_LINKER_FLAGS_DEBUG_INIT) + set(CMAKE_SHARED_LINKER_FLAGS_DEBUG_INIT "@LDFLAGS_DEBUG@") +endif() + +set(CMAKE_AR "@AR@") +set(CMAKE_RANLIB "@RANLIB@") +set(CMAKE_STRIP "@STRIP@") +set(CMAKE_OBJCOPY "@OBJCOPY@") +set(CMAKE_OBJDUMP "@OBJDUMP@") + +# Using our own built dependencies should not be +# affected by a potentially random environment. +set(CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH OFF) + +set(CMAKE_FIND_ROOT_PATH "@depends_prefix@") +list(APPEND CMAKE_PREFIX_PATH "${CMAKE_FIND_ROOT_PATH};${CMAKE_FIND_ROOT_PATH}/lib/") +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) +set(QT_TRANSLATIONS_DIR "@depends_prefix@/translations") +set(Qt5_DIR "${CMAKE_FIND_ROOT_PATH}/lib/cmake/Qt5" CACHE PATH "Path to Qt5 CMake configuration files" FORCE) + +if(CMAKE_SYSTEM_NAME STREQUAL "Darwin" AND NOT CMAKE_HOST_APPLE) + # The find_package(Qt ...) function internally uses find_library() + # calls for all dependencies to ensure their availability. + # In turn, the find_library() inspects the well-known locations + # on the file system; therefore, a hint is required. + set(CMAKE_FRAMEWORK_PATH "@OSX_SDK@/System/Library/Frameworks") +endif() + +# Set configuration options for the main build system. +set(qt_packages @qt_packages@) +if("${qt_packages}" STREQUAL "") + set(BUILD_GUI OFF CACHE BOOL "") +else() + set(BUILD_GUI ON CACHE BOOL "") +endif() + +set(qrencode_packages @qrencode_packages@) +if("${qrencode_packages}" STREQUAL "") + set(WITH_QRENCODE OFF CACHE BOOL "") +else() + set(WITH_QRENCODE ON CACHE BOOL "") +endif() + +set(zmq_packages @zmq_packages@) +if("${zmq_packages}" STREQUAL "") + set(WITH_ZMQ OFF CACHE BOOL "") +else() + set(WITH_ZMQ ON CACHE BOOL "") +endif() + +set(wallet_packages @wallet_packages@) +if("${wallet_packages}" STREQUAL "") + set(ENABLE_WALLET OFF CACHE BOOL "") +else() + set(ENABLE_WALLET ON CACHE BOOL "") +endif() + +set(bdb_packages @bdb_packages@) +if("${wallet_packages}" STREQUAL "" OR "${bdb_packages}" STREQUAL "") + set(WITH_BDB OFF CACHE BOOL "") +else() + set(WITH_BDB ON CACHE BOOL "") +endif() + +set(usdt_packages @usdt_packages@) +if("${usdt_packages}" STREQUAL "") + set(WITH_USDT OFF CACHE BOOL "") +else() + set(WITH_USDT ON CACHE BOOL "") +endif() + +if("@no_harden@") + set(ENABLE_HARDENING OFF CACHE BOOL "") +else() + set(ENABLE_HARDENING ON CACHE BOOL "") +endif() + +if("@multiprocess@" STREQUAL "1") + set(WITH_MULTIPROCESS ON CACHE BOOL "") + set(Libmultiprocess_ROOT "${CMAKE_CURRENT_LIST_DIR}" CACHE PATH "") + set(LibmultiprocessNative_ROOT "${CMAKE_CURRENT_LIST_DIR}/native" CACHE PATH "") +else() + set(WITH_MULTIPROCESS OFF CACHE BOOL "") +endif() \ No newline at end of file diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt new file mode 100644 index 0000000000..60ddd49ec1 --- /dev/null +++ b/doc/CMakeLists.txt @@ -0,0 +1,24 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +find_package(Doxygen COMPONENTS dot) + +if(DOXYGEN_FOUND) + set(doxyfile ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile) + + # In CMake 3.27, The FindDoxygen module's doxygen_add_docs() + # command gained a CONFIG_FILE option to specify a custom doxygen + # configuration file. + # TODO: Consider using it. + add_custom_target(docs + COMMAND Doxygen::doxygen ${doxyfile} + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + COMMENT "Generating developer documentation" + VERBATIM USES_TERMINAL + ) +else() + add_custom_target(docs + COMMAND ${CMAKE_COMMAND} -E echo "Error: Doxygen not found" + ) +endif() diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000000..a2ae3037fb --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,566 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include(GNUInstallDirs) +include(AddWindowsResources) +include(WindowsSystemConfiguration) + +configure_file(${PROJECT_SOURCE_DIR}/cmake/bitcoin-build-config.h.in ${CMAKE_CURRENT_SOURCE_DIR}/config/bitcoin-config.h USE_SOURCE_PERMISSIONS @ONLY) +include_directories(${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}) + +add_custom_target(generate_build_info + BYPRODUCTS ${PROJECT_BINARY_DIR}/src/bitcoin-build-info.h + COMMAND ${CMAKE_COMMAND} -DBUILD_INFO_HEADER_PATH=${PROJECT_BINARY_DIR}/src/bitcoin-build-info.h -DSOURCE_DIR=${PROJECT_SOURCE_DIR} -P ${PROJECT_SOURCE_DIR}/cmake/script/GenerateBuildInfo.cmake + COMMENT "Generating bitcoin-build-info.h" + VERBATIM +) +add_library(bitcoin_clientversion OBJECT EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/clientversion.cpp +) +target_link_libraries(bitcoin_clientversion + PRIVATE + core_interface +) +add_dependencies(bitcoin_clientversion generate_build_info) + +#============================= +# util library +# Firo does not have util subdirectory +#============================= + +add_library(bitcoin_util STATIC EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/bls/bls_batchverifier.h + ${CMAKE_CURRENT_SOURCE_DIR}/bls/bls_ies.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bls/bls_ies.h + ${CMAKE_CURRENT_SOURCE_DIR}/bls/bls_worker.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bls/bls_worker.h + ${CMAKE_CURRENT_SOURCE_DIR}/chainparamsbase.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/clientversion.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/compat/glibc_sanity.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/compat/glibcxx_sanity.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/compat/strnlen.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/crypto/scrypt.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/fs.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/mbstring.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/policy/rbf.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/primitives/block.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/random.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/protocol.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/support/cleanse.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/support/lockedpool.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sync.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/threadinterrupt.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/util.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/utilmoneystr.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/utilstrencodings.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/utiltime.cpp +) + +target_link_libraries(bitcoin_util + PRIVATE + core_interface + bitcoin_clientversion + bitcoin_crypto + Boost::thread + Boost::chrono + univalue + secp256k1 + leveldb + univalue + $<$:windows_system> +) + +add_subdirectory(crypto) +add_subdirectory(univalue) +if(WITH_MULTIPROCESS) + add_subdirectory(ipc) +endif() + +#============================= +# secp256k1 subtree +#============================= +message("") +message("Configuring secp256k1 subtree...") +# We need SECP256K1_BUILD to prevent nonnull warnings +# Basically saying to SECP256K1 we are building it. +add_compile_definitions(SECP256K1_BUILD=1) +set(SECP256K1_DISABLE_SHARED ON CACHE BOOL "" FORCE) +set(SECP256K1_ENABLE_MODULE_ECDH ON CACHE BOOL "" FORCE) +set(SECP256K1_ENABLE_MODULE_RECOVERY ON CACHE BOOL "" FORCE) +set(SECP256K1_ENABLE_MODULE_MUSIG OFF CACHE BOOL "" FORCE) +set(SECP256K1_BUILD_BENCHMARK OFF CACHE BOOL "" FORCE) +set(SECP256K1_BUILD_TESTS ${BUILD_TESTS} CACHE BOOL "" FORCE) +set(SECP256K1_BUILD_EXHAUSTIVE_TESTS ${BUILD_TESTS} CACHE BOOL "" FORCE) +if(NOT BUILD_TESTS) + # Always skip the ctime tests, if we are building no other tests. + # Otherwise, they are built if Valgrind is available. See SECP256K1_VALGRIND. + set(SECP256K1_BUILD_CTIME_TESTS ${BUILD_TESTS} CACHE BOOL "" FORCE) +endif() +set(SECP256K1_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) +include(GetTargetInterface) +# -fsanitize and related flags apply to both C++ and C, +# so we can pass them down to libsecp256k1 as CFLAGS and LDFLAGS. +get_target_interface(core_sanitizer_cxx_flags "" sanitize_interface COMPILE_OPTIONS) +set(SECP256K1_APPEND_CFLAGS ${core_sanitizer_cxx_flags} CACHE STRING "" FORCE) +unset(core_sanitizer_cxx_flags) +get_target_interface(core_sanitizer_linker_flags "" sanitize_interface LINK_OPTIONS) +set(SECP256K1_APPEND_LDFLAGS ${core_sanitizer_linker_flags} CACHE STRING "" FORCE) +unset(core_sanitizer_linker_flags) +# We want to build libsecp256k1 with the most tested RelWithDebInfo configuration. +enable_language(C) +foreach(config IN LISTS CMAKE_BUILD_TYPE CMAKE_CONFIGURATION_TYPES) + if(config STREQUAL "") + continue() + endif() + string(TOUPPER "${config}" config) + set(CMAKE_C_FLAGS_${config} "${CMAKE_C_FLAGS_RELWITHDEBINFO}") +endforeach() +# If the CFLAGS environment variable is defined during building depends +# and configuring this build system, its content might be duplicated. +if(DEFINED ENV{CFLAGS}) + deduplicate_flags(CMAKE_C_FLAGS) +endif() +add_subdirectory(secp256k1) +set_target_properties(secp256k1 PROPERTIES + EXCLUDE_FROM_ALL TRUE +) +string(APPEND CMAKE_C_COMPILE_OBJECT " ${APPEND_CPPFLAGS} ${APPEND_CFLAGS}") + +add_library(bitcoin_consensus STATIC EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/amount.h + ${CMAKE_CURRENT_SOURCE_DIR}/arith_uint256.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/arith_uint256.h + ${CMAKE_CURRENT_SOURCE_DIR}/bls/bls.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bls/bls.h + ${CMAKE_CURRENT_SOURCE_DIR}/consensus/merkle.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/consensus/merkle.h + ${CMAKE_CURRENT_SOURCE_DIR}/consensus/params.h + ${CMAKE_CURRENT_SOURCE_DIR}/consensus/validation.h + ${CMAKE_CURRENT_SOURCE_DIR}/crypto/scrypt.h + ${CMAKE_CURRENT_SOURCE_DIR}/flat-database.h + ${CMAKE_CURRENT_SOURCE_DIR}/hash.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/hash.h + ${CMAKE_CURRENT_SOURCE_DIR}/prevector.h + ${CMAKE_CURRENT_SOURCE_DIR}/primitives/block.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/primitives/block.h + ${CMAKE_CURRENT_SOURCE_DIR}/primitives/precomputed_hash.h + ${CMAKE_CURRENT_SOURCE_DIR}/primitives/transaction.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/primitives/transaction.h + ${CMAKE_CURRENT_SOURCE_DIR}/pubkey.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/pubkey.h + ${CMAKE_CURRENT_SOURCE_DIR}/script/bitcoinconsensus.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/script/interpreter.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/script/interpreter.h + ${CMAKE_CURRENT_SOURCE_DIR}/script/script.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/script/script.h + ${CMAKE_CURRENT_SOURCE_DIR}/script/script_error.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/script/script_error.h + ${CMAKE_CURRENT_SOURCE_DIR}/serialize.h + ${CMAKE_CURRENT_SOURCE_DIR}/tinyformat.h + ${CMAKE_CURRENT_SOURCE_DIR}/uint256.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/uint256.h + ${CMAKE_CURRENT_SOURCE_DIR}/utilstrencodings.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/utilstrencodings.h + ${CMAKE_CURRENT_SOURCE_DIR}/version.h +) +target_link_libraries(bitcoin_consensus + PRIVATE + core_interface + secp256k1 + leveldb + univalue + ${BLS_DASH_LIBRARY} + PUBLIC + univalue + OpenSSL::Crypto + bitcoin_crypto +) + +if(WITH_ZMQ) + add_subdirectory(zmq) +endif() + +# Home for common functionality shared by different executables and libraries. +# Similar to `bitcoin_util` library, but higher-level. +add_library(bitcoin_common STATIC EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/amount.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/base58.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bloom.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/chainparams.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/chainparamsbase.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/coins.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/compressor.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/core_read.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/core_write.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/hdmint/hdmint.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/init.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/key.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/keystore.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/bech32.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/merkleblock.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/netaddress.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/netbase.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/policy/policy.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/protocol.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/rawtransaction.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/saltedhasher.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/scheduler.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/script/sign.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/script/standard.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/warnings.cpp + $<$:${CMAKE_CURRENT_SOURCE_DIR}/stacktraces.cpp> +) +target_link_libraries(bitcoin_common + PUBLIC + core_interface + bitcoin_consensus + bitcoin_util + univalue + secp256k1 + Boost::headers + $<$:${BACKTRACE_LIBRARY}> + leveldb + $<$:firo_zmq> + $ + $<$:windows_system> +) + +apply_wrapped_exception_flags(bitcoin_common) + +include(InstallBinaryComponent) +set(installable_targets) +if(ENABLE_WALLET) + add_subdirectory(wallet) +endif() + + +# P2P and RPC server functionality used by `bitcoind` and `firo-qt` executables. +add_library(firo_node STATIC EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/activemasternode.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/addrdb.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/addrman.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/batchedlogger.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/batchproof_container.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bip47/paymentcode.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/blockencodings.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bloom.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/chain.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/checkpoints.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/coin_containers.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/compat/glibc_sanity.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/compat/glibcxx_sanity.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/dbwrapper.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/dsnotificationinterface.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/evo/cbtx.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/evo/deterministicmns.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/evo/evodb.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/evo/mnauth.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/evo/providertx.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/evo/simplifiedmns.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/evo/specialtx.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/evo/spork.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/httprpc.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/httpserver.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/init.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/lelantus.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/coin.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/innerproduct_proof_generator.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/innerproduct_proof_verifier.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/joinsplit.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/lelantus_primitives.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/lelantus_prover.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/lelantus_verifier.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/params.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/range_prover.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/range_verifier.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/schnorr_prover.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/schnorr_verifier.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/sigmaextended_prover.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/sigmaextended_verifier.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/liblelantus/spend_metadata.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/aead.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/bech32.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/bpplus.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/chaum.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/coin.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/f4grumble.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/grootle.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/hash.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/kdf.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/keys.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/mint_transaction.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/params.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/schnorr.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/spend_transaction.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/transcript.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libspark/util.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums_blockprocessor.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums_chainlocks.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums_commitment.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums_debug.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums_dkgsession.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums_dkgsessionhandler.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums_dkgsessionmgr.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums_init.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums_instantsend.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums_signing.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums_signing_shares.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmq/quorums_utils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/masternode-payments.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/masternode-sync.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/masternode-utils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/merkleblock.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/messagesigner.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/miner.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/mtpstate.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/net.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/net_processing.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/netfulfilledman.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/noui.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/policy/fees.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/policy/policy.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/policy/rbf.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/pow.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/primitives/mint_spend.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rest.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/blockchain.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/masternode.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/mining.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/misc.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/net.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/rawtransaction.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/rpcevo.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/rpcquorums.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/server.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/script/ismine.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/script/sigcache.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigma.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigma/coin.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigma/coinspend.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigma/params.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigma/spend_metadata.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/spark/primitives.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sparkname.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/spark/state.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/threadinterrupt.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/timedata.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/torcontrol.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/txdb.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/txmempool.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ui_interface.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/validation.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/validationinterface.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/versionbits.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/warnings.cpp +) + +target_link_libraries(firo_node + PRIVATE + core_interface + bitcoin_common + bitcoin_util + secp256k1 + $<$:firo_zmq> + leveldb + univalue + Boost::headers + Boost::thread + OpenSSL::Crypto + ${TOR_LIBRARY} + OpenSSL::SSL + ${MINIUPNP_LIBRARY} + ${ZLIB_LIBRARY} + $ + $ + $ + $ + $<$:windows_system> +) + +# Bitcoin Core firod. +if(BUILD_DAEMON) + add_executable(firod + ${CMAKE_CURRENT_SOURCE_DIR}/bitcoind.cpp + ) + add_windows_resources(firod bitcoind-res.rc) + target_link_libraries(firod + core_interface + univalue + Boost::thread + firo_node + $ + $ + $ + $<$:firo_zmq> + firo_cli + secp256k1 + secp256k1pp + $ + ${TOR_LIBRARY} + $<$:windows_system> + ) + set_platform_output_name(firod FIRO_DAEMON_NAME) + apply_wrapped_exception_flags(firod) + list(APPEND installable_targets firod) +endif() +if(WITH_MULTIPROCESS) + add_executable(bitcoin-node + ${CMAKE_CURRENT_SOURCE_DIR}/bitcoind.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/init/bitcoin-node.cpp + ) + target_link_libraries(bitcoin-node + core_interface + firo_node + bitcoin_ipc + $ + ) + list(APPEND installable_targets bitcoin-node) + + if(BUILD_TESTS) + # bitcoin_ipc_test library target is defined here in src/CMakeLists.txt + # instead of src/test/CMakeLists.txt so capnp files in src/test/ are able to + # reference capnp files in src/ipc/capnp/ by relative path. The Cap'n Proto + # compiler only allows importing by relative path when the importing and + # imported files are underneath the same compilation source prefix, so the + # source prefix must be src/, not src/test/ + add_library(bitcoin_ipc_test STATIC EXCLUDE_FROM_ALL + test/ipc_test.cpp + ) + target_capnp_sources(bitcoin_ipc_test ${PROJECT_SOURCE_DIR} + test/ipc_test.capnp + ) + add_dependencies(bitcoin_ipc_test bitcoin_ipc_headers) + endif() +endif() + + +add_library(firo_cli STATIC EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/client.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc/protocol.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/util.cpp +) +target_link_libraries(firo_cli + PUBLIC + core_interface + univalue + Boost::filesystem + Boost::thread + Boost::program_options + firo_node + $ + $ + $ + $<$:firo_zmq> + $ + ${TOR_LIBRARY} + $<$:windows_system> +) +target_include_directories(firo_cli + PUBLIC +) + +# Bitcoin Core RPC client +if(BUILD_CLI) + add_executable(firo-cli ${CMAKE_CURRENT_SOURCE_DIR}/bitcoin-cli.cpp) + add_windows_resources(firo-cli bitcoin-cli-res.rc) + target_link_libraries(firo-cli + core_interface + univalue + firo_node + $ + $ + $ + $<$:firo_zmq> + firo_cli + $ + ${TOR_LIBRARY} + $<$:windows_system> + ) + set_platform_output_name(firo-cli FIRO_CLI_NAME) + apply_wrapped_exception_flags(firo-cli) + list(APPEND installable_targets firo-cli) +endif() + + +if(BUILD_TX) + add_executable(firo-tx ${CMAKE_CURRENT_SOURCE_DIR}/bitcoin-tx.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/keystore.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/script/standard.cpp + ) + add_windows_resources(firo-tx bitcoin-tx-res.rc) + target_link_libraries(firo-tx + core_interface + bitcoin_crypto + firo_cli + bitcoin_common + bitcoin_util + univalue + secp256k1pp + secp256k1 + $<$:windows_system> + $<$:OpenSSL::Crypto> + ) + set_platform_output_name(firo-tx FIRO_TX_NAME) + apply_wrapped_exception_flags(firo-tx) + list(APPEND installable_targets firo-tx) +endif() + + + +if(BUILD_GUI) + add_subdirectory(qt) +endif() + + +if(BUILD_KERNEL_LIB) + add_subdirectory(kernel) +endif() + +if(BUILD_UTIL_CHAINSTATE) + add_executable(bitcoin-chainstate + ${CMAKE_CURRENT_SOURCE_DIR}/bitcoin-chainstate.cpp + ) + # TODO: The `SKIP_BUILD_RPATH` property setting can be deleted + # in the future after reordering Guix script commands to + # perform binary checks after the installation step. + # Relevant discussions: + # - https://github.com/hebasto/bitcoin/pull/236#issuecomment-2183120953 + # - https://github.com/bitcoin/bitcoin/pull/30312#issuecomment-2191235833 + set_target_properties(bitcoin-chainstate PROPERTIES + SKIP_BUILD_RPATH OFF + ) + target_link_libraries(bitcoin-chainstate + PRIVATE + core_interface + bitcoinkernel + ) +endif() + + +if(BUILD_BENCH) + add_subdirectory(bench) +endif() + +if(BUILD_TESTS) + add_subdirectory(test) +endif() + +if(BUILD_FUZZ_BINARY) + add_subdirectory(test/fuzz) +endif() + + +install(TARGETS ${installable_targets} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) +unset(installable_targets) + +if(INSTALL_MAN) + # TODO: these stubs are no longer needed. man pages should be generated at install time. + install(DIRECTORY ../doc/man/ + DESTINATION ${CMAKE_INSTALL_MANDIR}/man1 + FILES_MATCHING PATTERN *.1 + ) +endif() \ No newline at end of file diff --git a/src/Makefile.am b/src/Makefile.am index 337f9f5a7e..a825d9c7c3 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -7,6 +7,7 @@ DIST_SUBDIRS = secp256k1 univalue AM_LDFLAGS = $(PTHREAD_CFLAGS) $(LIBTOOL_LDFLAGS) $(HARDENED_LDFLAGS) AM_CXXFLAGS = $(HARDENED_CXXFLAGS) $(ERROR_CXXFLAGS) AM_CPPFLAGS = $(HARDENED_CPPFLAGS) +AM_CPPFLAGS += -I$(srcdir)/wallet -I$(srcdir)/../src/wallet -I$(srcdir) -I$(srcdir)/../src AM_LIBTOOLFLAGS = --preserve-dup-deps EXTRA_LIBRARIES = @@ -188,6 +189,7 @@ BITCOIN_CORE_H = \ script/sign.h \ script/standard.h \ script/ismine.h \ + sparkname.h \ streams.h \ support/allocators/secure.h \ support/allocators/zeroafterfree.h \ @@ -894,7 +896,9 @@ CLEANFILES += zmq/*.gcda zmq/*.gcno DISTCLEANFILES = obj/build.h -EXTRA_DIST = $(CTAES_DIST) +EXTRA_DIST = $(CTAES_DIST) \ + wallet/rpcdump.h \ + compat_layer.h config/bitcoin-config.h: config/stamp-h1 @$(MAKE) -C $(top_builddir) $(subdir)/$(@) diff --git a/src/Makefile.test.include b/src/Makefile.test.include index 626dee90eb..4e5bbec471 100644 --- a/src/Makefile.test.include +++ b/src/Makefile.test.include @@ -207,7 +207,7 @@ BITCOIN_TESTS += \ wallet/test/wallet_tests.cpp \ wallet/test/crypto_tests.cpp \ wallet/test/lelantus_tests.cpp \ - wallet/test/spark_tests.cpp \ + wallet/test/spark_wallet_tests.cpp \ wallet/test/sigma_tests.cpp \ wallet/test/mnemonic_tests.cpp \ wallet/test/txbuilder_tests.cpp diff --git a/src/activemasternode.h b/src/activemasternode.h index ea661641f4..0506b80a43 100644 --- a/src/activemasternode.h +++ b/src/activemasternode.h @@ -56,7 +56,7 @@ class CActiveMasternodeManager : public CValidationInterface std::string strError; public: - virtual void UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload); + virtual void UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload) override; void Init(); diff --git a/src/bench/CMakeLists.txt b/src/bench/CMakeLists.txt new file mode 100644 index 0000000000..964aba54e0 --- /dev/null +++ b/src/bench/CMakeLists.txt @@ -0,0 +1,46 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include(GenerateHeaders) +generate_header_from_raw(data/block413567.raw benchmark::data) + +add_executable(bench_firo + ${CMAKE_CURRENT_SOURCE_DIR}/bench_bitcoin.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bench.cpp + ${CMAKE_CURRENT_BINARY_DIR}/data/block413567.raw.h +# Benchmarks: + ${CMAKE_CURRENT_SOURCE_DIR}/base58.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ccoins_caching.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/checkblock.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/checkqueue.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/crypto_hash.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Examples.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/lockedpool.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/mempool_eviction.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/perf.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rollingbloom.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/verify_script.cpp +) + +target_link_libraries(bench_firo + core_interface + firo_node + Boost::headers +) + +if(ENABLE_WALLET) + target_sources(bench_firo + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/coin_selection.cpp + ) + target_link_libraries(bench_firo firo_wallet) +endif() + +add_test(NAME bench_sanity_check_high_priority + COMMAND bench_firo -sanity-check -priority-level=high +) + +install(TARGETS bench_firo + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) diff --git a/src/bench/bench.h b/src/bench/bench.h index 0e7605c726..90a942f6c3 100644 --- a/src/bench/bench.h +++ b/src/bench/bench.h @@ -7,6 +7,7 @@ #include #include +#include #include #include diff --git a/src/bip47/account.cpp b/src/bip47/account.cpp index adb0c7fac6..6a0c1f9538 100644 --- a/src/bip47/account.cpp +++ b/src/bip47/account.cpp @@ -67,8 +67,8 @@ uint32_t CAccountBase::getVersion() const /******************************************************************************/ -CAccountSender::CAccountSender(CExtKey const & walletKey, uint32_t accountNum, CPaymentCode const & theirPcode) -: CAccountBase(walletKey, accountNum), theirPcode(theirPcode) +CAccountSender::CAccountSender(CExtKey const & walletKey, uint32_t accountNumParam, CPaymentCode const & theirPcode) +: CAccountBase(walletKey, accountNumParam), theirPcode(theirPcode) { updateMyNextAddresses(); } @@ -141,8 +141,8 @@ uint256 CAccountSender::getNotificationTxId() const /******************************************************************************/ -CAccountReceiver::CAccountReceiver(CExtKey const & walletKey, uint32_t accountNum, std::string const & label) -: CAccountBase(walletKey, accountNum), label(label) +CAccountReceiver::CAccountReceiver(CExtKey const & walletKey, uint32_t accountNumParam, std::string const & label) +: CAccountBase(walletKey, accountNumParam), label(label) {} CBitcoinAddress const & CAccountReceiver::getMyNotificationAddress() const diff --git a/src/bip47/account.h b/src/bip47/account.h index 14939044db..065a101fd5 100644 --- a/src/bip47/account.h +++ b/src/bip47/account.h @@ -68,7 +68,7 @@ class CAccountSender : public CAccountBase { public: CAccountSender() = default; - CAccountSender(CExtKey const & walletKey, uint32_t accountNum, CPaymentCode const & theirPcode); + CAccountSender(CExtKey const & walletKey, uint32_t accountNumParam, CPaymentCode const & theirPcode); CPaymentChannel & getPaymentChannel() const; std::vector getMaskedPayload(COutPoint const & outpoint, CKey const & outpointSecret); @@ -104,9 +104,9 @@ class CAccountSender : public CAccountBase std::string label; void updateMyNextAddresses(); - virtual MyAddrContT const & generateMyUsedAddresses() const; - virtual MyAddrContT const & generateMyNextAddresses() const; - virtual bool markAddressUsed(CBitcoinAddress const &); + virtual MyAddrContT const & generateMyUsedAddresses() const override; + virtual MyAddrContT const & generateMyNextAddresses() const override; + virtual bool markAddressUsed(CBitcoinAddress const &) override; }; /******************************************************************************/ @@ -120,7 +120,7 @@ class CAccountReceiver : public CAccountBase { public: CAccountReceiver() = default; - CAccountReceiver(CExtKey const & walletKey, uint32_t accountNum, std::string const & label); + CAccountReceiver(CExtKey const & walletKey, uint32_t accountNumParam, std::string const & label); CBitcoinAddress const & getMyNotificationAddress() const; @@ -155,9 +155,9 @@ class CAccountReceiver : public CAccountBase MyAddrContT mutable usedAddresses, nextAddresses; std::string label; - virtual MyAddrContT const & generateMyUsedAddresses() const; - virtual MyAddrContT const & generateMyNextAddresses() const; - virtual bool markAddressUsed(CBitcoinAddress const &); + virtual MyAddrContT const & generateMyUsedAddresses() const override; + virtual MyAddrContT const & generateMyNextAddresses() const override; + virtual bool markAddressUsed(CBitcoinAddress const &) override; }; /******************************************************************************/ diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp index aeae0962db..c3346c94e3 100644 --- a/src/bitcoin-cli.cpp +++ b/src/bitcoin-cli.cpp @@ -306,8 +306,8 @@ int CommandLineRPC(int argc, char *argv[]) const UniValue reply = CallRPC(strMethod, params); // Parse reply - const UniValue& result = find_value(reply, "result"); - const UniValue& error = find_value(reply, "error"); + const auto result = find_value(reply, "result"); + const auto error = find_value(reply, "error"); if (!error.isNull()) { // Error diff --git a/src/bitcoin_bignum/bignum.h b/src/bitcoin_bignum/bignum.h index b1df2a67fc..04a8192e52 100644 --- a/src/bitcoin_bignum/bignum.h +++ b/src/bitcoin_bignum/bignum.h @@ -9,10 +9,10 @@ #include #include -#include "../../uint256.h" // for uint64 -#include "../../arith_uint256.h" -#include "../../version.h" -#include "../../clientversion.h" +#include "../uint256.h" // for uint64 +#include "../arith_uint256.h" +#include "../version.h" +#include "../clientversion.h" /** Errors thrown by the bignum class */ class bignum_error : public std::runtime_error { @@ -121,7 +121,7 @@ class CAutoBN_CTX /** Generates a cryptographically secure random number between zero and range exclusive * i.e. 0 < returned number < range * @param range The upper bound on the number. - * @return + * @return random BigNum */ static CBigNum randBignum(const CBigNum& range) { CBigNum ret; @@ -133,7 +133,7 @@ class CAutoBN_CTX /** Generates a cryptographically secure random k-bit number * @param k The bit length of the number. - * @return + * @return random k-bit BigNum */ static CBigNum RandKBitBigum(const uint32_t k){ CBigNum ret; @@ -495,7 +495,7 @@ class CAutoBN_CTX /** * exponentiation with an int. this^e * @param e the exponent as an int - * @return + * @return BigNum^e */ CBigNum pow(const int e) const { return this->pow(CBigNum(e)); @@ -504,7 +504,7 @@ class CAutoBN_CTX /** * exponentiation this^e * @param e the exponent - * @return + * @return BigNum^e */ CBigNum pow(const CBigNum& e) const { CAutoBN_CTX pctx; @@ -578,10 +578,10 @@ class CAutoBN_CTX /** * Calculates the greatest common divisor (GCD) of two numbers. - * @param m the second element + * @param b the second element * @return the GCD */ - CBigNum gcd( const CBigNum& b) const{ + CBigNum gcd(const CBigNum& b) const{ CAutoBN_CTX pctx; CBigNum ret; if (!BN_gcd(&ret, bn, &b, pctx)) @@ -591,7 +591,7 @@ class CAutoBN_CTX /** * Miller-Rabin primality test on this element - * @param checks: optional, the number of Miller-Rabin tests to run + * @param checks optional, the number of Miller-Rabin tests to run * default causes error rate of 2^-80. * @return true if prime */ diff --git a/src/bitcoind.cpp b/src/bitcoind.cpp index 253c03756f..53646ac9cf 100644 --- a/src/bitcoind.cpp +++ b/src/bitcoind.cpp @@ -162,7 +162,7 @@ bool AppInit(int argc, char* argv[]) } if (GetBoolArg("-daemon", false)) { -#if HAVE_DECL_DAEMON +#if defined(HAVE_DECL_DAEMON) && HAVE_DECL_DAEMON fprintf(stdout, "Firo server starting\n"); // Daemonize @@ -173,7 +173,7 @@ bool AppInit(int argc, char* argv[]) #else fprintf(stderr, "Error: -daemon is not supported on this operating system\n"); return false; -#endif // HAVE_DECL_DAEMON +#endif // defined(HAVE_DECL_DAEMON) && HAVE_DECL_DAEMON } fRet = AppInitMain(threadGroup, scheduler); diff --git a/src/bls/bls_worker.cpp b/src/bls/bls_worker.cpp index 92ca72ce93..4e82327ed6 100644 --- a/src/bls/bls_worker.cpp +++ b/src/bls/bls_worker.cpp @@ -84,7 +84,7 @@ bool CBLSWorker::GenerateContributions(int quorumThreshold, const BLSIdVector& i std::list > futures; size_t batchSize = 8; - for (size_t i = 0; i < quorumThreshold; i += batchSize) { + for (size_t i = 0; cmp::less(i, quorumThreshold); i += batchSize) { size_t start = i; size_t count = std::min(batchSize, quorumThreshold - start); auto f = [&, start, count](int threadId) { @@ -155,8 +155,8 @@ struct Aggregator { bool _parallel, ctpl::thread_pool& _workerPool, DoneCallback _doneCallback) : - workerPool(_workerPool), parallel(_parallel), + workerPool(_workerPool), aggQueue(0), doneCallback(std::move(_doneCallback)) { @@ -353,12 +353,12 @@ struct VectorAggregator { size_t _start, size_t _count, bool _parallel, ctpl::thread_pool& _workerPool, DoneCallback _doneCallback) : + doneCallback(std::move(_doneCallback)), vecs(_vecs), - parallel(_parallel), start(_start), count(_count), - workerPool(_workerPool), - doneCallback(std::move(_doneCallback)) + parallel(_parallel), + workerPool(_workerPool) { assert(!vecs.empty()); vecSize = vecs[0]->size(); @@ -761,7 +761,7 @@ std::future CBLSWorker::AsyncVerifyContributionShare(const CBLSId& forId, return std::move(p.second); } - auto f = [this, &forId, &vvec, &skContribution](int threadId) { + auto f = [&forId, &vvec, &skContribution](int threadId) { CBLSPublicKey pk1; if (!pk1.PublicKeyShare(*vvec, forId)) { return false; diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 0a57183bf8..219804f11a 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -494,11 +494,11 @@ class CMainParams : public CChainParams { consensus.nSparkNamesStartBlock = 1104500; // ~ May 28th 2025 consensus.nSparkNamesFee = standardSparkNamesFee; } - virtual bool SkipUndoForBlock(int nHeight) const + virtual bool SkipUndoForBlock(int nHeight) const override { return nHeight == 293526; } - virtual bool ApplyUndoForTxout(int nHeight, uint256 const & txid, int n) const + virtual bool ApplyUndoForTxout(int nHeight, uint256 const & txid, int n) const override { // We only apply first 23 tx inputs UNDOs for the tx 7702 in block 293526 if (!SkipUndoForBlock(nHeight)) { diff --git a/src/coin_containers.h b/src/coin_containers.h index 15da1224a1..e60e6457e4 100644 --- a/src/coin_containers.h +++ b/src/coin_containers.h @@ -63,7 +63,7 @@ namespace lelantus { // Use this version of code in case you need mobile api struct MintValueData { bool isJMint = false; - uint64_t amount; + uint64_t amount = 0; std::vector encryptedValue; uint256 txHash; diff --git a/src/coins.h b/src/coins.h index cd44012a5c..2b3310f5d1 100644 --- a/src/coins.h +++ b/src/coins.h @@ -206,11 +206,11 @@ class CCoinsViewCache : public CCoinsViewBacked CCoinsViewCache(CCoinsView *baseIn); // Standard CCoinsView methods - bool GetCoin(const COutPoint &outpoint, Coin &coin) const; - bool HaveCoin(const COutPoint &outpoint) const; - uint256 GetBestBlock() const; + bool GetCoin(const COutPoint &outpoint, Coin &coin) const override; + bool HaveCoin(const COutPoint &outpoint) const override; + uint256 GetBestBlock() const override; void SetBestBlock(const uint256 &hashBlock); - bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock); + bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override; /** * Check if we have the given utxo already loaded in this cache. diff --git a/src/compat_layer.h b/src/compat_layer.h new file mode 100644 index 0000000000..ec6d9880c8 --- /dev/null +++ b/src/compat_layer.h @@ -0,0 +1,124 @@ +#ifndef COMPAT_LAYER_H +#define COMPAT_LAYER_H + +#ifdef __cplusplus + #if defined(HAVE_MAYBE_UNUSED) + #define FIRO_UNUSED [[maybe_unused]] + #elif defined(HAVE_ATTRIBUTE_UNUSED) + #define FIRO_UNUSED __attribute__((unused)) + #else + #define FIRO_UNUSED + #endif +#else + // In C mode, if the compiler supports __attribute__((unused)), use it. + #if defined(__has_attribute) + #if __has_attribute(unused) + #define FIRO_UNUSED __attribute__((unused)) + #else + #define FIRO_UNUSED + #endif + #else + #define FIRO_UNUSED + #endif +#endif + +#if defined(__cplusplus) && (__cplusplus >= 201703L) + #if defined(__has_attribute) && __has_attribute(fallthrough) + #define FIRO_FALLTHROUGH [[fallthrough]] + #elif !defined(__clang__) && defined(__has_attribute) + #if __has_attribute(gnu::fallthrough) + #define FIRO_FALLTHROUGH [[gnu::fallthrough]] + #endif + #elif defined(__has_attribute) && __has_attribute(fallthrough) + #define FIRO_FALLTHROUGH __attribute__((fallthrough)) + #elif defined(__GNUC__) && (__GNUC__ >= 7) && !defined(__clang__) + #define FIRO_FALLTHROUGH __attribute__((fallthrough)) + #endif +#else + #define FIRO_FALLTHROUGH /* fallthrough */ +#endif + +#ifdef __cplusplus + + #include + #include + + namespace detail { + template + constexpr void check_integral_types() noexcept { + static_assert(std::is_integral_v && std::is_integral_v, + "cmp_* functions require integral types."); + } + } // namespace detail + + namespace cmp { + + template + constexpr bool equal(T t, U u) noexcept + { + // detail::check_integral_types(); // Option 1: use helper + static_assert(std::is_integral_v && std::is_integral_v, // Option 2: repeat + "cmp::* functions require integral types."); + if constexpr (std::is_signed_v == std::is_signed_v) + return t == u; + else if constexpr (std::is_signed_v) // T is signed, U is unsigned + // If t is negative, it cannot be equal to an unsigned u. + // Otherwise, convert t to its unsigned type for comparison. + return t >= 0 && std::make_unsigned_t(t) == u; + else // T is unsigned, U is signed + // If u is negative, it cannot be equal to an unsigned t. + // Otherwise, convert u to its unsigned type for comparison. + return u >= 0 && t == std::make_unsigned_t(u); + } + + template + constexpr bool not_equal(T t, U u) noexcept + { + // No separate static_assert needed here as equal has it. + return !equal(t, u); + } + + template + constexpr bool less(T t, U u) noexcept + { + // detail::check_integral_types(); // Option 1: use helper + static_assert(std::is_integral_v && std::is_integral_v, // Option 2: repeat + "* functions require integral types."); + if constexpr (std::is_signed_v == std::is_signed_v) + return t < u; + else if constexpr (std::is_signed_v) // T is signed, U is unsigned + // If t is negative, it's always less than an unsigned u. + // Otherwise, convert t to its unsigned type for comparison. + return t < 0 || std::make_unsigned_t(t) < u; + else // T is unsigned, U is signed + // If u is negative, t (unsigned) cannot be less than u. + // (i.e. t < u is false if u < 0) + // If u is non-negative, convert u to its unsigned type for comparison. + return u >= 0 && t < std::make_unsigned_t(u); + } + + template + constexpr bool greater(T t, U u) noexcept + { + return less(u, t); + } + + template + constexpr bool less_equal(T t, U u) noexcept + { + // t <= u is equivalent to !(u < t) + return !less(u, t); + } + + template + constexpr bool greater_equal(T t, U u) noexcept + { + // t >= u is equivalent to !(t < u) + return !less(t, u); + } + + } + +#endif + +#endif // COMPAT_LAYER_H \ No newline at end of file diff --git a/src/consensus/tx_verify.cpp b/src/consensus/tx_verify.cpp index bf68f8754b..cf81d2779f 100644 --- a/src/consensus/tx_verify.cpp +++ b/src/consensus/tx_verify.cpp @@ -2,8 +2,6 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "tx_verify.h" - #include "consensus.h" #include "primitives/transaction.h" #include "script/interpreter.h" @@ -201,7 +199,8 @@ bool CheckTransaction(const CTransaction& tx, CValidationState &state, bool fChe return true; } -bool Consensus::CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight) +namespace Consensus { +bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight) { // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. @@ -244,3 +243,4 @@ bool Consensus::CheckTxInputs(const CTransaction& tx, CValidationState& state, c return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange"); return true; } +} // namespace Consensus \ No newline at end of file diff --git a/src/crypto/CMakeLists.txt b/src/crypto/CMakeLists.txt new file mode 100644 index 0000000000..7e9e7a47df --- /dev/null +++ b/src/crypto/CMakeLists.txt @@ -0,0 +1,46 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +add_subdirectory(progpow) + +add_library(bitcoin_crypto STATIC EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/aes.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/chacha20.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/hmac_sha256.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/hmac_sha512.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/progpow.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ripemd160.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sha1.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sha256.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sha512.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/scrypt.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/MerkleTreeProof/arith_uint256.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/MerkleTreeProof/blake2 + ${CMAKE_CURRENT_SOURCE_DIR}/MerkleTreeProof/core.c + ${CMAKE_CURRENT_SOURCE_DIR}/MerkleTreeProof/merkle-tree.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/MerkleTreeProof/mtp.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/MerkleTreeProof/ref.c + ${CMAKE_CURRENT_SOURCE_DIR}/MerkleTreeProof/thread.c + ${CMAKE_CURRENT_SOURCE_DIR}/MerkleTreeProof/blake2/blake2b.c + ${CMAKE_CURRENT_SOURCE_DIR}/MerkleTreeProof/crypto/sha256.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Lyra2Z/Lyra2.c + ${CMAKE_CURRENT_SOURCE_DIR}/Lyra2Z/Lyra2Z.c + ${CMAKE_CURRENT_SOURCE_DIR}/Lyra2Z/Sponge.c + ${CMAKE_CURRENT_SOURCE_DIR}/Lyra2Z/blake.c + ${CMAKE_CURRENT_SOURCE_DIR}/../support/cleanse.cpp +) + +target_link_libraries(bitcoin_crypto + PRIVATE + core_interface + ${Boost_LIBRARIES} + PUBLIC + ethash + keccak +) + +target_include_directories(bitcoin_crypto + PUBLIC + ${Boost_INCLUDE_DIR} +) \ No newline at end of file diff --git a/src/crypto/Lyra2Z/Lyra2.c b/src/crypto/Lyra2Z/Lyra2.c index ac8a13d0d4..3c92720bed 100644 --- a/src/crypto/Lyra2Z/Lyra2.c +++ b/src/crypto/Lyra2Z/Lyra2.c @@ -49,11 +49,11 @@ int LYRA2(void *K, uint64_t kLen, const void *pwd, uint64_t pwdlen, const void * int64_t row = 2; //index of row to be processed int64_t prev = 1; //index of prev (last row ever computed/modified) int64_t rowa = 0; //index of row* (a previous row, deterministically picked during Setup and randomly picked while Wandering) - int64_t tau; //Time Loop iterator int64_t step = 1; //Visitation step (used during Setup and Wandering phases) int64_t window = 2; //Visitation window (used to define which rows can be revisited during Setup) int64_t gap = 1; //Modifier to the step, assuming the values 1 or -1 - int64_t i; //auxiliary iteration counter + uint64_t tau = 0; //Time Loop iterator + uint64_t i = 0; //auxiliary iteration counter //==========================================================================/ //========== Initializing the Memory Matrix and pointers to it =============// @@ -161,14 +161,14 @@ int LYRA2(void *K, uint64_t kLen, const void *pwd, uint64_t pwdlen, const void * gap = -gap; //inverts the modifier to the step } - } while (row < nRows); + } while (row < (int64_t)nRows); //==========================================================================/ //============================ Wandering Phase =============================// row = 0; //Resets the visitation to the first row of the memory matrix for (tau = 1; tau <= timeCost; tau++) { //Step is approximately half the number of all rows of the memory matrix for an odd tau; otherwise, it is -1 - step = (tau % 2 == 0) ? -1 : nRows / 2 - 1; + step = (tau % 2 == 0) ? (int64_t)-1 : (int64_t)(nRows / 2) - 1; do { //Selects a pseudorandom index row* //------------------------------------------------------------------------------------------ @@ -218,11 +218,11 @@ int LYRA2_old(void *K, uint64_t kLen, const void *pwd, uint64_t pwdlen, const vo int64_t row = 2; //index of row to be processed int64_t prev = 1; //index of prev (last row ever computed/modified) int64_t rowa = 0; //index of row* (a previous row, deterministically picked during Setup and randomly picked while Wandering) - int64_t tau; //Time Loop iterator int64_t step = 1; //Visitation step (used during Setup and Wandering phases) int64_t window = 2; //Visitation window (used to define which rows can be revisited during Setup) int64_t gap = 1; //Modifier to the step, assuming the values 1 or -1 - int64_t i; //auxiliary iteration counter + uint64_t tau = 0; //Time Loop iterator + uint64_t i = 0; //auxiliary iteration counter //==========================================================================/ //========== Initializing the Memory Matrix and pointers to it =============// @@ -330,14 +330,14 @@ int LYRA2_old(void *K, uint64_t kLen, const void *pwd, uint64_t pwdlen, const vo gap = -gap; //inverts the modifier to the step } - } while (row < nRows); + } while (row < (int64_t)nRows); //==========================================================================/ //============================ Wandering Phase =============================// row = 0; //Resets the visitation to the first row of the memory matrix for (tau = 1; tau <= timeCost; tau++) { //Step is approximately half the number of all rows of the memory matrix for an odd tau; otherwise, it is -1 - step = (tau % 2 == 0) ? -1 : nRows / 2 - 1; + step = (tau % 2 == 0) ? (int64_t)-1 : (int64_t)(nRows / 2) - 1; do { //Selects a pseudorandom index row* //------------------------------------------------------------------------------------------ diff --git a/src/crypto/Lyra2Z/Sponge.c b/src/crypto/Lyra2Z/Sponge.c index 5efd5b1bbf..6cdd12748a 100644 --- a/src/crypto/Lyra2Z/Sponge.c +++ b/src/crypto/Lyra2Z/Sponge.c @@ -163,7 +163,7 @@ inline void absorbBlockBlake2Safe(uint64_t *state, const uint64_t *in) { */ inline void reducedSqueezeRow0(uint64_t* state, uint64_t* rowOut, uint64_t nCols) { uint64_t* ptrWord = rowOut + (nCols-1)*BLOCK_LEN_INT64; //In Lyra2: pointer to M[0][C-1] - int i; + uint64_t i; //M[row][C-1-col] = H.reduced_squeeze() for (i = 0; i < nCols; i++) { ptrWord[0] = state[0]; @@ -199,7 +199,7 @@ inline void reducedSqueezeRow0(uint64_t* state, uint64_t* rowOut, uint64_t nCols inline void reducedDuplexRow1(uint64_t *state, uint64_t *rowIn, uint64_t *rowOut, uint64_t nCols) { uint64_t* ptrWordIn = rowIn; //In Lyra2: pointer to prev uint64_t* ptrWordOut = rowOut + (nCols-1)*BLOCK_LEN_INT64; //In Lyra2: pointer to row - int i; + uint64_t i; for (i = 0; i < nCols; i++) { @@ -260,7 +260,7 @@ inline void reducedDuplexRowSetup(uint64_t *state, uint64_t *rowIn, uint64_t *ro uint64_t* ptrWordIn = rowIn; //In Lyra2: pointer to prev uint64_t* ptrWordInOut = rowInOut; //In Lyra2: pointer to row* uint64_t* ptrWordOut = rowOut + (nCols-1)*BLOCK_LEN_INT64; //In Lyra2: pointer to row - int i; + uint64_t i; for (i = 0; i < nCols; i++) { //Absorbing "M[prev] [+] M[row*]" @@ -334,7 +334,7 @@ inline void reducedDuplexRow(uint64_t *state, uint64_t *rowIn, uint64_t *rowInOu uint64_t* ptrWordInOut = rowInOut; //In Lyra2: pointer to row* uint64_t* ptrWordIn = rowIn; //In Lyra2: pointer to prev uint64_t* ptrWordOut = rowOut; //In Lyra2: pointer to row - int i; + uint64_t i; for (i = 0; i < nCols; i++) { @@ -734,7 +734,7 @@ inline void reducedDuplexRowd(uint64_t *state, uint64_t *rowIn, uint64_t *rowInO Prints an array of unsigned chars */ void printArray(unsigned char *array, unsigned int size, char *name) { - int i; + uint64_t i; printf("%s: ", name); for (i = 0; i < size; i++) { printf("%2x|", array[i]); diff --git a/src/crypto/Lyra2Z/blake.c b/src/crypto/Lyra2Z/blake.c index 0650b9cf21..9f419f0ff8 100644 --- a/src/crypto/Lyra2Z/blake.c +++ b/src/crypto/Lyra2Z/blake.c @@ -40,15 +40,15 @@ extern "C"{ #endif -#if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_BLAKE +#if defined SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_BLAKE #define SPH_SMALL_FOOTPRINT_BLAKE 1 #endif -#if SPH_SMALL_FOOTPRINT_BLAKE +#if defined SPH_SMALL_FOOTPRINT_BLAKE #define SPH_COMPACT_BLAKE_32 1 #endif -#if SPH_64 && (SPH_SMALL_FOOTPRINT_BLAKE || !SPH_64_TRUE) +#if defined SPH_64 && (defined SPH_SMALL_FOOTPRINT_BLAKE || !defined SPH_64_TRUE) #define SPH_COMPACT_BLAKE_64 1 #endif @@ -88,7 +88,7 @@ static const sph_u64 IV512[8] = { #endif -#if SPH_COMPACT_BLAKE_32 || SPH_COMPACT_BLAKE_64 +#if defined SPH_COMPACT_BLAKE_32 || defined SPH_COMPACT_BLAKE_64 static const unsigned sigma[16][16] = { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, @@ -318,7 +318,7 @@ static const unsigned sigma[16][16] = { #define CSE SPH_C32(0x3F84D5B5) #define CSF SPH_C32(0xB5470917) -#if SPH_COMPACT_BLAKE_32 +#if defined SPH_COMPACT_BLAKE_32 static const sph_u32 CS[16] = { SPH_C32(0x243F6A88), SPH_C32(0x85A308D3), @@ -356,7 +356,7 @@ static const sph_u32 CS[16] = { #define CBE SPH_C64(0x0801F2E2858EFC16) #define CBF SPH_C64(0x636920D871574E69) -#if SPH_COMPACT_BLAKE_64 +#if defined SPH_COMPACT_BLAKE_64 static const sph_u64 CB[16] = { SPH_C64(0x243F6A8885A308D3), SPH_C64(0x13198A2E03707344), @@ -384,7 +384,7 @@ static const sph_u64 CB[16] = { b = SPH_ROTR32(b ^ c, 7); \ } while (0) -#if SPH_COMPACT_BLAKE_32 +#if defined SPH_COMPACT_BLAKE_32 #define ROUND_S(r) do { \ GS(M[sigma[r][0x0]], M[sigma[r][0x1]], \ @@ -433,7 +433,7 @@ static const sph_u64 CB[16] = { b = SPH_ROTR64(b ^ c, 11); \ } while (0) -#if SPH_COMPACT_BLAKE_64 +#if defined SPH_COMPACT_BLAKE_64 #define ROUND_B(r) do { \ GB(M[sigma[r][0x0]], M[sigma[r][0x1]], \ @@ -509,7 +509,7 @@ static const sph_u64 CB[16] = { (state)->T1 = T1; \ } while (0) -#if SPH_COMPACT_BLAKE_32 +#if defined SPH_COMPACT_BLAKE_32 #define COMPRESS32 do { \ sph_u32 M[16]; \ @@ -665,7 +665,7 @@ static const sph_u64 CB[16] = { (state)->T1 = T1; \ } while (0) -#if SPH_COMPACT_BLAKE_64 +#if defined SPH_COMPACT_BLAKE_64 #define COMPRESS64 do { \ sph_u64 M[16]; \ diff --git a/src/crypto/Lyra2Z/sph_types.h b/src/crypto/Lyra2Z/sph_types.h index 7295b0b370..7e9bef9621 100644 --- a/src/crypto/Lyra2Z/sph_types.h +++ b/src/crypto/Lyra2Z/sph_types.h @@ -833,7 +833,7 @@ typedef int32_t sph_s32; typedef uint_fast32_t sph_u32; typedef int_fast32_t sph_s32; #endif -#if !SPH_NO_64 +#if !defined(SPH_NO_64) #ifdef UINT64_MAX typedef uint64_t sph_u64; typedef int64_t sph_s64; @@ -844,7 +844,7 @@ typedef int_fast64_t sph_s64; #endif #define SPH_C32(x) ((sph_u32)(x)) -#if !SPH_NO_64 +#if !defined(SPH_NO_64) #define SPH_C64(x) ((sph_u64)(x)) #define SPH_64 1 #endif @@ -1060,14 +1060,16 @@ typedef long long sph_s64; /* * MIPS, little-endian. */ -#elif MIPSEL || _MIPSEL || __MIPSEL || __MIPSEL__ +#elif (defined(MIPSEL) && MIPSEL) || (defined(_MIPSEL) && _MIPSEL) \ + || (defined(__MIPSEL) && __MIPSEL) || (defined(__MIPSEL__) && __MIPSEL__) #define SPH_DETECT_LITTLE_ENDIAN 1 /* * MIPS, big-endian. */ -#elif MIPSEB || _MIPSEB || __MIPSEB || __MIPSEB__ +#elif (defined(MIPSEB) && MIPSEB) || (defined(_MIPSEB) && _MIPSEB) \ + || (defined(__MIPSEB) && __MIPSEB) || (defined(__MIPSEB__) && __MIPSEB__) #define SPH_DETECT_BIG_ENDIAN 1 @@ -1166,10 +1168,10 @@ typedef long long sph_s64; #define SPH_PPC64_GCC SPH_DETECT_PPC64_GCC #endif -#if SPH_LITTLE_ENDIAN && !defined SPH_LITTLE_FAST +#if defined SPH_LITTLE_ENDIAN && !defined SPH_LITTLE_FAST #define SPH_LITTLE_FAST 1 #endif -#if SPH_BIG_ENDIAN && !defined SPH_BIG_FAST +#if defined SPH_BIG_ENDIAN && !defined SPH_BIG_FAST #define SPH_BIG_FAST 1 #endif @@ -1177,7 +1179,7 @@ typedef long long sph_s64; #error SPH_UPTR defined, but endianness is not known. #endif -#if SPH_I386_GCC && !SPH_NO_ASM +#if defined SPH_I386_GCC && !defined SPH_NO_ASM /* * On x86 32-bit, with gcc, we use the bswapl opcode to byte-swap 32-bit @@ -1202,7 +1204,7 @@ sph_bswap64(sph_u64 x) #endif -#elif SPH_AMD64_GCC && !SPH_NO_ASM +#elif defined(SPH_AMD64_GCC) && !defined(SPH_NO_ASM) /* * On x86 64-bit, with gcc, we use the bswapl opcode to byte-swap 32-bit @@ -1294,7 +1296,7 @@ sph_bswap64(sph_u64 x) #endif -#if SPH_SPARCV9_GCC && !SPH_NO_ASM +#if defined(SPH_SPARCV9_GCC) && !defined(SPH_NO_ASM) /* * On UltraSPARC systems, native ordering is big-endian, but it is @@ -1403,9 +1405,9 @@ sph_enc32be(void *dst, sph_u32 val) static SPH_INLINE void sph_enc32be_aligned(void *dst, sph_u32 val) { -#if SPH_LITTLE_ENDIAN +#if defined(SPH_LITTLE_ENDIAN) && SPH_LITTLE_ENDIAN *(sph_u32 *)dst = sph_bswap32(val); -#elif SPH_BIG_ENDIAN +#elif defined(SPH_BIG_ENDIAN) && SPH_BIG_ENDIAN *(sph_u32 *)dst = val; #else ((unsigned char *)dst)[0] = (val >> 24); @@ -1463,9 +1465,9 @@ sph_dec32be(const void *src) static SPH_INLINE sph_u32 sph_dec32be_aligned(const void *src) { -#if SPH_LITTLE_ENDIAN +#if defined(SPH_LITTLE_ENDIAN) && SPH_LITTLE_ENDIAN return sph_bswap32(*(const sph_u32 *)src); -#elif SPH_BIG_ENDIAN +#elif defined(SPH_BIG_ENDIAN) && SPH_BIG_ENDIAN return *(const sph_u32 *)src; #else return ((sph_u32)(((const unsigned char *)src)[0]) << 24) @@ -1485,8 +1487,8 @@ static SPH_INLINE void sph_enc32le(void *dst, sph_u32 val) { #if defined SPH_UPTR -#if SPH_UNALIGNED -#if SPH_BIG_ENDIAN +#if defined SPH_UNALIGNED +#if defined SPH_BIG_ENDIAN val = sph_bswap32(val); #endif *(sph_u32 *)dst = val; @@ -1521,9 +1523,9 @@ sph_enc32le(void *dst, sph_u32 val) static SPH_INLINE void sph_enc32le_aligned(void *dst, sph_u32 val) { -#if SPH_LITTLE_ENDIAN +#if defined(SPH_LITTLE_ENDIAN) && SPH_LITTLE_ENDIAN *(sph_u32 *)dst = val; -#elif SPH_BIG_ENDIAN +#elif defined(SPH_BIG_ENDIAN) && SPH_BIG_ENDIAN *(sph_u32 *)dst = sph_bswap32(val); #else ((unsigned char *)dst)[0] = val; @@ -1543,8 +1545,8 @@ static SPH_INLINE sph_u32 sph_dec32le(const void *src) { #if defined SPH_UPTR -#if SPH_UNALIGNED -#if SPH_BIG_ENDIAN +#if defined SPH_UNALIGNED +#if defined SPH_BIG_ENDIAN return sph_bswap32(*(const sph_u32 *)src); #else return *(const sph_u32 *)src; @@ -1614,9 +1616,9 @@ sph_dec32le(const void *src) static SPH_INLINE sph_u32 sph_dec32le_aligned(const void *src) { -#if SPH_LITTLE_ENDIAN +#if defined(SPH_LITTLE_ENDIAN) && SPH_LITTLE_ENDIAN return *(const sph_u32 *)src; -#elif SPH_BIG_ENDIAN +#elif defined(SPH_BIG_ENDIAN) && SPH_BIG_ENDIAN #if SPH_SPARCV9_GCC && !SPH_NO_ASM sph_u32 tmp; @@ -1698,9 +1700,9 @@ sph_enc64be(void *dst, sph_u64 val) static SPH_INLINE void sph_enc64be_aligned(void *dst, sph_u64 val) { -#if SPH_LITTLE_ENDIAN +#if defined(SPH_LITTLE_ENDIAN) && SPH_LITTLE_ENDIAN *(sph_u64 *)dst = sph_bswap64(val); -#elif SPH_BIG_ENDIAN +#elif defined(SPH_BIG_ENDIAN) && SPH_BIG_ENDIAN *(sph_u64 *)dst = val; #else ((unsigned char *)dst)[0] = (val >> 56); @@ -1770,9 +1772,9 @@ sph_dec64be(const void *src) static SPH_INLINE sph_u64 sph_dec64be_aligned(const void *src) { -#if SPH_LITTLE_ENDIAN +#if defined(SPH_LITTLE_ENDIAN) && SPH_LITTLE_ENDIAN return sph_bswap64(*(const sph_u64 *)src); -#elif SPH_BIG_ENDIAN +#elif defined(SPH_BIG_ENDIAN) && SPH_BIG_ENDIAN return *(const sph_u64 *)src; #else return ((sph_u64)(((const unsigned char *)src)[0]) << 56) @@ -1796,8 +1798,8 @@ static SPH_INLINE void sph_enc64le(void *dst, sph_u64 val) { #if defined SPH_UPTR -#if SPH_UNALIGNED -#if SPH_BIG_ENDIAN +#if defined SPH_UNALIGNED +#if defined SPH_BIG_ENDIAN val = sph_bswap64(val); #endif *(sph_u64 *)dst = val; @@ -1840,9 +1842,9 @@ sph_enc64le(void *dst, sph_u64 val) static SPH_INLINE void sph_enc64le_aligned(void *dst, sph_u64 val) { -#if SPH_LITTLE_ENDIAN +#if defined(SPH_LITTLE_ENDIAN) && SPH_LITTLE_ENDIAN *(sph_u64 *)dst = val; -#elif SPH_BIG_ENDIAN +#elif defined(SPH_BIG_ENDIAN) && SPH_BIG_ENDIAN *(sph_u64 *)dst = sph_bswap64(val); #else ((unsigned char *)dst)[0] = val; @@ -1866,8 +1868,8 @@ static SPH_INLINE sph_u64 sph_dec64le(const void *src) { #if defined SPH_UPTR -#if SPH_UNALIGNED -#if SPH_BIG_ENDIAN +#if defined SPH_UNALIGNED +#if defined SPH_BIG_ENDIAN return sph_bswap64(*(const sph_u64 *)src); #else return *(const sph_u64 *)src; @@ -1934,9 +1936,9 @@ sph_dec64le(const void *src) static SPH_INLINE sph_u64 sph_dec64le_aligned(const void *src) { -#if SPH_LITTLE_ENDIAN +#if defined(SPH_LITTLE_ENDIAN) && SPH_LITTLE_ENDIAN return *(const sph_u64 *)src; -#elif SPH_BIG_ENDIAN +#elif defined(SPH_BIG_ENDIAN) && SPH_BIG_ENDIAN #if SPH_SPARCV9_GCC_64 && !SPH_NO_ASM sph_u64 tmp; diff --git a/src/crypto/MerkleTreeProof/argon2.h b/src/crypto/MerkleTreeProof/argon2.h index fc8682c2db..1b471f6bbf 100644 --- a/src/crypto/MerkleTreeProof/argon2.h +++ b/src/crypto/MerkleTreeProof/argon2.h @@ -30,7 +30,7 @@ extern "C" { #ifdef A2_VISCTL #define ARGON2_PUBLIC __attribute__((visibility("default"))) #define ARGON2_LOCAL __attribute__ ((visibility ("hidden"))) -#elif _MSC_VER +#elif defined(_MSC_VER) #define ARGON2_PUBLIC __declspec(dllexport) #define ARGON2_LOCAL #else diff --git a/src/crypto/MerkleTreeProof/blake2/blake2-impl.h b/src/crypto/MerkleTreeProof/blake2/blake2-impl.h index efcb88ff5e..6f8ba32280 100644 --- a/src/crypto/MerkleTreeProof/blake2/blake2-impl.h +++ b/src/crypto/MerkleTreeProof/blake2/blake2-impl.h @@ -21,6 +21,9 @@ #include #include +#include "../core.h" + + #if defined(_MSC_VER) #define BLAKE2_INLINE __inline #elif defined(__GNUC__) || defined(__clang__) @@ -171,6 +174,4 @@ static BLAKE2_INLINE uint64_t rotr64(const uint64_t w, const unsigned c) { return (w >> c) | (w << (64 - c)); } -void clear_internal_memory(void *v, size_t n); - #endif diff --git a/src/crypto/MerkleTreeProof/crypto/common.h b/src/crypto/MerkleTreeProof/crypto/common.h index 5e1482c99e..030bc26589 100644 --- a/src/crypto/MerkleTreeProof/crypto/common.h +++ b/src/crypto/MerkleTreeProof/crypto/common.h @@ -32,7 +32,7 @@ #define le64toh(x) OSSwapLittleToHostInt64(x) #else -#include +#include #endif uint16_t static inline ReadLE16(const unsigned char* ptr) diff --git a/src/crypto/MerkleTreeProof/merkle-tree.cpp b/src/crypto/MerkleTreeProof/merkle-tree.cpp index 79cf0d5b1b..ac149d065c 100644 --- a/src/crypto/MerkleTreeProof/merkle-tree.cpp +++ b/src/crypto/MerkleTreeProof/merkle-tree.cpp @@ -90,7 +90,7 @@ MerkleTree::Buffer MerkleTree::merkleRoot(const Elements& elements, MerkleTree::Elements MerkleTree::getProof(const Buffer& element) const { bool found = false; - size_t index; + size_t index = 0; for (size_t i = 0; (i < elements_.size()) && !found; ++i) { if (elements_[i] == element) { found = true; diff --git a/src/crypto/MerkleTreeProof/mtp.cpp b/src/crypto/MerkleTreeProof/mtp.cpp index fb66809fb9..7ea58142ab 100644 --- a/src/crypto/MerkleTreeProof/mtp.cpp +++ b/src/crypto/MerkleTreeProof/mtp.cpp @@ -27,9 +27,6 @@ using boost::numeric::bad_numeric_cast; using boost::numeric::positive_overflow; using boost::numeric::negative_overflow; -extern int validate_inputs(const argon2_context *context); -extern void clear_internal_memory(void *v, size_t n); - namespace mtp { @@ -280,8 +277,7 @@ bool mtp_verify(const char* input, const uint32_t target, } // step 7 - uint256 y[L + 1]; - std::memset(&y[0], 0, sizeof(y)); + uint256 y[L + 1] = {}; blake2b_state state_y0; blake2b_init(&state_y0, 32); // 256 bit @@ -497,7 +493,7 @@ bool mtp_hash1(const char* input, uint32_t target, uint8_t hash_root_mtp[16], // step 2 MerkleTree::Elements elements; - for (long int i = 0; i < instance.memory_blocks; ++i) { + for (uint32_t i = 0; i < instance.memory_blocks; ++i) { uint8_t digest[MERKLE_TREE_ELEMENT_SIZE_B]; compute_blake2b(instance.memory[i], digest); elements.emplace_back(digest, digest + sizeof(digest)); @@ -521,8 +517,8 @@ bool mtp_hash1(const char* input, uint32_t target, uint8_t hash_root_mtp[16], return false; } - std::memset(&y[0], 0, sizeof(y)); - std::memset(&blocks[0], 0, sizeof(sizeof(block) * L * 2)); + std::fill(std::begin(y), std::end(y), uint256()); + std::fill(std::begin(blocks), std::end(blocks), block()); blake2b_state state; blake2b_init(&state, 32); // 256 bit diff --git a/src/crypto/MerkleTreeProof/mtp.h b/src/crypto/MerkleTreeProof/mtp.h index 4a06fc1b34..d3aa4f4a19 100644 --- a/src/crypto/MerkleTreeProof/mtp.h +++ b/src/crypto/MerkleTreeProof/mtp.h @@ -23,7 +23,7 @@ constexpr int8_t MTP_L = 64; * into the block * * \param blockHeader [in/out] Transaction block which header will be used for calculation - * \param pow_limit [in] Network limit (hash must be less than that) + * \param powLimit [in] Network limit (hash must be less than that) */ uint256 hash(CBlockHeader & blockHeader, uint256 const & powLimit); @@ -34,7 +34,7 @@ uint256 hash(CBlockHeader & blockHeader, uint256 const & powLimit); * that is less than `target`. * \param nonce [in] Nonce to verify * \param blockHeader [in] Transaction block which header will be used for calculation - * \param pow_limit [in] Network limit (hash must be less than that) + * \param powLimit [in] Network limit (hash must be less than that) */ bool verify(uint32_t nonce, CBlockHeader const & blockHeader, uint256 const & powLimit, uint256 *mtpHashValue=nullptr); diff --git a/src/crypto/MerkleTreeProof/ref.c b/src/crypto/MerkleTreeProof/ref.c index aa6ef4b21e..38b02bfdbe 100644 --- a/src/crypto/MerkleTreeProof/ref.c +++ b/src/crypto/MerkleTreeProof/ref.c @@ -15,14 +15,15 @@ * software. If not, they may be obtained at the above URLs. */ -#include -#include -#include -#include + #include + #include + #include + #include -#include "argon2.h" -#include "core.h" -#include "ref.h" + #include "argon2.h" + #include "core.h" + #include "ref.h" + #include "../../compat_layer.h" #include "blake2/blamka-round-ref.h" #include "blake2/blake2-impl.h" @@ -38,7 +39,7 @@ * @param with_xor Whether to XOR into the new block (1) or just overwrite (0) * @pre all block pointers must be valid */ -static void fill_block(const block *prev_block, const block *ref_block, +FIRO_UNUSED static void fill_block(const block *prev_block, const block *ref_block, block *next_block, int with_xor) { block blockR, block_tmp; unsigned i; @@ -82,7 +83,7 @@ static void fill_block(const block *prev_block, const block *ref_block, xor_block(next_block, &blockR); } -static void next_addresses(block *address_block, block *input_block, +FIRO_UNUSED static void next_addresses(block *address_block, block *input_block, const block *zero_block) { input_block->v[6]++; fill_block(zero_block, input_block, address_block, 0); @@ -94,7 +95,8 @@ void fill_segment_mtp(const argon2_instance_t *instance, argon2_position_t position) { block *ref_block = NULL, *curr_block = NULL; - block address_block, input_block, zero_block; + FIRO_UNUSED block address_block; + block input_block, zero_block; uint64_t pseudo_rand, ref_index, ref_lane; uint32_t prev_offset, curr_offset; uint32_t starting_index; diff --git a/src/crypto/common.h b/src/crypto/common.h index bcca3d30ea..244de556f0 100644 --- a/src/crypto/common.h +++ b/src/crypto/common.h @@ -6,7 +6,7 @@ #define BITCOIN_CRYPTO_COMMON_H #if defined(HAVE_CONFIG_H) -#include "bitcoin-config.h" +#include "../config/bitcoin-config.h" #endif #include diff --git a/src/crypto/progpow/CMakeLists.txt b/src/crypto/progpow/CMakeLists.txt new file mode 100644 index 0000000000..91cc731b56 --- /dev/null +++ b/src/crypto/progpow/CMakeLists.txt @@ -0,0 +1,29 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +add_library(keccak STATIC EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/lib/keccak/keccak.c + ${CMAKE_CURRENT_SOURCE_DIR}/lib/keccak/keccakf800.c + ${CMAKE_CURRENT_SOURCE_DIR}/lib/keccak/keccakf1600.c +) + +add_library(ethash STATIC EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/lib/ethash/ethash.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/lib/ethash/managed.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/lib/ethash/primes.c + ${CMAKE_CURRENT_SOURCE_DIR}/lib/ethash/progpow.cpp +) + +target_link_libraries(ethash + PRIVATE + core_interface + ${Boost_LIBRARIES} + PUBLIC + keccak +) + +target_include_directories(ethash + PUBLIC + ${Boost_INCLUDE_DIR} +) \ No newline at end of file diff --git a/src/crypto/progpow/lib/ethash/endianness.hpp b/src/crypto/progpow/lib/ethash/endianness.hpp index 3b580d751f..e5c6c1fb5f 100644 --- a/src/crypto/progpow/lib/ethash/endianness.hpp +++ b/src/crypto/progpow/lib/ethash/endianness.hpp @@ -15,7 +15,7 @@ #include -#if _WIN32 +#if defined(_WIN32) #include @@ -27,13 +27,31 @@ #define __BIG_ENDIAN 4321 #define __BYTE_ORDER __LITTLE_ENDIAN -#elif __APPLE__ +#elif defined(__APPLE__) #include #define bswap32 __builtin_bswap32 #define bswap64 __builtin_bswap64 +#ifndef __BYTE_ORDER +#ifdef BYTE_ORDER +#define __BYTE_ORDER BYTE_ORDER +#endif +#endif + +#ifndef __LITTLE_ENDIAN +#ifdef LITTLE_ENDIAN +#define __LITTLE_ENDIAN LITTLE_ENDIAN +#endif +#endif + +#ifndef __BIG_ENDIAN +#ifdef BIG_ENDIAN +#define __BIG_ENDIAN BIG_ENDIAN +#endif +#endif + #else #include @@ -45,7 +63,7 @@ namespace ethash { -#if __BYTE_ORDER == __LITTLE_ENDIAN +#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN)) && (__BYTE_ORDER == __LITTLE_ENDIAN) struct le { @@ -62,8 +80,7 @@ struct be static uint64_t uint64(uint64_t x) noexcept { return bswap64(x); } }; - -#elif __BYTE_ORDER == __BIG_ENDIAN +#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN)) && (__BYTE_ORDER == __BIG_ENDIAN) struct le { diff --git a/src/crypto/progpow/lib/support/attributes.h b/src/crypto/progpow/lib/support/attributes.h index ec8baad3ae..bb246b3aa9 100644 --- a/src/crypto/progpow/lib/support/attributes.h +++ b/src/crypto/progpow/lib/support/attributes.h @@ -8,16 +8,16 @@ #define CRYPTO_PROGPOW_ATTRIBUTES_H_ /** inline */ -#if _MSC_VER || __STDC_VERSION__ +#if defined(_MSC_VER) || defined(__STDC_VERSION__) #define INLINE inline #else #define INLINE #endif /** [[always_inline]] */ -#if _MSC_VER +#if defined(_MSC_VER) #define ALWAYS_INLINE __forceinline -#elif defined(__has_attribute) && __STDC_VERSION__ +#elif defined(__has_attribute) && defined(__STDC_VERSION__) #if __has_attribute(always_inline) #define ALWAYS_INLINE __attribute__((always_inline)) #endif @@ -27,7 +27,7 @@ #endif /** [[no_sanitize()]] */ -#if __clang__ +#if defined(__clang__) #define NO_SANITIZE(sanitizer) \ __attribute__((no_sanitize(sanitizer))) #else diff --git a/src/cxxtimer.hpp b/src/cxxtimer.hpp index c3f0b72222..3b2830ac9a 100644 --- a/src/cxxtimer.hpp +++ b/src/cxxtimer.hpp @@ -107,7 +107,7 @@ class Timer { /** * Return the elapsed time. * - * @param duration_t + * @tparam duration_t * The duration type used to return the time elapsed. If not * specified, it returns the time as represented by * std::chrono::milliseconds. diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp index 94ebedeb72..88aa72ef52 100644 --- a/src/dbwrapper.cpp +++ b/src/dbwrapper.cpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include static leveldb::Options GetOptions(size_t nCacheSize) diff --git a/src/dbwrapper.h b/src/dbwrapper.h index 3e923064f4..56f6ed37a2 100644 --- a/src/dbwrapper.h +++ b/src/dbwrapper.h @@ -582,7 +582,7 @@ class CDBTransaction { struct ValueHolderImpl : ValueHolder { ValueHolderImpl(const V &_value, size_t _memoryUsage) : ValueHolder(_memoryUsage), value(_value) {} - virtual void Write(const CDataStream& ssKey, CommitTarget &commitTarget) { + virtual void Write(const CDataStream& ssKey, CommitTarget &commitTarget) override { // we're moving the value instead of copying it. This means that Write() can only be called once per // ValueHolderImpl instance. Commit() clears the write maps, so this ok. commitTarget.Write(ssKey, std::move(value)); diff --git a/src/evo/cbtx.cpp b/src/evo/cbtx.cpp index 3df70ef1d8..b17b84db9e 100644 --- a/src/evo/cbtx.cpp +++ b/src/evo/cbtx.cpp @@ -200,12 +200,12 @@ bool CalcCbTxMerkleRootQuorums(const CBlock& block, const CBlockIndex* pindexPre auto qcHash = ::SerializeHash(qc.commitment); const auto& params = Params().GetConsensus().llmqs.at((Consensus::LLMQType)qc.commitment.llmqType); auto& v = qcHashes[params.type]; - if (v.size() == params.signingActiveQuorumCount) { + if (cmp::equal(v.size(), params.signingActiveQuorumCount)) { v.pop_back(); } v.emplace_back(qcHash); hashCount++; - assert(v.size() <= params.signingActiveQuorumCount); + assert(cmp::less_equal(v.size(), params.signingActiveQuorumCount)); } } diff --git a/src/evo/deterministicmns.cpp b/src/evo/deterministicmns.cpp index c9d9e519b3..4fe69871dc 100644 --- a/src/evo/deterministicmns.cpp +++ b/src/evo/deterministicmns.cpp @@ -235,7 +235,7 @@ CDeterministicMNCPtr CDeterministicMNList::GetMNPayee() const std::vector CDeterministicMNList::GetProjectedMNPayees(int nCount) const { - if (nCount > GetValidMNsCount()) { + if (cmp::greater(nCount, GetValidMNsCount())) { nCount = GetValidMNsCount(); } diff --git a/src/evo/deterministicmns.h b/src/evo/deterministicmns.h index 767169e063..7801fe8d43 100644 --- a/src/evo/deterministicmns.h +++ b/src/evo/deterministicmns.h @@ -415,18 +415,18 @@ class CDeterministicMNList CDeterministicMNCPtr GetMNPayee() const; /** - * Calculates the projected MN payees for the next *count* blocks. The result is not guaranteed to be correct + * Calculates the projected MN payees for the next *nCount* blocks. The result is not guaranteed to be correct * as PoSe banning might occur later - * @param count - * @return + * @param nCount number of future blocks to project payees for (will be clamped to valid MN count) + * @return projected payees sorted by payment priority */ std::vector GetProjectedMNPayees(int nCount) const; /** * Calculate a quorum based on the modifier. The resulting list is deterministically sorted by score - * @param maxSize - * @param modifier - * @return + * @param maxSize maximum number of masternodes to include in the quorum + * @param modifier hash modifier used for score calculation + * @return std::vector selected quorum members, sorted by descending score */ std::vector CalculateQuorum(size_t maxSize, const uint256& modifier) const; std::vector> CalculateScores(const uint256& modifier) const; @@ -434,7 +434,7 @@ class CDeterministicMNList /** * Calculates the maximum penalty which is allowed at the height of this MN list. It is dynamic and might change * for every block. - * @return + * @return maximum penalty */ int CalcMaxPoSePenalty() const; @@ -443,8 +443,8 @@ class CDeterministicMNList * value later passed to PoSePunish. The percentage should be high enough to take per-block penalty decreasing for MNs * into account. This means, if you want to accept 2 failures per payment cycle, you should choose a percentage that * is higher then 50%, e.g. 66%. - * @param percent - * @return + * @param percent percentage of maximum penalty to calculate (1-100) + * @return computed penalty value */ int CalcPenalty(int percent) const; @@ -452,15 +452,16 @@ class CDeterministicMNList * Punishes a MN for misbehavior. If the resulting penalty score of the MN reaches the max penalty, it is banned. * Penalty scores are only increased when the MN is not already banned, which means that after banning the penalty * might appear lower then the current max penalty, while the MN is still banned. - * @param proTxHash - * @param penalty + * @param proTxHash the unique hash identifying the masternode to punish + * @param penalty positive penalty value to add to current PoSe score + * @param debugLogs when true, logs punishment details and ban events */ void PoSePunish(const uint256& proTxHash, int penalty, bool debugLogs); /** * Decrease penalty score of MN by 1. * Only allowed on non-banned MNs. - * @param proTxHash + * @param proTxHash The hash to uniquely identifying the masternode */ void PoSeDecrease(const uint256& proTxHash); diff --git a/src/fixed.h b/src/fixed.h index 36a766206b..64710c81b9 100644 --- a/src/fixed.h +++ b/src/fixed.h @@ -57,6 +57,7 @@ namespace detail { static const bool is_specialized = true; static const std::size_t size = 128; typedef __int128 value_type; + typedef unsigned __int128 unsigned_type; typedef type_from_size<128> next_size; }; #endif @@ -67,6 +68,7 @@ namespace detail { static const bool is_specialized = true; static const std::size_t size = 64; typedef int64_t value_type; + typedef uint64_t unsigned_type; typedef type_from_size<128> next_size; }; @@ -75,6 +77,7 @@ namespace detail { static const bool is_specialized = true; static const std::size_t size = 32; typedef int32_t value_type; + typedef uint32_t unsigned_type; typedef type_from_size<64> next_size; }; @@ -83,6 +86,7 @@ namespace detail { static const bool is_specialized = true; static const std::size_t size = 16; typedef int16_t value_type; + typedef uint16_t unsigned_type; typedef type_from_size<32> next_size; }; @@ -91,6 +95,7 @@ namespace detail { static const bool is_specialized = true; static const std::size_t size = 8; typedef int8_t value_type; + typedef uint8_t unsigned_type; typedef type_from_size<16> next_size; }; @@ -250,7 +255,7 @@ class Fixed : boost::operators >, boost::shiftable > { public: static const std::size_t base_size = base_type_info::size; - static const base_type fractional_mask = ~((~base_type(0)) << fractional_bits); + static const base_type fractional_mask = ~(static_cast(~base_type(0)) << fractional_bits); static const base_type integer_mask = ~fractional_mask; public: @@ -435,6 +440,11 @@ const std::size_t Fixed::integer_bits; template const std::size_t Fixed::total_bits; +template +const typename numeric::Fixed::base_type numeric::Fixed::fractional_mask; + +template +const typename numeric::Fixed::base_type numeric::Fixed::integer_mask; } #endif diff --git a/src/hash.cpp b/src/hash.cpp index b361c90d16..88fe2c1575 100644 --- a/src/hash.cpp +++ b/src/hash.cpp @@ -7,6 +7,8 @@ #include "crypto/hmac_sha512.h" #include "pubkey.h" +#include "compat_layer.h" + inline uint32_t ROTL32(uint32_t x, int8_t r) { @@ -49,8 +51,10 @@ unsigned int MurmurHash3(unsigned int nHashSeed, const std::vector pMint, bool fVerbose) { @@ -32,9 +30,6 @@ bool SortSmallest(const std::pair& a, const std::pair>& listMints) { @@ -47,8 +42,6 @@ void CMintPool::List(std::list>& listMints) /** * clear the current mintpool - * - * @return void */ void CMintPool::Reset() { diff --git a/src/hdmint/test/hdmint_tests.cpp b/src/hdmint/test/hdmint_tests.cpp index 02c37239c1..15f2e3c71a 100644 --- a/src/hdmint/test/hdmint_tests.cpp +++ b/src/hdmint/test/hdmint_tests.cpp @@ -46,7 +46,7 @@ BOOST_AUTO_TEST_CASE(deterministic) { vector denominationsForTx; vector vtxid; - int previousHeight; + FIRO_UNUSED int previousHeight; CBlock b; CWalletTx wtx; @@ -66,7 +66,7 @@ BOOST_AUTO_TEST_CASE(deterministic) int mempoolCount = 0; - for(int i = 0; i < denominations.size() - 1; i++) + for(int i = 0; cmp::less(i, denominations.size() - 1); i++) { vDMintsBuilder.clear(); denominationsForTx.clear(); @@ -91,7 +91,7 @@ BOOST_AUTO_TEST_CASE(deterministic) BOOST_CHECK_MESSAGE(stringError == "", "Mint Failed"); // Verify mint tx get added in the mempool - BOOST_CHECK_MESSAGE(mempool.size() == ++mempoolCount, "Mint tx was not added to mempool"); + BOOST_CHECK_MESSAGE(cmp::equal(mempool.size(), ++mempoolCount), "Mint tx was not added to mempool"); // Verify correct mint count BOOST_CHECK(mintCount == pwalletMain->zwallet->GetCount()); @@ -111,7 +111,7 @@ BOOST_AUTO_TEST_CASE(deterministic) sigmaState->Reset(); pwalletMain->ZapSigmaMints(); - for(int i = 0; i < denominations.size() - 1; i++) + for(int i = 0; cmp::less(i, denominations.size() - 1); i++) { vDMintsBuilder.clear(); denominationsForTx.clear(); @@ -145,7 +145,7 @@ BOOST_AUTO_TEST_CASE(deterministic) BOOST_CHECK(vDMints.size() == vDMintsRegenerated.size()); - for(int i=0; i denominationsForTx; vector vtxid; - int previousHeight; + FIRO_UNUSED int previousHeight; CBlock b; CWalletTx wtx; const int TOTAL_MINTS = 5; const int INITIAL_MINTS = TOTAL_MINTS-1; - sigma::CSigmaState *sigmaState = sigma::CSigmaState::GetState(); + FIRO_UNUSED sigma::CSigmaState *sigmaState = sigma::CSigmaState::GetState(); pwalletMain->SetBroadcastTransactions(true); @@ -245,7 +245,7 @@ BOOST_AUTO_TEST_CASE(blockchain_restore) { vector denominationsForTx; vector vtxid; - int previousHeight; + FIRO_UNUSED int previousHeight; CBlock b; CWalletTx wtx; @@ -261,7 +261,7 @@ BOOST_AUTO_TEST_CASE(blockchain_restore) vector vDMintsBuilder; const auto& sigmaParams = sigma::Params::get_default(); - for(int i = 0; i < denominations.size() - 1; i++) + for(int i = 0; cmp::less(i, denominations.size() - 1); i++) { vDMintsBuilder.clear(); denominationsForTx.clear(); @@ -331,9 +331,9 @@ BOOST_AUTO_TEST_CASE(blockchain_restore) BOOST_CHECK(vDMints.size() == vDMintsRegenerated.size()); - for(int i=0; i& setMempoo * * @param mintPoolEntries the set of mint pool entries to update * @param updatedMeta the CMintMeta objects to update - * @return void */ void CHDMintTracker::UpdateFromBlock(const std::list>& mintPoolEntries, const std::vector& updatedMeta){ if (mintPoolEntries.size() > 0) { @@ -811,7 +805,6 @@ void CHDMintTracker::UpdateFromBlock(const std::list& mints){ CWalletDB walletdb(strWalletFile); @@ -880,7 +873,6 @@ void CHDMintTracker::UpdateMintStateFromBlock(const std::vector& pubCoins){ CWalletDB walletdb(strWalletFile); @@ -1039,7 +1030,6 @@ void CHDMintTracker::UpdateLelantusMintStateFromMempool(const std::vector& spentSerials) { CWalletDB walletdb(strWalletFile); @@ -1143,7 +1133,6 @@ std::list CHDMintTracker::MintsAsLelantusEntries(bool fUnusedOnl /** * Sets up the in memory mint objects. * - * @param fUnusedOnly process unused mints only * @param fUnusedOnly process mature (ie. spendable due to sufficient confirmations) mints only * @param fUpdateStatus If the mints should be updated * @param fLoad If the mints should be loaded from database @@ -1286,8 +1275,6 @@ std::set CHDMintTracker::GetMempoolTxids(){ /** * map of serial hashes -> CMintMeta objects - * - * @return void */ void CHDMintTracker::Clear() { diff --git a/src/hdmint/wallet.cpp b/src/hdmint/wallet.cpp index 829dcc3448..d19ff10a2a 100644 --- a/src/hdmint/wallet.cpp +++ b/src/hdmint/wallet.cpp @@ -26,7 +26,6 @@ * Doesn't set encrypted values if the wallet is locked. * * @param strWalletFile wallet file string - * @return CHDMintWallet object */ CHDMintWallet::CHDMintWallet(const std::string& strWalletFile, bool resetCount) : strWalletFile(strWalletFile), tracker(strWalletFile) { @@ -785,7 +784,7 @@ CKeyID CHDMintWallet::GetMintSeedID(CWalletDB& walletdb, int32_t nCount){ * If seedId is passed, use that seedId and ignore key generation section. * Following that, get the key, and use it to generate the mint seed according to the specification. * - * @param mintSeed + * @param mintSeed mint seed * @param nCount (optional) count in the HD Chain of the key to use for mint generation. * @param seedId (optional) seedId of the key to use for mint generation. * @return success @@ -820,8 +819,8 @@ bool CHDMintWallet::CreateMintSeed(CWalletDB& walletdb, uint512& mintSeed, const } // HMAC-SHA512(SHA256(count),key) - unsigned char countHash[CSHA256().OUTPUT_SIZE]; - std::vector result(CSHA512().OUTPUT_SIZE); + unsigned char countHash[CSHA256::OUTPUT_SIZE]; + std::vector result(CSHA512::OUTPUT_SIZE); std::string nCountStr = std::to_string(nCount); CSHA256().Write(reinterpret_cast(nCountStr.c_str()), nCountStr.size()).Finalize(countHash); @@ -846,8 +845,6 @@ int32_t CHDMintWallet::GetCount() /** * Reset in-memory count to that of the database value. * Necessary during transaction creation when fee calcuation causes the creation to reset. - * - * @return void */ void CHDMintWallet::ResetCount(CWalletDB& walletdb) { @@ -858,7 +855,6 @@ void CHDMintWallet::ResetCount(CWalletDB& walletdb) * Set in-memory count to parameter passed * * @param nCount count to be set - * @return void */ void CHDMintWallet::SetCount(int32_t nCount) { @@ -867,8 +863,6 @@ void CHDMintWallet::SetCount(int32_t nCount) /** * Increment in-memory count of the next mint to use. - * - * @return void */ void CHDMintWallet::UpdateCountLocal() { @@ -879,8 +873,6 @@ void CHDMintWallet::UpdateCountLocal() /** * Increment database count of the next mint to use. * calls GenerateMintPool, which will run if we have exhausted the mintpool. - * - * @return void */ void CHDMintWallet::UpdateCountDB(CWalletDB& walletdb) { diff --git a/src/httprpc.cpp b/src/httprpc.cpp index 3a4510a21f..f58fb3088b 100644 --- a/src/httprpc.cpp +++ b/src/httprpc.cpp @@ -52,11 +52,11 @@ class HTTPRPCTimerInterface : public RPCTimerInterface HTTPRPCTimerInterface(struct event_base* _base) : base(_base) { } - const char* Name() + const char* Name() override { return "HTTP"; } - RPCTimerBase* NewTimer(boost::function& func, int64_t millis) + RPCTimerBase* NewTimer(boost::function& func, int64_t millis) override { return new HTTPRPCTimer(base, func, millis); } diff --git a/src/httpserver.cpp b/src/httpserver.cpp index f65a30c267..b8659ea123 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -46,7 +46,7 @@ class HTTPWorkItem : public HTTPClosure req(std::move(_req)), path(_path), func(_func) { } - void operator()() + void operator()() override { func(req.get(), path); } diff --git a/src/immer/memory_policy.hpp b/src/immer/memory_policy.hpp index d8556b9432..9795663ef1 100644 --- a/src/immer/memory_policy.hpp +++ b/src/immer/memory_policy.hpp @@ -111,10 +111,10 @@ struct memory_policy * @ref free_list_heap_policy. If `IMMER_NO_FREE_LIST` is defined to `1` * then it just uses the standard heap. */ -#if IMMER_NO_FREE_LIST +#if defined(IMMER_NO_FREE_LIST) using default_heap_policy = heap_policy>; #else -#if IMMER_NO_THREAD_SAFETY +#if defined(IMMER_NO_THREAD_SAFETY) using default_heap_policy = unsafe_free_list_heap_policy; #else using default_heap_policy = free_list_heap_policy; @@ -124,7 +124,7 @@ using default_heap_policy = free_list_heap_policy; /*! * By default we use thread safe reference counting. */ -#if IMMER_NO_THREAD_SAFETY +#if defined(IMMER_NO_THREAD_SAFETY) using default_refcount_policy = unsafe_refcount_policy; using default_lock_policy = no_lock_policy; #else diff --git a/src/init.cpp b/src/init.cpp index 4af82f4fc5..b088ad396a 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -415,7 +415,7 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-conf=", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME)); if (mode == HMM_BITCOIND) { -#if HAVE_DECL_DAEMON +#if defined(HAVE_DECL_DAEMON) && HAVE_DECL_DAEMON strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands")); #endif } @@ -1098,7 +1098,7 @@ bool AppInitBasicSetup() _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif -#if _MSC_VER >= 1400 +#if defined(_MSC_VER) && _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif @@ -1112,7 +1112,8 @@ bool AppInitBasicSetup() #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); - PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); + PSETPROCDEPPOL setProcDEPPol = reinterpret_cast( + reinterpret_cast(GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"))); if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); #endif @@ -1483,7 +1484,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler) return InitError(_("Unable to start HTTP server. See debug log for details.")); } - int64_t nStart; + int64_t nStart = 0; // ********************************************************* Step 5: verify wallet database integrity #ifdef ENABLE_WALLET diff --git a/src/keystore.h b/src/keystore.h index d9290722e1..faec0d818b 100644 --- a/src/keystore.h +++ b/src/keystore.h @@ -61,9 +61,9 @@ class CBasicKeyStore : public CKeyStore WatchOnlySet setWatchOnly; public: - bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey); - bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const; - bool HaveKey(const CKeyID &address) const + bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override; + bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const override; + bool HaveKey(const CKeyID &address) const override { bool result; { @@ -72,7 +72,7 @@ class CBasicKeyStore : public CKeyStore } return result; } - void GetKeys(std::set &setAddress) const + void GetKeys(std::set &setAddress) const override { setAddress.clear(); { @@ -85,7 +85,7 @@ class CBasicKeyStore : public CKeyStore } } } - bool GetKey(const CKeyID &address, CKey &keyOut) const + bool GetKey(const CKeyID &address, CKey &keyOut) const override { { LOCK(cs_KeyStore); @@ -98,14 +98,14 @@ class CBasicKeyStore : public CKeyStore } return false; } - virtual bool AddCScript(const CScript& redeemScript); - virtual bool HaveCScript(const CScriptID &hash) const; - virtual bool GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const; + virtual bool AddCScript(const CScript& redeemScript) override; + virtual bool HaveCScript(const CScriptID &hash) const override; + virtual bool GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const override; - virtual bool AddWatchOnly(const CScript &dest); - virtual bool RemoveWatchOnly(const CScript &dest); - virtual bool HaveWatchOnly(const CScript &dest) const; - virtual bool HaveWatchOnly() const; + virtual bool AddWatchOnly(const CScript &dest) override; + virtual bool RemoveWatchOnly(const CScript &dest) override; + virtual bool HaveWatchOnly(const CScript &dest) const override; + virtual bool HaveWatchOnly() const override; }; typedef std::vector > CKeyingMaterial; diff --git a/src/lelantus.cpp b/src/lelantus.cpp index 8d7200d0b5..130a72fa4b 100644 --- a/src/lelantus.cpp +++ b/src/lelantus.cpp @@ -390,7 +390,7 @@ bool CheckLelantusJoinSplitTransaction( "CheckLelantusJoinSplitTransaction: network hasn't yet switched over to lelantus payload data"); } } - const CTxIn &txin = tx.vin[0]; + FIRO_UNUSED const CTxIn &txin = tx.vin[0]; std::unique_ptr joinsplit; try { @@ -1384,7 +1384,7 @@ void CLelantusState::RemoveBlock(CBlockIndex *index) { if (nMintsToForget == 0) continue; - assert(coinGroup.nCoins >= nMintsToForget); + assert(cmp::greater_equal(coinGroup.nCoins, nMintsToForget)); auto isExtended = coins.first > 1; coinGroup.nCoins -= nMintsToForget; diff --git a/src/lelantus.h b/src/lelantus.h index 9d1d35ede0..51cd16de30 100644 --- a/src/lelantus.h +++ b/src/lelantus.h @@ -14,7 +14,7 @@ #include #include "coin_containers.h" -namespace lelantus_mintspend { class lelantus_mintspend_test; } +namespace lelantus_mintspend { struct lelantus_mintspend_test; } namespace lelantus { @@ -299,12 +299,12 @@ friend bool BuildLelantusStateFromIndex(CChain *, std::set &); void CheckSurgeCondition(); - friend class lelantus_mintspend::lelantus_mintspend_test; + friend struct lelantus_mintspend::lelantus_mintspend_test; }; Containers containers; - friend class lelantus_mintspend::lelantus_mintspend_test; + friend struct lelantus_mintspend::lelantus_mintspend_test; }; } // end of namespace lelantus diff --git a/src/liblelantus/challenge_generator_impl.h b/src/liblelantus/challenge_generator_impl.h index 35be9828ae..c584a19a3c 100644 --- a/src/liblelantus/challenge_generator_impl.h +++ b/src/liblelantus/challenge_generator_impl.h @@ -21,35 +21,35 @@ class ChallengeGeneratorImpl : public ChallengeGenerator { scalar_data.resize(32); } - void add(const GroupElement& group_element) { + void add(const GroupElement& group_element) override { group_element.serialize(data.data()); hash.Write(data.data(), data.size()); } - void add(const std::vector& group_elements) { + void add(const std::vector& group_elements) override { addSize(group_elements.size()); for (size_t i = 0; i < group_elements.size(); ++i) { add(group_elements[i]); } } - void add(const Scalar& scalar) { + void add(const Scalar& scalar) override { scalar.serialize(scalar_data.data()); hash.Write(scalar_data.data(), scalar_data.size()); } - void add(const std::vector& scalars) { + void add(const std::vector& scalars) override { addSize(scalars.size()); for (size_t i = 0; i < scalars.size(); ++i) { add(scalars[i]); } } - void add(const std::vector& data_) { + void add(const std::vector& data_) override { hash.Write(data_.data(), data_.size()); } - void get_challenge(Scalar& result_out) { + void get_challenge(Scalar& result_out) override { unsigned char result_data[CSHA256::OUTPUT_SIZE]; do { Hasher temp_hash = hash; diff --git a/src/liblelantus/lelantus_prover.cpp b/src/liblelantus/lelantus_prover.cpp index 3154b51ea6..4450d6fd30 100644 --- a/src/liblelantus/lelantus_prover.cpp +++ b/src/liblelantus/lelantus_prover.cpp @@ -221,7 +221,7 @@ void LelantusProver::generate_sigma_proofs( std::vector Qk; Qk.reserve(N * params->get_sigma_m()); for (std::size_t i = 0; i < N; ++i) { - for (std::size_t j = 0; j < params->get_sigma_m(); ++j) { + for (std::size_t j = 0; cmp::less(j, params->get_sigma_m()); ++j) { Pk_sum += (Pk[i][j] * qk_x_n.pow); Tk_Yk_sum += ((Tk[i][j] + Yk[i][j]) * qk_x_n.pow); qk_x_n.go_next(); diff --git a/src/liblelantus/lelantus_verifier.cpp b/src/liblelantus/lelantus_verifier.cpp index d645cd94b8..5eebc57d7a 100644 --- a/src/liblelantus/lelantus_verifier.cpp +++ b/src/liblelantus/lelantus_verifier.cpp @@ -52,7 +52,7 @@ bool LelantusVerifier::verify( } // max possible number of output coins is 8, - if (Cout.size() > (params->get_bulletproofs_max_m() / 2)) { + if (cmp::greater(Cout.size(), (params->get_bulletproofs_max_m() / 2))) { LogPrintf("Number of output coins are more than allowed."); return false; } diff --git a/src/liblelantus/range_verifier.cpp b/src/liblelantus/range_verifier.cpp index 3624ac89c8..e0cb136047 100644 --- a/src/liblelantus/range_verifier.cpp +++ b/src/liblelantus/range_verifier.cpp @@ -1,6 +1,8 @@ #include "range_verifier.h" #include "challenge_generator_impl.h" +#include "../../compat_layer.h" + // This is based on the 1 Jul 2018 revision of the Bulletproofs preprint: // https://eprint.iacr.org/2017/1066 @@ -62,7 +64,7 @@ bool RangeVerifier::verify(const std::vector >& V, con if (proofs[k].innerProductProof.R_.size() != log_mn) { return false; } - if (RangeProof::int_log2(m*n) != log_mn) { + if (cmp::not_equal(RangeProof::int_log2(m*n), log_mn)) { return false; } diff --git a/src/liblelantus/test/coin_tests.cpp b/src/liblelantus/test/coin_tests.cpp index 46805847b7..6abc99b54d 100644 --- a/src/liblelantus/test/coin_tests.cpp +++ b/src/liblelantus/test/coin_tests.cpp @@ -3,13 +3,15 @@ #include "../../version.h" #include "../lelantus_primitives.h" +#include "lelantus_test_fixture.h" + #include "streams.h" #include namespace lelantus { -BOOST_AUTO_TEST_SUITE(lelantus_coin_tests) +BOOST_FIXTURE_TEST_SUITE(lelantus_coin_tests, lelantus::LelantusTestingSetup) BOOST_AUTO_TEST_CASE(privatecoin) { diff --git a/src/liblelantus/test/lelantus_test.cpp b/src/liblelantus/test/lelantus_test.cpp index cedc520546..35e856987b 100644 --- a/src/liblelantus/test/lelantus_test.cpp +++ b/src/liblelantus/test/lelantus_test.cpp @@ -11,7 +11,7 @@ class ProtocolTests : public LelantusTestingSetup { public: ProtocolTests() - : params(Params::get_default()) + : m_params(Params::get_default()) { } @@ -55,7 +55,7 @@ class ProtocolTests : public LelantusTestingSetup } public: - Params const *params; + Params const *m_params; }; BOOST_FIXTURE_TEST_SUITE(lelantus_protocol_tests, ProtocolTests) @@ -65,7 +65,7 @@ BOOST_AUTO_TEST_CASE(prove_verify) size_t N = 100; uint64_t v1(5); - PrivateCoin input_coin1(params ,v1); + PrivateCoin input_coin1(m_params ,v1); std::vector> Cin = {{input_coin1, 0}}; std::vector indexes = {0}; @@ -75,28 +75,28 @@ BOOST_AUTO_TEST_CASE(prove_verify) Scalar Vin(5); uint64_t Vout(6); - std::vector Cout = {{params, 2}, {params, 1}}; + std::vector Cout = {{m_params, 2}, {m_params, 1}}; uint64_t f(1); LelantusProof proof; SchnorrProof qkSchnorrProof; - LelantusProver prover(params, LELANTUS_TX_VERSION_4_5); + LelantusProver prover(m_params, LELANTUS_TX_VERSION_4_5); prover.proof(anonymity_sets, {}, Vin, Cin, indexes, {}, Vout, Cout, f, proof, qkSchnorrProof); std::vector groupIds; auto Sin = ExtractSerials(anonymity_sets.size(), Cin, groupIds); auto Cout_Public = ExtractPublicCoins(Cout); - lelantus::LelantusVerifier verifier(params, LELANTUS_TX_VERSION_4_5); + lelantus::LelantusVerifier verifier(m_params, LELANTUS_TX_VERSION_4_5); BOOST_CHECK(verifier.verify(anonymity_sets, {}, Sin, {}, groupIds, Vin, Vout, f, Cout_Public, proof, qkSchnorrProof)); } BOOST_AUTO_TEST_CASE(prove_verify_many_coins) { - size_t N = 100; + FIRO_UNUSED size_t N = 100; - PrivateCoin input1(params ,2), input2(params, 2), input3(params, 1); + PrivateCoin input1(m_params ,2), input2(m_params, 2), input3(m_params, 1); std::vector> Cin = { {input1, 0}, {input2, 0}, {input3, 1} }; @@ -110,19 +110,19 @@ BOOST_AUTO_TEST_CASE(prove_verify_many_coins) Scalar Vin(5); uint64_t Vout(6), f(1); - std::vector Cout = {{params, 2}, {params, 1}}; + std::vector Cout = {{m_params, 2}, {m_params, 1}}; LelantusProof proof; SchnorrProof qkSchnorrProof; - LelantusProver prover(params, LELANTUS_TX_VERSION_4_5); + LelantusProver prover(m_params, LELANTUS_TX_VERSION_4_5); prover.proof(anonymity_sets, {}, Vin, Cin, indexes, {}, Vout, Cout, f, proof, qkSchnorrProof); std::vector groupIds; auto Sin = ExtractSerials(anonymity_sets.size(), Cin, groupIds); auto Cout_Public = ExtractPublicCoins(Cout); - lelantus::LelantusVerifier verifier(params, LELANTUS_TX_VERSION_4_5); + lelantus::LelantusVerifier verifier(m_params, LELANTUS_TX_VERSION_4_5); BOOST_CHECK(verifier.verify(anonymity_sets, {}, Sin, {}, groupIds, Vin, Vout, f, Cout_Public, proof, qkSchnorrProof)); //After Lelantus new update (after version LELANTUS_TX_VERSION_4_5) following 2 verifications will fail, as schnorr proof challenge depends also on Vout, Vin and fee values // BOOST_CHECK(verifier.verify(anonymity_sets, {}, Sin, {}, groupIds, Vin + 1, Vout + 1, f, Cout_Public, proof)); @@ -134,7 +134,7 @@ BOOST_AUTO_TEST_CASE(imbalance_proof_should_fail) size_t N = 100; // Input - PrivateCoin p1(params, 3); + PrivateCoin p1(m_params, 3); std::vector> Cin = {{p1, 0}}; std::vector indexs = {0}; @@ -146,7 +146,7 @@ BOOST_AUTO_TEST_CASE(imbalance_proof_should_fail) Scalar FakeVin(4); // Use this to generate proof // Output - std::vector Cout = {{params, 3}}; + std::vector Cout = {{m_params, 3}}; uint64_t Vout(3); uint64_t f(1); @@ -155,7 +155,7 @@ BOOST_AUTO_TEST_CASE(imbalance_proof_should_fail) SchnorrProof qkSchnorrProof; // Should be prevent from prover - LelantusProver prover(params, LELANTUS_TX_VERSION_4_5); + LelantusProver prover(m_params, LELANTUS_TX_VERSION_4_5); BOOST_CHECK_THROW(prover.proof(anonymitySets, {}, Vin, Cin, indexs, {}, Vout, Cout, f, proof, qkSchnorrProof), std::runtime_error); // Use fake vin @@ -166,7 +166,7 @@ BOOST_AUTO_TEST_CASE(imbalance_proof_should_fail) auto Sin = ExtractSerials(anonymitySets.size(), Cin, groupIds); auto publicCoins = ExtractPublicCoins(Cout); - LelantusVerifier verifier(params, LELANTUS_TX_VERSION_4_5); + LelantusVerifier verifier(m_params, LELANTUS_TX_VERSION_4_5); // input: 2 + 3(anonymous), output: 3 + 3(anonymous) + 1(fee) BOOST_CHECK(!verifier.verify(anonymitySets, {}, Sin, {}, groupIds, Vin, Vout, f, publicCoins, proof, qkSchnorrProof)); @@ -182,7 +182,7 @@ BOOST_AUTO_TEST_CASE(other_fail_to_validate) size_t N = 100; // Input - PrivateCoin p1(params, 1), p2(params, 2); + PrivateCoin p1(m_params, 1), p2(m_params, 2); std::vector> Cin = {{p1, 0}, {p2, 0}}; std::vector indexs = {0, 1}; @@ -194,7 +194,7 @@ BOOST_AUTO_TEST_CASE(other_fail_to_validate) Scalar Vin(4); // Output - std::vector Cout = {{params, 1}, {params, 2}}; + std::vector Cout = {{m_params, 1}, {m_params, 2}}; uint64_t Vout(3); uint64_t f(1); @@ -203,7 +203,7 @@ BOOST_AUTO_TEST_CASE(other_fail_to_validate) SchnorrProof qkSchnorrProof; // Should be prevent from prover - LelantusProver prover(params, LELANTUS_TX_VERSION_4_5); + LelantusProver prover(m_params, LELANTUS_TX_VERSION_4_5); prover.proof(anonymitySets, {}, Vin, Cin, indexs, {}, Vout, Cout, f, proof, qkSchnorrProof); // Verify @@ -211,7 +211,7 @@ BOOST_AUTO_TEST_CASE(other_fail_to_validate) auto Sin = ExtractSerials(anonymitySets.size(), Cin, groupIds); auto publicCoins = ExtractPublicCoins(Cout); - LelantusVerifier verifier(params, LELANTUS_TX_VERSION_4_5); + LelantusVerifier verifier(m_params, LELANTUS_TX_VERSION_4_5); BOOST_CHECK(verifier.verify(anonymitySets, {}, Sin, {}, groupIds, Vin, Vout, f, publicCoins, proof, qkSchnorrProof)); @@ -221,7 +221,7 @@ BOOST_AUTO_TEST_CASE(other_fail_to_validate) BOOST_CHECK(!verifier.verify(invalidAnonymitySets, {}, Sin, {}, groupIds, Vin, Vout, f, publicCoins, proof, qkSchnorrProof)); invalidAnonymitySets = anonymitySets; - invalidAnonymitySets[0].push_back(PrivateCoin(params, 1).getPublicCoin()); + invalidAnonymitySets[0].push_back(PrivateCoin(m_params, 1).getPublicCoin()); BOOST_CHECK(!verifier.verify(invalidAnonymitySets, {}, Sin, {}, groupIds, Vin, Vout, f, publicCoins, proof, qkSchnorrProof)); // Invalid serial diff --git a/src/liblelantus/threadpool.h b/src/liblelantus/threadpool.h index 8a3f2efd25..1bbfb9861c 100644 --- a/src/liblelantus/threadpool.h +++ b/src/liblelantus/threadpool.h @@ -71,7 +71,7 @@ class ParallelOpThreadPool { } public: - ParallelOpThreadPool(std::size_t thread_number) : number_of_threads(thread_number), shutdown(false) {} + ParallelOpThreadPool(std::size_t thread_number) : shutdown(false), number_of_threads(thread_number) {} ~ParallelOpThreadPool() { Shutdown(); diff --git a/src/libspark/bpplus.cpp b/src/libspark/bpplus.cpp index 810d90069e..01973f66e6 100644 --- a/src/libspark/bpplus.cpp +++ b/src/libspark/bpplus.cpp @@ -31,7 +31,7 @@ BPPlus::BPPlus( // Compute 2**N-1 for optimized verification TWO_N_MINUS_ONE = TWO; - for (int i = 0; i < log2(N); i++) { + for (int i = 0; cmp::less(i, log2(N)); i++) { TWO_N_MINUS_ONE *= TWO_N_MINUS_ONE; } TWO_N_MINUS_ONE -= ONE; diff --git a/src/libspark/f4grumble.cpp b/src/libspark/f4grumble.cpp index 839c27e9de..0b9dce3aca 100644 --- a/src/libspark/f4grumble.cpp +++ b/src/libspark/f4grumble.cpp @@ -51,7 +51,7 @@ F4Grumble::F4Grumble(const unsigned char network, const int l_M) { // Encode the input data std::vector F4Grumble::encode(const std::vector& input) { // Check the input size - if (input.size() != l_M) { + if (cmp::not_equal(input.size(), l_M)) { throw std::invalid_argument("Bad address size"); } @@ -74,7 +74,7 @@ std::vector F4Grumble::encode(const std::vector& i // Decode the input data std::vector F4Grumble::decode(const std::vector& input) { // Check the input size - if (input.size() != l_M) { + if (cmp::not_equal(input.size(), l_M)) { throw std::invalid_argument("Bad address size"); } diff --git a/src/libspark/hash.cpp b/src/libspark/hash.cpp index 2c6d71317d..978119b610 100644 --- a/src/libspark/hash.cpp +++ b/src/libspark/hash.cpp @@ -46,7 +46,7 @@ std::vector Hash::finalize() { // Finalize the hash function to a scalar Scalar Hash::finalize_scalar() { // Ensure we can properly populate a scalar - if (EVP_MD_size(EVP_sha512()) < SCALAR_ENCODING) { + if (cmp::less(EVP_MD_size(EVP_sha512()), SCALAR_ENCODING)) { throw std::runtime_error("Bad hash size!"); } diff --git a/src/libspark/kdf.cpp b/src/libspark/kdf.cpp index 238b922df4..e011eae9f4 100644 --- a/src/libspark/kdf.cpp +++ b/src/libspark/kdf.cpp @@ -18,7 +18,7 @@ KDF::KDF(const std::string label, std::size_t derived_key_size) { EVP_DigestUpdate(this->ctx, label_bytes.data(), label_bytes.size()); // Embed and set the derived key size - if (derived_key_size > EVP_MD_size(EVP_sha512())) { + if (cmp::greater(derived_key_size, EVP_MD_size(EVP_sha512()))) { throw std::invalid_argument("Requested KDF size is too large"); } include_size(derived_key_size); diff --git a/src/libspark/keys.h b/src/libspark/keys.h index 8e29d9b381..bf0623f23f 100644 --- a/src/libspark/keys.h +++ b/src/libspark/keys.h @@ -20,6 +20,7 @@ class SpendKey { const Scalar& get_s2() const; const Scalar& get_r() const; + SpendKey(const SpendKey&) = default; SpendKey& operator=(const SpendKey& other); bool operator==(const SpendKey& other) const; diff --git a/src/libspark/mint_transaction.cpp b/src/libspark/mint_transaction.cpp index f52a3b094e..e355c4ab8e 100644 --- a/src/libspark/mint_transaction.cpp +++ b/src/libspark/mint_transaction.cpp @@ -89,7 +89,7 @@ std::vector MintTransaction::getMintedCoinsSerialized() { void MintTransaction::setMintTransaction(std::vector& serializedCoins) { bool first = true; coins.reserve(serializedCoins.size()); - size_t i = 0; + FIRO_UNUSED size_t i = 0; for (auto& stream : serializedCoins) { Coin coin(params); stream >> coin; diff --git a/src/libspark/params.cpp b/src/libspark/params.cpp index b36280fb28..eaaadbe6f9 100644 --- a/src/libspark/params.cpp +++ b/src/libspark/params.cpp @@ -102,7 +102,7 @@ const GroupElement& Params::get_U() const { return this->U; } -const std::size_t Params::get_memo_bytes() const { +std::size_t Params::get_memo_bytes() const { return this->memo_bytes; } diff --git a/src/libspark/params.h b/src/libspark/params.h index 3b18f18ad5..6e53b46645 100644 --- a/src/libspark/params.h +++ b/src/libspark/params.h @@ -20,7 +20,7 @@ class Params { const GroupElement& get_H() const; const GroupElement& get_U() const; - const std::size_t get_memo_bytes() const; + std::size_t get_memo_bytes() const; std::size_t get_max_M_range() const; const std::vector& get_G_range() const; diff --git a/src/libspark/test/grootle_test.cpp b/src/libspark/test/grootle_test.cpp index 57d82635de..bb98ffef6e 100644 --- a/src/libspark/test/grootle_test.cpp +++ b/src/libspark/test/grootle_test.cpp @@ -21,7 +21,7 @@ BOOST_AUTO_TEST_CASE(batch) // Parameters const std::size_t n = 4; const std::size_t m = 3; - const std::size_t N = (std::size_t) std::pow(n, m); // N = 64 + FIRO_UNUSED const std::size_t N = (std::size_t) std::pow(n, m); // N = 64 // Generators GroupElement H; @@ -94,7 +94,7 @@ BOOST_AUTO_TEST_CASE(invalid_batch) // Parameters const std::size_t n = 4; const std::size_t m = 3; - const std::size_t N = (std::size_t) std::pow(n, m); // N = 64 + FIRO_UNUSED const std::size_t N = (std::size_t) std::pow(n, m); // N = 64 // Generators GroupElement H; diff --git a/src/libspark/transcript.cpp b/src/libspark/transcript.cpp index b75f8c4d31..78ab1d600f 100644 --- a/src/libspark/transcript.cpp +++ b/src/libspark/transcript.cpp @@ -108,7 +108,7 @@ void Transcript::add(const std::string label, const std::vector CQuorumBlockProcessor::GetMinedCommitmentsUntilB } uint32_t nMinedHeight = std::numeric_limits::max() - be32toh(std::get<2>(curKey)); - if (nMinedHeight > pindex->nHeight) { + if (cmp::greater(nMinedHeight, pindex->nHeight)) { break; } diff --git a/src/llmq/quorums_chainlocks.h b/src/llmq/quorums_chainlocks.h index 2ba298579c..c2cfbd8619 100644 --- a/src/llmq/quorums_chainlocks.h +++ b/src/llmq/quorums_chainlocks.h @@ -96,7 +96,7 @@ class CChainLocksHandler : public CRecoveredSigsListener void CheckActiveState(); void TrySignChainTip(); void EnforceBestChainLock(); - virtual void HandleNewRecoveredSig(const CRecoveredSig& recoveredSig); + virtual void HandleNewRecoveredSig(const CRecoveredSig& recoveredSig) override; bool HasChainLock(int nHeight, const uint256& blockHash); bool HasConflictingChainLock(int nHeight, const uint256& blockHash); diff --git a/src/llmq/quorums_commitment.cpp b/src/llmq/quorums_commitment.cpp index 85ef4bfa33..051cec8709 100644 --- a/src/llmq/quorums_commitment.cpp +++ b/src/llmq/quorums_commitment.cpp @@ -68,7 +68,7 @@ bool CFinalCommitment::Verify(const std::vector& members, return false; } - for (size_t i = members.size(); i < params.size; i++) { + for (size_t i = members.size(); cmp::less(i, params.size); i++) { if (validMembers[i]) { LogPrintfFinalCommitment("invalid validMembers bitset. bit %d should not be set\n", i); return false; @@ -122,11 +122,11 @@ bool CFinalCommitment::VerifyNull() const bool CFinalCommitment::VerifySizes(const Consensus::LLMQParams& params) const { - if (signers.size() != params.size) { + if (cmp::not_equal(signers.size(), params.size)) { LogPrintfFinalCommitment("invalid signers.size=%d\n", signers.size()); return false; } - if (validMembers.size() != params.size) { + if (cmp::not_equal(validMembers.size(), params.size)) { LogPrintfFinalCommitment("invalid signers.size=%d\n", signers.size()); return false; } @@ -166,7 +166,7 @@ bool CheckLLMQCommitment(const CTransaction& tx, const CBlockIndex* pindexPrev, return state.DoS(100, false, REJECT_INVALID, "bad-qc-version"); } - if (qcTx.nHeight != pindexPrev->nHeight + 1) { + if (cmp::not_equal(qcTx.nHeight, pindexPrev->nHeight + 1)) { return state.DoS(100, false, REJECT_INVALID, "bad-qc-height"); } diff --git a/src/llmq/quorums_debug.cpp b/src/llmq/quorums_debug.cpp index 13be503d0b..9976f45c97 100644 --- a/src/llmq/quorums_debug.cpp +++ b/src/llmq/quorums_debug.cpp @@ -42,11 +42,11 @@ UniValue CDKGDebugSessionStatus::ToJson(int detailLevel) const ret.push_back(Pair("quorumHeight", (int)quorumHeight)); ret.push_back(Pair("phase", (int)phase)); - ret.push_back(Pair("sentContributions", sentContributions)); - ret.push_back(Pair("sentComplaint", sentComplaint)); - ret.push_back(Pair("sentJustification", sentJustification)); - ret.push_back(Pair("sentPrematureCommitment", sentPrematureCommitment)); - ret.push_back(Pair("aborted", aborted)); + ret.push_back(Pair("sentContributions", debugStatus.status.sentContributions)); + ret.push_back(Pair("sentComplaint", debugStatus.status.sentComplaint)); + ret.push_back(Pair("sentJustification", debugStatus.status.sentJustification)); + ret.push_back(Pair("sentPrematureCommitment", debugStatus.status.sentPrematureCommitment)); + ret.push_back(Pair("aborted", debugStatus.status.aborted)); struct ArrOrCount { int count{0}; @@ -87,12 +87,12 @@ UniValue CDKGDebugSessionStatus::ToJson(int detailLevel) const for (size_t i = 0; i < members.size(); i++) { const auto& m = members[i]; - add(badMembers, i, m.bad); - add(weComplain, i, m.weComplain); - add(receivedContributions, i, m.receivedContribution); - add(receivedComplaints, i, m.receivedComplaint); - add(receivedJustifications, i, m.receivedJustification); - add(receivedPrematureCommitments, i, m.receivedPrematureCommitment); + add(badMembers, i, m.debugStatus.status.bad); + add(weComplain, i, m.debugStatus.status.weComplain); + add(receivedContributions, i, m.debugStatus.status.receivedContribution); + add(receivedComplaints, i, m.debugStatus.status.receivedComplaint); + add(receivedJustifications, i, m.debugStatus.status.receivedJustification); + add(receivedPrematureCommitments, i, m.debugStatus.status.receivedPrematureCommitment); } push(badMembers, "badMembers"); push(weComplain, "weComplain"); @@ -171,7 +171,7 @@ void CDKGDebugManager::InitLocalSessionStatus(Consensus::LLMQType llmqType, cons session.quorumHash = quorumHash; session.quorumHeight = (uint32_t)quorumHeight; session.phase = 0; - session.statusBitset = 0; + session.debugStatus.statusBitset = 0; session.members.clear(); session.members.resize((size_t)params.size); } diff --git a/src/llmq/quorums_debug.h b/src/llmq/quorums_debug.h index b52dec6669..988a663a58 100644 --- a/src/llmq/quorums_debug.h +++ b/src/llmq/quorums_debug.h @@ -21,8 +21,8 @@ namespace llmq class CDKGDebugMemberStatus { public: - union { - struct + union DebugStatus{ + struct Status { // is it locally considered as bad (and thus removed from the validMembers set) bool bad : 1; @@ -34,14 +34,15 @@ class CDKGDebugMemberStatus bool receivedComplaint : 1; bool receivedJustification : 1; bool receivedPrematureCommitment : 1; - }; + } status; uint8_t statusBitset; - }; + DebugStatus() : statusBitset(0) {} + } debugStatus {}; std::set complaintsFromMembers; public: - CDKGDebugMemberStatus() : statusBitset(0) {} + CDKGDebugMemberStatus() = default; }; class CDKGDebugSessionStatus @@ -52,8 +53,8 @@ class CDKGDebugSessionStatus uint32_t quorumHeight{0}; uint8_t phase{0}; - union { - struct + union DebugStatus{ + struct Status { // sent messages for DKG phases bool sentContributions : 1; @@ -62,14 +63,15 @@ class CDKGDebugSessionStatus bool sentPrematureCommitment : 1; bool aborted : 1; - }; + } status; uint8_t statusBitset; - }; + DebugStatus() : statusBitset(0) {} + } debugStatus {}; std::vector members; public: - CDKGDebugSessionStatus() : statusBitset(0) {} + CDKGDebugSessionStatus() = default; UniValue ToJson(int detailLevel) const; }; diff --git a/src/llmq/quorums_dkgsession.cpp b/src/llmq/quorums_dkgsession.cpp index cc525c6a48..ff6b0ca010 100644 --- a/src/llmq/quorums_dkgsession.cpp +++ b/src/llmq/quorums_dkgsession.cpp @@ -90,7 +90,7 @@ CDKGMember::CDKGMember(CDeterministicMNCPtr _dmn, size_t _idx) : bool CDKGSession::Init(const CBlockIndex* _pindexQuorum, const std::vector& mns, const uint256& _myProTxHash) { - if (mns.size() < params.minSize) { + if (cmp::less(mns.size(), params.minSize)) { return false; } @@ -199,7 +199,7 @@ void CDKGSession::SendContributions(CDKGPendingMessages& pendingMessages) logger.Flush(); quorumDKGDebugManager->UpdateLocalSessionStatus(params.type, [&](CDKGDebugSessionStatus& status) { - status.sentContributions = true; + status.debugStatus.status.sentContributions = true; return true; }); @@ -232,7 +232,7 @@ bool CDKGSession::PreVerifyMessage(const uint256& hash, const CDKGContribution& retBan = true; return false; } - if (qc.vvec->size() != params.threshold) { + if (cmp::not_equal(qc.vvec->size(), params.threshold)) { logger.Batch("invalid verification vector length"); retBan = true; return false; @@ -284,7 +284,7 @@ void CDKGSession::ReceiveMessage(const uint256& hash, const CDKGContribution& qc RelayInvToParticipants(inv); quorumDKGDebugManager->UpdateLocalMemberStatus(params.type, member->idx, [&](CDKGDebugMemberStatus& status) { - status.receivedContribution = true; + status.debugStatus.status.receivedContribution = true; return true; }); @@ -330,7 +330,7 @@ void CDKGSession::ReceiveMessage(const uint256& hash, const CDKGContribution& qc if (complain) { member->weComplain = true; quorumDKGDebugManager->UpdateLocalMemberStatus(params.type, member->idx, [&](CDKGDebugMemberStatus& status) { - status.weComplain = true; + status.debugStatus.status.weComplain = true; return true; }); return; @@ -392,7 +392,7 @@ void CDKGSession::VerifyPendingContributions() logger.Batch("invalid contribution from %s. will complain later", m->dmn->proTxHash.ToString()); m->weComplain = true; quorumDKGDebugManager->UpdateLocalMemberStatus(params.type, m->idx, [&](CDKGDebugMemberStatus& status) { - status.weComplain = true; + status.debugStatus.status.weComplain = true; return true; }); } else { @@ -475,7 +475,7 @@ void CDKGSession::SendComplaint(CDKGPendingMessages& pendingMessages) logger.Flush(); quorumDKGDebugManager->UpdateLocalSessionStatus(params.type, [&](CDKGDebugSessionStatus& status) { - status.sentComplaint = true; + status.debugStatus.status.sentComplaint = true; return true; }); @@ -551,7 +551,7 @@ void CDKGSession::ReceiveMessage(const uint256& hash, const CDKGComplaint& qc, b RelayInvToParticipants(inv); quorumDKGDebugManager->UpdateLocalMemberStatus(params.type, member->idx, [&](CDKGDebugMemberStatus& status) { - status.receivedComplaint = true; + status.debugStatus.status.receivedComplaint = true; return true; }); @@ -606,7 +606,7 @@ void CDKGSession::VerifyAndJustify(CDKGPendingMessages& pendingMessages) if (m->bad) { continue; } - if (m->badMemberVotes.size() >= params.dkgBadVotesThreshold) { + if (cmp::greater_equal(m->badMemberVotes.size(), params.dkgBadVotesThreshold)) { logger.Batch("%s marked as bad as %d other members voted for this", m->dmn->proTxHash.ToString(), m->badMemberVotes.size()); MarkBadMember(m->idx); continue; @@ -673,7 +673,7 @@ void CDKGSession::SendJustification(CDKGPendingMessages& pendingMessages, const logger.Flush(); quorumDKGDebugManager->UpdateLocalSessionStatus(params.type, [&](CDKGDebugSessionStatus& status) { - status.sentJustification = true; + status.debugStatus.status.sentJustification = true; return true; }); @@ -766,7 +766,7 @@ void CDKGSession::ReceiveMessage(const uint256& hash, const CDKGJustification& q RelayInvToParticipants(inv); quorumDKGDebugManager->UpdateLocalMemberStatus(params.type, member->idx, [&](CDKGDebugMemberStatus& status) { - status.receivedJustification = true; + status.debugStatus.status.receivedJustification = true; return true; }); @@ -993,7 +993,7 @@ void CDKGSession::SendCommitment(CDKGPendingMessages& pendingMessages) logger.Flush(); quorumDKGDebugManager->UpdateLocalSessionStatus(params.type, [&](CDKGDebugSessionStatus& status) { - status.sentPrematureCommitment = true; + status.debugStatus.status.sentPrematureCommitment = true; return true; }); @@ -1043,7 +1043,7 @@ bool CDKGSession::PreVerifyMessage(const uint256& hash, const CDKGPrematureCommi return false; } - for (size_t i = members.size(); i < params.size; i++) { + for (size_t i = members.size(); cmp::less(i, params.size); i++) { if (qc.validMembers[i]) { retBan = true; logger.Batch("invalid validMembers bitset. bit %d should not be set", i); @@ -1132,7 +1132,7 @@ void CDKGSession::ReceiveMessage(const uint256& hash, const CDKGPrematureCommitm RelayInvToParticipants(inv); quorumDKGDebugManager->UpdateLocalMemberStatus(params.type, member->idx, [&](CDKGDebugMemberStatus& status) { - status.receivedPrematureCommitment = true; + status.debugStatus.status.receivedPrematureCommitment = true; return true; }); @@ -1181,7 +1181,7 @@ std::vector CDKGSession::FinalizeCommitments() std::vector finalCommitments; for (const auto& p : commitmentsMap) { auto& cvec = p.second; - if (cvec.size() < params.minSize) { + if (cmp::less(cvec.size(), params.minSize)) { // commitment was signed by a minority continue; } @@ -1261,7 +1261,7 @@ void CDKGSession::MarkBadMember(size_t idx) return; } quorumDKGDebugManager->UpdateLocalMemberStatus(params.type, idx, [&](CDKGDebugMemberStatus& status) { - status.bad = true; + status.debugStatus.status.bad = true; return true; }); member->bad = true; diff --git a/src/llmq/quorums_dkgsessionhandler.cpp b/src/llmq/quorums_dkgsessionhandler.cpp index fe3bde4746..c691420607 100644 --- a/src/llmq/quorums_dkgsessionhandler.cpp +++ b/src/llmq/quorums_dkgsessionhandler.cpp @@ -64,7 +64,7 @@ std::list CDKGPendingMessages::PopPendingMes pendingMessages.pop_front(); } - return std::move(ret); + return ret; } bool CDKGPendingMessages::HasSeen(const uint256& hash) const @@ -143,7 +143,7 @@ bool CDKGSessionHandler::InitNewQuorum(const CBlockIndex* pindexQuorum) { //AssertLockHeld(cs_main); - const auto& consensus = Params().GetConsensus(); + FIRO_UNUSED const auto& consensus = Params().GetConsensus(); curSession = std::make_shared(params, blsWorker, dkgManager); @@ -325,7 +325,7 @@ std::set BatchVerifyMessageSigs(CDKGSession& session, const std::vector< } // are all messages from the same node? - NodeId firstNodeId; + NodeId firstNodeId = 0; first = true; bool nodeIdsAllSame = true; for (auto it = messages.begin(); it != messages.end(); ++it) { @@ -442,7 +442,7 @@ bool ProcessPendingMessageBatch(CDKGSession& session, CDKGPendingMessages& pendi void CDKGSessionHandler::HandleDKGRound() { uint256 curQuorumHash; - int curQuorumHeight; + FIRO_UNUSED int curQuorumHeight; WaitForNextPhase(QuorumPhase_None, QuorumPhase_Initialized, uint256(), []{return false;}); @@ -553,7 +553,7 @@ void CDKGSessionHandler::PhaseHandlerThread() HandleDKGRound(); } catch (AbortPhaseException& e) { quorumDKGDebugManager->UpdateLocalSessionStatus(params.type, [&](CDKGDebugSessionStatus& status) { - status.aborted = true; + status.debugStatus.status.aborted = true; return true; }); LogPrint("llmq-dkg", "CDKGSessionHandler::%s -- aborted current DKG session for llmq=%s\n", __func__, params.name); diff --git a/src/llmq/quorums_dkgsessionmgr.cpp b/src/llmq/quorums_dkgsessionmgr.cpp index a2f3907122..de55a939e9 100644 --- a/src/llmq/quorums_dkgsessionmgr.cpp +++ b/src/llmq/quorums_dkgsessionmgr.cpp @@ -49,7 +49,7 @@ void CDKGSessionManager::StopMessageHandlerPool() void CDKGSessionManager::UpdatedBlockTip(const CBlockIndex* pindexNew, bool fInitialDownload) { - const auto& consensus = Params().GetConsensus(); + FIRO_UNUSED const auto& consensus = Params().GetConsensus(); CleanupCache(); diff --git a/src/llmq/quorums_instantsend.cpp b/src/llmq/quorums_instantsend.cpp index 9db3cade75..8d687d59b9 100644 --- a/src/llmq/quorums_instantsend.cpp +++ b/src/llmq/quorums_instantsend.cpp @@ -125,7 +125,7 @@ std::unordered_map CInstantSendDb::RemoveConfirmed break; } uint32_t nHeight = std::numeric_limits::max() - be32toh(std::get<1>(curKey)); - if (nHeight > nUntilHeight) { + if (cmp::greater(nHeight, nUntilHeight)) { break; } @@ -164,7 +164,7 @@ void CInstantSendDb::RemoveArchivedInstantSendLocks(int nUntilHeight) break; } uint32_t nHeight = std::numeric_limits::max() - be32toh(std::get<1>(curKey)); - if (nHeight > nUntilHeight) { + if (cmp::greater(nHeight, nUntilHeight)) { break; } @@ -511,7 +511,7 @@ bool CInstantSendManager::CheckCanLock(const CTransaction& tx, bool printDebug, return true; } - CAmount nValueIn = 0; + FIRO_UNUSED CAmount nValueIn = 0; for (const auto& in : tx.vin) { CAmount v = 0; if (!CheckCanLock(in.prevout, printDebug, tx.GetHash(), &v, params)) { @@ -587,7 +587,7 @@ void CInstantSendManager::HandleNewRecoveredSig(const CRecoveredSig& recoveredSi if (llmqType == Consensus::LLMQ_NONE) { return; } - auto& params = Params().GetConsensus().llmqs.at(llmqType); + FIRO_UNUSED auto& params = Params().GetConsensus().llmqs.at(llmqType); uint256 txid; bool isInstantSendLock = false; @@ -609,7 +609,7 @@ void CInstantSendManager::HandleNewRecoveredSig(const CRecoveredSig& recoveredSi void CInstantSendManager::HandleNewInputLockRecoveredSig(const CRecoveredSig& recoveredSig, const uint256& txid) { - auto llmqType = Params().GetConsensus().llmqForInstantSend; + FIRO_UNUSED auto llmqType = Params().GetConsensus().llmqForInstantSend; CTransactionRef tx; uint256 hashBlock; diff --git a/src/llmq/quorums_instantsend.h b/src/llmq/quorums_instantsend.h index fd73d06689..3ed348cbf6 100644 --- a/src/llmq/quorums_instantsend.h +++ b/src/llmq/quorums_instantsend.h @@ -143,7 +143,7 @@ class CInstantSendManager : public CRecoveredSigsListener bool CheckCanLock(const COutPoint& outpoint, bool printDebug, const uint256& txHash, CAmount* retValue, const Consensus::Params& params); bool IsConflicted(const CTransaction& tx); - virtual void HandleNewRecoveredSig(const CRecoveredSig& recoveredSig); + virtual void HandleNewRecoveredSig(const CRecoveredSig& recoveredSig) override; void HandleNewInputLockRecoveredSig(const CRecoveredSig& recoveredSig, const uint256& txid); void HandleNewInstantSendLockRecoveredSig(const CRecoveredSig& recoveredSig); diff --git a/src/llmq/quorums_signing.cpp b/src/llmq/quorums_signing.cpp index d8a0f9e07e..202cc00ff0 100644 --- a/src/llmq/quorums_signing.cpp +++ b/src/llmq/quorums_signing.cpp @@ -250,7 +250,7 @@ void CRecoveredSigsDb::WriteRecoveredSig(const llmq::CRecoveredSig& recSig) db.WriteBatch(batch); { - int64_t t = GetTimeMillis(); + FIRO_UNUSED int64_t t = GetTimeMillis(); LOCK(cs); hasSigForIdCache.insert(std::make_pair((Consensus::LLMQType)recSig.llmqType, recSig.id), true); @@ -745,7 +745,7 @@ void CSigningManager::UnregisterRecoveredSigsListener(CRecoveredSigsListener* l) bool CSigningManager::AsyncSignIfMember(Consensus::LLMQType llmqType, const uint256& id, const uint256& msgHash, bool allowReSign) { - auto& params = Params().GetConsensus().llmqs.at(llmqType); + FIRO_UNUSED auto& params = Params().GetConsensus().llmqs.at(llmqType); if (!fMasternodeMode || activeMasternodeInfo.proTxHash.IsNull()) { return false; diff --git a/src/llmq/quorums_signing_shares.cpp b/src/llmq/quorums_signing_shares.cpp index 0568f5ff77..0815f5dd6c 100644 --- a/src/llmq/quorums_signing_shares.cpp +++ b/src/llmq/quorums_signing_shares.cpp @@ -320,7 +320,7 @@ bool CSigSharesManager::ProcessMessageSigSesAnn(CNode* pfrom, const CSigSesAnn& return true; // let's still try other announcements from the same message } - auto signHash = CLLMQUtils::BuildSignHash(llmqType, ann.quorumHash, ann.id, ann.msgHash); + FIRO_UNUSED auto signHash = CLLMQUtils::BuildSignHash(llmqType, ann.quorumHash, ann.id, ann.msgHash); LOCK(cs); auto& nodeState = nodeStates[pfrom->id]; @@ -647,7 +647,7 @@ void CSigSharesManager::ProcessPendingSigSharesFromNode(NodeId nodeId, const std::unordered_map, CQuorumCPtr, StaticSaltedHasher>& quorums, CConnman& connman) { - auto& nodeState = nodeStates[nodeId]; + FIRO_UNUSED auto& nodeState = nodeStates[nodeId]; cxxtimer::Timer t(true); for (auto& sigShare : sigShares) { @@ -701,7 +701,7 @@ void CSigSharesManager::ProcessSigShare(NodeId nodeId, const CSigShare& sigShare } size_t sigShareCount = sigShares.CountForSignHash(sigShare.GetSignHash()); - if (sigShareCount >= quorum->params.threshold) { + if (cmp::greater_equal(sigShareCount, quorum->params.threshold)) { canTryRecovery = true; } } @@ -722,7 +722,7 @@ void CSigSharesManager::TryRecoverSig(const CQuorumCPtr& quorum, const uint256& { LOCK(cs); - auto k = std::make_pair(quorum->params.type, id); + FIRO_UNUSED auto k = std::make_pair(quorum->params.type, id); auto signHash = CLLMQUtils::BuildSignHash(quorum->params.type, quorum->qc.quorumHash, id, msgHash); auto sigShares = this->sigShares.GetAllForSignHash(signHash); @@ -732,14 +732,14 @@ void CSigSharesManager::TryRecoverSig(const CQuorumCPtr& quorum, const uint256& sigSharesForRecovery.reserve((size_t) quorum->params.threshold); idsForRecovery.reserve((size_t) quorum->params.threshold); - for (auto it = sigShares->begin(); it != sigShares->end() && sigSharesForRecovery.size() < quorum->params.threshold; ++it) { + for (auto it = sigShares->begin(); it != sigShares->end() && cmp::less(sigSharesForRecovery.size(), quorum->params.threshold); ++it) { auto& sigShare = it->second; sigSharesForRecovery.emplace_back(sigShare.sigShare.Get()); idsForRecovery.emplace_back(quorum->members[sigShare.quorumMember]->proTxHash); } // check if we can recover the final signature - if (sigSharesForRecovery.size() < quorum->params.threshold) { + if (cmp::less(sigSharesForRecovery.size(), quorum->params.threshold)) { return; } } diff --git a/src/llmq/quorums_signing_shares.h b/src/llmq/quorums_signing_shares.h index 340c8ea07b..329ba63392 100644 --- a/src/llmq/quorums_signing_shares.h +++ b/src/llmq/quorums_signing_shares.h @@ -380,7 +380,7 @@ class CSigSharesManager : public CRecoveredSigsListener void Sign(const CQuorumCPtr& quorum, const uint256& id, const uint256& msgHash); void ForceReAnnouncement(const CQuorumCPtr& quorum, Consensus::LLMQType llmqType, const uint256& id, const uint256& msgHash); - void HandleNewRecoveredSig(const CRecoveredSig& recoveredSig); + void HandleNewRecoveredSig(const CRecoveredSig& recoveredSig) override; private: // all of these return false when the currently processed message should be aborted (as each message actually contains multiple messages) diff --git a/src/llmq/quorums_utils.cpp b/src/llmq/quorums_utils.cpp index 3af8aa8537..f5643e52da 100644 --- a/src/llmq/quorums_utils.cpp +++ b/src/llmq/quorums_utils.cpp @@ -43,7 +43,7 @@ uint256 CLLMQUtils::BuildSignHash(Consensus::LLMQType llmqType, const uint256& q std::set CLLMQUtils::GetQuorumConnections(Consensus::LLMQType llmqType, const CBlockIndex* pindexQuorum, const uint256& forMember) { - auto& params = Params().GetConsensus().llmqs.at(llmqType); + FIRO_UNUSED auto& params = Params().GetConsensus().llmqs.at(llmqType); auto mns = GetAllQuorumMembers(llmqType, pindexQuorum); std::set result; diff --git a/src/masternode-payments.cpp b/src/masternode-payments.cpp index 907a303072..9c04eb5af8 100644 --- a/src/masternode-payments.cpp +++ b/src/masternode-payments.cpp @@ -81,7 +81,7 @@ bool IsOldBudgetBlockValueValid(const CBlock& block, int nBlockHeight, CAmount b bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockReward, std::string& strErrorRet) { - const Consensus::Params& consensusParams = Params().GetConsensus(); + FIRO_UNUSED const Consensus::Params& consensusParams = Params().GetConsensus(); bool isBlockRewardValueMet = (block.vtx[0]->GetValueOut() <= blockReward); return isBlockRewardValueMet; @@ -98,7 +98,7 @@ bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, int nTime, C // we are still using budgets, but we have no data about them anymore, // we can only check masternode payments - const Consensus::Params& consensusParams = Params().GetConsensus(); + FIRO_UNUSED const Consensus::Params& consensusParams = Params().GetConsensus(); // Check for correct masternode payment if(mnpayments.IsTransactionValid(txNew, nBlockHeight, nTime, blockReward)) { diff --git a/src/miner.cpp b/src/miner.cpp index f41d9b52a4..b772c48b74 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1150,7 +1150,7 @@ void static FiroMiner(const CChainParams &chainparams) { const Consensus::Params ¶ms = chainparams.GetConsensus(); { LOCK2(cs_main, mempool.cs); - int nCount = 0; + FIRO_UNUSED int nCount = 0; fHasZnodesWinnerForNextBlock = params.IsRegtest() || chainActive.Height()+1 >= chainparams.GetConsensus().DIP0003EnforcementHeight; diff --git a/src/net.cpp b/src/net.cpp index 98d5d5b518..22ea040c82 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -67,19 +67,6 @@ #endif #endif - -namespace { - const int MAX_OUTBOUND_CONNECTIONS = 8; - const int MAX_FEELER_CONNECTIONS = 1; - - struct ListenSocket { - SOCKET socket; - bool whitelisted; - - ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {} - }; -} - constexpr const CConnman::CFullyConnectedOnly CConnman::FullyConnectedOnly; constexpr const CConnman::CAllNodes CConnman::AllNodes; diff --git a/src/net_processing.cpp b/src/net_processing.cpp index ed1f37e7f8..41f2958fc7 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -616,6 +616,8 @@ void UnregisterNodeSignals(CNodeSignals& nodeSignals) void AddToCompactExtraTransactions(const CTransactionRef& tx) { + LOCK(cs_main); + size_t max_extra_txn = GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN); if (max_extra_txn <= 0) return; @@ -2059,7 +2061,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr std::deque vWorkQueue; std::vector vEraseQueue; - int nInvType = MSG_TX; + FIRO_UNUSED int nInvType = MSG_TX; CTransactionRef ptx; // Read data and assign inv type @@ -2073,7 +2075,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr LOCK(cs_main); bool fMissingInputs = false; - bool fMissingInputsSigma = false; + FIRO_UNUSED bool fMissingInputsSigma = false; CValidationState state; CValidationState dummyState; // Dummy state for Dandelion stempool diff --git a/src/net_processing.h b/src/net_processing.h index 4a6ceb76da..a02930cff0 100644 --- a/src/net_processing.h +++ b/src/net_processing.h @@ -39,10 +39,10 @@ class PeerLogicValidation : public CValidationInterface { public: PeerLogicValidation(CConnman* connmanIn); - virtual void SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, int nPosInBlock); - virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload); - virtual void BlockChecked(const CBlock& block, const CValidationState& state); - virtual void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr& pblock); + virtual void SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, int nPosInBlock) override; + virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override; + virtual void BlockChecked(const CBlock& block, const CValidationState& state) override; + virtual void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr& pblock) override; }; struct CNodeStateStats { diff --git a/src/pow.cpp b/src/pow.cpp index ecd405499d..c5b690a959 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -84,7 +84,7 @@ unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHead uint32_t BlocksTargetSpacing = (params.nMTPFiveMinutesStartBlock == 0 && fMTP) || (params.nMTPFiveMinutesStartBlock > 0 && pindexLast->nHeight >= params.nMTPFiveMinutesStartBlock) ? params.nPowTargetSpacingMTP : params.nPowTargetSpacing; - if (pindexLast->nTime >= params.stage3StartTime) + if (cmp::greater_equal(pindexLast->nTime, params.stage3StartTime)) BlocksTargetSpacing /= 2; unsigned int TimeDaySeconds = 60 * 60 * 24; @@ -95,7 +95,7 @@ unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHead uint32_t StartingPoWBlock = 0; if (pblock->IsShorterBlocksSpacing()) { - if (pindexLast->nTime < params.stage3StartTime) { + if (cmp::less(pindexLast->nTime, params.stage3StartTime)) { // first time we see a block with shorter interval // Normally we should take difficulty and halve it. But to give some leeway to the miners // we divide it by 4 @@ -118,7 +118,7 @@ unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHead else if (pblock->nTime < params.stage3StartTime + BlocksTargetSpacing*PastBlocksMax*3) { // transition to stage3 happened recently, look for the last block before the transition const CBlockIndex *pindex = pindexLast; - while (pindex && pindex->nTime >= params.stage3StartTime) + while (pindex && cmp::greater_equal(pindex->nTime, params.stage3StartTime)) pindex = pindex->pprev; if (pindex) diff --git a/src/prevector.h b/src/prevector.h index cba2e30057..8f276b7058 100644 --- a/src/prevector.h +++ b/src/prevector.h @@ -147,16 +147,16 @@ class prevector { size_type _size; union direct_or_indirect { char direct[sizeof(T) * N]; - struct { + struct indirect{ size_type capacity; char* indirect; - }; + } data; } _union; T* direct_ptr(difference_type pos) { return reinterpret_cast(_union.direct) + pos; } const T* direct_ptr(difference_type pos) const { return reinterpret_cast(_union.direct) + pos; } - T* indirect_ptr(difference_type pos) { return reinterpret_cast(_union.indirect) + pos; } - const T* indirect_ptr(difference_type pos) const { return reinterpret_cast(_union.indirect) + pos; } + T* indirect_ptr(difference_type pos) { return reinterpret_cast(_union.data.indirect) + pos; } + const T* indirect_ptr(difference_type pos) const { return reinterpret_cast(_union.data.indirect) + pos; } bool is_direct() const { return _size <= N; } void change_capacity(size_type new_capacity) { @@ -174,17 +174,17 @@ class prevector { /* FIXME: Because malloc/realloc here won't call new_handler if allocation fails, assert success. These should instead use an allocator or new/delete so that handlers are called as necessary, but performance would be slightly degraded by doing so. */ - _union.indirect = static_cast(realloc(_union.indirect, ((size_t)sizeof(T)) * new_capacity)); - assert(_union.indirect); - _union.capacity = new_capacity; + _union.data.indirect = static_cast(realloc(_union.data.indirect, ((size_t)sizeof(T)) * new_capacity)); + assert(_union.data.indirect); + _union.data.capacity = new_capacity; } else { char* new_indirect = static_cast(malloc(((size_t)sizeof(T)) * new_capacity)); assert(new_indirect); T* src = direct_ptr(0); T* dst = reinterpret_cast(new_indirect); memcpy(dst, src, size() * sizeof(T)); - _union.indirect = new_indirect; - _union.capacity = new_capacity; + _union.data.indirect = new_indirect; + _union.data.capacity = new_capacity; _size += N + 1; } } @@ -300,7 +300,7 @@ class prevector { if (is_direct()) { return N; } else { - return _union.capacity; + return _union.data.capacity; } } @@ -434,8 +434,8 @@ class prevector { ~prevector() { clear(); if (!is_direct()) { - free(_union.indirect); - _union.indirect = NULL; + free(_union.data.indirect); + _union.data.indirect = NULL; } } @@ -487,7 +487,7 @@ class prevector { if (is_direct()) { return 0; } else { - return ((size_t)(sizeof(T))) * _union.capacity; + return ((size_t)(sizeof(T))) * _union.data.capacity; } } diff --git a/src/primitives/block.cpp b/src/primitives/block.cpp index e5389b93f8..1cbef37159 100644 --- a/src/primitives/block.cpp +++ b/src/primitives/block.cpp @@ -24,6 +24,7 @@ #include #include #include "precomputed_hash.h" +#include "../../compat_layer.h" unsigned char GetNfactor(int64_t nTimestamp) { int l = 0; @@ -70,17 +71,17 @@ bool CBlockHeader::IsProgPow() const { } bool CBlockHeader::IsShorterBlocksSpacing() const { - return (nTime > ZC_GENESIS_BLOCK_TIME && nTime >= Params().GetConsensus().stage3StartTime); + return (nTime > ZC_GENESIS_BLOCK_TIME && cmp::greater_equal(nTime, Params().GetConsensus().stage3StartTime)); } int CBlockHeader::GetTargetBlocksSpacing() const { const Consensus::Params ¶ms = Params().GetConsensus(); - if (nTime <= ZC_GENESIS_BLOCK_TIME) + if (cmp::less_equal(nTime, ZC_GENESIS_BLOCK_TIME)) return params.nPowTargetSpacing; - else if (nTime >= params.stage3StartTime) + else if (cmp::greater_equal(nTime, params.stage3StartTime)) return params.nPowTargetSpacingMTP/2; - else if ((params.nMTPFiveMinutesStartBlock == 0 && nTime >= params.nMTPSwitchTime) || - (params.nMTPFiveMinutesStartBlock != 0 && nHeight >= params.nMTPFiveMinutesStartBlock)) + else if ((params.nMTPFiveMinutesStartBlock == 0 && cmp::greater_equal(nTime, params.nMTPSwitchTime)) || + (params.nMTPFiveMinutesStartBlock != 0 && cmp::greater_equal(nHeight, params.nMTPFiveMinutesStartBlock))) return params.nPowTargetSpacingMTP; else return params.nPowTargetSpacing; diff --git a/src/primitives/transaction.cpp b/src/primitives/transaction.cpp index e36aaa986d..a79af6e76e 100644 --- a/src/primitives/transaction.cpp +++ b/src/primitives/transaction.cpp @@ -10,13 +10,13 @@ #include "utilstrencodings.h" /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/ -static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 50000; // 50KB +FIRO_UNUSED static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 50000; // 50KB /** Dust Soft Limit, allowed with additional fee per output */ -static const int64_t DUST_SOFT_LIMIT = 100000; // 0.001 FIRO +FIRO_UNUSED static const int64_t DUST_SOFT_LIMIT = 100000; // 0.001 FIRO /** The maximum allowed size for a serialized block, in bytes (network rule) */ -static const unsigned int MAX_BLOCK_SIZE = 2000000; // 2000KB block hard limit +FIRO_UNUSED static const unsigned int MAX_BLOCK_SIZE = 2000000; // 2000KB block hard limit /** Obsolete: maximum size for mined blocks */ -static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/4; // 500KB block soft limit +FIRO_UNUSED static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/4; // 500KB block soft limit std::string COutPoint::ToString() const { diff --git a/src/primitives/transaction.h b/src/primitives/transaction.h index 50cb5e7b55..4cf9035536 100644 --- a/src/primitives/transaction.h +++ b/src/primitives/transaction.h @@ -10,6 +10,7 @@ #include "script/script.h" #include "serialize.h" #include "uint256.h" +#include "../compat_layer.h" #include diff --git a/src/protocol.cpp b/src/protocol.cpp index a3766a953a..ca2e28c4a1 100644 --- a/src/protocol.cpp +++ b/src/protocol.cpp @@ -206,7 +206,7 @@ std::string CInv::GetCommand() const std::string cmd; if (type & MSG_WITNESS_FLAG) cmd.append("witness-"); - int masked = type & MSG_TYPE_MASK; + FIRO_UNUSED int masked = type & MSG_TYPE_MASK; // TODO: switch(masked) switch (type) { diff --git a/src/qt/CMakeLists.txt b/src/qt/CMakeLists.txt new file mode 100644 index 0000000000..c251df1031 --- /dev/null +++ b/src/qt/CMakeLists.txt @@ -0,0 +1,369 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + enable_language(OBJCXX) + set(CMAKE_OBJCXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO}") + set(CMAKE_OBJCXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}") + set(CMAKE_OBJCXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}") + set(CMAKE_OBJCXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL}") + string(APPEND CMAKE_OBJCXX_COMPILE_OBJECT " ${APPEND_CPPFLAGS} ${APPEND_CXXFLAGS}") +endif() + +get_target_property(qt_lib_type Qt5::Core TYPE) + +function(import_plugins target) + if(qt_lib_type STREQUAL "STATIC_LIBRARY") + set(plugins Qt5::QMinimalIntegrationPlugin) + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + list(APPEND plugins Qt5::QXcbIntegrationPlugin) + elseif(WIN32) + list(APPEND plugins Qt5::QWindowsIntegrationPlugin Qt5::QWindowsVistaStylePlugin) + elseif(APPLE) + list(APPEND plugins Qt5::QCocoaIntegrationPlugin Qt5::QMacStylePlugin) + endif() + qt5_import_plugins(${target} + INCLUDE ${plugins} + EXCLUDE_BY_TYPE imageformats iconengines + ) + endif() +endfunction() + +# For Qt-specific commands and variables, please consult: +# - https://cmake.org/cmake/help/latest/manual/cmake-qt.7.html +# - https://doc.qt.io/qt-5/cmake-manual.html + +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTOMOC_MOC_OPTIONS "-p${CMAKE_CURRENT_SOURCE_DIR}") +set(CMAKE_AUTORCC ON) +set(CMAKE_AUTOUIC ON) +set(CMAKE_AUTOUIC_SEARCH_PATHS forms) + +# TODO: The file(GLOB ...) command should be replaced with an explicit +# file list. Such a change must be synced with the corresponding change +# to https://github.com/bitcoin-core/bitcoin-maintainer-tools/blob/main/update-translations.py +file(GLOB ts_files RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} locale/*.ts) +set_source_files_properties(${ts_files} PROPERTIES OUTPUT_LOCATION ${CMAKE_CURRENT_BINARY_DIR}/locale) +qt5_add_translation(qm_files ${ts_files}) + +configure_file(bitcoin_locale.qrc bitcoin_locale.qrc USE_SOURCE_PERMISSIONS COPYONLY) + +# The firoqt sources have to include headers in +# order to parse them to collect translatable strings. +add_library(firoqt STATIC EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/bitcoin.qrc + ${CMAKE_CURRENT_BINARY_DIR}/bitcoin_locale.qrc + ${CMAKE_CURRENT_SOURCE_DIR}/addressbookpage.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/addresstablemodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/askpassphrasedialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/automintdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/automintmodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/automintnotification.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bantablemodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bitcoinaddressvalidator.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bitcoinamountfield.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bitcoingui.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bitcoinstrings.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bitcoinunits.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/cancelpassworddialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/clientmodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/coincontroldialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/coincontroltreewidget.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/csvmodelwriter.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/editaddressdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/guiutil.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/intro.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/manualmintdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/masternodelist.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/modaloverlay.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/networkstyle.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/notificator.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/notifymnemonic.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/openuridialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/optionsdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/optionsmodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/overviewpage.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/paymentserver.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/peertablemodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/platformstyle.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/qvalidatedlineedit.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/qvaluecombobox.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/receivecoinsdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/receiverequestdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/recentrequeststablemodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/recover.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpcconsole.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sendcoinsdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sendcoinsentry.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/signverifymessagedialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sparkmodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/splashscreen.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/trafficgraphwidget.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transactiondesc.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transactiondescdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transactionfilterproxy.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transactionrecord.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transactiontablemodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transactionview.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/utilitydialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/walletframe.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/walletmodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/walletmodeltransaction.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/walletview.cpp + $<$:${CMAKE_CURRENT_SOURCE_DIR}/macdockiconhandler.h> + $<$:${CMAKE_CURRENT_SOURCE_DIR}/macdockiconhandler.mm> + $<$:${CMAKE_CURRENT_SOURCE_DIR}/macnotificationhandler.h> + $<$:${CMAKE_CURRENT_SOURCE_DIR}/macnotificationhandler.mm> + $<$:${CMAKE_CURRENT_SOURCE_DIR}/winshutdownmonitor.cpp> + $<$:${CMAKE_CURRENT_SOURCE_DIR}/winshutdownmonitor.h> +) +target_compile_definitions(firoqt + PUBLIC + QT_NO_KEYWORDS + QT_USE_QSTRINGBUILDER +) +target_include_directories(firoqt + PUBLIC + $ + $ +) +set_property(SOURCE macnotificationhandler.mm + # Ignore warnings "'NSUserNotificationCenter' is deprecated: first deprecated in macOS 11.0". + APPEND PROPERTY COMPILE_OPTIONS -Wno-deprecated-declarations +) +# Add this to skip specific files from UIC processing +set_source_files_properties( + ${CMAKE_CURRENT_SOURCE_DIR}/clientmodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/clientmodel.h + PROPERTIES SKIP_AUTOUIC ON +) +target_link_libraries(firoqt + PUBLIC + leveldb + secp256k1 + univalue + secp256k1pp + Qt5::Widgets + Qt5::Network + PRIVATE + core_interface + firo_cli + firo_node + Boost::headers + $ + $<$:-framework\ AppKit> + Boost::thread + $ + $ + $ + ${TOR_LIBRARY} + $<$:firo_zmq> + $<$:windows_system> +) + +if(ENABLE_WALLET) + target_sources(firoqt + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/addressbookpage.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/automintdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/automintnotification.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/addresstablemodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/askpassphrasedialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/coincontroldialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/coincontroltreewidget.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/editaddressdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/exportviewkeydialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/manualmintdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/openuridialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/overviewpage.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/paymentserver.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/receivecoinsdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/receiverequestdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/recentrequeststablemodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sendcoinsdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sendcoinsentry.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/signverifymessagedialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transactiondesc.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transactiondescdialog.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transactionfilterproxy.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transactionrecord.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transactiontablemodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transactionview.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/walletframe.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/walletmodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/walletmodeltransaction.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/masternodelist.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/walletview.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/automintmodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sparkmodel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/createsparknamepage.cpp + ) + target_link_libraries(firoqt + PRIVATE + firo_wallet + Qt5::Network + ) +endif() + +if(WITH_DBUS AND NOT MINGW) + target_link_libraries(firoqt PRIVATE Qt5::DBus) +endif() + +if(qt_lib_type STREQUAL "STATIC_LIBRARY") + # We want to define static plugins to link ourselves, thus preventing + # automatic linking against a "sane" set of default static plugins. + qt5_import_plugins(firoqt + EXCLUDE_BY_TYPE bearer iconengines imageformats platforms styles + ) +endif() + +add_executable(firo-qt + ${CMAKE_CURRENT_SOURCE_DIR}/bitcoin.cpp +) + +add_windows_resources(firo-qt res/bitcoin-qt-res.rc) +target_link_libraries(firo-qt + PUBLIC + core_interface + firoqt + Qt5::Widgets + Qt5::Dependencies + firo_node + firo_cli + univalue + $ + $<$:firo_zmq> + Boost::thread + Boost::filesystem + Boost::thread + Boost::program_options + $ + $ + $ + ${TOR_LIBRARY} +) + +# Add macOS-specific frameworks +if(APPLE) + target_link_libraries(firo-qt PRIVATE + "-framework CoreVideo" + "-framework IOKit" + "-framework IOSurface" + "-framework ApplicationServices" + "-framework QuartzCore" + "-framework Security" + "-framework SystemConfiguration" + "-framework Metal" + "-framework Foundation" + "-framework AppKit" + "-framework Carbon" + ) +endif() + +apply_wrapped_exception_flags(firo-qt) +import_plugins(firo-qt) +set_platform_output_name(firo-qt FIRO_GUI_NAME) +list(APPEND installable_targets firo-qt) +set(installable_targets ${installable_targets} PARENT_SCOPE) +if(NOT WIN32) + install(FILES ${PROJECT_SOURCE_DIR}/doc/man/bitcoin-qt.1 + DESTINATION ${CMAKE_INSTALL_MANDIR}/man1 + RENAME firo-qt.1 + ) +endif() +if(WIN32) + set_target_properties(firo-qt PROPERTIES WIN32_EXECUTABLE TRUE) +endif() + +if(WITH_MULTIPROCESS) + add_executable(bitcoin-gui + ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp + ) + target_link_libraries(bitcoin-gui + core_interface + firoqt + firo_node + bitcoin_ipc + ) + import_plugins(bitcoin-gui) + install_binary_component(bitcoin-gui) + if(WIN32) + set_target_properties(bitcoin-gui PROPERTIES WIN32_EXECUTABLE TRUE) + endif() +endif() + +if(BUILD_GUI_TESTS AND NOT WIN32 AND NOT MINGW) + add_subdirectory(test) +else() + message(STATUS "Skipping GUI tests when cross-compiling for Windows") + if(BUILD_GUI_TESTS) + message(WARNING "BUILD_GUI_TESTS is enabled, but GUI tests are not supported when cross-compiling for Windows") + endif() +endif() + +# Gets sources to be parsed to gather translatable strings. +function(get_translatable_sources var) + set(result) + set(targets) + foreach(dir IN ITEMS ${ARGN}) + get_directory_property(dir_targets DIRECTORY ${PROJECT_SOURCE_DIR}/${dir} BUILDSYSTEM_TARGETS) + list(APPEND targets ${dir_targets}) + endforeach() + foreach(target IN LISTS targets) + get_target_property(target_sources ${target} SOURCES) + if(target_sources) + foreach(source IN LISTS target_sources) + # Get an expression from the generator expression, if any. + if(source MATCHES ":([^>]+)>$") + set(source ${CMAKE_MATCH_1}) + endif() + cmake_path(GET source EXTENSION LAST_ONLY ext) + if(ext STREQUAL ".qrc") + continue() + endif() + if(NOT IS_ABSOLUTE source) + get_target_property(target_source_dir ${target} SOURCE_DIR) + cmake_path(APPEND target_source_dir ${source} OUTPUT_VARIABLE source) + endif() + get_property(is_generated + SOURCE ${source} TARGET_DIRECTORY ${target} + PROPERTY GENERATED + ) + if(NOT is_generated) + list(APPEND result ${source}) + endif() + endforeach() + endif() + endforeach() + set(${var} ${result} PARENT_SCOPE) +endfunction() + +find_program(XGETTEXT_EXECUTABLE xgettext) +find_program(SED_EXECUTABLE sed) +if(NOT XGETTEXT_EXECUTABLE) + add_custom_target(translate + COMMAND ${CMAKE_COMMAND} -E echo "Error: GNU gettext-tools not found" + ) +elseif(NOT SED_EXECUTABLE) + add_custom_target(translate + COMMAND ${CMAKE_COMMAND} -E echo "Error: GNU sed not found" + ) +else() + set(translatable_sources_directories src src/qt) + if(ENABLE_WALLET) + list(APPEND translatable_sources_directories src/wallet) + endif() + get_translatable_sources(translatable_sources ${translatable_sources_directories}) + get_translatable_sources(qt_translatable_sources src/qt) + file(GLOB ui_files ${CMAKE_CURRENT_SOURCE_DIR}/forms/*.ui) + add_custom_target(translate + COMMAND ${CMAKE_COMMAND} -E env XGETTEXT=${XGETTEXT_EXECUTABLE} COPYRIGHT_HOLDERS=${COPYRIGHT_HOLDERS} ${Python3_EXECUTABLE} ${PROJECT_SOURCE_DIR}/share/qt/extract_strings_qt.py ${translatable_sources} + COMMAND Qt5::lupdate -no-obsolete -I ${PROJECT_SOURCE_DIR}/src -locations relative ${CMAKE_CURRENT_SOURCE_DIR}/bitcoinstrings.cpp ${ui_files} ${qt_translatable_sources} -ts ${CMAKE_CURRENT_SOURCE_DIR}/locale/bitcoin_en.ts + COMMAND Qt5::lconvert -drop-translations -o ${CMAKE_CURRENT_SOURCE_DIR}/locale/bitcoin_en.xlf -i ${CMAKE_CURRENT_SOURCE_DIR}/locale/bitcoin_en.ts + COMMAND ${SED_EXECUTABLE} -i.old -e "s|source-language=\"en\" target-language=\"en\"|source-language=\"en\"|" -e "/<\\/target>/d" ${CMAKE_CURRENT_SOURCE_DIR}/locale/bitcoin_en.xlf + COMMAND ${CMAKE_COMMAND} -E rm ${CMAKE_CURRENT_SOURCE_DIR}/locale/bitcoin_en.xlf.old + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/src + VERBATIM + ) +endif() diff --git a/src/qt/addressbookpage.cpp b/src/qt/addressbookpage.cpp index b0b8f94af1..18709b7b04 100644 --- a/src/qt/addressbookpage.cpp +++ b/src/qt/addressbookpage.cpp @@ -361,7 +361,7 @@ void AddressBookPage::on_exportButton_clicked() CSVModelWriter writer(filename); - QTableView *table; + FIRO_UNUSED QTableView *table; writer.setModel(proxyModel); if (ui->addressType->currentText() == AddressTableModel::Transparent) { writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); diff --git a/src/qt/addressbookpage.h b/src/qt/addressbookpage.h index e7d36e88e3..18ad864d9e 100644 --- a/src/qt/addressbookpage.h +++ b/src/qt/addressbookpage.h @@ -59,7 +59,7 @@ class AddressBookPage : public QDialog void updateSpark(); public Q_SLOTS: - void done(int retval); + void done(int retval) override; private: Ui::AddressBookPage *ui; @@ -118,7 +118,7 @@ class AddressBookFilterProxy : public QSortFilterProxyModel void setTypeFilter(quint32 modes); protected: - bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const; + bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const override; private: quint32 typeFilter; diff --git a/src/qt/addresstablemodel.cpp b/src/qt/addresstablemodel.cpp index 80a4cd3877..493967cc6e 100644 --- a/src/qt/addresstablemodel.cpp +++ b/src/qt/addresstablemodel.cpp @@ -12,6 +12,7 @@ #include "validation.h" #include "bip47/defs.h" #include "bip47/paymentchannel.h" +#include "../sparkname.h" #include @@ -826,7 +827,7 @@ QVariant PcodeAddressTableModel::data(const QModelIndex &index, int role) const return QVariant(); int const row = index.row(); - if(row >= pcodeData.size()) + if(cmp::greater_equal(row, pcodeData.size())) return QVariant(); if(role == Qt::DisplayRole || role == Qt::EditRole) @@ -856,7 +857,7 @@ bool PcodeAddressTableModel::setData(const QModelIndex &index, const QVariant &v if(!index.isValid()) return false; int const row = index.row(); - if(row >= pcodeData.size()) + if(cmp::greater_equal(row, pcodeData.size())) return false; if(role == Qt::EditRole) @@ -909,7 +910,7 @@ QVariant PcodeAddressTableModel::headerData(int section, Qt::Orientation orienta bool PcodeAddressTableModel::removeRows(int row, int count, const QModelIndex &) { - if(count != 1 || row >= pcodeData.size()) + if(count != 1 || cmp::greater_equal(row, pcodeData.size())) return false; wallet->LabelSendingPcode(pcodeData[row].first, "", true); diff --git a/src/qt/addresstablemodel.h b/src/qt/addresstablemodel.h index 59f8ab8b27..5ecfccd079 100644 --- a/src/qt/addresstablemodel.h +++ b/src/qt/addresstablemodel.h @@ -62,14 +62,14 @@ class AddressTableModel : public QAbstractTableModel /** @name Methods overridden from QAbstractTableModel @{*/ - int rowCount(const QModelIndex &parent) const; - int columnCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; - bool setData(const QModelIndex &index, const QVariant &value, int role); - QVariant headerData(int section, Qt::Orientation orientation, int role) const; - QModelIndex index(int row, int column, const QModelIndex &parent) const; - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); - Qt::ItemFlags flags(const QModelIndex &index) const; + int rowCount(const QModelIndex &parent) const override; + int columnCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role) const override; + bool setData(const QModelIndex &index, const QVariant &value, int role) override; + QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + QModelIndex index(int row, int column, const QModelIndex &parent) const override; + bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; + Qt::ItemFlags flags(const QModelIndex &index) const override; /*@}*/ /* Add an address to the model. @@ -130,13 +130,13 @@ class PcodeAddressTableModel : public AddressTableModel /** @name Methods overridden from QAbstractTableModel @{*/ - int rowCount(const QModelIndex &parent) const; - int columnCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; - bool setData(const QModelIndex &index, const QVariant &value, int role); - QVariant headerData(int section, Qt::Orientation orientation, int role) const; - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); - Qt::ItemFlags flags(const QModelIndex &index) const; + int rowCount(const QModelIndex &parent) const override; + int columnCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role) const override; + bool setData(const QModelIndex &index, const QVariant &value, int role) override; + QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; + Qt::ItemFlags flags(const QModelIndex &index) const override; /*@}*/ QString addRow(const QString &type, const QString &label, const QString &address, const QString &addressType) override; diff --git a/src/qt/askpassphrasedialog.h b/src/qt/askpassphrasedialog.h index 8656ba43ec..befdd5ad43 100644 --- a/src/qt/askpassphrasedialog.h +++ b/src/qt/askpassphrasedialog.h @@ -30,7 +30,7 @@ class AskPassphraseDialog : public QDialog explicit AskPassphraseDialog(Mode mode, QWidget *parent, const QString &info = ""); ~AskPassphraseDialog(); - void accept(); + void accept() override; void setModel(WalletModel *model); @@ -46,8 +46,8 @@ private Q_SLOTS: void secureClearPassFields(); protected: - bool event(QEvent *event); - bool eventFilter(QObject *object, QEvent *event); + bool event(QEvent *event) override; + bool eventFilter(QObject *object, QEvent *event) override; }; #endif // BITCOIN_QT_ASKPASSPHRASEDIALOG_H diff --git a/src/qt/automintdialog.cpp b/src/qt/automintdialog.cpp index 73ee1f80bf..ca48572e76 100644 --- a/src/qt/automintdialog.cpp +++ b/src/qt/automintdialog.cpp @@ -105,6 +105,8 @@ void AutoMintSparkDialog::reject() void AutoMintSparkDialog::setModel(WalletModel *model) { + LOCK(sparkModel->cs); + this->model = model; if (!this->model) { return; @@ -115,7 +117,7 @@ void AutoMintSparkDialog::setModel(WalletModel *model) return; } - ENTER_CRITICAL_SECTION(sparkModel->cs); + CCriticalSectionLocker criticalLocker(sparkModel->cs); if (this->model->getEncryptionStatus() != WalletModel::Locked) { ui->passLabel->setVisible(false); diff --git a/src/qt/automintdialog.h b/src/qt/automintdialog.h index 0d36080cab..8dca4d6a56 100644 --- a/src/qt/automintdialog.h +++ b/src/qt/automintdialog.h @@ -11,6 +11,17 @@ namespace Ui { class AutoMintDialog; } +class CCriticalSectionLocker { +public: + explicit CCriticalSectionLocker(CCriticalSection& mutex) : m_mutex(mutex) { ENTER_CRITICAL_SECTION(m_mutex); } + ~CCriticalSectionLocker() { LEAVE_CRITICAL_SECTION(m_mutex); } + CCriticalSectionLocker(const CCriticalSectionLocker&) = delete; + CCriticalSectionLocker& operator=(const CCriticalSectionLocker&) = delete; + +private: + CCriticalSection& m_mutex; +}; + enum class AutoMintSparkMode : uint8_t { MintAll, // come from overview page AutoMintAll // come from notification @@ -25,14 +36,14 @@ class AutoMintSparkDialog : public QDialog ~AutoMintSparkDialog(); public: - int exec(); + int exec() override; void setModel(WalletModel *model); void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; private Q_SLOTS: - void accept(); - void reject(); + void accept() override; + void reject() override; private: enum class AutoMintSparkProgress : uint8_t { diff --git a/src/qt/automintmodel.cpp b/src/qt/automintmodel.cpp index bb891e1dc3..cffd69ba60 100644 --- a/src/qt/automintmodel.cpp +++ b/src/qt/automintmodel.cpp @@ -19,7 +19,7 @@ IncomingFundNotifier::IncomingFundNotifier( connect(timer, &QTimer::timeout, this, &IncomingFundNotifier::check, Qt::QueuedConnection); - importTransactions(); + QMetaObject::invokeMethod(this, "importTransactions", Qt::QueuedConnection); subscribeToCoreSignals(); } @@ -34,9 +34,7 @@ IncomingFundNotifier::~IncomingFundNotifier() void IncomingFundNotifier::newBlock() { - TRY_LOCK(cs, lock); - if(!lock) - return; + LOCK(cs); if (!txs.empty()) { resetTimer(); @@ -45,10 +43,7 @@ void IncomingFundNotifier::newBlock() void IncomingFundNotifier::pushTransaction(uint256 const &id) { - TRY_LOCK(cs, lock); - if(!lock) - return; - + LOCK(cs); txs.push_back(id); resetTimer(); } @@ -115,16 +110,8 @@ void IncomingFundNotifier::check() void IncomingFundNotifier::importTransactions() { - TRY_LOCK(cs, lock); - if(!lock) - return; - - TRY_LOCK(cs_main,lock_main); - if (!lock_main) - return; - TRY_LOCK(wallet->cs_wallet,lock_wallet); - if (!lock_wallet) - return; + LOCK2(cs, cs_main); + LOCK(wallet->cs_wallet); for (auto const &tx : wallet->mapWallet) { if (tx.second.GetAvailableCredit() > 0 || tx.second.GetImmatureCredit() > 0) { diff --git a/src/qt/automintmodel.h b/src/qt/automintmodel.h index 128337299f..0ddb22ba50 100644 --- a/src/qt/automintmodel.h +++ b/src/qt/automintmodel.h @@ -2,7 +2,6 @@ #define FIRO_QT_AUTOMINTMODEL_H #include "../amount.h" -#include "../ui_interface.h" #include "../uint256.h" #include "../validation.h" @@ -27,13 +26,12 @@ public Q_SLOTS: void newBlock(); void pushTransaction(uint256 const &); void check(); + void importTransactions(); Q_SIGNALS: void matureFund(CAmount); private: - void importTransactions(); - void subscribeToCoreSignals(); void unsubscribeFromCoreSignals(); diff --git a/src/qt/automintnotification.h b/src/qt/automintnotification.h index c1aa87e8cb..d9bb59f7ba 100644 --- a/src/qt/automintnotification.h +++ b/src/qt/automintnotification.h @@ -29,8 +29,8 @@ public Q_SLOTS: bool close(); private Q_SLOTS: - void accept(); - void reject(); + void accept() override; + void reject() override; private: Ui::AutomintNotification *ui; diff --git a/src/qt/bantablemodel.h b/src/qt/bantablemodel.h index 062cfdc931..c490df9009 100644 --- a/src/qt/bantablemodel.h +++ b/src/qt/bantablemodel.h @@ -51,13 +51,13 @@ class BanTableModel : public QAbstractTableModel /** @name Methods overridden from QAbstractTableModel @{*/ - int rowCount(const QModelIndex &parent) const; - int columnCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role) const; - QModelIndex index(int row, int column, const QModelIndex &parent) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - void sort(int column, Qt::SortOrder order); + int rowCount(const QModelIndex &parent) const override; + int columnCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + QModelIndex index(int row, int column, const QModelIndex &parent) const override; + Qt::ItemFlags flags(const QModelIndex &index) const override; + void sort(int column, Qt::SortOrder order) override; bool shouldShow(); /*@}*/ diff --git a/src/qt/bitcoin.cpp b/src/qt/bitcoin.cpp index 7d387893e4..60f4a05474 100644 --- a/src/qt/bitcoin.cpp +++ b/src/qt/bitcoin.cpp @@ -31,7 +31,6 @@ #include "rpc/server.h" #include "scheduler.h" #include "stacktraces.h" -#include "ui_interface.h" #include "util.h" #include "warnings.h" @@ -517,7 +516,7 @@ void BitcoinApplication::initializeResult(int retval) window->addWallet(BitcoinGUI::DEFAULT_WALLET, walletModel); window->setCurrentWallet(BitcoinGUI::DEFAULT_WALLET); - + } #endif // If -min option passed, start window minimized. @@ -532,9 +531,10 @@ void BitcoinApplication::initializeResult(int retval) Q_EMIT splashFinished(window); #ifdef ENABLE_WALLET - if(newWallet) - NotifyMnemonic::notify(); - } + + if (pwalletMain) + if(newWallet) + NotifyMnemonic::notify(); // Now that initialization/startup is done, process any command-line // firo: URIs or payment requests: diff --git a/src/qt/bitcoinaddressvalidator.h b/src/qt/bitcoinaddressvalidator.h index 2a08e483e2..aac2648760 100644 --- a/src/qt/bitcoinaddressvalidator.h +++ b/src/qt/bitcoinaddressvalidator.h @@ -23,7 +23,7 @@ class BitcoinAddressEntryValidator : public QValidator public: explicit BitcoinAddressEntryValidator(QObject *parent); - State validate(QString &input, int &pos) const; + State validate(QString &input, int &pos) const override; }; /** Bitcoin address widget validator, checks for a valid bitcoin address. @@ -35,7 +35,7 @@ class BitcoinAddressCheckValidator : public QValidator public: explicit BitcoinAddressCheckValidator(QObject *parent); - State validate(QString &input, int &pos) const; + State validate(QString &input, int &pos) const override; bool validateSparkAddress(const std::string& address) const; }; diff --git a/src/qt/bitcoinamountfield.cpp b/src/qt/bitcoinamountfield.cpp index 0af10e7fd6..9abba8ef78 100644 --- a/src/qt/bitcoinamountfield.cpp +++ b/src/qt/bitcoinamountfield.cpp @@ -33,7 +33,7 @@ class AmountSpinBox: public QAbstractSpinBox connect(lineEdit(), &QLineEdit::textEdited, this, &AmountSpinBox::valueChanged); } - QValidator::State validate(QString &text, int &pos) const + QValidator::State validate(QString &text, int &pos) const override { if(text.isEmpty()) return QValidator::Intermediate; @@ -46,7 +46,7 @@ class AmountSpinBox: public QAbstractSpinBox return valid ? QValidator::Intermediate : QValidator::Invalid; } - void fixup(QString &input) const + void fixup(QString &input) const override { bool valid = false; CAmount val = parse(input, &valid); @@ -68,7 +68,7 @@ class AmountSpinBox: public QAbstractSpinBox Q_EMIT valueChanged(); } - void stepBy(int steps) + void stepBy(int steps) override { bool valid = false; CAmount val = value(&valid); @@ -95,7 +95,7 @@ class AmountSpinBox: public QAbstractSpinBox singleStep = step; } - QSize minimumSizeHint() const + QSize minimumSizeHint() const override { if(cachedMinimumSizeHint.isEmpty()) { @@ -153,7 +153,7 @@ class AmountSpinBox: public QAbstractSpinBox } protected: - bool event(QEvent *event) + bool event(QEvent *event) override { if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { @@ -168,7 +168,7 @@ class AmountSpinBox: public QAbstractSpinBox return QAbstractSpinBox::event(event); } - StepEnabled stepEnabled() const + StepEnabled stepEnabled() const override { if (isReadOnly()) // Disable steps when AmountSpinBox is read-only return StepNone; diff --git a/src/qt/bitcoinamountfield.h b/src/qt/bitcoinamountfield.h index 2f03a3d171..6a217de074 100644 --- a/src/qt/bitcoinamountfield.h +++ b/src/qt/bitcoinamountfield.h @@ -61,7 +61,7 @@ class BitcoinAmountField: public QWidget protected: /** Intercept focus-in event and ',' key presses */ - bool eventFilter(QObject *object, QEvent *event); + bool eventFilter(QObject *object, QEvent *event) override; private: AmountSpinBox *amount; diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp index d50b1ca851..f591055b07 100644 --- a/src/qt/bitcoingui.cpp +++ b/src/qt/bitcoingui.cpp @@ -34,7 +34,6 @@ #include "chainparams.h" #include "init.h" #include "lelantus.h" -#include "ui_interface.h" #include "util.h" #include "evo/deterministicmns.h" @@ -115,8 +114,8 @@ BitcoinGUI::BitcoinGUI(const PlatformStyle *_platformStyle, const NetworkStyle * toggleHideAction(0), encryptWalletAction(0), backupWalletAction(0), - changePassphraseAction(0), exportViewKeyAction(0), + changePassphraseAction(0), aboutQtAction(0), openRPCConsoleAction(0), openAction(0), @@ -1149,8 +1148,15 @@ void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmoun msg += tr("Label: %1\n").arg(label); else if (!address.isEmpty()) msg += tr("Address: %1\n").arg(address); - message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"), - msg, CClientUIInterface::MSG_INFORMATION); + + // Declare before lambda to ensure they're in scope + QString title = (amount < 0) ? tr("Sent transaction") : tr("Incoming transaction"); + QString finalMsg = msg; + + QMetaObject::invokeMethod(this, [this, title, finalMsg]() { + message(title, finalMsg, CClientUIInterface::MSG_INFORMATION); + }, Qt::QueuedConnection); + } #endif // ENABLE_WALLET diff --git a/src/qt/bitcoingui.h b/src/qt/bitcoingui.h index ba8965465a..933d0898cb 100644 --- a/src/qt/bitcoingui.h +++ b/src/qt/bitcoingui.h @@ -79,12 +79,12 @@ class BitcoinGUI : public QMainWindow bool enableWallet; protected: - void changeEvent(QEvent *e); - void closeEvent(QCloseEvent *event); - void showEvent(QShowEvent *event); - void dragEnterEvent(QDragEnterEvent *event); - void dropEvent(QDropEvent *event); - bool eventFilter(QObject *object, QEvent *event); + void changeEvent(QEvent *e) override; + void closeEvent(QCloseEvent *event) override; + void showEvent(QShowEvent *event) override; + void dragEnterEvent(QDragEnterEvent *event) override; + void dropEvent(QDropEvent *event) override; + bool eventFilter(QObject *object, QEvent *event) override; private: ClientModel *clientModel; @@ -146,7 +146,7 @@ class BitcoinGUI : public QMainWindow void createMenuBar(); /** Create the toolbars */ void createToolBars(); - void resizeEvent(QResizeEvent*); + void resizeEvent(QResizeEvent*) override; /** Create system tray icon and notification */ void createTrayIcon(const NetworkStyle *networkStyle); /** Create system tray menu (or setup the dock menu) */ @@ -199,7 +199,7 @@ public Q_SLOTS: void setEncryptionStatus(int status); /** Set the hd-enabled status as shown in the UI. - @param[in] status current hd enabled status + @param[in] hdEnabled current hd enabled status @see WalletModel::EncryptionStatus */ void setHDStatus(int hdEnabled); @@ -285,7 +285,7 @@ class UnitDisplayStatusBarControl : public QLabel protected: /** So that it responds to left-button clicks */ - void mousePressEvent(QMouseEvent *event); + void mousePressEvent(QMouseEvent *event) override; private: OptionsModel *optionsModel; diff --git a/src/qt/bitcoinunits.h b/src/qt/bitcoinunits.h index 6ef37de380..7223e39f48 100644 --- a/src/qt/bitcoinunits.h +++ b/src/qt/bitcoinunits.h @@ -103,8 +103,8 @@ class BitcoinUnits: public QAbstractListModel /** Unit identifier */ UnitRole = Qt::UserRole }; - int rowCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; + int rowCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role) const override; ///@} static QString removeSpaces(QString text) diff --git a/src/qt/cancelpassworddialog.h b/src/qt/cancelpassworddialog.h index fb12a45629..d919e2d0b0 100644 --- a/src/qt/cancelpassworddialog.h +++ b/src/qt/cancelpassworddialog.h @@ -11,7 +11,7 @@ class CancelPasswordDialog : public QMessageBox public: CancelPasswordDialog(const QString &title, const QString &text, int secDelay = 0, QWidget *parent = 0); - int exec(); + int exec() override; private Q_SLOTS: void countDown(); diff --git a/src/qt/clientmodel.cpp b/src/qt/clientmodel.cpp index e9643758ff..43b76673fc 100644 --- a/src/qt/clientmodel.cpp +++ b/src/qt/clientmodel.cpp @@ -15,7 +15,7 @@ #include "validation.h" #include "net.h" #include "txmempool.h" -#include "ui_interface.h" +#include "../ui_interface.h" #include "util.h" #include diff --git a/src/qt/coincontroldialog.h b/src/qt/coincontroldialog.h index 06c4104e26..f55d3931b3 100644 --- a/src/qt/coincontroldialog.h +++ b/src/qt/coincontroldialog.h @@ -35,7 +35,7 @@ class CCoinControlWidgetItem : public QTreeWidgetItem CCoinControlWidgetItem(int type = Type) : QTreeWidgetItem(type) {} CCoinControlWidgetItem(QTreeWidgetItem *parent, int type = Type) : QTreeWidgetItem(parent, type) {} - bool operator<(const QTreeWidgetItem &other) const; + bool operator<(const QTreeWidgetItem &other) const override; }; diff --git a/src/qt/coincontroltreewidget.h b/src/qt/coincontroltreewidget.h index 62645fcdb0..09059f9934 100644 --- a/src/qt/coincontroltreewidget.h +++ b/src/qt/coincontroltreewidget.h @@ -16,7 +16,7 @@ class CoinControlTreeWidget : public QTreeWidget explicit CoinControlTreeWidget(QWidget *parent = 0); protected: - virtual void keyPressEvent(QKeyEvent *event); + virtual void keyPressEvent(QKeyEvent *event) override; }; #endif // BITCOIN_QT_COINCONTROLTREEWIDGET_H diff --git a/src/qt/createsparknamepage.cpp b/src/qt/createsparknamepage.cpp index d71bcec2c4..3b9cd0543d 100644 --- a/src/qt/createsparknamepage.cpp +++ b/src/qt/createsparknamepage.cpp @@ -5,9 +5,11 @@ #include "createsparknamepage.h" #include "ui_createsparkname.h" #include "sendcoinsdialog.h" +#include "addresstablemodel.h" #include "platformstyle.h" #include "validation.h" +#include "compat_layer.h" #include #include @@ -34,6 +36,13 @@ CreateSparkNamePage::~CreateSparkNamePage() void CreateSparkNamePage::setModel(WalletModel *model) { this->model = model; + + connect(ui->sparkAddressEdit, &QLineEdit::textChanged, + this, &CreateSparkNamePage::checkSparkBalance, Qt::UniqueConnection); + connect(ui->sparkNameEdit, &QLineEdit::textChanged, + this, &CreateSparkNamePage::checkSparkBalance, Qt::UniqueConnection); + connect(ui->numberOfYearsEdit, qOverload(&QSpinBox::valueChanged), + this, &CreateSparkNamePage::checkSparkBalance, Qt::UniqueConnection); } void CreateSparkNamePage::on_generateButton_clicked() @@ -78,7 +87,7 @@ void CreateSparkNamePage::updateFee() { QString sparkName = ui->sparkNameEdit->text(); int numberOfYears = ui->numberOfYearsEdit->value(); - if (sparkName.isEmpty() || sparkName.length() > CSparkNameManager::maximumSparkNameLength || numberOfYears == 0 || numberOfYears > 10) + if (sparkName.isEmpty() || cmp::greater(sparkName.length(), CSparkNameManager::maximumSparkNameLength) || numberOfYears == 0 || numberOfYears > 10) ui->feeTextLabel->setText(feeText.arg("?")); else ui->feeTextLabel->setText(feeText.arg(QString::number(Params().GetConsensus().nSparkNamesFee[sparkName.length()]*numberOfYears))); @@ -109,7 +118,7 @@ bool CreateSparkNamePage::CreateSparkNameTransaction(const std::string &name, co assert(!name.empty() && name.length() <= CSparkNameManager::maximumSparkNameLength); CAmount sparkNameFee = consensusParams.nSparkNamesFee[name.length()]*COIN*numberOfYears; - CAmount txFee; + FIRO_UNUSED CAmount txFee; WalletModelTransaction tx = model->initSparkNameTransaction(sparkNameFee); @@ -143,6 +152,15 @@ bool CreateSparkNamePage::CreateSparkNameTransaction(const std::string &name, co QMessageBox::critical(this, tr("Error"), tr("Failed to send spark name transaction")); return false; } + + if (model->getEncryptionStatus() != WalletModel::Unencrypted) { + model->getAddressTableModel()->addRow( + AddressTableModel::Send, + QString::fromStdString(name), + "", + QString::fromStdString(address) + ); + } } catch (const std::exception &) { QMessageBox::critical(this, tr("Error"), tr("Failed to create spark name transaction")); @@ -152,3 +170,33 @@ bool CreateSparkNamePage::CreateSparkNameTransaction(const std::string &name, co return true; } +void CreateSparkNamePage::checkSparkBalance() +{ + if (!model) + return; + + QString sparkName = ui->sparkNameEdit->text(); + QString sparkAddress = ui->sparkAddressEdit->text(); + int numberOfYears = ui->numberOfYearsEdit->value(); + + if (sparkName.isEmpty() || + sparkName.length() > CSparkNameManager::maximumSparkNameLength || + !model->validateSparkAddress(sparkAddress)) { + ui->balanceWarningLabel->clear(); + ui->balanceWarningLabel->setVisible(false); + return; + } + + CAmount requiredFee = Params().GetConsensus().nSparkNamesFee[sparkName.length()] * COIN * numberOfYears; + CAmount available = model->getSparkBalance().first; + + if (available < requiredFee) { + ui->balanceWarningLabel->setText( + tr("⚠️ Not enough private funds to register this Spark name.") + ); + ui->balanceWarningLabel->setVisible(true); + } else { + ui->balanceWarningLabel->clear(); + ui->balanceWarningLabel->setVisible(false); + } +} diff --git a/src/qt/createsparknamepage.h b/src/qt/createsparknamepage.h index 80b8f6e67d..3c8ac4dc26 100644 --- a/src/qt/createsparknamepage.h +++ b/src/qt/createsparknamepage.h @@ -28,14 +28,14 @@ class CreateSparkNamePage : public QDialog void setModel(WalletModel *model); - void accept(); + void accept() override; private: Ui::CreateSparkNamePage *ui; WalletModel *model; bool CreateSparkNameTransaction(const std::string &name, const std::string &address, int numberOfYears, const std::string &additionalInfo); - + void checkSparkBalance(); void updateFee(); private Q_SLOTS: diff --git a/src/qt/editaddressdialog.h b/src/qt/editaddressdialog.h index 293dd3ea7b..cabe7ddf5d 100644 --- a/src/qt/editaddressdialog.h +++ b/src/qt/editaddressdialog.h @@ -48,7 +48,7 @@ class EditAddressDialog : public QDialog void setAddress(const QString &address); public Q_SLOTS: - void accept(); + void accept() override; private: bool saveCurrentRow(); diff --git a/src/qt/forms/createsparkname.ui b/src/qt/forms/createsparkname.ui index 0adc7f2efe..e2f0667e20 100644 --- a/src/qt/forms/createsparkname.ui +++ b/src/qt/forms/createsparkname.ui @@ -263,6 +263,39 @@ + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + false + + + color: orange; font-weight: bold; + + + true + + + + + diff --git a/src/qt/guiutil.h b/src/qt/guiutil.h index 88a783e4e8..a308ccc612 100644 --- a/src/qt/guiutil.h +++ b/src/qt/guiutil.h @@ -130,7 +130,7 @@ namespace GUIUtil explicit ToolTipToRichTextFilter(int size_threshold, QObject *parent = 0); protected: - bool eventFilter(QObject *obj, QEvent *evt); + bool eventFilter(QObject *obj, QEvent *evt) override; private: int size_threshold; @@ -172,7 +172,7 @@ namespace GUIUtil */ void clicked(const QPoint& point); protected: - void mouseReleaseEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event) override; }; class ClickableProgressBar : public QProgressBar @@ -185,7 +185,7 @@ namespace GUIUtil */ void clicked(const QPoint& point); protected: - void mouseReleaseEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event) override; }; #if defined(Q_OS_MAC) && QT_VERSION >= 0x050000 @@ -194,7 +194,7 @@ namespace GUIUtil // QProgressBar uses around 10% CPU even when app is in background class ProgressBar : public ClickableProgressBar { - bool event(QEvent *e) { + bool event(QEvent *e) override { return (e->type() != QEvent::StyleAnimationUpdate) ? QProgressBar::event(e) : false; } }; diff --git a/src/qt/modaloverlay.h b/src/qt/modaloverlay.h index d82983ea7d..53e9638451 100644 --- a/src/qt/modaloverlay.h +++ b/src/qt/modaloverlay.h @@ -36,8 +36,8 @@ public Q_SLOTS: bool isLayerVisible() { return layerIsVisible; } protected: - bool eventFilter(QObject * obj, QEvent * ev); - bool event(QEvent* ev); + bool eventFilter(QObject * obj, QEvent * ev) override; + bool event(QEvent* ev) override; private: Ui::ModalOverlay *ui; diff --git a/src/qt/openuridialog.h b/src/qt/openuridialog.h index 8438f22bd7..17674cd2b6 100644 --- a/src/qt/openuridialog.h +++ b/src/qt/openuridialog.h @@ -22,7 +22,7 @@ class OpenURIDialog : public QDialog QString getURI(); protected Q_SLOTS: - void accept(); + void accept() override; private: Ui::OpenURIDialog *ui; diff --git a/src/qt/optionsdialog.h b/src/qt/optionsdialog.h index 3169dac34e..5fa51599c7 100644 --- a/src/qt/optionsdialog.h +++ b/src/qt/optionsdialog.h @@ -28,7 +28,7 @@ class ProxyAddressValidator : public QValidator public: explicit ProxyAddressValidator(QObject *parent); - State validate(QString &input, int &pos) const; + State validate(QString &input, int &pos) const override; }; /** Preferences dialog. */ diff --git a/src/qt/optionsmodel.h b/src/qt/optionsmodel.h index 7d22dd2494..9130c53fd3 100644 --- a/src/qt/optionsmodel.h +++ b/src/qt/optionsmodel.h @@ -58,9 +58,9 @@ class OptionsModel : public QAbstractListModel void Init(bool resetSettings = false); void Reset(); - int rowCount(const QModelIndex & parent = QModelIndex()) const; - QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; - bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole); + int rowCount(const QModelIndex & parent = QModelIndex()) const override; + QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const override; + bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) override; /** Updates current unit in memory, settings and emits displayUnitChanged(newUnit) signal */ void setDisplayUnit(const QVariant &value); diff --git a/src/qt/overviewpage.cpp b/src/qt/overviewpage.cpp index 3e8fa406ac..efd47936ee 100644 --- a/src/qt/overviewpage.cpp +++ b/src/qt/overviewpage.cpp @@ -46,7 +46,7 @@ class TxViewDelegate : public QAbstractItemDelegate } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index ) const + const QModelIndex &index ) const override { painter->save(); @@ -110,7 +110,7 @@ class TxViewDelegate : public QAbstractItemDelegate painter->restore(); } - inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const + inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override { return QSize(DECORATION_SIZE, DECORATION_SIZE); } @@ -397,7 +397,7 @@ void OverviewPage::migrateClicked() { size_t confirmed, unconfirmed; auto privateBalance = walletModel->getWallet()->GetPrivateBalance(confirmed, unconfirmed); - auto lGracefulPeriod = ::Params().GetConsensus().nLelantusGracefulPeriod; + FIRO_UNUSED auto lGracefulPeriod = ::Params().GetConsensus().nLelantusGracefulPeriod; migrateAmount = "" + BitcoinUnits::formatHtmlWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), privateBalance.first); migrateAmount.append(""); QString info = tr("Your wallet needs to be unlocked to migrate your funds to Spark."); @@ -517,7 +517,7 @@ void OverviewPage::resizeEvent(QResizeEvent* event) ui->labelUnconfirmed->setFixedHeight(labelHeight); int buttonWidth = static_cast(newWidth * 0.15); - int buttonHeight = static_cast(newHeight * 0.05); + FIRO_UNUSED int buttonHeight = static_cast(newHeight * 0.05); int buttonMinHeight = static_cast(20); int buttonMaxHeight = static_cast(45); diff --git a/src/qt/paymentserver.cpp b/src/qt/paymentserver.cpp index 9bbd3e465b..724ffb0c0c 100644 --- a/src/qt/paymentserver.cpp +++ b/src/qt/paymentserver.cpp @@ -11,7 +11,6 @@ #include "base58.h" #include "chainparams.h" #include "policy/policy.h" -#include "ui_interface.h" #include "util.h" #include "wallet/wallet.h" diff --git a/src/qt/paymentserver.h b/src/qt/paymentserver.h index e96678e59d..50ecef2f36 100644 --- a/src/qt/paymentserver.h +++ b/src/qt/paymentserver.h @@ -92,7 +92,7 @@ private Q_SLOTS: protected: // Constructor registers this on the parent QApplication to // receive QEvent::FileOpen and QEvent:Drop events - bool eventFilter(QObject *object, QEvent *event); + bool eventFilter(QObject *object, QEvent *event) override; private: bool saveURIs; // true during startup diff --git a/src/qt/peertablemodel.h b/src/qt/peertablemodel.h index cc47b67ec9..642f3dfaae 100644 --- a/src/qt/peertablemodel.h +++ b/src/qt/peertablemodel.h @@ -61,13 +61,13 @@ class PeerTableModel : public QAbstractTableModel /** @name Methods overridden from QAbstractTableModel @{*/ - int rowCount(const QModelIndex &parent) const; - int columnCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role) const; - QModelIndex index(int row, int column, const QModelIndex &parent) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - void sort(int column, Qt::SortOrder order); + int rowCount(const QModelIndex &parent) const override; + int columnCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + QModelIndex index(int row, int column, const QModelIndex &parent) const override; + Qt::ItemFlags flags(const QModelIndex &index) const override; + void sort(int column, Qt::SortOrder order) override; /*@}*/ public Q_SLOTS: diff --git a/src/qt/qvalidatedlineedit.h b/src/qt/qvalidatedlineedit.h index 66734cc9d4..913790ee47 100644 --- a/src/qt/qvalidatedlineedit.h +++ b/src/qt/qvalidatedlineedit.h @@ -21,8 +21,8 @@ class QValidatedLineEdit : public QLineEdit bool isValid(); protected: - void focusInEvent(QFocusEvent *evt); - void focusOutEvent(QFocusEvent *evt); + void focusInEvent(QFocusEvent *evt) override; + void focusOutEvent(QFocusEvent *evt) override; private: bool valid; diff --git a/src/qt/receivecoinsdialog.cpp b/src/qt/receivecoinsdialog.cpp index a7ba5eabac..1fe56db1cc 100644 --- a/src/qt/receivecoinsdialog.cpp +++ b/src/qt/receivecoinsdialog.cpp @@ -138,7 +138,7 @@ void ReceiveCoinsDialog::clear() ui->reqLabel->setText(""); ui->reqMessage->setText(""); ui->reuseAddress->setChecked(false); - ui->createSparkNameButton->setVisible(false); + displayCheckBox(ui->addressTypeCombobox->currentIndex()); updateDisplayUnit(); } @@ -384,7 +384,7 @@ void ReceiveCoinsDialog::resizeEvent(QResizeEvent* event) // Set fixed, minimum, and maximum sizes for ComboBoxes int comboBoxMinHeight = 20; int comboBoxMaxHeight = 40; - int comboBoxWidth = newWidth * 0.08; + FIRO_UNUSED int comboBoxWidth = newWidth * 0.08; int comboBoxMinWidth = newWidth * 0.05; int comboBoxMaxWidth = newWidth * 0.1; @@ -401,7 +401,7 @@ void ReceiveCoinsDialog::resizeEvent(QResizeEvent* event) // Set sizes for buttons dynamically int buttonMinHeight = 20; int buttonMaxHeight = 35; - int buttonWidth = newWidth * 0.15; + FIRO_UNUSED int buttonWidth = newWidth * 0.15; int buttonMinWidth = newWidth * 0.1; int buttonMaxWidth = newWidth * 0.4; diff --git a/src/qt/receivecoinsdialog.h b/src/qt/receivecoinsdialog.h index 5d2ee4445c..ccb9e2fbb8 100644 --- a/src/qt/receivecoinsdialog.h +++ b/src/qt/receivecoinsdialog.h @@ -62,13 +62,13 @@ class ReceiveCoinsDialog : public QDialog void resizeEvent(QResizeEvent* event) override; public Q_SLOTS: void clear(); - void reject(); - void accept(); + void reject() override; + void accept() override; void chooseType(int idx); void displayCheckBox(int idx); protected: - virtual void keyPressEvent(QKeyEvent *event); + virtual void keyPressEvent(QKeyEvent *event) override; private: Ui::ReceiveCoinsDialog *ui; @@ -109,7 +109,7 @@ class RecentRequestsFilterProxy : public QSortFilterProxyModel void setTypeFilter(quint32 modes); protected: - bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const; + bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const override; private: quint32 typeFilter; diff --git a/src/qt/receiverequestdialog.h b/src/qt/receiverequestdialog.h index 8d785b7ec2..bb27a95f37 100644 --- a/src/qt/receiverequestdialog.h +++ b/src/qt/receiverequestdialog.h @@ -38,8 +38,8 @@ public Q_SLOTS: void copyImage(); protected: - virtual void mousePressEvent(QMouseEvent *event); - virtual void contextMenuEvent(QContextMenuEvent *event); + virtual void mousePressEvent(QMouseEvent *event) override; + virtual void contextMenuEvent(QContextMenuEvent *event) override; private: QMenu *contextMenu; diff --git a/src/qt/recentrequeststablemodel.cpp b/src/qt/recentrequeststablemodel.cpp index 0a4308f4e3..476983f188 100644 --- a/src/qt/recentrequeststablemodel.cpp +++ b/src/qt/recentrequeststablemodel.cpp @@ -11,6 +11,8 @@ #include "clientversion.h" #include "streams.h" +#include "../compat_layer.h" + #include const QString RecentRequestsTableModel::Transparent = "Transparent"; @@ -84,6 +86,7 @@ QVariant RecentRequestsTableModel::data(const QModelIndex &index, int role) cons { return tr("spark"); } + FIRO_FALLTHROUGH; case Message: if(rec->recipient.message.isEmpty() && role == Qt::DisplayRole) { @@ -137,7 +140,7 @@ void RecentRequestsTableModel::updateAmountColumnTitle() /** Gets title for amount column including current display unit if optionsModel reference available. */ QString RecentRequestsTableModel::getAmountTitle() { - return (this->walletModel->getOptionsModel() != NULL) ? tr("Requested") + " ("+BitcoinUnits::name(this->walletModel->getOptionsModel()->getDisplayUnit()) + ")" : ""; + return (this->walletModel->getOptionsModel() != NULL) ? tr("Requested") + " ("+BitcoinUnits::name(this->walletModel->getOptionsModel()->getDisplayUnit()) + ")" : QString(""); } QModelIndex RecentRequestsTableModel::index(int row, int column, const QModelIndex &parent) const diff --git a/src/qt/recentrequeststablemodel.h b/src/qt/recentrequeststablemodel.h index 26e4df5743..e3b1de6702 100644 --- a/src/qt/recentrequeststablemodel.h +++ b/src/qt/recentrequeststablemodel.h @@ -77,14 +77,14 @@ class RecentRequestsTableModel: public QAbstractTableModel /** @name Methods overridden from QAbstractTableModel @{*/ - int rowCount(const QModelIndex &parent) const; - int columnCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; - bool setData(const QModelIndex &index, const QVariant &value, int role); - QVariant headerData(int section, Qt::Orientation orientation, int role) const; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); - Qt::ItemFlags flags(const QModelIndex &index) const; + int rowCount(const QModelIndex &parent) const override; + int columnCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role) const override; + bool setData(const QModelIndex &index, const QVariant &value, int role) override; + QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; + bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; + Qt::ItemFlags flags(const QModelIndex &index) const override; /*@}*/ const RecentRequestEntry &entry(int row) const { return list[row]; } @@ -93,7 +93,7 @@ class RecentRequestsTableModel: public QAbstractTableModel void addNewRequest(RecentRequestEntry &recipient); public Q_SLOTS: - void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); + void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; void updateDisplayUnit(); private: diff --git a/src/qt/rpcconsole.cpp b/src/qt/rpcconsole.cpp index d0224aecaa..2c7bfe85fc 100644 --- a/src/qt/rpcconsole.cpp +++ b/src/qt/rpcconsole.cpp @@ -9,6 +9,8 @@ #include "rpcconsole.h" #include "ui_debugwindow.h" +#include "../compat_layer.h" + #include "bantablemodel.h" #include "clientmodel.h" #include "guiutil.h" @@ -117,8 +119,8 @@ class QtRPCTimerInterface: public RPCTimerInterface { public: ~QtRPCTimerInterface() {} - const char *Name() { return "Qt"; } - RPCTimerBase* NewTimer(boost::function& func, int64_t millis) + const char *Name() override { return "Qt"; } + RPCTimerBase* NewTimer(boost::function& func, int64_t millis) override { return new QtRPCTimerBase(func, millis); } @@ -140,7 +142,7 @@ class QtRPCTimerInterface: public RPCTimerInterface * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * - * @param[out] result stringified Result from the executed command(chain) + * @param[out] strResult stringified Result from the executed command(chain) * @param[in] strCommand Command line to split * @param[in] fExecute set true if you want the command to be executed * @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data @@ -201,7 +203,7 @@ bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string & char ch = strCommandTerminated[chpos]; switch(state) { - case STATE_COMMAND_EXECUTED_INNER: + case STATE_COMMAND_EXECUTED_INNER: FIRO_FALLTHROUGH; case STATE_COMMAND_EXECUTED: { bool breakParsing = true; @@ -264,10 +266,11 @@ bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string & } if (breakParsing) break; + FIRO_FALLTHROUGH; } - case STATE_ARGUMENT: // In or after argument - case STATE_EATING_SPACES_IN_ARG: - case STATE_EATING_SPACES_IN_BRACKETS: + case STATE_ARGUMENT: FIRO_FALLTHROUGH;// In or after argument + case STATE_EATING_SPACES_IN_ARG: FIRO_FALLTHROUGH; + case STATE_EATING_SPACES_IN_BRACKETS: FIRO_FALLTHROUGH; case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { @@ -370,7 +373,9 @@ bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string & strResult = lastResult.get_str(); else strResult = lastResult.write(2); + FIRO_FALLTHROUGH; case STATE_ARGUMENT: + FIRO_FALLTHROUGH; case STATE_EATING_SPACES: return true; default: // ERROR to end in one of the other states diff --git a/src/qt/rpcconsole.h b/src/qt/rpcconsole.h index 1e8894f717..de1c1d6251 100644 --- a/src/qt/rpcconsole.h +++ b/src/qt/rpcconsole.h @@ -59,8 +59,8 @@ class RPCConsole: public QWidget }; protected: - virtual bool eventFilter(QObject* obj, QEvent *event); - void keyPressEvent(QKeyEvent *); + virtual bool eventFilter(QObject* obj, QEvent *event) override; + void keyPressEvent(QKeyEvent *) override; private Q_SLOTS: void on_lineEdit_returnPressed(); @@ -71,9 +71,9 @@ private Q_SLOTS: void on_sldGraphRange_valueChanged(int value); /** update traffic statistics */ void updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut); - void resizeEvent(QResizeEvent *event); - void showEvent(QShowEvent *event); - void hideEvent(QHideEvent *event); + void resizeEvent(QResizeEvent *event) override; + void showEvent(QShowEvent *event) override; + void hideEvent(QHideEvent *event) override; /** Show custom context menu on Peers tab */ void showPeersTableContextMenu(const QPoint& point); /** Show custom context menu on Bans tab */ diff --git a/src/qt/sendcoinsdialog.cpp b/src/qt/sendcoinsdialog.cpp index bd5e509fbf..4d9b31eff7 100644 --- a/src/qt/sendcoinsdialog.cpp +++ b/src/qt/sendcoinsdialog.cpp @@ -3,6 +3,7 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsdialog.h" +#include "compat_layer.h" #include "ui_sendcoinsdialog.h" #include "addresstablemodel.h" @@ -20,7 +21,6 @@ #include "lelantus.h" #include "wallet/coincontrol.h" #include "validation.h" // mempool and minRelayTxFee -#include "ui_interface.h" #include "txmempool.h" #include "wallet/wallet.h" #include "overviewpage.h" @@ -539,7 +539,7 @@ void SendCoinsDialog::on_sendButton_clicked() } } - double txSize; + double txSize = 0.0; if ((fAnonymousMode == false) && (recipients.size() == sparkAddressCount) && spark::IsSparkAllowed()) { for (auto &transaction : transactions) { @@ -630,7 +630,7 @@ void SendCoinsDialog::on_sendButton_clicked() { for(int i = 0; i < ui->entries->count(); ++i) { - SendCoinsEntry *entry = qobject_cast(ui->entries->itemAt(i)->widget()); + FIRO_UNUSED SendCoinsEntry *entry = qobject_cast(ui->entries->itemAt(i)->widget()); } accept(); CoinControlDialog::coinControl->UnSelectAll(); diff --git a/src/qt/sendcoinsdialog.h b/src/qt/sendcoinsdialog.h index b117fafce9..f125391a14 100644 --- a/src/qt/sendcoinsdialog.h +++ b/src/qt/sendcoinsdialog.h @@ -50,8 +50,8 @@ class SendCoinsDialog : public QDialog public Q_SLOTS: void clear(); - void reject(); - void accept(); + void reject() override; + void accept() override; SendCoinsEntry *addEntry(); void updateBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool header); void updateTabsAndLabels(); @@ -117,7 +117,7 @@ class SendConfirmationDialog : public QMessageBox public: SendConfirmationDialog(const QString &title, const QString &text, int secDelay = 0, QWidget *parent = 0); - int exec(); + int exec() override; private Q_SLOTS: void countDown(); diff --git a/src/qt/sendcoinsentry.cpp b/src/qt/sendcoinsentry.cpp index 894f381c1e..4b7cab66bb 100644 --- a/src/qt/sendcoinsentry.cpp +++ b/src/qt/sendcoinsentry.cpp @@ -120,7 +120,9 @@ void SendCoinsEntry::on_payTo_textChanged(const QString &address) bool isSparkAddress = false; if (model) { - isSparkAddress = model->validateSparkAddress(address); + const QString payToText = ui->payTo->text(); + isSparkAddress = model->validateSparkAddress(address) || + (payToText.startsWith("@") && payToText.size() <= CSparkNameManager::maximumSparkNameLength + 1); } ui->messageLabel->setVisible(isSparkAddress); ui->messageTextLabel->setVisible(isSparkAddress); @@ -207,7 +209,7 @@ bool SendCoinsEntry::validate() isPcodeEntry = bip47::CPaymentCode::validate(ui->payTo->text().toStdString()); - if (ui->payTo->text().startsWith("@") && ui->payTo->text().size() <= CSparkNameManager::maximumSparkNameLength+1) { + if (ui->payTo->text().startsWith("@") && cmp::less_equal(ui->payTo->text().size(), CSparkNameManager::maximumSparkNameLength+1)) { ui->payTo->setValid(true); } else if (!(model->validateAddress(ui->payTo->text()) || model->validateSparkAddress(ui->payTo->text()) || isPcodeEntry)) diff --git a/src/qt/signverifymessagedialog.h b/src/qt/signverifymessagedialog.h index d2e04cd4fe..d33a2d038d 100644 --- a/src/qt/signverifymessagedialog.h +++ b/src/qt/signverifymessagedialog.h @@ -30,7 +30,7 @@ class SignVerifyMessageDialog : public QDialog void showTab_VM(bool fShow); protected: - bool eventFilter(QObject *object, QEvent *event); + bool eventFilter(QObject *object, QEvent *event) override; private: Ui::SignVerifyMessageDialog *ui; diff --git a/src/qt/sparkmodel.cpp b/src/qt/sparkmodel.cpp index 0311358ee5..acbdc19fea 100644 --- a/src/qt/sparkmodel.cpp +++ b/src/qt/sparkmodel.cpp @@ -62,7 +62,7 @@ AutoMintSparkModel* SparkModel::getAutoMintSparkModel() std::pair SparkModel::getSparkBalance() { - size_t confirmed, unconfirmed; + FIRO_UNUSED size_t confirmed, unconfirmed; return pwalletMain->GetSparkBalance(); } diff --git a/src/qt/splashscreen.cpp b/src/qt/splashscreen.cpp index 16a6ae820f..ee547bae38 100644 --- a/src/qt/splashscreen.cpp +++ b/src/qt/splashscreen.cpp @@ -13,7 +13,6 @@ #include "clientversion.h" #include "init.h" #include "util.h" -#include "ui_interface.h" #include "version.h" #ifdef ENABLE_WALLET @@ -29,12 +28,12 @@ SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : QSplashScreen(pixmap, f) { // set reference point, paddings - int paddingLeftCol2 = 232; - int paddingTopCol2 = 200; - int line1 = 0; - int line2 = 13; - int line3 = 26; - int line4 = 39; + FIRO_UNUSED int paddingLeftCol2 = 232; + FIRO_UNUSED int paddingTopCol2 = 200; + FIRO_UNUSED int line1 = 0; + FIRO_UNUSED int line2 = 13; + FIRO_UNUSED int line3 = 26; + FIRO_UNUSED int line4 = 39; float fontFactor = 1.0; diff --git a/src/qt/splashscreen.h b/src/qt/splashscreen.h index a11ff2ada7..1ab64c726b 100644 --- a/src/qt/splashscreen.h +++ b/src/qt/splashscreen.h @@ -26,8 +26,8 @@ class SplashScreen : public QSplashScreen // ~SplashScreen(); protected: - void paintEvent(QPaintEvent *event); - void closeEvent(QCloseEvent *event); + void paintEvent(QPaintEvent *event) override; + void closeEvent(QCloseEvent *event) override; public Q_SLOTS: /** Slot to call finish() method as it's not defined as slot */ diff --git a/src/qt/test/CMakeLists.txt b/src/qt/test/CMakeLists.txt new file mode 100644 index 0000000000..753ce6e935 --- /dev/null +++ b/src/qt/test/CMakeLists.txt @@ -0,0 +1,89 @@ +# Copyright (c) 2024-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +if(WIN32 OR MINGW) + message(FATAL_ERROR "The Qt tests are not supported on Windows") +endif() + +set(CMAKE_AUTOMOC_MOC_OPTIONS "-p${CMAKE_CURRENT_SOURCE_DIR}") + +add_executable(test_firo-qt + ${CMAKE_CURRENT_SOURCE_DIR}/compattests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpcnestedtests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test_main.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/uritests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test_sendcoinsentry.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../../test/test_bitcoin.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../../test/testutil.cpp +) + +# Add this to skip specific files from UIC processing +set_source_files_properties( + ${CMAKE_CURRENT_SOURCE_DIR}/../../test/test_bitcoin.cpp + PROPERTIES SKIP_AUTOUIC ON +) + +target_link_libraries(test_firo-qt + PRIVATE + core_interface + firoqt + firo_node + ${TOR_LIBRARY} + Boost::headers + Boost::unit_test_framework + Qt5::Test + Qt5::Dependencies + Qt5::Widgets + Boost::thread + $ + $ + $ + $<$:firo_zmq> + firo_cli + $ + $<$:windows_system> +) + +apply_wrapped_exception_flags(test_firo-qt) + +# Add macOS-specific frameworks +if(APPLE) + target_link_libraries(test_firo-qt PRIVATE + "-framework CoreVideo" + "-framework IOKit" + "-framework IOSurface" + "-framework ApplicationServices" + "-framework QuartzCore" + "-framework Security" + "-framework SystemConfiguration" + "-framework Metal" + "-framework Foundation" + "-framework AppKit" + "-framework Carbon" + ) +endif() + +import_plugins(test_firo-qt) + +if(ENABLE_WALLET) + target_sources(test_firo-qt + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/../../wallet/test/wallet_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../../wallet/test/wallet_test_fixture.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../../wallet/test/wallet_test_fixture.h + ) +endif() + +add_test(NAME test_firo-qt + COMMAND test_firo-qt +) +if(WIN32 AND VCPKG_TARGET_TRIPLET) + # On Windows, vcpkg configures Qt with `-opengl dynamic`, which makes + # the "minimal" platform plugin unusable due to internal Qt bugs. + set_tests_properties(test_firo-qt PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=windows" + ) +endif() + +list(APPEND installable_targets test_firo-qt) diff --git a/src/qt/test/test_main.cpp b/src/qt/test/test_main.cpp index ac8716a22a..716b49e889 100644 --- a/src/qt/test/test_main.cpp +++ b/src/qt/test/test_main.cpp @@ -41,7 +41,7 @@ int main(int argc, char *argv[]) // Don't remove this, it's needed to access // QCoreApplication:: in the tests QCoreApplication app(argc, argv); - app.setApplicationName("Bitcoin-Qt-test"); + app.setApplicationName("Firo-Qt-test"); SSL_library_init(); diff --git a/src/qt/trafficgraphwidget.h b/src/qt/trafficgraphwidget.h index 00660574af..1a3110de6e 100644 --- a/src/qt/trafficgraphwidget.h +++ b/src/qt/trafficgraphwidget.h @@ -25,7 +25,7 @@ class TrafficGraphWidget : public QWidget int getGraphRangeMins() const; protected: - void paintEvent(QPaintEvent *); + void paintEvent(QPaintEvent *) override; public Q_SLOTS: void updateRates(); diff --git a/src/qt/transactiondesc.cpp b/src/qt/transactiondesc.cpp index 956731d1ef..dd2bed0d50 100644 --- a/src/qt/transactiondesc.cpp +++ b/src/qt/transactiondesc.cpp @@ -43,13 +43,13 @@ QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx) else if (nDepth == 0) { if (wtx.InMempool()) { strTxStatus = "0/unconfirmed, in memory pool" + - (wtx.isAbandoned() ? ", "+tr("abandoned") : ""); + (wtx.isAbandoned() ? ", "+tr("abandoned") : QString("")); } else if (wtx.InStempool()) { strTxStatus = "0/unconfirmed, in dandelion stem pool"+ - (wtx.isAbandoned() ? ", "+tr("abandoned") : ""); + (wtx.isAbandoned() ? ", "+tr("abandoned") : QString("")); } else { strTxStatus = "0/unconfirmed, not in memory pool" + - (wtx.isAbandoned() ? ", "+tr("abandoned") : ""); + (wtx.isAbandoned() ? ", "+tr("abandoned") : QString("")); } } else if (nDepth < TransactionRecord::RecommendedNumConfirmations) diff --git a/src/qt/transactionfilterproxy.h b/src/qt/transactionfilterproxy.h index 53735fead3..0105d56f88 100644 --- a/src/qt/transactionfilterproxy.h +++ b/src/qt/transactionfilterproxy.h @@ -57,10 +57,10 @@ class TransactionFilterProxy : public QSortFilterProxyModel /** Set whether to show conflicted transactions. */ void setShowInactive(bool showInactive); - int rowCount(const QModelIndex &parent = QModelIndex()) const; + int rowCount(const QModelIndex &parent = QModelIndex()) const override; protected: - bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const; + bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const override; private: QDateTime dateFrom; diff --git a/src/qt/transactionrecord.cpp b/src/qt/transactionrecord.cpp index 1daa7ec600..c50b6ec72a 100644 --- a/src/qt/transactionrecord.cpp +++ b/src/qt/transactionrecord.cpp @@ -245,7 +245,7 @@ QList TransactionRecord::decomposeTransaction(const CWallet * parts.append(TransactionRecord(hash, nTime, TransactionRecord::MintSparkToSelf, "", -(nDebit - nChange), 0)); } else if (wtx.tx->IsSparkSpend()) { - CAmount fee; + CAmount fee = 0; try { spark::SpendTransaction spend = spark::ParseSparkSpend(*wtx.tx); fee = spend.getFee(); diff --git a/src/qt/transactiontablemodel.cpp b/src/qt/transactiontablemodel.cpp index f1d3157db7..540ad431a8 100644 --- a/src/qt/transactiontablemodel.cpp +++ b/src/qt/transactiontablemodel.cpp @@ -289,6 +289,11 @@ void TransactionTableModel::updateAmountColumnTitle() Q_EMIT headerDataChanged(Qt::Horizontal,Amount,Amount); } +void TransactionTableModel::refreshWallet() const +{ + priv->refreshWallet(); +} + void TransactionTableModel::updateTransaction(const QString &hash, int status, bool showTransaction) { uint256 updated; @@ -313,7 +318,7 @@ void TransactionTableModel::updateConfirmations() // Invalidate status (number of confirmations) and (possibly) description // for all rows. Qt is smart enough to only actually request the data for the // visible rows. - int numRows = std::min(300, priv->size()-1); + int numRows = std::min(100, priv->size()-1); Q_EMIT dataChanged(index(0, Status), index(numRows, Status)); Q_EMIT dataChanged(index(0, ToAddress), index(numRows, ToAddress)); } @@ -440,7 +445,13 @@ QString TransactionTableModel::lookupAddress(const TransactionRecord *wtx, bool } if(label.isEmpty() || tooltip) { - description += QString(" (") + QString::fromStdString(wtx->address) + QString(")"); + QString name = ""; + if (walletModel->GetSparkNameByAddress(QString::fromStdString(wtx->address), name)) + { + description += QString(" @") + name; + } else { + description += QString(" (") + QString::fromStdString(wtx->address) + QString(")"); + } } return description; } @@ -518,7 +529,7 @@ QString TransactionTableModel::formatTxToAddress(const TransactionRecord *wtx, b QString watchAddress; if (tooltip) { // Mark transactions involving watch-only addresses by adding " (watch-only)" - watchAddress = wtx->involvesWatchAddress ? QString(" (") + tr("watch-only") + QString(")") : ""; + watchAddress = wtx->involvesWatchAddress ? QString(" (") + tr("watch-only") + QString(")") : QString(""); } switch(wtx->type) @@ -908,8 +919,9 @@ static void NotifyTransactionChanged(TransactionTableModel *ttm, CWallet *wallet static void ShowProgress(TransactionTableModel *ttm, const std::string &title, int nProgress) { - if (nProgress == 0) + if (nProgress == 0) { fQueueNotifications = true; + } if (nProgress == 100) { @@ -924,6 +936,7 @@ static void ShowProgress(TransactionTableModel *ttm, const std::string &title, i vQueueNotifications[i].invoke(ttm); } std::vector().swap(vQueueNotifications); // clear + ttm->refreshWallet(); } } diff --git a/src/qt/transactiontablemodel.h b/src/qt/transactiontablemodel.h index d25a4acde3..2dc55d8461 100644 --- a/src/qt/transactiontablemodel.h +++ b/src/qt/transactiontablemodel.h @@ -81,16 +81,17 @@ class TransactionTableModel : public QAbstractTableModel PcodeRole }; - int rowCount(const QModelIndex &parent) const; - int columnCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role) const; - QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const; + int rowCount(const QModelIndex &parent) const override; + int columnCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const override; bool processingQueuedTransactions() { return fProcessingQueuedTransactions; } void updateNumISLocks(int numISLocks); void updateChainLockHeight(int chainLockHeight); int getNumISLocks() const; int getChainLockHeight() const; + void refreshWallet() const; private: CWallet* wallet; @@ -118,6 +119,7 @@ class TransactionTableModel : public QAbstractTableModel QVariant txInstantSendDecoration(const TransactionRecord *wtx) const; QVariant txAddressDecoration(const TransactionRecord *wtx) const; + public Q_SLOTS: /* New transaction, or transaction changed status */ void updateTransaction(const QString &hash, int status, bool showTransaction); diff --git a/src/qt/transactionview.cpp b/src/qt/transactionview.cpp index 05a6b95e00..2c56702b2a 100644 --- a/src/qt/transactionview.cpp +++ b/src/qt/transactionview.cpp @@ -17,7 +17,6 @@ #include "transactiontablemodel.h" #include "walletmodel.h" -#include "ui_interface.h" #include #include @@ -705,18 +704,18 @@ void TransactionView::resizeEvent(QResizeEvent* event) int headerHeight = newHeight * 0.1; // Calculate the height of widgets in the header subtracting a small margin - int widgetHeight = headerHeight - 5; + FIRO_UNUSED int widgetHeight = headerHeight - 5; // Determine widths for specific widgets as percentages of total width int comboBoxesWidgetWidth = newWidth * 0.10; - int addressWidgetWidth = newWidth * 0.25; + FIRO_UNUSED int addressWidgetWidth = newWidth * 0.25; dateWidget->setFixedWidth(comboBoxesWidgetWidth); typeWidget->setFixedWidth(comboBoxesWidgetWidth); amountWidget->setFixedWidth(comboBoxesWidgetWidth); instantsendWidget->setFixedWidth(comboBoxesWidgetWidth); - int tableViewHeight = newHeight - headerHeight; + FIRO_UNUSED int tableViewHeight = newHeight - headerHeight; // Calculate and set column widths based on new width, keeping proportions int statusColumnWidth = newWidth * 0.05; diff --git a/src/qt/transactionview.h b/src/qt/transactionview.h index 540e6252af..df166eda7b 100644 --- a/src/qt/transactionview.h +++ b/src/qt/transactionview.h @@ -90,7 +90,7 @@ class TransactionView : public QWidget QWidget *createDateRangeWidget(); void updateCalendarWidgets(); - bool eventFilter(QObject *obj, QEvent *event); + bool eventFilter(QObject *obj, QEvent *event) override; private Q_SLOTS: void contextualMenu(const QPoint &); diff --git a/src/qt/utilitydialog.h b/src/qt/utilitydialog.h index 086f707a44..60c60fe980 100644 --- a/src/qt/utilitydialog.h +++ b/src/qt/utilitydialog.h @@ -46,7 +46,7 @@ class ShutdownWindow : public QWidget static QWidget *showShutdownWindow(BitcoinGUI *window); protected: - void closeEvent(QCloseEvent *event); + void closeEvent(QCloseEvent *event) override; }; #endif // BITCOIN_QT_UTILITYDIALOG_H diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp index 085efd1c24..5a559668fc 100644 --- a/src/qt/walletmodel.cpp +++ b/src/qt/walletmodel.cpp @@ -18,7 +18,6 @@ #include "validation.h" #include "net.h" // for g_connman #include "sync.h" -#include "ui_interface.h" #include "util.h" // for GetBoolArg #include "wallet/wallet.h" #include "wallet/walletdb.h" // for BackupWallet @@ -141,12 +140,7 @@ void WalletModel::pollBalanceChanged() // Get required locks upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. - TRY_LOCK(cs_main, lockMain); - if(!lockMain) - return; - TRY_LOCK(wallet->cs_wallet, lockWallet); - if(!lockWallet) - return; + LOCK2(cs_main, wallet->cs_wallet); if(fForceCheckBalanceChanged || chainActive.Height() != cachedNumBlocks) { @@ -155,9 +149,9 @@ void WalletModel::pollBalanceChanged() // Balance and number of transactions might have changed cachedNumBlocks = chainActive.Height(); - checkBalanceChanged(); + QMetaObject::invokeMethod(this, "checkBalanceChanged", Qt::QueuedConnection); if(transactionTableModel) - transactionTableModel->updateConfirmations(); + QMetaObject::invokeMethod(transactionTableModel, "updateConfirmations", Qt::QueuedConnection); } } @@ -1315,6 +1309,16 @@ bool WalletModel::sparkNamesAllowed() const return chainHeight >= Params().GetConsensus().nSparkNamesStartBlock; } +bool WalletModel::GetSparkNameByAddress(const QString& sparkAddress, QString& name) +{ + LOCK(cs_main); + std::string name_ = name.toStdString(); + bool result = CSparkNameManager::GetInstance()->GetSparkNameByAddress(sparkAddress.toStdString(), name_); + if (result) + name = QString::fromStdString(name_); + return result; +} + bool WalletModel::validateSparkNameData(const QString &name, const QString &sparkAddress, const QString &additionalData, QString &strError) { CSparkNameTxData sparkNameData; @@ -1437,8 +1441,6 @@ WalletModel::SendCoinsReturn WalletModel::mintSparkCoins(std::vectorcs_wallet); - std::map::iterator mi = wallet->mapSparkAddressBook.find(strAddress); // Check if we have a new address or an updated label @@ -1484,8 +1486,6 @@ WalletModel::SendCoinsReturn WalletModel::spendSparkCoins(WalletModelTransaction CTxDestination dest = CBitcoinAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { - LOCK(wallet->cs_wallet); - if(validateAddress(rcp.address)) { std::map::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label diff --git a/src/qt/walletmodel.h b/src/qt/walletmodel.h index 05ea8d1b34..f072b0f658 100644 --- a/src/qt/walletmodel.h +++ b/src/qt/walletmodel.h @@ -186,7 +186,9 @@ class WalletModel : public QObject WalletModelTransaction &transaction); bool sparkNamesAllowed() const; - + + bool GetSparkNameByAddress(const QString& sparkAddress, QString& name); + bool validateSparkNameData(const QString &name, const QString &sparkAddress, const QString &additionalData, QString &strError); WalletModelTransaction initSparkNameTransaction(CAmount sparkNameFee); @@ -315,9 +317,6 @@ class WalletModel : public QObject void subscribeToCoreSignals(); void unsubscribeFromCoreSignals(); - void checkBalanceChanged(); - - Q_SIGNALS: // Signal that balance in wallet changed @@ -349,6 +348,8 @@ class WalletModel : public QObject void notifyWatchonlyChanged(bool fHaveWatchonly); public Q_SLOTS: + + void checkBalanceChanged(); /* Wallet status might have changed */ void updateStatus(); /* New transaction, or transaction changed status */ diff --git a/src/qt/walletview.cpp b/src/qt/walletview.cpp index 9f1ce0e98a..c809f19e64 100644 --- a/src/qt/walletview.cpp +++ b/src/qt/walletview.cpp @@ -23,7 +23,6 @@ #include "transactionview.h" #include "walletmodel.h" -#include "ui_interface.h" #include #include @@ -497,6 +496,8 @@ bool WalletView::eventFilter(QObject *watched, QEvent *event) case QEvent::Type::Move: repositionAutomintSparkNotification(); break; + default: + break; } return QStackedWidget::eventFilter(watched, event); diff --git a/src/qt/walletview.h b/src/qt/walletview.h index 99798f3e1e..7742b91989 100644 --- a/src/qt/walletview.h +++ b/src/qt/walletview.h @@ -62,7 +62,7 @@ class WalletView : public QStackedWidget void showOutOfSyncWarning(bool fShow); - bool eventFilter(QObject *watched, QEvent *event); + bool eventFilter(QObject *watched, QEvent *event) override; private: void setupTransactionPage(); diff --git a/src/qt/winshutdownmonitor.cpp b/src/qt/winshutdownmonitor.cpp index d6f40c38b8..859c1cb4b6 100644 --- a/src/qt/winshutdownmonitor.cpp +++ b/src/qt/winshutdownmonitor.cpp @@ -56,7 +56,8 @@ bool WinShutdownMonitor::nativeEventFilter(const QByteArray &eventType, void *pM void WinShutdownMonitor::registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId) { typedef BOOL (WINAPI *PSHUTDOWNBRCREATE)(HWND, LPCWSTR); - PSHUTDOWNBRCREATE shutdownBRCreate = (PSHUTDOWNBRCREATE)GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate"); + PSHUTDOWNBRCREATE shutdownBRCreate = reinterpret_cast( + reinterpret_cast(GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate"))); if (shutdownBRCreate == NULL) { qWarning() << "registerShutdownBlockReason: GetProcAddress for ShutdownBlockReasonCreate failed"; return; diff --git a/src/qt/winshutdownmonitor.h b/src/qt/winshutdownmonitor.h index 0bed55a2c6..080ddd0722 100644 --- a/src/qt/winshutdownmonitor.h +++ b/src/qt/winshutdownmonitor.h @@ -18,7 +18,7 @@ class WinShutdownMonitor : public QAbstractNativeEventFilter { public: /** Implements QAbstractNativeEventFilter interface for processing Windows messages */ - bool nativeEventFilter(const QByteArray &eventType, void *pMessage, long *pnResult); + bool nativeEventFilter(const QByteArray &eventType, void *pMessage, long *pnResult) override; /** Register the reason for blocking shutdown on Windows to allow clean client exit */ static void registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId); diff --git a/src/rest.cpp b/src/rest.cpp index e300bcbfda..410c4f21aa 100644 --- a/src/rest.cpp +++ b/src/rest.cpp @@ -16,6 +16,8 @@ #include "utilstrencodings.h" #include "version.h" +#include "compat_layer.h" + #include #include @@ -462,6 +464,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart) // convert hex to bin, continue then with bin part std::vector strRequestV = ParseHex(strRequestMutable); strRequestMutable.assign(strRequestV.begin(), strRequestV.end()); + FIRO_FALLTHROUGH; } case RF_BINARY: { diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 2d3e36c3e6..c4731d6dc9 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -8,6 +8,7 @@ #include "chainparams.h" #include "checkpoints.h" #include "coins.h" +#include "compat_layer.h" #include "core_io.h" #include "consensus/validation.h" #include "validation.h" @@ -210,7 +211,7 @@ UniValue getsparknamedata(const JSONRPCRequest& request) sparkNameManager->GetSparkAddress(sparkName, SparkAddr); UniValue result(UniValue::VOBJ); - unsigned char network = spark::GetNetworkType(); + FIRO_UNUSED unsigned char network = spark::GetNetworkType(); result.push_back(Pair("address", SparkAddr)); @@ -972,7 +973,7 @@ static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash, ss << hash; ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase); stats.nTransactions++; - for (const auto output : outputs) { + for (const auto& output : outputs) { ss << VARINT(output.first + 1); ss << *(const CScriptBase*)(&output.second.out.scriptPubKey); ss << VARINT(output.second.out.nValue); diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp index 28cb5f7684..f8066655da 100644 --- a/src/rpc/client.cpp +++ b/src/rpc/client.cpp @@ -16,9 +16,9 @@ class CRPCConvertParam { public: - std::string methodName; //!< method whose params want conversion - int paramIdx; //!< 0-based idx of param to convert - std::string paramName; //!< parameter name + std::string methodName {}; //!< method whose params want conversion + int paramIdx {}; //!< 0-based idx of param to convert + std::string paramName {}; //!< parameter name }; /** @@ -29,7 +29,7 @@ class CRPCConvertParam */ static const CRPCConvertParam vRPCConvertParams[] = { - { "stop", 0 }, + { "stop", 0, {} }, { "setmocktime", 0, "timestamp" }, { "getaddednodeinfo", 0 }, { "generate", 0, "nblocks" }, @@ -58,8 +58,8 @@ static const CRPCConvertParam vRPCConvertParams[] = { "getbalance", 2, "include_watchonly" }, { "getbalance", 3, "addlockconf" }, { "getblockhash", 0, "height" }, - { "move", 2 }, - { "move", 3 }, + { "move", 2, {} }, + { "move", 3, {} }, { "waitforblockheight", 0, "height" }, { "waitforblockheight", 1, "timeout" }, { "waitforblock", 1, "timeout" }, @@ -135,15 +135,15 @@ static const CRPCConvertParam vRPCConvertParams[] = { "getmempoolancestors", 1, "verbose" }, { "getmempooldescendants", 1, "verbose" }, { "bumpfee", 1, "options" }, - { "getblockhashes", 0 }, - { "getblockhashes", 1 }, - { "getspentinfo", 0}, - { "getaddresstxids", 0}, - { "getaddressbalance", 0}, - { "getAddressNumWBalance", 0}, - { "getaddressdeltas", 0}, - { "getaddressutxos", 0}, - { "getaddressmempool", 0}, + { "getblockhashes", 0, {} }, + { "getblockhashes", 1, {} }, + { "getspentinfo", 0, {} }, + { "getaddresstxids", 0, {} }, + { "getaddressbalance", 0, {} }, + { "getAddressNumWBalance", 0, {} }, + { "getaddressdeltas", 0, {} }, + { "getaddressutxos", 0, {} }, + { "getaddressmempool", 0, {} }, { "getspecialtxes", 1, "type" }, { "getspecialtxes", 2, "count" }, { "getspecialtxes", 3, "skip" }, @@ -160,53 +160,53 @@ static const CRPCConvertParam vRPCConvertParams[] = { "echojson", 8, "arg8" }, { "echojson", 9, "arg9" }, //[firo] - { "setmininput", 0 }, - { "mint", 0 }, - { "mintzerocoin", 0 }, - { "spendzerocoin", 0 }, - { "spendmanyzerocoin", 0 }, - { "spendmany", 1 }, - { "spendmany", 2 }, - { "spendmany", 4 }, - { "setgenerate", 0 }, - { "setgenerate", 1 }, - { "setmintzerocoinstatus", 2 }, - { "setmintzerocoinstatus", 1 }, - { "setsigmamintstatus", 1 }, - { "setlelantusmintstatus", 1 }, - { "listmintzerocoins", 0 }, - { "listsigmamints", 0 }, - { "listlelantusmints", 0 }, - { "listpubcoins", 0 }, - { "listsigmapubcoins", 0 }, - { "listspendzerocoins", 0 }, - { "listspendzerocoins", 1 }, - { "listsigmaspends", 0 }, - { "listsigmaspends", 1 }, - { "listlelantusjoinsplits", 0 }, - { "listlelantusjoinsplits", 1 }, - { "joinsplit", 0 }, - { "joinsplit", 1 }, - { "joinsplit", 2 }, - { "spendallzerocoin", 0 }, - { "remintzerocointosigma", 0 }, - { "getanonymityset", 0}, - { "getmintmetadata", 0 }, - { "getusedcoinserials", 0 }, - { "getlatestcoinids", 0 }, - { "getsparkmintmetadata", 0 }, - { "getmempooltxs", 0 }, + { "setmininput", 0, {} }, + { "mint", 0, {} }, + { "mintzerocoin", 0, {} }, + { "spendzerocoin", 0, {} }, + { "spendmanyzerocoin", 0, {} }, + { "spendmany", 1, {} }, + { "spendmany", 2, {} }, + { "spendmany", 4, {} }, + { "setgenerate", 0, {} }, + { "setgenerate", 1, {} }, + { "setmintzerocoinstatus", 2, {} }, + { "setmintzerocoinstatus", 1, {} }, + { "setsigmamintstatus", 1, {} }, + { "setlelantusmintstatus", 1, {} }, + { "listmintzerocoins", 0, {} }, + { "listsigmamints", 0, {} }, + { "listlelantusmints", 0, {} }, + { "listpubcoins", 0, {} }, + { "listsigmapubcoins", 0, {} }, + { "listspendzerocoins", 0, {} }, + { "listspendzerocoins", 1, {} }, + { "listsigmaspends", 0, {} }, + { "listsigmaspends", 1, {} }, + { "listlelantusjoinsplits", 0, {} }, + { "listlelantusjoinsplits", 1, {} }, + { "joinsplit", 0, {} }, + { "joinsplit", 1, {} }, + { "joinsplit", 2, {} }, + { "spendallzerocoin", 0, {} }, + { "remintzerocointosigma", 0, {} }, + { "getanonymityset", 0, {} }, + { "getmintmetadata", 0, {} }, + { "getusedcoinserials", 0, {} }, + { "getlatestcoinids", 0, {} }, + { "getsparkmintmetadata", 0, {} }, + { "getmempooltxs", 0, {} }, //Lelantus - { "mintspark", 0 }, - { "mintspark", 1 }, - { "mintspark", 2 }, - { "spendspark", 0 }, - { "spendspark", 1 }, + { "mintspark", 0, {} }, + { "mintspark", 1, {} }, + { "mintspark", 2, {} }, + { "spendspark", 0, {} }, + { "spendspark", 1, {} }, // Spark names - { "registersparkname", 2 }, - { "getsparknames", 0 }, + { "registersparkname", 2, {} }, + { "getsparknames", 0, {} }, /* Evo spork */ { "spork", 2, "features"}, diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 637a079cfb..1823c508ea 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -26,6 +26,8 @@ #include "utilstrencodings.h" #include "validationinterface.h" +#include "../compat_layer.h" + #include "masternode-payments.h" #include "masternode-sync.h" @@ -507,8 +509,8 @@ UniValue getblocktemplate(const JSONRPCRequest& request) int64_t nMaxVersionPreVB = -1; if (request.params.size() > 0) { - const UniValue& oparam = request.params[0].get_obj(); - const UniValue& modeval = find_value(oparam, "mode"); + const auto oparam = request.params[0].get_obj(); + const auto modeval = find_value(oparam, "mode"); if (modeval.isStr()) strMode = modeval.get_str(); else if (modeval.isNull()) @@ -521,7 +523,7 @@ UniValue getblocktemplate(const JSONRPCRequest& request) if (strMode == "proposal") { - const UniValue& dataval = find_value(oparam, "data"); + const auto dataval = find_value(oparam, "data"); if (!dataval.isStr()) throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal"); @@ -549,15 +551,15 @@ UniValue getblocktemplate(const JSONRPCRequest& request) return BIP22ValidationResult(state); } - const UniValue& aClientRules = find_value(oparam, "rules"); + const auto aClientRules = find_value(oparam, "rules"); if (aClientRules.isArray()) { for (unsigned int i = 0; i < aClientRules.size(); ++i) { - const UniValue& v = aClientRules[i]; + const auto v = aClientRules[i]; setClientRules.insert(v.get_str()); } } else { // NOTE: It is important that this NOT be read if versionbits is supported - const UniValue& uvMaxVersion = find_value(oparam, "maxversion"); + const auto uvMaxVersion = find_value(oparam, "maxversion"); if (uvMaxVersion.isNum()) { nMaxVersionPreVB = uvMaxVersion.get_int64(); } @@ -760,6 +762,7 @@ UniValue getblocktemplate(const JSONRPCRequest& request) // Ensure bit is set in block version pblock->nVersion |= VersionBitsMask(consensusParams, pos); // FALL THROUGH to get vbavailable set... + FIRO_FALLTHROUGH; case THRESHOLD_STARTED: { const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; @@ -886,7 +889,7 @@ class submitblock_StateCatcher : public CValidationInterface submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {} protected: - virtual void BlockChecked(const CBlock& block, const CValidationState& stateIn) { + virtual void BlockChecked(const CBlock& block, const CValidationState& stateIn) override { if (block.GetHash() != hash) return; found = true; @@ -1217,7 +1220,7 @@ static const CRPCCommand commands[] = { "mining", "pprpcsb", &pprpcsb, true, {"header_hash","mix_hash", "nonce"} }, { "mining", "submitblock", &submitblock, true, {"hexdata","parameters"} }, - { "generating", "setgenerate", &setgenerate, true }, + { "generating", "setgenerate", &setgenerate, true, {} }, { "generating", "generate", &generate, true, {"nblocks","maxtries"} }, { "generating", "generatetoaddress", &generatetoaddress, true, {"nblocks","address","maxtries"} }, diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp index 23e05ba435..3ba33efecb 100644 --- a/src/rpc/misc.cpp +++ b/src/rpc/misc.cpp @@ -1082,7 +1082,7 @@ UniValue getanonymityset(const JSONRPCRequest& request) UniValue ret(UniValue::VOBJ); UniValue mints(UniValue::VARR); - int i = 0; + FIRO_UNUSED int i = 0; for (const auto& coin : coins) { std::vector vch = coin.first.getValue().getvch(); std::vector data; @@ -1187,7 +1187,7 @@ UniValue getusedcoinserials(const JSONRPCRequest& request) UniValue serializedSerials(UniValue::VARR); int i = 0; for ( auto it = serials.begin(); it != serials.end(); ++it, ++i) { - if ((serials.size() - i - 1) < startNumber) + if (cmp::less((serials.size() - i - 1), startNumber)) continue; std::vector serialized; serialized.resize(32); @@ -1550,7 +1550,7 @@ UniValue getusedcoinstags(const JSONRPCRequest& request) UniValue serializedTags(UniValue::VARR); int i = 0; for ( auto it = tags.begin(); it != tags.end(); ++it, ++i) { - if ((tags.size() - i - 1) < startNumber) + if (cmp::less((tags.size() - i - 1), startNumber)) continue; std::vector serialized; serialized.resize(34); @@ -1598,7 +1598,7 @@ UniValue getusedcoinstagstxhashes(const JSONRPCRequest& request) UniValue serializedTagsTxIds(UniValue::VARR); int i = 0; for ( auto it = tags.begin(); it != tags.end(); ++it, ++i) { - if ((tags.size() - i - 1) < startNumber) + if (cmp::less((tags.size() - i - 1), startNumber)) continue; std::vector serialized; serialized.resize(34); @@ -2237,56 +2237,56 @@ UniValue echo(const JSONRPCRequest& request) } static const CRPCCommand commands[] = -{ // category name actor (function) okSafeMode - // --------------------- ------------------------ ----------------------- ---------- - { "control", "getinfo", &getinfo, true, {} }, /* uses wallet if enabled */ - { "control", "getmemoryinfo", &getmemoryinfo, true, {} }, - { "util", "validateaddress", &validateaddress, true, {"address"} }, /* uses wallet if enabled */ - { "util", "createmultisig", &createmultisig, true, {"nrequired","keys"} }, - { "util", "verifymessage", &verifymessage, true, {"address","signature","message"} }, - { "util", "signmessagewithprivkey", &signmessagewithprivkey, true, {"privkey","message"} }, +{ // category name actor (function) okSafeMode ArgNames + // --------------------- ------------------------ ----------------------- ---------- --------- + { "control", "getinfo", &getinfo, true, {} }, /* uses wallet if enabled */ + { "control", "getmemoryinfo", &getmemoryinfo, true, {} }, + { "util", "validateaddress", &validateaddress, true, {"address"} }, /* uses wallet if enabled */ + { "util", "createmultisig", &createmultisig, true, {"nrequired","keys"} }, + { "util", "verifymessage", &verifymessage, true, {"address","signature","message"} }, + { "util", "signmessagewithprivkey", &signmessagewithprivkey, true, {"privkey","message"} }, /* Address index */ - { "addressindex", "getaddressmempool", &getaddressmempool, true }, - { "addressindex", "getaddressutxos", &getaddressutxos, false }, - { "addressindex", "getaddressdeltas", &getaddressdeltas, false }, - { "addressindex", "getaddresstxids", &getaddresstxids, false }, - { "addressindex", "getaddressbalance", &getaddressbalance, false }, + { "addressindex", "getaddressmempool", &getaddressmempool, true, {} }, + { "addressindex", "getaddressutxos", &getaddressutxos, false, {} }, + { "addressindex", "getaddressdeltas", &getaddressdeltas, false, {} }, + { "addressindex", "getaddresstxids", &getaddresstxids, false, {} }, + { "addressindex", "getaddressbalance", &getaddressbalance, false, {} }, /* Znode features */ - { "firo", "znsync", &mnsync, true, {} }, - { "firo", "evoznsync", &mnsync, true, {} }, + { "firo", "znsync", &mnsync, true, {} }, + { "firo", "evoznsync", &mnsync, true, {} }, - { "firo", "verifyprivatetxown", &verifyprivatetxown, true, {} }, + { "firo", "verifyprivatetxown", &verifyprivatetxown, true, {} }, /* Not shown in help */ - { "hidden", "getinfoex", &getinfoex, false }, - { "addressindex", "gettotalsupply", &gettotalsupply, false }, - { "addressindex", "getzerocoinpoolbalance", &getzerocoinpoolbalance, false }, - { "addressindex", "getCVE17144amount", &getCVE17144amount, false }, + { "hidden", "getinfoex", &getinfoex, false, {} }, + { "addressindex", "gettotalsupply", &gettotalsupply, false, {} }, + { "addressindex", "getzerocoinpoolbalance", &getzerocoinpoolbalance, false, {} }, + { "addressindex", "getCVE17144amount", &getCVE17144amount, false, {} }, /* Mobile related */ - { "mobile", "getanonymityset", &getanonymityset, false }, - { "mobile", "getmintmetadata", &getmintmetadata, true }, - { "mobile", "getusedcoinserials", &getusedcoinserials, false }, - { "mobile", "getfeerate", &getfeerate, true }, - { "mobile", "getlatestcoinid", &getlatestcoinid, true }, + { "mobile", "getanonymityset", &getanonymityset, false, {} }, + { "mobile", "getmintmetadata", &getmintmetadata, true, {} }, + { "mobile", "getusedcoinserials", &getusedcoinserials, false, {} }, + { "mobile", "getfeerate", &getfeerate, true, {} }, + { "mobile", "getlatestcoinid", &getlatestcoinid, true, {} }, /* Mobile Spark */ - { "mobile", "getsparkanonymityset", &getsparkanonymityset, false }, - { "mobile", "getsparkanonymitysetmeta", &getsparkanonymitysetmeta, false }, - { "mobile", "getsparkanonymitysetsector", &getsparkanonymitysetsector, false }, - { "mobile", "getsparkmintmetadata", &getsparkmintmetadata, true }, - { "mobile", "getusedcoinstags", &getusedcoinstags, false }, - { "mobile", "getusedcoinstagstxhashes", &getusedcoinstagstxhashes, false }, - { "mobile", "getsparklatestcoinid", &getsparklatestcoinid, true }, - { "mobile", "getmempoolsparktxids", &getmempoolsparktxids, true }, - { "mobile", "getmempoolsparktxs", &getmempoolsparktxs, true }, - - { "mobile", "checkifmncollateral", &checkifmncollateral, false }, - - { "hidden", "setmocktime", &setmocktime, true, {"timestamp"}}, - { "hidden", "echo", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}}, - { "hidden", "echojson", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}}, + { "mobile", "getsparkanonymityset", &getsparkanonymityset, false, {} }, + { "mobile", "getsparkanonymitysetmeta", &getsparkanonymitysetmeta, false, {} }, + { "mobile", "getsparkanonymitysetsector", &getsparkanonymitysetsector, false,{} }, + { "mobile", "getsparkmintmetadata", &getsparkmintmetadata, true, {} }, + { "mobile", "getusedcoinstags", &getusedcoinstags, false, {} }, + { "mobile", "getusedcoinstagstxhashes", &getusedcoinstagstxhashes, false, {} }, + { "mobile", "getsparklatestcoinid", &getsparklatestcoinid, true, {} }, + { "mobile", "getmempoolsparktxids", &getmempoolsparktxids, true, {} }, + { "mobile", "getmempoolsparktxs", &getmempoolsparktxs, true, {} }, + + { "mobile", "checkifmncollateral", &checkifmncollateral, false, {} }, + + { "hidden", "setmocktime", &setmocktime, true, {"timestamp"} }, + { "hidden", "echo", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"} }, + { "hidden", "echojson", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"} }, }; void RegisterMiscRPCCommands(CRPCTable &t) diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index c2fe430098..9e4d0c424d 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -549,12 +549,12 @@ UniValue createrawtransaction(const JSONRPCRequest& request) } for (unsigned int idx = 0; idx < inputs.size(); idx++) { - const UniValue& input = inputs[idx]; - const UniValue& o = input.get_obj(); + const auto input = inputs[idx]; + const auto o = input.get_obj(); uint256 txid = ParseHashO(o, "txid"); - const UniValue& vout_v = find_value(o, "vout"); + const auto vout_v = find_value(o, "vout"); if (!vout_v.isNum()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); @@ -564,13 +564,13 @@ UniValue createrawtransaction(const JSONRPCRequest& request) uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits::max() - 1 : std::numeric_limits::max()); // set the sequence number if passed in the parameters object - const UniValue& sequenceObj = find_value(o, "sequence"); + const auto sequenceObj = find_value(o, "sequence"); if (sequenceObj.isNum()) { int64_t seqNr64 = sequenceObj.get_int64(); if (seqNr64 < 0 || seqNr64 > std::numeric_limits::max()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range"); else - nSequence = (uint32_t)seqNr64; + nSequence = static_cast(seqNr64); } CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence); diff --git a/src/rpc/rpcevo.cpp b/src/rpc/rpcevo.cpp index 6037b4835f..550cce60e6 100644 --- a/src/rpc/rpcevo.cpp +++ b/src/rpc/rpcevo.cpp @@ -946,8 +946,6 @@ UniValue protx_list(const JSONRPCRequest& request) UniValue ret(UniValue::VARR); - LOCK(cs_main); - if (type == "wallet") { if (!pwallet) { throw std::runtime_error("\"protx list wallet\" not supported when wallet is disabled"); @@ -1316,7 +1314,7 @@ UniValue spork(const JSONRPCRequest& request) UniValue sporkEnableOrDisableObj = request.params[2].get_obj(); std::vector enableOrDisableKeys = sporkEnableOrDisableObj.getKeys(); - for (const std::string enableOrDisable: enableOrDisableKeys) { + for (const std::string& enableOrDisable: enableOrDisableKeys) { if (enableOrDisable == "enable") { UniValue featuresToEnable = sporkEnableOrDisableObj["enable"]; diff --git a/src/rpc/rpcquorums.cpp b/src/rpc/rpcquorums.cpp index 2752cce224..29b69748b5 100644 --- a/src/rpc/rpcquorums.cpp +++ b/src/rpc/rpcquorums.cpp @@ -123,7 +123,7 @@ UniValue quorum_info(const JSONRPCRequest& request) throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid LLMQ type"); } - const auto& llmqParams = Params().GetConsensus().llmqs.at(llmqType); + FIRO_UNUSED const auto& llmqParams = Params().GetConsensus().llmqs.at(llmqType); uint256 quorumHash = ParseHashV(request.params[2], "quorumHash"); bool includeSkShare = false; diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index e2f4286c7b..20512ecff8 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -320,39 +320,39 @@ UniValue stop(const JSONRPCRequest& jsonRequest) * Call Table */ static const CRPCCommand vRPCCommands[] = -{ // category name actor (function) okSafe argNames - // --------------------- ------------------------ ----------------------- ------ ---------- +{ // category name actor (function) okSafe argNames + // --------------------- ------------------------ ----------------------- ------ ---------- /* Overall control/query calls */ - { "control", "help", &help, true }, - { "control", "stop", &stop, true }, + { "control", "help", &help, true, {} }, + { "control", "stop", &stop, true, {} }, /* Address index */ - { "addressindex", "getaddressmempool", &getaddressmempool, true }, - { "addressindex", "getaddressutxos", &getaddressutxos, false }, - { "addressindex", "getaddressdeltas", &getaddressdeltas, false }, - { "addressindex", "getaddresstxids", &getaddresstxids, false }, - { "addressindex", "getaddressbalance", &getaddressbalance, false }, - { "addressindex", "getAddressNumWBalance", &getAddressNumWBalance, false }, + { "addressindex", "getaddressmempool", &getaddressmempool, true, {} }, + { "addressindex", "getaddressutxos", &getaddressutxos, false, {} }, + { "addressindex", "getaddressdeltas", &getaddressdeltas, false, {} }, + { "addressindex", "getaddresstxids", &getaddresstxids, false, {} }, + { "addressindex", "getaddressbalance", &getaddressbalance, false, {} }, + { "addressindex", "getAddressNumWBalance", &getAddressNumWBalance, false, {} }, /* Mobile related */ - { "mobile", "getanonymityset", &getanonymityset, false }, - { "mobile", "getmintmetadata", &getmintmetadata, true }, - { "mobile", "getusedcoinserials", &getusedcoinserials, false }, - { "mobile", "getfeerate", &getfeerate, true }, - { "mobile", "getlatestcoinid", &getlatestcoinid, true }, + { "mobile", "getanonymityset", &getanonymityset, false, {} }, + { "mobile", "getmintmetadata", &getmintmetadata, true, {} }, + { "mobile", "getusedcoinserials", &getusedcoinserials, false, {} }, + { "mobile", "getfeerate", &getfeerate, true, {} }, + { "mobile", "getlatestcoinid", &getlatestcoinid, true, {} }, /* Mobile Spark */ - { "mobile", "getsparkanonymityset", &getsparkanonymityset, false }, - { "mobile", "getsparkanonymitysetmeta", &getsparkanonymitysetmeta, false }, - { "mobile", "getsparkanonymitysetsector", &getsparkanonymitysetsector, false }, - { "mobile", "getsparkmintmetadata", &getsparkmintmetadata, true }, - { "mobile", "getusedcoinstags", &getusedcoinstags, false }, - { "mobile", "getusedcoinstagstxhashes", &getusedcoinstagstxhashes, false }, - { "mobile", "getsparklatestcoinid", &getsparklatestcoinid, true }, - { "mobile", "getmempoolsparktxids", &getmempoolsparktxids, true }, - { "mobile", "getmempoolsparktxs", &getmempoolsparktxs, true }, - - - { "mobile", "checkifmncollateral", &checkifmncollateral, false }, + { "mobile", "getsparkanonymityset", &getsparkanonymityset, false, {} }, + { "mobile", "getsparkanonymitysetmeta", &getsparkanonymitysetmeta, false, {} }, + { "mobile", "getsparkanonymitysetsector", &getsparkanonymitysetsector, false, {} }, + { "mobile", "getsparkmintmetadata", &getsparkmintmetadata, true, {} }, + { "mobile", "getusedcoinstags", &getusedcoinstags, false, {} }, + { "mobile", "getusedcoinstagstxhashes", &getusedcoinstagstxhashes, false, {} }, + { "mobile", "getsparklatestcoinid", &getsparklatestcoinid, true, {} }, + { "mobile", "getmempoolsparktxids", &getmempoolsparktxids, true, {} }, + { "mobile", "getmempoolsparktxs", &getmempoolsparktxs, true, {} }, + + + { "mobile", "checkifmncollateral", &checkifmncollateral, false, {} }, }; diff --git a/src/rpc/server.h b/src/rpc/server.h index a9e700b932..e981ddf313 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -137,11 +137,11 @@ typedef UniValue(*rpcfn_type)(const JSONRPCRequest& jsonRequest); class CRPCCommand { public: - std::string category; - std::string name; + std::string category {}; + std::string name {}; rpcfn_type actor; - bool okSafeMode; - std::vector argNames; + bool okSafeMode {}; + std::vector argNames {}; }; /** @@ -241,7 +241,4 @@ void RPCNotifyBlockChange(bool ibd, const CBlockIndex *); // Retrieves any serialization flags requested in command line argument int RPCSerializationFlags(); -// Retrieves any serialization flags requested in command line argument -int RPCSerializationFlags(); - #endif // BITCOIN_RPCSERVER_H diff --git a/src/script/bitcoinconsensus.cpp b/src/script/bitcoinconsensus.cpp index c4ab441e2c..49da797ab3 100644 --- a/src/script/bitcoinconsensus.cpp +++ b/src/script/bitcoinconsensus.cpp @@ -47,7 +47,7 @@ class TxInputStream } int GetVersion() const { return m_version; } - int GetType() const { return m_type; } + FIRO_UNUSED int GetType() const { return m_type; } private: const int m_type; const int m_version; diff --git a/src/script/interpreter.h b/src/script/interpreter.h index 79894c5300..f51e29f93a 100644 --- a/src/script/interpreter.h +++ b/src/script/interpreter.h @@ -160,9 +160,9 @@ class TransactionSignatureChecker : public BaseSignatureChecker public: TransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn) : txTo(txToIn), nIn(nInIn), amount(amountIn), txdata(NULL) {} TransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, const PrecomputedTransactionData& txdataIn) : txTo(txToIn), nIn(nInIn), amount(amountIn), txdata(&txdataIn) {} - bool CheckSig(const std::vector& scriptSig, const std::vector& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const; - bool CheckLockTime(const CScriptNum& nLockTime) const; - bool CheckSequence(const CScriptNum& nSequence) const; + bool CheckSig(const std::vector& scriptSig, const std::vector& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override; + bool CheckLockTime(const CScriptNum& nLockTime) const override; + bool CheckSequence(const CScriptNum& nSequence) const override; }; class MutableTransactionSignatureChecker : public TransactionSignatureChecker diff --git a/src/script/ismine.cpp b/src/script/ismine.cpp index 13b9d622a0..413fe605e1 100644 --- a/src/script/ismine.cpp +++ b/src/script/ismine.cpp @@ -11,6 +11,8 @@ #include "script/standard.h" #include "script/sign.h" +#include "../compat_layer.h" + #include typedef std::vector valtype; @@ -148,7 +150,7 @@ isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey, bool& return ISMINE_SPENDABLE; break; } - case TX_SPARKMINT: {} + case TX_SPARKMINT: { FIRO_FALLTHROUGH; } case TX_SPARKSMINT: {} } diff --git a/src/script/sigcache.h b/src/script/sigcache.h index 238952bb95..f48b717cae 100644 --- a/src/script/sigcache.h +++ b/src/script/sigcache.h @@ -27,7 +27,7 @@ class CachingTransactionSignatureChecker : public TransactionSignatureChecker public: CachingTransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn, const CAmount& amount, bool storeIn, PrecomputedTransactionData& txdataIn) : TransactionSignatureChecker(txToIn, nInIn, amount, txdataIn), store(storeIn) {} - bool VerifySignature(const std::vector& vchSig, const CPubKey& vchPubKey, const uint256& sighash) const; + bool VerifySignature(const std::vector& vchSig, const CPubKey& vchPubKey, const uint256& sighash) const override; }; void InitSignatureCache(); diff --git a/src/script/sign.cpp b/src/script/sign.cpp index 9e1577fe39..c752febe45 100644 --- a/src/script/sign.cpp +++ b/src/script/sign.cpp @@ -404,7 +404,7 @@ class DummySignatureChecker : public BaseSignatureChecker public: DummySignatureChecker() {} - bool CheckSig(const std::vector& scriptSig, const std::vector& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const + bool CheckSig(const std::vector& scriptSig, const std::vector& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override { return true; } diff --git a/src/script/sign.h b/src/script/sign.h index 1cfc53c6c1..ca18ed7a0f 100644 --- a/src/script/sign.h +++ b/src/script/sign.h @@ -40,8 +40,8 @@ class TransactionSignatureCreator : public BaseSignatureCreator { public: TransactionSignatureCreator(const CKeyStore* keystoreIn, const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn=SIGHASH_ALL); - const BaseSignatureChecker& Checker() const { return checker; } - bool CreateSig(std::vector& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const; + const BaseSignatureChecker& Checker() const override { return checker; } + bool CreateSig(std::vector& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override; }; class MutableTransactionSignatureCreator : public TransactionSignatureCreator { @@ -55,8 +55,8 @@ class MutableTransactionSignatureCreator : public TransactionSignatureCreator { class DummySignatureCreator : public BaseSignatureCreator { public: DummySignatureCreator(const CKeyStore* keystoreIn) : BaseSignatureCreator(keystoreIn) {} - const BaseSignatureChecker& Checker() const; - bool CreateSig(std::vector& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const; + const BaseSignatureChecker& Checker() const override; + bool CreateSig(std::vector& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override; }; struct SignatureData { diff --git a/src/secp256k1/CMakeLists.txt b/src/secp256k1/CMakeLists.txt new file mode 100644 index 0000000000..7d60a8bf06 --- /dev/null +++ b/src/secp256k1/CMakeLists.txt @@ -0,0 +1,412 @@ +cmake_minimum_required(VERSION 3.16) + +#============================= +# Project / Package metadata +#============================= +project(libsecp256k1 + # The package (a.k.a. release) version is based on semantic versioning 2.0.0 of + # the API. All changes in experimental modules are treated as + # backwards-compatible and therefore at most increase the minor version. + VERSION 0.6.0 + DESCRIPTION "Optimized C library for ECDSA signatures and secret/public key operations on curve secp256k1." + HOMEPAGE_URL "https://github.com/bitcoin-core/secp256k1" + LANGUAGES C CXX +) +enable_testing() +list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake) + +if(CMAKE_VERSION VERSION_LESS 3.21) + # Emulates CMake 3.21+ behavior. + if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) + set(PROJECT_IS_TOP_LEVEL ON) + set(${PROJECT_NAME}_IS_TOP_LEVEL ON) + else() + set(PROJECT_IS_TOP_LEVEL OFF) + set(${PROJECT_NAME}_IS_TOP_LEVEL OFF) + endif() +endif() + +# The library version is based on libtool versioning of the ABI. The set of +# rules for updating the version can be found here: +# https://www.gnu.org/software/libtool/manual/html_node/Updating-version-info.html +# All changes in experimental modules are treated as if they don't affect the +# interface and therefore only increase the revision. +set(${PROJECT_NAME}_LIB_VERSION_CURRENT 5) +set(${PROJECT_NAME}_LIB_VERSION_REVISION 0) +set(${PROJECT_NAME}_LIB_VERSION_AGE 0) + +#============================= +# Language setup +#============================= +set(CMAKE_C_STANDARD 90) +set(CMAKE_C_EXTENSIONS OFF) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_EXTENSIONS OFF) + +#============================= +# Libraries +#============================= +find_package(GMP 6.2.1 REQUIRED) +find_package(OpenSSL 1.1.1 REQUIRED) + +#============================= +# Configurable options +#============================= +option(BUILD_SHARED_LIBS "Build shared libraries." ON) +option(SECP256K1_DISABLE_SHARED "Disable shared library. Overrides BUILD_SHARED_LIBS." OFF) +if(SECP256K1_DISABLE_SHARED) + set(BUILD_SHARED_LIBS OFF) +endif() + +option(SECP256K1_INSTALL "Enable installation." ${PROJECT_IS_TOP_LEVEL}) + +# Include main repo include directory +# TODO: Fix these and make them target properties. +# Project should only have ../include in include path. +# Not ${CMAKE_CURRENT_SOURCE_DIR} +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src) + +## Modules + +# We declare all options before processing them, to make sure we can express +# dependendencies while processing. +option(SECP256K1_ENABLE_MODULE_ECDH "Enable ECDH module." ON) +option(SECP256K1_ENABLE_MODULE_RECOVERY "Enable ECDSA pubkey recovery module." ON) + +set(SECP256K1_ECMULT_WINDOW_SIZE 15 CACHE STRING "Window size for ecmult precomputation for verification, specified as integer in range [2..24]. The default value is a reasonable setting for desktop machines (currently 15). [default=15]") +set_property(CACHE SECP256K1_ECMULT_WINDOW_SIZE PROPERTY STRINGS 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24) +include(CheckStringOptionValue) +check_string_option_value(SECP256K1_ECMULT_WINDOW_SIZE) +add_compile_definitions(ECMULT_WINDOW_SIZE=${SECP256K1_ECMULT_WINDOW_SIZE}) + +set(SECP256K1_ECMULT_GEN_KB 86 CACHE STRING "The size of the precomputed table for signing in multiples of 1024 bytes (on typical platforms). Larger values result in possibly better signing or key generation performance at the cost of a larger table. Valid choices are 2, 22, 86. The default value is a reasonable setting for desktop machines (currently 86). [default=86]") +set_property(CACHE SECP256K1_ECMULT_GEN_KB PROPERTY STRINGS 2 22 86) +check_string_option_value(SECP256K1_ECMULT_GEN_KB) +if(SECP256K1_ECMULT_GEN_KB EQUAL 2) + add_compile_definitions(COMB_BLOCKS=2) + add_compile_definitions(COMB_TEETH=5) +elseif(SECP256K1_ECMULT_GEN_KB EQUAL 22) + add_compile_definitions(COMB_BLOCKS=11) + add_compile_definitions(COMB_TEETH=6) +elseif(SECP256K1_ECMULT_GEN_KB EQUAL 86) + add_compile_definitions(COMB_BLOCKS=43) + add_compile_definitions(COMB_TEETH=6) +endif() + +set(SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY "OFF" CACHE STRING "Test-only override of the (autodetected by the C code) \"widemul\" setting. Legal values are: \"OFF\", \"int128_struct\", \"int128\" or \"int64\". [default=OFF]") +set_property(CACHE SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY PROPERTY STRINGS "OFF" "int128_struct" "int128" "int64") +check_string_option_value(SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY) +if(SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY) + string(TOUPPER "${SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY}" widemul_upper_value) + add_compile_definitions(USE_FORCE_WIDEMUL_${widemul_upper_value}=1) +endif() +mark_as_advanced(FORCE SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY) + +set(SECP256K1_ASM "AUTO" CACHE STRING "Assembly to use: \"AUTO\", \"OFF\", \"x86_64\" or \"arm32\" (experimental). [default=AUTO]") +set_property(CACHE SECP256K1_ASM PROPERTY STRINGS "AUTO" "OFF" "x86_64" "arm32") +check_string_option_value(SECP256K1_ASM) +if(SECP256K1_ASM STREQUAL "arm32") + enable_language(ASM) + include(CheckArm32Assembly) + check_arm32_assembly() + if(HAVE_ARM32_ASM) + add_compile_definitions(USE_EXTERNAL_ASM=1) + else() + message(FATAL_ERROR "ARM32 assembly requested but not available.") + endif() +elseif(SECP256K1_ASM) + include(CheckX86_64Assembly) + check_x86_64_assembly() + if(HAVE_X86_64_ASM) + set(SECP256K1_ASM "x86_64") + add_compile_definitions(USE_ASM_X86_64=1) + elseif(SECP256K1_ASM STREQUAL "AUTO") + set(SECP256K1_ASM "OFF") + else() + message(FATAL_ERROR "x86_64 assembly requested but not available.") + endif() +endif() + +option(SECP256K1_EXPERIMENTAL "Allow experimental configuration options." OFF) +if(NOT SECP256K1_EXPERIMENTAL) + if(SECP256K1_ASM STREQUAL "arm32") + message(FATAL_ERROR "ARM32 assembly is experimental. Use -DSECP256K1_EXPERIMENTAL=ON to allow.") + endif() +endif() + +set(SECP256K1_VALGRIND "AUTO" CACHE STRING "Build with extra checks for running inside Valgrind. [default=AUTO]") +set_property(CACHE SECP256K1_VALGRIND PROPERTY STRINGS "AUTO" "OFF" "ON") +check_string_option_value(SECP256K1_VALGRIND) +if(SECP256K1_VALGRIND) + find_package(Valgrind MODULE) + if(Valgrind_FOUND) + set(SECP256K1_VALGRIND ON) + include_directories(${Valgrind_INCLUDE_DIR}) + add_compile_definitions(VALGRIND) + elseif(SECP256K1_VALGRIND STREQUAL "AUTO") + set(SECP256K1_VALGRIND OFF) + else() + message(FATAL_ERROR "Valgrind support requested but valgrind/memcheck.h header not available.") + endif() +endif() + +option(SECP256K1_BUILD_BENCHMARK "Build benchmarks." OFF) +option(SECP256K1_BUILD_TESTS "Build tests." OFF) +option(SECP256K1_BUILD_EXHAUSTIVE_TESTS "Build exhaustive tests." OFF) + +# Redefine configuration flags. +# We leave assertions on, because they are only used in the examples, and we want them always on there. +if(MSVC) + string(REGEX REPLACE "/DNDEBUG[ \t\r\n]*" "" CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO}") + string(REGEX REPLACE "/DNDEBUG[ \t\r\n]*" "" CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}") + string(REGEX REPLACE "/DNDEBUG[ \t\r\n]*" "" CMAKE_C_FLAGS_MINSIZEREL "${CMAKE_C_FLAGS_MINSIZEREL}") +else() + string(REGEX REPLACE "-DNDEBUG[ \t\r\n]*" "" CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO}") + string(REGEX REPLACE "-DNDEBUG[ \t\r\n]*" "" CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}") + string(REGEX REPLACE "-DNDEBUG[ \t\r\n]*" "" CMAKE_C_FLAGS_MINSIZEREL "${CMAKE_C_FLAGS_MINSIZEREL}") + # Prefer -O2 optimization level. (-O3 is CMake's default for Release for many compilers.) + string(REGEX REPLACE "-O3( |$)" "-O2\\1" CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}") +endif() + +# Define custom "Coverage" build type. +set(CMAKE_C_FLAGS_COVERAGE "${CMAKE_C_FLAGS_RELWITHDEBINFO} -O0 -DCOVERAGE=1 --coverage" CACHE STRING + "Flags used by the C compiler during \"Coverage\" builds." + FORCE +) +set(CMAKE_EXE_LINKER_FLAGS_COVERAGE "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO} --coverage" CACHE STRING + "Flags used for linking binaries during \"Coverage\" builds." + FORCE +) +set(CMAKE_SHARED_LINKER_FLAGS_COVERAGE "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO} --coverage" CACHE STRING + "Flags used by the shared libraries linker during \"Coverage\" builds." + FORCE +) +mark_as_advanced( + CMAKE_C_FLAGS_COVERAGE + CMAKE_EXE_LINKER_FLAGS_COVERAGE + CMAKE_SHARED_LINKER_FLAGS_COVERAGE +) + +if(PROJECT_IS_TOP_LEVEL) + get_property(is_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + set(default_build_type "RelWithDebInfo") + if(is_multi_config) + set(CMAKE_CONFIGURATION_TYPES "${default_build_type}" "Release" "Debug" "MinSizeRel" "Coverage" CACHE STRING + "Supported configuration types." + FORCE + ) + else() + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY + STRINGS "${default_build_type}" "Release" "Debug" "MinSizeRel" "Coverage" + ) + if(NOT CMAKE_BUILD_TYPE) + message(STATUS "Setting build type to \"${default_build_type}\" as none was specified") + set(CMAKE_BUILD_TYPE "${default_build_type}" CACHE STRING + "Choose the type of build." + FORCE + ) + endif() + endif() +endif() + +include(TryAppendCFlags) +if(MSVC) + # Keep the following commands ordered lexicographically. + try_append_c_flags(/W3) # Production quality warning level. + try_append_c_flags(/wd4146) # Disable warning C4146 "unary minus operator applied to unsigned type, result still unsigned". + try_append_c_flags(/wd4244) # Disable warning C4244 "'conversion' conversion from 'type1' to 'type2', possible loss of data". + try_append_c_flags(/wd4267) # Disable warning C4267 "'var' : conversion from 'size_t' to 'type', possible loss of data". + # Eliminate deprecation warnings for the older, less secure functions. + add_compile_definitions(_CRT_SECURE_NO_WARNINGS) +else() + # Keep the following commands ordered lexicographically. + try_append_c_flags(-pedantic) + try_append_c_flags(-Wall) # GCC >= 2.95 and probably many other compilers. + try_append_c_flags(-Wcast-align) # GCC >= 2.95. + try_append_c_flags(-Wcast-align=strict) # GCC >= 8.0. + try_append_c_flags(-Wconditional-uninitialized) # Clang >= 3.0 only. + try_append_c_flags(-Wextra) # GCC >= 3.4, this is the newer name of -W, which we don't use because older GCCs will warn about unused functions. + try_append_c_flags(-Wnested-externs) + try_append_c_flags(-Wno-long-long) # GCC >= 3.0, -Wlong-long is implied by -pedantic. + try_append_c_flags(-Wno-overlength-strings) # GCC >= 4.2, -Woverlength-strings is implied by -pedantic. + try_append_c_flags(-Wno-unused-function) # GCC >= 3.0, -Wunused-function is implied by -Wall. + try_append_c_flags(-Wreserved-identifier) # Clang >= 13.0 only. + try_append_c_flags(-Wshadow) + try_append_c_flags(-Wstrict-prototypes) + try_append_c_flags(-Wundef) +endif() + +set(CMAKE_C_VISIBILITY_PRESET default) +set(CMAKE_CXX_VISIBILITY_PRESET default) + +set(SECP256K1_APPEND_CFLAGS "" CACHE STRING "Compiler flags that are appended to the command line after all other flags added by the build system. This variable is intended for debugging and special builds.") +if(SECP256K1_APPEND_CFLAGS) + # Appending to this low-level rule variable is the only way to + # guarantee that the flags appear at the end of the command line. + string(APPEND CMAKE_C_COMPILE_OBJECT " ${SECP256K1_APPEND_CFLAGS}") +endif() + +set(SECP256K1_APPEND_LDFLAGS "" CACHE STRING "Linker flags that are appended to the command line after all other flags added by the build system. This variable is intended for debugging and special builds.") +if(SECP256K1_APPEND_LDFLAGS) + # Appending to this low-level rule variable is the only way to + # guarantee that the flags appear at the end of the command line. + string(APPEND CMAKE_C_CREATE_SHARED_LIBRARY " ${SECP256K1_APPEND_LDFLAGS}") + string(APPEND CMAKE_C_LINK_EXECUTABLE " ${SECP256K1_APPEND_LDFLAGS}") +endif() + +if(NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin) +endif() +if(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib) +endif() +if(NOT CMAKE_ARCHIVE_OUTPUT_DIRECTORY) + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib) +endif() + +# If cross-compiling with MinGW, assume __int128 is 16 bytes. +if(MINGW) + set(SIZEOF__int128 16 CACHE INTERNAL "Assumed size of __int128 when cross-compiling for MinGW") + message(STATUS "Assuming __int128 is 16 bytes (MinGW cross-compiling)") +else() + include(CheckTypeSize) + check_type_size("__int128" SIZEOF__int128) + message(STATUS "Size of __int128 : ${SIZEOF__int128}") +endif() + +if(NOT SIZEOF__int128) + message(FATAL_ERROR "Unable to determine size of __int128") +endif() + +if(SIZEOF__int128 EQUAL 16) + add_compile_definitions(HAVE___INT128=1) +else() + message(FATAL_ERROR "secp256k1 requires __int128 type.") +endif() + +# Select field implementation +if(MINGW) + if(MINGW_ARCH STREQUAL "32") + # 32 bits + add_compile_definitions(USE_FIELD_10X26=1) # Use FIELD_10X26 implementation + add_compile_definitions(USE_SCALAR_8X32=1) # Use 8x32 scalar implementation + elseif(MINGW_ARCH STREQUAL "64") + # 64 bits + add_compile_definitions(USE_FIELD_5X52=1) # Use FIELD_5X52 implementation + add_compile_definitions(USE_SCALAR_4X64=1) # Use 4x64 scalar implementation + else() + message(FATAL_ERROR "Invalid architecture.") + endif() +else() + if(CMAKE_SIZEOF_VOID_P EQUAL 8) + # 64 bits + add_compile_definitions(USE_FIELD_5X52=1) # Use FIELD_5X52 implementation + add_compile_definitions(USE_SCALAR_4X64=1) # Use 4x64 scalar implementation + elseif(CMAKE_SIZEOF_VOID_P EQUAL 4) + # 32 bits + add_compile_definitions(USE_FIELD_10X26=1) # Use FIELD_10X26 implementation + add_compile_definitions(USE_SCALAR_8X32=1) # Use 8x32 scalar implementation + else() + message(FATAL_ERROR "Invalid architecture.") + endif() +endif() + +message(STATUS "Checking for __builtin_expect") +include(CheckCSourceCompiles) + +check_c_source_compiles(" +void myfunc() { __builtin_expect(0, 0); } +int main() { myfunc(); return 0; } +" HAVE_BUILTIN_EXPECT) + +if(HAVE_BUILTIN_EXPECT) + message(STATUS "yes") + add_compile_definitions(HAVE_BUILTIN_EXPECT=1) +else() + message(STATUS "no") +endif() + +add_subdirectory(src) + +message("\n") +message("secp256k1 configure summary") +message("===========================") +message("Build artifacts:") +if(BUILD_SHARED_LIBS) + set(library_type "Shared") +else() + set(library_type "Static") +endif() + +message(" library type ........................ ${library_type}") +message("Optional modules:") +message(" ECDH ................................ ${SECP256K1_ENABLE_MODULE_ECDH}") +message(" ECDSA pubkey recovery ............... ${SECP256K1_ENABLE_MODULE_RECOVERY}") +message("Parameters:") +message(" ecmult window size .................. ${SECP256K1_ECMULT_WINDOW_SIZE}") +message(" ecmult gen table size ............... ${SECP256K1_ECMULT_GEN_KB} KiB") +message("Optional features:") +message(" assembly ............................ ${SECP256K1_ASM}") +if(SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY) + message(" wide multiplication (test-only) ..... ${SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY}") +endif() +message("Optional binaries:") +message(" benchmark ........................... ${SECP256K1_BUILD_BENCHMARK}") +message(" noverify_tests ...................... ${SECP256K1_BUILD_TESTS}") +set(tests_status "${SECP256K1_BUILD_TESTS}") +if(CMAKE_BUILD_TYPE STREQUAL "Coverage") + set(tests_status OFF) +endif() +message(" tests ............................... ${tests_status}") +message(" exhaustive tests .................... ${SECP256K1_BUILD_EXHAUSTIVE_TESTS}") +message("") +if(CMAKE_CROSSCOMPILING) + set(cross_status "TRUE, for ${CMAKE_SYSTEM_NAME}, ${CMAKE_SYSTEM_PROCESSOR}") +else() + set(cross_status "FALSE") +endif() +message("Cross compiling ....................... ${cross_status}") +message("Valgrind .............................. ${SECP256K1_VALGRIND}") +get_directory_property(definitions COMPILE_DEFINITIONS) +string(REPLACE ";" " " definitions "${definitions}") +message("Preprocessor defined macros ........... ${definitions}") +message("C compiler ............................ ${CMAKE_C_COMPILER_ID} ${CMAKE_C_COMPILER_VERSION}, ${CMAKE_C_COMPILER}") +message("CFLAGS ................................ ${CMAKE_C_FLAGS}") +get_directory_property(compile_options COMPILE_OPTIONS) +string(REPLACE ";" " " compile_options "${compile_options}") +message("Compile options ....................... " ${compile_options}) +if(NOT is_multi_config) + message("Build type:") + message(" - CMAKE_BUILD_TYPE ................... ${CMAKE_BUILD_TYPE}") + string(TOUPPER "${CMAKE_BUILD_TYPE}" build_type) + message(" - CFLAGS ............................. ${CMAKE_C_FLAGS_${build_type}}") + message(" - LDFLAGS for executables ............ ${CMAKE_EXE_LINKER_FLAGS_${build_type}}") + message(" - LDFLAGS for shared libraries ....... ${CMAKE_SHARED_LINKER_FLAGS_${build_type}}") +else() + message("Supported configurations .............. ${CMAKE_CONFIGURATION_TYPES}") + message("RelWithDebInfo configuration:") + message(" - CFLAGS ............................. ${CMAKE_C_FLAGS_RELWITHDEBINFO}") + message(" - LDFLAGS for executables ............ ${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO}") + message(" - LDFLAGS for shared libraries ....... ${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO}") + message("Debug configuration:") + message(" - CFLAGS ............................. ${CMAKE_C_FLAGS_DEBUG}") + message(" - LDFLAGS for executables ............ ${CMAKE_EXE_LINKER_FLAGS_DEBUG}") + message(" - LDFLAGS for shared libraries ....... ${CMAKE_SHARED_LINKER_FLAGS_DEBUG}") +endif() +if(SECP256K1_APPEND_CFLAGS) + message("SECP256K1_APPEND_CFLAGS ............... ${SECP256K1_APPEND_CFLAGS}") +endif() +if(SECP256K1_APPEND_LDFLAGS) + message("SECP256K1_APPEND_LDFLAGS .............. ${SECP256K1_APPEND_LDFLAGS}") +endif() +message("") +if(SECP256K1_EXPERIMENTAL) + message( + " ******\n" + " WARNING: experimental build\n" + " Experimental features do not have stable APIs or properties, and may not be safe for production use.\n" + " ******\n" + ) +endif() \ No newline at end of file diff --git a/src/secp256k1/cmake/CheckArm32Assembly.cmake b/src/secp256k1/cmake/CheckArm32Assembly.cmake new file mode 100644 index 0000000000..baeeff0292 --- /dev/null +++ b/src/secp256k1/cmake/CheckArm32Assembly.cmake @@ -0,0 +1,6 @@ +function(check_arm32_assembly) + try_compile(HAVE_ARM32_ASM + ${PROJECT_BINARY_DIR}/check_arm32_assembly + SOURCES ${PROJECT_SOURCE_DIR}/cmake/source_arm32.s + ) +endfunction() diff --git a/src/secp256k1/cmake/CheckMemorySanitizer.cmake b/src/secp256k1/cmake/CheckMemorySanitizer.cmake new file mode 100644 index 0000000000..d9ef681e65 --- /dev/null +++ b/src/secp256k1/cmake/CheckMemorySanitizer.cmake @@ -0,0 +1,18 @@ +include_guard(GLOBAL) +include(CheckCSourceCompiles) + +function(check_memory_sanitizer output) + set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) + check_c_source_compiles(" + #if defined(__has_feature) + # if __has_feature(memory_sanitizer) + /* MemorySanitizer is enabled. */ + # elif + # error \"MemorySanitizer is disabled.\" + # endif + #else + # error \"__has_feature is not defined.\" + #endif + " HAVE_MSAN) + set(${output} ${HAVE_MSAN} PARENT_SCOPE) +endfunction() diff --git a/src/secp256k1/cmake/CheckStringOptionValue.cmake b/src/secp256k1/cmake/CheckStringOptionValue.cmake new file mode 100644 index 0000000000..5a4d939b9e --- /dev/null +++ b/src/secp256k1/cmake/CheckStringOptionValue.cmake @@ -0,0 +1,10 @@ +function(check_string_option_value option) + get_property(expected_values CACHE ${option} PROPERTY STRINGS) + if(expected_values) + if(${option} IN_LIST expected_values) + return() + endif() + message(FATAL_ERROR "${option} value is \"${${option}}\", but must be one of ${expected_values}.") + endif() + message(AUTHOR_WARNING "The STRINGS property must be set before invoking `check_string_option_value' function.") +endfunction() diff --git a/src/secp256k1/cmake/CheckX86_64Assembly.cmake b/src/secp256k1/cmake/CheckX86_64Assembly.cmake new file mode 100644 index 0000000000..ae82cd476e --- /dev/null +++ b/src/secp256k1/cmake/CheckX86_64Assembly.cmake @@ -0,0 +1,14 @@ +include(CheckCSourceCompiles) + +function(check_x86_64_assembly) + check_c_source_compiles(" + #include + + int main() + { + uint64_t a = 11, tmp; + __asm__ __volatile__(\"movq $0x100000000,%1; mulq %%rsi\" : \"+a\"(a) : \"S\"(tmp) : \"cc\", \"%rdx\"); + } + " HAVE_X86_64_ASM) + set(HAVE_X86_64_ASM ${HAVE_X86_64_ASM} PARENT_SCOPE) +endfunction() diff --git a/src/secp256k1/cmake/FindValgrind.cmake b/src/secp256k1/cmake/FindValgrind.cmake new file mode 100644 index 0000000000..3af5e691e4 --- /dev/null +++ b/src/secp256k1/cmake/FindValgrind.cmake @@ -0,0 +1,41 @@ +if(CMAKE_HOST_APPLE) + find_program(BREW_COMMAND brew) + execute_process( + COMMAND ${BREW_COMMAND} --prefix valgrind + OUTPUT_VARIABLE valgrind_brew_prefix + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE + ) +endif() + +set(hints_paths) +if(valgrind_brew_prefix) + set(hints_paths ${valgrind_brew_prefix}/include) +endif() + +find_path(Valgrind_INCLUDE_DIR + NAMES valgrind/memcheck.h + HINTS ${hints_paths} +) + +if(Valgrind_INCLUDE_DIR) + include(CheckCSourceCompiles) + set(CMAKE_REQUIRED_INCLUDES ${Valgrind_INCLUDE_DIR}) + check_c_source_compiles(" + #include + #if defined(NVALGRIND) + # error \"Valgrind does not support this platform.\" + #endif + + int main() {} + " Valgrind_WORKS) +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Valgrind + REQUIRED_VARS Valgrind_INCLUDE_DIR Valgrind_WORKS +) + +mark_as_advanced( + Valgrind_INCLUDE_DIR +) diff --git a/src/secp256k1/cmake/GeneratePkgConfigFile.cmake b/src/secp256k1/cmake/GeneratePkgConfigFile.cmake new file mode 100644 index 0000000000..9c1d7f1ddd --- /dev/null +++ b/src/secp256k1/cmake/GeneratePkgConfigFile.cmake @@ -0,0 +1,8 @@ +function(generate_pkg_config_file in_file) + set(prefix ${CMAKE_INSTALL_PREFIX}) + set(exec_prefix \${prefix}) + set(libdir \${exec_prefix}/${CMAKE_INSTALL_LIBDIR}) + set(includedir \${prefix}/${CMAKE_INSTALL_INCLUDEDIR}) + set(PACKAGE_VERSION ${PROJECT_VERSION}) + configure_file(${in_file} ${PROJECT_NAME}.pc @ONLY) +endfunction() diff --git a/src/secp256k1/cmake/TryAppendCFlags.cmake b/src/secp256k1/cmake/TryAppendCFlags.cmake new file mode 100644 index 0000000000..1d81a9317a --- /dev/null +++ b/src/secp256k1/cmake/TryAppendCFlags.cmake @@ -0,0 +1,24 @@ +include(CheckCCompilerFlag) + +function(secp256k1_check_c_flags_internal flags output) + string(MAKE_C_IDENTIFIER "${flags}" result) + string(TOUPPER "${result}" result) + set(result "C_SUPPORTS_${result}") + if(NOT MSVC) + set(CMAKE_REQUIRED_FLAGS "-Werror") + endif() + + # This avoids running a linker. + set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) + check_c_compiler_flag("${flags}" ${result}) + + set(${output} ${${result}} PARENT_SCOPE) +endfunction() + +# Append flags to the COMPILE_OPTIONS directory property if CC accepts them. +macro(try_append_c_flags) + secp256k1_check_c_flags_internal("${ARGV}" result) + if(result) + add_compile_options(${ARGV}) + endif() +endmacro() diff --git a/src/secp256k1/cmake/arm-linux-gnueabihf.toolchain.cmake b/src/secp256k1/cmake/arm-linux-gnueabihf.toolchain.cmake new file mode 100644 index 0000000000..0d91912b6d --- /dev/null +++ b/src/secp256k1/cmake/arm-linux-gnueabihf.toolchain.cmake @@ -0,0 +1,3 @@ +set(CMAKE_SYSTEM_NAME Linux) +set(CMAKE_SYSTEM_PROCESSOR arm) +set(CMAKE_C_COMPILER arm-linux-gnueabihf-gcc) diff --git a/src/secp256k1/cmake/config.cmake.in b/src/secp256k1/cmake/config.cmake.in new file mode 100644 index 0000000000..46b180ab19 --- /dev/null +++ b/src/secp256k1/cmake/config.cmake.in @@ -0,0 +1,5 @@ +@PACKAGE_INIT@ + +include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@-targets.cmake") + +check_required_components(@PROJECT_NAME@) diff --git a/src/secp256k1/cmake/source_arm32.s b/src/secp256k1/cmake/source_arm32.s new file mode 100644 index 0000000000..d3d9347057 --- /dev/null +++ b/src/secp256k1/cmake/source_arm32.s @@ -0,0 +1,9 @@ +.syntax unified +.eabi_attribute 24, 1 +.eabi_attribute 25, 1 +.text +.global main +main: + ldr r0, =0x002A + mov r7, #1 + swi 0 diff --git a/src/secp256k1/cmake/x86_64-w64-mingw32.toolchain.cmake b/src/secp256k1/cmake/x86_64-w64-mingw32.toolchain.cmake new file mode 100644 index 0000000000..96119b72d1 --- /dev/null +++ b/src/secp256k1/cmake/x86_64-w64-mingw32.toolchain.cmake @@ -0,0 +1,3 @@ +set(CMAKE_SYSTEM_NAME Windows) +set(CMAKE_SYSTEM_PROCESSOR x86_64) +set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc) diff --git a/src/secp256k1/configure.ac b/src/secp256k1/configure.ac index 66b388e3e0..c9b7ab17a0 100644 --- a/src/secp256k1/configure.ac +++ b/src/secp256k1/configure.ac @@ -152,6 +152,9 @@ AC_ARG_WITH([asm], [AS_HELP_STRING([--with-asm=x86_64|arm|no|auto] AC_CHECK_TYPES([__int128]) +dnl Require C++17 compiler (no GNU extensions) +AX_CXX_COMPILE_STDCXX([17], [noext], [mandatory], [nodefault]) + AC_MSG_CHECKING([for __builtin_expect]) AC_COMPILE_IFELSE([AC_LANG_SOURCE([[void myfunc() {__builtin_expect(0,0);}]])], [ AC_MSG_RESULT([yes]);AC_DEFINE(HAVE_BUILTIN_EXPECT,1,[Define this symbol if __builtin_expect is available]) ], diff --git a/src/secp256k1/contrib/lax_der_parsing.h b/src/secp256k1/contrib/lax_der_parsing.h index 6d27871a7c..63d88ed089 100644 --- a/src/secp256k1/contrib/lax_der_parsing.h +++ b/src/secp256k1/contrib/lax_der_parsing.h @@ -48,8 +48,8 @@ * 8.3.1. */ -#ifndef _SECP256K1_CONTRIB_LAX_DER_PARSING_H_ -#define _SECP256K1_CONTRIB_LAX_DER_PARSING_H_ +#ifndef SECP256K1_CONTRIB_LAX_DER_PARSING_H_ +#define SECP256K1_CONTRIB_LAX_DER_PARSING_H_ #include diff --git a/src/secp256k1/contrib/lax_der_privatekey_parsing.h b/src/secp256k1/contrib/lax_der_privatekey_parsing.h index 2fd088f8ab..fa2f9ade6a 100644 --- a/src/secp256k1/contrib/lax_der_privatekey_parsing.h +++ b/src/secp256k1/contrib/lax_der_privatekey_parsing.h @@ -25,8 +25,8 @@ * library are sufficient. */ -#ifndef _SECP256K1_CONTRIB_BER_PRIVATEKEY_H_ -#define _SECP256K1_CONTRIB_BER_PRIVATEKEY_H_ +#ifndef SECP256K1_CONTRIB_BER_PRIVATEKEY_H_ +#define SECP256K1_CONTRIB_BER_PRIVATEKEY_H_ #include diff --git a/src/secp256k1/include/GroupElement.h b/src/secp256k1/include/GroupElement.h index da9ec459cc..08dfb65877 100644 --- a/src/secp256k1/include/GroupElement.h +++ b/src/secp256k1/include/GroupElement.h @@ -1,5 +1,5 @@ -#ifndef SECP_GROUP_ELEMENT_H__ -#define SECP_GROUP_ELEMENT_H__ +#ifndef SECP_GROUP_ELEMENT_H +#define SECP_GROUP_ELEMENT_H #include "Scalar.h" @@ -134,4 +134,4 @@ namespace std { }; } // namespace std -#endif // SECP_GROUP_ELEMENT_H__ +#endif // SECP_GROUP_ELEMENT_H diff --git a/src/secp256k1/include/Scalar.h b/src/secp256k1/include/Scalar.h index 0a35bb9b77..8c36931377 100644 --- a/src/secp256k1/include/Scalar.h +++ b/src/secp256k1/include/Scalar.h @@ -1,5 +1,5 @@ -#ifndef SCALAR_H__ -#define SCALAR_H__ +#ifndef SCALAR_H +#define SCALAR_H #include #include @@ -139,4 +139,4 @@ struct hash { } // namespace std -#endif // SCALAR_H__ +#endif // SCALAR_H diff --git a/src/secp256k1/include/secp256k1.h b/src/secp256k1/include/secp256k1.h index f268e309d0..4f96d97956 100644 --- a/src/secp256k1/include/secp256k1.h +++ b/src/secp256k1/include/secp256k1.h @@ -1,5 +1,5 @@ -#ifndef _SECP256K1_ -# define _SECP256K1_ +#ifndef SECP256K1_ +# define SECP256K1_ # ifdef __cplusplus extern "C" { diff --git a/src/secp256k1/include/secp256k1_ecdh.h b/src/secp256k1/include/secp256k1_ecdh.h index 4b84d7a963..a7cf2cc1d2 100644 --- a/src/secp256k1/include/secp256k1_ecdh.h +++ b/src/secp256k1/include/secp256k1_ecdh.h @@ -1,5 +1,5 @@ -#ifndef _SECP256K1_ECDH_ -# define _SECP256K1_ECDH_ +#ifndef SECP256K1_ECDH_ +# define SECP256K1_ECDH_ # include "secp256k1.h" diff --git a/src/secp256k1/include/secp256k1_recovery.h b/src/secp256k1/include/secp256k1_recovery.h index 0553797253..cfdb76b957 100644 --- a/src/secp256k1/include/secp256k1_recovery.h +++ b/src/secp256k1/include/secp256k1_recovery.h @@ -1,5 +1,5 @@ -#ifndef _SECP256K1_RECOVERY_ -# define _SECP256K1_RECOVERY_ +#ifndef SECP256K1_RECOVERY_ +# define SECP256K1_RECOVERY_ # include "secp256k1.h" diff --git a/src/secp256k1/src/CMakeLists.txt b/src/secp256k1/src/CMakeLists.txt new file mode 100644 index 0000000000..e6a62df2b6 --- /dev/null +++ b/src/secp256k1/src/CMakeLists.txt @@ -0,0 +1,219 @@ +# Must be included before CMAKE_INSTALL_INCLUDEDIR is used. +include(GNUInstallDirs) + +# Add objects explicitly rather than linking to the object libs to keep them +# from being exported. +add_library(secp256k1 OBJECT secp256k1.c) + +set_property(TARGET secp256k1 PROPERTY POSITION_INDEPENDENT_CODE ON) + +target_link_libraries(secp256k1 + PUBLIC + ${GMP_LIBRARIES} + PRIVATE + OpenSSL::Crypto +) + +target_include_directories(secp256k1 + PUBLIC + ${GMP_INCLUDES} +) + +#============================= +# secp256k1 Configuration +#============================= +# Define this symbol if libgmp is installed +add_compile_definitions(HAVE_LIBGMP=1) +# Define this symbol to use the gmp implementation for num +add_compile_definitions(USE_NUM_GMP=1) +# Define this symbol to use the num-based field inverse implementation +add_compile_definitions(USE_FIELD_INV_NUM=1) +# Define this symbol to use the num-based scalar inverse implementation +add_compile_definitions(USE_SCALAR_INV_NUM=1) + +# Processing must be done in a topological sorting of the dependency graph +# (dependent module first). +if(SECP256K1_ENABLE_MODULE_RECOVERY) + add_compile_definitions(ENABLE_MODULE_RECOVERY=1) + message(STATUS "secp256k1: Recovery module enabled") +else() + message(STATUS "secp256k1: Recovery module disabled") +endif() + +if(SECP256K1_ENABLE_MODULE_ECDH) + add_compile_definitions(ENABLE_MODULE_ECDH=1) + message(STATUS "secp256k1: ECDH module enabled") +else() + message(STATUS "secp256k1: ECDH module disabled") +endif() + +add_library(secp256k1pp + ${CMAKE_CURRENT_SOURCE_DIR}/cpp/GroupElement.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/cpp/MultiExponent.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/cpp/Scalar.cpp +) + +set_property(TARGET secp256k1pp PROPERTY POSITION_INDEPENDENT_CODE ON) + +target_link_libraries(secp256k1pp + PUBLIC secp256k1 ${GMP_LIBRARIES} +) + +add_library(secp256k1_asm INTERFACE) +target_link_libraries(secp256k1_asm INTERFACE ${GMP_LIBRARIES}) +if(SECP256K1_ASM STREQUAL "arm32") + add_library(secp256k1_asm_arm OBJECT EXCLUDE_FROM_ALL) + target_sources(secp256k1_asm_arm PUBLIC + asm/field_10x26_arm.s + ) + target_sources(secp256k1 PRIVATE $) + target_link_libraries(secp256k1_asm INTERFACE secp256k1_asm_arm) +endif() + +if(WIN32) + # Define our export symbol only for shared libs. + set_target_properties(secp256k1 PROPERTIES DEFINE_SYMBOL SECP256K1_DLL_EXPORT) + target_compile_definitions(secp256k1 INTERFACE $<$>:SECP256K1_STATIC>) +endif() + +# Object libs don't know if they're being built for a shared or static lib. +# Grab the PIC property from secp256k1 which knows. +get_target_property(use_pic secp256k1 POSITION_INDEPENDENT_CODE) + +target_include_directories(secp256k1 INTERFACE + # Add the include path for parent projects so that they don't have to manually add it. + $>:${PROJECT_SOURCE_DIR}/include>> + $ +) + +# This emulates Libtool to make sure Libtool and CMake agree on the ABI version, +# see below "Calculate the version variables" in build-aux/ltmain.sh. +math(EXPR ${PROJECT_NAME}_soversion "${${PROJECT_NAME}_LIB_VERSION_CURRENT} - ${${PROJECT_NAME}_LIB_VERSION_AGE}") +set_target_properties(secp256k1 PROPERTIES + SOVERSION ${${PROJECT_NAME}_soversion} +) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + set_target_properties(secp256k1 PROPERTIES + VERSION ${${PROJECT_NAME}_soversion}.${${PROJECT_NAME}_LIB_VERSION_AGE}.${${PROJECT_NAME}_LIB_VERSION_REVISION} + ) +elseif(APPLE) + if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.17) + math(EXPR ${PROJECT_NAME}_compatibility_version "${${PROJECT_NAME}_LIB_VERSION_CURRENT} + 1") + set_target_properties(secp256k1 PROPERTIES + MACHO_COMPATIBILITY_VERSION ${${PROJECT_NAME}_compatibility_version} + MACHO_CURRENT_VERSION ${${PROJECT_NAME}_compatibility_version}.${${PROJECT_NAME}_LIB_VERSION_REVISION} + ) + unset(${PROJECT_NAME}_compatibility_version) + elseif(BUILD_SHARED_LIBS) + message(WARNING + "The 'compatibility version' and 'current version' values of the DYLIB " + "will diverge from the values set by the GNU Libtool. To ensure " + "compatibility, it is recommended to upgrade CMake to at least version 3.17." + ) + endif() +elseif(CMAKE_SYSTEM_NAME STREQUAL "Windows") + set(${PROJECT_NAME}_windows "secp256k1") + if(MSVC) + set(${PROJECT_NAME}_windows "${PROJECT_NAME}") + endif() + set_target_properties(secp256k1 PROPERTIES + ARCHIVE_OUTPUT_NAME "${${PROJECT_NAME}_windows}" + RUNTIME_OUTPUT_NAME "${${PROJECT_NAME}_windows}-${${PROJECT_NAME}_soversion}" + ) + unset(${PROJECT_NAME}_windows) +endif() +unset(${PROJECT_NAME}_soversion) + +if(SECP256K1_BUILD_BENCHMARK) + add_executable(bench_ecdh bench_ecdh.c) + target_link_libraries(bench_ecdh PUBLIC secp256k1) + add_executable(bench_recover bench_recover.c) + target_link_libraries(bench_recover PUBLIC secp256k1) + add_executable(bench_sign bench_sign.c) + target_link_libraries(bench_sign PUBLIC secp256k1) + add_executable(bench_verify bench_verify.c) + target_link_libraries(bench_verify PUBLIC secp256k1) + add_executable(bench_internal bench_internal.c) + target_link_libraries(bench_internal PUBLIC secp256k1_asm ${GMP_LIBRARIES}) + target_include_directories(bench_internal PUBLIC ${GMP_INCLUDES}) +endif() + +if(SECP256K1_BUILD_TESTS) + add_executable(noverify_tests tests.c) + target_compile_definitions(noverify_tests PRIVATE VERIFY) + target_link_libraries(noverify_tests secp256k1_asm ${GMP_LIBRARIES}) + target_include_directories(noverify_tests PUBLIC ${GMP_INCLUDES}) + add_test(NAME secp256k1_noverify_tests COMMAND noverify_tests) + if(NOT CMAKE_BUILD_TYPE STREQUAL "Coverage") + add_executable(tests tests.c) + target_compile_definitions(tests PRIVATE VERIFY) + target_link_libraries(tests secp256k1_asm ${GMP_LIBRARIES}) + target_include_directories(tests PUBLIC ${GMP_INCLUDES}) + add_test(NAME secp256k1_tests COMMAND tests) + endif() +endif() + +if(SECP256K1_BUILD_EXHAUSTIVE_TESTS) + # Note: do not include secp256k1_precomputed in exhaustive_tests (it uses runtime-generated tables). + add_executable(exhaustive_tests tests_exhaustive.c) + target_link_libraries(exhaustive_tests PRIVATE secp256k1_asm ${GMP_LIBRARIES}) + target_include_directories(exhaustive_tests PUBLIC ${GMP_INCLUDES}) + target_compile_definitions(exhaustive_tests PRIVATE $<$>:VERIFY>) + add_test(NAME secp256k1_exhaustive_tests COMMAND exhaustive_tests) +endif() + +if(SECP256K1_INSTALL) + install(TARGETS secp256k1 + EXPORT ${PROJECT_NAME}-targets + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + ) + set(${PROJECT_NAME}_headers + "${PROJECT_SOURCE_DIR}/include/secp256k1.h" + ) + if(SECP256K1_ENABLE_MODULE_ECDH) + list(APPEND ${PROJECT_NAME}_headers "${PROJECT_SOURCE_DIR}/include/secp256k1_ecdh.h") + endif() + if(SECP256K1_ENABLE_MODULE_RECOVERY) + list(APPEND ${PROJECT_NAME}_headers "${PROJECT_SOURCE_DIR}/include/secp256k1_recovery.h") + endif() + if(SECP256K1_ENABLE_MODULE_SCHNORR) + list(APPEND ${PROJECT_NAME}_headers "${PROJECT_SOURCE_DIR}/include/secp256k1_schnorr.h") + endif() + install(FILES ${${PROJECT_NAME}_headers} + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} + ) + + install(EXPORT ${PROJECT_NAME}-targets + FILE ${PROJECT_NAME}-targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} + ) + + include(CMakePackageConfigHelpers) + configure_package_config_file( + ${PROJECT_SOURCE_DIR}/cmake/config.cmake.in + ${PROJECT_NAME}-config.cmake + INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} + NO_SET_AND_CHECK_MACRO + ) + write_basic_package_version_file(${PROJECT_NAME}-config-version.cmake + COMPATIBILITY SameMinorVersion + ) + + install( + FILES + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-config.cmake + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-config-version.cmake + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} + ) + + include(GeneratePkgConfigFile) + generate_pkg_config_file(${PROJECT_SOURCE_DIR}/libsecp256k1.pc.in) + install( + FILES + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc + DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig + ) +endif() diff --git a/src/secp256k1/src/basic-config.h b/src/secp256k1/src/basic-config.h index c4c16eb7ca..41f2bbf13d 100644 --- a/src/secp256k1/src/basic-config.h +++ b/src/secp256k1/src/basic-config.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_BASIC_CONFIG_ -#define _SECP256K1_BASIC_CONFIG_ +#ifndef SECP256K1_BASIC_CONFIG_ +#define SECP256K1_BASIC_CONFIG_ #ifdef USE_BASIC_CONFIG @@ -29,4 +29,4 @@ #define USE_SCALAR_8X32 1 #endif // USE_BASIC_CONFIG -#endif // _SECP256K1_BASIC_CONFIG_ +#endif // SECP256K1_BASIC_CONFIG_ diff --git a/src/secp256k1/src/bench.h b/src/secp256k1/src/bench.h index 3a71b4aafa..50a58801ae 100644 --- a/src/secp256k1/src/bench.h +++ b/src/secp256k1/src/bench.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_BENCH_H_ -#define _SECP256K1_BENCH_H_ +#ifndef SECP256K1_BENCH_H_ +#define SECP256K1_BENCH_H_ #include #include diff --git a/src/secp256k1/src/cpp/GroupElement.cpp b/src/secp256k1/src/cpp/GroupElement.cpp index b94499cd8f..0008c2cafe 100644 --- a/src/secp256k1/src/cpp/GroupElement.cpp +++ b/src/secp256k1/src/cpp/GroupElement.cpp @@ -1,8 +1,12 @@ +#include "../../../compat_layer.h" + #include "include/GroupElement.h" #include "include/secp256k1.h" #include "../field.h" #include "../field_impl.h" +#include "../num.h" +#include "../num_impl.h" #include "../group.h" #include "../group_impl.h" #include "../hash.h" @@ -121,7 +125,7 @@ static int _convertBase( resLen++; } - if (resLen > Len) { + if (cmp::greater(resLen, Len)) { throw std::overflow_error("GroupElement::GroupElement: invalid count"); } @@ -131,7 +135,7 @@ static int _convertBase( } } - for (int i = 0; i < Len / 2; i++) { + for (int i = 0; cmp::less(i, Len / 2); i++) { unsigned char tmp = dst[i]; dst[i] = dst[Len - i - 1]; dst[Len - i - 1] = tmp; @@ -187,7 +191,7 @@ static void _convertToFieldElement(secp256k1_fe *r, const char* str, int base) { auto strLen = strlen(str); std::vector src(strLen, 0); - for (int i = 0; i < strLen; i++) { + for (int i = 0; cmp::less(i, strLen); i++) { char ch = str[i]; switch (base) { @@ -354,7 +358,7 @@ GroupElement& GroupElement::generate(unsigned char* seed){ secp256k1_fe t = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 4); secp256k1_ge add; secp256k1_gej accum; - int overflow; + FIRO_UNUSED int overflow; secp256k1_sha256_t sha256; unsigned char b32[32]; secp256k1_sha256_initialize(&sha256); @@ -431,13 +435,13 @@ std::string _convertToString(const unsigned char(&buffer) [Len], int base) { for (int i = 0; i < strLen; i++) { unsigned char v = dst[startAt + i]; - char ch; + char ch{}; switch (base) { case 10: ch = '0' + v; break; case 16: - if (v >= 0 && v <= 9) { + if (v <= 9) { ch = '0' + v; } else { ch = 'a' + v - 10; diff --git a/src/secp256k1/src/ecdsa.h b/src/secp256k1/src/ecdsa.h index 54ae101b92..94d27f338d 100644 --- a/src/secp256k1/src/ecdsa.h +++ b/src/secp256k1/src/ecdsa.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_ECDSA_ -#define _SECP256K1_ECDSA_ +#ifndef SECP256K1_ECDSA_ +#define SECP256K1_ECDSA_ #include diff --git a/src/secp256k1/src/ecdsa_impl.h b/src/secp256k1/src/ecdsa_impl.h index 9a42e519bd..c76f4a5dc8 100644 --- a/src/secp256k1/src/ecdsa_impl.h +++ b/src/secp256k1/src/ecdsa_impl.h @@ -5,8 +5,8 @@ **********************************************************************/ -#ifndef _SECP256K1_ECDSA_IMPL_H_ -#define _SECP256K1_ECDSA_IMPL_H_ +#ifndef SECP256K1_ECDSA_IMPL_H_ +#define SECP256K1_ECDSA_IMPL_H_ #include "scalar.h" #include "field.h" diff --git a/src/secp256k1/src/eckey.h b/src/secp256k1/src/eckey.h index 42739a3bea..5f91cdcbe9 100644 --- a/src/secp256k1/src/eckey.h +++ b/src/secp256k1/src/eckey.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_ECKEY_ -#define _SECP256K1_ECKEY_ +#ifndef SECP256K1_ECKEY_ +#define SECP256K1_ECKEY_ #include diff --git a/src/secp256k1/src/eckey_impl.h b/src/secp256k1/src/eckey_impl.h index ce38071ac2..75d72e7426 100644 --- a/src/secp256k1/src/eckey_impl.h +++ b/src/secp256k1/src/eckey_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_ECKEY_IMPL_H_ -#define _SECP256K1_ECKEY_IMPL_H_ +#ifndef SECP256K1_ECKEY_IMPL_H_ +#define SECP256K1_ECKEY_IMPL_H_ #include "eckey.h" diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index b0eda32e2f..3b8f2e68b5 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_ECMULT_ -#define _SECP256K1_ECMULT_ +#ifndef SECP256K1_ECMULT_ +#define SECP256K1_ECMULT_ #include "num.h" #include "group.h" diff --git a/src/secp256k1/src/ecmult_const.h b/src/secp256k1/src/ecmult_const.h index 2b0097655c..77a15fbd1b 100644 --- a/src/secp256k1/src/ecmult_const.h +++ b/src/secp256k1/src/ecmult_const.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_ECMULT_CONST_ -#define _SECP256K1_ECMULT_CONST_ +#ifndef SECP256K1_ECMULT_CONST_ +#define SECP256K1_ECMULT_CONST_ #include "scalar.h" #include "group.h" diff --git a/src/secp256k1/src/ecmult_const_impl.h b/src/secp256k1/src/ecmult_const_impl.h index bf1aaa7f21..ed925372db 100644 --- a/src/secp256k1/src/ecmult_const_impl.h +++ b/src/secp256k1/src/ecmult_const_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_ECMULT_CONST_IMPL_ -#define _SECP256K1_ECMULT_CONST_IMPL_ +#ifndef SECP256K1_ECMULT_CONST_IMPL_ +#define SECP256K1_ECMULT_CONST_IMPL_ #include "scalar.h" #include "group.h" @@ -54,7 +54,7 @@ static int secp256k1_wnaf_const(int *wnaf, secp256k1_scalar s, int w) { /* 1 2 3 */ int u_last; - int u; + int u = 0; int flip; int bit; diff --git a/src/secp256k1/src/ecmult_gen.h b/src/secp256k1/src/ecmult_gen.h index eb2cc9ead6..a4ae722568 100644 --- a/src/secp256k1/src/ecmult_gen.h +++ b/src/secp256k1/src/ecmult_gen.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_ECMULT_GEN_ -#define _SECP256K1_ECMULT_GEN_ +#ifndef SECP256K1_ECMULT_GEN_ +#define SECP256K1_ECMULT_GEN_ #include "scalar.h" #include "group.h" diff --git a/src/secp256k1/src/ecmult_gen_impl.h b/src/secp256k1/src/ecmult_gen_impl.h index 35f2546077..cead470aaf 100644 --- a/src/secp256k1/src/ecmult_gen_impl.h +++ b/src/secp256k1/src/ecmult_gen_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_ECMULT_GEN_IMPL_H_ -#define _SECP256K1_ECMULT_GEN_IMPL_H_ +#ifndef SECP256K1_ECMULT_GEN_IMPL_H_ +#define SECP256K1_ECMULT_GEN_IMPL_H_ #include "scalar.h" #include "group.h" diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 4bb3d29151..cd78438f61 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_ECMULT_IMPL_H_ -#define _SECP256K1_ECMULT_IMPL_H_ +#ifndef SECP256K1_ECMULT_IMPL_H_ +#define SECP256K1_ECMULT_IMPL_H_ #include diff --git a/src/secp256k1/src/field.h b/src/secp256k1/src/field.h index bbb1ee866c..242cd8f629 100644 --- a/src/secp256k1/src/field.h +++ b/src/secp256k1/src/field.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_FIELD_ -#define _SECP256K1_FIELD_ +#ifndef SECP256K1_FIELD_ +#define SECP256K1_FIELD_ /** Field element module. * diff --git a/src/secp256k1/src/field_10x26.h b/src/secp256k1/src/field_10x26.h index 61ee1e0965..ded1b6e817 100644 --- a/src/secp256k1/src/field_10x26.h +++ b/src/secp256k1/src/field_10x26.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_FIELD_REPR_ -#define _SECP256K1_FIELD_REPR_ +#ifndef SECP256K1_FIELD_REPR_ +#define SECP256K1_FIELD_REPR_ #include diff --git a/src/secp256k1/src/field_10x26_impl.h b/src/secp256k1/src/field_10x26_impl.h index 7b8c079608..42100e1ca3 100644 --- a/src/secp256k1/src/field_10x26_impl.h +++ b/src/secp256k1/src/field_10x26_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_FIELD_REPR_IMPL_H_ -#define _SECP256K1_FIELD_REPR_IMPL_H_ +#ifndef SECP256K1_FIELD_REPR_IMPL_H_ +#define SECP256K1_FIELD_REPR_IMPL_H_ #include "util.h" #include "num.h" diff --git a/src/secp256k1/src/field_5x52.h b/src/secp256k1/src/field_5x52.h index 8e69a560dc..335af49831 100644 --- a/src/secp256k1/src/field_5x52.h +++ b/src/secp256k1/src/field_5x52.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_FIELD_REPR_ -#define _SECP256K1_FIELD_REPR_ +#ifndef SECP256K1_FIELD_REPR_ +#define SECP256K1_FIELD_REPR_ #include diff --git a/src/secp256k1/src/field_5x52_asm_impl.h b/src/secp256k1/src/field_5x52_asm_impl.h index 98cc004bf0..31d1033960 100644 --- a/src/secp256k1/src/field_5x52_asm_impl.h +++ b/src/secp256k1/src/field_5x52_asm_impl.h @@ -11,8 +11,8 @@ * - December 2014, Pieter Wuille: converted from YASM to GCC inline assembly */ -#ifndef _SECP256K1_FIELD_INNER5X52_IMPL_H_ -#define _SECP256K1_FIELD_INNER5X52_IMPL_H_ +#ifndef SECP256K1_FIELD_INNER5X52_IMPL_H_ +#define SECP256K1_FIELD_INNER5X52_IMPL_H_ SECP256K1_INLINE static void secp256k1_fe_mul_inner(uint64_t *r, const uint64_t *a, const uint64_t * SECP256K1_RESTRICT b) { /** diff --git a/src/secp256k1/src/field_5x52_impl.h b/src/secp256k1/src/field_5x52_impl.h index 7a99eb21ec..da2d25225b 100644 --- a/src/secp256k1/src/field_5x52_impl.h +++ b/src/secp256k1/src/field_5x52_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_FIELD_REPR_IMPL_H_ -#define _SECP256K1_FIELD_REPR_IMPL_H_ +#ifndef SECP256K1_FIELD_REPR_IMPL_H_ +#define SECP256K1_FIELD_REPR_IMPL_H_ #if defined HAVE_CONFIG_H #include "libsecp256k1-config.h" diff --git a/src/secp256k1/src/field_5x52_int128_impl.h b/src/secp256k1/src/field_5x52_int128_impl.h index 0bf22bdd3e..4c6da8c960 100644 --- a/src/secp256k1/src/field_5x52_int128_impl.h +++ b/src/secp256k1/src/field_5x52_int128_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_FIELD_INNER5X52_IMPL_H_ -#define _SECP256K1_FIELD_INNER5X52_IMPL_H_ +#ifndef SECP256K1_FIELD_INNER5X52_IMPL_H_ +#define SECP256K1_FIELD_INNER5X52_IMPL_H_ #include diff --git a/src/secp256k1/src/field_impl.h b/src/secp256k1/src/field_impl.h index 5127b279bc..d47754bc8d 100644 --- a/src/secp256k1/src/field_impl.h +++ b/src/secp256k1/src/field_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_FIELD_IMPL_H_ -#define _SECP256K1_FIELD_IMPL_H_ +#ifndef SECP256K1_FIELD_IMPL_H_ +#define SECP256K1_FIELD_IMPL_H_ #if defined HAVE_CONFIG_H #include "libsecp256k1-config.h" diff --git a/src/secp256k1/src/gen_context.c b/src/secp256k1/src/gen_context.c index 1835fd491d..e59e1aa267 100644 --- a/src/secp256k1/src/gen_context.c +++ b/src/secp256k1/src/gen_context.c @@ -39,8 +39,8 @@ int main(int argc, char **argv) { return -1; } - fprintf(fp, "#ifndef _SECP256K1_ECMULT_STATIC_CONTEXT_\n"); - fprintf(fp, "#define _SECP256K1_ECMULT_STATIC_CONTEXT_\n"); + fprintf(fp, "#ifndef SECP256K1_ECMULT_STATIC_CONTEXT_\n"); + fprintf(fp, "#define SECP256K1_ECMULT_STATIC_CONTEXT_\n"); fprintf(fp, "#include \"group.h\"\n"); fprintf(fp, "#define SC SECP256K1_GE_STORAGE_CONST\n"); fprintf(fp, "static const secp256k1_ge_storage secp256k1_ecmult_static_context[64][16] = {\n"); diff --git a/src/secp256k1/src/group.h b/src/secp256k1/src/group.h index 4957b248fe..f4ff34acf8 100644 --- a/src/secp256k1/src/group.h +++ b/src/secp256k1/src/group.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_GROUP_ -#define _SECP256K1_GROUP_ +#ifndef SECP256K1_GROUP_ +#define SECP256K1_GROUP_ #include "num.h" #include "field.h" diff --git a/src/secp256k1/src/group_impl.h b/src/secp256k1/src/group_impl.h index 2e192b62fd..8db59dc5ff 100644 --- a/src/secp256k1/src/group_impl.h +++ b/src/secp256k1/src/group_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_GROUP_IMPL_H_ -#define _SECP256K1_GROUP_IMPL_H_ +#ifndef SECP256K1_GROUP_IMPL_H_ +#define SECP256K1_GROUP_IMPL_H_ #include "num.h" #include "field.h" diff --git a/src/secp256k1/src/hash.h b/src/secp256k1/src/hash.h index fca98cab9f..c024065cba 100644 --- a/src/secp256k1/src/hash.h +++ b/src/secp256k1/src/hash.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_HASH_ -#define _SECP256K1_HASH_ +#ifndef SECP256K1_HASH_ +#define SECP256K1_HASH_ #include #include diff --git a/src/secp256k1/src/hash_impl.h b/src/secp256k1/src/hash_impl.h index b47e65f830..848f63ceb4 100644 --- a/src/secp256k1/src/hash_impl.h +++ b/src/secp256k1/src/hash_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_HASH_IMPL_H_ -#define _SECP256K1_HASH_IMPL_H_ +#ifndef SECP256K1_HASH_IMPL_H_ +#define SECP256K1_HASH_IMPL_H_ #include "hash.h" diff --git a/src/secp256k1/src/modules/ecdh/main_impl.h b/src/secp256k1/src/modules/ecdh/main_impl.h index c23e4f82f7..d8b9543b5b 100644 --- a/src/secp256k1/src/modules/ecdh/main_impl.h +++ b/src/secp256k1/src/modules/ecdh/main_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_MODULE_ECDH_MAIN_ -#define _SECP256K1_MODULE_ECDH_MAIN_ +#ifndef SECP256K1_MODULE_ECDH_MAIN_ +#define SECP256K1_MODULE_ECDH_MAIN_ #include "include/secp256k1_ecdh.h" #include "ecmult_const_impl.h" diff --git a/src/secp256k1/src/modules/ecdh/tests_impl.h b/src/secp256k1/src/modules/ecdh/tests_impl.h index 7badc9033f..b194cf1dba 100644 --- a/src/secp256k1/src/modules/ecdh/tests_impl.h +++ b/src/secp256k1/src/modules/ecdh/tests_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_MODULE_ECDH_TESTS_ -#define _SECP256K1_MODULE_ECDH_TESTS_ +#ifndef SECP256K1_MODULE_ECDH_TESTS_ +#define SECP256K1_MODULE_ECDH_TESTS_ void test_ecdh_generator_basepoint(void) { unsigned char s_one[32] = { 0 }; diff --git a/src/secp256k1/src/modules/recovery/main_impl.h b/src/secp256k1/src/modules/recovery/main_impl.h index 86f2f0cb2b..978f266c0c 100755 --- a/src/secp256k1/src/modules/recovery/main_impl.h +++ b/src/secp256k1/src/modules/recovery/main_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_MODULE_RECOVERY_MAIN_ -#define _SECP256K1_MODULE_RECOVERY_MAIN_ +#ifndef SECP256K1_MODULE_RECOVERY_MAIN_ +#define SECP256K1_MODULE_RECOVERY_MAIN_ #include "include/secp256k1_recovery.h" @@ -123,7 +123,7 @@ static int secp256k1_ecdsa_sig_recover(const secp256k1_ecmult_context *ctx, cons int secp256k1_ecdsa_sign_recoverable(const secp256k1_context* ctx, secp256k1_ecdsa_recoverable_signature *signature, const unsigned char *msg32, const unsigned char *seckey, secp256k1_nonce_function noncefp, const void* noncedata) { secp256k1_scalar r, s; secp256k1_scalar sec, non, msg; - int recid; + int recid = 0; int ret = 0; int overflow = 0; VERIFY_CHECK(ctx != NULL); diff --git a/src/secp256k1/src/modules/recovery/tests_impl.h b/src/secp256k1/src/modules/recovery/tests_impl.h index 8932d5f0af..a357fa93b1 100644 --- a/src/secp256k1/src/modules/recovery/tests_impl.h +++ b/src/secp256k1/src/modules/recovery/tests_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_MODULE_RECOVERY_TESTS_ -#define _SECP256K1_MODULE_RECOVERY_TESTS_ +#ifndef SECP256K1_MODULE_RECOVERY_TESTS_ +#define SECP256K1_MODULE_RECOVERY_TESTS_ void test_ecdsa_recovery_end_to_end(void) { unsigned char extra[32] = {0x00}; diff --git a/src/secp256k1/src/num.h b/src/secp256k1/src/num.h index 7bb9c5be8c..32e0ed2c50 100644 --- a/src/secp256k1/src/num.h +++ b/src/secp256k1/src/num.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_NUM_ -#define _SECP256K1_NUM_ +#ifndef SECP256K1_NUM_ +#define SECP256K1_NUM_ #ifndef USE_NUM_NONE @@ -20,54 +20,54 @@ #endif /** Copy a number. */ -static void secp256k1_num_copy(secp256k1_num *r, const secp256k1_num *a); +void secp256k1_num_copy(secp256k1_num *r, const secp256k1_num *a); /** Convert a number's absolute value to a binary big-endian string. * There must be enough place. */ -static void secp256k1_num_get_bin(unsigned char *r, unsigned int rlen, const secp256k1_num *a); +void secp256k1_num_get_bin(unsigned char *r, unsigned int rlen, const secp256k1_num *a); /** Set a number to the value of a binary big-endian string. */ -static void secp256k1_num_set_bin(secp256k1_num *r, const unsigned char *a, unsigned int alen); +void secp256k1_num_set_bin(secp256k1_num *r, const unsigned char *a, unsigned int alen); /** Compute a modular inverse. The input must be less than the modulus. */ -static void secp256k1_num_mod_inverse(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *m); +void secp256k1_num_mod_inverse(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *m); /** Compute the jacobi symbol (a|b). b must be positive and odd. */ -static int secp256k1_num_jacobi(const secp256k1_num *a, const secp256k1_num *b); +int secp256k1_num_jacobi(const secp256k1_num *a, const secp256k1_num *b); /** Compare the absolute value of two numbers. */ -static int secp256k1_num_cmp(const secp256k1_num *a, const secp256k1_num *b); +int secp256k1_num_cmp(const secp256k1_num *a, const secp256k1_num *b); /** Test whether two number are equal (including sign). */ -static int secp256k1_num_eq(const secp256k1_num *a, const secp256k1_num *b); +int secp256k1_num_eq(const secp256k1_num *a, const secp256k1_num *b); /** Add two (signed) numbers. */ -static void secp256k1_num_add(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); +void secp256k1_num_add(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); /** Subtract two (signed) numbers. */ -static void secp256k1_num_sub(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); +void secp256k1_num_sub(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); /** Multiply two (signed) numbers. */ -static void secp256k1_num_mul(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); +void secp256k1_num_mul(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); /** Replace a number by its remainder modulo m. M's sign is ignored. The result is a number between 0 and m-1, even if r was negative. */ -static void secp256k1_num_mod(secp256k1_num *r, const secp256k1_num *m); +void secp256k1_num_mod(secp256k1_num *r, const secp256k1_num *m); /** Right-shift the passed number by bits bits. */ -static void secp256k1_num_shift(secp256k1_num *r, int bits); +void secp256k1_num_shift(secp256k1_num *r, int bits); /** Check whether a number is zero. */ -static int secp256k1_num_is_zero(const secp256k1_num *a); +int secp256k1_num_is_zero(const secp256k1_num *a); /** Check whether a number is one. */ -static int secp256k1_num_is_one(const secp256k1_num *a); +int secp256k1_num_is_one(const secp256k1_num *a); /** Check whether a number is strictly negative. */ -static int secp256k1_num_is_neg(const secp256k1_num *a); +int secp256k1_num_is_neg(const secp256k1_num *a); /** Change a number's sign. */ -static void secp256k1_num_negate(secp256k1_num *r); +void secp256k1_num_negate(secp256k1_num *r); #endif diff --git a/src/secp256k1/src/num_gmp.h b/src/secp256k1/src/num_gmp.h index 7dd813088a..25fc5e29d8 100644 --- a/src/secp256k1/src/num_gmp.h +++ b/src/secp256k1/src/num_gmp.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_NUM_REPR_ -#define _SECP256K1_NUM_REPR_ +#ifndef SECP256K1_NUM_REPR_ +#define SECP256K1_NUM_REPR_ #include diff --git a/src/secp256k1/src/num_gmp_impl.h b/src/secp256k1/src/num_gmp_impl.h index 3a46495eea..64da08632f 100644 --- a/src/secp256k1/src/num_gmp_impl.h +++ b/src/secp256k1/src/num_gmp_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_NUM_REPR_IMPL_H_ -#define _SECP256K1_NUM_REPR_IMPL_H_ +#ifndef SECP256K1_NUM_REPR_IMPL_H_ +#define SECP256K1_NUM_REPR_IMPL_H_ #include #include @@ -15,18 +15,18 @@ #include "num.h" #ifdef VERIFY -static void secp256k1_num_sanity(const secp256k1_num *a) { +void secp256k1_num_sanity(const secp256k1_num *a) { VERIFY_CHECK(a->limbs == 1 || (a->limbs > 1 && a->data[a->limbs-1] != 0)); } #else #define secp256k1_num_sanity(a) do { } while(0) #endif -static void secp256k1_num_copy(secp256k1_num *r, const secp256k1_num *a) { +void secp256k1_num_copy(secp256k1_num *r, const secp256k1_num *a) { *r = *a; } -static void secp256k1_num_get_bin(unsigned char *r, unsigned int rlen, const secp256k1_num *a) { +void secp256k1_num_get_bin(unsigned char *r, unsigned int rlen, const secp256k1_num *a) { unsigned char tmp[65]; int len = 0; int shift = 0; @@ -42,7 +42,7 @@ static void secp256k1_num_get_bin(unsigned char *r, unsigned int rlen, const sec memset(tmp, 0, sizeof(tmp)); } -static void secp256k1_num_set_bin(secp256k1_num *r, const unsigned char *a, unsigned int alen) { +void secp256k1_num_set_bin(secp256k1_num *r, const unsigned char *a, unsigned int alen) { int len; VERIFY_CHECK(alen > 0); VERIFY_CHECK(alen <= 64); @@ -59,7 +59,7 @@ static void secp256k1_num_set_bin(secp256k1_num *r, const unsigned char *a, unsi } } -static void secp256k1_num_add_abs(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { +void secp256k1_num_add_abs(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { mp_limb_t c = mpn_add(r->data, a->data, a->limbs, b->data, b->limbs); r->limbs = a->limbs; if (c != 0) { @@ -68,7 +68,7 @@ static void secp256k1_num_add_abs(secp256k1_num *r, const secp256k1_num *a, cons } } -static void secp256k1_num_sub_abs(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { +void secp256k1_num_sub_abs(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { mp_limb_t c = mpn_sub(r->data, a->data, a->limbs, b->data, b->limbs); (void)c; VERIFY_CHECK(c == 0); @@ -78,7 +78,7 @@ static void secp256k1_num_sub_abs(secp256k1_num *r, const secp256k1_num *a, cons } } -static void secp256k1_num_mod(secp256k1_num *r, const secp256k1_num *m) { +void secp256k1_num_mod(secp256k1_num *r, const secp256k1_num *m) { secp256k1_num_sanity(r); secp256k1_num_sanity(m); @@ -98,7 +98,7 @@ static void secp256k1_num_mod(secp256k1_num *r, const secp256k1_num *m) { } } -static void secp256k1_num_mod_inverse(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *m) { +void secp256k1_num_mod_inverse(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *m) { int i; mp_limb_t g[NUM_LIMBS+1]; mp_limb_t u[NUM_LIMBS+1]; @@ -144,7 +144,7 @@ static void secp256k1_num_mod_inverse(secp256k1_num *r, const secp256k1_num *a, memset(v, 0, sizeof(v)); } -static int secp256k1_num_jacobi(const secp256k1_num *a, const secp256k1_num *b) { +int secp256k1_num_jacobi(const secp256k1_num *a, const secp256k1_num *b) { int ret; mpz_t ga, gb; secp256k1_num_sanity(a); @@ -166,19 +166,19 @@ static int secp256k1_num_jacobi(const secp256k1_num *a, const secp256k1_num *b) return ret; } -static int secp256k1_num_is_one(const secp256k1_num *a) { +int secp256k1_num_is_one(const secp256k1_num *a) { return (a->limbs == 1 && a->data[0] == 1); } -static int secp256k1_num_is_zero(const secp256k1_num *a) { +int secp256k1_num_is_zero(const secp256k1_num *a) { return (a->limbs == 1 && a->data[0] == 0); } -static int secp256k1_num_is_neg(const secp256k1_num *a) { +int secp256k1_num_is_neg(const secp256k1_num *a) { return (a->limbs > 1 || a->data[0] != 0) && a->neg; } -static int secp256k1_num_cmp(const secp256k1_num *a, const secp256k1_num *b) { +int secp256k1_num_cmp(const secp256k1_num *a, const secp256k1_num *b) { if (a->limbs > b->limbs) { return 1; } @@ -188,7 +188,7 @@ static int secp256k1_num_cmp(const secp256k1_num *a, const secp256k1_num *b) { return mpn_cmp(a->data, b->data, a->limbs); } -static int secp256k1_num_eq(const secp256k1_num *a, const secp256k1_num *b) { +int secp256k1_num_eq(const secp256k1_num *a, const secp256k1_num *b) { if (a->limbs > b->limbs) { return 0; } @@ -201,7 +201,7 @@ static int secp256k1_num_eq(const secp256k1_num *a, const secp256k1_num *b) { return mpn_cmp(a->data, b->data, a->limbs) == 0; } -static void secp256k1_num_subadd(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b, int bneg) { +void secp256k1_num_subadd(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b, int bneg) { if (!(b->neg ^ bneg ^ a->neg)) { /* a and b have the same sign */ r->neg = a->neg; if (a->limbs >= b->limbs) { @@ -220,19 +220,19 @@ static void secp256k1_num_subadd(secp256k1_num *r, const secp256k1_num *a, const } } -static void secp256k1_num_add(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { +void secp256k1_num_add(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { secp256k1_num_sanity(a); secp256k1_num_sanity(b); secp256k1_num_subadd(r, a, b, 0); } -static void secp256k1_num_sub(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { +void secp256k1_num_sub(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { secp256k1_num_sanity(a); secp256k1_num_sanity(b); secp256k1_num_subadd(r, a, b, 1); } -static void secp256k1_num_mul(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { +void secp256k1_num_mul(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { mp_limb_t tmp[2*NUM_LIMBS+1]; secp256k1_num_sanity(a); secp256k1_num_sanity(b); @@ -259,7 +259,7 @@ static void secp256k1_num_mul(secp256k1_num *r, const secp256k1_num *a, const se memset(tmp, 0, sizeof(tmp)); } -static void secp256k1_num_shift(secp256k1_num *r, int bits) { +void secp256k1_num_shift(secp256k1_num *r, int bits) { if (bits % GMP_NUMB_BITS) { /* Shift within limbs. */ mpn_rshift(r->data, r->data, r->limbs, bits % GMP_NUMB_BITS); @@ -281,7 +281,7 @@ static void secp256k1_num_shift(secp256k1_num *r, int bits) { } } -static void secp256k1_num_negate(secp256k1_num *r) { +void secp256k1_num_negate(secp256k1_num *r) { r->neg ^= 1; } diff --git a/src/secp256k1/src/num_impl.h b/src/secp256k1/src/num_impl.h index 0b0e3a072a..1a5fe0f193 100644 --- a/src/secp256k1/src/num_impl.h +++ b/src/secp256k1/src/num_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_NUM_IMPL_H_ -#define _SECP256K1_NUM_IMPL_H_ +#ifndef SECP256K1_NUM_IMPL_H_ +#define SECP256K1_NUM_IMPL_H_ #if defined HAVE_CONFIG_H #include "libsecp256k1-config.h" diff --git a/src/secp256k1/src/scalar.h b/src/secp256k1/src/scalar.h index 27e9d8375e..1f5ebe3734 100644 --- a/src/secp256k1/src/scalar.h +++ b/src/secp256k1/src/scalar.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_SCALAR_ -#define _SECP256K1_SCALAR_ +#ifndef SECP256K1_SCALAR_ +#define SECP256K1_SCALAR_ #include "num.h" diff --git a/src/secp256k1/src/scalar_4x64.h b/src/secp256k1/src/scalar_4x64.h index cff406038f..d38413746c 100644 --- a/src/secp256k1/src/scalar_4x64.h +++ b/src/secp256k1/src/scalar_4x64.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_SCALAR_REPR_ -#define _SECP256K1_SCALAR_REPR_ +#ifndef SECP256K1_SCALAR_REPR_ +#define SECP256K1_SCALAR_REPR_ #include diff --git a/src/secp256k1/src/scalar_4x64_impl.h b/src/secp256k1/src/scalar_4x64_impl.h index 56e7bd82af..bec60c79a6 100644 --- a/src/secp256k1/src/scalar_4x64_impl.h +++ b/src/secp256k1/src/scalar_4x64_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_SCALAR_REPR_IMPL_H_ -#define _SECP256K1_SCALAR_REPR_IMPL_H_ +#ifndef SECP256K1_SCALAR_REPR_IMPL_H_ +#define SECP256K1_SCALAR_REPR_IMPL_H_ /* Limbs of the secp256k1 order. */ #define SECP256K1_N_0 ((uint64_t)0xBFD25E8CD0364141ULL) diff --git a/src/secp256k1/src/scalar_8x32.h b/src/secp256k1/src/scalar_8x32.h index 1319664f65..5b82d776fc 100644 --- a/src/secp256k1/src/scalar_8x32.h +++ b/src/secp256k1/src/scalar_8x32.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_SCALAR_REPR_ -#define _SECP256K1_SCALAR_REPR_ +#ifndef SECP256K1_SCALAR_REPR_ +#define SECP256K1_SCALAR_REPR_ #include diff --git a/src/secp256k1/src/scalar_8x32_impl.h b/src/secp256k1/src/scalar_8x32_impl.h index aae4f35c08..6368b7aabf 100644 --- a/src/secp256k1/src/scalar_8x32_impl.h +++ b/src/secp256k1/src/scalar_8x32_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_SCALAR_REPR_IMPL_H_ -#define _SECP256K1_SCALAR_REPR_IMPL_H_ +#ifndef SECP256K1_SCALAR_REPR_IMPL_H_ +#define SECP256K1_SCALAR_REPR_IMPL_H_ /* Limbs of the secp256k1 order. */ #define SECP256K1_N_0 ((uint32_t)0xD0364141UL) diff --git a/src/secp256k1/src/scalar_impl.h b/src/secp256k1/src/scalar_impl.h index f5b2376407..9bded8f401 100644 --- a/src/secp256k1/src/scalar_impl.h +++ b/src/secp256k1/src/scalar_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_SCALAR_IMPL_H_ -#define _SECP256K1_SCALAR_IMPL_H_ +#ifndef SECP256K1_SCALAR_IMPL_H_ +#define SECP256K1_SCALAR_IMPL_H_ #include "group.h" #include "scalar.h" diff --git a/src/secp256k1/src/scalar_low.h b/src/secp256k1/src/scalar_low.h index 5574c44c7a..a6a16e3784 100644 --- a/src/secp256k1/src/scalar_low.h +++ b/src/secp256k1/src/scalar_low.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_SCALAR_REPR_ -#define _SECP256K1_SCALAR_REPR_ +#ifndef SECP256K1_SCALAR_REPR_ +#define SECP256K1_SCALAR_REPR_ #include diff --git a/src/secp256k1/src/scalar_low_impl.h b/src/secp256k1/src/scalar_low_impl.h index 4f94441f49..ae720267c9 100644 --- a/src/secp256k1/src/scalar_low_impl.h +++ b/src/secp256k1/src/scalar_low_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_SCALAR_REPR_IMPL_H_ -#define _SECP256K1_SCALAR_REPR_IMPL_H_ +#ifndef SECP256K1_SCALAR_REPR_IMPL_H_ +#define SECP256K1_SCALAR_REPR_IMPL_H_ #include "scalar.h" diff --git a/src/secp256k1/src/scratch.h b/src/secp256k1/src/scratch.h index fef377af0d..e31285b598 100644 --- a/src/secp256k1/src/scratch.h +++ b/src/secp256k1/src/scratch.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_SCRATCH_ -#define _SECP256K1_SCRATCH_ +#ifndef SECP256K1_SCRATCH_ +#define SECP256K1_SCRATCH_ #define SECP256K1_SCRATCH_MAX_FRAMES 5 diff --git a/src/secp256k1/src/scratch_impl.h b/src/secp256k1/src/scratch_impl.h index c8a77e362f..dcfeb17749 100644 --- a/src/secp256k1/src/scratch_impl.h +++ b/src/secp256k1/src/scratch_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_SCRATCH_IMPL_H_ -#define _SECP256K1_SCRATCH_IMPL_H_ +#ifndef SECP256K1_SCRATCH_IMPL_H_ +#define SECP256K1_SCRATCH_IMPL_H_ #include "scratch.h" #include diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index fb8b882faa..a89208d3bc 100755 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -4,6 +4,10 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ +#ifndef SECP256K1_BUILD +#define SECP256K1_BUILD +#endif + #include "include/secp256k1.h" #include "util.h" @@ -552,10 +556,6 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif -#ifdef ENABLE_MODULE_SCHNORR -# include "modules/schnorr/main_impl.h" -#endif - #ifdef ENABLE_MODULE_RECOVERY # include "modules/recovery/main_impl.h" #endif diff --git a/src/secp256k1/src/testrand.h b/src/secp256k1/src/testrand.h index f8efa93c7c..e2b62a910f 100644 --- a/src/secp256k1/src/testrand.h +++ b/src/secp256k1/src/testrand.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_TESTRAND_H_ -#define _SECP256K1_TESTRAND_H_ +#ifndef SECP256K1_TESTRAND_H_ +#define SECP256K1_TESTRAND_H_ #if defined HAVE_CONFIG_H #include "libsecp256k1-config.h" diff --git a/src/secp256k1/src/testrand_impl.h b/src/secp256k1/src/testrand_impl.h index 15c7b9f12d..977707221a 100644 --- a/src/secp256k1/src/testrand_impl.h +++ b/src/secp256k1/src/testrand_impl.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_TESTRAND_IMPL_H_ -#define _SECP256K1_TESTRAND_IMPL_H_ +#ifndef SECP256K1_TESTRAND_IMPL_H_ +#define SECP256K1_TESTRAND_IMPL_H_ #include #include diff --git a/src/secp256k1/src/tests.c b/src/secp256k1/src/tests.c index 9ae7d30281..f52c6367a2 100644 --- a/src/secp256k1/src/tests.c +++ b/src/secp256k1/src/tests.c @@ -2952,7 +2952,7 @@ void run_ec_pubkey_parse_test(void) { 0xB8, 0x00 }; unsigned char sout[65]; - unsigned char shortkey[2]; + unsigned char shortkey[2] = {0}; secp256k1_ge ge; secp256k1_pubkey pubkey; size_t len; @@ -3348,8 +3348,8 @@ void test_ecdsa_sign_verify(void) { secp256k1_scalar one; secp256k1_scalar msg, key; secp256k1_scalar sigr, sigs; - int recid; - int getrec; + int recid = 0; + int getrec = 0; random_scalar_order_test(&msg); random_scalar_order_test(&key); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pubj, &key); diff --git a/src/secp256k1/src/util.h b/src/secp256k1/src/util.h index 68b8d406b9..d82ac54595 100644 --- a/src/secp256k1/src/util.h +++ b/src/secp256k1/src/util.h @@ -4,8 +4,8 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#ifndef _SECP256K1_UTIL_H_ -#define _SECP256K1_UTIL_H_ +#ifndef SECP256K1_UTIL_H_ +#define SECP256K1_UTIL_H_ #if defined HAVE_CONFIG_H #include "libsecp256k1-config.h" diff --git a/src/sigma.cpp b/src/sigma.cpp index 36c9a1e044..dc84794070 100644 --- a/src/sigma.cpp +++ b/src/sigma.cpp @@ -484,7 +484,7 @@ bool CheckSigmaTransaction( } std::vector denominations; - uint64_t totalValue = 0; + FIRO_UNUSED uint64_t totalValue = 0; BOOST_FOREACH(const CTxIn &txin, tx.vin){ if(!txin.scriptSig.IsSigmaSpend()) { return state.DoS(100, false, diff --git a/src/sigma.h b/src/sigma.h index ac7ef2d10d..efa0709338 100644 --- a/src/sigma.h +++ b/src/sigma.h @@ -15,8 +15,8 @@ #include "coin_containers.h" //tests -namespace sigma_mintspend_many { class sigma_mintspend_many; } -namespace sigma_mintspend { class sigma_mintspend_test; } +namespace sigma_mintspend_many { struct sigma_mintspend_many; } +namespace sigma_mintspend { struct sigma_mintspend_test; } namespace sigma_partialspend_mempool_tests { class partialspend; } namespace zerocoin_tests3_v3 { class zerocoin_mintspend_v3; } @@ -252,17 +252,17 @@ friend bool BuildSigmaStateFromIndex(CChain *, std::set &); void CheckSurgeCondition(int groupId, CoinDenomination denom); - friend class sigma_mintspend_many::sigma_mintspend_many; + friend struct sigma_mintspend_many::sigma_mintspend_many; friend class zerocoin_tests3_v3::zerocoin_mintspend_v3; - friend class sigma_mintspend::sigma_mintspend_test; + friend struct sigma_mintspend::sigma_mintspend_test; friend class sigma_partialspend_mempool_tests::partialspend; }; Containers containers; - friend class sigma_mintspend_many::sigma_mintspend_many; + friend struct sigma_mintspend_many::sigma_mintspend_many; friend class zerocoin_tests3_v3::zerocoin_mintspend_v3; - friend class sigma_mintspend::sigma_mintspend_test; + friend struct sigma_mintspend::sigma_mintspend_test; friend class sigma_partialspend_mempool_tests::partialspend; }; diff --git a/src/sigma/sigma_primitives.hpp b/src/sigma/sigma_primitives.hpp index ce3c8ee93a..2db8639ca3 100644 --- a/src/sigma/sigma_primitives.hpp +++ b/src/sigma/sigma_primitives.hpp @@ -1,4 +1,4 @@ -#include "../../crypto/sha256.h" +#include "../crypto/sha256.h" namespace sigma { diff --git a/src/sigma/test/r1_test.cpp b/src/sigma/test/r1_test.cpp index 6e40af3f37..df29846456 100644 --- a/src/sigma/test/r1_test.cpp +++ b/src/sigma/test/r1_test.cpp @@ -50,11 +50,12 @@ BOOST_AUTO_TEST_CASE(serialize_deserialize_proof) sigma::R1ProofVerifier verifier(g,h_,prover.get_B(), n, m); BOOST_CHECK(verifier.verify(proof)); - unsigned char buffer [proof.memoryRequired(n, m)]; - proof.serialize(buffer); + auto size = proof.memoryRequired(n, m); + std::vector buffer(size); + proof.serialize(buffer.data()); sigma::R1Proof resulted; - resulted.deserialize(buffer,n, m); + resulted.deserialize(buffer.data(), n, m); BOOST_CHECK(verifier.verify(resulted)); } diff --git a/src/sigma/test/serialize_test.cpp b/src/sigma/test/serialize_test.cpp index ff9069f160..895f5fbf92 100644 --- a/src/sigma/test/serialize_test.cpp +++ b/src/sigma/test/serialize_test.cpp @@ -90,10 +90,11 @@ BOOST_AUTO_TEST_CASE(proof_serialize) prover.proof(commits, index, r, true, initial_proof); - unsigned char buffer [initial_proof.memoryRequired()]; - initial_proof.serialize(buffer); + auto size = initial_proof.memoryRequired(); + std::vector buffer(size); + initial_proof.serialize(buffer.data()); sigma::SigmaPlusProof resulted_proof(n, m); - resulted_proof.deserialize(buffer); + resulted_proof.deserialize(buffer.data()); BOOST_CHECK(initial_proof.B_ == resulted_proof.B_); BOOST_CHECK(initial_proof.r1Proof_.A_ == resulted_proof.r1Proof_.A_); diff --git a/src/spark/sparkwallet.cpp b/src/spark/sparkwallet.cpp index 05ce3b53c9..f4a1e88959 100644 --- a/src/spark/sparkwallet.cpp +++ b/src/spark/sparkwallet.cpp @@ -373,7 +373,7 @@ void CSparkWallet::eraseMint(const uint256& hash, CWalletDB& walletdb) { void CSparkWallet::addOrUpdateMint(const CSparkMintMeta& mint, const uint256& lTagHash, CWalletDB& walletdb) { LOCK(cs_spark_wallet); - if (mint.i > lastDiversifier) { + if (cmp::greater(mint.i, lastDiversifier)) { lastDiversifier = mint.i; walletdb.writeDiversifier(lastDiversifier); } @@ -709,7 +709,7 @@ std::vector CSparkWallet::listAddressCoins(const int32_t& i, boo std::vector listMints; LOCK(cs_spark_wallet); for (auto& itr : coinMeta) { - if (itr.second.i == i) { + if (cmp::equal(itr.second.i, i)) { if (fUnusedOnly && itr.second.isUsed) continue; listMints.push_back(itr.second); @@ -899,7 +899,7 @@ bool CSparkWallet::CreateSparkMintTransactions( CAmount singleFee = nFeeRet / singleTxOutputs.size(); CAmount reminder = nFeeRet % singleTxOutputs.size(); for (size_t i = 0; i < singleTxOutputs.size(); ++i) { - if (singleTxOutputs[i].v <= singleFee) { + if (cmp::less_equal(singleTxOutputs[i].v, singleFee)) { singleTxOutputs.erase(singleTxOutputs.begin() + i); reminder += singleTxOutputs[i].v - singleFee; if (!singleTxOutputs.size()) { @@ -1088,7 +1088,7 @@ bool CSparkWallet::CreateSparkMintTransactions( if (nFeeRet >= nFeeNeeded) { for (auto &usedCoin : setCoins) { for (auto coin = itr->second.begin(); coin != itr->second.end(); coin++) { - if (usedCoin.first == coin->tx && usedCoin.second == coin->i) { + if (usedCoin.first == coin->tx && cmp::equal(usedCoin.second, coin->i)) { itr->first -= coin->tx->tx->vout[coin->i].nValue; itr->second.erase(coin); break; @@ -1483,7 +1483,7 @@ CWalletTx CSparkWallet::CreateSparkSpendTransaction( for (auto& coin : estimated.second) { spark::CSparkState::SparkCoinGroupInfo nextCoinGroupInfo; uint64_t groupId = coin.nId; - if (sparkState->GetLatestCoinID() > groupId && sparkState->GetCoinGroupInfo(groupId + 1, nextCoinGroupInfo)) { + if (cmp::greater(sparkState->GetLatestCoinID(), groupId) && sparkState->GetCoinGroupInfo(groupId + 1, nextCoinGroupInfo)) { if (nextCoinGroupInfo.firstBlock->nHeight <= coin.nHeight) groupId += 1; } @@ -1709,7 +1709,7 @@ bool GetCoinsToSpend( CAmount need = required - spend_val; auto itr = coins.begin(); - if (need >= itr->v) { + if (cmp::greater_equal(need, itr->v)) { choosen = *itr; coins.erase(itr); } else { @@ -1717,7 +1717,7 @@ bool GetCoinsToSpend( auto nextItr = coinIt; nextItr++; - if (coinIt->v >= need && (nextItr == coins.rend() || nextItr->v != coinIt->v)) { + if (cmp::greater_equal(coinIt->v, need) && (nextItr == coins.rend() || nextItr->v != coinIt->v)) { choosen = *coinIt; coins.erase(std::next(coinIt).base()); break; diff --git a/src/spark/sparkwallet.h b/src/spark/sparkwallet.h index c120a60355..bd8408e940 100644 --- a/src/spark/sparkwallet.h +++ b/src/spark/sparkwallet.h @@ -13,7 +13,7 @@ #include "../sync.h" #include "../sparkname.h" -class CRecipient; +struct CRecipient; class CReserveKey; class CCoinControl; extern CChain chainActive; diff --git a/src/spark/state.cpp b/src/spark/state.cpp index 476206dff1..f0415654df 100644 --- a/src/spark/state.cpp +++ b/src/spark/state.cpp @@ -1,4 +1,5 @@ #include "state.h" +#include "compat_layer.h" #include "sparkname.h" #include "../validation.h" #include "../batchproof_container.h" @@ -175,7 +176,7 @@ spark::SpendTransaction ParseSparkSpend(const CTransaction &tx) const spark::Params* params = spark::Params::get_default(); spark::SpendTransaction spendTransaction(params); serialized >> spendTransaction; - return std::move(spendTransaction); + return spendTransaction; } @@ -285,7 +286,7 @@ bool ConnectBlockSpark( return true; } - const auto& params = ::Params().GetConsensus(); + FIRO_UNUSED const auto& params = ::Params().GetConsensus(); CHash256 hash; bool updateHash = false; @@ -314,7 +315,7 @@ bool ConnectBlockSpark( } if (!pblock->sparkTxInfo->sparkNames.empty()) { - CSparkNameManager *sparkNameManager = CSparkNameManager::GetInstance(); + FIRO_UNUSED CSparkNameManager *sparkNameManager = CSparkNameManager::GetInstance(); for (const auto &sparkName : pblock->sparkTxInfo->sparkNames) { pindexNew->addedSparkNames[sparkName.first] = CSparkNameBlockIndexData(sparkName.second.name, @@ -412,7 +413,7 @@ bool CheckSparkBlock(CValidationState &state, const CBlock& block) { blockSpendsValue += txSpendsValue; } - if (blockSpendsValue > consensus.nMaxValueSparkSpendPerBlock) { + if (cmp::greater(blockSpendsValue, consensus.nMaxValueSparkSpendPerBlock)) { return state.DoS(100, false, REJECT_INVALID, "bad-txns-spark-spend-invalid"); } @@ -464,7 +465,7 @@ bool CheckSparkMintTransaction( for (size_t i = 0; i < coins.size(); i++) { auto& coin = coins[i]; - if (coin.v != txOuts[i].nValue) + if (cmp::not_equal(coin.v, txOuts[i].nValue)) return state.DoS(100, false, PUBCOIN_NOT_VALIDATE, @@ -913,7 +914,7 @@ std::vector getSerialContext(const CTransaction &tx) { return serial_context; } -static bool CheckSparkSpendTAg( +FIRO_UNUSED static bool CheckSparkSpendTAg( CValidationState& state, CSparkTxInfo* sparkTxInfo, const GroupElement& tag, @@ -1154,7 +1155,7 @@ void CSparkState::RemoveBlock(CBlockIndex *index) { if (nMintsToForget == 0) continue; - assert(coinGroup.nCoins >= nMintsToForget); + assert(cmp::greater_equal(coinGroup.nCoins, nMintsToForget)); auto isExtended = coins.first > 1; coinGroup.nCoins -= nMintsToForget; @@ -1257,7 +1258,7 @@ void CSparkState::GetCoinSet( uint256 blockHash; std::vector setHash; { - const auto ¶ms = ::Params().GetConsensus(); + FIRO_UNUSED const auto ¶ms = ::Params().GetConsensus(); LOCK(cs_main); maxHeight = chainActive.Height() - (ZC_MINT_CONFIRMATIONS - 1); } @@ -1422,7 +1423,7 @@ void CSparkState::GetCoinsForRecovery( std::vector>>>& coins) { coins.clear(); if (coinGroups.count(coinGroupID) == 0) { - throw std::runtime_error(std::string("There is no anonymity set with this id: " + coinGroupID)); + throw std::runtime_error(std::string("There is no anonymity set with this id: " + std::to_string(coinGroupID))); } SparkCoinGroupInfo &coinGroup = coinGroups[coinGroupID]; CBlockIndex *index = coinGroup.lastBlock; @@ -1450,11 +1451,11 @@ void CSparkState::GetCoinsForRecovery( if (id) { if (block->sparkMintedCoins.count(id) > 0) { for (const auto &coin : block->sparkMintedCoins[id]) { - if (counter < startIndex) { + if (cmp::less(counter, startIndex)) { ++counter; continue; } - if (counter >= endIndex) { + if (cmp::greater_equal(counter, endIndex)) { break; } std::pair> txHashContext; @@ -1465,7 +1466,7 @@ void CSparkState::GetCoinsForRecovery( } } } - if (block == coinGroup.firstBlock || counter >= endIndex) { + if (block == coinGroup.firstBlock || cmp::greater_equal(counter, endIndex)) { break ; } } diff --git a/src/spark/state.h b/src/spark/state.h index 87ee567363..37fe407608 100644 --- a/src/spark/state.h +++ b/src/spark/state.h @@ -13,7 +13,7 @@ #include "primitives.h" #include "sparkname.h" -namespace spark_mintspend { class spark_mintspend_test; } +namespace spark_mintspend { struct spark_mintspend_test; } namespace spark { @@ -269,7 +269,7 @@ class CSparkState { typedef std::map metainfo_container_t; metainfo_container_t extendedMintMetaInfo, mintMetaInfo, spendMetaInfo; - friend class spark_mintspend::spark_mintspend_test; + friend struct spark_mintspend::spark_mintspend_test; }; } // namespace spark diff --git a/src/sparkname.cpp b/src/sparkname.cpp index 70cecd5b60..27518cf7e7 100644 --- a/src/sparkname.cpp +++ b/src/sparkname.cpp @@ -236,6 +236,16 @@ bool CSparkNameManager::CheckSparkNameTx(const CTransaction &tx, int nHeight, CV return true; } +bool CSparkNameManager::GetSparkNameByAddress(const std::string& address, std::string& name) +{ + auto it = sparkNameAddresses.find(address); + if (it != sparkNameAddresses.end()) { + name = sparkNames[it->second].name; + return true; + } + return false; +} + bool CSparkNameManager::ValidateSparkNameData(const CSparkNameTxData &sparkNameData, std::string &errorDescription) { errorDescription.clear(); @@ -367,7 +377,7 @@ std::map CSparkNameManager::RemoveSparkNa std::map result; for (auto it = sparkNames.begin(); it != sparkNames.end();) - if (nHeight >= it->second.sparkNameValidityHeight) { + if (cmp::greater_equal(nHeight, it->second.sparkNameValidityHeight)) { std::string sparkAddressStr = it->second.sparkAddress; sparkNameAddresses.erase(sparkAddressStr); result[it->first] = it->second; diff --git a/src/sparkname.h b/src/sparkname.h index c0c7218f09..84bc8b4871 100644 --- a/src/sparkname.h +++ b/src/sparkname.h @@ -8,10 +8,6 @@ #include "libspark/keys.h" #include "libspark/spend_transaction.h" -namespace spark { - unsigned char GetNetworkType(); -} - /* * Spark alias transaction data. This is to be stored in the transaction's extra data field * right after Spark data. The transaction is considered a Spark alias transaction if it spends @@ -146,6 +142,9 @@ class CSparkNameManager // check the possibility to register a new spark name, return true if it's possible bool ValidateSparkNameData(const CSparkNameTxData &sparkNameData, std::string &errorDescription); + // Checking if an address is occupied with spark name + bool GetSparkNameByAddress(const std::string& address, std::string& name); + // get the size of the spark name transaction metadata size_t GetSparkNameTxDataSize(const CSparkNameTxData &sparkNameData); diff --git a/src/stacktraces.cpp b/src/stacktraces.cpp index dc485f71e1..5365da5a8c 100644 --- a/src/stacktraces.cpp +++ b/src/stacktraces.cpp @@ -10,7 +10,8 @@ #include "util.h" #include "utilstrencodings.h" -#include "bitcoin-config.h" +#include "config/bitcoin-config.h" + #include #include @@ -533,16 +534,18 @@ static void PrintCrashInfo(const crash_info& ci) static std::mutex g_stacktraces_mutex; static std::map>> g_stacktraces; -#if CRASH_HOOKS_WRAPPED_CXX_ABI +#ifdef CRASH_HOOKS_WRAPPED_CXX_ABI // These come in through -Wl,-wrap // It only works on GCC extern "C" void* __real___cxa_allocate_exception(size_t thrown_size); extern "C" void __real___cxa_free_exception(void * thrown_exception); -#if __clang__ +#if __clang__ && defined(WIN32) #error not supported on WIN32 (no dlsym support) #elif WIN32 extern "C" void __real__assert(const char *assertion, const char *file, unsigned int line); extern "C" void __real__wassert(const wchar_t *assertion, const wchar_t *file, unsigned int line); +#elif __APPLE__ +extern "C" void __real___assert_rtn(const char *function, const char *file, int line, const char *assertion); #else extern "C" void __real___assert_fail(const char *assertion, const char *file, unsigned int line, const char *function); #endif @@ -576,7 +579,7 @@ extern "C" void __real___assert_fail(const char *assertion, const char *file, un #endif #endif -#if CRASH_HOOKS_WRAPPED_CXX_ABI +#ifdef CRASH_HOOKS_WRAPPED_CXX_ABI #define WRAPPED_NAME(x) __wrap_##x #else #define WRAPPED_NAME(x) x diff --git a/src/support/allocators/mt_pooled_secure.h b/src/support/allocators/mt_pooled_secure.h index d857da1616..aded9b8ae1 100644 --- a/src/support/allocators/mt_pooled_secure.h +++ b/src/support/allocators/mt_pooled_secure.h @@ -63,7 +63,7 @@ struct mt_pooled_secure_allocator : public std::allocator { private: size_t get_bucket() { - auto tid = std::this_thread::get_id(); + FIRO_UNUSED auto tid = std::this_thread::get_id(); size_t x = std::hash{}(std::this_thread::get_id()); return x % pools.size(); } diff --git a/src/support/allocators/pooled_secure.h b/src/support/allocators/pooled_secure.h index 03fb2610ce..4c531c67f4 100644 --- a/src/support/allocators/pooled_secure.h +++ b/src/support/allocators/pooled_secure.h @@ -8,6 +8,8 @@ #include "support/lockedpool.h" #include "support/cleanse.h" +#include "../../compat_layer.h" + #include #include diff --git a/src/support/allocators/secure.h b/src/support/allocators/secure.h index 7fc0e269f4..3477c2933d 100644 --- a/src/support/allocators/secure.h +++ b/src/support/allocators/secure.h @@ -19,14 +19,15 @@ template struct secure_allocator : public std::allocator { // MSVC8 default copy constructor is broken - typedef std::allocator base; - typedef typename base::size_type size_type; - typedef typename base::difference_type difference_type; - typedef typename base::pointer pointer; - typedef typename base::const_pointer const_pointer; - typedef typename base::reference reference; - typedef typename base::const_reference const_reference; - typedef typename base::value_type value_type; + using base = std::allocator; + using size_type = std::size_t; + using difference_type = std::ptrdiff_t; + using value_type = T; + using pointer = T*; + using const_pointer = const T*; + using reference = T&; + using const_reference = const T&; + secure_allocator() throw() {} secure_allocator(const secure_allocator& a) throw() : base(a) {} template diff --git a/src/support/allocators/zeroafterfree.h b/src/support/allocators/zeroafterfree.h index 8ac7f890ed..5da7ebfd45 100644 --- a/src/support/allocators/zeroafterfree.h +++ b/src/support/allocators/zeroafterfree.h @@ -14,14 +14,15 @@ template struct zero_after_free_allocator : public std::allocator { // MSVC8 default copy constructor is broken - typedef std::allocator base; - typedef typename base::size_type size_type; - typedef typename base::difference_type difference_type; - typedef typename base::pointer pointer; - typedef typename base::const_pointer const_pointer; - typedef typename base::reference reference; - typedef typename base::const_reference const_reference; - typedef typename base::value_type value_type; + using base = std::allocator; + using size_type = std::size_t; + using difference_type = std::ptrdiff_t; + using value_type = T; + using pointer = T*; + using const_pointer = const T*; + using reference = T&; + using const_reference = const T&; + zero_after_free_allocator() throw() {} zero_after_free_allocator(const zero_after_free_allocator& a) throw() : base(a) {} template diff --git a/src/support/lockedpool.cpp b/src/support/lockedpool.cpp index 7464e327e5..258c6dacf2 100644 --- a/src/support/lockedpool.cpp +++ b/src/support/lockedpool.cpp @@ -149,9 +149,9 @@ class Win32LockedPageAllocator: public LockedPageAllocator { public: Win32LockedPageAllocator(); - void* AllocateLocked(size_t len, bool *lockingSuccess); - void FreeLocked(void* addr, size_t len); - size_t GetLimit(); + void* AllocateLocked(size_t len, bool *lockingSuccess) override; + void FreeLocked(void* addr, size_t len) override; + size_t GetLimit() override; private: size_t page_size; }; @@ -201,9 +201,9 @@ class PosixLockedPageAllocator: public LockedPageAllocator { public: PosixLockedPageAllocator(); - void* AllocateLocked(size_t len, bool *lockingSuccess); - void FreeLocked(void* addr, size_t len); - size_t GetLimit(); + void* AllocateLocked(size_t len, bool *lockingSuccess) override; + void FreeLocked(void* addr, size_t len) override; + size_t GetLimit() override; private: size_t page_size; }; diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt new file mode 100644 index 0000000000..b5f5a05c53 --- /dev/null +++ b/src/test/CMakeLists.txt @@ -0,0 +1,226 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +include(GenerateHeaders) +generate_header_from_json(data/base58_encode_decode.json) +generate_header_from_json(data/base58_keys_invalid.json) +generate_header_from_json(data/base58_keys_valid.json) +generate_header_from_json(data/script_tests.json) +generate_header_from_json(data/sighash.json) +generate_header_from_json(data/tx_invalid.json) +generate_header_from_json(data/tx_valid.json) + +# Do not use generator expressions in test sources because the +# SOURCES property is processed to gather test suite macros. +add_executable(test_firo + ${CMAKE_CURRENT_BINARY_DIR}/data/base58_encode_decode.json.h + ${CMAKE_CURRENT_BINARY_DIR}/data/base58_keys_invalid.json.h + ${CMAKE_CURRENT_BINARY_DIR}/data/base58_keys_valid.json.h + ${CMAKE_CURRENT_BINARY_DIR}/data/script_tests.json.h + ${CMAKE_CURRENT_BINARY_DIR}/data/sighash.json.h + ${CMAKE_CURRENT_BINARY_DIR}/data/tx_invalid.json.h + ${CMAKE_CURRENT_BINARY_DIR}/data/tx_valid.json.h + ${CMAKE_CURRENT_SOURCE_DIR}/addrman_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/allocator_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/amount_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/arith_uint256_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/base32_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/base58_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/base64_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bip32_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bip47_test_data.h + ${CMAKE_CURRENT_SOURCE_DIR}/bip47_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bip47_serialization_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/blockencodings_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bloom_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bswap_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/checkqueue_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/coins_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/compress_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/crypto_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/cuckoocache_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/DoS_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures.h + ${CMAKE_CURRENT_SOURCE_DIR}/getarg_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/hash_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/key_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/dbwrapper_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/lelantus_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/lelantus_mintspend_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/lelantus_state_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigma_lelantus_transition.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/limitedmap_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/main_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/mbstring_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/mempool_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/merkle_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/miner_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/mtp_halving_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/mtp_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/mtp_trans_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/firopow_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/multisig_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/netbase_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/net_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/pmt_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/prevector_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/raii_event_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/random_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/reverselock_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpc_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sanity_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/scheduler_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/scriptnum10.h + ${CMAKE_CURRENT_SOURCE_DIR}/scriptnum_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/script_P2SH_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/script_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/serialize_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sighash_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigma_manymintspend_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigma_mintspend_numinputs.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigma_mintspend_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigma_state_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigopcount_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/skiplist_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/streams_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test_bitcoin.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test_bitcoin.h + ${CMAKE_CURRENT_SOURCE_DIR}/test_random.h + ${CMAKE_CURRENT_SOURCE_DIR}/testutil.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/testutil.h + ${CMAKE_CURRENT_SOURCE_DIR}/timedata_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/transaction_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/txdb_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/txvalidationcache_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/uint256_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/univalue_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/util_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/multiexponentation_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/firsthalving_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/evospork_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/evo_deterministicmns_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/evo_simplifiedmns_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/progpow_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bls_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sparkname_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../hdmint/test/hdmint_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../hdmint/test/lelantus_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../liblelantus/test/challenge_generator_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../liblelantus/test/coin_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../liblelantus/test/inner_product_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../liblelantus/test/joinsplit_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../liblelantus/test/lelantus_primitives_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../liblelantus/test/lelantus_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../liblelantus/test/lelantus_test_fixture.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../liblelantus/test/lelantus_test_fixture.h + ${CMAKE_CURRENT_SOURCE_DIR}/../liblelantus/test/range_proof_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../liblelantus/test/schnorr_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/ownership_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../liblelantus/test/serialize_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../liblelantus/test/sigma_extended_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/transcript_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/schnorr_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/chaum_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/bpplus_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/grootle_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/aead_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/encrypt_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/coin_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/mint_transaction_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/spend_transaction_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/f4grumble_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../libspark/test/address_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../test/spark_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../test/spark_state_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../test/spark_mintspend_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../sigma/test/coin_spend_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../sigma/test/coin_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../sigma/test/primitives_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../sigma/test/protocol_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../sigma/test/r1_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../sigma/test/serialize_test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../sigma/test/sigma_primitive_types_test.cpp +) + +target_link_libraries(test_firo + core_interface + firo_cli + firo_node + bitcoin_consensus + secp256k1 + Boost::headers + libevent::extra + secp256k1pp + univalue + leveldb + firo_wallet + ${TOR_LIBRARY} + Boost::filesystem +) + +target_include_directories(test_firo + PUBLIC + ${CMAKE_CURRENT_BINARY_DIR} +) + +apply_wrapped_exception_flags(test_firo) + +if(ENABLE_WALLET) + add_subdirectory(${PROJECT_SOURCE_DIR}/src/wallet/test wallet) +endif() + +if(WITH_MULTIPROCESS) + target_link_libraries(bitcoin_ipc_test + PRIVATE + core_interface + univalue + ) + + target_sources(test_firo + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/ipc_tests.cpp + ) + target_link_libraries(test_firo bitcoin_ipc_test bitcoin_ipc) +endif() + +function(add_boost_test source_file) + if(NOT EXISTS ${source_file}) + return() + endif() + + file(READ "${source_file}" source_file_content) + string(REGEX + MATCH "(BOOST_FIXTURE_TEST_SUITE|BOOST_AUTO_TEST_SUITE)\\(([A-Za-z0-9_]+)" + test_suite_macro "${source_file_content}" + ) + string(REGEX + REPLACE "(BOOST_FIXTURE_TEST_SUITE|BOOST_AUTO_TEST_SUITE)\\(" "" + test_suite_name "${test_suite_macro}" + ) + if(test_suite_name) + add_test(NAME ${test_suite_name} + COMMAND test_firo --run_test=${test_suite_name} --catch_system_error=no --log_level=test_suite -- DEBUG_LOG_OUT + ) + set_property(TEST ${test_suite_name} PROPERTY + SKIP_REGULAR_EXPRESSION "no test cases matching filter" + ) + endif() +endfunction() + +function(add_all_test_targets) + get_target_property(test_source_dir test_firo SOURCE_DIR) + get_target_property(test_sources test_firo SOURCES) + foreach(test_source ${test_sources}) + cmake_path(IS_RELATIVE test_source result) + if(result) + cmake_path(APPEND test_source_dir ${test_source} OUTPUT_VARIABLE test_source) + endif() + add_boost_test(${test_source}) + endforeach() +endfunction() + +add_all_test_targets() + +list(APPEND installable_targets test_firo) \ No newline at end of file diff --git a/src/test/addrman_tests.cpp b/src/test/addrman_tests.cpp index 92a1bd4efb..357aaf03b7 100644 --- a/src/test/addrman_tests.cpp +++ b/src/test/addrman_tests.cpp @@ -27,7 +27,7 @@ class CAddrManTest : public CAddrMan insecure_rand = FastRandomContext(true); } - int RandomInt(int nMax) + int RandomInt(int nMax) override { state = (CHashWriter(SER_GETHASH, 0) << state).GetHash().GetCheapHash(); return (unsigned int)(state % nMax); diff --git a/src/test/allocator_tests.cpp b/src/test/allocator_tests.cpp index 3f15a0dec1..4a533b5bf2 100644 --- a/src/test/allocator_tests.cpp +++ b/src/test/allocator_tests.cpp @@ -131,7 +131,7 @@ class TestLockedPageAllocator: public LockedPageAllocator { public: TestLockedPageAllocator(int count_in, int lockedcount_in): count(count_in), lockedcount(lockedcount_in) {} - void* AllocateLocked(size_t len, bool *lockingSuccess) + void* AllocateLocked(size_t len, bool *lockingSuccess) override { *lockingSuccess = false; if (count > 0) { @@ -146,10 +146,10 @@ class TestLockedPageAllocator: public LockedPageAllocator } return 0; } - void FreeLocked(void* addr, size_t len) + void FreeLocked(void* addr, size_t len) override { } - size_t GetLimit() + size_t GetLimit() override { return std::numeric_limits::max(); } diff --git a/src/test/base58_tests.cpp b/src/test/base58_tests.cpp index 5d9ddbf81a..1db4a0f925 100644 --- a/src/test/base58_tests.cpp +++ b/src/test/base58_tests.cpp @@ -4,9 +4,9 @@ #include "base58.h" -#include "data/base58_encode_decode.json.h" -#include "data/base58_keys_invalid.json.h" -#include "data/base58_keys_valid.json.h" +#include +#include +#include #include "key.h" #include "script/script.h" diff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp index 80be45ff6e..ad391ab992 100644 --- a/src/test/coins_tests.cpp +++ b/src/test/coins_tests.cpp @@ -37,7 +37,7 @@ class CCoinsViewTest : public CCoinsView std::map map_; public: - bool GetCoin(const COutPoint& outpoint, Coin& coin) const + bool GetCoin(const COutPoint& outpoint, Coin& coin) const override { std::map::const_iterator it = map_.find(outpoint); if (it == map_.end()) { @@ -51,15 +51,15 @@ class CCoinsViewTest : public CCoinsView return true; } - bool HaveCoin(const COutPoint& outpoint) const + bool HaveCoin(const COutPoint& outpoint) const override { Coin coin; return GetCoin(outpoint, coin); } - uint256 GetBestBlock() const { return hashBestBlock_; } + uint256 GetBestBlock() const override { return hashBestBlock_; } - bool BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) + bool BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) override { for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); ) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { @@ -81,7 +81,7 @@ class CCoinsViewTest : public CCoinsView class CCoinsViewCacheTest : public CCoinsViewCache { public: - CCoinsViewCacheTest(CCoinsView* base) : CCoinsViewCache(base) {} + CCoinsViewCacheTest(CCoinsView* baseParam) : CCoinsViewCache(baseParam) {} void SelfTest() const { diff --git a/src/test/evo_deterministicmns_tests.cpp b/src/test/evo_deterministicmns_tests.cpp index afa5844526..d988b9c8b6 100644 --- a/src/test/evo_deterministicmns_tests.cpp +++ b/src/test/evo_deterministicmns_tests.cpp @@ -27,7 +27,7 @@ typedef std::map> SimpleUTXOMap; static SimpleUTXOMap BuildSimpleUtxoMap(const std::vector& txs) { SimpleUTXOMap utxos; - CAmount balance = 0; + FIRO_UNUSED CAmount balance = 0; for (size_t i = 0; i < txs.size(); i++) { auto& tx = txs[i]; size_t const znode_output = tx.vout.size() > 6 ? FindZnodeOutput(tx) : 0; @@ -247,7 +247,6 @@ BOOST_FIXTURE_TEST_CASE(dip3_activation, TestChainDIP3BeforeActivationSetup) ProcessNewBlock(Params(), block, true, nullptr); deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); - LOCK(cs_main); BOOST_ASSERT(chainActive.Height() == nHeight + 2); BOOST_ASSERT(block->GetHash() == chainActive.Tip()->GetBlockHash()); BOOST_ASSERT(deterministicMNManager->GetListAtChainTip().HasMN(tx.GetHash())); diff --git a/src/test/evospork_tests.cpp b/src/test/evospork_tests.cpp index e2c71c0053..7a0787ee04 100644 --- a/src/test/evospork_tests.cpp +++ b/src/test/evospork_tests.cpp @@ -25,7 +25,7 @@ typedef std::map> SimpleUTXOMap; static SimpleUTXOMap BuildSimpleUtxoMap(const std::vector& txs) { SimpleUTXOMap utxos; - CAmount balance = 0; + FIRO_UNUSED CAmount balance = 0; for (size_t i = 0; i < txs.size(); i++) { auto& tx = txs[i]; size_t const znode_output = tx.vout.size() > 6 ? FindZnodeOutput(tx) : 0; @@ -595,7 +595,7 @@ BOOST_AUTO_TEST_CASE(limit) {CSporkAction::sporkLimit, CSporkAction::featureSparkTransparentLimit, 100*COIN, 1050} }); - auto params = spark::Params::get_default(); + FIRO_UNUSED auto params = spark::Params::get_default(); BOOST_ASSERT(pwalletMain->sparkWallet); spark::Address address = pwalletMain->sparkWallet->generateNewAddress(); diff --git a/src/test/firsthalving_tests.cpp b/src/test/firsthalving_tests.cpp index 966c55a1ce..105da8182e 100644 --- a/src/test/firsthalving_tests.cpp +++ b/src/test/firsthalving_tests.cpp @@ -16,7 +16,7 @@ typedef std::map> SimpleUTXOMap; static SimpleUTXOMap BuildSimpleUtxoMap(const std::vector& txs) { SimpleUTXOMap utxos; - CAmount balance = 0; + FIRO_UNUSED CAmount balance = 0; for (size_t i = 0; i < txs.size(); i++) { auto& tx = txs[i]; size_t const znode_output = tx.vout.size() > 6 ? FindZnodeOutput(tx) : 0; diff --git a/src/test/fixtures.cpp b/src/test/fixtures.cpp index 958d5a4b5f..cfa08ff79b 100644 --- a/src/test/fixtures.cpp +++ b/src/test/fixtures.cpp @@ -352,7 +352,7 @@ std::vector SparkTestingSetup::GenerateMints( CWalletDB walletdb(pwalletMain->strWalletFile); std::vector mints; // Parameters - const spark::Params* params; + FIRO_UNUSED const spark::Params* params; params = spark::Params::get_default(); // Generate address @@ -383,8 +383,8 @@ std::vector SparkTestingSetup::GenerateMints( } std::vector walletMints = pwalletMain->sparkWallet->ListSparkMints(); - for (int i = 0; i < walletMints.size(); ++i) { - for (int j = 0; j < wtxAndFeeAll.size(); ++j) { + for (int i = 0; cmp::less(i, walletMints.size()); ++i) { + for (int j = 0; cmp::less(j, wtxAndFeeAll.size()); ++j) { if (walletMints[i].txid == wtxAndFeeAll[j].first.GetHash()) { mints.push_back(walletMints[i]); } diff --git a/src/test/lelantus_state_tests.cpp b/src/test/lelantus_state_tests.cpp index a48dc54c0e..d58c0281ba 100644 --- a/src/test/lelantus_state_tests.cpp +++ b/src/test/lelantus_state_tests.cpp @@ -81,7 +81,7 @@ class LelantusStateTests : public LelantusTestingSetup { std::vector indexes; auto index = GenerateBlock({}); - for (auto const s : serials) { + for (auto const& s : serials) { for (size_t i = 0; i != s.second; i++) { Scalar serial; serial.randomize(); @@ -91,7 +91,7 @@ class LelantusStateTests : public LelantusTestingSetup { } state.AddBlock(index); - return {index}; + return index; } void RemoveBlocks(CLelantusState &state, std::vector indexes) { diff --git a/src/test/lelantus_tests.cpp b/src/test/lelantus_tests.cpp index c7a6507920..7b81b99a27 100644 --- a/src/test/lelantus_tests.cpp +++ b/src/test/lelantus_tests.cpp @@ -606,7 +606,7 @@ BOOST_AUTO_TEST_CASE(checktransaction) bool hasSerial = false; BOOST_CHECK_MESSAGE(hasSerial = (info.spentSerials.count(serials[i]) > 0), "No serial as expected"); if (hasSerial) { - BOOST_CHECK_MESSAGE(ids[i] == info.spentSerials[serials[i]], "Serials group id is invalid"); + BOOST_CHECK_MESSAGE(cmp::equal(ids[i], info.spentSerials[serials[i]]), "Serials group id is invalid"); } } diff --git a/src/test/main_tests.cpp b/src/test/main_tests.cpp index 6a3d6230a5..a5ca2d2f63 100644 --- a/src/test/main_tests.cpp +++ b/src/test/main_tests.cpp @@ -15,7 +15,7 @@ BOOST_FIXTURE_TEST_SUITE(main_tests, TestingSetup) static void TestBlockSubsidyHalvings(const Consensus::Params& consensusParams) { - int maxHalvings = 64; + FIRO_UNUSED int maxHalvings = 64; CAmount nInitialSubsidy = 50 * COIN; BOOST_CHECK_EQUAL(GetBlockSubsidy(1, consensusParams, consensusParams.nMTPSwitchTime-1000), nInitialSubsidy); diff --git a/src/test/miner_tests.cpp b/src/test/miner_tests.cpp index 1cebe47bb7..3d1030fd12 100644 --- a/src/test/miner_tests.cpp +++ b/src/test/miner_tests.cpp @@ -27,7 +27,7 @@ BOOST_FIXTURE_TEST_SUITE(miner_tests, TestingSetup) static CFeeRate blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE); -static +FIRO_UNUSED static struct { unsigned char extranonce; unsigned int nonce; diff --git a/src/test/mtp_halving_tests.cpp b/src/test/mtp_halving_tests.cpp index 39a466d4cc..45674cbd4c 100644 --- a/src/test/mtp_halving_tests.cpp +++ b/src/test/mtp_halving_tests.cpp @@ -155,14 +155,14 @@ BOOST_AUTO_TEST_CASE(mtp_halving) CBlock bMtp = b; blockReward = 0; - for(int i = 0; i < oldBlock.vtx[0]->vout.size(); i++) { + for(int i = 0; cmp::less(i, oldBlock.vtx[0]->vout.size()); i++) { BOOST_CHECK_MESSAGE(oldBlock.vtx[0]->vout[i].nValue == bMtp.vtx[0]->vout[i].nValue * 2, "Block reward not halved"); } for(auto txout : bMtp.vtx[0]->vout) blockReward += txout.nValue; BOOST_CHECK_MESSAGE(blockReward == 25 * COIN, "Block reward not correct in MTP block"); - for(int i = 0; i < bMtp.vtx[0]->vout.size(); i++) + for(int i = 0; cmp::less(i, bMtp.vtx[0]->vout.size()); i++) { CBlock bModified = bMtp; CMutableTransaction modifiedTx = *bModified.vtx[0]; @@ -181,7 +181,7 @@ BOOST_AUTO_TEST_CASE(mtp_halving) } - for(int i = 1; i < bMtp.vtx[0]->vout.size() - 1; i++) + for(int i = 1; cmp::less(i, bMtp.vtx[0]->vout.size() - 1); i++) { CBlock bModified = bMtp; CPubKey modifiedKey; diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp index b9ed4952bb..269fc99df1 100644 --- a/src/test/net_tests.cpp +++ b/src/test/net_tests.cpp @@ -28,7 +28,7 @@ class CAddrManSerializationMock : public CAddrMan class CAddrManUncorrupted : public CAddrManSerializationMock { public: - void Serialize(CDataStream& s) const + void Serialize(CDataStream& s) const override { CAddrMan::Serialize(s); } @@ -37,7 +37,7 @@ class CAddrManUncorrupted : public CAddrManSerializationMock class CAddrManCorrupted : public CAddrManSerializationMock { public: - void Serialize(CDataStream& s) const + void Serialize(CDataStream& s) const override { // Produces corrupt output that claims addrman has 20 addrs when it only has one addr. unsigned char nVersion = 1; diff --git a/src/test/progpow_tests.cpp b/src/test/progpow_tests.cpp index c4a46a8c6b..3a644d5dd4 100644 --- a/src/test/progpow_tests.cpp +++ b/src/test/progpow_tests.cpp @@ -17,7 +17,7 @@ struct ProgpowTestingSetup : public TestChain100Setup { - CKey coinbaseKey; + CKey m_coinbaseKey; CScript coinbaseScript; Consensus::Params &mutableParams; Consensus::Params originalParams; @@ -27,7 +27,7 @@ struct ProgpowTestingSetup : public TestChain100Setup std::string errorCode; protected: - virtual void BlockChecked(const CBlock&, const CValidationState& state) { + virtual void BlockChecked(const CBlock&, const CValidationState& state) override { errorCode = state.GetRejectReason(); } }; @@ -36,8 +36,8 @@ struct ProgpowTestingSetup : public TestChain100Setup { originalParams = mutableParams; mutableParams.nPPSwitchTime = INT_MAX; - coinbaseKey.MakeNewKey(true); - coinbaseScript = GetScriptForDestination(coinbaseKey.GetPubKey().GetID()); + m_coinbaseKey.MakeNewKey(true); + coinbaseScript = GetScriptForDestination(m_coinbaseKey.GetPubKey().GetID()); } ~ProgpowTestingSetup() { @@ -69,21 +69,21 @@ BOOST_AUTO_TEST_CASE(transition) { mutableParams.nPPSwitchTime = INT_MAX; - CBlock regularBlock = CreateAndProcessBlock({}, coinbaseKey); + CBlock regularBlock = CreateAndProcessBlock({}, m_coinbaseKey); BOOST_ASSERT(!regularBlock.IsProgPow()); mutableParams.nPPSwitchTime = (uint32_t)(chainActive.Tip()->GetMedianTimePast()+10); SetMockTime(mutableParams.nPPSwitchTime+1); int oldHeight = chainActive.Height(); - CBlock ppBlock = CreateAndProcessBlock({}, coinbaseKey); + CBlock ppBlock = CreateAndProcessBlock({}, m_coinbaseKey); BOOST_ASSERT(chainActive.Height() == oldHeight+1); BOOST_ASSERT(ppBlock.IsProgPow()); // Try to add regular block after PP one. Should throw an exception SetMockTime(mutableParams.nPPSwitchTime-1); try { - CreateBlock({}, coinbaseKey); + CreateBlock({}, m_coinbaseKey); BOOST_ASSERT(false); } catch (std::runtime_error &err) { @@ -96,7 +96,7 @@ BOOST_AUTO_TEST_CASE(corruption) mutableParams.nPPSwitchTime = (uint32_t)(chainActive.Tip()->GetMedianTimePast()+10); SetMockTime(mutableParams.nPPSwitchTime+1); - CBlock block = CreateBlock({}, coinbaseKey); + CBlock block = CreateBlock({}, m_coinbaseKey); BOOST_ASSERT(block.IsProgPow()); CBlock modifiedBlock = block; diff --git a/src/test/script_tests.cpp b/src/test/script_tests.cpp index 24aae097ec..2a24675c23 100644 --- a/src/test/script_tests.cpp +++ b/src/test/script_tests.cpp @@ -456,7 +456,7 @@ class TestBuilder return comment; } - const CScript& GetScriptPubKey() + FIRO_UNUSED const CScript& GetScriptPubKey() { return creditTx->vout[0].scriptPubKey; } diff --git a/src/test/spark_tests.cpp b/src/test/spark_tests.cpp index ae4962a327..43b3d9d651 100644 --- a/src/test/spark_tests.cpp +++ b/src/test/spark_tests.cpp @@ -508,7 +508,7 @@ BOOST_AUTO_TEST_CASE(checktransaction) GenerateBlocks(10); auto outputAmount = 1 * COIN; - auto mintAmount = 2 * CENT - CENT; // a cent as fee + FIRO_UNUSED auto mintAmount = 2 * CENT - CENT; // a cent as fee CAmount fee; CWalletTx wtx = pwalletMain->SpendAndStoreSpark({{script, outputAmount, false}}, {}, fee); @@ -530,7 +530,7 @@ BOOST_AUTO_TEST_CASE(checktransaction) bool hasLTag = false; BOOST_CHECK_MESSAGE(hasLTag = (info.spentLTags.count(lTags[i]) > 0), "No linking tag as expected"); if (hasLTag) { - BOOST_CHECK_MESSAGE(ids[i] == info.spentLTags[lTags[i]], "linking tag group id is invalid"); + BOOST_CHECK_MESSAGE(cmp::equal(ids[i], info.spentLTags[lTags[i]]), "linking tag group id is invalid"); } } diff --git a/src/test/sparkname_tests.cpp b/src/test/sparkname_tests.cpp index 1f1ec1b376..836051f52f 100644 --- a/src/test/sparkname_tests.cpp +++ b/src/test/sparkname_tests.cpp @@ -6,6 +6,7 @@ #include "../net.h" #include "../sparkname.h" +#include "compat_layer.h" #include "test_bitcoin.h" #include "fixtures.h" #include @@ -22,10 +23,10 @@ class SparkNameTests : public SparkTestingSetup public: SparkNameTests() : SparkTestingSetup(), + mutableConsensus(const_cast(::Params().GetConsensus())), sparkState(CSparkState::GetState()), consensus(::Params().GetConsensus()), - sparkNameManager(CSparkNameManager::GetInstance()), - mutableConsensus(const_cast(::Params().GetConsensus())) { + sparkNameManager(CSparkNameManager::GetInstance()) { oldConsensus = mutableConsensus; } @@ -71,7 +72,7 @@ class SparkNameTests : public SparkTestingSetup LOCK(pwalletMain->cs_wallet); CAmount txFee; - size_t additionalSize = sparkNameManager->GetSparkNameTxDataSize(sparkNameData); + FIRO_UNUSED size_t additionalSize = sparkNameManager->GetSparkNameTxDataSize(sparkNameData); if (sparkNameFee == 0) { BOOST_ASSERT(sparkNameData.name.length() <= CSparkNameManager::maximumSparkNameLength); diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp index 7996589b66..c81bf458a7 100644 --- a/src/test/transaction_tests.cpp +++ b/src/test/transaction_tests.cpp @@ -193,7 +193,7 @@ BOOST_AUTO_TEST_CASE(tx_invalid) // verifyFlags is a comma separated list of script verification flags to apply, or "NONE" UniValue tests = read_json(std::string(json_tests::tx_invalid, json_tests::tx_invalid + sizeof(json_tests::tx_invalid))); - ScriptError err; + ScriptError err = {}; for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; std::string strTest = test.write(); diff --git a/src/test/txvalidationcache_tests.cpp b/src/test/txvalidationcache_tests.cpp index 39d3bd700a..61a106a6f3 100644 --- a/src/test/txvalidationcache_tests.cpp +++ b/src/test/txvalidationcache_tests.cpp @@ -17,7 +17,7 @@ BOOST_AUTO_TEST_SUITE(tx_validationcache_tests) -static bool +FIRO_UNUSED static bool ToMemPool(CMutableTransaction& tx) { LOCK(cs_main); diff --git a/src/tinyformat.h b/src/tinyformat.h index 17f0360c42..5b6667b604 100644 --- a/src/tinyformat.h +++ b/src/tinyformat.h @@ -138,6 +138,8 @@ namespace tfm = tinyformat; #include #include +#include "compat_layer.h" + #ifndef TINYFORMAT_ERROR # define TINYFORMAT_ERROR(reason) assert(0 && reason) #endif @@ -705,23 +707,29 @@ inline const char* streamStateFromFormat(std::ostream& out, bool& spacePadPositi break; case 'X': out.setf(std::ios::uppercase); - case 'x': case 'p': + FIRO_FALLTHROUGH; + case 'x': + FIRO_FALLTHROUGH; + case 'p': out.setf(std::ios::hex, std::ios::basefield); intConversion = true; break; case 'E': out.setf(std::ios::uppercase); + FIRO_FALLTHROUGH; case 'e': out.setf(std::ios::scientific, std::ios::floatfield); out.setf(std::ios::dec, std::ios::basefield); break; case 'F': out.setf(std::ios::uppercase); + FIRO_FALLTHROUGH; case 'f': out.setf(std::ios::fixed, std::ios::floatfield); break; case 'G': out.setf(std::ios::uppercase); + FIRO_FALLTHROUGH; case 'g': out.setf(std::ios::dec, std::ios::basefield); // As in boost::format, let stream decide float format. diff --git a/src/txdb.cpp b/src/txdb.cpp index 95346629c9..c57ebaf3b9 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -465,7 +465,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts(boost::functionnHeight >= firstInLastNBlocksHeight) { lastNBlocks.insert(std::pair(pindexNew->nHeight, pindexNew)); - if (lastNBlocks.size() > nBlocksToCheck) { + if (cmp::greater(lastNBlocks.size(), nBlocksToCheck)) { // pop the first element from the map auto firstElement = lastNBlocks.begin(); auto elementToPop = firstElement++; @@ -843,7 +843,7 @@ class CCoins void Unserialize(Stream &s) { unsigned int nCode = 0; // version - int nVersionDummy; + int nVersionDummy = 0; ::Unserialize(s, VARINT(nVersionDummy)); // header code ::Unserialize(s, VARINT(nCode)); diff --git a/src/txdb.h b/src/txdb.h index 15e44fcfe0..5a580d2bd6 100644 --- a/src/txdb.h +++ b/src/txdb.h @@ -100,12 +100,12 @@ class CCoinsViewDBCursor: public CCoinsViewCursor public: ~CCoinsViewDBCursor() {} - bool GetKey(COutPoint &key) const; - bool GetValue(Coin &coin) const; - unsigned int GetValueSize() const; + bool GetKey(COutPoint &key) const override; + bool GetValue(Coin &coin) const override; + unsigned int GetValueSize() const override; - bool Valid() const; - void Next(); + bool Valid() const override; + void Next() override; private: CCoinsViewDBCursor(CDBIterator* pcursorIn, const uint256 &hashBlockIn): @@ -158,15 +158,18 @@ class CBlockTreeDB : public CDBWrapper /** * This class was introduced as the logic for address and tx indices became too intricate. - * - * @param addressIndex, spentIndex - true if to update the corresponding index - * - * It is undefined behavior if the helper was created with addressIndex == false - * and getAddressIndex was called later (same for spentIndex and unspentIndex). */ class CDbIndexHelper : boost::noncopyable { public: + + /** + * @brief It is undefined behavior if the helper was created with addressIndex == false + * and getAddressIndex was called later (same for spentIndex and unspentIndex). + * + * @param addressIndex true if to update the corresponding index + * @param spentIndex true if to update the corresponding index + */ CDbIndexHelper(bool addressIndex, bool spentIndex); void ConnectTransaction(CTransaction const & tx, int height, int txNumber, CCoinsViewCache const & view); diff --git a/src/txmempool.cpp b/src/txmempool.cpp index 2ba4b625d0..a84627be56 100644 --- a/src/txmempool.cpp +++ b/src/txmempool.cpp @@ -1158,7 +1158,7 @@ void CTxMemPool::check(const CCoinsViewCache *pcoins) const LOCK(cs); std::list waitingOnDependants; for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) { - unsigned int i = 0; + FIRO_UNUSED unsigned int i = 0; checkTotal += it->GetTxSize(); innerUsage += it->DynamicMemoryUsage(); const CTransaction& tx = it->GetTx(); @@ -1170,8 +1170,8 @@ void CTxMemPool::check(const CCoinsViewCache *pcoins) const innerUsage += memusage::DynamicUsage(links.parents); bool fDependsWait = false; setEntries setParentCheck; - int64_t parentSizes = 0; - int64_t parentSigOpCost = 0; + FIRO_UNUSED int64_t parentSizes = 0; + FIRO_UNUSED int64_t parentSigOpCost = 0; if (!tx.HasPrivateInputs()) { BOOST_FOREACH(const CTxIn &txin, tx.vin) { // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's. diff --git a/src/txmempool.h b/src/txmempool.h index 97fca8e471..1eb257ec70 100644 --- a/src/txmempool.h +++ b/src/txmempool.h @@ -125,6 +125,7 @@ class CTxMemPoolEntry int64_t nSigOpsCost, LockPoints lp); CTxMemPoolEntry(const CTxMemPoolEntry& other); + CTxMemPoolEntry& operator=(const CTxMemPoolEntry& other) = default; const CTransaction& GetTx() const { return *this->tx; } CTransactionRef GetSharedTx() const { return this->tx; } @@ -797,8 +798,8 @@ class CCoinsViewMemPool : public CCoinsViewBacked public: CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn); - bool GetCoin(const COutPoint &outpoint, Coin &coin) const; - bool HaveCoin(const COutPoint &outpoint) const; + bool GetCoin(const COutPoint &outpoint, Coin &coin) const override; + bool HaveCoin(const COutPoint &outpoint) const override; }; // We want to sort transactions by coin age priority diff --git a/src/ui_interface.h b/src/ui_interface.h index 293665d547..b322a31df9 100644 --- a/src/ui_interface.h +++ b/src/ui_interface.h @@ -12,11 +12,12 @@ #include #include +#include "chain.h" + class CBasicKeyStore; class CWallet; class uint256; class CBlockIndex; -class CSparkNameBlockIndexData; class CDeterministicMNList; /** General change type (added, updated, removed). */ diff --git a/src/uint256.cpp b/src/uint256.cpp index 6be0a3b5bb..01bb8fed04 100644 --- a/src/uint256.cpp +++ b/src/uint256.cpp @@ -28,7 +28,7 @@ std::string base_blob::GetHex() const { char psz[sizeof(data) * 2 + 1]; for (unsigned int i = 0; i < sizeof(data); i++) - sprintf(psz + i * 2, "%02x", data[sizeof(data) - i - 1]); + snprintf(psz + i * 2, 3, "%02x", data[sizeof(data) - i - 1]); return std::string(psz, psz + sizeof(data) * 2); } diff --git a/src/undo.h b/src/undo.h index 3749d5d7a8..1cdecab552 100644 --- a/src/undo.h +++ b/src/undo.h @@ -51,7 +51,7 @@ class TxInUndoDeserializer // Old versions stored the version number for the last spend of // a transaction's outputs. Non-final spends were indicated with // height = 0. - int nVersionDummy; + int nVersionDummy = 0; ::Unserialize(s, VARINT(nVersionDummy)); } ::Unserialize(s, REF(CTxOutCompressor(REF(txout->out)))); diff --git a/src/univalue/CMakeLists.txt b/src/univalue/CMakeLists.txt new file mode 100644 index 0000000000..d146ed1720 --- /dev/null +++ b/src/univalue/CMakeLists.txt @@ -0,0 +1,31 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +add_library(univalue STATIC EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/lib/univalue.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/lib/univalue_read.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/lib/univalue_write.cpp +) +target_include_directories(univalue + PUBLIC + $ +) +target_link_libraries(univalue PRIVATE core_interface) + +if(BUILD_TESTS) + add_executable(unitester ${CMAKE_CURRENT_SOURCE_DIR}/test/unitester.cpp) + target_compile_definitions(unitester + PRIVATE + JSON_TEST_SRC=\"${CMAKE_CURRENT_SOURCE_DIR}/test\" + ) + target_link_libraries(unitester + PRIVATE + core_interface + univalue + ) + add_test(NAME univalue_test + COMMAND unitester + ) + +endif() diff --git a/src/univalue/include/univalue.h b/src/univalue/include/univalue.h index e8ce283519..52d16df4d3 100644 --- a/src/univalue/include/univalue.h +++ b/src/univalue/include/univalue.h @@ -278,6 +278,6 @@ static inline bool json_isspace(int ch) extern const UniValue NullUniValue; -const UniValue& find_value( const UniValue& obj, const std::string& name); +const UniValue& find_value(const UniValue& obj, const std::string& name); #endif // __UNIVALUE_H__ diff --git a/src/util.cpp b/src/util.cpp index 3c5296b2d3..e8567d3449 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -92,17 +92,12 @@ #include #include +#include "../../compat_layer.h" + // Work around clang compilation problem in Boost 1.46: // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION -namespace boost { - - namespace program_options { - std::string to_internal(const std::string&); - } - -} // namespace boost // znode fZnode bool fMasternodeMode = false; @@ -938,7 +933,7 @@ void RenameThreadPool(ctpl::thread_pool& tp, const char* baseName) // `doneCnt` should be at least `futures.size()` if tp size was increased (for whatever reason), // or at least `tp.size()` if tp size was decreased and queue was cleared // (which can happen on `stop()` if we were not fast enough to get all jobs to their threads). - } while (doneCnt < futures.size() && doneCnt < tp.size()); + } while (cmp::less(doneCnt.load(), futures.size()) && doneCnt < tp.size()); cond->notify_all(); diff --git a/src/util.h b/src/util.h index 65b1804a85..8f1c0ca1a0 100644 --- a/src/util.h +++ b/src/util.h @@ -16,6 +16,7 @@ #endif #include "compat.h" +#include "compat_layer.h" #include "tinyformat.h" #include "utiltime.h" @@ -162,7 +163,7 @@ bool IsArgSet(const std::string& strArg); * Return string argument or default value * * @param strArg Argument to get (e.g. "-foo") - * @param default (e.g. "1") + * @param strDefault (e.g. "1") * @return command-line argument or default value */ std::string GetArg(const std::string& strArg, const std::string& strDefault); @@ -171,7 +172,7 @@ std::string GetArg(const std::string& strArg, const std::string& strDefault); * Return integer argument or default value * * @param strArg Argument to get (e.g. "-foo") - * @param default (e.g. 1) + * @param nDefault (e.g. 1) * @return command-line argument (0 if invalid number) or default value */ int64_t GetArg(const std::string& strArg, int64_t nDefault); @@ -180,7 +181,7 @@ int64_t GetArg(const std::string& strArg, int64_t nDefault); * Return boolean argument or default value * * @param strArg Argument to get (e.g. "-foo") - * @param default (true or false) + * @param fDefault (true or false) * @return command-line argument or default value */ bool GetBoolArg(const std::string& strArg, bool fDefault); diff --git a/src/validation.cpp b/src/validation.cpp index 8cbb0b18bf..575e243eff 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -86,7 +86,6 @@ # error "Firo cannot be compiled without assertions." #endif -bool AbortNode(const std::string& strMessage, const std::string& userMessage=""); bool AbortNode(CValidationState &state, const std::string& strMessage, const std::string& userMessage=""); /** @@ -2780,12 +2779,12 @@ class WarningBitsConditionChecker : public AbstractThresholdConditionChecker public: WarningBitsConditionChecker(int bitIn) : bit(bitIn) {} - int64_t BeginTime(const Consensus::Params& params) const { return 0; } - int64_t EndTime(const Consensus::Params& params) const { return std::numeric_limits::max(); } - int Period(const Consensus::Params& params) const { return params.nMinerConfirmationWindow; } - int Threshold(const Consensus::Params& params) const { return params.nRuleChangeActivationThreshold; } + int64_t BeginTime(const Consensus::Params& params) const override { return 0; } + int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits::max(); } + int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; } + int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; } - bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const + bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override { return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) && ((pindex->nVersion >> bit) & 1) != 0 && @@ -3139,6 +3138,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin } if (!IsBlockPayeeValid(*block.vtx[0], pindex->nHeight, pindex->nTime, blockSubsidy)) { + LOCK(cs_main); mapRejectedBlocks.insert(std::make_pair(block.GetHash(), GetTime())); return state.DoS(0, error("ConnectBlock(EVPZNODES): couldn't find evo znode payments"), REJECT_INVALID, "bad-cb-payee"); @@ -4826,13 +4826,17 @@ bool IsTransactionInChain(const uint256& txId, int& nHeightTx) bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) { - const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1; + const uint32_t nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1; // once ProgPow always ProgPow - if (pindexPrev && pindexPrev->nTime >= consensusParams.nPPSwitchTime && block.nTime < consensusParams.nPPSwitchTime) + if (pindexPrev + && cmp::greater_equal(pindexPrev->nTime, consensusParams.nPPSwitchTime) + && cmp::less(block.nTime, consensusParams.nPPSwitchTime)) return state.Invalid(false, REJECT_INVALID, "bad-blk-progpow-state", "Cannot go back from ProgPOW"); - if (pindexPrev && pindexPrev->nTime >= consensusParams.stage3StartTime && block.nTime < consensusParams.stage3StartTime) + if (pindexPrev + && cmp::greater_equal(pindexPrev->nTime, consensusParams.stage3StartTime) + && cmp::less(block.nTime, consensusParams.stage3StartTime)) return state.Invalid(false, REJECT_INVALID, "bad-blk-stage3-state", "Cannot go back to 5 minutes between blocks"); if (block.IsProgPow() && block.nHeight != nHeight) @@ -4848,7 +4852,7 @@ bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Co ? pindexPrev->GetMedianTimePast() : block.GetBlockTime(); - bool fDIP0003Active_context = nHeight >= consensusParams.DIP0003Height; + bool fDIP0003Active_context = cmp::greater_equal(nHeight, consensusParams.DIP0003Height); // Check that all transactions are finalized for (const auto& tx : block.vtx) { @@ -4861,10 +4865,10 @@ bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Co } } - if (nHeight >= consensusParams.nSubsidyHalvingFirst) { - if (block.nTime >= consensusParams.stage3StartTime) { - bool fStage3 = nHeight < consensusParams.nSubsidyHalvingSecond; - bool fStage4 = nHeight >= consensusParams.stage4StartBlock; + if (cmp::greater_equal(nHeight, consensusParams.nSubsidyHalvingFirst)) { + if (cmp::greater_equal(block.nTime, consensusParams.stage3StartTime)) { + bool fStage3 = cmp::less(nHeight, consensusParams.nSubsidyHalvingSecond); + bool fStage4 = cmp::greater_equal(nHeight, consensusParams.stage4StartBlock); CAmount devPayoutValue = 0, communityPayoutValue = 0; CScript devPayoutScript = GetScriptForDestination(CBitcoinAddress(consensusParams.stage3DevelopmentFundAddress).Get()); CScript communityPayoutScript = GetScriptForDestination(CBitcoinAddress(consensusParams.stage3CommunityFundAddress).Get()); diff --git a/src/validation.h b/src/validation.h index 36051d4a93..a5a453063a 100644 --- a/src/validation.h +++ b/src/validation.h @@ -20,7 +20,7 @@ #include "timedata.h" #include "chainparams.h" #include "spentindex.h" - +#include "warnings.h" #include #include @@ -300,14 +300,6 @@ void UnloadBlockIndex(); void ThreadScriptCheck(); /** Check whether we are doing an initial block download (synchronizing from disk or network) */ bool IsInitialBlockDownload(); -/** Format a string that describes several potential problems detected by the core. - * strFor can have three values: - * - "rpc": get critical warnings, which should put the client in safe mode if non-empty - * - "statusbar": get all warnings - * - "gui": get all warnings, translated (where possible) for GUI - * This function only returns the highest priority warning of the set selected by strFor. - */ -std::string GetWarnings(const std::string& strFor); /** Retrieve a transaction (from memory pool, or from disk, if possible) */ bool GetTransaction(const uint256 &hash, CTransactionRef &tx, const Consensus::Params& params, uint256 &hashBlock, bool fAllowSlow = false); /** Find the best known block, and make it the tip of the block chain */ @@ -349,7 +341,7 @@ void UnlinkPrunedFiles(const std::set& setFilesToPrune); /** Create a new block index entry for a given block hash */ CBlockIndex * InsertBlockIndex(uint256 hash); /** Abort with a message */ -bool AbortNode(const std::string &strMessage, const std::string &userMessage); +bool AbortNode(const std::string &strMessage, const std::string &userMessage=""); /** Sends out an alert */ void AlertNotify(const std::string& strMessage); /** Flush all state, indexes and buffers to disk. */ diff --git a/src/versionbits.cpp b/src/versionbits.cpp index 1d2527f900..b008e30a9a 100644 --- a/src/versionbits.cpp +++ b/src/versionbits.cpp @@ -149,12 +149,12 @@ class VersionBitsConditionChecker : public AbstractThresholdConditionChecker { const Consensus::DeploymentPos id; protected: - int64_t BeginTime(const Consensus::Params& params) const { return params.vDeployments[id].nStartTime; } - int64_t EndTime(const Consensus::Params& params) const { return params.vDeployments[id].nTimeout; } - int Period(const Consensus::Params& params) const { return params.nMinerConfirmationWindow; } - int Threshold(const Consensus::Params& params) const { return params.nRuleChangeActivationThreshold; } + int64_t BeginTime(const Consensus::Params& params) const override { return params.vDeployments[id].nStartTime; } + int64_t EndTime(const Consensus::Params& params) const override { return params.vDeployments[id].nTimeout; } + int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; } + int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; } - bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const + bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override { return (((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) && (pindex->nVersion & Mask(params)) != 0); } diff --git a/src/wallet/CMakeLists.txt b/src/wallet/CMakeLists.txt new file mode 100644 index 0000000000..80d872118b --- /dev/null +++ b/src/wallet/CMakeLists.txt @@ -0,0 +1,51 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +# Wallet functionality used by bitcoind and bitcoin-wallet executables. + +add_library(firo_wallet STATIC EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/../activemasternode.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../masternode-sync.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../sigma.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../lelantus.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../hdmint/hdmint.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../hdmint/mintpool.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../hdmint/wallet.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../hdmint/tracker.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../spark/state.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../spark/sparkwallet.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../spark/primitives.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../policy/rbf.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../bip47/account.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../bip47/paymentchannel.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../bip47/bip47utils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../bip47/paymentcode.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../bip47/secretpoint.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../primitives/mint_spend.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/crypter.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/bip39.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/mnemoniccontainer.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/db.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpcdump.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rpcwallet.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigmaspendbuilder.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/txbuilder.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/lelantusjoinsplitbuilder.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/walletexcept.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/wallet.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/walletdb.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/authhelper.cpp +) +target_link_libraries(firo_wallet + PUBLIC + core_interface + bitcoin_util + univalue + secp256k1 + Boost::headers + leveldb +) + +# Firo only supports BDB for wallet storage. +target_link_libraries(firo_wallet PUBLIC BerkeleyDB::BerkeleyDB) \ No newline at end of file diff --git a/src/wallet/crypter.h b/src/wallet/crypter.h index ad5ab44004..30d44b6ee0 100644 --- a/src/wallet/crypter.h +++ b/src/wallet/crypter.h @@ -163,8 +163,8 @@ class CCryptoKeyStore : public CBasicKeyStore bool Lock(); virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector &vchCryptedSecret); - bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey); - bool HaveKey(const CKeyID &address) const + bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override; + bool HaveKey(const CKeyID &address) const override { { LOCK(cs_KeyStore); @@ -174,9 +174,9 @@ class CCryptoKeyStore : public CBasicKeyStore } return false; } - bool GetKey(const CKeyID &address, CKey& keyOut) const; - bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const; - void GetKeys(std::set &setAddress) const + bool GetKey(const CKeyID &address, CKey& keyOut) const override; + bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const override; + void GetKeys(std::set &setAddress) const override { if (!IsCrypted()) { diff --git a/src/wallet/lelantusjoinsplitbuilder.cpp b/src/wallet/lelantusjoinsplitbuilder.cpp index 7e41589141..8f8015f3ea 100644 --- a/src/wallet/lelantusjoinsplitbuilder.cpp +++ b/src/wallet/lelantusjoinsplitbuilder.cpp @@ -119,7 +119,7 @@ CWalletTx LelantusJoinSplitBuilder::Build( assert(tx.nLockTime < LOCKTIME_THRESHOLD); // Start with no fee and loop until there is enough fee; - uint32_t nCountNextUse; + uint32_t nCountNextUse = 0; if (pwalletMain->zwallet) { nCountNextUse = pwalletMain->zwallet->GetCount(); } diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp index 42b1430b38..500d09577d 100644 --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -19,6 +19,7 @@ #include "authhelper.h" #include "rpcwallet.h" +#include "rpcdump.h" #include #include diff --git a/src/wallet/rpcdump.h b/src/wallet/rpcdump.h new file mode 100644 index 0000000000..b9ce41c63c --- /dev/null +++ b/src/wallet/rpcdump.h @@ -0,0 +1,21 @@ +#ifndef FIRO_RPCDUMP_H +#define FIRO_RPCDUMP_H + +#include + +#include "rpcwallet.h" + +UniValue dumpprivkey_firo(const JSONRPCRequest& request); +UniValue dumpwallet_firo(const JSONRPCRequest& request); +UniValue dumpprivkey(const JSONRPCRequest& request); +UniValue dumpsparkviewkey(const JSONRPCRequest& request); +UniValue importprivkey(const JSONRPCRequest& request); +UniValue importaddress(const JSONRPCRequest& request); +UniValue importpubkey(const JSONRPCRequest& request); +UniValue dumpwallet(const JSONRPCRequest& request); +UniValue importwallet(const JSONRPCRequest& request); +UniValue importprunedfunds(const JSONRPCRequest& request); +UniValue removeprunedfunds(const JSONRPCRequest& request); +UniValue importmulti(const JSONRPCRequest& request); + +#endif // FIRO_RPCDUMP_H \ No newline at end of file diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index c2f4c0c288..61b0968f3b 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -32,6 +32,7 @@ #include "bip47/paymentchannel.h" #include "bip47/account.h" #include "wallet/coincontrol.h" +#include "rpcdump.h" #include @@ -475,7 +476,7 @@ UniValue getaddressesbyaccount(const JSONRPCRequest& request) // Find all addresses that have the given account UniValue ret(UniValue::VARR); - for (const std::pair& item : pwallet->mapAddressBook) { + for (const auto& item : pwallet->mapAddressBook) { const CBitcoinAddress& address = item.first; const std::string& strName = item.second.name; if (strName == strAccount) @@ -829,7 +830,7 @@ UniValue getreceivedbyaddress(const JSONRPCRequest& request) // Tally CAmount nAmount = 0; - for (const std::pair& pairWtx : pwallet->mapWallet) { + for (const std::pair& pairWtx : pwallet->mapWallet) { const CWalletTx& wtx = pairWtx.second; if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx)) continue; @@ -886,7 +887,7 @@ UniValue getreceivedbyaccount(const JSONRPCRequest& request) // Tally CAmount nAmount = 0; - for (const std::pair& pairWtx : pwallet->mapWallet) { + for (const std::pair& pairWtx : pwallet->mapWallet) { const CWalletTx& wtx = pairWtx.second; if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx)) continue; @@ -1464,7 +1465,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA // Tally std::map mapTally; - for (const std::pair& pairWtx : pwallet->mapWallet) { + for (const std::pair& pairWtx : pwallet->mapWallet) { const CWalletTx& wtx = pairWtx.second; if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx)) @@ -1496,7 +1497,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA // Reply UniValue ret(UniValue::VARR); std::map mapAccountTally; - for (const std::pair& item : pwallet->mapAddressBook) { + for (const auto& item : pwallet->mapAddressBook) { const CBitcoinAddress& address = item.first; const std::string& strAccount = item.second.name; std::map::iterator it = mapTally.find(address); @@ -1974,13 +1975,13 @@ UniValue listaccounts(const JSONRPCRequest& request) includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY; bool fAddLocked = (request.params.size() > 2 && request.params[2].get_bool()); std::map mapAccountBalances; - for (const std::pair& entry : pwallet->mapAddressBook) { + for (const auto& entry : pwallet->mapAddressBook) { if (IsMine(*pwallet, entry.first) & includeWatchonly) { // This address belongs to me mapAccountBalances[entry.second.name] = 0; } } - for (const std::pair& pairWtx : pwallet->mapWallet) { + for (const std::pair& pairWtx : pwallet->mapWallet) { const CWalletTx& wtx = pairWtx.second; CAmount nFee; std::string strSentAccount; @@ -2109,7 +2110,7 @@ UniValue listsinceblock(const JSONRPCRequest& request) UniValue transactions(UniValue::VARR); - for (const std::pair& pairWtx : pwallet->mapWallet) { + for (const std::pair& pairWtx : pwallet->mapWallet) { CWalletTx tx = pairWtx.second; if (depth == -1 || tx.GetDepthInMainChain() < depth) @@ -3849,7 +3850,7 @@ UniValue spendspark(const JSONRPCRequest& request) BOOST_FOREACH(const std::string& name_, keys) { spark::Address sAddress(params); - unsigned char coinNetwork; + FIRO_UNUSED unsigned char coinNetwork; bool isSparkAddress; std::string sparkAddressStr; @@ -3930,7 +3931,7 @@ UniValue spendspark(const JSONRPCRequest& request) else throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameters, no subtractFee: ") + name_); - CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount}; + CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount, {}, {}}; recipients.push_back(recipient); continue; @@ -4424,7 +4425,7 @@ UniValue spendmany(const JSONRPCRequest& request) { std::set setAddress; std::vector vecSend; - CAmount totalAmount = 0; + FIRO_UNUSED CAmount totalAmount = 0; auto keys = sendTo.getKeys(); if (keys.size() <= 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Required at least an address to send"); @@ -4546,7 +4547,7 @@ UniValue joinsplit(const JSONRPCRequest& request) { std::vector vecSend; std::vector vMints; - CAmount totalAmount = 0; + FIRO_UNUSED CAmount totalAmount = 0; auto keys = sendTo.getKeys(); std::vector mints = mintAmounts.empty() ? std::vector() : mintAmounts.getValues(); @@ -4572,7 +4573,7 @@ UniValue joinsplit(const JSONRPCRequest& request) { bool fSubtractFeeFromAmount = subtractFeeFromAmountSet.find(strAddr) != subtractFeeFromAmountSet.end(); - vecSend.push_back({scriptPubKey, nAmount, fSubtractFeeFromAmount}); + vecSend.push_back({scriptPubKey, nAmount, fSubtractFeeFromAmount, {}, {}}); } for(const auto& mint : mints) { @@ -4771,7 +4772,7 @@ UniValue listsigmapubcoins(const JSONRPCRequest& request) { EnsureSigmaWalletIsAvailable(); - sigma::CoinDenomination denomination; + sigma::CoinDenomination denomination{}; bool filter_by_denom = false; if (request.params.size() > 0) { filter_by_denom = true; @@ -5227,16 +5228,6 @@ UniValue removetxwallet(const JSONRPCRequest& request) { } - -extern UniValue dumpprivkey_firo(const JSONRPCRequest& request); // in rpcdump.cpp -extern UniValue importprivkey(const JSONRPCRequest& request); -extern UniValue importaddress(const JSONRPCRequest& request); -extern UniValue importpubkey(const JSONRPCRequest& request); -extern UniValue dumpwallet_firo(const JSONRPCRequest& request); -extern UniValue importwallet(const JSONRPCRequest& request); -extern UniValue importprunedfunds(const JSONRPCRequest& request); -extern UniValue removeprunedfunds(const JSONRPCRequest& request); - // Calculate the size of the transaction assuming all signatures are max size // Use DummySignatureCreator, which inserts 72 byte signatures everywhere. // TODO: re-use this in CWallet::CreateTransaction (right now @@ -5851,17 +5842,6 @@ UniValue setusednumber(const JSONRPCRequest& request) /******************************************************************************/ -extern UniValue dumpprivkey(const JSONRPCRequest& request); // in rpcdump.cpp -extern UniValue dumpsparkviewkey(const JSONRPCRequest& request); // in rpcdump.cpp -extern UniValue importprivkey(const JSONRPCRequest& request); -extern UniValue importaddress(const JSONRPCRequest& request); -extern UniValue importpubkey(const JSONRPCRequest& request); -extern UniValue dumpwallet(const JSONRPCRequest& request); -extern UniValue importwallet(const JSONRPCRequest& request); -extern UniValue importprunedfunds(const JSONRPCRequest& request); -extern UniValue removeprunedfunds(const JSONRPCRequest& request); -extern UniValue importmulti(const JSONRPCRequest& request); - static const CRPCCommand commands[] = { // category name actor (function) okSafeMode // --------------------- ------------------------ ----------------------- ---------- @@ -5920,54 +5900,54 @@ static const CRPCCommand commands[] = { "wallet", "walletpassphrase", &walletpassphrase, true, {"passphrase","timeout"} }, { "wallet", "removeprunedfunds", &removeprunedfunds, true, {"txid"} }, - { "wallet", "listunspentsigmamints", &listunspentsigmamints, false }, - { "wallet", "listunspentlelantusmints", &listunspentlelantusmints, false }, - { "wallet", "mint", &mint, false }, - { "wallet", "mintlelantus", &mintlelantus, false }, - { "wallet", "autoMintlelantus", &autoMintlelantus, false }, - { "wallet", "spendmany", &spendmany, false }, - { "wallet", "joinsplit", &joinsplit, false }, - { "wallet", "resetsigmamint", &resetsigmamint, false }, - { "wallet", "resetlelantusmint", &resetlelantusmint, false }, - { "wallet", "setsigmamintstatus", &setsigmamintstatus, false }, - { "wallet", "setlelantusmintstatus", &setlelantusmintstatus, false }, - { "wallet", "listsigmamints", &listsigmamints, false }, - { "wallet", "listsigmapubcoins", &listsigmapubcoins, false }, - { "wallet", "listlelantusmints", &listlelantusmints, false }, - - { "wallet", "setmininput", &setmininput, false }, - { "wallet", "regeneratemintpool", ®eneratemintpool, false }, - { "wallet", "removetxmempool", &removetxmempool, false }, - { "wallet", "removetxwallet", &removetxwallet, false }, - { "wallet", "listsigmaspends", &listsigmaspends, false }, - { "wallet", "listlelantusjoinsplits", &listlelantusjoinsplits, false }, + { "wallet", "listunspentsigmamints", &listunspentsigmamints, false, {} }, + { "wallet", "listunspentlelantusmints", &listunspentlelantusmints, false, {} }, + { "wallet", "mint", &mint, false, {} }, + { "wallet", "mintlelantus", &mintlelantus, false, {} }, + { "wallet", "autoMintlelantus", &autoMintlelantus, false, {} }, + { "wallet", "spendmany", &spendmany, false, {} }, + { "wallet", "joinsplit", &joinsplit, false, {} }, + { "wallet", "resetsigmamint", &resetsigmamint, false, {} }, + { "wallet", "resetlelantusmint", &resetlelantusmint, false, {} }, + { "wallet", "setsigmamintstatus", &setsigmamintstatus, false, {} }, + { "wallet", "setlelantusmintstatus", &setlelantusmintstatus, false, {} }, + { "wallet", "listsigmamints", &listsigmamints, false, {} }, + { "wallet", "listsigmapubcoins", &listsigmapubcoins, false, {} }, + { "wallet", "listlelantusmints", &listlelantusmints, false, {} }, + + { "wallet", "setmininput", &setmininput, false, {} }, + { "wallet", "regeneratemintpool", ®eneratemintpool, false, {} }, + { "wallet", "removetxmempool", &removetxmempool, false, {} }, + { "wallet", "removetxwallet", &removetxwallet, false, {} }, + { "wallet", "listsigmaspends", &listsigmaspends, false, {} }, + { "wallet", "listlelantusjoinsplits", &listlelantusjoinsplits, false, {} }, //spark - { "wallet", "listunspentsparkmints", &listunspentsparkmints, false }, - { "wallet", "listsparkmints", &listsparkmints, false }, - { "wallet", "listsparkspends", &listsparkspends, false }, - { "wallet", "getsparkdefaultaddress", &getsparkdefaultaddress, false }, - { "wallet", "getallsparkaddresses", &getallsparkaddresses, false }, - { "wallet", "getnewsparkaddress", &getnewsparkaddress, false }, - { "wallet", "getsparkbalance", &getsparkbalance, false }, - { "wallet", "getsparkaddressbalance", &getsparkaddressbalance, false }, - { "wallet", "resetsparkmints", &resetsparkmints, false }, - { "wallet", "setsparkmintstatus", &setsparkmintstatus, false }, - { "wallet", "mintspark", &mintspark, true }, - { "wallet", "automintspark", &automintspark, false }, - { "wallet", "spendspark", &spendspark, false }, - { "wallet", "lelantustospark", &lelantustospark, false }, - { "wallet", "identifysparkcoins", &identifysparkcoins, false }, - { "wallet", "getsparkcoinaddr", &getsparkcoinaddr, false }, - { "wallet", "registersparkname", ®istersparkname, false }, - { "wallet", "getsparknames", &getsparknames, true, {} }, + { "wallet", "listunspentsparkmints", &listunspentsparkmints, false, {} }, + { "wallet", "listsparkmints", &listsparkmints, false, {} }, + { "wallet", "listsparkspends", &listsparkspends, false, {} }, + { "wallet", "getsparkdefaultaddress", &getsparkdefaultaddress, false, {} }, + { "wallet", "getallsparkaddresses", &getallsparkaddresses, false, {} }, + { "wallet", "getnewsparkaddress", &getnewsparkaddress, false, {} }, + { "wallet", "getsparkbalance", &getsparkbalance, false, {} }, + { "wallet", "getsparkaddressbalance", &getsparkaddressbalance, false, {} }, + { "wallet", "resetsparkmints", &resetsparkmints, false, {} }, + { "wallet", "setsparkmintstatus", &setsparkmintstatus, false, {} }, + { "wallet", "mintspark", &mintspark, true, {} }, + { "wallet", "automintspark", &automintspark, false, {} }, + { "wallet", "spendspark", &spendspark, false, {} }, + { "wallet", "lelantustospark", &lelantustospark, false, {} }, + { "wallet", "identifysparkcoins", &identifysparkcoins, false, {} }, + { "wallet", "getsparkcoinaddr", &getsparkcoinaddr, false, {} }, + { "wallet", "registersparkname", ®istersparkname, false, {} }, + { "wallet", "getsparknames", &getsparknames, true, {} }, //bip47 - { "bip47", "createrapaddress", &createrapaddress, true }, - { "bip47", "setupchannel", &setupchannel, true }, - { "bip47", "sendtorapaddress", &sendtorapaddress, true }, - { "bip47", "listrapaddresses", &listrapaddresses, true }, - { "bip47", "setusednumber", &setusednumber, true } + { "bip47", "createrapaddress", &createrapaddress, true, {} }, + { "bip47", "setupchannel", &setupchannel, true, {} }, + { "bip47", "sendtorapaddress", &sendtorapaddress, true, {} }, + { "bip47", "listrapaddresses", &listrapaddresses, true, {} }, + { "bip47", "setusednumber", &setusednumber, true, {} } }; void RegisterWalletRPCCommands(CRPCTable &t) diff --git a/src/wallet/rpcwallet.h b/src/wallet/rpcwallet.h index bd5dad18ca..31e2f6a699 100644 --- a/src/wallet/rpcwallet.h +++ b/src/wallet/rpcwallet.h @@ -16,7 +16,7 @@ void RegisterWalletRPCCommands(CRPCTable &t); * @param[in] request JSONRPCRequest that wishes to access a wallet * @return NULL if no wallet should be used, or a pointer to the CWallet */ -CWallet *GetWalletForJSONRPCRequest(const JSONRPCRequest&); +CWallet *GetWalletForJSONRPCRequest(const JSONRPCRequest& request); std::string HelpRequiringPassphrase(CWallet *); void EnsureWalletIsUnlocked(CWallet *); diff --git a/src/wallet/sigmaspendbuilder.cpp b/src/wallet/sigmaspendbuilder.cpp index cda66d6986..a44efc8df4 100644 --- a/src/wallet/sigmaspendbuilder.cpp +++ b/src/wallet/sigmaspendbuilder.cpp @@ -107,8 +107,8 @@ static std::unique_ptr CreateSigner(const CSigmaEntry& coin) return signer; } -SigmaSpendBuilder::SigmaSpendBuilder(CWallet& wallet, CHDMintWallet& mintWallet, const CCoinControl *coinControl) : - TxBuilder(wallet), +SigmaSpendBuilder::SigmaSpendBuilder(CWallet& walletParam, CHDMintWallet& mintWallet, const CCoinControl *coinControlParam) : + TxBuilder(walletParam), mintWallet(mintWallet) { cs_main.lock(); @@ -120,7 +120,7 @@ SigmaSpendBuilder::SigmaSpendBuilder(CWallet& wallet, CHDMintWallet& mintWallet, throw; } - this->coinControl = coinControl; + this->coinControl = coinControlParam; } SigmaSpendBuilder::~SigmaSpendBuilder() diff --git a/src/wallet/sigmaspendbuilder.h b/src/wallet/sigmaspendbuilder.h index f05c49d030..89b8860319 100644 --- a/src/wallet/sigmaspendbuilder.h +++ b/src/wallet/sigmaspendbuilder.h @@ -15,7 +15,7 @@ class SigmaSpendBuilder : public TxBuilder std::vector denomChanges; public: - SigmaSpendBuilder(CWallet& wallet, CHDMintWallet& mintWallet, const CCoinControl *coinControl = nullptr); + SigmaSpendBuilder(CWallet& walletParam, CHDMintWallet& mintWallet, const CCoinControl *coinControlParam = nullptr); ~SigmaSpendBuilder() override; protected: diff --git a/src/wallet/test/CMakeLists.txt b/src/wallet/test/CMakeLists.txt new file mode 100644 index 0000000000..c472069744 --- /dev/null +++ b/src/wallet/test/CMakeLists.txt @@ -0,0 +1,20 @@ +# Copyright (c) 2023-present The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +# Do not use generator expressions in test sources because the +# SOURCES property is processed to gather test suite macros. + +target_sources(test_firo + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/accounting_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/crypto_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/lelantus_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/mnemonic_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/sigma_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/spark_wallet_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/txbuilder_tests.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/wallet_test_fixture.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/wallet_tests.cpp +) +target_link_libraries(test_firo firo_wallet) diff --git a/src/wallet/test/accounting_tests.cpp b/src/wallet/test/accounting_tests.cpp index 6a6bf88c31..5811fbf3c1 100644 --- a/src/wallet/test/accounting_tests.cpp +++ b/src/wallet/test/accounting_tests.cpp @@ -15,7 +15,7 @@ extern CWallet* pwalletMain; BOOST_FIXTURE_TEST_SUITE(accounting_tests, WalletTestingSetup) -static void +FIRO_UNUSED static void GetResults(std::map& results) { std::list aes; diff --git a/src/wallet/test/lelantus_tests.cpp b/src/wallet/test/lelantus_tests.cpp index 36d080072c..969600b445 100644 --- a/src/wallet/test/lelantus_tests.cpp +++ b/src/wallet/test/lelantus_tests.cpp @@ -167,12 +167,8 @@ BOOST_AUTO_TEST_CASE(mintlelantus_and_mint_all) LOCK2(cs_main, pwalletMain->cs_wallet); std::vector scripts; while (blocks != 0) { - CPubKey key; - { - LOCK(pwalletMain->cs_wallet); - key = pwalletMain->GenerateNewKey(); - } + key = pwalletMain->GenerateNewKey(); scripts.push_back(GetScriptForDestination(key.GetID())); auto blockCount = std::min(blocksPerScript, blocks); diff --git a/src/wallet/test/sigma_tests.cpp b/src/wallet/test/sigma_tests.cpp index fe372d8758..b77aa4e82f 100644 --- a/src/wallet/test/sigma_tests.cpp +++ b/src/wallet/test/sigma_tests.cpp @@ -43,7 +43,7 @@ struct WalletSigmaTestingSetup : WalletTestingSetup sigma::CSigmaState *sigmaState; }; -static void AddSigmaCoin(const sigma::PrivateCoin& coin, const sigma::CoinDenomination denomination) +FIRO_UNUSED static void AddSigmaCoin(const sigma::PrivateCoin& coin, const sigma::CoinDenomination denomination) { CSigmaEntry zerocoinTx; @@ -107,7 +107,7 @@ static void GenerateEmptyBlocks(int number_of_blocks) } } -static bool CheckDenominationCoins( +FIRO_UNUSED static bool CheckDenominationCoins( const std::vector>& expected, std::vector actualDenominations) { diff --git a/src/wallet/test/spark_tests.cpp b/src/wallet/test/spark_wallet_tests.cpp similarity index 98% rename from src/wallet/test/spark_tests.cpp rename to src/wallet/test/spark_wallet_tests.cpp index 1d05c9e9df..b5aa6b0c2f 100644 --- a/src/wallet/test/spark_tests.cpp +++ b/src/wallet/test/spark_wallet_tests.cpp @@ -37,7 +37,7 @@ void ExtractSpend(CTransaction const &tx, } } -BOOST_FIXTURE_TEST_SUITE(spark_tests, SparkTestingSetup) +BOOST_FIXTURE_TEST_SUITE(spark_wallet_tests, SparkTestingSetup) BOOST_AUTO_TEST_CASE(create_mint_recipient) { @@ -280,10 +280,7 @@ BOOST_AUTO_TEST_CASE(mintspark_and_mint_all) std::vector scripts; while (blocks != 0) { CPubKey key; - { - LOCK(pwalletMain->cs_wallet); - key = pwalletMain->GenerateNewKey(); - } + key = pwalletMain->GenerateNewKey(); scripts.push_back(GetScriptForDestination(key.GetID())); auto blockCount = std::min(blocksPerScript, blocks); GenerateBlocks(blockCount, &scripts.back()); diff --git a/src/wallet/test/txbuilder_tests.cpp b/src/wallet/test/txbuilder_tests.cpp index 9eae1c407b..3f97f4cc45 100644 --- a/src/wallet/test/txbuilder_tests.cpp +++ b/src/wallet/test/txbuilder_tests.cpp @@ -22,8 +22,8 @@ class TestInputSigner : public InputSigner { } - explicit TestInputSigner(const CScript& sig, const COutPoint& output = COutPoint(), uint32_t seq = CTxIn::SEQUENCE_FINAL) : - InputSigner(output, seq), + explicit TestInputSigner(const CScript& sig, const COutPoint& outputParam = COutPoint(), uint32_t seq = CTxIn::SEQUENCE_FINAL) : + InputSigner(outputParam, seq), signature(sig) { } @@ -46,7 +46,7 @@ class TestTxBuilder : public TxBuilder std::function adjustFee; public: - explicit TestTxBuilder(CWallet& wallet) : TxBuilder(wallet) + explicit TestTxBuilder(CWallet& walletParam) : TxBuilder(walletParam) { } diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp index e17a05f90d..7f7671f73e 100644 --- a/src/wallet/test/wallet_tests.cpp +++ b/src/wallet/test/wallet_tests.cpp @@ -40,7 +40,7 @@ BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup) static const CWallet wallet; static vector vCoins; -static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0) +FIRO_UNUSED static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0) { static int nextLockTime = 0; CMutableTransaction tx; @@ -63,13 +63,13 @@ static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = fa wtxn.emplace_back(std::move(wtx)); } -static void empty_wallet(void) +FIRO_UNUSED static void empty_wallet(void) { vCoins.clear(); wtxn.clear(); } -static bool equal_sets(CoinSet a, CoinSet b) +FIRO_UNUSED static bool equal_sets(CoinSet a, CoinSet b) { pair ret = mismatch(a.begin(), a.end(), b.begin()); return ret.first == a.end() && ret.second == b.end(); diff --git a/src/wallet/txbuilder.cpp b/src/wallet/txbuilder.cpp index 637bc26a14..cb853516ba 100644 --- a/src/wallet/txbuilder.cpp +++ b/src/wallet/txbuilder.cpp @@ -103,7 +103,7 @@ CWalletTx TxBuilder::Build(const std::vector& recipients, CAmount& f assert(tx.nLockTime < LOCKTIME_THRESHOLD); // Start with no fee and loop until there is enough fee; - uint32_t nCountNextUse; + uint32_t nCountNextUse = 0; if (pwalletMain->zwallet) { nCountNextUse = pwalletMain->zwallet->GetCount(); } diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 661f9746ab..28574bdac1 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -2446,7 +2446,10 @@ CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex *pindexStart, bool f while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200))) pindex = chainActive.Next(pindex); } - LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height(), pindex->nHeight); + + if (pindex) + LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height(), pindex->nHeight); + ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex); double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()); @@ -3023,7 +3026,7 @@ std::vector CWallet::CreateSigmaMintRecipients( vDMints.push_back(dMint); - return {scriptSerializedCoin, v, false}; + return {scriptSerializedCoin, v, false, {}, {}}; } ); @@ -3087,7 +3090,7 @@ CRecipient CWallet::CreateLelantusMintRecipient( script.insert(script.end(), serializedHash.begin(), serializedHash.end()); // overall Lelantus mint script size is 1 + 34 + 98 + 32 = 165 byte - return {script, CAmount(coin.getV()), false}; + return {script, CAmount(coin.getV()), false, {}, {}}; } } @@ -3538,11 +3541,15 @@ bool CWallet::GetCoinsToSpend( _("Can not choose coins within limit.")); } - if (SelectMintCoinsForAmount(best_spend_val - roundedRequired * zeros, denominations, coinsToMint_out) != best_spend_val - roundedRequired * zeros) { + if (cmp::not_equal( + SelectMintCoinsForAmount(best_spend_val - roundedRequired * zeros, denominations, coinsToMint_out), + best_spend_val - roundedRequired * zeros)) { throw std::invalid_argument( _("Problem with coin selection for re-mint while spending.")); } - if (SelectSpendCoinsForAmount(best_spend_val, coins, coinsToSpend_out) != best_spend_val) { + if (cmp::not_equal( + SelectSpendCoinsForAmount(best_spend_val, coins, coinsToSpend_out), + best_spend_val)) { throw std::invalid_argument( _("Problem with coin selection for spend.")); } @@ -4232,7 +4239,7 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMin bool CWallet::SelectCoins(const std::vector& vAvailableCoins, const CAmount& nTargetValue, std::set >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl, bool fForUseInInstantSend) const { std::vector vCoins(vAvailableCoins); - CoinType nCoinType = coinControl ? coinControl->nCoinType : CoinType::ALL_COINS; + FIRO_UNUSED CoinType nCoinType = coinControl ? coinControl->nCoinType : CoinType::ALL_COINS; // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs) @@ -4307,7 +4314,7 @@ bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, bool ov for (size_t idx = 0; idx < tx.vout.size(); idx++) { const CTxOut& txOut = tx.vout[idx]; - CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1}; + CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1, {}, {}}; vecSend.push_back(recipient); } @@ -4442,7 +4449,7 @@ bool CWallet::CreateTransaction(const std::vector& vecSend, CWalletT { std::vector vAvailableCoins; AvailableCoins(vAvailableCoins, true, coinControl, false, fUseInstantSend); - int nInstantSendConfirmationsRequired = Params().GetConsensus().nInstantSendConfirmationsRequired; + FIRO_UNUSED int nInstantSendConfirmationsRequired = Params().GetConsensus().nInstantSendConfirmationsRequired; nFeeRet = 0; if(nFeePay > 0) nFeeRet = nFeePay; @@ -4802,14 +4809,16 @@ bool CWallet::EraseFromWallet(uint256 hash) { } /** - * @brief CWallet::CreateMintTransaction - * @param vecSend - * @param wtxNew - * @param reservekey - * @param nFeeRet - * @param strFailReason - * @param coinControl - * @return + * @brief CWallet::CreateMintTransaction Create a new mint transaction (coin generation transaction) + * @param vecSend Vector of recipients containing amounts and scripts to send + * @param[out] wtxNew Reference to store the new wallet transaction + * @param reservekey Key reserve used for change address generation + * @param[out] nFeeRet Reference to store the calculated transaction fee + * @param[in,out] nChangePosInOut Requested/calculated position of change output (-1 for random) + * @param[out] strFailReason Reference to store failure description if unsuccessful + * @param coinControl Optional coin selection control parameters + * @param sign Whether to sign the transaction immediately + * @return true if transaction creation succeeded, false otherwise */ bool CWallet::CreateMintTransaction(const std::vector &vecSend, CWalletTx &wtxNew, CReserveKey &reservekey, @@ -5359,10 +5368,10 @@ bool CWallet::CreateLelantusMintTransactions( return false; } - if (nFeeRet >= nFeeNeeded) { + if (cmp::greater_equal(nFeeRet, nFeeNeeded)) { for (auto &usedCoin : setCoins) { for (auto coin = itr->second.begin(); coin != itr->second.end(); coin++) { - if (usedCoin.first == coin->tx && usedCoin.second == coin->i) { + if (usedCoin.first == coin->tx && cmp::equal(usedCoin.second, coin->i)) { itr->first -= coin->tx->tx->vout[coin->i].nValue; itr->second.erase(coin); break; @@ -5491,7 +5500,7 @@ CWallet::CreateMintTransaction(CScript pubCoin, int64_t nValue, CWalletTx &wtxNe int64_t &nFeeRet, std::string &strFailReason, const CCoinControl *coinControl) { std::vector vecSend; - CRecipient recipient = {pubCoin, nValue, false}; + CRecipient recipient = {pubCoin, nValue, false, {}, {}}; vecSend.push_back(recipient); int nChangePosRet = -1; return CreateMintTransaction(vecSend, wtxNew, reservekey, nFeeRet, nChangePosRet, strFailReason, @@ -5684,7 +5693,7 @@ std::string CWallet::MintAndStoreSpark( for (auto& output : outputs) value += output.v; - if ((value + payTxFee.GetFeePerK()) > GetBalance()) + if (cmp::greater((value + payTxFee.GetFeePerK()), GetBalance())) return _("Insufficient funds"); LogPrintf("payTxFee.GetFeePerK()=%s\n", payTxFee.GetFeePerK()); @@ -5946,7 +5955,7 @@ bool CWallet::LelantusToSpark(std::string& strFailReason) { } while (coins.size() > 0 || sigmaCoins.size() > 0) { - bool addMoreCoins = true; + FIRO_UNUSED bool addMoreCoins = true; std::size_t selectedNum = 0; CCoinControl coinControl; CAmount spendValue = 0; @@ -5975,7 +5984,7 @@ bool CWallet::LelantusToSpark(std::string& strFailReason) { if (selectedNum == Params().GetConsensus().nMaxLelantusInputPerTransaction) break; } - CRecipient recipient = {scriptChange, spendValue, true}; + CRecipient recipient = {scriptChange, spendValue, true, {}, {}}; CWalletTx result; JoinSplitLelantus({recipient}, {}, result, &coinControl); @@ -5990,7 +5999,7 @@ bool CWallet::LelantusToSpark(std::string& strFailReason) { COutPoint outPoint(result.GetHash(), i); coinControl.Select(outPoint); std::vector> wtxAndFee; - MintAndStoreSpark({}, wtxAndFee, true, true, false, &coinControl); + MintAndStoreSpark({}, wtxAndFee, true, true, false, false, &coinControl); } return true; @@ -6884,7 +6893,7 @@ spark::FullViewKey CWallet::GetSparkViewKey() { std::string CWallet::GetSparkViewKeyStr() { spark::FullViewKey key = GetSparkViewKey(); - int size = GetSerializeSize(key, SER_NETWORK, PROTOCOL_VERSION); + FIRO_UNUSED int size = GetSerializeSize(key, SER_NETWORK, PROTOCOL_VERSION); std::ostringstream keydata; ::Serialize(keydata, key); @@ -7331,10 +7340,13 @@ CWallet* CWallet::CreateWalletFromFile(const std::string walletFile) walletInstance->sparkWallet = std::make_unique(pwalletMain->strWalletFile); spark::Address address = walletInstance->sparkWallet->getDefaultAddress(); - unsigned char network = spark::GetNetworkType(); - if (!walletInstance->SetSparkAddressBook(address.encode(network), "", "receive")) { - InitError(_("Cannot write default spark address") += "\n"); - return NULL; + std::string addrStr = address.encode(spark::GetNetworkType()); + + if (walletInstance->mapSparkAddressBook.count(addrStr) == 0) { + if (!walletInstance->SetSparkAddressBook(addrStr, "", "receive")) { + InitError(_("Cannot write default spark address") += "\n"); + return NULL; + } } } @@ -7668,7 +7680,7 @@ CWalletTx CWallet::PrepareAndSendNotificationTx(bip47::CPaymentCode const & thei recipients.emplace_back(receiver); CScript opReturnScript = CScript() << OP_RETURN << std::vector(80); // Passing empty array to calc fees - recipients.push_back({opReturnScript, 0, false}); + recipients.push_back({opReturnScript, 0, false, {}, {}}); auto throwSigma = [](){throw std::runtime_error(std::string("There are unspent Sigma coins in your wallet. Using Sigma coins for BIP47 is not supported. Please spend your Sigma coins before establishing a BIP47 channel."));}; @@ -8337,7 +8349,7 @@ bool CWallet::DelAddressBook(const std::string& address) LOCK(cs_wallet); // mapAddressBook const spark::Params* params = spark::Params::get_default(); unsigned char network = spark::GetNetworkType(); - unsigned char coinNetwork; + unsigned char coinNetwork = {}; spark::Address addr(params); try { diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index a59c896037..80cefff9a4 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -190,8 +190,8 @@ struct CRecipient CScript scriptPubKey; CAmount nAmount; bool fSubtractFeeFromAmount; - std::string address; - std::string memo; + std::string address {}; + std::string memo {}; }; typedef std::map mapValue_t; @@ -1453,7 +1453,7 @@ class CReserveKey : public CReserveScript void ReturnKey(); bool GetReservedKey(CPubKey &pubkey); void KeepKey(); - void KeepScript() { KeepKey(); } + void KeepScript() override { KeepKey(); } }; diff --git a/src/wallet/walletdb.h b/src/wallet/walletdb.h index d56f1c8672..48e26af127 100644 --- a/src/wallet/walletdb.h +++ b/src/wallet/walletdb.h @@ -187,7 +187,7 @@ class CKeyMetadata class CWalletDB : public CDB { public: - CWalletDB(const std::string& strFilename, const char* pszMode = "r+", bool fFlushOnClose = true) : CDB(strFilename, pszMode, fFlushOnClose) + CWalletDB(const std::string& strFilename, const char* pszMode = "r+", bool fFlushOnCloseParam = true) : CDB(strFilename, pszMode, fFlushOnCloseParam) { } diff --git a/src/warnings.h b/src/warnings.h index a7aa657426..cc4804df71 100644 --- a/src/warnings.h +++ b/src/warnings.h @@ -14,7 +14,14 @@ void SetfLargeWorkForkFound(bool flag); bool GetfLargeWorkForkFound(); void SetfLargeWorkInvalidChainFound(bool flag); bool GetfLargeWorkInvalidChainFound(); -std::string GetWarnings(const std::string& strFor); +/** Format a string that describes several potential problems detected by the core. + * strFor can have three values: + * - "rpc": get critical warnings, which should put the client in safe mode if non-empty + * - "statusbar": get all warnings + * - "gui": get all warnings, translated (where possible) for GUI + * This function only returns the highest priority warning of the set selected by strFor. + */ + std::string GetWarnings(const std::string& strFor); static const bool DEFAULT_TESTSAFEMODE = false; diff --git a/src/zmq/CMakeLists.txt b/src/zmq/CMakeLists.txt new file mode 100644 index 0000000000..b891d42665 --- /dev/null +++ b/src/zmq/CMakeLists.txt @@ -0,0 +1,23 @@ +# Copyright (c) 2023-present The firo Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +add_library(firo_zmq STATIC EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/zmqabstractnotifier.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/zmqnotificationinterface.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/zmqpublishnotifier.cpp +) +target_compile_definitions(firo_zmq + INTERFACE + ENABLE_ZMQ=1 + PRIVATE + $<$:ZMQ_STATIC> +) +target_link_libraries(firo_zmq + PRIVATE + core_interface + univalue + zeromq + secp256k1 + leveldb +) diff --git a/src/zmq/zmqnotificationinterface.h b/src/zmq/zmqnotificationinterface.h index beabb78da6..e7683b95d4 100644 --- a/src/zmq/zmqnotificationinterface.h +++ b/src/zmq/zmqnotificationinterface.h @@ -24,8 +24,8 @@ class CZMQNotificationInterface : public CValidationInterface void Shutdown(); // CValidationInterface - void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock); - void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload); + void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock) override; + void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override; private: CZMQNotificationInterface(); diff --git a/src/zmq/zmqpublishnotifier.h b/src/zmq/zmqpublishnotifier.h index bcbecf1bde..aa7abf708b 100644 --- a/src/zmq/zmqpublishnotifier.h +++ b/src/zmq/zmqpublishnotifier.h @@ -24,32 +24,32 @@ class CZMQAbstractPublishNotifier : public CZMQAbstractNotifier */ bool SendMessage(const char *command, const void* data, size_t size); - bool Initialize(void *pcontext); - void Shutdown(); + bool Initialize (void *pcontext) override; + void Shutdown() override; }; class CZMQPublishHashBlockNotifier : public CZMQAbstractPublishNotifier { public: - bool NotifyBlock(const CBlockIndex *pindex); + bool NotifyBlock(const CBlockIndex *pindex) override; }; class CZMQPublishHashTransactionNotifier : public CZMQAbstractPublishNotifier { public: - bool NotifyTransaction(const CTransaction &transaction); + bool NotifyTransaction(const CTransaction &transaction) override; }; class CZMQPublishRawBlockNotifier : public CZMQAbstractPublishNotifier { public: - bool NotifyBlock(const CBlockIndex *pindex); + bool NotifyBlock(const CBlockIndex *pindex) override; }; class CZMQPublishRawTransactionNotifier : public CZMQAbstractPublishNotifier { public: - bool NotifyTransaction(const CTransaction &transaction); + bool NotifyTransaction(const CTransaction &transaction) override; }; #endif // BITCOIN_ZMQ_ZMQPUBLISHNOTIFIER_H