diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml index 60946a402..1fdf47c9d 100644 --- a/.github/workflows/c-cpp.yml +++ b/.github/workflows/c-cpp.yml @@ -23,11 +23,15 @@ jobs: BRANCH_NAME: ${{ github.head_ref || github.ref_name }} steps: - name: Clone the repository - run: git clone https://github.com/${{ github.repository }} ${{ env.TARGET_DIR}} || true + run: git clone https://github.com/${{github.repository}} ${{env.TARGET_DIR}} || true - name: Sync with remote repository run: git -C ${{env.TARGET_DIR}} fetch - name: Checkout to current branch run: git -C ${{env.TARGET_DIR}} checkout ${{env.BRANCH_NAME}} + - name: Set user.email + run: git -C ${{env.TARGET_DIR}} config --global user.email "github-actions[bot]@users.noreply.github.com" + - name: Set user.name + run: git -C ${{env.TARGET_DIR}} config --global user.name "github-actions" - name: Update local repository run: git -C ${{env.TARGET_DIR}} pull - name: Build the container @@ -36,7 +40,7 @@ jobs: run: ./scripts/auto.sh -s bdk stop - name: Restart the container run: ./scripts/auto.sh -s bdk up - - name: Clean previos build (if any) + - name: Clean previous build (if there is one) run: ./scripts/auto.sh -s bdk exec 'make -C build clean' || true - name: Configure MOLD linker run: ./scripts/auto.sh -s bdk exec 'cmake -S . -B build diff --git a/CMakeLists.txt b/CMakeLists.txt index 337606597..32130f6dc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,6 +16,8 @@ if (CMAKE_VERSION VERSION_GREATER_EQUAL "3.24.0") cmake_policy(SET CMP0135 NEW) endif() +# TODO: avoid FindBoost deprecation message in CMake 3.30+ (cmake --help-policy CMP0167) + # Project data project(bdk VERSION 0.2.0 DESCRIPTION "AppLayer Blockchain Development Kit") set(CMAKE_CXX_STANDARD 23) @@ -59,8 +61,8 @@ set(BUILD_DISCOVERY ON CACHE BOOL "Build helper discovery node program") set(BUILD_TOOLS OFF CACHE BOOL "Build tools related to subnet") set(BUILD_TESTNET OFF CACHE BOOL "Build the project for testnet") set(BUILD_BENCHMARK OFF CACHE BOOL "Build with the benchmark tests") -set(USE_LINT OFF CACHE BOOL "Run linter on compile (clang-tidy)") set(BUILD_VARIABLES_TESTS ON CACHE BOOL "Build tests for SafeVar (Contract variables)") +set(USE_LINT OFF CACHE BOOL "Run linter on compile (clang-tidy)") if(USE_LINT) set(CMAKE_CXX_CLANG_TIDY "clang-tidy;-header-filter=.;-checks=-*,abseil-*,boost-*,bugprone-*,cert-*,clang-analyzer-*,concurrency-*,cppcoreguidelines-*,hicpp-*,misc-*,modernize-*,performance-*,portability-*,readability-*") endif() @@ -79,6 +81,9 @@ message(STATUS "Find libs with suffix: ${CMAKE_FIND_LIBRARY_SUFFIXES}") message("Building tests: ${BUILD_TESTS}") message("Building Discovery Node: ${BUILD_DISCOVERY}") message("Building tools: ${BUILD_TOOLS}") +message("Building testnet: ${BUILD_TESTNET}") +message("Building benchmark tests: ${BUILD_BENCHMARK}") +message("Building SafeVar tests: ${BUILD_VARIABLES_TESTS}") message("Using lint: ${USE_LINT}") cable_add_buildinfo_library(PROJECT_NAME bdk) @@ -89,21 +94,22 @@ set(OPENSSL_USE_STATIC_LIBS ON) set(Protobuf_USE_STATIC_LIBS ON) # Find system packages (built-in) -find_package(Threads) find_package(Boost 1.83.0 REQUIRED COMPONENTS chrono filesystem program_options system thread nowide) find_package(OpenSSL 1.1.1 REQUIRED) -find_package(ZLIB REQUIRED) +find_package(Protobuf REQUIRED) # TODO: not used yet but will be, keep it for now +find_package(Threads) # Find system packages (custom) +find_package(Cares REQUIRED) # TODO: not used yet but will be, keep it for now find_package(CryptoPP 8.2.0 REQUIRED) +find_package(Ethash REQUIRED) +find_package(Evmc REQUIRED) +find_package(Evmone REQUIRED) +find_package(GRPC REQUIRED) # TODO: not used yet but will be, keep it for now +find_package(Keccak REQUIRED) find_package(Scrypt REQUIRED) - -# Add external modules -include(cmake/ProjectEthash.cmake) # Ethash -include(cmake/ProjectSecp256k1.cmake) # Bitcoin core fast implementation -include(cmake/ProjectSpeedb.cmake) # Speedb (Level/RocksDB drop-in replacement) -include(cmake/ProjectEVMOne.cmake) # EVMOne (EVMOne + EVMC) - +find_package(Secp256k1 REQUIRED) +find_package(Speedb REQUIRED) # Add catch2 as a library add_library(catch2 @@ -141,21 +147,21 @@ add_subdirectory(src/utils) add_subdirectory(tests) add_library(bdk_lib STATIC - ${UTILS_HEADERS} - ${UTILS_SOURCES} - ${CONTRACT_HEADERS} - ${CONTRACT_SOURCES} - ${CORE_HEADERS} - ${CORE_SOURCES} - ${NET_HEADERS} - ${NET_SOURCES} + ${UTILS_HEADERS} ${UTILS_SOURCES} ${CONTRACT_HEADERS} ${CONTRACT_SOURCES} + ${CORE_HEADERS} ${CORE_SOURCES} ${NET_HEADERS} ${NET_SOURCES} ) -target_include_directories(bdk_lib PRIVATE ${CMAKE_SOURCE_DIR}/include ${OPENSSL_INCLUDE_DIR}) +target_include_directories(bdk_lib PRIVATE + ${CMAKE_SOURCE_DIR}/include ${OPENSSL_INCLUDE_DIR} ${ETHASH_INCLUDE_DIR} ${KECCAK_INCLUDE_DIR} + ${EVMC_INCLUDE_DIR} ${EVMONE_INCLUDE_DIR} ${SPEEDB_INCLUDE_DIR} ${SECP256K1_INCLUDE_DIR} +) -target_link_libraries(bdk_lib PRIVATE EvmcInstructions EvmcLoader EvmcTooling Evmone - ${CRYPTOPP_LIBRARIES} ${SCRYPT_LIBRARY} Secp256k1 Ethash ${ETHASH_BYPRODUCTS} - Speedb ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES}) +target_link_libraries(bdk_lib PRIVATE + ${EVMC_INSTRUCTIONS_LIBRARY} ${EVMC_LOADER_LIBRARY} ${EVMONE_LIBRARY} + ${CRYPTOPP_LIBRARIES} ${SCRYPT_LIBRARY} ${SECP256K1_LIBRARY} + ${ETHASH_LIBRARY} ${KECCAK_LIBRARY} ${SPEEDB_LIBRARY} + ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} +) add_subdirectory(src/bins) diff --git a/Dockerfile b/Dockerfile index a85c0d1f8..b1a494745 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,40 +8,18 @@ FROM debian:trixie # Update the system RUN apt-get update && apt-get upgrade -y -# Install dependencies -RUN apt-get install -y \ - build-essential \ - cmake \ - tmux \ - clang-tidy \ - autoconf \ - libtool \ - pkg-config \ - libabsl-dev \ - libboost-all-dev \ - libc-ares-dev \ - libcrypto++-dev \ - libgrpc-dev \ - libgrpc++-dev \ - librocksdb-dev \ - libscrypt-dev \ - libsnappy-dev \ - libssl-dev \ - zlib1g-dev \ - openssl \ - protobuf-compiler \ - protobuf-compiler-grpc \ - nano \ - vim \ - unison \ - git - # Set the working directory in the Docker container WORKDIR /bdk-cpp # Copy the local folder to the container COPY . /bdk-cpp +# Install Docker-specific dependencies +RUN apt-get -y install nano vim unison curl jq unzip gcovr + +# Install dependencies +RUN bash /bdk-cpp/scripts/deps.sh --install + # Create the synchronized directory RUN mkdir /bdk-volume diff --git a/README.md b/README.md index 3dd233f41..a32b2dad7 100644 --- a/README.md +++ b/README.md @@ -35,8 +35,8 @@ The project has a Dockerfile at the root of the repository that will build the p * Build the image locally with `docker build -t bdk-cpp-dev:latest .` (if using Linux or Mac, run as `sudo`) * This will build the image and tag it as `bdk-cpp-dev:latest` - you can change the tag to whatever you want, but remember to change it on the next step * Run the container (you will be logged in as root): - * **For Linux/Mac**: `sudo docker run -it -v $(pwd):/bdk-volume -p 8080-8099:8080-8099 -p 8110-8111:8110-8111 bdk-cpp-dev:latest` - * **For Windows**: `docker run -it -v %cd%:/bdk-volume -p 8080-8099:8080-8099 -p 8110-8111:8110-8111 bdk-cpp-dev:latest` + * **For Linux/Mac**: `sudo docker run -it --name bdk-cpp -v $(pwd):/bdk-volume -p 8080-8099:8080-8099 -p 8110-8111:8110-8111 bdk-cpp-dev:latest` + * **For Windows**: `docker run -it --name bdk-cpp -v %cd%:/bdk-volume -p 8080-8099:8080-8099 -p 8110-8111:8110-8111 bdk-cpp-dev:latest` Remember that we are using our local repo as a volume, so every change in the local folder will be reflected to the container in real time, and vice-versa. @@ -44,19 +44,31 @@ Also, you can integrate the container with your favorite IDE or editor, e.g. [VS ## Developing manually -Install the following dependencies on your system: - -* **GCC** with support for **C++23** or higher -* **CMake 3.19.0** or higher -* **Boost 1.83** or higher (components: *chrono, filesystem, program-options, system, thread, nowide*) -* **OpenSSL 1.1.1** -* **CryptoPP 8.2.0** or higher -* **libscrypt** -* **zlib** -* **libsnappy** for database compression -* **tmux** (for deploying) -* (optional) **clang-tidy** for linting -* (optional) **mold** for faster/more efficient linking +You will need the following dependencies installed locally on your system: + +* *Toolchain binaries*: + * **git** + * **GCC** with support for **C++23** or higher + * **Make** + * **CMake 3.19.0** or higher + * **Protobuf** (protoc + grpc_cpp_plugin) + * **tmux** (for deploying) + * (optional) **ninja** if you prefer it over make + * (optional) **mold** if you prefer it over ld + * (optional) **doxygen** for generating docs + * (optional) **clang-tidy** for linting +* *Libraries*: + * **Boost 1.83** or higher (components: *chrono, filesystem, program-options, system, thread, nowide*) + * **OpenSSL 1.1.1** / **libssl 1.1.1** or higher + * **libzstd** + * **CryptoPP 8.2.0** or higher + * **libscrypt** + * **libc-ares** + * **gRPC** (libgrpc and libgrpc++) + * **secp256k1** + * **ethash** + **keccak** + * **EVMOne** + **EVMC** + * **Speedb** The versions of those dependencies should suffice out-of-the-box for at least the following distros (or greater, including their derivatives): @@ -66,21 +78,23 @@ The versions of those dependencies should suffice out-of-the-box for at least th * **Fedora 40** * Any rolling release distro from around **May 2024** onwards (check their repos to be sure) -For older distros, you may need to compile some dependencies from source (specifically CMake, Boost and/or GCC). Make sure to either uninstall them from the system first to prevent any version conflicts, or use a workaround like e.g. Debian's `update-alternatives` or similar. +There is a script called `scripts/deps.sh` which you can use to check if you have those dependencies installed (`deps.sh --check`), and install them in case you don't (`deps.sh --install`). The script expects dependencies to be installed either on `/usr` or `/usr/local`, giving preference to the latter if it finds anything there (so you can use a higher version of a dependency while still keeping your distro's default one). -Specifically for GCC, make sure to also export the right paths for compilation in your environment in case you're using a self-compiled build. For example, in a Linux system, put something like this in your `~/.bashrc` file, changing the version accordingly to whichever one you have installed: +**Please note that installing most dependencies through the script only works on APT-based distros** (Debian, Ubuntu and derivatives) - you can still check the dependencies on any distro and install the few ones labeled as "external" (those are fetched through `git`), but if you're on a distro with another package manager and/or a distro older than one of the minimum ones listed above, you're on your own. -```bash -PATH=/usr/local/gcc-14.1.0/bin:$PATH -LD_LIBRARY_PATH=/usr/local/gcc-14.1.0/lib64:$LD_LIBRARY_PATH -``` +### GCC-specific tips -#### One-liners +For Debian specifically, you can (and should) use `update-alternatives` to register and set your GCC version to a more up-to-date build if required. -* For APT-based distros: +If you're using a self-compiled GCC build out of the system path (e.g. `--prefix=/usr/local/gcc-X.Y.Z` instead of `--prefix=/usr/local`), don't forget to export its installation paths in your `PATH` and `LD_LIBRARY_PATH` env vars (to prevent e.g. "version `GLIBCXX_...'/`CXXABI_...` not found" errors). Put something like this in your `~/.bashrc` file for example, changing the version accordingly to whichever one you have installed: ```bash -sudo apt install build-essential cmake tmux clang-tidy autoconf libtool pkg-config libabsl-dev libboost-all-dev libc-ares-dev libcrypto++-dev libgrpc-dev libgrpc++-dev librocksdb-dev libscrypt-dev libsnappy-dev libssl-dev zlib1g-dev openssl protobuf-compiler protobuf-compiler-grpc unison git +# For GCC in /usr/local +export LD_LIBRARY_PATH=/usr/local/lib64:$LD_LIBRARY_PATH + +# For self-contained GCC outside /usr/local +export PATH=/usr/local/gcc-14.2.0/bin:$PATH +export LD_LIBRARY_PATH=/usr/local/gcc-14.2.0/lib64:$LD_LIBRARY_PATH ``` ## Documentation diff --git a/cmake/FindAbsl.cmake b/cmake/FindAbsl.cmake deleted file mode 100644 index bf039dfca..000000000 --- a/cmake/FindAbsl.cmake +++ /dev/null @@ -1,1378 +0,0 @@ -# Finds the Abseil (absl) libraries in the system. -# Custom-built/"copied-then-modded" from the original CMake config files -# (abslConfig.cmake, abslTargets.cmake, abslTargets-none.cmake). -# Those are hardcoded to link SHARED libraries, with no way to toggle to STATIC. -# This one links STATIC by default, and can be toggled with `set(ABSL_FIND_SHARED ON)`. -# WORKS ON LINUX PATHS ONLY. I won't bother porting to other systems. - -# Set up prefixes/suffixes and lib type -set(ABSL_INCLUDE_DIR "/usr/include") -set(ABSL_PATH_PREFIX "/usr/lib/x86_64-linux-gnu/") -if(ABSL_FIND_SHARED) - set(ABSL_LIB_TYPE SHARED) - set(ABSL_LIB_SUFFIX ".so") -else() - set(ABSL_LIB_TYPE STATIC) - set(ABSL_LIB_SUFFIX ".a") -endif() - -# Protect against multiple inclusion, which would fail when already imported targets are added once more. -set(_targetsDefined) -set(_targetsNotDefined) -set(_expectedTargets) -foreach(_expectedTarget absl::atomic_hook absl::errno_saver absl::log_severity absl::raw_logging_internal absl::spinlock_wait absl::config absl::dynamic_annotations absl::core_headers absl::malloc_internal absl::base_internal absl::base absl::throw_delegate absl::pretty_function absl::endian absl::bits absl::exponential_biased absl::periodic_sampler absl::scoped_set_env absl::strerror absl::fast_type_id absl::algorithm absl::algorithm_container absl::container absl::btree absl::compressed_tuple absl::fixed_array absl::inlined_vector_internal absl::inlined_vector absl::counting_allocator absl::flat_hash_map absl::flat_hash_set absl::node_hash_map absl::node_hash_set absl::container_memory absl::hash_function_defaults absl::hash_policy_traits absl::hashtablez_sampler absl::hashtable_debug absl::hashtable_debug_hooks absl::have_sse absl::node_hash_policy absl::raw_hash_map absl::container_common absl::raw_hash_set absl::layout absl::stacktrace absl::symbolize absl::examine_stack absl::failure_signal_handler absl::debugging_internal absl::demangle_internal absl::leak_check absl::leak_check_disable absl::debugging absl::flags_path_util absl::flags_program_name absl::flags_config absl::flags_marshalling absl::flags_commandlineflag_internal absl::flags_commandlineflag absl::flags_private_handle_accessor absl::flags_reflection absl::flags_internal absl::flags absl::flags_usage_internal absl::flags_usage absl::flags_parse absl::bind_front absl::function_ref absl::hash absl::city absl::memory absl::type_traits absl::meta absl::int128 absl::numeric absl::random_random absl::random_bit_gen_ref absl::random_internal_mock_helpers absl::random_distributions absl::random_seed_gen_exception absl::random_seed_sequences absl::random_internal_traits absl::random_internal_distribution_caller absl::random_internal_fast_uniform_bits absl::random_internal_seed_material absl::random_internal_pool_urbg absl::random_internal_salted_seed_seq absl::random_internal_iostream_state_saver absl::random_internal_generate_real absl::random_internal_wide_multiply absl::random_internal_fastmath absl::random_internal_nonsecure_base absl::random_internal_pcg_engine absl::random_internal_randen_engine absl::random_internal_platform absl::random_internal_randen absl::random_internal_randen_slow absl::random_internal_randen_hwaes absl::random_internal_randen_hwaes_impl absl::random_internal_distribution_test_util absl::random_internal_uniform_helper absl::status absl::statusor absl::strings absl::strings_internal absl::str_format absl::str_format_internal absl::cord absl::graphcycles_internal absl::kernel_timeout_internal absl::synchronization absl::time absl::civil_time absl::time_zone absl::any absl::bad_any_cast absl::bad_any_cast_impl absl::span absl::optional absl::bad_optional_access absl::bad_variant_access absl::variant absl::compare absl::utility) - list(APPEND _expectedTargets ${_expectedTarget}) - if(NOT TARGET ${_expectedTarget}) - list(APPEND _targetsNotDefined ${_expectedTarget}) - endif() - if(TARGET ${_expectedTarget}) - list(APPEND _targetsDefined ${_expectedTarget}) - endif() -endforeach() -if("${_targetsDefined}" STREQUAL "${_expectedTargets}") - unset(_targetsDefined) - unset(_targetsNotDefined) - unset(_expectedTargets) - set(CMAKE_IMPORT_FILE_VERSION) - cmake_policy(POP) - return() -endif() -if(NOT "${_targetsDefined}" STREQUAL "") - message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_targetsDefined}\nTargets not yet defined: ${_targetsNotDefined}\n") -endif() -unset(_targetsDefined) -unset(_targetsNotDefined) -unset(_expectedTargets) - -# Create imported target absl::atomic_hook -add_library(absl::atomic_hook INTERFACE IMPORTED) - -set_target_properties(absl::atomic_hook PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::errno_saver -add_library(absl::errno_saver INTERFACE IMPORTED) - -set_target_properties(absl::errno_saver PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::log_severity -add_library(absl::log_severity ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::log_severity PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::core_headers" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_log_severity${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_log_severity${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::raw_logging_internal -add_library(absl::raw_logging_internal ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::raw_logging_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::atomic_hook;absl::config;absl::core_headers;absl::log_severity" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_raw_logging_internal${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_raw_logging_internal${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::spinlock_wait -add_library(absl::spinlock_wait ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::spinlock_wait PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base_internal;absl::core_headers;absl::errno_saver" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_spinlock_wait${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_spinlock_wait${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::config -add_library(absl::config INTERFACE IMPORTED) - -set_target_properties(absl::config PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::dynamic_annotations -add_library(absl::dynamic_annotations INTERFACE IMPORTED) - -set_target_properties(absl::dynamic_annotations PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::core_headers -add_library(absl::core_headers INTERFACE IMPORTED) - -set_target_properties(absl::core_headers PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::malloc_internal -add_library(absl::malloc_internal ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::malloc_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base;absl::base_internal;absl::config;absl::core_headers;absl::dynamic_annotations;absl::raw_logging_internal;Threads::Threads" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_malloc_internal${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_malloc_internal${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::base_internal -add_library(absl::base_internal INTERFACE IMPORTED) - -set_target_properties(absl::base_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::base -add_library(absl::base ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::base PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::atomic_hook;absl::base_internal;absl::config;absl::core_headers;absl::dynamic_annotations;absl::log_severity;absl::raw_logging_internal;absl::spinlock_wait;absl::type_traits;Threads::Threads" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_base${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_base${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::throw_delegate -add_library(absl::throw_delegate ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::throw_delegate PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::raw_logging_internal" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_throw_delegate${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_throw_delegate${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::pretty_function -add_library(absl::pretty_function INTERFACE IMPORTED) - -set_target_properties(absl::pretty_function PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::endian -add_library(absl::endian INTERFACE IMPORTED) - -set_target_properties(absl::endian PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base;absl::config;absl::core_headers;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::bits -add_library(absl::bits INTERFACE IMPORTED) - -set_target_properties(absl::bits PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::exponential_biased -add_library(absl::exponential_biased ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::exponential_biased PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_exponential_biased${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_exponential_biased${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::periodic_sampler -add_library(absl::periodic_sampler ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::periodic_sampler PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::core_headers;absl::exponential_biased" -) - -# Create imported target absl::scoped_set_env -add_library(absl::scoped_set_env ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::scoped_set_env PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::raw_logging_internal" -) - -# Create imported target absl::strerror -add_library(absl::strerror ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::strerror PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers;absl::errno_saver" -) - -# Create imported target absl::fast_type_id -add_library(absl::fast_type_id INTERFACE IMPORTED) - -set_target_properties(absl::fast_type_id PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::algorithm -add_library(absl::algorithm INTERFACE IMPORTED) - -set_target_properties(absl::algorithm PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::algorithm_container -add_library(absl::algorithm_container INTERFACE IMPORTED) - -set_target_properties(absl::algorithm_container PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::algorithm;absl::core_headers;absl::meta;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::container -add_library(absl::container INTERFACE IMPORTED) - -set_target_properties(absl::container PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::btree -add_library(absl::btree INTERFACE IMPORTED) - -set_target_properties(absl::btree PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::container_common;absl::compare;absl::compressed_tuple;absl::container_memory;absl::cord;absl::core_headers;absl::layout;absl::memory;absl::strings;absl::throw_delegate;absl::type_traits;absl::utility;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::compressed_tuple -add_library(absl::compressed_tuple INTERFACE IMPORTED) - -set_target_properties(absl::compressed_tuple PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::utility;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::fixed_array -add_library(absl::fixed_array INTERFACE IMPORTED) - -set_target_properties(absl::fixed_array PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::compressed_tuple;absl::algorithm;absl::config;absl::core_headers;absl::dynamic_annotations;absl::throw_delegate;absl::memory;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::inlined_vector_internal -add_library(absl::inlined_vector_internal INTERFACE IMPORTED) - -set_target_properties(absl::inlined_vector_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::compressed_tuple;absl::core_headers;absl::memory;absl::span;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::inlined_vector -add_library(absl::inlined_vector INTERFACE IMPORTED) - -set_target_properties(absl::inlined_vector PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::algorithm;absl::core_headers;absl::inlined_vector_internal;absl::throw_delegate;absl::memory;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::counting_allocator -add_library(absl::counting_allocator INTERFACE IMPORTED) - -set_target_properties(absl::counting_allocator PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::flat_hash_map -add_library(absl::flat_hash_map INTERFACE IMPORTED) - -set_target_properties(absl::flat_hash_map PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::container_memory;absl::hash_function_defaults;absl::raw_hash_map;absl::algorithm_container;absl::memory;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::flat_hash_set -add_library(absl::flat_hash_set INTERFACE IMPORTED) - -set_target_properties(absl::flat_hash_set PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::container_memory;absl::hash_function_defaults;absl::raw_hash_set;absl::algorithm_container;absl::core_headers;absl::memory;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::node_hash_map -add_library(absl::node_hash_map INTERFACE IMPORTED) - -set_target_properties(absl::node_hash_map PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::container_memory;absl::hash_function_defaults;absl::node_hash_policy;absl::raw_hash_map;absl::algorithm_container;absl::memory;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::node_hash_set -add_library(absl::node_hash_set INTERFACE IMPORTED) - -set_target_properties(absl::node_hash_set PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::hash_function_defaults;absl::node_hash_policy;absl::raw_hash_set;absl::algorithm_container;absl::memory;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::container_memory -add_library(absl::container_memory INTERFACE IMPORTED) - -set_target_properties(absl::container_memory PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::memory;absl::type_traits;absl::utility;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::hash_function_defaults -add_library(absl::hash_function_defaults INTERFACE IMPORTED) - -set_target_properties(absl::hash_function_defaults PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::cord;absl::hash;absl::strings;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::hash_policy_traits -add_library(absl::hash_policy_traits INTERFACE IMPORTED) - -set_target_properties(absl::hash_policy_traits PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::meta;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::hashtablez_sampler -add_library(absl::hashtablez_sampler ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::hashtablez_sampler PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base;absl::exponential_biased;absl::have_sse;absl::synchronization" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_hashtablez_sampler${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_hashtablez_sampler${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::hashtable_debug -add_library(absl::hashtable_debug INTERFACE IMPORTED) - -set_target_properties(absl::hashtable_debug PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::hashtable_debug_hooks;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::hashtable_debug_hooks -add_library(absl::hashtable_debug_hooks INTERFACE IMPORTED) - -set_target_properties(absl::hashtable_debug_hooks PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::have_sse -add_library(absl::have_sse INTERFACE IMPORTED) - -set_target_properties(absl::have_sse PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::node_hash_policy -add_library(absl::node_hash_policy INTERFACE IMPORTED) - -set_target_properties(absl::node_hash_policy PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::raw_hash_map -add_library(absl::raw_hash_map INTERFACE IMPORTED) - -set_target_properties(absl::raw_hash_map PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::container_memory;absl::raw_hash_set;absl::throw_delegate;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::container_common -add_library(absl::container_common INTERFACE IMPORTED) - -set_target_properties(absl::container_common PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::raw_hash_set -add_library(absl::raw_hash_set ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::raw_hash_set PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::bits;absl::compressed_tuple;absl::config;absl::container_common;absl::container_memory;absl::core_headers;absl::endian;absl::hash_policy_traits;absl::hashtable_debug_hooks;absl::have_sse;absl::layout;absl::memory;absl::meta;absl::optional;absl::utility;absl::hashtablez_sampler" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_raw_hash_set${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_raw_hash_set${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::layout -add_library(absl::layout INTERFACE IMPORTED) - -set_target_properties(absl::layout PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers;absl::meta;absl::strings;absl::span;absl::utility;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::stacktrace -add_library(absl::stacktrace ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::stacktrace PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::debugging_internal;absl::config;absl::core_headers" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_stacktrace${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_stacktrace${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::symbolize -add_library(absl::symbolize ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::symbolize PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::debugging_internal;absl::demangle_internal;absl::base;absl::config;absl::core_headers;absl::dynamic_annotations;absl::malloc_internal;absl::raw_logging_internal;absl::strings" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_symbolize${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_symbolize${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::examine_stack -add_library(absl::examine_stack ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::examine_stack PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::stacktrace;absl::symbolize;absl::config;absl::core_headers;absl::raw_logging_internal" -) - -# Create imported target absl::failure_signal_handler -add_library(absl::failure_signal_handler ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::failure_signal_handler PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::examine_stack;absl::stacktrace;absl::base;absl::config;absl::core_headers;absl::errno_saver;absl::raw_logging_internal" -) - -# Create imported target absl::debugging_internal -add_library(absl::debugging_internal ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::debugging_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::core_headers;absl::config;absl::dynamic_annotations;absl::errno_saver;absl::raw_logging_internal" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_debugging_internal${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_debugging_internal${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::demangle_internal -add_library(absl::demangle_internal ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::demangle_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base;absl::core_headers" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_demangle_internal${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_demangle_internal${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::leak_check -add_library(absl::leak_check ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::leak_check PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers" -) - -# Create imported target absl::leak_check_disable -add_library(absl::leak_check_disable ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::leak_check_disable PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} -) - -# Create imported target absl::debugging -add_library(absl::debugging INTERFACE IMPORTED) - -set_target_properties(absl::debugging PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::stacktrace;absl::leak_check;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::flags_path_util -add_library(absl::flags_path_util INTERFACE IMPORTED) - -set_target_properties(absl::flags_path_util PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::strings;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::flags_program_name -add_library(absl::flags_program_name ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::flags_program_name PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers;absl::flags_path_util;absl::strings;absl::synchronization" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_flags_program_name${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_flags_program_name${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::flags_config -add_library(absl::flags_config ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::flags_config PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::flags_path_util;absl::flags_program_name;absl::core_headers;absl::strings;absl::synchronization" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_flags_config${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_flags_config${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::flags_marshalling -add_library(absl::flags_marshalling ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::flags_marshalling PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers;absl::log_severity;absl::strings;absl::str_format" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_flags_marshalling${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_flags_marshalling${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::flags_commandlineflag_internal -add_library(absl::flags_commandlineflag_internal ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::flags_commandlineflag_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::fast_type_id" - IMPORTED_LOCATION - "${ABSL_PATH_PREFIX}libabsl_flags_commandlineflag_internal${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_flags_commandlineflag_internal${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::flags_commandlineflag -add_library(absl::flags_commandlineflag ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::flags_commandlineflag PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::fast_type_id;absl::flags_commandlineflag_internal;absl::optional;absl::strings" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_flags_commandlineflag${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_flags_commandlineflag${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::flags_private_handle_accessor -add_library(absl::flags_private_handle_accessor ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::flags_private_handle_accessor PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::flags_commandlineflag;absl::flags_commandlineflag_internal;absl::strings" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_flags_private_handle_accessor${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_flags_private_handle_accessor${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::flags_reflection -add_library(absl::flags_reflection ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::flags_reflection PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::flags_commandlineflag;absl::flags_private_handle_accessor;absl::flags_config;absl::strings;absl::synchronization;absl::flat_hash_map" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_flags_reflection${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_flags_reflection${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::flags_internal -add_library(absl::flags_internal ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::flags_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base;absl::config;absl::flags_commandlineflag;absl::flags_commandlineflag_internal;absl::flags_config;absl::flags_marshalling;absl::synchronization;absl::meta;absl::utility" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_flags_internal${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_flags_internal${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::flags -add_library(absl::flags ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::flags PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::flags_commandlineflag;absl::flags_config;absl::flags_internal;absl::flags_reflection;absl::base;absl::core_headers;absl::strings" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_flags${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_flags${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::flags_usage_internal -add_library(absl::flags_usage_internal ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::flags_usage_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::flags_config;absl::flags;absl::flags_commandlineflag;absl::flags_internal;absl::flags_path_util;absl::flags_private_handle_accessor;absl::flags_program_name;absl::flags_reflection;absl::strings;absl::synchronization" -) - -# Create imported target absl::flags_usage -add_library(absl::flags_usage ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::flags_usage PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers;absl::flags_usage_internal;absl::strings;absl::synchronization" -) - -# Create imported target absl::flags_parse -add_library(absl::flags_parse ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::flags_parse PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers;absl::flags_config;absl::flags;absl::flags_commandlineflag;absl::flags_commandlineflag_internal;absl::flags_internal;absl::flags_private_handle_accessor;absl::flags_program_name;absl::flags_reflection;absl::flags_usage;absl::strings;absl::synchronization" -) - -# Create imported target absl::bind_front -add_library(absl::bind_front INTERFACE IMPORTED) - -set_target_properties(absl::bind_front PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base_internal;absl::compressed_tuple;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::function_ref -add_library(absl::function_ref INTERFACE IMPORTED) - -set_target_properties(absl::function_ref PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base_internal;absl::meta;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::hash -add_library(absl::hash ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::hash PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers;absl::endian;absl::fixed_array;absl::meta;absl::int128;absl::strings;absl::optional;absl::variant;absl::utility;absl::city" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_hash${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_hash${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::city -add_library(absl::city ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::city PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers;absl::endian" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_city${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_city${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::memory -add_library(absl::memory INTERFACE IMPORTED) - -set_target_properties(absl::memory PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::core_headers;absl::meta;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::type_traits -add_library(absl::type_traits INTERFACE IMPORTED) - -set_target_properties(absl::type_traits PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::meta -add_library(absl::meta INTERFACE IMPORTED) - -set_target_properties(absl::meta PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::int128 -add_library(absl::int128 ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::int128 PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::bits;absl::config;absl::core_headers" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_int128${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_int128${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::numeric -add_library(absl::numeric INTERFACE IMPORTED) - -set_target_properties(absl::numeric PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::int128;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_random -add_library(absl::random_random INTERFACE IMPORTED) - -set_target_properties(absl::random_random PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::random_distributions;absl::random_internal_nonsecure_base;absl::random_internal_pcg_engine;absl::random_internal_pool_urbg;absl::random_internal_randen_engine;absl::random_seed_sequences;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_bit_gen_ref -add_library(absl::random_bit_gen_ref INTERFACE IMPORTED) - -set_target_properties(absl::random_bit_gen_ref PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::core_headers;absl::random_internal_distribution_caller;absl::random_internal_fast_uniform_bits;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_internal_mock_helpers -add_library(absl::random_internal_mock_helpers INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_mock_helpers PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::fast_type_id;absl::optional;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_distributions -add_library(absl::random_distributions ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::random_distributions PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base_internal;absl::config;absl::core_headers;absl::random_internal_generate_real;absl::random_internal_distribution_caller;absl::random_internal_fast_uniform_bits;absl::random_internal_fastmath;absl::random_internal_iostream_state_saver;absl::random_internal_traits;absl::random_internal_uniform_helper;absl::random_internal_wide_multiply;absl::strings;absl::type_traits" -) - -# Create imported target absl::random_seed_gen_exception -add_library(absl::random_seed_gen_exception ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::random_seed_gen_exception PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config" -) - -# Create imported target absl::random_seed_sequences -add_library(absl::random_seed_sequences ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::random_seed_sequences PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::inlined_vector;absl::random_internal_nonsecure_base;absl::random_internal_pool_urbg;absl::random_internal_salted_seed_seq;absl::random_internal_seed_material;absl::random_seed_gen_exception;absl::span" -) - -# Create imported target absl::random_internal_traits -add_library(absl::random_internal_traits INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_traits PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_internal_distribution_caller -add_library(absl::random_internal_distribution_caller INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_distribution_caller PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::utility;absl::fast_type_id;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_internal_fast_uniform_bits -add_library(absl::random_internal_fast_uniform_bits INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_fast_uniform_bits PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_internal_seed_material -add_library(absl::random_internal_seed_material ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::random_internal_seed_material PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::core_headers;absl::optional;absl::random_internal_fast_uniform_bits;absl::raw_logging_internal;absl::span;absl::strings" -) - -# Create imported target absl::random_internal_pool_urbg -add_library(absl::random_internal_pool_urbg ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::random_internal_pool_urbg PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base;absl::config;absl::core_headers;absl::endian;absl::random_internal_randen;absl::random_internal_seed_material;absl::random_internal_traits;absl::random_seed_gen_exception;absl::raw_logging_internal;absl::span" -) - -# Create imported target absl::random_internal_salted_seed_seq -add_library(absl::random_internal_salted_seed_seq INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_salted_seed_seq PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::inlined_vector;absl::optional;absl::span;absl::random_internal_seed_material;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_internal_iostream_state_saver -add_library(absl::random_internal_iostream_state_saver INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_iostream_state_saver PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::int128;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_internal_generate_real -add_library(absl::random_internal_generate_real INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_generate_real PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::bits;absl::random_internal_fastmath;absl::random_internal_traits;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_internal_wide_multiply -add_library(absl::random_internal_wide_multiply INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_wide_multiply PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::bits;absl::config;absl::int128;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_internal_fastmath -add_library(absl::random_internal_fastmath INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_fastmath PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::bits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_internal_nonsecure_base -add_library(absl::random_internal_nonsecure_base INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_nonsecure_base PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::core_headers;absl::optional;absl::random_internal_pool_urbg;absl::random_internal_salted_seed_seq;absl::random_internal_seed_material;absl::span;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_internal_pcg_engine -add_library(absl::random_internal_pcg_engine INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_pcg_engine PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::int128;absl::random_internal_fastmath;absl::random_internal_iostream_state_saver;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_internal_randen_engine -add_library(absl::random_internal_randen_engine INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_randen_engine PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::endian;absl::random_internal_iostream_state_saver;absl::random_internal_randen;absl::raw_logging_internal;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::random_internal_platform -add_library(absl::random_internal_platform ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::random_internal_platform PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config" -) - -# Create imported target absl::random_internal_randen -add_library(absl::random_internal_randen ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::random_internal_randen PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::random_internal_platform;absl::random_internal_randen_hwaes;absl::random_internal_randen_slow" -) - -# Create imported target absl::random_internal_randen_slow -add_library(absl::random_internal_randen_slow ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::random_internal_randen_slow PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::random_internal_platform;absl::config" -) - -# Create imported target absl::random_internal_randen_hwaes -add_library(absl::random_internal_randen_hwaes ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::random_internal_randen_hwaes PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::random_internal_platform;absl::random_internal_randen_hwaes_impl;absl::config" -) - -# Create imported target absl::random_internal_randen_hwaes_impl -add_library(absl::random_internal_randen_hwaes_impl ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::random_internal_randen_hwaes_impl PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::random_internal_platform;absl::config" -) - -# Create imported target absl::random_internal_distribution_test_util -add_library(absl::random_internal_distribution_test_util ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::random_internal_distribution_test_util PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers;absl::raw_logging_internal;absl::strings;absl::str_format;absl::span" -) - -# Create imported target absl::random_internal_uniform_helper -add_library(absl::random_internal_uniform_helper INTERFACE IMPORTED) - -set_target_properties(absl::random_internal_uniform_helper PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::random_internal_traits;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::status -add_library(absl::status ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::status PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::atomic_hook;absl::config;absl::core_headers;absl::raw_logging_internal;absl::inlined_vector;absl::stacktrace;absl::symbolize;absl::strings;absl::cord;absl::str_format;absl::optional" -) - -# Create imported target absl::statusor -add_library(absl::statusor ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::statusor PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::status;absl::core_headers;absl::raw_logging_internal;absl::type_traits;absl::strings;absl::utility;absl::variant" -) - -# Create imported target absl::strings -add_library(absl::strings ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::strings PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::strings_internal;absl::base;absl::bits;absl::config;absl::core_headers;absl::endian;absl::int128;absl::memory;absl::raw_logging_internal;absl::throw_delegate;absl::type_traits" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_strings${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_strings${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::strings_internal -add_library(absl::strings_internal ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::strings_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::core_headers;absl::endian;absl::raw_logging_internal;absl::type_traits" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_strings_internal${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_strings_internal${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::str_format -add_library(absl::str_format INTERFACE IMPORTED) - -set_target_properties(absl::str_format PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::str_format_internal;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::str_format_internal -add_library(absl::str_format_internal ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::str_format_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::bits;absl::strings;absl::config;absl::core_headers;absl::type_traits;absl::int128;absl::span" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_str_format_internal${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_str_format_internal${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::cord -add_library(absl::cord ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::cord PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base;absl::base_internal;absl::compressed_tuple;absl::core_headers;absl::endian;absl::fixed_array;absl::function_ref;absl::inlined_vector;absl::optional;absl::raw_logging_internal;absl::strings;absl::strings_internal;absl::type_traits" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_cord${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_cord${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::graphcycles_internal -add_library(absl::graphcycles_internal ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::graphcycles_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base;absl::base_internal;absl::config;absl::core_headers;absl::malloc_internal;absl::raw_logging_internal" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_graphcycles_internal${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_graphcycles_internal${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::kernel_timeout_internal -add_library(absl::kernel_timeout_internal INTERFACE IMPORTED) - -set_target_properties(absl::kernel_timeout_internal PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::core_headers;absl::raw_logging_internal;absl::time;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::synchronization -add_library(absl::synchronization ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::synchronization PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::graphcycles_internal;absl::kernel_timeout_internal;absl::atomic_hook;absl::base;absl::base_internal;absl::config;absl::core_headers;absl::dynamic_annotations;absl::malloc_internal;absl::raw_logging_internal;absl::stacktrace;absl::symbolize;absl::time;Threads::Threads" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_synchronization${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_synchronization${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::time -add_library(absl::time ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::time PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base;absl::civil_time;absl::core_headers;absl::int128;absl::raw_logging_internal;absl::strings;absl::time_zone" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_time${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_time${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::civil_time -add_library(absl::civil_time ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::civil_time PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_civil_time${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_civil_time${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::time_zone -add_library(absl::time_zone ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::time_zone PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "\$<\$:>" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_time_zone${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_time_zone${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::any -add_library(absl::any INTERFACE IMPORTED) - -set_target_properties(absl::any PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::bad_any_cast;absl::config;absl::core_headers;absl::fast_type_id;absl::type_traits;absl::utility;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::bad_any_cast -add_library(absl::bad_any_cast INTERFACE IMPORTED) - -set_target_properties(absl::bad_any_cast PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::bad_any_cast_impl;absl::config;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::bad_any_cast_impl -add_library(absl::bad_any_cast_impl ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::bad_any_cast_impl PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::raw_logging_internal" -) - -# Create imported target absl::span -add_library(absl::span INTERFACE IMPORTED) - -set_target_properties(absl::span PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::algorithm;absl::core_headers;absl::throw_delegate;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::optional -add_library(absl::optional INTERFACE IMPORTED) - -set_target_properties(absl::optional PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::bad_optional_access;absl::base_internal;absl::config;absl::core_headers;absl::memory;absl::type_traits;absl::utility;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::bad_optional_access -add_library(absl::bad_optional_access ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::bad_optional_access PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::raw_logging_internal" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_bad_optional_access${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_bad_optional_access${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::bad_variant_access -add_library(absl::bad_variant_access ${ABSL_LIB_TYPE} IMPORTED) - -set_target_properties(absl::bad_variant_access PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::config;absl::raw_logging_internal" - IMPORTED_LOCATION "${ABSL_PATH_PREFIX}libabsl_bad_variant_access${ABSL_LIB_SUFFIX}" - IMPORTED_SONAME "libabsl_bad_variant_access${ABSL_LIB_SUFFIX}" -) - -# Create imported target absl::variant -add_library(absl::variant INTERFACE IMPORTED) - -set_target_properties(absl::variant PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::bad_variant_access;absl::base_internal;absl::config;absl::core_headers;absl::type_traits;absl::utility;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::compare -add_library(absl::compare INTERFACE IMPORTED) - -set_target_properties(absl::compare PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::core_headers;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Create imported target absl::utility -add_library(absl::utility INTERFACE IMPORTED) - -set_target_properties(absl::utility PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${ABSL_INCLUDE_DIR} - INTERFACE_LINK_LIBRARIES "absl::base_internal;absl::config;absl::type_traits;-Wl,--as-needed;-latomic;-Wl,--no-as-needed" -) - -# Get all library paths for checking if they exist -list(APPEND _IMPORT_CHECK_TARGETS absl::log_severity) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::log_severity - "${ABSL_PATH_PREFIX}libabsl_log_severity${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::raw_logging_internal) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::raw_logging_internal - "${ABSL_PATH_PREFIX}libabsl_raw_logging_internal${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::spinlock_wait) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::spinlock_wait - "${ABSL_PATH_PREFIX}libabsl_spinlock_wait${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::malloc_internal) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::malloc_internal - "${ABSL_PATH_PREFIX}libabsl_malloc_internal${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::base) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::base - "${ABSL_PATH_PREFIX}libabsl_base${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::throw_delegate) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::throw_delegate - "${ABSL_PATH_PREFIX}libabsl_throw_delegate${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::exponential_biased) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::exponential_biased - "${ABSL_PATH_PREFIX}libabsl_exponential_biased${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::periodic_sampler) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::periodic_sampler - "${ABSL_PATH_PREFIX}libabsl_periodic_sampler${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::scoped_set_env) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::scoped_set_env - "${ABSL_PATH_PREFIX}libabsl_scoped_set_env${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::strerror) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::strerror - "${ABSL_PATH_PREFIX}libabsl_strerror${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::hashtablez_sampler) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::hashtablez_sampler - "${ABSL_PATH_PREFIX}libabsl_hashtablez_sampler${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::raw_hash_set) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::raw_hash_set - "${ABSL_PATH_PREFIX}libabsl_raw_hash_set${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::stacktrace) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::stacktrace - "${ABSL_PATH_PREFIX}libabsl_stacktrace${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::symbolize) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::symbolize - "${ABSL_PATH_PREFIX}libabsl_symbolize${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::examine_stack) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::examine_stack - "${ABSL_PATH_PREFIX}libabsl_examine_stack${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::failure_signal_handler) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::failure_signal_handler - "${ABSL_PATH_PREFIX}libabsl_failure_signal_handler${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::debugging_internal) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::debugging_internal - "${ABSL_PATH_PREFIX}libabsl_debugging_internal${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::demangle_internal) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::demangle_internal - "${ABSL_PATH_PREFIX}libabsl_demangle_internal${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::leak_check) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::leak_check - "${ABSL_PATH_PREFIX}libabsl_leak_check${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::leak_check_disable) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::leak_check_disable - "${ABSL_PATH_PREFIX}libabsl_leak_check_disable${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::flags_program_name) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::flags_program_name - "${ABSL_PATH_PREFIX}libabsl_flags_program_name${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::flags_config) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::flags_config - "${ABSL_PATH_PREFIX}libabsl_flags_config${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::flags_marshalling) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::flags_marshalling - "${ABSL_PATH_PREFIX}libabsl_flags_marshalling${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::flags_commandlineflag_internal) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::flags_commandlineflag_internal - "${ABSL_PATH_PREFIX}libabsl_flags_commandlineflag_internal${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::flags_commandlineflag) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::flags_commandlineflag - "${ABSL_PATH_PREFIX}libabsl_flags_commandlineflag${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::flags_private_handle_accessor) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::flags_private_handle_accessor - "${ABSL_PATH_PREFIX}libabsl_flags_private_handle_accessor${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::flags_reflection) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::flags_reflection - "${ABSL_PATH_PREFIX}libabsl_flags_reflection${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::flags_internal) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::flags_internal - "${ABSL_PATH_PREFIX}libabsl_flags_internal${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::flags) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::flags - "${ABSL_PATH_PREFIX}libabsl_flags${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::flags_usage_internal) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::flags_usage_internal - "${ABSL_PATH_PREFIX}libabsl_flags_usage_internal${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::flags_usage) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::flags_usage - "${ABSL_PATH_PREFIX}libabsl_flags_usage${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::flags_parse) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::flags_parse - "${ABSL_PATH_PREFIX}libabsl_flags_parse${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::hash) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::hash - "${ABSL_PATH_PREFIX}libabsl_hash${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::city) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::city - "${ABSL_PATH_PREFIX}libabsl_city${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::int128) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::int128 - "${ABSL_PATH_PREFIX}libabsl_int128${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::random_distributions) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::random_distributions - "${ABSL_PATH_PREFIX}libabsl_random_distributions${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::random_seed_gen_exception) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::random_seed_gen_exception - "${ABSL_PATH_PREFIX}libabsl_random_seed_gen_exception${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::random_seed_sequences) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::random_seed_sequences - "${ABSL_PATH_PREFIX}libabsl_random_seed_sequences${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::random_internal_seed_material) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::random_internal_seed_material - "${ABSL_PATH_PREFIX}libabsl_random_internal_seed_material${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::random_internal_pool_urbg) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::random_internal_pool_urbg - "${ABSL_PATH_PREFIX}libabsl_random_internal_pool_urbg${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::random_internal_platform) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::random_internal_platform - "${ABSL_PATH_PREFIX}libabsl_random_internal_platform${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::random_internal_randen) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::random_internal_randen - "${ABSL_PATH_PREFIX}libabsl_random_internal_randen${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::random_internal_randen_slow) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::random_internal_randen_slow - "${ABSL_PATH_PREFIX}libabsl_random_internal_randen_slow${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::random_internal_randen_hwaes) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::random_internal_randen_hwaes - "${ABSL_PATH_PREFIX}libabsl_random_internal_randen_hwaes${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::random_internal_randen_hwaes_impl) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::random_internal_randen_hwaes_impl - "${ABSL_PATH_PREFIX}libabsl_random_internal_randen_hwaes_impl${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::random_internal_distribution_test_util) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::random_internal_distribution_test_util - "${ABSL_PATH_PREFIX}libabsl_random_internal_distribution_test_util${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::status) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::status - "${ABSL_PATH_PREFIX}libabsl_status${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::statusor) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::statusor - "${ABSL_PATH_PREFIX}libabsl_statusor${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::strings) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::strings - "${ABSL_PATH_PREFIX}libabsl_strings${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::strings_internal) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::strings_internal - "${ABSL_PATH_PREFIX}libabsl_strings_internal${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::str_format_internal) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::str_format_internal - "${ABSL_PATH_PREFIX}libabsl_str_format_internal${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::cord) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::cord - "${ABSL_PATH_PREFIX}libabsl_cord${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::graphcycles_internal) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::graphcycles_internal - "${ABSL_PATH_PREFIX}libabsl_graphcycles_internal${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::synchronization) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::synchronization - "${ABSL_PATH_PREFIX}libabsl_synchronization${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::time) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::time - "${ABSL_PATH_PREFIX}libabsl_time${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::civil_time) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::civil_time - "${ABSL_PATH_PREFIX}libabsl_civil_time${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::time_zone) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::time_zone - "${ABSL_PATH_PREFIX}libabsl_time_zone${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::bad_any_cast_impl) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::bad_any_cast_impl - "${ABSL_PATH_PREFIX}libabsl_bad_any_cast_impl${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::bad_optional_access) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::bad_optional_access - "${ABSL_PATH_PREFIX}libabsl_bad_optional_access${ABSL_LIB_SUFFIX}" -) -list(APPEND _IMPORT_CHECK_TARGETS absl::bad_variant_access) -list(APPEND _IMPORT_CHECK_FILES_FOR_absl::bad_variant_access - "${ABSL_PATH_PREFIX}libabsl_bad_variant_access${ABSL_LIB_SUFFIX}" -) - -# Loop over all imported files and verify that they actually exist -foreach(target ${_IMPORT_CHECK_TARGETS} ) - foreach(file ${_IMPORT_CHECK_FILES_FOR_${target}} ) - if(NOT EXISTS "${file}" ) - message(FATAL_ERROR "The imported target \"${target}\" references the file - \"${file}\" -but this file does not exist. Possible reasons include: -* The file was deleted, renamed, or moved to another location. -* An install or uninstall procedure did not complete successfully. -* The installation package was faulty and contained - \"${CMAKE_CURRENT_LIST_FILE}\" -but not all the files it references. -") - endif() - endforeach() - unset(_IMPORT_CHECK_FILES_FOR_${target}) -endforeach() -unset(_IMPORT_CHECK_TARGETS) - diff --git a/cmake/FindCares.cmake b/cmake/FindCares.cmake index 97beb316f..5122c420e 100644 --- a/cmake/FindCares.cmake +++ b/cmake/FindCares.cmake @@ -7,7 +7,7 @@ include(SelectLibraryConfigurations) include(FindPackageHandleStandardArgs) find_path(CARES_INCLUDE_DIR NAMES ares.h) -find_library(CARES_LIBRARY NAMES libcares.a) +find_library(CARES_LIBRARY NAMES libcares_static.a libcares.a) SELECT_LIBRARY_CONFIGURATIONS(Cares) diff --git a/cmake/FindEthash.cmake b/cmake/FindEthash.cmake new file mode 100644 index 000000000..d04eed652 --- /dev/null +++ b/cmake/FindEthash.cmake @@ -0,0 +1,20 @@ +# Find the Ethash libraries and define the following variables: +# ETHASH_FOUND +# ETHASH_INCLUDE_DIR +# ETHASH_LIBRARY + +include(SelectLibraryConfigurations) +include(FindPackageHandleStandardArgs) + +find_path(ETHASH_INCLUDE_DIR NAMES ethash.h PATH_SUFFIXES ethash) +find_library(ETHASH_LIBRARY NAMES libethash.a) + +SELECT_LIBRARY_CONFIGURATIONS(Ethash) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS( + Ethash DEFAULT_MSG + ETHASH_LIBRARY ETHASH_INCLUDE_DIR +) + +mark_as_advanced(ETHASH_INCLUDE_DIR ETHASH_LIBRARY) + diff --git a/cmake/FindEvmc.cmake b/cmake/FindEvmc.cmake new file mode 100644 index 000000000..56e606cea --- /dev/null +++ b/cmake/FindEvmc.cmake @@ -0,0 +1,22 @@ +# Find the EVMC libraries and define the following variables: +# EVMC_FOUND +# EVMC_INCLUDE_DIR +# EVMC_INSTRUCTIONS_LIBRARY +# EVMC_LOADER_LIBRARY + +include(SelectLibraryConfigurations) +include(FindPackageHandleStandardArgs) + +find_path(EVMC_INCLUDE_DIR NAMES evmc.h PATH_SUFFIXES evmc) +find_library(EVMC_INSTRUCTIONS_LIBRARY NAMES libevmc-instructions.a) +find_library(EVMC_LOADER_LIBRARY NAMES libevmc-loader.a) + +SELECT_LIBRARY_CONFIGURATIONS(Evmc) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS( + Evmc DEFAULT_MSG + EVMC_INSTRUCTIONS_LIBRARY EVMC_LOADER_LIBRARY EVMC_INCLUDE_DIR +) + +mark_as_advanced(EVMC_INCLUDE_DIR EVMC_INSTRUCTIONS_LIBRARY EVMC_LOADER_LIBRARY) + diff --git a/cmake/FindEvmone.cmake b/cmake/FindEvmone.cmake new file mode 100644 index 000000000..50c71f85a --- /dev/null +++ b/cmake/FindEvmone.cmake @@ -0,0 +1,20 @@ +# Find the EVMOne library and define the following variables: +# EVMONE_FOUND +# EVMONE_INCLUDE_DIR +# EVMONE_LIBRARY + +include(SelectLibraryConfigurations) +include(FindPackageHandleStandardArgs) + +find_path(EVMONE_INCLUDE_DIR NAMES evmone.h PATH_SUFFIXES evmone) +find_library(EVMONE_LIBRARY NAMES libevmone.a) + +SELECT_LIBRARY_CONFIGURATIONS(Evmone) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS( + Evmone DEFAULT_MSG + EVMONE_LIBRARY EVMONE_INCLUDE_DIR +) + +mark_as_advanced(EVMONE_INCLUDE_DIR EVMONE_LIBRARY) + diff --git a/cmake/FindKeccak.cmake b/cmake/FindKeccak.cmake new file mode 100644 index 000000000..4a81c8262 --- /dev/null +++ b/cmake/FindKeccak.cmake @@ -0,0 +1,20 @@ +# Find the Keccak libraries and define the following variables: +# KECCAK_FOUND +# KECCAK_INCLUDE_DIR +# KECCAK_LIBRARY + +include(SelectLibraryConfigurations) +include(FindPackageHandleStandardArgs) + +find_path(KECCAK_INCLUDE_DIR NAMES keccak.h PATH_SUFFIXES ethash) +find_library(KECCAK_LIBRARY NAMES libkeccak.a) + +SELECT_LIBRARY_CONFIGURATIONS(Keccak) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS( + Keccak DEFAULT_MSG + KECCAK_LIBRARY KECCAK_INCLUDE_DIR +) + +mark_as_advanced(KECCAK_INCLUDE_DIR KECCAK_LIBRARY) + diff --git a/cmake/FindSecp256k1.cmake b/cmake/FindSecp256k1.cmake new file mode 100644 index 000000000..835ee5dd5 --- /dev/null +++ b/cmake/FindSecp256k1.cmake @@ -0,0 +1,20 @@ +# Find the secp256k1 library and define the following variables: +# SECP256K1_FOUND +# SECP256K1_INCLUDE_DIR +# SECP256K1_LIBRARY + +include(SelectLibraryConfigurations) +include(FindPackageHandleStandardArgs) + +find_path(SECP256K1_INCLUDE_DIR NAMES secp256k1.h) +find_library(SECP256K1_LIBRARY NAMES libsecp256k1.a) + +SELECT_LIBRARY_CONFIGURATIONS(Secp256k1) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS( + Secp256k1 DEFAULT_MSG + SECP256K1_LIBRARY SECP256K1_INCLUDE_DIR +) + +mark_as_advanced(SECP256K1_INCLUDE_DIR SECP256K1_LIBRARY) + diff --git a/cmake/FindSpeedb.cmake b/cmake/FindSpeedb.cmake new file mode 100644 index 000000000..cb2959af1 --- /dev/null +++ b/cmake/FindSpeedb.cmake @@ -0,0 +1,20 @@ +# Find the Speedb library and define the following variables: +# SPEEDB_FOUND +# SPEEDB_INCLUDE_DIR +# SPEEDB_LIBRARY + +include(SelectLibraryConfigurations) +include(FindPackageHandleStandardArgs) + +find_path(SPEEDB_INCLUDE_DIR NAMES db.h PATH_SUFFIXES rocksdb) +find_library(SPEEDB_LIBRARY NAMES libspeedb.a) + +SELECT_LIBRARY_CONFIGURATIONS(Speedb) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS( + Speedb DEFAULT_MSG + SPEEDB_LIBRARY SPEEDB_INCLUDE_DIR +) + +mark_as_advanced(SPEEDB_INCLUDE_DIR SPEEDB_LIBRARY) + diff --git a/cmake/ProjectEVMOne.cmake b/cmake/ProjectEVMOne.cmake deleted file mode 100644 index e3f862a12..000000000 --- a/cmake/ProjectEVMOne.cmake +++ /dev/null @@ -1,87 +0,0 @@ -include(ExternalProject) - -if (MSVC) - set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) - set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) -endif() - -set(prefix "${CMAKE_BINARY_DIR}/deps") -set(EVMONE_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}evmone${CMAKE_STATIC_LIBRARY_SUFFIX}") -set(EVMONE_INCLUDE_DIR "${prefix}/include") -set(EVMONE_VERSION "0.11.0") -set(EVMC_INCLUDE_DIR "${prefix}/include") -set(EVMC_INSTRUCTIONS_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}evmc-instructions${CMAKE_STATIC_LIBRARY_SUFFIX}") -set(EVMC_LOADER_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}evmc-loader${CMAKE_STATIC_LIBRARY_SUFFIX}") -set(EVMC_TOOLING_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}tooling${CMAKE_STATIC_LIBRARY_SUFFIX}") - -if(DEBUG) - ## EVMONE Can't be compiled with address sanitizer/stack protector - ## due to GCC stack size limits and GCC not accepting -Wno-stack-usage as a ignore error flag - set(EVMONE_CXX_FLAGS "-O0 -g -fno-inline -fno-eliminate-unused-debug-types -Werror=unused-variable") # Provides faster compile time. - ExternalProject_Add( - evmone - PREFIX "${prefix}" - GIT_REPOSITORY https://github.com/chfast/evmone - GIT_TAG "v${EVMONE_VERSION}" - CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${prefix} - -DCMAKE_POSITION_INDEPENDENT_CODE=${CMAKE_POSITION_INDEPENDENT_CODE} - -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} - -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} - -DCMAKE_CXX_FLAGS=${EVMONE_CXX_FLAGS} - -DBUILD_SHARED_LIBS=OFF - -DEVMC_INSTALL=ON - -DCMAKE_INSTALL_LIBDIR=lib - ${_only_release_configuration} - LOG_CONFIGURE 1 - ${_overwrite_install_command} - LOG_INSTALL 1 - BUILD_BYPRODUCTS ${EVMONE_LIBRARY} - BUILD_BYPRODUCTS ${EVMC_INSTRUCTIONS_LIBRARY} - BUILD_BYPRODUCTS ${EVMC_LOADER_LIBRARY} - BUILD_BYPRODUCTS ${EVMC_TOOLING_LIBRARY} - ) -else() - ExternalProject_Add( - evmone - PREFIX "${prefix}" - GIT_REPOSITORY https://github.com/chfast/evmone - GIT_TAG "v${EVMONE_VERSION}" - CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${prefix} - -DCMAKE_POSITION_INDEPENDENT_CODE=${CMAKE_POSITION_INDEPENDENT_CODE} - -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} - -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} - -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} - -DBUILD_SHARED_LIBS=OFF - -DEVMC_INSTALL=ON - -DCMAKE_INSTALL_LIBDIR=lib - ${_only_release_configuration} - LOG_CONFIGURE 1 - ${_overwrite_install_command} - LOG_INSTALL 1 - BUILD_BYPRODUCTS ${EVMONE_LIBRARY} - BUILD_BYPRODUCTS ${EVMC_INSTRUCTIONS_LIBRARY} - BUILD_BYPRODUCTS ${EVMC_LOADER_LIBRARY} - BUILD_BYPRODUCTS ${EVMC_TOOLING_LIBRARY} - ) -endif() - -# Create imported library -add_library(Evmone STATIC IMPORTED) -file(MAKE_DIRECTORY "${EVMONE_INCLUDE_DIR}") # Must exist. -set_property(TARGET Evmone PROPERTY IMPORTED_CONFIGURATIONS Release) -set_property(TARGET Evmone PROPERTY IMPORTED_LOCATION_RELEASE "${EVMONE_LIBRARY}") -set_property(TARGET Evmone PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${EVMONE_INCLUDE_DIR}") -add_dependencies(Evmone evmone ${EVMONE_LIBRARY} ${EVMONE_BYPRODUCTS}) - -# Create an imported target for each library -add_library(EvmcInstructions STATIC IMPORTED) -set_property(TARGET EvmcInstructions PROPERTY IMPORTED_LOCATION "${EVMC_INSTRUCTIONS_LIBRARY}") -add_dependencies(EvmcInstructions evmone) - -add_library(EvmcLoader STATIC IMPORTED) -set_property(TARGET EvmcLoader PROPERTY IMPORTED_LOCATION "${EVMC_LOADER_LIBRARY}") -add_dependencies(EvmcLoader evmone) - -add_library(EvmcTooling STATIC IMPORTED) -set_property(TARGET EvmcTooling PROPERTY IMPORTED_LOCATION "${EVMC_TOOLING_LIBRARY}") -add_dependencies(EvmcTooling evmone) \ No newline at end of file diff --git a/cmake/ProjectEthash.cmake b/cmake/ProjectEthash.cmake deleted file mode 100644 index 4e0ff4ae6..000000000 --- a/cmake/ProjectEthash.cmake +++ /dev/null @@ -1,43 +0,0 @@ -include(ExternalProject) - -if (MSVC) - set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) - set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) -endif() - -set(prefix "${CMAKE_BINARY_DIR}/deps") -set(ETHASH_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}ethash${CMAKE_STATIC_LIBRARY_SUFFIX}") -set(ETHASH_INCLUDE_DIR "${prefix}/include") -set(ETHASH_BYPRODUCTS "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}keccak${CMAKE_STATIC_LIBRARY_SUFFIX}") - -set(ETHASH_VERSION "1.0.1") - -ExternalProject_Add( - ethash - PREFIX "${prefix}" - GIT_REPOSITORY https://github.com/chfast/ethash - GIT_TAG "v${ETHASH_VERSION}" - CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${prefix} - -DCMAKE_POSITION_INDEPENDENT_CODE=${CMAKE_POSITION_INDEPENDENT_CODE} - -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} - -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} - -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} - -DETHASH_BUILD_TESTS=OFF - -DETHASH_BUILD_ETHASH=ON - -DCMAKE_INSTALL_LIBDIR=lib - ${_only_release_configuration} - LOG_CONFIGURE 1 - ${_overwrite_install_command} - LOG_INSTALL 1 - BUILD_BYPRODUCTS "${ETHASH_LIBRARY}" - BUILD_BYPRODUCTS "${ETHASH_BYPRODUCTS}" -) - -# Create imported library -add_library(Ethash STATIC IMPORTED) -file(MAKE_DIRECTORY "${ETHASH_INCLUDE_DIR}") # Must exist. -set_property(TARGET Ethash PROPERTY IMPORTED_CONFIGURATIONS Release) -set_property(TARGET Ethash PROPERTY IMPORTED_LOCATION_RELEASE "${ETHASH_LIBRARY}") -set_property(TARGET Ethash PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${ETHASH_INCLUDE_DIR}") -add_dependencies(Ethash ethash ${ETHASH_LIBRARY} ${ETHASH_BYPRODUCTS}) - diff --git a/cmake/ProjectEvmc.cmake b/cmake/ProjectEvmc.cmake deleted file mode 100644 index e53458d0d..000000000 --- a/cmake/ProjectEvmc.cmake +++ /dev/null @@ -1,48 +0,0 @@ -include(ExternalProject) - -if (MSVC) - set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) - set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) -endif() - -set(prefix "${CMAKE_BINARY_DIR}/deps") -set(EVMC_INCLUDE_DIR "${prefix}/include") -set(EVMC_INSTRUCTIONS_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}evmc-instructions${CMAKE_STATIC_LIBRARY_SUFFIX}") -set(EVMC_LOADER_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}evmc-loader${CMAKE_STATIC_LIBRARY_SUFFIX}") -set(EVMC_TOOLING_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}tooling${CMAKE_STATIC_LIBRARY_SUFFIX}") - -set(EVMC_VERSION "11.0.1") - -ExternalProject_Add( - evmc - PREFIX "${prefix}" - GIT_REPOSITORY https://github.com/ethereum/evmc - GIT_TAG "v${EVMC_VERSION}" - CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${prefix} - -DCMAKE_POSITION_INDEPENDENT_CODE=${CMAKE_POSITION_INDEPENDENT_CODE} - -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} - -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} - -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} - -DCMAKE_INSTALL_LIBDIR=lib - ${_only_release_configuration} - LOG_CONFIGURE 1 - ${_overwrite_install_command} - LOG_INSTALL 1 - BUILD_BYPRODUCTS ${EVMC_INSTRUCTIONS_LIBRARY} - BUILD_BYPRODUCTS ${EVMC_LOADER_LIBRARY} - BUILD_BYPRODUCTS ${EVMC_TOOLING_LIBRARY} -) - -# Create an imported target for each library -add_library(EvmcInstructions STATIC IMPORTED) -set_property(TARGET EvmcInstructions PROPERTY IMPORTED_LOCATION "${EVMC_INSTRUCTIONS_LIBRARY}") -add_dependencies(EvmcInstructions evmc) - -add_library(EvmcLoader STATIC IMPORTED) -set_property(TARGET EvmcLoader PROPERTY IMPORTED_LOCATION "${EVMC_LOADER_LIBRARY}") -add_dependencies(EvmcLoader evmc) - -add_library(EvmcTooling STATIC IMPORTED) -set_property(TARGET EvmcTooling PROPERTY IMPORTED_LOCATION "${EVMC_TOOLING_LIBRARY}") -add_dependencies(EvmcTooling evmc) - diff --git a/cmake/ProjectSecp256k1.cmake b/cmake/ProjectSecp256k1.cmake deleted file mode 100644 index 34d621bea..000000000 --- a/cmake/ProjectSecp256k1.cmake +++ /dev/null @@ -1,40 +0,0 @@ -include(ExternalProject) - -if (MSVC) - set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) - set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) -endif() - -set(prefix "${CMAKE_BINARY_DIR}/deps") -set(SECP256K1_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}secp256k1${CMAKE_STATIC_LIBRARY_SUFFIX}") -set(SECP256K1_INCLUDE_DIR "${prefix}/include") - -set(SECP256K1_VERSION "0.4.1") - -ExternalProject_Add( - secp256k1 - PREFIX "${prefix}" - GIT_REPOSITORY https://github.com/bitcoin-core/secp256k1 - GIT_TAG "v${SECP256K1_VERSION}" - PATCH_COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_LIST_DIR}/secp256k1/CMakeLists.txt - CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${prefix} - -DCMAKE_POSITION_INDEPENDENT_CODE=${CMAKE_POSITION_INDEPENDENT_CODE} - -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} - -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} - -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} - ${_only_release_configuration} - -DCMAKE_INSTALL_LIBDIR=lib - LOG_CONFIGURE 1 - ${_overwrite_install_command} - LOG_INSTALL 1 - BUILD_BYPRODUCTS "${SECP256K1_LIBRARY}" -) - -# Create imported library -add_library(Secp256k1 STATIC IMPORTED) -file(MAKE_DIRECTORY "${SECP256K1_INCLUDE_DIR}") # Must exist. -set_property(TARGET Secp256k1 PROPERTY IMPORTED_CONFIGURATIONS Release) -set_property(TARGET Secp256k1 PROPERTY IMPORTED_LOCATION_RELEASE "${SECP256K1_LIBRARY}") -set_property(TARGET Secp256k1 PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${SECP256K1_INCLUDE_DIR}") -add_dependencies(Secp256k1 secp256k1) - diff --git a/cmake/ProjectSpeedb.cmake b/cmake/ProjectSpeedb.cmake deleted file mode 100644 index b9a77b097..000000000 --- a/cmake/ProjectSpeedb.cmake +++ /dev/null @@ -1,63 +0,0 @@ -include(ExternalProject) - -if (MSVC) - set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) - set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) -endif() - -set(prefix "${CMAKE_BINARY_DIR}/deps") -set(SPEEDB_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}speedb${CMAKE_STATIC_LIBRARY_SUFFIX}") -set(SPEEDB_INCLUDE_DIR "${prefix}/include") - -set(SPEEDB_VERSION "2.8.0") - -# Top: precompiled binary, bottom: compiled from source -# (Uncomment) either depending on the necessity - -# TODO: doesn't work, fails compile with -fPIE related errors, try to fix this someday -#ExternalProject_Add( -# speedb -# PREFIX "${prefix}" -# URL https://github.com/speedb-io/speedb/releases/download/speedb/v${SPEEDB_VERSION}/speedb-${SPEEDB_VERSION}.tar.gz -# URL_HASH SHA256=b1d4ce4ec4d4f30e0d525c704a2079bfc15684043faf29e907eba519a7d7f930 -# DOWNLOAD_NAME speedb-${SPEEDB_VERSION}.tar.gz -# DOWNLOAD_NO_PROGRESS 1 -# CONFIGURE_COMMAND "${CMAKE_COMMAND}" -E copy_directory "${prefix}/src/speedb/include/rocksdb" "${SPEEDB_INCLUDE_DIR}/rocksdb" -# BUILD_COMMAND "" -# INSTALL_COMMAND "${CMAKE_COMMAND}" -E copy "${prefix}/src/speedb/lib64/libspeedb.a" "${SPEEDB_LIBRARY}" -#) - -ExternalProject_Add( - speedb - PREFIX "${prefix}" - GIT_REPOSITORY https://github.com/speedb-io/speedb - GIT_TAG "speedb/v${SPEEDB_VERSION}" - CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${prefix} - -DCMAKE_POSITION_INDEPENDENT_CODE=${CMAKE_POSITION_INDEPENDENT_CODE} - -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} - -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} - -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} - -DCMAKE_BUILD_TYPE=Release - ${_only_release_configuration} - -DCMAKE_INSTALL_LIBDIR=lib - -DROCKSDB_BUILD_SHARED=OFF - -DFAIL_ON_WARNINGS=OFF - -DWITH_GFLAGS=OFF - -DWITH_RUNTIME_DEBUG=OFF - -DWITH_TESTS=OFF - -DWITH_BENCHMARK_TOOLS=OFF - -DWITH_CORE_TOOLS=OFF - -DWITH_TOOLS=OFF - -DWITH_TRACE_TOOLS=OFF - ${_overwrite_install_command} - BUILD_BYPRODUCTS "${SPEEDB_LIBRARY}" - UPDATE_COMMAND "" -) - -# Create imported library -add_library(Speedb STATIC IMPORTED) -set_property(TARGET Speedb PROPERTY IMPORTED_CONFIGURATIONS Release) -set_property(TARGET Speedb PROPERTY IMPORTED_LOCATION_RELEASE "${SPEEDB_LIBRARY}") -set_property(TARGET Speedb PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${SPEEDB_INCLUDE_DIR}") -add_dependencies(Speedb speedb SPEEDB_LIBRARY) - diff --git a/cmake/secp256k1/CMakeLists.txt b/cmake/secp256k1/CMakeLists.txt deleted file mode 100644 index 14267f670..000000000 --- a/cmake/secp256k1/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ -# This CMake config file for secp256k1 project from https://github.com/bitcoin-core/secp256k1 -# -# The secp256k1 project has been configured following official docs with following options: -# -# ./configure --disable-shared --disable-tests --disable-coverage --disable-openssl-tests --disable-exhaustive-tests --disable-jni --with-bignum=no --with-field=64bit --with-scalar=64bit --with-asm=no -# -# Build static context: -# make src/ecmult_static_context.h -# -# Copy src/ecmult_static_context.h and src/libsecp256k1-config.h -# -# Copy CFLAGS from Makefile to COMPILE_OPTIONS. - -list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/modules) - -cmake_minimum_required(VERSION 3.4) -project(secp256k1 LANGUAGES C) - -set(COMMON_COMPILE_FLAGS ENABLE_MODULE_RECOVERY ENABLE_MODULE_ECDH USE_ECMULT_STATIC_PRECOMPUTATION USE_FIELD_INV_BUILTIN USE_NUM_NONE USE_SCALAR_INV_BUILTIN) -if (MSVC) - set(COMPILE_FLAGS USE_FIELD_10X26 USE_SCALAR_8X32) - set(COMPILE_OPTIONS "") -else() - set(COMPILE_FLAGS USE_FIELD_5X52 USE_SCALAR_4X64 HAVE_BUILTIN_EXPECT HAVE___INT128) - set(COMPILE_OPTIONS -O2 -W -std=c89 -pedantic -Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes -Wno-unused-function -Wno-long-long -Wno-overlength-strings -fvisibility=hidden) -endif() - -add_library(secp256k1 STATIC src/secp256k1.c src/precomputed_ecmult.h src/precomputed_ecmult_gen.h src/precomputed_ecmult.c src/precomputed_ecmult_gen.c) -target_compile_definitions(secp256k1 PRIVATE ${COMMON_COMPILE_FLAGS} ${COMPILE_FLAGS}) -target_include_directories(secp256k1 PRIVATE ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src) -target_compile_options(secp256k1 PRIVATE ${COMPILE_OPTIONS}) - -install(TARGETS secp256k1 ARCHIVE DESTINATION lib) -install(DIRECTORY include/ DESTINATION include) - diff --git a/docker/bdk_cpp.dockerfile b/docker/bdk_cpp.dockerfile index 310ffd5ac..4cf037dfd 100644 --- a/docker/bdk_cpp.dockerfile +++ b/docker/bdk_cpp.dockerfile @@ -8,36 +8,14 @@ FROM debian:trixie # Update the system RUN apt-get update && apt-get upgrade -y +# Install Docker-specific dependencies +RUN apt-get -y install nano vim unison curl jq unzip gcovr + +# Copy the deps script to the container +COPY scripts/deps.sh / + # Install dependencies -RUN apt-get install -y \ - build-essential \ - cmake \ - clang-tidy \ - autoconf \ - libtool \ - pkg-config \ - libabsl-dev \ - libboost-all-dev \ - libc-ares-dev \ - libcrypto++-dev \ - libgrpc-dev \ - libgrpc++-dev \ - librocksdb-dev \ - libscrypt-dev \ - libsnappy-dev \ - libssl-dev \ - zlib1g-dev \ - openssl \ - protobuf-compiler \ - protobuf-compiler-grpc \ - curl \ - unison \ - mold \ - doxygen \ - jq \ - unzip \ - gcovr \ - git +RUN bash ./deps.sh --install # Create a directory for sonarcloud RUN mkdir /root/.sonar @@ -59,7 +37,8 @@ RUN /sonarcloud.sh # Update running paths ENV PATH=/root/.sonar/build-wrapper-linux-x86:$PATH -ENV PATH=/root/.sonar/sonar-scanner-6.1.0.4477-linux-x64/bin:$PATH +ENV PATH=/root/.sonar/sonar-scanner-6.2.0.4584-linux-x64/bin:$PATH # Copy the entrypoint script COPY docker/entrypoint.sh /entrypoint.sh + diff --git a/scripts/deps.sh b/scripts/deps.sh new file mode 100755 index 000000000..5248ac8d6 --- /dev/null +++ b/scripts/deps.sh @@ -0,0 +1,201 @@ +#!/bin/bash -e + +# =========================================================================== +# PRE-SCRIPT +# =========================================================================== + +# Parse CLI args +if [ "${1:-}" == "" ]; then + echo "Usage: $0 [--check|--install]" + echo " --check: print installed dependencies and exit" + echo " --install: install missing dependencies" + exit +fi + +# Helper function to check for an executable in the system. +# ONLY CHECKS /usr/local AND /usr BY DEFAULT. If both match, gives preference to the former. +# Returns the first found match, or an empty string if there is no match. +# Usage: HAS_EXEC=$(check_exec "execname") +# $1 = exec name (e.g. "gcc") +check_exec() { + FOUND1=$(find /usr/local/bin -name "$1" 2> /dev/null | head -n 1) + FOUND2=$(find /usr/bin -name "$1" 2> /dev/null | head -n 1) + if [ -n "$FOUND1" ]; then echo "$FOUND1"; elif [ -n "$FOUND2" ]; then echo "$FOUND2"; else echo ""; fi +} + +# Helper function to check for a library in the system. +# ONLY CHECKS /usr/local AND /usr. If both match, gives preference to the former. +# Returns the first found match, or an empty string if there is no match. +# Usage: HAS_LIB=$(check_lib "libname") +# $1 = library name, including suffix (e.g. "libz.a") +check_lib() { + FOUND1=$(find /usr/local/lib -name "$1" 2> /dev/null | head -n 1) + FOUND2=$(find /usr/lib -name "$1" 2> /dev/null | head -n 1) + if [ -n "$FOUND1" ]; then echo "$FOUND1"; elif [ -n "$FOUND2" ]; then echo "$FOUND2"; else echo ""; fi +} + +# Another version of check_lib() for use with libs with multiple components (e.g. Boost). +# Returns the first found match, or an empty string if there is no match. +# Usage: HAS_LIBS=$(check_libs "libname") +# $1 = library name, including suffix (e.g. "libboost_*.a") +check_libs() { + FOUND1=$(find /usr/local/lib -name "$1" 2> /dev/null | head -n 1) + FOUND2=$(find /usr/lib -name "$1" 2> /dev/null | head -n 1) + if [ -n "$FOUND1" ]; then echo "/usr/local/lib/$1"; elif [ -n "$FOUND2" ]; then echo "/usr/lib/$1"; else echo ""; fi +} + +# Versions for external dependencies - update numbers here if required +ETHASH_VERSION="1.0.1" +EVMONE_VERSION="0.11.0" +SPEEDB_VERSION="2.8.0" + +# =========================================================================== +# SCRIPT STARTS HERE +# =========================================================================== + +echo "-- Scanning for dependencies..." + +# Check toolchain binaries +# Necessary: git, gcc/g++, ld, make, cmake, tmux, protobuf-compiler (protoc), protobuf-compiler-grpc (grpc_cpp_plugin) +# Optional: ninja, mold, doxygen, clang-tidy +HAS_GIT=$(check_exec git) +HAS_GCC=$(check_exec gcc) +HAS_GPP=$(check_exec g++) +HAS_LD=$(check_exec ld) +HAS_MAKE=$(check_exec make) +HAS_CMAKE=$(check_exec cmake) +HAS_TMUX=$(check_exec tmux) +HAS_PROTOC=$(check_exec protoc) +HAS_GRPC=$(check_exec grpc_cpp_plugin) + +HAS_NINJA=$(check_exec ninja) +HAS_MOLD=$(check_exec mold) +HAS_DOXYGEN=$(check_exec doxygen) +HAS_CLANGTIDY=$(check_exec clang-tidy) + +# Check internal libraries +# Necessary: libboost-all-dev, openssl/libssl-dev, libzstd-dev, libcrypto++-dev, +# libscrypt-dev, libgrpc-dev, libgrpc++-dev, libc-ares-dev, libsecp256k1-dev +HAS_BOOST=$(check_libs "libboost_*.a") +HAS_LIBSSL=$(check_lib "libssl.a") +HAS_ZSTD=$(check_lib "libzstd.a") +HAS_LIBCRYPTOPP=$(check_lib "libcryptopp.a") +HAS_LIBSCRYPT=$(check_lib "libscrypt.a") +HAS_LIBCARES=$(check_lib "libcares_static.a") # Debian 13 and higher +if [ -z "$HAS_LIBCARES" ]; then HAS_LIBCARES=$(check_lib "libcares.a"); fi # Debian 12 and lower +HAS_LIBGRPC=$(check_lib "libgrpc.a") +HAS_LIBGRPCPP=$(check_lib "libgrpc++.a") +HAS_SECP256K1=$(check_lib "libsecp256k1.a") + +# Check external libraries +# Necessary: ethash (+ keccak), evmone (+ evmc), speedb +HAS_ETHASH=$(check_lib "libethash.a") +HAS_KECCAK=$(check_lib "libkeccak.a") +HAS_EVMC_INSTRUCTIONS=$(check_lib "libevmc-instructions.a") +HAS_EVMC_LOADER=$(check_lib "libevmc-loader.a") +HAS_EVMONE=$(check_lib "libevmone.a") +HAS_SPEEDB=$(check_lib "libspeedb.a") + +if [ "${1:-}" == "--check" ]; then + echo "-- Required toolchain binaries:" + echo -n "git: " && [ -n "$HAS_GIT" ] && echo "$HAS_GIT" || echo "not found" + echo -n "gcc: " && [ -n "$HAS_GCC" ] && echo "$HAS_GCC" || echo "not found" + echo -n "g++: " && [ -n "$HAS_GPP" ] && echo "$HAS_GPP" || echo "not found" + echo -n "ld: " && [ -n "$HAS_LD" ] && echo "$HAS_LD" || echo "not found" + echo -n "make: " && [ -n "$HAS_MAKE" ] && echo "$HAS_MAKE" || echo "not found" + echo -n "cmake: " && [ -n "$HAS_CMAKE" ] && echo "$HAS_CMAKE" || echo "not found" + echo -n "tmux: " && [ -n "$HAS_TMUX" ] && echo "$HAS_TMUX" || echo "not found" + echo -n "protoc: " && [ -n "$HAS_PROTOC" ] && echo "$HAS_PROTOC" || echo "not found" + echo -n "grpc_cpp_plugin: " && [ -n "$HAS_GRPC" ] && echo "$HAS_GRPC" || echo "not found" + + echo "-- Optional toolchain binaries:" + echo -n "ninja: " && [ -n "$HAS_NINJA" ] && echo "$HAS_NINJA" || echo "not found" + echo -n "mold: " && [ -n "$HAS_MOLD" ] && echo "$HAS_MOLD" || echo "not found" + echo -n "doxygen: " && [ -n "$HAS_DOXYGEN" ] && echo "$HAS_DOXYGEN" || echo "not found" + echo -n "clang-tidy: " && [ -n "$HAS_CLANGTIDY" ] && echo "$HAS_CLANGTIDY" || echo "not found" + + echo "-- Internal libraries:" + echo -n "boost: " && [ -n "$HAS_BOOST" ] && echo "$HAS_BOOST" || echo "not found" + echo -n "libssl: " && [ -n "$HAS_LIBSSL" ] && echo "$HAS_LIBSSL" || echo "not found" + echo -n "libzstd: " && [ -n "$HAS_ZSTD" ] && echo "$HAS_ZSTD" || echo "not found" + echo -n "libcryptopp: " && [ -n "$HAS_LIBCRYPTOPP" ] && echo "$HAS_LIBCRYPTOPP" || echo "not found" + echo -n "libscrypt: " && [ -n "$HAS_LIBSCRYPT" ] && echo "$HAS_LIBSCRYPT" || echo "not found" + echo -n "libcares: " && [ -n "$HAS_LIBCARES" ] && echo "$HAS_LIBCARES" || echo "not found" + echo -n "libgrpc: " && [ -n "$HAS_LIBGRPC" ] && echo "$HAS_LIBGRPC" || echo "not found" + echo -n "libgrpc++: " && [ -n "$HAS_LIBGRPCPP" ] && echo "$HAS_LIBGRPCPP" || echo "not found" + echo -n "libsecp256k1: " && [ -n "$HAS_SECP256K1" ] && echo "$HAS_SECP256K1" || echo "not found" + + echo "-- External libraries:" + echo -n "libethash: " && [ -n "$HAS_ETHASH" ] && echo "$HAS_ETHASH" || echo "not found" + echo -n "libkeccak: " && [ -n "$HAS_KECCAK" ] && echo "$HAS_KECCAK" || echo "not found" + echo -n "libevmc-instructions: " && [ -n "$HAS_EVMC_INSTRUCTIONS" ] && echo "$HAS_EVMC_INSTRUCTIONS" || echo "not found" + echo -n "libevmc-loader: " && [ -n "$HAS_EVMC_LOADER" ] && echo "$HAS_EVMC_LOADER" || echo "not found" + echo -n "libevmone: " && [ -n "$HAS_EVMONE" ] && echo "$HAS_EVMONE" || echo "not found" + echo -n "libspeedb: " && [ -n "$HAS_SPEEDB" ] && echo "$HAS_SPEEDB" || echo "not found" +elif [ "${1:-}" == "--install" ]; then + # Anti-anti-sudo prevention + if [ $(id -u) -ne 0 ]; then + echo "Please run this command as root." + exit + fi + + # Install binaries and internal libs (skip if not on an APT-based distro) + HAS_APT=$(check_exec apt) + if [ -n "$HAS_APT" ]; then + echo "-- Checking internal dependencies..." + PKGS="" + if [ -z "$HAS_GIT" ]; then PKGS+="git "; fi + if [ -z "$HAS_GCC" ] || [ -z "$HAS_GPP" ] || [ -z "$HAS_MAKE" ] || [ -z "$HAS_LD" ]; then PKGS+="build-essential "; fi + if [ -z "$HAS_CMAKE" ]; then PKGS+="cmake "; fi + if [ -z "$HAS_TMUX" ]; then PKGS+="tmux "; fi + if [ -z "$HAS_PROTOC" ]; then PKGS+="protobuf-compiler "; fi + if [ -z "$HAS_GRPC" ]; then PKGS+="protobuf-compiler-grpc "; fi + if [ -z "$HAS_NINJA" ]; then PKGS+="ninja-build "; fi + if [ -z "$HAS_MOLD" ]; then PKGS+="mold "; fi + if [ -z "$HAS_DOXYGEN" ]; then PKGS+="doxygen "; fi + if [ -z "$HAS_CLANGTIDY" ]; then PKGS+="clang-tidy "; fi + if [ -z "$HAS_BOOST" ]; then PKGS+="libboost-all-dev "; fi + if [ -z "$HAS_LIBSSL" ]; then PKGS+="libssl-dev "; fi + if [ -z "$HAS_ZSTD" ]; then PKGS+="libzstd-dev "; fi + if [ -z "$HAS_LIBCRYPTOPP" ]; then PKGS+="libcrypto++-dev "; fi + if [ -z "$HAS_LIBSCRYPT" ]; then PKGS+="libscrypt-dev "; fi + if [ -z "$HAS_LIBCARES" ]; then PKGS+="libc-ares-dev "; fi + if [ -z "$HAS_LIBGRPC" ]; then PKGS+="libgrpc-dev "; fi + if [ -z "$HAS_LIBGRPCPP" ]; then PKGS+="libgrpc++-dev "; fi + if [ -z "$HAS_SECP256K1" ]; then PKGS+="libsecp256k1-dev "; fi + if [ -n "$PKGS" ]; then + echo "-- Installing internal dependencies..." + apt-get install -y $PKGS + fi + else + echo "-- Skipping internal dependencies (non-APT-based distro, please install those manually)" + fi + + # Install external libs + echo "-- Checking external dependencies..." + if [ -z "$HAS_ETHASH" ] || [ -z "$HAS_KECCAK" ]; then + echo "-- Installing ethash..." + cd /usr/local/src && git clone --depth 1 --branch "v${ETHASH_VERSION}" https://github.com/chfast/ethash + cd ethash && mkdir build && cd build + cmake -DCMAKE_INSTALL_PREFIX="/usr/local" .. + cmake --build . -- -j$(nproc) && cmake --install . + fi + if [ -z "$HAS_EVMC_INSTRUCTIONS" ] || [ -z "$HAS_EVMC_LOADER" ] || [ -z "$HAS_EVMONE" ]; then + echo "-- Installing evmone..." + cd /usr/local/src && git clone --recurse-submodules --depth 1 --branch "v${EVMONE_VERSION}" https://github.com/chfast/evmone + cd evmone && mkdir build && cd build + cmake -DCMAKE_INSTALL_PREFIX="/usr/local" -DBUILD_SHARED_LIBS=OFF -DEVMC_INSTALL=ON .. + cmake --build . -- -j$(nproc) && cmake --install . + fi + if [ -z "$HAS_SPEEDB" ]; then + echo "-- Installing speedb..." + cd /usr/local/src && git clone --depth 1 --branch "speedb/v${SPEEDB_VERSION}" https://github.com/speedb-io/speedb + cd speedb && mkdir build && cd build + cmake -DCMAKE_INSTALL_PREFIX="/usr/local" -DCMAKE_BUILD_TYPE=Release \ + -DROCKSDB_BUILD_SHARED=OFF -DFAIL_ON_WARNINGS=OFF -DWITH_GFLAGS=OFF -DWITH_RUNTIME_DEBUG=OFF \ + -DWITH_BENCHMARK_TOOLS=OFF -DWITH_CORE_TOOLS=OFF -DWITH_TOOLS=OFF -DWITH_TRACE_TOOLS=OFF .. + cmake --build . -- -j$(nproc) && cmake --install . + fi + echo "-- Dependencies installed" +fi + diff --git a/src/bins/bdkd-discovery/CMakeLists.txt b/src/bins/bdkd-discovery/CMakeLists.txt index 7d149f222..16c2fc383 100644 --- a/src/bins/bdkd-discovery/CMakeLists.txt +++ b/src/bins/bdkd-discovery/CMakeLists.txt @@ -1,9 +1,17 @@ # Compile and link the Discovery Node test executable if set to build it if (BUILD_DISCOVERY) add_executable(bdkd-discovery "main.cpp") + add_dependencies(bdkd-discovery bdk_lib) - target_include_directories(bdkd-discovery PRIVATE bdk_lib ${OPENSSL_INCLUDE_DIR}) + + target_include_directories(bdkd-discovery PRIVATE + bdk_lib ${OPENSSL_INCLUDE_DIR} ${ETHASH_INCLUDE_DIR} ${KECCAK_INCLUDE_DIR} + ${SPEEDB_INCLUDE_DIR} ${SECP256K1_INCLUDE_DIR} + ) + target_link_libraries(bdkd-discovery - bdk_lib Speedb ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} Secp256k1 Ethash ${ETHASH_BYPRODUCTS} + bdk_lib ${SPEEDB_LIBRARY} ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} + ${ZLIB_LIBRARIES} ${SECP256K1_LIBRARY} ${ETHASH_LIBRARY} ${KECCAK_LIBRARY} ) endif() + diff --git a/src/bins/bdkd-tests/CMakeLists.txt b/src/bins/bdkd-tests/CMakeLists.txt index fc845906d..2fa369d94 100644 --- a/src/bins/bdkd-tests/CMakeLists.txt +++ b/src/bins/bdkd-tests/CMakeLists.txt @@ -1,9 +1,18 @@ # Compile and link the test executable if set to build it if (BUILD_TESTS) add_executable(bdkd-tests ${TESTS_HEADERS} ${TESTS_SOURCES}) + add_dependencies(bdkd-tests bdk_lib) - target_include_directories(bdkd-tests PRIVATE bdk_lib ${OPENSSL_INCLUDE_DIR}) - target_link_libraries(bdkd-tests - bdk_lib Speedb ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} Secp256k1 catch2 Ethash ${ETHASH_BYPRODUCTS} + + target_include_directories(bdkd-tests PRIVATE + bdk_lib ${OPENSSL_INCLUDE_DIR} ${ETHASH_INCLUDE_DIR} ${KECCAK_INCLUDE_DIR} + ${SPEEDB_INCLUDE_DIR} ${SECP256K1_INCLUDE_DIR} ) -endif() \ No newline at end of file + + target_link_libraries(bdkd-tests PRIVATE + bdk_lib catch2 + ${SPEEDB_LIBRARY} ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} + ${SECP256K1_LIBRARY} ${ETHASH_LIBRARY} ${KECCAK_LIBRARY} + ) +endif() + diff --git a/src/bins/bdkd/CMakeLists.txt b/src/bins/bdkd/CMakeLists.txt index 24b077237..3766f4604 100644 --- a/src/bins/bdkd/CMakeLists.txt +++ b/src/bins/bdkd/CMakeLists.txt @@ -2,7 +2,14 @@ add_executable(bdkd "main.cpp") add_dependencies(bdkd bdk_lib) -target_include_directories(bdkd PRIVATE bdk_lib ${OPENSSL_INCLUDE_DIR}) + +target_include_directories(bdkd PRIVATE + bdk_lib ${OPENSSL_INCLUDE_DIR} ${ETHASH_INCLUDE_DIR} ${KECCAK_INCLUDE_DIR} + ${SPEEDB_INCLUDE_DIR} ${SECP256K1_INCLUDE_DIR} +) + target_link_libraries(bdkd - bdk_lib Speedb ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} Secp256k1 Ethash ${ETHASH_BYPRODUCTS} -) \ No newline at end of file + bdk_lib ${SPEEDB_LIBRARY} ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} + ${SECP256K1_LIBRARY} ${ETHASH_LIBRARY} ${KECCAK_LIBRARY} +) + diff --git a/src/bins/bdkd/main.cpp b/src/bins/bdkd/main.cpp index aa33dcec4..6b57328ef 100644 --- a/src/bins/bdkd/main.cpp +++ b/src/bins/bdkd/main.cpp @@ -14,6 +14,8 @@ See the LICENSE.txt file in the project root for more information. #include "src/core/blockchain.h" #include "src/utils/clargs.h" +#include "src/utils/logger.h" + std::unique_ptr blockchain = nullptr; std::condition_variable cv; diff --git a/src/bins/contractabigenerator/CMakeLists.txt b/src/bins/contractabigenerator/CMakeLists.txt index 67e1d3df4..542fc16a9 100644 --- a/src/bins/contractabigenerator/CMakeLists.txt +++ b/src/bins/contractabigenerator/CMakeLists.txt @@ -2,7 +2,15 @@ add_executable(contractabigenerator "main.cpp") add_dependencies(contractabigenerator bdk_lib) -target_include_directories(contractabigenerator PRIVATE bdk_lib ${OPENSSL_INCLUDE_DIR}) + +target_include_directories(contractabigenerator PRIVATE + bdk_lib ${OPENSSL_INCLUDE_DIR} ${ETHASH_INCLUDE_DIR} ${KECCAK_INCLUDE_DIR} + ${SPEEDB_INCLUDE_DIR} ${SECP256K1_INCLUDE_DIR} +) + target_link_libraries(contractabigenerator - bdk_lib Speedb ${SNAPPY_LIBRARY} ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} Secp256k1 Ethash ${ETHASH_BYPRODUCTS} -) \ No newline at end of file + bdk_lib ${SPEEDB_LIBRARY} ${SNAPPY_LIBRARY} ${Boost_LIBRARIES} + ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} ${SECP256K1_LIBRARY} + ${ETHASH_LIBRARY} ${KECCAK_LIBRARY} +) + diff --git a/src/bins/faucet-api/CMakeLists.txt b/src/bins/faucet-api/CMakeLists.txt index 5d1001a90..2fa88de31 100644 --- a/src/bins/faucet-api/CMakeLists.txt +++ b/src/bins/faucet-api/CMakeLists.txt @@ -1,45 +1,67 @@ if (BUILD_FAUCET) add_library(rollup_faucet_lib STATIC - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/jsonrpc/encoding.h - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/jsonrpc/decoding.h - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/jsonrpc/encoding.cpp - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/jsonrpc/decoding.cpp - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httplistener.h - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httpparser.h - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httpserver.h - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httpsession.h - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/faucetmanager.h - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httplistener.cpp - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httpparser.cpp - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httpserver.cpp - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httpsession.cpp - ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/faucetmanager.cpp - + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/jsonrpc/encoding.h + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/jsonrpc/decoding.h + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/jsonrpc/encoding.cpp + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/jsonrpc/decoding.cpp + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httplistener.h + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httpparser.h + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httpserver.h + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httpsession.h + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/faucetmanager.h + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httplistener.cpp + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httpparser.cpp + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httpserver.cpp + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/httpsession.cpp + ${CMAKE_SOURCE_DIR}/src/bins/faucet-api/src/faucetmanager.cpp ) - target_include_directories(rollup_faucet_lib PRIVATE ${CMAKE_SOURCE_DIR}/include ${OPENSSL_INCLUDE_DIR} bdk_lib) + target_include_directories(rollup_faucet_lib PRIVATE + ${CMAKE_SOURCE_DIR}/include ${OPENSSL_INCLUDE_DIR} bdk_lib + ${ETHASH_INCLUDE_DIR} ${KECCAK_INCLUDE_DIR} + ${SPEEDB_INCLUDE_DIR} ${SECP256K1_INCLUDE_DIR} + ) target_link_libraries(rollup_faucet_lib PRIVATE bdk_lib - ${CRYPTOPP_LIBRARIES} ${SCRYPT_LIBRARY} Secp256k1 Ethash ${ETHASH_BYPRODUCTS} - Speedb ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} bdk_lib + ${CRYPTOPP_LIBRARIES} ${SCRYPT_LIBRARY} ${SECP256K1_LIBRARY} + ${ETHASH_LIBRARY} ${KECCAK_LIBRARY} ${SPEEDB_LIBRARY} + ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} bdk_lib ) # Compile and link the faucet-api executable add_executable(faucet-api "main.cpp") add_dependencies(faucet-api bdk_lib rollup_faucet_lib) - target_include_directories(faucet-api PRIVATE bdk_lib rollup_faucet_lib ${OPENSSL_INCLUDE_DIR}) + + target_include_directories(faucet-api PRIVATE + bdk_lib rollup_faucet_lib ${OPENSSL_INCLUDE_DIR} + ${ETHASH_INCLUDE_DIR} ${KECCAK_INCLUDE_DIR} + ${SPEEDB_INCLUDE_DIR} ${SECP256K1_INCLUDE_DIR} + ) + target_link_libraries(faucet-api - bdk_lib rollup_faucet_lib Speedb ${SNAPPY_LIBRARY} ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} Secp256k1 Ethash ${ETHASH_BYPRODUCTS} + bdk_lib rollup_faucet_lib + ${SPEEDB_LIBRARY} ${SNAPPY_LIBRARY} ${Boost_LIBRARIES} + ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} ${SECP256K1_LIBRARY} + ${ETHASH_LIBRARY} ${KECCAK_LIBRARY} ) # Compile and link the faucet-api executable add_executable(faucet-tester "main-tester.cpp") add_dependencies(faucet-tester bdk_lib rollup_faucet_lib) - target_include_directories(faucet-tester PRIVATE bdk_lib rollup_faucet_lib ${OPENSSL_INCLUDE_DIR}) + + target_include_directories(faucet-tester PRIVATE + bdk_lib rollup_faucet_lib ${OPENSSL_INCLUDE_DIR} + ${ETHASH_INCLUDE_DIR} ${KECCAK_INCLUDE_DIR} + ${SPEEDB_INCLUDE_DIR} ${SECP256K1_INCLUDE_DIR} + ) + target_link_libraries(faucet-tester - bdk_lib rollup_faucet_lib Speedb ${SNAPPY_LIBRARY} ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} Secp256k1 Ethash ${ETHASH_BYPRODUCTS} + bdk_lib rollup_faucet_lib + ${SPEEDB_LIBRARY} ${SNAPPY_LIBRARY} ${Boost_LIBRARIES} + ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} ${SECP256K1_LIBRARY} + ${ETHASH_LIBRARY} ${KECCAK_LIBRARY} ) endif() diff --git a/src/bins/network-sim/CMakeLists.txt b/src/bins/network-sim/CMakeLists.txt index 978a54e3b..488f4bda9 100644 --- a/src/bins/network-sim/CMakeLists.txt +++ b/src/bins/network-sim/CMakeLists.txt @@ -1,28 +1,43 @@ if (BUILD_NETWORK_SIM) add_library(network_sim_lib STATIC - ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/common.h - ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/httpclient.h - ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/networksimulator.h - ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/simulatorworker.h - ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/common.cpp - ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/httpclient.cpp - ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/networksimulator.cpp - ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/simulatorworker.cpp + ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/common.h + ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/httpclient.h + ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/networksimulator.h + ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/simulatorworker.h + ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/common.cpp + ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/httpclient.cpp + ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/networksimulator.cpp + ${CMAKE_SOURCE_DIR}/src/bins/network-sim/src/simulatorworker.cpp ) - target_include_directories(network_sim_lib PRIVATE ${CMAKE_SOURCE_DIR}/include ${OPENSSL_INCLUDE_DIR}) + target_include_directories(network_sim_lib PRIVATE + ${CMAKE_SOURCE_DIR}/include ${OPENSSL_INCLUDE_DIR} + ${ETHASH_INCLUDE_DIR} ${KECCAK_INCLUDE_DIR} + ${SPEEDB_INCLUDE_DIR} ${SECP256K1_INCLUDE_DIR} + ) target_link_libraries(network_sim_lib PRIVATE bdk_lib - ${CRYPTOPP_LIBRARIES} ${SCRYPT_LIBRARY} Secp256k1 Ethash ${ETHASH_BYPRODUCTS} - Speedb ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} - ) + ${CRYPTOPP_LIBRARIES} ${SCRYPT_LIBRARY} ${SECP256K1_LIBRARY} + ${ETHASH_LIBRARY} ${KECCAK_LIBRARY} ${SPEEDB_LIBRARY} + ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} + ) # Compile and link the ABI generator executable add_executable(network-sim "main.cpp") add_dependencies(network-sim bdk_lib network_sim_lib) - target_include_directories(network-sim PRIVATE bdk_lib network_sim_lib ${OPENSSL_INCLUDE_DIR}) + + target_include_directories(network-sim PRIVATE + bdk_lib network_sim_lib ${OPENSSL_INCLUDE_DIR} + ${ETHASH_INCLUDE_DIR} ${KECCAK_INCLUDE_DIR} + ${SPEEDB_INCLUDE_DIR} ${SECP256K1_INCLUDE_DIR} + ) + target_link_libraries(network-sim - bdk_lib network_sim_lib Speedb ${SNAPPY_LIBRARY} ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} Secp256k1 Ethash ${ETHASH_BYPRODUCTS} + bdk_lib network_sim_lib + ${SPEEDB_LIBRARY} ${SNAPPY_LIBRARY} ${Boost_LIBRARIES} + ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} ${SECP256K1_LIBRARY} + ${ETHASH_LIBRARY} ${KECCAK_LIBRARY} ) -endif() \ No newline at end of file +endif() + diff --git a/src/bins/networkdeployer/CMakeLists.txt b/src/bins/networkdeployer/CMakeLists.txt index 9eefe9ede..73564631a 100644 --- a/src/bins/networkdeployer/CMakeLists.txt +++ b/src/bins/networkdeployer/CMakeLists.txt @@ -2,7 +2,15 @@ add_executable(networkdeployer "main.cpp") add_dependencies(networkdeployer bdk_lib) -target_include_directories(networkdeployer PRIVATE bdk_lib ${OPENSSL_INCLUDE_DIR}) + +target_include_directories(networkdeployer PRIVATE + bdk_lib ${OPENSSL_INCLUDE_DIR} ${ETHASH_INCLUDE_DIR} ${KECCAK_INCLUDE_DIR} + ${SPEEDB_INCLUDE_DIR} ${SECP256K1_INCLUDE_DIR} +) + target_link_libraries(networkdeployer - bdk_lib Speedb ${SNAPPY_LIBRARY} ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} Secp256k1 Ethash ${ETHASH_BYPRODUCTS} -) \ No newline at end of file + bdk_lib ${SPEEDB_LIBRARY} ${SNAPPY_LIBRARY} ${Boost_LIBRARIES} + ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} ${SECP256K1_LIBRARY} + ${ETHASH_LIBRARY} ${KECCAK_LIBRARY} +) + diff --git a/src/bytes/initializer.h b/src/bytes/initializer.h index 478abc5a8..4f25d44c5 100644 --- a/src/bytes/initializer.h +++ b/src/bytes/initializer.h @@ -1,9 +1,9 @@ #ifndef BYTES_INITIALIZER_H #define BYTES_INITIALIZER_H -#include -#include -#include "view.h" +//#include // TODO: probably not used + +#include "view.h" // range.h -> ranges -> concepts namespace bytes { diff --git a/src/bytes/join.h b/src/bytes/join.h index cd5ed6acb..e77923e9d 100644 --- a/src/bytes/join.h +++ b/src/bytes/join.h @@ -1,11 +1,9 @@ #ifndef BYTES_JOIN_H #define BYTES_JOIN_H -#include "view.h" -#include "range.h" -#include "initializer.h" +//#include "utils/dynamicexception.h" // TODO: probably not used -#include "utils/dynamicexception.h" +#include "initializer.h" // view.h -> range.h namespace bytes { namespace detail { diff --git a/src/bytes/range.h b/src/bytes/range.h index 6ca2b7fb0..ab7c3908c 100644 --- a/src/bytes/range.h +++ b/src/bytes/range.h @@ -1,7 +1,7 @@ #ifndef BYTES_RANGE_H #define BYTES_RANGE_H -#include +//#include // TODO: probably not used #include using Byte = std::uint8_t; diff --git a/src/bytes/view.h b/src/bytes/view.h index a3bfacea1..b2fa20859 100644 --- a/src/bytes/view.h +++ b/src/bytes/view.h @@ -1,9 +1,7 @@ - #ifndef BYTES_VIEW_H #define BYTES_VIEW_H -#include -#include "range.h" +#include "range.h" // ranges -> span namespace bytes { diff --git a/src/contract/abi.cpp b/src/contract/abi.cpp index e5a0f0afb..757b038ed 100644 --- a/src/contract/abi.cpp +++ b/src/contract/abi.cpp @@ -33,14 +33,14 @@ Bytes ABI::Encoder::encodeInt(const int256_t& num) { uint256_t ABI::Decoder::decodeUint(const bytes::View &bytes, uint64_t &index) { if (index + 32 > bytes.size()) throw std::length_error("Data too short for uint256"); - uint256_t result = Utils::bytesToUint256(bytes.subspan(index, 32)); + uint256_t result = UintConv::bytesToUint256(bytes.subspan(index, 32)); index += 32; return result; } int256_t ABI::Decoder::decodeInt(const bytes::View& bytes, uint64_t& index) { if (index + 32 > bytes.size()) throw std::length_error("Data too short for int256"); - int256_t result = Utils::bytesToInt256(bytes.subspan(index, 32)); + int256_t result = IntConv::bytesToInt256(bytes.subspan(index, 32)); index += 32; return result; } diff --git a/src/contract/abi.h b/src/contract/abi.h index 06b7edbc5..245fd5099 100644 --- a/src/contract/abi.h +++ b/src/contract/abi.h @@ -8,12 +8,10 @@ See the LICENSE.txt file in the project root for more information. #ifndef ABI_H #define ABI_H -#include -#include - -#include "../utils/hex.h" -#include "../libs/json.hpp" -#include "../utils/utils.h" +#include "../utils/intconv.h" +#include "../utils/uintconv.h" +#include "../utils/strconv.h" +#include "../utils/utils.h" // libs/json.hpp -> string /// Namespace for Solidity ABI-related operations. namespace ABI { @@ -370,7 +368,7 @@ namespace ABI { Functor ret; std::string fullSig = funcSig + "(" + listArgumentTypes() + ")"; auto hash = Utils::sha3(Utils::create_view_span(fullSig)); - ret.value = Utils::bytesToUint32(hash.view(0,4)); + ret.value = UintConv::bytesToUint32(hash.view(0,4)); return ret; } }; // namespace FunctorEncoder @@ -402,15 +400,15 @@ namespace ABI { }; // Specialization for default solidity types - template <> struct TypeEncoder
{ static Bytes encode(const Address& add) { return Utils::padLeftBytes(add, 32); }}; - template <> struct TypeEncoder { static Bytes encode(const bool& b) { return Utils::padLeftBytes((b ? Bytes{0x01} : Bytes{0x00}), 32); }}; + template <> struct TypeEncoder
{ static Bytes encode(const Address& add) { return StrConv::padLeftBytes(add, 32); }}; + template <> struct TypeEncoder { static Bytes encode(const bool& b) { return StrConv::padLeftBytes((b ? Bytes{0x01} : Bytes{0x00}), 32); }}; template <> struct TypeEncoder { static Bytes encode(const Hash& hash) { return hash.asBytes(); }; }; template <> struct TypeEncoder { static Bytes encode(const Bytes& bytes) { int pad = 0; do { pad += 32; } while (pad < bytes.size()); - Bytes len = Utils::padLeftBytes(Utils::uintToBytes(bytes.size()), 32); - Bytes data = Utils::padRightBytes(bytes, pad); + Bytes len = StrConv::padLeftBytes(Utils::uintToBytes(bytes.size()), 32); + Bytes data = StrConv::padRightBytes(bytes, pad); len.reserve(len.size() + data.size()); len.insert(len.end(), std::make_move_iterator(data.begin()), std::make_move_iterator(data.end())); return len; @@ -421,8 +419,8 @@ namespace ABI { bytes::View bytes = Utils::create_view_span(str); int pad = 0; do { pad += 32; } while (pad < bytes.size()); - Bytes len = Utils::padLeftBytes(Utils::uintToBytes(bytes.size()), 32); - Bytes data = Utils::padRightBytes(bytes, pad); + Bytes len = StrConv::padLeftBytes(Utils::uintToBytes(bytes.size()), 32); + Bytes data = StrConv::padRightBytes(bytes, pad); len.reserve(len.size() + data.size()); len.insert(len.end(), std::make_move_iterator(data.begin()), std::make_move_iterator(data.end())); return len; @@ -493,7 +491,7 @@ namespace ABI { auto encodeItem = [&](const ItemType& item) { if (isDynamic()) { Bytes packed = TypeEncoder::encode(item); - append(result, Utils::padLeftBytes(Utils::uintToBytes(nextOffset), 32)); + append(result, StrConv::padLeftBytes(Utils::uintToBytes(nextOffset), 32)); nextOffset += packed.size(); dynamicBytes.insert(dynamicBytes.end(), packed.begin(), packed.end()); } else { @@ -519,20 +517,20 @@ namespace ABI { // Encode each item within the vector for (const auto& t : v) { - append(dynamicOffSets, Utils::uint256ToBytes(nextOffset)); + append(dynamicOffSets, UintConv::uint256ToBytes(nextOffset)); Bytes dynamicBytes = TypeEncoder::encode(t); // We're calling the encode function specialized for the T type. nextOffset += dynamicBytes.size(); dynamicData.insert(dynamicData.end(), dynamicBytes.begin(), dynamicBytes.end()); } // Add the array length, dynamic offsets and dynamic data - append(result, Utils::padLeftBytes(Utils::uintToBytes(v.size()), 32)); + append(result, StrConv::padLeftBytes(Utils::uintToBytes(v.size()), 32)); append(result, dynamicOffSets); result.insert(result.end(), dynamicData.begin(), dynamicData.end()); return result; } else { // Add array length and append - append(result, Utils::padLeftBytes(Utils::uintToBytes(v.size()), 32)); + append(result, StrConv::padLeftBytes(Utils::uintToBytes(v.size()), 32)); for (const auto& t : v) append(result, TypeEncoder::encode(t)); return result; } @@ -554,7 +552,7 @@ namespace ABI { auto encodeItem = [&](const ItemType& item) { if constexpr (isDynamic()) { Bytes packed = TypeEncoder::encode(item); - append(result, Utils::padLeftBytes(Utils::uintToBytes(nextOffset), 32)); + append(result, StrConv::padLeftBytes(Utils::uintToBytes(nextOffset), 32)); nextOffset += packed.size(); dynamicBytes.insert(dynamicBytes.end(), packed.begin(), packed.end()); } else append(result, TypeEncoder::encode(item)); @@ -598,7 +596,7 @@ namespace ABI { // Almost the same as ABI::Encoder::encode, but without the padding. int pad = 0; do { pad += 32; } while (pad < bytes.size()); - return Utils::padRightBytes(bytes, pad); + return StrConv::padRightBytes(bytes, pad); } }; @@ -607,7 +605,7 @@ namespace ABI { bytes::View bytes = Utils::create_view_span(str); int pad = 0; do { pad += 32; } while (pad < bytes.size()); - return Utils::padRightBytes(bytes, pad); + return StrConv::padRightBytes(bytes, pad); } }; @@ -714,7 +712,7 @@ namespace ABI { using ItemType = std::decay_t; if constexpr (isDynamic()) { Bytes packed = ABI::Encoder::TypeEncoder::encode(item.value); - append(result, Utils::padLeftBytes(Utils::uintToBytes(nextOffset), 32)); + append(result, StrConv::padLeftBytes(Utils::uintToBytes(nextOffset), 32)); nextOffset += packed.size(); dynamicBytes.insert(dynamicBytes.end(), packed.begin(), packed.end()); } else append(result, ABI::Encoder::TypeEncoder::encode(item.value)); diff --git a/src/contract/calltracer.cpp b/src/contract/calltracer.cpp index 59c593e44..4385f1b26 100644 --- a/src/contract/calltracer.cpp +++ b/src/contract/calltracer.cpp @@ -1,17 +1,20 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #include "calltracer.h" -#include "bytes/join.h" + +#include "../utils/uintconv.h" namespace trace { static Call::Type getCallType(const evmc_message& msg) { using enum Call::Type; - - if (msg.kind == EVMC_CALL) - return (msg.flags == EVMC_STATIC) ? STATICCALL : CALL; - - if (msg.kind == EVMC_DELEGATECALL) - return DELEGATECALL; - + if (msg.kind == EVMC_CALL) return (msg.flags == EVMC_STATIC) ? STATICCALL : CALL; + if (msg.kind == EVMC_DELEGATECALL) return DELEGATECALL; throw DynamicException("evmc_message is not from a function call"); } @@ -22,7 +25,7 @@ Bytes encodeRevertReason(std::string_view reason) { std::copy_n(reason.begin(), count, reasonEncoded.begin()); const uint256_t size(reason.size()); - const FixedBytes<32> sizeEncoded(Utils::uint256ToBytes(size)); + const FixedBytes<32> sizeEncoded(UintConv::uint256ToBytes(size)); return Utils::makeBytes(bytes::join( Hex::toBytes("0x08c379a0"), @@ -37,7 +40,7 @@ std::string decodeRevertReason(bytes::View data) { throw DynamicException("Encoded revert reason is expected to have exactly 100 bytes"); } - const size_t size = Utils::bytesToUint256(data.subspan(36, 32)).convert_to(); + const size_t size = UintConv::bytesToUint256(data.subspan(36, 32)).convert_to(); std::string res; res.reserve(size); @@ -56,7 +59,7 @@ Call::Call(const evmc_message& msg) json Call::toJson() const { using enum Call::Type; - + json res; switch (this->type) { @@ -76,7 +79,7 @@ json Call::toJson() const { res["from"] = this->from.hex(true); res["to"] = this->to.hex(true); - const uint256_t value = Utils::bytesToUint256(this->value); + const uint256_t value = UintConv::bytesToUint256(this->value); res["value"] = Hex::fromBytes(Utils::uintToBytes(value), true).forRPC(); res["gas"] = Hex::fromBytes(Utils::uintToBytes(this->gas), true).forRPC(); @@ -117,19 +120,13 @@ CallTracer::CallTracer(Call rootCall) : root_(std::make_unique(std::move(r } const Call& CallTracer::root() const { - if (!hasCalls()) - throw DynamicException("root call does not exists since no call was traced"); - + if (!hasCalls()) throw DynamicException("root call does not exists since no call was traced"); return *root_; } const Call& CallTracer::current() const { - if (!hasCalls()) - throw DynamicException("current call does not exists since no call was traced"); - - if (isFinished()) - throw DynamicException("call tracer is already finished, no call currently opened"); - + if (!hasCalls()) throw DynamicException("current call does not exists since no call was traced"); + if (isFinished()) throw DynamicException("call tracer is already finished, no call currently opened"); return *stack_.back(); } diff --git a/src/contract/calltracer.h b/src/contract/calltracer.h index d55c8a8d7..9e18cae7e 100644 --- a/src/contract/calltracer.h +++ b/src/contract/calltracer.h @@ -1,12 +1,16 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #ifndef CONTRACT_CALLTRACER_H #define CONTRACT_CALLTRACER_H -#include -#include #include -#include "../utils/utils.h" -#include "../utils/strings.h" -#include "../libs/zpp_bits.h" + +#include "../utils/utils.h" // strings.h, bytes/join.h (used in .cpp) libs/zpp_bits.h -> memory namespace trace { diff --git a/src/contract/contract.cpp b/src/contract/contract.cpp index cf44b8e60..6062cd24a 100644 --- a/src/contract/contract.cpp +++ b/src/contract/contract.cpp @@ -6,7 +6,9 @@ See the LICENSE.txt file in the project root for more information. */ #include "contract.h" -#include "contracthost.h" +#include "contracthost.h" // leave it in to avoid "invalid use of incomplete type" errors + +#include "../utils/dynamicexception.h" Address ContractGlobals::coinbase_ = Address(Hex::toBytes("0x0000000000000000000000000000000000000000")); Hash ContractGlobals::blockHash_ = Hash(); @@ -14,15 +16,28 @@ uint64_t ContractGlobals::blockHeight_ = 0; uint64_t ContractGlobals::blockTimestamp_ = 0; Address BaseContract::getOrigin() const { - if (this->host_ == nullptr) { - throw DynamicException("Contracts going haywire! trying to get origin without a host!"); - } + if (this->host_ == nullptr) throw DynamicException( + "Contracts going haywire! Trying to get origin without a host!" + ); return this->host_->get_tx_context().tx_origin; } uint64_t BaseContract::getNonce(const Address& address) const { - if (this->host_ == nullptr) { - throw DynamicException("Contracts going haywire! trying to get nonce without a host!"); - } + if (this->host_ == nullptr) throw DynamicException( + "Contracts going haywire! Trying to get nonce without a host!" + ); return this->host_->getNonce(address); -} \ No newline at end of file +} + +void BaseContract::ethCall(const evmc_message& data, ContractHost* host) { + throw DynamicException("Derived Class from Contract does not override ethCall()"); +} + +Bytes BaseContract::evmEthCall(const evmc_message& data, ContractHost* host) { + throw DynamicException("Derived Class from Contract does not override ethCall()"); +} + +Bytes BaseContract::ethCallView(const evmc_message &data, ContractHost* host) const { + throw DynamicException("Derived Class from Contract does not override ethCallView()"); +} + diff --git a/src/contract/contract.h b/src/contract/contract.h index c9ae010c4..34fc039ac 100644 --- a/src/contract/contract.h +++ b/src/contract/contract.h @@ -8,18 +8,7 @@ See the LICENSE.txt file in the project root for more information. #ifndef CONTRACT_H #define CONTRACT_H -#include -#include -#include -#include - -#include "../utils/db.h" -#include "../utils/strings.h" -#include "../utils/tx.h" -#include "../utils/utils.h" -#include "../utils/dynamicexception.h" -#include "variables/safebase.h" -#include "../core/dump.h" +#include "../core/dump.h" // core/storage.h, utils/db.h -> utils.h -> strings.h, libs/json.hpp -> cstdint, memory, string, tuple // Forward declarations. class ContractHost; @@ -102,7 +91,7 @@ class BaseContract : public ContractLocals, public Dumpable { batch.push_back(Utils::stringToBytes("contractName_"), Utils::stringToBytes(contractName_), this->getDBPrefix()); batch.push_back(Utils::stringToBytes("contractAddress_"), contractAddress_, this->getDBPrefix()); batch.push_back(Utils::stringToBytes("contractCreator_"), contractCreator_, this->getDBPrefix()); - batch.push_back(Utils::stringToBytes("contractChainId_"), Utils::uint64ToBytes(contractChainId_), this->getDBPrefix()); + batch.push_back(Utils::stringToBytes("contractChainId_"), UintConv::uint64ToBytes(contractChainId_), this->getDBPrefix()); return batch; } @@ -126,7 +115,7 @@ class BaseContract : public ContractLocals, public Dumpable { return Address(db.get(std::string("contractCreator_"), dbPrefix_)); }()), contractChainId_([&]() { - return Utils::bytesToUint64(db.get(std::string("contractChainId_"), dbPrefix_)); + return UintConv::bytesToUint64(db.get(std::string("contractChainId_"), dbPrefix_)); }()) {} @@ -138,9 +127,7 @@ class BaseContract : public ContractLocals, public Dumpable { * @param data The tuple of (from, to, gasLimit, gasPrice, value, data). * @throw DynamicException if the derived class does not override this. */ - virtual void ethCall(const evmc_message& data, ContractHost* host) { - throw DynamicException("Derived Class from Contract does not override ethCall()"); - } + virtual void ethCall(const evmc_message& data, ContractHost* host); /** * Invoke a contract function and returns the ABI serialized output. @@ -149,9 +136,7 @@ class BaseContract : public ContractLocals, public Dumpable { * @throw DynamicException if the derived class does not override this. * @returns The ABI serialized output. */ - virtual Bytes evmEthCall(const evmc_message& data, ContractHost* host) { - throw DynamicException("Derived Class from Contract does not override ethCall()"); - } + virtual Bytes evmEthCall(const evmc_message& data, ContractHost* host); /** * Do a contract call to a view function. @@ -160,9 +145,7 @@ class BaseContract : public ContractLocals, public Dumpable { * @return A string with the answer to the call. * @throw DynamicException if the derived class does not override this. */ - virtual Bytes ethCallView(const evmc_message &data, ContractHost* host) const { - throw DynamicException("Derived Class from Contract does not override ethCallView()"); - } + virtual Bytes ethCallView(const evmc_message &data, ContractHost* host) const; ///@{ /** Getter. */ diff --git a/src/contract/contractfactory.h b/src/contract/contractfactory.h index 6416bb14e..627309f1f 100644 --- a/src/contract/contractfactory.h +++ b/src/contract/contractfactory.h @@ -8,15 +8,11 @@ See the LICENSE.txt file in the project root for more information. #ifndef CONTRACTFACTORY_H #define CONTRACTFACTORY_H -#include "../utils/safehash.h" -#include "../utils/strings.h" -#include "../utils/utils.h" -#include "../utils/contractreflectioninterface.h" +// Leave it in to avoid "invalid use of incomplete type" warnings +#include "contracthost.h" // utils/{contractreflectioninterface.h,safehash.h,string.h,utils.h}, contractmanager.h -> abi.h, contract.h -#include "abi.h" -#include "contract.h" -#include "contracthost.h" -#include "contractmanager.h" +#include "../utils/evmcconv.h" +#include "../utils/uintconv.h" /// Factory **namespace** that does the setup, creation and registration of contracts to the blockchain. /// As it is a namespace, it must take the required arguments (such as current contract list, etc.) as parameters. @@ -36,7 +32,6 @@ See the LICENSE.txt file in the project root for more information. * > createContractFuncs_; */ namespace ContractFactory { - /** * Helper function to create a new contract from a given call info. * @tparam TContract The contract type to create. @@ -104,7 +99,7 @@ namespace ContractFactory { using ConstructorArguments = typename TContract::ConstructorArguments; using DecayedArguments = decltype(Utils::removeQualifiers()); DecayedArguments arguments = std::apply([&callInfo](auto&&... args) { - return ABI::Decoder::decodeData...>(Utils::getFunctionArgs(callInfo)); + return ABI::Decoder::decodeData...>(EVMCConv::getFunctionArgs(callInfo)); }, DecayedArguments{}); return arguments; } @@ -158,7 +153,7 @@ namespace ContractFactory { createSignature += ")"; auto hash = Utils::sha3(Utils::create_view_span(createSignature)); Functor functor; - functor.value = Utils::bytesToUint32(hash.view(0,4)); + functor.value = UintConv::bytesToUint32(hash.view(0,4)); createContractFuncs[functor] = createFunc; } diff --git a/src/contract/contracthost.cpp b/src/contract/contracthost.cpp index c5f69a17a..10b55a41d 100644 --- a/src/contract/contracthost.cpp +++ b/src/contract/contracthost.cpp @@ -1,3 +1,12 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#include "../utils/strconv.h" //cArrayToBytes + #include "contracthost.h" #include "dynamiccontract.h" @@ -150,7 +159,7 @@ evmc::Result ContractHost::createEVMContract(const evmc_message& msg, // Set the leftOverGas_ to the gas left after the execution throw DynamicException("Error when creating EVM contract, EVM status code: " + std::string(evmc_status_code_to_string(result.status_code)) + " bytes: " + - Hex::fromBytes(Utils::cArrayToBytes(result.output_data, result.output_size)).get()); + Hex::fromBytes(StrConv::cArrayToBytes(result.output_data, result.output_size)).get()); } if (result.output_size > 50000) { throw DynamicException("ContractHost createEVMContract: contract code too large"); @@ -246,15 +255,13 @@ evmc::Result ContractHost::processBDKPrecompile(const evmc_message& msg) { try { this->leftoverGas_ = msg.gas; this->deduceGas(1000); // CPP contract call is 1000 gas - if (msg.input_size < 4) { - throw DynamicException("ContractHost processBDKPrecompile: invalid input size"); - } - if (Utils::getFunctor(msg).value != 2865519127) { + if (msg.input_size < 4) throw DynamicException("ContractHost processBDKPrecompile: invalid input size"); + if (EVMCConv::getFunctor(msg).value != 2865519127) { // we only have one function on the BDKD precompile // getRandom() == 0xaacc5a17 == 2865519127 throw DynamicException("ContractHost processBDKPrecompile: invalid function selector"); } - auto ret = Utils::uint256ToBytes(this->randomGen_.operator()()); + auto ret = UintConv::uint256ToBytes(this->randomGen_.operator()()); return evmc::Result(EVMC_SUCCESS, this->leftoverGas_, 0, ret.data(), ret.size()); } catch (std::exception &e) { this->evmcThrows_.emplace_back(e.what()); @@ -266,7 +273,7 @@ evmc::Result ContractHost::processBDKPrecompile(const evmc_message& msg) { void ContractHost::execute(const evmc_message& msg, const ContractType& type) { const Address from(msg.sender); const Address to(msg.recipient); - const uint256_t value(Utils::evmcUint256ToUint256(msg.value)); + const uint256_t value(EVMCConv::evmcUint256ToUint256(msg.value)); const bool isContractCall = isCall(msg); if (isContractCall) { @@ -321,7 +328,7 @@ void ContractHost::execute(const evmc_message& msg, const ContractType& type) { // Set the leftOverGas_ to the gas left after the execution throw DynamicException("Error when executing EVM contract, EVM status code: " + std::string(evmc_status_code_to_string(result.status_code)) + " bytes: " + - Hex::fromBytes(Utils::cArrayToBytes(result.output_data, result.output_size)).get()); + Hex::fromBytes(StrConv::cArrayToBytes(result.output_data, result.output_size)).get()); } break; } @@ -336,7 +343,7 @@ void ContractHost::execute(const evmc_message& msg, const ContractType& type) { what += evmcError; what += " --- OTHER INFO: --- "; } - + this->addTxData_.gasUsed = msg.gas - this->leftoverGas_; this->addTxData_.succeeded = false; @@ -360,7 +367,7 @@ void ContractHost::execute(const evmc_message& msg, const ContractType& type) { this->addTxData_.gasUsed = msg.gas - this->leftoverGas_; this->addTxData_.succeeded = false; - + if (isContractCall) { this->traceCallReverted(std::move(output), this->addTxData_.gasUsed); } @@ -379,7 +386,7 @@ Bytes ContractHost::ethCallView(const evmc_message& msg, const ContractType& typ Bytes ret; //const Address from(tx.sender); const Address to(msg.recipient); - //const uint256_t value(Utils::evmcUint256ToUint256(tx.value)); + //const uint256_t value(EVMCConv::evmcUint256ToUint256(tx.value)); try { switch (type) { case ContractType::CPP: { @@ -400,7 +407,7 @@ Bytes ContractHost::ethCallView(const evmc_message& msg, const ContractType& typ // Set the leftOverGas_ to the gas left after the execution throw DynamicException("Error when executing (view) EVM contract, EVM status code: " + std::string(evmc_status_code_to_string(result.status_code)) + " bytes: " + - Hex::fromBytes(Utils::cArrayToBytes(result.output_data, result.output_size)).get()); + Hex::fromBytes(StrConv::cArrayToBytes(result.output_data, result.output_size)).get()); } ret = Bytes(result.output_data, result.output_data + result.output_size); break; @@ -454,9 +461,9 @@ evmc::bytes32 ContractHost::get_storage(const evmc::address& addr, // on SET_STORAGE, we can return multiple types of evmc_storage_status // But we simply say that the storage was modified ;) // TODO: Make it EIP-2200 compliant -evmc_storage_status ContractHost::set_storage(const evmc::address& addr, - const evmc::bytes32& key, - const evmc::bytes32& value) noexcept { +evmc_storage_status ContractHost::set_storage( + const evmc::address& addr, const evmc::bytes32& key, const evmc::bytes32& value +) noexcept { StorageKey storageKey(addr, key); try { Hash hashValue(value); @@ -474,9 +481,7 @@ evmc_storage_status ContractHost::set_storage(const evmc::address& addr, evmc::uint256be ContractHost::get_balance(const evmc::address& addr) const noexcept { try { auto it = accounts_.find(addr); - if (it != accounts_.end()) { - return Utils::uint256ToEvmcUint256(it->second->balance); - } + if (it != accounts_.end()) return EVMCConv::uint256ToEvmcUint256(it->second->balance); } catch (const std::exception& e) { this->evmcThrows_.emplace_back(e.what()); this->evmcThrow_ = true; @@ -487,9 +492,7 @@ evmc::uint256be ContractHost::get_balance(const evmc::address& addr) const noexc size_t ContractHost::get_code_size(const evmc::address& addr) const noexcept { try { auto it = accounts_.find(addr); - if (it != accounts_.end()) { - return it->second->code.size(); - } + if (it != accounts_.end()) return it->second->code.size(); } catch (const std::exception& e) { this->evmcThrows_.emplace_back(e.what()); this->evmcThrow_ = true; @@ -545,7 +548,7 @@ evmc::Result ContractHost::callEVMCreate(const evmc_message& msg) { auto sender = Address(msg.sender); auto& nonce = this->getNonce(sender); auto contractAddress = this->deriveContractAddress(nonce, sender); - uint256_t value = Utils::evmcUint256ToUint256(msg.value); + uint256_t value = EVMCConv::evmcUint256ToUint256(msg.value); this->stack_.registerNonce(sender, nonce); ++nonce; @@ -563,7 +566,7 @@ evmc::Result ContractHost::callEVMCreate(const evmc_message& msg) { evmc::Result ContractHost::callEVMCreate2(const evmc_message& msg) { try { Bytes code(msg.input_data, msg.input_data + msg.input_size); - uint256_t value = Utils::evmcUint256ToUint256(msg.value); + uint256_t value = EVMCConv::evmcUint256ToUint256(msg.value); auto salt = Hash(msg.create2_salt); auto sender = Address(msg.sender); auto contractAddress = this->deriveContractAddress(sender, salt, code); @@ -585,18 +588,12 @@ evmc::Result ContractHost::callCPPContract(const evmc_message& msg) { this->leftoverGas_ = msg.gas; this->deduceGas(1000); // CPP contract call is 1000 gas auto& contract = contracts_[recipient]; - if (contract == nullptr) { - throw DynamicException("ContractHost call: contract not found"); - } - this->setContractVars(contract.get(), - Address(msg.sender), - Utils::evmcUint256ToUint256(msg.value)); + if (contract == nullptr) throw DynamicException("ContractHost call: contract not found"); + this->setContractVars( + contract.get(), Address(msg.sender), EVMCConv::evmcUint256ToUint256(msg.value) + ); Bytes ret = contract->evmEthCall(msg, this); - return evmc::Result(EVMC_SUCCESS, - this->leftoverGas_, - 0, - ret.data(), - ret.size()); + return evmc::Result(EVMC_SUCCESS, this->leftoverGas_, 0, ret.data(), ret.size()); } catch (std::exception& e) { this->evmcThrows_.emplace_back(e.what()); this->evmcThrow_ = true; @@ -607,42 +604,36 @@ evmc::Result ContractHost::callCPPContract(const evmc_message& msg) { evmc::Result ContractHost::callEVMContract(const evmc_message& msg) { Address recipient(msg.recipient); auto &recipientAccount = *accounts_[recipient]; - evmc::Result result(evmc_execute(this->vm_, - &this->get_interface(), - this->to_context(), - evmc_revision::EVMC_LATEST_STABLE_REVISION, - &msg, - recipientAccount.code.data(), - recipientAccount.code.size())); - // gas_left is not linked with leftoverGas_, we need to link it. - this->leftoverGas_ = result.gas_left; - // EVM contract call is 5000 gas - this->deduceGas(5000); - // We need to set the gas left to the leftoverGas_ - result.gas_left = this->leftoverGas_; + evmc::Result result(evmc_execute( + this->vm_, + &this->get_interface(), + this->to_context(), + evmc_revision::EVMC_LATEST_STABLE_REVISION, + &msg, + recipientAccount.code.data(), + recipientAccount.code.size()) + ); + this->leftoverGas_ = result.gas_left; // gas_left is not linked with leftoverGas_, we need to link it. + this->deduceGas(5000); // EVM contract call is 5000 gas + result.gas_left = this->leftoverGas_; // We need to set the gas left to the leftoverGas_ return result; } ContractType ContractHost::decodeContractCallType(const evmc_message& msg) const { - switch (msg.kind) - { - case evmc_call_kind::EVMC_CREATE: { - return ContractType::CREATE; - } - case evmc_call_kind::EVMC_CREATE2: { - return ContractType::CREATE2; - } - default: - if (msg.recipient == BDK_PRECOMPILE) - return ContractType::PRECOMPILED; - Address recipient(msg.recipient); - // we need to take a reference to the account, not a reference - // to the pointer - const auto& recipientAccount = *accounts_[recipient]; - if (recipientAccount.contractType == ContractType::CPP) - return ContractType::CPP; - // else EVM call - return ContractType::EVM; + switch (msg.kind) { + case evmc_call_kind::EVMC_CREATE: { + return ContractType::CREATE; + } + case evmc_call_kind::EVMC_CREATE2: { + return ContractType::CREATE2; + } + default: + if (msg.recipient == BDK_PRECOMPILE) return ContractType::PRECOMPILED; + Address recipient(msg.recipient); + // we need to take a reference to the account, not a reference to the pointer + const auto& recipientAccount = *accounts_[recipient]; + if (recipientAccount.contractType == ContractType::CPP) return ContractType::CPP; + return ContractType::EVM; // else EVM call } } @@ -692,7 +683,7 @@ evmc_tx_context ContractHost::get_tx_context() const noexcept { evmc::bytes32 ContractHost::get_block_hash(int64_t number) const noexcept { try { - return Utils::uint256ToEvmcUint256(number); + return EVMCConv::uint256ToEvmcUint256(number); } catch (std::exception& e) { this->evmcThrows_.emplace_back(e.what()); this->evmcThrow_ = true; diff --git a/src/contract/contracthost.h b/src/contract/contracthost.h index 9ae8d1706..e79a133d7 100644 --- a/src/contract/contracthost.h +++ b/src/contract/contracthost.h @@ -1,23 +1,20 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #ifndef CONTRACT_HOST_H #define CONTRACT_HOST_H - -#include -#include "../utils/utils.h" -#include "../utils/strings.h" -#include "../utils/hex.h" -#include "../utils/safehash.h" -#include "../utils/db.h" -#include "../core/storage.h" -#include -#include "contractstack.h" -#include "../core/rdpos.h" -#include "../utils/contractreflectioninterface.h" +// utils/{contractreflectioninterface.h, db.h, safehash.h, (strings.h -> hex.h, evmc/evmc.hpp), utils.h}, +// contract.h -> core/{dump.h, storage.h -> calltracer.h} #include "contractmanager.h" -#include "../core/dump.h" -#include "calltracer.h" -#include "../bytes/join.h" +#include "contractstack.h" // utils/{strings.h,safehash.h, bytes/join.h} +#include "../utils/evmcconv.h" +#include "../utils/uintconv.h" // TODO: EVMC Static Mode Handling // TODO: Contract creating other contracts (EVM Factories) @@ -260,7 +257,7 @@ class ContractHost : public evmc::Host { } auto functor = ABI::FunctorEncoder::encode(functionName); Bytes fullData; - Utils::appendBytes(fullData, Utils::uint32ToBytes(functor.value)); + Utils::appendBytes(fullData, UintConv::uint32ToBytes(functor.value)); if constexpr (sizeof...(Args) > 0) { Utils::appendBytes(fullData, ABI::Encoder::encodeData(args...)); } @@ -313,7 +310,7 @@ class ContractHost : public evmc::Host { const std::string functionName = ContractReflectionInterface::getFunctionName(func); const BytesArr<4> encodedFunctor = - Utils::uint32ToBytes(ABI::FunctorEncoder::encode(functionName).value); + UintConv::uint32ToBytes(ABI::FunctorEncoder::encode(functionName).value); if constexpr (sizeof...(args) > 0) { const Bytes encodedArgs = ABI::Encoder::encodeData(args...); @@ -383,7 +380,7 @@ class ContractHost : public evmc::Host { } NestedCallSafeGuard guard(caller, caller->caller_, caller->value_); switch (recipientAcc.contractType) { - case ContractType::EVM : { + case ContractType::EVM: { this->deduceGas(10000); evmc_message msg; msg.kind = EVMC_CALL; @@ -398,13 +395,13 @@ class ContractHost : public evmc::Host { } auto functor = ABI::FunctorEncoder::encode(functionName); Bytes fullData; - Utils::appendBytes(fullData, Utils::uint32ToBytes(functor.value)); + Utils::appendBytes(fullData, UintConv::uint32ToBytes(functor.value)); if constexpr (sizeof...(Args) > 0) { Utils::appendBytes(fullData, ABI::Encoder::encodeData(args...)); } msg.input_data = fullData.data(); msg.input_size = fullData.size(); - msg.value = Utils::uint256ToEvmcUint256(value); + msg.value = EVMCConv::uint256ToEvmcUint256(value); msg.create2_salt = {}; msg.code_address = targetAddr.toEvmcAddress(); evmc::Result result (evmc_execute(this->vm_, &this->get_interface(), this->to_context(), @@ -422,7 +419,7 @@ class ContractHost : public evmc::Host { return std::get<0>(ABI::Decoder::decodeData(bytes::View(result.output_data, result.output_data + result.output_size))); } } break; - case ContractType::CPP : { + case ContractType::CPP: { this->deduceGas(1000); C* contract = this->getContract(targetAddr); this->setContractVars(contract, caller->getContractAddress(), value); diff --git a/src/contract/contractmanager.cpp b/src/contract/contractmanager.cpp index 325f40850..bf8d05408 100644 --- a/src/contract/contractmanager.cpp +++ b/src/contract/contractmanager.cpp @@ -5,15 +5,11 @@ This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. */ -#include "abi.h" -#include "contractfactory.h" -#include "contracthost.h" #include "contractmanager.h" +#include "contractfactory.h" #include "customcontracts.h" #include "../core/rdpos.h" -#include "../core/state.h" -#include "../utils/dynamicexception.h" ContractManager::ContractManager( const DB& db, boost::unordered_flat_map, SafeHash>& contracts, @@ -73,7 +69,7 @@ void ContractManager::ethCall(const evmc_message& callInfo, ContractHost* host) this->host_ = host; PointerNullifier nullifier(this->host_); const Address caller(callInfo.sender); - const Functor functor = Utils::getFunctor(callInfo); + const Functor functor = EVMCConv::getFunctor(callInfo); /// Call the function on this->createContractFuncs_ auto it = this->createContractFuncs_.find(functor); if (it == this->createContractFuncs_.end()) { @@ -90,12 +86,12 @@ Bytes ContractManager::ethCallView(const evmc_message& callInfo, ContractHost* h PointerNullifier nullifier(this->host_); // This hash is equivalent to "function getDeployedContracts() public view returns (Contract[] memory) {}" // 0xaa9a068f == uint32_t(2862220943); - auto functor = Utils::getFunctor(callInfo); + auto functor = EVMCConv::getFunctor(callInfo); if (functor.value == 2862220943) return ABI::Encoder::encodeData(this->getDeployedContracts()); // This hash is equivalent to "function getDeployedContractsForCreator(address creator) public view returns (Contract[] memory) {}" // 0x73474f5a == uint32_t(1934053210) if (functor.value == 1934053210) { - auto args = Utils::getFunctionArgs(callInfo); + auto args = EVMCConv::getFunctionArgs(callInfo); auto [addr] = ABI::Decoder::decodeData
(args); return ABI::Encoder::encodeData(this->getDeployedContractsForCreator(addr)); } diff --git a/src/contract/contractmanager.h b/src/contract/contractmanager.h index e8a86646f..c9569d9f9 100644 --- a/src/contract/contractmanager.h +++ b/src/contract/contractmanager.h @@ -8,22 +8,9 @@ See the LICENSE.txt file in the project root for more information. #ifndef CONTRACTMANAGER_H #define CONTRACTMANAGER_H -#include -#include -#include - -#include "abi.h" -#include "contract.h" -#include "event.h" -#include "variables/safeunorderedmap.h" - -#include "../utils/db.h" -#include "../utils/options.h" -#include "../utils/safehash.h" -#include "../utils/strings.h" -#include "../utils/tx.h" -#include "../utils/utils.h" -#include "../utils/contractreflectioninterface.h" +#include "../utils/contractreflectioninterface.h" // contract/abi.h -> utils.h -> strings.h, libs/json.hpp -> boost/unordered/unordered_flat_map.hpp + +#include "contract.h" // core/dump.h -> utils/db.h /** * Class that holds all current contract instances in the blockchain state. diff --git a/src/contract/contractstack.h b/src/contract/contractstack.h index f5acdc45f..46c0cc9cb 100644 --- a/src/contract/contractstack.h +++ b/src/contract/contractstack.h @@ -1,10 +1,15 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #ifndef STACKTRACE_H #define STACKTRACE_H -#include <../utils/strings.h> -#include <../utils/safehash.h> -#include <../contract/event.h> -#include "contract.h" +// leave it in to avoid "AddressSanitizer unknown-crash" runtime errors +#include "contract.h" // core/dump.h -> utils/db.h -> utils.h -> strings.h /** * ContractStack is a class/object required to initialize a sequence of contract executions (1 tx == 1 contract stack). diff --git a/src/contract/dynamiccontract.h b/src/contract/dynamiccontract.h index 47b8becc0..918df2205 100644 --- a/src/contract/dynamiccontract.h +++ b/src/contract/dynamiccontract.h @@ -8,12 +8,10 @@ See the LICENSE.txt file in the project root for more information. #ifndef DYNAMICCONTRACT_H #define DYNAMICCONTRACT_H -#include "abi.h" -#include "contract.h" -#include "contracthost.h" -#include "event.h" -#include "../utils/safehash.h" -#include "../utils/utils.h" +#include "../utils/evmcconv.h" // getFunctor, getFunctionArgs + +#include "contracthost.h" // contractmanager.h -> contract.h, ...utils/utils.h,safehash.h +#include "event.h" // abi.h /// Template for a smart contract. All contracts must inherit this class. class DynamicContract : public BaseContract { @@ -205,14 +203,14 @@ class DynamicContract : public BaseContract { Functor functor = ABI::FunctorEncoder::encode(funcSignature); auto registrationFunc = [this, instance, memFunc, funcSignature](const evmc_message &callInfo) { using DecayedArgsTuple = std::tuple...>; - DecayedArgsTuple decodedData = ABI::Decoder::decodeData...>(Utils::getFunctionArgs(callInfo)); + DecayedArgsTuple decodedData = ABI::Decoder::decodeData...>(EVMCConv::getFunctionArgs(callInfo)); std::apply([instance, memFunc](auto&&... args) { (instance->*memFunc)(std::forward(args)...); }, decodedData); }; auto registrationFuncEVM = [this, instance, memFunc, funcSignature](const evmc_message &callInfo) -> Bytes { using DecayedArgsTuple = std::tuple...>; - DecayedArgsTuple decodedData = ABI::Decoder::decodeData...>(Utils::getFunctionArgs(callInfo)); + DecayedArgsTuple decodedData = ABI::Decoder::decodeData...>(EVMCConv::getFunctionArgs(callInfo)); if constexpr (std::is_same_v) { std::apply([instance, memFunc](auto&&... args) { (instance->*memFunc)(std::forward(args)...); @@ -257,7 +255,7 @@ class DynamicContract : public BaseContract { Functor functor = ABI::FunctorEncoder::encode(funcSignature); auto registrationFunc = [this, instance, memFunc, funcSignature](const evmc_message &callInfo) -> Bytes { using DecayedArgsTuple = std::tuple...>; - DecayedArgsTuple decodedData = ABI::Decoder::decodeData...>(Utils::getFunctionArgs(callInfo)); + DecayedArgsTuple decodedData = ABI::Decoder::decodeData...>(EVMCConv::getFunctionArgs(callInfo)); // Use std::apply to call the member function and encode its return value return std::apply([instance, memFunc](Args... args) -> Bytes { // Call the member function and return its encoded result @@ -273,7 +271,7 @@ class DynamicContract : public BaseContract { }; auto registrationFuncEVM = [this, instance, memFunc, funcSignature](const evmc_message &callInfo) -> Bytes { using DecayedArgsTuple = std::tuple...>; - DecayedArgsTuple decodedData = ABI::Decoder::decodeData...>(Utils::getFunctionArgs(callInfo)); + DecayedArgsTuple decodedData = ABI::Decoder::decodeData...>(EVMCConv::getFunctionArgs(callInfo)); if constexpr (std::is_same_v) { // If the function's return type is void, call the member function and return an empty Bytes object std::apply([instance, memFunc](Args... args) { @@ -371,7 +369,7 @@ class DynamicContract : public BaseContract { this->host_ = host; PointerNullifier nullifier(this->host_); try { - Functor funcName = Utils::getFunctor(callInfo); + Functor funcName = EVMCConv::getFunctor(callInfo); if (this->isPayableFunction(funcName)) { auto func = this->payableFunctions_.find(funcName); if (func == this->payableFunctions_.end()) throw DynamicException("Functor not found for payable function"); @@ -395,7 +393,7 @@ class DynamicContract : public BaseContract { this->host_ = host; PointerNullifier nullifier(this->host_); try { - Functor funcName = Utils::getFunctor(callInfo); + Functor funcName = EVMCConv::getFunctor(callInfo); if (this->isPayableFunction(funcName)) { auto func = this->evmFunctions_.find(funcName); if (func == this->evmFunctions_.end()) throw DynamicException("Functor not found for payable function"); @@ -425,7 +423,7 @@ class DynamicContract : public BaseContract { this->host_ = host; PointerNullifier nullifier(this->host_); try { - Functor funcName = Utils::getFunctor(data); + Functor funcName = EVMCConv::getFunctor(data); auto func = this->viewFunctions_.find(funcName); if (func == this->viewFunctions_.end()) throw DynamicException("Functor not found"); return func->second(data); diff --git a/src/contract/event.cpp b/src/contract/event.cpp index eec548530..8540c6876 100644 --- a/src/contract/event.cpp +++ b/src/contract/event.cpp @@ -7,6 +7,8 @@ See the LICENSE.txt file in the project root for more information. #include "event.h" +#include "../utils/uintconv.h" + Event::Event(const std::string& jsonstr) { json obj = json::parse(jsonstr); this->name_ = obj["name"].get(); @@ -45,13 +47,13 @@ json Event::serializeForRPC() const { json obj = { {"address", this->address_.hex(true).get()}, {"blockHash", this->blockHash_.hex(true).get()}, - {"blockNumber", Hex::fromBytes(Utils::uint64ToBytes(this->blockIndex_), true).get()}, + {"blockNumber", Hex::fromBytes(UintConv::uint64ToBytes(this->blockIndex_), true).get()}, {"data", Hex::fromBytes(this->data_, true).get()}, - {"logIndex", Hex::fromBytes(Utils::uint64ToBytes(this->logIndex_), true).get()}, + {"logIndex", Hex::fromBytes(UintConv::uint64ToBytes(this->logIndex_), true).get()}, {"removed", false}, // We don't fake/alter events like Ethereum does {"topics", topicStr}, {"transactionHash", this->txHash_.hex(true).get()}, - {"transactionIndex", Hex::fromBytes(Utils::uint64ToBytes(this->txIndex_), true).get()} + {"transactionIndex", Hex::fromBytes(UintConv::uint64ToBytes(this->txIndex_), true).get()} }; return obj; } diff --git a/src/contract/event.h b/src/contract/event.h index b5b008831..2276ffbb2 100644 --- a/src/contract/event.h +++ b/src/contract/event.h @@ -8,26 +8,11 @@ See the LICENSE.txt file in the project root for more information. #ifndef EVENT_H #define EVENT_H -#include -#include -#include -#include - -#include "../libs/json.hpp" -#include "../libs/zpp_bits.h" - -#include "../utils/db.h" -#include "../utils/options.h" -#include "../utils/strings.h" -#include "../utils/utils.h" - -#include "abi.h" - #include -#include -#include #include +#include "abi.h" // utils.h -> (strings.h -> libs/zpp_bits.h), (libs/json.hpp -> algorithm, string) + namespace bmi = boost::multi_index; using json = nlohmann::ordered_json; diff --git a/src/contract/templates/dexv2/dexv2factory.cpp b/src/contract/templates/dexv2/dexv2factory.cpp index f5cf6eb95..7f424aca4 100644 --- a/src/contract/templates/dexv2/dexv2factory.cpp +++ b/src/contract/templates/dexv2/dexv2factory.cpp @@ -8,6 +8,8 @@ See the LICENSE.txt file in the project root for more information. #include "dexv2factory.h" #include "dexv2pair.h" +#include "../../../utils/uintconv.h" + DEXV2Factory::DEXV2Factory(const Address &address, const DB& db ) : DynamicContract(address, db), feeTo_(this), feeToSetter_(this), allPairs_(this), getPair_(this) @@ -118,7 +120,7 @@ DBBatch DEXV2Factory::dump() const dbBatch.push_back(Utils::stringToBytes("feeToSetter_"), this->feeToSetter_.get().view(), this->getDBPrefix()); for (const auto& address : this->allPairs_.get()) { - dbBatch.push_back(Utils::uint32ToBytes(i), address.view(), this->getNewPrefix("allPairs_")); + dbBatch.push_back(UintConv::uint32ToBytes(i), address.view(), this->getNewPrefix("allPairs_")); i++; } diff --git a/src/contract/templates/dexv2/dexv2pair.cpp b/src/contract/templates/dexv2/dexv2pair.cpp index 83b0e3e19..aaa658ddc 100644 --- a/src/contract/templates/dexv2/dexv2pair.cpp +++ b/src/contract/templates/dexv2/dexv2pair.cpp @@ -8,6 +8,8 @@ See the LICENSE.txt file in the project root for more information. #include "dexv2pair.h" #include "dexv2factory.h" +#include "../../../utils/uintconv.h" + DEXV2Pair::DEXV2Pair(const Address& address, const DB& db ) : ERC20(address, db), factory_(this), token0_(this), token1_(this), reserve0_(this), reserve1_(this), blockTimestampLast_(this), @@ -16,12 +18,12 @@ DEXV2Pair::DEXV2Pair(const Address& address, const DB& db this->factory_ = Address(db.get(std::string("factory_"), this->getDBPrefix())); this->token0_ = Address(db.get(std::string("token0_"), this->getDBPrefix())); this->token1_ = Address(db.get(std::string("token1_"), this->getDBPrefix())); - this->reserve0_ = Utils::bytesToUint112(db.get(std::string("reserve0_"), this->getDBPrefix())); - this->reserve1_ = Utils::bytesToUint112(db.get(std::string("reserve1_"), this->getDBPrefix())); - this->blockTimestampLast_ = Utils::bytesToUint32(db.get(std::string("blockTimestampLast_"), this->getDBPrefix())); - this->price0CumulativeLast_ = Utils::bytesToUint256(db.get(std::string("price0CumulativeLast_"), this->getDBPrefix())); - this->price1CumulativeLast_ = Utils::bytesToUint256(db.get(std::string("price1CumulativeLast_"), this->getDBPrefix())); - this->kLast_ = Utils::bytesToUint256(db.get(std::string("kLast_"), this->getDBPrefix())); + this->reserve0_ = UintConv::bytesToUint112(db.get(std::string("reserve0_"), this->getDBPrefix())); + this->reserve1_ = UintConv::bytesToUint112(db.get(std::string("reserve1_"), this->getDBPrefix())); + this->blockTimestampLast_ = UintConv::bytesToUint32(db.get(std::string("blockTimestampLast_"), this->getDBPrefix())); + this->price0CumulativeLast_ = UintConv::bytesToUint256(db.get(std::string("price0CumulativeLast_"), this->getDBPrefix())); + this->price1CumulativeLast_ = UintConv::bytesToUint256(db.get(std::string("price1CumulativeLast_"), this->getDBPrefix())); + this->kLast_ = UintConv::bytesToUint256(db.get(std::string("kLast_"), this->getDBPrefix())); this->factory_.commit(); this->token0_.commit(); @@ -259,12 +261,13 @@ DBBatch DEXV2Pair::dump() const dbBatch.push_back(Utils::stringToBytes("factory_"), this->factory_.get().view(), this->getDBPrefix()); dbBatch.push_back(Utils::stringToBytes("token0_"), this->token0_.get().view(), this->getDBPrefix()); dbBatch.push_back(Utils::stringToBytes("token1_"), this->token1_.get().view(), this->getDBPrefix()); - dbBatch.push_back(Utils::stringToBytes("reserve0_"), Utils::uint112ToBytes(this->reserve0_.get()), this->getDBPrefix()); - dbBatch.push_back(Utils::stringToBytes("reserve1_"), Utils::uint112ToBytes(this->reserve1_.get()), this->getDBPrefix()); - dbBatch.push_back(Utils::stringToBytes("blockTimestampLast_"), Utils::uint32ToBytes(this->blockTimestampLast_.get()), this->getDBPrefix()); - dbBatch.push_back(Utils::stringToBytes("price0CumulativeLast_"), Utils::uint256ToBytes(this->price0CumulativeLast_.get()), this->getDBPrefix()); - dbBatch.push_back(Utils::stringToBytes("price1CumulativeLast_"), Utils::uint256ToBytes(this->price1CumulativeLast_.get()), this->getDBPrefix()); - dbBatch.push_back(Utils::stringToBytes("kLast_"), Utils::uint256ToBytes(this->kLast_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("reserve0_"), UintConv::uint112ToBytes(this->reserve0_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("reserve1_"), UintConv::uint112ToBytes(this->reserve1_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("blockTimestampLast_"), UintConv::uint32ToBytes(this->blockTimestampLast_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("price0CumulativeLast_"), UintConv::uint256ToBytes(this->price0CumulativeLast_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("price1CumulativeLast_"), UintConv::uint256ToBytes(this->price1CumulativeLast_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("kLast_"), UintConv::uint256ToBytes(this->kLast_.get()), this->getDBPrefix()); return dbBatch; } + diff --git a/src/contract/templates/erc20.cpp b/src/contract/templates/erc20.cpp index 5615242a5..8365ec18a 100644 --- a/src/contract/templates/erc20.cpp +++ b/src/contract/templates/erc20.cpp @@ -7,14 +7,16 @@ See the LICENSE.txt file in the project root for more information. #include "erc20.h" +#include "../../utils/uintconv.h" + ERC20::ERC20(const Address& address, const DB& db) : DynamicContract(address, db), name_(this), symbol_(this), decimals_(this), totalSupply_(this), balances_(this), allowed_(this) { this->name_ = Utils::bytesToString(db.get(std::string("name_"), this->getDBPrefix())); this->symbol_ = Utils::bytesToString(db.get(std::string("symbol_"), this->getDBPrefix())); - this->decimals_ = Utils::bytesToUint8(db.get(std::string("decimals_"), this->getDBPrefix())); - this->totalSupply_ = Utils::bytesToUint256(db.get(std::string("totalSupply_"), this->getDBPrefix())); + this->decimals_ = UintConv::bytesToUint8(db.get(std::string("decimals_"), this->getDBPrefix())); + this->totalSupply_ = UintConv::bytesToUint256(db.get(std::string("totalSupply_"), this->getDBPrefix())); for (const auto& dbEntry : db.getBatch(this->getNewPrefix("balances_"))) { this->balances_[Address(dbEntry.key)] = Utils::fromBigEndian(dbEntry.value); } @@ -22,7 +24,7 @@ ERC20::ERC20(const Address& address, const DB& db) bytes::View key(dbEntry.key); Address owner(key.subspan(0,20)); Address spender(key.subspan(20)); - this->allowed_[owner][spender] = Utils::bytesToUint256(dbEntry.value); + this->allowed_[owner][spender] = UintConv::bytesToUint256(dbEntry.value); } this->name_.commit(); @@ -171,8 +173,8 @@ DBBatch ERC20::dump() const // Name, Symbol, Decimals, Total Supply dbBatch.push_back(Utils::stringToBytes("name_"), Utils::stringToBytes(name_.get()), this->getDBPrefix()); dbBatch.push_back(Utils::stringToBytes("symbol_"), Utils::stringToBytes(symbol_.get()), this->getDBPrefix()); - dbBatch.push_back(Utils::stringToBytes("decimals_"), Utils::uint8ToBytes(decimals_.get()), this->getDBPrefix()); - dbBatch.push_back(Utils::stringToBytes("totalSupply_"), Utils::uint256ToBytes(totalSupply_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("decimals_"), UintConv::uint8ToBytes(decimals_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("totalSupply_"), UintConv::uint256ToBytes(totalSupply_.get()), this->getDBPrefix()); // Balances for (auto it = balances_.cbegin(); it != balances_.cend(); ++it) { const auto& key = it->first; @@ -185,9 +187,7 @@ DBBatch ERC20::dump() const // Key = Address + Address, Value = uint256_t auto key = i->first.asBytes(); Utils::appendBytes(key, j->first.asBytes()); - dbBatch.push_back(key, - Utils::uint256ToBytes(j->second), - this->getNewPrefix("allowed_")); + dbBatch.push_back(key, UintConv::uint256ToBytes(j->second), this->getNewPrefix("allowed_")); } } return dbBatch; diff --git a/src/contract/templates/erc721.cpp b/src/contract/templates/erc721.cpp index 8e13f42fe..d87a3dd38 100644 --- a/src/contract/templates/erc721.cpp +++ b/src/contract/templates/erc721.cpp @@ -265,7 +265,7 @@ void ERC721::transferFrom(const Address& from, const Address& to, const uint256_ DBBatch ERC721::dump() const { DBBatch dbBatch = BaseContract::dump(); - boost::unordered_flat_map data { + boost::unordered_flat_map data { {"name_", Utils::stringToBytes(name_.get())}, {"symbol_", Utils::stringToBytes(symbol_.get())} }; diff --git a/src/contract/templates/erc721test.cpp b/src/contract/templates/erc721test.cpp index 7af0691ca..85b5738b3 100644 --- a/src/contract/templates/erc721test.cpp +++ b/src/contract/templates/erc721test.cpp @@ -1,14 +1,22 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #include "erc721test.h" +#include "../../utils/uintconv.h" ERC721Test::ERC721Test(const Address &address, const DB& db) : DynamicContract(address, db), ERC721(address, db), tokenIdCounter_(this), maxTokens_(this), totalSupply_(this) { - this->tokenIdCounter_ = Utils::bytesToUint64(db.get(std::string("tokenIdCounter_"), this->getDBPrefix())); - this->maxTokens_ = Utils::bytesToUint64(db.get(std::string("maxTokens_"), this->getDBPrefix())); - this->totalSupply_ = Utils::bytesToUint64(db.get(std::string("totalSupply_"), this->getDBPrefix())); + this->tokenIdCounter_ = UintConv::bytesToUint64(db.get(std::string("tokenIdCounter_"), this->getDBPrefix())); + this->maxTokens_ = UintConv::bytesToUint64(db.get(std::string("maxTokens_"), this->getDBPrefix())); + this->totalSupply_ = UintConv::bytesToUint64(db.get(std::string("totalSupply_"), this->getDBPrefix())); this->tokenIdCounter_.commit(); this->maxTokens_.commit(); @@ -41,9 +49,9 @@ ERC721Test::ERC721Test( DBBatch ERC721Test::dump() const { DBBatch batch = ERC721::dump(); - batch.push_back(Utils::stringToBytes("tokenIdCounter_"), Utils::uint64ToBytes(this->tokenIdCounter_.get()), this->getDBPrefix()); - batch.push_back(Utils::stringToBytes("maxTokens_"), Utils::uint64ToBytes(this->maxTokens_.get()), this->getDBPrefix()); - batch.push_back(Utils::stringToBytes("totalSupply_"), Utils::uint64ToBytes(this->totalSupply_.get()), this->getDBPrefix()); + batch.push_back(Utils::stringToBytes("tokenIdCounter_"), UintConv::uint64ToBytes(this->tokenIdCounter_.get()), this->getDBPrefix()); + batch.push_back(Utils::stringToBytes("maxTokens_"), UintConv::uint64ToBytes(this->maxTokens_.get()), this->getDBPrefix()); + batch.push_back(Utils::stringToBytes("totalSupply_"), UintConv::uint64ToBytes(this->totalSupply_.get()), this->getDBPrefix()); return batch; } diff --git a/src/contract/templates/pebble.cpp b/src/contract/templates/pebble.cpp index 7ca9afc95..b658633b6 100644 --- a/src/contract/templates/pebble.cpp +++ b/src/contract/templates/pebble.cpp @@ -1,32 +1,32 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #include "pebble.h" -#include "contract/variables/reentrancyguard.h" +#include "../variables/reentrancyguard.h" + +#include "../../utils/uintconv.h" Pebble::Pebble(const Address& address, const DB& db) - : DynamicContract(address, db), - ERC721(address, db), - ERC721URIStorage(address, db), - Ownable(address, db), - maxSupply_(this), - tokenIds_(this), - tokenRarity_(this), - totalNormal_(this), - totalGold_(this), - totalDiamond_(this), - raritySeed_(this), - diamondRarity_(this), - goldRarity_(this), - authorizer_(this), - minters_(this) { + : DynamicContract(address, db), ERC721(address, db), ERC721URIStorage(address, db), Ownable(address, db), + maxSupply_(this), tokenIds_(this), tokenRarity_(this), + totalNormal_(this), totalGold_(this), totalDiamond_(this), + raritySeed_(this), diamondRarity_(this), goldRarity_(this), + authorizer_(this), minters_(this) +{ // Load from DB. - this->maxSupply_ = Utils::bytesToUint256(db.get(std::string("maxSupply_"), this->getDBPrefix())); - this->tokenIds_ = Utils::bytesToUint256(db.get(std::string("tokenIds_"), this->getDBPrefix())); + this->maxSupply_ = UintConv::bytesToUint256(db.get(std::string("maxSupply_"), this->getDBPrefix())); + this->tokenIds_ = UintConv::bytesToUint256(db.get(std::string("tokenIds_"), this->getDBPrefix())); this->totalNormal_ = Utils::fromBigEndian(db.get(std::string("totalNormal_"), this->getDBPrefix())); this->totalGold_ = Utils::fromBigEndian(db.get(std::string("totalGold_"), this->getDBPrefix())); this->totalDiamond_ = Utils::fromBigEndian(db.get(std::string("totalDiamond_"), this->getDBPrefix())); - this->raritySeed_ = Utils::bytesToUint256(db.get(std::string("raritySeed_"), this->getDBPrefix())); - this->diamondRarity_ = Utils::bytesToUint256(db.get(std::string("diamondRarity_"), this->getDBPrefix())); - this->goldRarity_ = Utils::bytesToUint256(db.get(std::string("goldRarity_"), this->getDBPrefix())); + this->raritySeed_ = UintConv::bytesToUint256(db.get(std::string("raritySeed_"), this->getDBPrefix())); + this->diamondRarity_ = UintConv::bytesToUint256(db.get(std::string("diamondRarity_"), this->getDBPrefix())); + this->goldRarity_ = UintConv::bytesToUint256(db.get(std::string("goldRarity_"), this->getDBPrefix())); for (const auto& dbEntry : db.getBatch(this->getNewPrefix("tokenRarity_"))) { this->tokenRarity_[Utils::fromBigEndian(dbEntry.key)] = static_cast(Utils::fromBigEndian(dbEntry.value)); } @@ -117,19 +117,19 @@ DBBatch Pebble::dump() const { batch.delete_key(dbItem); } // Then, dump the contents of this class. - batch.push_back(Utils::stringToBytes("maxSupply_"), Utils::uint256ToBytes(this->maxSupply_.get()), this->getDBPrefix()); - batch.push_back(Utils::stringToBytes("tokenIds_"), Utils::uint256ToBytes(this->tokenIds_.get()), this->getDBPrefix()); - batch.push_back(Utils::stringToBytes("totalNormal_"), Utils::uint64ToBytes(this->totalNormal_.get()), this->getDBPrefix()); - batch.push_back(Utils::stringToBytes("totalGold_"), Utils::uint64ToBytes(this->totalGold_.get()), this->getDBPrefix()); - batch.push_back(Utils::stringToBytes("totalDiamond_"), Utils::uint64ToBytes(this->totalDiamond_.get()), this->getDBPrefix()); - batch.push_back(Utils::stringToBytes("raritySeed_"), Utils::uint256ToBytes(this->raritySeed_.get()), this->getDBPrefix()); - batch.push_back(Utils::stringToBytes("diamondRarity_"), Utils::uint256ToBytes(this->diamondRarity_.get()), this->getDBPrefix()); - batch.push_back(Utils::stringToBytes("goldRarity_"), Utils::uint256ToBytes(this->goldRarity_.get()), this->getDBPrefix()); + batch.push_back(Utils::stringToBytes("maxSupply_"), UintConv::uint256ToBytes(this->maxSupply_.get()), this->getDBPrefix()); + batch.push_back(Utils::stringToBytes("tokenIds_"), UintConv::uint256ToBytes(this->tokenIds_.get()), this->getDBPrefix()); + batch.push_back(Utils::stringToBytes("totalNormal_"), UintConv::uint64ToBytes(this->totalNormal_.get()), this->getDBPrefix()); + batch.push_back(Utils::stringToBytes("totalGold_"), UintConv::uint64ToBytes(this->totalGold_.get()), this->getDBPrefix()); + batch.push_back(Utils::stringToBytes("totalDiamond_"), UintConv::uint64ToBytes(this->totalDiamond_.get()), this->getDBPrefix()); + batch.push_back(Utils::stringToBytes("raritySeed_"), UintConv::uint256ToBytes(this->raritySeed_.get()), this->getDBPrefix()); + batch.push_back(Utils::stringToBytes("diamondRarity_"), UintConv::uint256ToBytes(this->diamondRarity_.get()), this->getDBPrefix()); + batch.push_back(Utils::stringToBytes("goldRarity_"), UintConv::uint256ToBytes(this->goldRarity_.get()), this->getDBPrefix()); for (auto it = this->tokenRarity_.cbegin(); it != this->tokenRarity_.cend(); ++it) { - batch.push_back(Utils::uint256ToBytes(it->first), Utils::uint8ToBytes(static_cast(it->second)), this->getNewPrefix("tokenRarity_")); + batch.push_back(UintConv::uint256ToBytes(it->first), UintConv::uint8ToBytes(static_cast(it->second)), this->getNewPrefix("tokenRarity_")); } for (auto it = this->minters_.cbegin(); it != this->minters_.cend(); ++it) { - batch.push_back(it->first.asBytes(), Utils::uint8ToBytes(static_cast(it->second)), this->getNewPrefix("minters_")); + batch.push_back(it->first.asBytes(), UintConv::uint8ToBytes(static_cast(it->second)), this->getNewPrefix("minters_")); } batch.push_back(Utils::stringToBytes("authorized_"), this->authorizer_.get().asBytes(), this->getDBPrefix()); return batch; diff --git a/src/contract/templates/pebble.h b/src/contract/templates/pebble.h index d870435a6..e261f73ba 100644 --- a/src/contract/templates/pebble.h +++ b/src/contract/templates/pebble.h @@ -1,7 +1,13 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #ifndef PEBBLE_H #define PEBBLE_H - #include "erc721uristorage.h" #include "ownable.h" #include "../variables/safeunorderedmap.h" diff --git a/src/contract/templates/randomnesstest.cpp b/src/contract/templates/randomnesstest.cpp index e326e382d..276778a9c 100644 --- a/src/contract/templates/randomnesstest.cpp +++ b/src/contract/templates/randomnesstest.cpp @@ -1,5 +1,14 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #include "randomnesstest.h" +#include "../../utils/uintconv.h" + RandomnessTest::RandomnessTest(const Address& address, const Address& creator, const uint64_t& chainId ) : DynamicContract("RandomnessTest", address, creator, chainId) { @@ -10,7 +19,7 @@ RandomnessTest::RandomnessTest(const Address& address, RandomnessTest::RandomnessTest(const Address& address, const DB& db) : DynamicContract(address, db) { - this->randomValue_ = Utils::bytesToUint256(db.get(std::string("randomValue_"), this->getDBPrefix())); + this->randomValue_ = UintConv::bytesToUint256(db.get(std::string("randomValue_"), this->getDBPrefix())); this->randomValue_.commit(); registerContractFunctions(); this->randomValue_.enableRegister(); @@ -35,7 +44,7 @@ uint256_t RandomnessTest::getRandom() const { DBBatch RandomnessTest::dump() const { DBBatch dbBatch = BaseContract::dump(); - dbBatch.push_back(Utils::stringToBytes("randomValue_"), Utils::uint256ToBytes(randomValue_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("randomValue_"), UintConv::uint256ToBytes(randomValue_.get()), this->getDBPrefix()); return dbBatch; } diff --git a/src/contract/templates/simplecontract.cpp b/src/contract/templates/simplecontract.cpp index 1cb15ddff..89395611f 100644 --- a/src/contract/templates/simplecontract.cpp +++ b/src/contract/templates/simplecontract.cpp @@ -7,6 +7,9 @@ See the LICENSE.txt file in the project root for more information. #include "simplecontract.h" +#include "../../utils/uintconv.h" +#include "../../utils/utils.h" + SimpleContract::SimpleContract( const std::string& name, const uint256_t& number, @@ -37,10 +40,10 @@ SimpleContract::SimpleContract( const DB& db ) : DynamicContract(address, db), name_(this), number_(this), tuple_(this) { this->name_ = Utils::bytesToString(db.get(std::string("name_"), this->getDBPrefix())); - this->number_ = Utils::bytesToUint256(db.get(std::string("number_"), this->getDBPrefix())); + this->number_ = UintConv::bytesToUint256(db.get(std::string("number_"), this->getDBPrefix())); this->tuple_ = std::make_tuple( Utils::bytesToString(db.get(std::string("tuple_name"), this->getDBPrefix())), - Utils::bytesToUint256(db.get(std::string("tuple_number"), this->getDBPrefix())) + UintConv::bytesToUint256(db.get(std::string("tuple_number"), this->getDBPrefix())) ); this->name_.commit(); @@ -222,9 +225,9 @@ DBBatch SimpleContract::dump() const DBBatch dbBatch; dbBatch.push_back(Utils::stringToBytes("name_"), Utils::stringToBytes(this->name_.get()), this->getDBPrefix()); - dbBatch.push_back(Utils::stringToBytes("number_"), Utils::uint256ToBytes(this->number_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("number_"), UintConv::uint256ToBytes(this->number_.get()), this->getDBPrefix()); dbBatch.push_back(Utils::stringToBytes("tuple_name"), Utils::stringToBytes(get<0>(this->tuple_)), this->getDBPrefix()); - dbBatch.push_back(Utils::stringToBytes("tuple_number"), Utils::uint256ToBytes(get<1>(this->tuple_)), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("tuple_number"), UintConv::uint256ToBytes(get<1>(this->tuple_)), this->getDBPrefix()); return dbBatch; } diff --git a/src/contract/templates/simplecontract.h b/src/contract/templates/simplecontract.h index 866d20622..40b654d7c 100644 --- a/src/contract/templates/simplecontract.h +++ b/src/contract/templates/simplecontract.h @@ -11,7 +11,6 @@ See the LICENSE.txt file in the project root for more information. #include "../dynamiccontract.h" #include "../variables/safestring.h" #include "../variables/safetuple.h" -#include "../../utils/utils.h" // SafeUintX_t aliases declared here /** * SimpleContract is a simple contract that stores a name, number and tuple. diff --git a/src/contract/templates/snailtracer.cpp b/src/contract/templates/snailtracer.cpp index 9caeefc38..f89d17819 100644 --- a/src/contract/templates/snailtracer.cpp +++ b/src/contract/templates/snailtracer.cpp @@ -1,5 +1,14 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #include "snailtracer.h" +#include "../../utils/intconv.h" + SnailTracer::SnailTracer( int256_t w, int256_t h, const Address& address, const Address& creator, const uint64_t& chainId ) : DynamicContract("SnailTracer", address, creator, chainId), width_(w), height_(h) { @@ -72,8 +81,8 @@ SnailTracer::SnailTracer( const Address& address, const DB& db ) : DynamicContract(address, db) { - this->width_ = Utils::bytesToInt256(db.get(std::string("width_"), this->getDBPrefix())); - this->height_ = Utils::bytesToInt256(db.get(std::string("height_"), this->getDBPrefix())); + this->width_ = IntConv::bytesToInt256(db.get(std::string("width_"), this->getDBPrefix())); + this->height_ = IntConv::bytesToInt256(db.get(std::string("height_"), this->getDBPrefix())); this->camera_ = std::get<0>(ABI::Decoder::decodeData(db.get(std::string("camera_"), this->getDBPrefix()))); this->deltaX_ = std::get<0>(ABI::Decoder::decodeData(db.get(std::string("deltaX_"), this->getDBPrefix()))); this->deltaY_ = std::get<0>(ABI::Decoder::decodeData(db.get(std::string("deltaY_"), this->getDBPrefix()))); @@ -503,8 +512,8 @@ void SnailTracer::registerContractFunctions() { DBBatch SnailTracer::dump() const { DBBatch dbBatch = BaseContract::dump(); - dbBatch.push_back(Utils::stringToBytes("width_"), Utils::int256ToBytes(width_.get()), this->getDBPrefix()); - dbBatch.push_back(Utils::stringToBytes("height_"), Utils::int256ToBytes(height_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("width_"), IntConv::int256ToBytes(width_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("height_"), IntConv::int256ToBytes(height_.get()), this->getDBPrefix()); dbBatch.push_back(Utils::stringToBytes("camera_"), ABI::Encoder::encodeData(camera_.raw()), this->getDBPrefix()); dbBatch.push_back(Utils::stringToBytes("deltaX_"), ABI::Encoder::encodeData(deltaX_.raw()), this->getDBPrefix()); dbBatch.push_back(Utils::stringToBytes("deltaY_"), ABI::Encoder::encodeData(deltaY_.raw()), this->getDBPrefix()); diff --git a/src/contract/templates/snailtraceroptimized.cpp b/src/contract/templates/snailtraceroptimized.cpp index 3523175b9..6f2841cec 100644 --- a/src/contract/templates/snailtraceroptimized.cpp +++ b/src/contract/templates/snailtraceroptimized.cpp @@ -1,5 +1,14 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #include "snailtraceroptimized.h" +#include "../../utils/intconv.h" + SnailTracerOptimized::SnailTracerOptimized( int136_t w, int136_t h, const Address& address, const Address& creator, const uint64_t& chainId ) : DynamicContract("SnailTracerOptimized", address, creator, chainId), width_(w), height_(h) { @@ -72,8 +81,8 @@ SnailTracerOptimized::SnailTracerOptimized( const Address& address, const DB& db ) : DynamicContract(address, db) { - this->width_ = Utils::bytesToInt136(db.get(std::string("width_"), this->getDBPrefix())); - this->height_ = Utils::bytesToInt136(db.get(std::string("height_"), this->getDBPrefix())); + this->width_ = IntConv::bytesToInt136(db.get(std::string("width_"), this->getDBPrefix())); + this->height_ = IntConv::bytesToInt136(db.get(std::string("height_"), this->getDBPrefix())); this->camera_ = std::get<0>(ABI::Decoder::decodeData(db.get(std::string("camera_"), this->getDBPrefix()))); this->deltaX_ = std::get<0>(ABI::Decoder::decodeData(db.get(std::string("deltaX_"), this->getDBPrefix()))); this->deltaY_ = std::get<0>(ABI::Decoder::decodeData(db.get(std::string("deltaY_"), this->getDBPrefix()))); @@ -503,8 +512,8 @@ void SnailTracerOptimized::registerContractFunctions() { DBBatch SnailTracerOptimized::dump() const { DBBatch dbBatch = BaseContract::dump(); - dbBatch.push_back(Utils::stringToBytes("width_"), Utils::int136ToBytes(width_.get()), this->getDBPrefix()); - dbBatch.push_back(Utils::stringToBytes("height_"), Utils::int136ToBytes(height_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("width_"), IntConv::int136ToBytes(width_.get()), this->getDBPrefix()); + dbBatch.push_back(Utils::stringToBytes("height_"), IntConv::int136ToBytes(height_.get()), this->getDBPrefix()); dbBatch.push_back(Utils::stringToBytes("camera_"), ABI::Encoder::encodeData(camera_.raw()), this->getDBPrefix()); dbBatch.push_back(Utils::stringToBytes("deltaX_"), ABI::Encoder::encodeData(deltaX_.raw()), this->getDBPrefix()); dbBatch.push_back(Utils::stringToBytes("deltaY_"), ABI::Encoder::encodeData(deltaY_.raw()), this->getDBPrefix()); diff --git a/src/contract/variables/safeint.cpp b/src/contract/variables/safeint.cpp new file mode 100644 index 000000000..9fbf2466c --- /dev/null +++ b/src/contract/variables/safeint.cpp @@ -0,0 +1,409 @@ +#include "safeint.h" + +// Explicit instantiations + +template class SafeInt_t<8>; +template class SafeInt_t<16>; +template class SafeInt_t<32>; +template class SafeInt_t<64>; + +template class SafeInt_t<24>; +template class SafeInt_t<40>; +template class SafeInt_t<48>; +template class SafeInt_t<56>; +template class SafeInt_t<72>; +template class SafeInt_t<80>; +template class SafeInt_t<88>; +template class SafeInt_t<96>; +template class SafeInt_t<104>; +template class SafeInt_t<112>; +template class SafeInt_t<120>; +template class SafeInt_t<128>; +template class SafeInt_t<136>; +template class SafeInt_t<144>; +template class SafeInt_t<152>; +template class SafeInt_t<160>; +template class SafeInt_t<168>; +template class SafeInt_t<176>; +template class SafeInt_t<184>; +template class SafeInt_t<192>; +template class SafeInt_t<200>; +template class SafeInt_t<208>; +template class SafeInt_t<216>; +template class SafeInt_t<224>; +template class SafeInt_t<232>; +template class SafeInt_t<240>; +template class SafeInt_t<248>; +template class SafeInt_t<256>; + +// Class impl starts here + +template requires IntInterval +SafeInt_t SafeInt_t::operator+(const int_t& other) const { + if ((other > 0) && (this->value_ > std::numeric_limits::max() - other)) { + throw std::overflow_error("Overflow in addition operation."); + } + if ((other < 0) && (this->value_ < std::numeric_limits::min() - other)) { + throw std::underflow_error("Underflow in addition operation."); + } + return SafeInt_t(this->value_ + other); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator+(const SafeInt_t& other) const { + if ((other.get() > 0) && (this->value_ > std::numeric_limits::max() - other.get())) { + throw std::overflow_error("Overflow in addition operation."); + } + if ((other.get() < 0) && (this->value_ < std::numeric_limits::min() - other.get())) { + throw std::underflow_error("Underflow in addition operation."); + } + return SafeInt_t(this->value_ + other.get()); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator-(const int_t& other) const { + if ((other < 0) && (this->value_ > std::numeric_limits::max() + other)) { + throw std::overflow_error("Overflow in subtraction operation."); + } + if ((other > 0) && (this->value_ < std::numeric_limits::min() + other)) { + throw std::underflow_error("Underflow in subtraction operation."); + } + return SafeInt_t(this->value_ - other); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator-(const SafeInt_t& other) const { + if ((other.get() < 0) && (this->value_ > std::numeric_limits::max() + other.get())) { + throw std::overflow_error("Overflow in subtraction operation."); + } + if ((other.get() > 0) && (this->value_ < std::numeric_limits::min() + other.get())) { + throw std::underflow_error("Underflow in subtraction operation."); + } + return SafeInt_t(this->value_ - other.get()); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator*(const int_t& other) const { + if (this->value_ == 0 || other == 0) { + throw std::domain_error("Multiplication by zero."); + } + if (this->value_ > std::numeric_limits::max() / other) { + throw std::overflow_error("Overflow in multiplication operation."); + } + if (this->value_ < std::numeric_limits::min() / other) { + throw std::underflow_error("Underflow in multiplication operation."); + } + return SafeInt_t(this->value_ * other); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator*(const SafeInt_t& other) const { + if (this->value_ == 0 || other.get() == 0) { + throw std::domain_error("Multiplication by zero."); + } + if (this->value_ > std::numeric_limits::max() / other.get()) { + throw std::overflow_error("Overflow in multiplication operation."); + } + if (this->value_ < std::numeric_limits::min() / other.get()) { + throw std::underflow_error("Underflow in multiplication operation."); + } + return SafeInt_t(this->value_ * other.get()); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator/(const int_t& other) const { + if (other == 0) throw std::domain_error("Division by zero"); + // Edge case - dividing the smallest negative number by -1 causes overflow + if (this->value_ == std::numeric_limits::min() && other == -1) { + throw std::overflow_error("Overflow in division operation."); + } + return SafeInt_t(this->value_ / other); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator/(const SafeInt_t& other) const { + if (other.get() == 0) throw std::domain_error("Division by zero"); + // Edge case - dividing the smallest negative number by -1 causes overflow + if (this->value_ == std::numeric_limits::min() && other.get() == -1) { + throw std::overflow_error("Overflow in division operation."); + } + return SafeInt_t(this->value_ / other.get()); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator%(const int_t& other) const { + if (other == 0) throw std::domain_error("Modulus by zero"); + return SafeInt_t(this->value_ % other); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator%(const SafeInt_t& other) const { + if (other.get() == 0) throw std::domain_error("Modulus by zero"); + return SafeInt_t(this->value_ % other.get()); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator&(const int_t& other) const { + return SafeInt_t(this->value_ & other); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator&(const SafeInt_t& other) const { + return SafeInt_t(this->value_ & other.get()); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator|(const int_t& other) const { + return SafeInt_t(this->value_ | other); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator|(const SafeInt_t& other) const { + return SafeInt_t(this->value_ | other.get()); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator^(const int_t& other) const { + return SafeInt_t(this->value_ ^ other); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator^(const SafeInt_t& other) const { + return SafeInt_t(this->value_ ^ other.get()); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator<<(const uint8_t& other) const { + return SafeInt_t(this->value_ << other); +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator>>(const uint8_t& other) const { + return SafeInt_t(this->value_ >> other); +} + +template requires IntInterval +SafeInt_t::operator bool() const { return bool(this->value_); } + +template requires IntInterval +bool SafeInt_t::operator==(const int_t& other) const { return (this->value_ == other); } + +template requires IntInterval +bool SafeInt_t::operator==(const SafeInt_t& other) const { return (this->value_ == other.get()); } + +template requires IntInterval +bool SafeInt_t::operator!=(const int_t& other) const { return (this->value_ != other); } + +template requires IntInterval +bool SafeInt_t::operator!=(const SafeInt_t& other) const { return (this->value_ != other.get()); } + +template requires IntInterval +bool SafeInt_t::operator<(const int_t& other) const { return (this->value_ < other); } + +template requires IntInterval +bool SafeInt_t::operator<(const SafeInt_t& other) const { return (this->value_ < other.get()); } + +template requires IntInterval +bool SafeInt_t::operator<=(const int_t& other) const { return (this->value_ <= other); } + +template requires IntInterval +bool SafeInt_t::operator<=(const SafeInt_t& other) const { return (this->value_ <= other.get()); } + +template requires IntInterval +bool SafeInt_t::operator>(const int_t& other) const { return (this->value_ > other); } + +template requires IntInterval +bool SafeInt_t::operator>(const SafeInt_t& other) const { return (this->value_ > other.get()); } + +template requires IntInterval +bool SafeInt_t::operator>=(const int_t& other) const { return (this->value_ >= other); } + +template requires IntInterval +bool SafeInt_t::operator>=(const SafeInt_t& other) const { return (this->value_ >= other.get()); } + +template requires IntInterval +SafeInt_t& SafeInt_t::operator=(const int_t& other) { + markAsUsed(); this->value_ = other; return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator=(const SafeInt_t& other) { + markAsUsed(); this->value_ = other.get(); return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator+=(const int_t& other) { + if ((other > 0) && (this->value_ > std::numeric_limits::max() - other)) { + throw std::overflow_error("Overflow in addition assignment operation."); + } + if ((other < 0) && (this->value_ < std::numeric_limits::min() - other)) { + throw std::underflow_error("Underflow in addition assignment operation."); + } + markAsUsed(); this->value_ += other; return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator+=(const SafeInt_t& other) { + if ((other.get() > 0) && (this->value_ > std::numeric_limits::max() - other.get())) { + throw std::overflow_error("Overflow in addition assignment operation."); + } + if ((other.get() < 0) && (this->value_ < std::numeric_limits::min() - other.get())) { + throw std::underflow_error("Underflow in addition assignment operation."); + } + markAsUsed(); this->value_ += other.get(); return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator-=(const int_t& other) { + if ((other < 0) && (this->value_ > std::numeric_limits::max() + other)) { + throw std::overflow_error("Overflow in subtraction assignment operation."); + } + if ((other > 0) && (this->value_ < std::numeric_limits::min() + other)) { + throw std::underflow_error("Underflow in subtraction assignment operation."); + } + markAsUsed(); this->value_ -= other; return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator-=(const SafeInt_t& other) { + if ((other.get() < 0) && (this->value_ > std::numeric_limits::max() + other.get())) { + throw std::overflow_error("Overflow in subtraction assignment operation."); + } + if ((other.get() > 0) && (this->value_ < std::numeric_limits::min() + other.get())) { + throw std::underflow_error("Underflow in subtraction assignment operation."); + } + markAsUsed(); this->value_ -= other.get(); return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator*=(const int_t& other) { + if (this->value_ == 0 || other == 0) { + throw std::domain_error("Multiplication by zero."); + } + if (this->value_ > std::numeric_limits::max() / other) { + throw std::overflow_error("Overflow in multiplication assignment operation."); + } + if (this->value_ < std::numeric_limits::min() / other) { + throw std::underflow_error("Underflow in multiplication assignment operation."); + } + markAsUsed(); this->value_ *= other; return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator*=(const SafeInt_t& other) { + if (this->value_ == 0 || other.get() == 0) { + throw std::domain_error("Multiplication by zero."); + } + if (this->value_ > std::numeric_limits::max() / other.get()) { + throw std::overflow_error("Overflow in multiplication assignment operation."); + } + if (this->value_ < std::numeric_limits::min() / other.get()) { + throw std::underflow_error("Underflow in multiplication assignment operation."); + } + markAsUsed(); this->value_ *= other.get(); return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator/=(const int_t& other) { + if (other == 0) throw std::domain_error("Division assignment by zero."); + // Handling the edge case where dividing the smallest negative number by -1 causes overflow + if (this->value_ == std::numeric_limits::min() && other == -1) { + throw std::overflow_error("Overflow in division assignment operation."); + } + markAsUsed(); this->value_ /= other; return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator/=(const SafeInt_t& other) { + if (other.get() == 0) throw std::domain_error("Division assignment by zero."); + // Handling the edge case where dividing the smallest negative number by -1 causes overflow + if (this->value_ == std::numeric_limits::min() && other.get() == -1) { + throw std::overflow_error("Overflow in division assignment operation."); + } + markAsUsed(); this->value_ /= other.get(); return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator%=(const int_t& other) { + if (other == 0) throw std::domain_error("Modulus assignment by zero."); + markAsUsed(); this->value_ %= other; return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator%=(const SafeInt_t& other) { + if (other.get() == 0) throw std::domain_error("Modulus assignment by zero."); + markAsUsed(); this->value_ %= other.get(); return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator&=(const int_t& other) { + markAsUsed(); this->value_ &= other; return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator&=(const SafeInt_t& other) { + markAsUsed(); this->value_ &= other.get(); return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator|=(const int_t& other) { + markAsUsed(); this->value_ |= other; return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator|=(const SafeInt_t& other) { + markAsUsed(); this->value_ |= other.get(); return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator^=(const int_t& other) { + markAsUsed(); this->value_ ^= other; return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator^=(const SafeInt_t& other) { + markAsUsed(); this->value_ ^= other.get(); return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator<<=(const uint8_t& other) { + markAsUsed(); this->value_ <<= other; return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator>>=(const uint8_t& other) { + markAsUsed(); this->value_ >>= other; return *this; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator++() { + if (this->value_ == std::numeric_limits::max()) { + throw std::overflow_error("Overflow in prefix increment operation."); + } + markAsUsed(); ++(this->value_); return *this; +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator++(int) { + if (this->value_ == std::numeric_limits::max()) { + throw std::overflow_error("Overflow in postfix increment operation."); + } + markAsUsed(); SafeInt_t temp(this->value_); ++(this->value_); return temp; +} + +template requires IntInterval +SafeInt_t& SafeInt_t::operator--() { + if (this->value_ == std::numeric_limits::min()) { + throw std::underflow_error("Underflow in prefix decrement operation."); + } + markAsUsed(); --(this->value_); return *this; +} + +template requires IntInterval +SafeInt_t SafeInt_t::operator--(int) { + if (this->value_ == std::numeric_limits::min()) { + throw std::underflow_error("Underflow in postfix decrement operation."); + } + markAsUsed(); SafeInt_t temp(this->value_); --(this->value_); return temp; +} + diff --git a/src/contract/variables/safeint.h b/src/contract/variables/safeint.h index 58de79b3a..3639a4149 100644 --- a/src/contract/variables/safeint.h +++ b/src/contract/variables/safeint.h @@ -591,4 +591,38 @@ template class SafeInt_t : public SafeBase { } }; +// Aliases for SafeInt +using SafeInt8_t = SafeInt_t<8>; +using SafeInt16_t = SafeInt_t<16>; +using SafeInt24_t = SafeInt_t<24>; +using SafeInt32_t = SafeInt_t<32>; +using SafeInt40_t = SafeInt_t<40>; +using SafeInt48_t = SafeInt_t<48>; +using SafeInt56_t = SafeInt_t<56>; +using SafeInt64_t = SafeInt_t<64>; +using SafeInt72_t = SafeInt_t<72>; +using SafeInt80_t = SafeInt_t<80>; +using SafeInt88_t = SafeInt_t<88>; +using SafeInt96_t = SafeInt_t<96>; +using SafeInt104_t = SafeInt_t<104>; +using SafeInt112_t = SafeInt_t<112>; +using SafeInt120_t = SafeInt_t<120>; +using SafeInt128_t = SafeInt_t<128>; +using SafeInt136_t = SafeInt_t<136>; +using SafeInt144_t = SafeInt_t<144>; +using SafeInt152_t = SafeInt_t<152>; +using SafeInt160_t = SafeInt_t<160>; +using SafeInt168_t = SafeInt_t<168>; +using SafeInt176_t = SafeInt_t<176>; +using SafeInt184_t = SafeInt_t<184>; +using SafeInt192_t = SafeInt_t<192>; +using SafeInt200_t = SafeInt_t<200>; +using SafeInt208_t = SafeInt_t<208>; +using SafeInt216_t = SafeInt_t<216>; +using SafeInt224_t = SafeInt_t<224>; +using SafeInt232_t = SafeInt_t<232>; +using SafeInt240_t = SafeInt_t<240>; +using SafeInt248_t = SafeInt_t<248>; +using SafeInt256_t = SafeInt_t<256>; + #endif // SAFEINT_T_H diff --git a/src/contract/variables/safeuint.cpp b/src/contract/variables/safeuint.cpp new file mode 100644 index 000000000..c4446cdaa --- /dev/null +++ b/src/contract/variables/safeuint.cpp @@ -0,0 +1,549 @@ +#include "safeuint.h" + +// Explicit instantiations + +template class SafeUint_t<8>; +template class SafeUint_t<16>; +template class SafeUint_t<32>; +template class SafeUint_t<64>; + +template class SafeUint_t<24>; +template class SafeUint_t<40>; +template class SafeUint_t<48>; +template class SafeUint_t<56>; +template class SafeUint_t<72>; +template class SafeUint_t<80>; +template class SafeUint_t<88>; +template class SafeUint_t<96>; +template class SafeUint_t<104>; +template class SafeUint_t<112>; +template class SafeUint_t<120>; +template class SafeUint_t<128>; +template class SafeUint_t<136>; +template class SafeUint_t<144>; +template class SafeUint_t<152>; +template class SafeUint_t<160>; +template class SafeUint_t<168>; +template class SafeUint_t<176>; +template class SafeUint_t<184>; +template class SafeUint_t<192>; +template class SafeUint_t<200>; +template class SafeUint_t<208>; +template class SafeUint_t<216>; +template class SafeUint_t<224>; +template class SafeUint_t<232>; +template class SafeUint_t<240>; +template class SafeUint_t<248>; +template class SafeUint_t<256>; + +/// Biggest int type for dealing with uint/int operations +using int256_t = boost::multiprecision::number< + boost::multiprecision::cpp_int_backend< + 256, 256, boost::multiprecision::signed_magnitude, + boost::multiprecision::cpp_int_check_type::checked, void + > +>; + +// Class impl starts here + +template requires UintInterval +SafeUint_t SafeUint_t::operator+(const SafeUint_t& other) const { + if (this->value_ > std::numeric_limits::max() - other.value_) { + throw std::overflow_error("Overflow in addition operation."); + } + return SafeUint_t(this->value_ + other.value_); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator+(const uint_t& other) const { + if (this->value_ > std::numeric_limits::max() - other) { + throw std::overflow_error("Overflow in addition operation."); + } + return SafeUint_t(this->value_ + other); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator+(const int& other) const { + // uint/int operations require a conversion to a bigger int type, which will + // be operated on instead of the original value, then the remainder is checked + // to see if it fits back into the original. This is expected behaviour. + // We use int256_t as it is the biggest int type used within the project. + // Another option is to disable `checked` in the Boost types, but then we lose the + // intrinsic over/underflow checks and rely on Boost itself to do the conversion correctly. + // See https://www.boost.org/doc/libs/1_77_0/libs/multiprecision/doc/html/boost_multiprecision/tut/ints/cpp_int.html + auto tmp = static_cast(this->value_); + tmp = tmp + other; + if (tmp < 0) { + throw std::underflow_error("Underflow in addition operation."); + } else if (tmp > static_cast(std::numeric_limits::max())) { + throw std::overflow_error("Overflow in addition operation."); + } + return SafeUint_t(static_cast(tmp)); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator-(const SafeUint_t& other) const { + if (this->value_ < other.value_) throw std::underflow_error("Underflow in subtraction operation."); + return SafeUint_t(this->value_ - other.value_); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator-(const uint_t& other) const { + if (this->value_ < other) throw std::underflow_error("Underflow in subtraction operation."); + return SafeUint_t(this->value_ - other); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator-(const int& other) const { + // See operator+. + auto tmp = static_cast(this->value_); + tmp = tmp - other; + if (tmp < 0) { + throw std::underflow_error("Underflow in addition operation."); + } else if (tmp > static_cast(std::numeric_limits::max())) { + throw std::overflow_error("Overflow in addition operation."); + } + return SafeUint_t(static_cast(tmp)); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator*(const SafeUint_t& other) const { + if (other.value_ == 0 || this->value_ == 0) throw std::domain_error("Multiplication by zero"); + if (this->value_ > std::numeric_limits::max() / other.value_) { + throw std::overflow_error("Overflow in multiplication operation."); + } + return SafeUint_t(this->value_ * other.value_); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator*(const uint_t& other) const { + if (other == 0 || this->value_ == 0) throw std::domain_error("Multiplication by zero"); + if (this->value_ > std::numeric_limits::max() / other) { + throw std::overflow_error("Overflow in multiplication operation."); + } + return SafeUint_t(this->value_ * other); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator*(const int& other) const { + if (other == 0 || this->value_ == 0) throw std::domain_error("Multiplication by zero"); + if (other < 0) { + throw std::underflow_error("Underflow in multiplication operation."); + } else { + if (this->value_ > std::numeric_limits::max() / other) { + throw std::overflow_error("Overflow in multiplication operation."); + } + } + return SafeUint_t(this->value_ * other); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator/(const SafeUint_t& other) const { + if (this->value_ == 0 || other.value_ == 0) throw std::domain_error("Division by zero"); + return SafeUint_t(this->value_ / other.value_); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator/(const uint_t& other) const { + if (this->value_ == 0 || other == 0) throw std::domain_error("Division by zero"); + return SafeUint_t(this->value_ / other); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator/(const int& other) const { + if (other == 0) throw std::domain_error("Division by zero"); + // Division by a negative number results in a negative result, which cannot be represented in an unsigned integer. + if (other < 0) throw std::domain_error("Division by a negative number"); + return SafeUint_t(this->value_ / other); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator%(const SafeUint_t& other) const { + if (this->value_ == 0 || other.value_ == 0) throw std::domain_error("Modulus by zero"); + return SafeUint_t(this->value_ % other.value_); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator%(const uint_t& other) const { + if (this->value_ == 0 || other == 0) throw std::domain_error("Modulus by zero"); + return SafeUint_t(this->value_ % other); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator%(const int& other) const { + if (this->value_ == 0 || other == 0) throw std::domain_error("Modulus by zero"); + return SafeUint_t(this->value_ % static_cast(other)); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator&(const SafeUint_t& other) const { + return SafeUint_t(this->value_ & other.value_); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator&(const uint_t& other) const { + return SafeUint_t(this->value_ & other); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator&(const int& other) const { + if (other < 0) throw std::domain_error("Bitwise AND with a negative number"); + return SafeUint_t(this->value_ & static_cast(other)); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator|(const SafeUint_t& other) const { + return SafeUint_t(this->value_ | other.value_); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator|(const uint_t& other) const { + return SafeUint_t(this->value_ | other); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator|(const int& other) const { + if (other < 0) throw std::domain_error("Bitwise OR with a negative number"); + return SafeUint_t(this->value_ | static_cast(other)); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator^(const SafeUint_t& other) const { + return SafeUint_t(this->value_ ^ other.value_); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator^(const uint_t& other) const { + return SafeUint_t(this->value_ ^ other); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator^(const int& other) const { + if (other < 0) throw std::domain_error("Bitwise XOR with a negative number"); + return SafeUint_t(this->value_ ^ static_cast(other)); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator<<(const uint8_t& other) const { + return SafeUint_t(this->value_ << other); +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator>>(const uint8_t& other) const { + return SafeUint_t(this->value_ >> other); +} + +template requires UintInterval +bool SafeUint_t::operator!() const { return !(this->value_); } + +template requires UintInterval +bool SafeUint_t::operator&&(const SafeUint_t& other) const { return this->value_ && other.value_; } + +template requires UintInterval +bool SafeUint_t::operator&&(const uint_t& other) const { return this->value_ && other; } + +template requires UintInterval +bool SafeUint_t::operator||(const SafeUint_t& other) const { return this->value_ || other.value_; } + +template requires UintInterval +bool SafeUint_t::operator||(const uint_t& other) const { return this->value_ || other; } + +template requires UintInterval +bool SafeUint_t::operator==(const SafeUint_t& other) const { return this->value_ == other.value_; } + +template requires UintInterval +bool SafeUint_t::operator==(const uint_t& other) const { return this->value_ == other; } + +template requires UintInterval +bool SafeUint_t::operator==(const int& other) const { + if (other < 0) return false; // Unsigned value will never equal a negative + return this->value_ == static_cast(other); +} + +template requires UintInterval +bool SafeUint_t::operator!=(const SafeUint_t& other) const { return this->value_ != other.value_; } + +template requires UintInterval +bool SafeUint_t::operator!=(const uint_t& other) const { return this->value_ != other; } + +template requires UintInterval +bool SafeUint_t::operator!=(const int& other) const { + if (other < 0) return true; // Unsigned value will always differ from a negative + return this->value_ != static_cast(other); +} + +template requires UintInterval +bool SafeUint_t::operator<(const SafeUint_t& other) const { return this->value_ < other.value_; } + +template requires UintInterval +bool SafeUint_t::operator<(const uint_t& other) const { return this->value_ < other; } + +template requires UintInterval +bool SafeUint_t::operator<(const int& other) const { + if (other < 0) return false; // Unsigned value will never be less than a negative + return this->value_ < static_cast(other); +} + +template requires UintInterval +bool SafeUint_t::operator<=(const SafeUint_t& other) const { return this->value_ <= other.value_; } + +template requires UintInterval +bool SafeUint_t::operator<=(const uint_t& other) const { return this->value_ <= other; } + +template requires UintInterval +bool SafeUint_t::operator<=(const int& other) const { + if (other < 0) return false; // Unsigned value will never be less nor equal than a negative + return this->value_ <= static_cast(other); +} + +template requires UintInterval +bool SafeUint_t::operator>(const SafeUint_t& other) const { return this->value_ > other.value_; } + +template requires UintInterval +bool SafeUint_t::operator>(const uint_t& other) const { return this->value_ > other; } + +template requires UintInterval +bool SafeUint_t::operator>(const int& other) const { + if (other < 0) return true; // Unsigned value will always be more than a negative + return this->value_ > static_cast(other); +} + +template requires UintInterval +bool SafeUint_t::operator>=(const SafeUint_t& other) const { return this->value_ >= other.value_; } + +template requires UintInterval +bool SafeUint_t::operator>=(const uint_t& other) const { return this->value_ >= other; } + +template requires UintInterval +bool SafeUint_t::operator>=(const int& other) const { + if (other < 0) return true; // Unsigned value will be never equal, but always more than a negative + return this->value_ >= static_cast(other); +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator=(const SafeUint_t& other) { + markAsUsed(); this->value_ = other.value_; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator=(const uint_t& other) { + markAsUsed(); this->value_ = other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator=(const int& other) { + if (other < 0) throw std::domain_error("Cannot assign negative value to SafeUint_t"); + markAsUsed(); this->value_ = static_cast(other); return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator+=(const SafeUint_t& other) { + if (this->value_ > std::numeric_limits::max() - other.value_) { + throw std::overflow_error("Overflow in addition assignment operation."); + } + markAsUsed(); this->value_ += other.value_; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator+=(const uint_t& other) { + if (this->value_ > std::numeric_limits::max() - other) { + throw std::overflow_error("Overflow in addition assignment operation."); + } + markAsUsed(); this->value_ += other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator+=(const int& other) { + // See operator+. + auto tmp = static_cast(this->value_); + tmp += other; + if (tmp < 0) { + throw std::underflow_error("Underflow in addition assignment operation."); + } else if (tmp > static_cast(std::numeric_limits::max())) { + throw std::overflow_error("Overflow in addition assignment operation."); + } + markAsUsed(); this->value_ = static_cast(tmp); return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator-=(const SafeUint_t& other) { + if (this->value_ < other.value_) throw std::underflow_error("Underflow in subtraction assignment operation."); + markAsUsed(); this->value_ -= other.value_; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator-=(const uint_t& other) { + if (this->value_ < other) throw std::underflow_error("Underflow in subtraction assignment operation."); + markAsUsed(); this->value_ -= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator-=(const int& other) { + // See operator+. + auto tmp = static_cast(this->value_); + tmp -= other; + if (tmp < 0) { + throw std::underflow_error("Underflow in addition assignment operation."); + } else if (tmp > static_cast(std::numeric_limits::max())) { + throw std::overflow_error("Overflow in addition assignment operation."); + } + markAsUsed(); this->value_ = static_cast(tmp); return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator*=(const SafeUint_t& other) { + if (other.value_ == 0 || this->value_ == 0) throw std::domain_error("Multiplication assignment by zero"); + if (this->value_ > std::numeric_limits::max() / other.value_) { + throw std::overflow_error("Overflow in multiplication assignment operation."); + } + markAsUsed(); this->value_ *= other.value_; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator*=(const uint_t& other) { + if (other == 0 || this->value_ == 0) throw std::domain_error("Multiplication assignment by zero"); + if (this->value_ > std::numeric_limits::max() / other) { + throw std::overflow_error("Overflow in multiplication assignment operation."); + } + markAsUsed(); this->value_ *= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator*=(const int& other) { + if (other == 0 || this->value_ == 0) throw std::domain_error("Multiplication assignment by zero"); + if (other < 0) { + throw std::underflow_error("Underflow in multiplication assignment operation."); + } else { + if (this->value_ > std::numeric_limits::max() / other) { + throw std::overflow_error("Overflow in multiplication assignment operation."); + } + } + markAsUsed(); this->value_ *= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator/=(const SafeUint_t& other) { + if (this->value_ == 0 || other.value_ == 0) throw std::domain_error("Division assignment by zero"); + markAsUsed(); this->value_ /= other.value_; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator/=(const uint_t& other) { + if (this->value_ == 0 || other == 0) throw std::domain_error("Division assignment by zero"); + markAsUsed(); this->value_ /= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator/=(const int& other) { + if (other == 0) throw std::domain_error("Division assignment by zero"); + // Division by a negative number results in a negative result, which cannot be represented in an unsigned integer. + if (other < 0) throw std::domain_error("Division assignment by a negative number"); + markAsUsed(); this->value_ /= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator%=(const SafeUint_t& other) { + if (this->value_ == 0 || other.value_ == 0) throw std::domain_error("Modulus assignment by zero"); + markAsUsed(); this->value_ %= other.value_; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator%=(const uint_t& other) { + if (this->value_ == 0 || other == 0) throw std::domain_error("Modulus assignment by zero"); + markAsUsed(); this->value_ %= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator%=(const int& other) { + if (this->value_ == 0 || other == 0) throw std::domain_error("Modulus assignment by zero"); + markAsUsed(); this->value_ %= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator&=(const SafeUint_t& other) { + markAsUsed(); this->value_ &= other.value_; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator&=(const uint_t& other) { + markAsUsed(); this->value_ &= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator&=(const int& other) { + if (other < 0) throw std::domain_error("Bitwise AND assignment with a negative value"); + markAsUsed(); this->value_ &= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator|=(const SafeUint_t& other) { + markAsUsed(); this->value_ |= other.value_; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator|=(const uint_t& other) { + markAsUsed(); this->value_ |= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator|=(const int& other) { + if (other < 0) throw std::domain_error("Bitwise OR assignment with a negative value"); + markAsUsed(); this->value_ |= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator^=(const SafeUint_t& other) { + markAsUsed(); this->value_ ^= other.value_; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator^=(const uint_t& other) { + markAsUsed(); this->value_ ^= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator^=(const int& other) { + if (other < 0) throw std::domain_error("Bitwise XOR assignment with a negative value."); + markAsUsed(); this->value_ ^= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator<<=(const uint8_t& other) { + markAsUsed(); this->value_ <<= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator>>=(const uint8_t& other) { + markAsUsed(); this->value_ >>= other; return *this; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator++() { + if (this->value_ == std::numeric_limits::max()) { + throw std::overflow_error("Overflow in prefix increment operation."); + } + markAsUsed(); ++(this->value_); return *this; +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator++(int) { + if (this->value_ == std::numeric_limits::max()) { + throw std::overflow_error("Overflow in postfix increment operation."); + } + SafeUint_t tmp(this->value_); + markAsUsed(); ++(this->value_); return tmp; +} + +template requires UintInterval +SafeUint_t& SafeUint_t::operator--() { + if (this->value_ == 0) throw std::underflow_error("Underflow in prefix decrement operation."); + markAsUsed(); --(this->value_); return *this; +} + +template requires UintInterval +SafeUint_t SafeUint_t::operator--(int) { + if (this->value_ == 0) throw std::underflow_error("Underflow in postfix decrement operation."); + SafeUint_t tmp(this->value_); + markAsUsed(); --(this->value_); return tmp; +} + diff --git a/src/contract/variables/safeuint.h b/src/contract/variables/safeuint.h index 9c18b7ff9..9c6c1c1e7 100644 --- a/src/contract/variables/safeuint.h +++ b/src/contract/variables/safeuint.h @@ -709,4 +709,38 @@ template class SafeUint_t : public SafeBase { } }; +// Aliases for SafeUint +using SafeUint8_t = SafeUint_t<8>; +using SafeUint16_t = SafeUint_t<16>; +using SafeUint24_t = SafeUint_t<24>; +using SafeUint32_t = SafeUint_t<32>; +using SafeUint40_t = SafeUint_t<40>; +using SafeUint48_t = SafeUint_t<48>; +using SafeUint56_t = SafeUint_t<56>; +using SafeUint64_t = SafeUint_t<64>; +using SafeUint72_t = SafeUint_t<72>; +using SafeUint80_t = SafeUint_t<80>; +using SafeUint88_t = SafeUint_t<88>; +using SafeUint96_t = SafeUint_t<96>; +using SafeUint104_t = SafeUint_t<104>; +using SafeUint112_t = SafeUint_t<112>; +using SafeUint120_t = SafeUint_t<120>; +using SafeUint128_t = SafeUint_t<128>; +using SafeUint136_t = SafeUint_t<136>; +using SafeUint144_t = SafeUint_t<144>; +using SafeUint152_t = SafeUint_t<152>; +using SafeUint160_t = SafeUint_t<160>; +using SafeUint168_t = SafeUint_t<168>; +using SafeUint176_t = SafeUint_t<176>; +using SafeUint184_t = SafeUint_t<184>; +using SafeUint192_t = SafeUint_t<192>; +using SafeUint200_t = SafeUint_t<200>; +using SafeUint208_t = SafeUint_t<208>; +using SafeUint216_t = SafeUint_t<216>; +using SafeUint224_t = SafeUint_t<224>; +using SafeUint232_t = SafeUint_t<232>; +using SafeUint240_t = SafeUint_t<240>; +using SafeUint248_t = SafeUint_t<248>; +using SafeUint256_t = SafeUint_t<256>; + #endif // SAFEUINT_T_H diff --git a/src/core/blockchain.cpp b/src/core/blockchain.cpp index e1927c8c2..aafd90296 100644 --- a/src/core/blockchain.cpp +++ b/src/core/blockchain.cpp @@ -7,8 +7,6 @@ See the LICENSE.txt file in the project root for more information. #include "blockchain.h" -#include "../utils/logger.h" - Blockchain::Blockchain(const std::string& blockchainPath) : options_(Options::fromFile(blockchainPath)), p2p_(options_.getP2PIp(), options_, storage_, state_), diff --git a/src/core/blockchain.h b/src/core/blockchain.h index 4de039c41..a98e69d5f 100644 --- a/src/core/blockchain.h +++ b/src/core/blockchain.h @@ -8,17 +8,10 @@ See the LICENSE.txt file in the project root for more information. #ifndef BLOCKCHAIN_H #define BLOCKCHAIN_H -#include "consensus.h" -#include "storage.h" -#include "state.h" -#include "rdpos.h" -#include "state.h" - -#include "../net/p2p/managerbase.h" -#include "../net/p2p/nodeconns.h" +//#include "../net/p2p/managerbase.h" // TODO: find out where this is coming from #include "../net/http/httpserver.h" -#include "../utils/options.h" -#include "../utils/db.h" + +#include "consensus.h" // state.h -> rdpos.h -> (utils/tx.h -> ecdsa.h -> utils.h -> logger.h), (dump.h -> utils/db.h, storage.h -> options.h) /** * Helper class that syncs the node with other nodes in the network. @@ -34,8 +27,9 @@ class Syncer : public Log::LogicalLocationProvider { public: /** * Constructor. - * @param nodeConns Reference to the NodeConns object. - * @param storage Reference to the blockchain storage. + * @param p2p Reference to the P2P::ManagerNormal object. + * @param storage Reference to the blockchain storage object. + * @param state Reference to the blockchain state object. */ explicit Syncer(P2P::ManagerNormal& p2p, const Storage& storage, State& state) : p2p_(p2p), storage_(storage), state_(state) {} diff --git a/src/core/consensus.cpp b/src/core/consensus.cpp index d343af89b..fa82139d6 100644 --- a/src/core/consensus.cpp +++ b/src/core/consensus.cpp @@ -6,7 +6,6 @@ See the LICENSE.txt file in the project root for more information. */ #include "consensus.h" -#include "blockchain.h" void Consensus::validatorLoop() { LOGINFO("Starting validator loop."); diff --git a/src/core/consensus.h b/src/core/consensus.h index 3a72b6dcf..09ee503ea 100644 --- a/src/core/consensus.h +++ b/src/core/consensus.h @@ -8,16 +8,11 @@ See the LICENSE.txt file in the project root for more information. #ifndef CONSENSUS_H #define CONSENSUS_H -#include +// TODO: find out where those are coming from +//#include +//#include "../utils/tx.h" -#include "rdpos.h" - -#include "../utils/ecdsa.h" -#include "../utils/logger.h" -#include "../utils/strings.h" -#include "../utils/tx.h" - -class Blockchain; // Forward declaration. +#include "state.h" // rdpos.h -> utils/tx.h -> ecdsa.h -> utils.h -> strings.h, logger.h, (libs/json.hpp -> boost/unordered/unordered_flat_map.hpp) // TODO: tests for Consensus (if necessary) diff --git a/src/core/dump.cpp b/src/core/dump.cpp index eb3ae2e18..ab985c5a0 100644 --- a/src/core/dump.cpp +++ b/src/core/dump.cpp @@ -6,7 +6,6 @@ See the LICENSE.txt file in the project root for more information. */ #include "dump.h" -#include "../contract/event.h" DumpManager::DumpManager( const Storage& storage, const Options& options, std::shared_mutex& stateMutex diff --git a/src/core/dump.h b/src/core/dump.h index e3a694eac..80a054a08 100644 --- a/src/core/dump.h +++ b/src/core/dump.h @@ -8,15 +8,13 @@ See the LICENSE.txt file in the project root for more information. #ifndef DUMP_H #define DUMP_H -#include -#include -#include -#include -#include +//TODO: find out where those are coming from +//#include +//#include +//#include #include -#include "storage.h" -#include "../utils/db.h" +#include "storage.h" // utils/db.h, ... -> utils.h -> libs/json.hpp -> functional, vector /// Abstraction of a dumpable object (an object that can be dumped to the database). class Dumpable { diff --git a/src/core/rdpos.cpp b/src/core/rdpos.cpp index 7b7c49adb..94f9423d1 100644 --- a/src/core/rdpos.cpp +++ b/src/core/rdpos.cpp @@ -6,9 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "rdpos.h" -#include "storage.h" -#include "state.h" -#include "../contract/contractmanager.h" + +#include "../utils/uintconv.h" rdPoS::rdPoS( const DB& db, DumpManager& dumpManager, const Storage& storage, @@ -278,7 +277,7 @@ DBBatch rdPoS::dump() const uint64_t i = 0; // add batch operations for (const auto &validator : this->validators_) { - dbBatch.push_back(Utils::uint64ToBytes(i), validator, DBPrefix::rdPoS); + dbBatch.push_back(UintConv::uint64ToBytes(i), validator, DBPrefix::rdPoS); i++; } return dbBatch; diff --git a/src/core/rdpos.h b/src/core/rdpos.h index 89946a6a6..dec001170 100644 --- a/src/core/rdpos.h +++ b/src/core/rdpos.h @@ -8,23 +8,17 @@ See the LICENSE.txt file in the project root for more information. #ifndef RDPOS_H #define RDPOS_H -#include "../contract/contract.h" -#include "../utils/strings.h" -#include "../utils/tx.h" -#include "../utils/safehash.h" -#include "../utils/randomgen.h" -#include "../utils/options.h" -#include "../net/p2p/managernormal.h" - -#include -#include #include -#include + +#include "../utils/tx.h" // ecdsa.h -> utils.h -> strings.h, (libs/json.hpp -> boost/unordered/unordered_flat_map.hpp) + +#include "../contract/contract.h" // dump.h -> storage.h -> safehash.h, randomgen.h, options.h + +#include "../net/p2p/managernormal.h" // Forward declarations. class rdPoS; class Storage; -class State; // "0x6fc5a2d6" -> Function for random tx // "0xcfffe746" -> Function for random hash tx @@ -78,7 +72,7 @@ class rdPoS : public BaseContract, public Log::LogicalLocationProvider { * @return `true` if tx data is valid, `false` otherwise. */ bool validateBlockTxSanityCheck(const TxValidator& hashTx, const TxValidator& seedTx) const; - + public: /// Enum for Validator transaction functions. enum class TxValidatorFunction { INVALID, RANDOMHASH, RANDOMSEED }; diff --git a/src/core/state.cpp b/src/core/state.cpp index 0b5a07e53..bab094915 100644 --- a/src/core/state.cpp +++ b/src/core/state.cpp @@ -5,9 +5,13 @@ This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. */ -#include "state.h" #include -#include "../contract/contracthost.h" + +#include "state.h" + +#include "../contract/contracthost.h" // contractmanager.h + +#include "../utils/uintconv.h" State::State( const DB& db, @@ -207,19 +211,19 @@ void State::processTransaction( } try { evmc_tx_context txContext; - txContext.tx_gas_price = Utils::uint256ToEvmcUint256(tx.getMaxFeePerGas()); + txContext.tx_gas_price = EVMCConv::uint256ToEvmcUint256(tx.getMaxFeePerGas()); txContext.tx_origin = tx.getFrom().toEvmcAddress(); txContext.block_coinbase = ContractGlobals::getCoinbase().toEvmcAddress(); txContext.block_number = ContractGlobals::getBlockHeight(); txContext.block_timestamp = ContractGlobals::getBlockTimestamp(); txContext.block_gas_limit = 10000000; txContext.block_prev_randao = {}; - txContext.chain_id = Utils::uint256ToEvmcUint256(this->options_.getChainID()); + txContext.chain_id = EVMCConv::uint256ToEvmcUint256(this->options_.getChainID()); txContext.block_base_fee = {}; txContext.blob_base_fee = {}; txContext.blob_hashes = nullptr; txContext.blob_hashes_count = 0; - Hash randomSeed(Utils::uint256ToBytes((randomnessHash.toUint256() + txIndex))); + Hash randomSeed(UintConv::uint256ToBytes((randomnessHash.toUint256() + txIndex))); ContractHost host( this->vm_, this->dumpManager_, @@ -451,7 +455,7 @@ Bytes State::ethCall(const evmc_message& callInfo) { txContext.block_timestamp = static_cast(ContractGlobals::getBlockTimestamp()); txContext.block_gas_limit = 10000000; txContext.block_prev_randao = {}; - txContext.chain_id = Utils::uint256ToEvmcUint256(this->options_.getChainID()); + txContext.chain_id = EVMCConv::uint256ToEvmcUint256(this->options_.getChainID()); txContext.block_base_fee = {}; txContext.blob_base_fee = {}; txContext.blob_hashes = nullptr; diff --git a/src/core/state.h b/src/core/state.h index 811b02f05..4a6cf2854 100644 --- a/src/core/state.h +++ b/src/core/state.h @@ -8,18 +8,10 @@ See the LICENSE.txt file in the project root for more information. #ifndef STATE_H #define STATE_H -#include -#include - -#include "../utils/db.h" -#include "../utils/logger.h" -#include "../utils/utils.h" #include "../contract/contract.h" -#include "../contract/contractmanager.h" -#include "storage.h" -#include "rdpos.h" -#include "dump.h" +#include "rdpos.h" // set, boost/unordered/unordered_flat_map.hpp +#include "dump.h" // utils/db.h, storage.h -> utils/randomgen.h -> utils.h -> logger.h, (strings.h -> evmc/evmc.hpp), (libs/json.hpp -> boost/unordered/unordered_flat_map.hpp) // TODO: We could possibly change the bool functions into an enum function, // to be able to properly return each error case. We need this in order to slash invalid rdPoS blocks. diff --git a/src/core/storage.cpp b/src/core/storage.cpp index e36a1577f..f7bec6e17 100644 --- a/src/core/storage.cpp +++ b/src/core/storage.cpp @@ -5,10 +5,10 @@ This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. */ -#include - #include "storage.h" +#include "../utils/uintconv.h" + static bool topicsMatch(const Event& event, const std::vector& topics) { if (topics.empty()) return true; // No topic filter applied const std::vector& eventTopics = event.getTopics(); @@ -20,14 +20,14 @@ static bool topicsMatch(const Event& event, const std::vector& topics) { static void storeBlock(DB& db, const FinalizedBlock& block, bool indexingEnabled) { DBBatch batch; batch.push_back(block.getHash(), block.serializeBlock(), DBPrefix::blocks); - batch.push_back(Utils::uint64ToBytes(block.getNHeight()), block.getHash(), DBPrefix::heightToBlock); + batch.push_back(UintConv::uint64ToBytes(block.getNHeight()), block.getHash(), DBPrefix::heightToBlock); if (indexingEnabled) { const auto& Txs = block.getTxs(); for (uint32_t i = 0; i < Txs.size(); i++) { const auto& TxHash = Txs[i].hash(); const FixedBytes<44> value( - bytes::join(block.getHash(), Utils::uint32ToBytes(i), Utils::uint64ToBytes(block.getNHeight())) + bytes::join(block.getHash(), UintConv::uint32ToBytes(i), UintConv::uint64ToBytes(block.getNHeight())) ); batch.push_back(TxHash, value, DBPrefix::txToBlock); } @@ -71,7 +71,7 @@ void Storage::initializeBlockchain() { } // Sanity check for genesis block. (check if genesis in DB matches genesis in Options) - const Hash genesisInDBHash(blocksDb_.get(Utils::uint64ToBytes(0), DBPrefix::heightToBlock)); + const Hash genesisInDBHash(blocksDb_.get(UintConv::uint64ToBytes(0), DBPrefix::heightToBlock)); FinalizedBlock genesisInDB = FinalizedBlock::fromBytes( blocksDb_.get(genesisInDBHash, DBPrefix::blocks), options_.getChainID() @@ -88,11 +88,11 @@ TxBlock Storage::getTxFromBlockWithIndex(bytes::View blockData, uint64_t txIndex // Count txs until index. uint64_t currentTx = 0; while (currentTx < txIndex) { - uint32_t txSize = Utils::bytesToUint32(blockData.subspan(index, 4)); + uint32_t txSize = UintConv::bytesToUint32(blockData.subspan(index, 4)); index += txSize + 4; currentTx++; } - uint64_t txSize = Utils::bytesToUint32(blockData.subspan(index, 4)); + uint64_t txSize = UintConv::bytesToUint32(blockData.subspan(index, 4)); index += 4; return TxBlock(blockData.subspan(index, txSize), this->options_.getChainID()); } @@ -108,7 +108,7 @@ void Storage::pushBlock(FinalizedBlock block) { bool Storage::blockExists(const Hash& hash) const { return blocksDb_.has(hash, DBPrefix::blocks); } -bool Storage::blockExists(uint64_t height) const { return blocksDb_.has(Utils::uint64ToBytes(height), DBPrefix::heightToBlock); } +bool Storage::blockExists(uint64_t height) const { return blocksDb_.has(UintConv::uint64ToBytes(height), DBPrefix::heightToBlock); } bool Storage::txExists(const Hash& tx) const { return blocksDb_.has(tx, DBPrefix::txToBlock); } @@ -119,7 +119,7 @@ std::shared_ptr Storage::getBlock(const Hash& hash) const } std::shared_ptr Storage::getBlock(uint64_t height) const { - Bytes blockHash = blocksDb_.get(Utils::uint64ToBytes(height), DBPrefix::heightToBlock); + Bytes blockHash = blocksDb_.get(UintConv::uint64ToBytes(height), DBPrefix::heightToBlock); if (blockHash.empty()) return nullptr; Bytes blockBytes = blocksDb_.get(blockHash, DBPrefix::blocks); return std::make_shared(FinalizedBlock::fromBytes(blockBytes, this->options_.getChainID())); @@ -133,8 +133,8 @@ std::tuple< const bytes::View txDataView = txData; const Hash blockHash(txDataView.subspan(0, 32)); - const uint64_t blockIndex = Utils::bytesToUint32(txDataView.subspan(32, 4)); - const uint64_t blockHeight = Utils::bytesToUint64(txDataView.subspan(36, 8)); + const uint64_t blockIndex = UintConv::bytesToUint32(txDataView.subspan(32, 4)); + const uint64_t blockHeight = UintConv::bytesToUint64(txDataView.subspan(36, 8)); const Bytes blockData = blocksDb_.get(blockHash, DBPrefix::blocks); return std::make_tuple( @@ -149,7 +149,7 @@ std::tuple< const Bytes blockData = blocksDb_.get(blockHash, DBPrefix::blocks); if (blockData.empty()) std::make_tuple(nullptr, Hash(), 0u, 0u); - const uint64_t blockHeight = Utils::bytesToUint64(bytes::View(blockData).subspan(201, 8)); + const uint64_t blockHeight = UintConv::bytesToUint64(bytes::View(blockData).subspan(201, 8)); return std::make_tuple( std::make_shared(getTxFromBlockWithIndex(blockData, blockIndex)), blockHash, blockIndex, blockHeight @@ -159,7 +159,7 @@ std::tuple< std::tuple< const std::shared_ptr, const Hash, const uint64_t, const uint64_t > Storage::getTxByBlockNumberAndIndex(uint64_t blockHeight, uint64_t blockIndex) const { - const Bytes blockHash = blocksDb_.get(Utils::uint64ToBytes(blockHeight), DBPrefix::heightToBlock); + const Bytes blockHash = blocksDb_.get(UintConv::uint64ToBytes(blockHeight), DBPrefix::heightToBlock); if (blockHash.empty()) return std::make_tuple(nullptr, Hash(), 0u, 0u); const Bytes blockData = blocksDb_.get(blockHash, DBPrefix::blocks); @@ -216,19 +216,16 @@ std::optional Storage::getTxAdditionalData(const Hash& txHash) void Storage::putEvent(const Event& event) { const Bytes key = Utils::makeBytes(bytes::join( - Utils::uint64ToBytes(event.getBlockIndex()), - Utils::uint64ToBytes(event.getTxIndex()), - Utils::uint64ToBytes(event.getLogIndex()), + UintConv::uint64ToBytes(event.getBlockIndex()), + UintConv::uint64ToBytes(event.getTxIndex()), + UintConv::uint64ToBytes(event.getLogIndex()), event.getAddress() )); - eventsDb_.put(key, Utils::stringToBytes(event.serializeToJson()), DBPrefix::events); } std::vector Storage::getEvents(uint64_t fromBlock, uint64_t toBlock, const Address& address, const std::vector& topics) const { - if (toBlock < fromBlock) { - std::swap(fromBlock, toBlock); - } + if (toBlock < fromBlock) std::swap(fromBlock, toBlock); if (uint64_t count = toBlock - fromBlock + 1; count > options_.getEventBlockCap()) { throw std::out_of_range( @@ -240,52 +237,35 @@ std::vector Storage::getEvents(uint64_t fromBlock, uint64_t toBlock, cons std::vector events; std::vector keys; - const Bytes startBytes = Utils::makeBytes(Utils::uint64ToBytes(fromBlock)); - const Bytes endBytes = Utils::makeBytes(Utils::uint64ToBytes(toBlock)); + const Bytes startBytes = Utils::makeBytes(UintConv::uint64ToBytes(fromBlock)); + const Bytes endBytes = Utils::makeBytes(UintConv::uint64ToBytes(toBlock)); for (Bytes key : eventsDb_.getKeys(DBPrefix::events, startBytes, endBytes)) { - uint64_t nHeight = Utils::bytesToUint64(Utils::create_view_span(key, 0, 8)); + uint64_t nHeight = UintConv::bytesToUint64(Utils::create_view_span(key, 0, 8)); Address currentAddress(Utils::create_view_span(key, 24, 20)); - - if (fromBlock > nHeight || toBlock < nHeight) { - continue; - } - - if (address == currentAddress || address == Address()) { - keys.push_back(std::move(key)); - } + if (fromBlock > nHeight || toBlock < nHeight) continue; + if (address == currentAddress || address == Address()) keys.push_back(std::move(key)); } for (DBEntry item : eventsDb_.getBatch(DBPrefix::events, keys)) { - if (events.size() >= options_.getEventLogCap()) { - break; - } - + if (events.size() >= options_.getEventLogCap()) break; Event event(Utils::bytesToString(item.value)); - - if (topicsMatch(event, topics)) { - events.push_back(std::move(event)); - } + if (topicsMatch(event, topics)) events.push_back(std::move(event)); } - return events; } std::vector Storage::getEvents(uint64_t blockIndex, uint64_t txIndex) const { - std::vector events; - + std::vector events; for ( Bytes fetchBytes = Utils::makeBytes(bytes::join( - DBPrefix::events, Utils::uint64ToBytes(blockIndex), Utils::uint64ToBytes(txIndex) + DBPrefix::events, UintConv::uint64ToBytes(blockIndex), UintConv::uint64ToBytes(txIndex) )); DBEntry entry : eventsDb_.getBatch(fetchBytes) ) { - if (events.size() >= options_.getEventLogCap()) { - break; - } - + if (events.size() >= options_.getEventLogCap()) break; events.emplace_back(Utils::bytesToString(entry.value)); } - return events; } + diff --git a/src/core/storage.h b/src/core/storage.h index fdd7e6217..d4eb289ae 100644 --- a/src/core/storage.h +++ b/src/core/storage.h @@ -8,18 +8,15 @@ See the LICENSE.txt file in the project root for more information. #ifndef STORAGE_H #define STORAGE_H -#include +//#include // TODO: find out where this is coming from #include "../utils/db.h" -#include "../utils/ecdsa.h" -#include "../utils/randomgen.h" -#include "../utils/safehash.h" -#include "../utils/utils.h" +#include "../utils/randomgen.h" // utils.h +#include "../utils/safehash.h" // tx.h -> ecdsa.h -> utils.h -> bytes/join.h, strings.h -> libs/zpp_bits.h #include "../utils/options.h" + #include "../contract/calltracer.h" #include "../contract/event.h" -#include "../libs/zpp_bits.h" -#include "../bytes/join.h" /** * Abstraction of the blockchain history. diff --git a/src/net/http/httpclient.cpp b/src/net/http/httpclient.cpp index 4ef3b36cf..4d4032feb 100644 --- a/src/net/http/httpclient.cpp +++ b/src/net/http/httpclient.cpp @@ -1,5 +1,14 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #include "httpclient.h" +#include "../utils/dynamicexception.h" + HTTPSyncClient::HTTPSyncClient(const std::string& host, const std::string& port) : host(host), port(port), resolver(ioc), stream(ioc) { this->connect(); } diff --git a/src/net/http/httpclient.h b/src/net/http/httpclient.h index a325dcb9f..6e5061ace 100644 --- a/src/net/http/httpclient.h +++ b/src/net/http/httpclient.h @@ -1,15 +1,18 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #ifndef HTTPCLIENT_H #define HTTPCLIENT_H -#include -#include -#include +#include // tcp_stream.hpp -> asio/ip/tcp.hpp #include #include #include -#include "../utils/dynamicexception.h" - namespace beast = boost::beast; // from namespace http = beast::http; // from namespace websocket = beast::websocket; // from diff --git a/src/net/http/httplistener.h b/src/net/http/httplistener.h index 8f4f8eb15..c42c32be9 100644 --- a/src/net/http/httplistener.h +++ b/src/net/http/httplistener.h @@ -8,8 +8,7 @@ See the LICENSE.txt file in the project root for more information. #ifndef HTTPLISTENER_H #define HTTPLISTENER_H -#include "httpparser.h" -#include "httpsession.h" +#include "httpsession.h" // httpparser.h /// Class for listening to, accepting and dispatching incoming connections/sessions. class HTTPListener : public std::enable_shared_from_this { diff --git a/src/net/http/httpparser.cpp b/src/net/http/httpparser.cpp index b6c1dabd9..3cb033951 100644 --- a/src/net/http/httpparser.cpp +++ b/src/net/http/httpparser.cpp @@ -6,6 +6,7 @@ See the LICENSE.txt file in the project root for more information. */ #include "httpparser.h" + #include "jsonrpc/call.h" std::string parseJsonRpcRequest( diff --git a/src/net/http/httpparser.h b/src/net/http/httpparser.h index 30e92cedc..f3127bd5a 100644 --- a/src/net/http/httpparser.h +++ b/src/net/http/httpparser.h @@ -8,41 +8,24 @@ See the LICENSE.txt file in the project root for more information. #ifndef HTTPPARSER_H #define HTTPPARSER_H -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include +// TODO: probably not used but not sure, leaving it here for now +//#include +//#include +//#include + +// Those are all also included by asio.hpp #include #include #include #include #include + #include #include #include #include -#include -#include -#include -#include -#include - -#include -#include -#include -#include "../utils/utils.h" +// finalizedblock.h -> merkle.h -> tx.h -> ecdsa.h -> utils.h -> libs/json.hpp -> algorithm, memory, string, vector #include "../utils/options.h" namespace beast = boost::beast; // from diff --git a/src/net/http/httpserver.cpp b/src/net/http/httpserver.cpp index fce50e15a..cc623060f 100644 --- a/src/net/http/httpserver.cpp +++ b/src/net/http/httpserver.cpp @@ -6,7 +6,6 @@ See the LICENSE.txt file in the project root for more information. */ #include "httpserver.h" -#include "../p2p/managernormal.h" std::string HTTPServer::getLogicalLocation() const { return p2p_.getLogicalLocation(); } diff --git a/src/net/http/httpserver.h b/src/net/http/httpserver.h index fab0e17eb..53b0f2ee4 100644 --- a/src/net/http/httpserver.h +++ b/src/net/http/httpserver.h @@ -8,8 +8,9 @@ See the LICENSE.txt file in the project root for more information. #ifndef HTTPSERVER_H #define HTTPSERVER_H -#include "httpparser.h" -#include "httplistener.h" +#include "httplistener.h" // httpsession.h -> httpparser.h + +#include "../p2p/managernormal.h" /// Abstraction of an HTTP server. class HTTPServer : public Log::LogicalLocationProvider { diff --git a/src/net/http/jsonrpc/blocktag.cpp b/src/net/http/jsonrpc/blocktag.cpp index a3b2608bf..6bb5c6f0b 100644 --- a/src/net/http/jsonrpc/blocktag.cpp +++ b/src/net/http/jsonrpc/blocktag.cpp @@ -1,5 +1,11 @@ -#include "blocktag.h" -#include "error.h" +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#include "blocktag.h" // parser.h -> error.h /** * Helper type for std::visit. @@ -8,12 +14,10 @@ template struct Overloaded : Ts... { using Ts::operator()...; }; - /// Explicit deduction guide template Overloaded(Ts...) -> Overloaded; - namespace jsonrpc { bool BlockTagOrNumber::isLatest(const Storage& storage) const { diff --git a/src/net/http/jsonrpc/blocktag.h b/src/net/http/jsonrpc/blocktag.h index 84e32e9f5..cd594a76b 100644 --- a/src/net/http/jsonrpc/blocktag.h +++ b/src/net/http/jsonrpc/blocktag.h @@ -1,3 +1,10 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #ifndef JSONRPC_BLOCKTAG_H #define JSONRPC_BLOCKTAG_H @@ -5,7 +12,6 @@ namespace jsonrpc { - /// @brief used to identify blocks using tags enum class BlockTag { LATEST, diff --git a/src/net/http/jsonrpc/call.cpp b/src/net/http/jsonrpc/call.cpp index ddb135022..5c91dfe06 100644 --- a/src/net/http/jsonrpc/call.cpp +++ b/src/net/http/jsonrpc/call.cpp @@ -1,3 +1,10 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #include "call.h" #include "methods.h" diff --git a/src/net/http/jsonrpc/call.h b/src/net/http/jsonrpc/call.h index f3189e75b..25d345f2f 100644 --- a/src/net/http/jsonrpc/call.h +++ b/src/net/http/jsonrpc/call.h @@ -1,9 +1,17 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #ifndef JSONRPC_CALL_H #define JSONRPC_CALL_H -#include "variadicparser.h" #include "../../p2p/managernormal.h" +#include "variadicparser.h" // parser.h -> utils/utils.h -> libs/json.hpp + namespace jsonrpc { /// @brief process a json RPC call diff --git a/src/net/http/jsonrpc/error.h b/src/net/http/jsonrpc/error.h index 874592e24..8a54a14c1 100644 --- a/src/net/http/jsonrpc/error.h +++ b/src/net/http/jsonrpc/error.h @@ -1,8 +1,15 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #ifndef JSONRPC_ERROR_H #define JSONRPC_ERROR_H -#include #include +#include namespace jsonrpc { diff --git a/src/net/http/jsonrpc/methods.cpp b/src/net/http/jsonrpc/methods.cpp index ab1876dca..fb0556f59 100644 --- a/src/net/http/jsonrpc/methods.cpp +++ b/src/net/http/jsonrpc/methods.cpp @@ -1,11 +1,18 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #include "methods.h" #include "blocktag.h" -#include "variadicparser.h" -#include "../../../core/storage.h" -#include "../../../core/state.h" +#include "variadicparser.h" // parser.h -> ranges, utils/utils.h -> libs/json.hpp + +#include "../../../utils/evmcconv.h" -#include +#include "../../../core/state.h" // dump.h -> utils/db.h, storage.h static inline constexpr std::string_view FIXED_BASE_FEE_PER_GAS = "0x9502f900"; // Fixed to 2.5 GWei @@ -120,7 +127,7 @@ static std::pair parseEvmcMessage(const json& request, cons parseIfExists(txJson, "gasPrice"); // gas price ignored as chain is fixed at 1 GWEI msg.value = parseIfExists(txJson, "value") - .transform([] (uint64_t val) { return Utils::uint256ToEvmcUint256(uint256_t(val)); }) + .transform([] (uint64_t val) { return EVMCConv::uint256ToEvmcUint256(uint256_t(val)); }) .value_or(evmc::uint256be{}); buffer = parseIfExists(txJson, "data").value_or(Bytes{}); diff --git a/src/net/http/jsonrpc/methods.h b/src/net/http/jsonrpc/methods.h index 3d5f0587e..9e0e225b9 100644 --- a/src/net/http/jsonrpc/methods.h +++ b/src/net/http/jsonrpc/methods.h @@ -1,6 +1,15 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #ifndef JSONRPC_METHODS_H #define JSONRPC_METHODS_H +#include "../../../libs/json.hpp" // Makes no difference but it should be here regardless + #include "../../p2p/managernormal.h" /** @@ -63,69 +72,37 @@ */ namespace jsonrpc { - -json web3_clientVersion(const json& request, const Options& options); - -json web3_sha3(const json& request); - -json net_version(const json& request, const Options& options); - -json net_listening(const json& request); - -json eth_protocolVersion(const json& request, const Options& options); - -json net_peerCount(const json& request, const P2P::ManagerNormal& manager); - -json eth_getBlockByHash(const json& request, const Storage& storage); - -json eth_getBlockByNumber(const json& request, const Storage& storage); - -json eth_getBlockTransactionCountByHash(const json& request, const Storage& storage); - -json eth_getBlockTransactionCountByNumber(const json& request, const Storage& storage); - -json eth_chainId(const json& request, const Options& options); - -json eth_syncing(const json& request); - -json eth_coinbase(const json& request, const Options& options); - -json eth_blockNumber(const json& request, const Storage& storage); - -json eth_call(const json& request, const Storage& storage, State& state); - -json eth_estimateGas(const json& request, const Storage& storage, State& state); - -json eth_gasPrice(const json& request); - -json eth_feeHistory(const json& request, const Storage& storage); - -json eth_getLogs(const json& request, const Storage& storage); - -json eth_getBalance(const json& request, const Storage& storage, const State& state); - -json eth_getTransactionCount(const json& request, const Storage& storage, const State& state); - -json eth_getCode(const json& request, const Storage& storage, const State& state); - -json eth_sendRawTransaction(const json& request, uint64_t chainId, State& state, P2P::ManagerNormal& p2p); - -json eth_getTransactionByHash(const json& request, const Storage& storage, const State& state); - -json eth_getTransactionByBlockHashAndIndex(const json& request, const Storage& storage); - -json eth_getTransactionByBlockNumberAndIndex(const json& request, const Storage& storage); - -json eth_getTransactionReceipt(const json& request, const Storage& storage); - -json eth_getUncleByBlockHashAndIndex(); - -json txpool_content(const json& request, const State& state); - -json debug_traceBlockByNumber(const json& request, const Storage& storage); - -json debug_traceTransaction(const json& request, const Storage& storage); - + json web3_clientVersion(const json& request, const Options& options); + json web3_sha3(const json& request); + json net_version(const json& request, const Options& options); + json net_listening(const json& request); + json eth_protocolVersion(const json& request, const Options& options); + json net_peerCount(const json& request, const P2P::ManagerNormal& manager); + json eth_getBlockByHash(const json& request, const Storage& storage); + json eth_getBlockByNumber(const json& request, const Storage& storage); + json eth_getBlockTransactionCountByHash(const json& request, const Storage& storage); + json eth_getBlockTransactionCountByNumber(const json& request, const Storage& storage); + json eth_chainId(const json& request, const Options& options); + json eth_syncing(const json& request); + json eth_coinbase(const json& request, const Options& options); + json eth_blockNumber(const json& request, const Storage& storage); + json eth_call(const json& request, const Storage& storage, State& state); + json eth_estimateGas(const json& request, const Storage& storage, State& state); + json eth_gasPrice(const json& request); + json eth_feeHistory(const json& request, const Storage& storage); + json eth_getLogs(const json& request, const Storage& storage); + json eth_getBalance(const json& request, const Storage& storage, const State& state); + json eth_getTransactionCount(const json& request, const Storage& storage, const State& state); + json eth_getCode(const json& request, const Storage& storage, const State& state); + json eth_sendRawTransaction(const json& request, uint64_t chainId, State& state, P2P::ManagerNormal& p2p); + json eth_getTransactionByHash(const json& request, const Storage& storage, const State& state); + json eth_getTransactionByBlockHashAndIndex(const json& request, const Storage& storage); + json eth_getTransactionByBlockNumberAndIndex(const json& request, const Storage& storage); + json eth_getTransactionReceipt(const json& request, const Storage& storage); + json eth_getUncleByBlockHashAndIndex(); + json txpool_content(const json& request, const State& state); + json debug_traceBlockByNumber(const json& request, const Storage& storage); + json debug_traceTransaction(const json& request, const Storage& storage); } // namespace jsonrpc #endif // JSONRPC_METHODS_H diff --git a/src/net/http/jsonrpc/parser.cpp b/src/net/http/jsonrpc/parser.cpp index 37fcb330e..639da96f5 100644 --- a/src/net/http/jsonrpc/parser.cpp +++ b/src/net/http/jsonrpc/parser.cpp @@ -1,5 +1,11 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #include "parser.h" -#include "error.h" static inline const std::regex hashFormat{"^0x[0-9a-f]{64}$"}; static inline const std::regex addressFormat{"^0x[0-9,a-f,A-F]{40}$"}; diff --git a/src/net/http/jsonrpc/parser.h b/src/net/http/jsonrpc/parser.h index 9eb683fbb..0b76897a0 100644 --- a/src/net/http/jsonrpc/parser.h +++ b/src/net/http/jsonrpc/parser.h @@ -1,15 +1,19 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #ifndef JSONRPC_PARSER_H #define JSONRPC_PARSER_H -#include "error.h" -#include "../../../utils/utils.h" -#include "../../../utils/strings.h" -#include "../../../utils/tx.h" -#include "../../../contract/contract.h" -#include "../../../contract/event.h" - #include +#include "../../../core/storage.h" // utils/safehash.h -> tx.h -> ecdsa.h -> utils.h + +#include "error.h" + namespace jsonrpc { /// @brief base template class for a json parser diff --git a/src/net/http/jsonrpc/variadicparser.h b/src/net/http/jsonrpc/variadicparser.h index 866634aa0..28593069a 100644 --- a/src/net/http/jsonrpc/variadicparser.h +++ b/src/net/http/jsonrpc/variadicparser.h @@ -1,3 +1,10 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #ifndef JSONRPC_VARIADICPARSER_H #define JSONRPC_VARIADICPARSER_H @@ -8,17 +15,13 @@ namespace jsonrpc { template struct VariadicParser { std::tuple operator()(const json& data) const { - if (data.is_array()) - return (*this)(data.begin(), data.end()); - + if (data.is_array()) return (*this)(data.begin(), data.end()); throw Error::insufficientValues(); } template inline std::tuple operator()(It it, It end) const { - if (it == end) - throw Error::insufficientValues(); - + if (it == end) throw Error::insufficientValues(); return std::tuple_cat(VariadicParser{}(it, end), VariadicParser{}(std::next(it), end)); } }; @@ -26,20 +29,14 @@ struct VariadicParser { template struct VariadicParser { std::tuple operator()(const json& data) const { - if (data.is_array()) - return (*this)(data.begin(), data.end()); - - if (data.is_object()) - return std::make_tuple(Parser{}(data)); - + if (data.is_array()) return (*this)(data.begin(), data.end()); + if (data.is_object()) return std::make_tuple(Parser{}(data)); throw Error::invalidType("object or array", data.type_name()); } template std::tuple operator()(It it, It end) const { - if (it == end) - throw Error::insufficientValues(); - + if (it == end) throw Error::insufficientValues(); return std::make_tuple(Parser{}(*it)); } }; @@ -47,20 +44,14 @@ struct VariadicParser { template struct VariadicParser> { std::tuple> operator()(const json& data) const { - if (data.is_array()) - return (*this)(data.begin(), data.end()); - - if (data.is_object()) - return std::make_tuple(Parser{}(data)); - + if (data.is_array()) return (*this)(data.begin(), data.end()); + if (data.is_object()) return std::make_tuple(Parser{}(data)); throw Error::invalidType("object or array", data.type_name()); } template std::tuple> operator()(It it, It end) const { - if (it == end) - return std::make_tuple(std::nullopt); - + if (it == end) return std::make_tuple(std::nullopt); return std::make_tuple(std::make_optional(Parser{}(*it))); } }; @@ -68,25 +59,16 @@ struct VariadicParser> { template struct VariadicParser> { std::tuple> operator()(const json& data) const { - if (data.is_array()) - return (*this)(data.begin(), data.end()); - - if (data.is_object()) - return std::make_tuple(Parser{}(data), std::optional(std::nullopt)); - + if (data.is_array()) return (*this)(data.begin(), data.end()); + if (data.is_object()) return std::make_tuple(Parser{}(data), std::optional(std::nullopt)); throw Error::invalidType("object or array", data.type_name()); } template std::tuple> operator()(It it, It end) const { - if (it == end) - throw Error::insufficientValues(); - + if (it == end) throw Error::insufficientValues(); std::tuple> res(Parser{}(*it++), std::optional()); - - if (it != end) - std::get<1>(res) = Parser{}(*it); - + if (it != end) std::get<1>(res) = Parser{}(*it); return res; } }; @@ -110,9 +92,7 @@ inline std::tuple parseAll(const json& data) { /// contains an array of values to be parsed template inline std::tuple parseAllParams(const json& target) { - if (!target.contains("params")) - throw DynamicException("\"params\" not available in json"); - + if (!target.contains("params")) throw DynamicException("\"params\" not available in json"); return parseAll(target["params"]); } diff --git a/src/net/p2p/broadcaster.cpp b/src/net/p2p/broadcaster.cpp index d18a7839f..45e302a33 100644 --- a/src/net/p2p/broadcaster.cpp +++ b/src/net/p2p/broadcaster.cpp @@ -1,5 +1,5 @@ /* -Copyright (c) [2023-2024] [Sparq Network] +Copyright (c) [2023-2024] [AppLayer Developers] This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. @@ -7,6 +7,7 @@ See the LICENSE.txt file in the project root for more information. #include "broadcaster.h" #include "managernormal.h" + #include "../../core/blockchain.h" namespace P2P { diff --git a/src/net/p2p/broadcaster.h b/src/net/p2p/broadcaster.h index 04d27fe93..a08dc1c9e 100644 --- a/src/net/p2p/broadcaster.h +++ b/src/net/p2p/broadcaster.h @@ -1,5 +1,5 @@ /* -Copyright (c) [2023-2024] [Sparq Network] +Copyright (c) [2023-2024] [AppLayer Developers] This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. @@ -8,14 +8,7 @@ See the LICENSE.txt file in the project root for more information. #ifndef BROADCASTER_H #define BROADCASTER_H -#include "encoding.h" // NodeID, NodeInfo - -#include "../../utils/logger.h" -#include "../../utils/safehash.h" - -#include -#include -#include +#include "encoding.h" // NodeID, NodeInfo, utils/safehash.h // Forward declaration. class Storage; @@ -82,7 +75,7 @@ namespace P2P { * @param storage Pointer to the blockchain's storage. * @param state Pointer to the blockchain's state. */ - explicit Broadcaster(ManagerNormal& manager, const Storage &storage, State &state) + explicit Broadcaster(ManagerNormal& manager, const Storage& storage, State& state) : manager_(manager), storage_(storage), state_(state) {} diff --git a/src/net/p2p/discovery.h b/src/net/p2p/discovery.h index 6bdfda956..4bf00e263 100644 --- a/src/net/p2p/discovery.h +++ b/src/net/p2p/discovery.h @@ -8,10 +8,10 @@ See the LICENSE.txt file in the project root for more information. #ifndef DISCOVERYWORKER_H #define DISCOVERYWORKER_H -#include -#include +//#include // TODO: find out where this is coming from #include -#include "session.h" + +#include "session.h" // encoding.h -> utils.h -> logger.h -> future namespace P2P { // Forward declarations. diff --git a/src/net/p2p/encoding.cpp b/src/net/p2p/encoding.cpp index 8659553d3..82fc2e566 100644 --- a/src/net/p2p/encoding.cpp +++ b/src/net/p2p/encoding.cpp @@ -7,6 +7,8 @@ See the LICENSE.txt file in the project root for more information. #include "encoding.h" +#include "../../utils/uintconv.h" + namespace P2P { // ------------------------------------------------------------------------------------------------------------------ @@ -20,10 +22,10 @@ namespace P2P { while (index < data.size()) { boost::asio::ip::address address; if (data.size() - index < 2) { throw DynamicException("Invalid data size."); } - auto nodeType = NodeType(Utils::bytesToUint8(data.subspan(index, 1))); - index += 1; - uint8_t ipVersion = Utils::bytesToUint8(data.subspan(index, 1)); + auto nodeType = NodeType(UintConv::bytesToUint8(data.subspan(index, 1))); index += 1; + uint8_t ipVersion = UintConv::bytesToUint8(data.subspan(index, 1)); + index += 1; // Move index to IP address if (ipVersion == 0) { // V4 if (data.size() - index < 4) { throw DynamicException("Invalid data size."); } BytesArr<4> ipBytes; @@ -40,7 +42,7 @@ namespace P2P { throw DynamicException("Invalid ip version."); } if (data.size() - index < 2) { throw DynamicException("Invalid data size."); } - auto port = Utils::bytesToUint16(data.subspan(index, 2)); + auto port = UintConv::bytesToUint16(data.subspan(index, 2)); nodes.insert({NodeID(address, port), nodeType}); index += 2; } @@ -50,8 +52,8 @@ namespace P2P { void nodesToMessage(Bytes& message, const boost::unordered_flat_map& nodes) { for (const auto& [nodeId, nodeType] : nodes) { const auto& [address, port] = nodeId; - Utils::appendBytes(message, Utils::uint8ToBytes(nodeType)); // Node type - Utils::appendBytes(message, Utils::uint8ToBytes(address.is_v4() ? 0 : 1)); + Utils::appendBytes(message, UintConv::uint8ToBytes(nodeType)); // Node type + Utils::appendBytes(message, UintConv::uint8ToBytes(address.is_v4() ? 0 : 1)); if (address.is_v4()) { auto addressBytes = address.to_v4().to_bytes(); Utils::appendBytes(message, addressBytes); @@ -59,14 +61,14 @@ namespace P2P { auto addressBytes = address.to_v6().to_bytes(); Utils::appendBytes(message, addressBytes); } - Utils::appendBytes(message, Utils::uint16ToBytes(uint16_t(port))); + Utils::appendBytes(message, UintConv::uint16ToBytes(uint16_t(port))); } } NodeInfo nodeInfoFromMessage(const bytes::View& data) { - uint64_t nodeVersion = Utils::bytesToUint64(data.subspan(0, 8)); - uint64_t nodeEpoch = Utils::bytesToUint64(data.subspan(8, 8)); - uint64_t nodeHeight = Utils::bytesToUint64(data.subspan(16, 8)); + uint64_t nodeVersion = UintConv::bytesToUint64(data.subspan(0, 8)); + uint64_t nodeEpoch = UintConv::bytesToUint64(data.subspan(8, 8)); + uint64_t nodeHeight = UintConv::bytesToUint64(data.subspan(16, 8)); Hash nodeHash(data.subspan(24, 32)); uint64_t currentEpoch = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch() @@ -82,12 +84,12 @@ namespace P2P { const boost::unordered_flat_map& nodes, const Options& options) { - Utils::appendBytes(message, Utils::uint64ToBytes(options.getVersion())); + Utils::appendBytes(message, UintConv::uint64ToBytes(options.getVersion())); uint64_t currentEpoch = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch() ).count(); - Utils::appendBytes(message, Utils::uint64ToBytes(currentEpoch)); - Utils::appendBytes(message, Utils::uint64ToBytes(latestBlock->getNHeight())); + Utils::appendBytes(message, UintConv::uint64ToBytes(currentEpoch)); + Utils::appendBytes(message, UintConv::uint64ToBytes(latestBlock->getNHeight())); Utils::appendBytes(message, latestBlock->getHash()); nodesToMessage(message, nodes); } @@ -98,7 +100,7 @@ namespace P2P { size_t index = 0; while (index < data.size()) { if (data.size() - index < 4) { throw DynamicException("Invalid data size."); } - uint32_t txSize = Utils::bytesToUint32(data.subspan(index, 4)); + uint32_t txSize = UintConv::bytesToUint32(data.subspan(index, 4)); index += 4; if (data.size() - index < txSize) { throw DynamicException("Invalid data size."); } bytes::View txData = data.subspan(index, txSize); @@ -114,7 +116,7 @@ namespace P2P { void txsToMessage(Bytes& message, const boost::unordered_flat_map& txs) { for (const auto& [txHash, tx] : txs) { Bytes rlp = tx.rlpSerialize(); - Utils::appendBytes(message, Utils::uint32ToBytes(rlp.size())); + Utils::appendBytes(message, UintConv::uint32ToBytes(rlp.size())); message.insert(message.end(), rlp.begin(), rlp.end()); } } @@ -122,7 +124,7 @@ namespace P2P { void txsToMessage(Bytes& message, const std::vector& txs) { for (const auto& tx : txs) { Bytes rlp = tx.rlpSerialize(); - Utils::appendBytes(message, Utils::uint32ToBytes(rlp.size())); + Utils::appendBytes(message, UintConv::uint32ToBytes(rlp.size())); message.insert(message.end(), rlp.begin(), rlp.end()); } } @@ -132,7 +134,7 @@ namespace P2P { size_t index = 0; while (index < data.size()) { if (data.size() - index < 8) { throw DynamicException("Invalid data size."); } - uint64_t blockSize = Utils::bytesToUint64(data.subspan(index, 8)); + uint64_t blockSize = UintConv::bytesToUint64(data.subspan(index, 8)); index += 8; if (data.size() - index < blockSize) { throw DynamicException("Invalid data size."); } bytes::View blockData = data.subspan(index, blockSize); @@ -145,7 +147,7 @@ namespace P2P { void blocksToMessage(Bytes& message, const std::vector>& blocks) { for (const auto& block : blocks) { Bytes serializedBlock = block->serializeBlock(); - Utils::appendBytes(message, Utils::uint64ToBytes(serializedBlock.size())); + Utils::appendBytes(message, UintConv::uint64ToBytes(serializedBlock.size())); Utils::appendBytes(message, serializedBlock); } } @@ -154,15 +156,15 @@ namespace P2P { // Implementation of all network messages that are in encoding.h (common code is in the helpers above). // ------------------------------------------------------------------------------------------------------------------ - RequestID::RequestID(const uint64_t& value) { std::ranges::copy(Utils::uint64ToBytes(value), begin()); } + RequestID::RequestID(const uint64_t& value) { std::ranges::copy(UintConv::uint64ToBytes(value), begin()); } - uint64_t RequestID::toUint64() const { return Utils::bytesToUint64(*this); } + uint64_t RequestID::toUint64() const { return UintConv::bytesToUint64(*this); } RequestID RequestID::random() { return RequestID(Utils::randBytes(8)); } CommandType getCommandType(const bytes::View message) { if (message.size() != 2) { throw DynamicException("Invalid Command Type size." + std::to_string(message.size())); } - uint16_t commandType = Utils::bytesToUint16(message); + uint16_t commandType = UintConv::bytesToUint16(message); if (commandType > commandPrefixes.size()) { throw DynamicException("Invalid command type."); } return static_cast(commandType); } @@ -171,7 +173,7 @@ namespace P2P { RequestType getRequestType(const bytes::View message) { if (message.size() != 1) { throw DynamicException("Invalid Request Type size. " + std::to_string(message.size())); } - uint8_t requestType = Utils::bytesToUint8(message); + uint8_t requestType = UintConv::bytesToUint8(message); if (requestType > typePrefixes.size()) { throw DynamicException("Invalid request type."); } return static_cast(requestType); } @@ -232,7 +234,7 @@ namespace P2P { const Bytes& id = Utils::randBytes(8); // TODO: const& prevents AddressSanitizer, this shouldn't be happening return Message(Utils::makeBytes(bytes::join( getRequestTypePrefix(Requesting), id, getCommandPrefix(RequestBlock), - Utils::uint64ToBytes(height), Utils::uint64ToBytes(heightEnd), Utils::uint64ToBytes(bytesLimit) + UintConv::uint64ToBytes(height), UintConv::uint64ToBytes(heightEnd), UintConv::uint64ToBytes(bytesLimit) ))); } @@ -268,9 +270,9 @@ namespace P2P { void RequestDecoder::requestBlock(const Message& message, uint64_t& height, uint64_t& heightEnd, uint64_t& bytesLimit) { if (message.size() != 35) { throw DynamicException("Invalid RequestBlock message size."); } if (message.command() != RequestBlock) { throw DynamicException("Invalid RequestBlock message command."); } - height = Utils::bytesToUint64(message.message().subspan(0, 8)); - heightEnd = Utils::bytesToUint64(message.message().subspan(8, 8)); - bytesLimit = Utils::bytesToUint64(message.message().subspan(16, 8)); + height = UintConv::bytesToUint64(message.message().subspan(0, 8)); + heightEnd = UintConv::bytesToUint64(message.message().subspan(8, 8)); + bytesLimit = UintConv::bytesToUint64(message.message().subspan(16, 8)); } Message AnswerEncoder::ping(const Message& request) { @@ -379,7 +381,7 @@ namespace P2P { const Bytes& serializedTx = tx.rlpSerialize(); // TODO: const& prevents AddressSanitizer, this shouldn't be happening return Message(Utils::makeBytes(bytes::join( getRequestTypePrefix(Broadcasting), - Utils::uint64ToBytes(FNVHash()(serializedTx)), + UintConv::uint64ToBytes(FNVHash()(serializedTx)), getCommandPrefix(BroadcastValidatorTx), serializedTx ))); @@ -390,7 +392,7 @@ namespace P2P { const Bytes& serializedTx = tx.rlpSerialize(); // TODO: const& prevents AddressSanitizer, this shouldn't be happening return Message(Utils::makeBytes(bytes::join( getRequestTypePrefix(Broadcasting), - Utils::uint64ToBytes(FNVHash()(serializedTx)), + UintConv::uint64ToBytes(FNVHash()(serializedTx)), getCommandPrefix(BroadcastTx), serializedTx ))); @@ -401,7 +403,7 @@ namespace P2P { const Bytes& serializedBlock = block->serializeBlock(); // TODO: const& prevents AddressSanitizer, this shouldn't be happening return Message(Utils::makeBytes(bytes::join( getRequestTypePrefix(Broadcasting), - Utils::uint64ToBytes(FNVHash()(serializedBlock)), + UintConv::uint64ToBytes(FNVHash()(serializedBlock)), getCommandPrefix(BroadcastBlock), serializedBlock ))); diff --git a/src/net/p2p/encoding.h b/src/net/p2p/encoding.h index ec899005b..426245931 100644 --- a/src/net/p2p/encoding.h +++ b/src/net/p2p/encoding.h @@ -8,13 +8,9 @@ See the LICENSE.txt file in the project root for more information. #ifndef P2P_ENCODING_H #define P2P_ENCODING_H -#include -#include - -#include "../../utils/utils.h" -#include "../../utils/safehash.h" -#include "../../utils/tx.h" -#include "../../utils/finalizedblock.h" +#include "../../utils/utils.h" // logger.h -> future +#include "../../utils/safehash.h" // tx.h -> ecdsa.h -> utils.h -> libs/json.hpp -> boost/unordered/unordered_flat_map.hpp +#include "../../utils/finalizedblock.h" // merkle.h -> tx.h #include "../../utils/options.h" namespace P2P { diff --git a/src/net/p2p/managerbase.h b/src/net/p2p/managerbase.h index 5d07f30ad..4206b8085 100644 --- a/src/net/p2p/managerbase.h +++ b/src/net/p2p/managerbase.h @@ -8,14 +8,12 @@ See the LICENSE.txt file in the project root for more information. #ifndef P2P_MANAGER_BASE #define P2P_MANAGER_BASE -#include "session.h" -#include "encoding.h" #include "discovery.h" -#include "../../utils/options.h" -#include "../../libs/BS_thread_pool_light.hpp" +#include "session.h" // encoding.h -> utils/options.h -namespace P2P { +class DiscoveryWorker; // Forward declaration +namespace P2P { /** * Base manager class meant to be inherited by the respective managers for * both node types (Normal and Discovery). diff --git a/src/net/p2p/managerdiscovery.h b/src/net/p2p/managerdiscovery.h index c05d60e7c..d0b610179 100644 --- a/src/net/p2p/managerdiscovery.h +++ b/src/net/p2p/managerdiscovery.h @@ -8,10 +8,7 @@ See the LICENSE.txt file in the project root for more information. #ifndef P2P_MANAGER_DISCOVERY_H #define P2P_MANAGER_DISCOVERY_H -#include "managerbase.h" - -#include -#include +#include "managerbase.h" // encoding.h -> utils/utils.h -> libs/json.hpp -> algorithm namespace P2P { /// Manager focused exclusively at Discovery nodes. diff --git a/src/net/p2p/managernormal.cpp b/src/net/p2p/managernormal.cpp index 966c0fcf6..290c06ba4 100644 --- a/src/net/p2p/managernormal.cpp +++ b/src/net/p2p/managernormal.cpp @@ -6,22 +6,14 @@ See the LICENSE.txt file in the project root for more information. */ #include "managernormal.h" -#include "../core/rdpos.h" + #include "../core/storage.h" #include "../core/state.h" -#include "nodeconns.h" namespace P2P{ + void ManagerNormal::start() { ManagerBase::start(); nodeConns_.start(); } - void ManagerNormal::start() { - ManagerBase::start(); - nodeConns_.start(); - } - - void ManagerNormal::stop() { - nodeConns_.stop(); - ManagerBase::stop(); - } + void ManagerNormal::stop() { nodeConns_.stop(); ManagerBase::stop(); } void ManagerNormal::sendMessageToAll(const std::shared_ptr message, const std::optional& originalSender) { std::unordered_set peerMap; diff --git a/src/net/p2p/managernormal.h b/src/net/p2p/managernormal.h index 094885324..e2318150d 100644 --- a/src/net/p2p/managernormal.h +++ b/src/net/p2p/managernormal.h @@ -9,11 +9,9 @@ See the LICENSE.txt file in the project root for more information. #define P2P_MANAGER_NORMAL_H #include "managerbase.h" -#include "nodeconns.h" +#include "nodeconns.h" // encoding.h -> optional, NodeID, NodeInfo #include "broadcaster.h" -#include - // Forward declaration. class Storage; class State; diff --git a/src/net/p2p/nodeconns.cpp b/src/net/p2p/nodeconns.cpp index d80187eae..3304e8607 100644 --- a/src/net/p2p/nodeconns.cpp +++ b/src/net/p2p/nodeconns.cpp @@ -7,7 +7,9 @@ See the LICENSE.txt file in the project root for more information. #include "nodeconns.h" #include "managernormal.h" -#include "../../core/blockchain.h" + +// TODO: find out where this is coming from +//#include // std::this_thread::sleep_for namespace P2P { void NodeConns::forceRefresh() { diff --git a/src/net/p2p/nodeconns.h b/src/net/p2p/nodeconns.h index d23ab64c1..3e759420c 100644 --- a/src/net/p2p/nodeconns.h +++ b/src/net/p2p/nodeconns.h @@ -8,15 +8,11 @@ See the LICENSE.txt file in the project root for more information. #ifndef NODECONNS_H #define NODECONNS_H -#include "encoding.h" // NodeID, NodeInfo - -#include "../../utils/logger.h" -#include "../../utils/safehash.h" - -#include // std::find -#include // std::this_thread::sleep_for #include +#include "../../utils/safehash.h" // tx.h -> ecdsa.h -> utils.h -> libs/json.hpp -> algorithm (std::find in .cpp), boost/unordered/unordered_flat_map.hpp + +#include "encoding.h" // NodeID, NodeInfo // TODO: tests for NodeConns (if necessary) diff --git a/src/net/p2p/session.cpp b/src/net/p2p/session.cpp index d29330fff..455aae8aa 100644 --- a/src/net/p2p/session.cpp +++ b/src/net/p2p/session.cpp @@ -7,10 +7,10 @@ See the LICENSE.txt file in the project root for more information. #include "session.h" #include "managerbase.h" -#include -namespace P2P { +#include "../../utils/uintconv.h" +namespace P2P { std::string Session::getLogicalLocation() const { return this->logSrc_; } Session::Session(tcp::socket &&socket, @@ -140,7 +140,7 @@ namespace P2P { void Session::write_handshake() { this->outboundHandshake_[0] = (this->manager_.nodeType() == NodeType::NORMAL_NODE) ? 0x00 : 0x01; - auto serverPort = Utils::uint16ToBytes(this->manager_.serverPort()); + auto serverPort = UintConv::uint16ToBytes(this->manager_.serverPort()); this->outboundHandshake_[1] = serverPort[0]; this->outboundHandshake_[2] = serverPort[1]; net::async_write(this->socket_, net::buffer(this->outboundHandshake_, 3), net::bind_executor( @@ -167,7 +167,7 @@ namespace P2P { return; } this->type_ = (!this->inboundHandshake_[0]) ? NodeType::NORMAL_NODE : NodeType::DISCOVERY_NODE; - this->serverPort_ = Utils::bytesToUint16(Utils::create_view_span(this->inboundHandshake_, 1, 2)); + this->serverPort_ = UintConv::bytesToUint16(Utils::create_view_span(this->inboundHandshake_, 1, 2)); // Ensure that the server does not inform us a port number that is actually different from the listen port number we // actually connected to, which could cause problems, since we already registered this OUTBOUND Session to port_. @@ -291,7 +291,7 @@ namespace P2P { void Session::on_read_header(boost::system::error_code ec, std::size_t) { if (ec) { this->handle_error(__func__, ec); return; } - uint64_t messageSize = Utils::bytesToUint64(this->inboundHeader_); + uint64_t messageSize = UintConv::bytesToUint64(this->inboundHeader_); if (messageSize > this->maxMessageSize_) { LOGWARNING("Peer " + toString(nodeId_) + " message too large: " + std::to_string(messageSize) + ", max: " + std::to_string(this->maxMessageSize_) + ", closing session"); @@ -328,7 +328,7 @@ namespace P2P { void Session::do_write_header() { // Nothing to do, someone called us by mistake. if (this->outboundMessage_ == nullptr) return; - this->outboundHeader_ = Utils::uint64ToBytes(this->outboundMessage_->rawMessage_.size()); + this->outboundHeader_ = UintConv::uint64ToBytes(this->outboundMessage_->rawMessage_.size()); net::async_write(this->socket_, net::buffer(this->outboundHeader_), net::bind_executor( this->strand_, std::bind_front( &Session::on_write_header, shared_from_this() diff --git a/src/net/p2p/session.h b/src/net/p2p/session.h index 266cf277e..7ffa3e0f0 100644 --- a/src/net/p2p/session.h +++ b/src/net/p2p/session.h @@ -8,18 +8,12 @@ See the LICENSE.txt file in the project root for more information. #ifndef P2P_SESSION_H #define P2P_SESSION_H -#include -#include -#include -#include #include -#include -#include + +#include // asio/buffer.hpp #include -#include -#include "../../utils/utils.h" -#include "encoding.h" +#include "encoding.h" // NodeID, NodeType, utils.h -> libs/json.hpp -> cstdlib, functional, memory, utility using boost::asio::ip::tcp; namespace net = boost::asio; // from diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index defa65b49..cabccc60c 100644 --- a/src/utils/CMakeLists.txt +++ b/src/utils/CMakeLists.txt @@ -13,6 +13,10 @@ set(UTILS_HEADERS ${CMAKE_SOURCE_DIR}/src/utils/logger.h ${CMAKE_SOURCE_DIR}/src/utils/dynamicexception.h ${CMAKE_SOURCE_DIR}/src/utils/finalizedblock.h + ${CMAKE_SOURCE_DIR}/src/utils/strconv.h + ${CMAKE_SOURCE_DIR}/src/utils/evmcconv.h + ${CMAKE_SOURCE_DIR}/src/utils/intconv.h + ${CMAKE_SOURCE_DIR}/src/utils/uintconv.h PARENT_SCOPE ) @@ -30,5 +34,9 @@ set(UTILS_SOURCES ${CMAKE_SOURCE_DIR}/src/utils/contractreflectioninterface.cpp ${CMAKE_SOURCE_DIR}/src/utils/jsonabi.cpp ${CMAKE_SOURCE_DIR}/src/utils/finalizedblock.cpp + ${CMAKE_SOURCE_DIR}/src/utils/strconv.cpp + ${CMAKE_SOURCE_DIR}/src/utils/evmcconv.cpp + ${CMAKE_SOURCE_DIR}/src/utils/intconv.cpp + ${CMAKE_SOURCE_DIR}/src/utils/uintconv.cpp PARENT_SCOPE ) diff --git a/src/utils/clargs.h b/src/utils/clargs.h index dc819bc1d..79bd4ef46 100644 --- a/src/utils/clargs.h +++ b/src/utils/clargs.h @@ -8,12 +8,9 @@ See the LICENSE.txt file in the project root for more information. #ifndef CLARGS_H #define CLARGS_H -#include -#include +#include // includes string internally (and probably algorithm somewhere due to std::transform) -#include "src/net/p2p/managerbase.h" - -#include "src/utils/logger.h" +#include "../net/p2p/managernormal.h" /// List of BDK programs that the argument parser is aware of. enum class BDKTool { FULL_NODE, DISCOVERY_NODE, UNIT_TEST_SUITE }; @@ -117,7 +114,7 @@ bool applyProcessOptions(ProcessOptions& opt) { return false; } - boost::to_upper(opt.logLevel); + std::transform(opt.logLevel.begin(), opt.logLevel.end(), opt.logLevel.begin(), ::toupper); if (opt.logLevel == "X") { opt.logLevel = "XTRACE"; } else if (opt.logLevel == "T") { opt.logLevel = "TRACE"; } diff --git a/src/utils/contractreflectioninterface.h b/src/utils/contractreflectioninterface.h index ddf4f2631..99b141c65 100644 --- a/src/utils/contractreflectioninterface.h +++ b/src/utils/contractreflectioninterface.h @@ -8,9 +8,7 @@ See the LICENSE.txt file in the project root for more information. #ifndef CONTRACTREFLECTIONINTERFACE_H #define CONTRACTREFLECTIONINTERFACE_H -#include -#include "contract/abi.h" -#include +#include "contract/abi.h" // string, libs/json.hpp -> boost/unordered/unordered_flat_map.hpp /** * Namespace for the reflection interface used for registering contract classes. diff --git a/src/utils/db.cpp b/src/utils/db.cpp index d0f385f12..7d7fdc5b9 100644 --- a/src/utils/db.cpp +++ b/src/utils/db.cpp @@ -7,6 +7,8 @@ See the LICENSE.txt file in the project root for more information. #include "db.h" +#include "dynamicexception.h" + DB::DB(const std::filesystem::path& path) { this->opts_.create_if_missing = true; if (!std::filesystem::exists(path)) { // Ensure the database path can actually be found @@ -33,7 +35,7 @@ bool DB::putBatch(const DBBatch& batch) { std::vector DB::getBatch( const Bytes& bytesPfx, const std::vector& keys - ) const { +) const { std::lock_guard lock(this->batchLock_); std::vector ret; std::unique_ptr it(this->db_->NewIterator(rocksdb::ReadOptions())); diff --git a/src/utils/db.h b/src/utils/db.h index a0aeb4cc0..bca1f39aa 100644 --- a/src/utils/db.h +++ b/src/utils/db.h @@ -8,17 +8,9 @@ See the LICENSE.txt file in the project root for more information. #ifndef DB_H #define DB_H -#include -#include -#include -#include -#include +#include // rocksdb/transaction_log.h -> rocksdb/write_batch.h, includes mutex somewhere in there too -#include -#include - -#include "utils.h" -#include "dynamicexception.h" +#include "utils.h" // libs/json.hpp -> (cstring, filesystem, string, vector) /// Namespace for accessing database prefixes. namespace DBPrefix { @@ -131,7 +123,7 @@ class DBBatch { }; /** - * Abstraction of a [Speedb](https://github.com/speedb-io/speedb) database (Speedb is a RocksDB drop-in replacement). + * Abstraction of a [Speedb](https://github.com/speedb-io/speedb) database (RocksDB drop-in replacement). * Keys begin with prefixes that separate entries in several categories. @see DBPrefix */ class DB { diff --git a/src/utils/dynamicexception.h b/src/utils/dynamicexception.h index ad444182d..aef87f56b 100644 --- a/src/utils/dynamicexception.h +++ b/src/utils/dynamicexception.h @@ -8,12 +8,13 @@ See the LICENSE.txt file in the project root for more information. #ifndef DYNAMIC_EXCEPTION_H #define DYNAMIC_EXCEPTION_H -#include -#include -#include -#include -#include -#include +// TODO: find out where those are coming from +//#include +//#include // put_time() +//#include + +#include // ctime +#include // ostringstream /// Abstraction of a custom exception class for dynamic message building and timestamping. class DynamicException : public std::exception { diff --git a/src/utils/ecdsa.cpp b/src/utils/ecdsa.cpp index cbe10058c..027aa4a7c 100644 --- a/src/utils/ecdsa.cpp +++ b/src/utils/ecdsa.cpp @@ -6,6 +6,7 @@ See the LICENSE.txt file in the project root for more information. */ #include "ecdsa.h" +#include "uintconv.h" const secp256k1_context* Secp256k1::getCtx() { static std::unique_ptr s_ctx{ @@ -39,12 +40,12 @@ UPubKey Secp256k1::recover(const Signature& sig, const Hash& msg) { Signature Secp256k1::makeSig(const uint256_t& r, const uint256_t& s, const uint8_t& v) { BytesArr<65> sig; // r = [0, 32], s = [32, 64], v = 65 - auto tmpR = Utils::uint256ToBytes(r); + auto tmpR = UintConv::uint256ToBytes(r); for (uint16_t i = 0; i < tmpR.size(); i++) { // Replace bytes from tmp to ret to make it 32 bytes in size sig[31 - i] = tmpR[tmpR.size() - i - 1]; } - auto tmpS = Utils::uint256ToBytes(s); + auto tmpS = UintConv::uint256ToBytes(s); for (uint16_t i = 0; i < tmpS.size(); i++) { // Replace bytes from tmp to ret to make it 32 bytes in size sig[63 - i] = tmpS[tmpS.size() - i - 1]; @@ -132,8 +133,8 @@ Signature Secp256k1::sign(const Hash& msg, const PrivKey& key) { auto sigView = Utils::create_view_span(sig); uint8_t rawV = v; - uint256_t r = Utils::bytesToUint256(sigView.subspan(0, 32)); - uint256_t s = Utils::bytesToUint256(sigView.subspan(32, 32)); + uint256_t r = UintConv::bytesToUint256(sigView.subspan(0, 32)); + uint256_t s = UintConv::bytesToUint256(sigView.subspan(32, 32)); if (s > (Secp256k1::ecConst / 2)) { rawV = static_cast(rawV ^ 1); diff --git a/src/utils/ecdsa.h b/src/utils/ecdsa.h index 08ef3b665..816a65c89 100644 --- a/src/utils/ecdsa.h +++ b/src/utils/ecdsa.h @@ -8,9 +8,8 @@ See the LICENSE.txt file in the project root for more information. #ifndef ECDSA_H #define ECDSA_H -#include -#include -#include +//#include // TODO: find out where this is coming from +#include // includes secp256k1.h #include "utils.h" diff --git a/src/utils/evmcconv.cpp b/src/utils/evmcconv.cpp new file mode 100644 index 000000000..77f8e678d --- /dev/null +++ b/src/utils/evmcconv.cpp @@ -0,0 +1,49 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#include "evmcconv.h" +#include "uintconv.h" + +uint256_t EVMCConv::evmcUint256ToUint256(const evmc::uint256be& i) { + // We can use the uint256ToBytes directly as it is std::span and we can create a span from an array + return UintConv::bytesToUint256(bytes::View(i.bytes, 32)); +} + +evmc::uint256be EVMCConv::uint256ToEvmcUint256(const uint256_t& i) { + // Convert the uint256_t to BytesArr<32> then copy it to evmc::uint256be + // evmc::uint256be is a struct with a single member, bytes, which holds a uint256 value in *big-endian* order + evmc::uint256be ret; + BytesArr<32> bytes = UintConv::uint256ToBytes(i); + std::copy(bytes.begin(), bytes.end(), ret.bytes); + return ret; +} + +BytesArr<32> EVMCConv::evmcUint256ToBytes(const evmc::uint256be& i) { + BytesArr<32> ret; + std::copy(i.bytes, i.bytes + 32, ret.begin()); + return ret; +} + +evmc::uint256be EVMCConv::bytesToEvmcUint256(const bytes::View b) { + evmc::uint256be ret; + std::copy(b.begin(), b.end(), ret.bytes); + return ret; +} + +Functor EVMCConv::getFunctor(const evmc_message& msg) { + Functor ret; + if (msg.input_size < 4) return ret; + // Memcpy the first 4 bytes from the input data to the function signature + ret.value = UintConv::bytesToUint32(bytes::View(msg.input_data, 4)); + return ret; +} + +bytes::View EVMCConv::getFunctionArgs(const evmc_message& msg) { + if (msg.input_size < 4) return bytes::View(); + return bytes::View(msg.input_data + 4, msg.input_size - 4); +} + diff --git a/src/utils/evmcconv.h b/src/utils/evmcconv.h new file mode 100644 index 000000000..17f3bafd1 --- /dev/null +++ b/src/utils/evmcconv.h @@ -0,0 +1,64 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#ifndef EVMCCONV_H +#define EVMCCONV_H + +#include + +#include "../bytes/view.h" + +#include "strings.h" // Functor + +using Byte = uint8_t; ///< Typedef for Byte. +using Bytes = std::vector; ///< Typedef for Bytes. +template using BytesArr = std::array; ///< Typedef for BytesArr. + +// TODO: reroute this later, this is a placeholder +using uint256_t = boost::multiprecision::number>; + +/// Namespace for general EVMC-related functions. +namespace EVMCConv { + /** + * Wrapper for EVMC's `ecrecover()` function. + * @param hash The hash to recover an address from. + * @param v The recover ID. + * @param r The first half of the ECDSA signature. + * @param s The second half of the ECDSA signature. + * @return The recovered address. + */ + evmc::address ecrecover(evmc::bytes32 hash, evmc::bytes32 v, evmc::bytes32 r, evmc::bytes32 s); // TODO: not implemented(???) + + ///@{ + /** + * Convert a given EVMC type to a BDK type, or vice-versa. + * @param i (or b) The type to convert. + * @return The converted type. + */ + uint256_t evmcUint256ToUint256(const evmc::uint256be& i); + evmc::uint256be uint256ToEvmcUint256(const uint256_t& i); + BytesArr<32> evmcUint256ToBytes(const evmc::uint256be& i); + evmc::uint256be bytesToEvmcUint256(const bytes::View b); + ///@} + + /** + * Get the functor of a evmc_message + * @param msg The evmc_message to get the functor from. + * @return The functor of the evmc_message (0 if evmc_message size == 0). + */ + Functor getFunctor(const evmc_message& msg); + + /** + * Get the bytes::View representing the function arguments of a given evmc_message. + * @param msg The evmc_message to get the function arguments from. + * @return The bytes::View representing the function arguments. + */ + bytes::View getFunctionArgs(const evmc_message& msg); +}; + +#endif // EVMCCONV_H + diff --git a/src/utils/finalizedblock.cpp b/src/utils/finalizedblock.cpp index f7328a716..7423387d2 100644 --- a/src/utils/finalizedblock.cpp +++ b/src/utils/finalizedblock.cpp @@ -6,7 +6,10 @@ See the LICENSE.txt file in the project root for more information. */ #include "finalizedblock.h" -#include "../core/rdpos.h" + +#include "../core/rdpos.h" // net/p2p/managernormal.h -> net/p2p/nodeconns.h (and broadcaster.h) -> thread + +#include "../utils/uintconv.h" FinalizedBlock FinalizedBlock::fromBytes(const bytes::View bytes, const uint64_t& requiredChainId) { try { @@ -20,9 +23,9 @@ FinalizedBlock FinalizedBlock::fromBytes(const bytes::View bytes, const uint64_t auto blockRandomness = Hash(bytes.subspan(97, 32)); auto validatorMerkleRoot = Hash(bytes.subspan(129, 32)); auto txMerkleRoot = Hash(bytes.subspan(161, 32)); - uint64_t timestamp = Utils::bytesToUint64(bytes.subspan(193, 8)); - uint64_t nHeight = Utils::bytesToUint64(bytes.subspan(201, 8)); - uint64_t txValidatorStart = Utils::bytesToUint64(bytes.subspan(209, 8)); + uint64_t timestamp = UintConv::bytesToUint64(bytes.subspan(193, 8)); + uint64_t nHeight = UintConv::bytesToUint64(bytes.subspan(201, 8)); + uint64_t txValidatorStart = UintConv::bytesToUint64(bytes.subspan(209, 8)); SLOGTRACE("Deserializing transactions..."); @@ -33,7 +36,7 @@ FinalizedBlock FinalizedBlock::fromBytes(const bytes::View bytes, const uint64_t uint64_t txCount = 0; uint64_t index = 217; // Start of block tx range while (index < txValidatorStart) { - uint64_t txSize = Utils::bytesToUint32(bytes.subspan(index, 4)); + uint64_t txSize = UintConv::bytesToUint32(bytes.subspan(index, 4)); index += txSize + 4; txCount++; } @@ -42,7 +45,7 @@ FinalizedBlock FinalizedBlock::fromBytes(const bytes::View bytes, const uint64_t uint64_t valTxCount = 0; index = txValidatorStart; while (index < bytes.size()) { - uint64_t txSize = Utils::bytesToUint32(bytes.subspan(index, 4)); + uint64_t txSize = UintConv::bytesToUint32(bytes.subspan(index, 4)); index += txSize + 4; valTxCount++; } @@ -56,7 +59,7 @@ FinalizedBlock FinalizedBlock::fromBytes(const bytes::View bytes, const uint64_t thrNum <= 1 || txCount <= 2000 ) { for (uint64_t i = 0; i < txCount; i++) { - uint64_t txSize = Utils::bytesToUint32(bytes.subspan(index, 4)); + uint64_t txSize = UintConv::bytesToUint32(bytes.subspan(index, 4)); index += 4; txs.emplace_back(bytes.subspan(index, txSize), requiredChainId); index += txSize; @@ -82,7 +85,7 @@ FinalizedBlock FinalizedBlock::fromBytes(const bytes::View bytes, const uint64_t std::vector txVec; uint64_t idx = startIdx; for (uint64_t ii = 0; ii < nTxs; ii++) { - uint64_t len = Utils::bytesToUint32(bytes.subspan(idx, 4)); + uint64_t len = UintConv::bytesToUint32(bytes.subspan(idx, 4)); idx += 4; txVec.emplace_back(bytes.subspan(idx, len), requiredChainId); idx += len; @@ -95,7 +98,7 @@ FinalizedBlock FinalizedBlock::fromBytes(const bytes::View bytes, const uint64_t // Update offset, skip if this is the last thread if (i >= txsPerThr.size() - 1) continue; for (uint64_t ii = 0; ii < nTxs; ii++) { - uint64_t len = Utils::bytesToUint32(bytes.subspan(thrOff, 4)); + uint64_t len = UintConv::bytesToUint32(bytes.subspan(thrOff, 4)); thrOff += len + 4; } } @@ -110,7 +113,7 @@ FinalizedBlock FinalizedBlock::fromBytes(const bytes::View bytes, const uint64_t // Deserialize the Validator transactions normally, no need to thread index = txValidatorStart; for (uint64_t i = 0; i < valTxCount; ++i) { - uint64_t txSize = Utils::bytesToUint32(bytes.subspan(index, 4)); + uint64_t txSize = UintConv::bytesToUint32(bytes.subspan(index, 4)); index += 4; txValidators.emplace_back(bytes.subspan(index, txSize), requiredChainId); if (txValidators.back().getNHeight() != nHeight) { @@ -169,7 +172,7 @@ FinalizedBlock FinalizedBlock::createNewValidBlock( Bytes header = Utils::makeBytes(bytes::join( prevBlockHash, blockRandomness, validatorMerkleRoot, txMerkleRoot, - Utils::uint64ToBytes(timestamp), Utils::uint64ToBytes(nHeight) + UintConv::uint64ToBytes(timestamp), UintConv::uint64ToBytes(nHeight) )); Hash headerHash = Utils::sha3(header); @@ -202,7 +205,7 @@ FinalizedBlock FinalizedBlock::createNewValidBlock( Bytes FinalizedBlock::serializeHeader() const { return Utils::makeBytes(bytes::join( prevBlockHash_, blockRandomness_, validatorMerkleRoot_, txMerkleRoot_, - Utils::uint64ToBytes(timestamp_), Utils::uint64ToBytes(nHeight_) + UintConv::uint64ToBytes(timestamp_), UintConv::uint64ToBytes(nHeight_) )); } @@ -218,18 +221,18 @@ Bytes FinalizedBlock::serializeBlock() const { // Serialize the transactions [4 Bytes + Tx Bytes] for (const auto &tx : this->txs_) { Bytes txBytes = tx.rlpSerialize(); - Utils::appendBytes(ret, Utils::uint32ToBytes(txBytes.size())); + Utils::appendBytes(ret, UintConv::uint32ToBytes(txBytes.size())); ret.insert(ret.end(), txBytes.begin(), txBytes.end()); } // Insert the txValidatorStart - BytesArr<8> txValidatorStart = Utils::uint64ToBytes(ret.size()); + BytesArr<8> txValidatorStart = UintConv::uint64ToBytes(ret.size()); std::memcpy(&ret[txValidatorStartLoc], txValidatorStart.data(), 8); // Serialize the Validator Transactions [4 Bytes + Tx Bytes] for (const auto &tx : this->txValidators_) { Bytes txBytes = tx.rlpSerialize(); - Utils::appendBytes(ret, Utils::uint32ToBytes(txBytes.size())); + Utils::appendBytes(ret, UintConv::uint32ToBytes(txBytes.size())); ret.insert(ret.end(), txBytes.begin(), txBytes.end()); } diff --git a/src/utils/finalizedblock.h b/src/utils/finalizedblock.h index 32a4b6005..00d53ed99 100644 --- a/src/utils/finalizedblock.h +++ b/src/utils/finalizedblock.h @@ -8,16 +8,7 @@ See the LICENSE.txt file in the project root for more information. #ifndef FINALIZEDBLOCK_H #define FINALIZEDBLOCK_H -#include -#include - -#include "utils.h" -#include "tx.h" -#include "strings.h" -#include "merkle.h" -#include "ecdsa.h" - -#include "../bytes/join.h" +#include "merkle.h" // tx.h -> ecdsa.h -> utils.h -> strings.h, (logger.h -> future), bytes/join.h /// Abstraction of a finalized block. Members are purposefully const due to the immutable nature of the structure. class FinalizedBlock { diff --git a/src/utils/hex.cpp b/src/utils/hex.cpp index 1cb45f3e2..fb5e71edc 100644 --- a/src/utils/hex.cpp +++ b/src/utils/hex.cpp @@ -7,6 +7,8 @@ See the LICENSE.txt file in the project root for more information. #include "hex.h" +#include "dynamicexception.h" + Hex::Hex(const std::string_view value, bool strict) : strict_(strict) { std::string ret(value); if (strict) { @@ -119,3 +121,17 @@ Bytes Hex::bytes() const { return ret; } +Hex& Hex::operator+=(const std::string& hex) { + if (Hex::isValid(hex, (hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')))) { + this->hex_ += (hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')) ? hex.substr(2) : hex; + } else { + throw DynamicException("Invalid Hex concat operation"); + } + return *this; +} + +Hex& Hex::operator+=(const Hex& other) { + this->hex_ += (other.strict_) ? other.hex_.substr(2) : other.hex_; + return *this; +} + diff --git a/src/utils/hex.h b/src/utils/hex.h index 3ed30d413..9e4099149 100644 --- a/src/utils/hex.h +++ b/src/utils/hex.h @@ -8,18 +8,16 @@ See the LICENSE.txt file in the project root for more information. #ifndef HEX_H #define HEX_H -#include -#include -#include -#include -#include -#include -#include -#include +// TODO: find out where those are coming from +//#include +//#include // dynamicexception.h -> sstream +//#include +//#include +//#include + #include -#include "dynamicexception.h" -#include "bytes/view.h" +#include "bytes/view.h" // bytes/ranges.h -> ranges -> span libs/zpp_bits.h -> span using Byte = uint8_t; using Bytes = std::vector; @@ -163,20 +161,10 @@ class Hex { * Concat operator. * @throw DynamicException on invalid concat. */ - Hex& operator+=(const std::string& hex) { - if (Hex::isValid(hex, (hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')))) { - this->hex_ += (hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')) ? hex.substr(2) : hex; - } else { - throw DynamicException("Invalid Hex concat operation"); - } - return *this; - } + Hex& operator+=(const std::string& hex); /// Concat operator. - Hex& operator+=(const Hex& other) { - this->hex_ += (other.strict_) ? other.hex_.substr(2) : other.hex_; - return *this; - } + Hex& operator+=(const Hex& other); /** * Default operator to return the internal hex string directly as a string. Example: diff --git a/src/utils/intconv.cpp b/src/utils/intconv.cpp new file mode 100644 index 000000000..24b517a91 --- /dev/null +++ b/src/utils/intconv.cpp @@ -0,0 +1,110 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#include "intconv.h" + +#include "dynamicexception.h" + +// ========================================================================== +// INT TO BYTES +// ========================================================================== + +BytesArr<32> IntConv::int256ToBytes(const int256_t& i) { + BytesArr<32> ret; + if (i < 0) { + int256_t absValue = -i; + Bytes tempBytes; + boost::multiprecision::export_bits(absValue, std::back_inserter(tempBytes), 8); + for (int j = 0; j < 32; j++) { + if (j < tempBytes.size()) { + ret[31 - j] = ~tempBytes[tempBytes.size() - j - 1]; + } else { + ret[31 - j] = 0xFF; + } + } + for (int j = 31; j >= 0; j--) { + if (ret[j] != 0xFF) { + ret[j]++; + break; + } else { + ret[j] = 0x00; + } + } + } else { + Bytes tempBytes; + boost::multiprecision::export_bits(i, std::back_inserter(tempBytes), 8); + std::copy(tempBytes.rbegin(), tempBytes.rend(), ret.rbegin()); + } + return ret; +} + +BytesArr<17> IntConv::int136ToBytes(const int136_t &i) { + BytesArr<17> ret; + Bytes tmp; + tmp.reserve(17); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (signed ii = 0; ii < tmp.size(); ii++) ret[16 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<8> IntConv::int64ToBytes(const int64_t& i) { + BytesArr<8> ret; + std::memcpy(&ret[0], &i, 8); + #if __BYTE_ORDER == __LITTLE_ENDIAN + std::reverse(ret.begin(), ret.end()); + #endif + return ret; +} + +// ========================================================================== +// BYTES TO INT +// ========================================================================== + +int256_t IntConv::bytesToInt256(const bytes::View b) { + if (b.size() != 32) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 32, got " + std::to_string(b.size()) + ); + uint256_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + + // Check the MSB to determine if the value is negative + // Manually compute two's complement in reverse, since boost::multiprecision::cpp_int doesn't support it + // Subtract one from the byte array + if (b[0] & 0x80) { + int borrow = 1; + for (int i = 31; i >= 0 && borrow; i--) { + borrow = (b[i] == 0); + ret -= (uint256_t(1) << (8 * (31 - i))); + } + ret = ~ret; + return -ret.convert_to(); + } else { + return ret.convert_to(); + } +} + +int136_t IntConv::bytesToInt136(const bytes::View b) { + if (b.size() != 18) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 18, got " + std::to_string(b.size()) + ); + int136_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +int64_t IntConv::bytesToInt64(const bytes::View b) { + if (b.size() != 8) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 8, got " + std::to_string(b.size()) + ); + int64_t ret = 0; + std::memcpy(&ret, b.data(), 8); + #if __BYTE_ORDER == __LITTLE_ENDIAN + return __builtin_bswap64(ret); + #endif + return ret; +} + diff --git a/src/utils/intconv.h b/src/utils/intconv.h new file mode 100644 index 000000000..f8e38b937 --- /dev/null +++ b/src/utils/intconv.h @@ -0,0 +1,82 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#ifndef INTCONV_H +#define INTCONV_H + +#include + +#include "../bytes/view.h" + +using Byte = uint8_t; ///< Typedef for Byte. +using Bytes = std::vector; ///< Typedef for Bytes. +template using BytesArr = std::array; ///< Typedef for BytesArr. + +// Used internally by bytesToInt256(). +using uint256_t = boost::multiprecision::number>; + +///@{ +/** Aliases for int_t. 8/16/32/64 are builtin from std. */ +using int256_t = boost::multiprecision::number>; +using int248_t = boost::multiprecision::number>; +using int240_t = boost::multiprecision::number>; +using int232_t = boost::multiprecision::number>; +using int224_t = boost::multiprecision::number>; +using int216_t = boost::multiprecision::number>; +using int208_t = boost::multiprecision::number>; +using int200_t = boost::multiprecision::number>; +using int192_t = boost::multiprecision::number>; +using int184_t = boost::multiprecision::number>; +using int176_t = boost::multiprecision::number>; +using int168_t = boost::multiprecision::number>; +using int160_t = boost::multiprecision::number>; +using int152_t = boost::multiprecision::number>; +using int144_t = boost::multiprecision::number>; +using int136_t = boost::multiprecision::number>; +using int128_t = boost::multiprecision::number>; +using int120_t = boost::multiprecision::number>; +using int112_t = boost::multiprecision::number>; +using int104_t = boost::multiprecision::number>; +using int96_t = boost::multiprecision::number>; +using int88_t = boost::multiprecision::number>; +using int80_t = boost::multiprecision::number>; +using int72_t = boost::multiprecision::number>; +using int56_t = boost::multiprecision::number>; +using int48_t = boost::multiprecision::number>; +using int40_t = boost::multiprecision::number>; +using int24_t = boost::multiprecision::number>; +///@} + +// TODO: theoretically missing the other intervals + +/// Namespace for signed integer conversion functions. +namespace IntConv { + ///@{ + /** + * Convert a given integer to a bytes string. Use `Hex()` to properly print it. + * @param i The integer to convert. + * @return The converted integer as a bytes string. + */ + BytesArr<32> int256ToBytes(const int256_t& i); + BytesArr<17> int136ToBytes(const int136_t& i); + BytesArr<8> int64ToBytes(const int64_t& i); + ///@} + + ///@{ + /** + * Convert a given bytes string to an integer. + * @param b The bytes string to convert. + * @return The converted integer. + * @throw DynamicException if string size is invalid. + */ + int256_t bytesToInt256(const bytes::View b); + int136_t bytesToInt136(const bytes::View b); + int64_t bytesToInt64(const bytes::View b); + ///@} +}; + +#endif // INTCONV_H diff --git a/src/utils/jsonabi.h b/src/utils/jsonabi.h index 0e9ee154d..a26e758a0 100644 --- a/src/utils/jsonabi.h +++ b/src/utils/jsonabi.h @@ -8,12 +8,7 @@ See the LICENSE.txt file in the project root for more information. #ifndef JSONABI_H #define JSONABI_H -#include - -#include "contractreflectioninterface.h" -#include "utils.h" // contains nlohmann/json.hpp - -#include "../contract/customcontracts.h" +#include "../contract/customcontracts.h" // contract templates -> dynamiccontract.h -> contracthost.h -> contractreflectioninterface.h -> contract/abi.h -> utils.h, libs/json.hpp /// Namespace for managing and converting contract ABI data to JSON format. namespace JsonAbi { diff --git a/src/utils/logger.h b/src/utils/logger.h index 90b7b3526..d84dc11fd 100644 --- a/src/utils/logger.h +++ b/src/utils/logger.h @@ -8,17 +8,19 @@ See the LICENSE.txt file in the project root for more information. #ifndef LOGGER_H #define LOGGER_H -#include -#include +// TODO: find out where those are coming from +//#include +//#include +//#include + +#include // used by core/consensus.h +#include // condition_variable, mutex +#include // used by core/consensus.h +#include // used by core/consensus.h +#include // used by core/consensus.h #include -#include -#include -#include -#include -#include -#include -#include -#include + +#include // includes string /// Enum for the log message types. enum class LogType { XTRACE, TRACE, DEBUG, INFO, WARNING, ERROR, FATAL, NONE }; @@ -159,26 +161,14 @@ namespace Log { return oss.str(); } - /** - * Get the ID of the current thread as a string. - * @return The ID of the current thread as a string. - */ - inline std::string getThreadIdAsString() { - std::ostringstream oss; - oss << std::this_thread::get_id(); - return oss.str(); - } - /// LOG macro provider of logical location when the class of `this` extends `LogicalLocationProvider`. - template - std::string getLogicalLocationIfAvailable(T* obj, std::true_type) { + template std::string getLogicalLocationIfAvailable(T* obj, std::true_type) { return obj->getLogicalLocation(); } - /// LOG macro provider of a default logical location (thread ID + value of `this` pointer). - template - std::string getLogicalLocationIfAvailable(T* obj, std::false_type) { - return "{" + getThreadIdAsString() + "," + pointerToHexString(obj) + "}"; + /// LOG macro provider of a default logical location (value of `this` pointer). + template std::string getLogicalLocationIfAvailable(T* obj, std::false_type) { + return "{" + pointerToHexString(obj) + "}"; } /// Get a pretty "ClassName::MethodName" for the current `this` object. diff --git a/src/utils/merkle.h b/src/utils/merkle.h index db2e9ad43..3b98f2901 100644 --- a/src/utils/merkle.h +++ b/src/utils/merkle.h @@ -8,15 +8,12 @@ See the LICENSE.txt file in the project root for more information. #ifndef MERKLE_H #define MERKLE_H -#include -#include +// TODO: find out where those are coming from +//#include +//#include -#include "safehash.h" -#include "strings.h" -#include "tx.h" -#include "utils.h" - -#include "../bytes/join.h" +//#include "safehash.h" // TODO: probably not used +#include "tx.h" // ecdsa.h -> utils.h -> strings.h, bytes/join.h /** * Custom implementation of a %Merkle tree. diff --git a/src/utils/options.cpp b/src/utils/options.cpp index 47b6d18a0..b9f07d758 100644 --- a/src/utils/options.cpp +++ b/src/utils/options.cpp @@ -7,6 +7,29 @@ See the LICENSE.txt file in the project root for more information. #include "options.h" +#include "dynamicexception.h" + +IndexingMode::IndexingMode(std::string_view mode) { + if (mode == "DISABLED") { + value_ = DISABLED.value_; + } else if (mode == "RPC") { + value_ = RPC.value_; + } else if (mode == "RPC_TRACE") { + value_ = RPC_TRACE.value_; + } else { + std::stringstream errorMessage; + errorMessage << "Invalid indexing mode value: \"" << mode << "\""; + throw DynamicException(errorMessage.str()); + } +} + +constexpr std::string_view IndexingMode::toString() const { + if (*this == DISABLED) return "DISABLED"; + if (*this == RPC) return "RPC"; + if (*this == RPC_TRACE) return "RPC_TRACE"; + throw DynamicException("Unknown indexing mode"); +} + Options::Options( const std::string& rootPath, const std::string& web3clientVersion, const uint64_t& version, const uint64_t& chainID, const Address& chainOwner, diff --git a/src/utils/options.h.in b/src/utils/options.h.in index ab555bddb..b5c7e43c9 100644 --- a/src/utils/options.h.in +++ b/src/utils/options.h.in @@ -8,12 +8,7 @@ See the LICENSE.txt file in the project root for more information. #ifndef OPTIONS_H #define OPTIONS_H -#include "utils.h" -#include "ecdsa.h" -#include "finalizedblock.h" - -#include -#include +#include "finalizedblock.h" // merkle.h -> tx.h -> ecdsa.h -> utils.h -> filesystem, boost/asio/ip/address.hpp /** * Example options.json file: @@ -57,45 +52,22 @@ See the LICENSE.txt file in the project root for more information. * } */ +// TODO: docs +/// Helper class for setting the node's indexing mode. class IndexingMode { -private: - int value_; - - constexpr explicit IndexingMode(int value) : value_(value) {} - -public: - static const IndexingMode DISABLED; - static const IndexingMode RPC; - static const IndexingMode RPC_TRACE; - - explicit IndexingMode(std::string_view mode) { - if (mode == "DISABLED") { - value_ = DISABLED.value_; - } else if (mode == "RPC") { - value_ = RPC.value_; - } else if (mode == "RPC_TRACE") { - value_ = RPC_TRACE.value_; - } else { - std::stringstream errorMessage; - errorMessage << "Invalid indexing mode value: \"" << mode << "\""; - throw DynamicException(errorMessage.str()); - } - } - - constexpr std::string_view toString() const { - if (*this == DISABLED) - return "DISABLED"; - - if (*this == RPC) - return "RPC"; + private: + int value_; + constexpr explicit IndexingMode(int value) : value_(value) {} - if (*this == RPC_TRACE) - return "RPC_TRACE"; + public: + static const IndexingMode DISABLED; + static const IndexingMode RPC; + static const IndexingMode RPC_TRACE; - throw DynamicException("Unknown indexing mode"); - } + explicit IndexingMode(std::string_view mode); // throws DynamicException + constexpr std::string_view toString() const; // throws DynamicException - constexpr bool operator==(const IndexingMode&) const = default; + constexpr bool operator==(const IndexingMode&) const = default; }; constexpr const IndexingMode IndexingMode::DISABLED{0}; diff --git a/src/utils/randomgen.h b/src/utils/randomgen.h index f345355f0..983967ba3 100644 --- a/src/utils/randomgen.h +++ b/src/utils/randomgen.h @@ -8,12 +8,13 @@ See the LICENSE.txt file in the project root for more information. #ifndef RANDOMGEN_H #define RANDOMGEN_H -#include -#include -#include -#include -#include -#include +// TODO: fond out where those are coming from (probably utils.h) +//#include +//#include +//#include +//#include +//#include +//#include #include "utils.h" diff --git a/src/utils/safehash.h b/src/utils/safehash.h index a07ca48a2..b41fb1308 100644 --- a/src/utils/safehash.h +++ b/src/utils/safehash.h @@ -8,15 +8,12 @@ See the LICENSE.txt file in the project root for more information. #ifndef HASH_H #define HASH_H -#include -#include +//#include // TODO: probably not used(?) -#include "../bytes/join.h" #include "../libs/wyhash.h" -#include "strings.h" -#include "utils.h" -#include "tx.h" +#include "tx.h" // ecdsa.h -> utils.h -> strings.h, bytes/join.h, boost/asio/ip/address.hpp +#include "uintconv.h" /** * Custom hashing implementation for use in `boost::unordered_flat_map` @@ -81,11 +78,11 @@ struct SafeHash { Bytes bytes; if (nodeId.first.is_v4()) { bytes = Utils::makeBytes(bytes::join( - nodeId.first.to_v4().to_bytes(), Utils::uint16ToBytes(nodeId.second) + nodeId.first.to_v4().to_bytes(), UintConv::uint16ToBytes(nodeId.second) )); } else { bytes = Utils::makeBytes(bytes::join( - nodeId.first.to_v6().to_bytes(), Utils::uint16ToBytes(nodeId.second) + nodeId.first.to_v6().to_bytes(), UintConv::uint16ToBytes(nodeId.second) )); } return SafeHash()(bytes); diff --git a/src/utils/strconv.cpp b/src/utils/strconv.cpp new file mode 100644 index 000000000..754243bfb --- /dev/null +++ b/src/utils/strconv.cpp @@ -0,0 +1,60 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#include "strconv.h" + +#include // std::transform + +Bytes StrConv::cArrayToBytes(const uint8_t* arr, size_t size) { + Bytes ret; + ret.reserve(size); + for (size_t i = 0; i < size; i++) ret.push_back(arr[i]); + return ret; +} + +Bytes StrConv::padLeftBytes(const bytes::View bytes, unsigned int charAmount, uint8_t sign) { + size_t padding = (charAmount > bytes.size()) ? (charAmount - bytes.size()) : 0; + Bytes padded = (padding != 0) ? Bytes(padding, sign) : Bytes(0, 0x00); + padded.reserve(bytes.size() + padded.size()); + padded.insert(padded.end(), bytes.begin(), bytes.end()); + return padded; +} + +Bytes StrConv::padRightBytes(const bytes::View bytes, unsigned int charAmount, uint8_t sign) { + size_t padding = (charAmount > bytes.size()) ? (charAmount - bytes.size()) : 0; + Bytes padded = (padding != 0) ? Bytes(padding, sign) : Bytes(0, 0x00); + Bytes ret; + ret.reserve(bytes.size() + padded.size()); + ret.insert(ret.end(), bytes.begin(), bytes.end()); + ret.insert(ret.end(), padded.begin(), padded.end()); + return ret; +} + +std::string StrConv::padLeft(std::string str, unsigned int charAmount, char sign) { + bool hasPrefix = (str.starts_with("0x") || str.starts_with("0X")); + if (hasPrefix) str = str.substr(2); + size_t padding = (charAmount > str.length()) ? (charAmount - str.length()) : 0; + std::string padded = (padding != 0) ? std::string(padding, sign) : ""; + return (hasPrefix ? "0x" : "") + padded + str; +} + +std::string StrConv::padRight(std::string str, unsigned int charAmount, char sign) { + bool hasPrefix = (str.starts_with("0x") || str.starts_with("0X")); + if (hasPrefix) str = str.substr(2); + size_t padding = (charAmount > str.length()) ? (charAmount - str.length()) : 0; + std::string padded = (padding != 0) ? std::string(padding, sign) : ""; + return (hasPrefix ? "0x" : "") + str + padded; +} + +void StrConv::toLower(std::string& str) { + std::transform(str.begin(), str.end(), str.begin(), ::tolower); +} + +void StrConv::toUpper(std::string& str) { + std::transform(str.begin(), str.end(), str.begin(), ::toupper); +} + diff --git a/src/utils/strconv.h b/src/utils/strconv.h new file mode 100644 index 000000000..bb822319a --- /dev/null +++ b/src/utils/strconv.h @@ -0,0 +1,73 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#ifndef STRCONV_H +#define STRCONV_H + +#include // uint8_t +#include +#include + +#include "../bytes/view.h" + +using Byte = uint8_t; ///< Typedef for Byte. +using Bytes = std::vector; ///< Typedef for Bytes. + +/// Namespace for general string manipulation and conversion functions. +namespace StrConv { + /** + * Convert a C-style raw byte array to a raw bytes string. + * @param arr The array to convert. + * @param size The size of the array. + * @return The converted raw bytes string. + */ + Bytes cArrayToBytes(const uint8_t* arr, size_t size); + + /** + * Add padding to the left of a byte vector. + * @param bytes The vector to pad. + * @param charAmount The total amount of characters the resulting string should have. + * If this is less than the string's original size, + * the string will remain untouched. + * e.g. `padLeftBytes("aaa", 5)` = "00aaa", `padLeftBytes("aaa", 2)` = "aaa" + * @param sign (optional) The character to use as padding. Defaults to '0'. + * @return The padded vector. + */ + Bytes padLeftBytes(const bytes::View bytes, unsigned int charAmount, uint8_t sign = 0x00); + + /** + * Add padding to the right of a byte vector. + * @param bytes The vector to pad. + * @param charAmount The total amount of characters the resulting string should have. + * If this is less than the string's original size, + * the string will remain untouched. + * e.g. `padLeftBytes("aaa", 5)` = "aaa00", `padLeftBytes("aaa", 2)` = "aaa" + * @param sign (optional) The character to use as padding. Defaults to '0'. + * @return The padded vector. + */ + Bytes padRightBytes(const bytes::View bytes, unsigned int charAmount, uint8_t sign = 0x00); + + /// Overload of padLeftBytes() that works with UTF-8 strings. + std::string padLeft(std::string str, unsigned int charAmount, char sign = '\x00'); + + /// Overload of padRightBytes() that works with UTF-8 strings. + std::string padRight(std::string str, unsigned int charAmount, char sign = '\x00'); + + /** + * Convert a string to all-lowercase. Conversion is done in-place. + * @param str The string to convert. + */ + void toLower(std::string& str); + + /** + * Convert a string to all-uppercase. Conversion is done in-place. + * @param str The string to convert. + */ + void toUpper(std::string& str); +}; + +#endif // STRCONV_H diff --git a/src/utils/strings.cpp b/src/utils/strings.cpp index badc2a027..ddc4f8646 100644 --- a/src/utils/strings.cpp +++ b/src/utils/strings.cpp @@ -6,9 +6,9 @@ See the LICENSE.txt file in the project root for more information. */ #include "strings.h" -#include "utils.h" +#include "utils.h" // also includes "strings.h" -Hash::Hash(const uint256_t& data) : FixedBytes<32>(Utils::uint256ToBytes(data)) {}; +Hash::Hash(const uint256_t& data) : FixedBytes<32>(UintConv::uint256ToBytes(data)) {}; Hash::Hash(const std::string_view sv) { if (sv.size() != 32) throw std::invalid_argument("Hash must be 32 bytes long."); @@ -20,7 +20,7 @@ Hash::Hash(const evmc::bytes32& data) { std::copy(data.bytes, data.bytes + 32, this->begin()); } -uint256_t Hash::toUint256() const { return Utils::bytesToUint256(*this); } +uint256_t Hash::toUint256() const { return UintConv::bytesToUint256(*this); } evmc::bytes32 Hash::toEvmcBytes32() const { evmc::bytes32 bytes; @@ -28,11 +28,11 @@ evmc::bytes32 Hash::toEvmcBytes32() const { return bytes; } -uint256_t Signature::r() const { return Utils::bytesToUint256(this->view(0, 32)); } +uint256_t Signature::r() const { return UintConv::bytesToUint256(this->view(0, 32)); } -uint256_t Signature::s() const { return Utils::bytesToUint256(this->view(32, 32)); } +uint256_t Signature::s() const { return UintConv::bytesToUint256(this->view(32, 32)); } -uint8_t Signature::v() const { return Utils::bytesToUint8(this->view(64, 1)); } +uint8_t Signature::v() const { return UintConv::bytesToUint8(this->view(64, 1)); } Address::Address(const std::string_view add, bool inBytes) { if (inBytes) { diff --git a/src/utils/strings.h b/src/utils/strings.h index d7c3dcef1..e0f43c0f4 100644 --- a/src/utils/strings.h +++ b/src/utils/strings.h @@ -8,16 +8,16 @@ See the LICENSE.txt file in the project root for more information. #ifndef STRINGS_H #define STRINGS_H -#include +#include // evmc/hex.hpp -> string #include -#include -#include -#include +#include "../libs/zpp_bits.h" // algorithm + +#include "../bytes/initializer.h" // bytes/view.h -> bytes/range.h -> ranges -> span + +#include "dynamicexception.h" // TODO: see the size todo below #include "hex.h" -#include "bytes/range.h" -#include "bytes/initializer.h" -#include "zpp_bits.h" +#include "uintconv.h" // TODO: It is possible to implement **fast** operators for some types, // such as Address, Functor and Hash. Taking advantage that memory located within @@ -44,47 +44,58 @@ template class FixedBytes { using serialize = zpp::bits::members<1>; public: + /// Empty constructor. constexpr FixedBytes() : data_() {}; - constexpr FixedBytes(std::initializer_list initList) { - if (initList.size() != N) - throw DynamicException("Given initializer list of size " + std::to_string(initList.size()) + - " is not suitable for initializing a FixedBytes<" + std::to_string(N) + ">"); + // TODO: maybe rework the size checks here so we don't have to use exceptions? - std::ranges::copy(initList, data_.begin()); + /// Constructor with initializer list. + constexpr FixedBytes(std::initializer_list ilist) { + if (ilist.size() != N) + throw DynamicException("Given initializer list of size " + std::to_string(ilist.size()) + + " is not suitable for initializing a FixedBytes<" + std::to_string(N) + ">"); + std::ranges::copy(ilist, data_.begin()); } + /// Constructor with a bytes initializer. constexpr FixedBytes(const bytes::Initializer auto& initializer) { initializer.to(data_); } + /// Constructor with a bytes range. constexpr explicit FixedBytes(const bytes::Range auto& data) { if (const size_t size = std::ranges::size(data); size != N) - throw DynamicException("Given bytes range of size " + std::to_string(size) + + throw DynamicException("Given bytes range of size " + std::to_string(size) + " is not suitable for initializing a FixedBytes<" + std::to_string(N) + ">"); - std::ranges::copy(data, data_.begin()); } + ///@{ + /* Get a pointer to the beginning of the bytes string. */ constexpr auto begin() { return data_.begin(); } - constexpr auto begin() const { return data_.begin(); } - constexpr auto cbegin() const { return data_.cbegin(); } + ///@} + ///@{ + /* Get a pointer to the end of the bytes string. */ constexpr auto end() { return data_.end(); } - constexpr auto end() const { return data_.end(); } - constexpr auto cend() const { return data_.cend(); } + ///@} + ///@{ + /* Get a pointer to the bytes string's underlying data. */ constexpr Byte* data() { return data_.data(); } - constexpr const Byte* data() const { return data_.data(); } + ///@} + /// Get the total size of the bytes string. constexpr size_t size() const { return data_.size(); } + ///@{ + /* Indexing operator. */ constexpr Byte& operator[](size_t index) { return data_[index]; } - constexpr const Byte& operator[](size_t index) const { return data_[index]; } + ///@} /** * Getter for `data_`, but returns it as a hex string. diff --git a/src/utils/tx.cpp b/src/utils/tx.cpp index a8bb0b908..ef3d318af 100644 --- a/src/utils/tx.cpp +++ b/src/utils/tx.cpp @@ -7,6 +7,9 @@ See the LICENSE.txt file in the project root for more information. #include "tx.h" +#include "dynamicexception.h" +#include "evmcconv.h" + TxBlock::TxBlock(const bytes::View bytes, const uint64_t&) { uint64_t index = 0; bytes::View txData = bytes.subspan(1); @@ -66,8 +69,8 @@ TxBlock::TxBlock( Hash msgHash = Utils::sha3(this->rlpSerialize(false)); // Do not include signature Signature sig = Secp256k1::sign(msgHash, privKey); - this->r_ = Utils::bytesToUint256(sig.view(0, 32)); - this->s_ = Utils::bytesToUint256(sig.view(32,32)); + this->r_ = UintConv::bytesToUint256(sig.view(0, 32)); + this->s_ = UintConv::bytesToUint256(sig.view(32,32)); this->v_ = sig[64]; if (pubKey != Secp256k1::recover(sig, msgHash)) { @@ -482,7 +485,7 @@ evmc_message TxBlock::txToMessage() const { msg.sender = this->from_.toEvmcAddress(); msg.input_data = (this->data_.empty()) ? nullptr : this->data_.data(); msg.input_size = this->data_.size(); - msg.value = Utils::uint256ToEvmcUint256(this->value_); + msg.value = EVMCConv::uint256ToEvmcUint256(this->value_); msg.create2_salt = {}; msg.code_address = this->to_.toEvmcAddress(); return msg; @@ -545,8 +548,8 @@ TxValidator::TxValidator( if (add != this->from_) throw DynamicException("Private key does not match sender address (from)"); Signature sig = Secp256k1::sign(msgHash, privKey); - this->r_ = Utils::bytesToUint256(sig.view(0, 32)); - this->s_ = Utils::bytesToUint256(sig.view(32,32)); + this->r_ = UintConv::bytesToUint256(sig.view(0, 32)); + this->s_ = UintConv::bytesToUint256(sig.view(32,32)); uint8_t recoveryIds = sig[64]; this->v_ = recoveryIds + (this->chainId_ * 2 + 35); diff --git a/src/utils/tx.h b/src/utils/tx.h index 233c78fb1..3a0b3b766 100644 --- a/src/utils/tx.h +++ b/src/utils/tx.h @@ -8,11 +8,8 @@ See the LICENSE.txt file in the project root for more information. #ifndef TX_H #define TX_H -#include "../bytes/view.h" - -#include "ecdsa.h" -#include "strings.h" -#include "utils.h" +#include "ecdsa.h" // utils.h -> strings.h, (bytes/join.h -> bytes/view.h) +#include "uintconv.h" /** * Abstraction of a block transaction. @@ -292,7 +289,7 @@ class TxValidator { inline const Bytes& getData() const { return this->data_; } inline Functor getFunctor() const { Functor ret; if (this->data_.size() < 4) return ret; - ret.value = Utils::bytesToUint32(Utils::create_view_span(this->data_, 0, 4)); + ret.value = UintConv::bytesToUint32(Utils::create_view_span(this->data_, 0, 4)); return ret; } inline const uint64_t& getChainId() const { return this->chainId_; } diff --git a/src/utils/uintconv.cpp b/src/utils/uintconv.cpp new file mode 100644 index 000000000..713abb524 --- /dev/null +++ b/src/utils/uintconv.cpp @@ -0,0 +1,603 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#include "uintconv.h" + +#include "dynamicexception.h" + +// ========================================================================== +// UINT TO BYTES +// ========================================================================== + +BytesArr<32> UintConv::uint256ToBytes(const uint256_t& i) { + BytesArr<32> ret; + Bytes tmp; + tmp.reserve(32); + ret.fill(0x00); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[31 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<31> UintConv::uint248ToBytes(const uint248_t &i) { + BytesArr<31> ret; + Bytes tmp; + tmp.reserve(31); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + // Replace bytes from tmp to ret to make it the right size. Applies to all similar functions. + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[30 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<30> UintConv::uint240ToBytes(const uint240_t &i) { + BytesArr<30> ret; + Bytes tmp; + tmp.reserve(30); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[29 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<29> UintConv::uint232ToBytes(const uint232_t &i) { + BytesArr<29> ret; + Bytes tmp; + tmp.reserve(29); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[28 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<28> UintConv::uint224ToBytes(const uint224_t &i) { + BytesArr<28> ret; + Bytes tmp; + tmp.reserve(28); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[27 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<27> UintConv::uint216ToBytes(const uint216_t &i) { + BytesArr<27> ret; + Bytes tmp; + tmp.reserve(27); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[26 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<26> UintConv::uint208ToBytes(const uint208_t &i) { + BytesArr<26> ret; + Bytes tmp; + tmp.reserve(26); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[25 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<25> UintConv::uint200ToBytes(const uint200_t &i) { + BytesArr<25> ret; + Bytes tmp; + tmp.reserve(25); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[24 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<24> UintConv::uint192ToBytes(const uint192_t &i) { + BytesArr<24> ret; + Bytes tmp; + tmp.reserve(24); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[23 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<23> UintConv::uint184ToBytes(const uint184_t &i) { + BytesArr<23> ret; + Bytes tmp; + tmp.reserve(23); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[22 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<22> UintConv::uint176ToBytes(const uint176_t &i) { + BytesArr<22> ret; + Bytes tmp; + tmp.reserve(22); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[21 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<21> UintConv::uint168ToBytes(const uint168_t &i) { + BytesArr<21> ret; + Bytes tmp; + tmp.reserve(21); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[20 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<20> UintConv::uint160ToBytes(const uint160_t &i) { + BytesArr<20> ret; + Bytes tmp; + tmp.reserve(20); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[19 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<19> UintConv::uint152ToBytes(const uint152_t &i) { + BytesArr<19> ret; + Bytes tmp; + tmp.reserve(19); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[18 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<18> UintConv::uint144ToBytes(const uint144_t &i) { + BytesArr<18> ret; + Bytes tmp; + tmp.reserve(18); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[17 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<17> UintConv::uint136ToBytes(const uint136_t &i) { + BytesArr<17> ret; + Bytes tmp; + tmp.reserve(17); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[16 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<16> UintConv::uint128ToBytes(const uint128_t &i) { + BytesArr<16> ret; + Bytes tmp; + tmp.reserve(16); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[15 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<15> UintConv::uint120ToBytes(const uint120_t &i) { + BytesArr<15> ret; + Bytes tmp; + tmp.reserve(15); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[14 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<14> UintConv::uint112ToBytes(const uint112_t &i) { + BytesArr<14> ret; + Bytes tmp; + tmp.reserve(14); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[13 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<13> UintConv::uint104ToBytes(const uint104_t &i) { + BytesArr<13> ret; + Bytes tmp; + tmp.reserve(13); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[12 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<12> UintConv::uint96ToBytes(const uint96_t &i) { + BytesArr<12> ret; + Bytes tmp; + tmp.reserve(12); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[11 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<11> UintConv::uint88ToBytes(const uint88_t &i) { + BytesArr<11> ret; + Bytes tmp; + tmp.reserve(11); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[10 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<10> UintConv::uint80ToBytes(const uint80_t &i) { + BytesArr<10> ret; + Bytes tmp; + tmp.reserve(10); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[9 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<9> UintConv::uint72ToBytes(const uint72_t &i) { + BytesArr<9> ret; + Bytes tmp; + tmp.reserve(9); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[8 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<7> UintConv::uint56ToBytes(const uint56_t &i) { + BytesArr<7> ret; + Bytes tmp; + tmp.reserve(7); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[6 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<6> UintConv::uint48ToBytes(const uint48_t &i) { + BytesArr<6> ret; + Bytes tmp; + tmp.reserve(6); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[5 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<5> UintConv::uint40ToBytes(const uint40_t &i) { + BytesArr<5> ret; + Bytes tmp; + tmp.reserve(5); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[4 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<3> UintConv::uint24ToBytes(const uint24_t &i) { + BytesArr<3> ret; + Bytes tmp; + tmp.reserve(3); + boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); + for (unsigned ii = 0; ii < tmp.size(); ii++) ret[2 - ii] = tmp[tmp.size() - ii - 1]; + return ret; +} + +BytesArr<8> UintConv::uint64ToBytes(const uint64_t& i) { + BytesArr<8> ret; + std::memcpy(&ret[0], &i, 8); + #if __BYTE_ORDER == __LITTLE_ENDIAN + std::reverse(ret.begin(), ret.end()); + #endif + return ret; +} + +BytesArr<4> UintConv::uint32ToBytes(const uint32_t& i) { + BytesArr<4> ret; + std::memcpy(&ret[0], &i, 4); + #if __BYTE_ORDER == __LITTLE_ENDIAN + std::reverse(ret.begin(), ret.end()); + #endif + return ret; +} + +BytesArr<2> UintConv::uint16ToBytes(const uint16_t& i) { + BytesArr<2> ret; + std::memcpy(&ret[0], &i, 2); + #if __BYTE_ORDER == __LITTLE_ENDIAN + std::reverse(ret.begin(), ret.end()); + #endif + return ret; +} + +BytesArr<1> UintConv::uint8ToBytes(const uint8_t& i) { + BytesArr<1> ret; + std::memcpy(&ret[0], &i, 1); + return ret; +} + +// ========================================================================== +// BYTES TO UINT +// ========================================================================== + +uint256_t UintConv::bytesToUint256(const bytes::View b) { + if (b.size() != 32) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 32, got " + std::to_string(b.size()) + ); + uint256_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint248_t UintConv::bytesToUint248(const bytes::View b) { + if (b.size() != 31) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 31, got " + std::to_string(b.size()) + ); + uint248_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint240_t UintConv::bytesToUint240(const bytes::View b) { + if (b.size() != 30) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 30, got " + std::to_string(b.size()) + ); + uint240_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint232_t UintConv::bytesToUint232(const bytes::View b) { + if (b.size() != 29) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 29, got " + std::to_string(b.size()) + ); + uint232_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint224_t UintConv::bytesToUint224(const bytes::View b) { + if (b.size() != 28) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 28, got " + std::to_string(b.size()) + ); + uint224_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint216_t UintConv::bytesToUint216(const bytes::View b) { + if (b.size() != 27) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 27, got " + std::to_string(b.size()) + ); + uint216_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint208_t UintConv::bytesToUint208(const bytes::View b) { + if (b.size() != 26) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 26, got " + std::to_string(b.size()) + ); + uint208_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint200_t UintConv::bytesToUint200(const bytes::View b) { + if (b.size() != 25) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 25, got " + std::to_string(b.size()) + ); + uint200_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint192_t UintConv::bytesToUint192(const bytes::View b) { + if (b.size() != 24) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 24, got " + std::to_string(b.size()) + ); + uint192_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint184_t UintConv::bytesToUint184(const bytes::View b) { + if (b.size() != 23) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 23, got " + std::to_string(b.size()) + ); + uint184_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint176_t UintConv::bytesToUint176(const bytes::View b) { + if (b.size() != 22) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 22, got " + std::to_string(b.size()) + ); + uint176_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint168_t UintConv::bytesToUint168(const bytes::View b) { + if (b.size() != 21) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 21, got " + std::to_string(b.size()) + ); + uint168_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint160_t UintConv::bytesToUint160(const bytes::View b) { + if (b.size() != 20) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 20, got " + std::to_string(b.size()) + ); + uint160_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint152_t UintConv::bytesToUint152(const bytes::View b) { + if (b.size() != 19) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 19, got " + std::to_string(b.size()) + ); + uint152_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint144_t UintConv::bytesToUint144(const bytes::View b) { + if (b.size() != 18) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 18, got " + std::to_string(b.size()) + ); + uint144_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint136_t UintConv::bytesToUint136(const bytes::View b) { + if (b.size() != 17) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 17, got " + std::to_string(b.size()) + ); + uint136_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint128_t UintConv::bytesToUint128(const bytes::View b) { + if (b.size() != 16) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 16, got " + std::to_string(b.size()) + ); + uint128_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint120_t UintConv::bytesToUint120(const bytes::View b) { + if (b.size() != 15) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 15, got " + std::to_string(b.size()) + ); + uint120_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint112_t UintConv::bytesToUint112(const bytes::View b) { + if (b.size() != 14) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 16, got " + std::to_string(b.size()) + ); + uint112_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint104_t UintConv::bytesToUint104(const bytes::View b) { + if (b.size() != 13) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 13, got " + std::to_string(b.size()) + ); + uint104_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint96_t UintConv::bytesToUint96(const bytes::View b) { + if (b.size() != 12) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 12, got " + std::to_string(b.size()) + ); + uint96_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint88_t UintConv::bytesToUint88(const bytes::View b) { + if (b.size() != 11) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 11, got " + std::to_string(b.size()) + ); + uint88_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint80_t UintConv::bytesToUint80(const bytes::View b) { + if (b.size() != 10) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 10, got " + std::to_string(b.size()) + ); + uint80_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint72_t UintConv::bytesToUint72(const bytes::View b) { + if (b.size() != 9) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 9, got " + std::to_string(b.size()) + ); + uint72_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint56_t UintConv::bytesToUint56(const bytes::View b) { + if (b.size() != 7) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 7, got " + std::to_string(b.size()) + ); + uint56_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint48_t UintConv::bytesToUint48(const bytes::View b) { + if (b.size() != 6) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 6, got " + std::to_string(b.size()) + ); + uint48_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint40_t UintConv::bytesToUint40(const bytes::View b) { + if (b.size() != 5) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 5, got " + std::to_string(b.size()) + ); + uint40_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint24_t UintConv::bytesToUint24(const bytes::View b) { + if (b.size() != 3) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 3, got " + std::to_string(b.size()) + ); + uint24_t ret; + boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); + return ret; +} + +uint64_t UintConv::bytesToUint64(const bytes::View b) { + if (b.size() != 8) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 8, got " + std::to_string(b.size()) + ); + uint64_t ret = 0; + std::memcpy(&ret, b.data(), 8); + #if __BYTE_ORDER == __LITTLE_ENDIAN + return __builtin_bswap64(ret); + #endif + return ret; +} + +uint32_t UintConv::bytesToUint32(const bytes::View b) { + if (b.size() != 4) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 4, got " + std::to_string(b.size()) + ); + uint32_t ret = 0; + std::memcpy(&ret, b.data(), 4); + #if __BYTE_ORDER == __LITTLE_ENDIAN + return __builtin_bswap32(ret); + #endif + return ret; +} + +uint16_t UintConv::bytesToUint16(const bytes::View b) { + if (b.size() != 2) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 2, got " + std::to_string(b.size()) + ); + uint16_t ret = 0; + std::memcpy(&ret, b.data(), 2); + #if __BYTE_ORDER == __LITTLE_ENDIAN + return __builtin_bswap16(ret); + #endif + return ret; +} + +uint8_t UintConv::bytesToUint8(const bytes::View b) { + if (b.size() != 1) throw DynamicException(std::string(__func__) + + ": Invalid bytes size - expected 1, got " + std::to_string(b.size()) + ); + uint8_t ret; + ret = b[0]; + return ret; +} + diff --git a/src/utils/uintconv.h b/src/utils/uintconv.h new file mode 100644 index 000000000..017dec170 --- /dev/null +++ b/src/utils/uintconv.h @@ -0,0 +1,137 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#ifndef UINTCONV_H +#define UINTCONV_H + +#include + +#include "../bytes/view.h" + +using Byte = uint8_t; ///< Typedef for Byte. +using Bytes = std::vector; ///< Typedef for Bytes. +template using BytesArr = std::array; ///< Typedef for BytesArr. + +///@{ +/** Aliases for uint_t. 8/16/32/64 are builtin from std. */ +using uint256_t = boost::multiprecision::number>; +using uint248_t = boost::multiprecision::number>; +using uint240_t = boost::multiprecision::number>; +using uint232_t = boost::multiprecision::number>; +using uint224_t = boost::multiprecision::number>; +using uint216_t = boost::multiprecision::number>; +using uint208_t = boost::multiprecision::number>; +using uint200_t = boost::multiprecision::number>; +using uint192_t = boost::multiprecision::number>; +using uint184_t = boost::multiprecision::number>; +using uint176_t = boost::multiprecision::number>; +using uint168_t = boost::multiprecision::number>; +using uint160_t = boost::multiprecision::number>; +using uint152_t = boost::multiprecision::number>; +using uint144_t = boost::multiprecision::number>; +using uint136_t = boost::multiprecision::number>; +using uint128_t = boost::multiprecision::number>; +using uint120_t = boost::multiprecision::number>; +using uint112_t = boost::multiprecision::number>; +using uint104_t = boost::multiprecision::number>; +using uint96_t = boost::multiprecision::number>; +using uint88_t = boost::multiprecision::number>; +using uint80_t = boost::multiprecision::number>; +using uint72_t = boost::multiprecision::number>; +using uint56_t = boost::multiprecision::number>; +using uint48_t = boost::multiprecision::number>; +using uint40_t = boost::multiprecision::number>; +using uint24_t = boost::multiprecision::number>; +///@} + +/// Namespace for unsigned integer conversion functions. +namespace UintConv { + ///@{ + /** + * Convert a given integer to a bytes string. Use `Hex()` to properly print it. + * @param i The integer to convert. + * @return The converted integer as a bytes string. + */ + BytesArr<32> uint256ToBytes(const uint256_t& i); + BytesArr<31> uint248ToBytes(const uint248_t& i); + BytesArr<30> uint240ToBytes(const uint240_t& i); + BytesArr<29> uint232ToBytes(const uint232_t& i); + BytesArr<28> uint224ToBytes(const uint224_t& i); + BytesArr<27> uint216ToBytes(const uint216_t& i); + BytesArr<26> uint208ToBytes(const uint208_t& i); + BytesArr<25> uint200ToBytes(const uint200_t& i); + BytesArr<24> uint192ToBytes(const uint192_t& i); + BytesArr<23> uint184ToBytes(const uint184_t& i); + BytesArr<22> uint176ToBytes(const uint176_t& i); + BytesArr<21> uint168ToBytes(const uint168_t& i); + BytesArr<20> uint160ToBytes(const uint160_t& i); + BytesArr<19> uint152ToBytes(const uint152_t& i); + BytesArr<18> uint144ToBytes(const uint144_t& i); + BytesArr<17> uint136ToBytes(const uint136_t& i); + BytesArr<16> uint128ToBytes(const uint128_t& i); + BytesArr<15> uint120ToBytes(const uint120_t& i); + BytesArr<14> uint112ToBytes(const uint112_t& i); + BytesArr<13> uint104ToBytes(const uint104_t& i); + BytesArr<12> uint96ToBytes(const uint96_t& i); + BytesArr<11> uint88ToBytes(const uint88_t& i); + BytesArr<10> uint80ToBytes(const uint80_t& i); + BytesArr<9> uint72ToBytes(const uint72_t& i); + BytesArr<7> uint56ToBytes(const uint56_t& i); + BytesArr<6> uint48ToBytes(const uint48_t& i); + BytesArr<5> uint40ToBytes(const uint40_t& i); + BytesArr<3> uint24ToBytes(const uint24_t& i); + + BytesArr<8> uint64ToBytes(const uint64_t& i); + BytesArr<4> uint32ToBytes(const uint32_t& i); + BytesArr<2> uint16ToBytes(const uint16_t& i); + BytesArr<1> uint8ToBytes(const uint8_t& i); + ///@} + + ///@{ + /** + * Convert a given bytes string to an integer. + * @param b The bytes string to convert. + * @return The converted integer. + * @throw DynamicException if string size is invalid. + */ + uint256_t bytesToUint256(const bytes::View b); + uint248_t bytesToUint248(const bytes::View b); + uint240_t bytesToUint240(const bytes::View b); + uint232_t bytesToUint232(const bytes::View b); + uint224_t bytesToUint224(const bytes::View b); + uint216_t bytesToUint216(const bytes::View b); + uint208_t bytesToUint208(const bytes::View b); + uint200_t bytesToUint200(const bytes::View b); + uint192_t bytesToUint192(const bytes::View b); + uint184_t bytesToUint184(const bytes::View b); + uint176_t bytesToUint176(const bytes::View b); + uint168_t bytesToUint168(const bytes::View b); + uint160_t bytesToUint160(const bytes::View b); + uint152_t bytesToUint152(const bytes::View b); + uint144_t bytesToUint144(const bytes::View b); + uint136_t bytesToUint136(const bytes::View b); + uint128_t bytesToUint128(const bytes::View b); + uint120_t bytesToUint120(const bytes::View b); + uint112_t bytesToUint112(const bytes::View b); + uint104_t bytesToUint104(const bytes::View b); + uint96_t bytesToUint96(const bytes::View b); + uint88_t bytesToUint88(const bytes::View b); + uint80_t bytesToUint80(const bytes::View b); + uint72_t bytesToUint72(const bytes::View b); + uint56_t bytesToUint56(const bytes::View b); + uint48_t bytesToUint48(const bytes::View b); + uint40_t bytesToUint40(const bytes::View b); + uint24_t bytesToUint24(const bytes::View b); + + uint64_t bytesToUint64(const bytes::View b); + uint32_t bytesToUint32(const bytes::View b); + uint16_t bytesToUint16(const bytes::View b); + uint8_t bytesToUint8(const bytes::View b); + ///@} +}; + +#endif // UINTCONV_H diff --git a/src/utils/utils.cpp b/src/utils/utils.cpp index de8636bdc..24d0bf589 100644 --- a/src/utils/utils.cpp +++ b/src/utils/utils.cpp @@ -5,9 +5,12 @@ This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. */ +//#include // TODO: probably not used + #include "utils.h" -#include +#include "dynamicexception.h" +#include "uintconv.h" std::mutex log_lock; std::mutex debug_mutex; @@ -26,28 +29,15 @@ void Utils::logToFile(std::string_view str) { log.close(); } -Functor Utils::getFunctor(const evmc_message& msg) { - Functor ret; - if (msg.input_size < 4) return ret; - // Memcpy the first 4 bytes from the input data to the function signature - ret.value = Utils::bytesToUint32(bytes::View(msg.input_data, 4)); - return ret; -} - Functor Utils::makeFunctor(std::string_view functionSignature) { Functor ret; // Create the hash Hash hash = Utils::sha3(bytes::View(reinterpret_cast(functionSignature.data()), functionSignature.size())); // Copy the first 4 bytes of the hash to the value - ret.value = Utils::bytesToUint32(hash.view(0,4)); + ret.value = UintConv::bytesToUint32(hash.view(0,4)); return ret; } -bytes::View Utils::getFunctionArgs(const evmc_message& msg) { - if (msg.input_size < 4) return bytes::View(); - return bytes::View(msg.input_data + 4, msg.input_size - 4); -} - void Utils::safePrint(std::string_view str) { Log::safePrint(str); } @@ -63,36 +53,10 @@ Hash Utils::sha3(const bytes::View input) { return ret; } -uint256_t Utils::evmcUint256ToUint256(const evmc::uint256be& i) { - // We can use the uint256ToBytes directly as it is std::span and we can create a span from an array - return Utils::bytesToUint256(bytes::View(i.bytes, 32)); -} - -evmc::uint256be Utils::uint256ToEvmcUint256(const uint256_t& i) { - // Convert the uint256_t to BytesArr<32> then copy it to evmc::uint256be - // evmc::uint256be is a struct with a single member, bytes, which holds a uint256 value in *big-endian* order - evmc::uint256be ret; - BytesArr<32> bytes = Utils::uint256ToBytes(i); - std::copy(bytes.begin(), bytes.end(), ret.bytes); - return ret; -} - -BytesArr<32> Utils::evmcUint256ToBytes(const evmc::uint256be& i) { - BytesArr<32> ret; - std::copy(i.bytes, i.bytes + 32, ret.begin()); - return ret; -} - -evmc::uint256be Utils::bytesToEvmcUint256(const bytes::View b) { - evmc::uint256be ret; - std::copy(b.begin(), b.end(), ret.bytes); - return ret; -} - Account::Account(const bytes::View& bytes) { if (bytes.size() < 73) throw DynamicException(std::string(__func__) + ": Invalid bytes size"); - this->balance = Utils::bytesToUint256(bytes.subspan(0,32)); - this->nonce = Utils::bytesToUint64(bytes.subspan(32,8)); + this->balance = UintConv::bytesToUint256(bytes.subspan(0,32)); + this->nonce = UintConv::bytesToUint64(bytes.subspan(32,8)); this->codeHash = Hash(bytes.subspan(40,32)); if (bytes[72] > 2) throw DynamicException(std::string(__func__) + ": Invalid contract type"); this->contractType = ContractType(bytes[72]); @@ -102,738 +66,20 @@ Account::Account(const bytes::View& bytes) { Bytes Account::serialize() const { // TODO: this could be optimized with bytes::join()? Bytes ret; - Utils::appendBytes(ret, Utils::uint256ToBytes(this->balance)); - Utils::appendBytes(ret, Utils::uint64ToBytes(this->nonce)); + Utils::appendBytes(ret, UintConv::uint256ToBytes(this->balance)); + Utils::appendBytes(ret, UintConv::uint64ToBytes(this->nonce)); Utils::appendBytes(ret, this->codeHash); ret.insert(ret.end(), char(this->contractType)); Utils::appendBytes(ret, this->code); return ret; } -Bytes Utils::cArrayToBytes(const uint8_t* arr, size_t size) { - Bytes ret; - ret.reserve(size); - for (size_t i = 0; i < size; i++) ret.push_back(arr[i]); - return ret; -} - -BytesArr<31> Utils::uint248ToBytes(const uint248_t &i) { - BytesArr<31> ret; - Bytes tmp; - tmp.reserve(31); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - // Replace bytes from tmp to ret to make it the right size. Applies to all similar functions. - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[30 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<30> Utils::uint240ToBytes(const uint240_t &i) { - BytesArr<30> ret; - Bytes tmp; - tmp.reserve(30); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[29 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<29> Utils::uint232ToBytes(const uint232_t &i) { - BytesArr<29> ret; - Bytes tmp; - tmp.reserve(29); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[28 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<28> Utils::uint224ToBytes(const uint224_t &i) { - BytesArr<28> ret; - Bytes tmp; - tmp.reserve(28); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[27 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<27> Utils::uint216ToBytes(const uint216_t &i) { - BytesArr<27> ret; - Bytes tmp; - tmp.reserve(27); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[26 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<26> Utils::uint208ToBytes(const uint208_t &i) { - BytesArr<26> ret; - Bytes tmp; - tmp.reserve(26); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[25 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<25> Utils::uint200ToBytes(const uint200_t &i) { - BytesArr<25> ret; - Bytes tmp; - tmp.reserve(25); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[24 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<24> Utils::uint192ToBytes(const uint192_t &i) { - BytesArr<24> ret; - Bytes tmp; - tmp.reserve(24); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[23 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<23> Utils::uint184ToBytes(const uint184_t &i) { - BytesArr<23> ret; - Bytes tmp; - tmp.reserve(23); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[22 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<22> Utils::uint176ToBytes(const uint176_t &i) { - BytesArr<22> ret; - Bytes tmp; - tmp.reserve(22); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[21 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<21> Utils::uint168ToBytes(const uint168_t &i) { - BytesArr<21> ret; - Bytes tmp; - tmp.reserve(21); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[20 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<20> Utils::uint160ToBytes(const uint160_t &i) { - BytesArr<20> ret; - Bytes tmp; - tmp.reserve(20); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[19 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<19> Utils::uint152ToBytes(const uint152_t &i) { - BytesArr<19> ret; - Bytes tmp; - tmp.reserve(19); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[18 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<18> Utils::uint144ToBytes(const uint144_t &i) { - BytesArr<18> ret; - Bytes tmp; - tmp.reserve(18); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[17 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<17> Utils::uint136ToBytes(const uint136_t &i) { - BytesArr<17> ret; - Bytes tmp; - tmp.reserve(17); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[16 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<16> Utils::uint128ToBytes(const uint128_t &i) { - BytesArr<16> ret; - Bytes tmp; - tmp.reserve(16); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[15 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<15> Utils::uint120ToBytes(const uint120_t &i) { - BytesArr<15> ret; - Bytes tmp; - tmp.reserve(15); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[14 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<14> Utils::uint112ToBytes(const uint112_t &i) { - BytesArr<14> ret; - Bytes tmp; - tmp.reserve(14); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[13 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<13> Utils::uint104ToBytes(const uint104_t &i) { - BytesArr<13> ret; - Bytes tmp; - tmp.reserve(13); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[12 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<12> Utils::uint96ToBytes(const uint96_t &i) { - BytesArr<12> ret; - Bytes tmp; - tmp.reserve(12); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[11 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<11> Utils::uint88ToBytes(const uint88_t &i) { - BytesArr<11> ret; - Bytes tmp; - tmp.reserve(11); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[10 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<10> Utils::uint80ToBytes(const uint80_t &i) { - BytesArr<10> ret; - Bytes tmp; - tmp.reserve(10); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[9 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<9> Utils::uint72ToBytes(const uint72_t &i) { - BytesArr<9> ret; - Bytes tmp; - tmp.reserve(9); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[8 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<7> Utils::uint56ToBytes(const uint56_t &i) { - BytesArr<7> ret; - Bytes tmp; - tmp.reserve(7); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[6 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<6> Utils::uint48ToBytes(const uint48_t &i) { - BytesArr<6> ret; - Bytes tmp; - tmp.reserve(6); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[5 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<5> Utils::uint40ToBytes(const uint40_t &i) { - BytesArr<5> ret; - Bytes tmp; - tmp.reserve(5); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[4 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<3> Utils::uint24ToBytes(const uint24_t &i) { - BytesArr<3> ret; - Bytes tmp; - tmp.reserve(3); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[2 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<32> Utils::uint256ToBytes(const uint256_t& i) { - BytesArr<32> ret; - Bytes tmp; - tmp.reserve(32); - ret.fill(0x00); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (unsigned ii = 0; ii < tmp.size(); ii++) ret[31 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -uint256_t Utils::bytesToUint256(const bytes::View b) { - if (b.size() != 32) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 32, got " + std::to_string(b.size()) - ); - uint256_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint248_t Utils::bytesToUint248(const bytes::View b) { - if (b.size() != 31) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 31, got " + std::to_string(b.size()) - ); - uint248_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint240_t Utils::bytesToUint240(const bytes::View b) { - if (b.size() != 30) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 30, got " + std::to_string(b.size()) - ); - uint240_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint232_t Utils::bytesToUint232(const bytes::View b) { - if (b.size() != 29) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 29, got " + std::to_string(b.size()) - ); - uint232_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint224_t Utils::bytesToUint224(const bytes::View b) { - if (b.size() != 28) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 28, got " + std::to_string(b.size()) - ); - uint224_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint216_t Utils::bytesToUint216(const bytes::View b) { - if (b.size() != 27) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 27, got " + std::to_string(b.size()) - ); - uint216_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint208_t Utils::bytesToUint208(const bytes::View b) { - if (b.size() != 26) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 26, got " + std::to_string(b.size()) - ); - uint208_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint200_t Utils::bytesToUint200(const bytes::View b) { - if (b.size() != 25) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 25, got " + std::to_string(b.size()) - ); - uint200_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint192_t Utils::bytesToUint192(const bytes::View b) { - if (b.size() != 24) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 24, got " + std::to_string(b.size()) - ); - uint192_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint184_t Utils::bytesToUint184(const bytes::View b) { - if (b.size() != 23) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 23, got " + std::to_string(b.size()) - ); - uint184_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint176_t Utils::bytesToUint176(const bytes::View b) { - if (b.size() != 22) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 22, got " + std::to_string(b.size()) - ); - uint176_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint168_t Utils::bytesToUint168(const bytes::View b) { - if (b.size() != 21) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 21, got " + std::to_string(b.size()) - ); - uint168_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint160_t Utils::bytesToUint160(const bytes::View b) { - if (b.size() != 20) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 20, got " + std::to_string(b.size()) - ); - uint160_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint152_t Utils::bytesToUint152(const bytes::View b) { - if (b.size() != 19) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 19, got " + std::to_string(b.size()) - ); - uint152_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint144_t Utils::bytesToUint144(const bytes::View b) { - if (b.size() != 18) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 18, got " + std::to_string(b.size()) - ); - uint144_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint136_t Utils::bytesToUint136(const bytes::View b) { - if (b.size() != 17) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 17, got " + std::to_string(b.size()) - ); - uint136_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint128_t Utils::bytesToUint128(const bytes::View b) { - if (b.size() != 16) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 16, got " + std::to_string(b.size()) - ); - uint128_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint120_t Utils::bytesToUint120(const bytes::View b) { - if (b.size() != 15) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 15, got " + std::to_string(b.size()) - ); - uint120_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint112_t Utils::bytesToUint112(const bytes::View b) { - if (b.size() != 14) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 16, got " + std::to_string(b.size()) - ); - uint112_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint104_t Utils::bytesToUint104(const bytes::View b) { - if (b.size() != 13) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 13, got " + std::to_string(b.size()) - ); - uint104_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint96_t Utils::bytesToUint96(const bytes::View b) { - if (b.size() != 12) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 12, got " + std::to_string(b.size()) - ); - uint96_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint88_t Utils::bytesToUint88(const bytes::View b) { - if (b.size() != 11) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 11, got " + std::to_string(b.size()) - ); - uint88_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint80_t Utils::bytesToUint80(const bytes::View b) { - if (b.size() != 10) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 10, got " + std::to_string(b.size()) - ); - uint80_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint72_t Utils::bytesToUint72(const bytes::View b) { - if (b.size() != 9) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 9, got " + std::to_string(b.size()) - ); - uint72_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint56_t Utils::bytesToUint56(const bytes::View b) { - if (b.size() != 7) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 7, got " + std::to_string(b.size()) - ); - uint56_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint48_t Utils::bytesToUint48(const bytes::View b) { - if (b.size() != 6) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 6, got " + std::to_string(b.size()) - ); - uint48_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint40_t Utils::bytesToUint40(const bytes::View b) { - if (b.size() != 5) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 5, got " + std::to_string(b.size()) - ); - uint40_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -uint24_t Utils::bytesToUint24(const bytes::View b) { - if (b.size() != 3) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 3, got " + std::to_string(b.size()) - ); - uint24_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -BytesArr<8> Utils::uint64ToBytes(const uint64_t& i) { - BytesArr<8> ret; - std::memcpy(&ret[0], &i, 8); - #if __BYTE_ORDER == __LITTLE_ENDIAN - std::reverse(ret.begin(), ret.end()); - #endif - return ret; -} - -uint64_t Utils::bytesToUint64(const bytes::View b) { - if (b.size() != 8) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 8, got " + std::to_string(b.size()) - ); - uint64_t ret = 0; - std::memcpy(&ret, b.data(), 8); - #if __BYTE_ORDER == __LITTLE_ENDIAN - return __builtin_bswap64(ret); - #endif - return ret; -} - -BytesArr<4> Utils::uint32ToBytes(const uint32_t& i) { - BytesArr<4> ret; - std::memcpy(&ret[0], &i, 4); - #if __BYTE_ORDER == __LITTLE_ENDIAN - std::reverse(ret.begin(), ret.end()); - #endif - return ret; -} - -uint32_t Utils::bytesToUint32(const bytes::View b) { - if (b.size() != 4) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 4, got " + std::to_string(b.size()) - ); - uint32_t ret = 0; - std::memcpy(&ret, b.data(), 4); - #if __BYTE_ORDER == __LITTLE_ENDIAN - return __builtin_bswap32(ret); - #endif - return ret; -} - -BytesArr<2> Utils::uint16ToBytes(const uint16_t& i) { - BytesArr<2> ret; - std::memcpy(&ret[0], &i, 2); - #if __BYTE_ORDER == __LITTLE_ENDIAN - std::reverse(ret.begin(), ret.end()); - #endif - return ret; -} - -uint16_t Utils::bytesToUint16(const bytes::View b) { - if (b.size() != 2) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 2, got " + std::to_string(b.size()) - ); - uint16_t ret = 0; - std::memcpy(&ret, b.data(), 2); - #if __BYTE_ORDER == __LITTLE_ENDIAN - return __builtin_bswap16(ret); - #endif - return ret; -} - -BytesArr<1> Utils::uint8ToBytes(const uint8_t& i) { - BytesArr<1> ret; - std::memcpy(&ret[0], &i, 1); - return ret; -} - -uint8_t Utils::bytesToUint8(const bytes::View b) { - if (b.size() != 1) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 1, got " + std::to_string(b.size()) - ); - uint8_t ret; - ret = b[0]; - return ret; -} - -int256_t Utils::bytesToInt256(const bytes::View b) { - if (b.size() != 32) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 32, got " + std::to_string(b.size()) - ); - uint256_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - - // Check the MSB to determine if the value is negative - // Manually compute two's complement in reverse, since boost::multiprecision::cpp_int doesn't support it - // Subtract one from the byte array - if (b[0] & 0x80) { - int borrow = 1; - for (int i = 31; i >= 0 && borrow; i--) { - borrow = (b[i] == 0); - ret -= (uint256_t(1) << (8 * (31 - i))); - } - ret = ~ret; - return -ret.convert_to(); - } else { - return ret.convert_to(); - } -} - -BytesArr<32> Utils::int256ToBytes(const int256_t& i) { - BytesArr<32> ret; - - if (i < 0) { - int256_t absValue = -i; - Bytes tempBytes; - boost::multiprecision::export_bits(absValue, std::back_inserter(tempBytes), 8); - for (int j = 0; j < 32; j++) { - if (j < tempBytes.size()) { - ret[31 - j] = ~tempBytes[tempBytes.size() - j - 1]; - } else { - ret[31 - j] = 0xFF; - } - } - for (int j = 31; j >= 0; j--) { - if (ret[j] != 0xFF) { - ret[j]++; - break; - } else { - ret[j] = 0x00; - } - } - } else { - Bytes tempBytes; - boost::multiprecision::export_bits(i, std::back_inserter(tempBytes), 8); - std::copy(tempBytes.rbegin(), tempBytes.rend(), ret.rbegin()); - } - - return ret; -} - -BytesArr<17> Utils::int136ToBytes(const int136_t &i) { - BytesArr<17> ret; - Bytes tmp; - tmp.reserve(17); - boost::multiprecision::export_bits(i, std::back_inserter(tmp), 8); - for (signed ii = 0; ii < tmp.size(); ii++) ret[16 - ii] = tmp[tmp.size() - ii - 1]; - return ret; -} - -BytesArr<8> Utils::int64ToBytes(const int64_t& i) { - BytesArr<8> ret; - std::memcpy(&ret[0], &i, 8); - #if __BYTE_ORDER == __LITTLE_ENDIAN - std::reverse(ret.begin(), ret.end()); - #endif - return ret; -} - -int136_t Utils::bytesToInt136(const bytes::View b) { - if (b.size() != 18) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 18, got " + std::to_string(b.size()) - ); - int136_t ret; - boost::multiprecision::import_bits(ret, b.begin(), b.end(), 8); - return ret; -} - -int64_t Utils::bytesToInt64(const bytes::View b) { - if (b.size() != 8) throw DynamicException(std::string(__func__) - + ": Invalid bytes size - expected 8, got " + std::to_string(b.size()) - ); - int64_t ret = 0; - std::memcpy(&ret, b.data(), 8); - #if __BYTE_ORDER == __LITTLE_ENDIAN - return __builtin_bswap64(ret); - #endif - return ret; -} - Bytes Utils::randBytes(const int& size) { Bytes bytes(size, 0x00); RAND_bytes(bytes.data(), size); return bytes; } -std::string Utils::padLeft(std::string str, unsigned int charAmount, char sign) { - bool hasPrefix = (str.starts_with("0x") || str.starts_with("0X")); - if (hasPrefix) str = str.substr(2); - size_t padding = (charAmount > str.length()) ? (charAmount - str.length()) : 0; - std::string padded = (padding != 0) ? std::string(padding, sign) : ""; - return (hasPrefix ? "0x" : "") + padded + str; -} - -std::string Utils::padRight(std::string str, unsigned int charAmount, char sign) { - bool hasPrefix = (str.starts_with("0x") || str.starts_with("0X")); - if (hasPrefix) str = str.substr(2); - size_t padding = (charAmount > str.length()) ? (charAmount - str.length()) : 0; - std::string padded = (padding != 0) ? std::string(padding, sign) : ""; - return (hasPrefix ? "0x" : "") + str + padded; -} - -Bytes Utils::padLeftBytes(const bytes::View bytes, unsigned int charAmount, uint8_t sign) { - size_t padding = (charAmount > bytes.size()) ? (charAmount - bytes.size()) : 0; - Bytes padded = (padding != 0) ? Bytes(padding, sign) : Bytes(0, 0x00); - padded.reserve(bytes.size() + padded.size()); - padded.insert(padded.end(), bytes.begin(), bytes.end()); - return padded; -} - -Bytes Utils::padRightBytes(const bytes::View bytes, unsigned int charAmount, uint8_t sign) { - size_t padding = (charAmount > bytes.size()) ? (charAmount - bytes.size()) : 0; - Bytes padded = (padding != 0) ? Bytes(padding, sign) : Bytes(0, 0x00); - Bytes ret; - ret.reserve(bytes.size() + padded.size()); - ret.insert(ret.end(), bytes.begin(), bytes.end()); - ret.insert(ret.end(), padded.begin(), padded.end()); - return ret; -} - json Utils::readConfigFile() { if (!std::filesystem::exists("config.json")) { SLOGINFO("No config file found, generating default"); @@ -861,3 +107,13 @@ std::string Utils::getSignalName(int signum) { return n; } +bytes::View Utils::create_view_span(const Bytes& vec, size_t start, size_t size) { + if (start + size > vec.size()) throw DynamicException("Invalid range for span"); + return bytes::View(vec.data() + start, size); +} + +bytes::View Utils::create_view_span(const std::string_view str, size_t start, size_t size) { + if (start + size > str.size()) throw DynamicException("Invalid range for span"); + return bytes::View(reinterpret_cast(str.data()) + start, size); +} + diff --git a/src/utils/utils.h b/src/utils/utils.h index 6e268fd35..61f34baea 100644 --- a/src/utils/utils.h +++ b/src/utils/utils.h @@ -8,42 +8,34 @@ See the LICENSE.txt file in the project root for more information. #ifndef UTILS_H #define UTILS_H -#include -#include -#include -#include +// TODO: find out where those are coming from +//#include +//#include +//#include +//#include + #include #include -#include -#include -#include -#include -#include -#include - -#include -#include -#include +#include // used by jsonrpc/parser.cpp + +// TODO: find out where those are coming from +//#include +//#include #include #include -#include #include -#include - -#include "strings.h" -#include "logger.h" -#include "../libs/zpp_bits.h" -#include "../libs/json.hpp" +#include "../libs/json.hpp" // algorithm, array, tuple -#include "../bytes/join.h" -#include "../bytes/range.h" -#include "../bytes/view.h" -#include "../bytes/initializer.h" +#include "../bytes/join.h" // range.h, view.h, initializer.h -#include "../contract/variables/safeuint.h" #include "../contract/variables/safeint.h" +#include "../contract/variables/safeuint.h" + +#include "dynamicexception.h" // included by strings.h, leave it for now to avoid AddressSanitizer runtime errors - TODO: see create_view_span() +#include "logger.h" +#include "strings.h" // hex.h, openssl/rand.h, libs/zpp_bits.h -> algorithm, array, span, variant /// Localhost IPv4 address constant inline const boost::asio::ip::address LOCALHOST = boost::asio::ip::address::from_string("127.0.0.1"); @@ -55,9 +47,7 @@ class Hash; /// Typedef for json. using json = nlohmann::ordered_json; -/// Typedef for bigint. -using bigint = boost::multiprecision::number>; - +// TODO: duplicated in hex.h, strconv.h, evmcconv.h and (u)intconv.h, find a better way to handle this using Byte = uint8_t; ///< Typedef for Byte. using Bytes = std::vector; ///< Typedef for Bytes. template using BytesArr = std::array; ///< Typedef for BytesArr. @@ -97,134 +87,6 @@ template struct printAtExit { ~printAtExit() { printDurationsHelper(id, timePoints, names); } }; -///@{ -/** Typedef for primitive integer type. */ -using uint24_t = boost::multiprecision::number>; -using uint40_t = boost::multiprecision::number>; -using uint48_t = boost::multiprecision::number>; -using uint56_t = boost::multiprecision::number>; -using uint72_t = boost::multiprecision::number>; -using uint80_t = boost::multiprecision::number>; -using uint88_t = boost::multiprecision::number>; -using uint96_t = boost::multiprecision::number>; -using uint104_t = boost::multiprecision::number>; -using uint112_t = boost::multiprecision::number>; -using uint120_t = boost::multiprecision::number>; -using uint128_t = boost::multiprecision::number>; -using uint136_t = boost::multiprecision::number>; -using uint144_t = boost::multiprecision::number>; -using uint152_t = boost::multiprecision::number>; -using uint160_t = boost::multiprecision::number>; -using uint168_t = boost::multiprecision::number>; -using uint176_t = boost::multiprecision::number>; -using uint184_t = boost::multiprecision::number>; -using uint192_t = boost::multiprecision::number>; -using uint200_t = boost::multiprecision::number>; -using uint208_t = boost::multiprecision::number>; -using uint216_t = boost::multiprecision::number>; -using uint224_t = boost::multiprecision::number>; -using uint232_t = boost::multiprecision::number>; -using uint240_t = boost::multiprecision::number>; -using uint248_t = boost::multiprecision::number>; -using uint256_t = boost::multiprecision::number>; -using int24_t = boost::multiprecision::number>; -using int40_t = boost::multiprecision::number>; -using int48_t = boost::multiprecision::number>; -using int56_t = boost::multiprecision::number>; -using int72_t = boost::multiprecision::number>; -using int80_t = boost::multiprecision::number>; -using int88_t = boost::multiprecision::number>; -using int96_t = boost::multiprecision::number>; -using int104_t = boost::multiprecision::number>; -using int112_t = boost::multiprecision::number>; -using int120_t = boost::multiprecision::number>; -using int128_t = boost::multiprecision::number>; -using int136_t = boost::multiprecision::number>; -using int144_t = boost::multiprecision::number>; -using int152_t = boost::multiprecision::number>; -using int160_t = boost::multiprecision::number>; -using int168_t = boost::multiprecision::number>; -using int176_t = boost::multiprecision::number>; -using int184_t = boost::multiprecision::number>; -using int192_t = boost::multiprecision::number>; -using int200_t = boost::multiprecision::number>; -using int208_t = boost::multiprecision::number>; -using int216_t = boost::multiprecision::number>; -using int224_t = boost::multiprecision::number>; -using int232_t = boost::multiprecision::number>; -using int240_t = boost::multiprecision::number>; -using int248_t = boost::multiprecision::number>; -using int256_t = boost::multiprecision::number>; -///@} - -///@{ -/** Typedef for SafeVariable integer type. */ -using SafeUint8_t = SafeUint_t<8>; -using SafeUint16_t = SafeUint_t<16>; -using SafeUint24_t = SafeUint_t<24>; -using SafeUint32_t = SafeUint_t<32>; -using SafeUint40_t = SafeUint_t<40>; -using SafeUint48_t = SafeUint_t<48>; -using SafeUint56_t = SafeUint_t<56>; -using SafeUint64_t = SafeUint_t<64>; -using SafeUint72_t = SafeUint_t<72>; -using SafeUint80_t = SafeUint_t<80>; -using SafeUint88_t = SafeUint_t<88>; -using SafeUint96_t = SafeUint_t<96>; -using SafeUint104_t = SafeUint_t<104>; -using SafeUint112_t = SafeUint_t<112>; -using SafeUint120_t = SafeUint_t<120>; -using SafeUint128_t = SafeUint_t<128>; -using SafeUint136_t = SafeUint_t<136>; -using SafeUint144_t = SafeUint_t<144>; -using SafeUint152_t = SafeUint_t<152>; -using SafeUint160_t = SafeUint_t<160>; -using SafeUint168_t = SafeUint_t<168>; -using SafeUint176_t = SafeUint_t<176>; -using SafeUint184_t = SafeUint_t<184>; -using SafeUint192_t = SafeUint_t<192>; -using SafeUint200_t = SafeUint_t<200>; -using SafeUint208_t = SafeUint_t<208>; -using SafeUint216_t = SafeUint_t<216>; -using SafeUint224_t = SafeUint_t<224>; -using SafeUint232_t = SafeUint_t<232>; -using SafeUint240_t = SafeUint_t<240>; -using SafeUint248_t = SafeUint_t<248>; -using SafeUint256_t = SafeUint_t<256>; -using SafeInt8_t = SafeInt_t<8>; -using SafeInt16_t = SafeInt_t<16>; -using SafeInt24_t = SafeInt_t<24>; -using SafeInt32_t = SafeInt_t<32>; -using SafeInt40_t = SafeInt_t<40>; -using SafeInt48_t = SafeInt_t<48>; -using SafeInt56_t = SafeInt_t<56>; -using SafeInt64_t = SafeInt_t<64>; -using SafeInt72_t = SafeInt_t<72>; -using SafeInt80_t = SafeInt_t<80>; -using SafeInt88_t = SafeInt_t<88>; -using SafeInt96_t = SafeInt_t<96>; -using SafeInt104_t = SafeInt_t<104>; -using SafeInt112_t = SafeInt_t<112>; -using SafeInt120_t = SafeInt_t<120>; -using SafeInt128_t = SafeInt_t<128>; -using SafeInt136_t = SafeInt_t<136>; -using SafeInt144_t = SafeInt_t<144>; -using SafeInt152_t = SafeInt_t<152>; -using SafeInt160_t = SafeInt_t<160>; -using SafeInt168_t = SafeInt_t<168>; -using SafeInt176_t = SafeInt_t<176>; -using SafeInt184_t = SafeInt_t<184>; -using SafeInt192_t = SafeInt_t<192>; -using SafeInt200_t = SafeInt_t<200>; -using SafeInt208_t = SafeInt_t<208>; -using SafeInt216_t = SafeInt_t<216>; -using SafeInt224_t = SafeInt_t<224>; -using SafeInt232_t = SafeInt_t<232>; -using SafeInt240_t = SafeInt_t<240>; -using SafeInt248_t = SafeInt_t<248>; -using SafeInt256_t = SafeInt_t<256>; -///@} - /** * Map with addresses for contracts deployed at protocol level (name -> address). * These contracts are deployed at the beginning of the chain and cannot be @@ -447,13 +309,6 @@ namespace Utils { */ void logToFile(std::string_view str); - /** - * Get the functor of a evmc_message - * @param msg The evmc_message to get the functor from. - * @return The functor of the evmc_message (0 if evmc_message size == 0). - */ - Functor getFunctor(const evmc_message& msg); - /** * Create a Functor based on a std::string with the function signature (e.g. "functionName(uint256,uint256)"). * @param funtionSignature The function signature. @@ -461,13 +316,6 @@ namespace Utils { */ Functor makeFunctor(std::string_view functionSignature); - /** - * Get the bytes::View representing the function arguments of a given evmc_message. - * @param msg The evmc_message to get the function arguments from. - * @return The bytes::View representing the function arguments. - */ - bytes::View getFunctionArgs(const evmc_message& msg); - /** * Print a string to stdout. Does not print if in a test. * @param str The string to print. @@ -494,157 +342,10 @@ namespace Utils { */ Bytes randBytes(const int& size); - ///@{ - /** - * Convert a given EVMC type to a BDK type, or vice-versa. - * @param i (or b) The type to convert. - * @return The converted type. - */ - uint256_t evmcUint256ToUint256(const evmc::uint256be& i); - evmc::uint256be uint256ToEvmcUint256(const uint256_t& i); - BytesArr<32> evmcUint256ToBytes(const evmc::uint256be& i); - evmc::uint256be bytesToEvmcUint256(const bytes::View b); - ///@} - - /** - * Wrapper for EVMC's `ecrecover()` function. - * @param hash The hash to recover an address from. - * @param v The recover ID. - * @param r The first half of the ECDSA signature. - * @param s The second half of the ECDSA signature. - * @return The recovered address. - */ - evmc::address ecrecover(evmc::bytes32 hash, evmc::bytes32 v, evmc::bytes32 r, evmc::bytes32 s); - - ///@{ - /** - * Convert a given integer to a bytes string. Use `Hex()` to properly print it. - * @param i The integer to convert. - * @return The converted integer as a bytes string. - */ - BytesArr<32> uint256ToBytes(const uint256_t& i); - BytesArr<31> uint248ToBytes(const uint248_t& i); - BytesArr<30> uint240ToBytes(const uint240_t& i); - BytesArr<29> uint232ToBytes(const uint232_t& i); - BytesArr<28> uint224ToBytes(const uint224_t& i); - BytesArr<27> uint216ToBytes(const uint216_t& i); - BytesArr<26> uint208ToBytes(const uint208_t& i); - BytesArr<25> uint200ToBytes(const uint200_t& i); - BytesArr<24> uint192ToBytes(const uint192_t& i); - BytesArr<23> uint184ToBytes(const uint184_t& i); - BytesArr<22> uint176ToBytes(const uint176_t& i); - BytesArr<21> uint168ToBytes(const uint168_t& i); - BytesArr<20> uint160ToBytes(const uint160_t& i); - BytesArr<19> uint152ToBytes(const uint152_t& i); - BytesArr<18> uint144ToBytes(const uint144_t& i); - BytesArr<17> uint136ToBytes(const uint136_t& i); - BytesArr<16> uint128ToBytes(const uint128_t& i); - BytesArr<15> uint120ToBytes(const uint120_t& i); - BytesArr<14> uint112ToBytes(const uint112_t& i); - BytesArr<13> uint104ToBytes(const uint104_t& i); - BytesArr<12> uint96ToBytes(const uint96_t& i); - BytesArr<11> uint88ToBytes(const uint88_t& i); - BytesArr<10> uint80ToBytes(const uint80_t& i); - BytesArr<9> uint72ToBytes(const uint72_t& i); - BytesArr<8> uint64ToBytes(const uint64_t& i); - BytesArr<7> uint56ToBytes(const uint56_t& i); - BytesArr<6> uint48ToBytes(const uint48_t& i); - BytesArr<5> uint40ToBytes(const uint40_t& i); - BytesArr<4> uint32ToBytes(const uint32_t& i); - BytesArr<3> uint24ToBytes(const uint24_t& i); - BytesArr<2> uint16ToBytes(const uint16_t& i); - BytesArr<1> uint8ToBytes(const uint8_t& i); - BytesArr<32> int256ToBytes(const int256_t& i); - BytesArr<17> int136ToBytes(const int136_t& i); - BytesArr<8> int64ToBytes(const int64_t& i); - ///@} - - ///@{ - /** - * Convert a given bytes string to an integer. - * @param b The bytes string to convert. - * @return The converted integer. - * @throw DynamicException if string size is invalid. - */ - uint256_t bytesToUint256(const bytes::View b); - uint248_t bytesToUint248(const bytes::View b); - uint240_t bytesToUint240(const bytes::View b); - uint232_t bytesToUint232(const bytes::View b); - uint224_t bytesToUint224(const bytes::View b); - uint216_t bytesToUint216(const bytes::View b); - uint208_t bytesToUint208(const bytes::View b); - uint200_t bytesToUint200(const bytes::View b); - uint192_t bytesToUint192(const bytes::View b); - uint184_t bytesToUint184(const bytes::View b); - uint176_t bytesToUint176(const bytes::View b); - uint168_t bytesToUint168(const bytes::View b); - uint160_t bytesToUint160(const bytes::View b); - uint152_t bytesToUint152(const bytes::View b); - uint144_t bytesToUint144(const bytes::View b); - uint136_t bytesToUint136(const bytes::View b); - uint128_t bytesToUint128(const bytes::View b); - uint120_t bytesToUint120(const bytes::View b); - uint112_t bytesToUint112(const bytes::View b); - uint104_t bytesToUint104(const bytes::View b); - uint96_t bytesToUint96(const bytes::View b); - uint88_t bytesToUint88(const bytes::View b); - uint80_t bytesToUint80(const bytes::View b); - uint72_t bytesToUint72(const bytes::View b); - uint64_t bytesToUint64(const bytes::View b); - uint56_t bytesToUint56(const bytes::View b); - uint48_t bytesToUint48(const bytes::View b); - uint40_t bytesToUint40(const bytes::View b); - uint32_t bytesToUint32(const bytes::View b); - uint24_t bytesToUint24(const bytes::View b); - uint16_t bytesToUint16(const bytes::View b); - uint8_t bytesToUint8(const bytes::View b); - int256_t bytesToInt256(const bytes::View b); - int136_t bytesToInt136(const bytes::View b); - int64_t bytesToInt64(const bytes::View b); - ///@} - - /** - * Convert a C-style raw byte array to a raw bytes string. - * @param arr The array to convert. - * @param size The size of the array. - * @return The converted raw bytes string. - */ - Bytes cArrayToBytes(const uint8_t* arr, size_t size); - - /** - * Add padding to the left of a byte vector. - * @param bytes The vector to pad. - * @param charAmount The total amount of characters the resulting string should have. - * If this is less than the string's original size, - * the string will remain untouched. - * e.g. `padLeftBytes("aaa", 5)` = "00aaa", `padLeftBytes("aaa", 2)` = "aaa" - * @param sign (optional) The character to use as padding. Defaults to '0'. - * @return The padded vector. - */ - Bytes padLeftBytes(const bytes::View bytes, unsigned int charAmount, uint8_t sign = 0x00); - - /** - * Add padding to the right of a byte vector. - * @param bytes The vector to pad. - * @param charAmount The total amount of characters the resulting string should have. - * If this is less than the string's original size, - * the string will remain untouched. - * e.g. `padLeftBytes("aaa", 5)` = "aaa00", `padLeftBytes("aaa", 2)` = "aaa" - * @param sign (optional) The character to use as padding. Defaults to '0'. - * @return The padded vector. - */ - Bytes padRightBytes(const bytes::View bytes, unsigned int charAmount, uint8_t sign = 0x00); - - /// Overload of padLeftBytes() that works with UTF-8 strings. - std::string padLeft(std::string str, unsigned int charAmount, char sign = '\x00'); - - /// Overload of padRightBytes() that works with UTF-8 strings. - std::string padRight(std::string str, unsigned int charAmount, char sign = '\x00'); - /** * Convert a big-endian byte-stream represented on a templated collection to a templated integer value. * `In` will typically be either std::string or bytes. - * `T` will typically be unsigned, u160, u256 or bigint. + * `T` will typically be unsigned, u160, u256 or boost::multiprecision::number. * @param bytes The byte stream to convert. * @return The converted integer type. */ @@ -656,22 +357,6 @@ namespace Utils { return ret; } - /** - * Convert a string to all-lowercase. Conversion is done in-place. - * @param str The string to convert. - */ - inline void toLower(std::string& str) { - std::transform(str.begin(), str.end(), str.begin(), ::tolower); - } - - /** - * Convert a string to all-uppercase. Conversion is done in-place. - * @param str The string to convert. - */ - inline void toUpper(std::string& str) { - std::transform(str.begin(), str.end(), str.begin(), ::toupper); - } - /** * Load HTTP port settings from a config file. Creates the file if it doesn't exist. * @return A JSON object with the settings. @@ -686,6 +371,7 @@ namespace Utils { */ template inline unsigned bytesRequired(T i) { // bigint does not carry sign bit on shift + using bigint = boost::multiprecision::number>; static_assert(std::is_same_v || !std::numeric_limits::is_signed, "only unsigned types or bigint supported"); unsigned ic = 0; for (; i != 0; ++ic, i >>= 8); @@ -694,7 +380,7 @@ namespace Utils { /** * Convert an unsigned integer to bytes. - * Takes uint as little endian and has no padding, as opposed to uintToBytes(). + * Takes uint as little endian and has no padding, as opposed to uintXToBytes(). * @param i The integer to convert. * @return The converted bytes string. */ @@ -744,11 +430,9 @@ namespace Utils { * @param start The start index of the subvector. * @param size The size of the subvector. * @return The converted span. + * @throw DynamicException if range is invalid. */ - inline bytes::View create_view_span(const Bytes& vec, size_t start, size_t size) { - if (start + size > vec.size()) throw DynamicException("Invalid range for span"); - return bytes::View(vec.data() + start, size); - } + bytes::View create_view_span(const Bytes& vec, size_t start, size_t size); /** * Convert an array to const span. @@ -765,10 +449,12 @@ namespace Utils { * @param start The start index of the subarray. * @param size The size of the subarray. * @return The converted span. + * @throw DynamicException if range is invalid. */ template inline bytes::View create_view_span( const BytesArr& arr, size_t start, size_t size ) { + // TODO: somehow migrate this to the cpp file so we can include dynamicexception.h only there, OR get rid of the exception altogether if (start + size > arr.size()) throw DynamicException("Invalid range for span"); return bytes::View(arr.data() + start, size); } @@ -788,13 +474,9 @@ namespace Utils { * @param start The start index of the substring. * @param size The size of the substring. * @return The converted span. + * @throw DynamicException if range is invalid. */ - inline bytes::View create_view_span(const std::string_view str, size_t start, size_t size) { - if (start + size > str.size()) { - throw DynamicException("Invalid range for span"); - } - return bytes::View(reinterpret_cast(str.data()) + start, size); - } + bytes::View create_view_span(const std::string_view str, size_t start, size_t size); /** * Append a vector to another. diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9cc4419fd..0020f7701 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -21,6 +21,8 @@ set (TESTS_SOURCES ${CMAKE_SOURCE_DIR}/tests/utils/utils.cpp ${CMAKE_SOURCE_DIR}/tests/utils/options.cpp ${CMAKE_SOURCE_DIR}/tests/utils/dynamicexception.cpp + ${CMAKE_SOURCE_DIR}/tests/utils/strconv.cpp + ${CMAKE_SOURCE_DIR}/tests/utils/uintconv.cpp ${CMAKE_SOURCE_DIR}/tests/contract/abi.cpp ${CMAKE_SOURCE_DIR}/tests/contract/erc20.cpp ${CMAKE_SOURCE_DIR}/tests/contract/erc20wrapper.cpp diff --git a/tests/benchmark/erc20.cpp b/tests/benchmark/erc20.cpp index bf21ba1ed..62e3bb412 100644 --- a/tests/benchmark/erc20.cpp +++ b/tests/benchmark/erc20.cpp @@ -5,10 +5,11 @@ */ #include "../src/libs/catch2/catch_amalgamated.hpp" + #include "../src/contract/templates/erc20.h" -#include "../src/contract/abi.h" -#include "../src/utils/options.h" -#include "../src/core/rdpos.h" + +#include "../src/utils/uintconv.h" + #include "../sdktestsuite.hpp" namespace TERC20BENCHMARK { @@ -49,7 +50,7 @@ namespace TERC20BENCHMARK { // Create the transaction for transfer - auto functor = Utils::uint32ToBytes(ABI::FunctorEncoder::encode("transfer").value); + auto functor = UintConv::uint32ToBytes(ABI::FunctorEncoder::encode("transfer").value); Bytes transferEncoded(functor.cbegin(), functor.cend()); Utils::appendBytes(transferEncoded, ABI::Encoder::encodeData(to, uint256_t("100"))); TxBlock transferTx = sdk.createNewTx(sdk.getChainOwnerAccount(), erc20Address, 0, transferEncoded); @@ -111,7 +112,7 @@ namespace TERC20BENCHMARK { REQUIRE(sdk.callViewFunction(erc20Address, &ERC20::balanceOf, sdk.getChainOwnerAccount().address) == uint256_t("10000000000000000000000")); // Create the transaction for transfer - auto functor = Utils::uint32ToBytes(ABI::FunctorEncoder::encode("transfer").value); + auto functor = UintConv::uint32ToBytes(ABI::FunctorEncoder::encode("transfer").value); Bytes transferEncoded(functor.cbegin(), functor.cend()); Utils::appendBytes(transferEncoded, ABI::Encoder::encodeData(to, uint256_t("100"))); TxBlock transferTx = sdk.createNewTx(sdk.getChainOwnerAccount(), erc20Address, 0, transferEncoded); @@ -158,4 +159,4 @@ namespace TERC20BENCHMARK { sdk.getState().saveToDB(); } } -} \ No newline at end of file +} diff --git a/tests/benchmark/erc721.cpp b/tests/benchmark/erc721.cpp index 3b5c21abd..18beb0586 100644 --- a/tests/benchmark/erc721.cpp +++ b/tests/benchmark/erc721.cpp @@ -5,11 +5,12 @@ */ #include "../src/libs/catch2/catch_amalgamated.hpp" -#include "../src/contract/abi.h" -#include "../src/utils/options.h" -#include "../src/core/rdpos.h" + +#include "../src/contract/templates/erc721test.h" + +#include "../src/utils/uintconv.h" + #include "../sdktestsuite.hpp" -#include "contract/templates/erc721test.h" namespace TERC721BENCHMARK { /* @@ -53,7 +54,7 @@ namespace TERC721BENCHMARK { // as the encoding is the same // Create the transaction for transfer - auto functor = Utils::uint32ToBytes(ABI::FunctorEncoder::encode
("mint").value); + auto functor = UintConv::uint32ToBytes(ABI::FunctorEncoder::encode
("mint").value); Bytes mintEncoded(functor.cbegin(), functor.cend()); Utils::appendBytes(mintEncoded, ABI::Encoder::encodeData
(to)); TxBlock transferTx = sdk.createNewTx(sdk.getChainOwnerAccount(), erc721Address, 0, mintEncoded); @@ -93,6 +94,8 @@ namespace TERC721BENCHMARK { // Dump the state sdk.getState().saveToDB(); } + + // TODO: AddressSanitizer heap-use-after-free here for some reason, someone plz fix it SECTION("EVM ERC721 Benchmark") { std::unique_ptr options = nullptr; Address to(Utils::randBytes(20)); @@ -104,7 +107,7 @@ namespace TERC721BENCHMARK { // as the encoding is the same // Create the transaction for transfer - auto functor = Utils::uint32ToBytes(ABI::FunctorEncoder::encode
("mint").value); + auto functor = UintConv::uint32ToBytes(ABI::FunctorEncoder::encode
("mint").value); Bytes mintEncoded(functor.cbegin(), functor.cend()); Utils::appendBytes(mintEncoded, ABI::Encoder::encodeData
(to)); TxBlock transferTx = sdk.createNewTx(sdk.getChainOwnerAccount(), erc721Address, 0, mintEncoded); diff --git a/tests/benchmark/snailtracer.cpp b/tests/benchmark/snailtracer.cpp index 3d76cd67a..c50b8dd92 100644 --- a/tests/benchmark/snailtracer.cpp +++ b/tests/benchmark/snailtracer.cpp @@ -5,10 +5,11 @@ */ #include "../src/libs/catch2/catch_amalgamated.hpp" + #include "../src/contract/templates/snailtracer.h" -#include "../src/contract/abi.h" -#include "../src/utils/options.h" -#include "../src/core/rdpos.h" + +#include "../src/utils/uintconv.h" + #include "../sdktestsuite.hpp" namespace TSNAILTRACERBENCHMARK { @@ -31,7 +32,7 @@ namespace TSNAILTRACERBENCHMARK { // as the encoding is the same // Create the transaction for transfer - auto functor = Utils::uint32ToBytes(ABI::FunctorEncoder::encode("Benchmark").value); + auto functor = UintConv::uint32ToBytes(ABI::FunctorEncoder::encode("Benchmark").value); Bytes benchmarkEncoded(functor.cbegin(), functor.cend()); //Utils::appendBytes(benchmarkEncoded, ABI::Encoder::encodeData(1024, 768)); // TODO: this is a bug, the function does not take any params yet it is called with them just fine TxBlock benchmarkTx = sdk.createNewTx(sdk.getChainOwnerAccount(), snailtracerAddress, 0, benchmarkEncoded); @@ -76,7 +77,7 @@ namespace TSNAILTRACERBENCHMARK { auto snailtracerAddress = sdk.deployBytecode(snailTracerBytecode); // Create the transaction for transfer - auto functor = Utils::uint32ToBytes(ABI::FunctorEncoder::encode("Benchmark").value); + auto functor = UintConv::uint32ToBytes(ABI::FunctorEncoder::encode("Benchmark").value); Bytes benchmarkEncoded(functor.cbegin(), functor.cend()); //Utils::appendBytes(benchmarkEncoded, ABI::Encoder::encodeData(1024, 768)); // TODO: this is a bug, the function does not take any params yet it is called with them just fine diff --git a/tests/benchmark/snailtraceroptimized.cpp b/tests/benchmark/snailtraceroptimized.cpp index c2abc6620..b7ffb2076 100644 --- a/tests/benchmark/snailtraceroptimized.cpp +++ b/tests/benchmark/snailtraceroptimized.cpp @@ -5,10 +5,11 @@ */ #include "../src/libs/catch2/catch_amalgamated.hpp" + #include "../src/contract/templates/snailtraceroptimized.h" -#include "../src/contract/abi.h" -#include "../src/utils/options.h" -#include "../src/core/rdpos.h" + +#include "../src/utils/uintconv.h" + #include "../sdktestsuite.hpp" namespace TSNAILTRACEROPTIMIZEDBENCHMARK { @@ -31,7 +32,7 @@ namespace TSNAILTRACEROPTIMIZEDBENCHMARK { // as the encoding is the same // Create the transaction for transfer - auto functor = Utils::uint32ToBytes(ABI::FunctorEncoder::encode("Benchmark").value); + auto functor = UintConv::uint32ToBytes(ABI::FunctorEncoder::encode("Benchmark").value); Bytes benchmarkEncoded(functor.cbegin(), functor.cend()); //Utils::appendBytes(benchmarkEncoded, ABI::Encoder::encodeData(1024, 768)); // TODO: this is a bug, the function does not take any params yet it is called with them just fine TxBlock benchmarkTx = sdk.createNewTx(sdk.getChainOwnerAccount(), snailtracerAddress, 0, benchmarkEncoded); @@ -76,7 +77,7 @@ namespace TSNAILTRACEROPTIMIZEDBENCHMARK { auto snailtracerAddress = sdk.deployBytecode(snailTracerBytecode); // Create the transaction for transfer - auto functor = Utils::uint32ToBytes(ABI::FunctorEncoder::encode("Benchmark").value); + auto functor = UintConv::uint32ToBytes(ABI::FunctorEncoder::encode("Benchmark").value); Bytes benchmarkEncoded(functor.cbegin(), functor.cend()); //Utils::appendBytes(benchmarkEncoded, ABI::Encoder::encodeData(1024, 768)); // TODO: this is a bug, the function does not take any params yet it is called with them just fine diff --git a/tests/benchmark/uniswapv2.cpp b/tests/benchmark/uniswapv2.cpp index 0a2f0eb67..c5ccb4ba6 100644 --- a/tests/benchmark/uniswapv2.cpp +++ b/tests/benchmark/uniswapv2.cpp @@ -6,21 +6,13 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/contract/contractmanager.h" -#include "../../src/contract/templates/dexv2/dexv2pair.h" + #include "../../src/contract/templates/dexv2/dexv2factory.h" #include "../../src/contract/templates/dexv2/dexv2router02.h" #include "../../src/contract/templates/nativewrapper.h" -#include "../../src/contract/abi.h" -#include "../../src/utils/db.h" -#include "../../src/utils/options.h" -#include "../../src/core/rdpos.h" -#include "../../src/core/state.h" #include "../sdktestsuite.hpp" -#include - // TODO: test events if/when implemented namespace TDEXV2 { diff --git a/tests/blockchainwrapper.hpp b/tests/blockchainwrapper.hpp index c69ba79b7..3bb568257 100644 --- a/tests/blockchainwrapper.hpp +++ b/tests/blockchainwrapper.hpp @@ -8,14 +8,7 @@ See the LICENSE.txt file in the project root for more information. #ifndef BLOCKCHAINWRAPPER_H #define BLOCKCHAINWRAPPER_H -#include "../src/core/storage.h" -#include "../src/core/state.h" -#include "../src/net/p2p/managernormal.h" -#include "../src/net/http/httpserver.h" -#include "../src/utils/options.h" -#include "../src/utils/db.h" -#include "../src/core/blockchain.h" -#include "../src/utils/utils.h" +#include "../src/core/blockchain.h" // net/http/httpserver.h, consensus.h -> state.h -> (rdpos.h -> net/p2p/managernormal.h), dump.h -> (storage.h -> utils/options.h), utils/db.h -> utils.h /** * Simple wrapper struct for management of all blockchain related objects. diff --git a/tests/contract/abi.cpp b/tests/contract/abi.cpp index 3a60348c0..812d697c6 100644 --- a/tests/contract/abi.cpp +++ b/tests/contract/abi.cpp @@ -5,15 +5,9 @@ This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. */ -#include "../../src/contract/abi.h" #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/libs/json.hpp" -#include "../../src/utils/strings.h" -#include "../../src/utils/utils.h" -#include -#include -#include +#include "../../src/contract/abi.h" // utils.h -> strings.h, libs/json.hpp -> vector using Catch::Matchers::Equals; diff --git a/tests/contract/calltracer.cpp b/tests/contract/calltracer.cpp index 7224a9f62..65b89527b 100644 --- a/tests/contract/calltracer.cpp +++ b/tests/contract/calltracer.cpp @@ -6,12 +6,15 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" + #include "../../src/contract/calltracer.h" + #include "../../src/contract/templates/erc20.h" #include "../../src/contract/templates/erc20wrapper.h" + +#include "../../src/utils/uintconv.h" + #include "../sdktestsuite.hpp" -#include "../blockchainwrapper.hpp" -#include "../src/contract/templates/simplecontract.h" static const Bytes testBytecode = Hex::toBytes("0x608060405234801561001057600080fd5b50610219806100206000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c80631003e2d2146100465780634fa522db14610062578063853255cc14610092575b600080fd5b610060600480360381019061005b9190610129565b6100b0565b005b61007c60048036038101906100779190610129565b6100cb565b6040516100899190610165565b60405180910390f35b61009a6100e5565b6040516100a79190610165565b60405180910390f35b806000808282546100c191906101af565b9250508190555050565b60006100d6826100b0565b6100de6100e5565b9050919050565b60008054905090565b600080fd5b6000819050919050565b610106816100f3565b811461011157600080fd5b50565b600081359050610123816100fd565b92915050565b60006020828403121561013f5761013e6100ee565b5b600061014d84828501610114565b91505092915050565b61015f816100f3565b82525050565b600060208201905061017a6000830184610156565b92915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b60006101ba826100f3565b91506101c5836100f3565b92508282019050808211156101dd576101dc610180565b5b9291505056fea264697066735822122010806f8bd0eb78dd8bf1e05d0621ad54dfe78cd22c6a67e02decd89cd4a2208064736f6c63430008130033"); static const Bytes testProxyBytecode = Hex::toBytes("0x608060405234801561001057600080fd5b50610341806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80637714eaca1461003b5780638e6113211461006b575b600080fd5b61005560048036038101906100509190610232565b61009b565b6040516100629190610281565b60405180910390f35b6100856004803603810190610080919061029c565b610121565b6040516100929190610281565b60405180910390f35b60008273ffffffffffffffffffffffffffffffffffffffff16634fa522db836040518263ffffffff1660e01b81526004016100d69190610281565b6020604051808303816000875af11580156100f5573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061011991906102de565b905092915050565b60008173ffffffffffffffffffffffffffffffffffffffff1663853255cc6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561016e573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061019291906102de565b9050919050565b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006101c98261019e565b9050919050565b6101d9816101be565b81146101e457600080fd5b50565b6000813590506101f6816101d0565b92915050565b6000819050919050565b61020f816101fc565b811461021a57600080fd5b50565b60008135905061022c81610206565b92915050565b6000806040838503121561024957610248610199565b5b6000610257858286016101e7565b92505060206102688582860161021d565b9150509250929050565b61027b816101fc565b82525050565b60006020820190506102966000830184610272565b92915050565b6000602082840312156102b2576102b1610199565b5b60006102c0848285016101e7565b91505092915050565b6000815190506102d881610206565b92915050565b6000602082840312156102f4576102f3610199565b5b6000610302848285016102c9565b9150509291505056fea26469706673582212201c63da23a5ecb525a33d51b61ad178576a9dbc8733cc98401d2be1db76021bbf64736f6c63430008130033"); @@ -104,7 +107,7 @@ TEST_CASE("CallTracer Tests", "[trace]") { REQUIRE(callTrace->value == FixedBytes<32>()); // TODO: gas and gasUsed? // TODO: what are these 4 bytes prefix? - REQUIRE(FixedBytes<32>(callTrace->input | std::views::drop(4)) == FixedBytes<32>(Utils::uint256ToBytes(uint256_t(33)))); + REQUIRE(FixedBytes<32>(callTrace->input | std::views::drop(4)) == FixedBytes<32>(UintConv::uint256ToBytes(uint256_t(33)))); REQUIRE(callTrace->output == Bytes()); REQUIRE(callTrace->calls.empty()); @@ -124,9 +127,9 @@ TEST_CASE("CallTracer Tests", "[trace]") { REQUIRE(callTrace->value == FixedBytes<32>()); // TODO: gas and gasUsed? // TODO: what are these 4 bytes prefix? - REQUIRE(FixedBytes<32>(callTrace->input | std::views::drop(4)) == FixedBytes<32>(Utils::uint256ToBytes(uint256_t(66)))); + REQUIRE(FixedBytes<32>(callTrace->input | std::views::drop(4)) == FixedBytes<32>(UintConv::uint256ToBytes(uint256_t(66)))); - REQUIRE(callTrace->output == Utils::makeBytes(Utils::uint256ToBytes(uint256_t(99)))); + REQUIRE(callTrace->output == Utils::makeBytes(UintConv::uint256ToBytes(uint256_t(99)))); REQUIRE(callTrace->calls.empty()); res = sdk.callViewFunction(contractAddress, &TestWrapper::sum); @@ -160,9 +163,9 @@ TEST_CASE("CallTracer Tests", "[trace]") { REQUIRE(callTrace->value == FixedBytes<32>()); // TODO: gas and gasUsed REQUIRE(Address(callTrace->input | std::views::drop(16) | std::views::take(20)) == testContractAddress); - REQUIRE(FixedBytes<32>(callTrace->input | std::views::drop(36)) == FixedBytes<32>(Utils::uint256ToBytes(uint256_t(55)))); + REQUIRE(FixedBytes<32>(callTrace->input | std::views::drop(36)) == FixedBytes<32>(UintConv::uint256ToBytes(uint256_t(55)))); - REQUIRE(callTrace->output == Utils::makeBytes(Utils::uint256ToBytes(uint256_t(100)))); + REQUIRE(callTrace->output == Utils::makeBytes(UintConv::uint256ToBytes(uint256_t(100)))); REQUIRE(callTrace->calls.size() == 1); const trace::Call& nestedCall = callTrace->calls.front(); @@ -171,9 +174,9 @@ TEST_CASE("CallTracer Tests", "[trace]") { REQUIRE(nestedCall.from == testProxyContractAddress); REQUIRE(nestedCall.to == testContractAddress); REQUIRE(nestedCall.value == FixedBytes<32>()); - REQUIRE(FixedBytes<32>(nestedCall.input | std::views::drop(4)) == FixedBytes<32>(Utils::uint256ToBytes(uint256_t(55)))); + REQUIRE(FixedBytes<32>(nestedCall.input | std::views::drop(4)) == FixedBytes<32>(UintConv::uint256ToBytes(uint256_t(55)))); - REQUIRE(nestedCall.output == Utils::makeBytes(Utils::uint256ToBytes(uint256_t(100)))); + REQUIRE(nestedCall.output == Utils::makeBytes(UintConv::uint256ToBytes(uint256_t(100)))); REQUIRE(nestedCall.calls.empty()); res = sdk.callViewFunction(testContractAddress, &TestWrapper::sum); @@ -294,7 +297,7 @@ TEST_CASE("CallTracer Tests", "[trace]") { REQUIRE(payCallTrace->status == trace::Status::SUCCEEDED); REQUIRE(payCallTrace->from == sdk.getOptions().getChainOwner()); REQUIRE(payCallTrace->to == bankAddress); - REQUIRE(payCallTrace->value == FixedBytes<32>(Utils::uint256ToBytes(uint256_t(4568)))); + REQUIRE(payCallTrace->value == FixedBytes<32>(UintConv::uint256ToBytes(uint256_t(4568)))); REQUIRE(payCallTrace->input == Hex::toBytes("0x1b9265b8")); REQUIRE(payCallTrace->output == Bytes()); REQUIRE(payCallTrace->calls.empty()); diff --git a/tests/contract/contractabigenerator.cpp b/tests/contract/contractabigenerator.cpp index 01c2796ce..5145e7f80 100644 --- a/tests/contract/contractabigenerator.cpp +++ b/tests/contract/contractabigenerator.cpp @@ -5,12 +5,11 @@ This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. */ -#include - #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/jsonabi.h" + +#include "../../src/utils/jsonabi.h" // customcontracts.h -> dynamiccontract.h -> contracthost.h -> contractreflectioninterface.h -> contract/abi.h -> libs/json.hpp -> filesystem + #include "expectedABI.cpp" /// yeah lmao include a .cpp wtf -#include TEST_CASE("ContractABIGenerator helper", "[contract][contractabigenerator]") { SECTION("ContractABIGenerator writeContractsToJson") { diff --git a/tests/contract/createcontract.cpp b/tests/contract/createcontract.cpp index 8d6ca6416..49bd6ffd0 100644 --- a/tests/contract/createcontract.cpp +++ b/tests/contract/createcontract.cpp @@ -6,8 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" + #include "../sdktestsuite.hpp" -#include "../../src/contract/templates/randomnesstest.h" /** * Contract Create Another Contract Solidity Contract: diff --git a/tests/contract/dexv2.cpp b/tests/contract/dexv2.cpp index aff3b422e..7d18e3e9c 100644 --- a/tests/contract/dexv2.cpp +++ b/tests/contract/dexv2.cpp @@ -6,21 +6,13 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/contract/contractmanager.h" -#include "../../src/contract/templates/dexv2/dexv2pair.h" + #include "../../src/contract/templates/dexv2/dexv2factory.h" #include "../../src/contract/templates/dexv2/dexv2router02.h" #include "../../src/contract/templates/nativewrapper.h" -#include "../../src/contract/abi.h" -#include "../../src/utils/db.h" -#include "../../src/utils/options.h" -#include "../../src/core/rdpos.h" -#include "../../src/core/state.h" #include "../sdktestsuite.hpp" -#include - // TODO: test events if/when implemented namespace TDEXV2 { diff --git a/tests/contract/erc20.cpp b/tests/contract/erc20.cpp index 12e752cbc..fa3197582 100644 --- a/tests/contract/erc20.cpp +++ b/tests/contract/erc20.cpp @@ -6,17 +6,11 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" + #include "../../src/contract/templates/erc20.h" -#include "../../src/contract/abi.h" -#include "../../src/utils/db.h" -#include "../../src/utils/options.h" -#include "../../src/contract/contractmanager.h" -#include "../../src/core/rdpos.h" #include "../sdktestsuite.hpp" -#include - // TODO: test events if/when implemented namespace TERC20 { diff --git a/tests/contract/erc20wrapper.cpp b/tests/contract/erc20wrapper.cpp index 3b3e71084..ec967c470 100644 --- a/tests/contract/erc20wrapper.cpp +++ b/tests/contract/erc20wrapper.cpp @@ -6,18 +6,10 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/contract/templates/erc20.h" -#include "../../src/contract/templates/erc20wrapper.h" -#include "../../src/contract/abi.h" -#include "../../src/utils/db.h" -#include "../../src/utils/options.h" -#include "../../src/contract/contractmanager.h" -#include "../../src/core/rdpos.h" -#include "../sdktestsuite.hpp" +#include "../../src/contract/templates/erc20wrapper.h" // erc20.h -#include -#include +#include "../sdktestsuite.hpp" // TODO: test events if/when implemented diff --git a/tests/contract/erc721.cpp b/tests/contract/erc721.cpp index 81d942926..9476cd637 100644 --- a/tests/contract/erc721.cpp +++ b/tests/contract/erc721.cpp @@ -5,14 +5,10 @@ */ #include "../../src/libs/catch2/catch_amalgamated.hpp" + #include "../../src/contract/templates/erc721test.h" -#include "../../src/contract/abi.h" -#include "../../src/utils/db.h" -#include "../../src/utils/options.h" -#include "../../src/contract/contractmanager.h" -#include "../../src/core/rdpos.h" -#include "../sdktestsuite.hpp" +#include "../sdktestsuite.hpp" namespace TERC721 { TEST_CASE("ERC721 Class", "[contract][erc721]") { @@ -225,4 +221,4 @@ namespace TERC721 { } } } -} \ No newline at end of file +} diff --git a/tests/contract/evm.cpp b/tests/contract/evm.cpp index a4fac915b..712f198a8 100644 --- a/tests/contract/evm.cpp +++ b/tests/contract/evm.cpp @@ -5,12 +5,9 @@ */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/contract/templates/erc20.h" -#include "../../src/contract/abi.h" -#include "../../src/utils/db.h" -#include "../../src/utils/options.h" -#include "../../src/contract/templates/erc20wrapper.h" -#include "../../src/core/rdpos.h" + +#include "../../src/contract/templates/erc20wrapper.h" // erc20.h + #include "../sdktestsuite.hpp" namespace TEVM { @@ -30,6 +27,7 @@ namespace TEVM { * } */ Bytes erc20bytecode = Hex::toBytes("0x608060405234801561000f575f80fd5b506040516115f23803806115f2833981810160405281019061003191906103aa565b6040518060400160405280600981526020017f54657374546f6b656e00000000000000000000000000000000000000000000008152506040518060400160405280600381526020017f545354000000000000000000000000000000000000000000000000000000000081525081600390816100ac9190610606565b5080600490816100bc9190610606565b5050506100cf33826100d560201b60201c565b506107ea565b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603610145575f6040517fec442f0500000000000000000000000000000000000000000000000000000000815260040161013c9190610714565b60405180910390fd5b6101565f838361015a60201b60201c565b5050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16036101aa578060025f82825461019e919061075a565b92505081905550610278565b5f805f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905081811015610233578381836040517fe450d38c00000000000000000000000000000000000000000000000000000000815260040161022a9392919061079c565b60405180910390fd5b8181035f808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550505b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16036102bf578060025f8282540392505081905550610309565b805f808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f82825401925050819055505b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8360405161036691906107d1565b60405180910390a3505050565b5f80fd5b5f819050919050565b61038981610377565b8114610393575f80fd5b50565b5f815190506103a481610380565b92915050565b5f602082840312156103bf576103be610373565b5b5f6103cc84828501610396565b91505092915050565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f600282049050600182168061045057607f821691505b6020821081036104635761046261040c565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f600883026104c57fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8261048a565b6104cf868361048a565b95508019841693508086168417925050509392505050565b5f819050919050565b5f61050a61050561050084610377565b6104e7565b610377565b9050919050565b5f819050919050565b610523836104f0565b61053761052f82610511565b848454610496565b825550505050565b5f90565b61054b61053f565b61055681848461051a565b505050565b5b818110156105795761056e5f82610543565b60018101905061055c565b5050565b601f8211156105be5761058f81610469565b6105988461047b565b810160208510156105a7578190505b6105bb6105b38561047b565b83018261055b565b50505b505050565b5f82821c905092915050565b5f6105de5f19846008026105c3565b1980831691505092915050565b5f6105f683836105cf565b9150826002028217905092915050565b61060f826103d5565b67ffffffffffffffff811115610628576106276103df565b5b6106328254610439565b61063d82828561057d565b5f60209050601f83116001811461066e575f841561065c578287015190505b61066685826105eb565b8655506106cd565b601f19841661067c86610469565b5f5b828110156106a35784890151825560018201915060208501945060208101905061067e565b868310156106c057848901516106bc601f8916826105cf565b8355505b6001600288020188555050505b505050505050565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6106fe826106d5565b9050919050565b61070e816106f4565b82525050565b5f6020820190506107275f830184610705565b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f61076482610377565b915061076f83610377565b92508282019050808211156107875761078661072d565b5b92915050565b61079681610377565b82525050565b5f6060820190506107af5f830186610705565b6107bc602083018561078d565b6107c9604083018461078d565b949350505050565b5f6020820190506107e45f83018461078d565b92915050565b610dfb806107f75f395ff3fe608060405234801561000f575f80fd5b5060043610610091575f3560e01c8063313ce56711610064578063313ce5671461013157806370a082311461014f57806395d89b411461017f578063a9059cbb1461019d578063dd62ed3e146101cd57610091565b806306fdde0314610095578063095ea7b3146100b357806318160ddd146100e357806323b872dd14610101575b5f80fd5b61009d6101fd565b6040516100aa9190610a74565b60405180910390f35b6100cd60048036038101906100c89190610b25565b61028d565b6040516100da9190610b7d565b60405180910390f35b6100eb6102af565b6040516100f89190610ba5565b60405180910390f35b61011b60048036038101906101169190610bbe565b6102b8565b6040516101289190610b7d565b60405180910390f35b6101396102e6565b6040516101469190610c29565b60405180910390f35b61016960048036038101906101649190610c42565b6102ee565b6040516101769190610ba5565b60405180910390f35b610187610333565b6040516101949190610a74565b60405180910390f35b6101b760048036038101906101b29190610b25565b6103c3565b6040516101c49190610b7d565b60405180910390f35b6101e760048036038101906101e29190610c6d565b6103e5565b6040516101f49190610ba5565b60405180910390f35b60606003805461020c90610cd8565b80601f016020809104026020016040519081016040528092919081815260200182805461023890610cd8565b80156102835780601f1061025a57610100808354040283529160200191610283565b820191905f5260205f20905b81548152906001019060200180831161026657829003601f168201915b5050505050905090565b5f80610297610467565b90506102a481858561046e565b600191505092915050565b5f600254905090565b5f806102c2610467565b90506102cf858285610480565b6102da858585610512565b60019150509392505050565b5f6012905090565b5f805f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20549050919050565b60606004805461034290610cd8565b80601f016020809104026020016040519081016040528092919081815260200182805461036e90610cd8565b80156103b95780601f10610390576101008083540402835291602001916103b9565b820191905f5260205f20905b81548152906001019060200180831161039c57829003601f168201915b5050505050905090565b5f806103cd610467565b90506103da818585610512565b600191505092915050565b5f60015f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905092915050565b5f33905090565b61047b8383836001610602565b505050565b5f61048b84846103e5565b90507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff811461050c57818110156104fd578281836040517ffb8f41b20000000000000000000000000000000000000000000000000000000081526004016104f493929190610d17565b60405180910390fd5b61050b84848484035f610602565b5b50505050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610582575f6040517f96c6fd1e0000000000000000000000000000000000000000000000000000000081526004016105799190610d4c565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16036105f2575f6040517fec442f050000000000000000000000000000000000000000000000000000000081526004016105e99190610d4c565b60405180910390fd5b6105fd8383836107d1565b505050565b5f73ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1603610672575f6040517fe602df050000000000000000000000000000000000000000000000000000000081526004016106699190610d4c565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16036106e2575f6040517f94280d620000000000000000000000000000000000000000000000000000000081526004016106d99190610d4c565b60405180910390fd5b8160015f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f208190555080156107cb578273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040516107c29190610ba5565b60405180910390a35b50505050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610821578060025f8282546108159190610d92565b925050819055506108ef565b5f805f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20549050818110156108aa578381836040517fe450d38c0000000000000000000000000000000000000000000000000000000081526004016108a193929190610d17565b60405180910390fd5b8181035f808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550505b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603610936578060025f8282540392505081905550610980565b805f808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f82825401925050819055505b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040516109dd9190610ba5565b60405180910390a3505050565b5f81519050919050565b5f82825260208201905092915050565b5f5b83811015610a21578082015181840152602081019050610a06565b5f8484015250505050565b5f601f19601f8301169050919050565b5f610a46826109ea565b610a5081856109f4565b9350610a60818560208601610a04565b610a6981610a2c565b840191505092915050565b5f6020820190508181035f830152610a8c8184610a3c565b905092915050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f610ac182610a98565b9050919050565b610ad181610ab7565b8114610adb575f80fd5b50565b5f81359050610aec81610ac8565b92915050565b5f819050919050565b610b0481610af2565b8114610b0e575f80fd5b50565b5f81359050610b1f81610afb565b92915050565b5f8060408385031215610b3b57610b3a610a94565b5b5f610b4885828601610ade565b9250506020610b5985828601610b11565b9150509250929050565b5f8115159050919050565b610b7781610b63565b82525050565b5f602082019050610b905f830184610b6e565b92915050565b610b9f81610af2565b82525050565b5f602082019050610bb85f830184610b96565b92915050565b5f805f60608486031215610bd557610bd4610a94565b5b5f610be286828701610ade565b9350506020610bf386828701610ade565b9250506040610c0486828701610b11565b9150509250925092565b5f60ff82169050919050565b610c2381610c0e565b82525050565b5f602082019050610c3c5f830184610c1a565b92915050565b5f60208284031215610c5757610c56610a94565b5b5f610c6484828501610ade565b91505092915050565b5f8060408385031215610c8357610c82610a94565b5b5f610c9085828601610ade565b9250506020610ca185828601610ade565b9150509250929050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f6002820490506001821680610cef57607f821691505b602082108103610d0257610d01610cab565b5b50919050565b610d1181610ab7565b82525050565b5f606082019050610d2a5f830186610d08565b610d376020830185610b96565b610d446040830184610b96565b949350505050565b5f602082019050610d5f5f830184610d08565b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f610d9c82610af2565b9150610da783610af2565b9250828201905080821115610dbf57610dbe610d65565b5b9291505056fea264697066735822122043402e069181d2f0057dcffd90d442615a3da729849963e98eada0e05475373164736f6c6343000819003300000000000000000000000000000000000000000000021e19e0c9bab2400000"); + /** * ERC20Wrapper: * pragma solidity ^0.8.0; @@ -277,4 +275,4 @@ namespace TEVM { REQUIRE (sdk.callViewFunction(erc20Address, &ERC20::balanceOf, erc20WrapperAddress) == uint256_t("6666666666666666666667")); } } -} \ No newline at end of file +} diff --git a/tests/contract/nativewrapper.cpp b/tests/contract/nativewrapper.cpp index d3f7ab338..2a0200f13 100644 --- a/tests/contract/nativewrapper.cpp +++ b/tests/contract/nativewrapper.cpp @@ -6,15 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/contract/templates/erc20.h" + #include "../../src/contract/templates/nativewrapper.h" -#include "../../src/contract/abi.h" -#include "../../src/utils/db.h" -#include "../../src/utils/options.h" -#include "../../src/contract/contractmanager.h" -#include "../../src/core/storage.h" -#include "../../src/core/state.h" -#include "../../src/core/rdpos.h" #include "../sdktestsuite.hpp" diff --git a/tests/contract/pebble.cpp b/tests/contract/pebble.cpp index ee6309c41..cdd5c1f6a 100644 --- a/tests/contract/pebble.cpp +++ b/tests/contract/pebble.cpp @@ -6,12 +6,11 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" + #include "../../src/contract/templates/pebble.h" #include "../sdktestsuite.hpp" -#include - namespace TPEBBLE { TEST_CASE("Pebble Class", "[contract][pebble]") { SECTION("Pebble creation") { diff --git a/tests/contract/randomness.cpp b/tests/contract/randomness.cpp index 0f17bc8ec..f39eca379 100644 --- a/tests/contract/randomness.cpp +++ b/tests/contract/randomness.cpp @@ -6,9 +6,11 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../sdktestsuite.hpp" + #include "../../src/contract/templates/randomnesstest.h" +#include "../sdktestsuite.hpp" + /** * Randomness Solidity Contract: * // SPDX-License-Identifier: MIT @@ -65,4 +67,4 @@ namespace TContractRandomness { REQUIRE(sdk.callViewFunction(randomnessContractAddr, &RandomnessTest::getRandom) == randomGen.operator()()); } } -} \ No newline at end of file +} diff --git a/tests/contract/simplecontract.cpp b/tests/contract/simplecontract.cpp index 0b9884170..a66e18627 100644 --- a/tests/contract/simplecontract.cpp +++ b/tests/contract/simplecontract.cpp @@ -6,17 +6,11 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/db.h" -#include "../../src/utils/options.h" -#include "../../src/core/rdpos.h" -#include "../../src/contract/abi.h" -#include "../../src/contract/contractmanager.h" + #include "../../src/contract/templates/simplecontract.h" #include "../sdktestsuite.hpp" -#include - namespace TSimpleContract { TEST_CASE("SimpleContract class", "[contract][simplecontract]") { SECTION("SimpleContract creation") { diff --git a/tests/contract/variables/safearray.cpp b/tests/contract/variables/safearray.cpp index 12a2b8976..100530a00 100644 --- a/tests/contract/variables/safearray.cpp +++ b/tests/contract/variables/safearray.cpp @@ -7,8 +7,6 @@ See the LICENSE.txt file in the project root for more information. #include "../../src/libs/catch2/catch_amalgamated.hpp" #include "../../src/contract/variables/safearray.h" -#include -#include namespace TSafeArray { TEST_CASE("SafeArray Class", "[contract][variables][safearray]") { diff --git a/tests/contract/variables/safeint_t.cpp b/tests/contract/variables/safeint_t.cpp index 78eff8069..74a43eb24 100644 --- a/tests/contract/variables/safeint_t.cpp +++ b/tests/contract/variables/safeint_t.cpp @@ -7,8 +7,7 @@ See the LICENSE.txt file in the project root for more information. #include "../../src/libs/catch2/catch_amalgamated.hpp" #include "../../src/contract/variables/safeint.h" -#include "../../src/utils/utils.h" -#include +#include "../../src/utils/intconv.h" // UnderlyingType // Helper struct and templates for testing multiple types template struct UnderlyingType; diff --git a/tests/contract/variables/safestring.cpp b/tests/contract/variables/safestring.cpp index 96c541986..4b3f9f6ba 100644 --- a/tests/contract/variables/safestring.cpp +++ b/tests/contract/variables/safestring.cpp @@ -5,10 +5,8 @@ This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. */ -#include "../../src/contract/variables/safestring.h" #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include -#include +#include "../../src/contract/variables/safestring.h" namespace TSafeString { TEST_CASE("SafeString class", "[contract][variables][safestring]") { diff --git a/tests/contract/variables/safetuple.cpp b/tests/contract/variables/safetuple.cpp index 9a6b1b9f6..ad4fcb4e9 100644 --- a/tests/contract/variables/safetuple.cpp +++ b/tests/contract/variables/safetuple.cpp @@ -7,10 +7,6 @@ See the LICENSE.txt file in the project root for more information. #include "../../src/libs/catch2/catch_amalgamated.hpp" #include "../../src/contract/variables/safetuple.h" -#include -#include -#include -#include namespace TSafeTuple { TEST_CASE("SafeTuple Class", "[contract][variables][safetuple]") { diff --git a/tests/contract/variables/safeuint_t.cpp b/tests/contract/variables/safeuint_t.cpp index 09af73de8..b3ade2509 100644 --- a/tests/contract/variables/safeuint_t.cpp +++ b/tests/contract/variables/safeuint_t.cpp @@ -7,8 +7,7 @@ See the LICENSE.txt file in the project root for more information. #include "../../src/libs/catch2/catch_amalgamated.hpp" #include "../../src/contract/variables/safeuint.h" -#include "../../src/utils/utils.h" -#include +#include "../../src/utils/uintconv.h" // UnderlyingType // Helper struct and templates for testing multiple types template struct UnderlyingType; diff --git a/tests/contract/variables/safeunorderedmap.cpp b/tests/contract/variables/safeunorderedmap.cpp index b7365afc8..53bafb620 100644 --- a/tests/contract/variables/safeunorderedmap.cpp +++ b/tests/contract/variables/safeunorderedmap.cpp @@ -6,10 +6,7 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/contract/variables/safeunorderedmap.h" -#include "../../src/utils/safehash.h" -#include -#include +#include "../../src/contract/variables/safeunorderedmap.h" // safehash.h namespace TSafeUnorderedMap { TEST_CASE("SafeUnorderedMap Class", "[contract][variables][safeunorderedmap]") { diff --git a/tests/core/blockchain.cpp b/tests/core/blockchain.cpp index fdac3bb0b..c66f1aaf2 100644 --- a/tests/core/blockchain.cpp +++ b/tests/core/blockchain.cpp @@ -5,29 +5,34 @@ This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. */ +// TODO: this is commented out on CMakeLists.txt, revise later + +#include + #include "../../src/libs/catch2/catch_amalgamated.hpp" + #include "../../src/core/blockchain.h" + #include "../../src/net/p2p/managerdiscovery.h" -#include -/// Forward decleration from tests/net/http/httpjsonrpc.cpp -/// For usage within sending transactions +// Forward declaration from tests/net/http/httpjsonrpc.cpp, for usage within sending transactions std::string makeHTTPRequest( - const std::string& reqBody, const std::string& host, const std::string& port, - const std::string& target, const std::string& requestType, const std::string& contentType + const std::string& reqBody, const std::string& host, const std::string& port, + const std::string& target, const std::string& requestType, const std::string& contentType ); - -void initialize(const std::string& blockchainPath, - const std::string& web3clientVersion, - const uint64_t& version, - const uint64_t& chainId, - const uint64_t& wsPort, - const uint64_t& httpPort, - const PrivKey& privKey, - const std::pair& discoveryNodes, - std::unique_ptr& blockchain, - bool clearFolder = true) { +void initialize( + const std::string& blockchainPath, + const std::string& web3clientVersion, + const uint64_t& version, + const uint64_t& chainId, + const uint64_t& wsPort, + const uint64_t& httpPort, + const PrivKey& privKey, + const std::pair& discoveryNodes, + std::unique_ptr& blockchain, + bool clearFolder = true +) { if (clearFolder) { if (std::filesystem::exists(blockchainPath)) { std::filesystem::remove_all(blockchainPath); @@ -420,3 +425,4 @@ namespace TBlockchain { } } } + diff --git a/tests/core/dumpmanager.cpp b/tests/core/dumpmanager.cpp index 93a862098..cf36d6bb8 100644 --- a/tests/core/dumpmanager.cpp +++ b/tests/core/dumpmanager.cpp @@ -6,17 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/core/rdpos.h" -#include "../../src/core/storage.h" -#include "../../src/core/state.h" -#include "../../src/utils/db.h" -#include "../../src/net/p2p/managernormal.h" -#include "../../src/net/p2p/managerdiscovery.h" -#include "../../src/contract/abi.h" -#include "../blockchainwrapper.hpp" -#include -#include +#include "../blockchainwrapper.hpp" // blockchain.h -> consensus.h -> state.h -> (rdpos.h -> net/p2p/managernormal.h), dump.h -> storage.h, utils/db.h -> utils.h -> filesystem const std::vector validatorPrivKeysState { Hash(Hex::toBytes("0x0a0415d68a5ec2df57aab65efc2a7231b59b029bae7ff1bd2e40df9af96418c8")), diff --git a/tests/core/rdpos.cpp b/tests/core/rdpos.cpp index 7fbf73f42..a4d536281 100644 --- a/tests/core/rdpos.cpp +++ b/tests/core/rdpos.cpp @@ -6,18 +6,11 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/core/rdpos.h" -#include "../../src/core/storage.h" -#include "../../src/core/state.h" -#include "../../src/utils/db.h" -#include "../../src/utils/options.h" -#include "../../src/net/p2p/managernormal.h" + #include "../../src/net/p2p/managerdiscovery.h" -#include "../blockchainwrapper.hpp" -#include "../sdktestsuite.hpp" -#include -#include +#include "../blockchainwrapper.hpp" // blockchain.h -> consensus.h -> state.h -> (rdpos.h -> net/p2p/managernormal.h), dump.h -> (storage.h -> utils/options.h), utils/db.h +#include "../sdktestsuite.hpp" const std::vector validatorPrivKeysRdpos { Hash(Hex::toBytes("0x0a0415d68a5ec2df57aab65efc2a7231b59b029bae7ff1bd2e40df9af96418c8")), diff --git a/tests/core/state.cpp b/tests/core/state.cpp index 676bb4349..0164e4d72 100644 --- a/tests/core/state.cpp +++ b/tests/core/state.cpp @@ -6,20 +6,13 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/core/rdpos.h" -#include "../../src/core/storage.h" -#include "../../src/core/state.h" -#include "../../src/utils/db.h" -#include "../../src/net/p2p/managernormal.h" + #include "../../src/net/p2p/managerdiscovery.h" -#include "../../src/contract/abi.h" -#include "../blockchainwrapper.hpp" -#include "../sdktestsuite.hpp" -#include -#include +#include "../../src/utils/uintconv.h" -#include "contract/contracthost.h" +#include "../blockchainwrapper.hpp" // blockchain.h -> consensus.h -> state.h -> (rdpos.h -> net/p2p/managernormal.h), dump.h -> storage.h, utils/db.h +#include "../sdktestsuite.hpp" // contracthost.h -> contractmanager.h -> contractreflectioninterface.h -> abi.h const std::vector validatorPrivKeysState { Hash(Hex::toBytes("0x0a0415d68a5ec2df57aab65efc2a7231b59b029bae7ff1bd2e40df9af96418c8")), @@ -36,7 +29,7 @@ const std::vector validatorPrivKeysState { std::pair buildCallInfo(const Address& addressToCall, const Functor& function, const Bytes& dataToCall) { std::pair callInfo; Bytes& messageBytes = std::get<1>(callInfo); - Utils::appendBytes(messageBytes, Utils::uint32ToBytes(function.value)); + Utils::appendBytes(messageBytes, UintConv::uint32ToBytes(function.value)); Utils::appendBytes(messageBytes, dataToCall); auto& [callKind, callFlags, diff --git a/tests/core/storage.cpp b/tests/core/storage.cpp index db5faded3..6da9be9ed 100644 --- a/tests/core/storage.cpp +++ b/tests/core/storage.cpp @@ -6,13 +6,10 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/core/storage.h" -#include "../../src/utils/db.h" -#include "../../src/utils/options.h" -#include "../blockchainwrapper.hpp" -#include -#include +#include "../../src/utils/uintconv.h" + +#include "../blockchainwrapper.hpp" // blockchain.h -> consensus.h -> state.h -> dump.h -> (storage.h -> utils/options.h), utils/db.h const std::vector validatorPrivKeysStorage { Hash(Hex::toBytes("0x0a0415d68a5ec2df57aab65efc2a7231b59b029bae7ff1bd2e40df9af96418c8")), @@ -40,11 +37,11 @@ TxBlock createRandomTx(const uint64_t& requiredChainId) { Address to(Utils::randBytes(20)); Bytes data = Utils::randBytes(32); uint64_t chainId = requiredChainId; - uint256_t nonce = Utils::bytesToUint32(Utils::randBytes(4)); - uint256_t value = Utils::bytesToUint64(Utils::randBytes(8)); - uint256_t maxGasPerFee = Utils::bytesToUint32(Utils::randBytes(4)); - uint256_t maxPriorityFeePerGas = Utils::bytesToUint32(Utils::randBytes(4)); - uint256_t gasLimit = Utils::bytesToUint32(Utils::randBytes(4)); + uint256_t nonce = UintConv::bytesToUint32(Utils::randBytes(4)); + uint256_t value = UintConv::bytesToUint64(Utils::randBytes(8)); + uint256_t maxGasPerFee = UintConv::bytesToUint32(Utils::randBytes(4)); + uint256_t maxPriorityFeePerGas = UintConv::bytesToUint32(Utils::randBytes(4)); + uint256_t gasLimit = UintConv::bytesToUint32(Utils::randBytes(4)); return TxBlock(to, from, data, chainId, nonce, value, maxPriorityFeePerGas, maxGasPerFee, gasLimit, txPrivKey); } diff --git a/tests/net/http/httpjsonrpc.cpp b/tests/net/http/httpjsonrpc.cpp index d106868d9..96b44d656 100644 --- a/tests/net/http/httpjsonrpc.cpp +++ b/tests/net/http/httpjsonrpc.cpp @@ -6,13 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/utils.h" -#include "../../src/utils/options.h" -#include "../../src/net/p2p/managernormal.h" -#include "../../src/net/http/httpserver.h" -#include "../../src/core/state.h" -#include "../../src/core/storage.h" -#include "../../blockchainwrapper.hpp" + +#include "../../blockchainwrapper.hpp" // blockchain.h -> (net/http/httpserver.h -> net/p2p/managernormal.h), consensus.h -> state.h -> dump.h -> (storage.h -> utils/options.h), utils/db.h -> utils.h std::string makeHTTPRequest( const std::string& reqBody, const std::string& host, const std::string& port, diff --git a/tests/net/p2p/p2p.cpp b/tests/net/p2p/p2p.cpp index 078ee0513..8fa34e317 100644 --- a/tests/net/p2p/p2p.cpp +++ b/tests/net/p2p/p2p.cpp @@ -6,19 +6,15 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/utils.h" -#include "../../src/net/p2p/managernormal.h" + #include "../../src/net/p2p/managerdiscovery.h" -#include "../../src/core/rdpos.h" -#include "../../src/core/storage.h" -#include "../../src/core/state.h" -#include "../../src/utils/db.h" -#include "../../blockchainwrapper.hpp" -#include "../../sdktestsuite.hpp" + +#include "../../blockchainwrapper.hpp" // blockchain.h -> consensus.h -> state.h -> (rdpos.h -> net/p2p/managernormal.h), dump.h -> storage.h, utils/db.h -> utils.h +#include "../../sdktestsuite.hpp" // contracthost.h -> contractmanager.h -> contractreflectioninterface.h -> abi.h using Catch::Matchers::Equals; -namespace TP2P { +namespace TP2P { const std::vector validatorPrivKeysP2P { Hash(Hex::toBytes("0x0a0415d68a5ec2df57aab65efc2a7231b59b029bae7ff1bd2e40df9af96418c8")), Hash(Hex::toBytes("0xb254f12b4ca3f0120f305cabf1188fe74f0bd38e58c932a3df79c4c55df8fa66")), diff --git a/tests/sdktestsuite.cpp b/tests/sdktestsuite.cpp index 91110e0c3..2bc2fdca7 100644 --- a/tests/sdktestsuite.cpp +++ b/tests/sdktestsuite.cpp @@ -5,14 +5,15 @@ This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. */ -#include "sdktestsuite.hpp" - #include "../../src/libs/catch2/catch_amalgamated.hpp" + #include "../../src/contract/templates/erc20.h" #include "../../src/contract/templates/simplecontract.h" #include "../../src/contract/templates/testThrowVars.h" -#include "../../src/utils/clargs.h" -#include + +#include "../../src/utils/clargs.h" // ProcessOptions + +#include "sdktestsuite.hpp" // Initialize static listen port generator parameters int SDKTestSuite::p2pListenPortMin_ = 20000; diff --git a/tests/sdktestsuite.hpp b/tests/sdktestsuite.hpp index 8ef39714e..5b492629c 100644 --- a/tests/sdktestsuite.hpp +++ b/tests/sdktestsuite.hpp @@ -8,18 +8,12 @@ See the LICENSE.txt file in the project root for more information. #ifndef SDKTESTSUITE_H #define SDKTESTSUITE_H -#include "../src/core/storage.h" -#include "../src/core/rdpos.h" -#include "../src/core/state.h" -#include "../src/net/p2p/managernormal.h" -#include "../src/net/http/httpserver.h" -#include "../src/utils/options.h" -#include "../src/utils/db.h" -#include "../src/core/blockchain.h" -#include "../src/utils/utils.h" -#include "contract/contracthost.h" -#include "statetest.hpp" +#include "../src/core/blockchain.h" // net/http/httpserver.h, consensus.h -> state.h -> rdpos.h -> net/p2p/managernormal.h, (utils/tx.h -> ecdsa.h -> utils.h -> libs/json.hpp -> tuple), (dump.h -> utils/db.h, storage.h -> options.h) + +#include "../src/utils/evmcconv.h" +#include "../src/utils/uintconv.h" +#include "statetest.hpp" /// Wrapper struct for accounts used within the SDKTestSuite. struct TestAccount { @@ -338,7 +332,7 @@ class SDKTestSuite { callSender = from.address.toEvmcAddress(); callInputData = data.data(); callInputSize = data.size(); - callValue = Utils::uint256ToEvmcUint256(value); + callValue = EVMCConv::uint256ToEvmcUint256(value); callCreate2Salt = {}; callCodeAddress = {}; auto usedGas = this->state_.estimateGas(callInfo); @@ -516,7 +510,7 @@ class SDKTestSuite { ContractReflectionInterface::getFunctionName(func) ); Bytes txData; - Utils::appendBytes(txData, Utils::uint32ToBytes(txFunctor.value)); + Utils::appendBytes(txData, UintConv::uint32ToBytes(txFunctor.value)); // Use the chain owner account if no account is provided TxBlock tx = this->createNewTx( ((!testAccount) ? this->getChainOwnerAccount() : testAccount), @@ -559,7 +553,7 @@ class SDKTestSuite { ContractReflectionInterface::getFunctionName(func) ); Bytes txData; - Utils::appendBytes(txData, Utils::uint32ToBytes(txFunctor.value)); + Utils::appendBytes(txData, UintConv::uint32ToBytes(txFunctor.value)); Utils::appendBytes( txData, ABI::Encoder::encodeData(std::forward(args)...) ); @@ -775,7 +769,7 @@ class SDKTestSuite { auto functor = ABI::FunctorEncoder::encode<>(ContractReflectionInterface::getFunctionName(func)); Bytes fullData; - Utils::appendBytes(fullData, Utils::uint32ToBytes(functor.value)); + Utils::appendBytes(fullData, UintConv::uint32ToBytes(functor.value)); callKind = EVMC_CALL; callFlags = 0; @@ -785,7 +779,7 @@ class SDKTestSuite { callSender = this->getChainOwnerAccount().address.toEvmcAddress(); callInputData = fullData.data(); callInputSize = fullData.size(); - callValue = Utils::uint256ToEvmcUint256(0); + callValue = EVMCConv::uint256ToEvmcUint256(0); callCreate2Salt = {}; callCodeAddress = contractAddress.toEvmcAddress(); return std::get<0>(ABI::Decoder::decodeData(this->state_.ethCall(callData))); @@ -822,7 +816,7 @@ class SDKTestSuite { callCodeAddress] = callData; auto functor = ABI::FunctorEncoder::encode(ContractReflectionInterface::getFunctionName(func)); Bytes fullData; - Utils::appendBytes(fullData, Utils::uint32ToBytes(functor.value)); + Utils::appendBytes(fullData, UintConv::uint32ToBytes(functor.value)); Utils::appendBytes(fullData, ABI::Encoder::encodeData(std::forward(args)...)); callKind = EVMC_CALL; @@ -833,7 +827,7 @@ class SDKTestSuite { callSender = this->getChainOwnerAccount().address.toEvmcAddress(); callInputData = fullData.data(); callInputSize = fullData.size(); - callValue = Utils::uint256ToEvmcUint256(0); + callValue = EVMCConv::uint256ToEvmcUint256(0); callCreate2Salt = {}; callCodeAddress = {}; diff --git a/tests/statetest.hpp b/tests/statetest.hpp index 71bd488fe..7f69fb69b 100644 --- a/tests/statetest.hpp +++ b/tests/statetest.hpp @@ -1,7 +1,16 @@ -#include "../src/core/state.h" -#include "../src/contract/contracthost.h" +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#ifndef STATETEST_HPP +#define STATETEST_HPP +#include "../src/core/state.h" +#include "../src/contract/contracthost.h" // TestState class // The only purpose of this class is to be able to allow @@ -12,19 +21,21 @@ class StateTest : public State { public: // StateTest has the same constructor as State - StateTest(const DB& db, Storage& storage, P2P::ManagerNormal& p2pManager, const uint64_t& snapshotHeight, const Options& options) : - State(db, storage, p2pManager, snapshotHeight, options) {}; - - /** - * Force a contract call, regardless of the current state. - */ - inline void call(const evmc_message& callInfo, - const evmc_tx_context& txContext, - const ContractType& type, - const Hash& randomness, - const Hash& txHash, - const Hash& blockHash, - int64_t& leftOverGas) { + StateTest( + const DB& db, Storage& storage, P2P::ManagerNormal& p2pManager, + const uint64_t& snapshotHeight, const Options& options + ) : State(db, storage, p2pManager, snapshotHeight, options) {}; + + // Force a contract call regardless of the current state + inline void call( + const evmc_message& callInfo, + const evmc_tx_context& txContext, + const ContractType& type, + const Hash& randomness, + const Hash& txHash, + const Hash& blockHash, + int64_t& leftOverGas + ) { ContractHost host( this->vm_, this->dumpManager_, @@ -41,4 +52,6 @@ class StateTest : public State { ); host.execute(callInfo, type); } -}; \ No newline at end of file +}; + +#endif // STATETEST_HPP diff --git a/tests/utils/block.cpp b/tests/utils/block.cpp index c9a3e841f..afc6d9293 100644 --- a/tests/utils/block.cpp +++ b/tests/utils/block.cpp @@ -6,9 +6,10 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/utils.h" -#include "../../src/utils/tx.h" -#include "../../src/utils/finalizedblock.h" + +#include "../../src/utils/finalizedblock.h" // merkle.h -> tx.h -> ecdsa.h -> utils.h + +#include "../../src/utils/uintconv.h" using Catch::Matchers::Equals; @@ -153,10 +154,10 @@ namespace TBlock { Address to(Utils::randBytes(20)); Bytes data = Utils::randBytes(32); uint64_t chainId = 8080; - uint256_t nonce = Utils::bytesToUint32(Utils::randBytes(4)); - uint256_t value = Utils::bytesToUint64(Utils::randBytes(8)); - uint256_t gasLimit = Utils::bytesToUint32(Utils::randBytes(4)); - uint256_t maxFeePerGas = Utils::bytesToUint32(Utils::randBytes(4)); + uint256_t nonce = UintConv::bytesToUint32(Utils::randBytes(4)); + uint256_t value = UintConv::bytesToUint64(Utils::randBytes(8)); + uint256_t gasLimit = UintConv::bytesToUint32(Utils::randBytes(4)); + uint256_t maxFeePerGas = UintConv::bytesToUint32(Utils::randBytes(4)); txs.emplace_back( to, from, @@ -254,10 +255,10 @@ namespace TBlock { Address to(Utils::randBytes(20)); Bytes data = Utils::randBytes(32); uint64_t chainId = 8080; - uint256_t nonce = Utils::bytesToUint32(Utils::randBytes(4)); - uint256_t value = Utils::bytesToUint64(Utils::randBytes(8)); - uint256_t gasLimit = Utils::bytesToUint32(Utils::randBytes(4)); - uint256_t maxFeePerGas = Utils::bytesToUint32(Utils::randBytes(4)); + uint256_t nonce = UintConv::bytesToUint32(Utils::randBytes(4)); + uint256_t value = UintConv::bytesToUint64(Utils::randBytes(8)); + uint256_t gasLimit = UintConv::bytesToUint32(Utils::randBytes(4)); + uint256_t maxFeePerGas = UintConv::bytesToUint32(Utils::randBytes(4)); auto tx = TxBlock( to, from, diff --git a/tests/utils/block_throw.cpp b/tests/utils/block_throw.cpp index a1fa4c222..0ddf85ae9 100644 --- a/tests/utils/block_throw.cpp +++ b/tests/utils/block_throw.cpp @@ -6,11 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/utils.h" -#include "../../src/utils/tx.h" -#include "../../src/utils/finalizedblock.h" -#include "../../src/utils/ecdsa.h" +#include "../../src/utils/finalizedblock.h" // merkle.h -> tx.h -> ecdsa.h -> utils.h using Catch::Matchers::Equals; diff --git a/tests/utils/db.cpp b/tests/utils/db.cpp index 43a5d5409..348c5d09f 100644 --- a/tests/utils/db.cpp +++ b/tests/utils/db.cpp @@ -6,11 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/db.h" -#include "../../src/utils/strings.h" -#include -#include +#include "../../src/utils/db.h" // utils.h -> strings.h, libs/json.hpp -> (filesystem, string) using Catch::Matchers::Equals; diff --git a/tests/utils/dynamicexception.cpp b/tests/utils/dynamicexception.cpp index 471244c23..5e929074a 100644 --- a/tests/utils/dynamicexception.cpp +++ b/tests/utils/dynamicexception.cpp @@ -1,141 +1,144 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + #include "../../src/libs/catch2/catch_amalgamated.hpp" + #include "../../src/utils/dynamicexception.h" -#include namespace TDynamicException { - - class CustomObject { + class CustomObject { public: - int value; - CustomObject(int v) : value(v) {} - friend std::ostream& operator<<(std::ostream& os, const CustomObject& obj) { - return os << "CustomObject(value=" << obj.value << ")"; - } - }; - - TEST_CASE("DynamicException Class", "[utils][dynamicexception]") { - SECTION("Exception message is set and retrieved correctly") { - const std::string filename = "test.cpp"; - const int line = 42; - const std::string function = "testFunction"; - const std::string message = "Test message"; - DynamicException exception("Function " + function + " failed: " + message + " at " + filename + ":", line); - - try { - throw exception; - } catch (const DynamicException& e) { - REQUIRE(e.what() == "Function " + function + " failed: " + message + " at " + filename + ":" + std::to_string(line)); - REQUIRE(e.getFile() == ""); - REQUIRE(e.getLine() == 0); - REQUIRE(e.getFunction() == ""); - } - } - - SECTION("Exception with file, line, and function information") { - const std::string filename = "test.cpp"; - const int line = 42; - const std::string function = "testFunction"; - const std::string message = "Error in file " + filename + " at line " + std::to_string(line) + " in function " + function; - DynamicException exception(message, filename, line, function); - - try { - throw exception; - } catch (const DynamicException& e) { - REQUIRE(e.what() == message); - REQUIRE(e.getFile() == filename); - REQUIRE(e.getLine() == line); - REQUIRE(e.getFunction() == function); - } - } - - - SECTION("Timestamp is correctly formatted") { - const std::string message = "Error with timestamp"; - DynamicException exception(message); - - try { - throw exception; - } catch (const DynamicException& e) { - std::string timestamp = e.getTimestamp(); - REQUIRE(!timestamp.empty()); - REQUIRE(timestamp.length() == 19); // Checking the length of the timestamp - REQUIRE(timestamp[4] == '-'); - REQUIRE(timestamp[7] == '-'); - REQUIRE(timestamp[10] == ' '); - REQUIRE(timestamp[13] == ':'); - REQUIRE(timestamp[16] == ':'); - } - } - - SECTION("Exception with single message") { - const std::string message = "Error with single string message"; - DynamicException exception(message); - - try { - throw exception; - } catch (const DynamicException& e) { - REQUIRE(e.what() == message); - REQUIRE(e.getFile() == ""); - REQUIRE(e.getLine() == 0); - REQUIRE(e.getFunction() == ""); - } - } - - SECTION("Exception with multiple messages") { - int a = 5; - int b = 10; - const std::string message = "Error with multiple messages: " + std::to_string(a) + " and " + std::to_string(b); - DynamicException exception("Error with multiple messages: ", a, " and ", b); - - try { - throw exception; - } catch (const DynamicException& e) { - REQUIRE(e.what() == message); - REQUIRE(e.getFile() == ""); - REQUIRE(e.getLine() == 0); - REQUIRE(e.getFunction() == ""); - } - } - - SECTION("Exception with various basic types") { - int intValue = 42; - double doubleValue = 3.14; - const std::string message = "Error occurred with values: "; - DynamicException exception(message, intValue, " and ", doubleValue); - - try { - throw exception; - } catch (const DynamicException& e) { - REQUIRE_THAT(e.what(), Catch::Matchers::Equals("Error occurred with values: 42 and 3.14")); - } - } - - SECTION("Exception with strings and literals") { - const std::string part1 = "Error: "; - const char* part2 = "Invalid operation"; - DynamicException exception(part1, part2); - - try { - throw exception; - } catch (const DynamicException& e) { - REQUIRE(e.what() == std::string("Error: Invalid operation")); - } - } - - - SECTION("Exception with custom objects") { - CustomObject obj(100); - DynamicException exception("Encountered an issue with ", obj); - - try { - throw exception; - } catch (const DynamicException& e) { - REQUIRE_THAT(e.what(), Catch::Matchers::Equals("Encountered an issue with CustomObject(value=100)")); - } - } + int value; + CustomObject(int v) : value(v) {} + friend std::ostream& operator<<(std::ostream& os, const CustomObject& obj) { + return os << "CustomObject(value=" << obj.value << ")"; + } + }; + + TEST_CASE("DynamicException Class", "[utils][dynamicexception]") { + SECTION("Exception message is set and retrieved correctly") { + const std::string filename = "test.cpp"; + const int line = 42; + const std::string function = "testFunction"; + const std::string message = "Test message"; + DynamicException exception("Function " + function + " failed: " + message + " at " + filename + ":", line); + + try { + throw exception; + } catch (const DynamicException& e) { + REQUIRE(e.what() == "Function " + function + " failed: " + message + " at " + filename + ":" + std::to_string(line)); + REQUIRE(e.getFile() == ""); + REQUIRE(e.getLine() == 0); + REQUIRE(e.getFunction() == ""); + } + } + SECTION("Exception with file, line, and function information") { + const std::string filename = "test.cpp"; + const int line = 42; + const std::string function = "testFunction"; + const std::string message = "Error in file " + filename + " at line " + std::to_string(line) + " in function " + function; + DynamicException exception(message, filename, line, function); + + try { + throw exception; + } catch (const DynamicException& e) { + REQUIRE(e.what() == message); + REQUIRE(e.getFile() == filename); + REQUIRE(e.getLine() == line); + REQUIRE(e.getFunction() == function); + } + } + SECTION("Timestamp is correctly formatted") { + const std::string message = "Error with timestamp"; + DynamicException exception(message); + + try { + throw exception; + } catch (const DynamicException& e) { + std::string timestamp = e.getTimestamp(); + REQUIRE(!timestamp.empty()); + REQUIRE(timestamp.length() == 19); // Checking the length of the timestamp + REQUIRE(timestamp[4] == '-'); + REQUIRE(timestamp[7] == '-'); + REQUIRE(timestamp[10] == ' '); + REQUIRE(timestamp[13] == ':'); + REQUIRE(timestamp[16] == ':'); + } + } + SECTION("Exception with single message") { + const std::string message = "Error with single string message"; + DynamicException exception(message); + + try { + throw exception; + } catch (const DynamicException& e) { + REQUIRE(e.what() == message); + REQUIRE(e.getFile() == ""); + REQUIRE(e.getLine() == 0); + REQUIRE(e.getFunction() == ""); + } } + + SECTION("Exception with multiple messages") { + int a = 5; + int b = 10; + const std::string message = "Error with multiple messages: " + std::to_string(a) + " and " + std::to_string(b); + DynamicException exception("Error with multiple messages: ", a, " and ", b); + + try { + throw exception; + } catch (const DynamicException& e) { + REQUIRE(e.what() == message); + REQUIRE(e.getFile() == ""); + REQUIRE(e.getLine() == 0); + REQUIRE(e.getFunction() == ""); + } + } + + SECTION("Exception with various basic types") { + int intValue = 42; + double doubleValue = 3.14; + const std::string message = "Error occurred with values: "; + DynamicException exception(message, intValue, " and ", doubleValue); + + try { + throw exception; + } catch (const DynamicException& e) { + REQUIRE_THAT(e.what(), Catch::Matchers::Equals("Error occurred with values: 42 and 3.14")); + } + } + + SECTION("Exception with strings and literals") { + const std::string part1 = "Error: "; + const char* part2 = "Invalid operation"; + DynamicException exception(part1, part2); + + try { + throw exception; + } catch (const DynamicException& e) { + REQUIRE(e.what() == std::string("Error: Invalid operation")); + } + } + + + SECTION("Exception with custom objects") { + CustomObject obj(100); + DynamicException exception("Encountered an issue with ", obj); + + try { + throw exception; + } catch (const DynamicException& e) { + REQUIRE_THAT(e.what(), Catch::Matchers::Equals("Encountered an issue with CustomObject(value=100)")); + } + } + } } + diff --git a/tests/utils/ecdsa.cpp b/tests/utils/ecdsa.cpp index 816d9f05d..947303687 100644 --- a/tests/utils/ecdsa.cpp +++ b/tests/utils/ecdsa.cpp @@ -6,8 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/utils.h" -#include "../../src/utils/ecdsa.h" + +#include "../../src/utils/ecdsa.h" // utils.h using Catch::Matchers::Equals; diff --git a/tests/utils/hex.cpp b/tests/utils/hex.cpp index f810f03a1..895d9dad9 100644 --- a/tests/utils/hex.cpp +++ b/tests/utils/hex.cpp @@ -6,7 +6,7 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/utils.h" + #include "../../src/utils/hex.h" using Catch::Matchers::Equals; diff --git a/tests/utils/merkle.cpp b/tests/utils/merkle.cpp index 155f55244..30878342f 100644 --- a/tests/utils/merkle.cpp +++ b/tests/utils/merkle.cpp @@ -5,12 +5,10 @@ This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. */ -#include - -#include "../../src/utils/merkle.h" -#include "../../src/utils/tx.h" #include "../../src/libs/catch2/catch_amalgamated.hpp" +#include "../../src/utils/merkle.h" // tx.h + using Catch::Matchers::Equals; namespace TMerkle { diff --git a/tests/utils/options.cpp b/tests/utils/options.cpp index cbddfa939..1a248cc40 100644 --- a/tests/utils/options.cpp +++ b/tests/utils/options.cpp @@ -6,8 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/options.h" -#include + +#include "../../src/utils/options.h" // finalizedblock.h -> merkle.h -> tx.h -> ecdsa.h -> utils.h -> filesystem const std::vector validatorPrivKeys_ { PrivKey(Hex::toBytes("0x0a0415d68a5ec2df57aab65efc2a7231b59b029bae7ff1bd2e40df9af96418c8")), diff --git a/tests/utils/randomgen.cpp b/tests/utils/randomgen.cpp index 958ee2721..75751ee8e 100644 --- a/tests/utils/randomgen.cpp +++ b/tests/utils/randomgen.cpp @@ -5,10 +5,9 @@ This software is distributed under the MIT License. See the LICENSE.txt file in the project root for more information. */ -#include +#include "../../src/libs/catch2/catch_amalgamated.hpp" #include "../../src/utils/randomgen.h" -#include "../../src/libs/catch2/catch_amalgamated.hpp" using Catch::Matchers::Equals; diff --git a/tests/utils/strconv.cpp b/tests/utils/strconv.cpp new file mode 100644 index 000000000..29070aadb --- /dev/null +++ b/tests/utils/strconv.cpp @@ -0,0 +1,57 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#include "../../src/libs/catch2/catch_amalgamated.hpp" + +#include "../../src/utils/strconv.h" + +#include "../../src/utils/hex.h" + +using Catch::Matchers::Equals; + +// TODO: missing tests for padLeft/padRight (no bytes) and cArrayToBytes + +namespace TUtils { + TEST_CASE("StrConv Namespace", "[utils][strconv]") { + SECTION("padLeftBytes Test") { + Bytes inputBytes = Hex::toBytes("0xabcdef"); + Bytes outputBytes = StrConv::padLeftBytes(inputBytes, 10, 0x00); + Bytes outputBytes2 = StrConv::padLeftBytes(inputBytes, 20, 0x11); + Bytes expectedOutputBytes = Hex::toBytes("0x00000000000000abcdef"); + Bytes expectedOutputBytes2 = Hex::toBytes("0x1111111111111111111111111111111111abcdef"); + REQUIRE(outputBytes == expectedOutputBytes); + REQUIRE(outputBytes2 == expectedOutputBytes2); + } + + SECTION("padRightBytes Test") { + Bytes inputBytes = Hex::toBytes("0xabcdef"); + Bytes outputBytes = StrConv::padRightBytes(inputBytes, 10, 0x00); + Bytes outputBytes2 = StrConv::padRightBytes(inputBytes, 20, 0x11); + Bytes expectedOutputBytes = Hex::toBytes("0xabcdef00000000000000"); + Bytes expectedOutputBytes2 = Hex::toBytes("0xabcdef1111111111111111111111111111111111"); + REQUIRE(outputBytes == expectedOutputBytes); + REQUIRE(outputBytes2 == expectedOutputBytes2); + } + + SECTION("toLower Test") { + std::string inputStr = "ABCDEF"; + std::string outputStr = inputStr; + StrConv::toLower(outputStr); + std::string expectedOutputStr = "abcdef"; + REQUIRE_THAT(outputStr, Equals(expectedOutputStr)); + } + + SECTION("toUpper Test") { + std::string inputStr = "abcdef"; + std::string outputStr = inputStr; + StrConv::toUpper(outputStr); + std::string expectedOutputStr = "ABCDEF"; + REQUIRE_THAT(outputStr, Equals(expectedOutputStr)); + } + } +} + diff --git a/tests/utils/strings.cpp b/tests/utils/strings.cpp index b980881b1..987b58466 100644 --- a/tests/utils/strings.cpp +++ b/tests/utils/strings.cpp @@ -6,8 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/strings.h" -#include "bytes/view.h" + +#include "../../src/utils/strings.h" // bytes/initializer.h -> bytes/view.h using Catch::Matchers::Equals; diff --git a/tests/utils/tx.cpp b/tests/utils/tx.cpp index b1d7551c5..b541154ea 100644 --- a/tests/utils/tx.cpp +++ b/tests/utils/tx.cpp @@ -6,8 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/utils.h" -#include "../../src/utils/tx.h" + +#include "../../src/utils/tx.h" // ecdsa.h -> utils.h using Catch::Matchers::Equals; diff --git a/tests/utils/tx_throw.cpp b/tests/utils/tx_throw.cpp index 07e2af918..a07f77a46 100644 --- a/tests/utils/tx_throw.cpp +++ b/tests/utils/tx_throw.cpp @@ -6,8 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/utils.h" -#include "../../src/utils/tx.h" + +#include "../../src/utils/tx.h" // ecdsa.h -> utils.h using Catch::Matchers::Equals; diff --git a/tests/utils/uintconv.cpp b/tests/utils/uintconv.cpp new file mode 100644 index 000000000..b2ea5c879 --- /dev/null +++ b/tests/utils/uintconv.cpp @@ -0,0 +1,773 @@ +/* +Copyright (c) [2023-2024] [AppLayer Developers] + +This software is distributed under the MIT License. +See the LICENSE.txt file in the project root for more information. +*/ + +#include "../../src/libs/catch2/catch_amalgamated.hpp" + +#include "../../src/utils/uintconv.h" + +#include "../../src/utils/utils.h" // strings.h -> hex.h + +using Catch::Matchers::Equals; + +// TODO: theoretically missing int_t tests + +namespace TUtils { + TEST_CASE("UintConv Namespace", "[utils][uintconv]") { + SECTION("uint256ToBytes Test") { + uint256_t uint256Input = uint256_t("91830918212381802449294565349763096207758814059154440393436864477986483867239"); + auto uint256Output = UintConv::uint256ToBytes(uint256Input); + BytesArr<32> uint256ExpectedOutput = BytesArr<32> {0xcb, 0x06, 0x75, 0x32, 0x90, 0xff, 0xac, 0x16, 0x72, 0x05, 0xd0, 0xf5, 0x3b, 0x64, 0xac, 0xfd, 0x80, 0xbe, 0x11, 0xed, 0xbb, 0x26, 0xa2, 0x24, 0xbe, 0xd9, 0x23, 0x9a, 0xe6, 0x74, 0x0e, 0x67}; + REQUIRE(uint256Output == uint256ExpectedOutput); + } + + SECTION("uint248ToBytes Test") { + uint248_t uint248Input = uint248_t("452312848503266318373324160190117140051835877600158453279131187530910662650"); + auto uint248Output = UintConv::uint248ToBytes(uint248Input); + BytesArr<31> uint248ExpectedOutput = BytesArr<31> {0xff, 0xff, 0xff, 0xff, 0x3d, 0x87, 0xd5, 0x8f, 0x2e, 0x16, 0xa4, 0x50, 0x99, 0xdf, 0xde, 0x83, 0xe8, 0x45, 0xd0, 0x13, 0x5e, 0x48, 0x6c, 0xf6, 0x6b, 0xa7, 0xff, 0xff, 0xff, 0xff, 0xfa}; + REQUIRE(uint248Output == uint248ExpectedOutput); + } + + SECTION("uint240ToBytes Test") { + uint240_t uint240Input = uint240_t("1766847064778384329583297500742918515827483896875618958121606201292619770"); + auto uint240Output = UintConv::uint240ToBytes(uint240Input); + BytesArr<30> uint240ExpectedOutput = BytesArr<30>{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa}; + REQUIRE(uint240Output == uint240ExpectedOutput); + } + + SECTION("uint232ToBytes Test") { + uint232_t uint232Input = uint232_t("6901746346790563717434755872277015452451108972170386555162524123799295"); + auto uint232Output = UintConv::uint232ToBytes(uint232Input); + BytesArr<29> uint232ExpectedOutput = BytesArr<29>{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x44, 0xe8, 0x0e, 0x70, 0x5c, 0x5f, 0x03, 0xf7, 0x10, 0xc1, 0x0f, 0x75, 0x8a, 0x39, 0x68, 0x1e, 0xb1, 0x5f, 0xfa, 0x0a, 0x1e, 0xff}; + REQUIRE(uint232Output == uint232ExpectedOutput); + } + + SECTION("uint224ToBytes Test") { + uint224_t uint224Input = uint224_t("26959946667150639194667015087019630673637144422540512481103110219215"); + auto uint224Output = UintConv::uint224ToBytes(uint224Input); + BytesArr<28> uint224ExpectedOutput = BytesArr<28> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x65, 0x76, 0x9d, 0x7c, 0x26, 0x91, 0x98, 0xd1, 0x0f, 0x67, 0xe0, 0xc2, 0x0d, 0xbe, 0xd2, 0xd6, 0x51, 0x43, 0xac, 0x25, 0xcf}; + REQUIRE(uint224Output == uint224ExpectedOutput); + } + + SECTION("uint216ToBytes Test") { + uint216_t uint216Input = uint216_t("105312291618557186697918027613670432318815095400549111254310917535"); + auto uint216Output = UintConv::uint216ToBytes(uint216Input); + BytesArr<27> uint216ExpectedOutput = BytesArr<27> {0xff, 0xff, 0xff, 0xfd, 0xf5, 0xf9, 0xc3, 0xb5, 0xf8, 0x4a, 0xed, 0x4c, 0x56, 0x99, 0xc5, 0xec, 0xdb, 0xbe, 0xe1, 0xb8, 0x32, 0x77, 0x5d, 0xaf, 0xff, 0x15, 0x9f}; + REQUIRE(uint216Output == uint216ExpectedOutput); + } + + SECTION("uint208ToBytes Test") { + uint208_t uint208Input = uint208_t("411176139330301510518742295639337626245613966408394965837151255"); + auto uint208Output = UintConv::uint208ToBytes(uint208Input); + BytesArr<26> uint208ExpectedOutput = BytesArr<26> {0xff, 0xe0, 0x23, 0x5e, 0x91, 0xfb, 0x47, 0x91, 0xd9, 0x68, 0xea, 0x08, 0x5f, 0xb3, 0x4e, 0x6b, 0xcc, 0xfe, 0xad, 0xd4, 0xab, 0xe5, 0x20, 0x3f, 0xfc, 0x17}; + REQUIRE(uint208Output == uint208ExpectedOutput); + } + + SECTION("uint200ToBytes Test") { + uint200_t uint200Input = uint200_t("1606931844258990275541962019341162602522202913782792831301375"); + auto uint200Output = UintConv::uint200ToBytes(uint200Input); + BytesArr<25> uint200ExpectedOutput = BytesArr<25> {0xff, 0xff, 0xbf, 0x44, 0xdb, 0xda, 0x25, 0xf4, 0xcf, 0xa0, 0x53, 0x3c, 0x00, 0xc9, 0x61, 0xdb, 0xfa, 0x45, 0x00, 0xd2, 0x92, 0x81, 0xba, 0xf6, 0xff}; + REQUIRE(uint200Output == uint200ExpectedOutput); + } + + SECTION("uint192ToBytes Test") { + uint192_t uint192Input = uint192_t("6277101735386680163835789423207166416102355144464034112895"); + auto uint192Output = UintConv::uint192ToBytes(uint192Input); + BytesArr<24> uint192ExpectedOutput = BytesArr<24> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf9, 0x1c, 0xc2, 0x2b, 0x56, 0x36, 0x47, 0xc5, 0x7c, 0xa2, 0x1a, 0x93, 0xf3, 0x08, 0x5a, 0x8b, 0x25, 0x7f}; + REQUIRE(uint192Output == uint192ExpectedOutput); + } + + SECTION("uint184ToBytes Test") { + uint184_t uint184Input = uint184_t("24519128653854221731733552434404946137899825954931634815"); + auto uint184Output = UintConv::uint184ToBytes(uint184Input); + BytesArr<23> uint184ExpectedOutput = BytesArr<23> {0xff, 0xfd, 0xdc, 0x9e, 0x27, 0x50, 0x33, 0x6b, 0x4a, 0x91, 0xcc, 0xe8, 0x44, 0x49, 0xbb, 0x90, 0x0d, 0xd0, 0x74, 0xe7, 0x24, 0x72, 0x7f}; + REQUIRE(uint184Output == uint184ExpectedOutput); + } + + SECTION("uint176ToBytes Test") { + uint176_t uint176Input = uint176_t("95180971304118053147396689196894323971171195136471135"); + auto uint176Output = UintConv::uint176ToBytes(uint176Input); + BytesArr<22> uint176ExpectedOutput = BytesArr<22> {0xfe, 0x65, 0x76, 0x9d, 0x7c, 0x26, 0x91, 0x38, 0x85, 0x28, 0x29, 0xfc, 0x3e, 0x82, 0xe5, 0xf0, 0x6c, 0xfe, 0xc8, 0x1f, 0x70, 0x5f}; + REQUIRE(uint176Output == uint176ExpectedOutput); + } + + SECTION("uint168ToBytes Test") { + uint168_t uint168Input = uint168_t("374114419156711147010143317175368451031918731001155"); + auto uint168Output = UintConv::uint168ToBytes(uint168Input); + BytesArr<21> uint168ExpectedOutput = BytesArr<21> {0xff, 0xfa, 0xbe, 0xc0, 0xe3, 0xb0, 0x36, 0x48, 0x66, 0x50, 0x4b, 0x1c, 0x90, 0xef, 0x13, 0xad, 0x42, 0x36, 0x72, 0xfd, 0x43}; + REQUIRE(uint168Output == uint168ExpectedOutput); + } + + SECTION("uint160ToBytes Test") { + uint160_t uint160Input = uint160_t("506797479317435130489084083375319966488594602593"); + auto uint160Output = UintConv::uint160ToBytes(uint160Input); + BytesArr<20> uint160ExpectedOutput = BytesArr<20> {0x58, 0xc5, 0x95, 0xbe, 0xdf, 0x1d, 0xea, 0x53, 0x2c, 0xf0, 0x6a, 0xf9, 0x09, 0x1a, 0x51, 0xb7, 0x5a, 0x11, 0xda, 0x61}; + REQUIRE(uint160Output == uint160ExpectedOutput); + } + + SECTION("uint152ToBytes Test") { + uint152_t uint152Input = uint152_t("5701991770823839524233143877797980545130986491"); + auto uint152Output = UintConv::uint152ToBytes(uint152Input); + BytesArr<19> uint152ExpectedOutput = BytesArr<19> {0xff, 0xaf, 0xa7, 0xc9, 0x9f, 0xec, 0x62, 0x36, 0xc7, 0x93, 0x33, 0xe4, 0x70, 0x1a, 0x7f, 0xe8, 0x28, 0x7b, 0xfb}; + REQUIRE(uint152Output == uint152ExpectedOutput); + } + + SECTION("uint144ToBytes Test") { + uint144_t uint144Input = uint144_t("22300745118530623141515718272648361505980415"); + auto uint144Output = UintConv::uint144ToBytes(uint144Input); + BytesArr<18> uint144ExpectedOutput = BytesArr<18> {0xff, 0xff, 0xff, 0xf0, 0x97, 0xb2, 0x0a, 0x93, 0xbd, 0xc2, 0x0f, 0xd1, 0xf9, 0x6a, 0x9b, 0x7f, 0xff, 0xff}; + REQUIRE(uint144Output == uint144ExpectedOutput); + } + + SECTION("uint136ToBytes Test") { + uint136_t uint136Input = uint136_t("87112285131760246616623899502532662132135"); + auto uint136Output = UintConv::uint136ToBytes(uint136Input); + BytesArr<17> uint136ExpectedOutput = BytesArr<17> {0xff, 0xff, 0xff, 0xd8, 0x8e, 0x94, 0x95, 0xee, 0xc9, 0x84, 0xf6, 0x26, 0xc7, 0xe9, 0x3f, 0xfd, 0xa7}; + REQUIRE(uint136Output == uint136ExpectedOutput); + } + + SECTION("uint128ToBytes Test") { + uint128_t uint128Input = uint128_t("340282366920938463463374607431768211401"); + auto uint128Output = UintConv::uint128ToBytes(uint128Input); + BytesArr<16> uint128ExpectedOutput = BytesArr<16> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9 }; + REQUIRE(uint128Output == uint128ExpectedOutput); + } + + SECTION("uint120ToBytes Test") { + uint120_t uint120Input = uint120_t("1329227915784915812903807060281344575"); + auto uint120Output = UintConv::uint120ToBytes(uint120Input); + BytesArr<15> uint120ExpectedOutput = BytesArr<15> {0xff, 0xff, 0xfe, 0xfd, 0x81, 0x8d, 0x0a, 0xce, 0x2d, 0x1a, 0xdc, 0x44, 0x9f, 0x42, 0x3f}; + REQUIRE(uint120Output == uint120ExpectedOutput); + } + + SECTION("uint112ToBytes Test") { + uint112_t uint112Input = uint112_t("5191296858514827628530496129220091"); + auto uint112Output = UintConv::uint112ToBytes(uint112Input); + BytesArr<14> uint112ExpectedOutput = BytesArr<14> {0xff, 0xf3, 0x60, 0xd3, 0x5e, 0xf3, 0x85, 0xc9, 0x7e, 0xa0, 0x4f, 0x94, 0x3d, 0xfb}; + REQUIRE(uint112Output == uint112ExpectedOutput); + } + + SECTION("uint104ToBytes Test") { + uint104_t uint104Input = uint104_t("20212409603611670423941251286011"); + auto uint104Output = UintConv::uint104ToBytes(uint104Input); + BytesArr<13> uint104ExpectedOutput = BytesArr<13> {0xff, 0x1d, 0xd1, 0x5b, 0x6a, 0x21, 0xe0, 0x63, 0x45, 0x02, 0xbf, 0x43, 0xfb}; + REQUIRE(uint104Output == uint104ExpectedOutput); + } + + SECTION("uint96ToBytes Test") { + uint96_t uint96Input = uint96_t("79128162514264331593543951331"); + auto uint96Output = UintConv::uint96ToBytes(uint96Input); + BytesArr<12> uint96ExpectedOutput = BytesArr<12> {0xff, 0xad, 0x48, 0x2d, 0x23, 0x37, 0xed, 0xb8, 0x20, 0x21, 0xa3, 0xe3}; + REQUIRE(uint96Output == uint96ExpectedOutput); + } + + SECTION("uint88ToBytes Test") { + uint88_t uint88Input = uint88_t("309185109821345061724781051"); + auto uint88Output = UintConv::uint88ToBytes(uint88Input); + BytesArr<11> uint88ExpectedOutput = BytesArr<11> {0xff, 0xc0, 0x7e, 0x63, 0x6f, 0xba, 0x4a, 0xde, 0x54, 0x79, 0xfb}; + REQUIRE(uint88Output == uint88ExpectedOutput); + } + + SECTION("uint80ToBytes Test") { + uint80_t uint80Input = uint80_t("1208925819614629174106171"); + auto uint80Output = UintConv::uint80ToBytes(uint80Input); + BytesArr<10> uint80ExpectedOutput = BytesArr<10> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf6, 0xd8, 0x3b}; + REQUIRE(uint80Output == uint80ExpectedOutput); + } + + SECTION("uint72ToBytes Test") { + uint72_t uint72Input = uint72_t("1722366182819645213691"); + auto uint72Output = UintConv::uint72ToBytes(uint72Input); + BytesArr<9> uint72ExpectedOutput = BytesArr<9> {0x5d, 0x5e, 0xa1, 0xe5, 0xc9, 0x8e, 0x75, 0xcb, 0xfb}; + REQUIRE(uint72Output == uint72ExpectedOutput); + } + + SECTION("uint64ToBytes Test") { + uint64_t uint64Input = uint64_t(11155010102558518614ULL); + auto uint64Output = UintConv::uint64ToBytes(uint64Input); + BytesArr<8> uint64ExpectedOutput = BytesArr<8> {0x9a, 0xce, 0x8e, 0x96, 0x24, 0xe4, 0xed, 0x56}; + REQUIRE(uint64Output == uint64ExpectedOutput); + } + + SECTION("uint56ToBytes Test") { + uint56_t uint56Input = uint56_t(72051594031927931); + auto uint56Output = UintConv::uint56ToBytes(uint56Input); + BytesArr<7> uint56ExpectedOutput = BytesArr<7> {0xff, 0xfa, 0x8b, 0x03, 0xc6, 0x12, 0x7b}; + REQUIRE(uint56Output == uint56ExpectedOutput); + } + + SECTION("uint48ToBytes Test") { + uint48_t uint48Input = uint48_t(281414176110651); + auto uint48Output = UintConv::uint48ToBytes(uint48Input); + BytesArr<6> uint48ExpectedOutput = BytesArr<6> {0xff, 0xf1, 0xd8, 0x00, 0x78, 0x3b}; + REQUIRE(uint48Output == uint48ExpectedOutput); + } + + SECTION("uint40ToBytes Test") { + uint40_t uint40Input = uint40_t(1019511621771); + auto uint40Output = UintConv::uint40ToBytes(uint40Input); + BytesArr<5> uint40ExpectedOutput = BytesArr<5> {0xed, 0x5f, 0xa0, 0xc8, 0x8b}; + REQUIRE(uint40Output == uint40ExpectedOutput); + } + + SECTION("uint32ToBytes Test") { + uint32_t uint32Input = 2004601498; + auto uint32Output = UintConv::uint32ToBytes(uint32Input); + BytesArr<4> uint32ExpectedOutput = BytesArr<4> {0x77, 0x7b, 0xca, 0x9a}; + REQUIRE(uint32Output == uint32ExpectedOutput); + } + + SECTION("uint24ToBytes Test") { + uint24_t uint24Input = 16117211; + auto uint24Output = UintConv::uint24ToBytes(uint24Input); + BytesArr<3> uint24ExpectedOutput = BytesArr<3> {0xf5, 0xed, 0xdb}; + REQUIRE(uint24Output == uint24ExpectedOutput); + } + + SECTION("uint16ToBytes Test") { + uint16_t uint16Input = 65452; + auto uint16Output = UintConv::uint16ToBytes(uint16Input); + BytesArr<2> uint16ExpectedOutput = BytesArr<2> {0xff, 0xac}; + REQUIRE(uint16Output == uint16ExpectedOutput); + } + + SECTION("uint8ToBytes Test") { + uint8_t uint8Input = 120; + auto uint8Output = UintConv::uint8ToBytes(uint8Input); + BytesArr<1> uint8ExpectedOutput = BytesArr<1> {0x78}; + REQUIRE(uint8Output == uint8ExpectedOutput); + } + + SECTION("bytesToUint256 Test") { + FixedBytes<32> bytesStr(bytes::view("\xcb\x06\x75\x32\x90\xff\xac\x16\x72\x05\xd0\xf5\x3b\x64\xac\xfd\x80\xbe\x11\xed\xbb\x26\xa2\x24\xbe\xd9\x23\x9a\xe6\x74\x0e\x67")); + auto uint256Output = UintConv::bytesToUint256(bytesStr); + uint256_t uint256ExpectedOutput = uint256_t("91830918212381802449294565349763096207758814059154440393436864477986483867239"); + REQUIRE(uint256Output == uint256ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint256(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint256(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint248 Test") { + BytesArr<31> bytesArr = BytesArr<31> {0xff, 0xff, 0xff, 0xff, 0x3d, 0x87, 0xd5, 0x8f, 0x2e, 0x16, 0xa4, 0x50, 0x99, 0xdf, 0xde, 0x83, 0xe8, 0x45, 0xd0, 0x13, 0x5e, 0x48, 0x6c, 0xf6, 0x6b, 0xa7, 0xff, 0xff, 0xff, 0xff, 0xfa}; + auto uint248Output = UintConv::bytesToUint248(bytesArr); + uint248_t uint248ExpectedOutput = uint248_t("452312848503266318373324160190117140051835877600158453279131187530910662650"); + REQUIRE(uint248Output == uint248ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint248(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint248(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint240 Test") { + BytesArr<30> bytesArr = BytesArr<30>{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa}; + auto uint240Output = UintConv::bytesToUint240(bytesArr); + uint240_t uint240ExpectedOutput = uint240_t("1766847064778384329583297500742918515827483896875618958121606201292619770"); + REQUIRE(uint240Output == uint240ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint240(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint240(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint232 Test") { + BytesArr<29> bytesArr = BytesArr<29>{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x44, 0xe8, 0x0e, 0x70, 0x5c, 0x5f, 0x03, 0xf7, 0x10, 0xc1, 0x0f, 0x75, 0x8a, 0x39, 0x68, 0x1e, 0xb1, 0x5f, 0xfa, 0x0a, 0x1e, 0xff}; + auto uint232Output = UintConv::bytesToUint232(bytesArr); + uint232_t uint232ExpectedOutput = uint232_t("6901746346790563717434755872277015452451108972170386555162524123799295"); + REQUIRE(uint232Output == uint232ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint232(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint232(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + SECTION("bytesToUint224 Test") { + BytesArr<28> bytesArr = BytesArr<28> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x65, 0x76, 0x9d, 0x7c, 0x26, 0x91, 0x98, 0xd1, 0x0f, 0x67, 0xe0, 0xc2, 0x0d, 0xbe, 0xd2, 0xd6, 0x51, 0x43, 0xac, 0x25, 0xcf}; + auto uint224Output = UintConv::bytesToUint224(bytesArr); + uint224_t uint224ExpectedOutput = uint224_t("26959946667150639194667015087019630673637144422540512481103110219215"); + REQUIRE(uint224Output == uint224ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint224(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint224(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + SECTION("bytesToUint216 Test") { + BytesArr<27> bytesArr = BytesArr<27> {0xff, 0xff, 0xff, 0xfd, 0xf5, 0xf9, 0xc3, 0xb5, 0xf8, 0x4a, 0xed, 0x4c, 0x56, 0x99, 0xc5, 0xec, 0xdb, 0xbe, 0xe1, 0xb8, 0x32, 0x77, 0x5d, 0xaf, 0xff, 0x15, 0x9f}; + auto uint216Output = UintConv::bytesToUint216(bytesArr); + uint216_t uint216ExpectedOutput = uint216_t("105312291618557186697918027613670432318815095400549111254310917535"); + REQUIRE(uint216Output == uint216ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint216(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint216(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + SECTION("bytesToUint208 Test") { + BytesArr<26> bytesArr = BytesArr<26> {0xff, 0xe0, 0x23, 0x5e, 0x91, 0xfb, 0x47, 0x91, 0xd9, 0x68, 0xea, 0x08, 0x5f, 0xb3, 0x4e, 0x6b, 0xcc, 0xfe, 0xad, 0xd4, 0xab, 0xe5, 0x20, 0x3f, 0xfc, 0x17}; + auto uint208Output = UintConv::bytesToUint208(bytesArr); + uint208_t uint208ExpectedOutput = uint208_t("411176139330301510518742295639337626245613966408394965837151255"); + REQUIRE(uint208Output == uint208ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint208(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint208(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + SECTION("bytesToUint200 Test") { + BytesArr<25> bytesArr = BytesArr<25> {0xff, 0xff, 0xbf, 0x44, 0xdb, 0xda, 0x25, 0xf4, 0xcf, 0xa0, 0x53, 0x3c, 0x00, 0xc9, 0x61, 0xdb, 0xfa, 0x45, 0x00, 0xd2, 0x92, 0x81, 0xba, 0xf6, 0xff}; + auto uint200Output = UintConv::bytesToUint200(bytesArr); + uint200_t uint200ExpectedOutput = uint200_t("1606931844258990275541962019341162602522202913782792831301375"); + REQUIRE(uint200Output == uint200ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint200(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint200(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + SECTION("bytesToUint192 Test") { + std::vector vec; + FixedBytes<24> bytesStr = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf9, 0x1c, 0xc2, 0x2b, 0x56, 0x36, 0x47, 0xc5, 0x7c, 0xa2, 0x1a, 0x93, 0xf3, 0x08, 0x5a, 0x8b, 0x25, 0x7f}; // TODO: initializer_list constructor for FixedBytes + auto uint192Output = UintConv::bytesToUint192(bytesStr); + uint192_t uint192ExpectedOutput = uint192_t("6277101735386680163835789423207166416102355144464034112895"); + REQUIRE(uint192Output == uint192ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint192(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint192(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + SECTION("bytesToUint184 Test") { + BytesArr<23> bytesArr = BytesArr<23> {0xff, 0xfd, 0xdc, 0x9e, 0x27, 0x50, 0x33, 0x6b, 0x4a, 0x91, 0xcc, 0xe8, 0x44, 0x49, 0xbb, 0x90, 0x0d, 0xd0, 0x74, 0xe7, 0x24, 0x72, 0x7f}; + auto uint184Output = UintConv::bytesToUint184(bytesArr); + uint184_t uint184ExpectedOutput = uint184_t("24519128653854221731733552434404946137899825954931634815"); + REQUIRE(uint184Output == uint184ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint184(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint184(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + SECTION("bytesToUint176 Test") { + BytesArr<22> bytesArr = BytesArr<22> {0xff, 0xff, 0xff, 0xff, 0x3d, 0x87, 0xd5, 0x8f, 0x2e, 0x16, 0xa4, 0x50, 0x99, 0xdf, 0xde, 0x83, 0xe8, 0x45, 0xd0, 0x13, 0x5e, 0x48}; + auto uint176Output = UintConv::bytesToUint176(bytesArr); + uint176_t uint176ExpectedOutput = uint176_t("95780971287177379879234105465257117190357643745779272"); + REQUIRE(uint176Output == uint176ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint176(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint176(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + SECTION("bytesToUint168 Test") { + BytesArr<21> bytesArr = BytesArr<21> {0xff, 0xff, 0xff, 0x3d, 0x87, 0xd5, 0x8f, 0x2e, 0x16, 0xa4, 0x50, 0x99, 0xdf, 0xde, 0x83, 0xe8, 0x45, 0xd0, 0x13, 0x5e, 0x48}; + auto uint168Output = UintConv::bytesToUint168(bytesArr); + uint168_t uint168ExpectedOutput = uint168_t("374144402216037378897559585538161667218367340305992"); + REQUIRE(uint168Output == uint168ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint168(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint168(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + SECTION("bytesToUint160 Test") { + FixedBytes<20> bytesStr(bytes::view("\x58\xc5\x95\xbe\xdf\x1d\xea\x53\x2c\xf0\x6a\xf9\x09\x1a\x51\xb7\x5a\x11\xda\x61")); + auto uint160Output = UintConv::bytesToUint160(bytesStr); + uint160_t uint160ExpectedOutput = uint160_t("506797479317435130489084083375319966488594602593"); + REQUIRE(uint160Output == uint160ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint160(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint160(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint152 Test") { + BytesArr<19> bytesArr = BytesArr<19> {0xff, 0xaf, 0xa7, 0xc9, 0x9f, 0xec, 0x62, 0x36, 0xc7, 0x93, 0x33, 0xe4, 0x70, 0x1a, 0x7f, 0xe8, 0x28, 0x7b, 0xfb}; + auto uint152Output = UintConv::bytesToUint152(bytesArr); + uint152_t uint152ExpectedOutput = uint152_t("5701991770823839524233143877797980545130986491"); + REQUIRE(uint152Output == uint152ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint152(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint152(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint144 Test") { + BytesArr<18> bytesArr = BytesArr<18> {0xff, 0xff, 0xff, 0xf0, 0x97, 0xb2, 0x0a, 0x93, 0xbd, 0xc2, 0x0f, 0xd1, 0xf9, 0x6a, 0x9b, 0x7f, 0xff, 0xff}; + auto uint144Output = UintConv::bytesToUint144(bytesArr); + uint144_t uint144ExpectedOutput = uint144_t("22300745118530623141515718272648361505980415"); + REQUIRE(uint144Output == uint144ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint144(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint144(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint136 Test") { + BytesArr<17> bytesArr = BytesArr<17> {0xff, 0xff, 0xff, 0xd8, 0x8e, 0x94, 0x95, 0xee, 0xc9, 0x84, 0xf6, 0x26, 0xc7, 0xe9, 0x3f, 0xfd, 0xa7}; + auto uint136Output = UintConv::bytesToUint136(bytesArr); + uint136_t uint136ExpectedOutput = uint136_t("87112285131760246616623899502532662132135"); + REQUIRE(uint136Output == uint136ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint136(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint136(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint128 Test") { + BytesArr<16> bytesArr = BytesArr<16> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9 }; + auto uint128Output = UintConv::bytesToUint128(bytesArr); + uint128_t uint128ExpectedOutput = uint128_t("340282366920938463463374607431768211401"); + REQUIRE(uint128Output == uint128ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint128(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint128(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + SECTION("bytesToUint120 Test") { + BytesArr<15> bytesArr = BytesArr<15> {0xff, 0xff, 0xff, 0xff, 0x3d, 0x87, 0xd5, 0x8f, 0x2e, 0x16, 0xa4, 0x50, 0x99, 0xdf, 0xde}; + auto uint120Output = UintConv::bytesToUint120(bytesArr); + uint120_t uint120ExpectedOutput = uint120_t("1329227995549816797027838164786077662"); + REQUIRE(uint120Output == uint120ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint120(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint120(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + SECTION("bytesToUint112 Test") { + BytesArr<14> bytesArr = BytesArr<14> {0xff, 0xf3, 0x60, 0xd3, 0x5e, 0xf3, 0x85, 0xc9, 0x7e, 0xa0, 0x4f, 0x94, 0x3d, 0xfb}; + auto uint112Output = UintConv::bytesToUint112(bytesArr); + uint112_t uint112ExpectedOutput = uint112_t("5191296858514827628530496129220091"); + REQUIRE(uint112Output == uint112ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint112(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint112(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + SECTION("bytesToUint104 Test") { + BytesArr<13> bytesArr = BytesArr<13> {0xff, 0x1d, 0xd1, 0x5b, 0x6a, 0x21, 0xe0, 0x63, 0x45, 0x02, 0xbf, 0x43, 0xfb}; + auto uint104Output = UintConv::bytesToUint104(bytesArr); + uint104_t uint104ExpectedOutput = uint104_t("20212409603611670423941251286011"); + REQUIRE(uint104Output == uint104ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffff"); + try { UintConv::bytesToUint104(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint104(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + + } + + + SECTION("bytesToUint96 Test") { + BytesArr<12> bytesArr = BytesArr<12> {0xff, 0xad, 0x48, 0x2d, 0x23, 0x37, 0xed, 0xb8, 0x20, 0x21, 0xa3, 0xe3}; + auto uint96Output = UintConv::bytesToUint96(bytesArr); + uint96_t uint96ExpectedOutput = uint96_t("79128162514264331593543951331"); + REQUIRE(uint96Output == uint96ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffff"); + try { UintConv::bytesToUint96(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint96(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint88 Test") { + BytesArr<11> bytesArr = BytesArr<11> {0xff, 0xc0, 0x7e, 0x63, 0x6f, 0xba, 0x4a, 0xde, 0x54, 0x79, 0xfb}; + auto uint88Output = UintConv::bytesToUint88(bytesArr); + uint88_t uint88ExpectedOutput = uint88_t("309185109821345061724781051"); + REQUIRE(uint88Output == uint88ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffff"); + try { UintConv::bytesToUint88(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint88(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + + SECTION("bytesToUint80 Test") { + BytesArr<10> bytesArr = BytesArr<10> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf6, 0xd8, 0x3b}; + auto uint80Output = UintConv::bytesToUint80(bytesArr); + uint80_t uint80ExpectedOutput = uint80_t("1208925819614629174106171"); + REQUIRE(uint80Output == uint80ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffff"); + try { UintConv::bytesToUint80(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint80(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint72 Test") { + BytesArr<9> bytesArr = BytesArr<9> {0x5d, 0x5e, 0xa1, 0xe5, 0xc9, 0x8e, 0x75, 0xcb, 0xfb}; + auto uint72Output = UintConv::bytesToUint72(bytesArr); + uint72_t uint72ExpectedOutput = uint72_t("1722366182819645213691"); + REQUIRE(uint72Output == uint72ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffff"); + try { UintConv::bytesToUint72(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint72(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint64 Test") { + FixedBytes<8> bytesStr(bytes::view("\x9a\xce\x8e\x96\x24\xe4\xed\x56")); + auto uint64Output = UintConv::bytesToUint64(bytesStr); + uint64_t uint64ExpectedOutput = uint64_t(11155010102558518614ULL); + REQUIRE(uint64Output == uint64ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffffff"); + try { UintConv::bytesToUint64(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint64(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint56 Test") { + BytesArr<7> bytesArr = BytesArr<7> {0xff, 0xfa, 0x8b, 0x03, 0xc6, 0x12, 0x7b}; + auto uint56Output = UintConv::bytesToUint56(bytesArr); + uint64_t uint56ExpectedOutput = uint64_t(72051594031927931); + REQUIRE(uint56Output == uint56ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffffff"); + try { UintConv::bytesToUint56(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint56(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint48 Test") { + BytesArr<6> bytesArr = BytesArr<6> {0xff, 0xf1, 0xd8, 0x00, 0x78, 0x3b}; + auto uint48Output = UintConv::bytesToUint48(bytesArr); + uint64_t uint48ExpectedOutput = uint64_t(281414176110651); + REQUIRE(uint48Output == uint48ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffffff"); + try { UintConv::bytesToUint48(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint48(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint40 Test") { + BytesArr<5> bytesArr = BytesArr<5> {0xed, 0x5f, 0xa0, 0xc8, 0x8b}; + auto uint40Output = UintConv::bytesToUint40(bytesArr); + uint64_t uint40ExpectedOutput = uint64_t(1019511621771); + REQUIRE(uint40Output == uint40ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffffff"); + try { UintConv::bytesToUint40(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint40(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint32 Test") { + FixedBytes<4> bytesStr(bytes::view("\x77\x7b\xca\x9a")); + auto uint32Output = UintConv::bytesToUint32(bytesStr); + uint32_t uint32ExpectedOutput = 2004601498; + REQUIRE(uint32Output == uint32ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xffffff"); + Bytes hiStr = Hex::toBytes("0xffffffffff"); + try { UintConv::bytesToUint32(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint32(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint24 Test") { + BytesArr<3> bytesArr = BytesArr<3> {0xf5, 0xed, 0xdb}; + auto uint24Output = UintConv::bytesToUint24(bytesArr); + uint32_t uint24ExpectedOutput = uint32_t(16117211); + REQUIRE(uint24Output == uint24ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xfffffff"); + Bytes hiStr = Hex::toBytes("0xffffffff"); + try { UintConv::bytesToUint24(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint24(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint16 Test") { + FixedBytes<2> bytesStr(bytes::view("\xff\xac")); + auto uint16Output = UintConv::bytesToUint16(bytesStr); + uint16_t uint16ExpectedOutput = 65452; + REQUIRE(uint16Output == uint16ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0xff"); + Bytes hiStr = Hex::toBytes("0xffffff"); + try { UintConv::bytesToUint16(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint16(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + + SECTION("bytesToUint8 Test") { + FixedBytes<1> bytesStr(bytes::view("\x78")); + auto uint8Output = UintConv::bytesToUint8(bytesStr); + uint8_t uint8ExpectedOutput = 120; + REQUIRE(uint8Output == uint8ExpectedOutput); + + bool catchLo = false; + bool catchHi = false; + Bytes loStr = Hex::toBytes("0x"); + Bytes hiStr = Hex::toBytes("0xffff"); + try { UintConv::bytesToUint8(loStr); } catch (std::exception &e) { catchLo = true; } + try { UintConv::bytesToUint8(hiStr); } catch (std::exception &e) { catchHi = true; } + REQUIRE(catchLo == true); + REQUIRE(catchHi == true); + } + } +} + diff --git a/tests/utils/utils.cpp b/tests/utils/utils.cpp index b5064e9f7..7e31ff521 100644 --- a/tests/utils/utils.cpp +++ b/tests/utils/utils.cpp @@ -6,10 +6,8 @@ See the LICENSE.txt file in the project root for more information. */ #include "../../src/libs/catch2/catch_amalgamated.hpp" -#include "../../src/utils/utils.h" -#include "../../src/utils/strings.h" -#include "../../src/utils/hex.h" -#include "bytes/view.h" + +#include "../../src/utils/utils.h" // (strings.h -> hex.h), (bytes/join.h -> bytes/range.h -> bytes/view.h) using Catch::Matchers::Equals; @@ -22,783 +20,11 @@ namespace TUtils { REQUIRE(sha3Output == Hash(sha3ExpectedOutput)); } - SECTION("uint256ToBytes Test") { - uint256_t uint256Input = uint256_t("91830918212381802449294565349763096207758814059154440393436864477986483867239"); - auto uint256Output = Utils::uint256ToBytes(uint256Input); - BytesArr<32> uint256ExpectedOutput = BytesArr<32> {0xcb, 0x06, 0x75, 0x32, 0x90, 0xff, 0xac, 0x16, 0x72, 0x05, 0xd0, 0xf5, 0x3b, 0x64, 0xac, 0xfd, 0x80, 0xbe, 0x11, 0xed, 0xbb, 0x26, 0xa2, 0x24, 0xbe, 0xd9, 0x23, 0x9a, 0xe6, 0x74, 0x0e, 0x67}; - REQUIRE(uint256Output == uint256ExpectedOutput); - } - - SECTION("uint248ToBytes Test") { - uint248_t uint248Input = uint248_t("452312848503266318373324160190117140051835877600158453279131187530910662650"); - auto uint248Output = Utils::uint248ToBytes(uint248Input); - BytesArr<31> uint248ExpectedOutput = BytesArr<31> {0xff, 0xff, 0xff, 0xff, 0x3d, 0x87, 0xd5, 0x8f, 0x2e, 0x16, 0xa4, 0x50, 0x99, 0xdf, 0xde, 0x83, 0xe8, 0x45, 0xd0, 0x13, 0x5e, 0x48, 0x6c, 0xf6, 0x6b, 0xa7, 0xff, 0xff, 0xff, 0xff, 0xfa}; - REQUIRE(uint248Output == uint248ExpectedOutput); - } - - SECTION("uint240ToBytes Test") { - uint240_t uint240Input = uint240_t("1766847064778384329583297500742918515827483896875618958121606201292619770"); - auto uint240Output = Utils::uint240ToBytes(uint240Input); - BytesArr<30> uint240ExpectedOutput = BytesArr<30>{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa}; - REQUIRE(uint240Output == uint240ExpectedOutput); - } - - SECTION("uint232ToBytes Test") { - uint232_t uint232Input = uint232_t("6901746346790563717434755872277015452451108972170386555162524123799295"); - auto uint232Output = Utils::uint232ToBytes(uint232Input); - BytesArr<29> uint232ExpectedOutput = BytesArr<29>{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x44, 0xe8, 0x0e, 0x70, 0x5c, 0x5f, 0x03, 0xf7, 0x10, 0xc1, 0x0f, 0x75, 0x8a, 0x39, 0x68, 0x1e, 0xb1, 0x5f, 0xfa, 0x0a, 0x1e, 0xff}; - REQUIRE(uint232Output == uint232ExpectedOutput); - } - - SECTION("uint224ToBytes Test") { - uint224_t uint224Input = uint224_t("26959946667150639194667015087019630673637144422540512481103110219215"); - auto uint224Output = Utils::uint224ToBytes(uint224Input); - BytesArr<28> uint224ExpectedOutput = BytesArr<28> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x65, 0x76, 0x9d, 0x7c, 0x26, 0x91, 0x98, 0xd1, 0x0f, 0x67, 0xe0, 0xc2, 0x0d, 0xbe, 0xd2, 0xd6, 0x51, 0x43, 0xac, 0x25, 0xcf}; - REQUIRE(uint224Output == uint224ExpectedOutput); - } - - SECTION("uint216ToBytes Test") { - uint216_t uint216Input = uint216_t("105312291618557186697918027613670432318815095400549111254310917535"); - auto uint216Output = Utils::uint216ToBytes(uint216Input); - BytesArr<27> uint216ExpectedOutput = BytesArr<27> {0xff, 0xff, 0xff, 0xfd, 0xf5, 0xf9, 0xc3, 0xb5, 0xf8, 0x4a, 0xed, 0x4c, 0x56, 0x99, 0xc5, 0xec, 0xdb, 0xbe, 0xe1, 0xb8, 0x32, 0x77, 0x5d, 0xaf, 0xff, 0x15, 0x9f}; - REQUIRE(uint216Output == uint216ExpectedOutput); - } - - SECTION("uint208ToBytes Test") { - uint208_t uint208Input = uint208_t("411176139330301510518742295639337626245613966408394965837151255"); - auto uint208Output = Utils::uint208ToBytes(uint208Input); - BytesArr<26> uint208ExpectedOutput = BytesArr<26> {0xff, 0xe0, 0x23, 0x5e, 0x91, 0xfb, 0x47, 0x91, 0xd9, 0x68, 0xea, 0x08, 0x5f, 0xb3, 0x4e, 0x6b, 0xcc, 0xfe, 0xad, 0xd4, 0xab, 0xe5, 0x20, 0x3f, 0xfc, 0x17}; - REQUIRE(uint208Output == uint208ExpectedOutput); - } - - SECTION("uint200ToBytes Test") { - uint200_t uint200Input = uint200_t("1606931844258990275541962019341162602522202913782792831301375"); - auto uint200Output = Utils::uint200ToBytes(uint200Input); - BytesArr<25> uint200ExpectedOutput = BytesArr<25> {0xff, 0xff, 0xbf, 0x44, 0xdb, 0xda, 0x25, 0xf4, 0xcf, 0xa0, 0x53, 0x3c, 0x00, 0xc9, 0x61, 0xdb, 0xfa, 0x45, 0x00, 0xd2, 0x92, 0x81, 0xba, 0xf6, 0xff}; - REQUIRE(uint200Output == uint200ExpectedOutput); - } - - SECTION("uint192ToBytes Test") { - uint192_t uint192Input = uint192_t("6277101735386680163835789423207166416102355144464034112895"); - auto uint192Output = Utils::uint192ToBytes(uint192Input); - BytesArr<24> uint192ExpectedOutput = BytesArr<24> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf9, 0x1c, 0xc2, 0x2b, 0x56, 0x36, 0x47, 0xc5, 0x7c, 0xa2, 0x1a, 0x93, 0xf3, 0x08, 0x5a, 0x8b, 0x25, 0x7f}; - REQUIRE(uint192Output == uint192ExpectedOutput); - } - - SECTION("uint184ToBytes Test") { - uint184_t uint184Input = uint184_t("24519128653854221731733552434404946137899825954931634815"); - auto uint184Output = Utils::uint184ToBytes(uint184Input); - BytesArr<23> uint184ExpectedOutput = BytesArr<23> {0xff, 0xfd, 0xdc, 0x9e, 0x27, 0x50, 0x33, 0x6b, 0x4a, 0x91, 0xcc, 0xe8, 0x44, 0x49, 0xbb, 0x90, 0x0d, 0xd0, 0x74, 0xe7, 0x24, 0x72, 0x7f}; - REQUIRE(uint184Output == uint184ExpectedOutput); - } - - SECTION("uint176ToBytes Test") { - uint176_t uint176Input = uint176_t("95180971304118053147396689196894323971171195136471135"); - auto uint176Output = Utils::uint176ToBytes(uint176Input); - BytesArr<22> uint176ExpectedOutput = BytesArr<22> {0xfe, 0x65, 0x76, 0x9d, 0x7c, 0x26, 0x91, 0x38, 0x85, 0x28, 0x29, 0xfc, 0x3e, 0x82, 0xe5, 0xf0, 0x6c, 0xfe, 0xc8, 0x1f, 0x70, 0x5f}; - REQUIRE(uint176Output == uint176ExpectedOutput); - } - - SECTION("uint168ToBytes Test") { - uint168_t uint168Input = uint168_t("374114419156711147010143317175368451031918731001155"); - auto uint168Output = Utils::uint168ToBytes(uint168Input); - BytesArr<21> uint168ExpectedOutput = BytesArr<21> {0xff, 0xfa, 0xbe, 0xc0, 0xe3, 0xb0, 0x36, 0x48, 0x66, 0x50, 0x4b, 0x1c, 0x90, 0xef, 0x13, 0xad, 0x42, 0x36, 0x72, 0xfd, 0x43}; - REQUIRE(uint168Output == uint168ExpectedOutput); - } - - SECTION("uint160ToBytes Test") { - uint160_t uint160Input = uint160_t("506797479317435130489084083375319966488594602593"); - auto uint160Output = Utils::uint160ToBytes(uint160Input); - BytesArr<20> uint160ExpectedOutput = BytesArr<20> {0x58, 0xc5, 0x95, 0xbe, 0xdf, 0x1d, 0xea, 0x53, 0x2c, 0xf0, 0x6a, 0xf9, 0x09, 0x1a, 0x51, 0xb7, 0x5a, 0x11, 0xda, 0x61}; - REQUIRE(uint160Output == uint160ExpectedOutput); - } - - SECTION("uint152ToBytes Test") { - uint152_t uint152Input = uint152_t("5701991770823839524233143877797980545130986491"); - auto uint152Output = Utils::uint152ToBytes(uint152Input); - BytesArr<19> uint152ExpectedOutput = BytesArr<19> {0xff, 0xaf, 0xa7, 0xc9, 0x9f, 0xec, 0x62, 0x36, 0xc7, 0x93, 0x33, 0xe4, 0x70, 0x1a, 0x7f, 0xe8, 0x28, 0x7b, 0xfb}; - REQUIRE(uint152Output == uint152ExpectedOutput); - } - - SECTION("uint144ToBytes Test") { - uint144_t uint144Input = uint144_t("22300745118530623141515718272648361505980415"); - auto uint144Output = Utils::uint144ToBytes(uint144Input); - BytesArr<18> uint144ExpectedOutput = BytesArr<18> {0xff, 0xff, 0xff, 0xf0, 0x97, 0xb2, 0x0a, 0x93, 0xbd, 0xc2, 0x0f, 0xd1, 0xf9, 0x6a, 0x9b, 0x7f, 0xff, 0xff}; - REQUIRE(uint144Output == uint144ExpectedOutput); - } - - SECTION("uint136ToBytes Test") { - uint136_t uint136Input = uint136_t("87112285131760246616623899502532662132135"); - auto uint136Output = Utils::uint136ToBytes(uint136Input); - BytesArr<17> uint136ExpectedOutput = BytesArr<17> {0xff, 0xff, 0xff, 0xd8, 0x8e, 0x94, 0x95, 0xee, 0xc9, 0x84, 0xf6, 0x26, 0xc7, 0xe9, 0x3f, 0xfd, 0xa7}; - REQUIRE(uint136Output == uint136ExpectedOutput); - } - - SECTION("uint128ToBytes Test") { - uint128_t uint128Input = uint128_t("340282366920938463463374607431768211401"); - auto uint128Output = Utils::uint128ToBytes(uint128Input); - BytesArr<16> uint128ExpectedOutput = BytesArr<16> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9 }; - REQUIRE(uint128Output == uint128ExpectedOutput); - } - - SECTION("uint120ToBytes Test") { - uint120_t uint120Input = uint120_t("1329227915784915812903807060281344575"); - auto uint120Output = Utils::uint120ToBytes(uint120Input); - BytesArr<15> uint120ExpectedOutput = BytesArr<15> {0xff, 0xff, 0xfe, 0xfd, 0x81, 0x8d, 0x0a, 0xce, 0x2d, 0x1a, 0xdc, 0x44, 0x9f, 0x42, 0x3f}; - REQUIRE(uint120Output == uint120ExpectedOutput); - } - - SECTION("uint112ToBytes Test") { - uint112_t uint112Input = uint112_t("5191296858514827628530496129220091"); - auto uint112Output = Utils::uint112ToBytes(uint112Input); - BytesArr<14> uint112ExpectedOutput = BytesArr<14> {0xff, 0xf3, 0x60, 0xd3, 0x5e, 0xf3, 0x85, 0xc9, 0x7e, 0xa0, 0x4f, 0x94, 0x3d, 0xfb}; - REQUIRE(uint112Output == uint112ExpectedOutput); - } - - SECTION("uint104ToBytes Test") { - uint104_t uint104Input = uint104_t("20212409603611670423941251286011"); - auto uint104Output = Utils::uint104ToBytes(uint104Input); - BytesArr<13> uint104ExpectedOutput = BytesArr<13> {0xff, 0x1d, 0xd1, 0x5b, 0x6a, 0x21, 0xe0, 0x63, 0x45, 0x02, 0xbf, 0x43, 0xfb}; - REQUIRE(uint104Output == uint104ExpectedOutput); - } - - SECTION("uint96ToBytes Test") { - uint96_t uint96Input = uint96_t("79128162514264331593543951331"); - auto uint96Output = Utils::uint96ToBytes(uint96Input); - BytesArr<12> uint96ExpectedOutput = BytesArr<12> {0xff, 0xad, 0x48, 0x2d, 0x23, 0x37, 0xed, 0xb8, 0x20, 0x21, 0xa3, 0xe3}; - REQUIRE(uint96Output == uint96ExpectedOutput); - } - - SECTION("uint88ToBytes Test") { - uint88_t uint88Input = uint88_t("309185109821345061724781051"); - auto uint88Output = Utils::uint88ToBytes(uint88Input); - BytesArr<11> uint88ExpectedOutput = BytesArr<11> {0xff, 0xc0, 0x7e, 0x63, 0x6f, 0xba, 0x4a, 0xde, 0x54, 0x79, 0xfb}; - REQUIRE(uint88Output == uint88ExpectedOutput); - } - - SECTION("uint80ToBytes Test") { - uint80_t uint80Input = uint80_t("1208925819614629174106171"); - auto uint80Output = Utils::uint80ToBytes(uint80Input); - BytesArr<10> uint80ExpectedOutput = BytesArr<10> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf6, 0xd8, 0x3b}; - REQUIRE(uint80Output == uint80ExpectedOutput); - } - - SECTION("uint72ToBytes Test") { - uint72_t uint72Input = uint72_t("1722366182819645213691"); - auto uint72Output = Utils::uint72ToBytes(uint72Input); - BytesArr<9> uint72ExpectedOutput = BytesArr<9> {0x5d, 0x5e, 0xa1, 0xe5, 0xc9, 0x8e, 0x75, 0xcb, 0xfb}; - REQUIRE(uint72Output == uint72ExpectedOutput); - } - - SECTION("uint64ToBytes Test") { - uint64_t uint64Input = uint64_t(11155010102558518614ULL); - auto uint64Output = Utils::uint64ToBytes(uint64Input); - BytesArr<8> uint64ExpectedOutput = BytesArr<8> {0x9a, 0xce, 0x8e, 0x96, 0x24, 0xe4, 0xed, 0x56}; - REQUIRE(uint64Output == uint64ExpectedOutput); - } - - SECTION("uint56ToBytes Test") { - uint56_t uint56Input = uint56_t(72051594031927931); - auto uint56Output = Utils::uint56ToBytes(uint56Input); - BytesArr<7> uint56ExpectedOutput = BytesArr<7> {0xff, 0xfa, 0x8b, 0x03, 0xc6, 0x12, 0x7b}; - REQUIRE(uint56Output == uint56ExpectedOutput); - } - - SECTION("uint48ToBytes Test") { - uint48_t uint48Input = uint48_t(281414176110651); - auto uint48Output = Utils::uint48ToBytes(uint48Input); - BytesArr<6> uint48ExpectedOutput = BytesArr<6> {0xff, 0xf1, 0xd8, 0x00, 0x78, 0x3b}; - REQUIRE(uint48Output == uint48ExpectedOutput); - } - - SECTION("uint40ToBytes Test") { - uint40_t uint40Input = uint40_t(1019511621771); - auto uint40Output = Utils::uint40ToBytes(uint40Input); - BytesArr<5> uint40ExpectedOutput = BytesArr<5> {0xed, 0x5f, 0xa0, 0xc8, 0x8b}; - REQUIRE(uint40Output == uint40ExpectedOutput); - } - - SECTION("uint32ToBytes Test") { - uint32_t uint32Input = 2004601498; - auto uint32Output = Utils::uint32ToBytes(uint32Input); - BytesArr<4> uint32ExpectedOutput = BytesArr<4> {0x77, 0x7b, 0xca, 0x9a}; - REQUIRE(uint32Output == uint32ExpectedOutput); - } - - SECTION("uint24ToBytes Test") { - uint24_t uint24Input = 16117211; - auto uint24Output = Utils::uint24ToBytes(uint24Input); - BytesArr<3> uint24ExpectedOutput = BytesArr<3> {0xf5, 0xed, 0xdb}; - REQUIRE(uint24Output == uint24ExpectedOutput); - } - - SECTION("uint16ToBytes Test") { - uint16_t uint16Input = 65452; - auto uint16Output = Utils::uint16ToBytes(uint16Input); - BytesArr<2> uint16ExpectedOutput = BytesArr<2> {0xff, 0xac}; - REQUIRE(uint16Output == uint16ExpectedOutput); - } - - SECTION("uint8ToBytes Test") { - uint8_t uint8Input = 120; - auto uint8Output = Utils::uint8ToBytes(uint8Input); - BytesArr<1> uint8ExpectedOutput = BytesArr<1> {0x78}; - REQUIRE(uint8Output == uint8ExpectedOutput); - } - SECTION("randBytes Test") { Bytes randBytesOutput = Utils::randBytes(32); REQUIRE(randBytesOutput.size() == 32); } - SECTION("bytesToUint256 Test") { - FixedBytes<32> bytesStr(bytes::view("\xcb\x06\x75\x32\x90\xff\xac\x16\x72\x05\xd0\xf5\x3b\x64\xac\xfd\x80\xbe\x11\xed\xbb\x26\xa2\x24\xbe\xd9\x23\x9a\xe6\x74\x0e\x67")); - auto uint256Output = Utils::bytesToUint256(bytesStr); - uint256_t uint256ExpectedOutput = uint256_t("91830918212381802449294565349763096207758814059154440393436864477986483867239"); - REQUIRE(uint256Output == uint256ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint256(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint256(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint248 Test") { - BytesArr<31> bytesArr = BytesArr<31> {0xff, 0xff, 0xff, 0xff, 0x3d, 0x87, 0xd5, 0x8f, 0x2e, 0x16, 0xa4, 0x50, 0x99, 0xdf, 0xde, 0x83, 0xe8, 0x45, 0xd0, 0x13, 0x5e, 0x48, 0x6c, 0xf6, 0x6b, 0xa7, 0xff, 0xff, 0xff, 0xff, 0xfa}; - auto uint248Output = Utils::bytesToUint248(bytesArr); - uint248_t uint248ExpectedOutput = uint248_t("452312848503266318373324160190117140051835877600158453279131187530910662650"); - REQUIRE(uint248Output == uint248ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint248(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint248(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint240 Test") { - BytesArr<30> bytesArr = BytesArr<30>{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa}; - auto uint240Output = Utils::bytesToUint240(bytesArr); - uint240_t uint240ExpectedOutput = uint240_t("1766847064778384329583297500742918515827483896875618958121606201292619770"); - REQUIRE(uint240Output == uint240ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint240(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint240(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint232 Test") { - BytesArr<29> bytesArr = BytesArr<29>{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x44, 0xe8, 0x0e, 0x70, 0x5c, 0x5f, 0x03, 0xf7, 0x10, 0xc1, 0x0f, 0x75, 0x8a, 0x39, 0x68, 0x1e, 0xb1, 0x5f, 0xfa, 0x0a, 0x1e, 0xff}; - auto uint232Output = Utils::bytesToUint232(bytesArr); - uint232_t uint232ExpectedOutput = uint232_t("6901746346790563717434755872277015452451108972170386555162524123799295"); - REQUIRE(uint232Output == uint232ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint232(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint232(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - SECTION("bytesToUint224 Test") { - BytesArr<28> bytesArr = BytesArr<28> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x65, 0x76, 0x9d, 0x7c, 0x26, 0x91, 0x98, 0xd1, 0x0f, 0x67, 0xe0, 0xc2, 0x0d, 0xbe, 0xd2, 0xd6, 0x51, 0x43, 0xac, 0x25, 0xcf}; - auto uint224Output = Utils::bytesToUint224(bytesArr); - uint224_t uint224ExpectedOutput = uint224_t("26959946667150639194667015087019630673637144422540512481103110219215"); - REQUIRE(uint224Output == uint224ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint224(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint224(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - SECTION("bytesToUint216 Test") { - BytesArr<27> bytesArr = BytesArr<27> {0xff, 0xff, 0xff, 0xfd, 0xf5, 0xf9, 0xc3, 0xb5, 0xf8, 0x4a, 0xed, 0x4c, 0x56, 0x99, 0xc5, 0xec, 0xdb, 0xbe, 0xe1, 0xb8, 0x32, 0x77, 0x5d, 0xaf, 0xff, 0x15, 0x9f}; - auto uint216Output = Utils::bytesToUint216(bytesArr); - uint216_t uint216ExpectedOutput = uint216_t("105312291618557186697918027613670432318815095400549111254310917535"); - REQUIRE(uint216Output == uint216ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint216(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint216(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - SECTION("bytesToUint208 Test") { - BytesArr<26> bytesArr = BytesArr<26> {0xff, 0xe0, 0x23, 0x5e, 0x91, 0xfb, 0x47, 0x91, 0xd9, 0x68, 0xea, 0x08, 0x5f, 0xb3, 0x4e, 0x6b, 0xcc, 0xfe, 0xad, 0xd4, 0xab, 0xe5, 0x20, 0x3f, 0xfc, 0x17}; - auto uint208Output = Utils::bytesToUint208(bytesArr); - uint208_t uint208ExpectedOutput = uint208_t("411176139330301510518742295639337626245613966408394965837151255"); - REQUIRE(uint208Output == uint208ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint208(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint208(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - SECTION("bytesToUint200 Test") { - BytesArr<25> bytesArr = BytesArr<25> {0xff, 0xff, 0xbf, 0x44, 0xdb, 0xda, 0x25, 0xf4, 0xcf, 0xa0, 0x53, 0x3c, 0x00, 0xc9, 0x61, 0xdb, 0xfa, 0x45, 0x00, 0xd2, 0x92, 0x81, 0xba, 0xf6, 0xff}; - auto uint200Output = Utils::bytesToUint200(bytesArr); - uint200_t uint200ExpectedOutput = uint200_t("1606931844258990275541962019341162602522202913782792831301375"); - REQUIRE(uint200Output == uint200ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint200(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint200(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - SECTION("bytesToUint192 Test") { - std::vector vec; - FixedBytes<24> bytesStr = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf9, 0x1c, 0xc2, 0x2b, 0x56, 0x36, 0x47, 0xc5, 0x7c, 0xa2, 0x1a, 0x93, 0xf3, 0x08, 0x5a, 0x8b, 0x25, 0x7f}; // TODO: initializer_list constructor for FixedBytes - auto uint192Output = Utils::bytesToUint192(bytesStr); - uint192_t uint192ExpectedOutput = uint192_t("6277101735386680163835789423207166416102355144464034112895"); - REQUIRE(uint192Output == uint192ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint192(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint192(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - SECTION("bytesToUint184 Test") { - BytesArr<23> bytesArr = BytesArr<23> {0xff, 0xfd, 0xdc, 0x9e, 0x27, 0x50, 0x33, 0x6b, 0x4a, 0x91, 0xcc, 0xe8, 0x44, 0x49, 0xbb, 0x90, 0x0d, 0xd0, 0x74, 0xe7, 0x24, 0x72, 0x7f}; - auto uint184Output = Utils::bytesToUint184(bytesArr); - uint184_t uint184ExpectedOutput = uint184_t("24519128653854221731733552434404946137899825954931634815"); - REQUIRE(uint184Output == uint184ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint184(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint184(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - SECTION("bytesToUint176 Test") { - BytesArr<22> bytesArr = BytesArr<22> {0xff, 0xff, 0xff, 0xff, 0x3d, 0x87, 0xd5, 0x8f, 0x2e, 0x16, 0xa4, 0x50, 0x99, 0xdf, 0xde, 0x83, 0xe8, 0x45, 0xd0, 0x13, 0x5e, 0x48}; - auto uint176Output = Utils::bytesToUint176(bytesArr); - uint176_t uint176ExpectedOutput = uint176_t("95780971287177379879234105465257117190357643745779272"); - REQUIRE(uint176Output == uint176ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint176(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint176(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - SECTION("bytesToUint168 Test") { - BytesArr<21> bytesArr = BytesArr<21> {0xff, 0xff, 0xff, 0x3d, 0x87, 0xd5, 0x8f, 0x2e, 0x16, 0xa4, 0x50, 0x99, 0xdf, 0xde, 0x83, 0xe8, 0x45, 0xd0, 0x13, 0x5e, 0x48}; - auto uint168Output = Utils::bytesToUint168(bytesArr); - uint168_t uint168ExpectedOutput = uint168_t("374144402216037378897559585538161667218367340305992"); - REQUIRE(uint168Output == uint168ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint168(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint168(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - SECTION("bytesToUint160 Test") { - FixedBytes<20> bytesStr(bytes::view("\x58\xc5\x95\xbe\xdf\x1d\xea\x53\x2c\xf0\x6a\xf9\x09\x1a\x51\xb7\x5a\x11\xda\x61")); - auto uint160Output = Utils::bytesToUint160(bytesStr); - uint160_t uint160ExpectedOutput = uint160_t("506797479317435130489084083375319966488594602593"); - REQUIRE(uint160Output == uint160ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint160(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint160(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint152 Test") { - BytesArr<19> bytesArr = BytesArr<19> {0xff, 0xaf, 0xa7, 0xc9, 0x9f, 0xec, 0x62, 0x36, 0xc7, 0x93, 0x33, 0xe4, 0x70, 0x1a, 0x7f, 0xe8, 0x28, 0x7b, 0xfb}; - auto uint152Output = Utils::bytesToUint152(bytesArr); - uint152_t uint152ExpectedOutput = uint152_t("5701991770823839524233143877797980545130986491"); - REQUIRE(uint152Output == uint152ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint152(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint152(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint144 Test") { - BytesArr<18> bytesArr = BytesArr<18> {0xff, 0xff, 0xff, 0xf0, 0x97, 0xb2, 0x0a, 0x93, 0xbd, 0xc2, 0x0f, 0xd1, 0xf9, 0x6a, 0x9b, 0x7f, 0xff, 0xff}; - auto uint144Output = Utils::bytesToUint144(bytesArr); - uint144_t uint144ExpectedOutput = uint144_t("22300745118530623141515718272648361505980415"); - REQUIRE(uint144Output == uint144ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint144(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint144(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint136 Test") { - BytesArr<17> bytesArr = BytesArr<17> {0xff, 0xff, 0xff, 0xd8, 0x8e, 0x94, 0x95, 0xee, 0xc9, 0x84, 0xf6, 0x26, 0xc7, 0xe9, 0x3f, 0xfd, 0xa7}; - auto uint136Output = Utils::bytesToUint136(bytesArr); - uint136_t uint136ExpectedOutput = uint136_t("87112285131760246616623899502532662132135"); - REQUIRE(uint136Output == uint136ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint136(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint136(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint128 Test") { - BytesArr<16> bytesArr = BytesArr<16> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9 }; - auto uint128Output = Utils::bytesToUint128(bytesArr); - uint128_t uint128ExpectedOutput = uint128_t("340282366920938463463374607431768211401"); - REQUIRE(uint128Output == uint128ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint128(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint128(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - SECTION("bytesToUint120 Test") { - BytesArr<15> bytesArr = BytesArr<15> {0xff, 0xff, 0xff, 0xff, 0x3d, 0x87, 0xd5, 0x8f, 0x2e, 0x16, 0xa4, 0x50, 0x99, 0xdf, 0xde}; - auto uint120Output = Utils::bytesToUint120(bytesArr); - uint120_t uint120ExpectedOutput = uint120_t("1329227995549816797027838164786077662"); - REQUIRE(uint120Output == uint120ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint120(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint120(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - SECTION("bytesToUint112 Test") { - BytesArr<14> bytesArr = BytesArr<14> {0xff, 0xf3, 0x60, 0xd3, 0x5e, 0xf3, 0x85, 0xc9, 0x7e, 0xa0, 0x4f, 0x94, 0x3d, 0xfb}; - auto uint112Output = Utils::bytesToUint112(bytesArr); - uint112_t uint112ExpectedOutput = uint112_t("5191296858514827628530496129220091"); - REQUIRE(uint112Output == uint112ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint112(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint112(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - SECTION("bytesToUint104 Test") { - BytesArr<13> bytesArr = BytesArr<13> {0xff, 0x1d, 0xd1, 0x5b, 0x6a, 0x21, 0xe0, 0x63, 0x45, 0x02, 0xbf, 0x43, 0xfb}; - auto uint104Output = Utils::bytesToUint104(bytesArr); - uint104_t uint104ExpectedOutput = uint104_t("20212409603611670423941251286011"); - REQUIRE(uint104Output == uint104ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xfffffffffffffffffffffffffffffffffff"); - try { Utils::bytesToUint104(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint104(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - - } - - - SECTION("bytesToUint96 Test") { - BytesArr<12> bytesArr = BytesArr<12> {0xff, 0xad, 0x48, 0x2d, 0x23, 0x37, 0xed, 0xb8, 0x20, 0x21, 0xa3, 0xe3}; - auto uint96Output = Utils::bytesToUint96(bytesArr); - uint96_t uint96ExpectedOutput = uint96_t("79128162514264331593543951331"); - REQUIRE(uint96Output == uint96ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffffff"); - try { Utils::bytesToUint96(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint96(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint88 Test") { - BytesArr<11> bytesArr = BytesArr<11> {0xff, 0xc0, 0x7e, 0x63, 0x6f, 0xba, 0x4a, 0xde, 0x54, 0x79, 0xfb}; - auto uint88Output = Utils::bytesToUint88(bytesArr); - uint88_t uint88ExpectedOutput = uint88_t("309185109821345061724781051"); - REQUIRE(uint88Output == uint88ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffff"); - try { Utils::bytesToUint88(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint88(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - - SECTION("bytesToUint80 Test") { - BytesArr<10> bytesArr = BytesArr<10> {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf6, 0xd8, 0x3b}; - auto uint80Output = Utils::bytesToUint80(bytesArr); - uint80_t uint80ExpectedOutput = uint80_t("1208925819614629174106171"); - REQUIRE(uint80Output == uint80ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffffff"); - try { Utils::bytesToUint80(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint80(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint72 Test") { - BytesArr<9> bytesArr = BytesArr<9> {0x5d, 0x5e, 0xa1, 0xe5, 0xc9, 0x8e, 0x75, 0xcb, 0xfb}; - auto uint72Output = Utils::bytesToUint72(bytesArr); - uint72_t uint72ExpectedOutput = uint72_t("1722366182819645213691"); - REQUIRE(uint72Output == uint72ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffffffff"); - try { Utils::bytesToUint72(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint72(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint64 Test") { - FixedBytes<8> bytesStr(bytes::view("\x9a\xce\x8e\x96\x24\xe4\xed\x56")); - auto uint64Output = Utils::bytesToUint64(bytesStr); - uint64_t uint64ExpectedOutput = uint64_t(11155010102558518614ULL); - REQUIRE(uint64Output == uint64ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffffff"); - try { Utils::bytesToUint64(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint64(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint56 Test") { - BytesArr<7> bytesArr = BytesArr<7> {0xff, 0xfa, 0x8b, 0x03, 0xc6, 0x12, 0x7b}; - auto uint56Output = Utils::bytesToUint56(bytesArr); - uint64_t uint56ExpectedOutput = uint64_t(72051594031927931); - REQUIRE(uint56Output == uint56ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffffff"); - try { Utils::bytesToUint56(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint56(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint48 Test") { - BytesArr<6> bytesArr = BytesArr<6> {0xff, 0xf1, 0xd8, 0x00, 0x78, 0x3b}; - auto uint48Output = Utils::bytesToUint48(bytesArr); - uint64_t uint48ExpectedOutput = uint64_t(281414176110651); - REQUIRE(uint48Output == uint48ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffffff"); - try { Utils::bytesToUint48(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint48(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint40 Test") { - BytesArr<5> bytesArr = BytesArr<5> {0xed, 0x5f, 0xa0, 0xc8, 0x8b}; - auto uint40Output = Utils::bytesToUint40(bytesArr); - uint64_t uint40ExpectedOutput = uint64_t(1019511621771); - REQUIRE(uint40Output == uint40ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffffff"); - try { Utils::bytesToUint40(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint40(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint32 Test") { - FixedBytes<4> bytesStr(bytes::view("\x77\x7b\xca\x9a")); - auto uint32Output = Utils::bytesToUint32(bytesStr); - uint32_t uint32ExpectedOutput = 2004601498; - REQUIRE(uint32Output == uint32ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xffffff"); - Bytes hiStr = Hex::toBytes("0xffffffffff"); - try { Utils::bytesToUint32(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint32(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint24 Test") { - BytesArr<3> bytesArr = BytesArr<3> {0xf5, 0xed, 0xdb}; - auto uint24Output = Utils::bytesToUint24(bytesArr); - uint32_t uint24ExpectedOutput = uint32_t(16117211); - REQUIRE(uint24Output == uint24ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xfffffff"); - Bytes hiStr = Hex::toBytes("0xffffffff"); - try { Utils::bytesToUint24(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint24(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint16 Test") { - FixedBytes<2> bytesStr(bytes::view("\xff\xac")); - auto uint16Output = Utils::bytesToUint16(bytesStr); - uint16_t uint16ExpectedOutput = 65452; - REQUIRE(uint16Output == uint16ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0xff"); - Bytes hiStr = Hex::toBytes("0xffffff"); - try { Utils::bytesToUint16(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint16(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("bytesToUint8 Test") { - FixedBytes<1> bytesStr(bytes::view("\x78")); - auto uint8Output = Utils::bytesToUint8(bytesStr); - uint8_t uint8ExpectedOutput = 120; - REQUIRE(uint8Output == uint8ExpectedOutput); - - bool catchLo = false; - bool catchHi = false; - Bytes loStr = Hex::toBytes("0x"); - Bytes hiStr = Hex::toBytes("0xffff"); - try { Utils::bytesToUint8(loStr); } catch (std::exception &e) { catchLo = true; } - try { Utils::bytesToUint8(hiStr); } catch (std::exception &e) { catchHi = true; } - REQUIRE(catchLo == true); - REQUIRE(catchHi == true); - } - - SECTION("padLeftBytes Test") { - Bytes inputBytes = Hex::toBytes("0xabcdef"); - Bytes outputBytes = Utils::padLeftBytes(inputBytes, 10, 0x00); - Bytes outputBytes2 = Utils::padLeftBytes(inputBytes, 20, 0x11); - Bytes expectedOutputBytes = Hex::toBytes("0x00000000000000abcdef"); - Bytes expectedOutputBytes2 = Hex::toBytes("0x1111111111111111111111111111111111abcdef"); - REQUIRE(outputBytes == expectedOutputBytes); - REQUIRE(outputBytes2 == expectedOutputBytes2); - } - - SECTION("padRightBytes Test") { - Bytes inputBytes = Hex::toBytes("0xabcdef"); - Bytes outputBytes = Utils::padRightBytes(inputBytes, 10, 0x00); - Bytes outputBytes2 = Utils::padRightBytes(inputBytes, 20, 0x11); - Bytes expectedOutputBytes = Hex::toBytes("0xabcdef00000000000000"); - Bytes expectedOutputBytes2 = Hex::toBytes("0xabcdef1111111111111111111111111111111111"); - REQUIRE(outputBytes == expectedOutputBytes); - REQUIRE(outputBytes2 == expectedOutputBytes2); - } - SECTION("fromBigEndian Test") { std::string_view inputBytes("\x10\x11\x40\xd6\xe7\x50\x6f\x80\x4c\xf7\xb0\x37\x0f\xa9\x0b\x04\xc5\xe9\x37\x4d\xdb\x0c\x8c\xbe\x12\xaf\x15\x0c\x8f\xf3\xee\x36"); @@ -822,22 +48,6 @@ namespace TUtils { REQUIRE(uint160Output5To25 == uint160ExpectedOutput5To25); } - SECTION("toLower Test") { - std::string inputStr = "ABCDEF"; - std::string outputStr = inputStr; - Utils::toLower(outputStr); - std::string expectedOutputStr = "abcdef"; - REQUIRE_THAT(outputStr, Equals(expectedOutputStr)); - } - - SECTION("toUpper Test") { - std::string inputStr = "abcdef"; - std::string outputStr = inputStr; - Utils::toUpper(outputStr); - std::string expectedOutputStr = "ABCDEF"; - REQUIRE_THAT(outputStr, Equals(expectedOutputStr)); - } - SECTION("appendBytes Test") { Bytes int1 = Bytes{0x78, 0xF0, 0xB2, 0x91}; Bytes int2 = Bytes{0xAC, 0x26, 0x0E, 0x43};